const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/LeadSiteHome-CBI2c8oW.js","assets/useLeadSiteSearchSuggestions-B_1iiVvT.js","assets/CityPagesModule-B-8O8lDs.js","assets/imageOptimization-Csrlnz8M.js","assets/LeadSiteLuxuryHome-BFHPAbpO.js","assets/LeadSiteLandRanchHome-DVxBwLih.js","assets/LeadSiteSearch-sKCQAGTc.js","assets/LeadSiteListingCardImage-u41wcYfQ.js","assets/LeadSiteMap-CJTuYTzd.js","assets/LeadSiteLuxurySearch-CKALcsU3.js","assets/LeadSiteListingDetail-CJ_F1Ya0.js","assets/ListingVideoTour-DlojDnow.js","assets/useListingVideos-Ts6TOJJe.js","assets/LeadSiteLuxuryListingDetail-CJ-hINuy.js","assets/LeadSiteCityPage-DhH-zpdT.js","assets/LeadSiteSubdivisionPage-B0Io5xjp.js","assets/PublicLiveEvent-DOkjihoj.js","assets/useLiveEngagement-DP9cGwG9.js","assets/LiveEventConsole-BqVMNk_W.js","assets/PostcardManager-C01a-L-h.js","assets/usePostcardZones-BfC1xmJf.js","assets/DirectMail-D6CZ0AmN.js","assets/LeadSiteEditor-BBdN6Ky3.js","assets/ImageUrlField-DnqAkxrj.js","assets/LeadSiteEditor-BzY4kI8E.css","assets/AdminLeadSiteThemes-yNCRo7Tf.js","assets/MLSListingDetail-phdp0tM2.js","assets/EmailCampaignComposer-BzA5EuCF.js","assets/EditorModeSelector-Ds3CoD2r.js","assets/SharedCampaignTemplates-BG7QWNoS.js","assets/TemplateEditorDialog-B5Dsnaiy.js","assets/AgentTemplates-CUl_UvoC.js","assets/TheLocalMoveHome-iM-q6Qbi.js","assets/tlm-hero-bg-BbD3acLf.js","assets/TheLocalMoveGetStarted-DRZygigH.js"])))=>i.map(i=>d[i]); var MHt=Object.defineProperty;var aJe=s=>{throw TypeError(s)};var LHt=(s,t,n)=>t in s?MHt(s,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):s[t]=n;var jr=(s,t,n)=>LHt(s,typeof t!="symbol"?t+"":t,n),AEe=(s,t,n)=>t.has(s)||aJe("Cannot "+n);var de=(s,t,n)=>(AEe(s,t,"read from private field"),n?n.call(s):t.get(s)),ts=(s,t,n)=>t.has(s)?aJe("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(s):t.set(s,n),Dt=(s,t,n,r)=>(AEe(s,t,"write to private field"),r?r.call(s,n):t.set(s,n),n),Ht=(s,t,n)=>(AEe(s,t,"access private method"),n);var Sx=(s,t,n,r)=>({set _(a){Dt(s,t,a,n)},get _(){return de(s,t,r)}});function PHt(s,t){for(var n=0;nr[a]})}}}return Object.freeze(Object.defineProperty(s,Symbol.toStringTag,{value:"Module"}))}(function(){const t=document.createElement("link").relList;if(t&&t.supports&&t.supports("modulepreload"))return;for(const a of document.querySelectorAll('link[rel="modulepreload"]'))r(a);new MutationObserver(a=>{for(const i of a)if(i.type==="childList")for(const l of i.addedNodes)l.tagName==="LINK"&&l.rel==="modulepreload"&&r(l)}).observe(document,{childList:!0,subtree:!0});function n(a){const i={};return a.integrity&&(i.integrity=a.integrity),a.referrerPolicy&&(i.referrerPolicy=a.referrerPolicy),a.crossOrigin==="use-credentials"?i.credentials="include":a.crossOrigin==="anonymous"?i.credentials="omit":i.credentials="same-origin",i}function r(a){if(a.ep)return;a.ep=!0;const i=n(a);fetch(a.href,i)}})();const IHt="modulepreload",DHt=function(s){return"/"+s},iJe={},Fi=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=DHt(c),c in iJe)return;iJe[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":IHt,d||(h.as="script"),h.crossOrigin="",h.href=c,o&&h.setAttribute("nonce",o),document.head.appendChild(h),d)return new Promise((m,f)=>{h.addEventListener("load",m),h.addEventListener("error",()=>f(new Error(`Unable to preload CSS for ${c}`)))})}))}function i(l){const o=new Event("vite:preloadError",{cancelable:!0});if(o.payload=l,window.dispatchEvent(o),!o.defaultPrevented)throw l}return a.then(l=>{for(const o of l||[])o.status==="rejected"&&i(o.reason);return t().catch(i)})};var Uf=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function Xc(s){return s&&s.__esModule&&Object.prototype.hasOwnProperty.call(s,"default")?s.default:s}function RHt(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 myt={exports:{}},_Se={},pyt={exports:{}},Bc={};/** * @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 lQ=Symbol.for("react.element"),OHt=Symbol.for("react.portal"),FHt=Symbol.for("react.fragment"),zHt=Symbol.for("react.strict_mode"),BHt=Symbol.for("react.profiler"),$Ht=Symbol.for("react.provider"),UHt=Symbol.for("react.context"),qHt=Symbol.for("react.forward_ref"),VHt=Symbol.for("react.suspense"),HHt=Symbol.for("react.memo"),GHt=Symbol.for("react.lazy"),oJe=Symbol.iterator;function WHt(s){return s===null||typeof s!="object"?null:(s=oJe&&s[oJe]||s["@@iterator"],typeof s=="function"?s:null)}var fyt={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},gyt=Object.assign,xyt={};function H$(s,t,n){this.props=s,this.context=t,this.refs=xyt,this.updater=n||fyt}H$.prototype.isReactComponent={};H$.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")};H$.prototype.forceUpdate=function(s){this.updater.enqueueForceUpdate(this,s,"forceUpdate")};function yyt(){}yyt.prototype=H$.prototype;function nBe(s,t,n){this.props=s,this.context=t,this.refs=xyt,this.updater=n||fyt}var rBe=nBe.prototype=new yyt;rBe.constructor=nBe;gyt(rBe,H$.prototype);rBe.isPureReactComponent=!0;var lJe=Array.isArray,vyt=Object.prototype.hasOwnProperty,aBe={current:null},byt={key:!0,ref:!0,__self:!0,__source:!0};function _yt(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)vyt.call(t,r)&&!byt.hasOwnProperty(r)&&(a[r]=t[r]);var o=arguments.length-2;if(o===1)a.children=n;else if(1>>1,he=me[ae];if(0>>1;aea(ge,ce))bea(Se,ge)?(me[ae]=Se,me[be]=ce,ae=be):(me[ae]=ge,me[ve]=ce,ae=ve);else if(bea(Se,ce))me[ae]=Se,me[be]=ce,ae=be;else break e}}return ue}function a(me,ue){var ce=me.sortIndex-ue.sortIndex;return ce!==0?ce:me.id-ue.id}if(typeof performance=="object"&&typeof performance.now=="function"){var i=performance;s.unstable_now=function(){return i.now()}}else{var l=Date,o=l.now();s.unstable_now=function(){return l.now()-o}}var c=[],d=[],u=1,h=null,m=3,f=!1,g=!1,y=!1,x=typeof setTimeout=="function"?setTimeout:null,_=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 k(me){for(var ue=n(d);ue!==null;){if(ue.callback===null)r(d);else if(ue.startTime<=me)r(d),ue.sortIndex=ue.expirationTime,t(c,ue);else break;ue=n(d)}}function A(me){if(y=!1,k(me),!g)if(n(c)!==null)g=!0,te(T);else{var ue=n(d);ue!==null&&ne(A,ue.startTime-me)}}function T(me,ue){g=!1,y&&(y=!1,_(M),M=-1),f=!0;var ce=m;try{for(k(ue),h=n(c);h!==null&&(!(h.expirationTime>ue)||me&&!$());){var ae=h.callback;if(typeof ae=="function"){h.callback=null,m=h.priorityLevel;var he=ae(h.expirationTime<=ue);ue=s.unstable_now(),typeof he=="function"?h.callback=he:h===n(c)&&r(c),k(ue)}else r(c);h=n(c)}if(h!==null)var xe=!0;else{var ve=n(d);ve!==null&&ne(A,ve.startTime-ue),xe=!1}return xe}finally{h=null,m=ce,f=!1}}var P=!1,I=null,M=-1,L=5,z=-1;function $(){return!(s.unstable_now()-zme||125ae?(me.sortIndex=ce,t(d,me),n(c)===null&&me===n(d)&&(y?(_(M),M=-1):y=!0,ne(A,ce-ae))):(me.sortIndex=he,t(c,me),g||f||(g=!0,te(T))),me},s.unstable_shouldYield=$,s.unstable_wrapCallback=function(me){var ue=m;return function(){var ce=m;m=ue;try{return me.apply(this,arguments)}finally{m=ce}}}})(Syt);kyt.exports=Syt;var SG=kyt.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 rGt=N,$_=SG;function La(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"),KIe=Object.prototype.hasOwnProperty,aGt=/^[: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]*$/,dJe={},uJe={};function iGt(s){return KIe.call(uJe,s)?!0:KIe.call(dJe,s)?!1:aGt.test(s)?uJe[s]=!0:(dJe[s]=!0,!1)}function oGt(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 lGt(s,t,n,r){if(t===null||typeof t>"u"||oGt(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 i1(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 Q0={};"children dangerouslySetInnerHTML defaultValue defaultChecked innerHTML suppressContentEditableWarning suppressHydrationWarning style".split(" ").forEach(function(s){Q0[s]=new i1(s,0,!1,s,null,!1,!1)});[["acceptCharset","accept-charset"],["className","class"],["htmlFor","for"],["httpEquiv","http-equiv"]].forEach(function(s){var t=s[0];Q0[t]=new i1(t,1,!1,s[1],null,!1,!1)});["contentEditable","draggable","spellCheck","value"].forEach(function(s){Q0[s]=new i1(s,2,!1,s.toLowerCase(),null,!1,!1)});["autoReverse","externalResourcesRequired","focusable","preserveAlpha"].forEach(function(s){Q0[s]=new i1(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){Q0[s]=new i1(s,3,!1,s.toLowerCase(),null,!1,!1)});["checked","multiple","muted","selected"].forEach(function(s){Q0[s]=new i1(s,3,!0,s,null,!1,!1)});["capture","download"].forEach(function(s){Q0[s]=new i1(s,4,!1,s,null,!1,!1)});["cols","rows","size","span"].forEach(function(s){Q0[s]=new i1(s,6,!1,s,null,!1,!1)});["rowSpan","start"].forEach(function(s){Q0[s]=new i1(s,5,!1,s.toLowerCase(),null,!1,!1)});var lBe=/[\-:]([a-z])/g;function cBe(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(lBe,cBe);Q0[t]=new i1(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(lBe,cBe);Q0[t]=new i1(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(lBe,cBe);Q0[t]=new i1(t,1,!1,s,"http://www.w3.org/XML/1998/namespace",!1,!1)});["tabIndex","crossOrigin"].forEach(function(s){Q0[s]=new i1(s,1,!1,s.toLowerCase(),null,!1,!1)});Q0.xlinkHref=new i1("xlinkHref",1,!1,"xlink:href","http://www.w3.org/1999/xlink",!0,!1);["src","href","action","formAction"].forEach(function(s){Q0[s]=new i1(s,1,!1,s.toLowerCase(),null,!0,!0)});function dBe(s,t,n,r){var a=Q0.hasOwnProperty(t)?Q0[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{MEe=!1,Error.prepareStackTrace=n}return(s=s?s.displayName||s.name:"")?PH(s):""}function cGt(s){switch(s.tag){case 5:return PH(s.type);case 16:return PH("Lazy");case 13:return PH("Suspense");case 19:return PH("SuspenseList");case 0:case 2:case 15:return s=LEe(s.type,!1),s;case 11:return s=LEe(s.type.render,!1),s;case 1:return s=LEe(s.type,!0),s;default:return""}}function QIe(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 v7:return"Fragment";case y7:return"Portal";case YIe:return"Profiler";case uBe:return"StrictMode";case ZIe:return"Suspense";case XIe:return"SuspenseList"}if(typeof s=="object")switch(s.$$typeof){case Tyt:return(s.displayName||"Context")+".Consumer";case Ayt:return(s._context.displayName||"Context")+".Provider";case hBe:var t=s.render;return s=s.displayName,s||(s=t.displayName||t.name||"",s=s!==""?"ForwardRef("+s+")":"ForwardRef"),s;case mBe:return t=s.displayName||null,t!==null?t:QIe(s.type)||"Memo";case VC:t=s._payload,s=s._init;try{return QIe(s(t))}catch{}}return null}function dGt(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 QIe(t);case 8:return t===uBe?"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 sE(s){switch(typeof s){case"boolean":case"number":case"string":case"undefined":return s;case"object":return s;default:return""}}function Myt(s){var t=s.type;return(s=s.nodeName)&&s.toLowerCase()==="input"&&(t==="checkbox"||t==="radio")}function uGt(s){var t=Myt(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 lte(s){s._valueTracker||(s._valueTracker=uGt(s))}function Lyt(s){if(!s)return!1;var t=s._valueTracker;if(!t)return!0;var n=t.getValue(),r="";return s&&(r=Myt(s)?s.checked?"true":"false":s.value),s=r,s!==n?(t.setValue(s),!0):!1}function e2e(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 JIe(s,t){var n=t.checked;return Ip({},t,{defaultChecked:void 0,defaultValue:void 0,value:void 0,checked:n??s._wrapperState.initialChecked})}function mJe(s,t){var n=t.defaultValue==null?"":t.defaultValue,r=t.checked!=null?t.checked:t.defaultChecked;n=sE(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 Pyt(s,t){t=t.checked,t!=null&&dBe(s,"checked",t,!1)}function e8e(s,t){Pyt(s,t);var n=sE(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")?t8e(s,t.type,n):t.hasOwnProperty("defaultValue")&&t8e(s,t.type,sE(t.defaultValue)),t.checked==null&&t.defaultChecked!=null&&(s.defaultChecked=!!t.defaultChecked)}function pJe(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 t8e(s,t,n){(t!=="number"||e2e(s.ownerDocument)!==s)&&(n==null?s.defaultValue=""+s._wrapperState.initialValue:s.defaultValue!==""+n&&(s.defaultValue=""+n))}var IH=Array.isArray;function J7(s,t,n,r){if(s=s.options,t){t={};for(var a=0;a"+t.valueOf().toString()+"",t=cte.firstChild;s.firstChild;)s.removeChild(s.firstChild);for(;t.firstChild;)s.appendChild(t.firstChild)}});function FK(s,t){if(t){var n=s.firstChild;if(n&&n===s.lastChild&&n.nodeType===3){n.nodeValue=t;return}}s.textContent=t}var CG={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},hGt=["Webkit","ms","Moz","O"];Object.keys(CG).forEach(function(s){hGt.forEach(function(t){t=t+s.charAt(0).toUpperCase()+s.substring(1),CG[t]=CG[s]})});function Oyt(s,t,n){return t==null||typeof t=="boolean"||t===""?"":n||typeof t!="number"||t===0||CG.hasOwnProperty(s)&&CG[s]?(""+t).trim():t+"px"}function Fyt(s,t){s=s.style;for(var n in t)if(t.hasOwnProperty(n)){var r=n.indexOf("--")===0,a=Oyt(n,t[n],r);n==="float"&&(n="cssFloat"),r?s.setProperty(n,a):s[n]=a}}var mGt=Ip({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 r8e(s,t){if(t){if(mGt[s]&&(t.children!=null||t.dangerouslySetInnerHTML!=null))throw Error(La(137,s));if(t.dangerouslySetInnerHTML!=null){if(t.children!=null)throw Error(La(60));if(typeof t.dangerouslySetInnerHTML!="object"||!("__html"in t.dangerouslySetInnerHTML))throw Error(La(61))}if(t.style!=null&&typeof t.style!="object")throw Error(La(62))}}function a8e(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 i8e=null;function pBe(s){return s=s.target||s.srcElement||window,s.correspondingUseElement&&(s=s.correspondingUseElement),s.nodeType===3?s.parentNode:s}var o8e=null,e9=null,t9=null;function xJe(s){if(s=uQ(s)){if(typeof o8e!="function")throw Error(La(280));var t=s.stateNode;t&&(t=SSe(t),o8e(s.stateNode,s.type,t))}}function zyt(s){e9?t9?t9.push(s):t9=[s]:e9=s}function Byt(){if(e9){var s=e9,t=t9;if(t9=e9=null,xJe(s),t)for(s=0;s>>=0,s===0?32:31-(NGt(s)/kGt|0)|0}var dte=64,ute=4194304;function DH(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 r2e(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=DH(o):(i&=l,i!==0&&(r=DH(i)))}else l=n&~a,l!==0?r=DH(l):i!==0&&(r=DH(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 cQ(s,t,n){s.pendingLanes|=t,t!==536870912&&(s.suspendedLanes=0,s.pingedLanes=0),s=s.eventTimes,t=31-H2(t),s[t]=n}function TGt(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=TG),SJe=" ",CJe=!1;function ivt(s,t){switch(s){case"keyup":return nWt.indexOf(t.keyCode)!==-1;case"keydown":return t.keyCode!==229;case"keypress":case"mousedown":case"focusout":return!0;default:return!1}}function ovt(s){return s=s.detail,typeof s=="object"&&"data"in s?s.data:null}var b7=!1;function aWt(s,t){switch(s){case"compositionend":return ovt(t);case"keypress":return t.which!==32?null:(CJe=!0,SJe);case"textInput":return s=t.data,s===SJe&&CJe?null:s;default:return null}}function iWt(s,t){if(b7)return s==="compositionend"||!wBe&&ivt(s,t)?(s=rvt(),fre=vBe=tT=null,b7=!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=MJe(n)}}function uvt(s,t){return s&&t?s===t?!0:s&&s.nodeType===3?!1:t&&t.nodeType===3?uvt(s,t.parentNode):"contains"in s?s.contains(t):s.compareDocumentPosition?!!(s.compareDocumentPosition(t)&16):!1:!1}function hvt(){for(var s=window,t=e2e();t instanceof s.HTMLIFrameElement;){try{var n=typeof t.contentWindow.location.href=="string"}catch{n=!1}if(n)s=t.contentWindow;else break;t=e2e(s.document)}return t}function jBe(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 fWt(s){var t=hvt(),n=s.focusedElem,r=s.selectionRange;if(t!==n&&n&&n.ownerDocument&&uvt(n.ownerDocument.documentElement,n)){if(r!==null&&jBe(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=LJe(n,i);var l=LJe(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,_7=null,m8e=null,MG=null,p8e=!1;function PJe(s,t,n){var r=n.window===n?n.document:n.nodeType===9?n:n.ownerDocument;p8e||_7==null||_7!==e2e(r)||(r=_7,"selectionStart"in r&&jBe(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}),MG&&VK(MG,r)||(MG=r,r=o2e(m8e,"onSelect"),0N7||(s.current=b8e[N7],b8e[N7]=null,N7--)}function Dh(s,t){N7++,b8e[N7]=s.current,s.current=t}var nE={},Uy=CE(nE),J1=CE(!1),HD=nE;function kB(s,t){var n=s.type.contextTypes;if(!n)return nE;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 eb(s){return s=s.childContextTypes,s!=null}function c2e(){cm(J1),cm(Uy)}function BJe(s,t,n){if(Uy.current!==nE)throw Error(La(168));Dh(Uy,t),Dh(J1,n)}function _vt(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(La(108,dGt(s)||"Unknown",a));return Ip({},n,r)}function d2e(s){return s=(s=s.stateNode)&&s.__reactInternalMemoizedMergedChildContext||nE,HD=Uy.current,Dh(Uy,s),Dh(J1,J1.current),!0}function $Je(s,t,n){var r=s.stateNode;if(!r)throw Error(La(169));n?(s=_vt(s,t,HD),r.__reactInternalMemoizedMergedChildContext=s,cm(J1),cm(Uy),Dh(Uy,s)):cm(J1),Dh(J1,n)}var o4=null,CSe=!1,GEe=!1;function wvt(s){o4===null?o4=[s]:o4.push(s)}function CWt(s){CSe=!0,wvt(s)}function AE(){if(!GEe&&o4!==null){GEe=!0;var s=0,t=Wu;try{var n=o4;for(Wu=1;s>=l,a-=l,U4=1<<32-H2(t)+a|n<M?(L=I,I=null):L=I.sibling;var z=m(_,I,k[M],A);if(z===null){I===null&&(I=L);break}s&&I&&z.alternate===null&&t(_,I),b=i(z,b,M),P===null?T=z:P.sibling=z,P=z,I=L}if(M===k.length)return n(_,I),Dm&&X6(_,M),T;if(I===null){for(;MM?(L=I,I=null):L=I.sibling;var $=m(_,I,z.value,A);if($===null){I===null&&(I=L);break}s&&I&&$.alternate===null&&t(_,I),b=i($,b,M),P===null?T=$:P.sibling=$,P=$,I=L}if(z.done)return n(_,I),Dm&&X6(_,M),T;if(I===null){for(;!z.done;M++,z=k.next())z=h(_,z.value,A),z!==null&&(b=i(z,b,M),P===null?T=z:P.sibling=z,P=z);return Dm&&X6(_,M),T}for(I=r(_,I);!z.done;M++,z=k.next())z=f(I,_,M,z.value,A),z!==null&&(s&&z.alternate!==null&&I.delete(z.key===null?M:z.key),b=i(z,b,M),P===null?T=z:P.sibling=z,P=z);return s&&I.forEach(function(V){return t(_,V)}),Dm&&X6(_,M),T}function x(_,b,k,A){if(typeof k=="object"&&k!==null&&k.type===v7&&k.key===null&&(k=k.props.children),typeof k=="object"&&k!==null){switch(k.$$typeof){case ote:e:{for(var T=k.key,P=b;P!==null;){if(P.key===T){if(T=k.type,T===v7){if(P.tag===7){n(_,P.sibling),b=a(P,k.props.children),b.return=_,_=b;break e}}else if(P.elementType===T||typeof T=="object"&&T!==null&&T.$$typeof===VC&&VJe(T)===P.type){n(_,P.sibling),b=a(P,k.props),b.ref=xV(_,P,k),b.return=_,_=b;break e}n(_,P);break}else t(_,P);P=P.sibling}k.type===v7?(b=tD(k.props.children,_.mode,A,k.key),b.return=_,_=b):(A=jre(k.type,k.key,k.props,null,_.mode,A),A.ref=xV(_,b,k),A.return=_,_=A)}return l(_);case y7:e:{for(P=k.key;b!==null;){if(b.key===P)if(b.tag===4&&b.stateNode.containerInfo===k.containerInfo&&b.stateNode.implementation===k.implementation){n(_,b.sibling),b=a(b,k.children||[]),b.return=_,_=b;break e}else{n(_,b);break}else t(_,b);b=b.sibling}b=e6e(k,_.mode,A),b.return=_,_=b}return l(_);case VC:return P=k._init,x(_,b,P(k._payload),A)}if(IH(k))return g(_,b,k,A);if(hV(k))return y(_,b,k,A);yte(_,k)}return typeof k=="string"&&k!==""||typeof k=="number"?(k=""+k,b!==null&&b.tag===6?(n(_,b.sibling),b=a(b,k),b.return=_,_=b):(n(_,b),b=JEe(k,_.mode,A),b.return=_,_=b),l(_)):n(_,b)}return x}var CB=Svt(!0),Cvt=Svt(!1),m2e=CE(null),p2e=null,C7=null,CBe=null;function ABe(){CBe=C7=p2e=null}function TBe(s){var t=m2e.current;cm(m2e),s._currentValue=t}function j8e(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 n9(s,t){p2e=s,CBe=C7=null,s=s.dependencies,s!==null&&s.firstContext!==null&&(s.lanes&t&&(G1=!0),s.firstContext=null)}function bj(s){var t=s._currentValue;if(CBe!==s)if(s={context:s,memoizedValue:t,next:null},C7===null){if(p2e===null)throw Error(La(308));C7=s,p2e.dependencies={lanes:0,firstContext:s}}else C7=C7.next=s;return t}var CI=null;function EBe(s){CI===null?CI=[s]:CI.push(s)}function Avt(s,t,n,r){var a=t.interleaved;return a===null?(n.next=n,EBe(t)):(n.next=a.next,a.next=n),t.interleaved=n,_3(s,r)}function _3(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 HC=!1;function MBe(s){s.updateQueue={baseState:s.memoizedState,firstBaseUpdate:null,lastBaseUpdate:null,shared:{pending:null,interleaved:null,lanes:0},effects:null}}function Tvt(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 Q4(s,t){return{eventTime:s,lane:t,tag:0,payload:null,callback:null,next:null}}function yT(s,t,n){var r=s.updateQueue;if(r===null)return null;if(r=r.shared,Td&2){var a=r.pending;return a===null?t.next=t:(t.next=a.next,a.next=t),r.pending=t,_3(s,n)}return a=r.interleaved,a===null?(t.next=t,EBe(r)):(t.next=a.next,a.next=t),r.interleaved=t,_3(s,n)}function xre(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,gBe(s,n)}}function HJe(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 f2e(s,t,n,r){var a=s.updateQueue;HC=!1;var i=a.firstBaseUpdate,l=a.lastBaseUpdate,o=a.shared.pending;if(o!==null){a.shared.pending=null;var c=o,d=c.next;c.next=null,l===null?i=d:l.next=d,l=c;var u=s.alternate;u!==null&&(u=u.updateQueue,o=u.lastBaseUpdate,o!==l&&(o===null?u.firstBaseUpdate=d:o.next=d,u.lastBaseUpdate=c))}if(i!==null){var h=a.baseState;l=0,u=d=c=null,o=i;do{var m=o.lane,f=o.eventTime;if((r&m)===m){u!==null&&(u=u.next={eventTime:f,lane:0,tag:o.tag,payload:o.payload,callback:o.callback,next:null});e:{var g=s,y=o;switch(m=t,f=n,y.tag){case 1:if(g=y.payload,typeof g=="function"){h=g.call(f,h,m);break e}h=g;break e;case 3:g.flags=g.flags&-65537|128;case 0:if(g=y.payload,m=typeof g=="function"?g.call(f,h,m):g,m==null)break e;h=Ip({},h,m);break e;case 2:HC=!0}}o.callback!==null&&o.lane!==0&&(s.flags|=64,m=a.effects,m===null?a.effects=[o]:m.push(o))}else f={eventTime:f,lane:m,tag:o.tag,payload:o.payload,callback:o.callback,next:null},u===null?(d=u=f,c=h):u=u.next=f,l|=m;if(o=o.next,o===null){if(o=a.shared.pending,o===null)break;m=o,o=m.next,m.next=null,a.lastBaseUpdate=m,a.shared.pending=null}}while(!0);if(u===null&&(c=h),a.baseState=c,a.firstBaseUpdate=d,a.lastBaseUpdate=u,t=a.shared.interleaved,t!==null){a=t;do l|=a.lane,a=a.next;while(a!==t)}else i===null&&(a.shared.lanes=0);KD|=l,s.lanes=l,s.memoizedState=h}}function GJe(s,t,n){if(s=t.effects,t.effects=null,s!==null)for(t=0;tn?n:4,s(!0);var r=KEe.transition;KEe.transition={};try{s(!1),t()}finally{Wu=n,KEe.transition=r}}function Gvt(){return _j().memoizedState}function MWt(s,t,n){var r=bT(s);if(n={lane:r,action:n,hasEagerState:!1,eagerState:null,next:null},Wvt(s))Kvt(t,n);else if(n=Avt(s,t,n,r),n!==null){var a=Vv();G2(n,s,r,a),Yvt(n,t,r)}}function LWt(s,t,n){var r=bT(s),a={lane:r,action:n,hasEagerState:!1,eagerState:null,next:null};if(Wvt(s))Kvt(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,lN(o,l)){var c=t.interleaved;c===null?(a.next=a,EBe(t)):(a.next=c.next,c.next=a),t.interleaved=a;return}}catch{}finally{}n=Avt(s,t,a,r),n!==null&&(a=Vv(),G2(n,s,r,a),Yvt(n,t,r))}}function Wvt(s){var t=s.alternate;return s===Tp||t!==null&&t===Tp}function Kvt(s,t){LG=x2e=!0;var n=s.pending;n===null?t.next=t:(t.next=n.next,n.next=t),s.pending=t}function Yvt(s,t,n){if(n&4194240){var r=t.lanes;r&=s.pendingLanes,n|=r,t.lanes=n,gBe(s,n)}}var y2e={readContext:bj,useCallback:gy,useContext:gy,useEffect:gy,useImperativeHandle:gy,useInsertionEffect:gy,useLayoutEffect:gy,useMemo:gy,useReducer:gy,useRef:gy,useState:gy,useDebugValue:gy,useDeferredValue:gy,useTransition:gy,useMutableSource:gy,useSyncExternalStore:gy,useId:gy,unstable_isNewReconciler:!1},PWt={readContext:bj,useCallback:function(s,t){return pk().memoizedState=[s,t===void 0?null:t],s},useContext:bj,useEffect:KJe,useImperativeHandle:function(s,t,n){return n=n!=null?n.concat([s]):null,vre(4194308,4,$vt.bind(null,t,s),n)},useLayoutEffect:function(s,t){return vre(4194308,4,s,t)},useInsertionEffect:function(s,t){return vre(4,2,s,t)},useMemo:function(s,t){var n=pk();return t=t===void 0?null:t,s=s(),n.memoizedState=[s,t],s},useReducer:function(s,t,n){var r=pk();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=MWt.bind(null,Tp,s),[r.memoizedState,s]},useRef:function(s){var t=pk();return s={current:s},t.memoizedState=s},useState:WJe,useDebugValue:zBe,useDeferredValue:function(s){return pk().memoizedState=s},useTransition:function(){var s=WJe(!1),t=s[0];return s=EWt.bind(null,s[1]),pk().memoizedState=s,[t,s]},useMutableSource:function(){},useSyncExternalStore:function(s,t,n){var r=Tp,a=pk();if(Dm){if(n===void 0)throw Error(La(407));n=n()}else{if(n=t(),Gx===null)throw Error(La(349));WD&30||Pvt(r,t,n)}a.memoizedState=n;var i={value:n,getSnapshot:t};return a.queue=i,KJe(Dvt.bind(null,r,i,s),[s]),r.flags|=2048,QK(9,Ivt.bind(null,r,i,n,t),void 0,null),n},useId:function(){var s=pk(),t=Gx.identifierPrefix;if(Dm){var n=q4,r=U4;n=(r&~(1<<32-H2(r)-1)).toString(32)+n,t=":"+t+"R"+n,n=ZK++,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[Gk]=t,s[WK]=r,a1t(s,t,!1,!1),t.stateNode=s;e:{switch(l=a8e(n,r),n){case"dialog":tm("cancel",s),tm("close",s),a=r;break;case"iframe":case"object":case"embed":tm("load",s),a=r;break;case"video":case"audio":for(a=0;aEB&&(t.flags|=128,r=!0,yV(i,!1),t.lanes=4194304)}else{if(!r)if(s=g2e(l),s!==null){if(t.flags|=128,r=!0,n=s.updateQueue,n!==null&&(t.updateQueue=n,t.flags|=4),yV(i,!0),i.tail===null&&i.tailMode==="hidden"&&!l.alternate&&!Dm)return xy(t),null}else 2*Rf()-i.renderingStartTime>EB&&n!==1073741824&&(t.flags|=128,r=!0,yV(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=Rf(),t.sibling=null,n=bp.current,Dh(bp,r?n&1|2:n&1),t):(xy(t),null);case 22:case 23:return HBe(),r=t.memoizedState!==null,s!==null&&s.memoizedState!==null!==r&&(t.flags|=8192),r&&t.mode&1?u_&1073741824&&(xy(t),t.subtreeFlags&6&&(t.flags|=8192)):xy(t),null;case 24:return null;case 25:return null}throw Error(La(156,t.tag))}function $Wt(s,t){switch(kBe(t),t.tag){case 1:return eb(t.type)&&c2e(),s=t.flags,s&65536?(t.flags=s&-65537|128,t):null;case 3:return AB(),cm(J1),cm(Uy),IBe(),s=t.flags,s&65536&&!(s&128)?(t.flags=s&-65537|128,t):null;case 5:return PBe(t),null;case 13:if(cm(bp),s=t.memoizedState,s!==null&&s.dehydrated!==null){if(t.alternate===null)throw Error(La(340));SB()}return s=t.flags,s&65536?(t.flags=s&-65537|128,t):null;case 19:return cm(bp),null;case 4:return AB(),null;case 10:return TBe(t.type._context),null;case 22:case 23:return HBe(),null;case 24:return null;default:return null}}var bte=!1,Py=!1,UWt=typeof WeakSet=="function"?WeakSet:Set,Vi=null;function A7(s,t){var n=s.ref;if(n!==null)if(typeof n=="function")try{n(null)}catch(r){nf(s,t,r)}else n.current=null}function L8e(s,t,n){try{n()}catch(r){nf(s,t,r)}}var aet=!1;function qWt(s,t){if(f8e=a2e,s=hvt(),jBe(s)){if("selectionStart"in s)var n={start:s.selectionStart,end:s.selectionEnd};else e:{n=(n=s.ownerDocument)&&n.defaultView||window;var r=n.getSelection&&n.getSelection();if(r&&r.rangeCount!==0){n=r.anchorNode;var a=r.anchorOffset,i=r.focusNode;r=r.focusOffset;try{n.nodeType,i.nodeType}catch{n=null;break e}var l=0,o=-1,c=-1,d=0,u=0,h=s,m=null;t:for(;;){for(var f;h!==n||a!==0&&h.nodeType!==3||(o=l+a),h!==i||r!==0&&h.nodeType!==3||(c=l+r),h.nodeType===3&&(l+=h.nodeValue.length),(f=h.firstChild)!==null;)m=h,h=f;for(;;){if(h===s)break t;if(m===n&&++d===a&&(o=l),m===i&&++u===r&&(c=l),(f=h.nextSibling)!==null)break;h=m,m=h.parentNode}h=f}n=o===-1||c===-1?null:{start:o,end:c}}else n=null}n=n||{start:0,end:0}}else n=null;for(g8e={focusedElem:s,selectionRange:n},a2e=!1,Vi=t;Vi!==null;)if(t=Vi,s=t.child,(t.subtreeFlags&1028)!==0&&s!==null)s.return=t,Vi=s;else for(;Vi!==null;){t=Vi;try{var g=t.alternate;if(t.flags&1024)switch(t.tag){case 0:case 11:case 15:break;case 1:if(g!==null){var y=g.memoizedProps,x=g.memoizedState,_=t.stateNode,b=_.getSnapshotBeforeUpdate(t.elementType===t.type?y:h2(t.type,y),x);_.__reactInternalSnapshotBeforeUpdate=b}break;case 3:var k=t.stateNode.containerInfo;k.nodeType===1?k.textContent="":k.nodeType===9&&k.documentElement&&k.removeChild(k.documentElement);break;case 5:case 6:case 4:case 17:break;default:throw Error(La(163))}}catch(A){nf(t,t.return,A)}if(s=t.sibling,s!==null){s.return=t.return,Vi=s;break}Vi=t.return}return g=aet,aet=!1,g}function PG(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&&L8e(t,n,i)}a=a.next}while(a!==r)}}function ESe(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 P8e(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 l1t(s){var t=s.alternate;t!==null&&(s.alternate=null,l1t(t)),s.child=null,s.deletions=null,s.sibling=null,s.tag===5&&(t=s.stateNode,t!==null&&(delete t[Gk],delete t[WK],delete t[v8e],delete t[kWt],delete t[SWt])),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 c1t(s){return s.tag===5||s.tag===3||s.tag===4}function iet(s){e:for(;;){for(;s.sibling===null;){if(s.return===null||c1t(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 I8e(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=l2e));else if(r!==4&&(s=s.child,s!==null))for(I8e(s,t,n),s=s.sibling;s!==null;)I8e(s,t,n),s=s.sibling}function D8e(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(D8e(s,t,n),s=s.sibling;s!==null;)D8e(s,t,n),s=s.sibling}var C0=null,T2=!1;function pC(s,t,n){for(n=n.child;n!==null;)d1t(s,t,n),n=n.sibling}function d1t(s,t,n){if(o5&&typeof o5.onCommitFiberUnmount=="function")try{o5.onCommitFiberUnmount(wSe,n)}catch{}switch(n.tag){case 5:Py||A7(n,t);case 6:var r=C0,a=T2;C0=null,pC(s,t,n),C0=r,T2=a,C0!==null&&(T2?(s=C0,n=n.stateNode,s.nodeType===8?s.parentNode.removeChild(n):s.removeChild(n)):C0.removeChild(n.stateNode));break;case 18:C0!==null&&(T2?(s=C0,n=n.stateNode,s.nodeType===8?HEe(s.parentNode,n):s.nodeType===1&&HEe(s,n),UK(s)):HEe(C0,n.stateNode));break;case 4:r=C0,a=T2,C0=n.stateNode.containerInfo,T2=!0,pC(s,t,n),C0=r,T2=a;break;case 0:case 11:case 14:case 15:if(!Py&&(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)&&L8e(n,t,l),a=a.next}while(a!==r)}pC(s,t,n);break;case 1:if(!Py&&(A7(n,t),r=n.stateNode,typeof r.componentWillUnmount=="function"))try{r.props=n.memoizedProps,r.state=n.memoizedState,r.componentWillUnmount()}catch(o){nf(n,t,o)}pC(s,t,n);break;case 21:pC(s,t,n);break;case 22:n.mode&1?(Py=(r=Py)||n.memoizedState!==null,pC(s,t,n),Py=r):pC(s,t,n);break;default:pC(s,t,n)}}function oet(s){var t=s.updateQueue;if(t!==null){s.updateQueue=null;var n=s.stateNode;n===null&&(n=s.stateNode=new UWt),t.forEach(function(r){var a=QWt.bind(null,s,r);n.has(r)||(n.add(r),r.then(a,a))})}}function t2(s,t){var n=t.deletions;if(n!==null)for(var r=0;ra&&(a=l),r&=~i}if(r=a,r=Rf()-r,r=(120>r?120:480>r?480:1080>r?1080:1920>r?1920:3e3>r?3e3:4320>r?4320:1960*HWt(r/1960))-r,10s?16:s,sT===null)var r=!1;else{if(s=sT,sT=null,_2e=0,Td&6)throw Error(La(331));var a=Td;for(Td|=4,Vi=s.current;Vi!==null;){var i=Vi,l=i.child;if(Vi.flags&16){var o=i.deletions;if(o!==null){for(var c=0;cRf()-qBe?eD(s,0):UBe|=n),tb(s,t)}function y1t(s,t){t===0&&(s.mode&1?(t=ute,ute<<=1,!(ute&130023424)&&(ute=4194304)):t=1);var n=Vv();s=_3(s,t),s!==null&&(cQ(s,t,n),tb(s,n))}function XWt(s){var t=s.memoizedState,n=0;t!==null&&(n=t.retryLane),y1t(s,n)}function QWt(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(La(314))}r!==null&&r.delete(t),y1t(s,n)}var v1t;v1t=function(s,t,n){if(s!==null)if(s.memoizedProps!==t.pendingProps||J1.current)G1=!0;else{if(!(s.lanes&n)&&!(t.flags&128))return G1=!1,zWt(s,t,n);G1=!!(s.flags&131072)}else G1=!1,Dm&&t.flags&1048576&&jvt(t,h2e,t.index);switch(t.lanes=0,t.tag){case 2:var r=t.type;bre(s,t),s=t.pendingProps;var a=kB(t,Uy.current);n9(t,n),a=RBe(null,t,r,s,a,n);var i=OBe();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,eb(r)?(i=!0,d2e(t)):i=!1,t.memoizedState=a.state!==null&&a.state!==void 0?a.state:null,MBe(t),a.updater=TSe,t.stateNode=a,a._reactInternals=t,k8e(t,r,s,n),t=A8e(null,t,r,!0,i,n)):(t.tag=0,Dm&&i&&NBe(t),Cv(null,t,a,n),t=t.child),t;case 16:r=t.elementType;e:{switch(bre(s,t),s=t.pendingProps,a=r._init,r=a(r._payload),t.type=r,a=t.tag=eKt(r),s=h2(r,s),a){case 0:t=C8e(null,t,r,s,n);break e;case 1:t=set(null,t,r,s,n);break e;case 11:t=eet(null,t,r,s,n);break e;case 14:t=tet(null,t,r,h2(r.type,s),n);break e}throw Error(La(306,r,""))}return t;case 0:return r=t.type,a=t.pendingProps,a=t.elementType===r?a:h2(r,a),C8e(s,t,r,a,n);case 1:return r=t.type,a=t.pendingProps,a=t.elementType===r?a:h2(r,a),set(s,t,r,a,n);case 3:e:{if(s1t(t),s===null)throw Error(La(387));r=t.pendingProps,i=t.memoizedState,a=i.element,Tvt(s,t),f2e(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=TB(Error(La(423)),t),t=net(s,t,r,n,a);break e}else if(r!==a){a=TB(Error(La(424)),t),t=net(s,t,r,n,a);break e}else for(N_=xT(t.stateNode.containerInfo.firstChild),C_=t,Dm=!0,D2=null,n=Cvt(t,null,r,n),t.child=n;n;)n.flags=n.flags&-3|4096,n=n.sibling;else{if(SB(),r===a){t=w3(s,t,n);break e}Cv(s,t,r,n)}t=t.child}return t;case 5:return Evt(t),s===null&&w8e(t),r=t.type,a=t.pendingProps,i=s!==null?s.memoizedProps:null,l=a.children,x8e(r,a)?l=null:i!==null&&x8e(r,i)&&(t.flags|=32),t1t(s,t),Cv(s,t,l,n),t.child;case 6:return s===null&&w8e(t),null;case 13:return n1t(s,t,n);case 4:return LBe(t,t.stateNode.containerInfo),r=t.pendingProps,s===null?t.child=CB(t,null,r,n):Cv(s,t,r,n),t.child;case 11:return r=t.type,a=t.pendingProps,a=t.elementType===r?a:h2(r,a),eet(s,t,r,a,n);case 7:return Cv(s,t,t.pendingProps,n),t.child;case 8:return Cv(s,t,t.pendingProps.children,n),t.child;case 12:return Cv(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,Dh(m2e,r._currentValue),r._currentValue=l,i!==null)if(lN(i.value,l)){if(i.children===a.children&&!J1.current){t=w3(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=Q4(-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),j8e(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(La(341));l.lanes|=n,o=l.alternate,o!==null&&(o.lanes|=n),j8e(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}Cv(s,t,a.children,n),t=t.child}return t;case 9:return a=t.type,r=t.pendingProps.children,n9(t,n),a=bj(a),r=r(a),t.flags|=1,Cv(s,t,r,n),t.child;case 14:return r=t.type,a=h2(r,t.pendingProps),a=h2(r.type,a),tet(s,t,r,a,n);case 15:return Jvt(s,t,t.type,t.pendingProps,n);case 17:return r=t.type,a=t.pendingProps,a=t.elementType===r?a:h2(r,a),bre(s,t),t.tag=1,eb(r)?(s=!0,d2e(t)):s=!1,n9(t,n),Zvt(t,r,a),k8e(t,r,a,n),A8e(null,t,r,!0,s,n);case 19:return r1t(s,t,n);case 22:return e1t(s,t,n)}throw Error(La(156,t.tag))};function b1t(s,t){return Wyt(s,t)}function JWt(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 sj(s,t,n,r){return new JWt(s,t,n,r)}function WBe(s){return s=s.prototype,!(!s||!s.isReactComponent)}function eKt(s){if(typeof s=="function")return WBe(s)?1:0;if(s!=null){if(s=s.$$typeof,s===hBe)return 11;if(s===mBe)return 14}return 2}function _T(s,t){var n=s.alternate;return n===null?(n=sj(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 jre(s,t,n,r,a,i){var l=2;if(r=s,typeof s=="function")WBe(s)&&(l=1);else if(typeof s=="string")l=5;else e:switch(s){case v7:return tD(n.children,a,i,t);case uBe:l=8,a|=8;break;case YIe:return s=sj(12,n,t,a|2),s.elementType=YIe,s.lanes=i,s;case ZIe:return s=sj(13,n,t,a),s.elementType=ZIe,s.lanes=i,s;case XIe:return s=sj(19,n,t,a),s.elementType=XIe,s.lanes=i,s;case Eyt:return LSe(n,a,i,t);default:if(typeof s=="object"&&s!==null)switch(s.$$typeof){case Ayt:l=10;break e;case Tyt:l=9;break e;case hBe:l=11;break e;case mBe:l=14;break e;case VC:l=16,r=null;break e}throw Error(La(130,s==null?s:typeof s,""))}return t=sj(l,n,t,a),t.elementType=s,t.type=r,t.lanes=i,t}function tD(s,t,n,r){return s=sj(7,s,r,t),s.lanes=n,s}function LSe(s,t,n,r){return s=sj(22,s,r,t),s.elementType=Eyt,s.lanes=n,s.stateNode={isHidden:!1},s}function JEe(s,t,n){return s=sj(6,s,null,t),s.lanes=n,s}function e6e(s,t,n){return t=sj(4,s.children!==null?s.children:[],s.key,t),t.lanes=n,t.stateNode={containerInfo:s.containerInfo,pendingChildren:null,implementation:s.implementation},t}function tKt(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=IEe(0),this.expirationTimes=IEe(-1),this.entangledLanes=this.finishedLanes=this.mutableReadLanes=this.expiredLanes=this.pingedLanes=this.suspendedLanes=this.pendingLanes=0,this.entanglements=IEe(0),this.identifierPrefix=r,this.onRecoverableError=a,this.mutableSourceEagerHydrationData=null}function KBe(s,t,n,r,a,i,l,o,c){return s=new tKt(s,t,n,o,c),t===1?(t=1,i===!0&&(t|=8)):t=0,i=sj(3,null,null,t),s.current=i,i.stateNode=s,i.memoizedState={element:r,isDehydrated:n,cache:null,transitions:null,pendingSuspenseBoundaries:null},MBe(i),s}function sKt(s,t,n){var r=3"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(N1t)}catch(s){console.error(s)}}N1t(),Nyt.exports=G_;var Lv=Nyt.exports;const QBe=Xc(Lv);var k1t,get=Lv;k1t=get.createRoot,get.hydrateRoot;const oKt=1,lKt=1e6;let t6e=0;function cKt(){return t6e=(t6e+1)%Number.MAX_SAFE_INTEGER,t6e.toString()}const s6e=new Map,xet=s=>{if(s6e.has(s))return;const t=setTimeout(()=>{s6e.delete(s),RG({type:"REMOVE_TOAST",toastId:s})},lKt);s6e.set(s,t)},dKt=(s,t)=>{switch(t.type){case"ADD_TOAST":return{...s,toasts:[t.toast,...s.toasts].slice(0,oKt)};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?xet(n):s.toasts.forEach(r=>{xet(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)}}},Nre=[];let kre={toasts:[]};function RG(s){kre=dKt(kre,s),Nre.forEach(t=>{t(kre)})}function xa({...s}){const t=cKt(),n=a=>RG({type:"UPDATE_TOAST",toast:{...a,id:t}}),r=()=>RG({type:"DISMISS_TOAST",toastId:t});return RG({type:"ADD_TOAST",toast:{...s,id:t,open:!0,onOpenChange:a=>{a||r()}}}),{id:t,dismiss:r,update:n}}function Ci(){const[s,t]=N.useState(kre);return N.useEffect(()=>(Nre.push(t),()=>{const n=Nre.indexOf(t);n>-1&&Nre.splice(n,1)}),[s]),{...s,toast:xa,dismiss:n=>RG({type:"DISMISS_TOAST",toastId:n})}}function la(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 yet(s,t){if(typeof s=="function")return s(t);s!=null&&(s.current=t)}function j3(...s){return t=>{let n=!1;const r=s.map(a=>{const i=yet(a,t);return!n&&typeof i=="function"&&(n=!0),i});if(n)return()=>{for(let a=0;a{const{children:l,...o}=i,c=N.useMemo(()=>o,Object.values(o));return e.jsx(n.Provider,{value:c,children:l})};r.displayName=s+"Provider";function a(i){const l=N.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 Um(s,t=[]){let n=[];function r(i,l){const o=N.createContext(l),c=n.length;n=[...n,l];const d=h=>{var _;const{scope:m,children:f,...g}=h,y=((_=m==null?void 0:m[s])==null?void 0:_[c])||o,x=N.useMemo(()=>g,Object.values(g));return e.jsx(y.Provider,{value:x,children:f})};d.displayName=i+"Provider";function u(h,m){var y;const f=((y=m==null?void 0:m[s])==null?void 0:y[c])||o,g=N.useContext(f);if(g)return g;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=>N.createContext(l));return function(o){const c=(o==null?void 0:o[s])||i;return N.useMemo(()=>({[`__scope${s}`]:{...o,[s]:c}}),[o,c])}};return a.scopeName=s,[r,hKt(a,...t)]}function hKt(...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 N.useMemo(()=>({[`__scope${t.scopeName}`]:l}),[l])}};return n.scopeName=t.scopeName,n}function rE(s){const t=mKt(s),n=N.forwardRef((r,a)=>{const{children:i,...l}=r,o=N.Children.toArray(i),c=o.find(pKt);if(c){const d=c.props.children,u=o.map(h=>h===c?N.Children.count(d)>1?N.Children.only(null):N.isValidElement(d)?d.props.children:null:h);return e.jsx(t,{...l,ref:a,children:N.isValidElement(d)?N.cloneElement(d,void 0,u):null})}return e.jsx(t,{...l,ref:a,children:i})});return n.displayName=`${s}.Slot`,n}var JBe=rE("Slot");function mKt(s){const t=N.forwardRef((n,r)=>{const{children:a,...i}=n;if(N.isValidElement(a)){const l=gKt(a),o=fKt(i,a.props);return a.type!==N.Fragment&&(o.ref=r?j3(r,l):l),N.cloneElement(a,o)}return N.Children.count(a)>1?N.Children.only(null):null});return t.displayName=`${s}.SlotClone`,t}var S1t=Symbol("radix.slottable");function C1t(s){const t=({children:n})=>e.jsx(e.Fragment,{children:n});return t.displayName=`${s}.Slottable`,t.__radixId=S1t,t}function pKt(s){return N.isValidElement(s)&&typeof s.type=="function"&&"__radixId"in s.type&&s.type.__radixId===S1t}function fKt(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 gKt(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 K$(s){const t=s+"CollectionProvider",[n,r]=Um(t),[a,i]=n(t,{collectionRef:{current:null},itemMap:new Map}),l=y=>{const{scope:x,children:_}=y,b=Rt.useRef(null),k=Rt.useRef(new Map).current;return e.jsx(a,{scope:x,itemMap:k,collectionRef:b,children:_})};l.displayName=t;const o=s+"CollectionSlot",c=rE(o),d=Rt.forwardRef((y,x)=>{const{scope:_,children:b}=y,k=i(o,_),A=jo(x,k.collectionRef);return e.jsx(c,{ref:A,children:b})});d.displayName=o;const u=s+"CollectionItemSlot",h="data-radix-collection-item",m=rE(u),f=Rt.forwardRef((y,x)=>{const{scope:_,children:b,...k}=y,A=Rt.useRef(null),T=jo(x,A),P=i(u,_);return Rt.useEffect(()=>(P.itemMap.set(A,{ref:A,...k}),()=>void P.itemMap.delete(A))),e.jsx(m,{[h]:"",ref:T,children:b})});f.displayName=u;function g(y){const x=i(s+"CollectionConsumer",y);return Rt.useCallback(()=>{const b=x.collectionRef.current;if(!b)return[];const k=Array.from(b.querySelectorAll(`[${h}]`));return Array.from(x.itemMap.values()).sort((P,I)=>k.indexOf(P.ref.current)-k.indexOf(I.ref.current))},[x.collectionRef,x.itemMap])}return[{Provider:l,Slot:d,ItemSlot:f},g,r]}var xKt=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","select","span","svg","ul"],Da=xKt.reduce((s,t)=>{const n=rE(`Primitive.${t}`),r=N.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 e$e(s,t){s&&Lv.flushSync(()=>s.dispatchEvent(t))}function cf(s){const t=N.useRef(s);return N.useEffect(()=>{t.current=s}),N.useMemo(()=>(...n)=>{var r;return(r=t.current)==null?void 0:r.call(t,...n)},[])}function yKt(s,t=globalThis==null?void 0:globalThis.document){const n=cf(s);N.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 vKt="DismissableLayer",B8e="dismissableLayer.update",bKt="dismissableLayer.pointerDownOutside",_Kt="dismissableLayer.focusOutside",vet,A1t=N.createContext({layers:new Set,layersWithOutsidePointerEventsDisabled:new Set,branches:new Set}),TE=N.forwardRef((s,t)=>{const{disableOutsidePointerEvents:n=!1,onEscapeKeyDown:r,onPointerDownOutside:a,onFocusOutside:i,onInteractOutside:l,onDismiss:o,...c}=s,d=N.useContext(A1t),[u,h]=N.useState(null),m=(u==null?void 0:u.ownerDocument)??(globalThis==null?void 0:globalThis.document),[,f]=N.useState({}),g=jo(t,I=>h(I)),y=Array.from(d.layers),[x]=[...d.layersWithOutsidePointerEventsDisabled].slice(-1),_=y.indexOf(x),b=u?y.indexOf(u):-1,k=d.layersWithOutsidePointerEventsDisabled.size>0,A=b>=_,T=jKt(I=>{const M=I.target,L=[...d.branches].some(z=>z.contains(M));!A||L||(a==null||a(I),l==null||l(I),I.defaultPrevented||o==null||o())},m),P=NKt(I=>{const M=I.target;[...d.branches].some(z=>z.contains(M))||(i==null||i(I),l==null||l(I),I.defaultPrevented||o==null||o())},m);return yKt(I=>{b===d.layers.size-1&&(r==null||r(I),!I.defaultPrevented&&o&&(I.preventDefault(),o()))},m),N.useEffect(()=>{if(u)return n&&(d.layersWithOutsidePointerEventsDisabled.size===0&&(vet=m.body.style.pointerEvents,m.body.style.pointerEvents="none"),d.layersWithOutsidePointerEventsDisabled.add(u)),d.layers.add(u),bet(),()=>{n&&d.layersWithOutsidePointerEventsDisabled.size===1&&(m.body.style.pointerEvents=vet)}},[u,m,n,d]),N.useEffect(()=>()=>{u&&(d.layers.delete(u),d.layersWithOutsidePointerEventsDisabled.delete(u),bet())},[u,d]),N.useEffect(()=>{const I=()=>f({});return document.addEventListener(B8e,I),()=>document.removeEventListener(B8e,I)},[]),e.jsx(Da.div,{...c,ref:g,style:{pointerEvents:k?A?"auto":"none":void 0,...s.style},onFocusCapture:la(s.onFocusCapture,P.onFocusCapture),onBlurCapture:la(s.onBlurCapture,P.onBlurCapture),onPointerDownCapture:la(s.onPointerDownCapture,T.onPointerDownCapture)})});TE.displayName=vKt;var wKt="DismissableLayerBranch",T1t=N.forwardRef((s,t)=>{const n=N.useContext(A1t),r=N.useRef(null),a=jo(t,r);return N.useEffect(()=>{const i=r.current;if(i)return n.branches.add(i),()=>{n.branches.delete(i)}},[n.branches]),e.jsx(Da.div,{...s,ref:a})});T1t.displayName=wKt;function jKt(s,t=globalThis==null?void 0:globalThis.document){const n=cf(s),r=N.useRef(!1),a=N.useRef(()=>{});return N.useEffect(()=>{const i=o=>{if(o.target&&!r.current){let c=function(){E1t(bKt,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 NKt(s,t=globalThis==null?void 0:globalThis.document){const n=cf(s),r=N.useRef(!1);return N.useEffect(()=>{const a=i=>{i.target&&!r.current&&E1t(_Kt,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 bet(){const s=new CustomEvent(B8e);document.dispatchEvent(s)}function E1t(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?e$e(a,i):a.dispatchEvent(i)}var kKt=TE,SKt=T1t,gf=globalThis!=null&&globalThis.document?N.useLayoutEffect:()=>{},CKt="Portal",Y$=N.forwardRef((s,t)=>{var o;const{container:n,...r}=s,[a,i]=N.useState(!1);gf(()=>i(!0),[]);const l=n||a&&((o=globalThis==null?void 0:globalThis.document)==null?void 0:o.body);return l?QBe.createPortal(e.jsx(Da.div,{...r,ref:t}),l):null});Y$.displayName=CKt;function AKt(s,t){return N.useReducer((n,r)=>t[n][r]??n,s)}var Xf=s=>{const{present:t,children:n}=s,r=TKt(t),a=typeof n=="function"?n({present:r.isPresent}):N.Children.only(n),i=jo(r.ref,EKt(a));return typeof n=="function"||r.isPresent?N.cloneElement(a,{ref:i}):null};Xf.displayName="Presence";function TKt(s){const[t,n]=N.useState(),r=N.useRef(null),a=N.useRef(s),i=N.useRef("none"),l=s?"mounted":"unmounted",[o,c]=AKt(l,{mounted:{UNMOUNT:"unmounted",ANIMATION_OUT:"unmountSuspended"},unmountSuspended:{MOUNT:"mounted",ANIMATION_END:"unmounted"},unmounted:{MOUNT:"mounted"}});return N.useEffect(()=>{const d=jte(r.current);i.current=o==="mounted"?d:"none"},[o]),gf(()=>{const d=r.current,u=a.current;if(u!==s){const m=i.current,f=jte(d);s?c("MOUNT"):f==="none"||(d==null?void 0:d.display)==="none"?c("UNMOUNT"):c(u&&m!==f?"ANIMATION_OUT":"UNMOUNT"),a.current=s}},[s,c]),gf(()=>{if(t){let d;const u=t.ownerDocument.defaultView??window,h=f=>{const y=jte(r.current).includes(f.animationName);if(f.target===t&&y&&(c("ANIMATION_END"),!a.current)){const x=t.style.animationFillMode;t.style.animationFillMode="forwards",d=u.setTimeout(()=>{t.style.animationFillMode==="forwards"&&(t.style.animationFillMode=x)})}},m=f=>{f.target===t&&(i.current=jte(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:N.useCallback(d=>{r.current=d?getComputedStyle(d):null,n(d)},[])}}function jte(s){return(s==null?void 0:s.animationName)||"none"}function EKt(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 MKt=oBe[" useInsertionEffect ".trim().toString()]||gf;function Ng({prop:s,defaultProp:t,onChange:n=()=>{},caller:r}){const[a,i,l]=LKt({defaultProp:t,onChange:n}),o=s!==void 0,c=o?s:a;{const u=N.useRef(s!==void 0);N.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=N.useCallback(u=>{var h;if(o){const m=PKt(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 LKt({defaultProp:s,onChange:t}){const[n,r]=N.useState(s),a=N.useRef(n),i=N.useRef(t);return MKt(()=>{i.current=t},[t]),N.useEffect(()=>{var l;a.current!==n&&((l=i.current)==null||l.call(i,n),a.current=n)},[n,a]),[n,r,i]}function PKt(s){return typeof s=="function"}var M1t=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"}),IKt="VisuallyHidden",OSe=N.forwardRef((s,t)=>e.jsx(Da.span,{...s,ref:t,style:{...M1t,...s.style}}));OSe.displayName=IKt;var DKt=OSe,t$e="ToastProvider",[s$e,RKt,OKt]=K$("Toast"),[L1t,hOn]=Um("Toast",[OKt]),[FKt,FSe]=L1t(t$e),P1t=s=>{const{__scopeToast:t,label:n="Notification",duration:r=5e3,swipeDirection:a="right",swipeThreshold:i=50,children:l}=s,[o,c]=N.useState(null),[d,u]=N.useState(0),h=N.useRef(!1),m=N.useRef(!1);return n.trim()||console.error(`Invalid prop \`label\` supplied to \`${t$e}\`. Expected non-empty \`string\`.`),e.jsx(s$e.Provider,{scope:t,children:e.jsx(FKt,{scope:t,label:n,duration:r,swipeDirection:a,swipeThreshold:i,toastCount:d,viewport:o,onViewportChange:c,onToastAdd:N.useCallback(()=>u(f=>f+1),[]),onToastRemove:N.useCallback(()=>u(f=>f-1),[]),isFocusedToastEscapeKeyDownRef:h,isClosePausedRef:m,children:l})})};P1t.displayName=t$e;var I1t="ToastViewport",zKt=["F8"],$8e="toast.viewportPause",U8e="toast.viewportResume",D1t=N.forwardRef((s,t)=>{const{__scopeToast:n,hotkey:r=zKt,label:a="Notifications ({hotkey})",...i}=s,l=FSe(I1t,n),o=RKt(n),c=N.useRef(null),d=N.useRef(null),u=N.useRef(null),h=N.useRef(null),m=jo(t,h,l.onViewportChange),f=r.join("+").replace(/Key/g,"").replace(/Digit/g,""),g=l.toastCount>0;N.useEffect(()=>{const x=_=>{var k;r.length!==0&&r.every(A=>_[A]||_.code===A)&&((k=h.current)==null||k.focus())};return document.addEventListener("keydown",x),()=>document.removeEventListener("keydown",x)},[r]),N.useEffect(()=>{const x=c.current,_=h.current;if(g&&x&&_){const b=()=>{if(!l.isClosePausedRef.current){const P=new CustomEvent($8e);_.dispatchEvent(P),l.isClosePausedRef.current=!0}},k=()=>{if(l.isClosePausedRef.current){const P=new CustomEvent(U8e);_.dispatchEvent(P),l.isClosePausedRef.current=!1}},A=P=>{!x.contains(P.relatedTarget)&&k()},T=()=>{x.contains(document.activeElement)||k()};return x.addEventListener("focusin",b),x.addEventListener("focusout",A),x.addEventListener("pointermove",b),x.addEventListener("pointerleave",T),window.addEventListener("blur",b),window.addEventListener("focus",k),()=>{x.removeEventListener("focusin",b),x.removeEventListener("focusout",A),x.removeEventListener("pointermove",b),x.removeEventListener("pointerleave",T),window.removeEventListener("blur",b),window.removeEventListener("focus",k)}}},[g,l.isClosePausedRef]);const y=N.useCallback(({tabbingDirection:x})=>{const b=o().map(k=>{const A=k.ref.current,T=[A,...QKt(A)];return x==="forwards"?T:T.reverse()});return(x==="forwards"?b.reverse():b).flat()},[o]);return N.useEffect(()=>{const x=h.current;if(x){const _=b=>{var T,P,I;const k=b.altKey||b.ctrlKey||b.metaKey;if(b.key==="Tab"&&!k){const M=document.activeElement,L=b.shiftKey;if(b.target===x&&L){(T=d.current)==null||T.focus();return}const V=y({tabbingDirection:L?"backwards":"forwards"}),W=V.findIndex(G=>G===M);n6e(V.slice(W+1))?b.preventDefault():L?(P=d.current)==null||P.focus():(I=u.current)==null||I.focus()}};return x.addEventListener("keydown",_),()=>x.removeEventListener("keydown",_)}},[o,y]),e.jsxs(SKt,{ref:c,role:"region","aria-label":a.replace("{hotkey}",f),tabIndex:-1,style:{pointerEvents:g?void 0:"none"},children:[g&&e.jsx(q8e,{ref:d,onFocusFromOutsideViewport:()=>{const x=y({tabbingDirection:"forwards"});n6e(x)}}),e.jsx(s$e.Slot,{scope:n,children:e.jsx(Da.ol,{tabIndex:-1,...i,ref:m})}),g&&e.jsx(q8e,{ref:u,onFocusFromOutsideViewport:()=>{const x=y({tabbingDirection:"backwards"});n6e(x)}})]})});D1t.displayName=I1t;var R1t="ToastFocusProxy",q8e=N.forwardRef((s,t)=>{const{__scopeToast:n,onFocusFromOutsideViewport:r,...a}=s,i=FSe(R1t,n);return e.jsx(OSe,{"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()}})});q8e.displayName=R1t;var mQ="Toast",BKt="toast.swipeStart",$Kt="toast.swipeMove",UKt="toast.swipeCancel",qKt="toast.swipeEnd",O1t=N.forwardRef((s,t)=>{const{forceMount:n,open:r,defaultOpen:a,onOpenChange:i,...l}=s,[o,c]=Ng({prop:r,defaultProp:a??!0,onChange:i,caller:mQ});return e.jsx(Xf,{present:n||o,children:e.jsx(GKt,{open:o,...l,ref:t,onClose:()=>c(!1),onPause:cf(s.onPause),onResume:cf(s.onResume),onSwipeStart:la(s.onSwipeStart,d=>{d.currentTarget.setAttribute("data-swipe","start")}),onSwipeMove:la(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:la(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:la(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)})})})});O1t.displayName=mQ;var[VKt,HKt]=L1t(mQ,{onClose(){}}),GKt=N.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:f,...g}=s,y=FSe(mQ,n),[x,_]=N.useState(null),b=jo(t,G=>_(G)),k=N.useRef(null),A=N.useRef(null),T=a||y.duration,P=N.useRef(0),I=N.useRef(T),M=N.useRef(0),{onToastAdd:L,onToastRemove:z}=y,$=cf(()=>{var X;(x==null?void 0:x.contains(document.activeElement))&&((X=y.viewport)==null||X.focus()),l()}),V=N.useCallback(G=>{!G||G===1/0||(window.clearTimeout(M.current),P.current=new Date().getTime(),M.current=window.setTimeout($,G))},[$]);N.useEffect(()=>{const G=y.viewport;if(G){const X=()=>{V(I.current),d==null||d()},te=()=>{const ne=new Date().getTime()-P.current;I.current=I.current-ne,window.clearTimeout(M.current),c==null||c()};return G.addEventListener($8e,te),G.addEventListener(U8e,X),()=>{G.removeEventListener($8e,te),G.removeEventListener(U8e,X)}}},[y.viewport,T,c,d,V]),N.useEffect(()=>{i&&!y.isClosePausedRef.current&&V(T)},[i,T,y.isClosePausedRef,V]),N.useEffect(()=>(L(),()=>z()),[L,z]);const W=N.useMemo(()=>x?V1t(x):null,[x]);return y.viewport?e.jsxs(e.Fragment,{children:[W&&e.jsx(WKt,{__scopeToast:n,role:"status","aria-live":r==="foreground"?"assertive":"polite","aria-atomic":!0,children:W}),e.jsx(VKt,{scope:n,onClose:$,children:Lv.createPortal(e.jsx(s$e.ItemSlot,{scope:n,children:e.jsx(kKt,{asChild:!0,onEscapeKeyDown:la(o,()=>{y.isFocusedToastEscapeKeyDownRef.current||$(),y.isFocusedToastEscapeKeyDownRef.current=!1}),children:e.jsx(Da.li,{role:"status","aria-live":"off","aria-atomic":!0,tabIndex:0,"data-state":i?"open":"closed","data-swipe-direction":y.swipeDirection,...g,ref:b,style:{userSelect:"none",touchAction:"none",...s.style},onKeyDown:la(s.onKeyDown,G=>{G.key==="Escape"&&(o==null||o(G.nativeEvent),G.nativeEvent.defaultPrevented||(y.isFocusedToastEscapeKeyDownRef.current=!0,$()))}),onPointerDown:la(s.onPointerDown,G=>{G.button===0&&(k.current={x:G.clientX,y:G.clientY})}),onPointerMove:la(s.onPointerMove,G=>{if(!k.current)return;const X=G.clientX-k.current.x,te=G.clientY-k.current.y,ne=!!A.current,me=["left","right"].includes(y.swipeDirection),ue=["left","up"].includes(y.swipeDirection)?Math.min:Math.max,ce=me?ue(0,X):0,ae=me?0:ue(0,te),he=G.pointerType==="touch"?10:2,xe={x:ce,y:ae},ve={originalEvent:G,delta:xe};ne?(A.current=xe,Nte($Kt,h,ve,{discrete:!1})):_et(xe,y.swipeDirection,he)?(A.current=xe,Nte(BKt,u,ve,{discrete:!1}),G.target.setPointerCapture(G.pointerId)):(Math.abs(X)>he||Math.abs(te)>he)&&(k.current=null)}),onPointerUp:la(s.onPointerUp,G=>{const X=A.current,te=G.target;if(te.hasPointerCapture(G.pointerId)&&te.releasePointerCapture(G.pointerId),A.current=null,k.current=null,X){const ne=G.currentTarget,me={originalEvent:G,delta:X};_et(X,y.swipeDirection,y.swipeThreshold)?Nte(qKt,f,me,{discrete:!0}):Nte(UKt,m,me,{discrete:!0}),ne.addEventListener("click",ue=>ue.preventDefault(),{once:!0})}})})})}),y.viewport)})]}):null}),WKt=s=>{const{__scopeToast:t,children:n,...r}=s,a=FSe(mQ,t),[i,l]=N.useState(!1),[o,c]=N.useState(!1);return ZKt(()=>l(!0)),N.useEffect(()=>{const d=window.setTimeout(()=>c(!0),1e3);return()=>window.clearTimeout(d)},[]),o?null:e.jsx(Y$,{asChild:!0,children:e.jsx(OSe,{...r,children:i&&e.jsxs(e.Fragment,{children:[a.label," ",n]})})})},KKt="ToastTitle",F1t=N.forwardRef((s,t)=>{const{__scopeToast:n,...r}=s;return e.jsx(Da.div,{...r,ref:t})});F1t.displayName=KKt;var YKt="ToastDescription",z1t=N.forwardRef((s,t)=>{const{__scopeToast:n,...r}=s;return e.jsx(Da.div,{...r,ref:t})});z1t.displayName=YKt;var B1t="ToastAction",$1t=N.forwardRef((s,t)=>{const{altText:n,...r}=s;return n.trim()?e.jsx(q1t,{altText:n,asChild:!0,children:e.jsx(n$e,{...r,ref:t})}):(console.error(`Invalid prop \`altText\` supplied to \`${B1t}\`. Expected non-empty \`string\`.`),null)});$1t.displayName=B1t;var U1t="ToastClose",n$e=N.forwardRef((s,t)=>{const{__scopeToast:n,...r}=s,a=HKt(U1t,n);return e.jsx(q1t,{asChild:!0,children:e.jsx(Da.button,{type:"button",...r,ref:t,onClick:la(s.onClick,a.onClose)})})});n$e.displayName=U1t;var q1t=N.forwardRef((s,t)=>{const{__scopeToast:n,altText:r,...a}=s;return e.jsx(Da.div,{"data-radix-toast-announce-exclude":"","data-radix-toast-announce-alt":r||void 0,...a,ref:t})});function V1t(s){const t=[];return Array.from(s.childNodes).forEach(r=>{if(r.nodeType===r.TEXT_NODE&&r.textContent&&t.push(r.textContent),XKt(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(...V1t(r))}}),t}function Nte(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?e$e(a,i):a.dispatchEvent(i)}var _et=(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 ZKt(s=()=>{}){const t=cf(s);gf(()=>{let n=0,r=0;return n=window.requestAnimationFrame(()=>r=window.requestAnimationFrame(t)),()=>{window.cancelAnimationFrame(n),window.cancelAnimationFrame(r)}},[t])}function XKt(s){return s.nodeType===s.ELEMENT_NODE}function QKt(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 n6e(s){const t=document.activeElement;return s.some(n=>n===t?!0:(n.focus(),document.activeElement!==t))}var JKt=P1t,H1t=D1t,G1t=O1t,W1t=F1t,K1t=z1t,Y1t=$1t,Z1t=n$e;function X1t(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,jet=Ol,RR=(s,t)=>n=>{var r;if((t==null?void 0:t.variants)==null)return jet(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=wet(u)||wet(h);return a[d][m]}),o=n&&Object.entries(n).reduce((d,u)=>{let[h,m]=u;return m===void 0||(d[h]=m),d},{}),c=t==null||(r=t.compoundVariants)===null||r===void 0?void 0:r.reduce((d,u)=>{let{class:h,className:m,...f}=u;return Object.entries(f).every(g=>{let[y,x]=g;return Array.isArray(x)?x.includes({...i,...o}[y]):{...i,...o}[y]===x})?[...d,h,m]:d},[]);return jet(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 eYt=s=>s.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase(),Q1t=(...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 tYt={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 J1t=N.forwardRef(({color:s="currentColor",size:t=24,strokeWidth:n=2,absoluteStrokeWidth:r,className:a="",children:i,iconNode:l,...o},c)=>N.createElement("svg",{ref:c,...tYt,width:t,height:t,stroke:s,strokeWidth:r?Number(n)*24/Number(t):n,className:Q1t("lucide",a),...o},[...l.map(([d,u])=>N.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 oe=(s,t)=>{const n=N.forwardRef(({className:r,...a},i)=>N.createElement(J1t,{ref:i,iconNode:t,className:Q1t(`lucide-${eYt(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 Sre=oe("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 Cre=oe("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 Are=oe("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 Tre=oe("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 gg=oe("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 Ere=oe("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 Mre=oe("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 J6=oe("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 eM=oe("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 Lre=oe("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 tM=oe("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 Pre=oe("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 Ire=oe("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 Dre=oe("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 Rre=oe("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 Ore=oe("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 sD=oe("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 Fre=oe("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 zre=oe("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 Bre=oe("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 $re=oe("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 Ure=oe("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 qre=oe("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 Vre=oe("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 Hre=oe("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 Gre=oe("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 Wre=oe("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 Kre=oe("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 nD=oe("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 rD=oe("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 Yre=oe("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 Zre=oe("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 Xre=oe("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 Qre=oe("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 Jre=oe("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 eae=oe("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 tae=oe("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 sae=oe("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 nae=oe("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 rae=oe("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 aae=oe("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 iae=oe("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 oae=oe("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 lae=oe("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 cae=oe("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 dae=oe("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 uae=oe("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 hae=oe("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 mae=oe("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 pae=oe("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 fae=oe("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 gae=oe("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 xae=oe("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 a9=oe("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 yae=oe("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 xg=oe("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 vae=oe("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 bae=oe("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 _ae=oe("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 wae=oe("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 jae=oe("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 Nae=oe("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 kae=oe("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 Sae=oe("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 Cae=oe("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 Aae=oe("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 Tae=oe("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 sM=oe("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 Eae=oe("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 Mae=oe("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 Lae=oe("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 OG=oe("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 Pae=oe("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 Iae=oe("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 Dae=oe("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 nM=oe("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 rM=oe("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 Wf=oe("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 Rae=oe("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 Oae=oe("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 Fae=oe("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=oe("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 zae=oe("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 c5=oe("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 Bae=oe("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 vi=oe("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 $ae=oe("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 Uae=oe("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 aM=oe("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 mg=oe("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 qae=oe("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 Vae=oe("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 Hae=oe("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 iM=oe("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 i9=oe("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 Gae=oe("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 Wae=oe("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 oM=oe("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 Om=oe("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 Kae=oe("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 Yae=oe("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 Zae=oe("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 Xae=oe("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 Qae=oe("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 Jae=oe("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 ku=oe("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 eie=oe("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 lM=oe("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 tie=oe("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 sie=oe("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 nie=oe("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 rie=oe("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 cM=oe("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 aie=oe("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 iie=oe("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 oie=oe("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 lie=oe("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 cie=oe("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 die=oe("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 uie=oe("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 hie=oe("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 mie=oe("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 pie=oe("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 fie=oe("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 gie=oe("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 xie=oe("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 yie=oe("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 vie=oe("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 o9=oe("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 bie=oe("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 _ie=oe("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 wie=oe("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 jie=oe("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 Nie=oe("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 Wx=oe("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 kie=oe("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 Sie=oe("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 Cie=oe("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 Aie=oe("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 Tie=oe("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 Eie=oe("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 FG=oe("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 Mie=oe("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 Lie=oe("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 J4=oe("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 Pie=oe("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 A_=oe("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 Iie=oe("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 Die=oe("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 Rie=oe("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 Oie=oe("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 Fie=oe("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 zie=oe("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 d5=oe("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 Bie=oe("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 wT=oe("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 yg=oe("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 dM=oe("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 uM=oe("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 $ie=oe("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 Uie=oe("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 qie=oe("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 Vie=oe("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 Hie=oe("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 Gie=oe("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 Wie=oe("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 Kie=oe("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 Yie=oe("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 Zie=oe("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 Xie=oe("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 Qie=oe("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 Jie=oe("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 eoe=oe("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 toe=oe("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 soe=oe("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 jT=oe("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 noe=oe("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 roe=oe("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 aoe=oe("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 ioe=oe("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 ooe=oe("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 loe=oe("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 coe=oe("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 hM=oe("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 doe=oe("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 uoe=oe("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 hoe=oe("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 moe=oe("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 poe=oe("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 foe=oe("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 goe=oe("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 xoe=oe("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 yoe=oe("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 voe=oe("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 Ep=oe("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 boe=oe("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 _oe=oe("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 woe=oe("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 joe=oe("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 Noe=oe("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 koe=oe("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 Soe=oe("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 Coe=oe("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 Aoe=oe("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 Toe=oe("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 aD=oe("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 Eoe=oe("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 Hv=oe("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 Moe=oe("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 Loe=oe("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 Poe=oe("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 NT=oe("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 zG=oe("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 Ioe=oe("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 mM=oe("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 Doe=oe("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 Roe=oe("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 Ooe=oe("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 BG=oe("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 Foe=oe("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 zoe=oe("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 Boe=oe("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 $oe=oe("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 vg=oe("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 Uoe=oe("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 qoe=oe("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 Voe=oe("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 Hoe=oe("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 Goe=oe("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 Ti=oe("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 iD=oe("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 Woe=oe("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 Koe=oe("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 Yoe=oe("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 Zoe=oe("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 Xoe=oe("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 Fm=oe("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 u5=oe("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 Qoe=oe("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 Joe=oe("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 ele=oe("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 tle=oe("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 kT=oe("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 df=oe("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 sle=oe("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 ld=oe("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 nle=oe("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 W2=oe("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 rle=oe("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 ale=oe("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 $G=oe("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 ile=oe("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 Pv=oe("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 ole=oe("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 lle=oe("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 cle=oe("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 dle=oe("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 UG=oe("CalendarX",[["path",{d:"M8 2v4",key:"1cmpym"}],["path",{d:"M16 2v4",key:"4m81vk"}],["rect",{width:"18",height:"18",x:"3",y:"4",rx:"2",key:"1hopcy"}],["path",{d:"M3 10h18",key:"8toen8"}],["path",{d:"m14 14-4 4",key:"rymu2i"}],["path",{d:"m10 14 4 4",key:"3sz06r"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const ta=oe("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 ule=oe("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 $0=oe("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 hle=oe("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 mle=oe("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 ple=oe("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 fle=oe("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 gle=oe("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 pM=oe("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 xle=oe("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 yle=oe("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 vle=oe("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 ble=oe("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 _le=oe("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 wle=oe("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 jle=oe("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 Nle=oe("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 kle=oe("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 Sle=oe("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 Cle=oe("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 Ale=oe("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 Tle=oe("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 fM=oe("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 gM=oe("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 Ele=oe("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 Mle=oe("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 Lle=oe("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 xM=oe("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 yM=oe("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 vM=oe("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 Ple=oe("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 bM=oe("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 Ile=oe("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 fl=oe("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 Dle=oe("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 _M=oe("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 Rle=oe("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 Ole=oe("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 wM=oe("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 jM=oe("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 Fle=oe("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 NM=oe("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 kM=oe("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 SM=oe("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 zle=oe("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 oD=oe("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 pa=oe("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 Ble=oe("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 $le=oe("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 Xo=oe("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 Ule=oe("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 qle=oe("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 Fc=oe("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 Qa=oe("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 zy=oe("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 Vle=oe("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 Hle=oe("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 Gle=oe("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 Wle=oe("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 Kle=oe("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 Yle=oe("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 Zle=oe("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 sb=oe("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 Xle=oe("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 lD=oe("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 Qle=oe("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 Jle=oe("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 ece=oe("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 Uo=oe("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 CM=oe("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 AM=oe("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 TM=oe("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 EM=oe("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 MM=oe("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 LM=oe("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 PM=oe("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 IM=oe("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 Po=oe("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 Hr=oe("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 DM=oe("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 RM=oe("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 OM=oe("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 FM=oe("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 tce=oe("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 zM=oe("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 sce=oe("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 nce=oe("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 rce=oe("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 ace=oe("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 ice=oe("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 oce=oe("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 lce=oe("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 BM=oe("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 Uk=oe("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 $M=oe("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 cce=oe("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 UM=oe("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 qM=oe("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 VM=oe("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 HM=oe("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 wp=oe("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 GM=oe("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 WM=oe("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 KM=oe("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 dce=oe("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 YM=oe("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 ZM=oe("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 XM=oe("CircleUser",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["circle",{cx:"12",cy:"10",r:"3",key:"ilqhr7"}],["path",{d:"M7 20.662V19a2 2 0 0 1 2-2h6a2 2 0 0 1 2 2v1.662",key:"154egf"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Nu=oe("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 bg=oe("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 uce=oe("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 hce=oe("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 l9=oe("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 e3=oe("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 mce=oe("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 lj=oe("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 pce=oe("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 fce=oe("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 QM=oe("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 JM=oe("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 gce=oe("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 xce=oe("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 yce=oe("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 vce=oe("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 bce=oe("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 _ce=oe("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 wce=oe("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 jce=oe("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 Nce=oe("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 qG=oe("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 kce=oe("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 Sce=oe("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 Cce=oe("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 Ace=oe("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 Tce=oe("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 Ece=oe("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 Mce=oe("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 Lce=oe("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 Pce=oe("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 Xr=oe("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 Ice=oe("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 Dce=oe("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 eL=oe("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 Rce=oe("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 Oce=oe("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 Fce=oe("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 zce=oe("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 Bce=oe("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 $ce=oe("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 Uce=oe("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 qce=oe("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 Vce=oe("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 Hce=oe("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 Gce=oe("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 Wce=oe("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 tL=oe("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 Kce=oe("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 Yce=oe("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 V4=oe("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 Zce=oe("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 l4=oe("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 cD=oe("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 Xce=oe("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 Qce=oe("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 T_=oe("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 Jce=oe("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 VG=oe("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 sL=oe("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 GC=oe("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 ede=oe("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 tde=oe("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 sde=oe("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 c9=oe("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 nde=oe("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 rde=oe("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 ade=oe("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 ide=oe("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 ode=oe("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 nL=oe("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 dD=oe("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 lde=oe("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 cde=oe("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 dde=oe("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 ude=oe("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 hde=oe("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 mde=oe("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 pde=oe("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 fde=oe("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 gde=oe("CopyX",[["line",{x1:"12",x2:"18",y1:"12",y2:"18",key:"1rg63v"}],["line",{x1:"12",x2:"18",y1:"18",y2:"12",key:"ebkxgr"}],["rect",{width:"14",height:"14",x:"8",y:"8",rx:"2",ry:"2",key:"17jyea"}],["path",{d:"M4 16c-1.1 0-2-.9-2-2V4c0-1.1.9-2 2-2h10c1.1 0 2 .9 2 2",key:"zix9uf"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Pa=oe("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 xde=oe("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 yde=oe("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 vde=oe("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 bde=oe("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 _de=oe("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 wde=oe("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 jde=oe("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 Nde=oe("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 kde=oe("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 Sde=oe("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 Cde=oe("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 Ade=oe("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 U0=oe("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 Tde=oe("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 Ede=oe("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 Mde=oe("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 Lde=oe("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 q0=oe("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 Pde=oe("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 Ide=oe("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 Dde=oe("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 Rde=oe("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 Ode=oe("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 Fde=oe("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 zde=oe("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 HG=oe("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 Bde=oe("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 $de=oe("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 Ude=oe("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 qde=oe("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 rL=oe("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 Vde=oe("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 Hde=oe("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 Gde=oe("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 Wde=oe("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 Kde=oe("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 Yde=oe("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 Zde=oe("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 Xde=oe("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 Qde=oe("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 Jde=oe("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 eue=oe("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 tue=oe("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 sue=oe("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 nue=oe("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 rue=oe("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 aue=oe("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 iue=oe("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 oue=oe("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 lue=oe("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 Ed=oe("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 cue=oe("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 due=oe("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 h5=oe("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 uue=oe("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 oi=oe("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 hue=oe("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 mue=oe("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 pue=oe("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 fue=oe("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 gue=oe("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 K2=oe("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 xue=oe("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 yue=oe("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 vue=oe("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 bue=oe("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 _ue=oe("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 wue=oe("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 aL=oe("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 jue=oe("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 Nue=oe("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 kue=oe("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 d9=oe("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 Ev=oe("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 Iy=oe("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 Sue=oe("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 Cue=oe("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 Aue=oe("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 Tue=oe("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 Eue=oe("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 Mue=oe("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 Lue=oe("Expand",[["path",{d:"m21 21-6-6m6 6v-4.8m0 4.8h-4.8",key:"1c15vz"}],["path",{d:"M3 16.2V21m0 0h4.8M3 21l6-6",key:"1fsnz2"}],["path",{d:"M21 7.8V3m0 0h-4.8M21 3l-6 6",key:"hawz9i"}],["path",{d:"M3 7.8V3m0 0h4.8M3 3l6 6",key:"u9ee12"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Tr=oe("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 Pue=oe("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 V0=oe("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 da=oe("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 Kf=oe("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 Iue=oe("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 Due=oe("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 Rue=oe("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 Oue=oe("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 Fue=oe("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 zue=oe("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 Bue=oe("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 $ue=oe("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 Uue=oe("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 que=oe("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 iL=oe("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 Vue=oe("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 Hue=oe("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 Gue=oe("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 oL=oe("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 lL=oe("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 cL=oe("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 dL=oe("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 Wue=oe("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 GG=oe("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 Kue=oe("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 Yue=oe("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 Zue=oe("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 uL=oe("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 Xue=oe("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 Que=oe("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 uD=oe("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 Jue=oe("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 t3=oe("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 ehe=oe("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 the=oe("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 she=oe("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 nhe=oe("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 rhe=oe("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 ahe=oe("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 ihe=oe("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 ohe=oe("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 lhe=oe("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 che=oe("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 dhe=oe("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 WC=oe("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 hL=oe("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 uhe=oe("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 hhe=oe("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 mhe=oe("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 phe=oe("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 fhe=oe("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 ghe=oe("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 xhe=oe("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 m5=oe("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 WG=oe("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 yhe=oe("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 vhe=oe("FileTerminal",[["path",{d:"M15 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7Z",key:"1rqfz7"}],["path",{d:"M14 2v4a2 2 0 0 0 2 2h4",key:"tnqrlb"}],["path",{d:"m8 16 2-2-2-2",key:"10vzyd"}],["path",{d:"M12 18h4",key:"1wd2n7"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Wr=oe("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 bhe=oe("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 _he=oe("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 whe=oe("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 jhe=oe("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 Nhe=oe("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 KG=oe("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 khe=oe("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 She=oe("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 Che=oe("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 Ahe=oe("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 The=oe("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 u9=oe("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 Ehe=oe("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 Rh=oe("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 Mhe=oe("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 cj=oe("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 Lhe=oe("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 Phe=oe("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 Ihe=oe("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 Dhe=oe("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 Rhe=oe("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 Ohe=oe("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 Fhe=oe("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 zhe=oe("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 s3=oe("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 Bhe=oe("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 Cu=oe("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 $he=oe("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 Uhe=oe("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 qhe=oe("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 ST=oe("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 Vhe=oe("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 Hhe=oe("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 YG=oe("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 Ghe=oe("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 Whe=oe("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 U2=oe("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 Khe=oe("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 Yhe=oe("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 Zhe=oe("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 Xhe=oe("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 Qhe=oe("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 Jhe=oe("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 eme=oe("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 tme=oe("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 sme=oe("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 mL=oe("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 nme=oe("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 rme=oe("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 ame=oe("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 ime=oe("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 ome=oe("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 lme=oe("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 cme=oe("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 dme=oe("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 ume=oe("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 hme=oe("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 mme=oe("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 H0=oe("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 pme=oe("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 pL=oe("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 fme=oe("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 gme=oe("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 xme=oe("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 yme=oe("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 vme=oe("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 bme=oe("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 _me=oe("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 wme=oe("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 jme=oe("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 Nme=oe("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 kme=oe("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 Sme=oe("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 Cme=oe("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 Ame=oe("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 Tme=oe("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 Eme=oe("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 Mme=oe("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 Lme=oe("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 Pme=oe("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 Ime=oe("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 Dme=oe("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 Rme=oe("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 Ome=oe("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 Fme=oe("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 zme=oe("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 Bme=oe("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 $me=oe("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 Ume=oe("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 qme=oe("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 hD=oe("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 Io=oe("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 Vme=oe("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 Hme=oe("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 fL=oe("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 Gme=oe("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 Wme=oe("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 Kme=oe("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 Yme=oe("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 Zme=oe("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 Xme=oe("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 Qme=oe("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 Jme=oe("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 epe=oe("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 tpe=oe("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 spe=oe("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 npe=oe("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 rpe=oe("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 ape=oe("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 ipe=oe("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 ope=oe("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 lpe=oe("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 au=oe("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 cpe=oe("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 dpe=oe("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 Oh=oe("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 upe=oe("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 hpe=oe("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 gL=oe("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 mpe=oe("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 xL=oe("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 Iw=oe("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 ppe=oe("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 Mp=oe("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 fpe=oe("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 gpe=oe("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 xpe=oe("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 ype=oe("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 ZG=oe("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 vpe=oe("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 mD=oe("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 R2=oe("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 bpe=oe("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 _pe=oe("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 XG=oe("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 Y2=oe("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 wpe=oe("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 jpe=oe("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 QG=oe("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 Npe=oe("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 CT=oe("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 kpe=oe("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 Spe=oe("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 h9=oe("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 m9=oe("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 JG=oe("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 Cpe=oe("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 Ape=oe("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 Tpe=oe("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 Epe=oe("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 Mpe=oe("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 Lpe=oe("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 Ppe=oe("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 Ipe=oe("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 pD=oe("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 Dpe=oe("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 Rpe=oe("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 co=oe("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 Ope=oe("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 Fpe=oe("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 zpe=oe("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 fD=oe("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 Bpe=oe("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 $pe=oe("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 Upe=oe("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 qpe=oe("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 Vpe=oe("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 Hpe=oe("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 Gpe=oe("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 _a=oe("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 yL=oe("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 vL=oe("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 Wpe=oe("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 Kpe=oe("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 Ype=oe("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 Zpe=oe("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 Xpe=oe("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 Gv=oe("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 Qpe=oe("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 Jpe=oe("ImageUpscale",[["path",{d:"M16 3h5v5",key:"1806ms"}],["path",{d:"M17 21h2a2 2 0 0 0 2-2",key:"130fy9"}],["path",{d:"M21 12v3",key:"1wzk3p"}],["path",{d:"m21 3-5 5",key:"1g5oa7"}],["path",{d:"M3 7V5a2 2 0 0 1 2-2",key:"kk3yz1"}],["path",{d:"m5 21 4.144-4.144a1.21 1.21 0 0 1 1.712 0L13 19",key:"fyekpt"}],["path",{d:"M9 3h3",key:"d52fa"}],["rect",{x:"3",y:"11",width:"10",height:"10",rx:"1",key:"1wpmix"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const pc=oe("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 efe=oe("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 tfe=oe("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 n3=oe("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 bL=oe("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 _L=oe("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 sfe=oe("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 nfe=oe("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 p5=oe("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 rfe=oe("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 dm=oe("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 AT=oe("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 afe=oe("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 ife=oe("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 ofe=oe("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 lfe=oe("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 r3=oe("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 TT=oe("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 cfe=oe("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 nb=oe("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 dfe=oe("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 ufe=oe("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 hfe=oe("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 mfe=oe("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 pfe=oe("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 ffe=oe("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 gfe=oe("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 xfe=oe("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 yfe=oe("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 vfe=oe("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 eW=oe("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 bfe=oe("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 _fe=oe("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 wL=oe("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 wfe=oe("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 jfe=oe("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 Nfe=oe("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 kfe=oe("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 Sfe=oe("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 Cfe=oe("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 tW=oe("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 ET=oe("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 G0=oe("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 Afe=oe("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 Tfe=oe("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 Efe=oe("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 a3=oe("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 Mfe=oe("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 Lfe=oe("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 Pfe=oe("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 Ife=oe("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 Dfe=oe("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 rb=oe("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 p9=oe("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 Rfe=oe("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 Ofe=oe("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 Z2=oe("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 Ffe=oe("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 cd=oe("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 gc=oe("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 W0=oe("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 zfe=oe("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 zm=oe("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 Bfe=oe("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 $fe=oe("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 sW=oe("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 Ufe=oe("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 qfe=oe("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 dj=oe("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 Vfe=oe("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 Hfe=oe("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 Gfe=oe("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 Wfe=oe("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 Kfe=oe("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 Yfe=oe("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 Zfe=oe("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 Kx=oe("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 us=oe("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 Xfe=oe("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 Qfe=oe("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 Jfe=oe("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 ege=oe("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 f9=oe("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 jL=oe("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 tge=oe("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 NL=oe("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 Au=oe("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 gD=oe("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 xD=oe("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 sge=oe("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 nge=oe("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 rge=oe("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 age=oe("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 g9=oe("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 ige=oe("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 x9=oe("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 nW=oe("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 oge=oe("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 lge=oe("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 cge=oe("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 y9=oe("MailX",[["path",{d:"M22 13V6a2 2 0 0 0-2-2H4a2 2 0 0 0-2 2v12c0 1.1.9 2 2 2h9",key:"1j9vog"}],["path",{d:"m22 7-8.97 5.7a1.94 1.94 0 0 1-2.06 0L2 7",key:"1ocrg3"}],["path",{d:"m17 17 4 4",key:"1b3523"}],["path",{d:"m21 17-4 4",key:"uinynz"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const mn=oe("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 dge=oe("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 uge=oe("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 hge=oe("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 mge=oe("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 pge=oe("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 fge=oe("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 gge=oe("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 xge=oe("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 yge=oe("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 vge=oe("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 bge=oe("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 _ge=oe("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 ii=oe("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 wge=oe("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 yD=oe("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 jge=oe("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 rW=oe("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 vD=oe("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 i3=oe("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 Nge=oe("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 um=oe("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 kge=oe("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 Sge=oe("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 MT=oe("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 Cge=oe("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 Age=oe("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 Tge=oe("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 v9=oe("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 Ege=oe("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 Mge=oe("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 Lge=oe("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 aW=oe("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 Pge=oe("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 Ige=oe("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 Dge=oe("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 Ud=oe("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 Rge=oe("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 Oge=oe("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 Fge=oe("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 zge=oe("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 b9=oe("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 Bge=oe("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 iW=oe("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 $ge=oe("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 Qk=oe("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 f5=oe("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 Uge=oe("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 qge=oe("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 Vge=oe("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 Hge=oe("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 Gge=oe("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 xo=oe("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 _9=oe("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 Wge=oe("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 kL=oe("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 uj=oe("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 Kge=oe("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 Yge=oe("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 Zge=oe("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 Xge=oe("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 Qge=oe("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 Jge=oe("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 exe=oe("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 txe=oe("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 X2=oe("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 sxe=oe("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 nxe=oe("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 rxe=oe("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 axe=oe("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 ixe=oe("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 oxe=oe("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 w9=oe("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 lxe=oe("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 cxe=oe("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 dxe=oe("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 bD=oe("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 uxe=oe("MonitorX",[["path",{d:"m14.5 12.5-5-5",key:"1jahn5"}],["path",{d:"m9.5 12.5 5-5",key:"1k2t7b"}],["rect",{width:"20",height:"14",x:"2",y:"3",rx:"2",key:"48i651"}],["path",{d:"M12 17v4",key:"1riwvh"}],["path",{d:"M8 21h8",key:"1ev6f3"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const hj=oe("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 hxe=oe("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 mxe=oe("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 pxe=oe("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 fxe=oe("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 gxe=oe("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 xxe=oe("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 yxe=oe("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 ru=oe("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 Qg=oe("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 vxe=oe("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 SL=oe("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 bxe=oe("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 _xe=oe("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 wxe=oe("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 jxe=oe("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 Nxe=oe("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 kxe=oe("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 Sxe=oe("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 Cxe=oe("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 Axe=oe("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 Txe=oe("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 Exe=oe("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 Mxe=oe("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 oW=oe("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 Lxe=oe("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 Pxe=oe("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 Ixe=oe("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 j9=oe("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 Dxe=oe("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 Rxe=oe("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 Oxe=oe("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 lW=oe("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 Fxe=oe("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 E_=oe("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 zxe=oe("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 Bxe=oe("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 $xe=oe("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 Uxe=oe("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 qxe=oe("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 Vxe=oe("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 Hxe=oe("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 Gxe=oe("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 Wxe=oe("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=oe("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 Kxe=oe("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 CL=oe("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 AL=oe("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 Yxe=oe("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 Zxe=oe("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 Xxe=oe("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 Qxe=oe("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 Jxe=oe("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 e0e=oe("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 t0e=oe("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 s0e=oe("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 n0e=oe("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 cW=oe("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 r0e=oe("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 a0e=oe("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 Ku=oe("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 i0e=oe("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 o0e=oe("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 TL=oe("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 l0e=oe("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 zc=oe("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 c0e=oe("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 EL=oe("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 d0e=oe("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 u0e=oe("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 ML=oe("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 LL=oe("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 PL=oe("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 IL=oe("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 h0e=oe("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 DL=oe("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 m0e=oe("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 p0e=oe("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 f0e=oe("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 RL=oe("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 g0e=oe("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 x0e=oe("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 y0e=oe("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 v0e=oe("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 c4=oe("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 LT=oe("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 b0e=oe("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 _0e=oe("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 uf=oe("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 K0=oe("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 w0e=oe("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 j0e=oe("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 O2=oe("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 N0e=oe("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 PT=oe("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 Ww=oe("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 N9=oe("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 k0e=oe("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 S0e=oe("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 Ja=oe("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 C0e=oe("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 IT=oe("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 A0e=oe("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 T0e=oe("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 dW=oe("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 E0e=oe("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 M0e=oe("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 L0e=oe("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 P0e=oe("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 I0e=oe("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 ga=oe("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 D0e=oe("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 R0e=oe("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 O0e=oe("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 F0e=oe("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 z0e=oe("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 B0e=oe("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 $0e=oe("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 U0e=oe("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 q0e=oe("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 V0e=oe("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 H0e=oe("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 uW=oe("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 DT=oe("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 G0e=oe("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 W0e=oe("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 K0e=oe("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 Y0e=oe("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 hW=oe("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 dd=oe("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 Z0e=oe("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 OL=oe("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 o3=oe("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 nn=oe("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 X0e=oe("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 Q0e=oe("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 J0e=oe("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 eye=oe("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 tye=oe("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 sye=oe("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 nye=oe("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 rye=oe("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 aye=oe("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 mW=oe("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 ab=oe("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 iye=oe("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 pW=oe("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 oye=oe("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 lye=oe("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 cye=oe("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 dye=oe("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 M_=oe("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 Q2=oe("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 uye=oe("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 _D=oe("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 hye=oe("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 mye=oe("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 pye=oe("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 fye=oe("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 Y0=oe("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 gye=oe("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 xye=oe("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 yye=oe("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 vye=oe("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 bye=oe("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 _ye=oe("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 wye=oe("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 jye=oe("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 Nye=oe("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 kye=oe("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 Sye=oe("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 Cye=oe("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 Aye=oe("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 Tye=oe("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 FL=oe("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 Eye=oe("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 Mye=oe("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 Lye=oe("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 Pye=oe("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 Iye=oe("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 RT=oe("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 Dye=oe("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 k9=oe("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 Rye=oe("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 oo=oe("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 Oye=oe("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 Fye=oe("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 zye=oe("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 Bye=oe("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 $ye=oe("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 S9=oe("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 Uye=oe("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 qye=oe("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 Vye=oe("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 fW=oe("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 Hye=oe("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 Gye=oe("Ribbon",[["path",{d:"M12 11.22C11 9.997 10 9 10 8a2 2 0 0 1 4 0c0 1-.998 2.002-2.01 3.22",key:"1rnhq3"}],["path",{d:"m12 18 2.57-3.5",key:"116vt7"}],["path",{d:"M6.243 9.016a7 7 0 0 1 11.507-.009",key:"10dq0b"}],["path",{d:"M9.35 14.53 12 11.22",key:"tdsyp2"}],["path",{d:"M9.35 14.53C7.728 12.246 6 10.221 6 7a6 5 0 0 1 12 0c-.005 3.22-1.778 5.235-3.43 7.5l3.557 4.527a1 1 0 0 1-.203 1.43l-1.894 1.36a1 1 0 0 1-1.384-.215L12 18l-2.679 3.593a1 1 0 0 1-1.39.213l-1.865-1.353a1 1 0 0 1-.203-1.422z",key:"nmifey"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const By=oe("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 Wye=oe("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 Kye=oe("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 zL=oe("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 Yye=oe("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 hf=oe("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 Zye=oe("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 wD=oe("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 Xye=oe("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 gW=oe("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 Qye=oe("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 BL=oe("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 $L=oe("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 Jye=oe("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 eve=oe("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 l3=oe("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 tve=oe("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 sve=oe("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 nve=oe("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 rve=oe("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 ave=oe("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 ive=oe("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 ove=oe("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 lve=oe("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 Kl=oe("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 UL=oe("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 xW=oe("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 cve=oe("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 dve=oe("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 uve=oe("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 hve=oe("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 mve=oe("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 pve=oe("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 fve=oe("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 gve=oe("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 xve=oe("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 yve=oe("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 vve=oe("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 bve=oe("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 _ve=oe("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 wve=oe("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 yW=oe("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 jve=oe("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 Nve=oe("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 kve=oe("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 Sve=oe("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 vW=oe("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 Gr=oe("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 Cve=oe("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 qL=oe("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 Ave=oe("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 Rr=oe("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 Tve=oe("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 Eve=oe("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 Mve=oe("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 Lve=oe("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 Pve=oe("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 Ive=oe("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 C9=oe("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 sc=oe("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 Dve=oe("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 Md=oe("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 bW=oe("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 Rve=oe("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 Ove=oe("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 A9=oe("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 Fve=oe("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 Wv=oe("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 zve=oe("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 Bve=oe("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 $ve=oe("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 jD=oe("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 Uve=oe("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 qve=oe("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 VL=oe("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 mf=oe("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 Vve=oe("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 Hve=oe("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 Gve=oe("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 g5=oe("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 Wve=oe("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 W1=oe("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 Kve=oe("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 Yve=oe("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 Zve=oe("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 Xve=oe("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 ND=oe("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 Qve=oe("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 Jve=oe("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 e1e=oe("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 t1e=oe("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 s1e=oe("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 n1e=oe("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 r1e=oe("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 a1e=oe("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 i1e=oe("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 o1e=oe("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 l1e=oe("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 c1e=oe("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 d1e=oe("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 u1e=oe("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 h1e=oe("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 m1e=oe("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 OT=oe("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 HL=oe("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 p1e=oe("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 f1e=oe("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 $y=oe("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 g1e=oe("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 x1e=oe("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 y1e=oe("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 nj=oe("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 v1e=oe("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 b1e=oe("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 _1e=oe("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 w1e=oe("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 c3=oe("Sparkle",[["path",{d:"M9.937 15.5A2 2 0 0 0 8.5 14.063l-6.135-1.582a.5.5 0 0 1 0-.962L8.5 9.936A2 2 0 0 0 9.937 8.5l1.582-6.135a.5.5 0 0 1 .963 0L14.063 8.5A2 2 0 0 0 15.5 9.937l6.135 1.581a.5.5 0 0 1 0 .964L15.5 14.063a2 2 0 0 0-1.437 1.437l-1.582 6.135a.5.5 0 0 1-.963 0z",key:"4pj2yx"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Cn=oe("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 j1e=oe("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 N1e=oe("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 k1e=oe("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 S1e=oe("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 C1e=oe("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 A1e=oe("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 T1e=oe("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 FT=oe("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 GL=oe("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 WL=oe("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 KL=oe("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 YL=oe("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 ZL=oe("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 XL=oe("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 QL=oe("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 JL=oe("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 eP=oe("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 tP=oe("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 sP=oe("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 nP=oe("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 rP=oe("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 aP=oe("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 iP=oe("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 ck=oe("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 d4=oe("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 oP=oe("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 lP=oe("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 cP=oe("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 dP=oe("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 uP=oe("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 hP=oe("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 E1e=oe("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 M1e=oe("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 mP=oe("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 pP=oe("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 fP=oe("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 gP=oe("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 xP=oe("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 yP=oe("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 vP=oe("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 bP=oe("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 _P=oe("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 wP=oe("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 jP=oe("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 NP=oe("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 kP=oe("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 SP=oe("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 CP=oe("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 xp=oe("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 AP=oe("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 TP=oe("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 EP=oe("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 MP=oe("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 LP=oe("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 PP=oe("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 L1e=oe("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 IP=oe("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 DP=oe("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 RP=oe("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 OP=oe("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 FP=oe("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 P1e=oe("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 I1e=oe("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 zP=oe("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 BP=oe("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 $P=oe("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 UP=oe("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 L_=oe("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 D1e=oe("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 R1e=oe("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 O1e=oe("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 F1e=oe("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 z1e=oe("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 Wa=oe("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 B1e=oe("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 $1e=oe("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 U1e=oe("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 q1e=oe("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 _W=oe("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 wW=oe("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 V1e=oe("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 H1e=oe("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 jW=oe("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 G1e=oe("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 W1e=oe("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 K1e=oe("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 Y1e=oe("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 Z1e=oe("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 J2=oe("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 X1e=oe("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 Q1e=oe("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 J1e=oe("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 ebe=oe("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 tbe=oe("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 sbe=oe("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 nbe=oe("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 rbe=oe("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 abe=oe("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 T9=oe("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 ibe=oe("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 obe=oe("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 lbe=oe("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 cbe=oe("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 dbe=oe("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 ube=oe("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 E9=oe("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 hbe=oe("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 M9=oe("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 mbe=oe("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 pf=oe("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 NW=oe("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 pbe=oe("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 fbe=oe("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 gbe=oe("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 xbe=oe("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 ybe=oe("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 vbe=oe("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 iu=oe("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 bbe=oe("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 _be=oe("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 wbe=oe("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 jbe=oe("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 qP=oe("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 Nbe=oe("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 kbe=oe("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 Sbe=oe("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 Cbe=oe("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 Abe=oe("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 Tbe=oe("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 VP=oe("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 Ebe=oe("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 Mbe=oe("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 Lbe=oe("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 Pbe=oe("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 kW=oe("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 SW=oe("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 ax=oe("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 Ibe=oe("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 Dbe=oe("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 Rbe=oe("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 Obe=oe("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 Fbe=oe("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 zbe=oe("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 CW=oe("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 Bbe=oe("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 $be=oe("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 Ube=oe("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 qbe=oe("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 Vbe=oe("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 Hbe=oe("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 Gbe=oe("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 Wbe=oe("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 Kbe=oe("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 Ybe=oe("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 Zbe=oe("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 Xbe=oe("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 Qbe=oe("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 Jbe=oe("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 e_e=oe("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 t_e=oe("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 s_e=oe("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 n_e=oe("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 r_e=oe("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 HP=oe("TramFront",[["rect",{width:"16",height:"16",x:"4",y:"3",rx:"2",key:"1wxw4b"}],["path",{d:"M4 11h16",key:"mpoxn0"}],["path",{d:"M12 3v8",key:"1h2ygw"}],["path",{d:"m8 19-2 3",key:"13i0xs"}],["path",{d:"m18 22-2-3",key:"1p0ohu"}],["path",{d:"M8 15h.01",key:"a7atzg"}],["path",{d:"M16 15h.01",key:"rnfrdf"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const qn=oe("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 a_e=oe("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 i_e=oe("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 GP=oe("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 zT=oe("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 o_e=oe("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 l_e=oe("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 eN=oe("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 c_e=oe("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 ml=oe("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 xd=oe("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 d_e=oe("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 u_e=oe("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 gl=oe("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 AW=oe("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 h_e=oe("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 m_e=oe("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 WP=oe("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 p_e=oe("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 f_e=oe("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 g_e=oe("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 x_e=oe("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 y_e=oe("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 v_e=oe("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 b_e=oe("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 L9=oe("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 TW=oe("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 __e=oe("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 BT=oe("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 w_e=oe("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 j_e=oe("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 N_e=oe("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 KP=oe("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 k_e=oe("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 kD=oe("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 S_e=oe("Unplug",[["path",{d:"m19 5 3-3",key:"yk6iyv"}],["path",{d:"m2 22 3-3",key:"19mgm9"}],["path",{d:"M6.3 20.3a2.4 2.4 0 0 0 3.4 0L12 18l-6-6-2.3 2.3a2.4 2.4 0 0 0 0 3.4Z",key:"goz73y"}],["path",{d:"M7.5 13.5 10 11",key:"7xgeeb"}],["path",{d:"M10.5 16.5 13 14",key:"10btkg"}],["path",{d:"m12 6 6 6 2.3-2.3a2.4 2.4 0 0 0 0-3.4l-2.6-2.6a2.4 2.4 0 0 0-3.4 0Z",key:"1snsnr"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const ni=oe("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 C_e=oe("Usb",[["circle",{cx:"10",cy:"7",r:"1",key:"dypaad"}],["circle",{cx:"4",cy:"20",r:"1",key:"22iqad"}],["path",{d:"M4.7 19.3 19 5",key:"1enqfc"}],["path",{d:"m21 3-3 1 2 2Z",key:"d3ov82"}],["path",{d:"M9.26 7.68 5 12l2 5",key:"1esawj"}],["path",{d:"m10 14 5 2 3.5-3.5",key:"v8oal5"}],["path",{d:"m18 12 1-1 1 1-1 1Z",key:"1bh22v"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const tN=oe("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 EW=oe("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 MW=oe("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 A_e=oe("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 Yl=oe("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 YP=oe("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 ZP=oe("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 XP=oe("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 T_e=oe("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 QP=oe("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 E_e=oe("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 JP=oe("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 eI=oe("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 M_e=oe("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 L_e=oe("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 Ro=oe("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 f_=oe("UsersRound",[["path",{d:"M18 21a8 8 0 0 0-16 0",key:"3ypg7q"}],["circle",{cx:"10",cy:"8",r:"5",key:"o932ke"}],["path",{d:"M22 20c0-3.37-2-6.5-4-8a5 5 0 0 0-.45-8.3",key:"10s06x"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Yn=oe("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 tI=oe("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 sI=oe("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 P_e=oe("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 P9=oe("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 I_e=oe("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 D_e=oe("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 R_e=oe("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 O_e=oe("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 F_e=oe("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 z_e=oe("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 na=oe("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 B_e=oe("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 $_e=oe("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 U_e=oe("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 q_e=oe("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 V_e=oe("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 LW=oe("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 H_e=oe("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 PW=oe("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 G_e=oe("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 W_e=oe("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 K_e=oe("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 nI=oe("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 I9=oe("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 Y_e=oe("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 Zg=oe("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 Z_e=oe("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 X_e=oe("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 Q_e=oe("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 J_e=oe("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 ewe=oe("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 twe=oe("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 swe=oe("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 nwe=oe("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 rwe=oe("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 awe=oe("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 iwe=oe("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 owe=oe("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 lwe=oe("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 cwe=oe("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 dwe=oe("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 uwe=oe("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 hwe=oe("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 mwe=oe("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 pwe=oe("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 fwe=oe("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 gwe=oe("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 IW=oe("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 DW=oe("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 xwe=oe("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 ywe=oe("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 sN=oe("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 hr=oe("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 vwe=oe("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 bwe=oe("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 ff=oe("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 $T=oe("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 D9=oe("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 sYt=Object.freeze(Object.defineProperty({__proto__:null,AArrowDown:Sre,AArrowUp:Cre,ALargeSmall:Are,Accessibility:Tre,Activity:gg,AirVent:Ere,Airplay:Mre,AlarmClock:Pre,AlarmClockCheck:J6,AlarmClockMinus:eM,AlarmClockOff:Lre,AlarmClockPlus:tM,AlarmSmoke:Ire,Album:Dre,AlignCenter:sD,AlignCenterHorizontal:Rre,AlignCenterVertical:Ore,AlignEndHorizontal:Fre,AlignEndVertical:zre,AlignHorizontalDistributeCenter:Bre,AlignHorizontalDistributeEnd:$re,AlignHorizontalDistributeStart:Ure,AlignHorizontalJustifyCenter:qre,AlignHorizontalJustifyEnd:Vre,AlignHorizontalJustifyStart:Hre,AlignHorizontalSpaceAround:Gre,AlignHorizontalSpaceBetween:Wre,AlignJustify:Kre,AlignLeft:nD,AlignRight:rD,AlignStartHorizontal:Yre,AlignStartVertical:Zre,AlignVerticalDistributeCenter:Xre,AlignVerticalDistributeEnd:Qre,AlignVerticalDistributeStart:Jre,AlignVerticalJustifyCenter:eae,AlignVerticalJustifyEnd:tae,AlignVerticalJustifyStart:sae,AlignVerticalSpaceAround:nae,AlignVerticalSpaceBetween:rae,Ambulance:aae,Ampersand:iae,Ampersands:oae,Amphora:lae,Anchor:cae,Angry:dae,Annoyed:uae,Antenna:hae,Anvil:mae,Aperture:pae,AppWindow:gae,AppWindowMac:fae,Apple:xae,Archive:xg,ArchiveRestore:a9,ArchiveX:yae,Armchair:vae,ArrowBigDown:_ae,ArrowBigDownDash:bae,ArrowBigLeft:jae,ArrowBigLeftDash:wae,ArrowBigRight:kae,ArrowBigRightDash:Nae,ArrowBigUp:Cae,ArrowBigUpDash:Sae,ArrowDown:Wf,ArrowDown01:Aae,ArrowDown10:Tae,ArrowDownAZ:sM,ArrowDownFromLine:Eae,ArrowDownLeft:Mae,ArrowDownNarrowWide:Lae,ArrowDownRight:OG,ArrowDownToDot:Pae,ArrowDownToLine:Iae,ArrowDownUp:Dae,ArrowDownWideNarrow:nM,ArrowDownZA:rM,ArrowLeft:ka,ArrowLeftFromLine:Rae,ArrowLeftRight:Oae,ArrowLeftToLine:Fae,ArrowRight:vi,ArrowRightFromLine:zae,ArrowRightLeft:c5,ArrowRightToLine:Bae,ArrowUp:Om,ArrowUp01:$ae,ArrowUp10:Uae,ArrowUpAZ:aM,ArrowUpDown:mg,ArrowUpFromDot:qae,ArrowUpFromLine:Vae,ArrowUpLeft:Hae,ArrowUpNarrowWide:iM,ArrowUpRight:i9,ArrowUpToLine:Gae,ArrowUpWideNarrow:Wae,ArrowUpZA:oM,ArrowsUpFromLine:Kae,Asterisk:Yae,AtSign:Zae,Atom:Xae,AudioLines:Qae,AudioWaveform:Jae,Award:ku,Axe:eie,Axis3d:lM,Baby:tie,Backpack:sie,Badge:yie,BadgeAlert:nie,BadgeCent:rie,BadgeCheck:cM,BadgeDollarSign:aie,BadgeEuro:iie,BadgeHelp:oie,BadgeIndianRupee:lie,BadgeInfo:cie,BadgeJapaneseYen:die,BadgeMinus:uie,BadgePercent:hie,BadgePlus:mie,BadgePoundSterling:pie,BadgeRussianRuble:fie,BadgeSwissFranc:gie,BadgeX:xie,BaggageClaim:vie,Ban:o9,Banana:bie,Bandage:_ie,Banknote:wie,Barcode:jie,Baseline:Nie,Bath:Wx,Battery:Eie,BatteryCharging:kie,BatteryFull:Sie,BatteryLow:Cie,BatteryMedium:Aie,BatteryWarning:Tie,Beaker:FG,Bean:Lie,BeanOff:Mie,Bed:A_,BedDouble:J4,BedSingle:Pie,Beef:Iie,Beer:Rie,BeerOff:Die,Bell:yg,BellDot:Oie,BellElectric:Fie,BellMinus:zie,BellOff:d5,BellPlus:Bie,BellRing:wT,BetweenHorizontalEnd:dM,BetweenHorizontalStart:uM,BetweenVerticalEnd:$ie,BetweenVerticalStart:Uie,BicepsFlexed:qie,Bike:Vie,Binary:Hie,Binoculars:Gie,Biohazard:Wie,Bird:Kie,Bitcoin:Yie,Blend:Zie,Blinds:Xie,Blocks:Qie,Bluetooth:soe,BluetoothConnected:Jie,BluetoothOff:eoe,BluetoothSearching:toe,Bold:jT,Bolt:noe,Bomb:roe,Bone:aoe,Book:Coe,BookA:ioe,BookAudio:ooe,BookCheck:loe,BookCopy:coe,BookDashed:hM,BookDown:doe,BookHeadphones:uoe,BookHeart:hoe,BookImage:moe,BookKey:poe,BookLock:foe,BookMarked:goe,BookMinus:xoe,BookOpen:Ep,BookOpenCheck:yoe,BookOpenText:voe,BookPlus:boe,BookText:_oe,BookType:woe,BookUp:Noe,BookUp2:joe,BookUser:koe,BookX:Soe,Bookmark:Hv,BookmarkCheck:Aoe,BookmarkMinus:Toe,BookmarkPlus:aD,BookmarkX:Eoe,BoomBox:Moe,Bot:NT,BotMessageSquare:Loe,BotOff:Poe,Box:zG,Boxes:Ioe,Braces:mM,Brackets:Doe,Brain:BG,BrainCircuit:Roe,BrainCog:Ooe,BrickWall:Foe,Briefcase:vg,BriefcaseBusiness:zoe,BriefcaseConveyorBelt:Boe,BriefcaseMedical:$oe,BringToFront:Uoe,Brush:qoe,Bug:Goe,BugOff:Voe,BugPlay:Hoe,Building:iD,Building2:Ti,Bus:Koe,BusFront:Woe,Cable:Zoe,CableCar:Yoe,Cake:Fm,CakeSlice:Xoe,Calculator:u5,Calendar:ta,Calendar1:Qoe,CalendarArrowDown:Joe,CalendarArrowUp:ele,CalendarCheck:kT,CalendarCheck2:tle,CalendarClock:df,CalendarCog:sle,CalendarDays:ld,CalendarFold:nle,CalendarHeart:W2,CalendarMinus:ale,CalendarMinus2:rle,CalendarOff:$G,CalendarPlus:Pv,CalendarPlus2:ile,CalendarRange:ole,CalendarSearch:lle,CalendarSync:cle,CalendarX:UG,CalendarX2:dle,Camera:$0,CameraOff:ule,Candy:ple,CandyCane:hle,CandyOff:mle,Cannabis:fle,Captions:pM,CaptionsOff:gle,Car:vle,CarFront:xle,CarTaxiFront:yle,Caravan:ble,Carrot:_le,CaseLower:wle,CaseSensitive:jle,CaseUpper:Nle,CassetteTape:kle,Cast:Sle,Castle:Cle,Cat:Ale,Cctv:Tle,ChartArea:fM,ChartBar:xM,ChartBarBig:gM,ChartBarDecreasing:Ele,ChartBarIncreasing:Mle,ChartBarStacked:Lle,ChartCandlestick:yM,ChartColumn:fl,ChartColumnBig:vM,ChartColumnDecreasing:Ple,ChartColumnIncreasing:bM,ChartColumnStacked:Ile,ChartGantt:Dle,ChartLine:_M,ChartNetwork:Rle,ChartNoAxesColumn:jM,ChartNoAxesColumnDecreasing:Ole,ChartNoAxesColumnIncreasing:wM,ChartNoAxesCombined:Fle,ChartNoAxesGantt:NM,ChartPie:kM,ChartScatter:SM,ChartSpline:zle,Check:pa,CheckCheck:oD,ChefHat:Ble,Cherry:$le,ChevronDown:Xo,ChevronFirst:Ule,ChevronLast:qle,ChevronLeft:Fc,ChevronRight:Qa,ChevronUp:zy,ChevronsDown:Hle,ChevronsDownUp:Vle,ChevronsLeft:Kle,ChevronsLeftRight:Wle,ChevronsLeftRightEllipsis:Gle,ChevronsRight:Zle,ChevronsRightLeft:Yle,ChevronsUp:Xle,ChevronsUpDown:sb,Chrome:lD,Church:Qle,Cigarette:ece,CigaretteOff:Jle,Circle:bg,CircleAlert:Uo,CircleArrowDown:CM,CircleArrowLeft:AM,CircleArrowOutDownLeft:TM,CircleArrowOutDownRight:EM,CircleArrowOutUpLeft:MM,CircleArrowOutUpRight:LM,CircleArrowRight:PM,CircleArrowUp:IM,CircleCheck:Hr,CircleCheckBig:Po,CircleChevronDown:DM,CircleChevronLeft:RM,CircleChevronRight:OM,CircleChevronUp:FM,CircleDashed:tce,CircleDivide:zM,CircleDollarSign:sce,CircleDot:rce,CircleDotDashed:nce,CircleEllipsis:ace,CircleEqual:ice,CircleFadingArrowUp:oce,CircleFadingPlus:lce,CircleGauge:BM,CircleHelp:Uk,CircleMinus:$M,CircleOff:cce,CircleParking:qM,CircleParkingOff:UM,CirclePause:VM,CirclePercent:HM,CirclePlay:wp,CirclePlus:GM,CirclePower:WM,CircleSlash:dce,CircleSlash2:KM,CircleStop:YM,CircleUser:XM,CircleUserRound:ZM,CircleX:Nu,CircuitBoard:uce,Citrus:hce,Clapperboard:l9,Clipboard:vce,ClipboardCheck:e3,ClipboardCopy:mce,ClipboardList:lj,ClipboardMinus:pce,ClipboardPaste:fce,ClipboardPen:JM,ClipboardPenLine:QM,ClipboardPlus:gce,ClipboardType:xce,ClipboardX:yce,Clock:Xr,Clock1:bce,Clock10:_ce,Clock11:wce,Clock12:jce,Clock2:Nce,Clock3:qG,Clock4:kce,Clock5:Sce,Clock6:Cce,Clock7:Ace,Clock8:Tce,Clock9:Ece,ClockAlert:Mce,ClockArrowDown:Lce,ClockArrowUp:Pce,Cloud:Kce,CloudAlert:Ice,CloudCog:Dce,CloudDownload:eL,CloudDrizzle:Rce,CloudFog:Oce,CloudHail:Fce,CloudLightning:zce,CloudMoon:$ce,CloudMoonRain:Bce,CloudOff:Uce,CloudRain:Vce,CloudRainWind:qce,CloudSnow:Hce,CloudSun:Wce,CloudSunRain:Gce,CloudUpload:tL,Cloudy:Yce,Clover:V4,Club:Zce,Code:cD,CodeXml:l4,Codepen:Xce,Codesandbox:Qce,Coffee:T_,Cog:Jce,Coins:VG,Columns2:sL,Columns3:GC,Columns4:ede,Combine:tde,Command:sde,Compass:c9,Component:nde,Computer:rde,ConciergeBell:ade,Cone:ide,Construction:ode,Contact:dD,ContactRound:nL,Container:lde,Contrast:cde,Cookie:dde,CookingPot:ude,Copy:Pa,CopyCheck:hde,CopyMinus:mde,CopyPlus:pde,CopySlash:fde,CopyX:gde,Copyleft:xde,Copyright:yde,CornerDownLeft:vde,CornerDownRight:bde,CornerLeftDown:_de,CornerLeftUp:wde,CornerRightDown:jde,CornerRightUp:Nde,CornerUpLeft:kde,CornerUpRight:Sde,Cpu:Cde,CreativeCommons:Ade,CreditCard:U0,Croissant:Tde,Crop:Ede,Cross:Mde,Crosshair:Lde,Crown:q0,Cuboid:Pde,CupSoda:Ide,Currency:Dde,Cylinder:Rde,Dam:Ode,Database:HG,DatabaseBackup:Fde,DatabaseZap:zde,Delete:Bde,Dessert:$de,Diameter:Ude,Diamond:Hde,DiamondMinus:qde,DiamondPercent:rL,DiamondPlus:Vde,Dice1:Gde,Dice2:Wde,Dice3:Kde,Dice4:Yde,Dice5:Zde,Dice6:Xde,Dices:Qde,Diff:Jde,Disc:nue,Disc2:eue,Disc3:tue,DiscAlbum:sue,Divide:rue,Dna:iue,DnaOff:aue,Dock:oue,Dog:lue,DollarSign:Ed,Donut:cue,DoorClosed:due,DoorOpen:h5,Dot:uue,Download:oi,DraftingCompass:hue,Drama:mue,Dribbble:pue,Drill:fue,Droplet:gue,Droplets:K2,Drum:xue,Drumstick:yue,Dumbbell:vue,Ear:_ue,EarOff:bue,Earth:aL,EarthLock:wue,Eclipse:jue,Egg:d9,EggFried:Nue,EggOff:kue,Ellipsis:Iy,EllipsisVertical:Ev,Equal:Aue,EqualApproximately:Sue,EqualNot:Cue,Eraser:Tue,EthernetPort:Eue,Euro:Mue,Expand:Lue,ExternalLink:Tr,Eye:da,EyeClosed:Pue,EyeOff:V0,Facebook:Kf,Factory:Iue,Fan:Due,FastForward:Rue,Feather:Oue,Fence:Fue,FerrisWheel:zue,Figma:Bue,File:u9,FileArchive:$ue,FileAudio:que,FileAudio2:Uue,FileAxis3d:iL,FileBadge:Hue,FileBadge2:Vue,FileBox:Gue,FileChartColumn:lL,FileChartColumnIncreasing:oL,FileChartLine:cL,FileChartPie:dL,FileCheck:GG,FileCheck2:Wue,FileClock:Kue,FileCode:Zue,FileCode2:Yue,FileCog:uL,FileDiff:Xue,FileDigit:Que,FileDown:uD,FileHeart:Jue,FileImage:t3,FileInput:ehe,FileJson:she,FileJson2:the,FileKey:rhe,FileKey2:nhe,FileLock:ihe,FileLock2:ahe,FileMinus:lhe,FileMinus2:ohe,FileMusic:che,FileOutput:dhe,FilePen:hL,FilePenLine:WC,FilePlus:hhe,FilePlus2:uhe,FileQuestion:mhe,FileScan:phe,FileSearch:ghe,FileSearch2:fhe,FileSliders:xhe,FileSpreadsheet:m5,FileStack:WG,FileSymlink:yhe,FileTerminal:vhe,FileText:Wr,FileType:_he,FileType2:bhe,FileUp:whe,FileUser:jhe,FileVideo:KG,FileVideo2:Nhe,FileVolume:She,FileVolume2:khe,FileWarning:Che,FileX:The,FileX2:Ahe,Files:Ehe,Film:Rh,Filter:cj,FilterX:Mhe,Fingerprint:Lhe,FireExtinguisher:Phe,Fish:Rhe,FishOff:Ihe,FishSymbol:Dhe,Flag:s3,FlagOff:Ohe,FlagTriangleLeft:Fhe,FlagTriangleRight:zhe,Flame:Cu,FlameKindling:Bhe,Flashlight:Uhe,FlashlightOff:$he,FlaskConical:ST,FlaskConicalOff:qhe,FlaskRound:Vhe,FlipHorizontal:YG,FlipHorizontal2:Hhe,FlipVertical:Whe,FlipVertical2:Ghe,Flower:Khe,Flower2:U2,Focus:Yhe,FoldHorizontal:Zhe,FoldVertical:Xhe,Folder:Nme,FolderArchive:Qhe,FolderCheck:Jhe,FolderClock:eme,FolderClosed:tme,FolderCode:sme,FolderCog:mL,FolderDot:nme,FolderDown:rme,FolderGit:ime,FolderGit2:ame,FolderHeart:ome,FolderInput:lme,FolderKanban:cme,FolderKey:dme,FolderLock:ume,FolderMinus:hme,FolderOpen:H0,FolderOpenDot:mme,FolderOutput:pme,FolderPen:pL,FolderPlus:fme,FolderRoot:gme,FolderSearch:yme,FolderSearch2:xme,FolderSymlink:vme,FolderSync:bme,FolderTree:_me,FolderUp:wme,FolderX:jme,Folders:kme,Footprints:Sme,Forklift:Cme,Forward:Ame,Frame:Tme,Framer:Eme,Frown:Mme,Fuel:Lme,Fullscreen:Pme,GalleryHorizontal:Dme,GalleryHorizontalEnd:Ime,GalleryThumbnails:Rme,GalleryVertical:Fme,GalleryVerticalEnd:Ome,Gamepad:Bme,Gamepad2:zme,Gauge:$me,Gavel:Ume,Gem:qme,Ghost:hD,Gift:Io,GitBranch:Hme,GitBranchPlus:Vme,GitCommitHorizontal:fL,GitCommitVertical:Gme,GitCompare:Kme,GitCompareArrows:Wme,GitFork:Yme,GitGraph:Zme,GitMerge:Xme,GitPullRequest:npe,GitPullRequestArrow:Qme,GitPullRequestClosed:Jme,GitPullRequestCreate:tpe,GitPullRequestCreateArrow:epe,GitPullRequestDraft:spe,Github:rpe,Gitlab:ape,GlassWater:ipe,Glasses:ope,Globe:au,GlobeLock:lpe,Goal:cpe,Grab:dpe,GraduationCap:Oh,Grape:upe,Grid2x2:xL,Grid2x2Check:hpe,Grid2x2Plus:gL,Grid2x2X:mpe,Grid3x3:Iw,Grip:fpe,GripHorizontal:ppe,GripVertical:Mp,Group:gpe,Guitar:xpe,Ham:ype,Hammer:ZG,Hand:XG,HandCoins:vpe,HandHeart:mD,HandHelping:R2,HandMetal:bpe,HandPlatter:_pe,Handshake:Y2,HardDrive:QG,HardDriveDownload:wpe,HardDriveUpload:jpe,HardHat:Npe,Hash:CT,Haze:kpe,HdmiPort:Spe,Heading:Epe,Heading1:h9,Heading2:m9,Heading3:JG,Heading4:Cpe,Heading5:Ape,Heading6:Tpe,HeadphoneOff:Mpe,Headphones:Lpe,Headset:Ppe,Heart:co,HeartCrack:Ipe,HeartHandshake:pD,HeartOff:Dpe,HeartPulse:Rpe,Heater:Ope,Hexagon:Fpe,Highlighter:zpe,History:fD,Hop:$pe,HopOff:Bpe,Hospital:Upe,Hotel:qpe,Hourglass:Vpe,House:_a,HousePlug:Hpe,HousePlus:Gpe,IceCreamBowl:yL,IceCreamCone:vL,IdCard:Wpe,Image:pc,ImageDown:Kpe,ImageMinus:Ype,ImageOff:Zpe,ImagePlay:Xpe,ImagePlus:Gv,ImageUp:Qpe,ImageUpscale:Jpe,Images:efe,Import:tfe,Inbox:n3,IndentDecrease:bL,IndentIncrease:_L,IndianRupee:sfe,Infinity:nfe,Info:p5,InspectionPanel:rfe,Instagram:dm,Italic:AT,IterationCcw:afe,IterationCw:ife,JapaneseYen:ofe,Joystick:lfe,Kanban:r3,Key:nb,KeyRound:TT,KeySquare:cfe,Keyboard:hfe,KeyboardMusic:dfe,KeyboardOff:ufe,Lamp:yfe,LampCeiling:mfe,LampDesk:pfe,LampFloor:ffe,LampWallDown:gfe,LampWallUp:xfe,LandPlot:vfe,Landmark:eW,Languages:bfe,Laptop:wfe,LaptopMinimal:wL,LaptopMinimalCheck:_fe,Lasso:Nfe,LassoSelect:jfe,Laugh:kfe,Layers:tW,Layers2:Sfe,Layers3:Cfe,LayoutDashboard:ET,LayoutGrid:G0,LayoutList:Afe,LayoutPanelLeft:Tfe,LayoutPanelTop:Efe,LayoutTemplate:a3,Leaf:Mfe,LeafyGreen:Lfe,Lectern:Pfe,LetterText:Ife,Library:rb,LibraryBig:Dfe,LifeBuoy:p9,Ligature:Rfe,Lightbulb:Z2,LightbulbOff:Ofe,Link:gc,Link2:cd,Link2Off:Ffe,Linkedin:W0,List:Kx,ListCheck:zfe,ListChecks:zm,ListCollapse:Bfe,ListEnd:$fe,ListFilter:sW,ListMinus:Ufe,ListMusic:qfe,ListOrdered:dj,ListPlus:Vfe,ListRestart:Hfe,ListStart:Gfe,ListTodo:Wfe,ListTree:Kfe,ListVideo:Yfe,ListX:Zfe,Loader:Qfe,LoaderCircle:us,LoaderPinwheel:Xfe,Locate:f9,LocateFixed:Jfe,LocateOff:ege,Lock:Au,LockKeyhole:tge,LockKeyholeOpen:jL,LockOpen:NL,LogIn:gD,LogOut:xD,Logs:sge,Lollipop:nge,Luggage:rge,Magnet:age,Mail:mn,MailCheck:g9,MailMinus:ige,MailOpen:x9,MailPlus:nW,MailQuestion:oge,MailSearch:lge,MailWarning:cge,MailX:y9,Mailbox:dge,Mails:uge,Map:yD,MapPin:ii,MapPinCheck:mge,MapPinCheckInside:hge,MapPinHouse:pge,MapPinMinus:gge,MapPinMinusInside:fge,MapPinOff:xge,MapPinPlus:vge,MapPinPlusInside:yge,MapPinX:_ge,MapPinXInside:bge,MapPinned:wge,Martini:jge,Maximize:vD,Maximize2:rW,Medal:i3,Megaphone:um,MegaphoneOff:Nge,Meh:kge,MemoryStick:Sge,Menu:MT,Merge:Cge,MessageCircle:Ud,MessageCircleCode:Age,MessageCircleDashed:Tge,MessageCircleHeart:v9,MessageCircleMore:Ege,MessageCircleOff:Mge,MessageCirclePlus:Lge,MessageCircleQuestion:aW,MessageCircleReply:Pge,MessageCircleWarning:Ige,MessageCircleX:Dge,MessageSquare:xo,MessageSquareCode:Rge,MessageSquareDashed:Oge,MessageSquareDiff:Fge,MessageSquareDot:zge,MessageSquareHeart:b9,MessageSquareLock:Bge,MessageSquareMore:iW,MessageSquareOff:$ge,MessageSquarePlus:Qk,MessageSquareQuote:f5,MessageSquareReply:Uge,MessageSquareShare:qge,MessageSquareText:Vge,MessageSquareWarning:Hge,MessageSquareX:Gge,MessagesSquare:_9,Mic:uj,MicOff:Wge,MicVocal:kL,Microchip:Kge,Microscope:Yge,Microwave:Zge,Milestone:Xge,Milk:Jge,MilkOff:Qge,Minimize:txe,Minimize2:exe,Minus:X2,Monitor:hj,MonitorCheck:sxe,MonitorCog:nxe,MonitorDot:rxe,MonitorDown:axe,MonitorOff:ixe,MonitorPause:oxe,MonitorPlay:w9,MonitorSmartphone:lxe,MonitorSpeaker:cxe,MonitorStop:dxe,MonitorUp:bD,MonitorX:uxe,Moon:mxe,MoonStar:hxe,Mountain:fxe,MountainSnow:pxe,Mouse:vxe,MouseOff:gxe,MousePointer:Qg,MousePointer2:xxe,MousePointerBan:yxe,MousePointerClick:ru,Move:oW,Move3d:SL,MoveDiagonal:_xe,MoveDiagonal2:bxe,MoveDown:Nxe,MoveDownLeft:wxe,MoveDownRight:jxe,MoveHorizontal:kxe,MoveLeft:Sxe,MoveRight:Cxe,MoveUp:Exe,MoveUpLeft:Axe,MoveUpRight:Txe,MoveVertical:Mxe,Music:j9,Music2:Lxe,Music3:Pxe,Music4:Ixe,Navigation:lW,Navigation2:Rxe,Navigation2Off:Dxe,NavigationOff:Oxe,Network:Fxe,Newspaper:E_,Nfc:zxe,Notebook:qxe,NotebookPen:Bxe,NotebookTabs:$xe,NotebookText:Uxe,NotepadText:Hxe,NotepadTextDashed:Vxe,Nut:Wxe,NutOff:Gxe,Octagon:Yxe,OctagonAlert:qk,OctagonMinus:Kxe,OctagonPause:CL,OctagonX:AL,Omega:Zxe,Option:Xxe,Orbit:Qxe,Origami:Jxe,Package:Ku,Package2:e0e,PackageCheck:t0e,PackageMinus:s0e,PackageOpen:n0e,PackagePlus:cW,PackageSearch:r0e,PackageX:a0e,PaintBucket:i0e,PaintRoller:o0e,Paintbrush:l0e,PaintbrushVertical:TL,Palette:zc,PanelBottom:u0e,PanelBottomClose:c0e,PanelBottomDashed:EL,PanelBottomOpen:d0e,PanelLeft:IL,PanelLeftClose:ML,PanelLeftDashed:LL,PanelLeftOpen:PL,PanelRight:p0e,PanelRightClose:h0e,PanelRightDashed:DL,PanelRightOpen:m0e,PanelTop:x0e,PanelTopClose:f0e,PanelTopDashed:RL,PanelTopOpen:g0e,PanelsLeftBottom:y0e,PanelsRightBottom:v0e,PanelsTopLeft:c4,Paperclip:LT,Parentheses:b0e,ParkingMeter:_0e,PartyPopper:uf,Pause:K0,PawPrint:w0e,PcCase:j0e,Pen:Ww,PenLine:O2,PenOff:N0e,PenTool:PT,Pencil:Ja,PencilLine:N9,PencilOff:k0e,PencilRuler:S0e,Pentagon:C0e,Percent:IT,PersonStanding:A0e,PhilippinePeso:T0e,Phone:ga,PhoneCall:dW,PhoneForwarded:E0e,PhoneIncoming:M0e,PhoneMissed:L0e,PhoneOff:P0e,PhoneOutgoing:I0e,Pi:D0e,Piano:R0e,Pickaxe:O0e,PictureInPicture:z0e,PictureInPicture2:F0e,PiggyBank:B0e,Pilcrow:q0e,PilcrowLeft:$0e,PilcrowRight:U0e,Pill:H0e,PillBottle:V0e,Pin:DT,PinOff:uW,Pipette:G0e,Pizza:W0e,Plane:hW,PlaneLanding:K0e,PlaneTakeoff:Y0e,Play:dd,Plug:o3,Plug2:Z0e,PlugZap:OL,Plus:nn,Pocket:Q0e,PocketKnife:X0e,Podcast:J0e,Pointer:tye,PointerOff:eye,Popcorn:sye,Popsicle:nye,PoundSterling:rye,Power:mW,PowerOff:aye,Presentation:ab,Printer:pW,PrinterCheck:iye,Projector:oye,Proportions:lye,Puzzle:cye,Pyramid:dye,QrCode:M_,Quote:Q2,Rabbit:uye,Radar:_D,Radiation:hye,Radical:mye,Radio:Y0,RadioReceiver:pye,RadioTower:fye,Radius:gye,RailSymbol:xye,Rainbow:yye,Rat:vye,Ratio:bye,Receipt:Tye,ReceiptCent:_ye,ReceiptEuro:wye,ReceiptIndianRupee:jye,ReceiptJapaneseYen:Nye,ReceiptPoundSterling:kye,ReceiptRussianRuble:Sye,ReceiptSwissFranc:Cye,ReceiptText:Aye,RectangleEllipsis:FL,RectangleHorizontal:Eye,RectangleVertical:Mye,Recycle:Lye,Redo:RT,Redo2:Pye,RedoDot:Iye,RefreshCcw:k9,RefreshCcwDot:Dye,RefreshCw:oo,RefreshCwOff:Rye,Refrigerator:Oye,Regex:Fye,RemoveFormatting:zye,Repeat:S9,Repeat1:Bye,Repeat2:$ye,Replace:qye,ReplaceAll:Uye,Reply:fW,ReplyAll:Vye,Rewind:Hye,Ribbon:Gye,Rocket:By,RockingChair:Wye,RollerCoaster:Kye,Rotate3d:zL,RotateCcw:hf,RotateCcwSquare:Yye,RotateCw:wD,RotateCwSquare:Zye,Route:gW,RouteOff:Xye,Router:Qye,Rows2:BL,Rows3:$L,Rows4:Jye,Rss:eve,Ruler:l3,RussianRuble:tve,Sailboat:sve,Salad:nve,Sandwich:rve,Satellite:ive,SatelliteDish:ave,Save:Kl,SaveAll:ove,SaveOff:lve,Scale:xW,Scale3d:UL,Scaling:cve,Scan:xve,ScanBarcode:dve,ScanEye:uve,ScanFace:hve,ScanLine:mve,ScanQrCode:pve,ScanSearch:fve,ScanText:gve,School:yve,Scissors:bve,ScissorsLineDashed:vve,ScreenShare:wve,ScreenShareOff:_ve,Scroll:jve,ScrollText:yW,Search:Gr,SearchCheck:Nve,SearchCode:kve,SearchSlash:Sve,SearchX:vW,Section:Cve,Send:Rr,SendHorizontal:qL,SendToBack:Ave,SeparatorHorizontal:Tve,SeparatorVertical:Eve,Server:Ive,ServerCog:Mve,ServerCrash:Lve,ServerOff:Pve,Settings:sc,Settings2:C9,Shapes:Dve,Share:bW,Share2:Md,Sheet:Rve,Shell:Ove,Shield:mf,ShieldAlert:A9,ShieldBan:Fve,ShieldCheck:Wv,ShieldEllipsis:zve,ShieldHalf:Bve,ShieldMinus:$ve,ShieldOff:jD,ShieldPlus:Uve,ShieldQuestion:qve,ShieldX:VL,Ship:Hve,ShipWheel:Vve,Shirt:Gve,ShoppingBag:g5,ShoppingBasket:Wve,ShoppingCart:W1,Shovel:Kve,ShowerHead:Yve,Shrink:Zve,Shrub:Xve,Shuffle:ND,Sigma:Qve,Signal:n1e,SignalHigh:Jve,SignalLow:e1e,SignalMedium:t1e,SignalZero:s1e,Signature:r1e,Signpost:i1e,SignpostBig:a1e,Siren:o1e,SkipBack:l1e,SkipForward:c1e,Skull:d1e,Slack:u1e,Slash:h1e,Slice:m1e,SlidersHorizontal:OT,SlidersVertical:HL,Smartphone:$y,SmartphoneCharging:p1e,SmartphoneNfc:f1e,Smile:x1e,SmilePlus:g1e,Snail:y1e,Snowflake:nj,Sofa:v1e,Soup:b1e,Space:_1e,Spade:w1e,Sparkle:c3,Sparkles:Cn,Speaker:j1e,Speech:N1e,SpellCheck:S1e,SpellCheck2:k1e,Spline:C1e,Split:A1e,SprayCan:T1e,Sprout:FT,Square:L_,SquareActivity:GL,SquareArrowDown:YL,SquareArrowDownLeft:WL,SquareArrowDownRight:KL,SquareArrowLeft:ZL,SquareArrowOutDownLeft:XL,SquareArrowOutDownRight:QL,SquareArrowOutUpLeft:JL,SquareArrowOutUpRight:eP,SquareArrowRight:tP,SquareArrowUp:rP,SquareArrowUpLeft:sP,SquareArrowUpRight:nP,SquareAsterisk:aP,SquareBottomDashedScissors:iP,SquareChartGantt:ck,SquareCheck:oP,SquareCheckBig:d4,SquareChevronDown:lP,SquareChevronLeft:cP,SquareChevronRight:dP,SquareChevronUp:uP,SquareCode:hP,SquareDashed:fP,SquareDashedBottom:M1e,SquareDashedBottomCode:E1e,SquareDashedKanban:mP,SquareDashedMousePointer:pP,SquareDivide:gP,SquareDot:xP,SquareEqual:yP,SquareFunction:vP,SquareKanban:bP,SquareLibrary:_P,SquareM:wP,SquareMenu:jP,SquareMinus:NP,SquareMousePointer:kP,SquareParking:CP,SquareParkingOff:SP,SquarePen:xp,SquarePercent:AP,SquarePi:TP,SquarePilcrow:EP,SquarePlay:MP,SquarePlus:LP,SquarePower:PP,SquareRadical:L1e,SquareScissors:IP,SquareSigma:DP,SquareSlash:RP,SquareSplitHorizontal:OP,SquareSplitVertical:FP,SquareSquare:P1e,SquareStack:I1e,SquareTerminal:zP,SquareUser:$P,SquareUserRound:BP,SquareX:UP,Squircle:D1e,Squirrel:R1e,Stamp:O1e,Star:Wa,StarHalf:F1e,StarOff:z1e,StepBack:B1e,StepForward:$1e,Stethoscope:U1e,Sticker:q1e,StickyNote:_W,Store:wW,StretchHorizontal:V1e,StretchVertical:H1e,Strikethrough:jW,Subscript:G1e,Sun:J2,SunDim:W1e,SunMedium:K1e,SunMoon:Y1e,SunSnow:Z1e,Sunrise:X1e,Sunset:Q1e,Superscript:J1e,SwatchBook:ebe,SwissFranc:tbe,SwitchCamera:sbe,Sword:nbe,Swords:rbe,Syringe:abe,Table:E9,Table2:T9,TableCellsMerge:ibe,TableCellsSplit:obe,TableColumnsSplit:lbe,TableOfContents:cbe,TableProperties:dbe,TableRowsSplit:ube,Tablet:M9,TabletSmartphone:hbe,Tablets:mbe,Tag:pf,Tags:NW,Tally1:pbe,Tally2:fbe,Tally3:gbe,Tally4:xbe,Tally5:ybe,Tangent:vbe,Target:iu,Telescope:bbe,Tent:wbe,TentTree:_be,Terminal:jbe,TestTube:Nbe,TestTubeDiagonal:qP,TestTubes:kbe,Text:Ebe,TextCursor:Cbe,TextCursorInput:Sbe,TextQuote:Abe,TextSearch:Tbe,TextSelect:VP,Theater:Mbe,Thermometer:kW,ThermometerSnowflake:Lbe,ThermometerSun:Pbe,ThumbsDown:SW,ThumbsUp:ax,Ticket:CW,TicketCheck:Ibe,TicketMinus:Dbe,TicketPercent:Rbe,TicketPlus:Obe,TicketSlash:Fbe,TicketX:zbe,Tickets:$be,TicketsPlane:Bbe,Timer:Vbe,TimerOff:Ube,TimerReset:qbe,ToggleLeft:Hbe,ToggleRight:Gbe,Toilet:Wbe,Tornado:Kbe,Torus:Ybe,Touchpad:Xbe,TouchpadOff:Zbe,TowerControl:Qbe,ToyBrick:Jbe,Tractor:e_e,TrafficCone:t_e,TrainFront:n_e,TrainFrontTunnel:s_e,TrainTrack:r_e,TramFront:HP,Trash:a_e,Trash2:qn,TreeDeciduous:i_e,TreePalm:GP,TreePine:zT,Trees:o_e,Trello:l_e,TrendingDown:eN,TrendingUp:ml,TrendingUpDown:c_e,Triangle:u_e,TriangleAlert:xd,TriangleRight:d_e,Trophy:gl,Truck:AW,Turtle:h_e,Tv:p_e,TvMinimal:WP,TvMinimalPlay:m_e,Twitch:f_e,Twitter:g_e,Type:y_e,TypeOutline:x_e,Umbrella:b_e,UmbrellaOff:v_e,Underline:L9,Undo:BT,Undo2:TW,UndoDot:__e,UnfoldHorizontal:w_e,UnfoldVertical:j_e,Ungroup:N_e,University:KP,Unlink:kD,Unlink2:k_e,Unplug:S_e,Upload:ni,Usb:C_e,User:Ro,UserCheck:tN,UserCog:EW,UserMinus:MW,UserPen:A_e,UserPlus:Yl,UserRound:eI,UserRoundCheck:YP,UserRoundCog:ZP,UserRoundMinus:XP,UserRoundPen:T_e,UserRoundPlus:QP,UserRoundSearch:E_e,UserRoundX:JP,UserSearch:M_e,UserX:L_e,Users:Yn,UsersRound:f_,Utensils:sI,UtensilsCrossed:tI,UtilityPole:P_e,Variable:P9,Vault:I_e,Vegan:D_e,VenetianMask:R_e,Vibrate:F_e,VibrateOff:O_e,Video:na,VideoOff:z_e,Videotape:B_e,View:$_e,Voicemail:U_e,Volleyball:q_e,Volume:G_e,Volume1:V_e,Volume2:LW,VolumeOff:H_e,VolumeX:PW,Vote:W_e,Wallet:I9,WalletCards:K_e,WalletMinimal:nI,Wallpaper:Y_e,Wand:Z_e,WandSparkles:Zg,Warehouse:X_e,WashingMachine:Q_e,Watch:J_e,Waves:ewe,Waypoints:twe,Webcam:swe,Webhook:rwe,WebhookOff:nwe,Weight:awe,Wheat:owe,WheatOff:iwe,WholeWord:lwe,Wifi:mwe,WifiHigh:cwe,WifiLow:dwe,WifiOff:uwe,WifiZero:hwe,Wind:fwe,WindArrowDown:pwe,Wine:IW,WineOff:gwe,Workflow:DW,Worm:xwe,WrapText:ywe,Wrench:sN,X:hr,Youtube:vwe,Zap:ff,ZapOff:bwe,ZoomIn:$T,ZoomOut:D9},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 zSe=Object.freeze(Object.defineProperty({__proto__:null,AArrowDown:Sre,AArrowDownIcon:Sre,AArrowUp:Cre,AArrowUpIcon:Cre,ALargeSmall:Are,ALargeSmallIcon:Are,Accessibility:Tre,AccessibilityIcon:Tre,Activity:gg,ActivityIcon:gg,ActivitySquare:GL,ActivitySquareIcon:GL,AirVent:Ere,AirVentIcon:Ere,Airplay:Mre,AirplayIcon:Mre,AlarmCheck:J6,AlarmCheckIcon:J6,AlarmClock:Pre,AlarmClockCheck:J6,AlarmClockCheckIcon:J6,AlarmClockIcon:Pre,AlarmClockMinus:eM,AlarmClockMinusIcon:eM,AlarmClockOff:Lre,AlarmClockOffIcon:Lre,AlarmClockPlus:tM,AlarmClockPlusIcon:tM,AlarmMinus:eM,AlarmMinusIcon:eM,AlarmPlus:tM,AlarmPlusIcon:tM,AlarmSmoke:Ire,AlarmSmokeIcon:Ire,Album:Dre,AlbumIcon:Dre,AlertCircle:Uo,AlertCircleIcon:Uo,AlertOctagon:qk,AlertOctagonIcon:qk,AlertTriangle:xd,AlertTriangleIcon:xd,AlignCenter:sD,AlignCenterHorizontal:Rre,AlignCenterHorizontalIcon:Rre,AlignCenterIcon:sD,AlignCenterVertical:Ore,AlignCenterVerticalIcon:Ore,AlignEndHorizontal:Fre,AlignEndHorizontalIcon:Fre,AlignEndVertical:zre,AlignEndVerticalIcon:zre,AlignHorizontalDistributeCenter:Bre,AlignHorizontalDistributeCenterIcon:Bre,AlignHorizontalDistributeEnd:$re,AlignHorizontalDistributeEndIcon:$re,AlignHorizontalDistributeStart:Ure,AlignHorizontalDistributeStartIcon:Ure,AlignHorizontalJustifyCenter:qre,AlignHorizontalJustifyCenterIcon:qre,AlignHorizontalJustifyEnd:Vre,AlignHorizontalJustifyEndIcon:Vre,AlignHorizontalJustifyStart:Hre,AlignHorizontalJustifyStartIcon:Hre,AlignHorizontalSpaceAround:Gre,AlignHorizontalSpaceAroundIcon:Gre,AlignHorizontalSpaceBetween:Wre,AlignHorizontalSpaceBetweenIcon:Wre,AlignJustify:Kre,AlignJustifyIcon:Kre,AlignLeft:nD,AlignLeftIcon:nD,AlignRight:rD,AlignRightIcon:rD,AlignStartHorizontal:Yre,AlignStartHorizontalIcon:Yre,AlignStartVertical:Zre,AlignStartVerticalIcon:Zre,AlignVerticalDistributeCenter:Xre,AlignVerticalDistributeCenterIcon:Xre,AlignVerticalDistributeEnd:Qre,AlignVerticalDistributeEndIcon:Qre,AlignVerticalDistributeStart:Jre,AlignVerticalDistributeStartIcon:Jre,AlignVerticalJustifyCenter:eae,AlignVerticalJustifyCenterIcon:eae,AlignVerticalJustifyEnd:tae,AlignVerticalJustifyEndIcon:tae,AlignVerticalJustifyStart:sae,AlignVerticalJustifyStartIcon:sae,AlignVerticalSpaceAround:nae,AlignVerticalSpaceAroundIcon:nae,AlignVerticalSpaceBetween:rae,AlignVerticalSpaceBetweenIcon:rae,Ambulance:aae,AmbulanceIcon:aae,Ampersand:iae,AmpersandIcon:iae,Ampersands:oae,AmpersandsIcon:oae,Amphora:lae,AmphoraIcon:lae,Anchor:cae,AnchorIcon:cae,Angry:dae,AngryIcon:dae,Annoyed:uae,AnnoyedIcon:uae,Antenna:hae,AntennaIcon:hae,Anvil:mae,AnvilIcon:mae,Aperture:pae,ApertureIcon:pae,AppWindow:gae,AppWindowIcon:gae,AppWindowMac:fae,AppWindowMacIcon:fae,Apple:xae,AppleIcon:xae,Archive:xg,ArchiveIcon:xg,ArchiveRestore:a9,ArchiveRestoreIcon:a9,ArchiveX:yae,ArchiveXIcon:yae,AreaChart:fM,AreaChartIcon:fM,Armchair:vae,ArmchairIcon:vae,ArrowBigDown:_ae,ArrowBigDownDash:bae,ArrowBigDownDashIcon:bae,ArrowBigDownIcon:_ae,ArrowBigLeft:jae,ArrowBigLeftDash:wae,ArrowBigLeftDashIcon:wae,ArrowBigLeftIcon:jae,ArrowBigRight:kae,ArrowBigRightDash:Nae,ArrowBigRightDashIcon:Nae,ArrowBigRightIcon:kae,ArrowBigUp:Cae,ArrowBigUpDash:Sae,ArrowBigUpDashIcon:Sae,ArrowBigUpIcon:Cae,ArrowDown:Wf,ArrowDown01:Aae,ArrowDown01Icon:Aae,ArrowDown10:Tae,ArrowDown10Icon:Tae,ArrowDownAZ:sM,ArrowDownAZIcon:sM,ArrowDownAz:sM,ArrowDownAzIcon:sM,ArrowDownCircle:CM,ArrowDownCircleIcon:CM,ArrowDownFromLine:Eae,ArrowDownFromLineIcon:Eae,ArrowDownIcon:Wf,ArrowDownLeft:Mae,ArrowDownLeftFromCircle:TM,ArrowDownLeftFromCircleIcon:TM,ArrowDownLeftFromSquare:XL,ArrowDownLeftFromSquareIcon:XL,ArrowDownLeftIcon:Mae,ArrowDownLeftSquare:WL,ArrowDownLeftSquareIcon:WL,ArrowDownNarrowWide:Lae,ArrowDownNarrowWideIcon:Lae,ArrowDownRight:OG,ArrowDownRightFromCircle:EM,ArrowDownRightFromCircleIcon:EM,ArrowDownRightFromSquare:QL,ArrowDownRightFromSquareIcon:QL,ArrowDownRightIcon:OG,ArrowDownRightSquare:KL,ArrowDownRightSquareIcon:KL,ArrowDownSquare:YL,ArrowDownSquareIcon:YL,ArrowDownToDot:Pae,ArrowDownToDotIcon:Pae,ArrowDownToLine:Iae,ArrowDownToLineIcon:Iae,ArrowDownUp:Dae,ArrowDownUpIcon:Dae,ArrowDownWideNarrow:nM,ArrowDownWideNarrowIcon:nM,ArrowDownZA:rM,ArrowDownZAIcon:rM,ArrowDownZa:rM,ArrowDownZaIcon:rM,ArrowLeft:ka,ArrowLeftCircle:AM,ArrowLeftCircleIcon:AM,ArrowLeftFromLine:Rae,ArrowLeftFromLineIcon:Rae,ArrowLeftIcon:ka,ArrowLeftRight:Oae,ArrowLeftRightIcon:Oae,ArrowLeftSquare:ZL,ArrowLeftSquareIcon:ZL,ArrowLeftToLine:Fae,ArrowLeftToLineIcon:Fae,ArrowRight:vi,ArrowRightCircle:PM,ArrowRightCircleIcon:PM,ArrowRightFromLine:zae,ArrowRightFromLineIcon:zae,ArrowRightIcon:vi,ArrowRightLeft:c5,ArrowRightLeftIcon:c5,ArrowRightSquare:tP,ArrowRightSquareIcon:tP,ArrowRightToLine:Bae,ArrowRightToLineIcon:Bae,ArrowUp:Om,ArrowUp01:$ae,ArrowUp01Icon:$ae,ArrowUp10:Uae,ArrowUp10Icon:Uae,ArrowUpAZ:aM,ArrowUpAZIcon:aM,ArrowUpAz:aM,ArrowUpAzIcon:aM,ArrowUpCircle:IM,ArrowUpCircleIcon:IM,ArrowUpDown:mg,ArrowUpDownIcon:mg,ArrowUpFromDot:qae,ArrowUpFromDotIcon:qae,ArrowUpFromLine:Vae,ArrowUpFromLineIcon:Vae,ArrowUpIcon:Om,ArrowUpLeft:Hae,ArrowUpLeftFromCircle:MM,ArrowUpLeftFromCircleIcon:MM,ArrowUpLeftFromSquare:JL,ArrowUpLeftFromSquareIcon:JL,ArrowUpLeftIcon:Hae,ArrowUpLeftSquare:sP,ArrowUpLeftSquareIcon:sP,ArrowUpNarrowWide:iM,ArrowUpNarrowWideIcon:iM,ArrowUpRight:i9,ArrowUpRightFromCircle:LM,ArrowUpRightFromCircleIcon:LM,ArrowUpRightFromSquare:eP,ArrowUpRightFromSquareIcon:eP,ArrowUpRightIcon:i9,ArrowUpRightSquare:nP,ArrowUpRightSquareIcon:nP,ArrowUpSquare:rP,ArrowUpSquareIcon:rP,ArrowUpToLine:Gae,ArrowUpToLineIcon:Gae,ArrowUpWideNarrow:Wae,ArrowUpWideNarrowIcon:Wae,ArrowUpZA:oM,ArrowUpZAIcon:oM,ArrowUpZa:oM,ArrowUpZaIcon:oM,ArrowsUpFromLine:Kae,ArrowsUpFromLineIcon:Kae,Asterisk:Yae,AsteriskIcon:Yae,AsteriskSquare:aP,AsteriskSquareIcon:aP,AtSign:Zae,AtSignIcon:Zae,Atom:Xae,AtomIcon:Xae,AudioLines:Qae,AudioLinesIcon:Qae,AudioWaveform:Jae,AudioWaveformIcon:Jae,Award:ku,AwardIcon:ku,Axe:eie,AxeIcon:eie,Axis3D:lM,Axis3DIcon:lM,Axis3d:lM,Axis3dIcon:lM,Baby:tie,BabyIcon:tie,Backpack:sie,BackpackIcon:sie,Badge:yie,BadgeAlert:nie,BadgeAlertIcon:nie,BadgeCent:rie,BadgeCentIcon:rie,BadgeCheck:cM,BadgeCheckIcon:cM,BadgeDollarSign:aie,BadgeDollarSignIcon:aie,BadgeEuro:iie,BadgeEuroIcon:iie,BadgeHelp:oie,BadgeHelpIcon:oie,BadgeIcon:yie,BadgeIndianRupee:lie,BadgeIndianRupeeIcon:lie,BadgeInfo:cie,BadgeInfoIcon:cie,BadgeJapaneseYen:die,BadgeJapaneseYenIcon:die,BadgeMinus:uie,BadgeMinusIcon:uie,BadgePercent:hie,BadgePercentIcon:hie,BadgePlus:mie,BadgePlusIcon:mie,BadgePoundSterling:pie,BadgePoundSterlingIcon:pie,BadgeRussianRuble:fie,BadgeRussianRubleIcon:fie,BadgeSwissFranc:gie,BadgeSwissFrancIcon:gie,BadgeX:xie,BadgeXIcon:xie,BaggageClaim:vie,BaggageClaimIcon:vie,Ban:o9,BanIcon:o9,Banana:bie,BananaIcon:bie,Bandage:_ie,BandageIcon:_ie,Banknote:wie,BanknoteIcon:wie,BarChart:wM,BarChart2:jM,BarChart2Icon:jM,BarChart3:fl,BarChart3Icon:fl,BarChart4:bM,BarChart4Icon:bM,BarChartBig:vM,BarChartBigIcon:vM,BarChartHorizontal:xM,BarChartHorizontalBig:gM,BarChartHorizontalBigIcon:gM,BarChartHorizontalIcon:xM,BarChartIcon:wM,Barcode:jie,BarcodeIcon:jie,Baseline:Nie,BaselineIcon:Nie,Bath:Wx,BathIcon:Wx,Battery:Eie,BatteryCharging:kie,BatteryChargingIcon:kie,BatteryFull:Sie,BatteryFullIcon:Sie,BatteryIcon:Eie,BatteryLow:Cie,BatteryLowIcon:Cie,BatteryMedium:Aie,BatteryMediumIcon:Aie,BatteryWarning:Tie,BatteryWarningIcon:Tie,Beaker:FG,BeakerIcon:FG,Bean:Lie,BeanIcon:Lie,BeanOff:Mie,BeanOffIcon:Mie,Bed:A_,BedDouble:J4,BedDoubleIcon:J4,BedIcon:A_,BedSingle:Pie,BedSingleIcon:Pie,Beef:Iie,BeefIcon:Iie,Beer:Rie,BeerIcon:Rie,BeerOff:Die,BeerOffIcon:Die,Bell:yg,BellDot:Oie,BellDotIcon:Oie,BellElectric:Fie,BellElectricIcon:Fie,BellIcon:yg,BellMinus:zie,BellMinusIcon:zie,BellOff:d5,BellOffIcon:d5,BellPlus:Bie,BellPlusIcon:Bie,BellRing:wT,BellRingIcon:wT,BetweenHorizonalEnd:dM,BetweenHorizonalEndIcon:dM,BetweenHorizonalStart:uM,BetweenHorizonalStartIcon:uM,BetweenHorizontalEnd:dM,BetweenHorizontalEndIcon:dM,BetweenHorizontalStart:uM,BetweenHorizontalStartIcon:uM,BetweenVerticalEnd:$ie,BetweenVerticalEndIcon:$ie,BetweenVerticalStart:Uie,BetweenVerticalStartIcon:Uie,BicepsFlexed:qie,BicepsFlexedIcon:qie,Bike:Vie,BikeIcon:Vie,Binary:Hie,BinaryIcon:Hie,Binoculars:Gie,BinocularsIcon:Gie,Biohazard:Wie,BiohazardIcon:Wie,Bird:Kie,BirdIcon:Kie,Bitcoin:Yie,BitcoinIcon:Yie,Blend:Zie,BlendIcon:Zie,Blinds:Xie,BlindsIcon:Xie,Blocks:Qie,BlocksIcon:Qie,Bluetooth:soe,BluetoothConnected:Jie,BluetoothConnectedIcon:Jie,BluetoothIcon:soe,BluetoothOff:eoe,BluetoothOffIcon:eoe,BluetoothSearching:toe,BluetoothSearchingIcon:toe,Bold:jT,BoldIcon:jT,Bolt:noe,BoltIcon:noe,Bomb:roe,BombIcon:roe,Bone:aoe,BoneIcon:aoe,Book:Coe,BookA:ioe,BookAIcon:ioe,BookAudio:ooe,BookAudioIcon:ooe,BookCheck:loe,BookCheckIcon:loe,BookCopy:coe,BookCopyIcon:coe,BookDashed:hM,BookDashedIcon:hM,BookDown:doe,BookDownIcon:doe,BookHeadphones:uoe,BookHeadphonesIcon:uoe,BookHeart:hoe,BookHeartIcon:hoe,BookIcon:Coe,BookImage:moe,BookImageIcon:moe,BookKey:poe,BookKeyIcon:poe,BookLock:foe,BookLockIcon:foe,BookMarked:goe,BookMarkedIcon:goe,BookMinus:xoe,BookMinusIcon:xoe,BookOpen:Ep,BookOpenCheck:yoe,BookOpenCheckIcon:yoe,BookOpenIcon:Ep,BookOpenText:voe,BookOpenTextIcon:voe,BookPlus:boe,BookPlusIcon:boe,BookTemplate:hM,BookTemplateIcon:hM,BookText:_oe,BookTextIcon:_oe,BookType:woe,BookTypeIcon:woe,BookUp:Noe,BookUp2:joe,BookUp2Icon:joe,BookUpIcon:Noe,BookUser:koe,BookUserIcon:koe,BookX:Soe,BookXIcon:Soe,Bookmark:Hv,BookmarkCheck:Aoe,BookmarkCheckIcon:Aoe,BookmarkIcon:Hv,BookmarkMinus:Toe,BookmarkMinusIcon:Toe,BookmarkPlus:aD,BookmarkPlusIcon:aD,BookmarkX:Eoe,BookmarkXIcon:Eoe,BoomBox:Moe,BoomBoxIcon:Moe,Bot:NT,BotIcon:NT,BotMessageSquare:Loe,BotMessageSquareIcon:Loe,BotOff:Poe,BotOffIcon:Poe,Box:zG,BoxIcon:zG,BoxSelect:fP,BoxSelectIcon:fP,Boxes:Ioe,BoxesIcon:Ioe,Braces:mM,BracesIcon:mM,Brackets:Doe,BracketsIcon:Doe,Brain:BG,BrainCircuit:Roe,BrainCircuitIcon:Roe,BrainCog:Ooe,BrainCogIcon:Ooe,BrainIcon:BG,BrickWall:Foe,BrickWallIcon:Foe,Briefcase:vg,BriefcaseBusiness:zoe,BriefcaseBusinessIcon:zoe,BriefcaseConveyorBelt:Boe,BriefcaseConveyorBeltIcon:Boe,BriefcaseIcon:vg,BriefcaseMedical:$oe,BriefcaseMedicalIcon:$oe,BringToFront:Uoe,BringToFrontIcon:Uoe,Brush:qoe,BrushIcon:qoe,Bug:Goe,BugIcon:Goe,BugOff:Voe,BugOffIcon:Voe,BugPlay:Hoe,BugPlayIcon:Hoe,Building:iD,Building2:Ti,Building2Icon:Ti,BuildingIcon:iD,Bus:Koe,BusFront:Woe,BusFrontIcon:Woe,BusIcon:Koe,Cable:Zoe,CableCar:Yoe,CableCarIcon:Yoe,CableIcon:Zoe,Cake:Fm,CakeIcon:Fm,CakeSlice:Xoe,CakeSliceIcon:Xoe,Calculator:u5,CalculatorIcon:u5,Calendar:ta,Calendar1:Qoe,Calendar1Icon:Qoe,CalendarArrowDown:Joe,CalendarArrowDownIcon:Joe,CalendarArrowUp:ele,CalendarArrowUpIcon:ele,CalendarCheck:kT,CalendarCheck2:tle,CalendarCheck2Icon:tle,CalendarCheckIcon:kT,CalendarClock:df,CalendarClockIcon:df,CalendarCog:sle,CalendarCogIcon:sle,CalendarDays:ld,CalendarDaysIcon:ld,CalendarFold:nle,CalendarFoldIcon:nle,CalendarHeart:W2,CalendarHeartIcon:W2,CalendarIcon:ta,CalendarMinus:ale,CalendarMinus2:rle,CalendarMinus2Icon:rle,CalendarMinusIcon:ale,CalendarOff:$G,CalendarOffIcon:$G,CalendarPlus:Pv,CalendarPlus2:ile,CalendarPlus2Icon:ile,CalendarPlusIcon:Pv,CalendarRange:ole,CalendarRangeIcon:ole,CalendarSearch:lle,CalendarSearchIcon:lle,CalendarSync:cle,CalendarSyncIcon:cle,CalendarX:UG,CalendarX2:dle,CalendarX2Icon:dle,CalendarXIcon:UG,Camera:$0,CameraIcon:$0,CameraOff:ule,CameraOffIcon:ule,CandlestickChart:yM,CandlestickChartIcon:yM,Candy:ple,CandyCane:hle,CandyCaneIcon:hle,CandyIcon:ple,CandyOff:mle,CandyOffIcon:mle,Cannabis:fle,CannabisIcon:fle,Captions:pM,CaptionsIcon:pM,CaptionsOff:gle,CaptionsOffIcon:gle,Car:vle,CarFront:xle,CarFrontIcon:xle,CarIcon:vle,CarTaxiFront:yle,CarTaxiFrontIcon:yle,Caravan:ble,CaravanIcon:ble,Carrot:_le,CarrotIcon:_le,CaseLower:wle,CaseLowerIcon:wle,CaseSensitive:jle,CaseSensitiveIcon:jle,CaseUpper:Nle,CaseUpperIcon:Nle,CassetteTape:kle,CassetteTapeIcon:kle,Cast:Sle,CastIcon:Sle,Castle:Cle,CastleIcon:Cle,Cat:Ale,CatIcon:Ale,Cctv:Tle,CctvIcon:Tle,ChartArea:fM,ChartAreaIcon:fM,ChartBar:xM,ChartBarBig:gM,ChartBarBigIcon:gM,ChartBarDecreasing:Ele,ChartBarDecreasingIcon:Ele,ChartBarIcon:xM,ChartBarIncreasing:Mle,ChartBarIncreasingIcon:Mle,ChartBarStacked:Lle,ChartBarStackedIcon:Lle,ChartCandlestick:yM,ChartCandlestickIcon:yM,ChartColumn:fl,ChartColumnBig:vM,ChartColumnBigIcon:vM,ChartColumnDecreasing:Ple,ChartColumnDecreasingIcon:Ple,ChartColumnIcon:fl,ChartColumnIncreasing:bM,ChartColumnIncreasingIcon:bM,ChartColumnStacked:Ile,ChartColumnStackedIcon:Ile,ChartGantt:Dle,ChartGanttIcon:Dle,ChartLine:_M,ChartLineIcon:_M,ChartNetwork:Rle,ChartNetworkIcon:Rle,ChartNoAxesColumn:jM,ChartNoAxesColumnDecreasing:Ole,ChartNoAxesColumnDecreasingIcon:Ole,ChartNoAxesColumnIcon:jM,ChartNoAxesColumnIncreasing:wM,ChartNoAxesColumnIncreasingIcon:wM,ChartNoAxesCombined:Fle,ChartNoAxesCombinedIcon:Fle,ChartNoAxesGantt:NM,ChartNoAxesGanttIcon:NM,ChartPie:kM,ChartPieIcon:kM,ChartScatter:SM,ChartScatterIcon:SM,ChartSpline:zle,ChartSplineIcon:zle,Check:pa,CheckCheck:oD,CheckCheckIcon:oD,CheckCircle:Po,CheckCircle2:Hr,CheckCircle2Icon:Hr,CheckCircleIcon:Po,CheckIcon:pa,CheckSquare:d4,CheckSquare2:oP,CheckSquare2Icon:oP,CheckSquareIcon:d4,ChefHat:Ble,ChefHatIcon:Ble,Cherry:$le,CherryIcon:$le,ChevronDown:Xo,ChevronDownCircle:DM,ChevronDownCircleIcon:DM,ChevronDownIcon:Xo,ChevronDownSquare:lP,ChevronDownSquareIcon:lP,ChevronFirst:Ule,ChevronFirstIcon:Ule,ChevronLast:qle,ChevronLastIcon:qle,ChevronLeft:Fc,ChevronLeftCircle:RM,ChevronLeftCircleIcon:RM,ChevronLeftIcon:Fc,ChevronLeftSquare:cP,ChevronLeftSquareIcon:cP,ChevronRight:Qa,ChevronRightCircle:OM,ChevronRightCircleIcon:OM,ChevronRightIcon:Qa,ChevronRightSquare:dP,ChevronRightSquareIcon:dP,ChevronUp:zy,ChevronUpCircle:FM,ChevronUpCircleIcon:FM,ChevronUpIcon:zy,ChevronUpSquare:uP,ChevronUpSquareIcon:uP,ChevronsDown:Hle,ChevronsDownIcon:Hle,ChevronsDownUp:Vle,ChevronsDownUpIcon:Vle,ChevronsLeft:Kle,ChevronsLeftIcon:Kle,ChevronsLeftRight:Wle,ChevronsLeftRightEllipsis:Gle,ChevronsLeftRightEllipsisIcon:Gle,ChevronsLeftRightIcon:Wle,ChevronsRight:Zle,ChevronsRightIcon:Zle,ChevronsRightLeft:Yle,ChevronsRightLeftIcon:Yle,ChevronsUp:Xle,ChevronsUpDown:sb,ChevronsUpDownIcon:sb,ChevronsUpIcon:Xle,Chrome:lD,ChromeIcon:lD,Church:Qle,ChurchIcon:Qle,Cigarette:ece,CigaretteIcon:ece,CigaretteOff:Jle,CigaretteOffIcon:Jle,Circle:bg,CircleAlert:Uo,CircleAlertIcon:Uo,CircleArrowDown:CM,CircleArrowDownIcon:CM,CircleArrowLeft:AM,CircleArrowLeftIcon:AM,CircleArrowOutDownLeft:TM,CircleArrowOutDownLeftIcon:TM,CircleArrowOutDownRight:EM,CircleArrowOutDownRightIcon:EM,CircleArrowOutUpLeft:MM,CircleArrowOutUpLeftIcon:MM,CircleArrowOutUpRight:LM,CircleArrowOutUpRightIcon:LM,CircleArrowRight:PM,CircleArrowRightIcon:PM,CircleArrowUp:IM,CircleArrowUpIcon:IM,CircleCheck:Hr,CircleCheckBig:Po,CircleCheckBigIcon:Po,CircleCheckIcon:Hr,CircleChevronDown:DM,CircleChevronDownIcon:DM,CircleChevronLeft:RM,CircleChevronLeftIcon:RM,CircleChevronRight:OM,CircleChevronRightIcon:OM,CircleChevronUp:FM,CircleChevronUpIcon:FM,CircleDashed:tce,CircleDashedIcon:tce,CircleDivide:zM,CircleDivideIcon:zM,CircleDollarSign:sce,CircleDollarSignIcon:sce,CircleDot:rce,CircleDotDashed:nce,CircleDotDashedIcon:nce,CircleDotIcon:rce,CircleEllipsis:ace,CircleEllipsisIcon:ace,CircleEqual:ice,CircleEqualIcon:ice,CircleFadingArrowUp:oce,CircleFadingArrowUpIcon:oce,CircleFadingPlus:lce,CircleFadingPlusIcon:lce,CircleGauge:BM,CircleGaugeIcon:BM,CircleHelp:Uk,CircleHelpIcon:Uk,CircleIcon:bg,CircleMinus:$M,CircleMinusIcon:$M,CircleOff:cce,CircleOffIcon:cce,CircleParking:qM,CircleParkingIcon:qM,CircleParkingOff:UM,CircleParkingOffIcon:UM,CirclePause:VM,CirclePauseIcon:VM,CirclePercent:HM,CirclePercentIcon:HM,CirclePlay:wp,CirclePlayIcon:wp,CirclePlus:GM,CirclePlusIcon:GM,CirclePower:WM,CirclePowerIcon:WM,CircleSlash:dce,CircleSlash2:KM,CircleSlash2Icon:KM,CircleSlashIcon:dce,CircleSlashed:KM,CircleSlashedIcon:KM,CircleStop:YM,CircleStopIcon:YM,CircleUser:XM,CircleUserIcon:XM,CircleUserRound:ZM,CircleUserRoundIcon:ZM,CircleX:Nu,CircleXIcon:Nu,CircuitBoard:uce,CircuitBoardIcon:uce,Citrus:hce,CitrusIcon:hce,Clapperboard:l9,ClapperboardIcon:l9,Clipboard:vce,ClipboardCheck:e3,ClipboardCheckIcon:e3,ClipboardCopy:mce,ClipboardCopyIcon:mce,ClipboardEdit:JM,ClipboardEditIcon:JM,ClipboardIcon:vce,ClipboardList:lj,ClipboardListIcon:lj,ClipboardMinus:pce,ClipboardMinusIcon:pce,ClipboardPaste:fce,ClipboardPasteIcon:fce,ClipboardPen:JM,ClipboardPenIcon:JM,ClipboardPenLine:QM,ClipboardPenLineIcon:QM,ClipboardPlus:gce,ClipboardPlusIcon:gce,ClipboardSignature:QM,ClipboardSignatureIcon:QM,ClipboardType:xce,ClipboardTypeIcon:xce,ClipboardX:yce,ClipboardXIcon:yce,Clock:Xr,Clock1:bce,Clock10:_ce,Clock10Icon:_ce,Clock11:wce,Clock11Icon:wce,Clock12:jce,Clock12Icon:jce,Clock1Icon:bce,Clock2:Nce,Clock2Icon:Nce,Clock3:qG,Clock3Icon:qG,Clock4:kce,Clock4Icon:kce,Clock5:Sce,Clock5Icon:Sce,Clock6:Cce,Clock6Icon:Cce,Clock7:Ace,Clock7Icon:Ace,Clock8:Tce,Clock8Icon:Tce,Clock9:Ece,Clock9Icon:Ece,ClockAlert:Mce,ClockAlertIcon:Mce,ClockArrowDown:Lce,ClockArrowDownIcon:Lce,ClockArrowUp:Pce,ClockArrowUpIcon:Pce,ClockIcon:Xr,Cloud:Kce,CloudAlert:Ice,CloudAlertIcon:Ice,CloudCog:Dce,CloudCogIcon:Dce,CloudDownload:eL,CloudDownloadIcon:eL,CloudDrizzle:Rce,CloudDrizzleIcon:Rce,CloudFog:Oce,CloudFogIcon:Oce,CloudHail:Fce,CloudHailIcon:Fce,CloudIcon:Kce,CloudLightning:zce,CloudLightningIcon:zce,CloudMoon:$ce,CloudMoonIcon:$ce,CloudMoonRain:Bce,CloudMoonRainIcon:Bce,CloudOff:Uce,CloudOffIcon:Uce,CloudRain:Vce,CloudRainIcon:Vce,CloudRainWind:qce,CloudRainWindIcon:qce,CloudSnow:Hce,CloudSnowIcon:Hce,CloudSun:Wce,CloudSunIcon:Wce,CloudSunRain:Gce,CloudSunRainIcon:Gce,CloudUpload:tL,CloudUploadIcon:tL,Cloudy:Yce,CloudyIcon:Yce,Clover:V4,CloverIcon:V4,Club:Zce,ClubIcon:Zce,Code:cD,Code2:l4,Code2Icon:l4,CodeIcon:cD,CodeSquare:hP,CodeSquareIcon:hP,CodeXml:l4,CodeXmlIcon:l4,Codepen:Xce,CodepenIcon:Xce,Codesandbox:Qce,CodesandboxIcon:Qce,Coffee:T_,CoffeeIcon:T_,Cog:Jce,CogIcon:Jce,Coins:VG,CoinsIcon:VG,Columns:sL,Columns2:sL,Columns2Icon:sL,Columns3:GC,Columns3Icon:GC,Columns4:ede,Columns4Icon:ede,ColumnsIcon:sL,Combine:tde,CombineIcon:tde,Command:sde,CommandIcon:sde,Compass:c9,CompassIcon:c9,Component:nde,ComponentIcon:nde,Computer:rde,ComputerIcon:rde,ConciergeBell:ade,ConciergeBellIcon:ade,Cone:ide,ConeIcon:ide,Construction:ode,ConstructionIcon:ode,Contact:dD,Contact2:nL,Contact2Icon:nL,ContactIcon:dD,ContactRound:nL,ContactRoundIcon:nL,Container:lde,ContainerIcon:lde,Contrast:cde,ContrastIcon:cde,Cookie:dde,CookieIcon:dde,CookingPot:ude,CookingPotIcon:ude,Copy:Pa,CopyCheck:hde,CopyCheckIcon:hde,CopyIcon:Pa,CopyMinus:mde,CopyMinusIcon:mde,CopyPlus:pde,CopyPlusIcon:pde,CopySlash:fde,CopySlashIcon:fde,CopyX:gde,CopyXIcon:gde,Copyleft:xde,CopyleftIcon:xde,Copyright:yde,CopyrightIcon:yde,CornerDownLeft:vde,CornerDownLeftIcon:vde,CornerDownRight:bde,CornerDownRightIcon:bde,CornerLeftDown:_de,CornerLeftDownIcon:_de,CornerLeftUp:wde,CornerLeftUpIcon:wde,CornerRightDown:jde,CornerRightDownIcon:jde,CornerRightUp:Nde,CornerRightUpIcon:Nde,CornerUpLeft:kde,CornerUpLeftIcon:kde,CornerUpRight:Sde,CornerUpRightIcon:Sde,Cpu:Cde,CpuIcon:Cde,CreativeCommons:Ade,CreativeCommonsIcon:Ade,CreditCard:U0,CreditCardIcon:U0,Croissant:Tde,CroissantIcon:Tde,Crop:Ede,CropIcon:Ede,Cross:Mde,CrossIcon:Mde,Crosshair:Lde,CrosshairIcon:Lde,Crown:q0,CrownIcon:q0,Cuboid:Pde,CuboidIcon:Pde,CupSoda:Ide,CupSodaIcon:Ide,CurlyBraces:mM,CurlyBracesIcon:mM,Currency:Dde,CurrencyIcon:Dde,Cylinder:Rde,CylinderIcon:Rde,Dam:Ode,DamIcon:Ode,Database:HG,DatabaseBackup:Fde,DatabaseBackupIcon:Fde,DatabaseIcon:HG,DatabaseZap:zde,DatabaseZapIcon:zde,Delete:Bde,DeleteIcon:Bde,Dessert:$de,DessertIcon:$de,Diameter:Ude,DiameterIcon:Ude,Diamond:Hde,DiamondIcon:Hde,DiamondMinus:qde,DiamondMinusIcon:qde,DiamondPercent:rL,DiamondPercentIcon:rL,DiamondPlus:Vde,DiamondPlusIcon:Vde,Dice1:Gde,Dice1Icon:Gde,Dice2:Wde,Dice2Icon:Wde,Dice3:Kde,Dice3Icon:Kde,Dice4:Yde,Dice4Icon:Yde,Dice5:Zde,Dice5Icon:Zde,Dice6:Xde,Dice6Icon:Xde,Dices:Qde,DicesIcon:Qde,Diff:Jde,DiffIcon:Jde,Disc:nue,Disc2:eue,Disc2Icon:eue,Disc3:tue,Disc3Icon:tue,DiscAlbum:sue,DiscAlbumIcon:sue,DiscIcon:nue,Divide:rue,DivideCircle:zM,DivideCircleIcon:zM,DivideIcon:rue,DivideSquare:gP,DivideSquareIcon:gP,Dna:iue,DnaIcon:iue,DnaOff:aue,DnaOffIcon:aue,Dock:oue,DockIcon:oue,Dog:lue,DogIcon:lue,DollarSign:Ed,DollarSignIcon:Ed,Donut:cue,DonutIcon:cue,DoorClosed:due,DoorClosedIcon:due,DoorOpen:h5,DoorOpenIcon:h5,Dot:uue,DotIcon:uue,DotSquare:xP,DotSquareIcon:xP,Download:oi,DownloadCloud:eL,DownloadCloudIcon:eL,DownloadIcon:oi,DraftingCompass:hue,DraftingCompassIcon:hue,Drama:mue,DramaIcon:mue,Dribbble:pue,DribbbleIcon:pue,Drill:fue,DrillIcon:fue,Droplet:gue,DropletIcon:gue,Droplets:K2,DropletsIcon:K2,Drum:xue,DrumIcon:xue,Drumstick:yue,DrumstickIcon:yue,Dumbbell:vue,DumbbellIcon:vue,Ear:_ue,EarIcon:_ue,EarOff:bue,EarOffIcon:bue,Earth:aL,EarthIcon:aL,EarthLock:wue,EarthLockIcon:wue,Eclipse:jue,EclipseIcon:jue,Edit:xp,Edit2:Ww,Edit2Icon:Ww,Edit3:O2,Edit3Icon:O2,EditIcon:xp,Egg:d9,EggFried:Nue,EggFriedIcon:Nue,EggIcon:d9,EggOff:kue,EggOffIcon:kue,Ellipsis:Iy,EllipsisIcon:Iy,EllipsisVertical:Ev,EllipsisVerticalIcon:Ev,Equal:Aue,EqualApproximately:Sue,EqualApproximatelyIcon:Sue,EqualIcon:Aue,EqualNot:Cue,EqualNotIcon:Cue,EqualSquare:yP,EqualSquareIcon:yP,Eraser:Tue,EraserIcon:Tue,EthernetPort:Eue,EthernetPortIcon:Eue,Euro:Mue,EuroIcon:Mue,Expand:Lue,ExpandIcon:Lue,ExternalLink:Tr,ExternalLinkIcon:Tr,Eye:da,EyeClosed:Pue,EyeClosedIcon:Pue,EyeIcon:da,EyeOff:V0,EyeOffIcon:V0,Facebook:Kf,FacebookIcon:Kf,Factory:Iue,FactoryIcon:Iue,Fan:Due,FanIcon:Due,FastForward:Rue,FastForwardIcon:Rue,Feather:Oue,FeatherIcon:Oue,Fence:Fue,FenceIcon:Fue,FerrisWheel:zue,FerrisWheelIcon:zue,Figma:Bue,FigmaIcon:Bue,File:u9,FileArchive:$ue,FileArchiveIcon:$ue,FileAudio:que,FileAudio2:Uue,FileAudio2Icon:Uue,FileAudioIcon:que,FileAxis3D:iL,FileAxis3DIcon:iL,FileAxis3d:iL,FileAxis3dIcon:iL,FileBadge:Hue,FileBadge2:Vue,FileBadge2Icon:Vue,FileBadgeIcon:Hue,FileBarChart:oL,FileBarChart2:lL,FileBarChart2Icon:lL,FileBarChartIcon:oL,FileBox:Gue,FileBoxIcon:Gue,FileChartColumn:lL,FileChartColumnIcon:lL,FileChartColumnIncreasing:oL,FileChartColumnIncreasingIcon:oL,FileChartLine:cL,FileChartLineIcon:cL,FileChartPie:dL,FileChartPieIcon:dL,FileCheck:GG,FileCheck2:Wue,FileCheck2Icon:Wue,FileCheckIcon:GG,FileClock:Kue,FileClockIcon:Kue,FileCode:Zue,FileCode2:Yue,FileCode2Icon:Yue,FileCodeIcon:Zue,FileCog:uL,FileCog2:uL,FileCog2Icon:uL,FileCogIcon:uL,FileDiff:Xue,FileDiffIcon:Xue,FileDigit:Que,FileDigitIcon:Que,FileDown:uD,FileDownIcon:uD,FileEdit:hL,FileEditIcon:hL,FileHeart:Jue,FileHeartIcon:Jue,FileIcon:u9,FileImage:t3,FileImageIcon:t3,FileInput:ehe,FileInputIcon:ehe,FileJson:she,FileJson2:the,FileJson2Icon:the,FileJsonIcon:she,FileKey:rhe,FileKey2:nhe,FileKey2Icon:nhe,FileKeyIcon:rhe,FileLineChart:cL,FileLineChartIcon:cL,FileLock:ihe,FileLock2:ahe,FileLock2Icon:ahe,FileLockIcon:ihe,FileMinus:lhe,FileMinus2:ohe,FileMinus2Icon:ohe,FileMinusIcon:lhe,FileMusic:che,FileMusicIcon:che,FileOutput:dhe,FileOutputIcon:dhe,FilePen:hL,FilePenIcon:hL,FilePenLine:WC,FilePenLineIcon:WC,FilePieChart:dL,FilePieChartIcon:dL,FilePlus:hhe,FilePlus2:uhe,FilePlus2Icon:uhe,FilePlusIcon:hhe,FileQuestion:mhe,FileQuestionIcon:mhe,FileScan:phe,FileScanIcon:phe,FileSearch:ghe,FileSearch2:fhe,FileSearch2Icon:fhe,FileSearchIcon:ghe,FileSignature:WC,FileSignatureIcon:WC,FileSliders:xhe,FileSlidersIcon:xhe,FileSpreadsheet:m5,FileSpreadsheetIcon:m5,FileStack:WG,FileStackIcon:WG,FileSymlink:yhe,FileSymlinkIcon:yhe,FileTerminal:vhe,FileTerminalIcon:vhe,FileText:Wr,FileTextIcon:Wr,FileType:_he,FileType2:bhe,FileType2Icon:bhe,FileTypeIcon:_he,FileUp:whe,FileUpIcon:whe,FileUser:jhe,FileUserIcon:jhe,FileVideo:KG,FileVideo2:Nhe,FileVideo2Icon:Nhe,FileVideoIcon:KG,FileVolume:She,FileVolume2:khe,FileVolume2Icon:khe,FileVolumeIcon:She,FileWarning:Che,FileWarningIcon:Che,FileX:The,FileX2:Ahe,FileX2Icon:Ahe,FileXIcon:The,Files:Ehe,FilesIcon:Ehe,Film:Rh,FilmIcon:Rh,Filter:cj,FilterIcon:cj,FilterX:Mhe,FilterXIcon:Mhe,Fingerprint:Lhe,FingerprintIcon:Lhe,FireExtinguisher:Phe,FireExtinguisherIcon:Phe,Fish:Rhe,FishIcon:Rhe,FishOff:Ihe,FishOffIcon:Ihe,FishSymbol:Dhe,FishSymbolIcon:Dhe,Flag:s3,FlagIcon:s3,FlagOff:Ohe,FlagOffIcon:Ohe,FlagTriangleLeft:Fhe,FlagTriangleLeftIcon:Fhe,FlagTriangleRight:zhe,FlagTriangleRightIcon:zhe,Flame:Cu,FlameIcon:Cu,FlameKindling:Bhe,FlameKindlingIcon:Bhe,Flashlight:Uhe,FlashlightIcon:Uhe,FlashlightOff:$he,FlashlightOffIcon:$he,FlaskConical:ST,FlaskConicalIcon:ST,FlaskConicalOff:qhe,FlaskConicalOffIcon:qhe,FlaskRound:Vhe,FlaskRoundIcon:Vhe,FlipHorizontal:YG,FlipHorizontal2:Hhe,FlipHorizontal2Icon:Hhe,FlipHorizontalIcon:YG,FlipVertical:Whe,FlipVertical2:Ghe,FlipVertical2Icon:Ghe,FlipVerticalIcon:Whe,Flower:Khe,Flower2:U2,Flower2Icon:U2,FlowerIcon:Khe,Focus:Yhe,FocusIcon:Yhe,FoldHorizontal:Zhe,FoldHorizontalIcon:Zhe,FoldVertical:Xhe,FoldVerticalIcon:Xhe,Folder:Nme,FolderArchive:Qhe,FolderArchiveIcon:Qhe,FolderCheck:Jhe,FolderCheckIcon:Jhe,FolderClock:eme,FolderClockIcon:eme,FolderClosed:tme,FolderClosedIcon:tme,FolderCode:sme,FolderCodeIcon:sme,FolderCog:mL,FolderCog2:mL,FolderCog2Icon:mL,FolderCogIcon:mL,FolderDot:nme,FolderDotIcon:nme,FolderDown:rme,FolderDownIcon:rme,FolderEdit:pL,FolderEditIcon:pL,FolderGit:ime,FolderGit2:ame,FolderGit2Icon:ame,FolderGitIcon:ime,FolderHeart:ome,FolderHeartIcon:ome,FolderIcon:Nme,FolderInput:lme,FolderInputIcon:lme,FolderKanban:cme,FolderKanbanIcon:cme,FolderKey:dme,FolderKeyIcon:dme,FolderLock:ume,FolderLockIcon:ume,FolderMinus:hme,FolderMinusIcon:hme,FolderOpen:H0,FolderOpenDot:mme,FolderOpenDotIcon:mme,FolderOpenIcon:H0,FolderOutput:pme,FolderOutputIcon:pme,FolderPen:pL,FolderPenIcon:pL,FolderPlus:fme,FolderPlusIcon:fme,FolderRoot:gme,FolderRootIcon:gme,FolderSearch:yme,FolderSearch2:xme,FolderSearch2Icon:xme,FolderSearchIcon:yme,FolderSymlink:vme,FolderSymlinkIcon:vme,FolderSync:bme,FolderSyncIcon:bme,FolderTree:_me,FolderTreeIcon:_me,FolderUp:wme,FolderUpIcon:wme,FolderX:jme,FolderXIcon:jme,Folders:kme,FoldersIcon:kme,Footprints:Sme,FootprintsIcon:Sme,ForkKnife:sI,ForkKnifeCrossed:tI,ForkKnifeCrossedIcon:tI,ForkKnifeIcon:sI,Forklift:Cme,ForkliftIcon:Cme,FormInput:FL,FormInputIcon:FL,Forward:Ame,ForwardIcon:Ame,Frame:Tme,FrameIcon:Tme,Framer:Eme,FramerIcon:Eme,Frown:Mme,FrownIcon:Mme,Fuel:Lme,FuelIcon:Lme,Fullscreen:Pme,FullscreenIcon:Pme,FunctionSquare:vP,FunctionSquareIcon:vP,GalleryHorizontal:Dme,GalleryHorizontalEnd:Ime,GalleryHorizontalEndIcon:Ime,GalleryHorizontalIcon:Dme,GalleryThumbnails:Rme,GalleryThumbnailsIcon:Rme,GalleryVertical:Fme,GalleryVerticalEnd:Ome,GalleryVerticalEndIcon:Ome,GalleryVerticalIcon:Fme,Gamepad:Bme,Gamepad2:zme,Gamepad2Icon:zme,GamepadIcon:Bme,GanttChart:NM,GanttChartIcon:NM,GanttChartSquare:ck,GanttChartSquareIcon:ck,Gauge:$me,GaugeCircle:BM,GaugeCircleIcon:BM,GaugeIcon:$me,Gavel:Ume,GavelIcon:Ume,Gem:qme,GemIcon:qme,Ghost:hD,GhostIcon:hD,Gift:Io,GiftIcon:Io,GitBranch:Hme,GitBranchIcon:Hme,GitBranchPlus:Vme,GitBranchPlusIcon:Vme,GitCommit:fL,GitCommitHorizontal:fL,GitCommitHorizontalIcon:fL,GitCommitIcon:fL,GitCommitVertical:Gme,GitCommitVerticalIcon:Gme,GitCompare:Kme,GitCompareArrows:Wme,GitCompareArrowsIcon:Wme,GitCompareIcon:Kme,GitFork:Yme,GitForkIcon:Yme,GitGraph:Zme,GitGraphIcon:Zme,GitMerge:Xme,GitMergeIcon:Xme,GitPullRequest:npe,GitPullRequestArrow:Qme,GitPullRequestArrowIcon:Qme,GitPullRequestClosed:Jme,GitPullRequestClosedIcon:Jme,GitPullRequestCreate:tpe,GitPullRequestCreateArrow:epe,GitPullRequestCreateArrowIcon:epe,GitPullRequestCreateIcon:tpe,GitPullRequestDraft:spe,GitPullRequestDraftIcon:spe,GitPullRequestIcon:npe,Github:rpe,GithubIcon:rpe,Gitlab:ape,GitlabIcon:ape,GlassWater:ipe,GlassWaterIcon:ipe,Glasses:ope,GlassesIcon:ope,Globe:au,Globe2:aL,Globe2Icon:aL,GlobeIcon:au,GlobeLock:lpe,GlobeLockIcon:lpe,Goal:cpe,GoalIcon:cpe,Grab:dpe,GrabIcon:dpe,GraduationCap:Oh,GraduationCapIcon:Oh,Grape:upe,GrapeIcon:upe,Grid:Iw,Grid2X2:xL,Grid2X2Icon:xL,Grid2X2Plus:gL,Grid2X2PlusIcon:gL,Grid2x2:xL,Grid2x2Check:hpe,Grid2x2CheckIcon:hpe,Grid2x2Icon:xL,Grid2x2Plus:gL,Grid2x2PlusIcon:gL,Grid2x2X:mpe,Grid2x2XIcon:mpe,Grid3X3:Iw,Grid3X3Icon:Iw,Grid3x3:Iw,Grid3x3Icon:Iw,GridIcon:Iw,Grip:fpe,GripHorizontal:ppe,GripHorizontalIcon:ppe,GripIcon:fpe,GripVertical:Mp,GripVerticalIcon:Mp,Group:gpe,GroupIcon:gpe,Guitar:xpe,GuitarIcon:xpe,Ham:ype,HamIcon:ype,Hammer:ZG,HammerIcon:ZG,Hand:XG,HandCoins:vpe,HandCoinsIcon:vpe,HandHeart:mD,HandHeartIcon:mD,HandHelping:R2,HandHelpingIcon:R2,HandIcon:XG,HandMetal:bpe,HandMetalIcon:bpe,HandPlatter:_pe,HandPlatterIcon:_pe,Handshake:Y2,HandshakeIcon:Y2,HardDrive:QG,HardDriveDownload:wpe,HardDriveDownloadIcon:wpe,HardDriveIcon:QG,HardDriveUpload:jpe,HardDriveUploadIcon:jpe,HardHat:Npe,HardHatIcon:Npe,Hash:CT,HashIcon:CT,Haze:kpe,HazeIcon:kpe,HdmiPort:Spe,HdmiPortIcon:Spe,Heading:Epe,Heading1:h9,Heading1Icon:h9,Heading2:m9,Heading2Icon:m9,Heading3:JG,Heading3Icon:JG,Heading4:Cpe,Heading4Icon:Cpe,Heading5:Ape,Heading5Icon:Ape,Heading6:Tpe,Heading6Icon:Tpe,HeadingIcon:Epe,HeadphoneOff:Mpe,HeadphoneOffIcon:Mpe,Headphones:Lpe,HeadphonesIcon:Lpe,Headset:Ppe,HeadsetIcon:Ppe,Heart:co,HeartCrack:Ipe,HeartCrackIcon:Ipe,HeartHandshake:pD,HeartHandshakeIcon:pD,HeartIcon:co,HeartOff:Dpe,HeartOffIcon:Dpe,HeartPulse:Rpe,HeartPulseIcon:Rpe,Heater:Ope,HeaterIcon:Ope,HelpCircle:Uk,HelpCircleIcon:Uk,HelpingHand:R2,HelpingHandIcon:R2,Hexagon:Fpe,HexagonIcon:Fpe,Highlighter:zpe,HighlighterIcon:zpe,History:fD,HistoryIcon:fD,Home:_a,HomeIcon:_a,Hop:$pe,HopIcon:$pe,HopOff:Bpe,HopOffIcon:Bpe,Hospital:Upe,HospitalIcon:Upe,Hotel:qpe,HotelIcon:qpe,Hourglass:Vpe,HourglassIcon:Vpe,House:_a,HouseIcon:_a,HousePlug:Hpe,HousePlugIcon:Hpe,HousePlus:Gpe,HousePlusIcon:Gpe,IceCream:vL,IceCream2:yL,IceCream2Icon:yL,IceCreamBowl:yL,IceCreamBowlIcon:yL,IceCreamCone:vL,IceCreamConeIcon:vL,IceCreamIcon:vL,Icon:J1t,IdCard:Wpe,IdCardIcon:Wpe,Image:pc,ImageDown:Kpe,ImageDownIcon:Kpe,ImageIcon:pc,ImageMinus:Ype,ImageMinusIcon:Ype,ImageOff:Zpe,ImageOffIcon:Zpe,ImagePlay:Xpe,ImagePlayIcon:Xpe,ImagePlus:Gv,ImagePlusIcon:Gv,ImageUp:Qpe,ImageUpIcon:Qpe,ImageUpscale:Jpe,ImageUpscaleIcon:Jpe,Images:efe,ImagesIcon:efe,Import:tfe,ImportIcon:tfe,Inbox:n3,InboxIcon:n3,Indent:_L,IndentDecrease:bL,IndentDecreaseIcon:bL,IndentIcon:_L,IndentIncrease:_L,IndentIncreaseIcon:_L,IndianRupee:sfe,IndianRupeeIcon:sfe,Infinity:nfe,InfinityIcon:nfe,Info:p5,InfoIcon:p5,Inspect:kP,InspectIcon:kP,InspectionPanel:rfe,InspectionPanelIcon:rfe,Instagram:dm,InstagramIcon:dm,Italic:AT,ItalicIcon:AT,IterationCcw:afe,IterationCcwIcon:afe,IterationCw:ife,IterationCwIcon:ife,JapaneseYen:ofe,JapaneseYenIcon:ofe,Joystick:lfe,JoystickIcon:lfe,Kanban:r3,KanbanIcon:r3,KanbanSquare:bP,KanbanSquareDashed:mP,KanbanSquareDashedIcon:mP,KanbanSquareIcon:bP,Key:nb,KeyIcon:nb,KeyRound:TT,KeyRoundIcon:TT,KeySquare:cfe,KeySquareIcon:cfe,Keyboard:hfe,KeyboardIcon:hfe,KeyboardMusic:dfe,KeyboardMusicIcon:dfe,KeyboardOff:ufe,KeyboardOffIcon:ufe,Lamp:yfe,LampCeiling:mfe,LampCeilingIcon:mfe,LampDesk:pfe,LampDeskIcon:pfe,LampFloor:ffe,LampFloorIcon:ffe,LampIcon:yfe,LampWallDown:gfe,LampWallDownIcon:gfe,LampWallUp:xfe,LampWallUpIcon:xfe,LandPlot:vfe,LandPlotIcon:vfe,Landmark:eW,LandmarkIcon:eW,Languages:bfe,LanguagesIcon:bfe,Laptop:wfe,Laptop2:wL,Laptop2Icon:wL,LaptopIcon:wfe,LaptopMinimal:wL,LaptopMinimalCheck:_fe,LaptopMinimalCheckIcon:_fe,LaptopMinimalIcon:wL,Lasso:Nfe,LassoIcon:Nfe,LassoSelect:jfe,LassoSelectIcon:jfe,Laugh:kfe,LaughIcon:kfe,Layers:tW,Layers2:Sfe,Layers2Icon:Sfe,Layers3:Cfe,Layers3Icon:Cfe,LayersIcon:tW,Layout:c4,LayoutDashboard:ET,LayoutDashboardIcon:ET,LayoutGrid:G0,LayoutGridIcon:G0,LayoutIcon:c4,LayoutList:Afe,LayoutListIcon:Afe,LayoutPanelLeft:Tfe,LayoutPanelLeftIcon:Tfe,LayoutPanelTop:Efe,LayoutPanelTopIcon:Efe,LayoutTemplate:a3,LayoutTemplateIcon:a3,Leaf:Mfe,LeafIcon:Mfe,LeafyGreen:Lfe,LeafyGreenIcon:Lfe,Lectern:Pfe,LecternIcon:Pfe,LetterText:Ife,LetterTextIcon:Ife,Library:rb,LibraryBig:Dfe,LibraryBigIcon:Dfe,LibraryIcon:rb,LibrarySquare:_P,LibrarySquareIcon:_P,LifeBuoy:p9,LifeBuoyIcon:p9,Ligature:Rfe,LigatureIcon:Rfe,Lightbulb:Z2,LightbulbIcon:Z2,LightbulbOff:Ofe,LightbulbOffIcon:Ofe,LineChart:_M,LineChartIcon:_M,Link:gc,Link2:cd,Link2Icon:cd,Link2Off:Ffe,Link2OffIcon:Ffe,LinkIcon:gc,Linkedin:W0,LinkedinIcon:W0,List:Kx,ListCheck:zfe,ListCheckIcon:zfe,ListChecks:zm,ListChecksIcon:zm,ListCollapse:Bfe,ListCollapseIcon:Bfe,ListEnd:$fe,ListEndIcon:$fe,ListFilter:sW,ListFilterIcon:sW,ListIcon:Kx,ListMinus:Ufe,ListMinusIcon:Ufe,ListMusic:qfe,ListMusicIcon:qfe,ListOrdered:dj,ListOrderedIcon:dj,ListPlus:Vfe,ListPlusIcon:Vfe,ListRestart:Hfe,ListRestartIcon:Hfe,ListStart:Gfe,ListStartIcon:Gfe,ListTodo:Wfe,ListTodoIcon:Wfe,ListTree:Kfe,ListTreeIcon:Kfe,ListVideo:Yfe,ListVideoIcon:Yfe,ListX:Zfe,ListXIcon:Zfe,Loader:Qfe,Loader2:us,Loader2Icon:us,LoaderCircle:us,LoaderCircleIcon:us,LoaderIcon:Qfe,LoaderPinwheel:Xfe,LoaderPinwheelIcon:Xfe,Locate:f9,LocateFixed:Jfe,LocateFixedIcon:Jfe,LocateIcon:f9,LocateOff:ege,LocateOffIcon:ege,Lock:Au,LockIcon:Au,LockKeyhole:tge,LockKeyholeIcon:tge,LockKeyholeOpen:jL,LockKeyholeOpenIcon:jL,LockOpen:NL,LockOpenIcon:NL,LogIn:gD,LogInIcon:gD,LogOut:xD,LogOutIcon:xD,Logs:sge,LogsIcon:sge,Lollipop:nge,LollipopIcon:nge,LucideAArrowDown:Sre,LucideAArrowUp:Cre,LucideALargeSmall:Are,LucideAccessibility:Tre,LucideActivity:gg,LucideActivitySquare:GL,LucideAirVent:Ere,LucideAirplay:Mre,LucideAlarmCheck:J6,LucideAlarmClock:Pre,LucideAlarmClockCheck:J6,LucideAlarmClockMinus:eM,LucideAlarmClockOff:Lre,LucideAlarmClockPlus:tM,LucideAlarmMinus:eM,LucideAlarmPlus:tM,LucideAlarmSmoke:Ire,LucideAlbum:Dre,LucideAlertCircle:Uo,LucideAlertOctagon:qk,LucideAlertTriangle:xd,LucideAlignCenter:sD,LucideAlignCenterHorizontal:Rre,LucideAlignCenterVertical:Ore,LucideAlignEndHorizontal:Fre,LucideAlignEndVertical:zre,LucideAlignHorizontalDistributeCenter:Bre,LucideAlignHorizontalDistributeEnd:$re,LucideAlignHorizontalDistributeStart:Ure,LucideAlignHorizontalJustifyCenter:qre,LucideAlignHorizontalJustifyEnd:Vre,LucideAlignHorizontalJustifyStart:Hre,LucideAlignHorizontalSpaceAround:Gre,LucideAlignHorizontalSpaceBetween:Wre,LucideAlignJustify:Kre,LucideAlignLeft:nD,LucideAlignRight:rD,LucideAlignStartHorizontal:Yre,LucideAlignStartVertical:Zre,LucideAlignVerticalDistributeCenter:Xre,LucideAlignVerticalDistributeEnd:Qre,LucideAlignVerticalDistributeStart:Jre,LucideAlignVerticalJustifyCenter:eae,LucideAlignVerticalJustifyEnd:tae,LucideAlignVerticalJustifyStart:sae,LucideAlignVerticalSpaceAround:nae,LucideAlignVerticalSpaceBetween:rae,LucideAmbulance:aae,LucideAmpersand:iae,LucideAmpersands:oae,LucideAmphora:lae,LucideAnchor:cae,LucideAngry:dae,LucideAnnoyed:uae,LucideAntenna:hae,LucideAnvil:mae,LucideAperture:pae,LucideAppWindow:gae,LucideAppWindowMac:fae,LucideApple:xae,LucideArchive:xg,LucideArchiveRestore:a9,LucideArchiveX:yae,LucideAreaChart:fM,LucideArmchair:vae,LucideArrowBigDown:_ae,LucideArrowBigDownDash:bae,LucideArrowBigLeft:jae,LucideArrowBigLeftDash:wae,LucideArrowBigRight:kae,LucideArrowBigRightDash:Nae,LucideArrowBigUp:Cae,LucideArrowBigUpDash:Sae,LucideArrowDown:Wf,LucideArrowDown01:Aae,LucideArrowDown10:Tae,LucideArrowDownAZ:sM,LucideArrowDownAz:sM,LucideArrowDownCircle:CM,LucideArrowDownFromLine:Eae,LucideArrowDownLeft:Mae,LucideArrowDownLeftFromCircle:TM,LucideArrowDownLeftFromSquare:XL,LucideArrowDownLeftSquare:WL,LucideArrowDownNarrowWide:Lae,LucideArrowDownRight:OG,LucideArrowDownRightFromCircle:EM,LucideArrowDownRightFromSquare:QL,LucideArrowDownRightSquare:KL,LucideArrowDownSquare:YL,LucideArrowDownToDot:Pae,LucideArrowDownToLine:Iae,LucideArrowDownUp:Dae,LucideArrowDownWideNarrow:nM,LucideArrowDownZA:rM,LucideArrowDownZa:rM,LucideArrowLeft:ka,LucideArrowLeftCircle:AM,LucideArrowLeftFromLine:Rae,LucideArrowLeftRight:Oae,LucideArrowLeftSquare:ZL,LucideArrowLeftToLine:Fae,LucideArrowRight:vi,LucideArrowRightCircle:PM,LucideArrowRightFromLine:zae,LucideArrowRightLeft:c5,LucideArrowRightSquare:tP,LucideArrowRightToLine:Bae,LucideArrowUp:Om,LucideArrowUp01:$ae,LucideArrowUp10:Uae,LucideArrowUpAZ:aM,LucideArrowUpAz:aM,LucideArrowUpCircle:IM,LucideArrowUpDown:mg,LucideArrowUpFromDot:qae,LucideArrowUpFromLine:Vae,LucideArrowUpLeft:Hae,LucideArrowUpLeftFromCircle:MM,LucideArrowUpLeftFromSquare:JL,LucideArrowUpLeftSquare:sP,LucideArrowUpNarrowWide:iM,LucideArrowUpRight:i9,LucideArrowUpRightFromCircle:LM,LucideArrowUpRightFromSquare:eP,LucideArrowUpRightSquare:nP,LucideArrowUpSquare:rP,LucideArrowUpToLine:Gae,LucideArrowUpWideNarrow:Wae,LucideArrowUpZA:oM,LucideArrowUpZa:oM,LucideArrowsUpFromLine:Kae,LucideAsterisk:Yae,LucideAsteriskSquare:aP,LucideAtSign:Zae,LucideAtom:Xae,LucideAudioLines:Qae,LucideAudioWaveform:Jae,LucideAward:ku,LucideAxe:eie,LucideAxis3D:lM,LucideAxis3d:lM,LucideBaby:tie,LucideBackpack:sie,LucideBadge:yie,LucideBadgeAlert:nie,LucideBadgeCent:rie,LucideBadgeCheck:cM,LucideBadgeDollarSign:aie,LucideBadgeEuro:iie,LucideBadgeHelp:oie,LucideBadgeIndianRupee:lie,LucideBadgeInfo:cie,LucideBadgeJapaneseYen:die,LucideBadgeMinus:uie,LucideBadgePercent:hie,LucideBadgePlus:mie,LucideBadgePoundSterling:pie,LucideBadgeRussianRuble:fie,LucideBadgeSwissFranc:gie,LucideBadgeX:xie,LucideBaggageClaim:vie,LucideBan:o9,LucideBanana:bie,LucideBandage:_ie,LucideBanknote:wie,LucideBarChart:wM,LucideBarChart2:jM,LucideBarChart3:fl,LucideBarChart4:bM,LucideBarChartBig:vM,LucideBarChartHorizontal:xM,LucideBarChartHorizontalBig:gM,LucideBarcode:jie,LucideBaseline:Nie,LucideBath:Wx,LucideBattery:Eie,LucideBatteryCharging:kie,LucideBatteryFull:Sie,LucideBatteryLow:Cie,LucideBatteryMedium:Aie,LucideBatteryWarning:Tie,LucideBeaker:FG,LucideBean:Lie,LucideBeanOff:Mie,LucideBed:A_,LucideBedDouble:J4,LucideBedSingle:Pie,LucideBeef:Iie,LucideBeer:Rie,LucideBeerOff:Die,LucideBell:yg,LucideBellDot:Oie,LucideBellElectric:Fie,LucideBellMinus:zie,LucideBellOff:d5,LucideBellPlus:Bie,LucideBellRing:wT,LucideBetweenHorizonalEnd:dM,LucideBetweenHorizonalStart:uM,LucideBetweenHorizontalEnd:dM,LucideBetweenHorizontalStart:uM,LucideBetweenVerticalEnd:$ie,LucideBetweenVerticalStart:Uie,LucideBicepsFlexed:qie,LucideBike:Vie,LucideBinary:Hie,LucideBinoculars:Gie,LucideBiohazard:Wie,LucideBird:Kie,LucideBitcoin:Yie,LucideBlend:Zie,LucideBlinds:Xie,LucideBlocks:Qie,LucideBluetooth:soe,LucideBluetoothConnected:Jie,LucideBluetoothOff:eoe,LucideBluetoothSearching:toe,LucideBold:jT,LucideBolt:noe,LucideBomb:roe,LucideBone:aoe,LucideBook:Coe,LucideBookA:ioe,LucideBookAudio:ooe,LucideBookCheck:loe,LucideBookCopy:coe,LucideBookDashed:hM,LucideBookDown:doe,LucideBookHeadphones:uoe,LucideBookHeart:hoe,LucideBookImage:moe,LucideBookKey:poe,LucideBookLock:foe,LucideBookMarked:goe,LucideBookMinus:xoe,LucideBookOpen:Ep,LucideBookOpenCheck:yoe,LucideBookOpenText:voe,LucideBookPlus:boe,LucideBookTemplate:hM,LucideBookText:_oe,LucideBookType:woe,LucideBookUp:Noe,LucideBookUp2:joe,LucideBookUser:koe,LucideBookX:Soe,LucideBookmark:Hv,LucideBookmarkCheck:Aoe,LucideBookmarkMinus:Toe,LucideBookmarkPlus:aD,LucideBookmarkX:Eoe,LucideBoomBox:Moe,LucideBot:NT,LucideBotMessageSquare:Loe,LucideBotOff:Poe,LucideBox:zG,LucideBoxSelect:fP,LucideBoxes:Ioe,LucideBraces:mM,LucideBrackets:Doe,LucideBrain:BG,LucideBrainCircuit:Roe,LucideBrainCog:Ooe,LucideBrickWall:Foe,LucideBriefcase:vg,LucideBriefcaseBusiness:zoe,LucideBriefcaseConveyorBelt:Boe,LucideBriefcaseMedical:$oe,LucideBringToFront:Uoe,LucideBrush:qoe,LucideBug:Goe,LucideBugOff:Voe,LucideBugPlay:Hoe,LucideBuilding:iD,LucideBuilding2:Ti,LucideBus:Koe,LucideBusFront:Woe,LucideCable:Zoe,LucideCableCar:Yoe,LucideCake:Fm,LucideCakeSlice:Xoe,LucideCalculator:u5,LucideCalendar:ta,LucideCalendar1:Qoe,LucideCalendarArrowDown:Joe,LucideCalendarArrowUp:ele,LucideCalendarCheck:kT,LucideCalendarCheck2:tle,LucideCalendarClock:df,LucideCalendarCog:sle,LucideCalendarDays:ld,LucideCalendarFold:nle,LucideCalendarHeart:W2,LucideCalendarMinus:ale,LucideCalendarMinus2:rle,LucideCalendarOff:$G,LucideCalendarPlus:Pv,LucideCalendarPlus2:ile,LucideCalendarRange:ole,LucideCalendarSearch:lle,LucideCalendarSync:cle,LucideCalendarX:UG,LucideCalendarX2:dle,LucideCamera:$0,LucideCameraOff:ule,LucideCandlestickChart:yM,LucideCandy:ple,LucideCandyCane:hle,LucideCandyOff:mle,LucideCannabis:fle,LucideCaptions:pM,LucideCaptionsOff:gle,LucideCar:vle,LucideCarFront:xle,LucideCarTaxiFront:yle,LucideCaravan:ble,LucideCarrot:_le,LucideCaseLower:wle,LucideCaseSensitive:jle,LucideCaseUpper:Nle,LucideCassetteTape:kle,LucideCast:Sle,LucideCastle:Cle,LucideCat:Ale,LucideCctv:Tle,LucideChartArea:fM,LucideChartBar:xM,LucideChartBarBig:gM,LucideChartBarDecreasing:Ele,LucideChartBarIncreasing:Mle,LucideChartBarStacked:Lle,LucideChartCandlestick:yM,LucideChartColumn:fl,LucideChartColumnBig:vM,LucideChartColumnDecreasing:Ple,LucideChartColumnIncreasing:bM,LucideChartColumnStacked:Ile,LucideChartGantt:Dle,LucideChartLine:_M,LucideChartNetwork:Rle,LucideChartNoAxesColumn:jM,LucideChartNoAxesColumnDecreasing:Ole,LucideChartNoAxesColumnIncreasing:wM,LucideChartNoAxesCombined:Fle,LucideChartNoAxesGantt:NM,LucideChartPie:kM,LucideChartScatter:SM,LucideChartSpline:zle,LucideCheck:pa,LucideCheckCheck:oD,LucideCheckCircle:Po,LucideCheckCircle2:Hr,LucideCheckSquare:d4,LucideCheckSquare2:oP,LucideChefHat:Ble,LucideCherry:$le,LucideChevronDown:Xo,LucideChevronDownCircle:DM,LucideChevronDownSquare:lP,LucideChevronFirst:Ule,LucideChevronLast:qle,LucideChevronLeft:Fc,LucideChevronLeftCircle:RM,LucideChevronLeftSquare:cP,LucideChevronRight:Qa,LucideChevronRightCircle:OM,LucideChevronRightSquare:dP,LucideChevronUp:zy,LucideChevronUpCircle:FM,LucideChevronUpSquare:uP,LucideChevronsDown:Hle,LucideChevronsDownUp:Vle,LucideChevronsLeft:Kle,LucideChevronsLeftRight:Wle,LucideChevronsLeftRightEllipsis:Gle,LucideChevronsRight:Zle,LucideChevronsRightLeft:Yle,LucideChevronsUp:Xle,LucideChevronsUpDown:sb,LucideChrome:lD,LucideChurch:Qle,LucideCigarette:ece,LucideCigaretteOff:Jle,LucideCircle:bg,LucideCircleAlert:Uo,LucideCircleArrowDown:CM,LucideCircleArrowLeft:AM,LucideCircleArrowOutDownLeft:TM,LucideCircleArrowOutDownRight:EM,LucideCircleArrowOutUpLeft:MM,LucideCircleArrowOutUpRight:LM,LucideCircleArrowRight:PM,LucideCircleArrowUp:IM,LucideCircleCheck:Hr,LucideCircleCheckBig:Po,LucideCircleChevronDown:DM,LucideCircleChevronLeft:RM,LucideCircleChevronRight:OM,LucideCircleChevronUp:FM,LucideCircleDashed:tce,LucideCircleDivide:zM,LucideCircleDollarSign:sce,LucideCircleDot:rce,LucideCircleDotDashed:nce,LucideCircleEllipsis:ace,LucideCircleEqual:ice,LucideCircleFadingArrowUp:oce,LucideCircleFadingPlus:lce,LucideCircleGauge:BM,LucideCircleHelp:Uk,LucideCircleMinus:$M,LucideCircleOff:cce,LucideCircleParking:qM,LucideCircleParkingOff:UM,LucideCirclePause:VM,LucideCirclePercent:HM,LucideCirclePlay:wp,LucideCirclePlus:GM,LucideCirclePower:WM,LucideCircleSlash:dce,LucideCircleSlash2:KM,LucideCircleSlashed:KM,LucideCircleStop:YM,LucideCircleUser:XM,LucideCircleUserRound:ZM,LucideCircleX:Nu,LucideCircuitBoard:uce,LucideCitrus:hce,LucideClapperboard:l9,LucideClipboard:vce,LucideClipboardCheck:e3,LucideClipboardCopy:mce,LucideClipboardEdit:JM,LucideClipboardList:lj,LucideClipboardMinus:pce,LucideClipboardPaste:fce,LucideClipboardPen:JM,LucideClipboardPenLine:QM,LucideClipboardPlus:gce,LucideClipboardSignature:QM,LucideClipboardType:xce,LucideClipboardX:yce,LucideClock:Xr,LucideClock1:bce,LucideClock10:_ce,LucideClock11:wce,LucideClock12:jce,LucideClock2:Nce,LucideClock3:qG,LucideClock4:kce,LucideClock5:Sce,LucideClock6:Cce,LucideClock7:Ace,LucideClock8:Tce,LucideClock9:Ece,LucideClockAlert:Mce,LucideClockArrowDown:Lce,LucideClockArrowUp:Pce,LucideCloud:Kce,LucideCloudAlert:Ice,LucideCloudCog:Dce,LucideCloudDownload:eL,LucideCloudDrizzle:Rce,LucideCloudFog:Oce,LucideCloudHail:Fce,LucideCloudLightning:zce,LucideCloudMoon:$ce,LucideCloudMoonRain:Bce,LucideCloudOff:Uce,LucideCloudRain:Vce,LucideCloudRainWind:qce,LucideCloudSnow:Hce,LucideCloudSun:Wce,LucideCloudSunRain:Gce,LucideCloudUpload:tL,LucideCloudy:Yce,LucideClover:V4,LucideClub:Zce,LucideCode:cD,LucideCode2:l4,LucideCodeSquare:hP,LucideCodeXml:l4,LucideCodepen:Xce,LucideCodesandbox:Qce,LucideCoffee:T_,LucideCog:Jce,LucideCoins:VG,LucideColumns:sL,LucideColumns2:sL,LucideColumns3:GC,LucideColumns4:ede,LucideCombine:tde,LucideCommand:sde,LucideCompass:c9,LucideComponent:nde,LucideComputer:rde,LucideConciergeBell:ade,LucideCone:ide,LucideConstruction:ode,LucideContact:dD,LucideContact2:nL,LucideContactRound:nL,LucideContainer:lde,LucideContrast:cde,LucideCookie:dde,LucideCookingPot:ude,LucideCopy:Pa,LucideCopyCheck:hde,LucideCopyMinus:mde,LucideCopyPlus:pde,LucideCopySlash:fde,LucideCopyX:gde,LucideCopyleft:xde,LucideCopyright:yde,LucideCornerDownLeft:vde,LucideCornerDownRight:bde,LucideCornerLeftDown:_de,LucideCornerLeftUp:wde,LucideCornerRightDown:jde,LucideCornerRightUp:Nde,LucideCornerUpLeft:kde,LucideCornerUpRight:Sde,LucideCpu:Cde,LucideCreativeCommons:Ade,LucideCreditCard:U0,LucideCroissant:Tde,LucideCrop:Ede,LucideCross:Mde,LucideCrosshair:Lde,LucideCrown:q0,LucideCuboid:Pde,LucideCupSoda:Ide,LucideCurlyBraces:mM,LucideCurrency:Dde,LucideCylinder:Rde,LucideDam:Ode,LucideDatabase:HG,LucideDatabaseBackup:Fde,LucideDatabaseZap:zde,LucideDelete:Bde,LucideDessert:$de,LucideDiameter:Ude,LucideDiamond:Hde,LucideDiamondMinus:qde,LucideDiamondPercent:rL,LucideDiamondPlus:Vde,LucideDice1:Gde,LucideDice2:Wde,LucideDice3:Kde,LucideDice4:Yde,LucideDice5:Zde,LucideDice6:Xde,LucideDices:Qde,LucideDiff:Jde,LucideDisc:nue,LucideDisc2:eue,LucideDisc3:tue,LucideDiscAlbum:sue,LucideDivide:rue,LucideDivideCircle:zM,LucideDivideSquare:gP,LucideDna:iue,LucideDnaOff:aue,LucideDock:oue,LucideDog:lue,LucideDollarSign:Ed,LucideDonut:cue,LucideDoorClosed:due,LucideDoorOpen:h5,LucideDot:uue,LucideDotSquare:xP,LucideDownload:oi,LucideDownloadCloud:eL,LucideDraftingCompass:hue,LucideDrama:mue,LucideDribbble:pue,LucideDrill:fue,LucideDroplet:gue,LucideDroplets:K2,LucideDrum:xue,LucideDrumstick:yue,LucideDumbbell:vue,LucideEar:_ue,LucideEarOff:bue,LucideEarth:aL,LucideEarthLock:wue,LucideEclipse:jue,LucideEdit:xp,LucideEdit2:Ww,LucideEdit3:O2,LucideEgg:d9,LucideEggFried:Nue,LucideEggOff:kue,LucideEllipsis:Iy,LucideEllipsisVertical:Ev,LucideEqual:Aue,LucideEqualApproximately:Sue,LucideEqualNot:Cue,LucideEqualSquare:yP,LucideEraser:Tue,LucideEthernetPort:Eue,LucideEuro:Mue,LucideExpand:Lue,LucideExternalLink:Tr,LucideEye:da,LucideEyeClosed:Pue,LucideEyeOff:V0,LucideFacebook:Kf,LucideFactory:Iue,LucideFan:Due,LucideFastForward:Rue,LucideFeather:Oue,LucideFence:Fue,LucideFerrisWheel:zue,LucideFigma:Bue,LucideFile:u9,LucideFileArchive:$ue,LucideFileAudio:que,LucideFileAudio2:Uue,LucideFileAxis3D:iL,LucideFileAxis3d:iL,LucideFileBadge:Hue,LucideFileBadge2:Vue,LucideFileBarChart:oL,LucideFileBarChart2:lL,LucideFileBox:Gue,LucideFileChartColumn:lL,LucideFileChartColumnIncreasing:oL,LucideFileChartLine:cL,LucideFileChartPie:dL,LucideFileCheck:GG,LucideFileCheck2:Wue,LucideFileClock:Kue,LucideFileCode:Zue,LucideFileCode2:Yue,LucideFileCog:uL,LucideFileCog2:uL,LucideFileDiff:Xue,LucideFileDigit:Que,LucideFileDown:uD,LucideFileEdit:hL,LucideFileHeart:Jue,LucideFileImage:t3,LucideFileInput:ehe,LucideFileJson:she,LucideFileJson2:the,LucideFileKey:rhe,LucideFileKey2:nhe,LucideFileLineChart:cL,LucideFileLock:ihe,LucideFileLock2:ahe,LucideFileMinus:lhe,LucideFileMinus2:ohe,LucideFileMusic:che,LucideFileOutput:dhe,LucideFilePen:hL,LucideFilePenLine:WC,LucideFilePieChart:dL,LucideFilePlus:hhe,LucideFilePlus2:uhe,LucideFileQuestion:mhe,LucideFileScan:phe,LucideFileSearch:ghe,LucideFileSearch2:fhe,LucideFileSignature:WC,LucideFileSliders:xhe,LucideFileSpreadsheet:m5,LucideFileStack:WG,LucideFileSymlink:yhe,LucideFileTerminal:vhe,LucideFileText:Wr,LucideFileType:_he,LucideFileType2:bhe,LucideFileUp:whe,LucideFileUser:jhe,LucideFileVideo:KG,LucideFileVideo2:Nhe,LucideFileVolume:She,LucideFileVolume2:khe,LucideFileWarning:Che,LucideFileX:The,LucideFileX2:Ahe,LucideFiles:Ehe,LucideFilm:Rh,LucideFilter:cj,LucideFilterX:Mhe,LucideFingerprint:Lhe,LucideFireExtinguisher:Phe,LucideFish:Rhe,LucideFishOff:Ihe,LucideFishSymbol:Dhe,LucideFlag:s3,LucideFlagOff:Ohe,LucideFlagTriangleLeft:Fhe,LucideFlagTriangleRight:zhe,LucideFlame:Cu,LucideFlameKindling:Bhe,LucideFlashlight:Uhe,LucideFlashlightOff:$he,LucideFlaskConical:ST,LucideFlaskConicalOff:qhe,LucideFlaskRound:Vhe,LucideFlipHorizontal:YG,LucideFlipHorizontal2:Hhe,LucideFlipVertical:Whe,LucideFlipVertical2:Ghe,LucideFlower:Khe,LucideFlower2:U2,LucideFocus:Yhe,LucideFoldHorizontal:Zhe,LucideFoldVertical:Xhe,LucideFolder:Nme,LucideFolderArchive:Qhe,LucideFolderCheck:Jhe,LucideFolderClock:eme,LucideFolderClosed:tme,LucideFolderCode:sme,LucideFolderCog:mL,LucideFolderCog2:mL,LucideFolderDot:nme,LucideFolderDown:rme,LucideFolderEdit:pL,LucideFolderGit:ime,LucideFolderGit2:ame,LucideFolderHeart:ome,LucideFolderInput:lme,LucideFolderKanban:cme,LucideFolderKey:dme,LucideFolderLock:ume,LucideFolderMinus:hme,LucideFolderOpen:H0,LucideFolderOpenDot:mme,LucideFolderOutput:pme,LucideFolderPen:pL,LucideFolderPlus:fme,LucideFolderRoot:gme,LucideFolderSearch:yme,LucideFolderSearch2:xme,LucideFolderSymlink:vme,LucideFolderSync:bme,LucideFolderTree:_me,LucideFolderUp:wme,LucideFolderX:jme,LucideFolders:kme,LucideFootprints:Sme,LucideForkKnife:sI,LucideForkKnifeCrossed:tI,LucideForklift:Cme,LucideFormInput:FL,LucideForward:Ame,LucideFrame:Tme,LucideFramer:Eme,LucideFrown:Mme,LucideFuel:Lme,LucideFullscreen:Pme,LucideFunctionSquare:vP,LucideGalleryHorizontal:Dme,LucideGalleryHorizontalEnd:Ime,LucideGalleryThumbnails:Rme,LucideGalleryVertical:Fme,LucideGalleryVerticalEnd:Ome,LucideGamepad:Bme,LucideGamepad2:zme,LucideGanttChart:NM,LucideGanttChartSquare:ck,LucideGauge:$me,LucideGaugeCircle:BM,LucideGavel:Ume,LucideGem:qme,LucideGhost:hD,LucideGift:Io,LucideGitBranch:Hme,LucideGitBranchPlus:Vme,LucideGitCommit:fL,LucideGitCommitHorizontal:fL,LucideGitCommitVertical:Gme,LucideGitCompare:Kme,LucideGitCompareArrows:Wme,LucideGitFork:Yme,LucideGitGraph:Zme,LucideGitMerge:Xme,LucideGitPullRequest:npe,LucideGitPullRequestArrow:Qme,LucideGitPullRequestClosed:Jme,LucideGitPullRequestCreate:tpe,LucideGitPullRequestCreateArrow:epe,LucideGitPullRequestDraft:spe,LucideGithub:rpe,LucideGitlab:ape,LucideGlassWater:ipe,LucideGlasses:ope,LucideGlobe:au,LucideGlobe2:aL,LucideGlobeLock:lpe,LucideGoal:cpe,LucideGrab:dpe,LucideGraduationCap:Oh,LucideGrape:upe,LucideGrid:Iw,LucideGrid2X2:xL,LucideGrid2X2Plus:gL,LucideGrid2x2:xL,LucideGrid2x2Check:hpe,LucideGrid2x2Plus:gL,LucideGrid2x2X:mpe,LucideGrid3X3:Iw,LucideGrid3x3:Iw,LucideGrip:fpe,LucideGripHorizontal:ppe,LucideGripVertical:Mp,LucideGroup:gpe,LucideGuitar:xpe,LucideHam:ype,LucideHammer:ZG,LucideHand:XG,LucideHandCoins:vpe,LucideHandHeart:mD,LucideHandHelping:R2,LucideHandMetal:bpe,LucideHandPlatter:_pe,LucideHandshake:Y2,LucideHardDrive:QG,LucideHardDriveDownload:wpe,LucideHardDriveUpload:jpe,LucideHardHat:Npe,LucideHash:CT,LucideHaze:kpe,LucideHdmiPort:Spe,LucideHeading:Epe,LucideHeading1:h9,LucideHeading2:m9,LucideHeading3:JG,LucideHeading4:Cpe,LucideHeading5:Ape,LucideHeading6:Tpe,LucideHeadphoneOff:Mpe,LucideHeadphones:Lpe,LucideHeadset:Ppe,LucideHeart:co,LucideHeartCrack:Ipe,LucideHeartHandshake:pD,LucideHeartOff:Dpe,LucideHeartPulse:Rpe,LucideHeater:Ope,LucideHelpCircle:Uk,LucideHelpingHand:R2,LucideHexagon:Fpe,LucideHighlighter:zpe,LucideHistory:fD,LucideHome:_a,LucideHop:$pe,LucideHopOff:Bpe,LucideHospital:Upe,LucideHotel:qpe,LucideHourglass:Vpe,LucideHouse:_a,LucideHousePlug:Hpe,LucideHousePlus:Gpe,LucideIceCream:vL,LucideIceCream2:yL,LucideIceCreamBowl:yL,LucideIceCreamCone:vL,LucideIdCard:Wpe,LucideImage:pc,LucideImageDown:Kpe,LucideImageMinus:Ype,LucideImageOff:Zpe,LucideImagePlay:Xpe,LucideImagePlus:Gv,LucideImageUp:Qpe,LucideImageUpscale:Jpe,LucideImages:efe,LucideImport:tfe,LucideInbox:n3,LucideIndent:_L,LucideIndentDecrease:bL,LucideIndentIncrease:_L,LucideIndianRupee:sfe,LucideInfinity:nfe,LucideInfo:p5,LucideInspect:kP,LucideInspectionPanel:rfe,LucideInstagram:dm,LucideItalic:AT,LucideIterationCcw:afe,LucideIterationCw:ife,LucideJapaneseYen:ofe,LucideJoystick:lfe,LucideKanban:r3,LucideKanbanSquare:bP,LucideKanbanSquareDashed:mP,LucideKey:nb,LucideKeyRound:TT,LucideKeySquare:cfe,LucideKeyboard:hfe,LucideKeyboardMusic:dfe,LucideKeyboardOff:ufe,LucideLamp:yfe,LucideLampCeiling:mfe,LucideLampDesk:pfe,LucideLampFloor:ffe,LucideLampWallDown:gfe,LucideLampWallUp:xfe,LucideLandPlot:vfe,LucideLandmark:eW,LucideLanguages:bfe,LucideLaptop:wfe,LucideLaptop2:wL,LucideLaptopMinimal:wL,LucideLaptopMinimalCheck:_fe,LucideLasso:Nfe,LucideLassoSelect:jfe,LucideLaugh:kfe,LucideLayers:tW,LucideLayers2:Sfe,LucideLayers3:Cfe,LucideLayout:c4,LucideLayoutDashboard:ET,LucideLayoutGrid:G0,LucideLayoutList:Afe,LucideLayoutPanelLeft:Tfe,LucideLayoutPanelTop:Efe,LucideLayoutTemplate:a3,LucideLeaf:Mfe,LucideLeafyGreen:Lfe,LucideLectern:Pfe,LucideLetterText:Ife,LucideLibrary:rb,LucideLibraryBig:Dfe,LucideLibrarySquare:_P,LucideLifeBuoy:p9,LucideLigature:Rfe,LucideLightbulb:Z2,LucideLightbulbOff:Ofe,LucideLineChart:_M,LucideLink:gc,LucideLink2:cd,LucideLink2Off:Ffe,LucideLinkedin:W0,LucideList:Kx,LucideListCheck:zfe,LucideListChecks:zm,LucideListCollapse:Bfe,LucideListEnd:$fe,LucideListFilter:sW,LucideListMinus:Ufe,LucideListMusic:qfe,LucideListOrdered:dj,LucideListPlus:Vfe,LucideListRestart:Hfe,LucideListStart:Gfe,LucideListTodo:Wfe,LucideListTree:Kfe,LucideListVideo:Yfe,LucideListX:Zfe,LucideLoader:Qfe,LucideLoader2:us,LucideLoaderCircle:us,LucideLoaderPinwheel:Xfe,LucideLocate:f9,LucideLocateFixed:Jfe,LucideLocateOff:ege,LucideLock:Au,LucideLockKeyhole:tge,LucideLockKeyholeOpen:jL,LucideLockOpen:NL,LucideLogIn:gD,LucideLogOut:xD,LucideLogs:sge,LucideLollipop:nge,LucideLuggage:rge,LucideMSquare:wP,LucideMagnet:age,LucideMail:mn,LucideMailCheck:g9,LucideMailMinus:ige,LucideMailOpen:x9,LucideMailPlus:nW,LucideMailQuestion:oge,LucideMailSearch:lge,LucideMailWarning:cge,LucideMailX:y9,LucideMailbox:dge,LucideMails:uge,LucideMap:yD,LucideMapPin:ii,LucideMapPinCheck:mge,LucideMapPinCheckInside:hge,LucideMapPinHouse:pge,LucideMapPinMinus:gge,LucideMapPinMinusInside:fge,LucideMapPinOff:xge,LucideMapPinPlus:vge,LucideMapPinPlusInside:yge,LucideMapPinX:_ge,LucideMapPinXInside:bge,LucideMapPinned:wge,LucideMartini:jge,LucideMaximize:vD,LucideMaximize2:rW,LucideMedal:i3,LucideMegaphone:um,LucideMegaphoneOff:Nge,LucideMeh:kge,LucideMemoryStick:Sge,LucideMenu:MT,LucideMenuSquare:jP,LucideMerge:Cge,LucideMessageCircle:Ud,LucideMessageCircleCode:Age,LucideMessageCircleDashed:Tge,LucideMessageCircleHeart:v9,LucideMessageCircleMore:Ege,LucideMessageCircleOff:Mge,LucideMessageCirclePlus:Lge,LucideMessageCircleQuestion:aW,LucideMessageCircleReply:Pge,LucideMessageCircleWarning:Ige,LucideMessageCircleX:Dge,LucideMessageSquare:xo,LucideMessageSquareCode:Rge,LucideMessageSquareDashed:Oge,LucideMessageSquareDiff:Fge,LucideMessageSquareDot:zge,LucideMessageSquareHeart:b9,LucideMessageSquareLock:Bge,LucideMessageSquareMore:iW,LucideMessageSquareOff:$ge,LucideMessageSquarePlus:Qk,LucideMessageSquareQuote:f5,LucideMessageSquareReply:Uge,LucideMessageSquareShare:qge,LucideMessageSquareText:Vge,LucideMessageSquareWarning:Hge,LucideMessageSquareX:Gge,LucideMessagesSquare:_9,LucideMic:uj,LucideMic2:kL,LucideMicOff:Wge,LucideMicVocal:kL,LucideMicrochip:Kge,LucideMicroscope:Yge,LucideMicrowave:Zge,LucideMilestone:Xge,LucideMilk:Jge,LucideMilkOff:Qge,LucideMinimize:txe,LucideMinimize2:exe,LucideMinus:X2,LucideMinusCircle:$M,LucideMinusSquare:NP,LucideMonitor:hj,LucideMonitorCheck:sxe,LucideMonitorCog:nxe,LucideMonitorDot:rxe,LucideMonitorDown:axe,LucideMonitorOff:ixe,LucideMonitorPause:oxe,LucideMonitorPlay:w9,LucideMonitorSmartphone:lxe,LucideMonitorSpeaker:cxe,LucideMonitorStop:dxe,LucideMonitorUp:bD,LucideMonitorX:uxe,LucideMoon:mxe,LucideMoonStar:hxe,LucideMoreHorizontal:Iy,LucideMoreVertical:Ev,LucideMountain:fxe,LucideMountainSnow:pxe,LucideMouse:vxe,LucideMouseOff:gxe,LucideMousePointer:Qg,LucideMousePointer2:xxe,LucideMousePointerBan:yxe,LucideMousePointerClick:ru,LucideMousePointerSquareDashed:pP,LucideMove:oW,LucideMove3D:SL,LucideMove3d:SL,LucideMoveDiagonal:_xe,LucideMoveDiagonal2:bxe,LucideMoveDown:Nxe,LucideMoveDownLeft:wxe,LucideMoveDownRight:jxe,LucideMoveHorizontal:kxe,LucideMoveLeft:Sxe,LucideMoveRight:Cxe,LucideMoveUp:Exe,LucideMoveUpLeft:Axe,LucideMoveUpRight:Txe,LucideMoveVertical:Mxe,LucideMusic:j9,LucideMusic2:Lxe,LucideMusic3:Pxe,LucideMusic4:Ixe,LucideNavigation:lW,LucideNavigation2:Rxe,LucideNavigation2Off:Dxe,LucideNavigationOff:Oxe,LucideNetwork:Fxe,LucideNewspaper:E_,LucideNfc:zxe,LucideNotebook:qxe,LucideNotebookPen:Bxe,LucideNotebookTabs:$xe,LucideNotebookText:Uxe,LucideNotepadText:Hxe,LucideNotepadTextDashed:Vxe,LucideNut:Wxe,LucideNutOff:Gxe,LucideOctagon:Yxe,LucideOctagonAlert:qk,LucideOctagonMinus:Kxe,LucideOctagonPause:CL,LucideOctagonX:AL,LucideOmega:Zxe,LucideOption:Xxe,LucideOrbit:Qxe,LucideOrigami:Jxe,LucideOutdent:bL,LucidePackage:Ku,LucidePackage2:e0e,LucidePackageCheck:t0e,LucidePackageMinus:s0e,LucidePackageOpen:n0e,LucidePackagePlus:cW,LucidePackageSearch:r0e,LucidePackageX:a0e,LucidePaintBucket:i0e,LucidePaintRoller:o0e,LucidePaintbrush:l0e,LucidePaintbrush2:TL,LucidePaintbrushVertical:TL,LucidePalette:zc,LucidePalmtree:GP,LucidePanelBottom:u0e,LucidePanelBottomClose:c0e,LucidePanelBottomDashed:EL,LucidePanelBottomInactive:EL,LucidePanelBottomOpen:d0e,LucidePanelLeft:IL,LucidePanelLeftClose:ML,LucidePanelLeftDashed:LL,LucidePanelLeftInactive:LL,LucidePanelLeftOpen:PL,LucidePanelRight:p0e,LucidePanelRightClose:h0e,LucidePanelRightDashed:DL,LucidePanelRightInactive:DL,LucidePanelRightOpen:m0e,LucidePanelTop:x0e,LucidePanelTopClose:f0e,LucidePanelTopDashed:RL,LucidePanelTopInactive:RL,LucidePanelTopOpen:g0e,LucidePanelsLeftBottom:y0e,LucidePanelsLeftRight:GC,LucidePanelsRightBottom:v0e,LucidePanelsTopBottom:$L,LucidePanelsTopLeft:c4,LucidePaperclip:LT,LucideParentheses:b0e,LucideParkingCircle:qM,LucideParkingCircleOff:UM,LucideParkingMeter:_0e,LucideParkingSquare:CP,LucideParkingSquareOff:SP,LucidePartyPopper:uf,LucidePause:K0,LucidePauseCircle:VM,LucidePauseOctagon:CL,LucidePawPrint:w0e,LucidePcCase:j0e,LucidePen:Ww,LucidePenBox:xp,LucidePenLine:O2,LucidePenOff:N0e,LucidePenSquare:xp,LucidePenTool:PT,LucidePencil:Ja,LucidePencilLine:N9,LucidePencilOff:k0e,LucidePencilRuler:S0e,LucidePentagon:C0e,LucidePercent:IT,LucidePercentCircle:HM,LucidePercentDiamond:rL,LucidePercentSquare:AP,LucidePersonStanding:A0e,LucidePhilippinePeso:T0e,LucidePhone:ga,LucidePhoneCall:dW,LucidePhoneForwarded:E0e,LucidePhoneIncoming:M0e,LucidePhoneMissed:L0e,LucidePhoneOff:P0e,LucidePhoneOutgoing:I0e,LucidePi:D0e,LucidePiSquare:TP,LucidePiano:R0e,LucidePickaxe:O0e,LucidePictureInPicture:z0e,LucidePictureInPicture2:F0e,LucidePieChart:kM,LucidePiggyBank:B0e,LucidePilcrow:q0e,LucidePilcrowLeft:$0e,LucidePilcrowRight:U0e,LucidePilcrowSquare:EP,LucidePill:H0e,LucidePillBottle:V0e,LucidePin:DT,LucidePinOff:uW,LucidePipette:G0e,LucidePizza:W0e,LucidePlane:hW,LucidePlaneLanding:K0e,LucidePlaneTakeoff:Y0e,LucidePlay:dd,LucidePlayCircle:wp,LucidePlaySquare:MP,LucidePlug:o3,LucidePlug2:Z0e,LucidePlugZap:OL,LucidePlugZap2:OL,LucidePlus:nn,LucidePlusCircle:GM,LucidePlusSquare:LP,LucidePocket:Q0e,LucidePocketKnife:X0e,LucidePodcast:J0e,LucidePointer:tye,LucidePointerOff:eye,LucidePopcorn:sye,LucidePopsicle:nye,LucidePoundSterling:rye,LucidePower:mW,LucidePowerCircle:WM,LucidePowerOff:aye,LucidePowerSquare:PP,LucidePresentation:ab,LucidePrinter:pW,LucidePrinterCheck:iye,LucideProjector:oye,LucideProportions:lye,LucidePuzzle:cye,LucidePyramid:dye,LucideQrCode:M_,LucideQuote:Q2,LucideRabbit:uye,LucideRadar:_D,LucideRadiation:hye,LucideRadical:mye,LucideRadio:Y0,LucideRadioReceiver:pye,LucideRadioTower:fye,LucideRadius:gye,LucideRailSymbol:xye,LucideRainbow:yye,LucideRat:vye,LucideRatio:bye,LucideReceipt:Tye,LucideReceiptCent:_ye,LucideReceiptEuro:wye,LucideReceiptIndianRupee:jye,LucideReceiptJapaneseYen:Nye,LucideReceiptPoundSterling:kye,LucideReceiptRussianRuble:Sye,LucideReceiptSwissFranc:Cye,LucideReceiptText:Aye,LucideRectangleEllipsis:FL,LucideRectangleHorizontal:Eye,LucideRectangleVertical:Mye,LucideRecycle:Lye,LucideRedo:RT,LucideRedo2:Pye,LucideRedoDot:Iye,LucideRefreshCcw:k9,LucideRefreshCcwDot:Dye,LucideRefreshCw:oo,LucideRefreshCwOff:Rye,LucideRefrigerator:Oye,LucideRegex:Fye,LucideRemoveFormatting:zye,LucideRepeat:S9,LucideRepeat1:Bye,LucideRepeat2:$ye,LucideReplace:qye,LucideReplaceAll:Uye,LucideReply:fW,LucideReplyAll:Vye,LucideRewind:Hye,LucideRibbon:Gye,LucideRocket:By,LucideRockingChair:Wye,LucideRollerCoaster:Kye,LucideRotate3D:zL,LucideRotate3d:zL,LucideRotateCcw:hf,LucideRotateCcwSquare:Yye,LucideRotateCw:wD,LucideRotateCwSquare:Zye,LucideRoute:gW,LucideRouteOff:Xye,LucideRouter:Qye,LucideRows:BL,LucideRows2:BL,LucideRows3:$L,LucideRows4:Jye,LucideRss:eve,LucideRuler:l3,LucideRussianRuble:tve,LucideSailboat:sve,LucideSalad:nve,LucideSandwich:rve,LucideSatellite:ive,LucideSatelliteDish:ave,LucideSave:Kl,LucideSaveAll:ove,LucideSaveOff:lve,LucideScale:xW,LucideScale3D:UL,LucideScale3d:UL,LucideScaling:cve,LucideScan:xve,LucideScanBarcode:dve,LucideScanEye:uve,LucideScanFace:hve,LucideScanLine:mve,LucideScanQrCode:pve,LucideScanSearch:fve,LucideScanText:gve,LucideScatterChart:SM,LucideSchool:yve,LucideSchool2:KP,LucideScissors:bve,LucideScissorsLineDashed:vve,LucideScissorsSquare:IP,LucideScissorsSquareDashedBottom:iP,LucideScreenShare:wve,LucideScreenShareOff:_ve,LucideScroll:jve,LucideScrollText:yW,LucideSearch:Gr,LucideSearchCheck:Nve,LucideSearchCode:kve,LucideSearchSlash:Sve,LucideSearchX:vW,LucideSection:Cve,LucideSend:Rr,LucideSendHorizonal:qL,LucideSendHorizontal:qL,LucideSendToBack:Ave,LucideSeparatorHorizontal:Tve,LucideSeparatorVertical:Eve,LucideServer:Ive,LucideServerCog:Mve,LucideServerCrash:Lve,LucideServerOff:Pve,LucideSettings:sc,LucideSettings2:C9,LucideShapes:Dve,LucideShare:bW,LucideShare2:Md,LucideSheet:Rve,LucideShell:Ove,LucideShield:mf,LucideShieldAlert:A9,LucideShieldBan:Fve,LucideShieldCheck:Wv,LucideShieldClose:VL,LucideShieldEllipsis:zve,LucideShieldHalf:Bve,LucideShieldMinus:$ve,LucideShieldOff:jD,LucideShieldPlus:Uve,LucideShieldQuestion:qve,LucideShieldX:VL,LucideShip:Hve,LucideShipWheel:Vve,LucideShirt:Gve,LucideShoppingBag:g5,LucideShoppingBasket:Wve,LucideShoppingCart:W1,LucideShovel:Kve,LucideShowerHead:Yve,LucideShrink:Zve,LucideShrub:Xve,LucideShuffle:ND,LucideSidebar:IL,LucideSidebarClose:ML,LucideSidebarOpen:PL,LucideSigma:Qve,LucideSigmaSquare:DP,LucideSignal:n1e,LucideSignalHigh:Jve,LucideSignalLow:e1e,LucideSignalMedium:t1e,LucideSignalZero:s1e,LucideSignature:r1e,LucideSignpost:i1e,LucideSignpostBig:a1e,LucideSiren:o1e,LucideSkipBack:l1e,LucideSkipForward:c1e,LucideSkull:d1e,LucideSlack:u1e,LucideSlash:h1e,LucideSlashSquare:RP,LucideSlice:m1e,LucideSliders:HL,LucideSlidersHorizontal:OT,LucideSlidersVertical:HL,LucideSmartphone:$y,LucideSmartphoneCharging:p1e,LucideSmartphoneNfc:f1e,LucideSmile:x1e,LucideSmilePlus:g1e,LucideSnail:y1e,LucideSnowflake:nj,LucideSofa:v1e,LucideSortAsc:iM,LucideSortDesc:nM,LucideSoup:b1e,LucideSpace:_1e,LucideSpade:w1e,LucideSparkle:c3,LucideSparkles:Cn,LucideSpeaker:j1e,LucideSpeech:N1e,LucideSpellCheck:S1e,LucideSpellCheck2:k1e,LucideSpline:C1e,LucideSplit:A1e,LucideSplitSquareHorizontal:OP,LucideSplitSquareVertical:FP,LucideSprayCan:T1e,LucideSprout:FT,LucideSquare:L_,LucideSquareActivity:GL,LucideSquareArrowDown:YL,LucideSquareArrowDownLeft:WL,LucideSquareArrowDownRight:KL,LucideSquareArrowLeft:ZL,LucideSquareArrowOutDownLeft:XL,LucideSquareArrowOutDownRight:QL,LucideSquareArrowOutUpLeft:JL,LucideSquareArrowOutUpRight:eP,LucideSquareArrowRight:tP,LucideSquareArrowUp:rP,LucideSquareArrowUpLeft:sP,LucideSquareArrowUpRight:nP,LucideSquareAsterisk:aP,LucideSquareBottomDashedScissors:iP,LucideSquareChartGantt:ck,LucideSquareCheck:oP,LucideSquareCheckBig:d4,LucideSquareChevronDown:lP,LucideSquareChevronLeft:cP,LucideSquareChevronRight:dP,LucideSquareChevronUp:uP,LucideSquareCode:hP,LucideSquareDashed:fP,LucideSquareDashedBottom:M1e,LucideSquareDashedBottomCode:E1e,LucideSquareDashedKanban:mP,LucideSquareDashedMousePointer:pP,LucideSquareDivide:gP,LucideSquareDot:xP,LucideSquareEqual:yP,LucideSquareFunction:vP,LucideSquareGanttChart:ck,LucideSquareKanban:bP,LucideSquareLibrary:_P,LucideSquareM:wP,LucideSquareMenu:jP,LucideSquareMinus:NP,LucideSquareMousePointer:kP,LucideSquareParking:CP,LucideSquareParkingOff:SP,LucideSquarePen:xp,LucideSquarePercent:AP,LucideSquarePi:TP,LucideSquarePilcrow:EP,LucideSquarePlay:MP,LucideSquarePlus:LP,LucideSquarePower:PP,LucideSquareRadical:L1e,LucideSquareScissors:IP,LucideSquareSigma:DP,LucideSquareSlash:RP,LucideSquareSplitHorizontal:OP,LucideSquareSplitVertical:FP,LucideSquareSquare:P1e,LucideSquareStack:I1e,LucideSquareTerminal:zP,LucideSquareUser:$P,LucideSquareUserRound:BP,LucideSquareX:UP,LucideSquircle:D1e,LucideSquirrel:R1e,LucideStamp:O1e,LucideStar:Wa,LucideStarHalf:F1e,LucideStarOff:z1e,LucideStars:Cn,LucideStepBack:B1e,LucideStepForward:$1e,LucideStethoscope:U1e,LucideSticker:q1e,LucideStickyNote:_W,LucideStopCircle:YM,LucideStore:wW,LucideStretchHorizontal:V1e,LucideStretchVertical:H1e,LucideStrikethrough:jW,LucideSubscript:G1e,LucideSubtitles:pM,LucideSun:J2,LucideSunDim:W1e,LucideSunMedium:K1e,LucideSunMoon:Y1e,LucideSunSnow:Z1e,LucideSunrise:X1e,LucideSunset:Q1e,LucideSuperscript:J1e,LucideSwatchBook:ebe,LucideSwissFranc:tbe,LucideSwitchCamera:sbe,LucideSword:nbe,LucideSwords:rbe,LucideSyringe:abe,LucideTable:E9,LucideTable2:T9,LucideTableCellsMerge:ibe,LucideTableCellsSplit:obe,LucideTableColumnsSplit:lbe,LucideTableOfContents:cbe,LucideTableProperties:dbe,LucideTableRowsSplit:ube,LucideTablet:M9,LucideTabletSmartphone:hbe,LucideTablets:mbe,LucideTag:pf,LucideTags:NW,LucideTally1:pbe,LucideTally2:fbe,LucideTally3:gbe,LucideTally4:xbe,LucideTally5:ybe,LucideTangent:vbe,LucideTarget:iu,LucideTelescope:bbe,LucideTent:wbe,LucideTentTree:_be,LucideTerminal:jbe,LucideTerminalSquare:zP,LucideTestTube:Nbe,LucideTestTube2:qP,LucideTestTubeDiagonal:qP,LucideTestTubes:kbe,LucideText:Ebe,LucideTextCursor:Cbe,LucideTextCursorInput:Sbe,LucideTextQuote:Abe,LucideTextSearch:Tbe,LucideTextSelect:VP,LucideTextSelection:VP,LucideTheater:Mbe,LucideThermometer:kW,LucideThermometerSnowflake:Lbe,LucideThermometerSun:Pbe,LucideThumbsDown:SW,LucideThumbsUp:ax,LucideTicket:CW,LucideTicketCheck:Ibe,LucideTicketMinus:Dbe,LucideTicketPercent:Rbe,LucideTicketPlus:Obe,LucideTicketSlash:Fbe,LucideTicketX:zbe,LucideTickets:$be,LucideTicketsPlane:Bbe,LucideTimer:Vbe,LucideTimerOff:Ube,LucideTimerReset:qbe,LucideToggleLeft:Hbe,LucideToggleRight:Gbe,LucideToilet:Wbe,LucideTornado:Kbe,LucideTorus:Ybe,LucideTouchpad:Xbe,LucideTouchpadOff:Zbe,LucideTowerControl:Qbe,LucideToyBrick:Jbe,LucideTractor:e_e,LucideTrafficCone:t_e,LucideTrain:HP,LucideTrainFront:n_e,LucideTrainFrontTunnel:s_e,LucideTrainTrack:r_e,LucideTramFront:HP,LucideTrash:a_e,LucideTrash2:qn,LucideTreeDeciduous:i_e,LucideTreePalm:GP,LucideTreePine:zT,LucideTrees:o_e,LucideTrello:l_e,LucideTrendingDown:eN,LucideTrendingUp:ml,LucideTrendingUpDown:c_e,LucideTriangle:u_e,LucideTriangleAlert:xd,LucideTriangleRight:d_e,LucideTrophy:gl,LucideTruck:AW,LucideTurtle:h_e,LucideTv:p_e,LucideTv2:WP,LucideTvMinimal:WP,LucideTvMinimalPlay:m_e,LucideTwitch:f_e,LucideTwitter:g_e,LucideType:y_e,LucideTypeOutline:x_e,LucideUmbrella:b_e,LucideUmbrellaOff:v_e,LucideUnderline:L9,LucideUndo:BT,LucideUndo2:TW,LucideUndoDot:__e,LucideUnfoldHorizontal:w_e,LucideUnfoldVertical:j_e,LucideUngroup:N_e,LucideUniversity:KP,LucideUnlink:kD,LucideUnlink2:k_e,LucideUnlock:NL,LucideUnlockKeyhole:jL,LucideUnplug:S_e,LucideUpload:ni,LucideUploadCloud:tL,LucideUsb:C_e,LucideUser:Ro,LucideUser2:eI,LucideUserCheck:tN,LucideUserCheck2:YP,LucideUserCircle:XM,LucideUserCircle2:ZM,LucideUserCog:EW,LucideUserCog2:ZP,LucideUserMinus:MW,LucideUserMinus2:XP,LucideUserPen:A_e,LucideUserPlus:Yl,LucideUserPlus2:QP,LucideUserRound:eI,LucideUserRoundCheck:YP,LucideUserRoundCog:ZP,LucideUserRoundMinus:XP,LucideUserRoundPen:T_e,LucideUserRoundPlus:QP,LucideUserRoundSearch:E_e,LucideUserRoundX:JP,LucideUserSearch:M_e,LucideUserSquare:$P,LucideUserSquare2:BP,LucideUserX:L_e,LucideUserX2:JP,LucideUsers:Yn,LucideUsers2:f_,LucideUsersRound:f_,LucideUtensils:sI,LucideUtensilsCrossed:tI,LucideUtilityPole:P_e,LucideVariable:P9,LucideVault:I_e,LucideVegan:D_e,LucideVenetianMask:R_e,LucideVerified:cM,LucideVibrate:F_e,LucideVibrateOff:O_e,LucideVideo:na,LucideVideoOff:z_e,LucideVideotape:B_e,LucideView:$_e,LucideVoicemail:U_e,LucideVolleyball:q_e,LucideVolume:G_e,LucideVolume1:V_e,LucideVolume2:LW,LucideVolumeOff:H_e,LucideVolumeX:PW,LucideVote:W_e,LucideWallet:I9,LucideWallet2:nI,LucideWalletCards:K_e,LucideWalletMinimal:nI,LucideWallpaper:Y_e,LucideWand:Z_e,LucideWand2:Zg,LucideWandSparkles:Zg,LucideWarehouse:X_e,LucideWashingMachine:Q_e,LucideWatch:J_e,LucideWaves:ewe,LucideWaypoints:twe,LucideWebcam:swe,LucideWebhook:rwe,LucideWebhookOff:nwe,LucideWeight:awe,LucideWheat:owe,LucideWheatOff:iwe,LucideWholeWord:lwe,LucideWifi:mwe,LucideWifiHigh:cwe,LucideWifiLow:dwe,LucideWifiOff:uwe,LucideWifiZero:hwe,LucideWind:fwe,LucideWindArrowDown:pwe,LucideWine:IW,LucideWineOff:gwe,LucideWorkflow:DW,LucideWorm:xwe,LucideWrapText:ywe,LucideWrench:sN,LucideX:hr,LucideXCircle:Nu,LucideXOctagon:AL,LucideXSquare:UP,LucideYoutube:vwe,LucideZap:ff,LucideZapOff:bwe,LucideZoomIn:$T,LucideZoomOut:D9,Luggage:rge,LuggageIcon:rge,MSquare:wP,MSquareIcon:wP,Magnet:age,MagnetIcon:age,Mail:mn,MailCheck:g9,MailCheckIcon:g9,MailIcon:mn,MailMinus:ige,MailMinusIcon:ige,MailOpen:x9,MailOpenIcon:x9,MailPlus:nW,MailPlusIcon:nW,MailQuestion:oge,MailQuestionIcon:oge,MailSearch:lge,MailSearchIcon:lge,MailWarning:cge,MailWarningIcon:cge,MailX:y9,MailXIcon:y9,Mailbox:dge,MailboxIcon:dge,Mails:uge,MailsIcon:uge,Map:yD,MapIcon:yD,MapPin:ii,MapPinCheck:mge,MapPinCheckIcon:mge,MapPinCheckInside:hge,MapPinCheckInsideIcon:hge,MapPinHouse:pge,MapPinHouseIcon:pge,MapPinIcon:ii,MapPinMinus:gge,MapPinMinusIcon:gge,MapPinMinusInside:fge,MapPinMinusInsideIcon:fge,MapPinOff:xge,MapPinOffIcon:xge,MapPinPlus:vge,MapPinPlusIcon:vge,MapPinPlusInside:yge,MapPinPlusInsideIcon:yge,MapPinX:_ge,MapPinXIcon:_ge,MapPinXInside:bge,MapPinXInsideIcon:bge,MapPinned:wge,MapPinnedIcon:wge,Martini:jge,MartiniIcon:jge,Maximize:vD,Maximize2:rW,Maximize2Icon:rW,MaximizeIcon:vD,Medal:i3,MedalIcon:i3,Megaphone:um,MegaphoneIcon:um,MegaphoneOff:Nge,MegaphoneOffIcon:Nge,Meh:kge,MehIcon:kge,MemoryStick:Sge,MemoryStickIcon:Sge,Menu:MT,MenuIcon:MT,MenuSquare:jP,MenuSquareIcon:jP,Merge:Cge,MergeIcon:Cge,MessageCircle:Ud,MessageCircleCode:Age,MessageCircleCodeIcon:Age,MessageCircleDashed:Tge,MessageCircleDashedIcon:Tge,MessageCircleHeart:v9,MessageCircleHeartIcon:v9,MessageCircleIcon:Ud,MessageCircleMore:Ege,MessageCircleMoreIcon:Ege,MessageCircleOff:Mge,MessageCircleOffIcon:Mge,MessageCirclePlus:Lge,MessageCirclePlusIcon:Lge,MessageCircleQuestion:aW,MessageCircleQuestionIcon:aW,MessageCircleReply:Pge,MessageCircleReplyIcon:Pge,MessageCircleWarning:Ige,MessageCircleWarningIcon:Ige,MessageCircleX:Dge,MessageCircleXIcon:Dge,MessageSquare:xo,MessageSquareCode:Rge,MessageSquareCodeIcon:Rge,MessageSquareDashed:Oge,MessageSquareDashedIcon:Oge,MessageSquareDiff:Fge,MessageSquareDiffIcon:Fge,MessageSquareDot:zge,MessageSquareDotIcon:zge,MessageSquareHeart:b9,MessageSquareHeartIcon:b9,MessageSquareIcon:xo,MessageSquareLock:Bge,MessageSquareLockIcon:Bge,MessageSquareMore:iW,MessageSquareMoreIcon:iW,MessageSquareOff:$ge,MessageSquareOffIcon:$ge,MessageSquarePlus:Qk,MessageSquarePlusIcon:Qk,MessageSquareQuote:f5,MessageSquareQuoteIcon:f5,MessageSquareReply:Uge,MessageSquareReplyIcon:Uge,MessageSquareShare:qge,MessageSquareShareIcon:qge,MessageSquareText:Vge,MessageSquareTextIcon:Vge,MessageSquareWarning:Hge,MessageSquareWarningIcon:Hge,MessageSquareX:Gge,MessageSquareXIcon:Gge,MessagesSquare:_9,MessagesSquareIcon:_9,Mic:uj,Mic2:kL,Mic2Icon:kL,MicIcon:uj,MicOff:Wge,MicOffIcon:Wge,MicVocal:kL,MicVocalIcon:kL,Microchip:Kge,MicrochipIcon:Kge,Microscope:Yge,MicroscopeIcon:Yge,Microwave:Zge,MicrowaveIcon:Zge,Milestone:Xge,MilestoneIcon:Xge,Milk:Jge,MilkIcon:Jge,MilkOff:Qge,MilkOffIcon:Qge,Minimize:txe,Minimize2:exe,Minimize2Icon:exe,MinimizeIcon:txe,Minus:X2,MinusCircle:$M,MinusCircleIcon:$M,MinusIcon:X2,MinusSquare:NP,MinusSquareIcon:NP,Monitor:hj,MonitorCheck:sxe,MonitorCheckIcon:sxe,MonitorCog:nxe,MonitorCogIcon:nxe,MonitorDot:rxe,MonitorDotIcon:rxe,MonitorDown:axe,MonitorDownIcon:axe,MonitorIcon:hj,MonitorOff:ixe,MonitorOffIcon:ixe,MonitorPause:oxe,MonitorPauseIcon:oxe,MonitorPlay:w9,MonitorPlayIcon:w9,MonitorSmartphone:lxe,MonitorSmartphoneIcon:lxe,MonitorSpeaker:cxe,MonitorSpeakerIcon:cxe,MonitorStop:dxe,MonitorStopIcon:dxe,MonitorUp:bD,MonitorUpIcon:bD,MonitorX:uxe,MonitorXIcon:uxe,Moon:mxe,MoonIcon:mxe,MoonStar:hxe,MoonStarIcon:hxe,MoreHorizontal:Iy,MoreHorizontalIcon:Iy,MoreVertical:Ev,MoreVerticalIcon:Ev,Mountain:fxe,MountainIcon:fxe,MountainSnow:pxe,MountainSnowIcon:pxe,Mouse:vxe,MouseIcon:vxe,MouseOff:gxe,MouseOffIcon:gxe,MousePointer:Qg,MousePointer2:xxe,MousePointer2Icon:xxe,MousePointerBan:yxe,MousePointerBanIcon:yxe,MousePointerClick:ru,MousePointerClickIcon:ru,MousePointerIcon:Qg,MousePointerSquareDashed:pP,MousePointerSquareDashedIcon:pP,Move:oW,Move3D:SL,Move3DIcon:SL,Move3d:SL,Move3dIcon:SL,MoveDiagonal:_xe,MoveDiagonal2:bxe,MoveDiagonal2Icon:bxe,MoveDiagonalIcon:_xe,MoveDown:Nxe,MoveDownIcon:Nxe,MoveDownLeft:wxe,MoveDownLeftIcon:wxe,MoveDownRight:jxe,MoveDownRightIcon:jxe,MoveHorizontal:kxe,MoveHorizontalIcon:kxe,MoveIcon:oW,MoveLeft:Sxe,MoveLeftIcon:Sxe,MoveRight:Cxe,MoveRightIcon:Cxe,MoveUp:Exe,MoveUpIcon:Exe,MoveUpLeft:Axe,MoveUpLeftIcon:Axe,MoveUpRight:Txe,MoveUpRightIcon:Txe,MoveVertical:Mxe,MoveVerticalIcon:Mxe,Music:j9,Music2:Lxe,Music2Icon:Lxe,Music3:Pxe,Music3Icon:Pxe,Music4:Ixe,Music4Icon:Ixe,MusicIcon:j9,Navigation:lW,Navigation2:Rxe,Navigation2Icon:Rxe,Navigation2Off:Dxe,Navigation2OffIcon:Dxe,NavigationIcon:lW,NavigationOff:Oxe,NavigationOffIcon:Oxe,Network:Fxe,NetworkIcon:Fxe,Newspaper:E_,NewspaperIcon:E_,Nfc:zxe,NfcIcon:zxe,Notebook:qxe,NotebookIcon:qxe,NotebookPen:Bxe,NotebookPenIcon:Bxe,NotebookTabs:$xe,NotebookTabsIcon:$xe,NotebookText:Uxe,NotebookTextIcon:Uxe,NotepadText:Hxe,NotepadTextDashed:Vxe,NotepadTextDashedIcon:Vxe,NotepadTextIcon:Hxe,Nut:Wxe,NutIcon:Wxe,NutOff:Gxe,NutOffIcon:Gxe,Octagon:Yxe,OctagonAlert:qk,OctagonAlertIcon:qk,OctagonIcon:Yxe,OctagonMinus:Kxe,OctagonMinusIcon:Kxe,OctagonPause:CL,OctagonPauseIcon:CL,OctagonX:AL,OctagonXIcon:AL,Omega:Zxe,OmegaIcon:Zxe,Option:Xxe,OptionIcon:Xxe,Orbit:Qxe,OrbitIcon:Qxe,Origami:Jxe,OrigamiIcon:Jxe,Outdent:bL,OutdentIcon:bL,Package:Ku,Package2:e0e,Package2Icon:e0e,PackageCheck:t0e,PackageCheckIcon:t0e,PackageIcon:Ku,PackageMinus:s0e,PackageMinusIcon:s0e,PackageOpen:n0e,PackageOpenIcon:n0e,PackagePlus:cW,PackagePlusIcon:cW,PackageSearch:r0e,PackageSearchIcon:r0e,PackageX:a0e,PackageXIcon:a0e,PaintBucket:i0e,PaintBucketIcon:i0e,PaintRoller:o0e,PaintRollerIcon:o0e,Paintbrush:l0e,Paintbrush2:TL,Paintbrush2Icon:TL,PaintbrushIcon:l0e,PaintbrushVertical:TL,PaintbrushVerticalIcon:TL,Palette:zc,PaletteIcon:zc,Palmtree:GP,PalmtreeIcon:GP,PanelBottom:u0e,PanelBottomClose:c0e,PanelBottomCloseIcon:c0e,PanelBottomDashed:EL,PanelBottomDashedIcon:EL,PanelBottomIcon:u0e,PanelBottomInactive:EL,PanelBottomInactiveIcon:EL,PanelBottomOpen:d0e,PanelBottomOpenIcon:d0e,PanelLeft:IL,PanelLeftClose:ML,PanelLeftCloseIcon:ML,PanelLeftDashed:LL,PanelLeftDashedIcon:LL,PanelLeftIcon:IL,PanelLeftInactive:LL,PanelLeftInactiveIcon:LL,PanelLeftOpen:PL,PanelLeftOpenIcon:PL,PanelRight:p0e,PanelRightClose:h0e,PanelRightCloseIcon:h0e,PanelRightDashed:DL,PanelRightDashedIcon:DL,PanelRightIcon:p0e,PanelRightInactive:DL,PanelRightInactiveIcon:DL,PanelRightOpen:m0e,PanelRightOpenIcon:m0e,PanelTop:x0e,PanelTopClose:f0e,PanelTopCloseIcon:f0e,PanelTopDashed:RL,PanelTopDashedIcon:RL,PanelTopIcon:x0e,PanelTopInactive:RL,PanelTopInactiveIcon:RL,PanelTopOpen:g0e,PanelTopOpenIcon:g0e,PanelsLeftBottom:y0e,PanelsLeftBottomIcon:y0e,PanelsLeftRight:GC,PanelsLeftRightIcon:GC,PanelsRightBottom:v0e,PanelsRightBottomIcon:v0e,PanelsTopBottom:$L,PanelsTopBottomIcon:$L,PanelsTopLeft:c4,PanelsTopLeftIcon:c4,Paperclip:LT,PaperclipIcon:LT,Parentheses:b0e,ParenthesesIcon:b0e,ParkingCircle:qM,ParkingCircleIcon:qM,ParkingCircleOff:UM,ParkingCircleOffIcon:UM,ParkingMeter:_0e,ParkingMeterIcon:_0e,ParkingSquare:CP,ParkingSquareIcon:CP,ParkingSquareOff:SP,ParkingSquareOffIcon:SP,PartyPopper:uf,PartyPopperIcon:uf,Pause:K0,PauseCircle:VM,PauseCircleIcon:VM,PauseIcon:K0,PauseOctagon:CL,PauseOctagonIcon:CL,PawPrint:w0e,PawPrintIcon:w0e,PcCase:j0e,PcCaseIcon:j0e,Pen:Ww,PenBox:xp,PenBoxIcon:xp,PenIcon:Ww,PenLine:O2,PenLineIcon:O2,PenOff:N0e,PenOffIcon:N0e,PenSquare:xp,PenSquareIcon:xp,PenTool:PT,PenToolIcon:PT,Pencil:Ja,PencilIcon:Ja,PencilLine:N9,PencilLineIcon:N9,PencilOff:k0e,PencilOffIcon:k0e,PencilRuler:S0e,PencilRulerIcon:S0e,Pentagon:C0e,PentagonIcon:C0e,Percent:IT,PercentCircle:HM,PercentCircleIcon:HM,PercentDiamond:rL,PercentDiamondIcon:rL,PercentIcon:IT,PercentSquare:AP,PercentSquareIcon:AP,PersonStanding:A0e,PersonStandingIcon:A0e,PhilippinePeso:T0e,PhilippinePesoIcon:T0e,Phone:ga,PhoneCall:dW,PhoneCallIcon:dW,PhoneForwarded:E0e,PhoneForwardedIcon:E0e,PhoneIcon:ga,PhoneIncoming:M0e,PhoneIncomingIcon:M0e,PhoneMissed:L0e,PhoneMissedIcon:L0e,PhoneOff:P0e,PhoneOffIcon:P0e,PhoneOutgoing:I0e,PhoneOutgoingIcon:I0e,Pi:D0e,PiIcon:D0e,PiSquare:TP,PiSquareIcon:TP,Piano:R0e,PianoIcon:R0e,Pickaxe:O0e,PickaxeIcon:O0e,PictureInPicture:z0e,PictureInPicture2:F0e,PictureInPicture2Icon:F0e,PictureInPictureIcon:z0e,PieChart:kM,PieChartIcon:kM,PiggyBank:B0e,PiggyBankIcon:B0e,Pilcrow:q0e,PilcrowIcon:q0e,PilcrowLeft:$0e,PilcrowLeftIcon:$0e,PilcrowRight:U0e,PilcrowRightIcon:U0e,PilcrowSquare:EP,PilcrowSquareIcon:EP,Pill:H0e,PillBottle:V0e,PillBottleIcon:V0e,PillIcon:H0e,Pin:DT,PinIcon:DT,PinOff:uW,PinOffIcon:uW,Pipette:G0e,PipetteIcon:G0e,Pizza:W0e,PizzaIcon:W0e,Plane:hW,PlaneIcon:hW,PlaneLanding:K0e,PlaneLandingIcon:K0e,PlaneTakeoff:Y0e,PlaneTakeoffIcon:Y0e,Play:dd,PlayCircle:wp,PlayCircleIcon:wp,PlayIcon:dd,PlaySquare:MP,PlaySquareIcon:MP,Plug:o3,Plug2:Z0e,Plug2Icon:Z0e,PlugIcon:o3,PlugZap:OL,PlugZap2:OL,PlugZap2Icon:OL,PlugZapIcon:OL,Plus:nn,PlusCircle:GM,PlusCircleIcon:GM,PlusIcon:nn,PlusSquare:LP,PlusSquareIcon:LP,Pocket:Q0e,PocketIcon:Q0e,PocketKnife:X0e,PocketKnifeIcon:X0e,Podcast:J0e,PodcastIcon:J0e,Pointer:tye,PointerIcon:tye,PointerOff:eye,PointerOffIcon:eye,Popcorn:sye,PopcornIcon:sye,Popsicle:nye,PopsicleIcon:nye,PoundSterling:rye,PoundSterlingIcon:rye,Power:mW,PowerCircle:WM,PowerCircleIcon:WM,PowerIcon:mW,PowerOff:aye,PowerOffIcon:aye,PowerSquare:PP,PowerSquareIcon:PP,Presentation:ab,PresentationIcon:ab,Printer:pW,PrinterCheck:iye,PrinterCheckIcon:iye,PrinterIcon:pW,Projector:oye,ProjectorIcon:oye,Proportions:lye,ProportionsIcon:lye,Puzzle:cye,PuzzleIcon:cye,Pyramid:dye,PyramidIcon:dye,QrCode:M_,QrCodeIcon:M_,Quote:Q2,QuoteIcon:Q2,Rabbit:uye,RabbitIcon:uye,Radar:_D,RadarIcon:_D,Radiation:hye,RadiationIcon:hye,Radical:mye,RadicalIcon:mye,Radio:Y0,RadioIcon:Y0,RadioReceiver:pye,RadioReceiverIcon:pye,RadioTower:fye,RadioTowerIcon:fye,Radius:gye,RadiusIcon:gye,RailSymbol:xye,RailSymbolIcon:xye,Rainbow:yye,RainbowIcon:yye,Rat:vye,RatIcon:vye,Ratio:bye,RatioIcon:bye,Receipt:Tye,ReceiptCent:_ye,ReceiptCentIcon:_ye,ReceiptEuro:wye,ReceiptEuroIcon:wye,ReceiptIcon:Tye,ReceiptIndianRupee:jye,ReceiptIndianRupeeIcon:jye,ReceiptJapaneseYen:Nye,ReceiptJapaneseYenIcon:Nye,ReceiptPoundSterling:kye,ReceiptPoundSterlingIcon:kye,ReceiptRussianRuble:Sye,ReceiptRussianRubleIcon:Sye,ReceiptSwissFranc:Cye,ReceiptSwissFrancIcon:Cye,ReceiptText:Aye,ReceiptTextIcon:Aye,RectangleEllipsis:FL,RectangleEllipsisIcon:FL,RectangleHorizontal:Eye,RectangleHorizontalIcon:Eye,RectangleVertical:Mye,RectangleVerticalIcon:Mye,Recycle:Lye,RecycleIcon:Lye,Redo:RT,Redo2:Pye,Redo2Icon:Pye,RedoDot:Iye,RedoDotIcon:Iye,RedoIcon:RT,RefreshCcw:k9,RefreshCcwDot:Dye,RefreshCcwDotIcon:Dye,RefreshCcwIcon:k9,RefreshCw:oo,RefreshCwIcon:oo,RefreshCwOff:Rye,RefreshCwOffIcon:Rye,Refrigerator:Oye,RefrigeratorIcon:Oye,Regex:Fye,RegexIcon:Fye,RemoveFormatting:zye,RemoveFormattingIcon:zye,Repeat:S9,Repeat1:Bye,Repeat1Icon:Bye,Repeat2:$ye,Repeat2Icon:$ye,RepeatIcon:S9,Replace:qye,ReplaceAll:Uye,ReplaceAllIcon:Uye,ReplaceIcon:qye,Reply:fW,ReplyAll:Vye,ReplyAllIcon:Vye,ReplyIcon:fW,Rewind:Hye,RewindIcon:Hye,Ribbon:Gye,RibbonIcon:Gye,Rocket:By,RocketIcon:By,RockingChair:Wye,RockingChairIcon:Wye,RollerCoaster:Kye,RollerCoasterIcon:Kye,Rotate3D:zL,Rotate3DIcon:zL,Rotate3d:zL,Rotate3dIcon:zL,RotateCcw:hf,RotateCcwIcon:hf,RotateCcwSquare:Yye,RotateCcwSquareIcon:Yye,RotateCw:wD,RotateCwIcon:wD,RotateCwSquare:Zye,RotateCwSquareIcon:Zye,Route:gW,RouteIcon:gW,RouteOff:Xye,RouteOffIcon:Xye,Router:Qye,RouterIcon:Qye,Rows:BL,Rows2:BL,Rows2Icon:BL,Rows3:$L,Rows3Icon:$L,Rows4:Jye,Rows4Icon:Jye,RowsIcon:BL,Rss:eve,RssIcon:eve,Ruler:l3,RulerIcon:l3,RussianRuble:tve,RussianRubleIcon:tve,Sailboat:sve,SailboatIcon:sve,Salad:nve,SaladIcon:nve,Sandwich:rve,SandwichIcon:rve,Satellite:ive,SatelliteDish:ave,SatelliteDishIcon:ave,SatelliteIcon:ive,Save:Kl,SaveAll:ove,SaveAllIcon:ove,SaveIcon:Kl,SaveOff:lve,SaveOffIcon:lve,Scale:xW,Scale3D:UL,Scale3DIcon:UL,Scale3d:UL,Scale3dIcon:UL,ScaleIcon:xW,Scaling:cve,ScalingIcon:cve,Scan:xve,ScanBarcode:dve,ScanBarcodeIcon:dve,ScanEye:uve,ScanEyeIcon:uve,ScanFace:hve,ScanFaceIcon:hve,ScanIcon:xve,ScanLine:mve,ScanLineIcon:mve,ScanQrCode:pve,ScanQrCodeIcon:pve,ScanSearch:fve,ScanSearchIcon:fve,ScanText:gve,ScanTextIcon:gve,ScatterChart:SM,ScatterChartIcon:SM,School:yve,School2:KP,School2Icon:KP,SchoolIcon:yve,Scissors:bve,ScissorsIcon:bve,ScissorsLineDashed:vve,ScissorsLineDashedIcon:vve,ScissorsSquare:IP,ScissorsSquareDashedBottom:iP,ScissorsSquareDashedBottomIcon:iP,ScissorsSquareIcon:IP,ScreenShare:wve,ScreenShareIcon:wve,ScreenShareOff:_ve,ScreenShareOffIcon:_ve,Scroll:jve,ScrollIcon:jve,ScrollText:yW,ScrollTextIcon:yW,Search:Gr,SearchCheck:Nve,SearchCheckIcon:Nve,SearchCode:kve,SearchCodeIcon:kve,SearchIcon:Gr,SearchSlash:Sve,SearchSlashIcon:Sve,SearchX:vW,SearchXIcon:vW,Section:Cve,SectionIcon:Cve,Send:Rr,SendHorizonal:qL,SendHorizonalIcon:qL,SendHorizontal:qL,SendHorizontalIcon:qL,SendIcon:Rr,SendToBack:Ave,SendToBackIcon:Ave,SeparatorHorizontal:Tve,SeparatorHorizontalIcon:Tve,SeparatorVertical:Eve,SeparatorVerticalIcon:Eve,Server:Ive,ServerCog:Mve,ServerCogIcon:Mve,ServerCrash:Lve,ServerCrashIcon:Lve,ServerIcon:Ive,ServerOff:Pve,ServerOffIcon:Pve,Settings:sc,Settings2:C9,Settings2Icon:C9,SettingsIcon:sc,Shapes:Dve,ShapesIcon:Dve,Share:bW,Share2:Md,Share2Icon:Md,ShareIcon:bW,Sheet:Rve,SheetIcon:Rve,Shell:Ove,ShellIcon:Ove,Shield:mf,ShieldAlert:A9,ShieldAlertIcon:A9,ShieldBan:Fve,ShieldBanIcon:Fve,ShieldCheck:Wv,ShieldCheckIcon:Wv,ShieldClose:VL,ShieldCloseIcon:VL,ShieldEllipsis:zve,ShieldEllipsisIcon:zve,ShieldHalf:Bve,ShieldHalfIcon:Bve,ShieldIcon:mf,ShieldMinus:$ve,ShieldMinusIcon:$ve,ShieldOff:jD,ShieldOffIcon:jD,ShieldPlus:Uve,ShieldPlusIcon:Uve,ShieldQuestion:qve,ShieldQuestionIcon:qve,ShieldX:VL,ShieldXIcon:VL,Ship:Hve,ShipIcon:Hve,ShipWheel:Vve,ShipWheelIcon:Vve,Shirt:Gve,ShirtIcon:Gve,ShoppingBag:g5,ShoppingBagIcon:g5,ShoppingBasket:Wve,ShoppingBasketIcon:Wve,ShoppingCart:W1,ShoppingCartIcon:W1,Shovel:Kve,ShovelIcon:Kve,ShowerHead:Yve,ShowerHeadIcon:Yve,Shrink:Zve,ShrinkIcon:Zve,Shrub:Xve,ShrubIcon:Xve,Shuffle:ND,ShuffleIcon:ND,Sidebar:IL,SidebarClose:ML,SidebarCloseIcon:ML,SidebarIcon:IL,SidebarOpen:PL,SidebarOpenIcon:PL,Sigma:Qve,SigmaIcon:Qve,SigmaSquare:DP,SigmaSquareIcon:DP,Signal:n1e,SignalHigh:Jve,SignalHighIcon:Jve,SignalIcon:n1e,SignalLow:e1e,SignalLowIcon:e1e,SignalMedium:t1e,SignalMediumIcon:t1e,SignalZero:s1e,SignalZeroIcon:s1e,Signature:r1e,SignatureIcon:r1e,Signpost:i1e,SignpostBig:a1e,SignpostBigIcon:a1e,SignpostIcon:i1e,Siren:o1e,SirenIcon:o1e,SkipBack:l1e,SkipBackIcon:l1e,SkipForward:c1e,SkipForwardIcon:c1e,Skull:d1e,SkullIcon:d1e,Slack:u1e,SlackIcon:u1e,Slash:h1e,SlashIcon:h1e,SlashSquare:RP,SlashSquareIcon:RP,Slice:m1e,SliceIcon:m1e,Sliders:HL,SlidersHorizontal:OT,SlidersHorizontalIcon:OT,SlidersIcon:HL,SlidersVertical:HL,SlidersVerticalIcon:HL,Smartphone:$y,SmartphoneCharging:p1e,SmartphoneChargingIcon:p1e,SmartphoneIcon:$y,SmartphoneNfc:f1e,SmartphoneNfcIcon:f1e,Smile:x1e,SmileIcon:x1e,SmilePlus:g1e,SmilePlusIcon:g1e,Snail:y1e,SnailIcon:y1e,Snowflake:nj,SnowflakeIcon:nj,Sofa:v1e,SofaIcon:v1e,SortAsc:iM,SortAscIcon:iM,SortDesc:nM,SortDescIcon:nM,Soup:b1e,SoupIcon:b1e,Space:_1e,SpaceIcon:_1e,Spade:w1e,SpadeIcon:w1e,Sparkle:c3,SparkleIcon:c3,Sparkles:Cn,SparklesIcon:Cn,Speaker:j1e,SpeakerIcon:j1e,Speech:N1e,SpeechIcon:N1e,SpellCheck:S1e,SpellCheck2:k1e,SpellCheck2Icon:k1e,SpellCheckIcon:S1e,Spline:C1e,SplineIcon:C1e,Split:A1e,SplitIcon:A1e,SplitSquareHorizontal:OP,SplitSquareHorizontalIcon:OP,SplitSquareVertical:FP,SplitSquareVerticalIcon:FP,SprayCan:T1e,SprayCanIcon:T1e,Sprout:FT,SproutIcon:FT,Square:L_,SquareActivity:GL,SquareActivityIcon:GL,SquareArrowDown:YL,SquareArrowDownIcon:YL,SquareArrowDownLeft:WL,SquareArrowDownLeftIcon:WL,SquareArrowDownRight:KL,SquareArrowDownRightIcon:KL,SquareArrowLeft:ZL,SquareArrowLeftIcon:ZL,SquareArrowOutDownLeft:XL,SquareArrowOutDownLeftIcon:XL,SquareArrowOutDownRight:QL,SquareArrowOutDownRightIcon:QL,SquareArrowOutUpLeft:JL,SquareArrowOutUpLeftIcon:JL,SquareArrowOutUpRight:eP,SquareArrowOutUpRightIcon:eP,SquareArrowRight:tP,SquareArrowRightIcon:tP,SquareArrowUp:rP,SquareArrowUpIcon:rP,SquareArrowUpLeft:sP,SquareArrowUpLeftIcon:sP,SquareArrowUpRight:nP,SquareArrowUpRightIcon:nP,SquareAsterisk:aP,SquareAsteriskIcon:aP,SquareBottomDashedScissors:iP,SquareBottomDashedScissorsIcon:iP,SquareChartGantt:ck,SquareChartGanttIcon:ck,SquareCheck:oP,SquareCheckBig:d4,SquareCheckBigIcon:d4,SquareCheckIcon:oP,SquareChevronDown:lP,SquareChevronDownIcon:lP,SquareChevronLeft:cP,SquareChevronLeftIcon:cP,SquareChevronRight:dP,SquareChevronRightIcon:dP,SquareChevronUp:uP,SquareChevronUpIcon:uP,SquareCode:hP,SquareCodeIcon:hP,SquareDashed:fP,SquareDashedBottom:M1e,SquareDashedBottomCode:E1e,SquareDashedBottomCodeIcon:E1e,SquareDashedBottomIcon:M1e,SquareDashedIcon:fP,SquareDashedKanban:mP,SquareDashedKanbanIcon:mP,SquareDashedMousePointer:pP,SquareDashedMousePointerIcon:pP,SquareDivide:gP,SquareDivideIcon:gP,SquareDot:xP,SquareDotIcon:xP,SquareEqual:yP,SquareEqualIcon:yP,SquareFunction:vP,SquareFunctionIcon:vP,SquareGanttChart:ck,SquareGanttChartIcon:ck,SquareIcon:L_,SquareKanban:bP,SquareKanbanIcon:bP,SquareLibrary:_P,SquareLibraryIcon:_P,SquareM:wP,SquareMIcon:wP,SquareMenu:jP,SquareMenuIcon:jP,SquareMinus:NP,SquareMinusIcon:NP,SquareMousePointer:kP,SquareMousePointerIcon:kP,SquareParking:CP,SquareParkingIcon:CP,SquareParkingOff:SP,SquareParkingOffIcon:SP,SquarePen:xp,SquarePenIcon:xp,SquarePercent:AP,SquarePercentIcon:AP,SquarePi:TP,SquarePiIcon:TP,SquarePilcrow:EP,SquarePilcrowIcon:EP,SquarePlay:MP,SquarePlayIcon:MP,SquarePlus:LP,SquarePlusIcon:LP,SquarePower:PP,SquarePowerIcon:PP,SquareRadical:L1e,SquareRadicalIcon:L1e,SquareScissors:IP,SquareScissorsIcon:IP,SquareSigma:DP,SquareSigmaIcon:DP,SquareSlash:RP,SquareSlashIcon:RP,SquareSplitHorizontal:OP,SquareSplitHorizontalIcon:OP,SquareSplitVertical:FP,SquareSplitVerticalIcon:FP,SquareSquare:P1e,SquareSquareIcon:P1e,SquareStack:I1e,SquareStackIcon:I1e,SquareTerminal:zP,SquareTerminalIcon:zP,SquareUser:$P,SquareUserIcon:$P,SquareUserRound:BP,SquareUserRoundIcon:BP,SquareX:UP,SquareXIcon:UP,Squircle:D1e,SquircleIcon:D1e,Squirrel:R1e,SquirrelIcon:R1e,Stamp:O1e,StampIcon:O1e,Star:Wa,StarHalf:F1e,StarHalfIcon:F1e,StarIcon:Wa,StarOff:z1e,StarOffIcon:z1e,Stars:Cn,StarsIcon:Cn,StepBack:B1e,StepBackIcon:B1e,StepForward:$1e,StepForwardIcon:$1e,Stethoscope:U1e,StethoscopeIcon:U1e,Sticker:q1e,StickerIcon:q1e,StickyNote:_W,StickyNoteIcon:_W,StopCircle:YM,StopCircleIcon:YM,Store:wW,StoreIcon:wW,StretchHorizontal:V1e,StretchHorizontalIcon:V1e,StretchVertical:H1e,StretchVerticalIcon:H1e,Strikethrough:jW,StrikethroughIcon:jW,Subscript:G1e,SubscriptIcon:G1e,Subtitles:pM,SubtitlesIcon:pM,Sun:J2,SunDim:W1e,SunDimIcon:W1e,SunIcon:J2,SunMedium:K1e,SunMediumIcon:K1e,SunMoon:Y1e,SunMoonIcon:Y1e,SunSnow:Z1e,SunSnowIcon:Z1e,Sunrise:X1e,SunriseIcon:X1e,Sunset:Q1e,SunsetIcon:Q1e,Superscript:J1e,SuperscriptIcon:J1e,SwatchBook:ebe,SwatchBookIcon:ebe,SwissFranc:tbe,SwissFrancIcon:tbe,SwitchCamera:sbe,SwitchCameraIcon:sbe,Sword:nbe,SwordIcon:nbe,Swords:rbe,SwordsIcon:rbe,Syringe:abe,SyringeIcon:abe,Table:E9,Table2:T9,Table2Icon:T9,TableCellsMerge:ibe,TableCellsMergeIcon:ibe,TableCellsSplit:obe,TableCellsSplitIcon:obe,TableColumnsSplit:lbe,TableColumnsSplitIcon:lbe,TableIcon:E9,TableOfContents:cbe,TableOfContentsIcon:cbe,TableProperties:dbe,TablePropertiesIcon:dbe,TableRowsSplit:ube,TableRowsSplitIcon:ube,Tablet:M9,TabletIcon:M9,TabletSmartphone:hbe,TabletSmartphoneIcon:hbe,Tablets:mbe,TabletsIcon:mbe,Tag:pf,TagIcon:pf,Tags:NW,TagsIcon:NW,Tally1:pbe,Tally1Icon:pbe,Tally2:fbe,Tally2Icon:fbe,Tally3:gbe,Tally3Icon:gbe,Tally4:xbe,Tally4Icon:xbe,Tally5:ybe,Tally5Icon:ybe,Tangent:vbe,TangentIcon:vbe,Target:iu,TargetIcon:iu,Telescope:bbe,TelescopeIcon:bbe,Tent:wbe,TentIcon:wbe,TentTree:_be,TentTreeIcon:_be,Terminal:jbe,TerminalIcon:jbe,TerminalSquare:zP,TerminalSquareIcon:zP,TestTube:Nbe,TestTube2:qP,TestTube2Icon:qP,TestTubeDiagonal:qP,TestTubeDiagonalIcon:qP,TestTubeIcon:Nbe,TestTubes:kbe,TestTubesIcon:kbe,Text:Ebe,TextCursor:Cbe,TextCursorIcon:Cbe,TextCursorInput:Sbe,TextCursorInputIcon:Sbe,TextIcon:Ebe,TextQuote:Abe,TextQuoteIcon:Abe,TextSearch:Tbe,TextSearchIcon:Tbe,TextSelect:VP,TextSelectIcon:VP,TextSelection:VP,TextSelectionIcon:VP,Theater:Mbe,TheaterIcon:Mbe,Thermometer:kW,ThermometerIcon:kW,ThermometerSnowflake:Lbe,ThermometerSnowflakeIcon:Lbe,ThermometerSun:Pbe,ThermometerSunIcon:Pbe,ThumbsDown:SW,ThumbsDownIcon:SW,ThumbsUp:ax,ThumbsUpIcon:ax,Ticket:CW,TicketCheck:Ibe,TicketCheckIcon:Ibe,TicketIcon:CW,TicketMinus:Dbe,TicketMinusIcon:Dbe,TicketPercent:Rbe,TicketPercentIcon:Rbe,TicketPlus:Obe,TicketPlusIcon:Obe,TicketSlash:Fbe,TicketSlashIcon:Fbe,TicketX:zbe,TicketXIcon:zbe,Tickets:$be,TicketsIcon:$be,TicketsPlane:Bbe,TicketsPlaneIcon:Bbe,Timer:Vbe,TimerIcon:Vbe,TimerOff:Ube,TimerOffIcon:Ube,TimerReset:qbe,TimerResetIcon:qbe,ToggleLeft:Hbe,ToggleLeftIcon:Hbe,ToggleRight:Gbe,ToggleRightIcon:Gbe,Toilet:Wbe,ToiletIcon:Wbe,Tornado:Kbe,TornadoIcon:Kbe,Torus:Ybe,TorusIcon:Ybe,Touchpad:Xbe,TouchpadIcon:Xbe,TouchpadOff:Zbe,TouchpadOffIcon:Zbe,TowerControl:Qbe,TowerControlIcon:Qbe,ToyBrick:Jbe,ToyBrickIcon:Jbe,Tractor:e_e,TractorIcon:e_e,TrafficCone:t_e,TrafficConeIcon:t_e,Train:HP,TrainFront:n_e,TrainFrontIcon:n_e,TrainFrontTunnel:s_e,TrainFrontTunnelIcon:s_e,TrainIcon:HP,TrainTrack:r_e,TrainTrackIcon:r_e,TramFront:HP,TramFrontIcon:HP,Trash:a_e,Trash2:qn,Trash2Icon:qn,TrashIcon:a_e,TreeDeciduous:i_e,TreeDeciduousIcon:i_e,TreePalm:GP,TreePalmIcon:GP,TreePine:zT,TreePineIcon:zT,Trees:o_e,TreesIcon:o_e,Trello:l_e,TrelloIcon:l_e,TrendingDown:eN,TrendingDownIcon:eN,TrendingUp:ml,TrendingUpDown:c_e,TrendingUpDownIcon:c_e,TrendingUpIcon:ml,Triangle:u_e,TriangleAlert:xd,TriangleAlertIcon:xd,TriangleIcon:u_e,TriangleRight:d_e,TriangleRightIcon:d_e,Trophy:gl,TrophyIcon:gl,Truck:AW,TruckIcon:AW,Turtle:h_e,TurtleIcon:h_e,Tv:p_e,Tv2:WP,Tv2Icon:WP,TvIcon:p_e,TvMinimal:WP,TvMinimalIcon:WP,TvMinimalPlay:m_e,TvMinimalPlayIcon:m_e,Twitch:f_e,TwitchIcon:f_e,Twitter:g_e,TwitterIcon:g_e,Type:y_e,TypeIcon:y_e,TypeOutline:x_e,TypeOutlineIcon:x_e,Umbrella:b_e,UmbrellaIcon:b_e,UmbrellaOff:v_e,UmbrellaOffIcon:v_e,Underline:L9,UnderlineIcon:L9,Undo:BT,Undo2:TW,Undo2Icon:TW,UndoDot:__e,UndoDotIcon:__e,UndoIcon:BT,UnfoldHorizontal:w_e,UnfoldHorizontalIcon:w_e,UnfoldVertical:j_e,UnfoldVerticalIcon:j_e,Ungroup:N_e,UngroupIcon:N_e,University:KP,UniversityIcon:KP,Unlink:kD,Unlink2:k_e,Unlink2Icon:k_e,UnlinkIcon:kD,Unlock:NL,UnlockIcon:NL,UnlockKeyhole:jL,UnlockKeyholeIcon:jL,Unplug:S_e,UnplugIcon:S_e,Upload:ni,UploadCloud:tL,UploadCloudIcon:tL,UploadIcon:ni,Usb:C_e,UsbIcon:C_e,User:Ro,User2:eI,User2Icon:eI,UserCheck:tN,UserCheck2:YP,UserCheck2Icon:YP,UserCheckIcon:tN,UserCircle:XM,UserCircle2:ZM,UserCircle2Icon:ZM,UserCircleIcon:XM,UserCog:EW,UserCog2:ZP,UserCog2Icon:ZP,UserCogIcon:EW,UserIcon:Ro,UserMinus:MW,UserMinus2:XP,UserMinus2Icon:XP,UserMinusIcon:MW,UserPen:A_e,UserPenIcon:A_e,UserPlus:Yl,UserPlus2:QP,UserPlus2Icon:QP,UserPlusIcon:Yl,UserRound:eI,UserRoundCheck:YP,UserRoundCheckIcon:YP,UserRoundCog:ZP,UserRoundCogIcon:ZP,UserRoundIcon:eI,UserRoundMinus:XP,UserRoundMinusIcon:XP,UserRoundPen:T_e,UserRoundPenIcon:T_e,UserRoundPlus:QP,UserRoundPlusIcon:QP,UserRoundSearch:E_e,UserRoundSearchIcon:E_e,UserRoundX:JP,UserRoundXIcon:JP,UserSearch:M_e,UserSearchIcon:M_e,UserSquare:$P,UserSquare2:BP,UserSquare2Icon:BP,UserSquareIcon:$P,UserX:L_e,UserX2:JP,UserX2Icon:JP,UserXIcon:L_e,Users:Yn,Users2:f_,Users2Icon:f_,UsersIcon:Yn,UsersRound:f_,UsersRoundIcon:f_,Utensils:sI,UtensilsCrossed:tI,UtensilsCrossedIcon:tI,UtensilsIcon:sI,UtilityPole:P_e,UtilityPoleIcon:P_e,Variable:P9,VariableIcon:P9,Vault:I_e,VaultIcon:I_e,Vegan:D_e,VeganIcon:D_e,VenetianMask:R_e,VenetianMaskIcon:R_e,Verified:cM,VerifiedIcon:cM,Vibrate:F_e,VibrateIcon:F_e,VibrateOff:O_e,VibrateOffIcon:O_e,Video:na,VideoIcon:na,VideoOff:z_e,VideoOffIcon:z_e,Videotape:B_e,VideotapeIcon:B_e,View:$_e,ViewIcon:$_e,Voicemail:U_e,VoicemailIcon:U_e,Volleyball:q_e,VolleyballIcon:q_e,Volume:G_e,Volume1:V_e,Volume1Icon:V_e,Volume2:LW,Volume2Icon:LW,VolumeIcon:G_e,VolumeOff:H_e,VolumeOffIcon:H_e,VolumeX:PW,VolumeXIcon:PW,Vote:W_e,VoteIcon:W_e,Wallet:I9,Wallet2:nI,Wallet2Icon:nI,WalletCards:K_e,WalletCardsIcon:K_e,WalletIcon:I9,WalletMinimal:nI,WalletMinimalIcon:nI,Wallpaper:Y_e,WallpaperIcon:Y_e,Wand:Z_e,Wand2:Zg,Wand2Icon:Zg,WandIcon:Z_e,WandSparkles:Zg,WandSparklesIcon:Zg,Warehouse:X_e,WarehouseIcon:X_e,WashingMachine:Q_e,WashingMachineIcon:Q_e,Watch:J_e,WatchIcon:J_e,Waves:ewe,WavesIcon:ewe,Waypoints:twe,WaypointsIcon:twe,Webcam:swe,WebcamIcon:swe,Webhook:rwe,WebhookIcon:rwe,WebhookOff:nwe,WebhookOffIcon:nwe,Weight:awe,WeightIcon:awe,Wheat:owe,WheatIcon:owe,WheatOff:iwe,WheatOffIcon:iwe,WholeWord:lwe,WholeWordIcon:lwe,Wifi:mwe,WifiHigh:cwe,WifiHighIcon:cwe,WifiIcon:mwe,WifiLow:dwe,WifiLowIcon:dwe,WifiOff:uwe,WifiOffIcon:uwe,WifiZero:hwe,WifiZeroIcon:hwe,Wind:fwe,WindArrowDown:pwe,WindArrowDownIcon:pwe,WindIcon:fwe,Wine:IW,WineIcon:IW,WineOff:gwe,WineOffIcon:gwe,Workflow:DW,WorkflowIcon:DW,Worm:xwe,WormIcon:xwe,WrapText:ywe,WrapTextIcon:ywe,Wrench:sN,WrenchIcon:sN,X:hr,XCircle:Nu,XCircleIcon:Nu,XIcon:hr,XOctagon:AL,XOctagonIcon:AL,XSquare:UP,XSquareIcon:UP,Youtube:vwe,YoutubeIcon:vwe,Zap:ff,ZapIcon:ff,ZapOff:bwe,ZapOffIcon:bwe,ZoomIn:$T,ZoomInIcon:$T,ZoomOut:D9,ZoomOutIcon:D9,createLucideIcon:oe,icons:sYt},Symbol.toStringTag,{value:"Module"})),r$e="-",nYt=s=>{const t=aYt(s),{conflictingClassGroups:n,conflictingClassGroupModifiers:r}=s;return{getClassGroupId:l=>{const o=l.split(r$e);return o[0]===""&&o.length!==1&&o.shift(),ebt(o,t)||rYt(l)},getConflictingClassGroupIds:(l,o)=>{const c=n[l]||[];return o&&r[l]?[...c,...r[l]]:c}}},ebt=(s,t)=>{var l;if(s.length===0)return t.classGroupId;const n=s[0],r=t.nextPart.get(n),a=r?ebt(s.slice(1),r):void 0;if(a)return a;if(t.validators.length===0)return;const i=s.join(r$e);return(l=t.validators.find(({validator:o})=>o(i)))==null?void 0:l.classGroupId},Net=/^\[(.+)\]$/,rYt=s=>{if(Net.test(s)){const t=Net.exec(s)[1],n=t==null?void 0:t.substring(0,t.indexOf(":"));if(n)return"arbitrary.."+n}},aYt=s=>{const{theme:t,prefix:n}=s,r={nextPart:new Map,validators:[]};return oYt(Object.entries(s.classGroups),n).forEach(([i,l])=>{V8e(l,r,i,t)}),r},V8e=(s,t,n,r)=>{s.forEach(a=>{if(typeof a=="string"){const i=a===""?t:ket(t,a);i.classGroupId=n;return}if(typeof a=="function"){if(iYt(a)){V8e(a(r),t,n,r);return}t.validators.push({validator:a,classGroupId:n});return}Object.entries(a).forEach(([i,l])=>{V8e(l,ket(t,i),n,r)})})},ket=(s,t)=>{let n=s;return t.split(r$e).forEach(r=>{n.nextPart.has(r)||n.nextPart.set(r,{nextPart:new Map,validators:[]}),n=n.nextPart.get(r)}),n},iYt=s=>s.isThemeGetter,oYt=(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,lYt=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)}}},tbt="!",cYt=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 x=0;xu?h-u:void 0;return{modifiers:c,hasImportantModifier:f,baseClassName:g,maybePostfixModifierPosition:y}};return n?o=>n({className:o,parseClassName:l}):l},dYt=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},uYt=s=>({cache:lYt(s.cacheSize),parseClassName:cYt(s),...nYt(s)}),hYt=/\s+/,mYt=(s,t)=>{const{parseClassName:n,getClassGroupId:r,getConflictingClassGroupIds:a}=t,i=[],l=s.trim().split(hYt);let o="";for(let c=l.length-1;c>=0;c-=1){const d=l[c],{modifiers:u,hasImportantModifier:h,baseClassName:m,maybePostfixModifierPosition:f}=n(d);let g=!!f,y=r(g?m.substring(0,f):m);if(!y){if(!g){o=d+(o.length>0?" "+o:o);continue}if(y=r(m),!y){o=d+(o.length>0?" "+o:o);continue}g=!1}const x=dYt(u).join(":"),_=h?x+tbt:x,b=_+y;if(i.includes(b))continue;i.push(b);const k=a(y,g);for(let A=0;A0?" "+o:o)}return o};function pYt(){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=uYt(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=mYt(c,n);return a(c,u),u}return function(){return i(pYt.apply(null,arguments))}}const Jh=s=>{const t=n=>n[s]||[];return t.isThemeGetter=!0,t},nbt=/^\[(?:([a-z-]+):)?(.+)\]$/i,gYt=/^\d+\/\d+$/,xYt=new Set(["px","full","screen"]),yYt=/^(\d+(\.\d+)?)?(xs|sm|md|lg|xl)$/,vYt=/\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$/,bYt=/^(rgba?|hsla?|hwb|(ok)?(lab|lch))\(.+\)$/,_Yt=/^(inset_)?-?((\d+)?\.?(\d+)[a-z]+|0)_-?((\d+)?\.?(\d+)[a-z]+|0)/,wYt=/^(url|image|image-set|cross-fade|element|(repeating-)?(linear|radial|conic)-gradient)\(.+\)$/,ES=s=>R9(s)||xYt.has(s)||gYt.test(s),fC=s=>Z$(s,"length",EYt),R9=s=>!!s&&!Number.isNaN(Number(s)),r6e=s=>Z$(s,"number",R9),bV=s=>!!s&&Number.isInteger(Number(s)),jYt=s=>s.endsWith("%")&&R9(s.slice(0,-1)),Jl=s=>nbt.test(s),gC=s=>yYt.test(s),NYt=new Set(["length","size","percentage"]),kYt=s=>Z$(s,NYt,rbt),SYt=s=>Z$(s,"position",rbt),CYt=new Set(["image","url"]),AYt=s=>Z$(s,CYt,LYt),TYt=s=>Z$(s,"",MYt),_V=()=>!0,Z$=(s,t,n)=>{const r=nbt.exec(s);return r?r[1]?typeof t=="string"?r[1]===t:t.has(r[1]):n(r[2]):!1},EYt=s=>vYt.test(s)&&!bYt.test(s),rbt=()=>!1,MYt=s=>_Yt.test(s),LYt=s=>wYt.test(s),PYt=()=>{const s=Jh("colors"),t=Jh("spacing"),n=Jh("blur"),r=Jh("brightness"),a=Jh("borderColor"),i=Jh("borderRadius"),l=Jh("borderSpacing"),o=Jh("borderWidth"),c=Jh("contrast"),d=Jh("grayscale"),u=Jh("hueRotate"),h=Jh("invert"),m=Jh("gap"),f=Jh("gradientColorStops"),g=Jh("gradientColorStopPositions"),y=Jh("inset"),x=Jh("margin"),_=Jh("opacity"),b=Jh("padding"),k=Jh("saturate"),A=Jh("scale"),T=Jh("sepia"),P=Jh("skew"),I=Jh("space"),M=Jh("translate"),L=()=>["auto","contain","none"],z=()=>["auto","hidden","clip","visible","scroll"],$=()=>["auto",Jl,t],V=()=>[Jl,t],W=()=>["",ES,fC],G=()=>["auto",R9,Jl],X=()=>["bottom","center","left","left-bottom","left-top","right","right-bottom","right-top","top"],te=()=>["solid","dashed","dotted","double","none"],ne=()=>["normal","multiply","screen","overlay","darken","lighten","color-dodge","color-burn","hard-light","soft-light","difference","exclusion","hue","saturation","color","luminosity"],me=()=>["start","end","center","between","around","evenly","stretch"],ue=()=>["","0",Jl],ce=()=>["auto","avoid","all","avoid-page","page","left","right","column"],ae=()=>[R9,Jl];return{cacheSize:500,separator:":",theme:{colors:[_V],spacing:[ES,fC],blur:["none","",gC,Jl],brightness:ae(),borderColor:[s],borderRadius:["none","","full",gC,Jl],borderSpacing:V(),borderWidth:W(),contrast:ae(),grayscale:ue(),hueRotate:ae(),invert:ue(),gap:V(),gradientColorStops:[s],gradientColorStopPositions:[jYt,fC],inset:$(),margin:$(),opacity:ae(),padding:V(),saturate:ae(),scale:ae(),sepia:ue(),skew:ae(),space:V(),translate:V()},classGroups:{aspect:[{aspect:["auto","square","video",Jl]}],container:["container"],columns:[{columns:[gC]}],"break-after":[{"break-after":ce()}],"break-before":[{"break-before":ce()}],"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:[...X(),Jl]}],overflow:[{overflow:z()}],"overflow-x":[{"overflow-x":z()}],"overflow-y":[{"overflow-y":z()}],overscroll:[{overscroll:L()}],"overscroll-x":[{"overscroll-x":L()}],"overscroll-y":[{"overscroll-y":L()}],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",bV,Jl]}],basis:[{basis:$()}],"flex-direction":[{flex:["row","row-reverse","col","col-reverse"]}],"flex-wrap":[{flex:["wrap","wrap-reverse","nowrap"]}],flex:[{flex:["1","auto","initial","none",Jl]}],grow:[{grow:ue()}],shrink:[{shrink:ue()}],order:[{order:["first","last","none",bV,Jl]}],"grid-cols":[{"grid-cols":[_V]}],"col-start-end":[{col:["auto",{span:["full",bV,Jl]},Jl]}],"col-start":[{"col-start":G()}],"col-end":[{"col-end":G()}],"grid-rows":[{"grid-rows":[_V]}],"row-start-end":[{row:["auto",{span:[bV,Jl]},Jl]}],"row-start":[{"row-start":G()}],"row-end":[{"row-end":G()}],"grid-flow":[{"grid-flow":["row","col","dense","row-dense","col-dense"]}],"auto-cols":[{"auto-cols":["auto","min","max","fr",Jl]}],"auto-rows":[{"auto-rows":["auto","min","max","fr",Jl]}],gap:[{gap:[m]}],"gap-x":[{"gap-x":[m]}],"gap-y":[{"gap-y":[m]}],"justify-content":[{justify:["normal",...me()]}],"justify-items":[{"justify-items":["start","end","center","stretch"]}],"justify-self":[{"justify-self":["auto","start","end","center","stretch"]}],"align-content":[{content:["normal",...me(),"baseline"]}],"align-items":[{items:["start","end","center","baseline","stretch"]}],"align-self":[{self:["auto","start","end","center","stretch","baseline"]}],"place-content":[{"place-content":[...me(),"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:[x]}],mx:[{mx:[x]}],my:[{my:[x]}],ms:[{ms:[x]}],me:[{me:[x]}],mt:[{mt:[x]}],mr:[{mr:[x]}],mb:[{mb:[x]}],ml:[{ml:[x]}],"space-x":[{"space-x":[I]}],"space-x-reverse":["space-x-reverse"],"space-y":[{"space-y":[I]}],"space-y-reverse":["space-y-reverse"],w:[{w:["auto","min","max","fit","svw","lvw","dvw",Jl,t]}],"min-w":[{"min-w":[Jl,t,"min","max","fit"]}],"max-w":[{"max-w":[Jl,t,"none","full","min","max","fit","prose",{screen:[gC]},gC]}],h:[{h:[Jl,t,"auto","min","max","fit","svh","lvh","dvh"]}],"min-h":[{"min-h":[Jl,t,"min","max","fit","svh","lvh","dvh"]}],"max-h":[{"max-h":[Jl,t,"min","max","fit","svh","lvh","dvh"]}],size:[{size:[Jl,t,"auto","min","max","fit"]}],"font-size":[{text:["base",gC,fC]}],"font-smoothing":["antialiased","subpixel-antialiased"],"font-style":["italic","not-italic"],"font-weight":[{font:["thin","extralight","light","normal","medium","semibold","bold","extrabold","black",r6e]}],"font-family":[{font:[_V]}],"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",Jl]}],"line-clamp":[{"line-clamp":["none",R9,r6e]}],leading:[{leading:["none","tight","snug","normal","relaxed","loose",ES,Jl]}],"list-image":[{"list-image":["none",Jl]}],"list-style-type":[{list:["none","disc","decimal",Jl]}],"list-style-position":[{list:["inside","outside"]}],"placeholder-color":[{placeholder:[s]}],"placeholder-opacity":[{"placeholder-opacity":[_]}],"text-alignment":[{text:["left","center","right","justify","start","end"]}],"text-color":[{text:[s]}],"text-opacity":[{"text-opacity":[_]}],"text-decoration":["underline","overline","line-through","no-underline"],"text-decoration-style":[{decoration:[...te(),"wavy"]}],"text-decoration-thickness":[{decoration:["auto","from-font",ES,fC]}],"underline-offset":[{"underline-offset":["auto",ES,Jl]}],"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",Jl]}],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",Jl]}],"bg-attachment":[{bg:["fixed","local","scroll"]}],"bg-clip":[{"bg-clip":["border","padding","content","text"]}],"bg-opacity":[{"bg-opacity":[_]}],"bg-origin":[{"bg-origin":["border","padding","content"]}],"bg-position":[{bg:[...X(),SYt]}],"bg-repeat":[{bg:["no-repeat",{repeat:["","x","y","round","space"]}]}],"bg-size":[{bg:["auto","cover","contain",kYt]}],"bg-image":[{bg:["none",{"gradient-to":["t","tr","r","br","b","bl","l","tl"]},AYt]}],"bg-color":[{bg:[s]}],"gradient-from-pos":[{from:[g]}],"gradient-via-pos":[{via:[g]}],"gradient-to-pos":[{to:[g]}],"gradient-from":[{from:[f]}],"gradient-via":[{via:[f]}],"gradient-to":[{to:[f]}],rounded:[{rounded:[i]}],"rounded-s":[{"rounded-s":[i]}],"rounded-e":[{"rounded-e":[i]}],"rounded-t":[{"rounded-t":[i]}],"rounded-r":[{"rounded-r":[i]}],"rounded-b":[{"rounded-b":[i]}],"rounded-l":[{"rounded-l":[i]}],"rounded-ss":[{"rounded-ss":[i]}],"rounded-se":[{"rounded-se":[i]}],"rounded-ee":[{"rounded-ee":[i]}],"rounded-es":[{"rounded-es":[i]}],"rounded-tl":[{"rounded-tl":[i]}],"rounded-tr":[{"rounded-tr":[i]}],"rounded-br":[{"rounded-br":[i]}],"rounded-bl":[{"rounded-bl":[i]}],"border-w":[{border:[o]}],"border-w-x":[{"border-x":[o]}],"border-w-y":[{"border-y":[o]}],"border-w-s":[{"border-s":[o]}],"border-w-e":[{"border-e":[o]}],"border-w-t":[{"border-t":[o]}],"border-w-r":[{"border-r":[o]}],"border-w-b":[{"border-b":[o]}],"border-w-l":[{"border-l":[o]}],"border-opacity":[{"border-opacity":[_]}],"border-style":[{border:[...te(),"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":[_]}],"divide-style":[{divide:te()}],"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:["",...te()]}],"outline-offset":[{"outline-offset":[ES,Jl]}],"outline-w":[{outline:[ES,fC]}],"outline-color":[{outline:[s]}],"ring-w":[{ring:W()}],"ring-w-inset":["ring-inset"],"ring-color":[{ring:[s]}],"ring-opacity":[{"ring-opacity":[_]}],"ring-offset-w":[{"ring-offset":[ES,fC]}],"ring-offset-color":[{"ring-offset":[s]}],shadow:[{shadow:["","inner","none",gC,TYt]}],"shadow-color":[{shadow:[_V]}],opacity:[{opacity:[_]}],"mix-blend":[{"mix-blend":[...ne(),"plus-lighter","plus-darker"]}],"bg-blend":[{"bg-blend":ne()}],filter:[{filter:["","none"]}],blur:[{blur:[n]}],brightness:[{brightness:[r]}],contrast:[{contrast:[c]}],"drop-shadow":[{"drop-shadow":["","none",gC,Jl]}],grayscale:[{grayscale:[d]}],"hue-rotate":[{"hue-rotate":[u]}],invert:[{invert:[h]}],saturate:[{saturate:[k]}],sepia:[{sepia:[T]}],"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":[_]}],"backdrop-saturate":[{"backdrop-saturate":[k]}],"backdrop-sepia":[{"backdrop-sepia":[T]}],"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",Jl]}],duration:[{duration:ae()}],ease:[{ease:["linear","in","out","in-out",Jl]}],delay:[{delay:ae()}],animate:[{animate:["none","spin","ping","pulse","bounce",Jl]}],transform:[{transform:["","gpu","none"]}],scale:[{scale:[A]}],"scale-x":[{"scale-x":[A]}],"scale-y":[{"scale-y":[A]}],rotate:[{rotate:[bV,Jl]}],"translate-x":[{"translate-x":[M]}],"translate-y":[{"translate-y":[M]}],"skew-x":[{"skew-x":[P]}],"skew-y":[{"skew-y":[P]}],"transform-origin":[{origin:["center","top","top-right","right","bottom-right","bottom","bottom-left","left","top-left",Jl]}],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",Jl]}],"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",Jl]}],fill:[{fill:[s,"none"]}],"stroke-w":[{stroke:[ES,fC,r6e]}],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"]}}},IYt=fYt(PYt);function Ot(...s){return IYt(Ol(s))}function _u(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 Cet(s){const t=new Date(s);return new Intl.DateTimeFormat("en-US",{month:"short",day:"numeric",year:"numeric"}).format(t)}function eY(s){return s?s.replace(/<[^>]*>/g,""):""}const DYt=JKt,abt=N.forwardRef(({className:s,...t},n)=>e.jsx(H1t,{ref:n,className:Ot("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}));abt.displayName=H1t.displayName;const RYt=RR("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"}}),ibt=N.forwardRef(({className:s,variant:t,...n},r)=>e.jsx(G1t,{ref:r,className:Ot(RYt({variant:t}),s),...n}));ibt.displayName=G1t.displayName;const OYt=N.forwardRef(({className:s,...t},n)=>e.jsx(Y1t,{ref:n,className:Ot("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}));OYt.displayName=Y1t.displayName;const obt=N.forwardRef(({className:s,...t},n)=>e.jsx(Z1t,{ref:n,className:Ot("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(hr,{className:"h-4 w-4"})}));obt.displayName=Z1t.displayName;const lbt=N.forwardRef(({className:s,...t},n)=>e.jsx(W1t,{ref:n,className:Ot("text-sm font-semibold",s),...t}));lbt.displayName=W1t.displayName;const cbt=N.forwardRef(({className:s,...t},n)=>e.jsx(K1t,{ref:n,className:Ot("text-sm opacity-90",s),...t}));cbt.displayName=K1t.displayName;function FYt(){const{toasts:s}=Ci();return e.jsxs(DYt,{children:[s.map(function({id:t,title:n,description:r,action:a,...i}){return e.jsxs(ibt,{...i,children:[e.jsxs("div",{className:"grid gap-1",children:[n&&e.jsx(lbt,{children:n}),r&&e.jsx(cbt,{children:r})]}),a,e.jsx(obt,{})]},t)}),e.jsx(abt,{})]})}var Aet=["light","dark"],zYt="(prefers-color-scheme: dark)",BYt=N.createContext(void 0),$Yt={setTheme:s=>{},themes:[]},UYt=()=>{var s;return(s=N.useContext(BYt))!=null?s:$Yt};N.memo(({forcedTheme:s,storageKey:t,attribute:n,enableSystem:r,enableColorScheme:a,defaultTheme:i,value:l,attrs:o,nonce:c})=>{let d=i==="system",u=n==="class"?`var d=document.documentElement,c=d.classList;${`c.remove(${o.map(g=>`'${g}'`).join(",")})`};`:`var d=document.documentElement,n='${n}',s='setAttribute';`,h=a?Aet.includes(i)&&i?`if(e==='light'||e==='dark'||!e)d.style.colorScheme=e||'${i}'`:"if(e==='light'||e==='dark')d.style.colorScheme=e":"",m=(g,y=!1,x=!0)=>{let _=l?l[g]:g,b=y?g+"|| ''":`'${_}'`,k="";return a&&x&&!y&&Aet.includes(g)&&(k+=`d.style.colorScheme = '${g}';`),n==="class"?y||_?k+=`c.add(${b})`:k+="null":_&&(k+=`d[s](n,${b})`),k},f=s?`!function(){${u}${m(s)}}()`:r?`!function(){try{${u}var e=localStorage.getItem('${t}');if('system'===e||(!e&&${d})){var t='${zYt}',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 N.createElement("script",{nonce:c,dangerouslySetInnerHTML:{__html:f}})});var qYt=s=>{switch(s){case"success":return GYt;case"info":return KYt;case"warning":return WYt;case"error":return YYt;default:return null}},VYt=Array(12).fill(0),HYt=({visible:s,className:t})=>Rt.createElement("div",{className:["sonner-loading-wrapper",t].filter(Boolean).join(" "),"data-visible":s},Rt.createElement("div",{className:"sonner-spinner"},VYt.map((n,r)=>Rt.createElement("div",{className:"sonner-loading-bar",key:`spinner-bar-${r}`})))),GYt=Rt.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 20 20",fill:"currentColor",height:"20",width:"20"},Rt.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"})),WYt=Rt.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",fill:"currentColor",height:"20",width:"20"},Rt.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"})),KYt=Rt.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 20 20",fill:"currentColor",height:"20",width:"20"},Rt.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"})),YYt=Rt.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 20 20",fill:"currentColor",height:"20",width:"20"},Rt.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"})),ZYt=Rt.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"},Rt.createElement("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),Rt.createElement("line",{x1:"6",y1:"6",x2:"18",y2:"18"})),XYt=()=>{let[s,t]=Rt.useState(document.hidden);return Rt.useEffect(()=>{let n=()=>{t(document.hidden)};return document.addEventListener("visibilitychange",n),()=>window.removeEventListener("visibilitychange",n)},[]),s},H8e=1,QYt=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:H8e++,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],Rt.isValidElement(d))i=!1,this.create({id:r,type:"default",message:d});else if(eZt(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)||H8e++;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}},B1=new QYt,JYt=(s,t)=>{let n=(t==null?void 0:t.id)||H8e++;return B1.addToast({title:s,...t,id:n}),n},eZt=s=>s&&typeof s=="object"&&"ok"in s&&typeof s.ok=="boolean"&&"status"in s&&typeof s.status=="number",tZt=JYt,sZt=()=>B1.toasts,nZt=()=>B1.getActiveToasts(),ie=Object.assign(tZt,{success:B1.success,info:B1.info,warning:B1.warning,error:B1.error,custom:B1.custom,message:B1.message,promise:B1.promise,dismiss:B1.dismiss,loading:B1.loading},{getHistory:sZt,getToasts:nZt});function rZt(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))}rZt(`: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 kte(s){return s.label!==void 0}var aZt=3,iZt="32px",oZt="16px",Tet=4e3,lZt=356,cZt=14,dZt=20,uZt=200;function s2(...s){return s.filter(Boolean).join(" ")}function hZt(s){let[t,n]=s.split("-"),r=[];return t&&r.push(t),n&&r.push(n),r}var mZt=s=>{var t,n,r,a,i,l,o,c,d,u,h;let{invert:m,toast:f,unstyled:g,interacting:y,setHeights:x,visibleToasts:_,heights:b,index:k,toasts:A,expanded:T,removeToast:P,defaultRichColors:I,closeButton:M,style:L,cancelButtonStyle:z,actionButtonStyle:$,className:V="",descriptionClassName:W="",duration:G,position:X,gap:te,loadingIcon:ne,expandByDefault:me,classNames:ue,icons:ce,closeButtonAriaLabel:ae="Close toast",pauseWhenPageIsHidden:he}=s,[xe,ve]=Rt.useState(null),[ge,be]=Rt.useState(null),[Se,Ie]=Rt.useState(!1),[Me,Re]=Rt.useState(!1),[Be,Ne]=Rt.useState(!1),[Ge,Ce]=Rt.useState(!1),[Fe,Ae]=Rt.useState(!1),[Xe,$e]=Rt.useState(0),[Ye,Je]=Rt.useState(0),Ke=Rt.useRef(f.duration||G||Tet),st=Rt.useRef(null),rt=Rt.useRef(null),Ze=k===0,ht=k+1<=_,Bt=f.type,Ct=f.dismissible!==!1,Yt=f.className||"",Kt=f.descriptionClassName||"",Xs=Rt.useMemo(()=>b.findIndex(Bn=>Bn.toastId===f.id)||0,[b,f.id]),zs=Rt.useMemo(()=>{var Bn;return(Bn=f.closeButton)!=null?Bn:M},[f.closeButton,M]),Vt=Rt.useMemo(()=>f.duration||G||Tet,[f.duration,G]),At=Rt.useRef(0),Os=Rt.useRef(0),Nt=Rt.useRef(0),ms=Rt.useRef(null),[Ys,It]=X.split("-"),Ds=Rt.useMemo(()=>b.reduce((Bn,Dn,Jn)=>Jn>=Xs?Bn:Bn+Dn.height,0),[b,Xs]),As=XYt(),Hs=f.invert||m,Rs=Bt==="loading";Os.current=Rt.useMemo(()=>Xs*te+Ds,[Xs,Ds]),Rt.useEffect(()=>{Ke.current=Vt},[Vt]),Rt.useEffect(()=>{Ie(!0)},[]),Rt.useEffect(()=>{let Bn=rt.current;if(Bn){let Dn=Bn.getBoundingClientRect().height;return Je(Dn),x(Jn=>[{toastId:f.id,height:Dn,position:f.position},...Jn]),()=>x(Jn=>Jn.filter(ua=>ua.toastId!==f.id))}},[x,f.id]),Rt.useLayoutEffect(()=>{if(!Se)return;let Bn=rt.current,Dn=Bn.style.height;Bn.style.height="auto";let Jn=Bn.getBoundingClientRect().height;Bn.style.height=Dn,Je(Jn),x(ua=>ua.find(Mr=>Mr.toastId===f.id)?ua.map(Mr=>Mr.toastId===f.id?{...Mr,height:Jn}:Mr):[{toastId:f.id,height:Jn,position:f.position},...ua])},[Se,f.title,f.description,x,f.id]);let en=Rt.useCallback(()=>{Re(!0),$e(Os.current),x(Bn=>Bn.filter(Dn=>Dn.toastId!==f.id)),setTimeout(()=>{P(f)},uZt)},[f,P,x,Os]);Rt.useEffect(()=>{if(f.promise&&Bt==="loading"||f.duration===1/0||f.type==="loading")return;let Bn;return T||y||he&&As?(()=>{if(Nt.current{var Dn;(Dn=f.onAutoClose)==null||Dn.call(f,f),en()},Ke.current)),()=>clearTimeout(Bn)},[T,y,f,Bt,he,As,en]),Rt.useEffect(()=>{f.delete&&en()},[en,f.delete]);function Rn(){var Bn,Dn,Jn;return ce!=null&&ce.loading?Rt.createElement("div",{className:s2(ue==null?void 0:ue.loader,(Bn=f==null?void 0:f.classNames)==null?void 0:Bn.loader,"sonner-loader"),"data-visible":Bt==="loading"},ce.loading):ne?Rt.createElement("div",{className:s2(ue==null?void 0:ue.loader,(Dn=f==null?void 0:f.classNames)==null?void 0:Dn.loader,"sonner-loader"),"data-visible":Bt==="loading"},ne):Rt.createElement(HYt,{className:s2(ue==null?void 0:ue.loader,(Jn=f==null?void 0:f.classNames)==null?void 0:Jn.loader),visible:Bt==="loading"})}return Rt.createElement("li",{tabIndex:0,ref:rt,className:s2(V,Yt,ue==null?void 0:ue.toast,(t=f==null?void 0:f.classNames)==null?void 0:t.toast,ue==null?void 0:ue.default,ue==null?void 0:ue[Bt],(n=f==null?void 0:f.classNames)==null?void 0:n[Bt]),"data-sonner-toast":"","data-rich-colors":(r=f.richColors)!=null?r:I,"data-styled":!(f.jsx||f.unstyled||g),"data-mounted":Se,"data-promise":!!f.promise,"data-swiped":Fe,"data-removed":Me,"data-visible":ht,"data-y-position":Ys,"data-x-position":It,"data-index":k,"data-front":Ze,"data-swiping":Be,"data-dismissible":Ct,"data-type":Bt,"data-invert":Hs,"data-swipe-out":Ge,"data-swipe-direction":ge,"data-expanded":!!(T||me&&Se),style:{"--index":k,"--toasts-before":k,"--z-index":A.length-k,"--offset":`${Me?Xe:Os.current}px`,"--initial-height":me?"auto":`${Ye}px`,...L,...f.style},onDragEnd:()=>{Ne(!1),ve(null),ms.current=null},onPointerDown:Bn=>{Rs||!Ct||(st.current=new Date,$e(Os.current),Bn.target.setPointerCapture(Bn.pointerId),Bn.target.tagName!=="BUTTON"&&(Ne(!0),ms.current={x:Bn.clientX,y:Bn.clientY}))},onPointerUp:()=>{var Bn,Dn,Jn,ua;if(Ge||!Ct)return;ms.current=null;let Mr=Number(((Bn=rt.current)==null?void 0:Bn.style.getPropertyValue("--swipe-amount-x").replace("px",""))||0),sn=Number(((Dn=rt.current)==null?void 0:Dn.style.getPropertyValue("--swipe-amount-y").replace("px",""))||0),ki=new Date().getTime()-((Jn=st.current)==null?void 0:Jn.getTime()),ia=xe==="x"?Mr:sn,vr=Math.abs(ia)/ki;if(Math.abs(ia)>=dZt||vr>.11){$e(Os.current),(ua=f.onDismiss)==null||ua.call(f,f),be(xe==="x"?Mr>0?"right":"left":sn>0?"down":"up"),en(),Ce(!0),Ae(!1);return}Ne(!1),ve(null)},onPointerMove:Bn=>{var Dn,Jn,ua,Mr;if(!ms.current||!Ct||((Dn=window.getSelection())==null?void 0:Dn.toString().length)>0)return;let sn=Bn.clientY-ms.current.y,ki=Bn.clientX-ms.current.x,ia=(Jn=s.swipeDirections)!=null?Jn:hZt(X);!xe&&(Math.abs(ki)>1||Math.abs(sn)>1)&&ve(Math.abs(ki)>Math.abs(sn)?"x":"y");let vr={x:0,y:0};xe==="y"?(ia.includes("top")||ia.includes("bottom"))&&(ia.includes("top")&&sn<0||ia.includes("bottom")&&sn>0)&&(vr.y=sn):xe==="x"&&(ia.includes("left")||ia.includes("right"))&&(ia.includes("left")&&ki<0||ia.includes("right")&&ki>0)&&(vr.x=ki),(Math.abs(vr.x)>0||Math.abs(vr.y)>0)&&Ae(!0),(ua=rt.current)==null||ua.style.setProperty("--swipe-amount-x",`${vr.x}px`),(Mr=rt.current)==null||Mr.style.setProperty("--swipe-amount-y",`${vr.y}px`)}},zs&&!f.jsx?Rt.createElement("button",{"aria-label":ae,"data-disabled":Rs,"data-close-button":!0,onClick:Rs||!Ct?()=>{}:()=>{var Bn;en(),(Bn=f.onDismiss)==null||Bn.call(f,f)},className:s2(ue==null?void 0:ue.closeButton,(a=f==null?void 0:f.classNames)==null?void 0:a.closeButton)},(i=ce==null?void 0:ce.close)!=null?i:ZYt):null,f.jsx||N.isValidElement(f.title)?f.jsx?f.jsx:typeof f.title=="function"?f.title():f.title:Rt.createElement(Rt.Fragment,null,Bt||f.icon||f.promise?Rt.createElement("div",{"data-icon":"",className:s2(ue==null?void 0:ue.icon,(l=f==null?void 0:f.classNames)==null?void 0:l.icon)},f.promise||f.type==="loading"&&!f.icon?f.icon||Rn():null,f.type!=="loading"?f.icon||(ce==null?void 0:ce[Bt])||qYt(Bt):null):null,Rt.createElement("div",{"data-content":"",className:s2(ue==null?void 0:ue.content,(o=f==null?void 0:f.classNames)==null?void 0:o.content)},Rt.createElement("div",{"data-title":"",className:s2(ue==null?void 0:ue.title,(c=f==null?void 0:f.classNames)==null?void 0:c.title)},typeof f.title=="function"?f.title():f.title),f.description?Rt.createElement("div",{"data-description":"",className:s2(W,Kt,ue==null?void 0:ue.description,(d=f==null?void 0:f.classNames)==null?void 0:d.description)},typeof f.description=="function"?f.description():f.description):null),N.isValidElement(f.cancel)?f.cancel:f.cancel&&kte(f.cancel)?Rt.createElement("button",{"data-button":!0,"data-cancel":!0,style:f.cancelButtonStyle||z,onClick:Bn=>{var Dn,Jn;kte(f.cancel)&&Ct&&((Jn=(Dn=f.cancel).onClick)==null||Jn.call(Dn,Bn),en())},className:s2(ue==null?void 0:ue.cancelButton,(u=f==null?void 0:f.classNames)==null?void 0:u.cancelButton)},f.cancel.label):null,N.isValidElement(f.action)?f.action:f.action&&kte(f.action)?Rt.createElement("button",{"data-button":!0,"data-action":!0,style:f.actionButtonStyle||$,onClick:Bn=>{var Dn,Jn;kte(f.action)&&((Jn=(Dn=f.action).onClick)==null||Jn.call(Dn,Bn),!Bn.defaultPrevented&&en())},className:s2(ue==null?void 0:ue.actionButton,(h=f==null?void 0:f.classNames)==null?void 0:h.actionButton)},f.action.label):null))};function Eet(){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 pZt(s,t){let n={};return[s,t].forEach((r,a)=>{let i=a===1,l=i?"--mobile-offset":"--offset",o=i?oZt:iZt;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 fZt=N.forwardRef(function(s,t){let{invert:n,position:r="bottom-right",hotkey:a=["altKey","KeyT"],expand:i,closeButton:l,className:o,offset:c,mobileOffset:d,theme:u="light",richColors:h,duration:m,style:f,visibleToasts:g=aZt,toastOptions:y,dir:x=Eet(),gap:_=cZt,loadingIcon:b,icons:k,containerAriaLabel:A="Notifications",pauseWhenPageIsHidden:T}=s,[P,I]=Rt.useState([]),M=Rt.useMemo(()=>Array.from(new Set([r].concat(P.filter(he=>he.position).map(he=>he.position)))),[P,r]),[L,z]=Rt.useState([]),[$,V]=Rt.useState(!1),[W,G]=Rt.useState(!1),[X,te]=Rt.useState(u!=="system"?u:typeof window<"u"&&window.matchMedia&&window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light"),ne=Rt.useRef(null),me=a.join("+").replace(/Key/g,"").replace(/Digit/g,""),ue=Rt.useRef(null),ce=Rt.useRef(!1),ae=Rt.useCallback(he=>{I(xe=>{var ve;return(ve=xe.find(ge=>ge.id===he.id))!=null&&ve.delete||B1.dismiss(he.id),xe.filter(({id:ge})=>ge!==he.id)})},[]);return Rt.useEffect(()=>B1.subscribe(he=>{if(he.dismiss){I(xe=>xe.map(ve=>ve.id===he.id?{...ve,delete:!0}:ve));return}setTimeout(()=>{QBe.flushSync(()=>{I(xe=>{let ve=xe.findIndex(ge=>ge.id===he.id);return ve!==-1?[...xe.slice(0,ve),{...xe[ve],...he},...xe.slice(ve+1)]:[he,...xe]})})})}),[]),Rt.useEffect(()=>{if(u!=="system"){te(u);return}if(u==="system"&&(window.matchMedia&&window.matchMedia("(prefers-color-scheme: dark)").matches?te("dark"):te("light")),typeof window>"u")return;let he=window.matchMedia("(prefers-color-scheme: dark)");try{he.addEventListener("change",({matches:xe})=>{te(xe?"dark":"light")})}catch{he.addListener(({matches:ve})=>{try{te(ve?"dark":"light")}catch(ge){console.error(ge)}})}},[u]),Rt.useEffect(()=>{P.length<=1&&V(!1)},[P]),Rt.useEffect(()=>{let he=xe=>{var ve,ge;a.every(be=>xe[be]||xe.code===be)&&(V(!0),(ve=ne.current)==null||ve.focus()),xe.code==="Escape"&&(document.activeElement===ne.current||(ge=ne.current)!=null&&ge.contains(document.activeElement))&&V(!1)};return document.addEventListener("keydown",he),()=>document.removeEventListener("keydown",he)},[a]),Rt.useEffect(()=>{if(ne.current)return()=>{ue.current&&(ue.current.focus({preventScroll:!0}),ue.current=null,ce.current=!1)}},[ne.current]),Rt.createElement("section",{ref:t,"aria-label":`${A} ${me}`,tabIndex:-1,"aria-live":"polite","aria-relevant":"additions text","aria-atomic":"false",suppressHydrationWarning:!0},M.map((he,xe)=>{var ve;let[ge,be]=he.split("-");return P.length?Rt.createElement("ol",{key:he,dir:x==="auto"?Eet():x,tabIndex:-1,ref:ne,className:o,"data-sonner-toaster":!0,"data-theme":X,"data-y-position":ge,"data-lifted":$&&P.length>1&&!i,"data-x-position":be,style:{"--front-toast-height":`${((ve=L[0])==null?void 0:ve.height)||0}px`,"--width":`${lZt}px`,"--gap":`${_}px`,...f,...pZt(c,d)},onBlur:Se=>{ce.current&&!Se.currentTarget.contains(Se.relatedTarget)&&(ce.current=!1,ue.current&&(ue.current.focus({preventScroll:!0}),ue.current=null))},onFocus:Se=>{Se.target instanceof HTMLElement&&Se.target.dataset.dismissible==="false"||ce.current||(ce.current=!0,ue.current=Se.relatedTarget)},onMouseEnter:()=>V(!0),onMouseMove:()=>V(!0),onMouseLeave:()=>{W||V(!1)},onDragEnd:()=>V(!1),onPointerDown:Se=>{Se.target instanceof HTMLElement&&Se.target.dataset.dismissible==="false"||G(!0)},onPointerUp:()=>G(!1)},P.filter(Se=>!Se.position&&xe===0||Se.position===he).map((Se,Ie)=>{var Me,Re;return Rt.createElement(mZt,{key:Se.id,icons:k,index:Ie,toast:Se,defaultRichColors:h,duration:(Me=y==null?void 0:y.duration)!=null?Me:m,className:y==null?void 0:y.className,descriptionClassName:y==null?void 0:y.descriptionClassName,invert:n,visibleToasts:g,closeButton:(Re=y==null?void 0:y.closeButton)!=null?Re:l,interacting:W,position:he,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:ae,toasts:P.filter(Be=>Be.position==Se.position),heights:L.filter(Be=>Be.position==Se.position),setHeights:z,expandByDefault:i,gap:_,loadingIcon:b,expanded:$,pauseWhenPageIsHidden:T,swipeDirections:s.swipeDirections})})):null}))});const gZt=({...s})=>{const{theme:t="system"}=UYt();return e.jsx(fZt,{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 xZt=oBe[" useId ".trim().toString()]||(()=>{}),yZt=0;function _g(s){const[t,n]=N.useState(xZt());return gf(()=>{s||n(r=>r??String(yZt++))},[s]),s||(t?`radix-${t}`:"")}const vZt=["top","right","bottom","left"],aE=Math.min,g_=Math.max,N2e=Math.round,Ste=Math.floor,iE=s=>({x:s,y:s}),bZt={left:"right",right:"left",bottom:"top",top:"bottom"},_Zt={start:"end",end:"start"};function G8e(s,t,n){return g_(s,aE(t,n))}function N3(s,t){return typeof s=="function"?s(t):s}function k3(s){return s.split("-")[0]}function X$(s){return s.split("-")[1]}function a$e(s){return s==="x"?"y":"x"}function i$e(s){return s==="y"?"height":"width"}function oE(s){return["top","bottom"].includes(k3(s))?"y":"x"}function o$e(s){return a$e(oE(s))}function wZt(s,t,n){n===void 0&&(n=!1);const r=X$(s),a=o$e(s),i=i$e(a);let l=a==="x"?r===(n?"end":"start")?"right":"left":r==="start"?"bottom":"top";return t.reference[i]>t.floating[i]&&(l=k2e(l)),[l,k2e(l)]}function jZt(s){const t=k2e(s);return[W8e(s),t,W8e(t)]}function W8e(s){return s.replace(/start|end/g,t=>_Zt[t])}function NZt(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 kZt(s,t,n,r){const a=X$(s);let i=NZt(k3(s),n==="start",r);return a&&(i=i.map(l=>l+"-"+a),t&&(i=i.concat(i.map(W8e)))),i}function k2e(s){return s.replace(/left|right|bottom|top/g,t=>bZt[t])}function SZt(s){return{top:0,right:0,bottom:0,left:0,...s}}function dbt(s){return typeof s!="number"?SZt(s):{top:s,right:s,bottom:s,left:s}}function S2e(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 Met(s,t,n){let{reference:r,floating:a}=s;const i=oE(t),l=o$e(t),o=i$e(l),c=k3(t),d=i==="y",u=r.x+r.width/2-a.width/2,h=r.y+r.height/2-a.height/2,m=r[o]/2-a[o]/2;let f;switch(c){case"top":f={x:u,y:r.y-a.height};break;case"bottom":f={x:u,y:r.y+r.height};break;case"right":f={x:r.x+r.width,y:h};break;case"left":f={x:r.x-a.width,y:h};break;default:f={x:r.x,y:r.y}}switch(X$(t)){case"start":f[l]-=m*(n&&d?-1:1);break;case"end":f[l]+=m*(n&&d?-1:1);break}return f}const CZt=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}=Met(d,r,c),m=r,f={},g=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}=N3(s,t)||{};if(d==null)return{};const h=dbt(u),m={x:n,y:r},f=o$e(a),g=i$e(f),y=await l.getDimensions(d),x=f==="y",_=x?"top":"left",b=x?"bottom":"right",k=x?"clientHeight":"clientWidth",A=i.reference[g]+i.reference[f]-m[f]-i.floating[g],T=m[f]-i.reference[f],P=await(l.getOffsetParent==null?void 0:l.getOffsetParent(d));let I=P?P[k]:0;(!I||!await(l.isElement==null?void 0:l.isElement(P)))&&(I=o.floating[k]||i.floating[g]);const M=A/2-T/2,L=I/2-y[g]/2-1,z=aE(h[_],L),$=aE(h[b],L),V=z,W=I-y[g]-$,G=I/2-y[g]/2+M,X=G8e(V,G,W),te=!c.arrow&&X$(a)!=null&&G!==X&&i.reference[g]/2-(GG<=0)){var $,V;const G=((($=i.flip)==null?void 0:$.index)||0)+1,X=I[G];if(X)return{data:{index:G,overflows:z},reset:{placement:X}};let te=(V=z.filter(ne=>ne.overflows[0]<=0).sort((ne,me)=>ne.overflows[1]-me.overflows[1])[0])==null?void 0:V.placement;if(!te)switch(f){case"bestFit":{var W;const ne=(W=z.filter(me=>{if(P){const ue=oE(me.placement);return ue===b||ue==="y"}return!0}).map(me=>[me.placement,me.overflows.filter(ue=>ue>0).reduce((ue,ce)=>ue+ce,0)]).sort((me,ue)=>me[1]-ue[1])[0])==null?void 0:W[0];ne&&(te=ne);break}case"initialPlacement":te=o;break}if(a!==te)return{reset:{placement:te}}}return{}}}};function Let(s,t){return{top:s.top-t.height,right:s.right-t.width,bottom:s.bottom-t.height,left:s.left-t.width}}function Pet(s){return vZt.some(t=>s[t]>=0)}const EZt=function(s){return s===void 0&&(s={}),{name:"hide",options:s,async fn(t){const{rects:n}=t,{strategy:r="referenceHidden",...a}=N3(s,t);switch(r){case"referenceHidden":{const i=await tY(t,{...a,elementContext:"reference"}),l=Let(i,n.reference);return{data:{referenceHiddenOffsets:l,referenceHidden:Pet(l)}}}case"escaped":{const i=await tY(t,{...a,altBoundary:!0}),l=Let(i,n.floating);return{data:{escapedOffsets:l,escaped:Pet(l)}}}default:return{}}}}};async function MZt(s,t){const{placement:n,platform:r,elements:a}=s,i=await(r.isRTL==null?void 0:r.isRTL(a.floating)),l=k3(n),o=X$(n),c=oE(n)==="y",d=["left","top"].includes(l)?-1:1,u=i&&c?-1:1,h=N3(t,s);let{mainAxis:m,crossAxis:f,alignmentAxis:g}=typeof h=="number"?{mainAxis:h,crossAxis:0,alignmentAxis:null}:{mainAxis:h.mainAxis||0,crossAxis:h.crossAxis||0,alignmentAxis:h.alignmentAxis};return o&&typeof g=="number"&&(f=o==="end"?g*-1:g),c?{x:f*u,y:m*d}:{x:m*d,y:f*u}}const LZt=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 MZt(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}}}}},PZt=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:x=>{let{x:_,y:b}=x;return{x:_,y:b}}},...c}=N3(s,t),d={x:n,y:r},u=await tY(t,c),h=oE(k3(a)),m=a$e(h);let f=d[m],g=d[h];if(i){const x=m==="y"?"top":"left",_=m==="y"?"bottom":"right",b=f+u[x],k=f-u[_];f=G8e(b,f,k)}if(l){const x=h==="y"?"top":"left",_=h==="y"?"bottom":"right",b=g+u[x],k=g-u[_];g=G8e(b,g,k)}const y=o.fn({...t,[m]:f,[h]:g});return{...y,data:{x:y.x-n,y:y.y-r,enabled:{[m]:i,[h]:l}}}}}},IZt=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}=N3(s,t),u={x:n,y:r},h=oE(a),m=a$e(h);let f=u[m],g=u[h];const y=N3(o,t),x=typeof y=="number"?{mainAxis:y,crossAxis:0}:{mainAxis:0,crossAxis:0,...y};if(c){const k=m==="y"?"height":"width",A=i.reference[m]-i.floating[k]+x.mainAxis,T=i.reference[m]+i.reference[k]-x.mainAxis;fT&&(f=T)}if(d){var _,b;const k=m==="y"?"width":"height",A=["top","left"].includes(k3(a)),T=i.reference[h]-i.floating[k]+(A&&((_=l.offset)==null?void 0:_[h])||0)+(A?0:x.crossAxis),P=i.reference[h]+i.reference[k]+(A?0:((b=l.offset)==null?void 0:b[h])||0)-(A?x.crossAxis:0);gP&&(g=P)}return{[m]:f,[h]:g}}}},DZt=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}=N3(s,t),u=await tY(t,d),h=k3(a),m=X$(a),f=oE(a)==="y",{width:g,height:y}=i.floating;let x,_;h==="top"||h==="bottom"?(x=h,_=m===(await(l.isRTL==null?void 0:l.isRTL(o.floating))?"start":"end")?"left":"right"):(_=h,x=m==="end"?"top":"bottom");const b=y-u.top-u.bottom,k=g-u.left-u.right,A=aE(y-u[x],b),T=aE(g-u[_],k),P=!t.middlewareData.shift;let I=A,M=T;if((n=t.middlewareData.shift)!=null&&n.enabled.x&&(M=k),(r=t.middlewareData.shift)!=null&&r.enabled.y&&(I=b),P&&!m){const z=g_(u.left,0),$=g_(u.right,0),V=g_(u.top,0),W=g_(u.bottom,0);f?M=g-2*(z!==0||$!==0?z+$:g_(u.left,u.right)):I=y-2*(V!==0||W!==0?V+W:g_(u.top,u.bottom))}await c({...t,availableWidth:M,availableHeight:I});const L=await l.getDimensions(o.floating);return g!==L.width||y!==L.height?{reset:{rects:!0}}:{}}}};function BSe(){return typeof window<"u"}function Q$(s){return ubt(s)?(s.nodeName||"").toLowerCase():"#document"}function P_(s){var t;return(s==null||(t=s.ownerDocument)==null?void 0:t.defaultView)||window}function U5(s){var t;return(t=(ubt(s)?s.ownerDocument:s.document)||window.document)==null?void 0:t.documentElement}function ubt(s){return BSe()?s instanceof Node||s instanceof P_(s).Node:!1}function cN(s){return BSe()?s instanceof Element||s instanceof P_(s).Element:!1}function C5(s){return BSe()?s instanceof HTMLElement||s instanceof P_(s).HTMLElement:!1}function Iet(s){return!BSe()||typeof ShadowRoot>"u"?!1:s instanceof ShadowRoot||s instanceof P_(s).ShadowRoot}function pQ(s){const{overflow:t,overflowX:n,overflowY:r,display:a}=dN(s);return/auto|scroll|overlay|hidden|clip/.test(t+r+n)&&!["inline","contents"].includes(a)}function RZt(s){return["table","td","th"].includes(Q$(s))}function $Se(s){return[":popover-open",":modal"].some(t=>{try{return s.matches(t)}catch{return!1}})}function l$e(s){const t=c$e(),n=cN(s)?dN(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 OZt(s){let t=lE(s);for(;C5(t)&&!MB(t);){if(l$e(t))return t;if($Se(t))return null;t=lE(t)}return null}function c$e(){return typeof CSS>"u"||!CSS.supports?!1:CSS.supports("-webkit-backdrop-filter","none")}function MB(s){return["html","body","#document"].includes(Q$(s))}function dN(s){return P_(s).getComputedStyle(s)}function USe(s){return cN(s)?{scrollLeft:s.scrollLeft,scrollTop:s.scrollTop}:{scrollLeft:s.scrollX,scrollTop:s.scrollY}}function lE(s){if(Q$(s)==="html")return s;const t=s.assignedSlot||s.parentNode||Iet(s)&&s.host||U5(s);return Iet(t)?t.host:t}function hbt(s){const t=lE(s);return MB(t)?s.ownerDocument?s.ownerDocument.body:s.body:C5(t)&&pQ(t)?t:hbt(t)}function sY(s,t,n){var r;t===void 0&&(t=[]),n===void 0&&(n=!0);const a=hbt(s),i=a===((r=s.ownerDocument)==null?void 0:r.body),l=P_(a);if(i){const o=K8e(l);return t.concat(l,l.visualViewport||[],pQ(a)?a:[],o&&n?sY(o):[])}return t.concat(a,sY(a,[],n))}function K8e(s){return s.parent&&Object.getPrototypeOf(s.parent)?s.frameElement:null}function mbt(s){const t=dN(s);let n=parseFloat(t.width)||0,r=parseFloat(t.height)||0;const a=C5(s),i=a?s.offsetWidth:n,l=a?s.offsetHeight:r,o=N2e(n)!==i||N2e(r)!==l;return o&&(n=i,r=l),{width:n,height:r,$:o}}function d$e(s){return cN(s)?s:s.contextElement}function O9(s){const t=d$e(s);if(!C5(t))return iE(1);const n=t.getBoundingClientRect(),{width:r,height:a,$:i}=mbt(t);let l=(i?N2e(n.width):n.width)/r,o=(i?N2e(n.height):n.height)/a;return(!l||!Number.isFinite(l))&&(l=1),(!o||!Number.isFinite(o))&&(o=1),{x:l,y:o}}const FZt=iE(0);function pbt(s){const t=P_(s);return!c$e()||!t.visualViewport?FZt:{x:t.visualViewport.offsetLeft,y:t.visualViewport.offsetTop}}function zZt(s,t,n){return t===void 0&&(t=!1),!n||t&&n!==P_(s)?!1:t}function ZD(s,t,n,r){t===void 0&&(t=!1),n===void 0&&(n=!1);const a=s.getBoundingClientRect(),i=d$e(s);let l=iE(1);t&&(r?cN(r)&&(l=O9(r)):l=O9(s));const o=zZt(i,n,r)?pbt(i):iE(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=P_(i),f=r&&cN(r)?P_(r):r;let g=m,y=K8e(g);for(;y&&r&&f!==g;){const x=O9(y),_=y.getBoundingClientRect(),b=dN(y),k=_.left+(y.clientLeft+parseFloat(b.paddingLeft))*x.x,A=_.top+(y.clientTop+parseFloat(b.paddingTop))*x.y;c*=x.x,d*=x.y,u*=x.x,h*=x.y,c+=k,d+=A,g=P_(y),y=K8e(g)}}return S2e({width:u,height:h,x:c,y:d})}function BZt(s){let{elements:t,rect:n,offsetParent:r,strategy:a}=s;const i=a==="fixed",l=U5(r),o=t?$Se(t.floating):!1;if(r===l||o&&i)return n;let c={scrollLeft:0,scrollTop:0},d=iE(1);const u=iE(0),h=C5(r);if((h||!h&&!i)&&((Q$(r)!=="body"||pQ(l))&&(c=USe(r)),C5(r))){const m=ZD(r);d=O9(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 $Zt(s){return Array.from(s.getClientRects())}function Y8e(s,t){const n=USe(s).scrollLeft;return t?t.left+n:ZD(U5(s)).left+n}function UZt(s){const t=U5(s),n=USe(s),r=s.ownerDocument.body,a=g_(t.scrollWidth,t.clientWidth,r.scrollWidth,r.clientWidth),i=g_(t.scrollHeight,t.clientHeight,r.scrollHeight,r.clientHeight);let l=-n.scrollLeft+Y8e(s);const o=-n.scrollTop;return dN(r).direction==="rtl"&&(l+=g_(t.clientWidth,r.clientWidth)-a),{width:a,height:i,x:l,y:o}}function qZt(s,t){const n=P_(s),r=U5(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=c$e();(!d||d&&t==="fixed")&&(o=a.offsetLeft,c=a.offsetTop)}return{width:i,height:l,x:o,y:c}}function VZt(s,t){const n=ZD(s,!0,t==="fixed"),r=n.top+s.clientTop,a=n.left+s.clientLeft,i=C5(s)?O9(s):iE(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 Det(s,t,n){let r;if(t==="viewport")r=qZt(s,n);else if(t==="document")r=UZt(U5(s));else if(cN(t))r=VZt(t,n);else{const a=pbt(s);r={...t,x:t.x-a.x,y:t.y-a.y}}return S2e(r)}function fbt(s,t){const n=lE(s);return n===t||!cN(n)||MB(n)?!1:dN(n).position==="fixed"||fbt(n,t)}function HZt(s,t){const n=t.get(s);if(n)return n;let r=sY(s,[],!1).filter(o=>cN(o)&&Q$(o)!=="body"),a=null;const i=dN(s).position==="fixed";let l=i?lE(s):s;for(;cN(l)&&!MB(l);){const o=dN(l),c=l$e(l);!c&&o.position==="fixed"&&(a=null),(i?!c&&!a:!c&&o.position==="static"&&!!a&&["absolute","fixed"].includes(a.position)||pQ(l)&&!c&&fbt(s,l))?r=r.filter(u=>u!==l):a=o,l=lE(l)}return t.set(s,r),r}function GZt(s){let{element:t,boundary:n,rootBoundary:r,strategy:a}=s;const l=[...n==="clippingAncestors"?$Se(t)?[]:HZt(t,this._c):[].concat(n),r],o=l[0],c=l.reduce((d,u)=>{const h=Det(t,u,a);return d.top=g_(h.top,d.top),d.right=aE(h.right,d.right),d.bottom=aE(h.bottom,d.bottom),d.left=g_(h.left,d.left),d},Det(t,o,a));return{width:c.right-c.left,height:c.bottom-c.top,x:c.left,y:c.top}}function WZt(s){const{width:t,height:n}=mbt(s);return{width:t,height:n}}function KZt(s,t,n){const r=C5(t),a=U5(t),i=n==="fixed",l=ZD(s,!0,i,t);let o={scrollLeft:0,scrollTop:0};const c=iE(0);if(r||!r&&!i)if((Q$(t)!=="body"||pQ(a))&&(o=USe(t)),r){const f=ZD(t,!0,i,t);c.x=f.x+t.clientLeft,c.y=f.y+t.clientTop}else a&&(c.x=Y8e(a));let d=0,u=0;if(a&&!r&&!i){const f=a.getBoundingClientRect();u=f.top+o.scrollTop,d=f.left+o.scrollLeft-Y8e(a,f)}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 a6e(s){return dN(s).position==="static"}function Ret(s,t){if(!C5(s)||dN(s).position==="fixed")return null;if(t)return t(s);let n=s.offsetParent;return U5(s)===n&&(n=n.ownerDocument.body),n}function gbt(s,t){const n=P_(s);if($Se(s))return n;if(!C5(s)){let a=lE(s);for(;a&&!MB(a);){if(cN(a)&&!a6e(a))return a;a=lE(a)}return n}let r=Ret(s,t);for(;r&&RZt(r)&&a6e(r);)r=Ret(r,t);return r&&MB(r)&&a6e(r)&&!l$e(r)?n:r||OZt(s)||n}const YZt=async function(s){const t=this.getOffsetParent||gbt,n=this.getDimensions,r=await n(s.floating);return{reference:KZt(s.reference,await t(s.floating),s.strategy),floating:{x:0,y:0,width:r.width,height:r.height}}};function ZZt(s){return dN(s).direction==="rtl"}const XZt={convertOffsetParentRelativeRectToViewportRelativeRect:BZt,getDocumentElement:U5,getClippingRect:GZt,getOffsetParent:gbt,getElementRects:YZt,getClientRects:$Zt,getDimensions:WZt,getScale:O9,isElement:cN,isRTL:ZZt};function QZt(s,t){let n=null,r;const a=U5(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 f=Ste(u),g=Ste(a.clientWidth-(d+h)),y=Ste(a.clientHeight-(u+m)),x=Ste(d),b={rootMargin:-f+"px "+-g+"px "+-y+"px "+-x+"px",threshold:g_(0,aE(1,c))||1};let k=!0;function A(T){const P=T[0].intersectionRatio;if(P!==c){if(!k)return l();P?l(!1,P):r=setTimeout(()=>{l(!1,1e-7)},1e3)}k=!1}try{n=new IntersectionObserver(A,{...b,root:a.ownerDocument})}catch{n=new IntersectionObserver(A,b)}n.observe(s)}return l(!0),i}function JZt(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=d$e(s),u=a||i?[...d?sY(d):[],...sY(t)]:[];u.forEach(_=>{a&&_.addEventListener("scroll",n,{passive:!0}),i&&_.addEventListener("resize",n)});const h=d&&o?QZt(d,n):null;let m=-1,f=null;l&&(f=new ResizeObserver(_=>{let[b]=_;b&&b.target===d&&f&&(f.unobserve(t),cancelAnimationFrame(m),m=requestAnimationFrame(()=>{var k;(k=f)==null||k.observe(t)})),n()}),d&&!c&&f.observe(d),f.observe(t));let g,y=c?ZD(s):null;c&&x();function x(){const _=ZD(s);y&&(_.x!==y.x||_.y!==y.y||_.width!==y.width||_.height!==y.height)&&n(),y=_,g=requestAnimationFrame(x)}return n(),()=>{var _;u.forEach(b=>{a&&b.removeEventListener("scroll",n),i&&b.removeEventListener("resize",n)}),h==null||h(),(_=f)==null||_.disconnect(),f=null,c&&cancelAnimationFrame(g)}}const eXt=LZt,tXt=PZt,sXt=TZt,nXt=DZt,rXt=EZt,Oet=AZt,aXt=IZt,iXt=(s,t,n)=>{const r=new Map,a={platform:XZt,...n},i={...a.platform,_c:r};return CZt(s,t,{...a,platform:i})};var _we=typeof document<"u"?N.useLayoutEffect:N.useEffect;function C2e(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(!C2e(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)&&!C2e(s[i],t[i]))return!1}return!0}return s!==s&&t!==t}function xbt(s){return typeof window>"u"?1:(s.ownerDocument.defaultView||window).devicePixelRatio||1}function Fet(s,t){const n=xbt(s);return Math.round(t*n)/n}function i6e(s){const t=N.useRef(s);return _we(()=>{t.current=s}),t}function oXt(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]=N.useState({x:0,y:0,strategy:n,placement:t,middlewareData:{},isPositioned:!1}),[m,f]=N.useState(r);C2e(m,r)||f(r);const[g,y]=N.useState(null),[x,_]=N.useState(null),b=N.useCallback(me=>{me!==P.current&&(P.current=me,y(me))},[]),k=N.useCallback(me=>{me!==I.current&&(I.current=me,_(me))},[]),A=i||g,T=l||x,P=N.useRef(null),I=N.useRef(null),M=N.useRef(u),L=c!=null,z=i6e(c),$=i6e(a),V=i6e(d),W=N.useCallback(()=>{if(!P.current||!I.current)return;const me={placement:t,strategy:n,middleware:m};$.current&&(me.platform=$.current),iXt(P.current,I.current,me).then(ue=>{const ce={...ue,isPositioned:V.current!==!1};G.current&&!C2e(M.current,ce)&&(M.current=ce,Lv.flushSync(()=>{h(ce)}))})},[m,t,n,$,V]);_we(()=>{d===!1&&M.current.isPositioned&&(M.current.isPositioned=!1,h(me=>({...me,isPositioned:!1})))},[d]);const G=N.useRef(!1);_we(()=>(G.current=!0,()=>{G.current=!1}),[]),_we(()=>{if(A&&(P.current=A),T&&(I.current=T),A&&T){if(z.current)return z.current(A,T,W);W()}},[A,T,W,z,L]);const X=N.useMemo(()=>({reference:P,floating:I,setReference:b,setFloating:k}),[b,k]),te=N.useMemo(()=>({reference:A,floating:T}),[A,T]),ne=N.useMemo(()=>{const me={position:n,left:0,top:0};if(!te.floating)return me;const ue=Fet(te.floating,u.x),ce=Fet(te.floating,u.y);return o?{...me,transform:"translate("+ue+"px, "+ce+"px)",...xbt(te.floating)>=1.5&&{willChange:"transform"}}:{position:n,left:ue,top:ce}},[n,o,te.floating,u.x,u.y]);return N.useMemo(()=>({...u,update:W,refs:X,elements:te,floatingStyles:ne}),[u,W,X,te,ne])}const lXt=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?Oet({element:r.current,padding:a}).fn(n):{}:r?Oet({element:r,padding:a}).fn(n):{}}}},cXt=(s,t)=>({...eXt(s),options:[s,t]}),dXt=(s,t)=>({...tXt(s),options:[s,t]}),uXt=(s,t)=>({...aXt(s),options:[s,t]}),hXt=(s,t)=>({...sXt(s),options:[s,t]}),mXt=(s,t)=>({...nXt(s),options:[s,t]}),pXt=(s,t)=>({...rXt(s),options:[s,t]}),fXt=(s,t)=>({...lXt(s),options:[s,t]});var gXt="Arrow",ybt=N.forwardRef((s,t)=>{const{children:n,width:r=10,height:a=5,...i}=s;return e.jsx(Da.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"})})});ybt.displayName=gXt;var xXt=ybt;function fQ(s){const[t,n]=N.useState(void 0);return gf(()=>{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 u$e="Popper",[vbt,q5]=Um(u$e),[yXt,bbt]=vbt(u$e),_bt=s=>{const{__scopePopper:t,children:n}=s,[r,a]=N.useState(null);return e.jsx(yXt,{scope:t,anchor:r,onAnchorChange:a,children:n})};_bt.displayName=u$e;var wbt="PopperAnchor",jbt=N.forwardRef((s,t)=>{const{__scopePopper:n,virtualRef:r,...a}=s,i=bbt(wbt,n),l=N.useRef(null),o=jo(t,l);return N.useEffect(()=>{i.onAnchorChange((r==null?void 0:r.current)||l.current)}),r?null:e.jsx(Da.div,{...a,ref:o})});jbt.displayName=wbt;var h$e="PopperContent",[vXt,bXt]=vbt(h$e),Nbt=N.forwardRef((s,t)=>{var Se,Ie,Me,Re,Be,Ne;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:f="optimized",onPlaced:g,...y}=s,x=bbt(h$e,n),[_,b]=N.useState(null),k=jo(t,Ge=>b(Ge)),[A,T]=N.useState(null),P=fQ(A),I=(P==null?void 0:P.width)??0,M=(P==null?void 0:P.height)??0,L=r+(i!=="center"?"-"+i:""),z=typeof u=="number"?u:{top:0,right:0,bottom:0,left:0,...u},$=Array.isArray(d)?d:[d],V=$.length>0,W={padding:z,boundary:$.filter(wXt),altBoundary:V},{refs:G,floatingStyles:X,placement:te,isPositioned:ne,middlewareData:me}=oXt({strategy:"fixed",placement:L,whileElementsMounted:(...Ge)=>JZt(...Ge,{animationFrame:f==="always"}),elements:{reference:x.anchor},middleware:[cXt({mainAxis:a+M,alignmentAxis:l}),c&&dXt({mainAxis:!0,crossAxis:!1,limiter:h==="partial"?uXt():void 0,...W}),c&&hXt({...W}),mXt({...W,apply:({elements:Ge,rects:Ce,availableWidth:Fe,availableHeight:Ae})=>{const{width:Xe,height:$e}=Ce.reference,Ye=Ge.floating.style;Ye.setProperty("--radix-popper-available-width",`${Fe}px`),Ye.setProperty("--radix-popper-available-height",`${Ae}px`),Ye.setProperty("--radix-popper-anchor-width",`${Xe}px`),Ye.setProperty("--radix-popper-anchor-height",`${$e}px`)}}),A&&fXt({element:A,padding:o}),jXt({arrowWidth:I,arrowHeight:M}),m&&pXt({strategy:"referenceHidden",...W})]}),[ue,ce]=Cbt(te),ae=cf(g);gf(()=>{ne&&(ae==null||ae())},[ne,ae]);const he=(Se=me.arrow)==null?void 0:Se.x,xe=(Ie=me.arrow)==null?void 0:Ie.y,ve=((Me=me.arrow)==null?void 0:Me.centerOffset)!==0,[ge,be]=N.useState();return gf(()=>{_&&be(window.getComputedStyle(_).zIndex)},[_]),e.jsx("div",{ref:G.setFloating,"data-radix-popper-content-wrapper":"",style:{...X,transform:ne?X.transform:"translate(0, -200%)",minWidth:"max-content",zIndex:ge,"--radix-popper-transform-origin":[(Re=me.transformOrigin)==null?void 0:Re.x,(Be=me.transformOrigin)==null?void 0:Be.y].join(" "),...((Ne=me.hide)==null?void 0:Ne.referenceHidden)&&{visibility:"hidden",pointerEvents:"none"}},dir:s.dir,children:e.jsx(vXt,{scope:n,placedSide:ue,onArrowChange:T,arrowX:he,arrowY:xe,shouldHideArrow:ve,children:e.jsx(Da.div,{"data-side":ue,"data-align":ce,...y,ref:k,style:{...y.style,animation:ne?void 0:"none"}})})})});Nbt.displayName=h$e;var kbt="PopperArrow",_Xt={top:"bottom",right:"left",bottom:"top",left:"right"},Sbt=N.forwardRef(function(t,n){const{__scopePopper:r,...a}=t,i=bXt(kbt,r),l=_Xt[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(xXt,{...a,ref:n,style:{...a.style,display:"block"}})})});Sbt.displayName=kbt;function wXt(s){return s!==null}var jXt=s=>({name:"transformOrigin",options:s,fn(t){var x,_,b;const{placement:n,rects:r,middlewareData:a}=t,l=((x=a.arrow)==null?void 0:x.centerOffset)!==0,o=l?0:s.arrowWidth,c=l?0:s.arrowHeight,[d,u]=Cbt(n),h={start:"0%",center:"50%",end:"100%"}[u],m=(((_=a.arrow)==null?void 0:_.x)??0)+o/2,f=(((b=a.arrow)==null?void 0:b.y)??0)+c/2;let g="",y="";return d==="bottom"?(g=l?h:`${m}px`,y=`${-c}px`):d==="top"?(g=l?h:`${m}px`,y=`${r.floating.height+c}px`):d==="right"?(g=`${-c}px`,y=l?h:`${f}px`):d==="left"&&(g=`${r.floating.width+c}px`,y=l?h:`${f}px`),{data:{x:g,y}}}});function Cbt(s){const[t,n="center"]=s.split("-");return[t,n]}var gQ=_bt,J$=jbt,xQ=Nbt,yQ=Sbt,[qSe,pOn]=Um("Tooltip",[q5]),VSe=q5(),Abt="TooltipProvider",NXt=700,Z8e="tooltip.open",[kXt,m$e]=qSe(Abt),Tbt=s=>{const{__scopeTooltip:t,delayDuration:n=NXt,skipDelayDuration:r=300,disableHoverableContent:a=!1,children:i}=s,l=N.useRef(!0),o=N.useRef(!1),c=N.useRef(0);return N.useEffect(()=>{const d=c.current;return()=>window.clearTimeout(d)},[]),e.jsx(kXt,{scope:t,isOpenDelayedRef:l,delayDuration:n,onOpen:N.useCallback(()=>{window.clearTimeout(c.current),l.current=!1},[]),onClose:N.useCallback(()=>{window.clearTimeout(c.current),c.current=window.setTimeout(()=>l.current=!0,r)},[r]),isPointerInTransitRef:o,onPointerInTransitChange:N.useCallback(d=>{o.current=d},[]),disableHoverableContent:a,children:i})};Tbt.displayName=Abt;var nY="Tooltip",[SXt,HSe]=qSe(nY),Ebt=s=>{const{__scopeTooltip:t,children:n,open:r,defaultOpen:a,onOpenChange:i,disableHoverableContent:l,delayDuration:o}=s,c=m$e(nY,s.__scopeTooltip),d=VSe(t),[u,h]=N.useState(null),m=_g(),f=N.useRef(0),g=l??c.disableHoverableContent,y=o??c.delayDuration,x=N.useRef(!1),[_,b]=Ng({prop:r,defaultProp:a??!1,onChange:I=>{I?(c.onOpen(),document.dispatchEvent(new CustomEvent(Z8e))):c.onClose(),i==null||i(I)},caller:nY}),k=N.useMemo(()=>_?x.current?"delayed-open":"instant-open":"closed",[_]),A=N.useCallback(()=>{window.clearTimeout(f.current),f.current=0,x.current=!1,b(!0)},[b]),T=N.useCallback(()=>{window.clearTimeout(f.current),f.current=0,b(!1)},[b]),P=N.useCallback(()=>{window.clearTimeout(f.current),f.current=window.setTimeout(()=>{x.current=!0,b(!0),f.current=0},y)},[y,b]);return N.useEffect(()=>()=>{f.current&&(window.clearTimeout(f.current),f.current=0)},[]),e.jsx(gQ,{...d,children:e.jsx(SXt,{scope:t,contentId:m,open:_,stateAttribute:k,trigger:u,onTriggerChange:h,onTriggerEnter:N.useCallback(()=>{c.isOpenDelayedRef.current?P():A()},[c.isOpenDelayedRef,P,A]),onTriggerLeave:N.useCallback(()=>{g?T():(window.clearTimeout(f.current),f.current=0)},[T,g]),onOpen:A,onClose:T,disableHoverableContent:g,children:n})})};Ebt.displayName=nY;var X8e="TooltipTrigger",Mbt=N.forwardRef((s,t)=>{const{__scopeTooltip:n,...r}=s,a=HSe(X8e,n),i=m$e(X8e,n),l=VSe(n),o=N.useRef(null),c=jo(t,o,a.onTriggerChange),d=N.useRef(!1),u=N.useRef(!1),h=N.useCallback(()=>d.current=!1,[]);return N.useEffect(()=>()=>document.removeEventListener("pointerup",h),[h]),e.jsx(J$,{asChild:!0,...l,children:e.jsx(Da.button,{"aria-describedby":a.open?a.contentId:void 0,"data-state":a.stateAttribute,...r,ref:c,onPointerMove:la(s.onPointerMove,m=>{m.pointerType!=="touch"&&!u.current&&!i.isPointerInTransitRef.current&&(a.onTriggerEnter(),u.current=!0)}),onPointerLeave:la(s.onPointerLeave,()=>{a.onTriggerLeave(),u.current=!1}),onPointerDown:la(s.onPointerDown,()=>{a.open&&a.onClose(),d.current=!0,document.addEventListener("pointerup",h,{once:!0})}),onFocus:la(s.onFocus,()=>{d.current||a.onOpen()}),onBlur:la(s.onBlur,a.onClose),onClick:la(s.onClick,a.onClose)})})});Mbt.displayName=X8e;var CXt="TooltipPortal",[fOn,AXt]=qSe(CXt,{forceMount:void 0}),LB="TooltipContent",Lbt=N.forwardRef((s,t)=>{const n=AXt(LB,s.__scopeTooltip),{forceMount:r=n.forceMount,side:a="top",...i}=s,l=HSe(LB,s.__scopeTooltip);return e.jsx(Xf,{present:r||l.open,children:l.disableHoverableContent?e.jsx(Pbt,{side:a,...i,ref:t}):e.jsx(TXt,{side:a,...i,ref:t})})}),TXt=N.forwardRef((s,t)=>{const n=HSe(LB,s.__scopeTooltip),r=m$e(LB,s.__scopeTooltip),a=N.useRef(null),i=jo(t,a),[l,o]=N.useState(null),{trigger:c,onClose:d}=n,u=a.current,{onPointerInTransitChange:h}=r,m=N.useCallback(()=>{o(null),h(!1)},[h]),f=N.useCallback((g,y)=>{const x=g.currentTarget,_={x:g.clientX,y:g.clientY},b=IXt(_,x.getBoundingClientRect()),k=DXt(_,b),A=RXt(y.getBoundingClientRect()),T=FXt([...k,...A]);o(T),h(!0)},[h]);return N.useEffect(()=>()=>m(),[m]),N.useEffect(()=>{if(c&&u){const g=x=>f(x,u),y=x=>f(x,c);return c.addEventListener("pointerleave",g),u.addEventListener("pointerleave",y),()=>{c.removeEventListener("pointerleave",g),u.removeEventListener("pointerleave",y)}}},[c,u,f,m]),N.useEffect(()=>{if(l){const g=y=>{const x=y.target,_={x:y.clientX,y:y.clientY},b=(c==null?void 0:c.contains(x))||(u==null?void 0:u.contains(x)),k=!OXt(_,l);b?m():k&&(m(),d())};return document.addEventListener("pointermove",g),()=>document.removeEventListener("pointermove",g)}},[c,u,l,d,m]),e.jsx(Pbt,{...s,ref:i})}),[EXt,MXt]=qSe(nY,{isInside:!1}),LXt=C1t("TooltipContent"),Pbt=N.forwardRef((s,t)=>{const{__scopeTooltip:n,children:r,"aria-label":a,onEscapeKeyDown:i,onPointerDownOutside:l,...o}=s,c=HSe(LB,n),d=VSe(n),{onClose:u}=c;return N.useEffect(()=>(document.addEventListener(Z8e,u),()=>document.removeEventListener(Z8e,u)),[u]),N.useEffect(()=>{if(c.trigger){const h=m=>{const f=m.target;f!=null&&f.contains(c.trigger)&&u()};return window.addEventListener("scroll",h,{capture:!0}),()=>window.removeEventListener("scroll",h,{capture:!0})}},[c.trigger,u]),e.jsx(TE,{asChild:!0,disableOutsidePointerEvents:!1,onEscapeKeyDown:i,onPointerDownOutside:l,onFocusOutside:h=>h.preventDefault(),onDismiss:u,children:e.jsxs(xQ,{"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(LXt,{children:r}),e.jsx(EXt,{scope:n,isInside:!0,children:e.jsx(DKt,{id:c.contentId,role:"tooltip",children:a||r})})]})})});Lbt.displayName=LB;var Ibt="TooltipArrow",PXt=N.forwardRef((s,t)=>{const{__scopeTooltip:n,...r}=s,a=VSe(n);return MXt(Ibt,n).isInside?null:e.jsx(yQ,{...a,...r,ref:t})});PXt.displayName=Ibt;function IXt(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 DXt(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 RXt(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 OXt(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 FXt(s){const t=s.slice();return t.sort((n,r)=>n.xr.x?1:n.yr.y?1:0),zXt(t)}function zXt(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 BXt=Tbt,$Xt=Ebt,UXt=Mbt,Dbt=Lbt;const fN=BXt,wu=$Xt,ju=UXt,nu=N.forwardRef(({className:s,sideOffset:t=4,...n},r)=>e.jsx(Dbt,{ref:r,sideOffset:t,className:Ot("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}));nu.displayName=Dbt.displayName;var eU=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(){}},XD=typeof window>"u"||"Deno"in globalThis;function Av(){}function qXt(s,t){return typeof s=="function"?s(t):s}function Q8e(s){return typeof s=="number"&&s>=0&&s!==1/0}function Rbt(s,t){return Math.max(s+(t||0)-Date.now(),0)}function UT(s,t){return typeof s=="function"?s(t):s}function Uw(s,t){return typeof s=="function"?s(t):s}function zet(s,t){const{type:n="all",exact:r,fetchStatus:a,predicate:i,queryKey:l,stale:o}=s;if(l){if(r){if(t.queryHash!==p$e(l,t.options))return!1}else if(!rY(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 Bet(s,t){const{exact:n,status:r,predicate:a,mutationKey:i}=s;if(i){if(!t.options.mutationKey)return!1;if(n){if(QD(t.options.mutationKey)!==QD(i))return!1}else if(!rY(t.options.mutationKey,i))return!1}return!(r&&t.state.status!==r||a&&!a(t))}function p$e(s,t){return((t==null?void 0:t.queryKeyHashFn)||QD)(s)}function QD(s){return JSON.stringify(s,(t,n)=>J8e(n)?Object.keys(n).sort().reduce((r,a)=>(r[a]=n[a],r),{}):n)}function rY(s,t){return s===t?!0:typeof s!=typeof t?!1:s&&t&&typeof s=="object"&&typeof t=="object"?Object.keys(t).every(n=>rY(s[n],t[n])):!1}function Obt(s,t){if(s===t)return s;const n=$et(s)&&$et(t);if(n||J8e(s)&&J8e(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 eDe(s,t,n){return typeof n.structuralSharing=="function"?n.structuralSharing(s,t):n.structuralSharing!==!1?Obt(s,t):t}function HXt(s,t,n=0){const r=[...s,t];return n&&r.length>n?r.slice(1):r}function GXt(s,t,n=0){const r=[t,...s];return n&&r.length>n?r.slice(0,-1):r}var f$e=Symbol();function Fbt(s,t){return!s.queryFn&&(t!=null&&t.initialPromise)?()=>t.initialPromise:!s.queryFn||s.queryFn===f$e?()=>Promise.reject(new Error(`Missing queryFn: '${s.queryHash}'`)):s.queryFn}function zbt(s,t){return typeof s=="function"?s(...t):!!s}var KI,yA,pz,tyt,WXt=(tyt=class extends eU{constructor(){super();ts(this,KI);ts(this,yA);ts(this,pz);Dt(this,pz,t=>{if(!XD&&window.addEventListener){const n=()=>t();return window.addEventListener("visibilitychange",n,!1),()=>{window.removeEventListener("visibilitychange",n)}}})}onSubscribe(){de(this,yA)||this.setEventListener(de(this,pz))}onUnsubscribe(){var t;this.hasListeners()||((t=de(this,yA))==null||t.call(this),Dt(this,yA,void 0))}setEventListener(t){var n;Dt(this,pz,t),(n=de(this,yA))==null||n.call(this),Dt(this,yA,t(r=>{typeof r=="boolean"?this.setFocused(r):this.onFocus()}))}setFocused(t){de(this,KI)!==t&&(Dt(this,KI,t),this.onFocus())}onFocus(){const t=this.isFocused();this.listeners.forEach(n=>{n(t)})}isFocused(){var t;return typeof de(this,KI)=="boolean"?de(this,KI):((t=globalThis.document)==null?void 0:t.visibilityState)!=="hidden"}},KI=new WeakMap,yA=new WeakMap,pz=new WeakMap,tyt),g$e=new WXt,fz,vA,gz,syt,KXt=(syt=class extends eU{constructor(){super();ts(this,fz,!0);ts(this,vA);ts(this,gz);Dt(this,gz,t=>{if(!XD&&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(){de(this,vA)||this.setEventListener(de(this,gz))}onUnsubscribe(){var t;this.hasListeners()||((t=de(this,vA))==null||t.call(this),Dt(this,vA,void 0))}setEventListener(t){var n;Dt(this,gz,t),(n=de(this,vA))==null||n.call(this),Dt(this,vA,t(this.setOnline.bind(this)))}setOnline(t){de(this,fz)!==t&&(Dt(this,fz,t),this.listeners.forEach(r=>{r(t)}))}isOnline(){return de(this,fz)}},fz=new WeakMap,vA=new WeakMap,gz=new WeakMap,syt),T2e=new KXt;function tDe(){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 YXt(s){return Math.min(1e3*2**s,3e4)}function Bbt(s){return(s??"online")==="online"?T2e.isOnline():!0}var $bt=class extends Error{constructor(s){super("CancelledError"),this.revert=s==null?void 0:s.revert,this.silent=s==null?void 0:s.silent}};function o6e(s){return s instanceof $bt}function Ubt(s){let t=!1,n=0,r=!1,a;const i=tDe(),l=y=>{var x;r||(m(new $bt(y)),(x=s.abort)==null||x.call(s))},o=()=>{t=!0},c=()=>{t=!1},d=()=>g$e.isFocused()&&(s.networkMode==="always"||T2e.isOnline())&&s.canRun(),u=()=>Bbt(s.networkMode)&&s.canRun(),h=y=>{var x;r||(r=!0,(x=s.onSuccess)==null||x.call(s,y),a==null||a(),i.resolve(y))},m=y=>{var x;r||(r=!0,(x=s.onError)==null||x.call(s,y),a==null||a(),i.reject(y))},f=()=>new Promise(y=>{var x;a=_=>{(r||d())&&y(_)},(x=s.onPause)==null||x.call(s)}).then(()=>{var y;a=void 0,r||(y=s.onContinue)==null||y.call(s)}),g=()=>{if(r)return;let y;const x=n===0?s.initialPromise:void 0;try{y=x??s.fn()}catch(_){y=Promise.reject(_)}Promise.resolve(y).then(h).catch(_=>{var P;if(r)return;const b=s.retry??(XD?0:3),k=s.retryDelay??YXt,A=typeof k=="function"?k(n,_):k,T=b===!0||typeof b=="number"&&nd()?void 0:f()).then(()=>{t?m(_):g()})})};return{promise:i,cancel:l,continue:()=>(a==null||a(),i),cancelRetry:o,continueRetry:c,canStart:u,start:()=>(u()?g():f().then(g),i)}}var ZXt=s=>setTimeout(s,0);function XXt(){let s=[],t=0,n=o=>{o()},r=o=>{o()},a=ZXt;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 Xg=XXt(),YI,nyt,qbt=(nyt=class{constructor(){ts(this,YI)}destroy(){this.clearGcTimeout()}scheduleGc(){this.clearGcTimeout(),Q8e(this.gcTime)&&Dt(this,YI,setTimeout(()=>{this.optionalRemove()},this.gcTime))}updateGcTime(s){this.gcTime=Math.max(this.gcTime||0,s??(XD?1/0:5*60*1e3))}clearGcTimeout(){de(this,YI)&&(clearTimeout(de(this,YI)),Dt(this,YI,void 0))}},YI=new WeakMap,nyt),xz,ZI,Rw,XI,ky,qZ,QI,p2,WS,ryt,QXt=(ryt=class extends qbt{constructor(t){super();ts(this,p2);ts(this,xz);ts(this,ZI);ts(this,Rw);ts(this,XI);ts(this,ky);ts(this,qZ);ts(this,QI);Dt(this,QI,!1),Dt(this,qZ,t.defaultOptions),this.setOptions(t.options),this.observers=[],Dt(this,XI,t.client),Dt(this,Rw,de(this,XI).getQueryCache()),this.queryKey=t.queryKey,this.queryHash=t.queryHash,Dt(this,xz,JXt(this.options)),this.state=t.state??de(this,xz),this.scheduleGc()}get meta(){return this.options.meta}get promise(){var t;return(t=de(this,ky))==null?void 0:t.promise}setOptions(t){this.options={...de(this,qZ),...t},this.updateGcTime(this.options.gcTime)}optionalRemove(){!this.observers.length&&this.state.fetchStatus==="idle"&&de(this,Rw).remove(this)}setData(t,n){const r=eDe(this.state.data,t,this.options);return Ht(this,p2,WS).call(this,{data:r,type:"success",dataUpdatedAt:n==null?void 0:n.updatedAt,manual:n==null?void 0:n.manual}),r}setState(t,n){Ht(this,p2,WS).call(this,{type:"setState",state:t,setStateOptions:n})}cancel(t){var r,a;const n=(r=de(this,ky))==null?void 0:r.promise;return(a=de(this,ky))==null||a.cancel(t),n?n.then(Av).catch(Av):Promise.resolve()}destroy(){super.destroy(),this.cancel({silent:!0})}reset(){this.destroy(),this.setState(de(this,xz))}isActive(){return this.observers.some(t=>Uw(t.options.enabled,this)!==!1)}isDisabled(){return this.getObserversCount()>0?!this.isActive():this.options.queryFn===f$e||this.state.dataUpdateCount+this.state.errorUpdateCount===0}isStatic(){return this.getObserversCount()>0?this.observers.some(t=>UT(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:!Rbt(this.state.dataUpdatedAt,t)}onFocus(){var n;const t=this.observers.find(r=>r.shouldFetchOnWindowFocus());t==null||t.refetch({cancelRefetch:!1}),(n=de(this,ky))==null||n.continue()}onOnline(){var n;const t=this.observers.find(r=>r.shouldFetchOnReconnect());t==null||t.refetch({cancelRefetch:!1}),(n=de(this,ky))==null||n.continue()}addObserver(t){this.observers.includes(t)||(this.observers.push(t),this.clearGcTimeout(),de(this,Rw).notify({type:"observerAdded",query:this,observer:t}))}removeObserver(t){this.observers.includes(t)&&(this.observers=this.observers.filter(n=>n!==t),this.observers.length||(de(this,ky)&&(de(this,QI)?de(this,ky).cancel({revert:!0}):de(this,ky).cancelRetry()),this.scheduleGc()),de(this,Rw).notify({type:"observerRemoved",query:this,observer:t}))}getObserversCount(){return this.observers.length}invalidate(){this.state.isInvalidated||Ht(this,p2,WS).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(de(this,ky))return de(this,ky).continueRetry(),de(this,ky).promise}if(t&&this.setOptions(t),!this.options.queryFn){const m=this.observers.find(f=>f.options.queryFn);m&&this.setOptions(m.options)}const r=new AbortController,a=m=>{Object.defineProperty(m,"signal",{enumerable:!0,get:()=>(Dt(this,QI,!0),r.signal)})},i=()=>{const m=Fbt(this.options,n),g=(()=>{const y={client:de(this,XI),queryKey:this.queryKey,meta:this.meta};return a(y),y})();return Dt(this,QI,!1),this.options.persister?this.options.persister(m,g,this):m(g)},o=(()=>{const m={fetchOptions:n,options:this.options,queryKey:this.queryKey,client:de(this,XI),state:this.state,fetchFn:i};return a(m),m})();(d=this.options.behavior)==null||d.onFetch(o,this),Dt(this,ZI,this.state),(this.state.fetchStatus==="idle"||this.state.fetchMeta!==((u=o.fetchOptions)==null?void 0:u.meta))&&Ht(this,p2,WS).call(this,{type:"fetch",meta:(h=o.fetchOptions)==null?void 0:h.meta});const c=m=>{var f,g,y,x;o6e(m)&&m.silent||Ht(this,p2,WS).call(this,{type:"error",error:m}),o6e(m)||((g=(f=de(this,Rw).config).onError)==null||g.call(f,m,this),(x=(y=de(this,Rw).config).onSettled)==null||x.call(y,this.state.data,m,this)),this.scheduleGc()};return Dt(this,ky,Ubt({initialPromise:n==null?void 0:n.initialPromise,fn:o.fetchFn,abort:r.abort.bind(r),onSuccess:m=>{var f,g,y,x;if(m===void 0){c(new Error(`${this.queryHash} data is undefined`));return}try{this.setData(m)}catch(_){c(_);return}(g=(f=de(this,Rw).config).onSuccess)==null||g.call(f,m,this),(x=(y=de(this,Rw).config).onSettled)==null||x.call(y,m,this.state.error,this),this.scheduleGc()},onError:c,onFail:(m,f)=>{Ht(this,p2,WS).call(this,{type:"failed",failureCount:m,error:f})},onPause:()=>{Ht(this,p2,WS).call(this,{type:"pause"})},onContinue:()=>{Ht(this,p2,WS).call(this,{type:"continue"})},retry:o.options.retry,retryDelay:o.options.retryDelay,networkMode:o.options.networkMode,canRun:()=>!0})),de(this,ky).start()}},xz=new WeakMap,ZI=new WeakMap,Rw=new WeakMap,XI=new WeakMap,ky=new WeakMap,qZ=new WeakMap,QI=new WeakMap,p2=new WeakSet,WS=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,...Vbt(r.data,this.options),fetchMeta:t.meta??null};case"success":return Dt(this,ZI,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 o6e(a)&&a.revert&&de(this,ZI)?{...de(this,ZI),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),Xg.batch(()=>{this.observers.forEach(r=>{r.onQueryUpdate()}),de(this,Rw).notify({query:this,type:"updated",action:t})})},ryt);function Vbt(s,t){return{fetchFailureCount:0,fetchFailureReason:null,fetchStatus:Bbt(t.networkMode)?"fetching":"paused",...s===void 0&&{error:null,status:"pending"}}}function JXt(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 _k,ayt,eQt=(ayt=class extends eU{constructor(t={}){super();ts(this,_k);this.config=t,Dt(this,_k,new Map)}build(t,n,r){const a=n.queryKey,i=n.queryHash??p$e(a,n);let l=this.get(i);return l||(l=new QXt({client:t,queryKey:a,queryHash:i,options:t.defaultQueryOptions(n),state:r,defaultOptions:t.getQueryDefaults(a)}),this.add(l)),l}add(t){de(this,_k).has(t.queryHash)||(de(this,_k).set(t.queryHash,t),this.notify({type:"added",query:t}))}remove(t){const n=de(this,_k).get(t.queryHash);n&&(t.destroy(),n===t&&de(this,_k).delete(t.queryHash),this.notify({type:"removed",query:t}))}clear(){Xg.batch(()=>{this.getAll().forEach(t=>{this.remove(t)})})}get(t){return de(this,_k).get(t)}getAll(){return[...de(this,_k).values()]}find(t){const n={exact:!0,...t};return this.getAll().find(r=>zet(n,r))}findAll(t={}){const n=this.getAll();return Object.keys(t).length>0?n.filter(r=>zet(t,r)):n}notify(t){Xg.batch(()=>{this.listeners.forEach(n=>{n(t)})})}onFocus(){Xg.batch(()=>{this.getAll().forEach(t=>{t.onFocus()})})}onOnline(){Xg.batch(()=>{this.getAll().forEach(t=>{t.onOnline()})})}},_k=new WeakMap,ayt),wk,kv,JI,jk,LC,iyt,tQt=(iyt=class extends qbt{constructor(t){super();ts(this,jk);ts(this,wk);ts(this,kv);ts(this,JI);this.mutationId=t.mutationId,Dt(this,kv,t.mutationCache),Dt(this,wk,[]),this.state=t.state||Hbt(),this.setOptions(t.options),this.scheduleGc()}setOptions(t){this.options=t,this.updateGcTime(this.options.gcTime)}get meta(){return this.options.meta}addObserver(t){de(this,wk).includes(t)||(de(this,wk).push(t),this.clearGcTimeout(),de(this,kv).notify({type:"observerAdded",mutation:this,observer:t}))}removeObserver(t){Dt(this,wk,de(this,wk).filter(n=>n!==t)),this.scheduleGc(),de(this,kv).notify({type:"observerRemoved",mutation:this,observer:t})}optionalRemove(){de(this,wk).length||(this.state.status==="pending"?this.scheduleGc():de(this,kv).remove(this))}continue(){var t;return((t=de(this,JI))==null?void 0:t.continue())??this.execute(this.state.variables)}async execute(t){var i,l,o,c,d,u,h,m,f,g,y,x,_,b,k,A,T,P,I,M;const n=()=>{Ht(this,jk,LC).call(this,{type:"continue"})};Dt(this,JI,Ubt({fn:()=>this.options.mutationFn?this.options.mutationFn(t):Promise.reject(new Error("No mutationFn found")),onFail:(L,z)=>{Ht(this,jk,LC).call(this,{type:"failed",failureCount:L,error:z})},onPause:()=>{Ht(this,jk,LC).call(this,{type:"pause"})},onContinue:n,retry:this.options.retry??0,retryDelay:this.options.retryDelay,networkMode:this.options.networkMode,canRun:()=>de(this,kv).canRun(this)}));const r=this.state.status==="pending",a=!de(this,JI).canStart();try{if(r)n();else{Ht(this,jk,LC).call(this,{type:"pending",variables:t,isPaused:a}),await((l=(i=de(this,kv).config).onMutate)==null?void 0:l.call(i,t,this));const z=await((c=(o=this.options).onMutate)==null?void 0:c.call(o,t));z!==this.state.context&&Ht(this,jk,LC).call(this,{type:"pending",context:z,variables:t,isPaused:a})}const L=await de(this,JI).start();return await((u=(d=de(this,kv).config).onSuccess)==null?void 0:u.call(d,L,t,this.state.context,this)),await((m=(h=this.options).onSuccess)==null?void 0:m.call(h,L,t,this.state.context)),await((g=(f=de(this,kv).config).onSettled)==null?void 0:g.call(f,L,null,this.state.variables,this.state.context,this)),await((x=(y=this.options).onSettled)==null?void 0:x.call(y,L,null,t,this.state.context)),Ht(this,jk,LC).call(this,{type:"success",data:L}),L}catch(L){try{throw await((b=(_=de(this,kv).config).onError)==null?void 0:b.call(_,L,t,this.state.context,this)),await((A=(k=this.options).onError)==null?void 0:A.call(k,L,t,this.state.context)),await((P=(T=de(this,kv).config).onSettled)==null?void 0:P.call(T,void 0,L,this.state.variables,this.state.context,this)),await((M=(I=this.options).onSettled)==null?void 0:M.call(I,void 0,L,t,this.state.context)),L}finally{Ht(this,jk,LC).call(this,{type:"error",error:L})}}finally{de(this,kv).runNext(this)}}},wk=new WeakMap,kv=new WeakMap,JI=new WeakMap,jk=new WeakSet,LC=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),Xg.batch(()=>{de(this,wk).forEach(r=>{r.onMutationUpdate(t)}),de(this,kv).notify({mutation:this,type:"updated",action:t})})},iyt);function Hbt(){return{context:void 0,data:void 0,error:null,failureCount:0,failureReason:null,isPaused:!1,status:"idle",variables:void 0,submittedAt:0}}var m4,f2,VZ,oyt,sQt=(oyt=class extends eU{constructor(t={}){super();ts(this,m4);ts(this,f2);ts(this,VZ);this.config=t,Dt(this,m4,new Set),Dt(this,f2,new Map),Dt(this,VZ,0)}build(t,n,r){const a=new tQt({mutationCache:this,mutationId:++Sx(this,VZ)._,options:t.defaultMutationOptions(n),state:r});return this.add(a),a}add(t){de(this,m4).add(t);const n=Cte(t);if(typeof n=="string"){const r=de(this,f2).get(n);r?r.push(t):de(this,f2).set(n,[t])}this.notify({type:"added",mutation:t})}remove(t){if(de(this,m4).delete(t)){const n=Cte(t);if(typeof n=="string"){const r=de(this,f2).get(n);if(r)if(r.length>1){const a=r.indexOf(t);a!==-1&&r.splice(a,1)}else r[0]===t&&de(this,f2).delete(n)}}this.notify({type:"removed",mutation:t})}canRun(t){const n=Cte(t);if(typeof n=="string"){const r=de(this,f2).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=Cte(t);if(typeof n=="string"){const a=(r=de(this,f2).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(){Xg.batch(()=>{de(this,m4).forEach(t=>{this.notify({type:"removed",mutation:t})}),de(this,m4).clear(),de(this,f2).clear()})}getAll(){return Array.from(de(this,m4))}find(t){const n={exact:!0,...t};return this.getAll().find(r=>Bet(n,r))}findAll(t={}){return this.getAll().filter(n=>Bet(t,n))}notify(t){Xg.batch(()=>{this.listeners.forEach(n=>{n(t)})})}resumePausedMutations(){const t=this.getAll().filter(n=>n.state.isPaused);return Xg.batch(()=>Promise.all(t.map(n=>n.continue().catch(Av))))}},m4=new WeakMap,f2=new WeakMap,VZ=new WeakMap,oyt);function Cte(s){var t;return(t=s.options.scope)==null?void 0:t.id}function E2e(s){return{onFetch:(t,n)=>{var u,h,m,f,g;const r=t.options,a=(m=(h=(u=t.fetchOptions)==null?void 0:u.meta)==null?void 0:h.fetchMore)==null?void 0:m.direction,i=((f=t.state.data)==null?void 0:f.pages)||[],l=((g=t.state.data)==null?void 0:g.pageParams)||[];let o={pages:[],pageParams:[]},c=0;const d=async()=>{let y=!1;const x=k=>{Object.defineProperty(k,"signal",{enumerable:!0,get:()=>(t.signal.aborted?y=!0:t.signal.addEventListener("abort",()=>{y=!0}),t.signal)})},_=Fbt(t.options,t.fetchOptions),b=async(k,A,T)=>{if(y)return Promise.reject();if(A==null&&k.pages.length)return Promise.resolve(k);const I=(()=>{const $={client:t.client,queryKey:t.queryKey,pageParam:A,direction:T?"backward":"forward",meta:t.options.meta};return x($),$})(),M=await _(I),{maxPages:L}=t.options,z=T?GXt:HXt;return{pages:z(k.pages,M,L),pageParams:z(k.pageParams,A,L)}};if(a&&i.length){const k=a==="backward",A=k?Gbt:sDe,T={pages:i,pageParams:l},P=A(r,T);o=await b(T,P,k)}else{const k=s??i.length;do{const A=c===0?l[0]??r.initialPageParam:sDe(r,o);if(c>0&&A==null)break;o=await b(o,A),c++}while(c{var y,x;return(x=(y=t.options).persister)==null?void 0:x.call(y,d,{client:t.client,queryKey:t.queryKey,meta:t.options.meta,signal:t.signal},n)}:t.fetchFn=d}}}function sDe(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 Gbt(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 nQt(s,t){return t?sDe(s,t)!=null:!1}function rQt(s,t){return!t||!s.getPreviousPageParam?!1:Gbt(s,t)!=null}var ef,bA,_A,yz,vz,wA,bz,_z,lyt,aQt=(lyt=class{constructor(s={}){ts(this,ef);ts(this,bA);ts(this,_A);ts(this,yz);ts(this,vz);ts(this,wA);ts(this,bz);ts(this,_z);Dt(this,ef,s.queryCache||new eQt),Dt(this,bA,s.mutationCache||new sQt),Dt(this,_A,s.defaultOptions||{}),Dt(this,yz,new Map),Dt(this,vz,new Map),Dt(this,wA,0)}mount(){Sx(this,wA)._++,de(this,wA)===1&&(Dt(this,bz,g$e.subscribe(async s=>{s&&(await this.resumePausedMutations(),de(this,ef).onFocus())})),Dt(this,_z,T2e.subscribe(async s=>{s&&(await this.resumePausedMutations(),de(this,ef).onOnline())})))}unmount(){var s,t;Sx(this,wA)._--,de(this,wA)===0&&((s=de(this,bz))==null||s.call(this),Dt(this,bz,void 0),(t=de(this,_z))==null||t.call(this),Dt(this,_z,void 0))}isFetching(s){return de(this,ef).findAll({...s,fetchStatus:"fetching"}).length}isMutating(s){return de(this,bA).findAll({...s,status:"pending"}).length}getQueryData(s){var n;const t=this.defaultQueryOptions({queryKey:s});return(n=de(this,ef).get(t.queryHash))==null?void 0:n.state.data}ensureQueryData(s){const t=this.defaultQueryOptions(s),n=de(this,ef).build(this,t),r=n.state.data;return r===void 0?this.fetchQuery(s):(s.revalidateIfStale&&n.isStaleByTime(UT(t.staleTime,n))&&this.prefetchQuery(t),Promise.resolve(r))}getQueriesData(s){return de(this,ef).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=de(this,ef).get(r.queryHash),i=a==null?void 0:a.state.data,l=qXt(t,i);if(l!==void 0)return de(this,ef).build(this,r).setData(l,{...n,manual:!0})}setQueriesData(s,t,n){return Xg.batch(()=>de(this,ef).findAll(s).map(({queryKey:r})=>[r,this.setQueryData(r,t,n)]))}getQueryState(s){var n;const t=this.defaultQueryOptions({queryKey:s});return(n=de(this,ef).get(t.queryHash))==null?void 0:n.state}removeQueries(s){const t=de(this,ef);Xg.batch(()=>{t.findAll(s).forEach(n=>{t.remove(n)})})}resetQueries(s,t){const n=de(this,ef);return Xg.batch(()=>(n.findAll(s).forEach(r=>{r.reset()}),this.refetchQueries({type:"active",...s},t)))}cancelQueries(s,t={}){const n={revert:!0,...t},r=Xg.batch(()=>de(this,ef).findAll(s).map(a=>a.cancel(n)));return Promise.all(r).then(Av).catch(Av)}invalidateQueries(s,t={}){return Xg.batch(()=>(de(this,ef).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=Xg.batch(()=>de(this,ef).findAll(s).filter(a=>!a.isDisabled()&&!a.isStatic()).map(a=>{let i=a.fetch(void 0,n);return n.throwOnError||(i=i.catch(Av)),a.state.fetchStatus==="paused"?Promise.resolve():i}));return Promise.all(r).then(Av)}fetchQuery(s){const t=this.defaultQueryOptions(s);t.retry===void 0&&(t.retry=!1);const n=de(this,ef).build(this,t);return n.isStaleByTime(UT(t.staleTime,n))?n.fetch(t):Promise.resolve(n.state.data)}prefetchQuery(s){return this.fetchQuery(s).then(Av).catch(Av)}fetchInfiniteQuery(s){return s.behavior=E2e(s.pages),this.fetchQuery(s)}prefetchInfiniteQuery(s){return this.fetchInfiniteQuery(s).then(Av).catch(Av)}ensureInfiniteQueryData(s){return s.behavior=E2e(s.pages),this.ensureQueryData(s)}resumePausedMutations(){return T2e.isOnline()?de(this,bA).resumePausedMutations():Promise.resolve()}getQueryCache(){return de(this,ef)}getMutationCache(){return de(this,bA)}getDefaultOptions(){return de(this,_A)}setDefaultOptions(s){Dt(this,_A,s)}setQueryDefaults(s,t){de(this,yz).set(QD(s),{queryKey:s,defaultOptions:t})}getQueryDefaults(s){const t=[...de(this,yz).values()],n={};return t.forEach(r=>{rY(s,r.queryKey)&&Object.assign(n,r.defaultOptions)}),n}setMutationDefaults(s,t){de(this,vz).set(QD(s),{mutationKey:s,defaultOptions:t})}getMutationDefaults(s){const t=[...de(this,vz).values()],n={};return t.forEach(r=>{rY(s,r.mutationKey)&&Object.assign(n,r.defaultOptions)}),n}defaultQueryOptions(s){if(s._defaulted)return s;const t={...de(this,_A).queries,...this.getQueryDefaults(s.queryKey),...s,_defaulted:!0};return t.queryHash||(t.queryHash=p$e(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===f$e&&(t.enabled=!1),t}defaultMutationOptions(s){return s!=null&&s._defaulted?s:{...de(this,_A).mutations,...(s==null?void 0:s.mutationKey)&&this.getMutationDefaults(s.mutationKey),...s,_defaulted:!0}}clear(){de(this,ef).clear(),de(this,bA).clear()}},ef=new WeakMap,bA=new WeakMap,_A=new WeakMap,yz=new WeakMap,vz=new WeakMap,wA=new WeakMap,bz=new WeakMap,_z=new WeakMap,lyt),I1,rd,HZ,Sv,e8,wz,jA,NA,GZ,jz,Nz,t8,s8,kA,kz,Su,OH,nDe,rDe,aDe,iDe,oDe,lDe,cDe,Kbt,cyt,Wbt=(cyt=class extends eU{constructor(t,n){super();ts(this,Su);ts(this,I1);ts(this,rd);ts(this,HZ);ts(this,Sv);ts(this,e8);ts(this,wz);ts(this,jA);ts(this,NA);ts(this,GZ);ts(this,jz);ts(this,Nz);ts(this,t8);ts(this,s8);ts(this,kA);ts(this,kz,new Set);this.options=n,Dt(this,I1,t),Dt(this,NA,null),Dt(this,jA,tDe()),this.options.experimental_prefetchInRender||de(this,jA).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&&(de(this,rd).addObserver(this),qet(de(this,rd),this.options)?Ht(this,Su,OH).call(this):this.updateResult(),Ht(this,Su,iDe).call(this))}onUnsubscribe(){this.hasListeners()||this.destroy()}shouldFetchOnReconnect(){return dDe(de(this,rd),this.options,this.options.refetchOnReconnect)}shouldFetchOnWindowFocus(){return dDe(de(this,rd),this.options,this.options.refetchOnWindowFocus)}destroy(){this.listeners=new Set,Ht(this,Su,oDe).call(this),Ht(this,Su,lDe).call(this),de(this,rd).removeObserver(this)}setOptions(t){const n=this.options,r=de(this,rd);if(this.options=de(this,I1).defaultQueryOptions(t),this.options.enabled!==void 0&&typeof this.options.enabled!="boolean"&&typeof this.options.enabled!="function"&&typeof Uw(this.options.enabled,de(this,rd))!="boolean")throw new Error("Expected enabled to be a boolean or a callback that returns a boolean");Ht(this,Su,cDe).call(this),de(this,rd).setOptions(this.options),n._defaulted&&!A2e(this.options,n)&&de(this,I1).getQueryCache().notify({type:"observerOptionsUpdated",query:de(this,rd),observer:this});const a=this.hasListeners();a&&Vet(de(this,rd),r,this.options,n)&&Ht(this,Su,OH).call(this),this.updateResult(),a&&(de(this,rd)!==r||Uw(this.options.enabled,de(this,rd))!==Uw(n.enabled,de(this,rd))||UT(this.options.staleTime,de(this,rd))!==UT(n.staleTime,de(this,rd)))&&Ht(this,Su,nDe).call(this);const i=Ht(this,Su,rDe).call(this);a&&(de(this,rd)!==r||Uw(this.options.enabled,de(this,rd))!==Uw(n.enabled,de(this,rd))||i!==de(this,kA))&&Ht(this,Su,aDe).call(this,i)}getOptimisticResult(t){const n=de(this,I1).getQueryCache().build(de(this,I1),t),r=this.createResult(n,t);return oQt(this,r)&&(Dt(this,Sv,r),Dt(this,wz,this.options),Dt(this,e8,de(this,rd).state)),r}getCurrentResult(){return de(this,Sv)}trackResult(t,n){return new Proxy(t,{get:(r,a)=>(this.trackProp(a),n==null||n(a),Reflect.get(r,a))})}trackProp(t){de(this,kz).add(t)}getCurrentQuery(){return de(this,rd)}refetch({...t}={}){return this.fetch({...t})}fetchOptimistic(t){const n=de(this,I1).defaultQueryOptions(t),r=de(this,I1).getQueryCache().build(de(this,I1),n);return r.fetch().then(()=>this.createResult(r,n))}fetch(t){return Ht(this,Su,OH).call(this,{...t,cancelRefetch:t.cancelRefetch??!0}).then(()=>(this.updateResult(),de(this,Sv)))}createResult(t,n){var L;const r=de(this,rd),a=this.options,i=de(this,Sv),l=de(this,e8),o=de(this,wz),d=t!==r?t.state:de(this,HZ),{state:u}=t;let h={...u},m=!1,f;if(n._optimisticResults){const z=this.hasListeners(),$=!z&&qet(t,n),V=z&&Vet(t,r,n,a);($||V)&&(h={...h,...Vbt(u.data,t.options)}),n._optimisticResults==="isRestoring"&&(h.fetchStatus="idle")}let{error:g,errorUpdatedAt:y,status:x}=h;f=h.data;let _=!1;if(n.placeholderData!==void 0&&f===void 0&&x==="pending"){let z;i!=null&&i.isPlaceholderData&&n.placeholderData===(o==null?void 0:o.placeholderData)?(z=i.data,_=!0):z=typeof n.placeholderData=="function"?n.placeholderData((L=de(this,Nz))==null?void 0:L.state.data,de(this,Nz)):n.placeholderData,z!==void 0&&(x="success",f=eDe(i==null?void 0:i.data,z,n),m=!0)}if(n.select&&f!==void 0&&!_)if(i&&f===(l==null?void 0:l.data)&&n.select===de(this,GZ))f=de(this,jz);else try{Dt(this,GZ,n.select),f=n.select(f),f=eDe(i==null?void 0:i.data,f,n),Dt(this,jz,f),Dt(this,NA,null)}catch(z){Dt(this,NA,z)}de(this,NA)&&(g=de(this,NA),f=de(this,jz),y=Date.now(),x="error");const b=h.fetchStatus==="fetching",k=x==="pending",A=x==="error",T=k&&b,P=f!==void 0,M={status:x,fetchStatus:h.fetchStatus,isPending:k,isSuccess:x==="success",isError:A,isInitialLoading:T,isLoading:T,data:f,dataUpdatedAt:h.dataUpdatedAt,error:g,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&&!k,isLoadingError:A&&!P,isPaused:h.fetchStatus==="paused",isPlaceholderData:m,isRefetchError:A&&P,isStale:x$e(t,n),refetch:this.refetch,promise:de(this,jA),isEnabled:Uw(n.enabled,t)!==!1};if(this.options.experimental_prefetchInRender){const z=W=>{M.status==="error"?W.reject(M.error):M.data!==void 0&&W.resolve(M.data)},$=()=>{const W=Dt(this,jA,M.promise=tDe());z(W)},V=de(this,jA);switch(V.status){case"pending":t.queryHash===r.queryHash&&z(V);break;case"fulfilled":(M.status==="error"||M.data!==V.value)&&$();break;case"rejected":(M.status!=="error"||M.error!==V.reason)&&$();break}}return M}updateResult(){const t=de(this,Sv),n=this.createResult(de(this,rd),this.options);if(Dt(this,e8,de(this,rd).state),Dt(this,wz,this.options),de(this,e8).data!==void 0&&Dt(this,Nz,de(this,rd)),A2e(n,t))return;Dt(this,Sv,n);const r=()=>{if(!t)return!0;const{notifyOnChangeProps:a}=this.options,i=typeof a=="function"?a():a;if(i==="all"||!i&&!de(this,kz).size)return!0;const l=new Set(i??de(this,kz));return this.options.throwOnError&&l.add("error"),Object.keys(de(this,Sv)).some(o=>{const c=o;return de(this,Sv)[c]!==t[c]&&l.has(c)})};Ht(this,Su,Kbt).call(this,{listeners:r()})}onQueryUpdate(){this.updateResult(),this.hasListeners()&&Ht(this,Su,iDe).call(this)}},I1=new WeakMap,rd=new WeakMap,HZ=new WeakMap,Sv=new WeakMap,e8=new WeakMap,wz=new WeakMap,jA=new WeakMap,NA=new WeakMap,GZ=new WeakMap,jz=new WeakMap,Nz=new WeakMap,t8=new WeakMap,s8=new WeakMap,kA=new WeakMap,kz=new WeakMap,Su=new WeakSet,OH=function(t){Ht(this,Su,cDe).call(this);let n=de(this,rd).fetch(this.options,t);return t!=null&&t.throwOnError||(n=n.catch(Av)),n},nDe=function(){Ht(this,Su,oDe).call(this);const t=UT(this.options.staleTime,de(this,rd));if(XD||de(this,Sv).isStale||!Q8e(t))return;const r=Rbt(de(this,Sv).dataUpdatedAt,t)+1;Dt(this,t8,setTimeout(()=>{de(this,Sv).isStale||this.updateResult()},r))},rDe=function(){return(typeof this.options.refetchInterval=="function"?this.options.refetchInterval(de(this,rd)):this.options.refetchInterval)??!1},aDe=function(t){Ht(this,Su,lDe).call(this),Dt(this,kA,t),!(XD||Uw(this.options.enabled,de(this,rd))===!1||!Q8e(de(this,kA))||de(this,kA)===0)&&Dt(this,s8,setInterval(()=>{(this.options.refetchIntervalInBackground||g$e.isFocused())&&Ht(this,Su,OH).call(this)},de(this,kA)))},iDe=function(){Ht(this,Su,nDe).call(this),Ht(this,Su,aDe).call(this,Ht(this,Su,rDe).call(this))},oDe=function(){de(this,t8)&&(clearTimeout(de(this,t8)),Dt(this,t8,void 0))},lDe=function(){de(this,s8)&&(clearInterval(de(this,s8)),Dt(this,s8,void 0))},cDe=function(){const t=de(this,I1).getQueryCache().build(de(this,I1),this.options);if(t===de(this,rd))return;const n=de(this,rd);Dt(this,rd,t),Dt(this,HZ,t.state),this.hasListeners()&&(n==null||n.removeObserver(this),t.addObserver(this))},Kbt=function(t){Xg.batch(()=>{t.listeners&&this.listeners.forEach(n=>{n(de(this,Sv))}),de(this,I1).getQueryCache().notify({query:de(this,rd),type:"observerResultsUpdated"})})},cyt);function iQt(s,t){return Uw(t.enabled,s)!==!1&&s.state.data===void 0&&!(s.state.status==="error"&&t.retryOnMount===!1)}function qet(s,t){return iQt(s,t)||s.state.data!==void 0&&dDe(s,t,t.refetchOnMount)}function dDe(s,t,n){if(Uw(t.enabled,s)!==!1&&UT(t.staleTime,s)!=="static"){const r=typeof n=="function"?n(s):n;return r==="always"||r!==!1&&x$e(s,t)}return!1}function Vet(s,t,n,r){return(s!==t||Uw(r.enabled,s)===!1)&&(!n.suspense||s.state.status!=="error")&&x$e(s,n)}function x$e(s,t){return Uw(t.enabled,s)!==!1&&s.isStaleByTime(UT(t.staleTime,s))}function oQt(s,t){return!A2e(s.getCurrentResult(),t)}var lQt=class extends Wbt{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:E2e()})}getOptimisticResult(s){return s.behavior=E2e(),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 g,y;const{state:n}=s,r=super.createResult(s,t),{isFetching:a,isRefetching:i,isError:l,isRefetchError:o}=r,c=(y=(g=n.fetchMeta)==null?void 0:g.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:nQt(t,n.data),hasPreviousPage:rQt(t,n.data),isFetchNextPageError:d,isFetchingNextPage:u,isFetchPreviousPageError:h,isFetchingPreviousPage:m,isRefetchError:o&&!d&&!h,isRefetching:i&&!u&&!m}}},SA,CA,D1,p4,g3,wwe,uDe,dyt,cQt=(dyt=class extends eU{constructor(n,r){super();ts(this,g3);ts(this,SA);ts(this,CA);ts(this,D1);ts(this,p4);Dt(this,SA,n),this.setOptions(r),this.bindMethods(),Ht(this,g3,wwe).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=de(this,SA).defaultMutationOptions(n),A2e(this.options,r)||de(this,SA).getMutationCache().notify({type:"observerOptionsUpdated",mutation:de(this,D1),observer:this}),r!=null&&r.mutationKey&&this.options.mutationKey&&QD(r.mutationKey)!==QD(this.options.mutationKey)?this.reset():((a=de(this,D1))==null?void 0:a.state.status)==="pending"&&de(this,D1).setOptions(this.options)}onUnsubscribe(){var n;this.hasListeners()||(n=de(this,D1))==null||n.removeObserver(this)}onMutationUpdate(n){Ht(this,g3,wwe).call(this),Ht(this,g3,uDe).call(this,n)}getCurrentResult(){return de(this,CA)}reset(){var n;(n=de(this,D1))==null||n.removeObserver(this),Dt(this,D1,void 0),Ht(this,g3,wwe).call(this),Ht(this,g3,uDe).call(this)}mutate(n,r){var a;return Dt(this,p4,r),(a=de(this,D1))==null||a.removeObserver(this),Dt(this,D1,de(this,SA).getMutationCache().build(de(this,SA),this.options)),de(this,D1).addObserver(this),de(this,D1).execute(n)}},SA=new WeakMap,CA=new WeakMap,D1=new WeakMap,p4=new WeakMap,g3=new WeakSet,wwe=function(){var r;const n=((r=de(this,D1))==null?void 0:r.state)??Hbt();Dt(this,CA,{...n,isPending:n.status==="pending",isSuccess:n.status==="success",isError:n.status==="error",isIdle:n.status==="idle",mutate:this.mutate,reset:this.reset})},uDe=function(n){Xg.batch(()=>{var r,a,i,l,o,c,d,u;if(de(this,p4)&&this.hasListeners()){const h=de(this,CA).variables,m=de(this,CA).context;(n==null?void 0:n.type)==="success"?((a=(r=de(this,p4)).onSuccess)==null||a.call(r,n.data,h,m),(l=(i=de(this,p4)).onSettled)==null||l.call(i,n.data,null,h,m)):(n==null?void 0:n.type)==="error"&&((c=(o=de(this,p4)).onError)==null||c.call(o,n.error,h,m),(u=(d=de(this,p4)).onSettled)==null||u.call(d,void 0,n.error,h,m))}this.listeners.forEach(h=>{h(de(this,CA))})})},dyt),Ybt=N.createContext(void 0),as=s=>{const t=N.useContext(Ybt);if(!t)throw new Error("No QueryClient set, use QueryClientProvider to set one");return t},dQt=({client:s,children:t})=>(N.useEffect(()=>(s.mount(),()=>{s.unmount()}),[s]),e.jsx(Ybt.Provider,{value:s,children:t})),Zbt=N.createContext(!1),uQt=()=>N.useContext(Zbt);Zbt.Provider;function hQt(){let s=!1;return{clearReset:()=>{s=!1},reset:()=>{s=!0},isReset:()=>s}}var mQt=N.createContext(hQt()),pQt=()=>N.useContext(mQt),fQt=(s,t)=>{(s.suspense||s.throwOnError||s.experimental_prefetchInRender)&&(t.isReset()||(s.retryOnMount=!1))},gQt=s=>{N.useEffect(()=>{s.clearReset()},[s])},xQt=({result:s,errorResetBoundary:t,throwOnError:n,query:r,suspense:a})=>s.isError&&!t.isReset()&&!s.isFetching&&r&&(a&&s.data===void 0||zbt(n,[s.error,r])),yQt=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))}},vQt=(s,t)=>s.isLoading&&s.isFetching&&!t,bQt=(s,t)=>(s==null?void 0:s.suspense)&&t.isPending,Het=(s,t,n)=>t.fetchOptimistic(s).catch(()=>{n.clearReset()});function Xbt(s,t,n){var h,m,f,g,y;const r=uQt(),a=pQt(),i=as(),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",yQt(l),fQt(l,a),gQt(a);const o=!i.getQueryCache().get(l.queryHash),[c]=N.useState(()=>new t(i,l)),d=c.getOptimisticResult(l),u=!r&&s.subscribed!==!1;if(N.useSyncExternalStore(N.useCallback(x=>{const _=u?c.subscribe(Xg.batchCalls(x)):Av;return c.updateResult(),_},[c,u]),()=>c.getCurrentResult(),()=>c.getCurrentResult()),N.useEffect(()=>{c.setOptions(l)},[l,c]),bQt(l,d))throw Het(l,c,a);if(xQt({result:d,errorResetBoundary:a,throwOnError:l.throwOnError,query:i.getQueryCache().get(l.queryHash),suspense:l.suspense}))throw d.error;if((g=(f=i.getDefaultOptions().queries)==null?void 0:f._experimental_afterQuery)==null||g.call(f,l,d),l.experimental_prefetchInRender&&!XD&&vQt(d,r)){const x=o?Het(l,c,a):(y=i.getQueryCache().get(l.queryHash))==null?void 0:y.promise;x==null||x.catch(Av).finally(()=>{c.updateResult()})}return l.notifyOnChangeProps?d:c.trackResult(d)}function mt(s,t){return Xbt(s,Wbt)}function _t(s,t){const n=as(),[r]=N.useState(()=>new cQt(n,s));N.useEffect(()=>{r.setOptions(s)},[r,s]);const a=N.useSyncExternalStore(N.useCallback(l=>r.subscribe(Xg.batchCalls(l)),[r]),()=>r.getCurrentResult(),()=>r.getCurrentResult()),i=N.useCallback((l,o)=>{r.mutate(l,o).catch(Av)},[r]);if(a.error&&zbt(r.options.throwOnError,[a.error]))throw a.error;return{...a,mutate:i,mutateAsync:a.mutate}}function _Qt(s,t){return Xbt(s,lQt)}/** * @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 aY(){return aY=Object.assign?Object.assign.bind():function(s){for(var t=1;t"u")throw new Error(t)}function Qbt(s,t){if(!s){typeof console<"u"&&console.warn(t);try{throw new Error(t)}catch{}}}function jQt(){return Math.random().toString(36).substr(2,8)}function Wet(s,t){return{usr:s.state,key:s.key,idx:t}}function hDe(s,t,n,r){return n===void 0&&(n=null),aY({pathname:typeof s=="string"?s:s.pathname,search:"",hash:""},typeof t=="string"?tU(t):t,{state:n,key:t&&t.key||r||jQt()})}function M2e(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 tU(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 NQt(s,t,n,r){r===void 0&&(r={});let{window:a=document.defaultView,v5Compat:i=!1}=r,l=a.history,o=nT.Pop,c=null,d=u();d==null&&(d=0,l.replaceState(aY({},l.state,{idx:d}),""));function u(){return(l.state||{idx:null}).idx}function h(){o=nT.Pop;let x=u(),_=x==null?null:x-d;d=x,c&&c({action:o,location:y.location,delta:_})}function m(x,_){o=nT.Push;let b=hDe(y.location,x,_);d=u()+1;let k=Wet(b,d),A=y.createHref(b);try{l.pushState(k,"",A)}catch(T){if(T instanceof DOMException&&T.name==="DataCloneError")throw T;a.location.assign(A)}i&&c&&c({action:o,location:y.location,delta:1})}function f(x,_){o=nT.Replace;let b=hDe(y.location,x,_);d=u();let k=Wet(b,d),A=y.createHref(b);l.replaceState(k,"",A),i&&c&&c({action:o,location:y.location,delta:0})}function g(x){let _=a.location.origin!=="null"?a.location.origin:a.location.href,b=typeof x=="string"?x:M2e(x);return b=b.replace(/ $/,"%20"),Lp(_,"No window.location.(origin|href) available to create URL for href: "+b),new URL(b,_)}let y={get action(){return o},get location(){return s(a,l)},listen(x){if(c)throw new Error("A history only accepts one active listener");return a.addEventListener(Get,h),c=x,()=>{a.removeEventListener(Get,h),c=null}},createHref(x){return t(a,x)},createURL:g,encodeLocation(x){let _=g(x);return{pathname:_.pathname,search:_.search,hash:_.hash}},push:m,replace:f,go(x){return l.go(x)}};return y}var Ket;(function(s){s.data="data",s.deferred="deferred",s.redirect="redirect",s.error="error"})(Ket||(Ket={}));function kQt(s,t,n){return n===void 0&&(n="/"),SQt(s,t,n,!1)}function SQt(s,t,n,r){let a=typeof t=="string"?tU(t):t,i=PB(a.pathname||"/",n);if(i==null)return null;let l=Jbt(s);CQt(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("/")&&(Lp(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=qT([r,c.relativePath]),u=n.concat(c);i.children&&i.children.length>0&&(Lp(i.index!==!0,"Index routes must not have child routes. Please remove "+('all child routes from route path "'+d+'".')),Jbt(i.children,t,u,d)),!(i.path==null&&!i.index)&&t.push({path:d,score:IQt(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 e_t(i.path))a(i,l,c)}),t}function e_t(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=e_t(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 CQt(s){s.sort((t,n)=>t.score!==n.score?n.score-t.score:DQt(t.routesMeta.map(r=>r.childrenIndex),n.routesMeta.map(r=>r.childrenIndex)))}const AQt=/^:[\w-]+$/,TQt=3,EQt=2,MQt=1,LQt=10,PQt=-2,Yet=s=>s==="*";function IQt(s,t){let n=s.split("/"),r=n.length;return n.some(Yet)&&(r+=PQt),t&&(r+=EQt),n.filter(a=>!Yet(a)).reduce((a,i)=>a+(AQt.test(i)?TQt:i===""?MQt:LQt),r)}function DQt(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 RQt(s,t,n){let{routesMeta:r}=s,a={},i="/",l=[];for(let o=0;o{let{paramName:m,isOptional:f}=u;if(m==="*"){let y=o[h]||"";l=i.slice(0,i.length-y.length).replace(/(.)\/+$/,"$1")}const g=o[h];return f&&!g?d[m]=void 0:d[m]=(g||"").replace(/%2F/g,"/"),d},{}),pathname:i,pathnameBase:l,pattern:s}}function OQt(s,t,n){t===void 0&&(t=!1),n===void 0&&(n=!0),Qbt(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 FQt(s){try{return s.split("/").map(t=>decodeURIComponent(t).replace(/\//g,"%2F")).join("/")}catch(t){return Qbt(!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 PB(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 zQt(s,t){t===void 0&&(t="/");let{pathname:n,search:r="",hash:a=""}=typeof s=="string"?tU(s):s;return{pathname:n?n.startsWith("/")?n:BQt(n,t):t,search:qQt(r),hash:VQt(a)}}function BQt(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 l6e(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 $Qt(s){return s.filter((t,n)=>n===0||t.route.path&&t.route.path.length>0)}function y$e(s,t){let n=$Qt(s);return t?n.map((r,a)=>a===n.length-1?r.pathname:r.pathnameBase):n.map(r=>r.pathnameBase)}function v$e(s,t,n,r){r===void 0&&(r=!1);let a;typeof s=="string"?a=tU(s):(a=aY({},s),Lp(!a.pathname||!a.pathname.includes("?"),l6e("?","pathname","search",a)),Lp(!a.pathname||!a.pathname.includes("#"),l6e("#","pathname","hash",a)),Lp(!a.search||!a.search.includes("#"),l6e("#","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=zQt(a,o),d=l&&l!=="/"&&l.endsWith("/"),u=(i||l===".")&&n.endsWith("/");return!c.pathname.endsWith("/")&&(d||u)&&(c.pathname+="/"),c}const qT=s=>s.join("/").replace(/\/\/+/g,"/"),UQt=s=>s.replace(/\/+$/,"").replace(/^\/*/,"/"),qQt=s=>!s||s==="?"?"":s.startsWith("?")?s:"?"+s,VQt=s=>!s||s==="#"?"":s.startsWith("#")?s:"#"+s;function HQt(s){return s!=null&&typeof s.status=="number"&&typeof s.statusText=="string"&&typeof s.internal=="boolean"&&"data"in s}const t_t=["post","put","patch","delete"];new Set(t_t);const GQt=["get",...t_t];new Set(GQt);/** * 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 iY(){return iY=Object.assign?Object.assign.bind():function(s){for(var t=1;t{o.current=!0}),N.useCallback(function(d,u){if(u===void 0&&(u={}),!o.current)return;if(typeof d=="number"){r.go(d);return}let h=v$e(d,JSON.parse(l),i,u.relative==="path");s==null&&t!=="/"&&(h.pathname=h.pathname==="/"?t:qT([t,h.pathname])),(u.replace?r.replace:r.push)(h,u.state,u)},[t,r,l,i,s])}const YQt=N.createContext(null);function ZQt(s){let t=N.useContext(V5).outlet;return t&&N.createElement(YQt.Provider,{value:s},t)}function uo(){let{matches:s}=N.useContext(V5),t=s[s.length-1];return t?t.params:{}}function KSe(s,t){let{relative:n}=t===void 0?{}:t,{future:r}=N.useContext(O3),{matches:a}=N.useContext(V5),{pathname:i}=Id(),l=JSON.stringify(y$e(a,r.v7_relativeSplatPath));return N.useMemo(()=>v$e(s,JSON.parse(l),i,n==="path"),[s,l,i,n])}function XQt(s,t){return QQt(s,t)}function QQt(s,t,n,r){sU()||Lp(!1);let{navigator:a}=N.useContext(O3),{matches:i}=N.useContext(V5),l=i[i.length-1],o=l?l.params:{};l&&l.pathname;let c=l?l.pathnameBase:"/";l&&l.route;let d=Id(),u;if(t){var h;let x=typeof t=="string"?tU(t):t;c==="/"||(h=x.pathname)!=null&&h.startsWith(c)||Lp(!1),u=x}else u=d;let m=u.pathname||"/",f=m;if(c!=="/"){let x=c.replace(/^\//,"").split("/");f="/"+m.replace(/^\//,"").split("/").slice(x.length).join("/")}let g=kQt(s,{pathname:f}),y=nJt(g&&g.map(x=>Object.assign({},x,{params:Object.assign({},o,x.params),pathname:qT([c,a.encodeLocation?a.encodeLocation(x.pathname).pathname:x.pathname]),pathnameBase:x.pathnameBase==="/"?c:qT([c,a.encodeLocation?a.encodeLocation(x.pathnameBase).pathname:x.pathnameBase])})),i,n,r);return t&&y?N.createElement(WSe.Provider,{value:{location:iY({pathname:"/",search:"",hash:"",state:null,key:"default"},u),navigationType:nT.Pop}},y):y}function JQt(){let s=oJt(),t=HQt(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 N.createElement(N.Fragment,null,N.createElement("h2",null,"Unexpected Application Error!"),N.createElement("h3",{style:{fontStyle:"italic"}},t),n?N.createElement("pre",{style:a},n):null,null)}const eJt=N.createElement(JQt,null);class tJt extends N.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?N.createElement(V5.Provider,{value:this.props.routeContext},N.createElement(n_t.Provider,{value:this.state.error,children:this.props.component})):this.props.children}}function sJt(s){let{routeContext:t,match:n,children:r}=s,a=N.useContext(GSe);return a&&a.static&&a.staticContext&&(n.route.errorElement||n.route.ErrorBoundary)&&(a.staticContext._deepestRenderedBoundaryId=n.route.id),N.createElement(V5.Provider,{value:t},r)}function nJt(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||Lp(!1),l=l.slice(0,Math.min(l.length,u+1))}let c=!1,d=-1;if(n&&r&&r.v7_partialHydration)for(let u=0;u=0?l=l.slice(0,d+1):l=[l[0]];break}}}return l.reduceRight((u,h,m)=>{let f,g=!1,y=null,x=null;n&&(f=o&&h.route.id?o[h.route.id]:void 0,y=h.route.errorElement||eJt,c&&(d<0&&m===0?(g=!0,x=null):d===m&&(g=!0,x=h.route.hydrateFallbackElement||null)));let _=t.concat(l.slice(0,m+1)),b=()=>{let k;return f?k=y:g?k=x:h.route.Component?k=N.createElement(h.route.Component,null):h.route.element?k=h.route.element:k=u,N.createElement(sJt,{match:h,routeContext:{outlet:u,matches:_,isDataRoute:n!=null},children:k})};return n&&(h.route.ErrorBoundary||h.route.errorElement||m===0)?N.createElement(tJt,{location:n.location,revalidation:n.revalidation,component:y,error:f,children:b(),routeContext:{outlet:null,matches:_,isDataRoute:!0}}):b()},null)}var a_t=function(s){return s.UseBlocker="useBlocker",s.UseRevalidator="useRevalidator",s.UseNavigateStable="useNavigate",s}(a_t||{}),P2e=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}(P2e||{});function rJt(s){let t=N.useContext(GSe);return t||Lp(!1),t}function aJt(s){let t=N.useContext(s_t);return t||Lp(!1),t}function iJt(s){let t=N.useContext(V5);return t||Lp(!1),t}function i_t(s){let t=iJt(),n=t.matches[t.matches.length-1];return n.route.id||Lp(!1),n.route.id}function oJt(){var s;let t=N.useContext(n_t),n=aJt(P2e.UseRouteError),r=i_t(P2e.UseRouteError);return t!==void 0?t:(s=n.errors)==null?void 0:s[r]}function lJt(){let{router:s}=rJt(a_t.UseNavigateStable),t=i_t(P2e.UseNavigateStable),n=N.useRef(!1);return r_t(()=>{n.current=!0}),N.useCallback(function(a,i){i===void 0&&(i={}),n.current&&(typeof a=="number"?s.navigate(a):s.navigate(a,iY({fromRouteId:t},i)))},[s,t])}function cJt(s,t){s==null||s.v7_startTransition,s==null||s.v7_relativeSplatPath}function nN(s){let{to:t,replace:n,state:r,relative:a}=s;sU()||Lp(!1);let{future:i,static:l}=N.useContext(O3),{matches:o}=N.useContext(V5),{pathname:c}=Id(),d=tr(),u=v$e(t,y$e(o,i.v7_relativeSplatPath),c,a==="path"),h=JSON.stringify(u);return N.useEffect(()=>d(JSON.parse(h),{replace:n,state:r,relative:a}),[d,h,a,n,r]),null}function o_t(s){return ZQt(s.context)}function Ss(s){Lp(!1)}function dJt(s){let{basename:t="/",children:n=null,location:r,navigationType:a=nT.Pop,navigator:i,static:l=!1,future:o}=s;sU()&&Lp(!1);let c=t.replace(/^\/*/,"/"),d=N.useMemo(()=>({basename:c,navigator:i,static:l,future:iY({v7_relativeSplatPath:!1},o)}),[c,o,i,l]);typeof r=="string"&&(r=tU(r));let{pathname:u="/",search:h="",hash:m="",state:f=null,key:g="default"}=r,y=N.useMemo(()=>{let x=PB(u,c);return x==null?null:{location:{pathname:x,search:h,hash:m,state:f,key:g},navigationType:a}},[c,u,h,m,f,g,a]);return y==null?null:N.createElement(O3.Provider,{value:d},N.createElement(WSe.Provider,{children:n,value:y}))}function I2e(s){let{children:t,location:n}=s;return XQt(mDe(t),n)}new Promise(()=>{});function mDe(s,t){t===void 0&&(t=[]);let n=[];return N.Children.forEach(s,(r,a)=>{if(!N.isValidElement(r))return;let i=[...t,a];if(r.type===N.Fragment){n.push.apply(n,mDe(r.props.children,i));return}r.type!==Ss&&Lp(!1),!r.props.index||!r.props.children||Lp(!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=mDe(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 D2e(){return D2e=Object.assign?Object.assign.bind():function(s){for(var t=1;t=0)&&(n[a]=s[a]);return n}function uJt(s){return!!(s.metaKey||s.altKey||s.ctrlKey||s.shiftKey)}function hJt(s,t){return s.button===0&&(!t||t==="_self")&&!uJt(s)}function pDe(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 mJt(s,t){let n=pDe(s);return t&&t.forEach((r,a)=>{n.has(a)||t.getAll(a).forEach(i=>{n.append(a,i)})}),n}const pJt=["onClick","relative","reloadDocument","replace","state","target","to","preventScrollReset","viewTransition"],fJt=["aria-current","caseSensitive","className","end","style","to","viewTransition","children"],gJt="6";try{window.__reactRouterVersion=gJt}catch{}const xJt=N.createContext({isTransitioning:!1}),yJt="startTransition",Zet=oBe[yJt];function vJt(s){let{basename:t,children:n,future:r,window:a}=s,i=N.useRef();i.current==null&&(i.current=wQt({window:a,v5Compat:!0}));let l=i.current,[o,c]=N.useState({action:l.action,location:l.location}),{v7_startTransition:d}=r||{},u=N.useCallback(h=>{d&&Zet?Zet(()=>c(h)):c(h)},[c,d]);return N.useLayoutEffect(()=>l.listen(u),[l,u]),N.useEffect(()=>cJt(r),[r]),N.createElement(dJt,{basename:t,children:n,location:o.location,navigationType:o.action,navigator:l,future:r})}const bJt=typeof window<"u"&&typeof window.document<"u"&&typeof window.document.createElement<"u",_Jt=/^(?:[a-z][a-z0-9+.-]*:|\/\/)/i,cr=N.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=l_t(t,pJt),{basename:f}=N.useContext(O3),g,y=!1;if(typeof d=="string"&&_Jt.test(d)&&(g=d,bJt))try{let k=new URL(window.location.href),A=d.startsWith("//")?new URL(k.protocol+d):new URL(d),T=PB(A.pathname,f);A.origin===k.origin&&T!=null?d=T+A.search+A.hash:y=!0}catch{}let x=WQt(d,{relative:a}),_=jJt(d,{replace:l,state:o,target:c,preventScrollReset:u,relative:a,viewTransition:h});function b(k){r&&r(k),k.defaultPrevented||_(k)}return N.createElement("a",D2e({},m,{href:g||x,onClick:y||i?r:b,ref:n,target:c}))}),wV=N.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=l_t(t,fJt),m=KSe(c,{relative:h.relative}),f=Id(),g=N.useContext(s_t),{navigator:y,basename:x}=N.useContext(O3),_=g!=null&&NJt(m)&&d===!0,b=y.encodeLocation?y.encodeLocation(m).pathname:m.pathname,k=f.pathname,A=g&&g.navigation&&g.navigation.location?g.navigation.location.pathname:null;a||(k=k.toLowerCase(),A=A?A.toLowerCase():null,b=b.toLowerCase()),A&&x&&(A=PB(A,x)||A);const T=b!=="/"&&b.endsWith("/")?b.length-1:b.length;let P=k===b||!l&&k.startsWith(b)&&k.charAt(T)==="/",I=A!=null&&(A===b||!l&&A.startsWith(b)&&A.charAt(b.length)==="/"),M={isActive:P,isPending:I,isTransitioning:_},L=P?r:void 0,z;typeof i=="function"?z=i(M):z=[i,P?"active":null,I?"pending":null,_?"transitioning":null].filter(Boolean).join(" ");let $=typeof o=="function"?o(M):o;return N.createElement(cr,D2e({},h,{"aria-current":L,className:z,ref:n,style:$,to:c,viewTransition:d}),typeof u=="function"?u(M):u)});var fDe;(function(s){s.UseScrollRestoration="useScrollRestoration",s.UseSubmit="useSubmit",s.UseSubmitFetcher="useSubmitFetcher",s.UseFetcher="useFetcher",s.useViewTransitionState="useViewTransitionState"})(fDe||(fDe={}));var Xet;(function(s){s.UseFetcher="useFetcher",s.UseFetchers="useFetchers",s.UseScrollRestoration="useScrollRestoration"})(Xet||(Xet={}));function wJt(s){let t=N.useContext(GSe);return t||Lp(!1),t}function jJt(s,t){let{target:n,replace:r,state:a,preventScrollReset:i,relative:l,viewTransition:o}=t===void 0?{}:t,c=tr(),d=Id(),u=KSe(s,{relative:l});return N.useCallback(h=>{if(hJt(h,n)){h.preventDefault();let m=r!==void 0?r:M2e(d)===M2e(u);c(s,{replace:m,state:a,preventScrollReset:i,relative:l,viewTransition:o})}},[d,c,u,r,a,n,s,i,l,o])}function $c(s){let t=N.useRef(pDe(s)),n=N.useRef(!1),r=Id(),a=N.useMemo(()=>mJt(r.search,n.current?null:t.current),[r.search]),i=tr(),l=N.useCallback((o,c)=>{const d=pDe(typeof o=="function"?o(a):o);n.current=!0,i("?"+d,c)},[i,a]);return[a,l]}function NJt(s,t){t===void 0&&(t={});let n=N.useContext(xJt);n==null&&Lp(!1);let{basename:r}=wJt(fDe.useViewTransitionState),a=KSe(s,{relative:t.relative});if(!n.isTransitioning)return!1;let i=PB(n.currentLocation.pathname,r)||n.currentLocation.pathname,l=PB(n.nextLocation.pathname,r)||n.nextLocation.pathname;return L2e(a.pathname,l)!=null||L2e(a.pathname,i)!=null}var kJt=typeof Element<"u",SJt=typeof Map=="function",CJt=typeof Set=="function",AJt=typeof ArrayBuffer=="function"&&!!ArrayBuffer.isView;function jwe(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(!jwe(s[r],t[r]))return!1;return!0}var i;if(SJt&&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(!jwe(r.value[1],t.get(r.value[0])))return!1;return!0}if(CJt&&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(AJt&&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(kJt&&s instanceof Element)return!1;for(r=n;r--!==0;)if(!((a[r]==="_owner"||a[r]==="__v"||a[r]==="__o")&&s.$$typeof)&&!jwe(s[a[r]],t[a[r]]))return!1;return!0}return s!==s&&t!==t}var TJt=function(t,n){try{return jwe(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 EJt=Xc(TJt);var MJt=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}},LJt=MJt;const Qet=Xc(LJt);var PJt=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))(c_t||{}),c6e={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"]}},Jet=Object.values(c_t),b$e={accesskey:"accessKey",charset:"charSet",class:"className",contenteditable:"contentEditable",contextmenu:"contextMenu","http-equiv":"httpEquiv",itemprop:"itemProp",tabindex:"tabIndex"},DJt=Object.entries(b$e).reduce((s,[t,n])=>(s[n]=t,s),{}),q2="data-rh",F9={DEFAULT_TITLE:"defaultTitle",DEFER:"defer",ENCODE_SPECIAL_CHARACTERS:"encodeSpecialCharacters",ON_CHANGE_CLIENT_STATE:"onChangeClientState",TITLE_TEMPLATE:"titleTemplate",PRIORITIZE_SEO_TAGS:"prioritizeSeoTags"},z9=(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},RJt=s=>{let t=z9(s,"title");const n=z9(s,F9.TITLE_TEMPLATE);if(Array.isArray(t)&&(t=t.join("")),n&&t)return n.replace(/%s/g,()=>t);const r=z9(s,F9.DEFAULT_TITLE);return t||r||void 0},OJt=s=>z9(s,F9.ON_CHANGE_CLIENT_STATE)||(()=>{}),d6e=(s,t)=>t.filter(n=>typeof n[s]<"u").map(n=>n[s]).reduce((n,r)=>({...n,...r}),{}),FJt=(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),jV=(s,t,n)=>{const r={};return n.filter(a=>Array.isArray(a[s])?!0:(typeof a[s]<"u"&&zJt(`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:FJt(["href"],s),bodyAttributes:d6e("bodyAttributes",s),defer:z9(s,F9.DEFER),encode:z9(s,F9.ENCODE_SPECIAL_CHARACTERS),htmlAttributes:d6e("htmlAttributes",s),linkTags:jV("link",["rel","href"],s),metaTags:jV("meta",["name","charset","http-equiv","property","itemprop"],s),noscriptTags:jV("noscript",["innerHTML"],s),onChangeClientState:OJt(s),scriptTags:jV("script",["src","innerHTML"],s),styleTags:jV("style",["cssText"],s),title:RJt(s),titleAttributes:d6e("titleAttributes",s),prioritizeSeoTags:BJt(s,F9.PRIORITIZE_SEO_TAGS)}),d_t=s=>Array.isArray(s)?s.join(""):s,UJt=(s,t)=>{const n=Object.keys(s);for(let r=0;rArray.isArray(s)?s.reduce((n,r)=>(UJt(r,t)?n.priority.push(r):n.default.push(r),n),{priority:[],default:[]}):{default:s,priority:[]},ett=(s,t)=>({...s,[t]:void 0}),qJt=["noscript","script","style"],gDe=(s,t=!0)=>t===!1?String(s):String(s).replace(/&/g,"&").replace(//g,">").replace(/"/g,""").replace(/'/g,"'"),u_t=s=>Object.keys(s).reduce((t,n)=>{const r=typeof s[n]<"u"?`${n}="${s[n]}"`:`${n}`;return t?`${t} ${r}`:r},""),VJt=(s,t,n,r)=>{const a=u_t(n),i=d_t(t);return a?`<${s} ${q2}="true" ${a}>${gDe(i,r)}`:`<${s} ${q2}="true">${gDe(i,r)}`},HJt=(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}="${gDe(i[u],n)}"`;return d?`${d} ${h}`:h},""),o=i.innerHTML||i.cssText||"",c=qJt.indexOf(s)===-1;return`${r}<${s} ${q2}="true" ${l}${c?"/>":`>${o}`}`},""),h_t=(s,t={})=>Object.keys(s).reduce((n,r)=>{const a=b$e[r];return n[a||r]=s[r],n},t),GJt=(s,t,n)=>{const r={key:t,[q2]:!0},a=h_t(n,r);return[Rt.createElement("title",a,t)]},Nwe=(s,t)=>t.map((n,r)=>{const a={key:r,[q2]:!0};return Object.keys(n).forEach(i=>{const o=b$e[i]||i;if(o==="innerHTML"||o==="cssText"){const c=n.innerHTML||n.cssText;a.dangerouslySetInnerHTML={__html:c}}else a[o]=n[i]}),Rt.createElement(s,a)}),Dw=(s,t,n=!0)=>{switch(s){case"title":return{toComponent:()=>GJt(s,t.title,t.titleAttributes),toString:()=>VJt(s,t.title,t.titleAttributes,n)};case"bodyAttributes":case"htmlAttributes":return{toComponent:()=>h_t(t),toString:()=>u_t(t)};default:return{toComponent:()=>Nwe(s,t),toString:()=>HJt(s,t,n)}}},WJt=({metaTags:s,linkTags:t,scriptTags:n,encode:r})=>{const a=u6e(s,c6e.meta),i=u6e(t,c6e.link),l=u6e(n,c6e.script);return{priorityMethods:{toComponent:()=>[...Nwe("meta",a.priority),...Nwe("link",i.priority),...Nwe("script",l.priority)],toString:()=>`${Dw("meta",a.priority,r)} ${Dw("link",i.priority,r)} ${Dw("script",l.priority,r)}`},metaTags:a.default,linkTags:i.default,scriptTags:l.default}},KJt=s=>{const{baseTag:t,bodyAttributes:n,encode:r=!0,htmlAttributes:a,noscriptTags:i,styleTags:l,title:o="",titleAttributes:c,prioritizeSeoTags:d}=s;let{linkTags:u,metaTags:h,scriptTags:m}=s,f={toComponent:()=>{},toString:()=>""};return d&&({priorityMethods:f,linkTags:u,metaTags:h,scriptTags:m}=WJt(s)),{priority:f,base:Dw("base",t,r),bodyAttributes:Dw("bodyAttributes",n,r),htmlAttributes:Dw("htmlAttributes",a,r),link:Dw("link",u,r),meta:Dw("meta",h,r),noscript:Dw("noscript",i,r),script:Dw("script",m,r),style:Dw("style",l,r),title:Dw("title",{title:o,titleAttributes:c},r)}},xDe=KJt,Ate=[],m_t=!!(typeof window<"u"&&window.document&&window.document.createElement),yDe=class{constructor(s,t){jr(this,"instances",[]);jr(this,"canUseDOM",m_t);jr(this,"context");jr(this,"value",{setHelmet:s=>{this.context.helmet=s},helmetInstances:{get:()=>this.canUseDOM?Ate:this.instances,add:s=>{(this.canUseDOM?Ate:this.instances).push(s)},remove:s=>{const t=(this.canUseDOM?Ate:this.instances).indexOf(s);(this.canUseDOM?Ate:this.instances).splice(t,1)}}});this.context=s,this.canUseDOM=t||!1,t||(s.helmet=xDe({baseTag:[],bodyAttributes:{},encodeSpecialCharacters:!0,htmlAttributes:{},linkTags:[],metaTags:[],noscriptTags:[],scriptTags:[],styleTags:[],title:"",titleAttributes:{}}))}},YJt={},p_t=Rt.createContext(YJt),n8,f_t=(n8=class extends N.Component{constructor(n){super(n);jr(this,"helmetData");this.helmetData=new yDe(this.props.context||{},n8.canUseDOM)}render(){return Rt.createElement(p_t.Provider,{value:this.helmetData.value},this.props.children)}},jr(n8,"canUseDOM",m_t),n8),tF=(s,t)=>{const n=document.head||document.querySelector("head"),r=n.querySelectorAll(`${s}[${q2}]`),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(q2,"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}},vDe=(s,t)=>{const n=document.getElementsByTagName(s)[0];if(!n)return;const r=n.getAttribute(q2),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(q2):n.getAttribute(q2)!==l.join(",")&&n.setAttribute(q2,l.join(","))},ZJt=(s,t)=>{typeof s<"u"&&document.title!==s&&(document.title=d_t(s)),vDe("title",t)},ttt=(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;vDe("body",r),vDe("html",a),ZJt(h,m);const f={baseTag:tF("base",n),linkTags:tF("link",i),metaTags:tF("meta",l),noscriptTags:tF("noscript",o),scriptTags:tF("script",d),styleTags:tF("style",u)},g={},y={};Object.keys(f).forEach(x=>{const{newTags:_,oldTags:b}=f[x];_.length&&(g[x]=_),b.length&&(y[x]=f[x].oldTags)}),t&&t(),c(s,g,y)},NV=null,XJt=s=>{NV&&cancelAnimationFrame(NV),s.defer?NV=requestAnimationFrame(()=>{ttt(s,()=>{NV=null})}):(ttt(s),NV=null)},QJt=XJt,stt=class extends N.Component{constructor(){super(...arguments);jr(this,"rendered",!1)}shouldComponentUpdate(t){return!IJt(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=$Jt(t.get().map(i=>{const l={...i.props};return delete l.context,l}));f_t.canUseDOM?QJt(a):xDe&&(r=xDe(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}},WIe,ic=(WIe=class extends N.Component{shouldComponentUpdate(s){return!EJt(ett(this.props,"helmetData"),ett(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 Qet(Jet.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 ${Jet.join(", ")} are allowed. Helmet does not support rendering <${s.type}> elements. Refer to our API for more information.`),Qet(!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 Rt.Children.forEach(s,r=>{if(!r||!r.props)return;const{children:a,...i}=r.props,l=Object.keys(i).reduce((c,d)=>(c[DJt[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 yDe)){const a=r;r=new yDe(a.context,!0),delete n.helmetData}return r?Rt.createElement(stt,{...n,context:r.value}):Rt.createElement(p_t.Consumer,null,a=>Rt.createElement(stt,{...n,context:a}))}},jr(WIe,"defaultProps",{defer:!0,encodeSpecialCharacters:!0,prioritizeSeoTags:!1}),WIe);const JJt=s=>{let t;return s?t=s:typeof fetch>"u"?t=(...n)=>Fi(async()=>{const{default:r}=await Promise.resolve().then(()=>nU);return{default:r}},void 0).then(({default:r})=>r(...n)):t=fetch,(...n)=>t(...n)};class _$e extends Error{constructor(t,n="FunctionsError",r){super(t),this.name=n,this.context=r}}class ees extends _$e{constructor(t){super("Failed to send a request to the Edge Function","FunctionsFetchError",t)}}class tes extends _$e{constructor(t){super("Relay Error invoking the Edge Function","FunctionsRelayError",t)}}class ses extends _$e{constructor(t){super("Edge Function returned a non-2xx status code","FunctionsHttpError",t)}}var bDe;(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"})(bDe||(bDe={}));var nes=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 res{constructor(t,{headers:n={},customFetch:r,region:a=bDe.Any}={}){this.url=t,this.headers=n,this.region=a,this.fetch=JJt(r)}setAuth(t){this.headers.Authorization=`Bearer ${t}`}invoke(t,n={}){var r;return nes(this,void 0,void 0,function*(){try{const{headers:a,method:i,body:l}=n;let o={},{region:c}=n;c||(c=this.region),c&&c!=="any"&&(o["x-region"]=c);let d;l&&(a&&!Object.prototype.hasOwnProperty.call(a,"Content-Type")||!a)&&(typeof Blob<"u"&&l instanceof Blob||l instanceof ArrayBuffer?(o["Content-Type"]="application/octet-stream",d=l):typeof l=="string"?(o["Content-Type"]="text/plain",d=l):typeof FormData<"u"&&l instanceof FormData?d=l:(o["Content-Type"]="application/json",d=JSON.stringify(l)));const u=yield this.fetch(`${this.url}/${t}`,{method:i||"POST",headers:Object.assign(Object.assign(Object.assign({},o),this.headers),a),body:d}).catch(g=>{throw new ees(g)}),h=u.headers.get("x-relay-error");if(h&&h==="true")throw new tes(u);if(!u.ok)throw new ses(u);let m=((r=u.headers.get("Content-Type"))!==null&&r!==void 0?r:"text/plain").split(";")[0].trim(),f;return m==="application/json"?f=yield u.json():m==="application/octet-stream"?f=yield u.blob():m==="text/event-stream"?f=u:m==="multipart/form-data"?f=yield u.formData():f=yield u.text(),{data:f,error:null}}catch(a){return{data:null,error:a}}})}}var V1={},w$e={},YSe={},vQ={},ZSe={},XSe={},aes=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")},IB=aes();const ies=IB.fetch,g_t=IB.fetch.bind(IB),x_t=IB.Headers,oes=IB.Request,les=IB.Response,nU=Object.freeze(Object.defineProperty({__proto__:null,Headers:x_t,Request:oes,Response:les,default:g_t,fetch:ies},Symbol.toStringTag,{value:"Module"})),ces=RHt(nU);var QSe={};Object.defineProperty(QSe,"__esModule",{value:!0});let des=class extends Error{constructor(t){super(t.message),this.name="PostgrestError",this.details=t.details,this.hint=t.hint,this.code=t.code}};QSe.default=des;var y_t=Uf&&Uf.__importDefault||function(s){return s&&s.__esModule?s:{default:s}};Object.defineProperty(XSe,"__esModule",{value:!0});const ues=y_t(ces),hes=y_t(QSe);let mes=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=ues.default:this.fetch=fetch}throwOnError(){return this.shouldThrowOnError=!0,this}setHeader(t,n){return this.headers=Object.assign({},this.headers),this.headers[t]=n,this}then(t,n){this.schema===void 0||(["GET","HEAD"].includes(this.method)?this.headers["Accept-Profile"]=this.schema:this.headers["Content-Profile"]=this.schema),this.method!=="GET"&&this.method!=="HEAD"&&(this.headers["Content-Type"]="application/json");const r=this.fetch;let a=r(this.url.toString(),{method:this.method,headers:this.headers,body:JSON.stringify(this.body),signal:this.signal}).then(async i=>{var l,o,c;let d=null,u=null,h=null,m=i.status,f=i.statusText;if(i.ok){if(this.method!=="HEAD"){const _=await i.text();_===""||(this.headers.Accept==="text/csv"||this.headers.Accept&&this.headers.Accept.includes("application/vnd.pgrst.plan+text")?u=_:u=JSON.parse(_))}const y=(l=this.headers.Prefer)===null||l===void 0?void 0:l.match(/count=(exact|planned|estimated)/),x=(o=i.headers.get("content-range"))===null||o===void 0?void 0:o.split("/");y&&x&&x.length>1&&(h=parseInt(x[1])),this.isMaybeSingle&&this.method==="GET"&&Array.isArray(u)&&(u.length>1?(d={code:"PGRST116",details:`Results contain ${u.length} rows, application/vnd.pgrst.object+json requires 1 row`,hint:null,message:"JSON object requested, multiple (or no) rows returned"},u=null,h=null,m=406,f="Not Acceptable"):u.length===1?u=u[0]:u=null)}else{const y=await i.text();try{d=JSON.parse(y),Array.isArray(d)&&i.status===404&&(u=[],d=null,m=200,f="OK")}catch{i.status===404&&y===""?(m=204,f="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,f="OK"),d&&this.shouldThrowOnError)throw new hes.default(d)}return{error:d,data:u,count:h,status:m,statusText:f}});return this.shouldThrowOnError||(a=a.catch(i=>{var l,o,c;return{error:{message:`${(l=i==null?void 0:i.name)!==null&&l!==void 0?l:"FetchError"}: ${i==null?void 0:i.message}`,details:`${(o=i==null?void 0:i.stack)!==null&&o!==void 0?o:""}`,hint:"",code:`${(c=i==null?void 0:i.code)!==null&&c!==void 0?c:""}`},data:null,count:null,status:0,statusText:""}})),a.then(t,n)}returns(){return this}overrideTypes(){return this}};XSe.default=mes;var pes=Uf&&Uf.__importDefault||function(s){return s&&s.__esModule?s:{default:s}};Object.defineProperty(ZSe,"__esModule",{value:!0});const fes=pes(XSe);let ges=class extends fes.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}};ZSe.default=ges;var xes=Uf&&Uf.__importDefault||function(s){return s&&s.__esModule?s:{default:s}};Object.defineProperty(vQ,"__esModule",{value:!0});const yes=xes(ZSe);let ves=class extends yes.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}};vQ.default=ves;var bes=Uf&&Uf.__importDefault||function(s){return s&&s.__esModule?s:{default:s}};Object.defineProperty(YSe,"__esModule",{value:!0});const kV=bes(vQ);let _es=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 kV.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 kV.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 kV.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 kV.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 kV.default({method:n,url:this.url,headers:this.headers,schema:this.schema,fetch:this.fetch,allowEmpty:!1})}};YSe.default=_es;var JSe={},e4e={};Object.defineProperty(e4e,"__esModule",{value:!0});e4e.version=void 0;e4e.version="0.0.0-automated";Object.defineProperty(JSe,"__esModule",{value:!0});JSe.DEFAULT_HEADERS=void 0;const wes=e4e;JSe.DEFAULT_HEADERS={"X-Client-Info":`postgrest-js/${wes.version}`};var v_t=Uf&&Uf.__importDefault||function(s){return s&&s.__esModule?s:{default:s}};Object.defineProperty(w$e,"__esModule",{value:!0});const jes=v_t(YSe),Nes=v_t(vQ),kes=JSe;let Ses=class b_t{constructor(t,{headers:n={},schema:r,fetch:a}={}){this.url=t,this.headers=Object.assign(Object.assign({},kes.DEFAULT_HEADERS),n),this.schemaName=r,this.fetch=a}from(t){const n=new URL(`${this.url}/${t}`);return new jes.default(n,{headers:Object.assign({},this.headers),schema:this.schemaName,fetch:this.fetch})}schema(t){return new b_t(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 Nes.default({method:l,url:o,headers:d,schema:this.schemaName,body:c,fetch:this.fetch,allowEmpty:!1})}};w$e.default=Ses;var rU=Uf&&Uf.__importDefault||function(s){return s&&s.__esModule?s:{default:s}};Object.defineProperty(V1,"__esModule",{value:!0});V1.PostgrestError=V1.PostgrestBuilder=V1.PostgrestTransformBuilder=V1.PostgrestFilterBuilder=V1.PostgrestQueryBuilder=V1.PostgrestClient=void 0;const __t=rU(w$e);V1.PostgrestClient=__t.default;const w_t=rU(YSe);V1.PostgrestQueryBuilder=w_t.default;const j_t=rU(vQ);V1.PostgrestFilterBuilder=j_t.default;const N_t=rU(ZSe);V1.PostgrestTransformBuilder=N_t.default;const k_t=rU(XSe);V1.PostgrestBuilder=k_t.default;const S_t=rU(QSe);V1.PostgrestError=S_t.default;var Ces=V1.default={PostgrestClient:__t.default,PostgrestQueryBuilder:w_t.default,PostgrestFilterBuilder:j_t.default,PostgrestTransformBuilder:N_t.default,PostgrestBuilder:k_t.default,PostgrestError:S_t.default};const{PostgrestClient:Aes,PostgrestQueryBuilder:wOn,PostgrestFilterBuilder:jOn,PostgrestTransformBuilder:NOn,PostgrestBuilder:kOn,PostgrestError:SOn}=Ces;let _De;typeof window>"u"?_De=require("ws"):_De=window.WebSocket;const Tes=_De,Ees="2.11.10",Mes={"X-Client-Info":`realtime-js/${Ees}`},Les="1.0.0",C_t=1e4,Pes=1e3;var B9;(function(s){s[s.connecting=0]="connecting",s[s.open=1]="open",s[s.closing=2]="closing",s[s.closed=3]="closed"})(B9||(B9={}));var jv;(function(s){s.closed="closed",s.errored="errored",s.joined="joined",s.joining="joining",s.leaving="leaving"})(jv||(jv={}));var E2;(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"})(E2||(E2={}));var wDe;(function(s){s.websocket="websocket"})(wDe||(wDe={}));var vI;(function(s){s.Connecting="connecting",s.Open="open",s.Closing="closing",s.Closed="closed"})(vI||(vI={}));class Ies{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 A_t{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 Ah;(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"})(Ah||(Ah={}));const ntt=(s,t,n={})=>{var r;const a=(r=n.skipTypes)!==null&&r!==void 0?r:[];return Object.keys(t).reduce((i,l)=>(i[l]=Des(l,s,t,a),i),{})},Des=(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)?T_t(i,l):jDe(l)},T_t=(s,t)=>{if(s.charAt(0)==="_"){const n=s.slice(1,s.length);return zes(t,n)}switch(s){case Ah.bool:return Res(t);case Ah.float4:case Ah.float8:case Ah.int2:case Ah.int4:case Ah.int8:case Ah.numeric:case Ah.oid:return Oes(t);case Ah.json:case Ah.jsonb:return Fes(t);case Ah.timestamp:return Bes(t);case Ah.abstime:case Ah.date:case Ah.daterange:case Ah.int4range:case Ah.int8range:case Ah.money:case Ah.reltime:case Ah.text:case Ah.time:case Ah.timestamptz:case Ah.timetz:case Ah.tsrange:case Ah.tstzrange:return jDe(t);default:return jDe(t)}},jDe=s=>s,Res=s=>{switch(s){case"t":return!0;case"f":return!1;default:return s}},Oes=s=>{if(typeof s=="string"){const t=parseFloat(s);if(!Number.isNaN(t))return t}return s},Fes=s=>{if(typeof s=="string")try{return JSON.parse(s)}catch(t){return console.log(`JSON parse error: ${t}`),s}return s},zes=(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=>T_t(t,o))}return s},Bes=s=>typeof s=="string"?s.replace(" ","T"):s,E_t=s=>{let t=s;return t=t.replace(/^ws/i,"http"),t=t.replace(/(\/socket\/websocket|\/socket|\/websocket)\/?$/i,""),t.replace(/\/+$/,"")};class h6e{constructor(t,n,r={},a=C_t){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 rtt;(function(s){s.SYNC="sync",s.JOIN="join",s.LEAVE="leave"})(rtt||(rtt={}));class RW{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=RW.syncState(this.state,a,i,l),this.pendingDiffs.forEach(c=>{this.state=RW.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=RW.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(x=>x.presence_ref),f=h.map(x=>x.presence_ref),g=u.filter(x=>f.indexOf(x.presence_ref)<0),y=h.filter(x=>m.indexOf(x.presence_ref)<0);g.length>0&&(o[d]=g),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(f=>f.presence_ref),m=u.filter(f=>h.indexOf(f.presence_ref)<0);t[o].unshift(...m)}r(o,u,c)}),this.map(l,(o,c)=>{let d=t[o];if(!d)return;const u=c.map(h=>h.presence_ref);d=d.filter(h=>u.indexOf(h.presence_ref)<0),t[o]=d,a(o,d,c),d.length===0&&delete t[o]}),t}static map(t,n){return Object.getOwnPropertyNames(t).map(r=>n(r,t[r]))}static transformState(t){return t=this.cloneDeep(t),Object.getOwnPropertyNames(t).reduce((n,r)=>{const a=t[r];return"metas"in a?n[r]=a.metas.map(i=>(i.presence_ref=i.phx_ref,delete i.phx_ref,delete i.phx_ref_prev,i)):n[r]=a,n},{})}static cloneDeep(t){return JSON.parse(JSON.stringify(t))}onJoin(t){this.caller.onJoin=t}onLeave(t){this.caller.onLeave=t}onSync(t){this.caller.onSync=t}inPendingSyncState(){return!this.joinRef||this.joinRef!==this.channel._joinRef()}}var att;(function(s){s.ALL="*",s.INSERT="INSERT",s.UPDATE="UPDATE",s.DELETE="DELETE"})(att||(att={}));var itt;(function(s){s.BROADCAST="broadcast",s.PRESENCE="presence",s.POSTGRES_CHANGES="postgres_changes",s.SYSTEM="system"})(itt||(itt={}));var e4;(function(s){s.SUBSCRIBED="SUBSCRIBED",s.TIMED_OUT="TIMED_OUT",s.CLOSED="CLOSED",s.CHANNEL_ERROR="CHANNEL_ERROR"})(e4||(e4={}));class j$e{constructor(t,n={config:{}},r){this.topic=t,this.params=n,this.socket=r,this.bindings={},this.state=jv.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 h6e(this,E2.join,this.params,this.timeout),this.rejoinTimer=new A_t(()=>this._rejoinUntilConnected(),this.socket.reconnectAfterMs),this.joinPush.receive("ok",()=>{this.state=jv.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=jv.closed,this.socket._remove(this)}),this._onError(a=>{this._isLeaving()||this._isClosed()||(this.socket.log("channel",`error ${this.topic}`,a),this.state=jv.errored,this.rejoinTimer.scheduleTimeout())}),this.joinPush.receive("timeout",()=>{this._isJoining()&&(this.socket.log("channel",`timeout ${this.topic}`,this.joinPush.timeout),this.state=jv.errored,this.rejoinTimer.scheduleTimeout())}),this._on(E2.reply,{},(a,i)=>{this._trigger(this._replyEventName(i),a)}),this.presence=new RW(this),this.broadcastEndpointURL=E_t(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(e4.CHANNEL_ERROR,u)),this._onClose(()=>t==null?void 0:t(e4.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(e4.SUBSCRIBED);return}else{const m=this.bindings.postgres_changes,f=(h=m==null?void 0:m.length)!==null&&h!==void 0?h:0,g=[];for(let y=0;y{this.state=jv.errored,t==null||t(e4.CHANNEL_ERROR,new Error(JSON.stringify(Object.values(u).join(", ")||"error")))}).receive("timeout",()=>{t==null||t(e4.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=jv.leaving;const n=()=>{this.socket.log("channel",`leave ${this.topic}`),this._trigger(E2.close,"leave",this._joinRef())};return this.joinPush.destroy(),new Promise(r=>{const a=new h6e(this,E2.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 h6e(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}=E2;if(r&&[o,c,d,u].indexOf(l)>=0&&r!==this._joinRef())return;let m=this._onMessage(l,n,r);if(n&&!m)throw"channel onMessage callbacks must return the payload, modified or unmodified";["insert","update","delete"].includes(l)?(a=this.bindings.postgres_changes)===null||a===void 0||a.filter(f=>{var g,y,x;return((g=f.filter)===null||g===void 0?void 0:g.event)==="*"||((x=(y=f.filter)===null||y===void 0?void 0:y.event)===null||x===void 0?void 0:x.toLocaleLowerCase())===l}).map(f=>f.callback(m,r)):(i=this.bindings[l])===null||i===void 0||i.filter(f=>{var g,y,x,_,b,k;if(["broadcast","presence","postgres_changes"].includes(l))if("id"in f){const A=f.id,T=(g=f.filter)===null||g===void 0?void 0:g.event;return A&&((y=n.ids)===null||y===void 0?void 0:y.includes(A))&&(T==="*"||(T==null?void 0:T.toLocaleLowerCase())===((x=n.data)===null||x===void 0?void 0:x.type.toLocaleLowerCase()))}else{const A=(b=(_=f==null?void 0:f.filter)===null||_===void 0?void 0:_.event)===null||b===void 0?void 0:b.toLocaleLowerCase();return A==="*"||A===((k=n==null?void 0:n.event)===null||k===void 0?void 0:k.toLocaleLowerCase())}else return f.type.toLocaleLowerCase()===l}).map(f=>{if(typeof m=="object"&&"ids"in m){const g=m.data,{schema:y,table:x,commit_timestamp:_,type:b,errors:k}=g;m=Object.assign(Object.assign({},{schema:y,table:x,commit_timestamp:_,eventType:b,new:{},old:{},errors:k}),this._getPayloadRecords(g))}f.callback(m,r)})}_isClosed(){return this.state===jv.closed}_isJoined(){return this.state===jv.joined}_isJoining(){return this.state===jv.joining}_isLeaving(){return this.state===jv.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&&j$e.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(E2.close,{},t)}_onError(t){this._on(E2.error,{},n=>t(n))}_canPush(){return this.socket.isConnected()&&this._isJoined()}_rejoin(t=this.timeout){this._isLeaving()||(this.socket._leaveOpenTopic(this.topic),this.state=jv.joining,this.joinPush.resend(t))}_getPayloadRecords(t){const n={new:{},old:{}};return(t.type==="INSERT"||t.type==="UPDATE")&&(n.new=ntt(t.columns,t.record)),(t.type==="UPDATE"||t.type==="DELETE")&&(n.old=ntt(t.columns,t.old_record)),n}}const ott=()=>{},$es=` addEventListener("message", (e) => { if (e.data.event === "start") { setInterval(() => postMessage({ event: "keepAlive" }), e.data.interval); } });`;class Ues{constructor(t,n){var r;this.accessTokenValue=null,this.apiKey=null,this.channels=new Array,this.endPoint="",this.httpEndpoint="",this.headers=Mes,this.params={},this.timeout=C_t,this.heartbeatIntervalMs=25e3,this.heartbeatTimer=void 0,this.pendingHeartbeatRef=null,this.heartbeatCallback=ott,this.ref=0,this.logger=ott,this.conn=null,this.sendBuffer=[],this.serializer=new Ies,this.stateChangeCallbacks={open:[],close:[],error:[],message:[]},this.accessToken=null,this._resolveFetch=i=>{let l;return i?l=i:typeof fetch>"u"?l=(...o)=>Fi(async()=>{const{default:c}=await Promise.resolve().then(()=>nU);return{default:c}},void 0).then(({default:c})=>c(...o)):l=fetch,(...o)=>l(...o)},this.endPoint=`${t}/${wDe.websocket}`,this.httpEndpoint=E_t(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 A_t(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=Tes),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 qes(this.endpointURL(),void 0,{close:()=>{this.conn=null}})}}endpointURL(){return this._appendParams(this.endPoint,Object.assign({},this.params,{vsn:Les}))}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 B9.connecting:return vI.Connecting;case B9.open:return vI.Open;case B9.closing:return vI.Closing;default:return vI.Closed}}isConnected(){return this.connectionState()===vI.Open}channel(t,n={config:{}}){const r=`realtime:${t}`,a=this.getChannels().find(i=>i.topic===r);if(a)return a;{const i=new j$e(`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(E2.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(Pes,"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(E2.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([$es],{type:"application/javascript"});n=URL.createObjectURL(r)}return n}}class qes{constructor(t,n,r){this.binaryType="arraybuffer",this.onclose=()=>{},this.onerror=()=>{},this.onmessage=()=>{},this.onopen=()=>{},this.readyState=B9.connecting,this.send=()=>{},this.url=null,this.url=t,this.close=r.close}}class N$e extends Error{constructor(t){super(t),this.__isStorageError=!0,this.name="StorageError"}}function Rx(s){return typeof s=="object"&&s!==null&&"__isStorageError"in s}class Ves extends N$e{constructor(t,n){super(t),this.name="StorageApiError",this.status=n}toJSON(){return{name:this.name,message:this.message,status:this.status}}}class NDe extends N$e{constructor(t,n){super(t),this.name="StorageUnknownError",this.originalError=n}}var Hes=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 M_t=s=>{let t;return s?t=s:typeof fetch>"u"?t=(...n)=>Fi(async()=>{const{default:r}=await Promise.resolve().then(()=>nU);return{default:r}},void 0).then(({default:r})=>r(...n)):t=fetch,(...n)=>t(...n)},Ges=()=>Hes(void 0,void 0,void 0,function*(){return typeof Response>"u"?(yield Fi(()=>Promise.resolve().then(()=>nU),void 0)).Response:Response}),kDe=s=>{if(Array.isArray(s))return s.map(n=>kDe(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]=kDe(r)}),t};var OR=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 m6e=s=>s.msg||s.message||s.error_description||s.error||JSON.stringify(s),Wes=(s,t,n)=>OR(void 0,void 0,void 0,function*(){const r=yield Ges();s instanceof r&&!(n!=null&&n.noResolveJson)?s.json().then(a=>{t(new Ves(m6e(a),s.status||500))}).catch(a=>{t(new NDe(m6e(a),a))}):t(new NDe(m6e(s),s))}),Kes=(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 bQ(s,t,n,r,a,i){return OR(this,void 0,void 0,function*(){return new Promise((l,o)=>{s(n,Kes(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=>Wes(c,o,r))})})}function R2e(s,t,n,r){return OR(this,void 0,void 0,function*(){return bQ(s,"GET",t,n,r)})}function KC(s,t,n,r,a){return OR(this,void 0,void 0,function*(){return bQ(s,"POST",t,r,a,n)})}function Yes(s,t,n,r,a){return OR(this,void 0,void 0,function*(){return bQ(s,"PUT",t,r,a,n)})}function Zes(s,t,n,r){return OR(this,void 0,void 0,function*(){return bQ(s,"HEAD",t,Object.assign(Object.assign({},n),{noResolveJson:!0}),r)})}function L_t(s,t,n,r,a){return OR(this,void 0,void 0,function*(){return bQ(s,"DELETE",t,r,a,n)})}var A1=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 Xes={limit:100,offset:0,sortBy:{column:"name",order:"asc"}},ltt={cacheControl:"3600",contentType:"text/plain;charset=UTF-8",upsert:!1};class Qes{constructor(t,n={},r,a){this.url=t,this.headers=n,this.bucketId=r,this.fetch=M_t(a)}uploadOrUpdate(t,n,r,a){return A1(this,void 0,void 0,function*(){try{let i;const l=Object.assign(Object.assign({},ltt),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(Rx(i))return{data:null,error:i};throw i}})}upload(t,n,r){return A1(this,void 0,void 0,function*(){return this.uploadOrUpdate("POST",t,n,r)})}uploadToSignedUrl(t,n,r,a){return A1(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:ltt.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(Rx(c))return{data:null,error:c};throw c}})}createSignedUploadUrl(t,n){return A1(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 KC(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 N$e("No token returned by API");return{data:{signedUrl:l.toString(),path:t,token:o},error:null}}catch(r){if(Rx(r))return{data:null,error:r};throw r}})}update(t,n,r){return A1(this,void 0,void 0,function*(){return this.uploadOrUpdate("PUT",t,n,r)})}move(t,n,r){return A1(this,void 0,void 0,function*(){try{return{data:yield KC(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(Rx(a))return{data:null,error:a};throw a}})}copy(t,n,r){return A1(this,void 0,void 0,function*(){try{return{data:{path:(yield KC(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(Rx(a))return{data:null,error:a};throw a}})}createSignedUrl(t,n,r){return A1(this,void 0,void 0,function*(){try{let a=this._getFinalPath(t),i=yield KC(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(Rx(a))return{data:null,error:a};throw a}})}createSignedUrls(t,n,r){return A1(this,void 0,void 0,function*(){try{const a=yield KC(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(Rx(a))return{data:null,error:a};throw a}})}download(t,n){return A1(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 R2e(this.fetch,`${this.url}/${a}/${o}${l}`,{headers:this.headers,noResolveJson:!0})).blob(),error:null}}catch(o){if(Rx(o))return{data:null,error:o};throw o}})}info(t){return A1(this,void 0,void 0,function*(){const n=this._getFinalPath(t);try{const r=yield R2e(this.fetch,`${this.url}/object/info/${n}`,{headers:this.headers});return{data:kDe(r),error:null}}catch(r){if(Rx(r))return{data:null,error:r};throw r}})}exists(t){return A1(this,void 0,void 0,function*(){const n=this._getFinalPath(t);try{return yield Zes(this.fetch,`${this.url}/object/${n}`,{headers:this.headers}),{data:!0,error:null}}catch(r){if(Rx(r)&&r instanceof NDe){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 A1(this,void 0,void 0,function*(){try{return{data:yield L_t(this.fetch,`${this.url}/object/${this.bucketId}`,{prefixes:t},{headers:this.headers}),error:null}}catch(n){if(Rx(n))return{data:null,error:n};throw n}})}list(t,n,r){return A1(this,void 0,void 0,function*(){try{const a=Object.assign(Object.assign(Object.assign({},Xes),n),{prefix:t||""});return{data:yield KC(this.fetch,`${this.url}/object/list/${this.bucketId}`,a,{headers:this.headers},r),error:null}}catch(a){if(Rx(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 Jes="2.7.1",ets={"X-Client-Info":`storage-js/${Jes}`};var sF=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 tts{constructor(t,n={},r){this.url=t,this.headers=Object.assign(Object.assign({},ets),n),this.fetch=M_t(r)}listBuckets(){return sF(this,void 0,void 0,function*(){try{return{data:yield R2e(this.fetch,`${this.url}/bucket`,{headers:this.headers}),error:null}}catch(t){if(Rx(t))return{data:null,error:t};throw t}})}getBucket(t){return sF(this,void 0,void 0,function*(){try{return{data:yield R2e(this.fetch,`${this.url}/bucket/${t}`,{headers:this.headers}),error:null}}catch(n){if(Rx(n))return{data:null,error:n};throw n}})}createBucket(t,n={public:!1}){return sF(this,void 0,void 0,function*(){try{return{data:yield KC(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(Rx(r))return{data:null,error:r};throw r}})}updateBucket(t,n){return sF(this,void 0,void 0,function*(){try{return{data:yield Yes(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(Rx(r))return{data:null,error:r};throw r}})}emptyBucket(t){return sF(this,void 0,void 0,function*(){try{return{data:yield KC(this.fetch,`${this.url}/bucket/${t}/empty`,{},{headers:this.headers}),error:null}}catch(n){if(Rx(n))return{data:null,error:n};throw n}})}deleteBucket(t){return sF(this,void 0,void 0,function*(){try{return{data:yield L_t(this.fetch,`${this.url}/bucket/${t}`,{},{headers:this.headers}),error:null}}catch(n){if(Rx(n))return{data:null,error:n};throw n}})}}class sts extends tts{constructor(t,n={},r){super(t,n,r)}from(t){return new Qes(this.url,this.headers,t,this.fetch)}}const nts="2.49.10";let FH="";typeof Deno<"u"?FH="deno":typeof document<"u"?FH="web":typeof navigator<"u"&&navigator.product==="ReactNative"?FH="react-native":FH="node";const rts={"X-Client-Info":`supabase-js-${FH}/${nts}`},ats={headers:rts},its={schema:"public"},ots={autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,flowType:"implicit"},lts={};var cts=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 dts=s=>{let t;return s?t=s:typeof fetch>"u"?t=g_t:t=fetch,(...n)=>t(...n)},uts=()=>typeof Headers>"u"?x_t:Headers,hts=(s,t,n)=>{const r=dts(n),a=uts();return(i,l)=>cts(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 mts=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 pts(s){return s.endsWith("/")?s:s+"/"}function fts(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:()=>mts(this,void 0,void 0,function*(){return""})};return s.accessToken?m.accessToken=s.accessToken:delete m.accessToken,m}const P_t="2.69.1",QF=30*1e3,SDe=3,p6e=SDe*QF,gts="http://localhost:9999",xts="supabase.auth.token",yts={"X-Client-Info":`gotrue-js/${P_t}`},CDe="X-Supabase-Api-Version",I_t={"2024-01-01":{timestamp:Date.parse("2024-01-01T00:00:00.0Z"),name:"2024-01-01"}},vts=/^([a-z0-9_-]{4})*($|[a-z0-9_-]{3}$|[a-z0-9_-]{2}$)$/i,bts=6e5;class k$e extends Error{constructor(t,n,r){super(t),this.__isAuthError=!0,this.name="AuthError",this.status=n,this.code=r}}function ec(s){return typeof s=="object"&&s!==null&&"__isAuthError"in s}class _ts extends k$e{constructor(t,n,r){super(t,n,r),this.name="AuthApiError",this.status=n,this.code=r}}function wts(s){return ec(s)&&s.name==="AuthApiError"}class D_t extends k$e{constructor(t,n){super(t),this.name="AuthUnknownError",this.originalError=n}}class EE extends k$e{constructor(t,n,r,a){super(t,r,a),this.name=n,this.status=r}}class PC extends EE{constructor(){super("Auth session missing!","AuthSessionMissingError",400,void 0)}}function jts(s){return ec(s)&&s.name==="AuthSessionMissingError"}class f6e extends EE{constructor(){super("Auth session or user missing","AuthInvalidTokenResponseError",500,void 0)}}class Tte extends EE{constructor(t){super(t,"AuthInvalidCredentialsError",400,void 0)}}class Ete extends EE{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 Nts(s){return ec(s)&&s.name==="AuthImplicitGrantRedirectError"}class ctt extends EE{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 ADe extends EE{constructor(t,n){super(t,"AuthRetryableFetchError",n,void 0)}}function g6e(s){return ec(s)&&s.name==="AuthRetryableFetchError"}class dtt extends EE{constructor(t,n,r){super(t,"AuthWeakPasswordError",n,"weak_password"),this.reasons=r}}class OW extends EE{constructor(t){super(t,"AuthInvalidJwtError",400,"invalid_jwt")}}const utt="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_".split(""),htt=` \r=`.split(""),kts=(()=>{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 mtt(s){const t=[],n=l=>{t.push(String.fromCodePoint(l))},r={utf8seq:0,codepoint:0},a={queue:0,queuedBits:0},i=l=>{Ats(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 Cts(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}Sts(r,t)}}function Ats(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 Tts(s){const t=[],n={queue:0,queuedBits:0},r=a=>{t.push(a)};for(let a=0;at.push(n)),new Uint8Array(t)}function Mts(s){return Math.round(Date.now()/1e3)+s}function Lts(){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 dk=()=>typeof window<"u"&&typeof document<"u",D6={tested:!1,writable:!1},FW=()=>{if(!dk())return!1;try{if(typeof globalThis.localStorage!="object")return!1}catch{return!1}if(D6.tested)return D6.writable;const s=`lswt-${Math.random()}${Math.random()}`;try{globalThis.localStorage.setItem(s,s),globalThis.localStorage.removeItem(s),D6.tested=!0,D6.writable=!0}catch{D6.tested=!0,D6.writable=!1}return D6.writable};function Pts(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 O_t=s=>{let t;return s?t=s:typeof fetch>"u"?t=(...n)=>Fi(async()=>{const{default:r}=await Promise.resolve().then(()=>nU);return{default:r}},void 0).then(({default:r})=>r(...n)):t=fetch,(...n)=>t(...n)},Its=s=>typeof s=="object"&&s!==null&&"status"in s&&"ok"in s&&"json"in s&&typeof s.json=="function",F_t=async(s,t,n)=>{await s.setItem(t,JSON.stringify(n))},Mte=async(s,t)=>{const n=await s.getItem(t);if(!n)return null;try{return JSON.parse(n)}catch{return n}},Lte=async(s,t)=>{await s.removeItem(t)};class t4e{constructor(){this.promise=new t4e.promiseConstructor((t,n)=>{this.resolve=t,this.reject=n})}}t4e.promiseConstructor=Promise;function x6e(s){const t=s.split(".");if(t.length!==3)throw new OW("Invalid JWT structure");for(let r=0;r{setTimeout(()=>t(null),s)})}function Rts(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 Ots(s){return("0"+s.toString(16)).substr(-2)}function Fts(){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,Ots).join("")}async function zts(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 Bts(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 zts(s);return btoa(n).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}async function nF(s,t,n=!1){const r=Fts();let a=r;n&&(a+="/PASSWORD_RECOVERY"),await F_t(s,`${t}-code-verifier`,a);const i=await Bts(r);return[i,r===i?"plain":"s256"]}const $ts=/^2[0-9]{3}-(0[1-9]|1[0-2])-(0[1-9]|1[0-9]|2[0-9]|3[0-1])$/i;function Uts(s){const t=s.headers.get(CDe);if(!t||!t.match($ts))return null;try{return new Date(`${t}T00:00:00.0Z`)}catch{return null}}function qts(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 Vts(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 Hts=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),Gts=[502,503,504];async function ptt(s){var t;if(!Its(s))throw new ADe(rI(s),0);if(Gts.includes(s.status))throw new ADe(rI(s),s.status);let n;try{n=await s.json()}catch(i){throw new D_t(rI(i),i)}let r;const a=Uts(s);if(a&&a.getTime()>=I_t["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 dtt(rI(n),s.status,((t=n.weak_password)===null||t===void 0?void 0:t.reasons)||[]);if(r==="session_not_found")throw new PC}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 dtt(rI(n),s.status,n.weak_password.reasons);throw new _ts(rI(n),s.status||500,r)}const Wts=(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 Kc(s,t,n,r){var a;const i=Object.assign({},r==null?void 0:r.headers);i[CDe]||(i[CDe]=I_t["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 Kts(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 Kts(s,t,n,r,a,i){const l=Wts(t,r,a,i);let o;try{o=await s(n,Object.assign({},l))}catch(c){throw console.error(c),new ADe(rI(c),0)}if(o.ok||await ptt(o),r!=null&&r.noResolveJson)return o;try{return await o.json()}catch(c){await ptt(c)}}function IC(s){var t;let n=null;Qts(s)&&(n=Object.assign({},s),s.expires_at||(n.expires_at=Mts(s.expires_in)));const r=(t=s.user)!==null&&t!==void 0?t:s;return{data:{session:n,user:r},error:null}}function ftt(s){const t=IC(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 cA(s){var t;return{data:{user:(t=s.user)!==null&&t!==void 0?t:s},error:null}}function Yts(s){return{data:s,error:null}}function Zts(s){const{action_link:t,email_otp:n,hashed_token:r,redirect_to:a,verification_type:i}=s,l=Hts(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 Xts(s){return s}function Qts(s){return s.access_token&&s.refresh_token&&s.expires_in}var Jts=function(s,t){var n={};for(var r in s)Object.prototype.hasOwnProperty.call(s,r)&&t.indexOf(r)<0&&(n[r]=s[r]);if(s!=null&&typeof Object.getOwnPropertySymbols=="function")for(var a=0,r=Object.getOwnPropertySymbols(s);a0&&(f.forEach(g=>{const y=parseInt(g.split(";")[0].split("=")[1].substring(0,1)),x=JSON.parse(g.split(";")[1].split("=")[1]);d[`${x}Page`]=y}),d.total=parseInt(m)),{data:Object.assign(Object.assign({},h),d),error:null}}catch(d){if(ec(d))return{data:{users:[]},error:d};throw d}}async getUserById(t){try{return await Kc(this.fetch,"GET",`${this.url}/admin/users/${t}`,{headers:this.headers,xform:cA})}catch(n){if(ec(n))return{data:{user:null},error:n};throw n}}async updateUserById(t,n){try{return await Kc(this.fetch,"PUT",`${this.url}/admin/users/${t}`,{body:n,headers:this.headers,xform:cA})}catch(r){if(ec(r))return{data:{user:null},error:r};throw r}}async deleteUser(t,n=!1){try{return await Kc(this.fetch,"DELETE",`${this.url}/admin/users/${t}`,{headers:this.headers,body:{should_soft_delete:n},xform:cA})}catch(r){if(ec(r))return{data:{user:null},error:r};throw r}}async _listFactors(t){try{const{data:n,error:r}=await Kc(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(ec(n))return{data:null,error:n};throw n}}async _deleteFactor(t){try{return{data:await Kc(this.fetch,"DELETE",`${this.url}/admin/users/${t.userId}/factors/${t.id}`,{headers:this.headers}),error:null}}catch(n){if(ec(n))return{data:null,error:n};throw n}}}const tss={getItem:s=>FW()?globalThis.localStorage.getItem(s):null,setItem:(s,t)=>{FW()&&globalThis.localStorage.setItem(s,t)},removeItem:s=>{FW()&&globalThis.localStorage.removeItem(s)}};function gtt(s={}){return{getItem:t=>s[t]||null,setItem:(t,n)=>{s[t]=n},removeItem:t=>{delete s[t]}}}function sss(){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 rF={debug:!!(globalThis&&FW()&&globalThis.localStorage&&globalThis.localStorage.getItem("supabase.gotrue-js.locks.debug")==="true")};class z_t extends Error{constructor(t){super(t),this.isAcquireTimeout=!0}}class nss extends z_t{}async function rss(s,t,n){rF.debug&&console.log("@supabase/gotrue-js: navigatorLock: acquire lock",s,t);const r=new globalThis.AbortController;return t>0&&setTimeout(()=>{r.abort(),rF.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){rF.debug&&console.log("@supabase/gotrue-js: navigatorLock: acquired",s,a.name);try{return await n()}finally{rF.debug&&console.log("@supabase/gotrue-js: navigatorLock: released",s,a.name)}}else{if(t===0)throw rF.debug&&console.log("@supabase/gotrue-js: navigatorLock: not immediately available",s),new nss(`Acquiring an exclusive Navigator LockManager lock "${s}" immediately failed`);if(rF.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()}}))}sss();const ass={url:gts,storageKey:xts,autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,headers:yts,flowType:"implicit",debug:!1,hasCustomAuthorizationHeader:!1};async function xtt(s,t,n){return await n()}class oY{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=oY.nextInstanceID,oY.nextInstanceID+=1,this.instanceID>0&&dk()&&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({},ass),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 ess({url:a.url,headers:a.headers,fetch:a.fetch}),this.url=a.url,this.headers=a.headers,this.fetch=O_t(a.fetch),this.lock=a.lock||xtt,this.detectSessionInUrl=a.detectSessionInUrl,this.flowType=a.flowType,this.hasCustomAuthorizationHeader=a.hasCustomAuthorizationHeader,a.lock?this.lock=a.lock:dk()&&(!((n=globalThis==null?void 0:globalThis.navigator)===null||n===void 0)&&n.locks)?this.lock=rss:this.lock=xtt,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:FW()?this.storage=tss:(this.memoryStorage={},this.storage=gtt(this.memoryStorage)):(this.memoryStorage={},this.storage=gtt(this.memoryStorage)),dk()&&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} (${P_t}) ${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=Pts(window.location.href);let r="none";if(this._isImplicitGrantCallback(n)?r="implicit":await this._isPKCECallback(n)&&(r="pkce"),dk()&&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),Nts(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 ec(n)?{error:n}:{error:new D_t("Unexpected error during initialization",n)}}finally{await this._handleVisibilityChange(),this._debug("#_initialize()","end")}}async signInAnonymously(t){var n,r,a;try{const i=await Kc(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:IC}),{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(ec(i))return{data:{user:null,session:null},error:i};throw i}}async signUp(t){var n,r,a;try{let i;if("email"in t){const{email:u,password:h,options:m}=t;let f=null,g=null;this.flowType==="pkce"&&([f,g]=await nF(this.storage,this.storageKey)),i=await Kc(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,redirectTo:m==null?void 0:m.emailRedirectTo,body:{email:u,password:h,data:(n=m==null?void 0:m.data)!==null&&n!==void 0?n:{},gotrue_meta_security:{captcha_token:m==null?void 0:m.captchaToken},code_challenge:f,code_challenge_method:g},xform:IC})}else if("phone"in t){const{phone:u,password:h,options:m}=t;i=await Kc(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:IC})}else throw new Tte("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(ec(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 Kc(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:ftt})}else if("phone"in t){const{phone:i,password:l,options:o}=t;n=await Kc(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:ftt})}else throw new Tte("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 f6e}:(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(ec(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 Mte(this.storage,`${this.storageKey}-code-verifier`),[r,a]=(n??"").split("/");try{const{data:i,error:l}=await Kc(this.fetch,"POST",`${this.url}/token?grant_type=pkce`,{headers:this.headers,body:{auth_code:t,code_verifier:r},xform:IC});if(await Lte(this.storage,`${this.storageKey}-code-verifier`),l)throw l;return!i||!i.session||!i.user?{data:{user:null,session:null,redirectType:null},error:new f6e}:(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(ec(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 Kc(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:IC}),{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 f6e}:(c.session&&(await this._saveSession(c.session),await this._notifyAllSubscribers("SIGNED_IN",c.session)),{data:c,error:d})}catch(n){if(ec(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 nF(this.storage,this.storageKey));const{error:h}=await Kc(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 Kc(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 Tte("You must provide either an email or phone number.")}catch(o){if(ec(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 Kc(this.fetch,"POST",`${this.url}/verify`,{headers:this.headers,body:Object.assign(Object.assign({},t),{gotrue_meta_security:{captcha_token:i}}),redirectTo:a,xform:IC});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(ec(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 nF(this.storage,this.storageKey)),await Kc(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:Yts})}catch(i){if(ec(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 PC;const{error:a}=await Kc(this.fetch,"GET",`${this.url}/reauthenticate`,{headers:this.headers,jwt:n.access_token});return{data:{user:null,session:null},error:a}})}catch(t){if(ec(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 Kc(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 Kc(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 Tte("You must provide either an email or phone number and a type")}catch(n){if(ec(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 Mte(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 Kc(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:t,xform:cA}):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 PC}:await Kc(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:cA})})}catch(n){if(ec(n))return jts(n)&&(await this._removeSession(),await Lte(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 PC;const l=a.session;let o=null,c=null;this.flowType==="pkce"&&t.email!=null&&([o,c]=await nF(this.storage,this.storageKey));const{data:d,error:u}=await Kc(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:cA});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(ec(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 PC;const n=Date.now()/1e3;let r=n,a=!0,i=null;const{payload:l}=x6e(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(ec(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 PC;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(ec(n))return{data:{user:null,session:null},error:n};throw n}}async _getSessionFromURL(t,n){try{if(!dk())throw new Ete("No browser detected.");if(t.error||t.error_description||t.error_code)throw new Ete(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 ctt("Not a valid PKCE flow url.");break;case"pkce":if(this.flowType==="implicit")throw new Ete("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 ctt("No code detected.");const{data:b,error:k}=await this._exchangeCodeForSession(t.code);if(k)throw k;const A=new URL(window.location.href);return A.searchParams.delete("code"),window.history.replaceState(window.history.state,"",A.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 Ete("No session defined in URL");const u=Math.round(Date.now()/1e3),h=parseInt(o);let m=u+h;c&&(m=parseInt(c));const f=m-u;f*1e3<=QF&&console.warn(`@supabase/gotrue-js: Session as retrieved from URL expires in ${f}s, should have been closer to ${h}s`);const g=m-h;u-g>=120?console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued over 120s ago, URL could be stale",g,m,u):u-g<0&&console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued in the future? Check the device clock for skew",g,m,u);const{data:y,error:x}=await this._getUser(i);if(x)throw x;const _={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:_,redirectType:t.type},error:null}}catch(r){if(ec(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 Mte(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&&!(wts(o)&&(o.status===404||o.status===401||o.status===403)))return{error:o}}return t!=="others"&&(await this._removeSession(),await Lte(this.storage,`${this.storageKey}-code-verifier`)),{error:null}})}onAuthStateChange(t){const n=Lts(),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 nF(this.storage,this.storageKey,!0));try{return await Kc(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(ec(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(ec(n))return{data:null,error:n};throw n}}async linkIdentity(t){var n;try{const{data:r,error:a}=await this._useSession(async i=>{var l,o,c,d,u;const{data:h,error:m}=i;if(m)throw m;const f=await this._getUrlForProvider(`${this.url}/user/identities/authorize`,t.provider,{redirectTo:(l=t.options)===null||l===void 0?void 0:l.redirectTo,scopes:(o=t.options)===null||o===void 0?void 0:o.scopes,queryParams:(c=t.options)===null||c===void 0?void 0:c.queryParams,skipBrowserRedirect:!0});return await Kc(this.fetch,"GET",f,{headers:this.headers,jwt:(u=(d=h.session)===null||d===void 0?void 0:d.access_token)!==null&&u!==void 0?u:void 0})});if(a)throw a;return dk()&&!(!((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(ec(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 Kc(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(ec(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 Rts(async a=>(a>0&&await Dts(200*Math.pow(2,a-1)),this._debug(n,"refreshing attempt",a),await Kc(this.fetch,"POST",`${this.url}/token?grant_type=refresh_token`,{body:{refresh_token:t},headers:this.headers,xform:IC})),(a,i)=>{const l=200*Math.pow(2,a);return i&&g6e(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(),QF);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)/QF);this._debug("#_autoRefreshTokenTick()",`access token expires in ${a} ticks, a tick lasts ${QF}ms, refresh threshold is ${SDe} ticks`),a<=SDe&&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 z_t)this._debug("auto refresh token tick lock not available");else throw t}}async _handleVisibilityChange(){if(this._debug("#_handleVisibilityChange()"),!dk()||!(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 nF(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 Kc(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(ec(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 Kc(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(ec(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 Kc(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(ec(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 Kc(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(ec(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}=x6e(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+bts>Date.now()))return r;const{data:a,error:i}=await Kc(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 OW("JWKS is empty");if(this.jwks=a,this.jwks_cached_at=Date.now(),r=a.keys.find(l=>l.kid===t),!r)throw new OW("No matching signing key found in JWKS");return r}async getClaims(t,n={keys:[]}){try{let r=t;if(!r){const{data:f,error:g}=await this.getSession();if(g||!f.session)return{data:null,error:g};r=f.session.access_token}const{header:a,payload:i,signature:l,raw:{header:o,payload:c}}=x6e(r);if(qts(i.exp),!a.kid||a.alg==="HS256"||!("crypto"in globalThis&&"subtle"in globalThis.crypto)){const{error:f}=await this.getUser(r);if(f)throw f;return{data:{claims:i,header:a,signature:l},error:null}}const d=Vts(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,Ets(`${o}.${c}`)))throw new OW("Invalid JWT signature");return{data:{claims:i,header:a,signature:l},error:null}}catch(r){if(ec(r))return{data:null,error:r};throw r}}}oY.nextInstanceID=0;const iss=oY;class oss extends iss{constructor(t){super(t)}}var lss=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 css{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=pts(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:its,realtime:lts,auth:Object.assign(Object.assign({},ots),{storageKey:d}),global:ats},h=fts(r??{},u);this.storageKey=(a=h.auth.storageKey)!==null&&a!==void 0?a:"",this.headers=(i=h.global.headers)!==null&&i!==void 0?i:{},h.accessToken?(this.accessToken=h.accessToken,this.auth=new Proxy({},{get:(m,f)=>{throw new Error(`@supabase/supabase-js: Supabase Client is configured with the accessToken option, accessing supabase.auth.${String(f)} is not possible`)}})):this.auth=this._initSupabaseAuthClient((l=h.auth)!==null&&l!==void 0?l:{},this.headers,h.global.fetch),this.fetch=hts(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 Aes(new URL("rest/v1",c).href,{headers:this.headers,schema:h.db.schema,fetch:this.fetch}),h.accessToken||this._listenForAuthEvents()}get functions(){return new res(this.functionsUrl.href,{headers:this.headers,customFetch:this.fetch})}get storage(){return new sts(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 lss(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 oss({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 Ues(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 dss=(s,t,n)=>new css(s,t,n),uss="https://relzejiswnotikjgvjhz.supabase.co",hss="eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6InJlbHplamlzd25vdGlramd2amh6Iiwicm9sZSI6ImFub24iLCJpYXQiOjE3NjE5NTAzNDQsImV4cCI6MjA3NzUyNjM0NH0.dzIkIr_oFSbFE3oWS0ktIr83iKHHkZxt40Gc7SpC_mM",H=dss(uss,hss,{auth:{storage:localStorage,persistSession:!0,autoRefreshToken:!0}}),mss=Object.freeze(Object.defineProperty({__proto__:null,supabase:H},Symbol.toStringTag,{value:"Module"})),B_t=N.createContext(void 0),pss=({children:s})=>{const[t,n]=N.useState(null),[r,a]=N.useState(null),[i,l]=N.useState(!0),[o,c]=N.useState(!0),[d,u]=N.useState(!1),[h,m]=N.useState(!1),[f,g]=N.useState(!1),[y,x]=N.useState(null),[_,b]=N.useState([]),[k,A]=N.useState(null),T=N.useRef(null),P=N.useRef(!1),I=N.useRef(!1),M=tr(),L=()=>{u(!1),m(!1),g(!1),x(null),b([]),A(null),T.current=null,P.current=!1},z=async G=>{if(!(P.current&&T.current===G)&&!I.current){I.current=!0,c(!0);try{console.log("Checking roles via RPC for user:",G);const[{data:X,error:te},{data:ne,error:me},{data:ue,error:ce}]=await Promise.all([H.rpc("has_role",{_user_id:G,_role:"admin"}),H.rpc("has_role",{_user_id:G,_role:"brokerage_manager"}),H.rpc("has_role",{_user_id:G,_role:"coach"})]);if(te||me)console.error("Role RPC errors:",{isAdminError:te,isBrokerError:me,isCoachError:ce}),u(!1),m(!1),g(!1);else{const xe=!!X,ve=!!ne,ge=!!ue;console.log("RPC roles result:",{adminValue:xe,brokerValue:ve,coachValue:ge}),u(xe),m(ve),g(ge)}const{data:ae,error:he}=await H.from("profiles").select("brokerage_id").eq("id",G).single();if(x(!he&&ae?ae.brokerage_id:null),ne){console.log("Fetching managed brokerages for user:",G);const{data:xe,error:ve}=await H.from("brokerage_manager_assignments").select("brokerage_id").eq("user_id",G);if(console.log("Managed brokerage assignments result:",{assignments:xe,assignmentsError:ve}),ve||!xe){console.error("Error fetching managed brokerage assignments:",ve),b([]);return}const ge=Array.from(new Set(xe.map(Me=>Me.brokerage_id).filter(Boolean)));if(ge.length===0){b([]);return}const{data:be,error:Se}=await H.from("brokerages").select("id, name").in("id",ge);if(console.log("Managed brokerages details result:",{brokeragesData:be,brokeragesError:Se}),Se||!be){console.error("Error fetching managed brokerages details:",Se),b([]);return}const Ie=be.map(Me=>({id:Me.id,name:Me.name})).sort((Me,Re)=>ge.indexOf(Me.id)-ge.indexOf(Re.id));console.log("Parsed managed brokerages:",Ie),b(Ie),Ie.length>0&&A(Me=>Me??Ie[0].id)}else console.log("User is not a brokerage manager, skipping managed brokerages fetch"),b([]);T.current=G,P.current=!0}catch(X){console.error("Unexpected error in checkRoles:",X),L()}finally{I.current=!1,c(!1)}}};N.useEffect(()=>{let G=!0,X=!1;const te=()=>{!G||X||(X=!0,l(!1))},{data:{subscription:ne}}=H.auth.onAuthStateChange((ce,ae)=>{console.log("Auth event:",ce),G&&(a(ae),n((ae==null?void 0:ae.user)??null),te(),ce==="PASSWORD_RECOVERY"&&(console.log("Password recovery detected, redirecting to profile"),setTimeout(()=>{M("/profile?reset=true")},100)),ae!=null&&ae.user?(!P.current||T.current!==ae.user.id)&&setTimeout(()=>{z(ae.user.id)},0):(L(),c(!1)))}),me=window.setTimeout(()=>{console.warn("Auth initialization timeout reached. Continuing without blocking UI."),te()},4e3);return(async()=>{try{const{data:{session:ce}}=await H.auth.getSession();if(!G)return;a(ce),n((ce==null?void 0:ce.user)??null),ce!=null&&ce.user?await z(ce.user.id):L()}catch(ce){console.error("Error restoring auth session:",ce),G&&(a(null),n(null),L())}finally{te()}})(),()=>{G=!1,window.clearTimeout(me),ne.unsubscribe()}},[]);const $=async(G,X)=>{const{error:te}=await H.auth.signInWithPassword({email:G,password:X});if(te)throw ie.error(te.message),te;ie.success("Welcome back!")},V=async(G,X,te)=>{var ae;const ne=`${window.location.origin}/dashboard`,me=localStorage.getItem("levelup_referral_code")||null,{data:ue,error:ce}=await H.auth.signUp({email:G,password:X,options:{emailRedirectTo:ne,data:{name:te,referred_by_code:me}}});if(ce)throw ie.error(ce.message),ce;if(me&&((ae=ue.user)!=null&&ae.id))try{await H.from("profiles").update({referred_by_code:me}).eq("id",ue.user.id),localStorage.removeItem("levelup_referral_code")}catch(he){console.warn("Failed to attach referral code to profile",he)}ie.success("Account created! Welcome to LevelUp."),M("/dashboard")},W=async()=>{try{const{data:{session:G}}=await H.auth.getSession();if(G){const{error:X}=await H.auth.signOut();X?X.message==="Auth session missing!"?console.warn("Sign out warning (ignored):",X.message):(console.error("Sign out error:",X),ie.error(X.message)):ie.success("Signed out successfully")}else console.log("No active session found, redirecting to auth");n(null),a(null),u(!1),m(!1),x(null),b([]),A(null),M("/auth")}catch(G){console.error("Unexpected sign out error:",G),M("/auth")}};return e.jsx(B_t.Provider,{value:{user:t,session:r,loading:i,rolesLoading:o,signIn:$,signUp:V,signOut:W,isAdmin:d,isBrokerageManager:h,isCoach:f,brokerageId:y,managedBrokerages:_,selectedBrokerageId:k,setSelectedBrokerageId:A},children:s})},Ls=()=>{const s=N.useContext(B_t);if(s===void 0)throw new Error("useAuth must be used within an AuthProvider");return s},$_t=N.createContext({onlineUsers:[],totalOnline:0}),fss=async s=>{try{const{data:t}=await H.storage.from("avatars").list(`${s}`);if(t&&t.length>0){const{data:n}=H.storage.from("avatars").getPublicUrl(`${s}/${t[0].name}`);return n.publicUrl}}catch{}},gss=({children:s})=>{const{user:t,brokerageId:n,isAdmin:r}=Ls(),[a,i]=N.useState([]),[l,o]=N.useState(null);N.useEffect(()=>{if(!t)return;let d=!1;H.auth.getSession().then(({data:h})=>{var f;const m=(f=h.session)==null?void 0:f.access_token;if(m)try{H.realtime.setAuth(m)}catch{}});const u=H.channel("app-presence-v2",{config:{presence:{key:t.id},broadcast:{self:!0}}});return u.on("presence",{event:"sync"},()=>{const h=u.presenceState(),m=[];Object.entries(h).forEach(([f,g])=>{if(g&&g.length>0){const y=g[0];m.push({id:f,name:y.name||"Unknown",avatarUrl:y.avatarUrl,brokerageId:y.brokerageId,onlineSince:y.onlineSince})}}),console.log("[Presence] sync, users:",m.length,m),i(m)}).on("presence",{event:"join"},({key:h,newPresences:m})=>{console.log("[Presence] join",h,m)}).on("presence",{event:"leave"},({key:h})=>{console.log("[Presence] leave",h)}).subscribe(async(h,m)=>{var f;if(console.log("[Presence] subscribe status:",h,m),h==="SUBSCRIBED"&&!d){const{data:g}=await H.from("profiles").select("name, brokerage_id").eq("id",t.id).maybeSingle(),y=await fss(t.id),x=await u.track({name:(g==null?void 0:g.name)||((f=t.email)==null?void 0:f.split("@")[0])||"User",avatarUrl:y,brokerageId:g==null?void 0:g.brokerage_id,onlineSince:new Date().toISOString()});console.log("[Presence] track result:",x)}}),o(u),()=>{d=!0;try{u.untrack()}catch{}H.removeChannel(u)}},[t==null?void 0:t.id]);const c=a.filter(d=>d.id===(t==null?void 0:t.id)?!1:!!(r||n&&d.brokerageId===n||!n&&!d.brokerageId));return e.jsx($_t.Provider,{value:{onlineUsers:c,totalOnline:a.length},children:s})},U_t=()=>N.useContext($_t),q_t=N.createContext(void 0),R6="levelup_admin_session",xC="levelup_impersonation",y6e="levelup_impersonation_return",xss=({children:s})=>{const[t,n]=N.useState(!1),[r,a]=N.useState(null),[i,l]=N.useState(!1);N.useEffect(()=>{const d=sessionStorage.getItem(xC);if(d)try{const u=JSON.parse(d);n(!0),a(u)}catch{sessionStorage.removeItem(xC)}},[]);const o=async(d,u)=>{l(!0);try{const{data:{session:h}}=await H.auth.getSession();if(!h)return ie.error("No active session found"),!1;const m={access_token:h.access_token,refresh_token:h.refresh_token};sessionStorage.setItem(R6,JSON.stringify(m)),u&&sessionStorage.setItem(y6e,u);const f=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/impersonate-user",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${h.access_token}`},body:JSON.stringify({targetUserId:d})}),g=await f.json();if(!f.ok)throw new Error(g.error||"Failed to impersonate user");const y={id:g.targetUser.id,name:g.targetUser.name,email:g.targetUser.email};if(sessionStorage.setItem(xC,JSON.stringify(y)),g.method==="session"){const{error:x}=await H.auth.setSession({access_token:g.access_token,refresh_token:g.refresh_token});if(x)throw console.error("Set session error:",x),sessionStorage.removeItem(R6),sessionStorage.removeItem(xC),new Error("Failed to establish impersonation session")}else{const x=g.type||"recovery",{error:_}=await H.auth.verifyOtp({token_hash:g.token_hash,type:x});if(_)throw console.error("Verify OTP error:",_),sessionStorage.removeItem(R6),sessionStorage.removeItem(xC),new Error("Failed to establish impersonation session")}return n(!0),a(y),ie.success(`Now viewing as ${y.name}`),window.location.href="/dashboard",!0}catch(h){return console.error("Impersonation error:",h),ie.error(h.message||"Failed to impersonate user"),sessionStorage.removeItem(R6),sessionStorage.removeItem(xC),!1}finally{l(!1)}},c=async()=>{l(!0);try{const d=sessionStorage.getItem(R6);if(!d){await H.auth.signOut(),window.location.href="/auth";return}const u=JSON.parse(d);await H.auth.signOut();const{error:h}=await H.auth.setSession({access_token:u.access_token,refresh_token:u.refresh_token});if(sessionStorage.removeItem(R6),sessionStorage.removeItem(xC),h){console.error("Failed to restore admin session:",h),ie.error("Admin session expired, please sign in again"),window.location.href="/auth";return}n(!1),a(null),ie.success("Returned to your account");const m=sessionStorage.getItem(y6e)||"/admin/members";sessionStorage.removeItem(y6e),window.location.href=m}catch(d){console.error("Stop impersonation error:",d),ie.error("Failed to restore admin session"),sessionStorage.removeItem(R6),sessionStorage.removeItem(xC),window.location.href="/auth"}finally{l(!1)}};return e.jsx(q_t.Provider,{value:{isImpersonating:t,impersonatedUser:r,startImpersonation:o,stopImpersonation:c,isLoading:i},children:s})},s4e=()=>{const s=N.useContext(q_t);if(s===void 0)throw new Error("useImpersonation must be used within an ImpersonationProvider");return s},DB=RR("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=N.forwardRef(({className:s,variant:t,size:n,asChild:r=!1,...a},i)=>{const l=r?JBe:"button";return e.jsx(l,{className:Ot(DB({variant:t,size:n,className:s})),ref:i,...a})});B.displayName="Button";const yss=()=>{const{isImpersonating:s,impersonatedUser:t,stopImpersonation:n,isLoading:r}=s4e();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(xd,{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(us,{className:"h-4 w-4 animate-spin"}):e.jsxs(e.Fragment,{children:[e.jsx(hr,{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"})]})})]})})},V_t=N.createContext(void 0),aF="levelup_acting_as",Pte="levelup_acting_as_self",vss=({children:s})=>{const{user:t}=Ls(),[n,r]=N.useState(!1),[a,i]=N.useState([]),[l,o]=N.useState(null),[c,d]=N.useState({}),[u,h]=N.useState(!0),[m,f]=N.useState(()=>sessionStorage.getItem(Pte)==="true");N.useEffect(()=>{if(!(t!=null&&t.id)){r(!1),i([]),o(null),d({}),h(!1);return}(async()=>{h(!0);try{const{data:k}=await H.rpc("has_role",{_user_id:t.id,_role:"assistant"});if(!k){r(!1),i([]),o(null),d({}),h(!1);return}r(!0);const{data:A,error:T}=await H.from("agent_assistant_assignments").select("agent_id, permissions").eq("assistant_id",t.id);if(T||!A||A.length===0){i([]),h(!1);return}const P=A.map(L=>L.agent_id),{data:I}=await H.from("profiles").select("id, name, email, avatar_url").in("id",P),M=(I||[]).map(L=>({id:L.id,name:L.name||L.email||"Unknown",email:L.email||"",avatar_url:L.avatar_url}));if(i(M),sessionStorage.getItem(Pte)==="true")f(!0),o(null),d({});else{const L=sessionStorage.getItem(aF);if(L){const z=M.find($=>$.id===L);if(z){o(z);const $=A.find(V=>V.agent_id===L);d(($==null?void 0:$.permissions)||{})}else if(M.length>0){o(M[0]);const $=A.find(V=>V.agent_id===M[0].id);d(($==null?void 0:$.permissions)||{}),sessionStorage.setItem(aF,M[0].id)}}else if(M.length>0){o(M[0]);const z=A.find($=>$.agent_id===M[0].id);d((z==null?void 0:z.permissions)||{}),sessionStorage.setItem(aF,M[0].id)}}}catch(k){console.error("Error loading assistant data:",k)}finally{h(!1)}})()},[t==null?void 0:t.id]);const g=b=>{o(b),f(!1),sessionStorage.removeItem(Pte),b?(sessionStorage.setItem(aF,b.id),H.from("agent_assistant_assignments").select("permissions").eq("assistant_id",(t==null?void 0:t.id)||"").eq("agent_id",b.id).single().then(({data:k})=>{d((k==null?void 0:k.permissions)||{})})):(sessionStorage.removeItem(aF),d({}))},y=()=>{f(!0),o(null),d({}),sessionStorage.setItem(Pte,"true"),sessionStorage.removeItem(aF)},x=b=>!n||m?!0:c[b]===!0,_=n&&l&&!m?l.id:(t==null?void 0:t.id)||null;return e.jsx(V_t.Provider,{value:{isAssistant:n,assignedAgents:a,actingAsAgent:l,setActingAsAgent:g,effectiveUserId:_,permissions:c,hasPermission:x,isLoading:u,isActingAsSelf:m,setActingAsSelf:y},children:s})},n4e=()=>{const s=N.useContext(V_t);if(s===void 0)throw new Error("useActingAs must be used within an ActingAsProvider");return s},Ya=()=>{const{effectiveUserId:s}=n4e();return s};var H_t={exports:{}},G_t={};/** * @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 RB=N;function bss(s,t){return s===t&&(s!==0||1/s===1/t)||s!==s&&t!==t}var _ss=typeof Object.is=="function"?Object.is:bss,wss=RB.useState,jss=RB.useEffect,Nss=RB.useLayoutEffect,kss=RB.useDebugValue;function Sss(s,t){var n=t(),r=wss({inst:{value:n,getSnapshot:t}}),a=r[0].inst,i=r[1];return Nss(function(){a.value=n,a.getSnapshot=t,v6e(a)&&i({inst:a})},[s,n,t]),jss(function(){return v6e(a)&&i({inst:a}),s(function(){v6e(a)&&i({inst:a})})},[s]),kss(n),n}function v6e(s){var t=s.getSnapshot;s=s.value;try{var n=t();return!_ss(s,n)}catch{return!0}}function Css(s,t){return t()}var Ass=typeof window>"u"||typeof window.document>"u"||typeof window.document.createElement>"u"?Css:Sss;G_t.useSyncExternalStore=RB.useSyncExternalStore!==void 0?RB.useSyncExternalStore:Ass;H_t.exports=G_t;var Tss=H_t.exports;function Ess(){return Tss.useSyncExternalStore(Mss,()=>!0,()=>!1)}function Mss(){return()=>{}}var S$e="Avatar",[Lss,COn]=Um(S$e),[Pss,W_t]=Lss(S$e),K_t=N.forwardRef((s,t)=>{const{__scopeAvatar:n,...r}=s,[a,i]=N.useState("idle");return e.jsx(Pss,{scope:n,imageLoadingStatus:a,onImageLoadingStatusChange:i,children:e.jsx(Da.span,{...r,ref:t})})});K_t.displayName=S$e;var Y_t="AvatarImage",Z_t=N.forwardRef((s,t)=>{const{__scopeAvatar:n,src:r,onLoadingStatusChange:a=()=>{},...i}=s,l=W_t(Y_t,n),o=Iss(r,i),c=cf(d=>{a(d),l.onImageLoadingStatusChange(d)});return gf(()=>{o!=="idle"&&c(o)},[o,c]),o==="loaded"?e.jsx(Da.img,{...i,ref:t,src:r}):null});Z_t.displayName=Y_t;var X_t="AvatarFallback",Q_t=N.forwardRef((s,t)=>{const{__scopeAvatar:n,delayMs:r,...a}=s,i=W_t(X_t,n),[l,o]=N.useState(r===void 0);return N.useEffect(()=>{if(r!==void 0){const c=window.setTimeout(()=>o(!0),r);return()=>window.clearTimeout(c)}},[r]),l&&i.imageLoadingStatus!=="loaded"?e.jsx(Da.span,{...a,ref:t}):null});Q_t.displayName=X_t;function ytt(s,t){return s?t?(s.src!==t&&(s.src=t),s.complete&&s.naturalWidth>0?"loaded":"loading"):"error":"idle"}function Iss(s,{referrerPolicy:t,crossOrigin:n}){const r=Ess(),a=N.useRef(null),i=r?(a.current||(a.current=new window.Image),a.current):null,[l,o]=N.useState(()=>ytt(i,s));return gf(()=>{o(ytt(i,s))},[i,s]),gf(()=>{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 J_t=K_t,ewt=Z_t,twt=Q_t;const Ua=N.forwardRef(({className:s,...t},n)=>e.jsx(J_t,{ref:n,className:Ot("relative flex h-10 w-10 shrink-0 overflow-hidden rounded-full",s),...t}));Ua.displayName=J_t.displayName;const Gi=N.forwardRef(({className:s,...t},n)=>e.jsx(ewt,{ref:n,className:Ot("aspect-square h-full w-full",s),...t}));Gi.displayName=ewt.displayName;const qa=N.forwardRef(({className:s,...t},n)=>e.jsx(twt,{ref:n,className:Ot("flex h-full w-full items-center justify-center rounded-full bg-muted",s),...t}));qa.displayName=twt.displayName;const Dss=RR("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 We({className:s,variant:t,...n}){return e.jsx("div",{className:Ot(Dss({variant:t}),s),...n})}var Rss=N.createContext(void 0);function F3(s){const t=N.useContext(Rss);return s||t||"ltr"}var b6e=0;function r4e(){N.useEffect(()=>{const s=document.querySelectorAll("[data-radix-focus-guard]");return document.body.insertAdjacentElement("afterbegin",s[0]??vtt()),document.body.insertAdjacentElement("beforeend",s[1]??vtt()),b6e++,()=>{b6e===1&&document.querySelectorAll("[data-radix-focus-guard]").forEach(t=>t.remove()),b6e--}},[])}function vtt(){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 _6e="focusScope.autoFocusOnMount",w6e="focusScope.autoFocusOnUnmount",btt={bubbles:!1,cancelable:!0},Oss="FocusScope",_Q=N.forwardRef((s,t)=>{const{loop:n=!1,trapped:r=!1,onMountAutoFocus:a,onUnmountAutoFocus:i,...l}=s,[o,c]=N.useState(null),d=cf(a),u=cf(i),h=N.useRef(null),m=jo(t,y=>c(y)),f=N.useRef({paused:!1,pause(){this.paused=!0},resume(){this.paused=!1}}).current;N.useEffect(()=>{if(r){let y=function(k){if(f.paused||!o)return;const A=k.target;o.contains(A)?h.current=A:DC(h.current,{select:!0})},x=function(k){if(f.paused||!o)return;const A=k.relatedTarget;A!==null&&(o.contains(A)||DC(h.current,{select:!0}))},_=function(k){if(document.activeElement===document.body)for(const T of k)T.removedNodes.length>0&&DC(o)};document.addEventListener("focusin",y),document.addEventListener("focusout",x);const b=new MutationObserver(_);return o&&b.observe(o,{childList:!0,subtree:!0}),()=>{document.removeEventListener("focusin",y),document.removeEventListener("focusout",x),b.disconnect()}}},[r,o,f.paused]),N.useEffect(()=>{if(o){wtt.add(f);const y=document.activeElement;if(!o.contains(y)){const _=new CustomEvent(_6e,btt);o.addEventListener(_6e,d),o.dispatchEvent(_),_.defaultPrevented||(Fss(qss(swt(o)),{select:!0}),document.activeElement===y&&DC(o))}return()=>{o.removeEventListener(_6e,d),setTimeout(()=>{const _=new CustomEvent(w6e,btt);o.addEventListener(w6e,u),o.dispatchEvent(_),_.defaultPrevented||DC(y??document.body,{select:!0}),o.removeEventListener(w6e,u),wtt.remove(f)},0)}}},[o,d,u,f]);const g=N.useCallback(y=>{if(!n&&!r||f.paused)return;const x=y.key==="Tab"&&!y.altKey&&!y.ctrlKey&&!y.metaKey,_=document.activeElement;if(x&&_){const b=y.currentTarget,[k,A]=zss(b);k&&A?!y.shiftKey&&_===A?(y.preventDefault(),n&&DC(k,{select:!0})):y.shiftKey&&_===k&&(y.preventDefault(),n&&DC(A,{select:!0})):_===b&&y.preventDefault()}},[n,r,f.paused]);return e.jsx(Da.div,{tabIndex:-1,...l,ref:m,onKeyDown:g})});_Q.displayName=Oss;function Fss(s,{select:t=!1}={}){const n=document.activeElement;for(const r of s)if(DC(r,{select:t}),document.activeElement!==n)return}function zss(s){const t=swt(s),n=_tt(t,s),r=_tt(t.reverse(),s);return[n,r]}function swt(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 _tt(s,t){for(const n of s)if(!Bss(n,{upTo:t}))return n}function Bss(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 $ss(s){return s instanceof HTMLInputElement&&"select"in s}function DC(s,{select:t=!1}={}){if(s&&s.focus){const n=document.activeElement;s.focus({preventScroll:!0}),s!==n&&$ss(s)&&t&&s.select()}}var wtt=Uss();function Uss(){let s=[];return{add(t){const n=s[0];t!==n&&(n==null||n.pause()),s=jtt(s,t),s.unshift(t)},remove(t){var n;s=jtt(s,t),(n=s[0])==null||n.resume()}}}function jtt(s,t){const n=[...s],r=n.indexOf(t);return r!==-1&&n.splice(r,1),n}function qss(s){return s.filter(t=>t.tagName!=="A")}var j6e="rovingFocusGroup.onEntryFocus",Vss={bubbles:!1,cancelable:!0},wQ="RovingFocusGroup",[TDe,nwt,Hss]=K$(wQ),[Gss,ME]=Um(wQ,[Hss]),[Wss,Kss]=Gss(wQ),rwt=N.forwardRef((s,t)=>e.jsx(TDe.Provider,{scope:s.__scopeRovingFocusGroup,children:e.jsx(TDe.Slot,{scope:s.__scopeRovingFocusGroup,children:e.jsx(Yss,{...s,ref:t})})}));rwt.displayName=wQ;var Yss=N.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=N.useRef(null),f=jo(t,m),g=F3(i),[y,x]=Ng({prop:l,defaultProp:o??null,onChange:c,caller:wQ}),[_,b]=N.useState(!1),k=cf(d),A=nwt(n),T=N.useRef(!1),[P,I]=N.useState(0);return N.useEffect(()=>{const M=m.current;if(M)return M.addEventListener(j6e,k),()=>M.removeEventListener(j6e,k)},[k]),e.jsx(Wss,{scope:n,orientation:r,dir:g,loop:a,currentTabStopId:y,onItemFocus:N.useCallback(M=>x(M),[x]),onItemShiftTab:N.useCallback(()=>b(!0),[]),onFocusableItemAdd:N.useCallback(()=>I(M=>M+1),[]),onFocusableItemRemove:N.useCallback(()=>I(M=>M-1),[]),children:e.jsx(Da.div,{tabIndex:_||P===0?-1:0,"data-orientation":r,...h,ref:f,style:{outline:"none",...s.style},onMouseDown:la(s.onMouseDown,()=>{T.current=!0}),onFocus:la(s.onFocus,M=>{const L=!T.current;if(M.target===M.currentTarget&&L&&!_){const z=new CustomEvent(j6e,Vss);if(M.currentTarget.dispatchEvent(z),!z.defaultPrevented){const $=A().filter(te=>te.focusable),V=$.find(te=>te.active),W=$.find(te=>te.id===y),X=[V,W,...$].filter(Boolean).map(te=>te.ref.current);owt(X,u)}}T.current=!1}),onBlur:la(s.onBlur,()=>b(!1))})})}),awt="RovingFocusGroupItem",iwt=N.forwardRef((s,t)=>{const{__scopeRovingFocusGroup:n,focusable:r=!0,active:a=!1,tabStopId:i,children:l,...o}=s,c=_g(),d=i||c,u=Kss(awt,n),h=u.currentTabStopId===d,m=nwt(n),{onFocusableItemAdd:f,onFocusableItemRemove:g,currentTabStopId:y}=u;return N.useEffect(()=>{if(r)return f(),()=>g()},[r,f,g]),e.jsx(TDe.ItemSlot,{scope:n,id:d,focusable:r,active:a,children:e.jsx(Da.span,{tabIndex:h?0:-1,"data-orientation":u.orientation,...o,ref:t,onMouseDown:la(s.onMouseDown,x=>{r?u.onItemFocus(d):x.preventDefault()}),onFocus:la(s.onFocus,()=>u.onItemFocus(d)),onKeyDown:la(s.onKeyDown,x=>{if(x.key==="Tab"&&x.shiftKey){u.onItemShiftTab();return}if(x.target!==x.currentTarget)return;const _=Qss(x,u.orientation,u.dir);if(_!==void 0){if(x.metaKey||x.ctrlKey||x.altKey||x.shiftKey)return;x.preventDefault();let k=m().filter(A=>A.focusable).map(A=>A.ref.current);if(_==="last")k.reverse();else if(_==="prev"||_==="next"){_==="prev"&&k.reverse();const A=k.indexOf(x.currentTarget);k=u.loop?Jss(k,A+1):k.slice(A+1)}setTimeout(()=>owt(k))}}),children:typeof l=="function"?l({isCurrentTabStop:h,hasTabStop:y!=null}):l})})});iwt.displayName=awt;var Zss={ArrowLeft:"prev",ArrowUp:"prev",ArrowRight:"next",ArrowDown:"next",PageUp:"first",Home:"first",PageDown:"last",End:"last"};function Xss(s,t){return t!=="rtl"?s:s==="ArrowLeft"?"ArrowRight":s==="ArrowRight"?"ArrowLeft":s}function Qss(s,t,n){const r=Xss(s.key,n);if(!(t==="vertical"&&["ArrowLeft","ArrowRight"].includes(r))&&!(t==="horizontal"&&["ArrowUp","ArrowDown"].includes(r)))return Zss[r]}function owt(s,t=!1){const n=document.activeElement;for(const r of s)if(r===n||(r.focus({preventScroll:t}),document.activeElement!==n))return}function Jss(s,t){return s.map((n,r)=>s[(t+r)%s.length])}var a4e=rwt,i4e=iwt,ens=function(s){if(typeof document>"u")return null;var t=Array.isArray(s)?s[0]:s;return t.ownerDocument.body},iF=new WeakMap,Ite=new WeakMap,Dte={},N6e=0,lwt=function(s){return s&&(s.host||lwt(s.parentNode))},tns=function(s,t){return t.map(function(n){if(s.contains(n))return n;var r=lwt(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})},sns=function(s,t,n,r){var a=tns(t,Array.isArray(s)?s:[s]);Dte[n]||(Dte[n]=new WeakMap);var i=Dte[n],l=[],o=new Set,c=new Set(a),d=function(h){!h||o.has(h)||(o.add(h),d(h.parentNode))};a.forEach(d);var u=function(h){!h||c.has(h)||Array.prototype.forEach.call(h.children,function(m){if(o.has(m))u(m);else try{var f=m.getAttribute(r),g=f!==null&&f!=="false",y=(iF.get(m)||0)+1,x=(i.get(m)||0)+1;iF.set(m,y),i.set(m,x),l.push(m),y===1&&g&&Ite.set(m,!0),x===1&&m.setAttribute(n,"true"),g||m.setAttribute(r,"true")}catch(_){console.error("aria-hidden: cannot operate on ",m,_)}})};return u(t),o.clear(),N6e++,function(){l.forEach(function(h){var m=iF.get(h)-1,f=i.get(h)-1;iF.set(h,m),i.set(h,f),m||(Ite.has(h)||h.removeAttribute(r),Ite.delete(h)),f||h.removeAttribute(n)}),N6e--,N6e||(iF=new WeakMap,iF=new WeakMap,Ite=new WeakMap,Dte={})}},o4e=function(s,t,n){n===void 0&&(n="data-aria-hidden");var r=Array.from(Array.isArray(s)?s:[s]),a=ens(s);return a?(r.push.apply(r,Array.from(a.querySelectorAll("[aria-live]"))),sns(r,a,n,"aria-hidden")):function(){return null}},Wk=function(){return Wk=Object.assign||function(t){for(var n,r=1,a=arguments.length;r"u")return vns;var t=bns(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])}},wns=hwt(),$9="data-scroll-locked",jns=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(rns,` { overflow: hidden `).concat(r,`; padding-right: `).concat(o,"px ").concat(r,`; } body[`).concat($9,`] { 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(kwe,` { right: `).concat(o,"px ").concat(r,`; } .`).concat(Swe,` { margin-right: `).concat(o,"px ").concat(r,`; } .`).concat(kwe," .").concat(kwe,` { right: 0 `).concat(r,`; } .`).concat(Swe," .").concat(Swe,` { margin-right: 0 `).concat(r,`; } body[`).concat($9,`] { `).concat(ans,": ").concat(o,`px; } `)},ktt=function(){var s=parseInt(document.body.getAttribute($9)||"0",10);return isFinite(s)?s:0},Nns=function(){N.useEffect(function(){return document.body.setAttribute($9,(ktt()+1).toString()),function(){var s=ktt()-1;s<=0?document.body.removeAttribute($9):document.body.setAttribute($9,s.toString())}},[])},kns=function(s){var t=s.noRelative,n=s.noImportant,r=s.gapMode,a=r===void 0?"margin":r;Nns();var i=N.useMemo(function(){return _ns(a)},[a]);return N.createElement(wns,{styles:jns(i,!t,a,n?"":"!important")})},EDe=!1;if(typeof window<"u")try{var Rte=Object.defineProperty({},"passive",{get:function(){return EDe=!0,!0}});window.addEventListener("test",Rte,Rte),window.removeEventListener("test",Rte,Rte)}catch{EDe=!1}var oF=EDe?{passive:!1}:!1,Sns=function(s){return s.tagName==="TEXTAREA"},mwt=function(s,t){if(!(s instanceof Element))return!1;var n=window.getComputedStyle(s);return n[t]!=="hidden"&&!(n.overflowY===n.overflowX&&!Sns(s)&&n[t]==="visible")},Cns=function(s){return mwt(s,"overflowY")},Ans=function(s){return mwt(s,"overflowX")},Stt=function(s,t){var n=t.ownerDocument,r=t;do{typeof ShadowRoot<"u"&&r instanceof ShadowRoot&&(r=r.host);var a=pwt(s,r);if(a){var i=fwt(s,r),l=i[1],o=i[2];if(l>o)return!0}r=r.parentNode}while(r&&r!==n.body);return!1},Tns=function(s){var t=s.scrollTop,n=s.scrollHeight,r=s.clientHeight;return[t,n,r]},Ens=function(s){var t=s.scrollLeft,n=s.scrollWidth,r=s.clientWidth;return[t,n,r]},pwt=function(s,t){return s==="v"?Cns(t):Ans(t)},fwt=function(s,t){return s==="v"?Tns(t):Ens(t)},Mns=function(s,t){return s==="h"&&t==="rtl"?-1:1},Lns=function(s,t,n,r,a){var i=Mns(s,window.getComputedStyle(t).direction),l=i*r,o=n.target,c=t.contains(o),d=!1,u=l>0,h=0,m=0;do{if(!o)break;var f=fwt(s,o),g=f[0],y=f[1],x=f[2],_=y-x-i*g;(g||_)&&pwt(s,o)&&(h+=_,m+=g);var b=o.parentNode;o=b&&b.nodeType===Node.DOCUMENT_FRAGMENT_NODE?b.host:b}while(!c&&o!==document.body||c&&(t.contains(o)||t===o));return(u&&(Math.abs(h)<1||!a)||!u&&(Math.abs(m)<1||!a))&&(d=!0),d},Ote=function(s){return"changedTouches"in s?[s.changedTouches[0].clientX,s.changedTouches[0].clientY]:[0,0]},Ctt=function(s){return[s.deltaX,s.deltaY]},Att=function(s){return s&&"current"in s?s.current:s},Pns=function(s,t){return s[0]===t[0]&&s[1]===t[1]},Ins=function(s){return` .block-interactivity-`.concat(s,` {pointer-events: none;} .allow-interactivity-`).concat(s,` {pointer-events: all;} `)},Dns=0,lF=[];function Rns(s){var t=N.useRef([]),n=N.useRef([0,0]),r=N.useRef(),a=N.useState(Dns++)[0],i=N.useState(hwt)[0],l=N.useRef(s);N.useEffect(function(){l.current=s},[s]),N.useEffect(function(){if(s.inert){document.body.classList.add("block-interactivity-".concat(a));var y=nns([s.lockRef.current],(s.shards||[]).map(Att),!0).filter(Boolean);return y.forEach(function(x){return x.classList.add("allow-interactivity-".concat(a))}),function(){document.body.classList.remove("block-interactivity-".concat(a)),y.forEach(function(x){return x.classList.remove("allow-interactivity-".concat(a))})}}},[s.inert,s.lockRef.current,s.shards]);var o=N.useCallback(function(y,x){if("touches"in y&&y.touches.length===2||y.type==="wheel"&&y.ctrlKey)return!l.current.allowPinchZoom;var _=Ote(y),b=n.current,k="deltaX"in y?y.deltaX:b[0]-_[0],A="deltaY"in y?y.deltaY:b[1]-_[1],T,P=y.target,I=Math.abs(k)>Math.abs(A)?"h":"v";if("touches"in y&&I==="h"&&P.type==="range")return!1;var M=Stt(I,P);if(!M)return!0;if(M?T=I:(T=I==="v"?"h":"v",M=Stt(I,P)),!M)return!1;if(!r.current&&"changedTouches"in y&&(k||A)&&(r.current=T),!T)return!0;var L=r.current||T;return Lns(L,x,y,L==="h"?k:A,!0)},[]),c=N.useCallback(function(y){var x=y;if(!(!lF.length||lF[lF.length-1]!==i)){var _="deltaY"in x?Ctt(x):Ote(x),b=t.current.filter(function(T){return T.name===x.type&&(T.target===x.target||x.target===T.shadowParent)&&Pns(T.delta,_)})[0];if(b&&b.should){x.cancelable&&x.preventDefault();return}if(!b){var k=(l.current.shards||[]).map(Att).filter(Boolean).filter(function(T){return T.contains(x.target)}),A=k.length>0?o(x,k[0]):!l.current.noIsolation;A&&x.cancelable&&x.preventDefault()}}},[]),d=N.useCallback(function(y,x,_,b){var k={name:y,delta:x,target:_,should:b,shadowParent:Ons(_)};t.current.push(k),setTimeout(function(){t.current=t.current.filter(function(A){return A!==k})},1)},[]),u=N.useCallback(function(y){n.current=Ote(y),r.current=void 0},[]),h=N.useCallback(function(y){d(y.type,Ctt(y),y.target,o(y,s.lockRef.current))},[]),m=N.useCallback(function(y){d(y.type,Ote(y),y.target,o(y,s.lockRef.current))},[]);N.useEffect(function(){return lF.push(i),s.setCallbacks({onScrollCapture:h,onWheelCapture:h,onTouchMoveCapture:m}),document.addEventListener("wheel",c,oF),document.addEventListener("touchmove",c,oF),document.addEventListener("touchstart",u,oF),function(){lF=lF.filter(function(y){return y!==i}),document.removeEventListener("wheel",c,oF),document.removeEventListener("touchmove",c,oF),document.removeEventListener("touchstart",u,oF)}},[]);var f=s.removeScrollBar,g=s.inert;return N.createElement(N.Fragment,null,g?N.createElement(i,{styles:Ins(a)}):null,f?N.createElement(kns,{noRelative:s.noRelative,gapMode:s.gapMode}):null)}function Ons(s){for(var t=null;s!==null;)s instanceof ShadowRoot&&(t=s.host,s=s.host),s=s.parentNode;return t}const Fns=hns(uwt,Rns);var jQ=N.forwardRef(function(s,t){return N.createElement(l4e,Wk({},s,{ref:t,sideCar:Fns}))});jQ.classNames=l4e.classNames;var MDe=["Enter"," "],zns=["ArrowDown","PageUp","Home"],gwt=["ArrowUp","PageDown","End"],Bns=[...zns,...gwt],$ns={ltr:[...MDe,"ArrowRight"],rtl:[...MDe,"ArrowLeft"]},Uns={ltr:["ArrowLeft"],rtl:["ArrowRight"]},NQ="Menu",[lY,qns,Vns]=K$(NQ),[FR,xwt]=Um(NQ,[Vns,q5,ME]),c4e=q5(),ywt=ME(),[Hns,zR]=FR(NQ),[Gns,kQ]=FR(NQ),vwt=s=>{const{__scopeMenu:t,open:n=!1,children:r,dir:a,onOpenChange:i,modal:l=!0}=s,o=c4e(t),[c,d]=N.useState(null),u=N.useRef(!1),h=cf(i),m=F3(a);return N.useEffect(()=>{const f=()=>{u.current=!0,document.addEventListener("pointerdown",g,{capture:!0,once:!0}),document.addEventListener("pointermove",g,{capture:!0,once:!0})},g=()=>u.current=!1;return document.addEventListener("keydown",f,{capture:!0}),()=>{document.removeEventListener("keydown",f,{capture:!0}),document.removeEventListener("pointerdown",g,{capture:!0}),document.removeEventListener("pointermove",g,{capture:!0})}},[]),e.jsx(gQ,{...o,children:e.jsx(Hns,{scope:t,open:n,onOpenChange:h,content:c,onContentChange:d,children:e.jsx(Gns,{scope:t,onClose:N.useCallback(()=>h(!1),[h]),isUsingKeyboardRef:u,dir:m,modal:l,children:r})})})};vwt.displayName=NQ;var Wns="MenuAnchor",C$e=N.forwardRef((s,t)=>{const{__scopeMenu:n,...r}=s,a=c4e(n);return e.jsx(J$,{...a,...r,ref:t})});C$e.displayName=Wns;var A$e="MenuPortal",[Kns,bwt]=FR(A$e,{forceMount:void 0}),_wt=s=>{const{__scopeMenu:t,forceMount:n,children:r,container:a}=s,i=zR(A$e,t);return e.jsx(Kns,{scope:t,forceMount:n,children:e.jsx(Xf,{present:n||i.open,children:e.jsx(Y$,{asChild:!0,container:a,children:r})})})};_wt.displayName=A$e;var mj="MenuContent",[Yns,T$e]=FR(mj),wwt=N.forwardRef((s,t)=>{const n=bwt(mj,s.__scopeMenu),{forceMount:r=n.forceMount,...a}=s,i=zR(mj,s.__scopeMenu),l=kQ(mj,s.__scopeMenu);return e.jsx(lY.Provider,{scope:s.__scopeMenu,children:e.jsx(Xf,{present:r||i.open,children:e.jsx(lY.Slot,{scope:s.__scopeMenu,children:l.modal?e.jsx(Zns,{...a,ref:t}):e.jsx(Xns,{...a,ref:t})})})})}),Zns=N.forwardRef((s,t)=>{const n=zR(mj,s.__scopeMenu),r=N.useRef(null),a=jo(t,r);return N.useEffect(()=>{const i=r.current;if(i)return o4e(i)},[]),e.jsx(E$e,{...s,ref:a,trapFocus:n.open,disableOutsidePointerEvents:n.open,disableOutsideScroll:!0,onFocusOutside:la(s.onFocusOutside,i=>i.preventDefault(),{checkForDefaultPrevented:!1}),onDismiss:()=>n.onOpenChange(!1)})}),Xns=N.forwardRef((s,t)=>{const n=zR(mj,s.__scopeMenu);return e.jsx(E$e,{...s,ref:t,trapFocus:!1,disableOutsidePointerEvents:!1,disableOutsideScroll:!1,onDismiss:()=>n.onOpenChange(!1)})}),Qns=rE("MenuContent.ScrollLock"),E$e=N.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:f,disableOutsideScroll:g,...y}=s,x=zR(mj,n),_=kQ(mj,n),b=c4e(n),k=ywt(n),A=qns(n),[T,P]=N.useState(null),I=N.useRef(null),M=jo(t,I,x.onContentChange),L=N.useRef(0),z=N.useRef(""),$=N.useRef(0),V=N.useRef(null),W=N.useRef("right"),G=N.useRef(0),X=g?jQ:N.Fragment,te=g?{as:Qns,allowPinchZoom:!0}:void 0,ne=ue=>{var Se,Ie;const ce=z.current+ue,ae=A().filter(Me=>!Me.disabled),he=document.activeElement,xe=(Se=ae.find(Me=>Me.ref.current===he))==null?void 0:Se.textValue,ve=ae.map(Me=>Me.textValue),ge=drs(ve,ce,xe),be=(Ie=ae.find(Me=>Me.textValue===ge))==null?void 0:Ie.ref.current;(function Me(Re){z.current=Re,window.clearTimeout(L.current),Re!==""&&(L.current=window.setTimeout(()=>Me(""),1e3))})(ce),be&&setTimeout(()=>be.focus())};N.useEffect(()=>()=>window.clearTimeout(L.current),[]),r4e();const me=N.useCallback(ue=>{var ae,he;return W.current===((ae=V.current)==null?void 0:ae.side)&&hrs(ue,(he=V.current)==null?void 0:he.area)},[]);return e.jsx(Yns,{scope:n,searchRef:z,onItemEnter:N.useCallback(ue=>{me(ue)&&ue.preventDefault()},[me]),onItemLeave:N.useCallback(ue=>{var ce;me(ue)||((ce=I.current)==null||ce.focus(),P(null))},[me]),onTriggerLeave:N.useCallback(ue=>{me(ue)&&ue.preventDefault()},[me]),pointerGraceTimerRef:$,onPointerGraceIntentChange:N.useCallback(ue=>{V.current=ue},[]),children:e.jsx(X,{...te,children:e.jsx(_Q,{asChild:!0,trapped:a,onMountAutoFocus:la(i,ue=>{var ce;ue.preventDefault(),(ce=I.current)==null||ce.focus({preventScroll:!0})}),onUnmountAutoFocus:l,children:e.jsx(TE,{asChild:!0,disableOutsidePointerEvents:o,onEscapeKeyDown:d,onPointerDownOutside:u,onFocusOutside:h,onInteractOutside:m,onDismiss:f,children:e.jsx(a4e,{asChild:!0,...k,dir:_.dir,orientation:"vertical",loop:r,currentTabStopId:T,onCurrentTabStopIdChange:P,onEntryFocus:la(c,ue=>{_.isUsingKeyboardRef.current||ue.preventDefault()}),preventScrollOnEntryFocus:!0,children:e.jsx(xQ,{role:"menu","aria-orientation":"vertical","data-state":Fwt(x.open),"data-radix-menu-content":"",dir:_.dir,...b,...y,ref:M,style:{outline:"none",...y.style},onKeyDown:la(y.onKeyDown,ue=>{const ae=ue.target.closest("[data-radix-menu-content]")===ue.currentTarget,he=ue.ctrlKey||ue.altKey||ue.metaKey,xe=ue.key.length===1;ae&&(ue.key==="Tab"&&ue.preventDefault(),!he&&xe&&ne(ue.key));const ve=I.current;if(ue.target!==ve||!Bns.includes(ue.key))return;ue.preventDefault();const be=A().filter(Se=>!Se.disabled).map(Se=>Se.ref.current);gwt.includes(ue.key)&&be.reverse(),lrs(be)}),onBlur:la(s.onBlur,ue=>{ue.currentTarget.contains(ue.target)||(window.clearTimeout(L.current),z.current="")}),onPointerMove:la(s.onPointerMove,cY(ue=>{const ce=ue.target,ae=G.current!==ue.clientX;if(ue.currentTarget.contains(ce)&&ae){const he=ue.clientX>G.current?"right":"left";W.current=he,G.current=ue.clientX}}))})})})})})})});wwt.displayName=mj;var Jns="MenuGroup",M$e=N.forwardRef((s,t)=>{const{__scopeMenu:n,...r}=s;return e.jsx(Da.div,{role:"group",...r,ref:t})});M$e.displayName=Jns;var ers="MenuLabel",jwt=N.forwardRef((s,t)=>{const{__scopeMenu:n,...r}=s;return e.jsx(Da.div,{...r,ref:t})});jwt.displayName=ers;var O2e="MenuItem",Ttt="menu.itemSelect",d4e=N.forwardRef((s,t)=>{const{disabled:n=!1,onSelect:r,...a}=s,i=N.useRef(null),l=kQ(O2e,s.__scopeMenu),o=T$e(O2e,s.__scopeMenu),c=jo(t,i),d=N.useRef(!1),u=()=>{const h=i.current;if(!n&&h){const m=new CustomEvent(Ttt,{bubbles:!0,cancelable:!0});h.addEventListener(Ttt,f=>r==null?void 0:r(f),{once:!0}),e$e(h,m),m.defaultPrevented?d.current=!1:l.onClose()}};return e.jsx(Nwt,{...a,ref:c,disabled:n,onClick:la(s.onClick,u),onPointerDown:h=>{var m;(m=s.onPointerDown)==null||m.call(s,h),d.current=!0},onPointerUp:la(s.onPointerUp,h=>{var m;d.current||(m=h.currentTarget)==null||m.click()}),onKeyDown:la(s.onKeyDown,h=>{const m=o.searchRef.current!=="";n||m&&h.key===" "||MDe.includes(h.key)&&(h.currentTarget.click(),h.preventDefault())})})});d4e.displayName=O2e;var Nwt=N.forwardRef((s,t)=>{const{__scopeMenu:n,disabled:r=!1,textValue:a,...i}=s,l=T$e(O2e,n),o=ywt(n),c=N.useRef(null),d=jo(t,c),[u,h]=N.useState(!1),[m,f]=N.useState("");return N.useEffect(()=>{const g=c.current;g&&f((g.textContent??"").trim())},[i.children]),e.jsx(lY.ItemSlot,{scope:n,disabled:r,textValue:a??m,children:e.jsx(i4e,{asChild:!0,...o,focusable:!r,children:e.jsx(Da.div,{role:"menuitem","data-highlighted":u?"":void 0,"aria-disabled":r||void 0,"data-disabled":r?"":void 0,...i,ref:d,onPointerMove:la(s.onPointerMove,cY(g=>{r?l.onItemLeave(g):(l.onItemEnter(g),g.defaultPrevented||g.currentTarget.focus({preventScroll:!0}))})),onPointerLeave:la(s.onPointerLeave,cY(g=>l.onItemLeave(g))),onFocus:la(s.onFocus,()=>h(!0)),onBlur:la(s.onBlur,()=>h(!1))})})})}),trs="MenuCheckboxItem",kwt=N.forwardRef((s,t)=>{const{checked:n=!1,onCheckedChange:r,...a}=s;return e.jsx(Ewt,{scope:s.__scopeMenu,checked:n,children:e.jsx(d4e,{role:"menuitemcheckbox","aria-checked":F2e(n)?"mixed":n,...a,ref:t,"data-state":P$e(n),onSelect:la(a.onSelect,()=>r==null?void 0:r(F2e(n)?!0:!n),{checkForDefaultPrevented:!1})})})});kwt.displayName=trs;var Swt="MenuRadioGroup",[srs,nrs]=FR(Swt,{value:void 0,onValueChange:()=>{}}),Cwt=N.forwardRef((s,t)=>{const{value:n,onValueChange:r,...a}=s,i=cf(r);return e.jsx(srs,{scope:s.__scopeMenu,value:n,onValueChange:i,children:e.jsx(M$e,{...a,ref:t})})});Cwt.displayName=Swt;var Awt="MenuRadioItem",Twt=N.forwardRef((s,t)=>{const{value:n,...r}=s,a=nrs(Awt,s.__scopeMenu),i=n===a.value;return e.jsx(Ewt,{scope:s.__scopeMenu,checked:i,children:e.jsx(d4e,{role:"menuitemradio","aria-checked":i,...r,ref:t,"data-state":P$e(i),onSelect:la(r.onSelect,()=>{var l;return(l=a.onValueChange)==null?void 0:l.call(a,n)},{checkForDefaultPrevented:!1})})})});Twt.displayName=Awt;var L$e="MenuItemIndicator",[Ewt,rrs]=FR(L$e,{checked:!1}),Mwt=N.forwardRef((s,t)=>{const{__scopeMenu:n,forceMount:r,...a}=s,i=rrs(L$e,n);return e.jsx(Xf,{present:r||F2e(i.checked)||i.checked===!0,children:e.jsx(Da.span,{...a,ref:t,"data-state":P$e(i.checked)})})});Mwt.displayName=L$e;var ars="MenuSeparator",Lwt=N.forwardRef((s,t)=>{const{__scopeMenu:n,...r}=s;return e.jsx(Da.div,{role:"separator","aria-orientation":"horizontal",...r,ref:t})});Lwt.displayName=ars;var irs="MenuArrow",Pwt=N.forwardRef((s,t)=>{const{__scopeMenu:n,...r}=s,a=c4e(n);return e.jsx(yQ,{...a,...r,ref:t})});Pwt.displayName=irs;var ors="MenuSub",[AOn,Iwt]=FR(ors),zH="MenuSubTrigger",Dwt=N.forwardRef((s,t)=>{const n=zR(zH,s.__scopeMenu),r=kQ(zH,s.__scopeMenu),a=Iwt(zH,s.__scopeMenu),i=T$e(zH,s.__scopeMenu),l=N.useRef(null),{pointerGraceTimerRef:o,onPointerGraceIntentChange:c}=i,d={__scopeMenu:s.__scopeMenu},u=N.useCallback(()=>{l.current&&window.clearTimeout(l.current),l.current=null},[]);return N.useEffect(()=>u,[u]),N.useEffect(()=>{const h=o.current;return()=>{window.clearTimeout(h),c(null)}},[o,c]),e.jsx(C$e,{asChild:!0,...d,children:e.jsx(Nwt,{id:a.triggerId,"aria-haspopup":"menu","aria-expanded":n.open,"aria-controls":a.contentId,"data-state":Fwt(n.open),...s,ref:j3(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:la(s.onPointerMove,cY(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:la(s.onPointerLeave,cY(h=>{var f,g;u();const m=(f=n.content)==null?void 0:f.getBoundingClientRect();if(m){const y=(g=n.content)==null?void 0:g.dataset.side,x=y==="right",_=x?-5:5,b=m[x?"left":"right"],k=m[x?"right":"left"];i.onPointerGraceIntentChange({area:[{x:h.clientX+_,y:h.clientY},{x:b,y:m.top},{x:k,y:m.top},{x:k,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:la(s.onKeyDown,h=>{var f;const m=i.searchRef.current!=="";s.disabled||m&&h.key===" "||$ns[r.dir].includes(h.key)&&(n.onOpenChange(!0),(f=n.content)==null||f.focus(),h.preventDefault())})})})});Dwt.displayName=zH;var Rwt="MenuSubContent",Owt=N.forwardRef((s,t)=>{const n=bwt(mj,s.__scopeMenu),{forceMount:r=n.forceMount,...a}=s,i=zR(mj,s.__scopeMenu),l=kQ(mj,s.__scopeMenu),o=Iwt(Rwt,s.__scopeMenu),c=N.useRef(null),d=jo(t,c);return e.jsx(lY.Provider,{scope:s.__scopeMenu,children:e.jsx(Xf,{present:r||i.open,children:e.jsx(lY.Slot,{scope:s.__scopeMenu,children:e.jsx(E$e,{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:la(s.onFocusOutside,u=>{u.target!==o.trigger&&i.onOpenChange(!1)}),onEscapeKeyDown:la(s.onEscapeKeyDown,u=>{l.onClose(),u.preventDefault()}),onKeyDown:la(s.onKeyDown,u=>{var f;const h=u.currentTarget.contains(u.target),m=Uns[l.dir].includes(u.key);h&&m&&(i.onOpenChange(!1),(f=o.trigger)==null||f.focus(),u.preventDefault())})})})})})});Owt.displayName=Rwt;function Fwt(s){return s?"open":"closed"}function F2e(s){return s==="indeterminate"}function P$e(s){return F2e(s)?"indeterminate":s?"checked":"unchecked"}function lrs(s){const t=document.activeElement;for(const n of s)if(n===t||(n.focus(),document.activeElement!==t))return}function crs(s,t){return s.map((n,r)=>s[(t+r)%s.length])}function drs(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=crs(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 urs(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 hrs(s,t){if(!t)return!1;const n={x:s.clientX,y:s.clientY};return urs(n,t)}function cY(s){return t=>t.pointerType==="mouse"?s(t):void 0}var mrs=vwt,prs=C$e,frs=_wt,grs=wwt,xrs=M$e,yrs=jwt,vrs=d4e,brs=kwt,_rs=Cwt,wrs=Twt,jrs=Mwt,Nrs=Lwt,krs=Pwt,Srs=Dwt,Crs=Owt,u4e="DropdownMenu",[Ars,TOn]=Um(u4e,[xwt]),o1=xwt(),[Trs,zwt]=Ars(u4e),Bwt=s=>{const{__scopeDropdownMenu:t,children:n,dir:r,open:a,defaultOpen:i,onOpenChange:l,modal:o=!0}=s,c=o1(t),d=N.useRef(null),[u,h]=Ng({prop:a,defaultProp:i??!1,onChange:l,caller:u4e});return e.jsx(Trs,{scope:t,triggerId:_g(),triggerRef:d,contentId:_g(),open:u,onOpenChange:h,onOpenToggle:N.useCallback(()=>h(m=>!m),[h]),modal:o,children:e.jsx(mrs,{...c,open:u,onOpenChange:h,dir:r,modal:o,children:n})})};Bwt.displayName=u4e;var $wt="DropdownMenuTrigger",Uwt=N.forwardRef((s,t)=>{const{__scopeDropdownMenu:n,disabled:r=!1,...a}=s,i=zwt($wt,n),l=o1(n);return e.jsx(prs,{asChild:!0,...l,children:e.jsx(Da.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:j3(t,i.triggerRef),onPointerDown:la(s.onPointerDown,o=>{!r&&o.button===0&&o.ctrlKey===!1&&(i.onOpenToggle(),i.open||o.preventDefault())}),onKeyDown:la(s.onKeyDown,o=>{r||(["Enter"," "].includes(o.key)&&i.onOpenToggle(),o.key==="ArrowDown"&&i.onOpenChange(!0),["Enter"," ","ArrowDown"].includes(o.key)&&o.preventDefault())})})})});Uwt.displayName=$wt;var Ers="DropdownMenuPortal",qwt=s=>{const{__scopeDropdownMenu:t,...n}=s,r=o1(t);return e.jsx(frs,{...r,...n})};qwt.displayName=Ers;var Vwt="DropdownMenuContent",Hwt=N.forwardRef((s,t)=>{const{__scopeDropdownMenu:n,...r}=s,a=zwt(Vwt,n),i=o1(n),l=N.useRef(!1);return e.jsx(grs,{id:a.contentId,"aria-labelledby":a.triggerId,...i,...r,ref:t,onCloseAutoFocus:la(s.onCloseAutoFocus,o=>{var c;l.current||(c=a.triggerRef.current)==null||c.focus(),l.current=!1,o.preventDefault()}),onInteractOutside:la(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)"}})});Hwt.displayName=Vwt;var Mrs="DropdownMenuGroup",Lrs=N.forwardRef((s,t)=>{const{__scopeDropdownMenu:n,...r}=s,a=o1(n);return e.jsx(xrs,{...a,...r,ref:t})});Lrs.displayName=Mrs;var Prs="DropdownMenuLabel",Gwt=N.forwardRef((s,t)=>{const{__scopeDropdownMenu:n,...r}=s,a=o1(n);return e.jsx(yrs,{...a,...r,ref:t})});Gwt.displayName=Prs;var Irs="DropdownMenuItem",Wwt=N.forwardRef((s,t)=>{const{__scopeDropdownMenu:n,...r}=s,a=o1(n);return e.jsx(vrs,{...a,...r,ref:t})});Wwt.displayName=Irs;var Drs="DropdownMenuCheckboxItem",Kwt=N.forwardRef((s,t)=>{const{__scopeDropdownMenu:n,...r}=s,a=o1(n);return e.jsx(brs,{...a,...r,ref:t})});Kwt.displayName=Drs;var Rrs="DropdownMenuRadioGroup",Ors=N.forwardRef((s,t)=>{const{__scopeDropdownMenu:n,...r}=s,a=o1(n);return e.jsx(_rs,{...a,...r,ref:t})});Ors.displayName=Rrs;var Frs="DropdownMenuRadioItem",Ywt=N.forwardRef((s,t)=>{const{__scopeDropdownMenu:n,...r}=s,a=o1(n);return e.jsx(wrs,{...a,...r,ref:t})});Ywt.displayName=Frs;var zrs="DropdownMenuItemIndicator",Zwt=N.forwardRef((s,t)=>{const{__scopeDropdownMenu:n,...r}=s,a=o1(n);return e.jsx(jrs,{...a,...r,ref:t})});Zwt.displayName=zrs;var Brs="DropdownMenuSeparator",Xwt=N.forwardRef((s,t)=>{const{__scopeDropdownMenu:n,...r}=s,a=o1(n);return e.jsx(Nrs,{...a,...r,ref:t})});Xwt.displayName=Brs;var $rs="DropdownMenuArrow",Urs=N.forwardRef((s,t)=>{const{__scopeDropdownMenu:n,...r}=s,a=o1(n);return e.jsx(krs,{...a,...r,ref:t})});Urs.displayName=$rs;var qrs="DropdownMenuSubTrigger",Qwt=N.forwardRef((s,t)=>{const{__scopeDropdownMenu:n,...r}=s,a=o1(n);return e.jsx(Srs,{...a,...r,ref:t})});Qwt.displayName=qrs;var Vrs="DropdownMenuSubContent",Jwt=N.forwardRef((s,t)=>{const{__scopeDropdownMenu:n,...r}=s,a=o1(n);return e.jsx(Crs,{...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)"}})});Jwt.displayName=Vrs;var Hrs=Bwt,Grs=Uwt,Wrs=qwt,ejt=Hwt,tjt=Gwt,sjt=Wwt,njt=Kwt,rjt=Ywt,ajt=Zwt,ijt=Xwt,ojt=Qwt,ljt=Jwt;const qd=Hrs,Vd=Grs,Krs=N.forwardRef(({className:s,inset:t,children:n,...r},a)=>e.jsxs(ojt,{ref:a,className:Ot("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(Qa,{className:"ml-auto h-4 w-4"})]}));Krs.displayName=ojt.displayName;const Yrs=N.forwardRef(({className:s,...t},n)=>e.jsx(ljt,{ref:n,className:Ot("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}));Yrs.displayName=ljt.displayName;const Ld=N.forwardRef(({className:s,sideOffset:t=4,...n},r)=>e.jsx(Wrs,{children:e.jsx(ejt,{ref:r,sideOffset:t,className:Ot("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})}));Ld.displayName=ejt.displayName;const ba=N.forwardRef(({className:s,inset:t,...n},r)=>e.jsx(sjt,{ref:r,className:Ot("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}));ba.displayName=sjt.displayName;const Zrs=N.forwardRef(({className:s,children:t,checked:n,...r},a)=>e.jsxs(njt,{ref:a,className:Ot("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(ajt,{children:e.jsx(pa,{className:"h-4 w-4"})})}),t]}));Zrs.displayName=njt.displayName;const Xrs=N.forwardRef(({className:s,children:t,...n},r)=>e.jsxs(rjt,{ref:r,className:Ot("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(ajt,{children:e.jsx(bg,{className:"h-2 w-2 fill-current"})})}),t]}));Xrs.displayName=rjt.displayName;const cE=N.forwardRef(({className:s,inset:t,...n},r)=>e.jsx(tjt,{ref:r,className:Ot("px-2 py-1.5 text-sm font-semibold",t&&"pl-8",s),...n}));cE.displayName=tjt.displayName;const s1=N.forwardRef(({className:s,...t},n)=>e.jsx(ijt,{ref:n,className:Ot("-mx-1 my-1 h-px bg-muted",s),...t}));s1.displayName=ijt.displayName;const Qrs=()=>{const{isAssistant:s,actingAsAgent:t,assignedAgents:n,setActingAsAgent:r,isActingAsSelf:a,setActingAsSelf:i}=n4e();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(Ro,{className:"h-4 w-4 flex-shrink-0"}),e.jsx("span",{className:"font-medium text-sm",children:"My Account"})]}):e.jsxs(e.Fragment,{children:[e.jsx(Yn,{className:"h-4 w-4 flex-shrink-0"}),e.jsx("span",{className:"font-medium text-sm",children:"Acting as"})]}),e.jsxs(qd,{children:[e.jsx(Vd,{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(Ro,{className:"h-4 w-4"}),e.jsx("strong",{children:"My Account"})]}):t?e.jsxs(e.Fragment,{children:[e.jsxs(Ua,{className:"h-5 w-5",children:[e.jsx(Gi,{src:t.avatar_url||void 0}),e.jsx(qa,{className:"text-[10px] bg-primary-foreground/30",children:l(t.name)})]}),e.jsx("strong",{children:t.name})]}):e.jsx("strong",{children:"Select..."}),e.jsx(Xo,{className:"h-3 w-3"})]})}),e.jsxs(Ld,{align:"start",className:"z-[2147483647]",children:[e.jsxs(ba,{onClick:i,className:"gap-2",children:[e.jsx(Ro,{className:"h-4 w-4"}),e.jsx("span",{children:"My Account"}),a&&e.jsx(We,{variant:"secondary",className:"ml-auto text-[10px]",children:"Current"})]}),e.jsx(s1,{}),n.map(o=>e.jsxs(ba,{onClick:()=>r(o),className:"gap-2",children:[e.jsxs(Ua,{className:"h-6 w-6",children:[e.jsx(Gi,{src:o.avatar_url||void 0}),e.jsx(qa,{className:"text-[10px]",children:l(o.name)})]}),e.jsx("span",{children:o.name}),!a&&o.id===(t==null?void 0:t.id)&&e.jsx(We,{variant:"secondary",className:"ml-auto text-[10px]",children:"Current"})]},o.id))]})]})]}),e.jsx(We,{variant:"secondary",className:"bg-primary-foreground/20 text-primary-foreground border-0 text-xs",children:a?"Personal Mode":"Assistant Mode"})]})})},jn=({children:s,requireAdmin:t=!1,requireBrokerageManager:n=!1})=>{const{user:r,loading:a,rolesLoading:i,isAdmin:l,isBrokerageManager:o}=Ls(),c=Id();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 d=c.pathname+c.search+c.hash;return d&&d!=="/auth"&&sessionStorage.setItem("redirectAfterLogin",d),e.jsx(nN,{to:"/auth",replace:!0})}return t&&!l?e.jsx(nN,{to:"/dashboard",replace:!0}):n&&!o&&!l?e.jsx(nN,{to:"/dashboard",replace:!0}):e.jsx(e.Fragment,{children:s})};var I$e={};(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 ce=new OffscreenCanvas(1,1),ae=ce.getContext("2d");ae.fillRect(0,0,1,1);var he=ce.transferToImageBitmap();ae.createPattern(he,"no-repeat")}catch{return!1}return!0}();function c(){}function d(ce){var ae=n.exports.Promise,he=ae!==void 0?ae:t.Promise;return typeof he=="function"?new he(ce):(ce(c,c),null)}var u=function(ce,ae){return{transform:function(he){if(ce)return he;if(ae.has(he))return ae.get(he);var xe=new OffscreenCanvas(he.width,he.height),ve=xe.getContext("2d");return ve.drawImage(he,0,0),ae.set(he,xe),xe},clear:function(){ae.clear()}}}(o,new Map),h=function(){var ce=Math.floor(16.666666666666668),ae,he,xe={},ve=0;return typeof requestAnimationFrame=="function"&&typeof cancelAnimationFrame=="function"?(ae=function(ge){var be=Math.random();return xe[be]=requestAnimationFrame(function Se(Ie){ve===Ie||ve+ce-1{const{data:t,error:n}=await H.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 eas(){const s=as();return _t({mutationFn:async t=>{const{error:n}=await H.from("celebration_queue").update({seen_at:new Date().toISOString()}).eq("id",t);if(n)throw n},onSuccess:()=>{s.invalidateQueries({queryKey:["celebrations"]})}})}function tas(){const s=as(),{user:t}=Ls();return _t({mutationFn:async n=>{const{error:r}=await H.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"]})}})}var h4e="Dialog",[cjt,djt]=Um(h4e),[sas,gN]=cjt(h4e),ujt=s=>{const{__scopeDialog:t,children:n,open:r,defaultOpen:a,onOpenChange:i,modal:l=!0}=s,o=N.useRef(null),c=N.useRef(null),[d,u]=Ng({prop:r,defaultProp:a??!1,onChange:i,caller:h4e});return e.jsx(sas,{scope:t,triggerRef:o,contentRef:c,contentId:_g(),titleId:_g(),descriptionId:_g(),open:d,onOpenChange:u,onOpenToggle:N.useCallback(()=>u(h=>!h),[u]),modal:l,children:n})};ujt.displayName=h4e;var hjt="DialogTrigger",mjt=N.forwardRef((s,t)=>{const{__scopeDialog:n,...r}=s,a=gN(hjt,n),i=jo(t,a.triggerRef);return e.jsx(Da.button,{type:"button","aria-haspopup":"dialog","aria-expanded":a.open,"aria-controls":a.contentId,"data-state":O$e(a.open),...r,ref:i,onClick:la(s.onClick,a.onOpenToggle)})});mjt.displayName=hjt;var D$e="DialogPortal",[nas,pjt]=cjt(D$e,{forceMount:void 0}),fjt=s=>{const{__scopeDialog:t,forceMount:n,children:r,container:a}=s,i=gN(D$e,t);return e.jsx(nas,{scope:t,forceMount:n,children:N.Children.map(r,l=>e.jsx(Xf,{present:n||i.open,children:e.jsx(Y$,{asChild:!0,container:a,children:l})}))})};fjt.displayName=D$e;var z2e="DialogOverlay",gjt=N.forwardRef((s,t)=>{const n=pjt(z2e,s.__scopeDialog),{forceMount:r=n.forceMount,...a}=s,i=gN(z2e,s.__scopeDialog);return i.modal?e.jsx(Xf,{present:r||i.open,children:e.jsx(aas,{...a,ref:t})}):null});gjt.displayName=z2e;var ras=rE("DialogOverlay.RemoveScroll"),aas=N.forwardRef((s,t)=>{const{__scopeDialog:n,...r}=s,a=gN(z2e,n);return e.jsx(jQ,{as:ras,allowPinchZoom:!0,shards:[a.contentRef],children:e.jsx(Da.div,{"data-state":O$e(a.open),...r,ref:t,style:{pointerEvents:"auto",...r.style}})})}),JD="DialogContent",xjt=N.forwardRef((s,t)=>{const n=pjt(JD,s.__scopeDialog),{forceMount:r=n.forceMount,...a}=s,i=gN(JD,s.__scopeDialog);return e.jsx(Xf,{present:r||i.open,children:i.modal?e.jsx(ias,{...a,ref:t}):e.jsx(oas,{...a,ref:t})})});xjt.displayName=JD;var ias=N.forwardRef((s,t)=>{const n=gN(JD,s.__scopeDialog),r=N.useRef(null),a=jo(t,n.contentRef,r);return N.useEffect(()=>{const i=r.current;if(i)return o4e(i)},[]),e.jsx(yjt,{...s,ref:a,trapFocus:n.open,disableOutsidePointerEvents:!0,onCloseAutoFocus:la(s.onCloseAutoFocus,i=>{var l;i.preventDefault(),(l=n.triggerRef.current)==null||l.focus()}),onPointerDownOutside:la(s.onPointerDownOutside,i=>{const l=i.detail.originalEvent,o=l.button===0&&l.ctrlKey===!0;(l.button===2||o)&&i.preventDefault()}),onFocusOutside:la(s.onFocusOutside,i=>i.preventDefault())})}),oas=N.forwardRef((s,t)=>{const n=gN(JD,s.__scopeDialog),r=N.useRef(!1),a=N.useRef(!1);return e.jsx(yjt,{...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()}})}),yjt=N.forwardRef((s,t)=>{const{__scopeDialog:n,trapFocus:r,onOpenAutoFocus:a,onCloseAutoFocus:i,...l}=s,o=gN(JD,n),c=N.useRef(null),d=jo(t,c);return r4e(),e.jsxs(e.Fragment,{children:[e.jsx(_Q,{asChild:!0,loop:!0,trapped:r,onMountAutoFocus:a,onUnmountAutoFocus:i,children:e.jsx(TE,{role:"dialog",id:o.contentId,"aria-describedby":o.descriptionId,"aria-labelledby":o.titleId,"data-state":O$e(o.open),...l,ref:d,onDismiss:()=>o.onOpenChange(!1)})}),e.jsxs(e.Fragment,{children:[e.jsx(cas,{titleId:o.titleId}),e.jsx(uas,{contentRef:c,descriptionId:o.descriptionId})]})]})}),R$e="DialogTitle",vjt=N.forwardRef((s,t)=>{const{__scopeDialog:n,...r}=s,a=gN(R$e,n);return e.jsx(Da.h2,{id:a.titleId,...r,ref:t})});vjt.displayName=R$e;var bjt="DialogDescription",_jt=N.forwardRef((s,t)=>{const{__scopeDialog:n,...r}=s,a=gN(bjt,n);return e.jsx(Da.p,{id:a.descriptionId,...r,ref:t})});_jt.displayName=bjt;var wjt="DialogClose",jjt=N.forwardRef((s,t)=>{const{__scopeDialog:n,...r}=s,a=gN(wjt,n);return e.jsx(Da.button,{type:"button",...r,ref:t,onClick:la(s.onClick,()=>a.onOpenChange(!1))})});jjt.displayName=wjt;function O$e(s){return s?"open":"closed"}var Njt="DialogTitleWarning",[las,kjt]=uKt(Njt,{contentName:JD,titleName:R$e,docsSlug:"dialog"}),cas=({titleId:s})=>{const t=kjt(Njt),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 N.useEffect(()=>{s&&(document.getElementById(s)||console.error(n))},[n,s]),null},das="DialogDescriptionWarning",uas=({contentRef:s,descriptionId:t})=>{const r=`Warning: Missing \`Description\` or \`aria-describedby={undefined}\` for {${kjt(das).contentName}}.`;return N.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},m4e=ujt,F$e=mjt,p4e=fjt,aU=gjt,iU=xjt,SQ=vjt,CQ=_jt,AQ=jjt;const Bs=m4e,Ao=F$e,has=p4e,EOn=AQ,Sjt=N.forwardRef(({className:s,...t},n)=>e.jsx(aU,{ref:n,className:Ot("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}));Sjt.displayName=aU.displayName;const Fs=N.forwardRef(({className:s,children:t,overlayClassName:n,...r},a)=>e.jsxs(has,{children:[e.jsx(Sjt,{className:n}),e.jsxs(iU,{ref:a,className:Ot("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(AQ,{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(hr,{className:"h-4 w-4"}),e.jsx("span",{className:"sr-only",children:"Close"})]})]})]}));Fs.displayName=iU.displayName;const qs=({className:s,...t})=>e.jsx("div",{className:Ot("flex flex-col space-y-1.5 text-center sm:text-left",s),...t});qs.displayName="DialogHeader";const Cr=({className:s,...t})=>e.jsx("div",{className:Ot("flex flex-col-reverse sm:flex-row sm:justify-end sm:space-x-2",s),...t});Cr.displayName="DialogFooter";const $s=N.forwardRef(({className:s,...t},n)=>e.jsx(SQ,{ref:n,className:Ot("text-lg font-semibold leading-none tracking-tight",s),...t}));$s.displayName=SQ.displayName;const Ar=N.forwardRef(({className:s,...t},n)=>e.jsx(CQ,{ref:n,className:Ot("text-sm text-muted-foreground",s),...t}));Ar.displayName=CQ.displayName;const mas={points_earned:gl,listing_created:_a,deal_closed:Ed,custom:Wa},Mtt={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"},Ltt=()=>{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 pas(){const{user:s}=Ls(),t=as(),{data:n}=Jrs(),r=eas(),[a,i]=N.useState(null),[l,o]=N.useState(!1),c=N.useCallback(()=>{const f=Date.now()+3e3,g={startVelocity:30,spread:360,ticks:60,zIndex:9999},y=(_,b)=>Math.random()*(b-_)+_,x=setInterval(()=>{const _=f-Date.now();if(_<=0){clearInterval(x);return}const b=50*(_/3e3);Ett({...g,particleCount:b,origin:{x:y(.1,.3),y:Math.random()-.2},colors:["#ff6b6b","#feca57","#48dbfb","#ff9ff3","#54a0ff","#5f27cd"]}),Ett({...g,particleCount:b,origin:{x:y(.7,.9),y:Math.random()-.2},colors:["#ff6b6b","#feca57","#48dbfb","#ff9ff3","#54a0ff","#5f27cd"]})},250)},[]);N.useEffect(()=>{Ltt()||n&&n.length>0&&!a&&(i(n[0]),o(!0),setTimeout(c,100))},[n,a,c]);const d=async()=>{if(a){const m=a.id;o(!1),i(null),t.setQueryData(["celebrations","pending",s==null?void 0:s.id],f=>(f==null?void 0:f.filter(g=>g.id!==m))??[]),await r.mutateAsync(m)}};if(Ltt()||!a)return null;const u=mas[a.celebration_type]||Wa,h=Mtt[a.celebration_type]||Mtt.custom;return e.jsx(Bs,{open:l,onOpenChange:m=>!m&&d(),children:e.jsxs(Fs,{className:"sm:max-w-md text-center border-0 overflow-hidden",children:[e.jsx("div",{className:`absolute inset-0 bg-gradient-to-br ${h} opacity-10`}),e.jsxs("div",{className:"relative z-10 py-6",children:[e.jsx("div",{className:"flex justify-center mb-4",children:e.jsx("div",{className:`w-20 h-20 rounded-full bg-gradient-to-br ${h} flex items-center justify-center animate-bounce`,children:e.jsx(u,{className:"w-10 h-10 text-white"})})}),e.jsxs("div",{className:"flex justify-center gap-1 mb-4",children:[e.jsx(Cn,{className:"w-5 h-5 text-yellow-500 animate-pulse"}),e.jsx(Cn,{className:"w-5 h-5 text-yellow-500 animate-pulse delay-75"}),e.jsx(Cn,{className:"w-5 h-5 text-yellow-500 animate-pulse delay-150"})]}),e.jsxs("h2",{className:"text-2xl font-bold mb-2 bg-gradient-to-r from-primary to-secondary bg-clip-text text-transparent",children:["🎉 ",a.title]}),a.points_amount&&a.points_amount>0&&e.jsxs("div",{className:"text-4xl font-bold text-primary mb-2",children:["+",a.points_amount," points!"]}),a.message&&e.jsx("p",{className:"text-muted-foreground mb-6",children:a.message}),e.jsx(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 xn({className:s,...t}){return e.jsx("div",{className:Ot("animate-pulse rounded-md bg-muted",s),...t})}const we=N.forwardRef(({className:s,type:t,...n},r)=>e.jsx("input",{type:t,className:Ot("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}));we.displayName="Input";var fas="Label",Cjt=N.forwardRef((s,t)=>e.jsx(Da.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())}}));Cjt.displayName=fas;var Ajt=Cjt;const gas=RR("text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70"),re=N.forwardRef(({className:s,...t},n)=>e.jsx(Ajt,{ref:n,className:Ot(gas(),s),...t}));re.displayName=Ajt.displayName;const Ws=N.forwardRef(({className:s,...t},n)=>e.jsx("textarea",{className:Ot("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}));Ws.displayName="Textarea";var f4e="Tabs",[xas,MOn]=Um(f4e,[ME]),Tjt=ME(),[yas,z$e]=xas(f4e),Ejt=N.forwardRef((s,t)=>{const{__scopeTabs:n,value:r,onValueChange:a,defaultValue:i,orientation:l="horizontal",dir:o,activationMode:c="automatic",...d}=s,u=F3(o),[h,m]=Ng({prop:r,onChange:a,defaultProp:i??"",caller:f4e});return e.jsx(yas,{scope:n,baseId:_g(),value:h,onValueChange:m,orientation:l,dir:u,activationMode:c,children:e.jsx(Da.div,{dir:u,"data-orientation":l,...d,ref:t})})});Ejt.displayName=f4e;var Mjt="TabsList",Ljt=N.forwardRef((s,t)=>{const{__scopeTabs:n,loop:r=!0,...a}=s,i=z$e(Mjt,n),l=Tjt(n);return e.jsx(a4e,{asChild:!0,...l,orientation:i.orientation,dir:i.dir,loop:r,children:e.jsx(Da.div,{role:"tablist","aria-orientation":i.orientation,...a,ref:t})})});Ljt.displayName=Mjt;var Pjt="TabsTrigger",Ijt=N.forwardRef((s,t)=>{const{__scopeTabs:n,value:r,disabled:a=!1,...i}=s,l=z$e(Pjt,n),o=Tjt(n),c=Ojt(l.baseId,r),d=Fjt(l.baseId,r),u=r===l.value;return e.jsx(i4e,{asChild:!0,...o,focusable:!a,active:u,children:e.jsx(Da.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:la(s.onMouseDown,h=>{!a&&h.button===0&&h.ctrlKey===!1?l.onValueChange(r):h.preventDefault()}),onKeyDown:la(s.onKeyDown,h=>{[" ","Enter"].includes(h.key)&&l.onValueChange(r)}),onFocus:la(s.onFocus,()=>{const h=l.activationMode!=="manual";!u&&!a&&h&&l.onValueChange(r)})})})});Ijt.displayName=Pjt;var Djt="TabsContent",Rjt=N.forwardRef((s,t)=>{const{__scopeTabs:n,value:r,forceMount:a,children:i,...l}=s,o=z$e(Djt,n),c=Ojt(o.baseId,r),d=Fjt(o.baseId,r),u=r===o.value,h=N.useRef(u);return N.useEffect(()=>{const m=requestAnimationFrame(()=>h.current=!1);return()=>cancelAnimationFrame(m)},[]),e.jsx(Xf,{present:a||u,children:({present:m})=>e.jsx(Da.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})})});Rjt.displayName=Djt;function Ojt(s,t){return`${s}-trigger-${t}`}function Fjt(s,t){return`${s}-content-${t}`}var vas=Ejt,zjt=Ljt,Bjt=Ijt,$jt=Rjt;const ya=vas,va=N.forwardRef(({className:s,...t},n)=>e.jsx(zjt,{ref:n,className:Ot("inline-flex h-10 items-center justify-center rounded-md bg-muted p-1 text-muted-foreground",s),...t}));va.displayName=zjt.displayName;const ls=N.forwardRef(({className:s,...t},n)=>e.jsx(Bjt,{ref:n,className:Ot("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}));ls.displayName=Bjt.displayName;const _s=N.forwardRef(({className:s,...t},n)=>e.jsx($jt,{ref:n,className:Ot("mt-2 ring-offset-background focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2",s),...t}));_s.displayName=$jt.displayName;const dY="#0d0d0d",B2e="#1a1a1a",R0="#c9a84c",TQ="#f0d78c",A5={captured:"lup_lead_captured_v1",stickyDismissed:"lup_sticky_dismissed_v1",exitShown:"lup_exit_shown_v1",savedListings:"lup_saved_listings_v1"};async function g4e(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 H.functions.invoke("public-site-lead",{body:t});if(r)throw r;try{localStorage.setItem(A5.captured,JSON.stringify({email:s.email,ts:Date.now()}))}catch{}return n}function B$e(){try{return!!localStorage.getItem(A5.captured)}catch{return!1}}function bas(){try{const s=localStorage.getItem(A5.captured);return s?JSON.parse(s).email??null:null}catch{return null}}function $$e({open:s,onClose:t,children:n}){return N.useEffect(()=>{if(!s)return;const r=document.body.style.overflow;return document.body.style.overflow="hidden",()=>{document.body.style.overflow=r}},[s]),s?Lv.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, ${B2e} 0%, ${dY} 100%)`,border:`1px solid ${R0}33`,boxShadow:`0 30px 80px rgba(0,0,0,0.6), 0 0 0 1px ${R0}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(hr,{className:"h-4 w-4"})}),n]})}),document.body):null}function U$e(){const[s,t]=N.useState({first_name:"",email:"",phone:"",area:""}),[n,r]=N.useState(!1),[a,i]=N.useState("");return{values:s,setValues:t,loading:n,setLoading:r,honeypot:a,setHoneypot:i}}function q$e({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(Ro,{className:"absolute left-3.5 top-1/2 -translate-y-1/2 h-4 w-4 text-white/40"}),e.jsx("input",{type:"text",placeholder:"First name",value:s.first_name,onChange:d=>t({...s,first_name:d.target.value}),className:o,style:c})]}),e.jsxs("div",{className:"relative",children:[e.jsx(mn,{className:"absolute left-3.5 top-1/2 -translate-y-1/2 h-4 w-4 text-white/40"}),e.jsx("input",{type:"email",required:!0,placeholder:"Email address",value:s.email,onChange:d=>t({...s,email:d.target.value}),className:o,style:c})]}),a&&e.jsxs("div",{className:"relative",children:[e.jsx(ga,{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(ii,{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 V$e({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, ${TQ} 0%, ${R0} 100%)`,color:dY,boxShadow:`0 8px 24px ${R0}55`},children:s})}function Ptt({open:s,onClose:t,initialCriteria:n}){const{values:r,setValues:a,loading:i,setLoading:l,honeypot:o,setHoneypot:c}=U$e(),[d,u]=N.useState(!1),h=async m=>{if(m.preventDefault(),!!r.email){l(!0);try{await g4e({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(A5.stickyDismissed,"1")}catch{}setTimeout(t,2200)}catch{ie.error("Something went wrong. Please try again.")}finally{l(!1)}}};return e.jsx($$e,{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(yg,{className:"h-4 w-4",style:{color:R0}}),e.jsx("span",{className:"text-xs uppercase tracking-[0.2em]",style:{color:TQ},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:`${R0}22`,border:`1px solid ${R0}55`},children:e.jsx(Cn,{className:"h-5 w-5",style:{color:R0}})}),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(q$e,{values:r,setValues:a,honeypot:o,setHoneypot:c}),e.jsx(V$e,{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 _as(){const[s,t]=N.useState(!0),[n,r]=N.useState(!1);N.useEffect(()=>{try{const i=!!localStorage.getItem(A5.stickyDismissed)||B$e();t(i)}catch{t(!1)}},[]);const a=()=>{t(!0);try{localStorage.setItem(A5.stickyDismissed,"1")}catch{}};return s?e.jsx(Ptt,{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, ${B2e} 0%, ${dY} 100%)`,borderTop:`1px solid ${R0}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:`${R0}22`,border:`1px solid ${R0}55`},children:e.jsx(yg,{className:"h-4 w-4",style:{color:R0}})}),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, ${TQ} 0%, ${R0} 100%)`,color:dY},children:"Get Alerts"}),e.jsx("button",{onClick:a,className:"p-2 text-white/50 hover:text-white transition","aria-label":"Dismiss",children:e.jsx(hr,{className:"h-4 w-4"})})]})}),e.jsx(Ptt,{open:n,onClose:()=>r(!1)})]})}function was(){const[s,t]=N.useState(!1),n=N.useRef(!1);N.useEffect(()=>{try{if(sessionStorage.getItem(A5.exitShown)||B$e())return}catch{}const m=setTimeout(()=>{n.current=!0},8e3),f=g=>{if(n.current&&!(g.clientY>0)){t(!0);try{sessionStorage.setItem(A5.exitShown,"1")}catch{}window.removeEventListener("mouseleave",f),document.removeEventListener("mouseleave",f)}};return document.addEventListener("mouseleave",f),()=>{clearTimeout(m),document.removeEventListener("mouseleave",f)}},[]);const{values:r,setValues:a,loading:i,setLoading:l,honeypot:o,setHoneypot:c}=U$e(),[d,u]=N.useState(!1),h=async m=>{if(m.preventDefault(),!!r.email){l(!0);try{await g4e({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{ie.error("Something went wrong. Please try again.")}finally{l(!1)}}};return e.jsx($$e,{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, ${dY} 0%, ${B2e} 60%, ${R0} 130%)`},children:e.jsx("div",{className:"absolute top-4 left-6",children:e.jsx("span",{className:"text-[10px] uppercase tracking-[0.25em]",style:{color:TQ},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:B2e,border:`1px solid ${R0}55`,boxShadow:"0 8px 24px rgba(0,0,0,0.5)"},children:e.jsx(Cn,{className:"h-6 w-6",style:{color:R0}})}),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(q$e,{values:r,setValues:a,honeypot:o,setHoneypot:c,showPhone:!1}),e.jsx(V$e,{type:"submit",disabled:i||!r.email,children:i?"Sending…":"Send My List"})]})]})]})})}function jas(){const[s,t]=N.useState([]);N.useEffect(()=>{try{const o=localStorage.getItem(A5.savedListings);o&&t(JSON.parse(o))}catch{}},[]);const n=o=>{t(o);try{localStorage.setItem(A5.savedListings,JSON.stringify(o))}catch{}},r=N.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 Nas({listingId:s,listingAddress:t,className:n}){const{has:r,add:a,remove:i}=jas(),l=r(s),[o,c]=N.useState(!1),d=()=>{if(l){i(s);return}if(B$e()){a(s),ie.success("Saved to your favorites"),g4e({lead_type:"saved_listing",email:bas()||"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(co,{className:`h-5 w-5 ${l?"fill-current":""}`})}),e.jsx(kas,{open:o,onClose:()=>c(!1),listingId:s,listingAddress:t,onSaved:()=>a(s)})]})}function kas({open:s,onClose:t,listingId:n,listingAddress:r,onSaved:a}){const{values:i,setValues:l,loading:o,setLoading:c,honeypot:d,setHoneypot:u}=U$e(),h=async m=>{if(m.preventDefault(),!!i.email){c(!0);try{await g4e({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(),ie.success("Saved to your favorites"),t()}catch{ie.error("Something went wrong. Please try again.")}finally{c(!1)}}};return e.jsx($$e,{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(co,{className:"h-4 w-4",style:{color:R0}}),e.jsx("span",{className:"text-xs uppercase tracking-[0.2em]",style:{color:TQ},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(q$e,{values:i,setValues:l,honeypot:d,setHoneypot:u}),e.jsx(V$e,{type:"submit",disabled:o||!i.email,children:o?"Saving…":"Save Home"})]})]})})}function uY(s,[t,n]){return Math.min(n,Math.max(t,s))}function EQ(s){const t=N.useRef({value:s,previous:s});return N.useMemo(()=>(t.current.value!==s&&(t.current.previous=t.current.value,t.current.value=s),t.current.previous),[s])}var Ujt=["PageUp","PageDown"],qjt=["ArrowUp","ArrowDown","ArrowLeft","ArrowRight"],Vjt={"from-left":["Home","PageDown","ArrowDown","ArrowLeft"],"from-right":["Home","PageDown","ArrowDown","ArrowRight"],"from-bottom":["Home","PageDown","ArrowDown","ArrowLeft"],"from-top":["Home","PageDown","ArrowUp","ArrowLeft"]},oU="Slider",[LDe,Sas,Cas]=K$(oU),[Hjt,LOn]=Um(oU,[Cas]),[Aas,x4e]=Hjt(oU),Gjt=N.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:f=!1,form:g,...y}=s,x=N.useRef(new Set),_=N.useRef(0),k=l==="horizontal"?Tas:Eas,[A=[],T]=Ng({prop:u,defaultProp:d,onChange:$=>{var W;(W=[...x.current][_.current])==null||W.focus(),h($)}}),P=N.useRef(A);function I($){const V=Das(A,$);z($,V)}function M($){z($,_.current)}function L(){const $=P.current[_.current];A[_.current]!==$&&m(A)}function z($,V,{commit:W}={commit:!1}){const G=zas(i),X=Bas(Math.round(($-r)/i)*i+r,G),te=uY(X,[r,a]);T((ne=[])=>{const me=Pas(ne,te,V);if(Fas(me,c*i)){_.current=me.indexOf(te);const ue=String(me)!==String(ne);return ue&&W&&m(me),ue?me:ne}else return ne})}return e.jsx(Aas,{scope:s.__scopeSlider,name:n,disabled:o,min:r,max:a,valueIndexToChangeRef:_,thumbs:x.current,values:A,orientation:l,form:g,children:e.jsx(LDe.Provider,{scope:s.__scopeSlider,children:e.jsx(LDe.Slot,{scope:s.__scopeSlider,children:e.jsx(k,{"aria-disabled":o,"data-disabled":o?"":void 0,...y,ref:t,onPointerDown:la(y.onPointerDown,()=>{o||(P.current=A)}),min:r,max:a,inverted:f,onSlideStart:o?void 0:I,onSlideMove:o?void 0:M,onSlideEnd:o?void 0:L,onHomeKeyDown:()=>!o&&z(r,0,{commit:!0}),onEndKeyDown:()=>!o&&z(a,A.length-1,{commit:!0}),onStepKeyDown:({event:$,direction:V})=>{if(!o){const X=Ujt.includes($.key)||$.shiftKey&&qjt.includes($.key)?10:1,te=_.current,ne=A[te],me=i*X*V;z(ne+me,te,{commit:!0})}}})})})})});Gjt.displayName=oU;var[Wjt,Kjt]=Hjt(oU,{startEdge:"left",endEdge:"right",size:"width",direction:1}),Tas=N.forwardRef((s,t)=>{const{min:n,max:r,dir:a,inverted:i,onSlideStart:l,onSlideMove:o,onSlideEnd:c,onStepKeyDown:d,...u}=s,[h,m]=N.useState(null),f=jo(t,k=>m(k)),g=N.useRef(void 0),y=F3(a),x=y==="ltr",_=x&&!i||!x&&i;function b(k){const A=g.current||h.getBoundingClientRect(),T=[0,A.width],I=H$e(T,_?[n,r]:[r,n]);return g.current=A,I(k-A.left)}return e.jsx(Wjt,{scope:s.__scopeSlider,startEdge:_?"left":"right",endEdge:_?"right":"left",direction:_?1:-1,size:"width",children:e.jsx(Yjt,{dir:y,"data-orientation":"horizontal",...u,ref:f,style:{...u.style,"--radix-slider-thumb-transform":"translateX(-50%)"},onSlideStart:k=>{const A=b(k.clientX);l==null||l(A)},onSlideMove:k=>{const A=b(k.clientX);o==null||o(A)},onSlideEnd:()=>{g.current=void 0,c==null||c()},onStepKeyDown:k=>{const T=Vjt[_?"from-left":"from-right"].includes(k.key);d==null||d({event:k,direction:T?-1:1})}})})}),Eas=N.forwardRef((s,t)=>{const{min:n,max:r,inverted:a,onSlideStart:i,onSlideMove:l,onSlideEnd:o,onStepKeyDown:c,...d}=s,u=N.useRef(null),h=jo(t,u),m=N.useRef(void 0),f=!a;function g(y){const x=m.current||u.current.getBoundingClientRect(),_=[0,x.height],k=H$e(_,f?[r,n]:[n,r]);return m.current=x,k(y-x.top)}return e.jsx(Wjt,{scope:s.__scopeSlider,startEdge:f?"bottom":"top",endEdge:f?"top":"bottom",size:"height",direction:f?1:-1,children:e.jsx(Yjt,{"data-orientation":"vertical",...d,ref:h,style:{...d.style,"--radix-slider-thumb-transform":"translateY(50%)"},onSlideStart:y=>{const x=g(y.clientY);i==null||i(x)},onSlideMove:y=>{const x=g(y.clientY);l==null||l(x)},onSlideEnd:()=>{m.current=void 0,o==null||o()},onStepKeyDown:y=>{const _=Vjt[f?"from-bottom":"from-top"].includes(y.key);c==null||c({event:y,direction:_?-1:1})}})})}),Yjt=N.forwardRef((s,t)=>{const{__scopeSlider:n,onSlideStart:r,onSlideMove:a,onSlideEnd:i,onHomeKeyDown:l,onEndKeyDown:o,onStepKeyDown:c,...d}=s,u=x4e(oU,n);return e.jsx(Da.span,{...d,ref:t,onKeyDown:la(s.onKeyDown,h=>{h.key==="Home"?(l(h),h.preventDefault()):h.key==="End"?(o(h),h.preventDefault()):Ujt.concat(qjt).includes(h.key)&&(c(h),h.preventDefault())}),onPointerDown:la(s.onPointerDown,h=>{const m=h.target;m.setPointerCapture(h.pointerId),h.preventDefault(),u.thumbs.has(m)?m.focus():r(h)}),onPointerMove:la(s.onPointerMove,h=>{h.target.hasPointerCapture(h.pointerId)&&a(h)}),onPointerUp:la(s.onPointerUp,h=>{const m=h.target;m.hasPointerCapture(h.pointerId)&&(m.releasePointerCapture(h.pointerId),i(h))})})}),Zjt="SliderTrack",Xjt=N.forwardRef((s,t)=>{const{__scopeSlider:n,...r}=s,a=x4e(Zjt,n);return e.jsx(Da.span,{"data-disabled":a.disabled?"":void 0,"data-orientation":a.orientation,...r,ref:t})});Xjt.displayName=Zjt;var PDe="SliderRange",Qjt=N.forwardRef((s,t)=>{const{__scopeSlider:n,...r}=s,a=x4e(PDe,n),i=Kjt(PDe,n),l=N.useRef(null),o=jo(t,l),c=a.values.length,d=a.values.map(m=>t2t(m,a.min,a.max)),u=c>1?Math.min(...d):0,h=100-Math.max(...d);return e.jsx(Da.span,{"data-orientation":a.orientation,"data-disabled":a.disabled?"":void 0,...r,ref:o,style:{...s.style,[i.startEdge]:u+"%",[i.endEdge]:h+"%"}})});Qjt.displayName=PDe;var IDe="SliderThumb",Jjt=N.forwardRef((s,t)=>{const n=Sas(s.__scopeSlider),[r,a]=N.useState(null),i=jo(t,o=>a(o)),l=N.useMemo(()=>r?n().findIndex(o=>o.ref.current===r):-1,[n,r]);return e.jsx(Mas,{...s,ref:i,index:l})}),Mas=N.forwardRef((s,t)=>{const{__scopeSlider:n,index:r,name:a,...i}=s,l=x4e(IDe,n),o=Kjt(IDe,n),[c,d]=N.useState(null),u=jo(t,b=>d(b)),h=c?l.form||!!c.closest("form"):!0,m=fQ(c),f=l.values[r],g=f===void 0?0:t2t(f,l.min,l.max),y=Ias(r,l.values.length),x=m==null?void 0:m[o.size],_=x?Ras(x,g,o.direction):0;return N.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(${g}% + ${_}px)`},children:[e.jsx(LDe.ItemSlot,{scope:s.__scopeSlider,children:e.jsx(Da.span,{role:"slider","aria-label":s["aria-label"]||y,"aria-valuemin":l.min,"aria-valuenow":f,"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:f===void 0?{display:"none"}:s.style,onFocus:la(s.onFocus,()=>{l.valueIndexToChangeRef.current=r})})}),h&&e.jsx(e2t,{name:a??(l.name?l.name+(l.values.length>1?"[]":""):void 0),form:l.form,value:f},r)]})});Jjt.displayName=IDe;var Las="RadioBubbleInput",e2t=N.forwardRef(({__scopeSlider:s,value:t,...n},r)=>{const a=N.useRef(null),i=jo(a,r),l=EQ(t);return N.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(Da.input,{style:{display:"none"},...n,ref:i,defaultValue:t})});e2t.displayName=Las;function Pas(s=[],t,n){const r=[...s];return r[n]=t,r.sort((a,i)=>a-i)}function t2t(s,t,n){const i=100/(n-t)*(s-t);return uY(i,[0,100])}function Ias(s,t){return t>2?`Value ${s+1} of ${t}`:t===2?["Minimum","Maximum"][s]:void 0}function Das(s,t){if(s.length===1)return 0;const n=s.map(a=>Math.abs(a-t)),r=Math.min(...n);return n.indexOf(r)}function Ras(s,t,n){const r=s/2,i=H$e([0,50],[0,r]);return(r-i(t)*n)*n}function Oas(s){return s.slice(0,-1).map((t,n)=>s[n+1]-t)}function Fas(s,t){if(t>0){const n=Oas(s);return Math.min(...n)>=t}return!0}function H$e(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 zas(s){return(String(s).split(".")[1]||"").length}function Bas(s,t){const n=Math.pow(10,t);return Math.round(s*n)/n}var s2t=Gjt,$as=Xjt,Uas=Qjt,qas=Jjt;const qf=N.forwardRef(({className:s,...t},n)=>e.jsxs(s2t,{ref:n,className:Ot("relative flex w-full touch-none select-none items-center",s),...t,children:[e.jsx($as,{className:"relative h-2 w-full grow overflow-hidden rounded-full bg-secondary",children:e.jsx(Uas,{className:"absolute h-full bg-primary"})}),e.jsx(qas,{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"})]}));qf.displayName=s2t.displayName;var Vas=[" ","Enter","ArrowUp","ArrowDown"],Has=[" ","Enter"],eR="Select",[y4e,v4e,Gas]=K$(eR),[lU,POn]=Um(eR,[Gas,q5]),b4e=q5(),[Was,LE]=lU(eR),[Kas,Yas]=lU(eR),n2t=s=>{const{__scopeSelect:t,children:n,open:r,defaultOpen:a,onOpenChange:i,value:l,defaultValue:o,onValueChange:c,dir:d,name:u,autoComplete:h,disabled:m,required:f,form:g}=s,y=b4e(t),[x,_]=N.useState(null),[b,k]=N.useState(null),[A,T]=N.useState(!1),P=F3(d),[I,M]=Ng({prop:r,defaultProp:a??!1,onChange:i,caller:eR}),[L,z]=Ng({prop:l,defaultProp:o,onChange:c,caller:eR}),$=N.useRef(null),V=x?g||!!x.closest("form"):!0,[W,G]=N.useState(new Set),X=Array.from(W).map(te=>te.props.value).join(";");return e.jsx(gQ,{...y,children:e.jsxs(Was,{required:f,scope:t,trigger:x,onTriggerChange:_,valueNode:b,onValueNodeChange:k,valueNodeHasChildren:A,onValueNodeHasChildrenChange:T,contentId:_g(),value:L,onValueChange:z,open:I,onOpenChange:M,dir:P,triggerPointerDownPosRef:$,disabled:m,children:[e.jsx(y4e.Provider,{scope:t,children:e.jsx(Kas,{scope:s.__scopeSelect,onNativeOptionAdd:N.useCallback(te=>{G(ne=>new Set(ne).add(te))},[]),onNativeOptionRemove:N.useCallback(te=>{G(ne=>{const me=new Set(ne);return me.delete(te),me})},[]),children:n})}),V?e.jsxs(C2t,{"aria-hidden":!0,required:f,tabIndex:-1,name:u,autoComplete:h,value:L,onChange:te=>z(te.target.value),disabled:m,form:g,children:[L===void 0?e.jsx("option",{value:""}):null,Array.from(W)]},X):null]})})};n2t.displayName=eR;var r2t="SelectTrigger",a2t=N.forwardRef((s,t)=>{const{__scopeSelect:n,disabled:r=!1,...a}=s,i=b4e(n),l=LE(r2t,n),o=l.disabled||r,c=jo(t,l.onTriggerChange),d=v4e(n),u=N.useRef("touch"),[h,m,f]=T2t(y=>{const x=d().filter(k=>!k.disabled),_=x.find(k=>k.value===l.value),b=E2t(x,y,_);b!==void 0&&l.onValueChange(b.value)}),g=y=>{o||(l.onOpenChange(!0),f()),y&&(l.triggerPointerDownPosRef.current={x:Math.round(y.pageX),y:Math.round(y.pageY)})};return e.jsx(J$,{asChild:!0,...i,children:e.jsx(Da.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":A2t(l.value)?"":void 0,...a,ref:c,onClick:la(a.onClick,y=>{y.currentTarget.focus(),u.current!=="mouse"&&g(y)}),onPointerDown:la(a.onPointerDown,y=>{u.current=y.pointerType;const x=y.target;x.hasPointerCapture(y.pointerId)&&x.releasePointerCapture(y.pointerId),y.button===0&&y.ctrlKey===!1&&y.pointerType==="mouse"&&(g(y),y.preventDefault())}),onKeyDown:la(a.onKeyDown,y=>{const x=h.current!=="";!(y.ctrlKey||y.altKey||y.metaKey)&&y.key.length===1&&m(y.key),!(x&&y.key===" ")&&Vas.includes(y.key)&&(g(),y.preventDefault())})})})});a2t.displayName=r2t;var i2t="SelectValue",o2t=N.forwardRef((s,t)=>{const{__scopeSelect:n,className:r,style:a,children:i,placeholder:l="",...o}=s,c=LE(i2t,n),{onValueNodeHasChildrenChange:d}=c,u=i!==void 0,h=jo(t,c.onValueNodeChange);return gf(()=>{d(u)},[d,u]),e.jsx(Da.span,{...o,ref:h,style:{pointerEvents:"none"},children:A2t(c.value)?e.jsx(e.Fragment,{children:l}):i})});o2t.displayName=i2t;var Zas="SelectIcon",l2t=N.forwardRef((s,t)=>{const{__scopeSelect:n,children:r,...a}=s;return e.jsx(Da.span,{"aria-hidden":!0,...a,ref:t,children:r||"▼"})});l2t.displayName=Zas;var Xas="SelectPortal",c2t=s=>e.jsx(Y$,{asChild:!0,...s});c2t.displayName=Xas;var tR="SelectContent",d2t=N.forwardRef((s,t)=>{const n=LE(tR,s.__scopeSelect),[r,a]=N.useState();if(gf(()=>{a(new DocumentFragment)},[]),!n.open){const i=r;return i?Lv.createPortal(e.jsx(u2t,{scope:s.__scopeSelect,children:e.jsx(y4e.Slot,{scope:s.__scopeSelect,children:e.jsx("div",{children:s.children})})}),i):null}return e.jsx(h2t,{...s,ref:t})});d2t.displayName=tR;var l2=10,[u2t,PE]=lU(tR),Qas="SelectContentImpl",Jas=rE("SelectContent.RemoveScroll"),h2t=N.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:f,sticky:g,hideWhenDetached:y,avoidCollisions:x,..._}=s,b=LE(tR,n),[k,A]=N.useState(null),[T,P]=N.useState(null),I=jo(t,Se=>A(Se)),[M,L]=N.useState(null),[z,$]=N.useState(null),V=v4e(n),[W,G]=N.useState(!1),X=N.useRef(!1);N.useEffect(()=>{if(k)return o4e(k)},[k]),r4e();const te=N.useCallback(Se=>{const[Ie,...Me]=V().map(Ne=>Ne.ref.current),[Re]=Me.slice(-1),Be=document.activeElement;for(const Ne of Se)if(Ne===Be||(Ne==null||Ne.scrollIntoView({block:"nearest"}),Ne===Ie&&T&&(T.scrollTop=0),Ne===Re&&T&&(T.scrollTop=T.scrollHeight),Ne==null||Ne.focus(),document.activeElement!==Be))return},[V,T]),ne=N.useCallback(()=>te([M,k]),[te,M,k]);N.useEffect(()=>{W&&ne()},[W,ne]);const{onOpenChange:me,triggerPointerDownPosRef:ue}=b;N.useEffect(()=>{if(k){let Se={x:0,y:0};const Ie=Re=>{var Be,Ne;Se={x:Math.abs(Math.round(Re.pageX)-(((Be=ue.current)==null?void 0:Be.x)??0)),y:Math.abs(Math.round(Re.pageY)-(((Ne=ue.current)==null?void 0:Ne.y)??0))}},Me=Re=>{Se.x<=10&&Se.y<=10?Re.preventDefault():k.contains(Re.target)||me(!1),document.removeEventListener("pointermove",Ie),ue.current=null};return ue.current!==null&&(document.addEventListener("pointermove",Ie),document.addEventListener("pointerup",Me,{capture:!0,once:!0})),()=>{document.removeEventListener("pointermove",Ie),document.removeEventListener("pointerup",Me,{capture:!0})}}},[k,me,ue]),N.useEffect(()=>{const Se=()=>me(!1);return window.addEventListener("blur",Se),window.addEventListener("resize",Se),()=>{window.removeEventListener("blur",Se),window.removeEventListener("resize",Se)}},[me]);const[ce,ae]=T2t(Se=>{const Ie=V().filter(Be=>!Be.disabled),Me=Ie.find(Be=>Be.ref.current===document.activeElement),Re=E2t(Ie,Se,Me);Re&&setTimeout(()=>Re.ref.current.focus())}),he=N.useCallback((Se,Ie,Me)=>{const Re=!X.current&&!Me;(b.value!==void 0&&b.value===Ie||Re)&&(L(Se),Re&&(X.current=!0))},[b.value]),xe=N.useCallback(()=>k==null?void 0:k.focus(),[k]),ve=N.useCallback((Se,Ie,Me)=>{const Re=!X.current&&!Me;(b.value!==void 0&&b.value===Ie||Re)&&$(Se)},[b.value]),ge=r==="popper"?DDe:m2t,be=ge===DDe?{side:o,sideOffset:c,align:d,alignOffset:u,arrowPadding:h,collisionBoundary:m,collisionPadding:f,sticky:g,hideWhenDetached:y,avoidCollisions:x}:{};return e.jsx(u2t,{scope:n,content:k,viewport:T,onViewportChange:P,itemRefCallback:he,selectedItem:M,onItemLeave:xe,itemTextRefCallback:ve,focusSelectedItem:ne,selectedItemText:z,position:r,isPositioned:W,searchRef:ce,children:e.jsx(jQ,{as:Jas,allowPinchZoom:!0,children:e.jsx(_Q,{asChild:!0,trapped:b.open,onMountAutoFocus:Se=>{Se.preventDefault()},onUnmountAutoFocus:la(a,Se=>{var Ie;(Ie=b.trigger)==null||Ie.focus({preventScroll:!0}),Se.preventDefault()}),children:e.jsx(TE,{asChild:!0,disableOutsidePointerEvents:!0,onEscapeKeyDown:i,onPointerDownOutside:l,onFocusOutside:Se=>Se.preventDefault(),onDismiss:()=>b.onOpenChange(!1),children:e.jsx(ge,{role:"listbox",id:b.contentId,"data-state":b.open?"open":"closed",dir:b.dir,onContextMenu:Se=>Se.preventDefault(),..._,...be,onPlaced:()=>G(!0),ref:I,style:{display:"flex",flexDirection:"column",outline:"none",..._.style},onKeyDown:la(_.onKeyDown,Se=>{const Ie=Se.ctrlKey||Se.altKey||Se.metaKey;if(Se.key==="Tab"&&Se.preventDefault(),!Ie&&Se.key.length===1&&ae(Se.key),["ArrowUp","ArrowDown","Home","End"].includes(Se.key)){let Re=V().filter(Be=>!Be.disabled).map(Be=>Be.ref.current);if(["ArrowUp","End"].includes(Se.key)&&(Re=Re.slice().reverse()),["ArrowUp","ArrowDown"].includes(Se.key)){const Be=Se.target,Ne=Re.indexOf(Be);Re=Re.slice(Ne+1)}setTimeout(()=>te(Re)),Se.preventDefault()}})})})})})})});h2t.displayName=Qas;var eis="SelectItemAlignedPosition",m2t=N.forwardRef((s,t)=>{const{__scopeSelect:n,onPlaced:r,...a}=s,i=LE(tR,n),l=PE(tR,n),[o,c]=N.useState(null),[d,u]=N.useState(null),h=jo(t,I=>u(I)),m=v4e(n),f=N.useRef(!1),g=N.useRef(!0),{viewport:y,selectedItem:x,selectedItemText:_,focusSelectedItem:b}=l,k=N.useCallback(()=>{if(i.trigger&&i.valueNode&&o&&d&&y&&x&&_){const I=i.trigger.getBoundingClientRect(),M=d.getBoundingClientRect(),L=i.valueNode.getBoundingClientRect(),z=_.getBoundingClientRect();if(i.dir!=="rtl"){const Be=z.left-M.left,Ne=L.left-Be,Ge=I.left-Ne,Ce=I.width+Ge,Fe=Math.max(Ce,M.width),Ae=window.innerWidth-l2,Xe=uY(Ne,[l2,Math.max(l2,Ae-Fe)]);o.style.minWidth=Ce+"px",o.style.left=Xe+"px"}else{const Be=M.right-z.right,Ne=window.innerWidth-L.right-Be,Ge=window.innerWidth-I.right-Ne,Ce=I.width+Ge,Fe=Math.max(Ce,M.width),Ae=window.innerWidth-l2,Xe=uY(Ne,[l2,Math.max(l2,Ae-Fe)]);o.style.minWidth=Ce+"px",o.style.right=Xe+"px"}const $=m(),V=window.innerHeight-l2*2,W=y.scrollHeight,G=window.getComputedStyle(d),X=parseInt(G.borderTopWidth,10),te=parseInt(G.paddingTop,10),ne=parseInt(G.borderBottomWidth,10),me=parseInt(G.paddingBottom,10),ue=X+te+W+me+ne,ce=Math.min(x.offsetHeight*5,ue),ae=window.getComputedStyle(y),he=parseInt(ae.paddingTop,10),xe=parseInt(ae.paddingBottom,10),ve=I.top+I.height/2-l2,ge=V-ve,be=x.offsetHeight/2,Se=x.offsetTop+be,Ie=X+te+Se,Me=ue-Ie;if(Ie<=ve){const Be=$.length>0&&x===$[$.length-1].ref.current;o.style.bottom="0px";const Ne=d.clientHeight-y.offsetTop-y.offsetHeight,Ge=Math.max(ge,be+(Be?xe:0)+Ne+ne),Ce=Ie+Ge;o.style.height=Ce+"px"}else{const Be=$.length>0&&x===$[0].ref.current;o.style.top="0px";const Ge=Math.max(ve,X+y.offsetTop+(Be?he:0)+be)+Me;o.style.height=Ge+"px",y.scrollTop=Ie-ve+y.offsetTop}o.style.margin=`${l2}px 0`,o.style.minHeight=ce+"px",o.style.maxHeight=V+"px",r==null||r(),requestAnimationFrame(()=>f.current=!0)}},[m,i.trigger,i.valueNode,o,d,y,x,_,i.dir,r]);gf(()=>k(),[k]);const[A,T]=N.useState();gf(()=>{d&&T(window.getComputedStyle(d).zIndex)},[d]);const P=N.useCallback(I=>{I&&g.current===!0&&(k(),b==null||b(),g.current=!1)},[k,b]);return e.jsx(sis,{scope:n,contentWrapper:o,shouldExpandOnScrollRef:f,onScrollButtonChange:P,children:e.jsx("div",{ref:c,style:{display:"flex",flexDirection:"column",position:"fixed",zIndex:A},children:e.jsx(Da.div,{...a,ref:h,style:{boxSizing:"border-box",maxHeight:"100%",...a.style}})})})});m2t.displayName=eis;var tis="SelectPopperPosition",DDe=N.forwardRef((s,t)=>{const{__scopeSelect:n,align:r="start",collisionPadding:a=l2,...i}=s,l=b4e(n);return e.jsx(xQ,{...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)"}})});DDe.displayName=tis;var[sis,G$e]=lU(tR,{}),RDe="SelectViewport",p2t=N.forwardRef((s,t)=>{const{__scopeSelect:n,nonce:r,...a}=s,i=PE(RDe,n),l=G$e(RDe,n),o=jo(t,i.onViewportChange),c=N.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(y4e.Slot,{scope:n,children:e.jsx(Da.div,{"data-radix-select-viewport":"",role:"presentation",...a,ref:o,style:{position:"relative",flex:1,overflow:"hidden auto",...a.style},onScroll:la(a.onScroll,d=>{const u=d.currentTarget,{contentWrapper:h,shouldExpandOnScrollRef:m}=l;if(m!=null&&m.current&&h){const f=Math.abs(c.current-u.scrollTop);if(f>0){const g=window.innerHeight-l2*2,y=parseFloat(h.style.minHeight),x=parseFloat(h.style.height),_=Math.max(y,x);if(_0?A:0,h.style.justifyContent="flex-end")}}}c.current=u.scrollTop})})})]})});p2t.displayName=RDe;var f2t="SelectGroup",[nis,ris]=lU(f2t),ais=N.forwardRef((s,t)=>{const{__scopeSelect:n,...r}=s,a=_g();return e.jsx(nis,{scope:n,id:a,children:e.jsx(Da.div,{role:"group","aria-labelledby":a,...r,ref:t})})});ais.displayName=f2t;var g2t="SelectLabel",x2t=N.forwardRef((s,t)=>{const{__scopeSelect:n,...r}=s,a=ris(g2t,n);return e.jsx(Da.div,{id:a.id,...r,ref:t})});x2t.displayName=g2t;var $2e="SelectItem",[iis,y2t]=lU($2e),v2t=N.forwardRef((s,t)=>{const{__scopeSelect:n,value:r,disabled:a=!1,textValue:i,...l}=s,o=LE($2e,n),c=PE($2e,n),d=o.value===r,[u,h]=N.useState(i??""),[m,f]=N.useState(!1),g=jo(t,b=>{var k;return(k=c.itemRefCallback)==null?void 0:k.call(c,b,r,a)}),y=_g(),x=N.useRef("touch"),_=()=>{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(iis,{scope:n,value:r,disabled:a,textId:y,isSelected:d,onItemTextChange:N.useCallback(b=>{h(k=>k||((b==null?void 0:b.textContent)??"").trim())},[]),children:e.jsx(y4e.ItemSlot,{scope:n,value:r,disabled:a,textValue:u,children:e.jsx(Da.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:g,onFocus:la(l.onFocus,()=>f(!0)),onBlur:la(l.onBlur,()=>f(!1)),onClick:la(l.onClick,()=>{x.current!=="mouse"&&_()}),onPointerUp:la(l.onPointerUp,()=>{x.current==="mouse"&&_()}),onPointerDown:la(l.onPointerDown,b=>{x.current=b.pointerType}),onPointerMove:la(l.onPointerMove,b=>{var k;x.current=b.pointerType,a?(k=c.onItemLeave)==null||k.call(c):x.current==="mouse"&&b.currentTarget.focus({preventScroll:!0})}),onPointerLeave:la(l.onPointerLeave,b=>{var k;b.currentTarget===document.activeElement&&((k=c.onItemLeave)==null||k.call(c))}),onKeyDown:la(l.onKeyDown,b=>{var A;((A=c.searchRef)==null?void 0:A.current)!==""&&b.key===" "||(Has.includes(b.key)&&_(),b.key===" "&&b.preventDefault())})})})})});v2t.displayName=$2e;var BH="SelectItemText",b2t=N.forwardRef((s,t)=>{const{__scopeSelect:n,className:r,style:a,...i}=s,l=LE(BH,n),o=PE(BH,n),c=y2t(BH,n),d=Yas(BH,n),[u,h]=N.useState(null),m=jo(t,_=>h(_),c.onItemTextChange,_=>{var b;return(b=o.itemTextRefCallback)==null?void 0:b.call(o,_,c.value,c.disabled)}),f=u==null?void 0:u.textContent,g=N.useMemo(()=>e.jsx("option",{value:c.value,disabled:c.disabled,children:f},c.value),[c.disabled,c.value,f]),{onNativeOptionAdd:y,onNativeOptionRemove:x}=d;return gf(()=>(y(g),()=>x(g)),[y,x,g]),e.jsxs(e.Fragment,{children:[e.jsx(Da.span,{id:c.textId,...i,ref:m}),c.isSelected&&l.valueNode&&!l.valueNodeHasChildren?Lv.createPortal(i.children,l.valueNode):null]})});b2t.displayName=BH;var _2t="SelectItemIndicator",w2t=N.forwardRef((s,t)=>{const{__scopeSelect:n,...r}=s;return y2t(_2t,n).isSelected?e.jsx(Da.span,{"aria-hidden":!0,...r,ref:t}):null});w2t.displayName=_2t;var ODe="SelectScrollUpButton",j2t=N.forwardRef((s,t)=>{const n=PE(ODe,s.__scopeSelect),r=G$e(ODe,s.__scopeSelect),[a,i]=N.useState(!1),l=jo(t,r.onScrollButtonChange);return gf(()=>{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(k2t,{...s,ref:l,onAutoScroll:()=>{const{viewport:o,selectedItem:c}=n;o&&c&&(o.scrollTop=o.scrollTop-c.offsetHeight)}}):null});j2t.displayName=ODe;var FDe="SelectScrollDownButton",N2t=N.forwardRef((s,t)=>{const n=PE(FDe,s.__scopeSelect),r=G$e(FDe,s.__scopeSelect),[a,i]=N.useState(!1),l=jo(t,r.onScrollButtonChange);return gf(()=>{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(k2t,{...s,ref:l,onAutoScroll:()=>{const{viewport:o,selectedItem:c}=n;o&&c&&(o.scrollTop=o.scrollTop+c.offsetHeight)}}):null});N2t.displayName=FDe;var k2t=N.forwardRef((s,t)=>{const{__scopeSelect:n,onAutoScroll:r,...a}=s,i=PE("SelectScrollButton",n),l=N.useRef(null),o=v4e(n),c=N.useCallback(()=>{l.current!==null&&(window.clearInterval(l.current),l.current=null)},[]);return N.useEffect(()=>()=>c(),[c]),gf(()=>{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(Da.div,{"aria-hidden":!0,...a,ref:t,style:{flexShrink:0,...a.style},onPointerDown:la(a.onPointerDown,()=>{l.current===null&&(l.current=window.setInterval(r,50))}),onPointerMove:la(a.onPointerMove,()=>{var d;(d=i.onItemLeave)==null||d.call(i),l.current===null&&(l.current=window.setInterval(r,50))}),onPointerLeave:la(a.onPointerLeave,()=>{c()})})}),ois="SelectSeparator",S2t=N.forwardRef((s,t)=>{const{__scopeSelect:n,...r}=s;return e.jsx(Da.div,{"aria-hidden":!0,...r,ref:t})});S2t.displayName=ois;var zDe="SelectArrow",lis=N.forwardRef((s,t)=>{const{__scopeSelect:n,...r}=s,a=b4e(n),i=LE(zDe,n),l=PE(zDe,n);return i.open&&l.position==="popper"?e.jsx(yQ,{...a,...r,ref:t}):null});lis.displayName=zDe;var cis="SelectBubbleInput",C2t=N.forwardRef(({__scopeSelect:s,value:t,...n},r)=>{const a=N.useRef(null),i=jo(r,a),l=EQ(t);return N.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(Da.select,{...n,style:{...M1t,...n.style},ref:i,defaultValue:t})});C2t.displayName=cis;function A2t(s){return s===""||s===void 0}function T2t(s){const t=cf(s),n=N.useRef(""),r=N.useRef(0),a=N.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=N.useCallback(()=>{n.current="",window.clearTimeout(r.current)},[]);return N.useEffect(()=>()=>window.clearTimeout(r.current),[]),[n,a,i]}function E2t(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=dis(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 dis(s,t){return s.map((n,r)=>s[(t+r)%s.length])}var uis=n2t,M2t=a2t,his=o2t,mis=l2t,pis=c2t,L2t=d2t,fis=p2t,P2t=x2t,I2t=v2t,gis=b2t,xis=w2t,D2t=j2t,R2t=N2t,O2t=S2t;const Ns=uis,ks=his,ws=N.forwardRef(({className:s,children:t,...n},r)=>e.jsxs(M2t,{ref:r,className:Ot("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(mis,{asChild:!0,children:e.jsx(Xo,{className:"h-4 w-4 opacity-50"})})]}));ws.displayName=M2t.displayName;const F2t=N.forwardRef(({className:s,...t},n)=>e.jsx(D2t,{ref:n,className:Ot("flex cursor-default items-center justify-center py-1",s),...t,children:e.jsx(zy,{className:"h-4 w-4"})}));F2t.displayName=D2t.displayName;const z2t=N.forwardRef(({className:s,...t},n)=>e.jsx(R2t,{ref:n,className:Ot("flex cursor-default items-center justify-center py-1",s),...t,children:e.jsx(Xo,{className:"h-4 w-4"})}));z2t.displayName=R2t.displayName;const js=N.forwardRef(({className:s,children:t,position:n="popper",...r},a)=>e.jsx(pis,{children:e.jsxs(L2t,{ref:a,className:Ot("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(F2t,{}),e.jsx(fis,{className:Ot("p-1",n==="popper"&&"h-[var(--radix-select-trigger-height)] w-full min-w-[var(--radix-select-trigger-width)]"),children:t}),e.jsx(z2t,{})]})}));js.displayName=L2t.displayName;const yis=N.forwardRef(({className:s,...t},n)=>e.jsx(P2t,{ref:n,className:Ot("py-1.5 pl-8 pr-2 text-sm font-semibold",s),...t}));yis.displayName=P2t.displayName;const nt=N.forwardRef(({className:s,children:t,...n},r)=>e.jsxs(I2t,{ref:r,className:Ot("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(xis,{children:e.jsx(pa,{className:"h-4 w-4"})})}),e.jsx(gis,{children:t})]}));nt.displayName=I2t.displayName;const vis=N.forwardRef(({className:s,...t},n)=>e.jsx(O2t,{ref:n,className:Ot("-mx-1 my-1 h-px bg-muted",s),...t}));vis.displayName=O2t.displayName;const bis=s=>mt({queryKey:["public-listings",s],queryFn:async()=>{let t=H.from("listings").select(` id, slug, agent_id, property_address, city, state, neighborhood, price, property_type, status, bedrooms, bathrooms, square_footage, lot_size, year_built, has_hoa, description, latitude, longitude, created_at, updated_at, photos:listing_photos(id, photo_url, is_primary), agent:profiles!listings_agent_id_fkey(id, name, email, phone, avatar_url, brokerage_name, brokerage:brokerages(name)) `).eq("is_approved",!0).eq("is_public",!0).order("created_at",{ascending:!1});if(s!=null&&s.status&&(t=t.eq("status",s.status)),s!=null&&s.propertyType&&(t=t.eq("property_type",s.propertyType)),s!=null&&s.city){const a=s.city.replace(/[%,()]/g," ").trim();if(a){const i=`%${a}%`;t=t.or(`city.ilike.${i},neighborhood.ilike.${i},property_address.ilike.${i}`)}}s!=null&&s.minPrice&&(t=t.gte("price",s.minPrice)),s!=null&&s.maxPrice&&(t=t.lte("price",s.maxPrice));const{data:n,error:r}=await t;if(r)throw r;return n}}),_is=()=>mt({queryKey:["public-listings-search-index"],staleTime:5*60*1e3,queryFn:async()=>{const{data:s,error:t}=await H.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)}}}),wis=s=>mt({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=H.from("listings").select(` id, slug, agent_id, property_address, city, state, neighborhood, price, property_type, status, bedrooms, bathrooms, square_footage, lot_size, year_built, has_hoa, description, agent_notes, agent_notes_public, mls_link, video_link, video_id, latitude, longitude, page_config, page_theme, created_at, updated_at, photos:listing_photos(id, photo_url, is_primary, sort_order), agent:profiles!listings_agent_id_fkey(id, name, email, phone, avatar_url, brokerage_name, brokerage:brokerages(name)), video:agent_videos!listings_video_id_fkey(id, playback_url, thumbnail_url, title, duration_seconds, bunny_video_id) `).eq("is_approved",!0).eq("is_public",!0);t?n=n.eq("id",s):n=n.eq("slug",s);const{data:r,error:a}=await n.single();if(a)throw a;return r},enabled:!!s}),jis=()=>_t({mutationFn:async({listingId:s,agentId:t,firstName:n,lastName:r,email:a,phone:i,shareToken:l,leadType:o="info_request",preferredDate:c,preferredTime:d,showingMode:u,message:h})=>{let m=null,f=null;if(l){const{data:_}=await H.from("listing_shares").select("id, sharing_agent_id").eq("share_token",l).eq("listing_id",s).maybeSingle();_&&(m=_.id,f=_.sharing_agent_id)}const{data:g,error:y}=await H.from("listing_leads").insert({listing_id:s,agent_id:f||t,first_name:n,last_name:r,email:a,phone:i,share_id:m,referred_by_agent_id:f,lead_type:o,preferred_date:c||null,preferred_time:d||null,showing_mode:u||null,message:h||null}).select().single();if(y)throw y;const{error:x}=await H.functions.invoke("process-listing-lead",{body:{leadId:g.id}});return x&&console.error("Error processing lead:",x),g}}),Nis=()=>_t({mutationFn:async s=>{const{error:t}=await H.rpc("increment_listing_share_click",{p_share_token:s});if(t)throw t}}),Itt="/assets/levelup-logo-color-BeKd2k_g.png",kis={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"},Sis={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"},Dtt={single_family:"Single Family",condo:"Condo",townhouse:"Townhouse",land:"Land",multi_family:"Multi-Family",luxury:"Luxury",commercial:"Commercial",other:"Other"},Fte=s=>new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:0}).format(s),SV=s=>new Intl.NumberFormat("en-US").format(s);function B2t({slugOverride:s}={}){var Yt,Kt,Xs,zs,Vt;const t=uo(),n=s||t.slugOrId,[r]=$c(),{data:a,isLoading:i}=wis(n||""),l=jis(),o=Nis(),c=r.get("ref"),[d,u]=N.useState(""),[h,m]=N.useState(""),[f,g]=N.useState(""),[y,x]=N.useState(""),[_,b]=N.useState(""),[k,A]=N.useState(""),[T,P]=N.useState(""),[I,M]=N.useState("in_person"),[L,z]=N.useState("info"),[$,V]=N.useState(!1),[W,G]=N.useState(!1),[X,te]=N.useState(null),[ne,me]=N.useState(!1);N.useState(!1);const[ue,ce]=N.useState(!1),[ae,he]=N.useState(20),[xe,ve]=N.useState(6.5),[ge,be]=N.useState(30),Se=N.useRef(null),[Ie,Me]=N.useState(!1);N.useEffect(()=>{const At=()=>Me(window.scrollY>300);return window.addEventListener("scroll",At,{passive:!0}),()=>window.removeEventListener("scroll",At)},[]),N.useEffect(()=>{c&&o.mutate(c)},[c]),N.useEffect(()=>{window.scrollTo({top:0,left:0,behavior:"auto"})},[n]);const Re=(a==null?void 0:a.photos)||[],Be=Re.find(At=>At.is_primary)||Re[0],Ne=N.useMemo(()=>{if(!(a!=null&&a.price))return 0;const At=a.price*(1-ae/100),Os=xe/100/12,Nt=ge*12;return Os===0?At/Nt:At*Os/(1-Math.pow(1+Os,-Nt))},[a==null?void 0:a.price,ae,xe,ge]),Ge=async()=>{const At=window.location.href;if(navigator.share)try{await navigator.share({title:document.title,url:At})}catch{}else await navigator.clipboard.writeText(At),ie.success("Link copied to clipboard")},Ce=async At=>{if(At.preventDefault(),!d.trim()||!f.trim()||!a)return;const Os=L==="showing";if(Os&&!k){ie.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:f.trim(),phone:y.trim(),shareToken:c,leadType:Os?"showing_request":"info_request",preferredDate:Os?k:null,preferredTime:Os&&T||null,showingMode:Os?I:null,message:_.trim()||null}),G(!0),ie.success(Os?"Showing request sent! The agent will confirm details shortly.":"Thanks! The agent will be in touch soon.")}catch(Nt){console.error("Lead submission error:",Nt),ie.error(`Failed to submit: ${Nt.message||"Please try again"}`)}finally{V(!1)}},Fe=()=>{X!==null&&te(X===0?Re.length-1:X-1)},Ae=()=>{X!==null&&te(X===Re.length-1?0:X+1)};if(i)return e.jsx("div",{className:"min-h-screen bg-neutral-950",children:e.jsx(xn,{className:"h-[100svh] w-full rounded-none bg-neutral-900"})});if(!a)return e.jsxs("div",{className:"min-h-screen bg-background",children:[e.jsx("header",{className:"border-b bg-card",children:e.jsx("div",{className:"container mx-auto px-4 py-4",children:e.jsx(cr,{to:"/public/listings",className:"flex items-center gap-2",children:e.jsx("img",{src:Itt,alt:"LevelUp",className:"h-8"})})})}),e.jsxs("div",{className:"container mx-auto px-4 py-24 text-center",children:[e.jsx(_a,{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(cr,{to:typeof window<"u"&&window.location.host==="listings.relevelup.com"?"/":"/public/listings",children:"Browse All Listings"})})]})]});const Xe=a.property_address?`${a.property_address} — ${a.city}, ${a.state}`:`${a.city}, ${a.state} Home for Sale`,$e=((Kt=(Yt=a.agent)==null?void 0:Yt.brokerage)==null?void 0:Kt.name)||((Xs=a.agent)==null?void 0:Xs.brokerage_name),Ye=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,Je=a.description||"",Ke=Je.length>420,st=ue||!Ke?Je:Je.slice(0,420).trimEnd()+"…",rt=a.page_config||{},Ze=At=>{var Os;return(((Os=rt.sections)==null?void 0:Os[At])??!0)!==!1},ht=Array.isArray(rt.addons)?rt.addons:[],Bt=rt.custom_note||"",Ct=rt.accent_color||null;return e.jsxs(e.Fragment,{children:[e.jsxs(ic,{children:[e.jsxs("title",{children:[Xe," | LevelUp Listings"]}),e.jsx("meta",{name:"description",content:`${Fte(a.price)} · ${a.bedrooms||""}BD ${a.bathrooms||""}BA ${a.square_footage?a.square_footage.toLocaleString()+" sqft · ":""}${Dtt[a.property_type]} in ${a.city}, ${a.state}. ${Je.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:Xe}),e.jsx("meta",{property:"og:description",content:`${Fte(a.price)} · ${a.city}, ${a.state}`}),e.jsx("meta",{property:"og:type",content:"website"}),e.jsx("meta",{property:"og:url",content:`https://listings.relevelup.com/${a.slug||a.id}`}),Be&&e.jsx("meta",{property:"og:image",content:Be.photo_url}),e.jsx("meta",{property:"og:site_name",content:"LevelUp Listings"}),e.jsx("meta",{name:"twitter:card",content:"summary_large_image"}),e.jsx("meta",{name:"twitter:title",content:Xe}),e.jsx("meta",{name:"twitter:description",content:`${Fte(a.price)} · ${a.city}, ${a.state}`}),Be&&e.jsx("meta",{name:"twitter:image",content:Be.photo_url}),e.jsx("meta",{name:"robots",content:"index, follow"}),e.jsx("script",{type:"application/ld+json",children:JSON.stringify({"@context":"https://schema.org","@type":"RealEstateListing",name:a.property_address||`${a.city}, ${a.state} Home`,description:Je,url:`https://listings.relevelup.com/${a.slug||a.id}`,datePosted:a.created_at,image:Re.map(At=>At.photo_url),address:{"@type":"PostalAddress",streetAddress:a.property_address||void 0,addressLocality:a.city,addressRegion:a.state,addressCountry:"US"},offers:{"@type":"Offer",price:a.price,priceCurrency:"USD",availability:a.status==="sold"?"https://schema.org/SoldOut":a.status==="under_contract"?"https://schema.org/LimitedAvailability":"https://schema.org/InStock"},numberOfRooms:a.bedrooms||void 0,numberOfBathroomsTotal:a.bathrooms||void 0,floorSize:a.square_footage?{"@type":"QuantitativeValue",value:a.square_footage,unitCode:"FTK"}:void 0,yearBuilt:a.year_built||void 0})}),e.jsx("style",{children:` .font-display { font-family: 'Fraunces', ui-serif, Georgia, serif; font-optical-sizing: auto; letter-spacing: -0.02em; } @keyframes kb-zoom { from { transform: scale(1.08); } to { transform: scale(1); } } .kb-zoom { animation: kb-zoom 12s ease-out forwards; } .noscroll::-webkit-scrollbar { display: none; } `})]}),e.jsxs("div",{className:"bg-neutral-950 text-neutral-100 min-h-screen",children:[e.jsx("header",{className:`fixed inset-x-0 top-0 z-40 transition-all duration-300 ${Ie?"bg-neutral-950/85 backdrop-blur-xl border-b border-white/10 py-3":"bg-gradient-to-b from-black/60 to-transparent py-4"}`,children:e.jsxs("div",{className:"max-w-7xl mx-auto px-4 sm:px-6 flex items-center justify-between gap-3",children:[e.jsxs(cr,{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"})]}),Ie&&e.jsx("div",{className:"hidden md:flex items-center gap-1 text-sm",children:[["overview","Overview"],["gallery","Gallery"],["story","The Story"],["video","Video"],["map","Location"],["payment","Payment"],["agent","Agent"]].map(([At,Os])=>e.jsx("a",{href:`#${At}`,className:"px-3 py-1.5 rounded-full text-white/70 hover:text-white hover:bg-white/10 transition",children:Os},At))}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Nas,{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:Ge,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(Md,{className:"h-4 w-4 text-white"})}),e.jsx(B,{size:"sm",onClick:()=>me(!0),className:"hidden sm:inline-flex bg-white text-neutral-900 hover:bg-white/90 rounded-full h-9 px-4 font-medium",children:"Request Tour"})]})]})}),e.jsxs("section",{ref:Se,id:"overview",className:"relative h-[100svh] min-h-[620px] w-full overflow-hidden",children:[Be?e.jsx("img",{src:Be.photo_url,alt:a.property_address||`${a.city}, ${a.state}`,className:"absolute inset-0 h-full w-full object-cover kb-zoom"}):e.jsx("div",{className:"absolute inset-0 bg-gradient-to-br from-neutral-800 to-neutral-950"}),e.jsx("div",{className:"absolute inset-0 bg-gradient-to-t from-black via-black/50 to-black/20"}),e.jsx("div",{className:"absolute inset-0 bg-gradient-to-r from-black/40 via-transparent to-transparent"}),e.jsxs("div",{className:"absolute top-24 right-4 sm:right-8 z-10 flex flex-col items-end gap-2",children:[e.jsx(We,{className:`${kis[a.status]} text-white border-0 uppercase tracking-widest text-[10px] px-3 py-1 rounded-full shadow-lg`,children:Sis[a.status]}),Re.length>0&&e.jsxs("button",{onClick:()=>te(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($0,{className:"h-3.5 w-3.5"}),Re.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:Fte(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:SV(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(Ro,{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}),$e&&e.jsx("p",{className:"text-xs text-white/60",children:$e})]}),e.jsx(B,{size:"sm",onClick:()=>me(!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"]})]})})]}),Ze("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:A_,label:"Bedrooms",value:a.bedrooms},a.bathrooms&&{icon:Wx,label:"Bathrooms",value:a.bathrooms},a.square_footage&&{icon:L_,label:"Interior",value:`${SV(a.square_footage)} sqft`},a.lot_size&&{icon:l3,label:"Lot Size",value:a.lot_size},a.year_built&&{icon:ta,label:"Year Built",value:a.year_built},!a.year_built&&a.square_footage&&{icon:u5,label:"Price / sqft",value:`$${SV(Math.round(a.price/a.square_footage))}`}].filter(Boolean).slice(0,5).map((At,Os)=>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(At.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:At.label}),e.jsx("p",{className:"font-display text-2xl text-white font-light",children:At.value})]})]},Os))})}),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:[Ze("story")&&Je&&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:st})}),Ke&&e.jsx("button",{onClick:()=>ce(!ue),className:"mt-4 text-sm text-white/60 hover:text-white underline underline-offset-4",children:ue?"Show less":"Read more"}),e.jsxs("div",{className:"mt-8 flex flex-wrap gap-2",children:[e.jsxs(We,{variant:"outline",className:"border-white/20 text-white/80 bg-white/5",children:[e.jsx(Ti,{className:"h-3 w-3 mr-1.5"}),Dtt[a.property_type]]}),a.has_hoa&&e.jsx(We,{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(Tr,{className:"h-3.5 w-3.5 mr-1.5"})," MLS"]})})]}),(Bt||a.agent_notes&&a.agent_notes_public)&&e.jsxs("div",{className:"mt-10 rounded-2xl border border-white/10 bg-white/5 p-6",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-3",children:[e.jsx(Cn,{className:"h-4 w-4 text-amber-300"}),e.jsx("p",{className:"text-[11px] uppercase tracking-[0.25em] text-white/60",children:"A note from the agent"})]}),e.jsxs("p",{className:"text-white/80 whitespace-pre-wrap leading-relaxed italic font-display",children:['"',Bt||a.agent_notes,'"']})]})]}),Ze("gallery")&&Re.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:()=>te(0),className:"text-sm text-white/60 hover:text-white underline underline-offset-4 hidden sm:inline",children:["View all ",Re.length]})]}),e.jsx("div",{className:"grid grid-cols-4 gap-2 sm:gap-3",children:Re.slice(0,7).map((At,Os)=>{const Nt=["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"],ms=Os===6&&Re.length>7;return e.jsxs("button",{onClick:()=>te(Os),className:`${Nt[Os]} relative rounded-xl overflow-hidden group bg-neutral-900`,children:[e.jsx("img",{src:At.photo_url,alt:`Photo ${Os+1}`,className:"absolute inset-0 h-full w-full object-cover group-hover:scale-[1.04] transition-transform duration-500"}),ms&&e.jsxs("div",{className:"absolute inset-0 bg-black/60 flex flex-col items-center justify-center text-white",children:[e.jsx($0,{className:"h-6 w-6 mb-1"}),e.jsxs("span",{className:"font-medium",children:["+",Re.length-7," more"]})]})]},At.id)})})]}),Ze("video")&&((zs=a.video)==null?void 0:zs.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"})})]}),Ze("map")&&Ye&&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:Ye,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(ii,{className:"h-4 w-4"}),a.property_address?`${a.property_address}, `:"",a.city,", ",a.state]})]}),Ze("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:["$",SV(Math.round(Ne))]}),e.jsx("p",{className:"text-white/60",children:"/ month"})]}),e.jsxs("div",{className:"grid sm:grid-cols-3 gap-8",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsx(re,{className:"text-white/70 text-xs uppercase tracking-widest",children:"Down Payment"}),e.jsxs("span",{className:"text-white font-medium",children:[ae,"%"]})]}),e.jsx(qf,{value:[ae],onValueChange:At=>he(At[0]),min:0,max:50,step:1}),e.jsxs("p",{className:"text-xs text-white/50 mt-2",children:["$",SV(Math.round(a.price*ae/100))," down"]})]}),e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsx(re,{className:"text-white/70 text-xs uppercase tracking-widest",children:"Interest Rate"}),e.jsxs("span",{className:"text-white font-medium",children:[xe.toFixed(2),"%"]})]}),e.jsx(qf,{value:[xe],onValueChange:At=>ve(At[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(re,{className:"text-white/70 text-xs uppercase tracking-widest",children:"Loan Term"}),e.jsxs("span",{className:"text-white font-medium",children:[ge," yr"]})]}),e.jsx(qf,{value:[ge],onValueChange:At=>be(At[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."})]})]}),ht.map(At=>{const Os=At.type,Nt=At.data||{};if(Os==="extra_video"&&Nt.url){const ms=String(Nt.url).includes("youtu")?`https://www.youtube.com/embed/${String(Nt.url).split(/[/=]/).pop()}`:Nt.url;return e.jsxs("section",{children:[e.jsx("p",{className:"text-[11px] uppercase tracking-[0.3em] text-white/40 mb-2",children:Nt.eyebrow||"Featured Video"}),e.jsx("h2",{className:"font-display text-3xl sm:text-4xl font-light text-white mb-6",children:Nt.title||"Watch"}),e.jsx("div",{className:"relative rounded-2xl overflow-hidden bg-black shadow-2xl aspect-video",children:e.jsx("iframe",{src:ms,className:"absolute inset-0 h-full w-full",allowFullScreen:!0,title:Nt.title||"Video"})})]},At.id)}return Os==="3d_tour"&&Nt.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:Nt.title||"Step inside"}),e.jsx("div",{className:"relative rounded-2xl overflow-hidden bg-black shadow-2xl aspect-video",children:e.jsx("iframe",{src:Nt.url,className:"absolute inset-0 h-full w-full",allowFullScreen:!0,title:"3D Tour"})})]},At.id):Os==="floor_plan"&&Nt.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:Nt.title||"Layout"}),e.jsx("img",{src:Nt.image_url,alt:"Floor plan",className:"w-full rounded-2xl border border-white/10"})]},At.id):Os==="testimonial"&&Nt.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:['"',Nt.quote,'"']}),Nt.author&&e.jsxs("p",{className:"mt-4 text-sm text-white/60",children:["— ",Nt.author]})]},At.id):Os==="custom_cta"&&Nt.label?e.jsxs("section",{className:"rounded-2xl p-8 text-center",style:{background:Ct?`${Ct}22`:"rgba(255,255,255,0.05)",border:`1px solid ${Ct||"rgba(255,255,255,0.1)"}`},children:[Nt.title&&e.jsx("h3",{className:"font-display text-3xl text-white mb-4",children:Nt.title}),e.jsx(B,{asChild:!0,size:"lg",style:Ct?{background:Ct}:void 0,children:e.jsx("a",{href:Nt.url||"#agent",children:Nt.label})})]},At.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(Ro,{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}),$e&&e.jsx("p",{className:"text-sm text-white/60 mt-0.5",children:$e})]})]}),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(ga,{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(mn,{className:"h-3.5 w-3.5 mr-1.5"}),"Email"]})})]})]}),e.jsx("div",{id:"contact",className:"rounded-2xl border border-white/10 bg-white text-neutral-900 p-6 shadow-2xl",children:e.jsx(Rtt,{submitted:W,activeTab:L,setActiveTab:z,firstName:d,setFirstName:u,lastName:h,setLastName:m,email:f,setEmail:g,phone:y,setPhone:x,message:_,setMessage:b,preferredDate:k,setPreferredDate:A,preferredTime:T,setPreferredTime:P,showingMode:I,setShowingMode:M,isSubmitting:$,onSubmit:Ce})})]})]}),e.jsxs("div",{className:"lg:hidden fixed bottom-0 inset-x-0 z-40 bg-neutral-950/95 backdrop-blur-xl border-t border-white/10 px-4 py-3 flex items-center gap-2 safe-area-inset-bottom",children:[((Vt=a.agent)==null?void 0:Vt.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(ga,{className:"h-4 w-4 mr-1.5"}),"Call"]})}),e.jsxs(B,{onClick:()=>me(!0),className:"bg-white text-neutral-900 hover:bg-white/90 flex-[2] font-medium",children:[e.jsx(df,{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:Itt,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(Bs,{open:X!==null,onOpenChange:()=>te(null),children:e.jsxs(Fs,{className:"max-w-6xl p-0 bg-black/95 border-0",children:[e.jsx(qs,{className:"sr-only",children:e.jsx($s,{children:"Photo Gallery"})}),e.jsx("button",{onClick:()=>te(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(hr,{className:"h-5 w-5"})}),X!==null&&Re[X]&&e.jsxs("div",{className:"relative",children:[e.jsx("img",{src:Re[X].photo_url,alt:`Photo ${X+1}`,className:"w-full max-h-[85vh] object-contain"}),Re.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(Fc,{className:"h-6 w-6"})}),e.jsx("button",{onClick:Ae,className:"absolute right-4 top-1/2 -translate-y-1/2 rounded-full bg-white/10 hover:bg-white/20 p-3 text-white",children:e.jsx(Qa,{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:[X+1," / ",Re.length]})]})]})]})}),e.jsx(Bs,{open:ne,onOpenChange:me,children:e.jsxs(Fs,{className:"max-w-md p-0 bg-white text-neutral-900",children:[e.jsx(qs,{className:"sr-only",children:e.jsx($s,{children:"Contact the agent"})}),e.jsx("div",{className:"p-6",children:e.jsx(Rtt,{submitted:W,activeTab:L,setActiveTab:z,firstName:d,setFirstName:u,lastName:h,setLastName:m,email:f,setEmail:g,phone:y,setPhone:x,message:_,setMessage:b,preferredDate:k,setPreferredDate:A,preferredTime:T,setPreferredTime:P,showingMode:I,setShowingMode:M,isSubmitting:$,onSubmit:Ce})})]})})]})]})}function Rtt(s){const{submitted:t,activeTab:n,setActiveTab:r,firstName:a,setFirstName:i,lastName:l,setLastName:o,email:c,setEmail:d,phone:u,setPhone:h,message:m,setMessage:f,preferredDate:g,setPreferredDate:y,preferredTime:x,setPreferredTime:_,showingMode:b,setShowingMode:k,isSubmitting:A,onSubmit:T}=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(pa,{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(ya,{value:n,onValueChange:P=>r(P),children:[e.jsxs(va,{className:"grid w-full grid-cols-2 mb-4",children:[e.jsxs(ls,{value:"info",className:"gap-1.5",children:[e.jsx(xo,{className:"h-3.5 w-3.5"})," Get Info"]}),e.jsxs(ls,{value:"showing",className:"gap-1.5",children:[e.jsx(df,{className:"h-3.5 w-3.5"})," Request Tour"]})]}),e.jsxs("form",{onSubmit:T,className:"space-y-3",children:[e.jsxs(_s,{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(re,{htmlFor:"preferredDate",children:"Preferred Date *"}),e.jsx(we,{id:"preferredDate",type:"date",value:g,onChange:P=>y(P.target.value),min:new Date().toISOString().split("T")[0],required:n==="showing"})]}),e.jsxs("div",{children:[e.jsx(re,{htmlFor:"preferredTime",children:"Preferred Time"}),e.jsxs(Ns,{value:x,onValueChange:_,children:[e.jsx(ws,{id:"preferredTime",children:e.jsx(ks,{placeholder:"Any time"})}),e.jsxs(js,{children:[e.jsx(nt,{value:"morning",children:"Morning (9am–12pm)"}),e.jsx(nt,{value:"afternoon",children:"Afternoon (12pm–5pm)"}),e.jsx(nt,{value:"evening",children:"Evening (5pm–8pm)"})]})]})]})]}),e.jsxs("div",{children:[e.jsx(re,{htmlFor:"showingMode",children:"Tour Type"}),e.jsxs(Ns,{value:b,onValueChange:P=>k(P),children:[e.jsx(ws,{id:"showingMode",children:e.jsx(ks,{})}),e.jsxs(js,{children:[e.jsx(nt,{value:"in_person",children:"🏡 In-person showing"}),e.jsx(nt,{value:"video",children:"📱 Video tour (FaceTime/Zoom)"}),e.jsx(nt,{value:"either",children:"Either works for me"})]})]})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(re,{htmlFor:"firstName",children:"First Name *"}),e.jsx(we,{id:"firstName",value:a,onChange:P=>i(P.target.value),required:!0})]}),e.jsxs("div",{children:[e.jsx(re,{htmlFor:"lastName",children:"Last Name"}),e.jsx(we,{id:"lastName",value:l,onChange:P=>o(P.target.value)})]})]}),e.jsxs("div",{children:[e.jsx(re,{htmlFor:"email",children:"Email *"}),e.jsx(we,{id:"email",type:"email",value:c,onChange:P=>d(P.target.value),required:!0})]}),e.jsxs("div",{children:[e.jsxs(re,{htmlFor:"phone",children:["Phone ",n==="showing"&&"*"]}),e.jsx(we,{id:"phone",type:"tel",value:u,onChange:P=>h(P.target.value),required:n==="showing"})]}),e.jsxs("div",{children:[e.jsx(re,{htmlFor:"message",children:n==="showing"?"Anything else?":"Message (optional)"}),e.jsx(Ws,{id:"message",value:m,onChange:P=>f(P.target.value),rows:2})]}),e.jsx(B,{type:"submit",disabled:A,className:"w-full bg-neutral-900 hover:bg-neutral-800 text-white h-11",children:A?"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 U2e="/assets/levelup-logo-white-C2RAgAoG.png",Cis="/assets/listings-hero-noir-BHCJrhvU.jpg";var $2t={exports:{}};(function(s,t){(function(n,r){s.exports=r()})(Uf,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(j,p){var v=p[0],S=p[1],E=p[2],R=p[3],F=v*R-E*S;return F?(j[0]=R*(F=1/F),j[1]=-S*F,j[2]=-E*F,j[3]=v*F,j):null}function h(){var j=new d(9);return d!=Float32Array&&(j[1]=0,j[2]=0,j[3]=0,j[5]=0,j[6]=0,j[7]=0),j[0]=1,j[4]=1,j[8]=1,j}function m(j,p){var v=p[0],S=p[1],E=p[2],R=p[3],F=p[4],q=p[5],K=p[6],J=p[7],le=p[8];return j[0]=F*le-q*J,j[1]=E*J-S*le,j[2]=S*q-E*F,j[3]=q*K-R*le,j[4]=v*le-E*K,j[5]=E*R-v*q,j[6]=R*J-F*K,j[7]=S*K-v*J,j[8]=v*F-S*R,j}function f(j,p,v){var S=p[0],E=p[1],R=p[2],F=p[3],q=p[4],K=p[5],J=p[6],le=p[7],fe=p[8],ye=v[0],Te=v[1],Pe=v[2],Ue=v[3],Qe=v[4],at=v[5],pt=v[6],dt=v[7],wt=v[8];return j[0]=ye*S+Te*F+Pe*J,j[1]=ye*E+Te*q+Pe*le,j[2]=ye*R+Te*K+Pe*fe,j[3]=Ue*S+Qe*F+at*J,j[4]=Ue*E+Qe*q+at*le,j[5]=Ue*R+Qe*K+at*fe,j[6]=pt*S+dt*F+wt*J,j[7]=pt*E+dt*q+wt*le,j[8]=pt*R+dt*K+wt*fe,j}function g(){var j=new d(16);return d!=Float32Array&&(j[1]=0,j[2]=0,j[3]=0,j[4]=0,j[6]=0,j[7]=0,j[8]=0,j[9]=0,j[11]=0,j[12]=0,j[13]=0,j[14]=0),j[0]=1,j[5]=1,j[10]=1,j[15]=1,j}function y(j){var p=new d(16);return p[0]=j[0],p[1]=j[1],p[2]=j[2],p[3]=j[3],p[4]=j[4],p[5]=j[5],p[6]=j[6],p[7]=j[7],p[8]=j[8],p[9]=j[9],p[10]=j[10],p[11]=j[11],p[12]=j[12],p[13]=j[13],p[14]=j[14],p[15]=j[15],p}function x(j){return j[0]=1,j[1]=0,j[2]=0,j[3]=0,j[4]=0,j[5]=1,j[6]=0,j[7]=0,j[8]=0,j[9]=0,j[10]=1,j[11]=0,j[12]=0,j[13]=0,j[14]=0,j[15]=1,j}function _(j,p){var v=p[0],S=p[1],E=p[2],R=p[3],F=p[4],q=p[5],K=p[6],J=p[7],le=p[8],fe=p[9],ye=p[10],Te=p[11],Pe=p[12],Ue=p[13],Qe=p[14],at=p[15],pt=v*q-S*F,dt=v*K-E*F,wt=v*J-R*F,Tt=S*K-E*q,Lt=S*J-R*q,fs=E*J-R*K,Jt=le*Ue-fe*Pe,ps=le*Qe-ye*Pe,rs=le*at-Te*Pe,is=fe*Qe-ye*Ue,dn=fe*at-Te*Ue,fn=ye*at-Te*Qe,_n=pt*fn-dt*dn+wt*is+Tt*rs-Lt*ps+fs*Jt;return _n?(j[0]=(q*fn-K*dn+J*is)*(_n=1/_n),j[1]=(E*dn-S*fn-R*is)*_n,j[2]=(Ue*fs-Qe*Lt+at*Tt)*_n,j[3]=(ye*Lt-fe*fs-Te*Tt)*_n,j[4]=(K*rs-F*fn-J*ps)*_n,j[5]=(v*fn-E*rs+R*ps)*_n,j[6]=(Qe*wt-Pe*fs-at*dt)*_n,j[7]=(le*fs-ye*wt+Te*dt)*_n,j[8]=(F*dn-q*rs+J*Jt)*_n,j[9]=(S*rs-v*dn-R*Jt)*_n,j[10]=(Pe*Lt-Ue*wt+at*pt)*_n,j[11]=(fe*wt-le*Lt-Te*pt)*_n,j[12]=(q*ps-F*is-K*Jt)*_n,j[13]=(v*is-S*ps+E*Jt)*_n,j[14]=(Ue*dt-Pe*Tt-Qe*pt)*_n,j[15]=(le*Tt-fe*dt+ye*pt)*_n,j):null}function b(j,p,v){var S=p[0],E=p[1],R=p[2],F=p[3],q=p[4],K=p[5],J=p[6],le=p[7],fe=p[8],ye=p[9],Te=p[10],Pe=p[11],Ue=p[12],Qe=p[13],at=p[14],pt=p[15],dt=v[0],wt=v[1],Tt=v[2],Lt=v[3];return j[0]=dt*S+wt*q+Tt*fe+Lt*Ue,j[1]=dt*E+wt*K+Tt*ye+Lt*Qe,j[2]=dt*R+wt*J+Tt*Te+Lt*at,j[3]=dt*F+wt*le+Tt*Pe+Lt*pt,j[4]=(dt=v[4])*S+(wt=v[5])*q+(Tt=v[6])*fe+(Lt=v[7])*Ue,j[5]=dt*E+wt*K+Tt*ye+Lt*Qe,j[6]=dt*R+wt*J+Tt*Te+Lt*at,j[7]=dt*F+wt*le+Tt*Pe+Lt*pt,j[8]=(dt=v[8])*S+(wt=v[9])*q+(Tt=v[10])*fe+(Lt=v[11])*Ue,j[9]=dt*E+wt*K+Tt*ye+Lt*Qe,j[10]=dt*R+wt*J+Tt*Te+Lt*at,j[11]=dt*F+wt*le+Tt*Pe+Lt*pt,j[12]=(dt=v[12])*S+(wt=v[13])*q+(Tt=v[14])*fe+(Lt=v[15])*Ue,j[13]=dt*E+wt*K+Tt*ye+Lt*Qe,j[14]=dt*R+wt*J+Tt*Te+Lt*at,j[15]=dt*F+wt*le+Tt*Pe+Lt*pt,j}function k(j,p,v){var S,E,R,F,q,K,J,le,fe,ye,Te,Pe,Ue=v[0],Qe=v[1],at=v[2];return p===j?(j[12]=p[0]*Ue+p[4]*Qe+p[8]*at+p[12],j[13]=p[1]*Ue+p[5]*Qe+p[9]*at+p[13],j[14]=p[2]*Ue+p[6]*Qe+p[10]*at+p[14],j[15]=p[3]*Ue+p[7]*Qe+p[11]*at+p[15]):(E=p[1],R=p[2],F=p[3],q=p[4],K=p[5],J=p[6],le=p[7],fe=p[8],ye=p[9],Te=p[10],Pe=p[11],j[0]=S=p[0],j[1]=E,j[2]=R,j[3]=F,j[4]=q,j[5]=K,j[6]=J,j[7]=le,j[8]=fe,j[9]=ye,j[10]=Te,j[11]=Pe,j[12]=S*Ue+q*Qe+fe*at+p[12],j[13]=E*Ue+K*Qe+ye*at+p[13],j[14]=R*Ue+J*Qe+Te*at+p[14],j[15]=F*Ue+le*Qe+Pe*at+p[15]),j}function A(j,p,v){var S=v[0],E=v[1],R=v[2];return j[0]=p[0]*S,j[1]=p[1]*S,j[2]=p[2]*S,j[3]=p[3]*S,j[4]=p[4]*E,j[5]=p[5]*E,j[6]=p[6]*E,j[7]=p[7]*E,j[8]=p[8]*R,j[9]=p[9]*R,j[10]=p[10]*R,j[11]=p[11]*R,j[12]=p[12],j[13]=p[13],j[14]=p[14],j[15]=p[15],j}function T(j,p,v){var S=Math.sin(v),E=Math.cos(v),R=p[4],F=p[5],q=p[6],K=p[7],J=p[8],le=p[9],fe=p[10],ye=p[11];return p!==j&&(j[0]=p[0],j[1]=p[1],j[2]=p[2],j[3]=p[3],j[12]=p[12],j[13]=p[13],j[14]=p[14],j[15]=p[15]),j[4]=R*E+J*S,j[5]=F*E+le*S,j[6]=q*E+fe*S,j[7]=K*E+ye*S,j[8]=J*E-R*S,j[9]=le*E-F*S,j[10]=fe*E-q*S,j[11]=ye*E-K*S,j}function P(j,p,v){var S=Math.sin(v),E=Math.cos(v),R=p[0],F=p[1],q=p[2],K=p[3],J=p[8],le=p[9],fe=p[10],ye=p[11];return p!==j&&(j[4]=p[4],j[5]=p[5],j[6]=p[6],j[7]=p[7],j[12]=p[12],j[13]=p[13],j[14]=p[14],j[15]=p[15]),j[0]=R*E-J*S,j[1]=F*E-le*S,j[2]=q*E-fe*S,j[3]=K*E-ye*S,j[8]=R*S+J*E,j[9]=F*S+le*E,j[10]=q*S+fe*E,j[11]=K*S+ye*E,j}function I(j,p,v){var S=Math.sin(v),E=Math.cos(v),R=p[0],F=p[1],q=p[2],K=p[3],J=p[4],le=p[5],fe=p[6],ye=p[7];return p!==j&&(j[8]=p[8],j[9]=p[9],j[10]=p[10],j[11]=p[11],j[12]=p[12],j[13]=p[13],j[14]=p[14],j[15]=p[15]),j[0]=R*E+J*S,j[1]=F*E+le*S,j[2]=q*E+fe*S,j[3]=K*E+ye*S,j[4]=J*E-R*S,j[5]=le*E-F*S,j[6]=fe*E-q*S,j[7]=ye*E-K*S,j}function M(j,p){return j[0]=p[0],j[1]=0,j[2]=0,j[3]=0,j[4]=0,j[5]=p[1],j[6]=0,j[7]=0,j[8]=0,j[9]=0,j[10]=p[2],j[11]=0,j[12]=0,j[13]=0,j[14]=0,j[15]=1,j}function L(j,p,v){var S,E,R,F=v[0],q=v[1],K=v[2],J=Math.sqrt(F*F+q*q+K*K);return J0&&(R=1/Math.sqrt(R)),j[0]=p[0]*R,j[1]=p[1]*R,j[2]=p[2]*R,j}function Re(j,p){return j[0]*p[0]+j[1]*p[1]+j[2]*p[2]}function Be(j,p,v){var S=p[0],E=p[1],R=p[2],F=v[0],q=v[1],K=v[2];return j[0]=E*K-R*q,j[1]=R*F-S*K,j[2]=S*q-E*F,j}function Ne(j,p,v,S){var E=p[0],R=p[1],F=p[2];return j[0]=E+S*(v[0]-E),j[1]=R+S*(v[1]-R),j[2]=F+S*(v[2]-F),j}function Ge(j,p,v){var S=p[0],E=p[1],R=p[2],F=v[3]*S+v[7]*E+v[11]*R+v[15];return j[0]=(v[0]*S+v[4]*E+v[8]*R+v[12])/(F=F||1),j[1]=(v[1]*S+v[5]*E+v[9]*R+v[13])/F,j[2]=(v[2]*S+v[6]*E+v[10]*R+v[14])/F,j}function Ce(j,p,v){var S=p[0],E=p[1],R=p[2];return j[0]=S*v[0]+E*v[3]+R*v[6],j[1]=S*v[1]+E*v[4]+R*v[7],j[2]=S*v[2]+E*v[5]+R*v[8],j}function Fe(j,p,v){var S=v[0],E=v[1],R=v[2],F=v[3],q=p[0],K=p[1],J=p[2],le=E*J-R*K,fe=R*q-S*J,ye=S*K-E*q;return j[0]=q+F*(le+=le)+E*(ye+=ye)-R*(fe+=fe),j[1]=K+F*fe+R*le-S*ye,j[2]=J+F*ye+S*fe-E*le,j}function Ae(j){return j[0]=0,j[1]=0,j[2]=0,j}function Xe(j,p){return j[0]===p[0]&&j[1]===p[1]&&j[2]===p[2]}var $e=ue,Ye=ce,Je=X;function Ke(){var j=new d(4);return d!=Float32Array&&(j[0]=0,j[1]=0,j[2]=0,j[3]=0),j}function st(j,p,v){return j[0]=p[0]*v,j[1]=p[1]*v,j[2]=p[2]*v,j[3]=p[3]*v,j}function rt(j,p){var v=p[0],S=p[1],E=p[2],R=p[3],F=v*v+S*S+E*E+R*R;return F>0&&(F=1/Math.sqrt(F)),j[0]=v*F,j[1]=S*F,j[2]=E*F,j[3]=R*F,j}function Ze(j,p){return j[0]*p[0]+j[1]*p[1]+j[2]*p[2]+j[3]*p[3]}function ht(j,p,v){var S=p[0],E=p[1],R=p[2],F=p[3];return j[0]=v[0]*S+v[4]*E+v[8]*R+v[12]*F,j[1]=v[1]*S+v[5]*E+v[9]*R+v[13]*F,j[2]=v[2]*S+v[6]*E+v[10]*R+v[14]*F,j[3]=v[3]*S+v[7]*E+v[11]*R+v[15]*F,j}function Bt(){var j=new d(4);return d!=Float32Array&&(j[0]=0,j[1]=0,j[2]=0),j[3]=1,j}function Ct(j){return j[0]=0,j[1]=0,j[2]=0,j[3]=1,j}function Yt(j,p,v){v*=.5;var S=p[0],E=p[1],R=p[2],F=p[3],q=Math.sin(v),K=Math.cos(v);return j[0]=S*K+F*q,j[1]=E*K+R*q,j[2]=R*K-E*q,j[3]=F*K-S*q,j}function Kt(j,p,v){v*=.5;var S=p[0],E=p[1],R=p[2],F=p[3],q=Math.sin(v),K=Math.cos(v);return j[0]=S*K-R*q,j[1]=E*K+F*q,j[2]=R*K+S*q,j[3]=F*K-E*q,j}W(),Ke();var Xs,zs,Vt,At=rt,Os=(Xs=W(),zs=te(1,0,0),Vt=te(0,1,0),function(j,p,v){var S=Re(p,v);return S<-.999999?(Be(Xs,zs,p),Je(Xs)<1e-6&&Be(Xs,Vt,p),Me(Xs,Xs),function(E,R,F){F*=.5;var q=Math.sin(F);E[0]=q*R[0],E[1]=q*R[1],E[2]=q*R[2],E[3]=Math.cos(F)}(j,Xs,Math.PI),j):S>.999999?(j[0]=0,j[1]=0,j[2]=0,j[3]=1,j):(Be(Xs,p,v),j[0]=Xs[0],j[1]=Xs[1],j[2]=Xs[2],j[3]=1+S,At(j,j))});function Nt(){var j=new d(2);return d!=Float32Array&&(j[0]=0,j[1]=0),j}function ms(j,p){var v=new d(2);return v[0]=j,v[1]=p,v}function Ys(j,p,v){return j[0]=p,j[1]=v,j}function It(j,p,v){return j[0]=p[0]+v[0],j[1]=p[1]+v[1],j}function Ds(j,p,v){return j[0]=p[0]-v[0],j[1]=p[1]-v[1],j}function As(j,p,v){return j[0]=p[0]*v,j[1]=p[1]*v,j}function Hs(j){var p=j[0],v=j[1];return Math.sqrt(p*p+v*v)}function Rs(j,p){var v=p[0],S=p[1],E=v*v+S*S;return E>0&&(E=1/Math.sqrt(E)),j[0]=p[0]*E,j[1]=p[1]*E,j}function en(j,p){return j[0]*p[0]+j[1]*p[1]}Bt(),Bt(),h();var Rn,Bn,Dn=Ds;function Jn(j){return j&&j.__esModule&&Object.prototype.hasOwnProperty.call(j,"default")?j.default:j}Nt();var ua=function(){if(Bn)return Rn;function j(p,v,S,E){this.cx=3*p,this.bx=3*(S-p)-this.cx,this.ax=1-this.cx-this.bx,this.cy=3*v,this.by=3*(E-v)-this.cy,this.ay=1-this.cy-this.by,this.p1x=p,this.p1y=v,this.p2x=S,this.p2y=E}return Bn=1,Rn=j,j.prototype={sampleCurveX:function(p){return((this.ax*p+this.bx)*p+this.cx)*p},sampleCurveY:function(p){return((this.ay*p+this.by)*p+this.cy)*p},sampleCurveDerivativeX:function(p){return(3*this.ax*p+2*this.bx)*p+this.cx},solveCurveX:function(p,v){if(v===void 0&&(v=1e-6),p<0)return 0;if(p>1)return 1;for(var S=p,E=0;E<8;E++){var R=this.sampleCurveX(S)-p;if(Math.abs(R)R?q=S:K=S,S=.5*(K-q)+q;return S},solve:function(p,v){return this.sampleCurveY(this.solveCurveX(p,v))}},Rn}(),Mr=Jn(ua);function sn(j,p){this.x=j,this.y=p}function ki(j,p){if(Array.isArray(j)){if(!Array.isArray(p)||j.length!==p.length)return!1;for(let v=0;v=1)return 1;const p=j*j,v=p*j;return 4*(j<.5?v:3*(j-p)+v-.75)}function xs(j,p,v,S){const E=new Mr(j,p,v,S);return function(R){return E.solve(R)}}const Ve=xs(.25,.1,.25,1);function it(j,p,v){return Math.min(v,Math.max(p,j))}function ft(j,p,v){return(v=it((v-j)/(p-j),0,1))*v*(3-2*v)}function kt(j,p,v){const S=v-p,E=((j-p)%S+S)%S+p;return E===p?v:E}function Ut(j,p,v){if(!j.length)return v(null,[]);let S=j.length;const E=new Array(j.length);let R=null;j.forEach((F,q)=>{p(F,(K,J)=>{K&&(R=K),E[q]=J,--S===0&&v(R,E)})})}let es=1;function Ms(){return es++}function bs(j){return j<=1?1:Math.pow(2,Math.ceil(Math.log2(j)))}function Zs(j,p){j.forEach(v=>{p[v]&&(p[v]=p[v].bind(p))})}function kn(j,p,v){const S={};for(const E in j)S[E]=p.call(this,j[E],E,j);return S}function gn(j,p,v){const S={};for(const E in j)p.call(this,j[E],E,j)&&(S[E]=j[E]);return S}function xr(j){return Array.isArray(j)?j.map(xr):typeof j=="object"&&j?kn(j,xr):j}function Kr(j,p){for(let v=0;v=0)return!0;return!1}const ca={};function Er(j){ca[j]||(typeof console<"u"&&console.warn(j),ca[j]=!0)}function qr(j,p,v){return(v.y-j.y)*(p.x-j.x)>(p.y-j.y)*(v.x-j.x)}function Xt(j){let p=0;for(let v,S,E=0,R=j.length,F=R-1;E@\,;\:\\"\/\[\]\?\=\{\}\x7F]+)(?:\=(?:([^\x00-\x20\(\)<>@\,;\:\\"\/\[\]\?\=\{\}\x7F]+)|(?:\"((?:[^"\\]|\\.)*)\")))?/g,(v,S,E,R)=>{const F=E||R;return p[S]=!F||F.toLowerCase(),""}),p["max-age"]){const v=parseInt(p["max-age"],10);isNaN(v)?delete p["max-age"]:p["max-age"]=v}return p}let ja,ea=null;function dr(j,p){return[j[4*p],j[4*p+1],j[4*p+2],j[4*p+3]]}function Wi(j,p,v,S){for(;p>1;j[E]>1;j[E]<=S?p=E+1:v=E}return p}function oa(j){return j>0?1/(1.001-j):1+j}function Ha(j){return j>0?1-1/(1.001-j):-j}function $i(j,p,v){return(j-p.min)*(v.max-v.min)/(p.max-p.min)+v.min}const Ta={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(!Ta.API_URL)return null;try{const j=new URL(Ta.API_URL);return j.hostname==="api.mapbox.cn"?"https://events.mapbox.cn/events/v2":j.hostname==="api.mapbox.com"?"https://events.mapbox.com/events/v2":null}catch{return null}},SESSION_PATH:"/map-sessions/v1",FEEDBACK_URL:"https://apps.mapbox.com/feedback",TILE_URL_VERSION:"v4",RASTER_URL_PREFIX:"raster/v1",RASTERARRAYS_URL_PREFIX:"rasterarrays/v1",REQUIRE_ACCESS_TOKEN:!0,ACCESS_TOKEN:null,DEFAULT_STYLE:"mapbox://styles/mapbox/standard",MAX_PARALLEL_IMAGE_REQUESTS:16,DRACO_URL:"/mapbox-gl-js/draco_decoder_gltf_v1.5.6.wasm",MESHOPT_URL:"/mapbox-gl-js/meshopt_base_v0.20.wasm",MESHOPT_SIMD_URL:"/mapbox-gl-js/meshopt_simd_v0.20.wasm",BUILDING_GEN_URL:"/mapbox-gl-js/building-gen/building_gen_v1.2.4.wasm",GLYPHS_URL:"mapbox://fonts/mapbox/{fontstack}/{range}.pbf",TILES3D_URL_PREFIX:"3dtiles/v1",TILE_PROVIDER_URLS:Object.assign(Object.create(null),{pmtiles:"/mapbox-gl-js/mapbox-gl-pmtiles-provider-v0.0.1.js"})};function Wn(){return new URL(Ta.DRACO_URL,Ta.API_URL).href}function Ra(){if(typeof WebAssembly!="object")throw new Error("WebAssembly not supported, cannot instantiate meshoptimizer");return new URL(function(){if(ja===void 0){if(typeof WebAssembly!="object")return!1;const j=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]);ja=WebAssembly.validate(j)}return ja}()?Ta.MESHOPT_SIMD_URL:Ta.MESHOPT_URL,Ta.API_URL).href}function mo(){return new URL(Ta.BUILDING_GEN_URL,Ta.API_URL).href}function Ho(j){return Ta.API_URL_REGEX.test(j)}function No(j){return Ta.API_SPRITE_REGEX.test(j)}let Go,Dd,Tu,Vm,Uc,Eu;function Ec(){return Go==null&&(Go=self.OffscreenCanvas&&new OffscreenCanvas(1,1).getContext("2d")&&typeof self.createImageBitmap=="function"),Go}const Gd={now:()=>Vm!==void 0?Vm:performance.now(),setNow(j){Vm=j},restoreNow(){Vm=void 0},frame(j){const p=requestAnimationFrame(j);return{cancel:()=>cancelAnimationFrame(p)}},getImageData(j,p=0){const{width:v,height:S}=j;Uc||(Uc=document.createElement("canvas"));const E=Uc.getContext("2d",{willReadFrequently:!0});if(!E)throw new Error("failed to create canvas 2d context");return(v>Uc.width||S>Uc.height)&&(Uc.width=v,Uc.height=S),E.clearRect(-p,-p,v+2*p,S+2*p),E.drawImage(j,0,0,v,S),E.getImageData(-p,-p,v+2*p,S+2*p)},resolveURL:j=>(Dd||(Dd=document.createElement("a")),Dd.href=j,Dd.href),get devicePixelRatio(){return window.devicePixelRatio},get prefersReducedMotion(){return!!window.matchMedia&&(Tu==null&&(Tu=window.matchMedia("(prefers-reduced-motion: reduce)")),Tu.matches)},hasCanvasFingerprintNoise(){if(Eu!==void 0)return Eu;if(!Ec())return Eu=!1,!1;const j=new OffscreenCanvas(85,1),p=j.getContext("2d",{willReadFrequently:!0});let v=0;for(let E=0;E0?`?${R}`:""}`}const Hm="mapbox-tiles";let ay=500,wf=50;const jf=["language","worldview","jobid"];let cu;function Sg(){try{return caches}catch{}}function Eo(){const j=Sg();j&&cu==null&&(cu=j.open(Hm))}let po=1/0;const Gm={supported:!1,testSupport:function(j){!wh&&Cg&&(Bl?bd(j):hm=j)}};let hm,Cg,wh=!1,Bl=!1;const Wm=typeof self<"u"?self:{};function bd(j){const p=j.createTexture();j.bindTexture(j.TEXTURE_2D,p);try{if(j.texImage2D(j.TEXTURE_2D,0,j.RGBA,j.RGBA,j.UNSIGNED_BYTE,Cg),j.isContextLost())return;Gm.supported=!0}catch{}j.deleteTexture(p),wh=!0}Wm.document&&(Cg=Wm.document.createElement("img"),Cg.onload=function(){hm&&bd(hm),hm=null,Bl=!0},Cg.onerror=function(){wh=!0,hm=null},Cg.src="data:image/webp;base64,UklGRh4AAABXRUJQVlA4TBEAAAAvAQAAAAfQ//73v/+BiOh/AAA=");const n0={Unknown:"Unknown",Style:"Style",Source:"Source",Tile:"Tile",Glyphs:"Glyphs",SpriteImage:"SpriteImage",SpriteJSON:"SpriteJSON",Iconset:"Iconset",Image:"Image",Model:"Model"};Object.freeze(n0);class kb extends Error{constructor(p,v,S){v===401&&Ho(S)&&(p+=": you may have provided an invalid Mapbox access token. See https://docs.mapbox.com/api/overview/#access-tokens-and-token-scopes"),super(p),this.status=v,this.url=S}toString(){return`${this.name}: ${this.message} (${this.status}): ${this.url}`}}function Km(j){return typeof j=="object"&&j!==null&&"status"in j&&j.status===404}const _i=Jr()?()=>self.worker.referrer:()=>(location.protocol==="blob:"?parent:self).location.href,Ym=function(j,p){return/^file:/.test(v=j.url)||/^file:/.test(_i())&&!/^\w+:/.test(v)?function(S,E){const R=new XMLHttpRequest;R.open(S.method||"GET",S.url,!0),S.type==="arrayBuffer"&&(R.responseType="arraybuffer");for(const F in S.headers)R.setRequestHeader(F,S.headers[F]);return S.type==="json"&&(R.responseType="text",R.setRequestHeader("Accept","application/json")),R.withCredentials=S.credentials==="include",R.onerror=()=>{E(new Error(R.statusText))},R.onload=()=>{if((R.status>=200&&R.status<300||R.status===0)&&R.response!==null){let F=R.response;if(S.type==="json")try{F=JSON.parse(R.response)}catch(K){return E(K)}const q=new Headers;R.getAllResponseHeaders().trim().split(/[\r\n]+/).forEach(K=>{const J=K.split(": "),le=J.shift(),fe=J.join(": ");q.append(le,fe)}),E(null,F,q)}else E(new kb(R.statusText,R.status,S.url))},R.send(S.body),{cancel:()=>R.abort()}}(j,p):function(S,E){const R=new AbortController,F=new Request(S.url,{method:S.method||"GET",body:S.body,credentials:S.credentials,headers:S.headers,referrer:_i(),referrerPolicy:S.referrerPolicy,signal:R.signal});let q=!1,K=!1;const J=(le=F.url).indexOf("sku=")>0&&Ho(le);var le;S.type==="json"&&F.headers.set("Accept","application/json");const fe=(Te,Pe,Ue)=>{if(K)return;if(Te&&Te.message!=="SecurityError"&&Er(Te.toString()),Pe&&Ue)return ye(Pe);const Qe=Date.now();fetch(F).then(at=>{if(at.ok){const pt=J?at.clone():null;return ye(at,pt,Qe)}return E(new kb(at.statusText,at.status,S.url))}).catch(at=>{at.name!=="AbortError"&&E(new Error(`${at.message} ${S.url}`))})},ye=(Te,Pe,Ue)=>{(S.type==="arrayBuffer"?Te.arrayBuffer():S.type==="json"?Te.json():Te.text()).then(Qe=>{K||(Pe&&Ue&&function(at,pt,dt){if(Eo(),cu==null)return;const wt=Or(pt.headers.get("cache-control")||"");if(wt["no-store"])return;const Tt={status:pt.status,statusText:pt.statusText,headers:new Headers};pt.headers.forEach((rs,is)=>Tt.headers.set(is,rs)),wt["max-age"]&&Tt.headers.set("Expires",new Date(dt+1e3*wt["max-age"]).toUTCString());const Lt=Tt.headers.get("expires");if(!Lt||new Date(Lt).getTime()-dt<42e4)return;let fs=Nb(at.url,{persistentParams:jf});if(pt.status===206){const rs=at.headers.get("Range");if(!rs)return;Tt.status=200,fs=s0(fs,{range:rs})}const Jt=new Response((ps=pt.status)!==200&&ps!==404&&[101,103,204,205,304].includes(ps)?null:pt.body,Tt);var ps;Eo(),cu!=null&&cu.then(rs=>rs.put(fs,Jt)).catch(rs=>Er(rs.message))}(F,Pe,Ue),q=!0,E(null,Qe,Te.headers))}).catch(Qe=>{K||E(new Error(Qe.message))})};return J?function(Te,Pe){if(Eo(),cu==null)return Pe(null);cu.then(Ue=>{let Qe=Nb(Te.url,{persistentParams:jf});const at=Te.headers.get("Range");at&&(Qe=s0(Qe,{range:at})),Ue.match(Qe).then(pt=>{const dt=function(wt){if(!wt)return!1;const Tt=new Date(wt.headers.get("expires")||0),Lt=Or(wt.headers.get("cache-control")||"");return Number(Tt)>Date.now()&&!Lt["no-cache"]}(pt);Ue.delete(Qe).catch(Pe),dt&&Ue.put(Qe,pt.clone()).catch(Pe),Pe(null,pt,dt)}).catch(Pe)}).catch(Pe)}(F,fe):fe(null,null),{cancel:()=>{K=!0,q||R.abort()}}}(j,p);var v},iy=function(j,p){return Ym(Object.assign(j,{type:"arrayBuffer"}),p)};function qh(j){const p=document.createElement("a");return p.href=j,p.protocol===location.protocol&&p.host===location.host}let Fp,Zm;Fp=[],Zm=0;const mm=function(j,p){if(Gm.supported&&(j.headers||(j.headers={}),j.headers.accept="image/webp,*/*"),Zm>=Ta.MAX_PARALLEL_IMAGE_REQUESTS){const R={requestParameters:j,callback:p,cancelled:!1,cancel(){this.cancelled=!0}};return Fp.push(R),R}Zm++;let v=!1;const S=()=>{if(!v)for(v=!0,Zm--;Fp.length&&Zm{S(),R?p(R):F&&function(K,J){const le=new Blob([new Uint8Array(K)],{type:"image/png"});createImageBitmap(le).then(fe=>{J(null,fe)}).catch(fe=>{J(new Error(`Could not load image because of ${fe.message}. Please make sure to use a supported image type such as PNG or JPEG. Note that SVGs are not supported.`))})}(F,(K,J)=>p(K,J,q))});return{cancel:()=>{E.cancel(),S()}}};var Qf,mx,Xm,Vh={exports:{}},zp={exports:{}},Ag={exports:{}},Jy=function(){if(Xm)return Vh.exports;Xm=1;var j=(Qf||(Qf=1,zp.exports=function(v,S){var E,R,F,q,K,J,le,fe;for(R=v.length-(E=3&v.length),F=S,K=3432918353,J=461845907,fe=0;fe>>16)*K&65535)<<16)&4294967295)<<15|le>>>17))*J+(((le>>>16)*J&65535)<<16)&4294967295)<<13|F>>>19))+((5*(F>>>16)&65535)<<16)&4294967295))+(((q>>>16)+58964&65535)<<16);switch(le=0,E){case 3:le^=(255&v.charCodeAt(fe+2))<<16;case 2:le^=(255&v.charCodeAt(fe+1))<<8;case 1:F^=le=(65535&(le=(le=(65535&(le^=255&v.charCodeAt(fe)))*K+(((le>>>16)*K&65535)<<16)&4294967295)<<15|le>>>17))*J+(((le>>>16)*J&65535)<<16)&4294967295}return F^=v.length,F=2246822507*(65535&(F^=F>>>16))+((2246822507*(F>>>16)&65535)<<16)&4294967295,F=3266489909*(65535&(F^=F>>>13))+((3266489909*(F>>>16)&65535)<<16)&4294967295,(F^=F>>>16)>>>0}),zp.exports),p=(mx||(mx=1,Ag.exports=function(v,S){for(var E,R=v.length,F=S^R,q=0;R>=4;)E=1540483477*(65535&(E=255&v.charCodeAt(q)|(255&v.charCodeAt(++q))<<8|(255&v.charCodeAt(++q))<<16|(255&v.charCodeAt(++q))<<24))+((1540483477*(E>>>16)&65535)<<16),F=1540483477*(65535&F)+((1540483477*(F>>>16)&65535)<<16)^(E=1540483477*(65535&(E^=E>>>24))+((1540483477*(E>>>16)&65535)<<16)),R-=4,++q;switch(R){case 3:F^=(255&v.charCodeAt(q+2))<<16;case 2:F^=(255&v.charCodeAt(q+1))<<8;case 1:F=1540483477*(65535&(F^=255&v.charCodeAt(q)))+((1540483477*(F>>>16)&65535)<<16)}return F=1540483477*(65535&(F^=F>>>13))+((1540483477*(F>>>16)&65535)<<16),(F^=F>>>15)>>>0}),Ag.exports);return Vh.exports=j,Vh.exports.murmur3=j,Vh.exports.murmur2=p,Vh.exports}(),Jc=Jn(Jy);class Nc{constructor(p,...v){Object.assign(this,v[0]||{}),this.type=p}}class Qm extends Nc{constructor(p,v={}){super("error",Object.assign({error:p},v))}}function Rd(j,p,v){v[j]&&v[j].indexOf(p)!==-1||(v[j]=v[j]||[],v[j].push(p))}function Jm(j,p,v){if(v&&v[j]){const S=v[j].indexOf(p);S!==-1&&v[j].splice(S,1)}}class Hh{on(p,v){return this._listeners=this._listeners||{},Rd(p,v,this._listeners),this}off(p,v){return Jm(p,v,this._listeners),Jm(p,v,this._oneTimeListeners),this}once(p,v){return v?(this._oneTimeListeners=this._oneTimeListeners||{},Rd(p,v,this._oneTimeListeners),this):new Promise(S=>{this.once(p,S)})}fire(p,v){const S=typeof p=="string"?new Nc(p,v):p,E=S.type;if(this.listens(E)){S.target=this;const R=this._listeners&&this._listeners[E]?this._listeners[E].slice():[];for(const K of R)K.call(this,S);const F=this._oneTimeListeners&&this._oneTimeListeners[E]?this._oneTimeListeners[E].slice():[];for(const K of F)Jm(E,K,this._oneTimeListeners),K.call(this,S);const q=this._eventedParent;if(q){const K=typeof this._eventedParentData=="function"?this._eventedParentData():this._eventedParentData;Object.assign(S,K),q.fire(S)}}else S instanceof Qm&&console.error(S.error);return this}listens(p){return!!(this._listeners&&this._listeners[p]&&this._listeners[p].length>0||this._oneTimeListeners&&this._oneTimeListeners[p]&&this._oneTimeListeners[p].length>0||this._eventedParent&&this._eventedParent.listens(p))}setEventedParent(p,v){return this._eventedParent=p,this._eventedParentData=v,this}}class Wt{constructor(p){typeof p=="string"?this.name=p:(this.name=p.name,this.iconsetId=p.iconsetId)}static from(p){return new Wt(p)}static toString(p){return p.iconsetId?`${p.name}${p.iconsetId}`:p.name}static parse(p){const[v,S]=p.split("");return new Wt({name:v,iconsetId:S})}static isEqual(p,v){return p.name===v.name&&p.iconsetId===v.iconsetId}toString(){return Wt.toString(this)}serialize(){return{name:this.name,iconsetId:this.iconsetId}}}var ze,xt={},ss=function(){if(ze)return xt;ze=1;var j={transparent:[0,0,0,0],aliceblue:[240,248,255,1],antiquewhite:[250,235,215,1],aqua:[0,255,255,1],aquamarine:[127,255,212,1],azure:[240,255,255,1],beige:[245,245,220,1],bisque:[255,228,196,1],black:[0,0,0,1],blanchedalmond:[255,235,205,1],blue:[0,0,255,1],blueviolet:[138,43,226,1],brown:[165,42,42,1],burlywood:[222,184,135,1],cadetblue:[95,158,160,1],chartreuse:[127,255,0,1],chocolate:[210,105,30,1],coral:[255,127,80,1],cornflowerblue:[100,149,237,1],cornsilk:[255,248,220,1],crimson:[220,20,60,1],cyan:[0,255,255,1],darkblue:[0,0,139,1],darkcyan:[0,139,139,1],darkgoldenrod:[184,134,11,1],darkgray:[169,169,169,1],darkgreen:[0,100,0,1],darkgrey:[169,169,169,1],darkkhaki:[189,183,107,1],darkmagenta:[139,0,139,1],darkolivegreen:[85,107,47,1],darkorange:[255,140,0,1],darkorchid:[153,50,204,1],darkred:[139,0,0,1],darksalmon:[233,150,122,1],darkseagreen:[143,188,143,1],darkslateblue:[72,61,139,1],darkslategray:[47,79,79,1],darkslategrey:[47,79,79,1],darkturquoise:[0,206,209,1],darkviolet:[148,0,211,1],deeppink:[255,20,147,1],deepskyblue:[0,191,255,1],dimgray:[105,105,105,1],dimgrey:[105,105,105,1],dodgerblue:[30,144,255,1],firebrick:[178,34,34,1],floralwhite:[255,250,240,1],forestgreen:[34,139,34,1],fuchsia:[255,0,255,1],gainsboro:[220,220,220,1],ghostwhite:[248,248,255,1],gold:[255,215,0,1],goldenrod:[218,165,32,1],gray:[128,128,128,1],green:[0,128,0,1],greenyellow:[173,255,47,1],grey:[128,128,128,1],honeydew:[240,255,240,1],hotpink:[255,105,180,1],indianred:[205,92,92,1],indigo:[75,0,130,1],ivory:[255,255,240,1],khaki:[240,230,140,1],lavender:[230,230,250,1],lavenderblush:[255,240,245,1],lawngreen:[124,252,0,1],lemonchiffon:[255,250,205,1],lightblue:[173,216,230,1],lightcoral:[240,128,128,1],lightcyan:[224,255,255,1],lightgoldenrodyellow:[250,250,210,1],lightgray:[211,211,211,1],lightgreen:[144,238,144,1],lightgrey:[211,211,211,1],lightpink:[255,182,193,1],lightsalmon:[255,160,122,1],lightseagreen:[32,178,170,1],lightskyblue:[135,206,250,1],lightslategray:[119,136,153,1],lightslategrey:[119,136,153,1],lightsteelblue:[176,196,222,1],lightyellow:[255,255,224,1],lime:[0,255,0,1],limegreen:[50,205,50,1],linen:[250,240,230,1],magenta:[255,0,255,1],maroon:[128,0,0,1],mediumaquamarine:[102,205,170,1],mediumblue:[0,0,205,1],mediumorchid:[186,85,211,1],mediumpurple:[147,112,219,1],mediumseagreen:[60,179,113,1],mediumslateblue:[123,104,238,1],mediumspringgreen:[0,250,154,1],mediumturquoise:[72,209,204,1],mediumvioletred:[199,21,133,1],midnightblue:[25,25,112,1],mintcream:[245,255,250,1],mistyrose:[255,228,225,1],moccasin:[255,228,181,1],navajowhite:[255,222,173,1],navy:[0,0,128,1],oldlace:[253,245,230,1],olive:[128,128,0,1],olivedrab:[107,142,35,1],orange:[255,165,0,1],orangered:[255,69,0,1],orchid:[218,112,214,1],palegoldenrod:[238,232,170,1],palegreen:[152,251,152,1],paleturquoise:[175,238,238,1],palevioletred:[219,112,147,1],papayawhip:[255,239,213,1],peachpuff:[255,218,185,1],peru:[205,133,63,1],pink:[255,192,203,1],plum:[221,160,221,1],powderblue:[176,224,230,1],purple:[128,0,128,1],rebeccapurple:[102,51,153,1],red:[255,0,0,1],rosybrown:[188,143,143,1],royalblue:[65,105,225,1],saddlebrown:[139,69,19,1],salmon:[250,128,114,1],sandybrown:[244,164,96,1],seagreen:[46,139,87,1],seashell:[255,245,238,1],sienna:[160,82,45,1],silver:[192,192,192,1],skyblue:[135,206,235,1],slateblue:[106,90,205,1],slategray:[112,128,144,1],slategrey:[112,128,144,1],snow:[255,250,250,1],springgreen:[0,255,127,1],steelblue:[70,130,180,1],tan:[210,180,140,1],teal:[0,128,128,1],thistle:[216,191,216,1],tomato:[255,99,71,1],turquoise:[64,224,208,1],violet:[238,130,238,1],wheat:[245,222,179,1],white:[255,255,255,1],whitesmoke:[245,245,245,1],yellow:[255,255,0,1],yellowgreen:[154,205,50,1]};function p(R){return(R=Math.round(R))<0?0:R>255?255:R}function v(R){return p(R[R.length-1]==="%"?parseFloat(R)/100*255:parseInt(R))}function S(R){return(F=R[R.length-1]==="%"?parseFloat(R)/100:parseFloat(R))<0?0:F>1?1:F;var F}function E(R,F,q){return q<0?q+=1:q>1&&(q-=1),6*q<1?R+(F-R)*q*6:2*q<1?F:3*q<2?R+(F-R)*(2/3-q)*6:R}try{xt.parseCSSColor=function(R){var F,q=R.replace(/ /g,"").toLowerCase();if(q in j)return j[q].slice();if(q[0]==="#")return q.length===4?(F=parseInt(q.substr(1),16))>=0&&F<=4095?[(3840&F)>>4|(3840&F)>>8,240&F|(240&F)>>4,15&F|(15&F)<<4,1]:null:q.length===7&&(F=parseInt(q.substr(1),16))>=0&&F<=16777215?[(16711680&F)>>16,(65280&F)>>8,255&F,1]:null;var K=q.indexOf("("),J=q.indexOf(")");if(K!==-1&&J+1===q.length){var le=q.substr(0,K),fe=q.substr(K+1,J-(K+1)).split(","),ye=1;switch(le){case"rgba":if(fe.length!==4)return null;ye=S(fe.pop());case"rgb":return fe.length!==3?null:[v(fe[0]),v(fe[1]),v(fe[2]),ye];case"hsla":if(fe.length!==4)return null;ye=S(fe.pop());case"hsl":if(fe.length!==3)return null;var Te=(parseFloat(fe[0])%360+360)%360/360,Pe=S(fe[1]),Ue=S(fe[2]),Qe=Ue<=.5?Ue*(Pe+1):Ue+Pe-Ue*Pe,at=2*Ue-Qe;return[p(255*E(at,Qe,Te+1/3)),p(255*E(at,Qe,Te)),p(255*E(at,Qe,Te-1/3)),ye];default:return null}}return null}}catch{}return xt}();class cs{constructor(p,v,S,E=1){this.r=p,this.g=v,this.b=S,this.a=E}static parse(p){if(!p)return;if(p instanceof cs)return p;if(typeof p!="string")return;const v=ss.parseCSSColor(p);return v?new cs(v[0]/255,v[1]/255,v[2]/255,v[3]):void 0}toString(){const[p,v,S,E]=[this.r,this.g,this.b,this.a];return`rgba(${Math.round(255*p)},${Math.round(255*v)},${Math.round(255*S)},${E})`}toNonPremultipliedRenderColor(p){const{r:v,g:S,b:E,a:R}=this;return new Mn(p,v,S,E,R)}toPremultipliedRenderColor(p){const{r:v,g:S,b:E,a:R}=this;return new Xn(p,v*R,S*R,E*R,R)}clone(){return new cs(this.r,this.g,this.b,this.a)}}class tn{constructor(p,v,S,E,R,F=!1){if(this.premultiplied=!1,this.premultiplied=F,p){const q=p.image.height,K=q*q;this.premultiplied?(v=R===0?0:v/R*(q-1),S=R===0?0:S/R*(q-1),E=R===0?0:E/R*(q-1)):(v*=q-1,S*=q-1,E*=q-1),v=Math.max(0,Math.min(q-1,v)),S=Math.max(0,Math.min(q-1,S)),E=Math.max(0,Math.min(q-1,E));const J=Math.floor(v),le=Math.floor(S),fe=Math.floor(E),ye=Math.ceil(v),Te=Math.ceil(S),Pe=Math.ceil(E),Ue=v-J,Qe=S-le,at=E-fe,pt=p.image.data,dt=4*(J+le*K+fe*q),wt=4*(J+le*K+Pe*q),Tt=4*(J+Te*K+fe*q),Lt=4*(J+Te*K+Pe*q),fs=4*(ye+le*K+fe*q),Jt=4*(ye+le*K+Pe*q),ps=4*(ye+Te*K+fe*q),rs=4*(ye+Te*K+Pe*q);this.r=mr(mr(mr(pt[dt],pt[wt],at),mr(pt[Tt],pt[Lt],at),Qe),mr(mr(pt[fs],pt[Jt],at),mr(pt[ps],pt[rs],at),Qe),Ue)/255*(this.premultiplied?R:1),this.g=mr(mr(mr(pt[dt+1],pt[wt+1],at),mr(pt[Tt+1],pt[Lt+1],at),Qe),mr(mr(pt[fs+1],pt[Jt+1],at),mr(pt[ps+1],pt[rs+1],at),Qe),Ue)/255*(this.premultiplied?R:1),this.b=mr(mr(mr(pt[dt+2],pt[wt+2],at),mr(pt[Tt+2],pt[Lt+2],at),Qe),mr(mr(pt[fs+2],pt[Jt+2],at),mr(pt[ps+2],pt[rs+2],at),Qe),Ue)/255*(this.premultiplied?R:1),this.a=R}else this.r=v,this.g=S,this.b=E,this.a=R}toArray(){const{r:p,g:v,b:S,a:E}=this;return[255*p,255*v,255*S,E]}toHslaArray(){let{r:p,g:v,b:S,a:E}=this;if(this.premultiplied){if(E===0)return[0,0,0,0];const Pe=1/E;p*=Pe,v*=Pe,S*=Pe}const R=Math.min(Math.max(p,0),1),F=Math.min(Math.max(v,0),1),q=Math.min(Math.max(S,0),1),K=Math.min(R,F,q),J=Math.max(R,F,q),le=J-K,fe=.5*(K+J);if(le===0)return[0,0,100*fe,E];const ye=fe>.5?le/(2-J-K):le/(J+K);let Te;switch(J){case R:Te=60*((F-q)/le+(Fmr(S,p[E],v))}cs.black=new cs(0,0,0,1),cs.white=new cs(1,1,1,1),cs.transparent=new cs(0,0,0,0),cs.red=new cs(1,0,0,1),cs.blue=new cs(0,0,1,1);var Ki=Object.freeze({__proto__:null,array:Ba,color:function(j,p,v){return new cs(mr(j.r,p.r,v),mr(j.g,p.g,v),mr(j.b,p.b,v),mr(j.a,p.a,v))},number:mr});class Ui extends Error{constructor(p,v){super(v),this.message=v,this.key=p}}class tl{constructor(p,v=[]){this.parent=p,this.bindings={};for(const[S,E]of v)this.bindings[S]=E}concat(p){return new tl(this,p)}get(p){if(this.bindings[p])return this.bindings[p];if(this.parent)return this.parent.get(p);throw new Error(`${p} not found in scope.`)}has(p){return!!this.bindings[p]||!!this.parent&&this.parent.has(p)}}const Mc={kind:"null"},Lr={kind:"number"},Za={kind:"string"},ci={kind:"boolean"},jl={kind:"color"},xc={kind:"object"},qi={kind:"value"},Gh={kind:"collator"},px={kind:"formatted"},fx={kind:"resolvedImage"};function du(j,p){return{kind:"array",itemType:j,N:p}}function $l(j){if(j.kind==="array"){const p=$l(j.itemType);return typeof j.N=="number"?`array<${p}, ${j.N}>`:j.itemType.kind==="value"?"array":`array<${p}>`}return j.kind}const c1=[Mc,Lr,Za,ci,jl,px,xc,du(qi),fx];function Tg(j,p){if(p.kind==="error")return null;if(j.kind==="array"){if(p.kind==="array"&&(p.N===0&&p.itemType.kind==="value"||!Tg(j.itemType,p.itemType))&&(typeof j.N!="number"||j.N===p.N))return null}else{if(j.kind===p.kind)return null;if(j.kind==="value"){for(const v of c1)if(!Tg(v,p))return null}}return`Expected ${$l(j)} but found ${$l(p)} instead.`}function r0(j,p){return p.some(v=>v.kind===j.kind)}function Od(j,p){return p.some(v=>v==="null"?j===null:v==="array"?Array.isArray(j):v==="object"?j&&!Array.isArray(j)&&typeof j=="object":v===typeof j)}function ep(j,p){return j.kind==="array"&&p.kind==="array"?j.N===p.N&&ep(j.itemType,p.itemType):j.kind===p.kind}class a0{constructor(p,v,S){this.sensitivity=p?v?"variant":"case":v?"accent":"base",this.locale=S,this.collator=new Intl.Collator(this.locale?this.locale:[],{sensitivity:this.sensitivity,usage:"search"})}compare(p,v){return this.collator.compare(p,v)}resolvedLocale(){return new Intl.Collator(this.locale?this.locale:[]).resolvedOptions().locale}}class oy{constructor(p,v,S,E,R){this.text=p.normalize?p.normalize():p,this.image=v,this.scale=S,this.fontStack=E,this.textColor=R}}class ed{constructor(p){this.sections=p}static fromString(p){return new ed([new oy(p,null,null,null,null)])}isEmpty(){return this.sections.length===0||!this.sections.some(p=>p.text.length!==0||!!p.image&&p.image.hasPrimary())}static factory(p){return p instanceof ed?p:ed.fromString(p)}toString(){return this.sections.length===0?"":this.sections.map(p=>p.text).join("")}serialize(){const p=["format"];for(const v of this.sections){if(v.image){const E=v.image.getPrimary().id.toString();p.push(["image",E]);continue}p.push(v.text);const S={};v.fontStack&&(S["text-font"]=["literal",v.fontStack.split(",")]),v.scale&&(S["font-scale"]=v.scale),v.textColor&&(S["text-color"]=["rgba"].concat(v.textColor.toNonPremultipliedRenderColor(null).toArray())),p.push(S)}return p}}class ud{constructor(p,v={}){this.id=Wt.from(p),this.params=v.params,this.sx=v.sx||1,this.sy=v.sy||1}toString(){return JSON.stringify(this)}static parse(p){let v,S,E,R;try{({id:v,params:S,sx:E,sy:R}=JSON.parse(p)||{})}catch{return null}return v?new ud(v,{params:S,sx:E,sy:R}):null}scaleSelf(p,v=p){return this.sx*=p,this.sy*=v,this}}class Mu{constructor(p,v,S,E,R=!1){this.primaryId=Wt.from(p),this.primaryOptions=v,S&&(this.secondaryId=Wt.from(S)),this.secondaryOptions=E,this.available=R}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(p){return typeof p=="string"?Mu.build({name:p}):p}static build(p,v,S,E){return!p||typeof p=="object"&&!("name"in p)?null:new Mu(p,S,v,E)}}function pm(j,p,v,S){return typeof j=="number"&&j>=0&&j<=255&&typeof p=="number"&&p>=0&&p<=255&&typeof v=="number"&&v>=0&&v<=255?S===void 0||typeof S=="number"&&S>=0&&S<=1?null:`Invalid rgba value [${[j,p,v,S].join(", ")}]: 'a' must be between 0 and 1.`:`Invalid rgba value [${(typeof S=="number"?[j,p,v,S]:[j,p,v]).join(", ")}]: 'r', 'g', and 'b' must be between 0 and 255.`}function Nf(j){if(j===null||typeof j=="string"||typeof j=="boolean"||typeof j=="number"||j instanceof cs||j instanceof a0||j instanceof ed||j instanceof Mu)return!0;if(Array.isArray(j)){for(const p of j)if(!Nf(p))return!1;return!0}if(typeof j=="object"){for(const p in j)if(!Nf(j[p]))return!1;return!0}return!1}function il(j){if(j===null)return Mc;if(typeof j=="string")return Za;if(typeof j=="boolean")return ci;if(typeof j=="number")return Lr;if(j instanceof cs)return jl;if(j instanceof a0)return Gh;if(j instanceof ed)return px;if(j instanceof Mu)return fx;if(Array.isArray(j)){const p=j.length;let v;for(const S of j){const E=il(S);if(v){if(v===E)continue;v=qi;break}v=E}return du(v||qi,p)}return xc}function wa(j){const p=typeof j;return j===null?"":p==="string"||p==="number"||p==="boolean"?String(j):j instanceof ed||j instanceof Mu||j instanceof cs?j.toString():JSON.stringify(j)}class Ir{constructor(p,v){this.type=p,this.value=v}static parse(p,v){if(p.length!==2)return v.error(`'literal' expression requires exactly one argument, but found ${p.length-1} instead.`);if(!Nf(p[1]))return v.error("invalid value");const S=p[1];let E=il(S);const R=v.expectedType;return E.kind!=="array"||E.N!==0||!R||R.kind!=="array"||typeof R.N=="number"&&R.N!==0||(E=R),new Ir(E,S)}evaluate(){return this.value}eachChild(){}outputDefined(){return!0}serialize(){return this.type.kind==="array"||this.type.kind==="object"?["literal",this.value]:this.value instanceof cs?["rgba"].concat(this.value.toNonPremultipliedRenderColor(null).toArray()):this.value instanceof ed?this.value.serialize():this.value}}class Pl{constructor(p){this.name="ExpressionEvaluationError",this.message=p}toJSON(){return this.message}}const Na={string:Za,number:Lr,boolean:ci,object:xc};class fm{constructor(p,v){this.type=p,this.args=v}static parse(p,v){if(p.length<2)return v.error("Expected at least one argument.");let S,E=1;const R=p[0];if(R==="array"){let q,K;if(p.length>2){const J=p[1];if(typeof J!="string"||!(J in Na)||J==="object")return v.error('The item type argument of "array" must be one of string, number, boolean',1);q=Na[J],E++}else q=qi;if(p.length>3){if(p[2]!==null&&(typeof p[2]!="number"||p[2]<0||p[2]!==Math.floor(p[2])))return v.error('The length argument to "array" must be a positive integer literal',2);K=p[2],E++}S=du(q,K)}else S=Na[R];const F=[];for(;Ep.outputDefined())}serialize(){const p=this.type,v=[p.kind];if(p.kind==="array"){const S=p.itemType;if(S.kind==="string"||S.kind==="number"||S.kind==="boolean"){v.push(S.kind);const E=p.N;(typeof E=="number"||this.args.length>1)&&v.push(E)}}return v.concat(this.args.map(S=>S.serialize()))}}class td{constructor(p){this.type=px,this.sections=p}static parse(p,v){if(p.length<2)return v.error("Expected at least one argument.");const S=p[1];if(!Array.isArray(S)&&typeof S=="object")return v.error("First argument must be an image or text section.");const E=[];let R=!1;for(let F=1;F<=p.length-1;++F){const q=p[F];if(R&&typeof q=="object"&&!Array.isArray(q)){R=!1;let K=null;if(q["font-scale"]&&(K=v.parseObjectValue(q["font-scale"],F,"font-scale",Lr),!K))return null;let J=null;if(q["text-font"]&&(J=v.parseObjectValue(q["text-font"],F,"text-font",du(Za)),!J))return null;let le=null;if(q["text-color"]&&(le=v.parseObjectValue(q["text-color"],F,"text-color",jl),!le))return null;const fe=E[E.length-1];fe.scale=K,fe.font=J,fe.textColor=le}else{const K=v.parse(p[F],F,qi);if(!K)return null;const J=K.type.kind;if(J!=="string"&&J!=="value"&&J!=="null"&&J!=="resolvedImage")return v.error("Formatted text type must be 'string', 'value', 'image' or 'null'.");R=!0,E.push({content:K,scale:null,font:null,textColor:null})}}return new td(E)}evaluate(p){return new ed(this.sections.map(v=>{const S=v.content.evaluate(p);return ep(il(S),fx)?new oy("",S,null,null,null):new oy(wa(S),null,v.scale?v.scale.evaluate(p):null,v.font?v.font.evaluate(p).join(","):null,v.textColor?v.textColor.evaluate(p):null)}))}eachChild(p){for(const v of this.sections)p(v.content),v.scale&&p(v.scale),v.font&&p(v.font),v.textColor&&p(v.textColor)}outputDefined(){return!1}serialize(){const p=["format"];for(const v of this.sections){p.push(v.content.serialize());const S={};v.scale&&(S["font-scale"]=v.scale.serialize()),v.font&&(S["text-font"]=v.font.serialize()),v.textColor&&(S["text-color"]=v.textColor.serialize()),p.push(S)}return p}}class ra{constructor(p,v,S,E){this._imageWarnHistory={},this.type=fx,this.namePrimary=p,this.nameSecondary=v,S&&(this.paramsPrimary=S.params,this.iconsetIdPrimary=S.iconset?S.iconset.id:void 0),E&&(this.paramsSecondary=E.params,this.iconsetIdSecondary=E.iconset?E.iconset.id:void 0)}static parse(p,v){if(p.length<2)return v.error("Expected two or more arguments.");let S=1;const E=[];function R(){if(SWt.isEqual(F,R)),E.available){const F=E.getSecondary()?E.getSecondary().id:null;F&&(E.available=p.availableImages.some(q=>Wt.isEqual(q,F)))}}return E}eachChild(p){if(p(this.namePrimary),this.paramsPrimary)for(const v in this.paramsPrimary)this.paramsPrimary[v]&&p(this.paramsPrimary[v]);if(this.nameSecondary&&(p(this.nameSecondary),this.paramsSecondary))for(const v in this.paramsSecondary)this.paramsSecondary[v]&&p(this.paramsSecondary[v])}outputDefined(){return!1}serializeOptions(p,v){const S={};if(v&&(S.iconset={id:v}),p){S.params={};for(const E in p)p[E]&&(S.params[E]=p[E].serialize())}return Object.keys(S).length>0?S:void 0}serialize(){const p=["image",this.namePrimary.serialize()];if(this.paramsPrimary||this.iconsetIdPrimary){const v=this.serializeOptions(this.paramsPrimary,this.iconsetIdPrimary);v&&p.push(v)}if(this.nameSecondary&&(p.push(this.nameSecondary.serialize()),this.paramsSecondary||this.iconsetIdSecondary)){const v=this.serializeOptions(this.paramsSecondary,this.iconsetIdSecondary);v&&p.push(v)}return p}}function Eg(j){return Jf(j)?"string":i0(j)?"number":kf(j)?"boolean":Array.isArray(j)?"array":j===null?"null":gx(j)?"object":typeof j}function gx(j){return j!=null&&!Array.isArray(j)&&typeof j!="function"&&!(j instanceof String||j instanceof Number||j instanceof Boolean)&&typeof j=="object"}function Jf(j){return typeof j=="string"||j instanceof String}function i0(j){return typeof j=="number"||j instanceof Number}function kf(j){return typeof j=="boolean"||j instanceof Boolean}const Lc={"to-boolean":ci,"to-color":jl,"to-number":Lr,"to-string":Za};class tp{constructor(p,v){this.type=p,this.args=v}static parse(p,v){if(p.length<2)return v.error("Expected at least one argument.");const S=p[0],E=[];let R=Mc;if(S==="to-array"){if(!Array.isArray(p[1]))return null;const F=p[1].length;if(v.expectedType){if(v.expectedType.kind!=="array")return v.error(`Expected ${v.expectedType.kind} but found array.`);R=du(v.expectedType.itemType,F)}else{if(!(F>0&&Nf(p[1][0])))return null;R=du(il(p[1][0]),F)}for(let q=0;q4?`Invalid rbga value ${JSON.stringify(v)}: expected an array containing either three or four numeric values.`:pm(v[0],v[1],v[2],v[3]),!S))return new cs(v[0]/255,v[1]/255,v[2]/255,v[3])}throw new Pl(S||`Could not parse color from value '${typeof v=="string"?v:String(JSON.stringify(v))}'`)}if(this.type.kind==="number"){let v=null;for(const S of this.args){if(v=S.evaluate(p),v===null)return 0;const E=Number(v);if(!isNaN(E))return E}throw new Pl(`Could not convert ${JSON.stringify(v)} to number.`)}return this.type.kind==="formatted"?ed.fromString(wa(this.args[0].evaluate(p))):this.type.kind==="resolvedImage"?Mu.build(wa(this.args[0].evaluate(p))):this.type.kind==="array"?this.args.map(v=>v.evaluate(p)):wa(this.args[0].evaluate(p))}eachChild(p){this.args.forEach(p)}outputDefined(){return this.args.every(p=>p.outputDefined())}serialize(){if(this.type.kind==="formatted")return new td([{content:this.args[0],scale:null,font:null,textColor:null}]).serialize();if(this.type.kind==="resolvedImage")return new ra(this.args[0]).serialize();const p=this.type.kind==="array"?[]:[`to-${this.type.kind}`];return this.eachChild(v=>{p.push(v.serialize())}),p}}const ih=["Unknown","Point","LineString","Polygon"];class uu{constructor(p,v,S){this.globals=null,this.feature=null,this.featureState=null,this.formattedSection=null,this._parseColorCache={},this.availableImages=null,this.canonical=null,this.featureTileCoord=null,this.featureDistanceData=null,this.scope=p,this.options=v,this.iconImageUseTheme=S}id(){return this.feature&&this.feature.id!==void 0?this.feature.id:null}geometryType(){return this.feature?typeof this.feature.type=="number"?ih[this.feature.type]:this.feature.type:null}geometry(){return this.feature&&"geometry"in this.feature?this.feature.geometry:null}canonicalID(){return this.canonical}properties(){return this.feature&&this.feature.properties||{}}measureLight(p){return this.globals.brightness||0}distanceFromCenter(){if(this.featureTileCoord&&this.featureDistanceData){const p=this.featureDistanceData.center,v=this.featureDistanceData.scale,{x:S,y:E}=this.featureTileCoord;return this.featureDistanceData.bearing[0]*(S*v-p[0])+this.featureDistanceData.bearing[1]*(E*v-p[1])}return 0}parseColor(p){let v=this._parseColorCache[p];return v||(v=this._parseColorCache[p]=cs.parse(p)),v}getConfig(p){return this.options?this.options.get(p):null}}class qc{constructor(p,v,S,E,R){this.name=p,this.type=v,this._evaluate=S,this.args=E,this._overloadIndex=R}evaluate(p){if(!this._evaluate){const v=qc.definitions[this.name];this._evaluate=Array.isArray(v)?v[2]:v.overloads[this._overloadIndex][1]}return this._evaluate(p,this.args)}eachChild(p){this.args.forEach(p)}outputDefined(){return!1}serialize(){return[this.name].concat(this.args.map(p=>p.serialize()))}static parse(p,v){const S=p[0],E=qc.definitions[S];if(!E)return v.error(`Unknown expression "${S}". If you wanted a literal array, use ["literal", [...]].`,0);const R=Array.isArray(E)?E[0]:E.type,F=Array.isArray(E)?[[E[1],E[2]]]:E.overloads,q=[];let K=null,J=-1;for(const[le,fe]of F){if(Array.isArray(le)&&le.length!==p.length-1)continue;q.push(le),J++,K=new Bj(v.registry,v.path,null,v.scope,void 0,v._scope,v.options,v.iconImageUseTheme);const ye=[];let Te=!1;for(let Pe=1;Peye)).map(sp).join(" | "),fe=[];for(let ye=1;yev;){if(S-v>600){const K=S-v+1,J=p-v+1,le=Math.log(K),fe=.5*Math.exp(2*le/3),ye=.5*Math.sqrt(le*fe*(K-fe)/K)*(J-K/2<0?-1:1);tv(j,p,Math.max(v,Math.floor(p-J*fe/K+ye)),Math.min(S,Math.floor(p+(K-J)*fe/K+ye)),E)}const R=j[p];let F=v,q=S;for(yc(j,v,p),E(j[S],R)>0&&yc(j,v,S);F0;)q--}E(j[v],R)===0?yc(j,v,q):(q++,yc(j,q,S)),q<=p&&(v=q+1),p<=q&&(S=q-1)}}function yc(j,p,v){const S=j[p];j[p]=j[v],j[v]=S}function Mg(j,p){return jp?1:0}function o0(j){let p=0;for(let v,S,E=0,R=j.length,F=R-1;E=p[2]||j[1]<=p[1]||j[3]>=p[3])}function d1(j,p,v){const S=j[0]-p[0],E=j[1]-p[1],R=j[0]-v[0],F=j[1]-v[1];return S*F-R*E===0&&S*R<=0&&E*F<=0}function hu(j,p,v){return p[1]>j[1]!=v[1]>j[1]&&j[0]<(v[0]-p[0])*(j[1]-p[1])/(v[1]-p[1])+p[0]}function Il(j,p,v=!1){let S=!1;for(let E=0,R=p.length;E0&&q<0||F<0&&q>0}function Oo(j,p,v,S){return(E=[S[0]-v[0],S[1]-v[1]])[0]*(R=[p[0]-j[0],p[1]-j[1]])[1]-E[1]*R[0]!==0&&!(!Wo(j,p,v,S)||!Wo(v,S,j,p));var E,R}function Fd(j){const p=new sn(Number.POSITIVE_INFINITY,Number.POSITIVE_INFINITY),v=new sn(Number.NEGATIVE_INFINITY,Number.NEGATIVE_INFINITY);for(const S of j[0])p.x>S.x&&(p.x=S.x),p.y>S.y&&(p.y=S.y),v.xv[2]){const E=.5*S;let R=j[0]-v[0]>E?-S:v[0]-j[0]>E?S:0;R===0&&(R=j[0]-v[2]>E?-S:v[2]-j[0]>E?S:0),j[0]+=R}oh(p,j)}function c0(j,p,v,S){const E=Math.pow(2,S.z)*Vc,R=[S.x*Vc,S.y*Vc],F=[];if(!j)return F;for(const q of j)for(const K of q){const J=[K.x+R[0],K.y+R[1]];mu(J,p,v,E),F.push(J)}return F}function ew(j,p,v,S){const E=Math.pow(2,S.z)*Vc,R=[S.x*Vc,S.y*Vc],F=[];if(!j)return F;for(const K of j){const J=[];for(const le of K){const fe=[le.x+R[0],le.y+R[1]];oh(p,fe),J.push(fe)}F.push(J)}if(p[2]-p[0]<=E/2){(q=p)[0]=q[1]=1/0,q[2]=q[3]=-1/0;for(const K of F)for(const J of K)mu(J,p,v,E)}var q;return F}class d0{constructor(p,v){this.type=ci,this.geojson=p,this.geometries=v}static parse(p,v){if(p.length!==2)return v.error(`'within' expression requires exactly one argument, but found ${p.length-1} instead.`);if(Nf(p[1])){const S=p[1];if(S.type==="FeatureCollection")for(let E=0;Ev)return Tb(R,F,(v-(S-q))/q)}return p[p.length-1]}pointToSegmentDistance(p,v,S){let[E,R]=v,F=np(S[0]-E)*this.kx,q=(S[1]-R)*this.ky;if(F!==0||q!==0){const K=(np(p[0]-E)*this.kx*F+(p[1]-R)*this.ky*q)/(F*F+q*q);K>1?(E=S[0],R=S[1]):K>0&&(E+=F/this.kx*K,R+=q/this.ky*K)}return F=np(p[0]-E)*this.kx,q=(p[1]-R)*this.ky,Math.sqrt(F*F+q*q)}pointOnLine(p,v){let S=1/0,E=p[0][0],R=p[0][1],F=0,q=0;for(let K=0;K1?(J=p[K+1][0],le=p[K+1][1]):Te>0&&(J+=fe/this.kx*Te,le+=ye/this.ky*Te)),fe=np(v[0]-J)*this.kx,ye=(v[1]-le)*this.ky;const Pe=fe*fe+ye*ye;PeR.index||E.index===R.index&&E.t>R.t){const J=E;E=R,R=J}const F=[E.point],q=E.index+1,K=R.index;!Oj(S[q],F[0])&&q<=K&&F.push(S[q]);for(let J=q+1;J<=K;J++)F.push(S[J]);return Oj(S[K],R.point)||F.push(R.point),F}lineSliceAlong(p,v,S){let E=0;const R=[];for(let F=0;Fp&&R.length===0&&R.push(Tb(q,K,(p-(E-J))/J)),E>=v)return R.push(Tb(q,K,(v-(E-J))/J)),R;E>p&&R.push(K)}return R}bufferPoint(p,v){const S=v/this.ky,E=v/this.kx;return[p[0]-E,p[1]-S,p[0]+E,p[1]+S]}bufferBBox(p,v){const S=v/this.ky,E=v/this.kx;return[p[0]-E,p[1]-S,p[2]+E,p[3]+S]}insideBBox(p,v){return np(p[0]-v[0])>=0&&np(p[0]-v[2])<=0&&p[1]>=v[1]&&p[1]<=v[3]}}function Oj(j,p){return j[0]===p[0]&&j[1]===p[1]}function Tb(j,p,v){const S=np(p[0]-j[0]);return[j[0]+S*v,j[1]+(p[1]-j[1])*v]}function np(j){for(;j<-180;)j+=360;for(;j>180;)j-=360;return j}class ch{constructor(p=[],v=(S,E)=>SE?1:0){if(this.data=p,this.length=this.data.length,this.compare=v,this.length>0)for(let S=(this.length>>1)-1;S>=0;S--)this._down(S)}push(p){this.data.push(p),this._up(this.length++)}pop(){if(this.length===0)return;const p=this.data[0],v=this.data.pop();return--this.length>0&&(this.data[0]=v,this._down(0)),p}peek(){return this.data[0]}_up(p){const{data:v,compare:S}=this,E=v[p];for(;p>0;){const R=p-1>>1,F=v[R];if(S(E,F)>=0)break;v[p]=F,p=R}v[p]=E}_down(p){const{data:v,compare:S}=this,E=this.length>>1,R=v[p];for(;p=0)break;v[p]=v[F],p=F}v[p]=R}}var sr=8192;function m1(j,p){return p.dist-j.dist}function p1(j){const p=[1/0,1/0,-1/0,-1/0];if(p.length!==j.length)return!1;for(let v=0;v=j[0]&&j[1]j[1])return[null,null];const v=sv(j);if(p){if(v===2)return[j,null];const S=Math.floor(v/2);return[[j[0],j[0]+S],[j[0]+S,j[1]]]}{if(v===1)return[j,null];const S=Math.floor(v/2)-1;return[[j[0],j[0]+S],[j[0]+S+1,j[1]]]}}function u0(j,p){const v=[1/0,1/0,-1/0,-1/0];if(!Bp(p,j.length))return v;for(let S=p[0];S<=p[1];++S)oh(v,j[S]);return v}function Eb(j){const p=[1/0,1/0,-1/0,-1/0];for(let v=0;vp[2]&&(S=j[0]-p[2]),j[1]>p[3]&&(E=j[1]-p[3]),j[3]=S)return S;if(Sf(E,R)){if(Mb(j,p))return 0}else if(Mb(p,j))return 0;let F=S;for(const q of j)for(let K=0,J=q.length,le=J-1;K=R)continue;const le=J.range1;if(sv(le)<=q){if(!Bp(le,j.length))return NaN;if(p){const fe=vc(j,le,v,S);if((R=Math.min(R,fe))===0)return R}else for(let fe=le[0];fe<=le[1];++fe){const ye=W3(j[fe],v,S);if((R=Math.min(R,ye))===0)return R}}else{const fe=ly(le,p);if(fe[0]!==null){const ye=nv(u0(j,fe[0]),K,S);ye=F)continue;const fe=le.range1,ye=le.range2;if(sv(fe)<=K&&sv(ye)<=J){if(!Bp(fe,j.length)||!Bp(ye,v.length))return NaN;if(p&&S?F=Math.min(F,a6(j,fe,v,ye,E)):p||S?p&&!S?F=Math.min(F,TN(v,ye,j,fe,E)):!p&&S&&(F=Math.min(F,TN(j,fe,v,ye,E))):F=Math.min(F,oS(j,fe,v,ye,E)),F===0)return F}else{const Te=ly(fe,p),Pe=ly(ye,S);f1(q,F,E,j,v,Te[0],Pe[0]),f1(q,F,E,j,v,Te[0],Pe[1]),f1(q,F,E,j,v,Te[1],Pe[0]),f1(q,F,E,j,v,Te[1],Pe[1])}}return F}function sw(j,p,v,S,E=1/0){let R=E;const F=u0(j,[0,j.length-1]);for(const q of v)if(!(R!==1/0&&nv(F,u0(q,[0,q.length-1]),S)>=R)&&(R=Math.min(R,yx(j,p,q,!0,S,R)),R===0))return R;return R}function Lb(j,p,v,S,E=1/0){let R=E;const F=u0(j,[0,j.length-1]);for(const q of v){if(R!==1/0&&nv(F,Eb(q),S)>=R)continue;const K=i6(j,p,q,S,R);if(isNaN(K))return K;if((R=Math.min(R,K))===0)return R}return R}function EN(j){return j==="Point"||j==="MultiPoint"||j==="LineString"||j==="MultiLineString"||j==="Polygon"||j==="MultiPolygon"}class g1{constructor(p,v){this.type=Lr,this.geojson=p,this.geometries=v}static parse(p,v){if(p.length!==2)return v.error(`'distance' expression requires either one argument, but found ' ${p.length-1} instead.`);if(Nf(p[1])){const S=p[1];if(S.type==="FeatureCollection"){for(let E=0;E{p&&!x1(v)&&(p=!1)}),p}function Cf(j){if(j instanceof qc&&j.name==="feature-state")return!1;let p=!0;return j.eachChild(v=>{p&&!Cf(v)&&(p=!1)}),p}function Wd(j,p){if(j instanceof qc&&p.indexOf(j.name)>=0)return!1;let v=!0;return j.eachChild(S=>{v&&!Wd(S,p)&&(v=!1)}),v}function vx(j,p,v){return[j,p,v].filter(Boolean).join("")}function zj(j,p){switch(j){case"string":return wa(p);case"number":return+p;case"boolean":return!!p;case"color":return cs.parse(p);case"formatted":return ed.fromString(wa(p));case"resolvedImage":return Mu.build(wa(p))}return p}function cS(j,p,v,S){return S!==void 0&&(j=S*Math.round(j/S)),p!==void 0&&jv&&(j=v),j}class eg{constructor(p,v,S,E=!1){this.type=p,this.key=v,this.scope=S,this.featureConstant=E}static parse(p,v){let S=v.expectedType;if(S==null&&(S=qi),p.length<2||p.length>3)return v.error("Invalid number of arguments for 'config' expression.");const E=v.parse(p[1],1);if(!(E instanceof Ir))return v.error("Key name of 'config' expression must be a string literal.");let R,F=!0;const q=wa(E.value);if(p.length>=3){const K=v.parse(p[2],2);if(!(K instanceof Ir))return v.error("Scope of 'config' expression must be a string literal.");R=wa(K.value)}if(v.options){const K=vx(q,R,v._scope),J=v.options.get(K);J&&(F=x1(J.value||J.default))}return new eg(S,q,R,F)}evaluate(p){const v=vx(this.key,this.scope,p.scope),S=p.getConfig(v);if(!S)return null;const{type:E,value:R,values:F,minValue:q,maxValue:K,stepValue:J}=S,le=S.default.evaluate(p);let fe=le;if(R){const ye=p.scope;p.scope=(ye||"").split("").slice(1).join(""),fe=R.evaluate(p),p.scope=ye}return E&&(fe=zj(E,fe)),fe===void 0||q===void 0&&K===void 0&&J===void 0||(typeof fe=="number"?fe=cS(fe,q,K,J):Array.isArray(fe)&&(fe=fe.map(ye=>typeof ye=="number"?cS(ye,q,K,J):ye))),R!==void 0&&fe!==void 0&&F&&!F.includes(fe)&&(fe=le,E&&(fe=zj(E,fe))),(E&&E!==this.type||fe!==void 0&&!ep(il(fe),this.type))&&(fe=zj(this.type.kind,fe)),fe}eachChild(){}outputDefined(){return!1}serialize(){const p=["config",this.key];return this.scope&&p.concat(this.scope),p}}class $p{constructor(p,v){this.type=v.type,this.name=p,this.boundExpression=v}static parse(p,v){if(p.length!==2||typeof p[1]!="string")return v.error("'var' expression requires exactly one string literal argument.");const S=p[1];return v.scope.has(S)?new $p(S,v.scope.get(S)):v.error(`Unknown variable "${S}". Make sure "${S}" has been bound in an enclosing "let" expression before using it.`,1)}evaluate(p){return this.boundExpression.evaluate(p)}eachChild(){}outputDefined(){return!1}serialize(){return["var",this.name]}}class Bj{constructor(p,v=[],S,E=new tl,R=[],F,q,K){this.registry=p,this.path=v,this.key=v.map(J=>typeof J=="string"?`['${J}']`:`[${J}]`).join(""),this.scope=E,this.errors=R,this.expectedType=S,this._scope=F,this.options=q,this.iconImageUseTheme=K}parse(p,v,S,E,R={}){return v||S?this.concat(v,null,S,E)._parse(p,R):this._parse(p,R)}parseObjectValue(p,v,S,E,R,F={}){return this.concat(v,S,E,R)._parse(p,F)}_parse(p,v){function S(E,R,F){return F==="assert"?new fm(R,[E]):F==="coerce"?new tp(R,[E]):E}if(p!==null&&typeof p!="string"&&typeof p!="boolean"&&typeof p!="number"||(p=["literal",p]),Array.isArray(p)){if(p.length===0)return this.error('Expected an array with at least one element. If you wanted a literal array, use ["literal", []].');const E=typeof p[0]=="string"?this.registry[p[0]]:void 0;if(E){let R=E.parse(p,this);if(!R)return null;if(this.expectedType){const F=this.expectedType,q=R.type;if(F.kind!=="string"&&F.kind!=="number"&&F.kind!=="boolean"&&F.kind!=="object"&&F.kind!=="array"||q.kind!=="value")if(F.kind!=="color"&&F.kind!=="formatted"&&F.kind!=="resolvedImage"||q.kind!=="value"&&q.kind!=="string"){if(this.checkSubtype(F,q))return null}else R=S(R,F,v.typeAnnotation||"coerce");else R=S(R,F,v.typeAnnotation||"assert")}if(!(R instanceof Ir)&&R.type.kind!=="resolvedImage"&&MN(R)){const F=new uu(this._scope,this.options,this.iconImageUseTheme);try{R=new Ir(R.type,R.evaluate(F))}catch(q){return this.error(q.message),null}}return R}return tp.parse(["to-array",p],this)}return this.error(p===void 0?"'undefined' value invalid. Use null instead.":typeof p=="object"?'Bare objects invalid. Use ["literal", {...}] instead.':`Expected an array, but found ${typeof p} instead.`)}concat(p,v,S,E){let R=typeof p=="number"?this.path.concat(p):this.path;R=typeof v=="string"?R.concat(v):R;const F=E?this.scope.concat(E):this.scope;return new Bj(this.registry,R,S||null,F,this.errors,this._scope,this.options,this.iconImageUseTheme)}error(p,...v){const S=`${this.key}${v.map(E=>`[${E}]`).join("")}`;this.errors.push(new Ui(S,p))}checkSubtype(p,v){const S=Tg(p,v);return S&&this.error(S),S}}function MN(j){if(j instanceof $p)return MN(j.boundExpression);if(j instanceof qc&&j.name==="error"||j instanceof ev||j instanceof d0||j instanceof g1||j instanceof eg)return!1;const p=j instanceof tp||j instanceof fm;let v=!0;return j.eachChild(S=>{v=p?v&&MN(S):v&&S instanceof Ir}),!!v&&x1(j)&&Wd(j,["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 nw(j,p){const v=j.length-1;let S,E,R=0,F=v,q=0;for(;R<=F;)if(q=Math.floor((R+F)/2),S=j[q],E=j[q+1],S<=p){if(q===v||pp))throw new Pl("Input is not a number.");F=q-1}return 0}class rw{constructor(p,v,S){this.type=p,this.input=v,this.labels=[],this.outputs=[];for(const[E,R]of S)this.labels.push(E),this.outputs.push(R)}static parse(p,v){if(p.length-1<4)return v.error(`Expected at least 4 arguments, but found only ${p.length-1}.`);if((p.length-1)%2!=0)return v.error("Expected an even number of arguments.");const S=v.parse(p[1],1,Lr);if(!S)return null;const E=[];let R=null;v.expectedType&&v.expectedType.kind!=="value"&&(R=v.expectedType);for(let F=1;F=q)return v.error('Input/output pairs for "step" expressions must be arranged with input values in strictly ascending order.',J);const fe=v.parse(K,le,R);if(!fe)return null;R=R||fe.type,E.push([q,fe])}return new rw(R,S,E)}evaluate(p){const v=this.labels,S=this.outputs;if(v.length===1)return S[0].evaluate(p);const E=this.input.evaluate(p);if(E<=v[0])return S[0].evaluate(p);const R=v.length;return E>=v[R-1]?S[R-1].evaluate(p):S[nw(v,E)].evaluate(p)}eachChild(p){p(this.input);for(const v of this.outputs)p(v)}outputDefined(){return this.outputs.every(p=>p.outputDefined())}serialize(){const p=["step",this.input.serialize()];for(let v=0;v0&&p.push(this.labels[v]),p.push(this.outputs[v].serialize());return p}}const Up=.95047,rp=1.08883,dS=4/29,cy=6/29,aw=3*cy*cy,iw=cy*cy*cy,LN=Math.PI/180,PN=180/Math.PI;function IN(j){return j>iw?Math.pow(j,1/3):j/aw+dS}function ow(j){return j>cy?j*j*j:aw*(j-dS)}function lw(j){return 255*(j<=.0031308?12.92*j:1.055*Math.pow(j,1/2.4)-.055)}function Pb(j){return(j/=255)<=.04045?j/12.92:Math.pow((j+.055)/1.055,2.4)}function $j(j){const p=Pb(j.r),v=Pb(j.g),S=Pb(j.b),E=IN((.4124564*p+.3575761*v+.1804375*S)/Up),R=IN((.2126729*p+.7151522*v+.072175*S)/1);return{l:116*R-16,a:500*(E-R),b:200*(R-IN((.0193339*p+.119192*v+.9503041*S)/rp)),alpha:j.a}}function DN(j){let p=(j.l+16)/116,v=isNaN(j.a)?p:p+j.a/500,S=isNaN(j.b)?p:p-j.b/200;return p=1*ow(p),v=Up*ow(v),S=rp*ow(S),new cs(lw(3.2404542*v-1.5371385*p-.4985314*S),lw(-.969266*v+1.8760108*p+.041556*S),lw(.0556434*v-.2040259*p+1.0572252*S),j.alpha)}function K3(j,p,v){const S=p-j;return j+v*(S>180||S<-180?S-360*Math.round(S/360):S)}const Ib={forward:$j,reverse:DN,interpolate:function(j,p,v){return{l:mr(j.l,p.l,v),a:mr(j.a,p.a,v),b:mr(j.b,p.b,v),alpha:mr(j.alpha,p.alpha,v)}}},dy={forward:function(j){const{l:p,a:v,b:S}=$j(j),E=Math.atan2(S,v)*PN;return{h:E<0?E+360:E,c:Math.sqrt(v*v+S*S),l:p,alpha:j.a}},reverse:function(j){const p=j.h*LN,v=j.c;return DN({l:j.l,a:Math.cos(p)*v,b:Math.sin(p)*v,alpha:j.alpha})},interpolate:function(j,p,v){return{h:K3(j.h,p.h,v),c:mr(j.c,p.c,v),l:mr(j.l,p.l,v),alpha:mr(j.alpha,p.alpha,v)}}};var cw=Object.freeze({__proto__:null,hcl:dy,lab:Ib});class Wh{constructor(p,v,S,E,R){this.type=p,this.operator=v,this.interpolation=S,this.input=E,this.labels=[],this.outputs=[];for(const[F,q]of R)this.labels.push(F),this.outputs.push(q)}static interpolationFactor(p,v,S,E){let R=0;if(p.name==="exponential")R=dw(v,p.base,S,E);else if(p.name==="linear")R=dw(v,1,S,E);else if(p.name==="cubic-bezier"){const F=p.controlPoints;R=new Mr(F[0],F[1],F[2],F[3]).solve(dw(v,1,S,E))}return R}static parse(p,v){let[S,E,R,...F]=p;if(!Array.isArray(E)||E.length===0)return v.error("Expected an interpolation type expression.",1);if(E[0]==="linear")E={name:"linear"};else if(E[0]==="exponential"){const J=E[1];if(typeof J!="number")return v.error("Exponential interpolation requires a numeric base.",1,1);E={name:"exponential",base:J}}else{if(E[0]!=="cubic-bezier")return v.error(`Unknown interpolation type ${String(E[0])}`,1,0);{const J=E.slice(1);if(J.length!==4||J.some(le=>typeof le!="number"||le<0||le>1))return v.error("Cubic bezier interpolation requires four numeric arguments with values between 0 and 1.",1);E={name:"cubic-bezier",controlPoints:J}}}if(p.length-1<4)return v.error(`Expected at least 4 arguments, but found only ${p.length-1}.`);if(p.length-1>3&&(p.length-1)%2!=0)return v.error("Expected an even number of arguments.");if(R=v.parse(R,2,Lr),!R)return null;const q=[];let K=null;S==="interpolate-hcl"||S==="interpolate-lab"?K=jl:v.expectedType&&v.expectedType.kind!=="value"&&(K=v.expectedType);for(let J=0;J=le)return v.error('Input/output pairs for "interpolate" expressions must be arranged with input values in strictly ascending order.',ye);const Pe=v.parse(fe,Te,K);if(!Pe)return null;K=K||Pe.type,q.push([le,Pe])}return K.kind==="number"||K.kind==="color"||K.kind==="array"&&K.itemType.kind==="number"&&typeof K.N=="number"?new Wh(K,S,E,R,q):v.error(`Type ${$l(K)} is not interpolatable.`)}evaluate(p){const v=this.labels,S=this.outputs;if(v.length===1)return S[0].evaluate(p);const E=this.input.evaluate(p);if(E<=v[0])return S[0].evaluate(p);const R=v.length;if(E>=v[R-1])return S[R-1].evaluate(p);const F=nw(v,E),q=Wh.interpolationFactor(this.interpolation,E,v[F],v[F+1]),K=S[F].evaluate(p),J=S[F+1].evaluate(p);return this.operator==="interpolate"?Ki[this.type.kind.toLowerCase()](K,J,q):this.operator==="interpolate-hcl"?dy.reverse(dy.interpolate(dy.forward(K),dy.forward(J),q)):Ib.reverse(Ib.interpolate(Ib.forward(K),Ib.forward(J),q))}eachChild(p){p(this.input);for(const v of this.outputs)p(v)}outputDefined(){return this.outputs.every(p=>p.outputDefined())}serialize(){let p;p=this.interpolation.name==="linear"?["linear"]:this.interpolation.name==="exponential"?this.interpolation.base===1?["linear"]:["exponential",this.interpolation.base]:["cubic-bezier",...this.interpolation.controlPoints];const v=[this.operator,p,this.input.serialize()];for(let S=0;STg(E,q.type));return new Db(F?qi:S,R)}evaluate(p){let v,S=null,E=0;for(const R of this.args){if(E++,S=R.evaluate(p),S&&S instanceof Mu&&!S.available&&(v||(v=S),S=null,E===this.args.length))return v;if(S!==null)break}return S}eachChild(p){this.args.forEach(p)}outputDefined(){return this.args.every(p=>p.outputDefined())}serialize(){const p=["coalesce"];return this.eachChild(v=>{p.push(v.serialize())}),p}}class ke{constructor(p,v){this.type=v.type,this.bindings=[].concat(p),this.result=v}evaluate(p){return this.result.evaluate(p)}eachChild(p){for(const v of this.bindings)p(v[1]);p(this.result)}static parse(p,v){if(p.length<4)return v.error(`Expected at least 3 arguments, but found ${p.length-1} instead.`);const S=[];for(let R=1;R=S.length)throw new Pl("Array index out of bounds: index exceeds array size");if(v!==Math.floor(v))throw new Pl("Array index must be an integer. Use at-interpolated for fractional indices");return S[v]}eachChild(p){p(this.index),p(this.input)}outputDefined(){return!1}serialize(){return["at",this.index.serialize(),this.input.serialize()]}}class ut{constructor(p,v,S){this.type=p,this.index=v,this.input=S}static parse(p,v){if(p.length!==3)return v.error(`Expected 2 arguments, but found ${p.length-1} instead.`);const S=v.parse(p[1],1,Lr),E=v.parse(p[2],2,du(v.expectedType||qi));return S&&E?new ut(E.type.itemType,S,E):null}evaluate(p){const v=this.index.evaluate(p),S=this.input.evaluate(p);if(v<0)throw new Pl(`Array index out of bounds: ${v} < 0.`);if(v>S.length-1)throw new Pl(`Array index out of bounds: ${v} > ${S.length-1}.`);if(v===Math.floor(v))return S[v];const E=Math.floor(v),R=Math.ceil(v),F=S[E],q=S[R];if(typeof F!="number"||typeof q!="number")throw new Pl(`Cannot interpolate between non-number values at index ${v}.`);const K=v-E;return F*(1-K)+q*K}eachChild(p){p(this.index),p(this.input)}outputDefined(){return!1}serialize(){return["at-interpolated",this.index.serialize(),this.input.serialize()]}}class yt{constructor(p,v){this.type=ci,this.needle=p,this.haystack=v}static parse(p,v){if(p.length!==3)return v.error(`Expected 2 arguments, but found ${p.length-1} instead.`),null;const S=v.parse(p[1],1,qi),E=v.parse(p[2],2,qi);return S&&E?r0(S.type,[ci,Za,Lr,Mc,qi])?new yt(S,E):(v.error(`Expected first argument to be of type boolean, string, number or null, but found ${$l(S.type)} instead`),null):null}evaluate(p){const v=this.needle.evaluate(p),S=this.haystack.evaluate(p);if(S==null)return!1;if(!Od(v,["boolean","string","number","null"]))throw new Pl(`Expected first argument to be of type boolean, string, number or null, but found ${$l(il(v))} instead.`);if(!Od(S,["string","array"]))throw new Pl(`Expected second argument to be of type array or string, but found ${$l(il(S))} instead.`);return S.indexOf(v)>=0}eachChild(p){p(this.needle),p(this.haystack)}outputDefined(){return!0}serialize(){return["in",this.needle.serialize(),this.haystack.serialize()]}}class Gt{constructor(p,v,S){this.type=Lr,this.needle=p,this.haystack=v,this.fromIndex=S}static parse(p,v){if(p.length<=2||p.length>=5)return v.error(`Expected 3 or 4 arguments, but found ${p.length-1} instead.`),null;const S=v.parse(p[1],1,qi),E=v.parse(p[2],2,qi);if(!S||!E)return null;if(!r0(S.type,[ci,Za,Lr,Mc,qi]))return v.error(`Expected first argument to be of type boolean, string, number or null, but found ${$l(S.type)} instead`),null;if(p.length===4){const R=v.parse(p[3],3,Lr);return R?new Gt(S,E,R):null}return new Gt(S,E)}evaluate(p){const v=this.needle.evaluate(p),S=this.haystack.evaluate(p);if(!Od(v,["boolean","string","number","null"]))throw new Pl(`Expected first argument to be of type boolean, string, number or null, but found ${$l(il(v))} instead.`);if(!Od(S,["string","array"]))throw new Pl(`Expected second argument to be of type array or string, but found ${$l(il(S))} instead.`);if(this.fromIndex){const E=this.fromIndex.evaluate(p);return S.indexOf(v,E)}return S.indexOf(v)}eachChild(p){p(this.needle),p(this.haystack),this.fromIndex&&p(this.fromIndex)}outputDefined(){return!1}serialize(){if(this.fromIndex!=null&&this.fromIndex!==void 0){const p=this.fromIndex.serialize();return["index-of",this.needle.serialize(),this.haystack.serialize(),p]}return["index-of",this.needle.serialize(),this.haystack.serialize()]}}class ns{constructor(p,v,S,E,R,F){this.inputType=p,this.type=v,this.input=S,this.cases=E,this.outputs=R,this.otherwise=F}static parse(p,v){if(p.length<5)return v.error(`Expected at least 4 arguments, but found only ${p.length-1}.`);if(p.length%2!=1)return v.error("Expected an even number of arguments.");let S,E;v.expectedType&&v.expectedType.kind!=="value"&&(E=v.expectedType);const R={},F=[];for(let J=2;JNumber.MAX_SAFE_INTEGER)return ye.error(`Branch labels must be integers no larger than ${Number.MAX_SAFE_INTEGER}.`);if(typeof Pe=="number"&&Math.floor(Pe)!==Pe)return ye.error("Numeric branch labels must be integer values.");if(S){if(ye.checkSubtype(S,il(Pe)))return null}else S=il(Pe);if(R[String(Pe)]!==void 0)return ye.error("Branch labels must be unique.");R[String(Pe)]=F.length}const Te=v.parse(fe,J,E);if(!Te)return null;E=E||Te.type,F.push(Te)}const q=v.parse(p[1],1,qi);if(!q)return null;const K=v.parse(p[p.length-1],p.length-1,E);return K?q.type.kind!=="value"&&v.concat(1).checkSubtype(S,q.type)?null:new ns(S,E,q,R,F,K):null}evaluate(p){const v=this.input.evaluate(p);return(ep(il(v),this.inputType)&&this.outputs[this.cases[v]]||this.otherwise).evaluate(p)}eachChild(p){p(this.input),this.outputs.forEach(p),p(this.otherwise)}outputDefined(){return this.outputs.every(p=>p.outputDefined())&&this.otherwise.outputDefined()}serialize(){const p=["match",this.input.serialize()],v=Object.keys(this.cases).sort(),S=[],E={};for(const F of v){const q=E[this.cases[F]];q===void 0?(E[this.cases[F]]=S.length,S.push([this.cases[F],[F]])):S[q][1].push(F)}const R=F=>this.inputType.kind==="number"?Number(F):F;for(const[F,q]of S)p.push(q.length===1?R(q[0]):q.map(R)),p.push(this.outputs[F].serialize());return p.push(this.otherwise.serialize()),p}}class ds{constructor(p,v,S){this.type=p,this.branches=v,this.otherwise=S}static parse(p,v){if(p.length<4)return v.error(`Expected at least 3 arguments, but found only ${p.length-1}.`),null;if(p.length%2!=0)return v.error("Expected an odd number of arguments."),null;let S;v.expectedType&&v.expectedType.kind!=="value"&&(S=v.expectedType);const E=[];for(let F=1;Fv.outputDefined())&&this.otherwise.outputDefined()}serialize(){const p=["case"];return this.eachChild(v=>{p.push(v.serialize())}),p}}class vs{constructor(p,v,S,E){this.type=p,this.input=v,this.beginIndex=S,this.endIndex=E}static parse(p,v){if(p.length<=2||p.length>=5)return v.error(`Expected 3 or 4 arguments, but found ${p.length-1} instead.`),null;const S=v.parse(p[1],1,qi),E=v.parse(p[2],2,Lr);if(!S||!E)return null;if(!r0(S.type,[du(qi),Za,qi]))return v.error(`Expected first argument to be of type array or string, but found ${$l(S.type)} instead`),null;if(p.length===4){const R=v.parse(p[3],3,Lr);return R?new vs(S.type,S,E,R):null}return new vs(S.type,S,E)}evaluate(p){const v=this.input.evaluate(p),S=this.beginIndex.evaluate(p);if(!Od(v,["string","array"]))throw new Pl(`Expected first argument to be of type array or string, but found ${$l(il(v))} instead.`);if(this.endIndex){const E=this.endIndex.evaluate(p);return v.slice(S,E)}return v.slice(S)}eachChild(p){p(this.input),p(this.beginIndex),this.endIndex&&p(this.endIndex)}outputDefined(){return!1}serialize(){if(this.endIndex!=null&&this.endIndex!==void 0){const p=this.endIndex.serialize();return["slice",this.input.serialize(),this.beginIndex.serialize(),p]}return["slice",this.input.serialize(),this.beginIndex.serialize()]}}class Ts{constructor(p,v){this.type=du(Za),this.str=p,this.delimiter=v}static parse(p,v){if(p.length!==3)return v.error(`Expected 2 arguments, but found ${p.length-1} instead.`);const S=v.parse(p[1],1,Za),E=v.parse(p[2],2,Za);return S&&E?new Ts(S,E):void 0}evaluate(p){const v=this.str.evaluate(p),S=this.delimiter.evaluate(p);return v.split(S)}eachChild(p){p(this.str),p(this.delimiter)}outputDefined(){return!1}serialize(){return["split",this.str.serialize(),this.delimiter.serialize()]}}function Vs(j,p){return j==="=="||j==="!="?p.kind==="boolean"||p.kind==="string"||p.kind==="number"||p.kind==="null"||p.kind==="value":p.kind==="string"||p.kind==="number"||p.kind==="value"}function bn(j,p,v,S){return S.compare(p,v)===0}function $n(j,p,v){const S=j!=="=="&&j!=="!=";return class U2t{constructor(R,F,q){this.type=ci,this.lhs=R,this.rhs=F,this.collator=q,this.hasUntypedArgument=R.type.kind==="value"||F.type.kind==="value"}static parse(R,F){if(R.length!==3&&R.length!==4)return F.error("Expected two or three arguments.");const q=R[0];let K=F.parse(R[1],1,qi);if(!K)return null;if(!Vs(q,K.type))return F.concat(1).error(`"${q}" comparisons are not supported for type '${$l(K.type)}'.`);let J=F.parse(R[2],2,qi);if(!J)return null;if(!Vs(q,J.type))return F.concat(2).error(`"${q}" comparisons are not supported for type '${$l(J.type)}'.`);if(K.type.kind!==J.type.kind&&K.type.kind!=="value"&&J.type.kind!=="value")return F.error(`Cannot compare types '${$l(K.type)}' and '${$l(J.type)}'.`);S&&(K.type.kind==="value"&&J.type.kind!=="value"?K=new fm(J.type,[K]):K.type.kind!=="value"&&J.type.kind==="value"&&(J=new fm(K.type,[J])));let le=null;if(R.length===4){if(K.type.kind!=="string"&&J.type.kind!=="string"&&K.type.kind!=="value"&&J.type.kind!=="value")return F.error("Cannot use collator to compare non-string types.");if(le=F.parse(R[3],3,Gh),!le)return null}return new U2t(K,J,le)}evaluate(R){const F=this.lhs.evaluate(R),q=this.rhs.evaluate(R);if(S&&this.hasUntypedArgument){const K=il(F),J=il(q);if(K.kind!==J.kind||K.kind!=="string"&&K.kind!=="number")throw new Pl(`Expected arguments for "${j}" to be (string, string) or (number, number), but found (${K.kind}, ${J.kind}) instead.`)}if(this.collator&&!S&&this.hasUntypedArgument){const K=il(F),J=il(q);if(K.kind!=="string"||J.kind!=="string")return p(R,F,q)}return this.collator?v(R,F,q,this.collator.evaluate(R)):p(R,F,q)}eachChild(R){R(this.lhs),R(this.rhs),this.collator&&R(this.collator)}outputDefined(){return!0}serialize(){const R=[j];return this.eachChild(F=>{R.push(F.serialize())}),R}}}const Gs=$n("==",function(j,p,v){return p===v},bn),En=$n("!=",function(j,p,v){return p!==v},function(j,p,v,S){return!bn(0,p,v,S)}),Kn=$n("<",function(j,p,v){return p",function(j,p,v){return p>v},function(j,p,v,S){return S.compare(p,v)>0}),ur=$n("<=",function(j,p,v){return p<=v},function(j,p,v,S){return S.compare(p,v)<=0}),Ln=$n(">=",function(j,p,v){return p>=v},function(j,p,v,S){return S.compare(p,v)>=0});class Pr{constructor(p,v,S,E,R,F){this.type=Za,this.number=p,this.locale=v,this.currency=S,this.unit=E,this.minFractionDigits=R,this.maxFractionDigits=F}static parse(p,v){if(p.length!==3)return v.error("Expected two arguments.");const S=v.parse(p[1],1,Lr);if(!S)return null;const E=p[2];if(typeof E!="object"||Array.isArray(E))return v.error("NumberFormat options argument must be an object.");let R=null;if(E.locale&&(R=v.parseObjectValue(E.locale,2,"locale",Za),!R))return null;let F=null;if(E.currency&&(F=v.parseObjectValue(E.currency,2,"currency",Za),!F))return null;let q=null;if(E.unit&&(q=v.parseObjectValue(E.unit,2,"unit",Za),!q))return null;let K=null;if(E["min-fraction-digits"]&&(K=v.parseObjectValue(E["min-fraction-digits"],2,"min-fraction-digits",Lr),!K))return null;let J=null;return E["max-fraction-digits"]&&(J=v.parseObjectValue(E["max-fraction-digits"],2,"max-fraction-digits",Lr),!J)?null:new Pr(S,R,F,q,K,J)}evaluate(p){return new Intl.NumberFormat(this.locale?this.locale.evaluate(p):[],{style:(this.currency?"currency":this.unit&&"unit")||"decimal",currency:this.currency?this.currency.evaluate(p):void 0,unit:this.unit?this.unit.evaluate(p):void 0,minimumFractionDigits:this.minFractionDigits?this.minFractionDigits.evaluate(p):void 0,maximumFractionDigits:this.maxFractionDigits?this.maxFractionDigits.evaluate(p):void 0}).format(this.number.evaluate(p))}eachChild(p){p(this.number),this.locale&&p(this.locale),this.currency&&p(this.currency),this.unit&&p(this.unit),this.minFractionDigits&&p(this.minFractionDigits),this.maxFractionDigits&&p(this.maxFractionDigits)}outputDefined(){return!1}serialize(){const p={};return this.locale&&(p.locale=this.locale.serialize()),this.currency&&(p.currency=this.currency.serialize()),this.unit&&(p.unit=this.unit.serialize()),this.minFractionDigits&&(p["min-fraction-digits"]=this.minFractionDigits.serialize()),this.maxFractionDigits&&(p["max-fraction-digits"]=this.maxFractionDigits.serialize()),["number-format",this.number.serialize(),p]}}class ha{constructor(p){this.type=Lr,this.input=p}static parse(p,v){if(p.length!==2)return v.error(`Expected 1 argument, but found ${p.length-1} instead.`),null;const S=v.parse(p[1],1);return S?S.type.kind!=="array"&&S.type.kind!=="string"&&S.type.kind!=="value"?(v.error(`Expected argument of type string or array, but found ${$l(S.type)} instead.`),null):new ha(S):null}evaluate(p){const v=this.input.evaluate(p);if(typeof v=="string"||Array.isArray(v))return v.length;throw new Pl(`Expected value to be of type string or array, but found ${$l(il(v))} instead.`)}eachChild(p){p(this.input)}outputDefined(){return!1}serialize(){const p=["length"];return this.eachChild(v=>{p.push(v.serialize())}),p}}function aa(j){return function(){j=1831565813+(j|=0)|0;let p=Math.imul(j^j>>>15,1|j);return p=p+Math.imul(p^p>>>7,61|p)^p,((p^p>>>14)>>>0)/4294967296}}const Ei={"==":Gs,"!=":En,">":wr,"<":Kn,">=":Ln,"<=":ur,array:fm,at:Oe,"at-interpolated":ut,boolean:fm,case:ds,coalesce:Db,collator:ev,format:td,image:ra,in:yt,"index-of":Gt,interpolate:Wh,"interpolate-hcl":Wh,"interpolate-lab":Wh,length:ha,let:ke,literal:Ir,match:ns,number:fm,"number-format":Pr,object:fm,slice:vs,step:rw,string:fm,"to-boolean":tp,"to-color":tp,"to-number":tp,"to-string":tp,var:$p,within:d0,distance:g1,config:eg,split:Ts};function hi(j,[p,v,S,E]){p=p.evaluate(j),v=v.evaluate(j),S=S.evaluate(j);const R=E?E.evaluate(j):1,F=pm(p,v,S,R);if(F)throw new Pl(F);return new cs(p/255,v/255,S/255,R)}function Ko(j,[p,v,S,E]){p=p.evaluate(j),v=v.evaluate(j),S=S.evaluate(j);const R=E?E.evaluate(j):1,F=function(J,le,fe,ye){return typeof J=="number"&&J>=0&&J<=360?typeof le=="number"&&le>=0&&le<=100&&typeof fe=="number"&&fe>=0&&fe<=100?ye===void 0||typeof ye=="number"&&ye>=0&&ye<=1?null:`Invalid hsla value [${[J,le,fe,ye].join(", ")}]: 'a' must be between 0 and 1.`:`Invalid hsla value [${(typeof ye=="number"?[J,le,fe,ye]:[J,le,fe]).join(", ")}]: 's', and 'l' must be between 0 and 100.`:`Invalid hsla value [${(typeof ye=="number"?[J,le,fe,ye]:[J,le,fe]).join(", ")}]: 'h' must be between 0 and 360.`}(p,v,S,R);if(F)throw new Pl(F);const q=`hsla(${p}, ${v}%, ${S}%, ${R})`,K=cs.parse(q);if(!K)throw new Pl(`Failed to parse HSLA color: ${q}`);return K}function wi(j,p){return j in p}function xl(j,p){const v=p[j];return v===void 0?null:v}function _d(j){return{type:j}}function Yo(j){if(j instanceof eg)return new Set([j.key]);let p=new Set;return j.eachChild(v=>{p=new Set([...p,...Yo(v)])}),p}function Si(j){if(j instanceof qc&&j.name==="is-active-floor")return!0;let p=!1;return j.eachChild(v=>{!p&&Si(v)&&(p=!0)}),p}function Ga(j){return{result:"success",value:j}}function Qo(j){return{result:"error",value:j}}function so(j,p){return!!j&&!!j.parameters&&j.parameters.indexOf(p)>-1}function zo(j){return j["property-type"]==="data-driven"}function hd(j){return so(j.expression,"measure-light")}function jh(j){return so(j.expression,"zoom")}function md(j){return!!j.expression&&j.expression.interpolated}function Kd(j){return typeof j=="object"&&j!==null&&!Array.isArray(j)}function zd(j){return j}function qp(j,p){const v=p.type==="color",S=j.stops&&typeof j.stops[0][0]=="object",E=S||!(S||j.property!==void 0),R=j.type||(md(p)?"exponential":"interval");if(v&&((j=Object.assign({},j)).stops&&(j.stops=j.stops.map(J=>[J[0],cs.parse(J[1])])),j.default=cs.parse(j.default?j.default:p.default)),j.colorSpace&&j.colorSpace!=="rgb"&&!cw[j.colorSpace])throw new Error(`Unknown color space: ${j.colorSpace}`);let F,q,K;if(R==="exponential")F=pu;else if(R==="interval")F=Hc;else if(R==="categorical"){F=oc,q=Object.create(null);for(const J of j.stops)q[J[0]]=J[1];K=typeof j.stops[0][0]}else{if(R!=="identity")throw new Error(`Unknown function type "${R}"`);F=bc}if(S){const J={},le=[];for(let Te=0;TeTe[0]),evaluate:({zoom:Te},Pe)=>pu({stops:fe,base:j.base},p,Te).evaluate(Te,Pe)}}if(E){const J=R==="exponential"?{name:"exponential",base:j.base!==void 0?j.base:1}:null;return{kind:"camera",interpolationType:J,interpolationFactor:Wh.interpolationFactor.bind(void 0,J),zoomStops:j.stops.map(le=>le[0]),evaluate:({zoom:le})=>F(j,p,le,q,K)}}return{kind:"source",evaluate(J,le){const fe=le&&le.properties?le.properties[j.property]:void 0;return fe===void 0?sd(j.default,p.default):F(j,p,fe,q,K)}}}function sd(j,p,v){return j!==void 0?j:p!==void 0?p:v!==void 0?v:void 0}function oc(j,p,v,S,E){return sd(typeof v===E?S[v]:void 0,j.default,p.default)}function Hc(j,p,v){if(!i0(v))return sd(j.default,p.default);const S=j.stops.length;if(S===1||v<=j.stops[0][0])return j.stops[0][1];if(v>=j.stops[S-1][0])return j.stops[S-1][1];const E=nw(j.stops.map(R=>R[0]),v);return j.stops[E][1]}function pu(j,p,v){const S=j.base!==void 0?j.base:1;if(!i0(v))return sd(j.default,p.default);const E=j.stops.length;if(E===1||v<=j.stops[0][0])return j.stops[0][1];if(v>=j.stops[E-1][0])return j.stops[E-1][1];const R=nw(j.stops.map(le=>le[0]),v),F=function(le,fe,ye,Te){const Pe=Te-ye,Ue=le-ye;return Pe===0?0:fe===1?Ue/Pe:(Math.pow(fe,Ue)-1)/(Math.pow(fe,Pe)-1)}(v,S,j.stops[R][0],j.stops[R+1][0]),q=j.stops[R][1],K=j.stops[R+1][1];let J=Ki[p.type]||zd;if(j.colorSpace&&j.colorSpace!=="rgb"){const le=cw[j.colorSpace];J=(fe,ye)=>le.reverse(le.interpolate(le.forward(fe),le.forward(ye),F))}return typeof q.evaluate=="function"?{evaluate(...le){const fe=q.evaluate.apply(void 0,le),ye=K.evaluate.apply(void 0,le);if(fe!==void 0&&ye!==void 0)return J(fe,ye,F)}}:J(q,K,F)}function bc(j,p,v){return p.type==="color"?v=cs.parse(v):p.type==="formatted"?v=ed.fromString(v.toString()):p.type==="resolvedImage"?v=Mu.build(v.toString()):Eg(v)===p.type||p.type==="enum"&&p.values[v]||(v=void 0),sd(v,j.default,p.default)}qc.register(Ei,{error:[{kind:"error"},[Za],(j,[p])=>{throw new Pl(p.evaluate(j))}],typeof:[Za,[qi],(j,[p])=>$l(il(p.evaluate(j)))],"to-rgba":[du(Lr,4),[jl],(j,[p])=>p.evaluate(j).toNonPremultipliedRenderColor(null).toArray()],"to-hsla":[du(Lr,4),[jl],(j,[p])=>p.evaluate(j).toNonPremultipliedRenderColor(null).toHslaArray()],rgb:[jl,[Lr,Lr,Lr],hi],rgba:[jl,[Lr,Lr,Lr,Lr],hi],hsl:[jl,[Lr,Lr,Lr],Ko],hsla:[jl,[Lr,Lr,Lr,Lr],Ko],has:{type:ci,overloads:[[[Za],(j,[p])=>wi(p.evaluate(j),j.properties())],[[Za,xc],(j,[p,v])=>wi(p.evaluate(j),v.evaluate(j))]]},get:{type:qi,overloads:[[[Za],(j,[p])=>xl(p.evaluate(j),j.properties())],[[Za,xc],(j,[p,v])=>xl(p.evaluate(j),v.evaluate(j))]]},"feature-state":[qi,[Za],(j,[p])=>xl(p.evaluate(j),j.featureState||{})],properties:[xc,[],j=>j.properties()],"geometry-type":[Za,[],j=>j.geometryType()],worldview:[Za,[],j=>j.globals.worldview||""],"is-active-floor":[ci,_d(Za),(j,p)=>{if(!(j.globals&&j.globals.activeFloors&&j.globals.activeFloors.size>0))return!1;if(p.length===0)return!0;const v=j.globals.activeFloors;return p.some(S=>{const E=S.evaluate(j);return v.has(E)})}],id:[qi,[],j=>j.id()],zoom:[Lr,[],j=>j.globals.zoom],pitch:[Lr,[],j=>j.globals.pitch||0],"distance-from-center":[Lr,[],j=>j.distanceFromCenter()],"measure-light":[Lr,[Za],(j,[p])=>j.measureLight(p.evaluate(j))],"heatmap-density":[Lr,[],j=>j.globals.heatmapDensity||0],"line-progress":[Lr,[],j=>j.globals.lineProgress||0],"raster-value":[Lr,[],j=>j.globals.rasterValue||0],"raster-particle-speed":[Lr,[],j=>j.globals.rasterParticleSpeed||0],"sky-radial-progress":[Lr,[],j=>j.globals.skyRadialProgress||0],accumulated:[qi,[],j=>j.globals.accumulated===void 0?null:j.globals.accumulated],"+":[Lr,_d(Lr),(j,p)=>{let v=0;for(const S of p)v+=S.evaluate(j);return v}],"*":[Lr,_d(Lr),(j,p)=>{let v=1;for(const S of p)v*=S.evaluate(j);return v}],"-":{type:Lr,overloads:[[[Lr,Lr],(j,[p,v])=>p.evaluate(j)-v.evaluate(j)],[[Lr],(j,[p])=>-p.evaluate(j)]]},"/":[Lr,[Lr,Lr],(j,[p,v])=>p.evaluate(j)/v.evaluate(j)],"%":[Lr,[Lr,Lr],(j,[p,v])=>p.evaluate(j)%v.evaluate(j)],ln2:[Lr,[],()=>Math.LN2],pi:[Lr,[],()=>Math.PI],e:[Lr,[],()=>Math.E],"^":[Lr,[Lr,Lr],(j,[p,v])=>Math.pow(p.evaluate(j),v.evaluate(j))],sqrt:[Lr,[Lr],(j,[p])=>Math.sqrt(p.evaluate(j))],log10:[Lr,[Lr],(j,[p])=>Math.log(p.evaluate(j))/Math.LN10],ln:[Lr,[Lr],(j,[p])=>Math.log(p.evaluate(j))],log2:[Lr,[Lr],(j,[p])=>Math.log2(p.evaluate(j))],sin:[Lr,[Lr],(j,[p])=>Math.sin(p.evaluate(j))],cos:[Lr,[Lr],(j,[p])=>Math.cos(p.evaluate(j))],tan:[Lr,[Lr],(j,[p])=>Math.tan(p.evaluate(j))],asin:[Lr,[Lr],(j,[p])=>Math.asin(p.evaluate(j))],acos:[Lr,[Lr],(j,[p])=>Math.acos(p.evaluate(j))],atan:[Lr,[Lr],(j,[p])=>Math.atan(p.evaluate(j))],min:[Lr,_d(Lr),(j,p)=>Math.min(...p.map(v=>v.evaluate(j)))],max:[Lr,_d(Lr),(j,p)=>Math.max(...p.map(v=>v.evaluate(j)))],abs:[Lr,[Lr],(j,[p])=>Math.abs(p.evaluate(j))],round:[Lr,[Lr],(j,[p])=>{const v=p.evaluate(j);return v<0?-Math.round(-v):Math.round(v)}],floor:[Lr,[Lr],(j,[p])=>Math.floor(p.evaluate(j))],ceil:[Lr,[Lr],(j,[p])=>Math.ceil(p.evaluate(j))],"filter-==":[ci,[Za,qi],(j,[p,v])=>j.properties()[p.value]===v.value],"filter-id-==":[ci,[qi],(j,[p])=>j.id()===p.value],"filter-type-==":[ci,[Za],(j,[p])=>j.geometryType()===p.value],"filter-<":[ci,[Za,qi],(j,[p,v])=>{const S=j.properties()[p.value],E=v.value;return typeof S==typeof E&&S{const v=j.id(),S=p.value;return typeof v==typeof S&&v":[ci,[Za,qi],(j,[p,v])=>{const S=j.properties()[p.value],E=v.value;return typeof S==typeof E&&S>E}],"filter-id->":[ci,[qi],(j,[p])=>{const v=j.id(),S=p.value;return typeof v==typeof S&&v>S}],"filter-<=":[ci,[Za,qi],(j,[p,v])=>{const S=j.properties()[p.value],E=v.value;return typeof S==typeof E&&S<=E}],"filter-id-<=":[ci,[qi],(j,[p])=>{const v=j.id(),S=p.value;return typeof v==typeof S&&v<=S}],"filter->=":[ci,[Za,qi],(j,[p,v])=>{const S=j.properties()[p.value],E=v.value;return typeof S==typeof E&&S>=E}],"filter-id->=":[ci,[qi],(j,[p])=>{const v=j.id(),S=p.value;return typeof v==typeof S&&v>=S}],"filter-has":[ci,[qi],(j,[p])=>p.value in j.properties()],"filter-has-id":[ci,[],j=>j.id()!==null&&j.id()!==void 0],"filter-type-in":[ci,[du(Za)],(j,[p])=>p.value.indexOf(j.geometryType())>=0],"filter-id-in":[ci,[du(qi)],(j,[p])=>p.value.indexOf(j.id())>=0],"filter-in-small":[ci,[Za,du(qi)],(j,[p,v])=>v.value.indexOf(j.properties()[p.value])>=0],"filter-in-large":[ci,[Za,du(qi)],(j,[p,v])=>function(S,E,R,F){for(;R<=F;){const q=R+F>>1;if(E[q]===S)return!0;E[q]>S?F=q-1:R=q+1}return!1}(j.properties()[p.value],v.value,0,v.value.length-1)],all:{type:ci,overloads:[[[ci,ci],(j,[p,v])=>p.evaluate(j)&&v.evaluate(j)],[_d(ci),(j,p)=>{for(const v of p)if(!v.evaluate(j))return!1;return!0}]]},any:{type:ci,overloads:[[[ci,ci],(j,[p,v])=>p.evaluate(j)||v.evaluate(j)],[_d(ci),(j,p)=>{for(const v of p)if(v.evaluate(j))return!0;return!1}]]},"!":[ci,[ci],(j,[p])=>!p.evaluate(j)],"is-supported-script":[ci,[Za],(j,[p])=>{const v=j.globals&&j.globals.isSupportedScript;return!v||v(p.evaluate(j))}],upcase:[Za,[Za],(j,[p])=>p.evaluate(j).toUpperCase()],downcase:[Za,[Za],(j,[p])=>p.evaluate(j).toLowerCase()],concat:[Za,_d(qi),(j,p)=>p.map(v=>wa(v.evaluate(j))).join("")],"resolved-locale":[Za,[Gh],(j,[p])=>p.evaluate(j).resolvedLocale()],random:[Lr,[Lr,Lr,qi],(j,p)=>{const[v,S,E]=p.map(F=>F.evaluate(j));if(v>S||v===S)return v;let R;if(typeof E=="string")R=function(F){let q=0;if(F.length===0)return q;for(let K=0;KJSON.stringify(fe)).join(", ")}, but found ${JSON.stringify(le)} instead.`);return le}catch(le){const fe=le;return this._warningHistory[fe.message]||(this._warningHistory[fe.message]=!0,typeof console<"u"&&console.warn(`Failed to evaluate expression "${JSON.stringify(this.expression.serialize())}". ${fe.message}`)),this._defaultValue}}}function gm(j){return Array.isArray(j)&&j.length>0&&typeof j[0]=="string"&&j[0]in Ei}function Pc(j,p,v,S,E){const R=new Bj(Ei,[],p?function(q){const K={color:jl,string:Za,number:Lr,enum:Za,boolean:ci,formatted:px,resolvedImage:fx};return q.type==="array"?du(K[q.value]||qi,q.length):K[q.type]}(p):void 0,void 0,void 0,v,S,E),F=R.parse(j,void 0,void 0,void 0,p&&p.type==="string"?{typeAnnotation:"coerce"}:void 0);return F?Ga(new Lu(F,p,v,S,E)):Qo(R.errors)}class Zu{constructor(p,v,S,E){this.kind=p,this._styleExpression=v,this.isLightConstant=S,this.isLineProgressConstant=E,this.isStateDependent=p!=="constant"&&!Cf(v.expression),this.configDependencies=Yo(v.expression),this.isIndoorDependent=Si(v.expression)}evaluateWithoutErrorHandling(p,v,S,E,R,F){return this._styleExpression.evaluateWithoutErrorHandling(p,v,S,E,R,F)}evaluate(p,v,S,E,R,F,q){return this._styleExpression.evaluate(p,v,S,E,R,F,void 0,void 0,q)}}class Dl{constructor(p,v,S,E,R,F){this.kind=p,this.zoomStops=S,this._styleExpression=v,this.isStateDependent=p!=="camera"&&!Cf(v.expression),this.isIndoorDependent=Si(v.expression),this.isLightConstant=R,this.isLineProgressConstant=F,this.configDependencies=Yo(v.expression),this.interpolationType=E}evaluateWithoutErrorHandling(p,v,S,E,R,F){return this._styleExpression.evaluateWithoutErrorHandling(p,v,S,E,R,F)}evaluate(p,v,S,E,R,F){return this._styleExpression.evaluate(p,v,S,E,R,F)}interpolationFactor(p,v,S){return this.interpolationType?Wh.interpolationFactor(this.interpolationType,p,v,S):0}}function Pu(j,p,v,S,E){if((j=Pc(j,p,v,S,E)).result==="error")return j;const R=j.value.expression,F=x1(R);if(!F&&!zo(p))return Qo([new Ui("","data expressions not supported")]);const q=Wd(R,["zoom","pitch","distance-from-center"]);if(!q&&!jh(p))return Qo([new Ui("","zoom expressions not supported")]);const K=Wd(R,["measure-light"]);if(!K&&!hd(p))return Qo([new Ui("","measure-light expression not supported")]);const J=Wd(R,["line-progress"]);if(!J&&!function(ye){return so(ye.expression,"line-progress")}(p))return Qo([new Ui("","line-progress expression not supported")]);const le=p.expression&&p.expression.relaxZoomRestriction,fe=wd(R);return fe||q||le?fe instanceof Ui?Qo([fe]):fe instanceof Wh&&!md(p)?Qo([new Ui("",'"interpolate" expressions cannot be used with this property')]):Ga(fe?new Dl(F&&J?"camera":"composite",j.value,fe.labels,fe instanceof Wh?fe.interpolation:void 0,K,J):new Zu(F&&J?"constant":"source",j.value,K,J)):Qo([new Ui("",'"zoom" expression may only be used as input to a top-level "step" or "interpolate" expression, or in the properties of atmosphere.')])}class xm{constructor(p,v){this._parameters=p,this._specification=v,Object.assign(this,qp(this._parameters,this._specification))}static deserialize(p){return new xm(p._parameters,p._specification)}static serialize(p){return{_parameters:p._parameters,_specification:p._specification}}}function wd(j){let p=null;if(j instanceof ke)p=wd(j.result);else if(j instanceof Db){for(const v of j.args)if(p=wd(v),p)break}else(j instanceof rw||j instanceof Wh)&&j.input instanceof qc&&j.input.name==="zoom"&&(p=j);return p instanceof Ui||j.eachChild(v=>{const S=wd(v);S instanceof Ui?p=S:p&&S&&p!==S&&(p=new Ui("",'Only one zoom-based "step" or "interpolate" subexpression may be used in an expression.'))}),p}var Vp,Hp,ym=function(){if(Hp)return Vp;Hp=1,Vp=p;var j=3;function p(v,S,E){var R=this.cells=[];if(v instanceof ArrayBuffer){this.arrayBuffer=v;var F=new Int32Array(this.arrayBuffer);v=F[0],this.d=(S=F[1])+2*(E=F[2]);for(var q=0;q=ye[Ue+0]&&R>=ye[Ue+1])?(K[Pe]=!0,q.push(fe[Pe])):K[Pe]=!1}}},p.prototype._forEachCell=function(v,S,E,R,F,q,K,J){for(var le=this._convertToCellCoord(v),fe=this._convertToCellCoord(S),ye=this._convertToCellCoord(E),Te=this._convertToCellCoord(R),Pe=le;Pe<=ye;Pe++)for(var Ue=fe;Ue<=Te;Ue++){var Qe=this.d*Ue+Pe;if((!J||J(this._convertFromCellCoord(Pe),this._convertFromCellCoord(Ue),this._convertFromCellCoord(Pe+1),this._convertFromCellCoord(Ue+1)))&&F.call(this,v,S,E,R,Qe,q,K,J))return}},p.prototype._convertFromCellCoord=function(v){return(v-this.padding)/this.scale},p.prototype._convertToCellCoord=function(v){return Math.max(0,Math.min(this.d-1,Math.floor(v*this.scale)+this.padding))},p.prototype.toArrayBuffer=function(){if(this.arrayBuffer)return this.arrayBuffer;for(var v=this.cells,S=j+this.cells.length+1+1,E=0,R=0;R=0||(E[R]=kc(j[R],p)));j instanceof Error&&(E.message=j.message)}if(E.$name)throw new Error("$name property is reserved for worker serialization logic.");return S!=="Object"&&(E.$name=S),E}throw new Error("can't serialize object of type "+typeof j)}function Xl(j){if(j==null||typeof j=="boolean"||typeof j=="number"||typeof j=="string"||j instanceof Boolean||j instanceof Number||j instanceof String||j instanceof Date||j instanceof RegExp||fo(j)||j instanceof ImageBitmap||ArrayBuffer.isView(j)||j instanceof ImageData)return j;if(Array.isArray(j))return j.map(Xl);if(typeof j=="object"){const p=j.$name||"Object";if(p==="Map"){const E=j.entries||[],R=new Map;for(let F=0;Fj>=1536&&j<=1791,Kh=j=>j>=1872&&j<=1919,h0=j=>j>=2208&&j<=2303,Yd=j=>j>=11904&&j<=12031,ap=j=>j>=12032&&j<=12255,rv=j=>j>=12272&&j<=12287,y1=j=>j>=12288&&j<=12351,av=j=>j>=12352&&j<=12447,vm=j=>j>=12448&&j<=12543,Gp=j=>j>=12544&&j<=12591,uw=j=>j>=12704&&j<=12735,bx=j=>j>=12736&&j<=12783,m0=j=>j>=12784&&j<=12799,uy=j=>j>=12800&&j<=13055,hw=j=>j>=13056&&j<=13311,mw=j=>j>=13312&&j<=19903,tg=j=>j>=19968&&j<=40959,hy=j=>j>=40960&&j<=42127,sg=j=>j>=42128&&j<=42191,Rb=j=>j>=44032&&j<=55215,v1=j=>j>=63744&&j<=64255,b1=j=>j>=64336&&j<=65023,pw=j=>j>=65040&&j<=65055,_1=j=>j>=65072&&j<=65103,fu=j=>j>=65104&&j<=65135,p0=j=>j>=65136&&j<=65279,Af=j=>j>=65280&&j<=65519;function Wp(j){for(const p of j)if(RN(p.charCodeAt(0)))return!0;return!1}function uS(j){for(const p of j)if(!w1(p.charCodeAt(0)))return!1;return!0}function w1(j){return!(cc(j)||Kh(j)||h0(j)||b1(j)||p0(j))}function hS(j){return!(j<11904||!(uw(j)||Gp(j)||_1(j)||v1(j)||hw(j)||Yd(j)||bx(j)||y1(j)||mw(j)||tg(j)||uy(j)||Af(j)||av(j)||rv(j)||ap(j)||m0(j)||vm(j)||pw(j)||sg(j)||hy(j)))}function RN(j){return!(j!==746&&j!==747&&(j<4352||!(uw(j)||Gp(j)||_1(j)&&!(j>=65097&&j<=65103)||v1(j)||hw(j)||Yd(j)||bx(j)||!(!y1(j)||j>=12296&&j<=12305||j>=12308&&j<=12319||j===12336)||mw(j)||tg(j)||uy(j)||(p=>p>=12592&&p<=12687)(j)||(p=>p>=43360&&p<=43391)(j)||(p=>p>=55216&&p<=55295)(j)||(p=>p>=4352&&p<=4607)(j)||Rb(j)||av(j)||rv(j)||(p=>p>=12688&&p<=12703)(j)||ap(j)||m0(j)||vm(j)&&j!==12540||!(!Af(j)||j===65288||j===65289||j===65293||j>=65306&&j<=65310||j===65339||j===65341||j===65343||j>=65371&&j<=65503||j===65507||j>=65512&&j<=65519)||!(!fu(j)||j>=65112&&j<=65118||j>=65123&&j<=65126)||(p=>p>=5120&&p<=5759)(j)||(p=>p>=6320&&p<=6399)(j)||pw(j)||(p=>p>=19904&&p<=19967)(j)||hy(j)||sg(j))))}function iv(j){return j===12312||j===12313||j===12316||j===12540||j===12448}function ov(j){return!(RN(j)||function(p){return!!((v=>v>=128&&v<=255)(p)&&(p===167||p===169||p===174||p===177||p===188||p===189||p===190||p===215||p===247)||(v=>v>=8192&&v<=8303)(p)&&(p===8214||p===8224||p===8225||p===8240||p===8241||p===8251||p===8252||p===8258||p===8263||p===8264||p===8265||p===8273)||(v=>v>=8448&&v<=8527)(p)||(v=>v>=8528&&v<=8591)(p)||(v=>v>=8960&&v<=9215)(p)&&(p>=8960&&p<=8967||p>=8972&&p<=8991||p>=8996&&p<=9e3||p===9003||p>=9085&&p<=9114||p>=9150&&p<=9165||p===9167||p>=9169&&p<=9179||p>=9186&&p<=9215)||(v=>v>=9216&&v<=9279)(p)&&p!==9251||(v=>v>=9280&&v<=9311)(p)||(v=>v>=9312&&v<=9471)(p)||(v=>v>=9632&&v<=9727)(p)||(v=>v>=9728&&v<=9983)(p)&&!(p>=9754&&p<=9759)||(v=>v>=11008&&v<=11263)(p)&&(p>=11026&&p<=11055||p>=11088&&p<=11097||p>=11192&&p<=11243)||y1(p)||vm(p)||(v=>v>=57344&&v<=63743)(p)||_1(p)||fu(p)||Af(p)||p===8734||p===8756||p===8757||p>=9984&&p<=10087||p>=10102&&p<=10131||p===65532||p===65533)}(j))}function mS(j){return cc(j)||Kh(j)||h0(j)||b1(j)||p0(j)}function lv(j){return j>=1424&&j<=2303||b1(j)||p0(j)}function _x(j,p){return!(!p&&lv(j)||j>=2304&&j<=3583||j>=3840&&j<=4255||(v=>v>=6016&&v<=6143)(j))}function Uj(j){for(const p of j)if(lv(p.charCodeAt(0)))return!0;return!1}const Iu={unavailable:"unavailable",deferred:"deferred",loading:"loading",parsing:"parsing",parsed:"parsed",loaded:"loaded",error:"error"};let Yh=null,jd=Iu.unavailable,Kp=null;const ON=function(j){j&&typeof j=="string"&&j.indexOf("NetworkError")>-1&&(jd=Iu.error),Yh&&Yh(j)};function qj(){FN.fire(new Nc("pluginStateChange",{pluginStatus:jd,pluginURL:Kp}))}const FN=new Hh,f0=function(){return jd},zN=function(){if(jd!==Iu.deferred||!Kp)throw new Error("rtl-text-plugin cannot be downloaded unless a pluginURL is specified");jd=Iu.loading,qj(),Kp&&iy({url:Kp},j=>{j?ON(j):(jd=Iu.loaded,qj())})},Ig={applyArabicShaping:null,processBidirectionalText:null,processStyledBidirectionalText:null,isLoaded:()=>jd===Iu.loaded||Ig.applyArabicShaping!=null,isLoading:()=>jd===Iu.loading,setState(j){jd=j.pluginStatus,Kp=j.pluginURL},isParsing:()=>jd===Iu.parsing,isParsed:()=>jd===Iu.parsed,getPluginURL:()=>Kp},o6=function(){Ig.isLoading()||Ig.isLoaded()||f0()!=="deferred"||zN()};class xi{constructor(p,v){this.zoom=p,v?(this.now=v.now,this.fadeDuration=v.fadeDuration,this.transition=v.transition,this.pitch=v.pitch,this.brightness=v.brightness,this.worldview=v.worldview,this.activeFloors=v.activeFloors):(this.now=0,this.fadeDuration=0,this.transition={},this.pitch=0,this.brightness=0)}isSupportedScript(p){return function(v,S){for(const E of v)if(!_x(E.charCodeAt(0),S))return!1;return!0}(p,Ig.isLoaded())}}class BN{constructor(p,v,S,E,R){this.property=p,this.value=v,this.expression=function(F,q,K,J,le){if(Kd(F))return new xm(F,q);if(gm(F)||Array.isArray(F)&&F.length>0){const fe=Pu(F,q,K,J,le);if(fe.result==="error")throw new Error(fe.value.map(ye=>`${ye.key}: ${ye.message}`).join(", "));return fe.value}{let fe=F;return typeof F=="string"&&q.type==="color"&&(fe=cs.parse(F)),{kind:"constant",configDependencies:new Set,isIndoorDependent:!1,evaluate:()=>fe}}}(v===void 0?p.specification.default:v,p.specification,S,E,R)}isIndoorDependent(){return this.expression.isIndoorDependent}isDataDriven(){return this.expression.kind==="source"||this.expression.kind==="composite"}possiblyEvaluate(p,v,S,E){return this.property.possiblyEvaluate(this,p,v,S,E)}}class pS{constructor(p,v,S,E){this.property=p,this.value=new BN(p,void 0,v,S,E)}transitioned(p,v){return new $N(this.property,this.value,v,Object.assign({},p.transition,this.transition),p.now)}untransitioned(){return new $N(this.property,this.value,null,{},0)}}class Y3{constructor(p,v,S,E){this._properties=p,this._values=Object.create(p.defaultTransitionablePropertyValues),this._scope=v,this._options=S,this._iconImageUseTheme=E,this._isIndoorDependent=!1,this.configDependencies=new Set}getValue(p){return xr(this._values[p].value.value)}setValue(p,v){this._values.hasOwnProperty(p)||(this._values[p]=new pS(this._values[p].property,this._scope,this._options,this._iconImageUseTheme)),this._values[p].value=new BN(this._values[p].property,v===null?void 0:xr(v),this._scope,this._options,this._iconImageUseTheme),this._values[p].value.expression.configDependencies&&(this.configDependencies=new Set([...this.configDependencies,...this._values[p].value.expression.configDependencies]),this._isIndoorDependent=this._isIndoorDependent||this._values[p].value.isIndoorDependent())}setTransitionOrValue(p,v){v&&(this._options=v);const S=this._properties.properties;if(p)for(const E in p){const R=p[E];if(E.endsWith("-transition")){const F=E.slice(0,-11);S[F]&&this.setTransition(F,R)}else S.hasOwnProperty(E)&&this.setValue(E,R)}}getTransition(p){return xr(this._values[p].transition)}setTransition(p,v){this._values.hasOwnProperty(p)||(this._values[p]=new pS(this._values[p].property)),this._values[p].transition=xr(v)||void 0}serialize(){const p={};for(const v of Object.keys(this._values)){const S=this.getValue(v);S!==void 0&&(p[v]=S);const E=this.getTransition(v);E!==void 0&&(p[`${v}-transition`]=E)}return p}transitioned(p,v){const S=new Z3(this._properties);for(const E of Object.keys(this._values))S._values[E]=this._values[E].transitioned(p,v._values[E]);return S}untransitioned(){const p=new Z3(this._properties);for(const v of Object.keys(this._values))p._values[v]=this._values[v].untransitioned();return p}isIndoorDependent(){return this._isIndoorDependent}}class $N{constructor(p,v,S,E,R){const F=E.delay||0,q=E.duration||0;R=R||0,this.property=p,this.value=v,this.begin=R+F,this.end=this.begin+q,p.specification.transition&&(E.delay||E.duration)&&(this.prior=S)}possiblyEvaluate(p,v,S){const E=p.now||0,R=this.value.possiblyEvaluate(p,v,S),F=this.prior;if(F){if(E>this.end)return this.prior=null,R;if(this.value.isDataDriven())return this.prior=null,R;if(E":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 fS(j){return j instanceof Number||j instanceof String||j instanceof Boolean?j.valueOf():j}function UN(j){if(Array.isArray(j))return j.map(UN);if(j instanceof Object&&!(j instanceof Number||j instanceof String||j instanceof Boolean)){const p={};for(const v in j)p[v]=UN(j[v]);return p}return fS(j)}function gS(j){if(j===!0||j===!1)return!0;if(!Array.isArray(j)||j.length===0)return!1;switch(j[0]){case"has":return j.length>=2&&j[1]!=="$id"&&j[1]!=="$type";case"in":return j.length>=3&&(typeof j[1]!="string"||Array.isArray(j[2]));case"!in":case"!has":case"none":return!1;case"==":case"!=":case">":case">=":case"<":case"<=":return j.length!==3||Array.isArray(j[1])||Array.isArray(j[2]);case"any":case"all":for(const p of j.slice(1))if(!gS(p)&&typeof p!="boolean")return!1;return!0;default:return!0}}function Q3(j,p="",v=null,S="fill"){if(j==null)return{filter:()=>!0,needGeometry:!1,needFeature:!1};gS(j)||(j=eC(j));const E=j;let R=!0;try{R=function(le){if(!Hj(le))return le;let fe=UN(le);return c6(fe),fe=l6(fe),fe}(E)}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(E,null,2)} `)}let F=null,q=null;if(S!=="background"&&S!=="sky"&&S!=="slot"){q=Is[`filter_${S}`];const le=Pc(R,q,p,v);if(le.result==="error")throw new Error(le.value.map(fe=>`${fe.key}: ${fe.message}`).join(", "));F=(fe,ye,Te)=>le.value.evaluate(fe,ye,{},Te)}let K=null,J=null;if(R!==E){const le=Pc(E,q,p,v);if(le.result==="error")throw new Error(le.value.map(fe=>`${fe.key}: ${fe.message}`).join(", "));K=(fe,ye,Te,Pe,Ue)=>le.value.evaluate(fe,ye,{},Te,void 0,void 0,Pe,Ue),J=!x1(le.value.expression)}return{filter:F,dynamicFilter:K||void 0,needGeometry:yO(R),needFeature:!!J}}function l6(j){if(!Array.isArray(j))return j;const p=function(v){if(d6.has(v[0])){for(let S=1;Sl6(v))}function c6(j){let p=!1;const v=[];if(j[0]==="case"){for(let S=1;S",">=","<","<=","to-boolean"]);function J3(j,p){return jp?1:0}function yO(j){if(!Array.isArray(j))return!1;if(j[0]==="within"||j[0]==="distance")return!0;for(let p=1;p"||p==="<="||p===">="?Q(j[1],j[2],p):p==="any"?(v=j.slice(1),["any"].concat(v.map(eC))):p==="all"?["all"].concat(j.slice(1).map(eC)):p==="none"?["all"].concat(j.slice(1).map(eC).map(tt)):p==="in"?ee(j[1],j.slice(2)):p==="!in"?tt(ee(j[1],j.slice(2))):p==="has"?Le(j[1]):p!=="!has"||tt(Le(j[1]));var v}function Q(j,p,v){switch(j){case"$type":return[`filter-type-${v}`,p];case"$id":return[`filter-id-${v}`,p];default:return[`filter-${v}`,j,p]}}function ee(j,p){if(p.length===0)return!1;switch(j){case"$type":return["filter-type-in",["literal",p]];case"$id":return["filter-id-in",["literal",p]];default:return p.length>200&&!p.some(v=>typeof v!=typeof p[0])?["filter-in-large",j,["literal",p.sort(J3)]]:["filter-in-small",j,["literal",p]]}}function Le(j){switch(j){case"$type":return!0;case"$id":return["filter-has-id"];default:return["filter-has",j]}}function tt(j){return["!",j]}const lt="";function St(j,p){return p?`${j}${lt}${p}`:j}function Ps(j){const p=j.indexOf(lt);return p>=0?j.slice(p+1):""}let Fn;const kr=()=>Fn||(Fn=new dc({"icon-size":new Qn(Is.layout_symbol["icon-size"]),"icon-image":new Qn(Is.layout_symbol["icon-image"]),"icon-rotate":new Qn(Is.layout_symbol["icon-rotate"]),"icon-offset":new Qn(Is.layout_symbol["icon-offset"]),"text-size":new Qn(Is.layout_symbol["text-size"]),"text-rotate":new Qn(Is.layout_symbol["text-rotate"]),"text-offset":new Qn(Is.layout_symbol["text-offset"])}));let Sa;const Ai=()=>Sa||(Sa=new dc({"icon-opacity":new Qn(Is.paint_symbol["icon-opacity"]),"icon-occlusion-opacity":new Qn(Is.paint_symbol["icon-occlusion-opacity"]),"icon-emissive-strength":new Qn(Is.paint_symbol["icon-emissive-strength"]),"text-emissive-strength":new Qn(Is.paint_symbol["text-emissive-strength"]),"icon-color":new Qn(Is.paint_symbol["icon-color"]),"icon-halo-color":new Qn(Is.paint_symbol["icon-halo-color"]),"icon-halo-width":new Qn(Is.paint_symbol["icon-halo-width"]),"icon-halo-blur":new Qn(Is.paint_symbol["icon-halo-blur"]),"icon-translate":new Qn(Is.paint_symbol["icon-translate"]),"text-opacity":new Qn(Is.paint_symbol["text-opacity"]),"text-occlusion-opacity":new Qn(Is.paint_symbol["text-occlusion-opacity"]),"text-color":new Qn(Is.paint_symbol["text-color"],{runtimeType:jl,getOverride:j=>j.textColor,hasOverride:j=>!!j.textColor}),"text-halo-color":new Qn(Is.paint_symbol["text-halo-color"]),"text-halo-width":new Qn(Is.paint_symbol["text-halo-width"]),"text-halo-blur":new Qn(Is.paint_symbol["text-halo-blur"]),"text-translate":new Qn(Is.paint_symbol["text-translate"]),"symbol-z-offset":new Qn(Is.paint_symbol["symbol-z-offset"]),"icon-color-use-theme":new Qn({type:"string",default:"default","property-type":"data-driven"}),"icon-halo-color-use-theme":new Qn({type:"string",default:"default","property-type":"data-driven"}),"text-color-use-theme":new Qn({type:"string",default:"default","property-type":"data-driven"}),"text-halo-color-use-theme":new Qn({type:"string",default:"default","property-type":"data-driven"})}));class ol{constructor(p,v,S,E,R,F){this._conditionSpec=p,this._propertiesSpec=S;const q=Pc(p,Is.appearance.condition);if(q.result==="success"&&(this.condition=q.value),this.name=v,S){this.layoutProperties=new bm(kr()),this.unevaluatedLayout=new X3(kr(),E,R,F),this.paintProperties=new bm(Ai()),this.unevaluatedPaint=new X3(Ai(),E,R,"");for(const K in S)K in this.unevaluatedLayout._values?this.unevaluatedLayout.setValue(K,S[K]):K in this.unevaluatedPaint._values&&this.unevaluatedPaint.setValue(K,S[K])}}isActive(p){return!(this.condition||!p.isHidden||this.name!=="hidden")||this.condition.evaluate(p.globals,p.feature,p.featureState,p.canonical)}getCondition(){return this.condition}getName(){return this.name}getLayoutProperty(p){return this.layoutProperties.get(p)}getPaintProperty(p){return this.paintProperties.get(p)}getUnevaluatedLayoutProperties(){return this.unevaluatedLayout}getUnevaluatedLayoutProperty(p){return this.unevaluatedLayout._values[p]}getUnevaluatedPaintProperty(p){return this.unevaluatedPaint._values[p]}recalculate(p,v,S){this.unevaluatedLayout&&(this.layoutProperties=this.unevaluatedLayout.possiblyEvaluate(p,void 0,v,S)),this.unevaluatedPaint&&(this.paintProperties=this.unevaluatedPaint.possiblyEvaluate(p,void 0,v,""))}serialize(){const p={};p.condition=this.condition.expression.serialize(),this.name&&(p.name=this.name);const v=this.unevaluatedLayout?this.unevaluatedLayout.serialize():{},S=this.unevaluatedPaint?this.unevaluatedPaint.serialize():{},E=Object.assign({},v,S);return Object.keys(E).length>0&&(p.properties=E),p}hasIconLayoutProperties(){const p=this.hasLayoutProperty("icon-image"),v=this.hasLayoutProperty("icon-size"),S=this.hasLayoutProperty("icon-offset"),E=this.hasLayoutProperty("icon-rotate");return p||v||S||E}hasTextLayoutProperties(){const p=this.hasLayoutProperty("text-size"),v=this.hasLayoutProperty("text-offset"),S=this.hasLayoutProperty("text-rotate");return p||v||S}hasIconPaintProperties(){return!!this.unevaluatedPaint&&Object.keys(this.unevaluatedPaint._values).filter(p=>!p.endsWith("-use-theme")).some(p=>(p.startsWith("icon-")||p==="symbol-z-offset")&&this.hasPaintProperty(p))}hasTextPaintProperties(){return!!this.unevaluatedPaint&&Object.keys(this.unevaluatedPaint._values).filter(p=>!p.endsWith("-use-theme")).some(p=>(p.startsWith("text-")||p==="symbol-z-offset")&&this.hasPaintProperty(p))}hasLayoutProperty(p){return this.unevaluatedLayout&&this.unevaluatedLayout._values[p].value!==void 0}hasPaintProperty(p){return this.unevaluatedPaint&&this.unevaluatedPaint._values[p].value!==void 0}}const di="-transition",Du=new Set(["fill","line","background","hillshade","raster"]);class ll extends Hh{constructor(p,v,S,E,R,F){if(super(),this.id=p.id,this.fqid=St(this.id,S),this.type=p.type,this.scope=S,this.lut=E,this.options=R,this.iconImageUseTheme=F,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},p.type!=="custom"){if(this.metadata=p.metadata,this.minzoom=p.minzoom,this.maxzoom=p.maxzoom,p.type&&p.type!=="background"&&p.type!=="sky"&&p.type!=="slot"){this.source=p.source,this.sourceLayer=p["source-layer"],this.filter=p.filter;const q=Pc(this.filter,Is[`filter_${p.type}`]);q.result!=="error"&&(this.expressionDependencies.configDependencies=new Set([...this.expressionDependencies.configDependencies,...q.value.configDependencies]),this.expressionDependencies.isIndoorDependent=this.expressionDependencies.isIndoorDependent||q.value.isIndoorDependent)}if(p.slot&&(this.slot=p.slot),p.appearances&&this.setAppearances(p.appearances),v.layout&&(this._unevaluatedLayout=new X3(v.layout,this.scope,R,this.iconImageUseTheme),this.expressionDependencies.configDependencies=new Set([...this.expressionDependencies.configDependencies,...this._unevaluatedLayout.configDependencies]),this.expressionDependencies.isIndoorDependent=this.expressionDependencies.isIndoorDependent||this._unevaluatedLayout.isIndoorDependent()),v.paint){this._transitionablePaint=new Y3(v.paint,this.scope,R);for(const q in p.paint)this.setPaintProperty(q,p.paint[q]);for(const q in p.layout)this.setLayoutProperty(q,p.layout[q]);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 bm(v.paint)}}}onAdd(p){}onRemove(p){}isDraped(p){return!this.is3D(!0)&&Du.has(this.type)}getLayoutProperty(p){return p==="visibility"?this.visibility:this._unevaluatedLayout.getValue(p)}setLayoutProperty(p,v){if(this.type==="custom"&&p==="visibility")return void(this.visibility=v);const S=this._unevaluatedLayout;S._properties.properties[p]&&(S.setValue(p,v),this.expressionDependencies.configDependencies=new Set([...this.expressionDependencies.configDependencies,...S.configDependencies]),this.expressionDependencies.isIndoorDependent=this.expressionDependencies.isIndoorDependent||S.isIndoorDependent(),p==="visibility"&&this.possiblyEvaluateVisibility())}setAppearances(p){this.appearances=[],p.forEach(v=>{this.appearances.push(new ol(v.condition,v.name,v.properties,this.scope,this.options,this.iconImageUseTheme))}),this.appearancesVersion++}possiblyEvaluateVisibility(){this._unevaluatedLayout._values.visibility&&(this.visibility=this._unevaluatedLayout._values.visibility.possiblyEvaluate({zoom:0}))}getPaintProperty(p){return p.endsWith(di)?this._transitionablePaint.getTransition(p.slice(0,-11)):this._transitionablePaint.getValue(p)}isPaintProperty(p){return!!this._transitionablePaint._properties.properties[p]}setPaintProperty(p,v){const S=this._transitionablePaint,E=S._properties.properties;if(p.endsWith(di)){const fe=p.slice(0,-11);return E[fe]&&S.setTransition(fe,v||void 0),!1}if(!E[p])return!1;const R=S._values[p],F=R.value.isDataDriven(),q=R.value;S.setValue(p,v),this.expressionDependencies.configDependencies=new Set([...this.expressionDependencies.configDependencies,...S.configDependencies]),this.expressionDependencies.isIndoorDependent=this.expressionDependencies.isIndoorDependent||S.isIndoorDependent(),this._handleSpecialPaintPropertyUpdate(p);const K=S._values[p].value,J=K.isDataDriven(),le=p.endsWith("pattern")||p==="line-dasharray";return J||F||le||this._handleOverridablePaintPropertyUpdate(p,q,K)}_handleSpecialPaintPropertyUpdate(p){}getProgramIds(){return null}getDefaultProgramParams(p,v,S){return null}_handleOverridablePaintPropertyUpdate(p,v,S){return!1}isHidden(p){return!!(this.minzoom&&p=this.maxzoom)||this.visibility==="none"}updateTransitions(p){this._transitioningPaint=this._transitionablePaint.transitioned(p,this._transitioningPaint)}hasTransition(){return this._transitioningPaint.hasTransition()}recalculate(p,v){this._unevaluatedLayout&&(this.layout=this._unevaluatedLayout.possiblyEvaluate(p,void 0,v,this.iconImageUseTheme)),this.paint=this._transitioningPaint.possiblyEvaluate(p,void 0,v)}serialize(){const p={id:this.id,type:this.type,slot:this.slot,source:this.source,"source-layer":this.sourceLayer,metadata:this.metadata,minzoom:this.minzoom,maxzoom:this.maxzoom,filter:this.filter,layout:this._unevaluatedLayout&&this._unevaluatedLayout.serialize(),paint:this._transitionablePaint&&this._transitionablePaint.serialize()};return this.appearances.length!==0&&(p.appearances=this.appearances.map(v=>v.serialize())),gn(p,(v,S)=>!(v===void 0||S==="layout"&&!Object.keys(v).length||S==="paint"&&!Object.keys(v).length))}is3D(p){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 p in this.paint._values){const v=this.paint.get(p);if(v instanceof Vj&&zo(v.property.specification)&&(v.value.kind==="source"||v.value.kind==="composite")&&v.value.isStateDependent)return!0}for(const p of this.appearances)if(!Cf(p.condition.expression))return!0;return!1}compileFilter(p){this._filterCompiled||(this._featureFilter=Q3(this.filter,this.scope,p),this._filterCompiled=!0)}invalidateCompiledFilter(){this._filterCompiled=!1}dynamicFilter(){return this._featureFilter.dynamicFilter}dynamicFilterNeedsFeature(){return this._featureFilter.needFeature}dynamicFilterNeedsGeometry(){return this._featureFilter.needGeometry}getLayerRenderingStats(){return this._stats}resetLayerRenderingStats(p){this._stats&&(p.renderPass==="shadow"?this._stats.numRenderedVerticesInShadowPass=0:this._stats.numRenderedVerticesInTransparentPass=0)}getAppearances(){return this.appearances}queryRenderedFeatures(p,v,S){return{}}queryRadius(p){}queryIntersectsFeature(p,v,S,E,R,F,q,K,J,le){}}const Tf={Int8:Int8Array,Uint8:Uint8Array,Int16:Int16Array,Uint16:Uint16Array,Int32:Int32Array,Uint32:Uint32Array,Float32:Float32Array};class x0{constructor(p,v){this._structArray=p,this._pos1=v*this.size,this._pos2=this._pos1/2,this._pos4=this._pos1/4,this._pos8=this._pos1/8}}const br=new ArrayBuffer(0);class yn{constructor(){this._reallocCount=0,this.capacity=0,this.length=0}static serialize(p,v){return p._trim(),v&&p.arrayBuffer&&v.add(p.arrayBuffer),{length:p.length,arrayBuffer:p.arrayBuffer}}static deserialize(p){const v=Object.create(this.prototype);return v.arrayBuffer=p.arrayBuffer,v.length=p.length,p.arrayBuffer?v.capacity=p.arrayBuffer.byteLength/v.bytesPerElement:(v.capacity=0,v.arrayBuffer=br),v._refreshViews(),v}_trim(){this.length!==this.capacity&&(this.capacity=this.length,this.arrayBuffer=this.arrayBuffer.slice(0,this.length*this.bytesPerElement),this._refreshViews())}clear(){this.length=0}resize(p){this.reserve(p),this.length=p}reserve(p){if(p>this.capacity){this._reallocCount++,this.capacity=Math.max(p,Math.floor(5*this.capacity),128),this.arrayBuffer=new ArrayBuffer(this.capacity*this.bytesPerElement);const v=this.uint8;this._refreshViews(),v&&this.uint8.set(v)}}reserveForAdditional(p){this.reserve(this.length+p)}_refreshViews(){throw new Error("StructArray#_refreshViews() must be implemented by each concrete StructArray layout")}emplace(...p){throw new Error("StructArray#emplace() must be implemented by each concrete StructArray layout")}emplaceBack(...p){throw new Error("StructArray#emplaceBack() must be implemented by each concrete StructArray layout")}destroy(){this.int8=this.uint8=this.int16=this.uint16=this.int32=this.uint32=this.float32=null,this.arrayBuffer=null}}function Pn(j,p=1){let v=0,S=0;return{members:j.map(E=>{const R=Tf[E.type].BYTES_PER_ELEMENT,F=v=yi(v,Math.max(p,R)),q=E.components||1;return S=Math.max(S,R),v+=R*q,{name:E.name,type:E.type,components:q,offset:F}}),size:yi(v,Math.max(S,p)),alignment:p}}function yi(j,p){return Math.ceil(j/p)*p}class Mi extends yn{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer)}emplaceBack(p,v){const S=this.length;return this.resize(S+1),this.emplace(S,p,v)}emplace(p,v,S){const E=2*p;return this.int16[E+0]=v,this.int16[E+1]=S,p}}Mi.prototype.bytesPerElement=4,pr(Mi,"StructArrayLayout2i4");class Fo extends yn{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer)}emplaceBack(p,v,S){const E=this.length;return this.resize(E+1),this.emplace(E,p,v,S)}emplace(p,v,S,E){const R=3*p;return this.int16[R+0]=v,this.int16[R+1]=S,this.int16[R+2]=E,p}}Fo.prototype.bytesPerElement=6,pr(Fo,"StructArrayLayout3i6");class Yi extends yn{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer)}emplaceBack(p,v,S,E){const R=this.length;return this.resize(R+1),this.emplace(R,p,v,S,E)}emplace(p,v,S,E,R){const F=4*p;return this.int16[F+0]=v,this.int16[F+1]=S,this.uint16[F+2]=E,this.uint16[F+3]=R,p}}Yi.prototype.bytesPerElement=8,pr(Yi,"StructArrayLayout2i2ui8");class rl extends yn{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(p){const v=this.length;return this.resize(v+1),this.emplace(v,p)}emplace(p,v){return this.float32[1*p+0]=v,p}}rl.prototype.bytesPerElement=4,pr(rl,"StructArrayLayout1f4");class _m extends yn{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(p,v,S){const E=this.length;return this.resize(E+1),this.emplace(E,p,v,S)}emplace(p,v,S,E){const R=4*p,F=2*p;return this.int16[R+0]=v,this.int16[R+1]=S,this.float32[F+1]=E,p}}_m.prototype.bytesPerElement=8,pr(_m,"StructArrayLayout2i1f8");class Sc extends yn{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer)}emplaceBack(p,v,S){const E=this.length;return this.resize(E+1),this.emplace(E,p,v,S)}emplace(p,v,S,E){const R=4*p;return this.int16[R+0]=v,this.int16[R+1]=S,this.int16[R+2]=E,p}}Sc.prototype.bytesPerElement=8,pr(Sc,"StructArrayLayout3i8");class j1 extends yn{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer)}emplaceBack(p,v,S,E){const R=this.length;return this.resize(R+1),this.emplace(R,p,v,S,E)}emplace(p,v,S,E,R){const F=4*p;return this.int16[F+0]=v,this.int16[F+1]=S,this.int16[F+2]=E,this.int16[F+3]=R,p}}j1.prototype.bytesPerElement=8,pr(j1,"StructArrayLayout4i8");class u6 extends yn{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer)}emplaceBack(p,v,S,E,R){const F=this.length;return this.resize(F+1),this.emplace(F,p,v,S,E,R)}emplace(p,v,S,E,R,F){const q=5*p;return this.int16[q+0]=v,this.int16[q+1]=S,this.int16[q+2]=E,this.int16[q+3]=R,this.int16[q+4]=F,p}}u6.prototype.bytesPerElement=10,pr(u6,"StructArrayLayout5i10");class h6 extends yn{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(p,v,S,E,R,F,q){const K=this.length;return this.resize(K+1),this.emplace(K,p,v,S,E,R,F,q)}emplace(p,v,S,E,R,F,q,K){const J=6*p,le=12*p,fe=3*p;return this.int16[J+0]=v,this.int16[J+1]=S,this.uint8[le+4]=E,this.uint8[le+5]=R,this.uint8[le+6]=F,this.uint8[le+7]=q,this.float32[fe+2]=K,p}}h6.prototype.bytesPerElement=12,pr(h6,"StructArrayLayout2i4ub1f12");class N1 extends yn{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(p,v,S){const E=this.length;return this.resize(E+1),this.emplace(E,p,v,S)}emplace(p,v,S,E){const R=3*p;return this.float32[R+0]=v,this.float32[R+1]=S,this.float32[R+2]=E,p}}N1.prototype.bytesPerElement=12,pr(N1,"StructArrayLayout3f12");class fw extends yn{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(p,v,S,E,R){const F=this.length;return this.resize(F+1),this.emplace(F,p,v,S,E,R)}emplace(p,v,S,E,R,F){const q=6*p,K=3*p;return this.uint16[q+0]=v,this.uint16[q+1]=S,this.uint16[q+2]=E,this.uint16[q+3]=R,this.float32[K+2]=F,p}}fw.prototype.bytesPerElement=12,pr(fw,"StructArrayLayout4ui1f12");class tC extends yn{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer)}emplaceBack(p,v,S,E){const R=this.length;return this.resize(R+1),this.emplace(R,p,v,S,E)}emplace(p,v,S,E,R){const F=4*p;return this.uint16[F+0]=v,this.uint16[F+1]=S,this.uint16[F+2]=E,this.uint16[F+3]=R,p}}tC.prototype.bytesPerElement=8,pr(tC,"StructArrayLayout4ui8");class vO extends yn{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer)}emplaceBack(p,v,S,E,R,F){const q=this.length;return this.resize(q+1),this.emplace(q,p,v,S,E,R,F)}emplace(p,v,S,E,R,F,q){const K=6*p;return this.int16[K+0]=v,this.int16[K+1]=S,this.int16[K+2]=E,this.int16[K+3]=R,this.int16[K+4]=F,this.int16[K+5]=q,p}}vO.prototype.bytesPerElement=12,pr(vO,"StructArrayLayout6i12");class uq extends yn{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer)}emplaceBack(p,v,S,E,R,F,q,K,J,le,fe,ye){const Te=this.length;return this.resize(Te+1),this.emplace(Te,p,v,S,E,R,F,q,K,J,le,fe,ye)}emplace(p,v,S,E,R,F,q,K,J,le,fe,ye,Te){const Pe=12*p;return this.int16[Pe+0]=v,this.int16[Pe+1]=S,this.int16[Pe+2]=E,this.int16[Pe+3]=R,this.uint16[Pe+4]=F,this.uint16[Pe+5]=q,this.uint16[Pe+6]=K,this.uint16[Pe+7]=J,this.int16[Pe+8]=le,this.int16[Pe+9]=fe,this.int16[Pe+10]=ye,this.int16[Pe+11]=Te,p}}uq.prototype.bytesPerElement=24,pr(uq,"StructArrayLayout4i4ui4i24");class hq extends yn{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(p,v,S,E,R,F){const q=this.length;return this.resize(q+1),this.emplace(q,p,v,S,E,R,F)}emplace(p,v,S,E,R,F,q){const K=10*p,J=5*p;return this.int16[K+0]=v,this.int16[K+1]=S,this.int16[K+2]=E,this.float32[J+2]=R,this.float32[J+3]=F,this.float32[J+4]=q,p}}hq.prototype.bytesPerElement=20,pr(hq,"StructArrayLayout3i3f20");class Gj extends yn{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(p,v,S,E){const R=this.length;return this.resize(R+1),this.emplace(R,p,v,S,E)}emplace(p,v,S,E,R){const F=4*p;return this.float32[F+0]=v,this.float32[F+1]=S,this.float32[F+2]=E,this.float32[F+3]=R,p}}Gj.prototype.bytesPerElement=16,pr(Gj,"StructArrayLayout4f16");class m6 extends yn{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.uint32=new Uint32Array(this.arrayBuffer)}emplaceBack(p){const v=this.length;return this.resize(v+1),this.emplace(v,p)}emplace(p,v){return this.uint32[1*p+0]=v,p}}m6.prototype.bytesPerElement=4,pr(m6,"StructArrayLayout1ul4");class k1 extends yn{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer)}emplaceBack(p,v){const S=this.length;return this.resize(S+1),this.emplace(S,p,v)}emplace(p,v,S){const E=2*p;return this.uint16[E+0]=v,this.uint16[E+1]=S,p}}k1.prototype.bytesPerElement=4,pr(k1,"StructArrayLayout2ui4");class bO extends yn{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer),this.uint32=new Uint32Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer)}emplaceBack(p,v,S,E,R,F,q,K,J,le,fe,ye,Te){const Pe=this.length;return this.resize(Pe+1),this.emplace(Pe,p,v,S,E,R,F,q,K,J,le,fe,ye,Te)}emplace(p,v,S,E,R,F,q,K,J,le,fe,ye,Te,Pe){const Ue=20*p,Qe=10*p;return this.int16[Ue+0]=v,this.int16[Ue+1]=S,this.int16[Ue+2]=E,this.int16[Ue+3]=R,this.int16[Ue+4]=F,this.float32[Qe+3]=q,this.float32[Qe+4]=K,this.float32[Qe+5]=J,this.float32[Qe+6]=le,this.int16[Ue+14]=fe,this.uint32[Qe+8]=ye,this.uint16[Ue+18]=Te,this.uint16[Ue+19]=Pe,p}}bO.prototype.bytesPerElement=40,pr(bO,"StructArrayLayout5i4f1i1ul2ui40");class p6 extends yn{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer)}emplaceBack(p,v,S,E,R,F,q){const K=this.length;return this.resize(K+1),this.emplace(K,p,v,S,E,R,F,q)}emplace(p,v,S,E,R,F,q,K){const J=8*p;return this.int16[J+0]=v,this.int16[J+1]=S,this.int16[J+2]=E,this.int16[J+4]=R,this.int16[J+5]=F,this.int16[J+6]=q,this.int16[J+7]=K,p}}p6.prototype.bytesPerElement=16,pr(p6,"StructArrayLayout3i2i2i16");class mq extends yn{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer)}emplaceBack(p,v,S,E,R){const F=this.length;return this.resize(F+1),this.emplace(F,p,v,S,E,R)}emplace(p,v,S,E,R,F){const q=4*p,K=8*p;return this.float32[q+0]=v,this.float32[q+1]=S,this.float32[q+2]=E,this.int16[K+6]=R,this.int16[K+7]=F,p}}mq.prototype.bytesPerElement=16,pr(mq,"StructArrayLayout2f1f2i16");class f6 extends yn{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(p,v,S,E,R,F){const q=this.length;return this.resize(q+1),this.emplace(q,p,v,S,E,R,F)}emplace(p,v,S,E,R,F,q){const K=20*p,J=5*p;return this.uint8[K+0]=v,this.uint8[K+1]=S,this.float32[J+1]=E,this.float32[J+2]=R,this.float32[J+3]=F,this.float32[J+4]=q,p}}f6.prototype.bytesPerElement=20,pr(f6,"StructArrayLayout2ub4f20");class Zd extends yn{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer)}emplaceBack(p,v,S){const E=this.length;return this.resize(E+1),this.emplace(E,p,v,S)}emplace(p,v,S,E){const R=3*p;return this.uint16[R+0]=v,this.uint16[R+1]=S,this.uint16[R+2]=E,p}}Zd.prototype.bytesPerElement=6,pr(Zd,"StructArrayLayout3ui6");class _O extends yn{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer),this.uint32=new Uint32Array(this.arrayBuffer)}emplaceBack(p,v,S,E,R,F,q,K,J,le,fe,ye,Te,Pe,Ue,Qe,at,pt,dt,wt,Tt){const Lt=this.length;return this.resize(Lt+1),this.emplace(Lt,p,v,S,E,R,F,q,K,J,le,fe,ye,Te,Pe,Ue,Qe,at,pt,dt,wt,Tt)}emplace(p,v,S,E,R,F,q,K,J,le,fe,ye,Te,Pe,Ue,Qe,at,pt,dt,wt,Tt,Lt){const fs=30*p,Jt=15*p,ps=60*p;return this.int16[fs+0]=v,this.int16[fs+1]=S,this.int16[fs+2]=E,this.float32[Jt+2]=R,this.float32[Jt+3]=F,this.uint16[fs+8]=q,this.uint16[fs+9]=K,this.uint32[Jt+5]=J,this.uint32[Jt+6]=le,this.uint32[Jt+7]=fe,this.uint16[fs+16]=ye,this.uint16[fs+17]=Te,this.uint16[fs+18]=Pe,this.float32[Jt+10]=Ue,this.float32[Jt+11]=Qe,this.uint8[ps+48]=at,this.uint8[ps+49]=pt,this.uint8[ps+50]=dt,this.uint32[Jt+13]=wt,this.int16[fs+28]=Tt,this.uint8[ps+58]=Lt,p}}_O.prototype.bytesPerElement=60,pr(_O,"StructArrayLayout3i2f2ui3ul3ui2f3ub1ul1i1ub60");class pq extends yn{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer),this.uint32=new Uint32Array(this.arrayBuffer)}emplaceBack(p,v,S,E,R,F,q,K,J,le,fe,ye,Te,Pe,Ue,Qe,at,pt,dt,wt,Tt,Lt,fs,Jt,ps,rs,is,dn,fn,_n,Sn,wn,Un){const ln=this.length;return this.resize(ln+1),this.emplace(ln,p,v,S,E,R,F,q,K,J,le,fe,ye,Te,Pe,Ue,Qe,at,pt,dt,wt,Tt,Lt,fs,Jt,ps,rs,is,dn,fn,_n,Sn,wn,Un)}emplace(p,v,S,E,R,F,q,K,J,le,fe,ye,Te,Pe,Ue,Qe,at,pt,dt,wt,Tt,Lt,fs,Jt,ps,rs,is,dn,fn,_n,Sn,wn,Un,ln){const Nn=20*p,Tn=40*p,Vn=80*p;return this.float32[Nn+0]=v,this.float32[Nn+1]=S,this.int16[Tn+4]=E,this.int16[Tn+5]=R,this.int16[Tn+6]=F,this.int16[Tn+7]=q,this.int16[Tn+8]=K,this.int16[Tn+9]=J,this.int16[Tn+10]=le,this.int16[Tn+11]=fe,this.int16[Tn+12]=ye,this.uint16[Tn+13]=Te,this.uint16[Tn+14]=Pe,this.uint16[Tn+15]=Ue,this.uint16[Tn+16]=Qe,this.uint16[Tn+17]=at,this.uint16[Tn+18]=pt,this.uint16[Tn+19]=dt,this.uint16[Tn+20]=wt,this.uint16[Tn+21]=Tt,this.uint16[Tn+22]=Lt,this.uint16[Tn+23]=fs,this.uint16[Tn+24]=Jt,this.uint16[Tn+25]=ps,this.uint16[Tn+26]=rs,this.uint16[Tn+27]=is,this.uint32[Nn+14]=dn,this.float32[Nn+15]=fn,this.float32[Nn+16]=_n,this.float32[Nn+17]=Sn,this.float32[Nn+18]=wn,this.uint8[Vn+76]=Un,this.uint16[Tn+39]=ln,p}}pq.prototype.bytesPerElement=80,pr(pq,"StructArrayLayout2f9i15ui1ul4f1ub1ui80");class wO extends yn{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(p,v,S,E,R,F){const q=this.length;return this.resize(q+1),this.emplace(q,p,v,S,E,R,F)}emplace(p,v,S,E,R,F,q){const K=6*p;return this.float32[K+0]=v,this.float32[K+1]=S,this.float32[K+2]=E,this.float32[K+3]=R,this.float32[K+4]=F,this.float32[K+5]=q,p}}wO.prototype.bytesPerElement=24,pr(wO,"StructArrayLayout6f24");class xS extends yn{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(p,v,S,E,R){const F=this.length;return this.resize(F+1),this.emplace(F,p,v,S,E,R)}emplace(p,v,S,E,R,F){const q=5*p;return this.float32[q+0]=v,this.float32[q+1]=S,this.float32[q+2]=E,this.float32[q+3]=R,this.float32[q+4]=F,p}}xS.prototype.bytesPerElement=20,pr(xS,"StructArrayLayout5f20");class g6 extends yn{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(p,v,S,E,R,F,q){const K=this.length;return this.resize(K+1),this.emplace(K,p,v,S,E,R,F,q)}emplace(p,v,S,E,R,F,q,K){const J=7*p;return this.float32[J+0]=v,this.float32[J+1]=S,this.float32[J+2]=E,this.float32[J+3]=R,this.float32[J+4]=F,this.float32[J+5]=q,this.float32[J+6]=K,p}}g6.prototype.bytesPerElement=28,pr(g6,"StructArrayLayout7f28");class fq extends yn{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(p,v,S,E,R,F,q,K,J,le,fe){const ye=this.length;return this.resize(ye+1),this.emplace(ye,p,v,S,E,R,F,q,K,J,le,fe)}emplace(p,v,S,E,R,F,q,K,J,le,fe,ye){const Te=11*p;return this.float32[Te+0]=v,this.float32[Te+1]=S,this.float32[Te+2]=E,this.float32[Te+3]=R,this.float32[Te+4]=F,this.float32[Te+5]=q,this.float32[Te+6]=K,this.float32[Te+7]=J,this.float32[Te+8]=le,this.float32[Te+9]=fe,this.float32[Te+10]=ye,p}}fq.prototype.bytesPerElement=44,pr(fq,"StructArrayLayout11f44");class gq extends yn{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(p,v,S,E,R,F,q,K,J){const le=this.length;return this.resize(le+1),this.emplace(le,p,v,S,E,R,F,q,K,J)}emplace(p,v,S,E,R,F,q,K,J,le){const fe=9*p;return this.float32[fe+0]=v,this.float32[fe+1]=S,this.float32[fe+2]=E,this.float32[fe+3]=R,this.float32[fe+4]=F,this.float32[fe+5]=q,this.float32[fe+6]=K,this.float32[fe+7]=J,this.float32[fe+8]=le,p}}gq.prototype.bytesPerElement=36,pr(gq,"StructArrayLayout9f36");class yS extends yn{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(p,v){const S=this.length;return this.resize(S+1),this.emplace(S,p,v)}emplace(p,v,S){const E=2*p;return this.float32[E+0]=v,this.float32[E+1]=S,p}}yS.prototype.bytesPerElement=8,pr(yS,"StructArrayLayout2f8");class xq extends yn{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.uint32=new Uint32Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer)}emplaceBack(p,v,S,E){const R=this.length;return this.resize(R+1),this.emplace(R,p,v,S,E)}emplace(p,v,S,E,R){const F=6*p;return this.uint32[3*p+0]=v,this.uint16[F+2]=S,this.uint16[F+3]=E,this.uint16[F+4]=R,p}}xq.prototype.bytesPerElement=12,pr(xq,"StructArrayLayout1ul3ui12");class vS extends yn{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer)}emplaceBack(p){const v=this.length;return this.resize(v+1),this.emplace(v,p)}emplace(p,v){return this.uint16[1*p+0]=v,p}}vS.prototype.bytesPerElement=2,pr(vS,"StructArrayLayout1ui2");class yq extends yn{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(p,v,S,E,R,F,q,K,J,le,fe,ye,Te,Pe,Ue,Qe){const at=this.length;return this.resize(at+1),this.emplace(at,p,v,S,E,R,F,q,K,J,le,fe,ye,Te,Pe,Ue,Qe)}emplace(p,v,S,E,R,F,q,K,J,le,fe,ye,Te,Pe,Ue,Qe,at){const pt=16*p;return this.float32[pt+0]=v,this.float32[pt+1]=S,this.float32[pt+2]=E,this.float32[pt+3]=R,this.float32[pt+4]=F,this.float32[pt+5]=q,this.float32[pt+6]=K,this.float32[pt+7]=J,this.float32[pt+8]=le,this.float32[pt+9]=fe,this.float32[pt+10]=ye,this.float32[pt+11]=Te,this.float32[pt+12]=Pe,this.float32[pt+13]=Ue,this.float32[pt+14]=Qe,this.float32[pt+15]=at,p}}yq.prototype.bytesPerElement=64,pr(yq,"StructArrayLayout16f64");class jO extends yn{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(p,v,S,E,R,F,q){const K=this.length;return this.resize(K+1),this.emplace(K,p,v,S,E,R,F,q)}emplace(p,v,S,E,R,F,q,K){const J=10*p,le=5*p;return this.uint16[J+0]=v,this.uint16[J+1]=S,this.uint16[J+2]=E,this.uint16[J+3]=R,this.float32[le+2]=F,this.float32[le+3]=q,this.float32[le+4]=K,p}}jO.prototype.bytesPerElement=20,pr(jO,"StructArrayLayout4ui3f20");class NO extends yn{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer)}emplaceBack(p){const v=this.length;return this.resize(v+1),this.emplace(v,p)}emplace(p,v){return this.int16[1*p+0]=v,p}}NO.prototype.bytesPerElement=2,pr(NO,"StructArrayLayout1i2");class kO extends yn{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer)}emplaceBack(p){const v=this.length;return this.resize(v+1),this.emplace(v,p)}emplace(p,v){return this.uint8[1*p+0]=v,p}}kO.prototype.bytesPerElement=1,pr(kO,"StructArrayLayout1ub1");class UJ extends x0{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]}}UJ.prototype.size=40;class vq extends bO{get(p){return new UJ(this,p)}}pr(vq,"CollisionBoxArray");class qJ extends x0{get projectedAnchorX(){return this._structArray.int16[this._pos2+0]}get projectedAnchorY(){return this._structArray.int16[this._pos2+1]}get projectedAnchorZ(){return this._structArray.int16[this._pos2+2]}get tileAnchorX(){return this._structArray.float32[this._pos4+2]}get tileAnchorY(){return this._structArray.float32[this._pos4+3]}get glyphStartIndex(){return this._structArray.uint16[this._pos2+8]}get numGlyphs(){return this._structArray.uint16[this._pos2+9]}get vertexStartIndex(){return this._structArray.uint32[this._pos4+5]}get lineStartIndex(){return this._structArray.uint32[this._pos4+6]}get lineLength(){return this._structArray.uint32[this._pos4+7]}get segment(){return this._structArray.uint16[this._pos2+16]}get lowerSize(){return this._structArray.uint16[this._pos2+17]}get upperSize(){return this._structArray.uint16[this._pos2+18]}get lineOffsetX(){return this._structArray.float32[this._pos4+10]}get lineOffsetY(){return this._structArray.float32[this._pos4+11]}get writingMode(){return this._structArray.uint8[this._pos1+48]}get placedOrientation(){return this._structArray.uint8[this._pos1+49]}set placedOrientation(p){this._structArray.uint8[this._pos1+49]=p}get hidden(){return this._structArray.uint8[this._pos1+50]}set hidden(p){this._structArray.uint8[this._pos1+50]=p}get crossTileID(){return this._structArray.uint32[this._pos4+13]}set crossTileID(p){this._structArray.uint32[this._pos4+13]=p}get associatedIconIndex(){return this._structArray.int16[this._pos2+28]}get flipState(){return this._structArray.uint8[this._pos1+58]}set flipState(p){this._structArray.uint8[this._pos1+58]=p}}qJ.prototype.size=60;class VJ extends _O{get(p){return new qJ(this,p)}}pr(VJ,"PlacedSymbolArray");class x6 extends x0{get tileAnchorX(){return this._structArray.float32[this._pos4+0]}get tileAnchorY(){return this._structArray.float32[this._pos4+1]}get projectedAnchorX(){return this._structArray.int16[this._pos2+4]}get projectedAnchorY(){return this._structArray.int16[this._pos2+5]}get projectedAnchorZ(){return this._structArray.int16[this._pos2+6]}get rightJustifiedTextSymbolIndex(){return this._structArray.int16[this._pos2+7]}get centerJustifiedTextSymbolIndex(){return this._structArray.int16[this._pos2+8]}get leftJustifiedTextSymbolIndex(){return this._structArray.int16[this._pos2+9]}get verticalPlacedTextSymbolIndex(){return this._structArray.int16[this._pos2+10]}get placedIconSymbolIndex(){return this._structArray.int16[this._pos2+11]}get verticalPlacedIconSymbolIndex(){return this._structArray.int16[this._pos2+12]}get key(){return this._structArray.uint16[this._pos2+13]}get textBoxStartIndex(){return this._structArray.uint16[this._pos2+14]}get textBoxEndIndex(){return this._structArray.uint16[this._pos2+15]}get verticalTextBoxStartIndex(){return this._structArray.uint16[this._pos2+16]}get verticalTextBoxEndIndex(){return this._structArray.uint16[this._pos2+17]}get iconBoxStartIndex(){return this._structArray.uint16[this._pos2+18]}get iconBoxEndIndex(){return this._structArray.uint16[this._pos2+19]}get verticalIconBoxStartIndex(){return this._structArray.uint16[this._pos2+20]}get verticalIconBoxEndIndex(){return this._structArray.uint16[this._pos2+21]}get featureIndex(){return this._structArray.uint16[this._pos2+22]}get numHorizontalGlyphVertices(){return this._structArray.uint16[this._pos2+23]}get numVerticalGlyphVertices(){return this._structArray.uint16[this._pos2+24]}get numIconVertices(){return this._structArray.uint16[this._pos2+25]}get numVerticalIconVertices(){return this._structArray.uint16[this._pos2+26]}get useRuntimeCollisionCircles(){return this._structArray.uint16[this._pos2+27]}get crossTileID(){return this._structArray.uint32[this._pos4+14]}set crossTileID(p){this._structArray.uint32[this._pos4+14]=p}get textOffset0(){return this._structArray.float32[this._pos4+15]}get textOffset1(){return this._structArray.float32[this._pos4+16]}get collisionCircleDiameter(){return this._structArray.float32[this._pos4+17]}get zOffset(){return this._structArray.float32[this._pos4+18]}set zOffset(p){this._structArray.float32[this._pos4+18]=p}get hasIconTextFit(){return this._structArray.uint8[this._pos1+76]}get elevationFeatureIndex(){return this._structArray.uint16[this._pos2+39]}}x6.prototype.size=80;class HJ extends pq{get(p){return new x6(this,p)}}pr(HJ,"SymbolInstanceArray");class GJ extends rl{getoffsetX(p){return this.float32[1*p+0]}}pr(GJ,"GlyphOffsetArray");class y6 extends Mi{getx(p){return this.int16[2*p+0]}gety(p){return this.int16[2*p+1]}}pr(y6,"SymbolLineVertexArray");class WJ extends x0{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]}}WJ.prototype.size=12;class bq extends xq{get(p){return new WJ(this,p)}}pr(bq,"FeatureIndexArray");class KJ extends k1{geta_centroid_pos0(p){return this.uint16[2*p+0]}geta_centroid_pos1(p){return this.uint16[2*p+1]}}pr(KJ,"FillExtrusionCentroidArray");class _q extends x0{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]}}_q.prototype.size=6;class wq extends Fo{get(p){return new _q(this,p)}}pr(wq,"FillExtrusionWallArray");const YJ=Pn([{name:"a_pos",components:2,type:"Int16"}],4),qAe=Pn([{name:"a_circle_z_offset",components:1,type:"Float32"}],4),VAe=Pn([{name:"a_pos_3",components:3,type:"Int16"},{name:"a_pos_normal_3",components:3,type:"Int16"}]);class Ul{constructor(p=[]){this.segments=p}_prepareSegment(p,v,S,E,R){let F=this.segments[this.segments.length-1];return p>Ul.MAX_VERTEX_ARRAY_LENGTH&&Er(`Max vertices per segment is ${Ul.MAX_VERTEX_ARRAY_LENGTH}: bucket requested ${p}`),(!F||F.vertexLength+p>Ul.MAX_VERTEX_ARRAY_LENGTH||F.sortKey!==E||R!==void 0&&F&&F.batchIndex!==void 0&&F.batchIndex!==R)&&(F={vertexOffset:v,primitiveOffset:S,vertexLength:0,primitiveLength:0},E!==void 0&&(F.sortKey=E),R!==void 0&&(F.batchIndex=R),this.segments.push(F)),F}prepareSegment(p,v,S,E,R){return this._prepareSegment(p,v.length,S.length,E,R)}get(){return this.segments}destroy(){for(const p of this.segments)for(const v in p.vaos)p.vaos[v].destroy()}static simpleSegment(p,v,S,E){return new Ul([{vertexOffset:p,primitiveOffset:v,vertexLength:S,primitiveLength:E,vaos:{},sortKey:0}])}}function SO(j,p){return 256*(j=it(Math.floor(j),0,255))+it(Math.floor(p),0,255)}Ul.MAX_VERTEX_ARRAY_LENGTH=Math.pow(2,16)-1,pr(Ul,"SegmentVector");const HAe=Pn([{name:"a_pattern",components:4,type:"Uint16"},{name:"a_pixel_ratio",components:1,type:"Float32"}]),GAe=Pn([{name:"a_pattern_b",components:4,type:"Uint16"}]),WAe=Pn([{name:"a_dash",components:4,type:"Uint16"}]);class v6{constructor(){this.ids=[],this.uniqueIds=[],this.positions=[],this.indexed=!1}add(p,v,S,E){this.ids.push(jq(p)),this.positions.push(v,S,E)}eachPosition(p,v){const S=jq(p);let E=0,R=this.ids.length-1;for(;E>1;this.ids[F]>=S?R=F:E=F+1}for(;this.ids[E]===S;)v(this.positions[3*E],this.positions[3*E+1],this.positions[3*E+2]),E++}static serialize(p,v){const S=new Float64Array(p.ids),E=new Uint32Array(p.positions);return b6(S,E,0,S.length-1),v&&(v.add(S.buffer),v.add(E.buffer)),{ids:S,positions:E}}static deserialize(p){const v=new v6;let S;v.ids=p.ids,v.positions=p.positions;for(const E of v.ids)E!==S&&v.uniqueIds.push(E),S=E;return v.indexed=!0,v}}function jq(j){const p=+j;return Number.isSafeInteger(p)?p:Jc(String(j))}function b6(j,p,v,S){for(;v>1];let R=v-1,F=S+1;for(;;){do R++;while(j[R]E);if(R>=F)break;cv(j,R,F),cv(p,3*R,3*F),cv(p,3*R+1,3*F+1),cv(p,3*R+2,3*F+2)}F-v`u_${R}`),this.type=S,this.context=E}setUniform(p,v,S,E,R){const F=E.constantOr(this.value);v.set(p,R,F instanceof cs?F.toPremultipliedRenderColor(this.lutExpression&&this.lutExpression.kind==="constant"&&this.lutExpression.value==="none"?null:this.context.lut):F)}getBinding(p,v){return this.type==="color"?new YAe(p):new Nh(p)}}class pe{constructor(p,v){this.uniformNames=v.map(S=>`u_${S}`),this.pattern=null,this.patternTransition=null,this.pixelRatio=1}setConstantPatternPositions(p,v){this.pixelRatio=p.pixelRatio||1,this.pattern=p.tl.concat(p.br),this.patternTransition=v?v.tl.concat(v.br):this.pattern}setUniform(p,v,S,E,R){let F=null;R!=="u_pattern"&&R!=="u_dash"||(F=this.pattern),R==="u_pattern_b"&&(F=this.patternTransition),R==="u_pixel_ratio"&&(F=this.pixelRatio),F&&v.set(p,R,F)}getBinding(p,v){return v==="u_pattern"||v==="u_pattern_b"||v==="u_dash"?new KAe(p):new Nh(p)}}class je{constructor(p,v,S,E){this.expression=p,this.type=S,this.maxValue=0,this.paintVertexAttributes=v.map(R=>({name:`a_${R}`,type:"Float32",components:S==="color"?2:1,offset:0})),this.paintVertexArray=new E}populatePaintArray(p,v,S,E,R,F,q,K){const J=this.paintVertexArray.length,le=this.expression.kind==="composite"||this.expression.kind==="source"?this.expression.evaluate(new xi(0,{brightness:F,worldview:K}),v,{},R,E,q):this.expression.kind==="constant"&&this.expression.value,fe=Z(this.lutExpression,v,{},E,R,F,q,K);this.paintVertexArray.resize(p),this._setPaintValue(J,p,le,fe?null:this.context.lut)}updatePaintArray(p,v,S,E,R,F,q,K){const J=this.expression.kind==="composite"||this.expression.kind==="source"?this.expression.evaluate({zoom:0,brightness:q,worldview:K},S,E,void 0,R):this.expression.kind==="constant"&&this.expression.value,le=Z(this.lutExpression,S,E,R,void 0,q,void 0,K);this._setPaintValue(p,v,J,le?null:this.context.lut)}_setPaintValue(p,v,S,E){if(this.type==="color"){const R=Y(S.toPremultipliedRenderColor(E));for(let F=p;F`u_${q}_t`),this.type=S,this.useIntegerZoom=E,this.context=R,this.maxValue=0,this.paintVertexAttributes=v.map(q=>({name:`a_${q}`,type:"Float32",components:S==="color"?4:2,offset:0})),this.paintVertexArray=new F}populatePaintArray(p,v,S,E,R,F,q,K){const J=this.expression.evaluate(new xi(this.context.zoom,{brightness:F,worldview:K}),v,{},R,E,q),le=this.expression.evaluate(new xi(this.context.zoom+1,{brightness:F,worldview:K}),v,{},R,E,q),fe=Z(this.lutExpression,v,{},E,R,F,q,K),ye=this.paintVertexArray.length;this.paintVertexArray.resize(p),this._setPaintValue(ye,p,J,le,fe?null:this.context.lut)}updatePaintArray(p,v,S,E,R,F,q,K){const J=this.expression.evaluate({zoom:this.context.zoom,brightness:q,worldview:K},S,E,void 0,R),le=this.expression.evaluate({zoom:this.context.zoom+1,brightness:q,worldview:K},S,E,void 0,R),fe=Z(this.lutExpression,S,E,R,void 0,q,void 0,K);this._setPaintValue(p,v,J,le,fe?null:this.context.lut)}_setPaintValue(p,v,S,E,R){if(this.type==="color"){const F=Y(S.toPremultipliedRenderColor(R)),q=Y(E.toPremultipliedRenderColor(R));for(let K=p;K!0){this.binders={},this._buffers=[],this.context=v;const E=[],R=p;for(const F in p.paint._values){const q=R.paint.get(F);if(F.endsWith("-use-theme")||!S(F)||!(q instanceof Vj&&zo(q.property.specification)))continue;const K=ot(F,p.type),J=q.value,le=q.property.specification.type,fe=!!q.property.useIntegerZoom,ye=F==="line-dasharray"||F.endsWith("pattern"),Te=R.paint.get(`${F}-use-theme`),Pe=F==="line-dasharray"&&R.layout.get("line-cap").value.kind!=="constant"||Te&&Te.value.kind!=="constant";if(J.kind!=="constant"||Pe)if(J.kind==="source"||Pe||ye){const Ue=Pt(F,le,"source");this.binders[F]=ye?new He(J,K,le,Ue,p.id):new je(J,K,le,Ue),E.push(`/a_${F}`)}else{const Ue=Pt(F,le,"composite");this.binders[F]=new Ee(J,K,le,fe,v,Ue),E.push(`/z_${F}`)}else this.binders[F]=ye?new pe(J.value,K):new se(J.value,K,le,v),E.push(`/u_${F}`);Te&&(this.binders[F].lutExpression=Te.value)}this.cacheKey=E.sort().join("")}getMaxValue(p){const v=this.binders[p];return v instanceof je||v instanceof Ee?v.maxValue:0}populatePaintArrays(p,v,S,E,R,F,q,K){for(const J in this.binders){const le=this.binders[J];le.context=this.context,(le instanceof je||le instanceof Ee||le instanceof He)&&le.populatePaintArray(p,v,S,E,R,F,q,K)}}setConstantPatternPositions(p,v){for(const S in this.binders){const E=this.binders[S];E instanceof pe&&E.setConstantPatternPositions(p,v)}}getPatternTransitionVertexBuffer(p){const v=this.binders[p];return v instanceof He?v.paintTransitionVertexBuffer:null}updatePaintArrays(p,v,S,E,R,F,q,K,J,le){let fe=!1;const ye=Object.keys(p),Te=ye.length!==0&&!K,Pe=Te?ye:v.uniqueIds;this.context.lut=R.lut;for(const Ue in this.binders){const Qe=this.binders[Ue];if(Qe.context=this.context,(Qe instanceof je||Qe instanceof Ee||Qe instanceof He)&&Qe.expression&&Qe.expression.kind&&Qe.expression.kind!=="constant"&&(Qe.expression.isStateDependent===!0||Qe.expression.isLightConstant===!1)){const at=R.paint.get(Ue);Qe.expression=at.value;for(const pt of Pe){const dt=p[pt.toString()];v.eachPosition(pt,(wt,Tt,Lt)=>{const fs=E.feature(wt);Qe.updatePaintArray(Tt,Lt,fs,dt,F,q,J,le)})}if(!Te)for(const pt of S.uniqueIds){const dt=p[pt.toString()];S.eachPosition(pt,(wt,Tt,Lt)=>{const fs=E.feature(wt);Qe.updatePaintArray(Tt,Lt,fs,dt,F,q,J,le)})}fe=!0}}return fe}defines(){const p=[];for(const v in this.binders){const S=this.binders[v];(S instanceof se||S instanceof pe)&&p.push(...S.uniformNames.map(E=>`#define HAS_UNIFORM_${E}`))}return p}getPaintVertexBuffers(){return this._buffers}getUniforms(p){const v=[];for(const S in this.binders){const E=this.binders[S];if(E instanceof se||E instanceof pe||E instanceof Ee)for(const R of E.uniformNames)v.push({name:R,property:S,binding:E.getBinding(p,R)})}return v}setUniforms(p,v,S,E,R){for(const{name:F,property:q,binding:K}of S)this.binders[q].setUniform(p,K,R,E.get(q),F)}updatePaintBuffers(){this._buffers=[];for(const p in this.binders){const v=this.binders[p];(v instanceof je||v instanceof Ee||v instanceof He)&&v.paintVertexBuffer&&this._buffers.push(v.paintVertexBuffer),v instanceof He&&v.paintTransitionVertexBuffer&&this._buffers.push(v.paintTransitionVertexBuffer)}}upload(p){for(const v in this.binders){const S=this.binders[v];(S instanceof je||S instanceof Ee||S instanceof He)&&S.upload(p)}this.updatePaintBuffers()}destroy(){for(const p in this.binders){const v=this.binders[p];(v instanceof je||v instanceof Ee||v instanceof He)&&v.destroy()}}}class et{constructor(p,v,S=()=>!0){this.programConfigurations={};for(const E of p)this.programConfigurations[E.id]=new qe(E,v,S);this.needsUpload=!1,this._featureMap=new v6,this._featureMapWithoutIds=new v6,this._bufferOffset=0,this._idlessCounter=0}populatePaintArrays(p,v,S,E,R,F,q,K,J){for(const le in this.programConfigurations)this.programConfigurations[le].populatePaintArrays(p,v,E,R,F,q,K,J);v.id!==void 0?this._featureMap.add(v.id,S,this._bufferOffset,p):(this._featureMapWithoutIds.add(this._idlessCounter,S,this._bufferOffset,p),this._idlessCounter+=1),this._bufferOffset=p,this.needsUpload=!0}updatePaintArrays(p,v,S,E,R,F,q,K){for(const J of S)this.needsUpload=this.programConfigurations[J.id].updatePaintArrays(p,this._featureMap,this._featureMapWithoutIds,v,J,E,R,F,q||0,K)||this.needsUpload}get(p){return this.programConfigurations[p]}upload(p){if(this.needsUpload){for(const v in this.programConfigurations)this.programConfigurations[v].upload(p);this.needsUpload=!1}}destroy(){for(const p in this.programConfigurations)this.programConfigurations[p].destroy()}}const ct={"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 ot(j,p){return ct[j]||[j.replace(`${p}-`,"").replace(/-/g,"_")]}const bt={"line-pattern":{source:fw,composite:fw},"fill-pattern":{source:fw,composite:fw},"fill-extrusion-pattern":{source:fw,composite:fw},"line-dasharray":{source:tC,composite:tC}},vt={color:{source:yS,composite:Gj},number:{source:rl,composite:yS}};function Pt(j,p,v){const S=bt[j];return S&&S[v]||vt[p][v]}pr(se,"ConstantBinder"),pr(pe,"PatternConstantBinder"),pr(je,"SourceExpressionBinder"),pr(He,"PatternCompositeBinder"),pr(Ee,"CompositeExpressionBinder"),pr(qe,"ProgramConfiguration",{omit:["_buffers"]}),pr(et,"ProgramConfigurationSet");const Ft=sr/Math.PI/2,jt=64,ys=[jt,32,16],Qt=-Ft,gs=Ft;function $t(j,p,v,S=Ft){return v=Nr(v),[j*Math.sin(v)*S,-p*S,j*Math.cos(v)*S]}function Zt(j,p,v){return $t(Math.cos(Nr(j)),Math.sin(Nr(j)),p,v)}const hs=63710088e-1,Us=2*Math.PI*hs;class Cs{constructor(p,v){if(isNaN(p)||isNaN(v))throw new Error(`Invalid LngLat object: (${p}, ${v})`);if(this.lng=+p,this.lat=+v,this.lat>90||this.lat<-90)throw new Error("Invalid LngLat latitude value: must be between -90 and 90")}wrap(){return new Cs(kt(this.lng,-180,180),this.lat)}toArray(){return[this.lng,this.lat]}toString(){return`LngLat(${this.lng}, ${this.lat})`}distanceTo(p){const v=Math.PI/180,S=this.lat*v,E=p.lat*v,R=Math.sin(S)*Math.sin(E)+Math.cos(S)*Math.cos(E)*Math.cos((p.lng-this.lng)*v);return hs*Math.acos(Math.min(R,1))}toBounds(p=0){const v=360*p/40075017,S=v/Math.cos(Math.PI/180*this.lat);return new hn({lng:this.lng-S,lat:this.lat-v},{lng:this.lng+S,lat:this.lat+v})}toEcef(p){return Zt(this.lat,this.lng,Ft+p*Ft/hs)}static convert(p){if(p instanceof Cs)return p;if(Array.isArray(p)&&(p.length===2||p.length===3))return new Cs(Number(p[0]),Number(p[1]));if(!Array.isArray(p)&&typeof p=="object"&&p!==null)return new Cs(Number("lng"in p?p.lng:p.lon),Number(p.lat));throw new Error("`LngLatLike` argument must be specified as a LngLat instance, an object {lng: , lat: }, an object {lon: , lat: }, or an array of [, ]")}}class hn{constructor(p,v){p&&(v?this.setSouthWest(p).setNorthEast(v):Array.isArray(p)&&p.length===4?this.setSouthWest([p[0],p[1]]).setNorthEast([p[2],p[3]]):this.setSouthWest(p[0]).setNorthEast(p[1]))}setNorthEast(p){return this._ne=p instanceof Cs?new Cs(p.lng,p.lat):Cs.convert(p),this}setSouthWest(p){return this._sw=p instanceof Cs?new Cs(p.lng,p.lat):Cs.convert(p),this}extend(p){const v=this._sw,S=this._ne;let E,R;if(p instanceof Cs)E=p,R=p;else{if(!(p instanceof hn))return Array.isArray(p)?p.length===4||p.every(Array.isArray)?this.extend(hn.convert(p)):this.extend(Cs.convert(p)):typeof p=="object"&&p!==null&&p.hasOwnProperty("lat")&&(p.hasOwnProperty("lon")||p.hasOwnProperty("lng"))?this.extend(Cs.convert(p)):this;if(E=p._sw,R=p._ne,!E||!R)return this}return v||S?(v.lng=Math.min(E.lng,v.lng),v.lat=Math.min(E.lat,v.lat),S.lng=Math.max(R.lng,S.lng),S.lat=Math.max(R.lat,S.lat)):(this._sw=new Cs(E.lng,E.lat),this._ne=new Cs(R.lng,R.lat)),this}getCenter(){return new Cs((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 Cs(this.getWest(),this.getNorth())}getSouthEast(){return new Cs(this.getEast(),this.getSouth())}getWest(){return this._sw.lng}getSouth(){return this._sw.lat}getEast(){return this._ne.lng}getNorth(){return this._ne.lat}toArray(){return[this._sw.toArray(),this._ne.toArray()]}toString(){return`LngLatBounds(${this._sw.toString()}, ${this._ne.toString()})`}isEmpty(){return!(this._sw&&this._ne)}contains(p){const{lng:v,lat:S}=Cs.convert(p);let E=this._sw.lng<=v&&v<=this._ne.lng;return this._sw.lng>this._ne.lng&&(E=this._sw.lng>=v&&v>=this._ne.lng),this._sw.lat<=S&&S<=this._ne.lat&&E}static convert(p){if(p)return p instanceof hn?p:new hn(p)}}function an(j){return Us*Math.cos(j*Math.PI/180)}function An(j){return(180+j)/360}function On(j){return(180-180/Math.PI*Math.log(Math.tan(Math.PI/4+j*Math.PI/360)))/360}function Ks(j,p){return j/an(p)}function Es(j){return 360*j-180}function cn(j){return 360/Math.PI*Math.atan(Math.exp((180-360*j)*Math.PI/180))-90}function pn(j,p){return j*an(cn(p))}const vn=85.051129;function fr(j){return Math.cos(Nr(it(j,-85.051129,vn)))}function nr(j,p){const v=it(p,0,25.5),S=Math.pow(2,v);return fr(j)*Us/(512*S)}function rr(j){return 1/Math.cos(j*Math.PI/180)}function In(j,p=0){const v=Math.exp(Math.PI*(1-(j.y+p/sr)/(1<=K?(fa(j,p,v,J,le,R,fe,q,K),fa(j,J,le,S,E,fe,F,q,K)):j.push(F)}function Fr(j,p,v){let S=j[0],E=S.x,R=S.y;p(S);const F=[S];for(let q=1;qj.x+1||Sj.y+1)&&Er("Geometry exceeds allowed extent, reduce your vector tile buffer size"),j}function Ea(j,p,v){const S=j.loadGeometry(),E=j.extent,R=sr/E;if(p&&v&&v.projection.isReprojectedInTileSpace){const F=1<{const Te=Es((p.x+ye.x/E)/F),Pe=cn((p.y+ye.y/E)/F),Ue=le.project(Te,Pe);ye.x=(Ue.x*q-K)*E,ye.y=(Ue.y*q-J)*E};for(let ye=0;ye=E||Pe.y<0||Pe.y>=E||(fe(Pe),Te.push(Pe));S[ye]=Te}}for(const F of S)for(const q of F)Li(q,R);return S}function Pi(j,p){return{type:j.type,id:j.id,properties:j.properties,geometry:p?Ea(j):[]}}class ti{constructor(p,v,S,E,R){this.properties={},this.extent=S,this.type=0,this.id=void 0,this._pbf=p,this._geometry=-1,this._keys=E,this._values=R,p.readFields(So,this,v)}loadGeometry(){const p=this._pbf;p.pos=this._geometry;const v=p.readVarint()+p.pos,S=[];let E,R=1,F=0,q=0,K=0;for(;p.pos>3}if(F--,R===1||R===2)q+=p.readSVarint(),K+=p.readSVarint(),R===1&&(E&&S.push(E),E=[]),E&&E.push(new sn(q,K));else{if(R!==7)throw new Error(`unknown command ${R}`);E&&E.push(E[0].clone())}}return E&&S.push(E),S}bbox(){const p=this._pbf;p.pos=this._geometry;const v=p.readVarint()+p.pos;let S=1,E=0,R=0,F=0,q=1/0,K=-1/0,J=1/0,le=-1/0;for(;p.pos>3}if(E--,S===1||S===2)R+=p.readSVarint(),F+=p.readSVarint(),RK&&(K=R),Fle&&(le=F);else if(S!==7)throw new Error(`unknown command ${S}`)}return[q,J,K,le]}toGeoJSON(p,v,S){const E=this.extent*Math.pow(2,S),R=this.extent*p,F=this.extent*v,q=this.loadGeometry();function K(ye){return[360*(ye.x+R)/E-180,360/Math.PI*Math.atan(Math.exp((1-2*(ye.y+F)/E)*Math.PI))-90]}function J(ye){return ye.map(K)}let le;if(this.type===1){const ye=[];for(const Pe of q)ye.push(Pe[0]);const Te=J(ye);le=ye.length===1?{type:"Point",coordinates:Te[0]}:{type:"MultiPoint",coordinates:Te}}else if(this.type===2){const ye=q.map(J);le=ye.length===1?{type:"LineString",coordinates:ye[0]}:{type:"MultiLineString",coordinates:ye}}else{if(this.type!==3)throw new Error("unknown feature type");{const ye=function(Pe){const Ue=Pe.length;if(Ue<=1)return[Pe];const Qe=[];let at,pt;for(let dt=0;dt=this._features.length)throw new Error("feature index out of bounds");this._pbf.pos=this._features[p];const v=this._pbf.readVarint()+this._pbf.pos;return new ti(this._pbf,v,this.extent,this._keys,this._values)}}function ql(j,p,v){j===15?p.version=v.readVarint():j===1?p.name=v.readString():j===5?p.extent=v.readVarint():j===2?p._features.push(v.pos):j===3?p._keys.push(v.readString()):j===4&&p._values.push(function(S){let E=null;const R=S.readVarint()+S.pos;for(;S.pos>3;E=F===1?S.readString():F===2?S.readFloat():F===3?S.readDouble():F===4?S.readVarint64():F===5?S.readVarint():F===6?S.readSVarint():F===7?S.readBoolean():null}if(E==null)throw new Error("unknown feature value");return E}(v))}class Bo{constructor(p,v){this.layers=p.readFields(ji,{},v)}}function ji(j,p,v){if(j===3){const S=new Gc(v,v.readVarint()+v.pos);S.length&&(p[S.name]=S)}}const Ni="3d_elevation_id",Vl="level";class nd{constructor(){this._valid=!1}reset(p){return this.feature=p,this._valid=!0,this._geometry=p.loadGeometry(),this._geometry.length!==0&&this._geometry[0].length!==0||(this._valid=!1),this}geometry(p,v){return this._valid&&p(v(this._geometry)),this}require(p,v,S){return this.get(p,!0,v,S)}optional(p,v,S){return this.get(p,!1,v,S)}success(){return this._valid}get(p,v,S,E){const R=this.feature.properties.hasOwnProperty(p)?+this.feature.properties[p]:void 0;return this._valid&&R!==void 0&&!Number.isNaN(R)?S(E?E(R):R):v&&(this._valid=!1),this}}class $o{constructor(p,v){this.featureFunc=p,this.vertexFunc=v}parseFeature(p,v,S){return this.featureFunc(p,v,S)}parseVertex(p,v,S){return this.vertexFunc(p,v,S)}}const ui=new $o((j,p,v)=>j.reset(p).require(Ni,S=>{v.id=S}).optional("fixed_height_relative",S=>{v.constantHeight=S},vl.decodeRelativeHeight).geometry(S=>{v.bounds=S},Fd).success(),(j,p,v)=>j.reset(p).require(Ni,S=>{v.id=S}).require("elevation_idx",S=>{v.idx=S}).require("extent",S=>{v.extent=S}).require("height_relative",S=>{v.height=S},vl.decodeRelativeHeight).geometry(S=>{v.position=S},vl.getPoint).success()),Ic=new $o((j,p,v)=>j.reset(p).require(Ni,S=>{v.id=S}).optional("fixed_height",S=>{v.constantHeight=S},vl.decodeMetricHeight).geometry(S=>{v.bounds=S},Fd).success(),(j,p,v)=>j.reset(p).require(Ni,S=>{v.id=S}).require("elevation_idx",S=>{v.idx=S}).require("extent",S=>{v.extent=S}).require("height",S=>{v.height=S},vl.decodeMetricHeight).geometry(S=>{v.position=S},vl.getPoint).success());class vl{static getPoint(p){return ms(p[0][0].x,p[0][0].y)}static decodeRelativeHeight(p){return 1e-4*p*5}static decodeMetricHeight(p){return 1e-4*p}static getVersionSchema(p){return p?p==="1.0.1"?Ic:void 0:ui}static parse(p){const v=[],S=[],E=p.length,R=new nd;for(let F=0;F=0);if(R===0)return 0;R!==p.length&&(v=!1)}return v?2:1}function kh(j,p){for(const v of j.projections){const S=uh(p,j.points[0],v.axis);if(v.projection[1]S[1])return 0}return 1}function ip(j,p){let v=0;const S=[0,0,0,0];for(let E=0;E=0&&v++;return v}class my{constructor(p,v){this.points=p||new Array(8).fill([0,0,0]),this.planes=v||new Array(6).fill([0,0,0,0]),this.bounds=sl.fromPoints(this.points),this.projections=[],this.frustumEdges=[$e([],this.points[2],this.points[3]),$e([],this.points[0],this.points[3]),$e([],this.points[4],this.points[0]),$e([],this.points[5],this.points[1]),$e([],this.points[6],this.points[2]),$e([],this.points[7],this.points[3])];for(const S of this.frustumEdges){const E=[0,-S[2],S[1]],R=[S[2],0,-S[0]];this.projections.push({axis:E,projection:uh(this.points,this.points[0],E)}),this.projections.push({axis:R,projection:uh(this.points,this.points[0],R)})}}static fromInvProjectionMatrix(p,v,S,E){const R=Math.pow(2,S),F=[[-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(J=>{const le=ht([],J,p),fe=1/le[3]/v*R;return(ye=le)[0]=(Te=le)[0]*(Pe=[fe,fe,E?1/le[3]:fe,fe])[0],ye[1]=Te[1]*Pe[1],ye[2]=Te[2]*Pe[2],ye[3]=Te[3]*Pe[3],ye;var ye,Te,Pe}),q=[[0,1,2],[6,5,4],[0,3,7],[2,1,5],[3,2,6],[0,4,5]].map(J=>{const le=Me([],Be([],$e([],F[J[0]],F[J[1]]),$e([],F[J[2]],F[J[1]]))),fe=-Re(le,F[J[1]]);return le.concat(fe)}),K=[];for(let J=0;JJ[1]||J[0]>K[1])return 0}return 1}containsPoint(p){for(const v of this.planes){const S=v[3];if(Re([v[0],v[1],v[2]],p)+S<0)return!1}return!0}}class sl{static fromPoints(p){const v=[1/0,1/0,1/0],S=[-1/0,-1/0,-1/0];for(const E of p)ae(v,v,E),he(S,S,E);return new sl(v,S)}static fromTileIdAndHeight(p,v,S){const E=1<p.max[v]||p.min[v]>this.max[v])return!1;return!0}intersectsAabbXY(p){return!(this.min[0]>p.max[0]||p.min[0]>this.max[0]||this.min[1]>p.max[1]||p.min[1]>this.max[1])}encapsulate(p){for(let v=0;v<3;v++)this.min[v]=Math.min(this.min[v],p.min[v]),this.max[v]=Math.max(this.max[v],p.max[v])}encapsulatePoint(p){for(let v=0;v<3;v++)this.min[v]=Math.min(this.min[v],p[v]),this.max[v]=Math.max(this.max[v],p[v])}closestPoint(p){return[Math.max(Math.min(this.max[0],p[0]),this.min[0]),Math.max(Math.min(this.max[1],p[1]),this.min[1]),Math.max(Math.min(this.max[2],p[2]),this.min[2])]}}pr(sl,"Aabb");class dv{constructor(p,v){this.feature=p,this.metersToTile=v,this.index=0}get(){const p=this.feature.vertices[this.index],v=this.feature.vertexProps[this.index].dir,S=v[1],E=-v[0],R=(p.extent+1)*this.metersToTile;return[new sn(Math.trunc(p.position[0]+S*R),Math.trunc(p.position[1]+E*R)),new sn(Math.trunc(p.position[0]-S*R),Math.trunc(p.position[1]-E*R))]}next(){this.index++}valid(){return this.index{return q.a0?xe(K,K,1/J):ne(K,0,0,1)}getSafeArea(){return this.safeArea}isTunnel(){return this.heightRange.max<=-5}getClosestEdge(p){if(this.edges.length===0)return;let v=0,S=Number.POSITIVE_INFINITY,E=0;const[R,F,q,K,J,le,fe]=this._tmpVec2;Ys(fe,p.x,p.y);const ye=new Ru(fe,null);for(let Te=0;Te0?en(K,q)/wt:0,Lt=it(Tt,0,1),fs=Math.abs((Tt-Lt)*this.edgeProps[Te].len);Ds(J,fe,Qe),Ys(le,Ue[1],-Ue[0]);const Jt=fs+Math.abs(en(J,le));Jt=0;--F){const q=this.edges[F].a,K=this.edges[F].b,{position:J,height:le,extent:fe}=this.vertices[q],{position:ye,height:Te,extent:Pe}=this.vertices[K],Ue=this.vertexProps[q].dir,Qe=this.vertexProps[K].dir;if(ne(v,J[0]/p,J[1]/p,le),ne(S,ye[0]/p,ye[1]/p,Te),ne(E,Ue[1],-Ue[0],0),xe(E,E,fe),ne(R,Qe[1],-Qe[0],0),xe(R,R,Pe),this.distSqLines(te(v[0]+.5*E[0],v[1]+.5*E[1],v[2]+.5*E[2]),te(S[0]-.5*R[0],S[1]-.5*R[1],S[2]-.5*R[2]),te(v[0]-.5*E[0],v[1]-.5*E[1],v[2]-.5*E[2]),te(S[0]+.5*R[0],S[1]+.5*R[1],S[2]+.5*R[2]))<=.0025000000000000005)continue;const at=this.vertices.length,pt=It(Nt(),J,ye);this.vertices.push({position:As(pt,pt,.5),height:.5*(le+Te),extent:.5*(fe+Pe)});const dt=It(Nt(),Ue,Qe);this.vertexProps.push({dir:Rs(dt,dt)}),this.edges.splice(F,1),this.edgeProps.splice(F,1),this.edges.push({a:q,b:at}),this.edges.push({a:at,b:K});const wt=Ds(Nt(),this.vertices[at].position,J),Tt=Hs(wt),Lt={vec:wt,dir:As(Nt(),wt,1/Tt),len:Tt};this.edgeProps.push(Lt),this.edgeProps.push(Lt)}}distSqLines(p,v,S,E){const R=ue(W(),v,p),F=ue(W(),E,S),q=ue(W(),p,S),K=Re(R,R),J=Re(R,F),le=Re(R,q),fe=Re(F,F),ye=Re(F,q),Te=K*fe-J*J;if(Te===0)return be(Ne(R,S,E,Re(q,F)/Re(F,F)),p);const Pe=(K*ye-J*le)/Te;return be(Ne(R,p,v,(J*ye-le*fe)/Te),Ne(F,S,E,Pe))}}class Ql{static parseFrom(p,v){const S=vl.parse(p);if(!S)return[];let{vertices:E,features:R}=S;const F=1/In(v);R.sort((le,fe)=>le.id-fe.id),E.sort((le,fe)=>le.id-fe.id||le.idx-fe.idx),E=E.filter((le,fe,ye)=>fe===ye.findIndex(Te=>Te.id===le.id&&Te.idx===le.idx));const q=new Array;let K=0;const J=E.length;for(const le of R){if(le.constantHeight){q.push(new uv(le.id,le.bounds,le.constantHeight));continue}for(;K!==J&&E[K].idE.id===S)}}class uc{constructor(p,v){this.zScale=1,this.xOffset=0,this.yOffset=0,p.equals(v)||(this.zScale=Math.pow(2,v.z-p.z),this.xOffset=(p.x*this.zScale-v.x)*sr,this.yOffset=(p.y*this.zScale-v.y)*sr)}constantElevation(p,v){if(p.constantHeight!=null)return this.computeBiasedHeight(p.constantHeight,v)}pointElevation(p,v,S){const E=this.constantElevation(v,S);return E??(p.x=p.x*this.zScale+this.xOffset,p.y=p.y*this.zScale+this.yOffset,this.computeBiasedHeight(v.pointElevation(p),S))}computeBiasedHeight(p,v){return v<=0?p:p+v*ft(0,v,p>=0?p:Math.abs(.5*p))}}pr(uv,"ElevationFeature");class cl{constructor(p){this.zoom=p.zoom,this.overscaling=p.overscaling,this.layers=p.layers,this.layerIds=this.layers.map(v=>v.fqid),this.index=p.index,this.hasPattern=!1,this.projection=p.projection,this.layoutVertexArray=new Mi,this.indexArray=new Zd,this.segments=new Ul,this.programConfigurations=new et(p.layers,{zoom:p.zoom,lut:p.lut}),this.stateDependentLayerIds=this.layers.filter(v=>v.isStateDependent()).map(v=>v.id),this.elevationMode=this.layers[0].layout.get("circle-elevation-reference"),this.hasElevation=!1,this.elevationMode!=="none"&&(this.elevatedLayoutVertexArray=new rl),this.worldview=p.worldview,this.hasAppearances=null}updateFootprints(p,v){}updateAppearances(p,v,S,E){return{hasLayoutChanges:!1,hasUboChanges:!1}}populate(p,v,S,E){const R=this.layers[0],F=[];let q=null;R.type==="circle"&&(q=R.layout.get("circle-sort-key"));for(const{feature:J,id:le,index:fe,sourceLayerIndex:ye}of p){const Te=this.layers[0]._featureFilter.needGeometry,Pe=Pi(J,Te);if(!this.layers[0]._featureFilter.filter(new xi(this.zoom,{worldview:this.worldview,activeFloors:v.activeFloors}),Pe,S))continue;const Ue=q?q.evaluate(Pe,{},S):void 0,Qe={id:le,properties:J.properties,type:J.type,sourceLayerIndex:ye,index:fe,geometry:Te?Pe.geometry:Ea(J,S,E),patterns:{},sortKey:Ue};F.push(Qe)}q&&F.sort((J,le)=>J.sortKey-le.sortKey);let K=null;E.projection.name==="globe"&&(this.globeExtVertexArray=new vO,K=E.projection);for(const J of F){const{geometry:le,index:fe,sourceLayerIndex:ye}=J,Te=p[fe].feature;this.addFeature(J,le,fe,v.availableImages,S,K,v.brightness,v.elevationFeatures),v.featureIndex.insert(Te,le,fe,ye,this.index)}this.hasElevation||(this.elevatedLayoutVertexArray=void 0)}update(p,v,S,E,R,F,q){this.programConfigurations.updatePaintArrays(p,v,R,S,E,F,q,this.worldview)}isEmpty(){return this.layoutVertexArray.length===0}uploadPending(){return!this.uploaded||this.programConfigurations.needsUpload}upload(p){this.uploaded||(this.layoutVertexBuffer=p.createVertexBuffer(this.layoutVertexArray,YJ.members),this.indexBuffer=p.createIndexBuffer(this.indexArray),this.globeExtVertexArray&&(this.globeExtVertexBuffer=p.createVertexBuffer(this.globeExtVertexArray,VAe.members)),this.elevatedLayoutVertexArray&&(this.elevatedLayoutVertexBuffer=p.createVertexBuffer(this.elevatedLayoutVertexArray,qAe.members))),this.programConfigurations.upload(p),this.uploaded=!0}destroy(){this.layoutVertexBuffer&&(this.layoutVertexBuffer.destroy(),this.indexBuffer.destroy(),this.programConfigurations.destroy(),this.segments.destroy(),this.globeExtVertexBuffer&&this.globeExtVertexBuffer.destroy(),this.elevatedLayoutVertexBuffer&&this.elevatedLayoutVertexBuffer.destroy())}addFeature(p,v,S,E,R,F,q,K){let J;this.elevationMode!=="none"&&(J=Ql.getElevationFeature(p,K));for(const le of v)for(const fe of le){const ye=fe.x,Te=fe.y;if(ye<0||ye>=sr||Te<0||Te>=sr)continue;if(F){const Qe=F.projectTilePoint(ye,Te,R),at=F.upVector(R,ye,Te);this.addGlobeExtVertex(Qe,at),this.addGlobeExtVertex(Qe,at),this.addGlobeExtVertex(Qe,at),this.addGlobeExtVertex(Qe,at)}const Pe=this.segments.prepareSegment(4,this.layoutVertexArray,this.indexArray,p.sortKey),Ue=Pe.vertexLength;if(this.addCircleVertex(ye,Te,-1,-1),this.addCircleVertex(ye,Te,1,-1),this.addCircleVertex(ye,Te,1,1),this.addCircleVertex(ye,Te,-1,1),this.elevationMode!=="none"){const Qe=J?J.pointElevation(new sn(ye,Te)):0;this.hasElevation=this.hasElevation||Qe!==0;for(let at=0;at<4;at++)this.elevatedLayoutVertexArray.emplaceBack(Qe)}this.indexArray.emplaceBack(Ue,Ue+1,Ue+2),this.indexArray.emplaceBack(Ue,Ue+2,Ue+3),Pe.vertexLength+=4,Pe.primitiveLength+=2}this.programConfigurations.populatePaintArrays(this.layoutVertexArray.length,p,S,{},E,R,q,void 0,this.worldview)}addCircleVertex(p,v,S,E){this.layoutVertexArray.emplaceBack(2*p+(S+1)/2,2*v+(E+1)/2)}addGlobeExtVertex(p,v){this.globeExtVertexArray.emplaceBack(p.x,p.y,p.z,v[0]*16384,v[1]*16384,v[2]*16384)}}function gu(j,p){for(let v=0;v1){if(qN(j,p))return!0;for(let S=0;S1?v:v.sub(p)._mult(E)._add(p))}function nC(j,p){let v,S,E,R=!1;for(let F=0;Fp.y!=E.y>p.y&&p.x<(E.x-S.x)*(p.y-S.y)/(E.y-S.y)+S.x&&(R=!R)}return R}function y0(j,p){let v=!1;for(let S=0,E=j.length-1;Sp.y!=F.y>p.y&&p.x<(F.x-R.x)*(p.y-R.y)/(F.y-R.y)+R.x&&(v=!v)}return v}function VN(j,p,v,S,E){for(const F of j)if(p<=F.x&&v<=F.y&&S>=F.x&&E>=F.y)return!0;const R=[new sn(p,v),new sn(p,E),new sn(S,E),new sn(S,v)];if(j.length>2){for(const F of R)if(y0(j,F))return!0}for(let F=0;FE.x&&p.x>E.x||j.yE.y&&p.y>E.y)return!1;const R=qr(j,p,v[0]);return R!==qr(j,p,v[1])||R!==qr(j,p,v[2])||R!==qr(j,p,v[3])}function GN(j,p,v,S,E,R){let F=p.y-j.y,q=j.x-p.x;if(R=R||0){const K=F*F+q*q;if(K===0)return!0;const J=Math.sqrt(K);F/=J,q/=J}return!((v.x-j.x)*F+(v.y-j.y)*q-R<0||(S.x-j.x)*F+(S.y-j.y)*q-R<0||(E.x-j.x)*F+(E.y-j.y)*q-R<0)}function AO(j,p,v,S,E,R,F){return!(GN(j,p,S,E,R,F)||GN(p,v,S,E,R,F)||GN(v,j,S,E,R,F)||GN(S,E,j,p,v,F)||GN(E,R,j,p,v,F)||GN(R,S,j,p,v,F))}function rC(j,p,v){const S=p.paint.get(j).value;return S.kind==="constant"?S.value:v.programConfigurations.get(p.id).getMaxValue(j)}function ZJ(j){return Math.sqrt(j[0]*j[0]+j[1]*j[1])}function WKe(j,p,v,S,E){if(!p[0]&&!p[1])return j;const R=sn.convert(p)._mult(E);v==="viewport"&&R._rotate(-S);const F=[];for(let q=0;q>v&&p.y===this.y>>v}url(p,v){const S=function(R,F,q){const K=2**q,J=2*Math.PI*6378137,le=J*(R/K-.5),fe=J*(.5-(F+1)/K);return`${le},${fe},${le+J/K},${fe+J/K}`}(this.x,this.y,this.z),E=function(R,F,q){let K,J="";for(let le=R;le>0;le--)K=1<this.canonical.z?new wx(p,this.wrap,this.canonical.z,this.canonical.x,this.canonical.y):new wx(p,this.wrap,p,this.canonical.x>>v,this.canonical.y>>v)}calculateScaledKey(p,v=!0){if(this.overscaledZ===p&&v)return this.key;if(p>this.canonical.z)return TO(this.wrap*+v,p,this.canonical.z,this.canonical.x,this.canonical.y);{const S=this.canonical.z-p;return TO(this.wrap*+v,p,p,this.canonical.x>>S,this.canonical.y>>S)}}isChildOf(p){if(p.wrap!==this.wrap)return!1;const v=this.canonical.z-p.canonical.z;return p.overscaledZ===0||p.overscaledZ>v&&p.canonical.y===this.canonical.y>>v}children(p){if(this.overscaledZ>=p)return[new wx(this.overscaledZ+1,this.wrap,this.canonical.z,this.canonical.x,this.canonical.y)];const v=this.canonical.z+1,S=2*this.canonical.x,E=2*this.canonical.y;return[new wx(v,this.wrap,v,S,E),new wx(v,this.wrap,v,S+1,E),new wx(v,this.wrap,v,S,E+1),new wx(v,this.wrap,v,S+1,E+1)]}isLessThan(p){return this.wrapp.wrap)&&(this.overscaledZp.overscaledZ)&&(this.canonical.xp.canonical.x)&&this.canonical.y{let p=j.canonical.x-1,v=j.wrap;return p<0&&(p=(1<{let p=j.canonical.x+1,v=j.wrap;return p===1<new wx(j.overscaledZ,j.wrap,j.canonical.z,j.canonical.x,(j.canonical.y===0?1<new wx(j.overscaledZ,j.wrap,j.canonical.z,j.canonical.x,j.canonical.y===(1<1?null:function(S,E,R,F){const q=Math.sin(R);return S*(Math.sin((1-F)*R)/q)+E*(Math.sin(F*R)/q)}(j.a[p],j.b[p],j.angle,it(v,0,1))+j.center[p]}function WN(j){if(j.z<=1)return I$t[j.z+2*j.y+j.x];const p=XAe(JJ(j));return sl.fromPoints(p)}function wS(j,p,v){return xe(j,j,1-v),ve(j,j,p,v)}function eYe(j,p){const v=jS(p.zoom);if(v===0)return WN(j);const S=JJ(j),E=XAe(S),R=An(S.getWest())*p.worldSize,F=An(S.getEast())*p.worldSize,q=On(S.getNorth())*p.worldSize,K=On(S.getSouth())*p.worldSize,J=[R,q,0],le=[F,q,0],fe=[R,K,0],ye=[F,K,0],Te=_([],p.globeMatrix);return Ge(J,J,Te),Ge(le,le,Te),Ge(fe,fe,Te),Ge(ye,ye,Te),E[0]=wS(E[0],fe,v),E[1]=wS(E[1],ye,v),E[2]=wS(E[2],le,v),E[3]=wS(E[3],J,v),sl.fromPoints(E)}function tYe(j,p,v){for(const S of j)Ge(S,S,p),xe(S,S,v)}function sYe(j,p,v,S){const E=p/j.worldSize,R=j.globeMatrix;if(v.z<=1){const ps=WN(v).getCorners();return tYe(ps,R,E),sl.fromPoints(ps)}const F=JJ(v,S),q=XAe(F,Ft+QJ(j._tileCoverLift));tYe(q,R,E);const K=Number.MAX_VALUE,J=[-K,-K,-K],le=[K,K,K];if(F.contains(j.center)){for(const is of q)ae(le,le,is),he(J,J,is);J[2]=0;const ps=j.point,rs=[ps.x*E,ps.y*E,0];return ae(le,le,rs),he(J,J,rs),new sl(le,J)}if(j._tileCoverLift>0){for(const ps of q)ae(le,le,ps),he(J,J,ps);return new sl(le,J)}const fe=[R[12]*E,R[13]*E,R[14]*E],ye=F.getCenter(),Te=it(j.center.lat,-85.051129,vn),Pe=it(ye.lat,-85.051129,vn),Ue=An(j.center.lng),Qe=On(Te);let at=Ue-An(ye.lng);const pt=Qe-On(Pe);at>.5?at-=1:at<-.5&&(at+=1);let dt=0;Math.abs(at)>Math.abs(pt)?dt=at>=0?1:3:(dt=pt>=0?0:2,ve(fe,fe,[R[4]*E,R[5]*E,R[6]*E],-Math.sin(Nr(pt>=0?F.getSouth():F.getNorth()))*Ft));const wt=q[dt],Tt=q[(dt+1)%4],Lt=new D$t(wt,Tt,fe),fs=[ZAe(Lt,0)||wt[0],ZAe(Lt,1)||wt[1],ZAe(Lt,2)||wt[2]],Jt=jS(j.zoom);if(Jt>0){const ps=function({x:is,y:dn,z:fn},_n,Sn,wn,Un){const ln=1/(1<.5?zr=-1:yr<-.5&&(zr=1),Nn=((Nn+zr)*_n-(wn*=_n))*Sn+wn,Tn=((Tn+zr)*_n-wn)*Sn+wn,Vn=(Vn*_n-(Un*=_n))*Sn+Un,ar=(ar*_n-Un)*Sn+Un,[[Nn,ar,0],[Tn,ar,0],[Tn,Vn,0],[Nn,Vn,0]]}(v,p,j._pixelsPerMercatorPixel,Ue,Qe);for(let is=0;isMath.PI/2*1.01}const oYe=Nr(85),R$t=Math.cos(oYe),O$t=Math.sin(oYe),F$t=g(),lYe=j=>{const p=[];return j.paint.get("circle-pitch-alignment")==="map"&&p.push("PITCH_WITH_MAP"),j.paint.get("circle-pitch-scale")==="map"&&p.push("SCALE_WITH_MAP"),p};function cYe(j,p,v,S,E,R,F,q,K){if(R&&j.queryGeometry.isAboveHorizon)return!1;R&&(K*=j.pixelToTileUnitsFactor);const J=j.tileID.canonical,le=v.projection.upVectorScale(J,v.center.lat,v.worldSize).metersToTile;for(const fe of p)for(const ye of fe){const Te=ye.add(q),Pe=E&&v.elevation?v.elevation.exaggeration()*E.getElevationAt(Te.x,Te.y,!0):0,Ue=v.projection.projectTilePoint(Te.x,Te.y,J);if(Pe>0){const dt=v.projection.upVector(J,Te.x,Te.y);Ue.x+=dt[0]*le*Pe,Ue.y+=dt[1]*le*Pe,Ue.z+=dt[2]*le*Pe}const Qe=R?Te:z$t(Ue.x,Ue.y,Ue.z,S),at=R?j.tilespaceRays.map(dt=>$$t(dt,Pe)):j.queryGeometry.screenGeometry,pt=ht([],[Ue.x,Ue.y,Ue.z,1],S);if(!F&&R?K*=pt[3]/v.cameraToCenterDistance:F&&!R&&(K*=v.cameraToCenterDistance/pt[3]),R){const dt=cn((ye.y/sr+J.y)/(1<j.width||E.height>j.height||v.x>j.width-E.width||v.y>j.height-E.height)throw new RangeError("out of range source coordinates for image copy");if(E.width>p.width||E.height>p.height||S.x>p.width-E.width||S.y>p.height-E.height)throw new RangeError("out of range destination coordinates for image copy");const K=j.data,J=p.data,le=R===4&&q;for(let fe=0;fe{p[j.evaluationKey]=K;const J=j.expression.evaluate(p),le=J?J.toNonPremultipliedRenderColor(null):null;le&&(E.data[F+q+0]=Math.floor(255*le.r),E.data[F+q+1]=Math.floor(255*le.g),E.data[F+q+2]=Math.floor(255*le.b),E.data[F+q+3]=Math.floor(255*le.a))};if(j.clips)for(let F=0,q=0;F80*v){q=j[0],K=j[1];let le=q,fe=K;for(let ye=v;yele&&(le=Te),Pe>fe&&(fe=Pe)}J=Math.max(le-q,fe-K),J=J!==0?32767/J:0}return Aq(R,F,v,q,K,J,0),F}function vYe(j,p,v,S,E){let R;if(E===function(F,q,K,J){let le=0;for(let fe=q,ye=K-J;fe0)for(let F=p;F=p;F-=S)R=jYe(F/S|0,j[F],j[F+1],R);return R&&MO(R,R.next)&&(Mq(R),R=R.next),R}function N6(j,p){if(!j)return j;p||(p=j);let v,S=j;do if(v=!1,S.steiner||!MO(S,S.next)&&op(S.prev,S,S.next)!==0)S=S.next;else{if(Mq(S),S=p=S.prev,S===S.next)break;v=!0}while(v||S!==p);return p}function Aq(j,p,v,S,E,R,F){if(!j)return;!F&&R&&function(K,J,le,fe){let ye=K;do ye.z===0&&(ye.z=sTe(ye.x,ye.y,J,le,fe)),ye.prevZ=ye.prev,ye.nextZ=ye.next,ye=ye.next;while(ye!==K);ye.prevZ.nextZ=null,ye.prevZ=null,function(Te){let Pe,Ue=1;do{let Qe,at=Te;Te=null;let pt=null;for(Pe=0;at;){Pe++;let dt=at,wt=0;for(let Lt=0;Lt0||Tt>0&&dt;)wt!==0&&(Tt===0||!dt||at.z<=dt.z)?(Qe=at,at=at.nextZ,wt--):(Qe=dt,dt=dt.nextZ,Tt--),pt?pt.nextZ=Qe:Te=Qe,Qe.prevZ=pt,pt=Qe;at=dt}pt.nextZ=null,Ue*=2}while(Pe>1)}(ye)}(j,S,E,R);let q=j;for(;j.prev!==j.next;){const K=j.prev,J=j.next;if(R?W$t(j,S,E,R):G$t(j))p.push(K.i,j.i,J.i),Mq(j),j=J.next,q=J.next;else if((j=J)===q){F?F===1?Aq(j=K$t(N6(j),p),p,v,S,E,R,2):F===2&&Y$t(j,p,v,S,E,R):Aq(N6(j),p,v,S,E,R,1);break}}}function G$t(j){const p=j.prev,v=j,S=j.next;if(op(p,v,S)>=0)return!1;const E=p.x,R=v.x,F=S.x,q=p.y,K=v.y,J=S.y,le=Math.min(E,R,F),fe=Math.min(q,K,J),ye=Math.max(E,R,F),Te=Math.max(q,K,J);let Pe=S.next;for(;Pe!==p;){if(Pe.x>=le&&Pe.x<=ye&&Pe.y>=fe&&Pe.y<=Te&&Tq(E,q,R,K,F,J,Pe.x,Pe.y)&&op(Pe.prev,Pe,Pe.next)>=0)return!1;Pe=Pe.next}return!0}function W$t(j,p,v,S){const E=j.prev,R=j,F=j.next;if(op(E,R,F)>=0)return!1;const q=E.x,K=R.x,J=F.x,le=E.y,fe=R.y,ye=F.y,Te=Math.min(q,K,J),Pe=Math.min(le,fe,ye),Ue=Math.max(q,K,J),Qe=Math.max(le,fe,ye),at=sTe(Te,Pe,p,v,S),pt=sTe(Ue,Qe,p,v,S);let dt=j.prevZ,wt=j.nextZ;for(;dt&&dt.z>=at&&wt&&wt.z<=pt;){if(dt.x>=Te&&dt.x<=Ue&&dt.y>=Pe&&dt.y<=Qe&&dt!==E&&dt!==F&&Tq(q,le,K,fe,J,ye,dt.x,dt.y)&&op(dt.prev,dt,dt.next)>=0||(dt=dt.prevZ,wt.x>=Te&&wt.x<=Ue&&wt.y>=Pe&&wt.y<=Qe&&wt!==E&&wt!==F&&Tq(q,le,K,fe,J,ye,wt.x,wt.y)&&op(wt.prev,wt,wt.next)>=0))return!1;wt=wt.nextZ}for(;dt&&dt.z>=at;){if(dt.x>=Te&&dt.x<=Ue&&dt.y>=Pe&&dt.y<=Qe&&dt!==E&&dt!==F&&Tq(q,le,K,fe,J,ye,dt.x,dt.y)&&op(dt.prev,dt,dt.next)>=0)return!1;dt=dt.prevZ}for(;wt&&wt.z<=pt;){if(wt.x>=Te&&wt.x<=Ue&&wt.y>=Pe&&wt.y<=Qe&&wt!==E&&wt!==F&&Tq(q,le,K,fe,J,ye,wt.x,wt.y)&&op(wt.prev,wt,wt.next)>=0)return!1;wt=wt.nextZ}return!0}function K$t(j,p){let v=j;do{const S=v.prev,E=v.next.next;!MO(S,E)&&_Ye(S,v,v.next,E)&&Eq(S,E)&&Eq(E,S)&&(p.push(S.i,v.i,E.i),Mq(v),Mq(v.next),v=j=E),v=v.next}while(v!==j);return N6(v)}function Y$t(j,p,v,S,E,R){let F=j;do{let q=F.next.next;for(;q!==F.prev;){if(F.i!==q.i&&eUt(F,q)){let K=wYe(F,q);return F=N6(F,F.next),K=N6(K,K.next),Aq(F,p,v,S,E,R,0),void Aq(K,p,v,S,E,R,0)}q=q.next}F=F.next}while(F!==j)}function Z$t(j,p){let v=j.x-p.x;return v===0&&(v=j.y-p.y,v===0)&&(v=(j.next.y-j.y)/(j.next.x-j.x)-(p.next.y-p.y)/(p.next.x-p.x)),v}function X$t(j,p){const v=function(E,R){let F=R;const q=E.x,K=E.y;let J,le=-1/0;if(MO(E,F))return F;do{if(MO(E,F.next))return F.next;if(K<=F.y&&K>=F.next.y&&F.next.y!==F.y){const Ue=F.x+(K-F.y)*(F.next.x-F.x)/(F.next.y-F.y);if(Ue<=q&&Ue>le&&(le=Ue,J=F.x=F.x&&F.x>=ye&&q!==F.x&&bYe(KJ.x||F.x===J.x&&Q$t(J,F)))&&(J=F,Pe=Ue)}F=F.next}while(F!==fe);return J}(j,p);if(!v)return p;const S=wYe(v,j);return N6(S,S.next),N6(v,v.next)}function Q$t(j,p){return op(j.prev,j,p.prev)<0&&op(p.next,j,j.next)<0}function sTe(j,p,v,S,E){return(j=1431655765&((j=858993459&((j=252645135&((j=16711935&((j=(j-v)*E|0)|j<<8))|j<<4))|j<<2))|j<<1))|(p=1431655765&((p=858993459&((p=252645135&((p=16711935&((p=(p-S)*E|0)|p<<8))|p<<4))|p<<2))|p<<1))<<1}function J$t(j){let p=j,v=j;do(p.x=(j-F)*(R-q)&&(j-F)*(S-q)>=(v-F)*(p-q)&&(v-F)*(R-q)>=(E-F)*(S-q)}function Tq(j,p,v,S,E,R,F,q){return!(j===F&&p===q)&&bYe(j,p,v,S,E,R,F,q)}function eUt(j,p){return j.next.i!==p.i&&j.prev.i!==p.i&&!function(v,S){let E=v;do{if(E.i!==v.i&&E.next.i!==v.i&&E.i!==S.i&&E.next.i!==S.i&&_Ye(E,E.next,v,S))return!0;E=E.next}while(E!==v);return!1}(j,p)&&(Eq(j,p)&&Eq(p,j)&&function(v,S){let E=v,R=!1;const F=(v.x+S.x)/2,q=(v.y+S.y)/2;do E.y>q!=E.next.y>q&&E.next.y!==E.y&&F<(E.next.x-E.x)*(q-E.y)/(E.next.y-E.y)+E.x&&(R=!R),E=E.next;while(E!==v);return R}(j,p)&&(op(j.prev,j,p.prev)||op(j,p.prev,p))||MO(j,p)&&op(j.prev,j,j.next)>0&&op(p.prev,p,p.next)>0)}function op(j,p,v){return(p.y-j.y)*(v.x-p.x)-(p.x-j.x)*(v.y-p.y)}function MO(j,p){return j.x===p.x&&j.y===p.y}function _Ye(j,p,v,S){const E=see(op(j,p,v)),R=see(op(j,p,S)),F=see(op(v,S,j)),q=see(op(v,S,p));return E!==R&&F!==q||!(E!==0||!tee(j,v,p))||!(R!==0||!tee(j,S,p))||!(F!==0||!tee(v,j,S))||!(q!==0||!tee(v,p,S))}function tee(j,p,v){return p.x<=Math.max(j.x,v.x)&&p.x>=Math.min(j.x,v.x)&&p.y<=Math.max(j.y,v.y)&&p.y>=Math.min(j.y,v.y)}function see(j){return j>0?1:j<0?-1:0}function Eq(j,p){return op(j.prev,j,j.next)<0?op(j,p,j.next)>=0&&op(j,j.prev,p)>=0:op(j,p,j.prev)<0||op(j,j.next,p)<0}function wYe(j,p){const v=nTe(j.i,j.x,j.y),S=nTe(p.i,p.x,p.y),E=j.next,R=p.prev;return j.next=p,p.prev=j,v.next=E,E.prev=v,S.next=v,v.prev=S,R.next=S,S.prev=R,S}function jYe(j,p,v,S){const E=nTe(j,p,v);return S?(E.next=S.next,E.prev=S,S.next.prev=E,S.next=E):(E.prev=E,E.next=E),E}function Mq(j){j.next.prev=j.prev,j.prev.next=j.next,j.prevZ&&(j.prevZ.nextZ=j.nextZ),j.nextZ&&(j.nextZ.prevZ=j.prevZ)}function nTe(j,p,v){return{i:j,x:p,y:v,prev:null,next:null,z:0,prevZ:null,nextZ:null,steiner:!1}}function Lq(j,p){const v=j.length;if(v<=1)return[j];const S=[];let E,R;for(let F=0;F1)for(let F=0;F=sr&&v>=sr}static evaluate(p){if(p.length===0)return new NS;let v=[];for(const K of p)v.push(...K.portals);if(v.length===0)return new NS;for(const K of v){const J=K.va,le=K.vb;(NS.isOnBorder(J.x,le.x)||NS.isOnBorder(J.y,le.y))&&(K.type="border")}const S=v.filter(K=>K.type!=="unevaluated"),E=v.filter(K=>K.type==="unevaluated");if(E.length===0)return new NS;E.sort((K,J)=>K.hash===J.hash?K.isTunnel===J.isTunnel?0:K.isTunnel?-1:1:K.hashK.hashR!=="fill-tunnel-structure-color"),this.tunnelProgramConfigurations=new et(v,{zoom:S,lut:E},R=>R!=="fill-bridge-guard-rail-color")}addVertices(p,v){const S=this.unevalVertices.length;for(let E=0;E=R.min.x&&fe.x<=R.max.x&&fe.y>=R.min.y&&fe.y<=R.max.y||ye.x>=R.min.x&&ye.x<=R.max.x&&ye.y>=R.min.y&&ye.y<=R.max.y||HN(fe,ye,q))||this.isOnBorder(fe.x,ye.x)||this.isOnBorder(fe.y,ye.y))continue;const Te=hv.computeEdgeHash(this.unevalVertices[J],this.unevalVertices[le]);let Pe,Ue=this.vertexHashLookup.get(hv.computePosHash(fe));Ue!=null?Pe=Ue.next:(Ue=this.vertexHashLookup.get(hv.computePosHash(ye)),Pe=Ue!=null?Ue.prev:Te),this.unevalEdges.push({polygonIdx:p,a:J,b:le,hash:Te,portalHash:Pe,isTunnel:E,type:"unevaluated",featureInfo:F})}}addPortalCandidates(p,v,S,E,R){if(v.length!==0){this.vertexHashLookup.clear();for(const F of v){if(F.length===0)continue;const q=F[0];let K=hv.computeEdgeHash(q[q.length-2],q[q.length-1]);for(let J=0;J({vertexOffset:0,primitiveOffset:this.indexArray.length}),S=ye=>{ye.primitiveLength=this.indexArray.length-ye.primitiveOffset},E=new sUt(this.vertexPositions,this.vertexNormals,this.indexArray);this.prepareEdges(p.portals,this.unevalEdges);const R=v(),F=v(),q=v(),K=(ye,Te)=>{ye.sort((Ue,Qe)=>Ue.type===Te&&Qe.type!==Te?-1:Ue.type!==Te&&Qe.type===Te?1:0);const Pe=ye.findIndex(Ue=>Ue.type!==Te);return Pe>=0?Pe:ye.length};let J=0;this.unevalEdges.length>0&&(J=K(this.unevalEdges,"none"),this.constructBridgeStructures(E,this.unevalVertices,this.unevalHeights,this.unevalEdges,{min:0,max:J},this.tileToMeters)),S(q);const le=v(),fe=v();if(this.unevalEdges.length>0){const ye=this.unevalEdges.splice(J),Te=K(ye,"tunnel")+J;this.unevalEdges.push(...ye),this.constructTunnelStructures(E,this.unevalVertices,this.unevalHeights,this.unevalEdges,{min:0,max:J},{min:J,max:Te})}S(le),E.addTriangles(this.unevalTriangles,this.unevalVertices,this.unevalHeights),S(fe),E.addTriangles(this.unevalTunnelTriangles,this.unevalVertices,this.unevalHeights),S(F),E.addTriangles(this.unevalTunnelTriangles,this.unevalVertices,[-.1]),S(R),this.maskSegments=Ul.simpleSegment(0,fe.primitiveOffset,0,fe.primitiveLength),this.depthSegments=Ul.simpleSegment(0,F.primitiveOffset,0,F.primitiveLength),this.renderableBridgeSegments=Ul.simpleSegment(0,q.primitiveOffset,0,q.primitiveLength),this.renderableTunnelSegments=Ul.simpleSegment(0,le.primitiveOffset,0,le.primitiveLength),this.shadowCasterSegments=Ul.simpleSegment(0,R.primitiveOffset,0,R.primitiveLength)}update(p,v,S,E,R,F,q,K){this.bridgeProgramConfigurations.updatePaintArrays(p,v,R,S,E,F,q,K),this.tunnelProgramConfigurations.updatePaintArrays(p,v,R,S,E,F,q,K)}upload(p){this.vertexBuffer||this.vertexPositions.length===0||this.vertexNormals.length===0||this.indexArray.length===0||(this.vertexBuffer=p.createVertexBuffer(this.vertexPositions,V$t.members),this.vertexBufferNormal=p.createVertexBuffer(this.vertexNormals,H$t.members),this.indexBuffer=p.createIndexBuffer(this.indexArray),this.bridgeProgramConfigurations.upload(p),this.tunnelProgramConfigurations.upload(p))}destroy(){this.vertexBuffer&&(this.vertexBuffer.destroy(),this.vertexBufferNormal.destroy(),this.indexBuffer.destroy()),this.maskSegments&&(this.maskSegments.destroy(),this.depthSegments.destroy(),this.renderableBridgeSegments.destroy(),this.renderableTunnelSegments.destroy(),this.shadowCasterSegments.destroy()),this.bridgeProgramConfigurations.destroy(),this.tunnelProgramConfigurations.destroy()}populatePaintArrays(p,v,S,E,R){const F=(q,K)=>{for(let J=0;Jne(Sn,v[wn].x,v[wn].y,S[wn]*K),fe=W(),ye=W(),Te=W(),Pe=W(),Ue=W(),Qe=(Sn,wn)=>{const Un=q.get(hv.computePosHash(v[wn])),ln=Un.from,Nn=Un.to;if(!ln||!Nn)return;le(fe,ln),le(ye,wn),le(Te,Nn),Ae(Pe),Xe(fe,ye)||($e(Ue,ye,fe),Me(Pe,Ue)),Xe(Te,ye)||($e(Ue,Te,ye),me(Pe,Pe,Me(Ue,Ue)));const Tn=Je(Pe);return Tn>0?xe(Sn,Pe,1/Tn):void 0};let at=Number.POSITIVE_INFINITY;this.sortSubarray(E,R.min,R.max,(Sn,wn)=>Sn.featureInfo.featureIndex-wn.featureInfo.featureIndex);const pt=W(),dt=W(),wt=W(),Tt=W(),Lt=W(),fs=W(),Jt=W(),ps=W(),rs=W(),is=[W(),W(),W(),W()],dn=[W(),W(),W(),W()],fn=[{coord:new sn(0,0),height:0},{coord:new sn(0,0),height:0}],_n=(Sn,wn)=>Sn>wn;for(let Sn=R.min;Snat.featureInfo.featureIndex-pt.featureInfo.featureIndex;this.sortSubarray(E,R.min,R.max,K),this.sortSubarray(E,F.min,F.max,K);const J=at=>Me(at,at),le=[{coord:new sn(0,0),height:0},{coord:new sn(0,0),height:0}],fe=(at,pt)=>atq.hash===K.hash?K.polygonIdx-q.polygonIdx:K.hash>q.hash?1:-1);let S=0,E=0,R=0,F=v[S].polygonIdx;do E++,(E===v.length||v[S].hash!==v[E].hash)&&((E-S===1||v[E-1].polygonIdx!==F)&&(RJ.portalHashle.hash?q++:le.hash>J.portalHash?K++:(J.type=le.type,q++)}}}isOnBorder(p,v){return p<=0&&v<=0||p>=sr&&v>=sr}addFeatureSection(p,v,S,E){return p!==v&&(v=p,S.push({featureIndex:p,vertexStart:E.getVertexCount()}),E.clearVertexLookup()),v}sortSubarray(p,v,S,E){const R=p.slice(v,S);R.sort(E),p.splice(v,R.length,...R)}static computeEdgeHash(p,v){return(p.y===v.y&&p.x>v.x||p.y>v.y)&&([p,v]=[v,p]),BigInt(hv.computePosHash(p))<<32n|BigInt(hv.computePosHash(v))}static computePosHash(p){return((65535&p.x)<<16|65535&p.y)>>>0}}function nUt(j,p){return j>p?1:j0))return v;v=v.left}}return null}contains(p){for(var v=this._root,S=this._compare;v;){var E=S(p,v.key);if(E===0)return!0;v=E<0?v.left:v.right}return!1}remove(p){var v=this.find(p);if(!v)return!1;if(this.splay(v),v.left)if(v.right){var S=this.minNode(v.right);S.parent!==v&&(this.replace(S,S.right),S.right=v.right,S.right.parent=S),this.replace(v,S),S.left=v.left,S.left.parent=S}else this.replace(v,v.left);else this.replace(v,v.right);return this._size--,!0}removeNode(p){if(!p)return!1;if(this.splay(p),p.left)if(p.right){var v=this.minNode(p.right);v.parent!==p&&(this.replace(v,v.right),v.right=p.right,v.right.parent=v),this.replace(p,v),v.left=p.left,v.left.parent=v}else this.replace(p,p.left);else this.replace(p,p.right);return this._size--,!0}erase(p){var v=this.find(p);if(v){this.splay(v);var S=v.left,E=v.right,R=null;S&&(S.parent=null,R=this.maxNode(S),this.splay(R),this._root=R),E&&(S?R.right=E:this._root=E,E.parent=R),this._size--}}pop(){var p=this._root,v=null;if(p){for(;p.left;)p=p.left;v={key:p.key,data:p.data},this.remove(p.key)}return v}next(p){var v=p;if(v)if(v.right)for(v=v.right;v&&v.left;)v=v.left;else for(v=p.parent;v&&v.right===p;)p=v,v=v.parent;return v}prev(p){var v=p;if(v)if(v.left)for(v=v.left;v&&v.right;)v=v.right;else for(v=p.parent;v&&v.left===p;)p=v,v=v.parent;return v}forEach(p){for(var v=this._root,S=[],E=!1,R=0;!E;)v?(S.push(v),v=v.left):S.length>0?(p(v=S.pop(),R++),v=v.right):E=!0;return this}range(p,v,S,E){const R=[],F=this._compare;let q,K=this._root;for(;R.length!==0||K;)if(K)R.push(K),K=K.left;else{if(K=R.pop(),q=F(K.key,v),q>0)break;if(F(K.key,p)>=0&&S.call(E,K))return this;K=K.right}return this}keys(){for(var p=this._root,v=[],S=[],E=!1;!E;)p?(v.push(p),p=p.left):v.length>0?(p=v.pop(),S.push(p.key),p=p.right):E=!0;return S}values(){for(var p=this._root,v=[],S=[],E=!1;!E;)p?(v.push(p),p=p.left):v.length>0?(p=v.pop(),S.push(p.data),p=p.right):E=!0;return S}at(p){for(var v=this._root,S=[],E=!1,R=0;!E;)if(v)S.push(v),v=v.left;else if(S.length>0){if(v=S.pop(),R===p)return v;R++,v=v.right}else E=!0;return null}load(p=[],v=[],S=!1){if(this._size!==0)throw new Error("bulk-load: tree is not empty");const E=p.length;return S&&lTe(p,v,0,E-1,this._compare),this._root=oTe(null,p,v,0,E),this._size=E,this}min(){var p=this.minNode(this._root);return p?p.key:null}max(){var p=this.maxNode(this._root);return p?p.key:null}isEmpty(){return this._root===null}get size(){return this._size}static createTree(p,v,S,E,R){return new iTe(S,R).load(p,v,E)}}function oTe(j,p,v,S,E){const R=E-S;if(R>0){const F=S+Math.floor(R/2),q={key:p[F],data:v[F],parent:j};return q.left=oTe(q,p,v,S,F),q.right=oTe(q,p,v,F+1,E),q}return null}function lTe(j,p,v,S,E){if(v>=S)return;const R=j[v+S>>1];let F=v-1,q=S+1;for(;;){do F++;while(E(j[F],R)<0);do q--;while(E(j[q],R)>0);if(F>=q)break;let K=j[F];j[F]=j[q],j[q]=K,K=p[F],p[F]=p[q],p[q]=K}lTe(j,p,v,q,E),lTe(j,p,q+1,S,E)}const kYe=11102230246251565e-32,fy=134217729,rUt=(3+8*kYe)*kYe;function cTe(j,p,v,S,E){let R,F,q,K,J=p[0],le=S[0],fe=0,ye=0;le>J==le>-J?(R=J,J=p[++fe]):(R=le,le=S[++ye]);let Te=0;if(feJ==le>-J?(F=J+R,q=R-(F-J),J=p[++fe]):(F=le+R,q=R-(F-le),le=S[++ye]),R=F,q!==0&&(E[Te++]=q);feJ==le>-J?(F=R+J,K=F-R,q=R-(F-K)+(J-K),J=p[++fe]):(F=R+le,K=F-R,q=R-(F-K)+(le-K),le=S[++ye]),R=F,q!==0&&(E[Te++]=q);for(;fe0:(S[0]-p[0])*(v[1]-p[1])-(v[0]-p[0])*(S[1]-p[1])>0}isAbove(p){return!this.isBelow(p)}isVertical(){return this.point[0]===this.otherEvent.point[0]}get inResult(){return this.resultTransition!==0}clone(){const p=new PO(this.point,this.left,this.otherEvent,this.isSubject,this.type);return p.contourId=this.contourId,p.resultTransition=this.resultTransition,p.prevInResult=this.prevInResult,p.isExteriorRing=this.isExteriorRing,p.inOut=this.inOut,p.otherInOut=this.otherInOut,p}}function KN(j,p){return j[0]===p[0]&&j[1]===p[1]}function dTe(j,p,v){const S=function(E,R,F,q,K,J){const le=(R-J)*(F-K),fe=(E-K)*(q-J),ye=le-fe;if(le===0||fe===0||le>0!=fe>0)return ye;const Te=Math.abs(le+fe);return Math.abs(ye)>=33306690738754716e-32*Te?ye:-function(Pe,Ue,Qe,at,pt,dt,wt){let Tt,Lt,fs,Jt,ps,rs,is,dn,fn,_n,Sn,wn,Un,ln,Nn,Tn,Vn,ar;const zr=Pe-pt,yr=Qe-pt,gr=Ue-dt,ir=at-dt;ln=zr*ir,rs=fy*zr,is=rs-(rs-zr),dn=zr-is,rs=fy*ir,fn=rs-(rs-ir),_n=ir-fn,Nn=dn*_n-(ln-is*fn-dn*fn-is*_n),Tn=gr*yr,rs=fy*gr,is=rs-(rs-gr),dn=gr-is,rs=fy*yr,fn=rs-(rs-yr),_n=yr-fn,Vn=dn*_n-(Tn-is*fn-dn*fn-is*_n),Sn=Nn-Vn,ps=Nn-Sn,LO[0]=Nn-(Sn+ps)+(ps-Vn),wn=ln+Sn,ps=wn-ln,Un=ln-(wn-ps)+(Sn-ps),Sn=Un-Tn,ps=Un-Sn,LO[1]=Un-(Sn+ps)+(ps-Tn),ar=wn+Sn,ps=ar-wn,LO[2]=wn-(ar-ps)+(Sn-ps),LO[3]=ar;let Dr=function(bo,pi){let ko=pi[0];for(let Ii=1;Ii<4;Ii++)ko+=pi[Ii];return ko}(0,LO),Zr=22204460492503146e-32*wt;if(Dr>=Zr||-Dr>=Zr||(ps=Pe-zr,Tt=Pe-(zr+ps)+(ps-pt),ps=Qe-yr,fs=Qe-(yr+ps)+(ps-pt),ps=Ue-gr,Lt=Ue-(gr+ps)+(ps-dt),ps=at-ir,Jt=at-(ir+ps)+(ps-dt),Tt===0&&Lt===0&&fs===0&&Jt===0)||(Zr=11093356479670487e-47*wt+rUt*Math.abs(Dr),Dr+=zr*Jt+ir*Tt-(gr*fs+yr*Lt),Dr>=Zr||-Dr>=Zr))return Dr;ln=Tt*ir,rs=fy*Tt,is=rs-(rs-Tt),dn=Tt-is,rs=fy*ir,fn=rs-(rs-ir),_n=ir-fn,Nn=dn*_n-(ln-is*fn-dn*fn-is*_n),Tn=Lt*yr,rs=fy*Lt,is=rs-(rs-Lt),dn=Lt-is,rs=fy*yr,fn=rs-(rs-yr),_n=yr-fn,Vn=dn*_n-(Tn-is*fn-dn*fn-is*_n),Sn=Nn-Vn,ps=Nn-Sn,mv[0]=Nn-(Sn+ps)+(ps-Vn),wn=ln+Sn,ps=wn-ln,Un=ln-(wn-ps)+(Sn-ps),Sn=Un-Tn,ps=Un-Sn,mv[1]=Un-(Sn+ps)+(ps-Tn),ar=wn+Sn,ps=ar-wn,mv[2]=wn-(ar-ps)+(Sn-ps),mv[3]=ar;const Aa=cTe(4,LO,4,mv,SYe);ln=zr*Jt,rs=fy*zr,is=rs-(rs-zr),dn=zr-is,rs=fy*Jt,fn=rs-(rs-Jt),_n=Jt-fn,Nn=dn*_n-(ln-is*fn-dn*fn-is*_n),Tn=gr*fs,rs=fy*gr,is=rs-(rs-gr),dn=gr-is,rs=fy*fs,fn=rs-(rs-fs),_n=fs-fn,Vn=dn*_n-(Tn-is*fn-dn*fn-is*_n),Sn=Nn-Vn,ps=Nn-Sn,mv[0]=Nn-(Sn+ps)+(ps-Vn),wn=ln+Sn,ps=wn-ln,Un=ln-(wn-ps)+(Sn-ps),Sn=Un-Tn,ps=Un-Sn,mv[1]=Un-(Sn+ps)+(ps-Tn),ar=wn+Sn,ps=ar-wn,mv[2]=wn-(ar-ps)+(Sn-ps),mv[3]=ar;const ma=cTe(Aa,SYe,4,mv,CYe);ln=Tt*Jt,rs=fy*Tt,is=rs-(rs-Tt),dn=Tt-is,rs=fy*Jt,fn=rs-(rs-Jt),_n=Jt-fn,Nn=dn*_n-(ln-is*fn-dn*fn-is*_n),Tn=Lt*fs,rs=fy*Lt,is=rs-(rs-Lt),dn=Lt-is,rs=fy*fs,fn=rs-(rs-fs),_n=fs-fn,Vn=dn*_n-(Tn-is*fn-dn*fn-is*_n),Sn=Nn-Vn,ps=Nn-Sn,mv[0]=Nn-(Sn+ps)+(ps-Vn),wn=ln+Sn,ps=wn-ln,Un=ln-(wn-ps)+(Sn-ps),Sn=Un-Tn,ps=Un-Sn,mv[1]=Un-(Sn+ps)+(ps-Tn),ar=wn+Sn,ps=ar-wn,mv[2]=wn-(ar-ps)+(Sn-ps),mv[3]=ar;const mi=cTe(ma,CYe,4,mv,AYe);return AYe[mi-1]}(E,R,F,q,K,J,Te)}(j[0],j[1],p[0],p[1],v[0],v[1]);return S>0?-1:S<0?1:0}function iC(j,p){const v=j.point,S=p.point;return v[0]>S[0]?1:v[0]S[1]?1:-1:function(E,R,F){return E.left!==R.left?E.left?1:-1:dTe(F,E.otherEvent.point,R.otherEvent.point)!==0?E.isBelow(R.otherEvent.point)?-1:1:!E.isSubject&&R.isSubject?1:-1}(j,p,v)}function oC(j,p,v){const S=new PO(p,!1,j,j.isSubject),E=new PO(p,!0,j.otherEvent,j.isSubject);return KN(j.point,j.otherEvent.point)&&console.warn("what is that, a collapsed segment?",j),S.contourId=E.contourId=j.contourId,iC(E,j.otherEvent)>0&&(j.otherEvent.left=!0,E.left=!1),j.otherEvent.otherEvent=E,j.otherEvent=S,v.push(E),v.push(S),v}function nee(j,p){return j[0]*p[1]-j[1]*p[0]}function uTe(j,p){return j[0]*p[0]+j[1]*p[1]}function hTe(j,p,v){const S=function(K,J,le,fe){const ye=[J[0]-K[0],J[1]-K[1]],Te=[fe[0]-le[0],fe[1]-le[1]];function Pe(fs,Jt,ps){return[fs[0]+Jt*ps[0],fs[1]+Jt*ps[1]]}const Ue=[le[0]-K[0],le[1]-K[1]];let Qe=nee(ye,Te),at=Qe*Qe;const pt=uTe(ye,ye);if(at>0){const fs=nee(Ue,Te)/Qe;if(fs<0||fs>1)return null;const Jt=nee(Ue,ye)/Qe;return Jt<0||Jt>1?null:fs===0||fs===1?[Pe(K,fs,ye)]:Jt===0||Jt===1?[Pe(le,Jt,Te)]:[Pe(K,fs,ye)]}if(Qe=nee(Ue,ye),at=Qe*Qe,at>0)return null;const dt=uTe(ye,Ue)/pt,wt=dt+uTe(ye,Te)/pt,Tt=Math.min(dt,wt),Lt=Math.max(dt,wt);return Tt<=1&&Lt>=0?Tt===1?[Pe(K,Tt>0?Tt:0,ye)]:Lt===0?[Pe(K,Lt<1?Lt:1,ye)]:[Pe(K,Tt>0?Tt:0,ye),Pe(K,Lt<1?Lt:1,ye)]:null}(j.point,j.otherEvent.point,p.point,p.otherEvent.point),E=S?S.length:0;if(E===0||E===1&&(KN(j.point,p.point)||KN(j.otherEvent.point,p.otherEvent.point))||E===2&&j.isSubject===p.isSubject)return 0;if(E===1)return!KN(j.point,S[0])&&!KN(j.otherEvent.point,S[0])&&oC(j,S[0],v),!KN(p.point,S[0])&&!KN(p.otherEvent.point,S[0])&&oC(p,S[0],v),1;const R=[];let F=!1,q=!1;return KN(j.point,p.point)?F=!0:iC(j,p)===1?R.push(p,j):R.push(j,p),KN(j.otherEvent.point,p.otherEvent.point)?q=!0:iC(j.otherEvent,p.otherEvent)===1?R.push(p.otherEvent,j.otherEvent):R.push(j.otherEvent,p.otherEvent),F&&q||F?(p.type=1,j.type=p.inOut===j.inOut?2:3,F&&!q&&oC(R[1].otherEvent,R[0].point,v),2):q?(oC(R[0],R[1].point,v),3):R[0]!==R[3].otherEvent?(oC(R[0],R[1].point,v),oC(R[1],R[2].point,v),3):(oC(R[0],R[1].point,v),oC(R[3].otherEvent,R[2].point,v),3)}function aUt(j,p){if(j===p)return 0;if(dTe(j.point,j.otherEvent.point,p.point)!==0||dTe(j.point,j.otherEvent.point,p.otherEvent.point)!==0)return KN(j.point,p.point)?j.isBelow(p.otherEvent.point)?-1:1:j.point[0]===p.point[0]?j.point[1](p.contourId??0)?1:-1}return iC(j,p)===1?1:-1}class iUt{constructor(){this.points=[],this.holeIds=[],this.holeOf=null,this.depth=null}isExterior(){return this.holeOf==null}}function oUt(j,p,v,S){let E,R=j+1,F=p[j].point;const q=p.length;for(RS;)R--;return R}function lUt(j,p,v){const S=new iUt;if(j.prevInResult!=null){const E=j.prevInResult,R=E.outputContourId;if(E.resultTransition>0){const F=p[R];if(F.holeOf!=null){const q=F.holeOf;p[q].holeIds.push(v),S.holeOf=q,S.depth=p[R].depth}else p[R].holeIds.push(v),S.holeOf=R,S.depth=p[R].depth+1}else S.holeOf=null,S.depth=p[R].depth}else S.holeOf=null,S.depth=0;return S}const EYe=Math.max,MYe=Math.min;let ree=0;function LYe(j,p,v,S,E,R){let F,q,K,J,le,fe;for(F=0,q=j.length-1;F0?fe.left=!0:le.left=!0;const ye=K[0],Te=K[1];E[0]=MYe(E[0],ye),E[1]=MYe(E[1],Te),E[2]=EYe(E[2],ye),E[3]=EYe(E[3],Te),S.push(le),S.push(fe)}}const aee=[];function PYe(j,p,v){let S=j,E=p;typeof j[0][0][0]=="number"&&(S=[j]),typeof p[0][0][0]=="number"&&(E=[p]);let R=function(ye,Te,Pe){let Ue=null;return ye.length*Te.length===0&&(Pe===0?Ue=aee:Pe===2?Ue=ye:(Pe===1||Pe===3)&&(Ue=ye.length===0?Te:ye)),Ue}(S,E,v);if(R)return R===aee?null:R;const F=[1/0,1/0,-1/0,-1/0],q=[1/0,1/0,-1/0,-1/0],K=function(ye,Te,Pe,Ue,Qe){const at=new ch(void 0,iC);let pt,dt,wt,Tt,Lt,fs;for(wt=0,Tt=ye.length;wtUe[2]||Ue[0]>Pe[2]||Pe[1]>Ue[3]||Ue[1]>Pe[3])&&(Qe===0?at=aee:Qe===2?at=ye:(Qe===1||Qe===3)&&(at=ye.concat(Te))),at}(S,E,F,q,v),R)return R===aee?null:R;const J=function(ye,Te,Pe,Ue,Qe,at){const pt=new iTe(aUt),dt=[],wt=Math.min(Ue[2],Qe[2]);let Tt,Lt,fs;for(;ye.length!==0;){let Jt=ye.pop();if(dt.push(Jt),at===0&&Jt.point[0]>wt||at===2&&Jt.point[0]>Ue[2])break;if(Jt.left){Lt=Tt=pt.insert(Jt),fs=pt.minNode(),Tt=Tt!==fs?pt.prev(Tt):null,Lt=pt.next(Lt);const ps=Tt?Tt.key:null;let rs;if(Iq(Jt,ps,at),Lt&&hTe(Jt,Lt.key,ye)===2&&(Iq(Jt,ps,at),Iq(Lt.key,Jt,at)),Tt&&hTe(Tt.key,Jt,ye)===2){let is=Tt;is=is!==fs?pt.prev(is):null,rs=is?is.key:null,Iq(ps,rs,at),Iq(Jt,ps,at)}}else Jt=Jt.otherEvent,Lt=Tt=pt.find(Jt),Tt&&Lt&&(Tt=Tt!==fs?pt.prev(Tt):null,Lt=pt.next(Lt),pt.remove(Jt),Lt&&Tt&&hTe(Tt.key,Lt.key,ye))}return dt}(K,0,0,F,q,v),le=function(ye){let Te,Pe;const Ue=function(pt){let dt,wt,Tt,Lt,fs;const Jt=[];for(wt=0,Tt=pt.length;wt{Qe[fs]=!0,fs=Ue.length)&&Ue[Tt];);at.push(dt)}return at}(J),fe=[];for(let ye=0;ye{F.push(new sn(fe,K+(fe-q)/(J-q)*(le-K)))}:(F,q,K,J,le,fe)=>{F.push(new sn(q+(fe-K)/(le-K)*(J-q),fe))};for(const F of j){const q=[];for(const K of F){if(K.length<=2)continue;const J=[];for(let ye=0;yep&&R(J,Te,Pe,Ue,Qe,p):at>v?pt=p&&R(J,Te,Pe,Ue,Qe,p),pt>v&&at<=v&&R(J,Te,Pe,Ue,Qe,v)}let le=K[K.length-1];const fe=S===0?le.x:le.y;fe>=p&&fe<=v&&J.push(le),J.length&&(le=J[J.length-1],J[0].x===le.x&&J[0].y===le.y||J.push(J[0]),q.push(J))}q.length&&E.push(q)}return E}function cUt(j,p){const v=PYe(mTe(j),mTe([p]),0);return v==null?[]:IYe(v)}function dUt(j,p,v=0){let E=mTe(j,65536);const R=[];for(;p.valid();p.next()){const[F,q]=p.get();let K=F.x*65536,J=F.y*65536,le=q.x*65536,fe=q.y*65536;const ye=le-K,Te=fe-J,Pe=Math.hypot(ye,Te);if(Pe===0)continue;K-=ye*v,J-=Te*v,le+=ye*v,fe+=Te*v;const Ue=Math.trunc(Te/Pe*3),Qe=-Math.trunc(ye/Pe*3);R.push([[[K,J],[le,fe],[le+Ue,fe+Qe],[K+Ue,J+Qe],[K,J]]])}return R.length>0&&(E=PYe(E,R,2)),IYe(E,1/65536,128)}function mTe(j,p=1){return[j.map(v=>v.map(S=>[S.x*p,S.y*p]))]}function IYe(j,p=1,v){return j.map(S=>S.map((E,R)=>{const F=E.map(q=>{let K=q[0],J=q[1];return v&&(K=Math.round(K/v)*v,J=Math.round(J/v)*v),new sn(K*p,J*p)._round()});return R>0&&F.reverse(),F}))}class pTe{constructor(p,v){this.layoutVertexArray=new Mi,this.indexArray=new Zd,this.lineIndexArray=new k1,this.triangleSegments=new Ul,this.lineSegments=new Ul,this.programConfigurations=new et(p.layers,{zoom:p.zoom,lut:p.lut}),this.uploaded=!1,v&&(this.elevatedLayoutVertexArray=new rl)}update(p,v,S,E,R,F,q,K){this.programConfigurations.updatePaintArrays(p,v,R,S,E,F,q,K)}isEmpty(){return this.layoutVertexArray.length===0}needsUpload(){return this.programConfigurations.needsUpload}upload(p){this.uploaded||(this.layoutVertexBuffer=p.createVertexBuffer(this.layoutVertexArray,U$t.members),this.indexBuffer=p.createIndexBuffer(this.indexArray),this.lineIndexBuffer=p.createIndexBuffer(this.lineIndexArray),this.elevatedLayoutVertexArray&&this.elevatedLayoutVertexArray.length>0&&(this.elevatedLayoutVertexBuffer=p.createVertexBuffer(this.elevatedLayoutVertexArray,q$t.members))),this.programConfigurations.upload(p),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(p,v,S,E,R,F,q){this.programConfigurations.populatePaintArrays(this.layoutVertexArray.length,p,v,S,E,R,F,void 0,q)}}class oee{constructor(p){this.zoom=p.zoom,this.pixelRatio=p.pixelRatio,this.overscaling=p.overscaling,this.layers=p.layers,this.layerIds=this.layers.map(v=>v.fqid),this.index=p.index,this.hasPattern=!1,this.patternFeatures=[],this.lut=p.lut,this.bufferData=new pTe(p,!1),this.elevationBufferData=new pTe(p,!0),this.stateDependentLayerIds=this.layers.filter(v=>v.isStateDependent()).map(v=>v.id),this.projection=p.projection,this.elevationMode=this.layers[0].layout.get("fill-elevation-reference"),this.sourceLayerIndex=p.sourceLayerIndex,this.worldview=p.worldview,this.hasAppearances=null}updateFootprints(p,v){}updateAppearances(p,v,S,E){return{hasLayoutChanges:!1,hasUboChanges:!1}}populate(p,v,S,E){this.hasPattern=rTe("fill",this.layers,this.pixelRatio,v);const R=this.layers[0].layout.get("fill-sort-key"),F=[];for(const{feature:q,id:K,index:J,sourceLayerIndex:le}of p){const fe=this.layers[0]._featureFilter.needGeometry,ye=Pi(q,fe);if(!this.layers[0]._featureFilter.filter(new xi(this.zoom,{worldview:this.worldview,activeFloors:v.activeFloors}),ye,S))continue;const Te=R?R.evaluate(ye,{},S,v.availableImages):void 0,Pe={id:K,properties:q.properties,type:q.type,sourceLayerIndex:le,index:J,geometry:fe?ye.geometry:Ea(q,S,E),patterns:{},sortKey:Te};F.push(Pe)}R&&F.sort((q,K)=>q.sortKey-K.sortKey);for(const q of F){const{geometry:K,index:J,sourceLayerIndex:le}=q;if(this.hasPattern){const fe=aTe("fill",this.layers,q,this.zoom,this.pixelRatio,v);this.patternFeatures.push(fe)}else this.addFeature(q,K,J,S,{},v.availableImages,v.brightness,v.elevationFeatures);v.featureIndex.insert(p[J].feature,K,J,le,this.index)}}update(p,v,S,E,R,F,q){this.bufferData.update(p,v,S,E,R,F,q,this.worldview),this.elevationBufferData.update(p,v,S,E,R,F,q,this.worldview),this.elevatedStructures&&this.elevatedStructures.update(p,v,S,E,R,F,q,this.worldview)}addFeatures(p,v,S,E,R,F){for(const q of this.patternFeatures)this.addFeature(q,q.geometry,q.index,v,S,E,F,p.elevationFeatures)}isEmpty(){return this.bufferData.isEmpty()&&this.elevationBufferData.isEmpty()}uploadPending(){return!this.uploaded||this.bufferData.needsUpload()||this.elevationBufferData.needsUpload()}upload(p){this.bufferData.upload(p),this.elevationBufferData.upload(p),this.elevatedStructures&&this.elevatedStructures.upload(p)}destroy(){this.bufferData.destroy(),this.elevationBufferData.destroy(),this.elevatedStructures&&this.elevatedStructures.destroy()}addFeature(p,v,S,E,R,F=[],q,K){const J=Lq(v,500);this.elevationMode!=="none"?this.addElevatedRoadFeature(p,J,E,S,K):this.addGeometry(J,this.bufferData),this.bufferData.populatePaintArrays(p,S,R,F,E,q,this.worldview),this.elevationBufferData.populatePaintArrays(p,S,R,F,E,q,this.worldview)}getUnevaluatedPortalGraph(){return this.elevatedStructures?this.elevatedStructures.unevaluatedPortals:void 0}setEvaluatedPortalGraph(p,v,S,E,R){this.elevatedStructures&&(this.elevatedStructures.construct(p),this.elevatedStructures.populatePaintArrays(v,S,E,R,this.worldview))}addElevatedRoadFeature(p,v,S,E,R){const F=new Array,q=Ql.getElevationFeature(p,R);if(!q)return void this.addGeometry(v,this.bufferData);{const J=this.clipPolygonsToTile(v,1);J.length>0&&F.push({polygons:J,elevationFeature:q,elevationTileID:S})}const K={guardRailEnabled:this.layers[0].layout.get("fill-construct-bridge-guard-rail").evaluate(p,{},S),featureIndex:E};for(const J of F)if(J.elevationFeature){if(this.elevationMode==="hd-road-base"){this.elevatedStructures||(this.elevatedStructures=new hv(J.elevationTileID,this.layers,this.zoom,this.lut));const fe=J.elevationFeature.isTunnel();let ye=0;p.properties.hasOwnProperty(Vl)&&(ye=+p.properties[Vl]),this.elevatedStructures.addPortalCandidates(J.elevationFeature.id,J.polygons,fe,J.elevationFeature,ye)}J.elevationFeature.constantHeight==null&&(J.polygons=this.prepareElevatedPolygons(J.polygons,J.elevationFeature,J.elevationTileID));const le=new uc(S,J.elevationTileID);this.addElevatedGeometry(J.polygons,le,J.elevationFeature,this.elevationMode==="hd-road-base"?0:.05,E,K)}}addElevatedGeometry(p,v,S,E,R,F){const q={elevation:S,elevationSampler:v,bias:E,index:R,featureInfo:F},[K,J]=this.addGeometry(p,this.elevationBufferData,q);this.elevationBufferData.heightRange==null?this.elevationBufferData.heightRange={min:K,max:J}:(this.elevationBufferData.heightRange.min=Math.min(this.elevationBufferData.heightRange.min,K),this.elevationBufferData.heightRange.max=Math.max(this.elevationBufferData.heightRange.max,J))}addGeometry(p,v,S){let E=Number.POSITIVE_INFINITY,R=Number.NEGATIVE_INFINITY,F=null;S&&(F=S.elevationSampler.constantElevation(S.elevation,S.bias),F!=null&&(E=F,R=F));const q=(K,J,le)=>{if(S!=null)if(J.push(K),F!=null)v.elevatedLayoutVertexArray.emplaceBack(F),le.push(F);else{const fe=S.elevationSampler.pointElevation(K,S.elevation,S.bias);v.elevatedLayoutVertexArray.emplaceBack(fe),le.push(fe),E=Math.min(E,fe),R=Math.max(R,fe)}};for(const K of p){let J=0;for(const dt of K)J+=dt.length;const le=v.triangleSegments.prepareSegment(J,v.layoutVertexArray,v.indexArray),fe=le.vertexLength,ye=[],Te=[],Pe=[],Ue=[],Qe=[],at=v.layoutVertexArray.length;for(const dt of K){if(dt.length===0)continue;dt!==K[0]&&Te.push(ye.length/2);const wt=v.lineSegments.prepareSegment(dt.length,v.layoutVertexArray,v.lineIndexArray),Tt=wt.vertexLength;S&&Qe.push(v.layoutVertexArray.length-at),q(dt[0],Pe,Ue),v.layoutVertexArray.emplaceBack(dt[0].x,dt[0].y),v.lineIndexArray.emplaceBack(Tt+dt.length-1,Tt),ye.push(dt[0].x),ye.push(dt[0].y);for(let Lt=1;Lt0&&S&&this.elevationMode==="hd-road-base"){const dt=S.elevation.isTunnel(),wt=S.elevation.safeArea,Tt=this.elevatedStructures.addVertices(Pe,Ue);this.elevatedStructures.addTriangles(pt,Tt,dt);const Lt=Qe.length;if(Lt>0){for(let fs=0;fs=S&&Te.max.x<=R&&Te.min.y>=E&&Te.max.y<=F?K:J).push(ye)}if(K.length===p.length)return p;const le=[new sn(S,E),new sn(R,E),new sn(R,F),new sn(S,F),new sn(S,E)],fe=K;for(const ye of J)fe.push(...cUt(ye,le));return fe}}let DYe,RYe,OYe,FYe;pr(oee,"FillBucket",{omit:["layers","patternFeatures"]}),pr(pTe,"FillBufferData"),pr(hv,"ElevatedStructures");class lee{constructor(p,v,S,E){if(this.triangleCount=v.length/3,this.min=new sn(0,0),this.max=new sn(0,0),this.xScale=0,this.yScale=0,this.cellsX=0,this.cellsY=0,this.cells=[],this.payload=[],this.triangleCount===0||p.length===0)return;const[R,F]=[p[0].clone(),p[0].clone()];for(let fe=1;fefe.cellIdx-ye.cellIdx||fe.triIdx-ye.triIdx);let le=0;for(;lethis.max.x||this.min.x>p.x||p.y>this.max.y||this.min.y>p.y)return;const S=YN(p.x-this.min.x,this.xScale,this.cellsX),E=YN(p.y-this.min.y,this.yScale,this.cellsY),R=this.cells[E*this.cellsX+S];if(R){this._lazyInitLookup();for(let F=0;Fthis.max.x||this.min.x>v.x||p.y>this.max.y||this.min.y>v.y)return;this._lazyInitLookup();const E=YN(p.x-this.min.x,this.xScale,this.cellsX),R=YN(v.x-this.min.x,this.xScale,this.cellsX),F=YN(p.y-this.min.y,this.yScale,this.cellsY),q=YN(v.y-this.min.y,this.yScale,this.cellsY);for(let K=F;K<=q;K++)for(let J=E;J<=R;J++){const le=this.cells[K*this.cellsX+J];if(le)for(let fe=0;fev.fqid),this.index=p.index,this.hasPattern=!1,this.stateDependentLayerIds=this.layers.filter(v=>v.isStateDependent()).map(v=>v.id),this.footprints=[],this.worldview=p.worldview,this.hasAppearances=null}updateFootprints(p,v){for(const S of this.footprints)v.push({footprint:S,id:p})}updateAppearances(p,v,S,E){return{hasLayoutChanges:!1,hasUboChanges:!1}}populate(p,v,S,E){const R=[];for(const{feature:F,id:q,index:K,sourceLayerIndex:J}of p){const le=this.layers[0]._featureFilter.needGeometry,fe=Pi(F,le);if(!this.layers[0]._featureFilter.filter(new xi(this.zoom,{worldview:this.worldview,activeFloors:v.activeFloors}),fe,S))continue;const ye={id:q,properties:F.properties,type:F.type,sourceLayerIndex:J,index:K,geometry:le?fe.geometry:Ea(F,S,E),patterns:{}};R.push(ye)}for(const F of R){const{geometry:q,index:K,sourceLayerIndex:J}=F;this.addFeature(F,q,K,S,{},v.availableImages,v.brightness),v.featureIndex.insert(p[K].feature,q,K,J,this.index)}}isEmpty(){return this.footprints.length===0}uploadPending(){return!1}upload(p){}update(p,v,S,E,R,F,q){}destroy(){}addFeature(p,v,S,E,R,F=[],q){for(const K of Lq(v,2)){const J=[],le=[],fe=[],ye=new sn(1/0,1/0),Te=new sn(-1/0,-1/0);for(const Qe of K)if(Qe.length!==0){Qe!==K[0]&&fe.push(le.length/2);for(let at=0;atp.max.x||j.max.xp.max.y||j.max.ynew sn((K.x+R.x*sr)*q-F.x*sr,(K.y+R.y*sr)*q-F.y*sr))}return gTe(v,E,j.indices,0,j.indices.length,0,0)}function VYe(j,p,v,S){const E=Math.pow(2,S.z-v.z);return new sn((j+v.x*sr)*E-S.x*sr,(p+v.y*sr)*E-S.y*sr)}function HYe(j,p){const v=[];p.grid.queryPoint(j,v);const S=p.indices,E=p.vertices;for(let R=0;R0&&(S.length>1&&v.push(S),S=[])}return S.length>1&&v.push(S),v}const yTe=ti.types,_Ut=["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"],wUt=["fill-extrusion-flood-light-ground-radius"],jUt=Math.pow(2,13),NUt=Math.pow(2,15)-1,hee=new sn(0,1),kS=2147483648,mee=1073741824;function Rq(j,p,v,S,E,R,F,q){j.emplaceBack((p<<1)+F,(v<<1)+R,(Math.floor(S*jUt)<<1)+E,Math.round(q))}function Oq(j,p,v){j.emplaceBack(p.x*sr,p.y*sr,v?1:0)}function pee(j,p,v,S,E,R){j.emplaceBack(p.x,p.y,(v.x<<1)+S,(v.y<<1)+E,R)}function Fq(j,p,v){j.emplaceBack(p.x,p.y,p.z,v[0]*16384,v[1]*16384,v[2]*16384)}class WYe{constructor(){this.vertexOffset=0,this.vertexCount=0,this.indexOffset=0,this.indexCount=0}}class vTe{constructor(){this.centroidXY=new sn(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 sn(Number.MAX_VALUE,Number.MAX_VALUE),this.max=new sn(-Number.MAX_VALUE,-Number.MAX_VALUE),this.height=0,this.buildingId=0,this.groupCentroidPos=new sn(0,0)}span(){return new sn(this.max.x-this.min.x,this.max.y-this.min.y)}}class bTe{constructor(){this.acc=new sn(0,0),this.accCount=0,this.centroidDataIndex=0}startRing(p,v){p.min.x===Number.MAX_VALUE&&(p.min.x=p.max.x=v.x,p.min.y=p.max.y=v.y)}appendEdge(p,v,S){this.accCount++,this.acc._add(v);let E=!!this.borders;v.xp.max.x&&(p.max.x=v.x,E=!0),v.yp.max.y&&(p.max.y=v.y,E=!0),((v.x===0||v.x===sr)&&v.x===S.x)!=((v.y===0||v.y===sr)&&v.y===S.y)&&this.processBorderOverlap(v,S),E&&this.checkBorderIntersection(v,S)}checkBorderIntersection(p,v){v.x<0!=p.x<0&&this.addBorderIntersection(0,mr(v.y,p.y,(0-v.x)/(p.x-v.x))),v.x>sr!=p.x>sr&&this.addBorderIntersection(1,mr(v.y,p.y,(sr-v.x)/(p.x-v.x))),v.y<0!=p.y<0&&this.addBorderIntersection(2,mr(v.x,p.x,(0-v.y)/(p.y-v.y))),v.y>sr!=p.y>sr&&this.addBorderIntersection(3,mr(v.x,p.x,(sr-v.y)/(p.y-v.y)))}addBorderIntersection(p,v){this.borders||(this.borders=[[Number.MAX_VALUE,-Number.MAX_VALUE],[Number.MAX_VALUE,-Number.MAX_VALUE],[Number.MAX_VALUE,-Number.MAX_VALUE],[Number.MAX_VALUE,-Number.MAX_VALUE]]);const S=this.borders[p];vS[1]&&(S[1]=v)}processBorderOverlap(p,v){if(p.x===v.x){if(p.y===v.y)return;const S=p.x===0?0:1;this.addBorderIntersection(S,v.y),this.addBorderIntersection(S,p.y)}else{const S=p.y===0?2:3;this.addBorderIntersection(S,v.x),this.addBorderIntersection(S,p.x)}}centroid(){return this.accCount===0?new sn(0,0):new sn(Math.floor(Math.max(0,this.acc.x)/this.accCount),Math.floor(Math.max(0,this.acc.y)/this.accCount))}intersectsCount(){return this.borders?this.borders.reduce((p,v)=>p+ +(v[0]!==Number.MAX_VALUE),0):0}}function KYe(j,p){const v=j.add(p)._unit(),S=it(j.x*v.x+j.y*v.y,-1,1);var E,R,F;return F=Math.acos(S),Math.min(4,Math.max(-4,Math.tan(F)))/4*NUt*((E=j).x*(R=p).y-E.y*R.x<0?-1:1)}const kUt=[j=>j.x<0,j=>j.x>sr,j=>j.y<0,j=>j.y>sr];function SUt(j,p,v,S){const E=[4];if(S===0)return E;v._mult(S);const R=j.sub(v),F=p.sub(v),q=[j,p,R,F];for(let K=0;K<4;K++)for(const J of q)if(kUt[K](J)){E.push(K);break}return E}class _Te{constructor(p){this.groundRadiusArray=null,this.groundRadiusBuffer=null,this.vertexArray=new u6,this.indexArray=new Zd,this.programConfigurations=new et(p.layers,{zoom:p.zoom,lut:p.lut},v=>wUt.includes(v)),this._segments=new Ul,this.hiddenByLandmarkVertexArray=new kO,this._segmentToGroundQuads={},this._segmentToGroundQuads[0]=[],this._segmentToRegionTriCounts={},this._segmentToRegionTriCounts[0]=[0,0,0,0,0],this.regionSegments={},this.regionSegments[4]=new Ul}getDefaultSegment(){return this.regionSegments[4]}hasData(){return this.vertexArray.length!==0}addData(p,v,S,E=!1){const R=p.length;if(R>2){let F=Math.max(0,this._segments.get().length-1);const q=this._segments._prepareSegment(4*R,this.vertexArray.length,2*this._segmentToGroundQuads[F].length);let K;F!==this._segments.get().length-1&&(F++,this._segmentToGroundQuads[F]=[],this._segmentToRegionTriCounts[F]=[0,0,0,0,0]);{const J=p[0],le=p[1];K=KYe(J.sub(p[R-1])._perp()._unit(),le.sub(J)._perp()._unit())}for(let J=0;JE.region-R.region);for(let S=0;SK+J,0);let q=0;for(let K=0;K<=4;K++){const J=F[K];if(J!==0){let le=this.regionSegments[K];le||(le=this.regionSegments[K]=new Ul);const fe={vertexOffset:R.vertexOffset,primitiveOffset:R.primitiveOffset+q,vertexLength:R.vertexLength,primitiveLength:J};le.get().push(fe)}q+=J}for(let K=0;K0?this.hiddenByLandmarkVertexBuffer=p.createVertexBuffer(this.hiddenByLandmarkVertexArray,gUt.members,!0):this.hiddenByLandmarkVertexBuffer&&this.hiddenByLandmarkVertexBuffer.updateData(this.hiddenByLandmarkVertexArray),this._needsHiddenByLandmarkUpdate=!1)}destroy(){if(this.vertexBuffer){this.vertexBuffer.destroy(),this.indexBuffer.destroy(),this.hiddenByLandmarkVertexBuffer&&this.hiddenByLandmarkVertexBuffer.destroy(),this.groundRadiusBuffer&&this.groundRadiusBuffer.destroy(),this._segments&&this._segments.destroy(),this.programConfigurations.destroy();for(let p=0;p<=4;p++){const v=this.regionSegments[p];v&&v.destroy()}}}}class fee{constructor(p){this.zoom=p.zoom,this.canonical=p.canonical,this.overscaling=p.overscaling,this.layers=p.layers,this.pixelRatio=p.pixelRatio,this.layerIds=this.layers.map(v=>v.fqid),this.index=p.index,this.hasPattern=!1,this.edgeRadius=0,this.projection=p.projection,this.activeReplacements=[],this.replacementUpdateTime=0,this.centroidData=[],this.footprintIndices=new Zd,this.footprintVertices=new Mi,this.footprintSegments=[],this.layoutVertexArray=new j1,this.centroidVertexArray=new KJ,this.wallVertexArray=new wq,this.indexArray=new Zd,this.programConfigurations=new et(p.layers,{zoom:p.zoom,lut:p.lut},v=>_Ut.includes(v)),this.segments=new Ul,this.stateDependentLayerIds=this.layers.filter(v=>v.isStateDependent()).map(v=>v.id),this.groundEffect=new _Te(p),this.maxHeight=0,this.partLookup={},this.triangleSubSegments=[],this.polygonSegments=[],this.buildingGroups=new Map,this.worldview=p.worldview,this.hasAppearances=null}updateFootprints(p,v){}updateAppearances(p,v,S,E){return{hasLayoutChanges:!1,hasUboChanges:!1}}populate(p,v,S,E){this.features=[],this.hasPattern=rTe("fill-extrusion",this.layers,this.pixelRatio,v),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=In(S),this.edgeRadius=this.layers[0].layout.get("fill-extrusion-edge-radius")/this.tileToMeter,this.wallMode=this.layers[0].paint.get("fill-extrusion-line-width").constantOr(1)!==0;for(const{feature:R,id:F,index:q,sourceLayerIndex:K}of p){const J=this.layers[0]._featureFilter.needGeometry,le=Pi(R,J);if(!this.layers[0]._featureFilter.filter(new xi(this.zoom,{worldview:this.worldview,activeFloors:v.activeFloors}),le,S))continue;const fe={id:F,sourceLayerIndex:K,index:q,geometry:J?le.geometry:Ea(R,S,E),properties:R.properties,type:R.type,patterns:{}},ye=this.layoutVertexArray.length,Te=yTe[fe.type]==="Polygon";if(this.hasPattern)this.features.push({featureId:R.id,feature:aTe("fill-extrusion",this.layers,fe,this.zoom,this.pixelRatio,v)});else if(this.wallMode)for(const Pe of fe.geometry)for(const Ue of GYe(Pe,Te))this.addFeature(R.id,fe,[Ue],q,S,{},v.availableImages,E,v.brightness);else this.addFeature(R.id,fe,fe.geometry,q,S,{},v.availableImages,E,v.brightness);v.featureIndex.insert(R,fe.geometry,q,K,this.index,ye)}this._finalizeBuildingGroups(),this.sortBorders(),this.projection.name==="mercator"&&this.splitToSubtiles(),this.groundEffect.prepareBorderSegments(),this.polygonSegments.length=0}addFeatures(p,v,S,E,R,F){for(const{featureId:q,feature:K}of this.features){const J=yTe[K.type]==="Polygon",{geometry:le}=K;if(this.wallMode)for(const fe of le)for(const ye of GYe(fe,J))this.addFeature(q,K,[ye],K.index,v,S,E,R,F);else this.addFeature(q,K,le,K.index,v,S,E,R,F)}this._finalizeBuildingGroups(),this.sortBorders(),this.projection.name==="mercator"&&this.splitToSubtiles()}update(p,v,S,E,R,F,q){this.programConfigurations.updatePaintArrays(p,v,R,S,E,F,q,this.worldview),this.groundEffect.update(p,v,R,S,E,F,q,this.worldview)}isEmpty(){return this.layoutVertexArray.length===0}uploadPending(){return!this.uploaded||this.programConfigurations.needsUpload||this.groundEffect.programConfigurations.needsUpload}upload(p){this.uploaded||(this.layoutVertexBuffer=p.createVertexBuffer(this.layoutVertexArray,yUt),this.indexBuffer=p.createIndexBuffer(this.indexArray),this.wallVertexBuffer=p.createVertexBuffer(this.wallVertexArray,fUt.members),this.layoutVertexExtArray&&(this.layoutVertexExtBuffer=p.createVertexBuffer(this.layoutVertexExtArray,xUt.members,!0)),this.groundEffect.upload(p)),this.groundEffect.uploadPaintProperties(p),this.programConfigurations.upload(p),this.uploaded=!0}uploadCentroid(p){this.groundEffect.uploadHiddenByLandmark(p),this.needsCentroidUpdate&&(!this.centroidVertexBuffer&&this.centroidVertexArray.length>0?this.centroidVertexBuffer=p.createVertexBuffer(this.centroidVertexArray,pUt.members,!0):this.centroidVertexBuffer&&this.centroidVertexBuffer.updateData(this.centroidVertexArray),this.needsCentroidUpdate=!1)}destroy(){this.layoutVertexBuffer&&(this.layoutVertexBuffer.destroy(),this.centroidVertexBuffer&&this.centroidVertexBuffer.destroy(),this.layoutVertexExtBuffer&&this.layoutVertexExtBuffer.destroy(),this.groundEffect.destroy(),this.indexBuffer.destroy(),this.programConfigurations.destroy(),this.segments.destroy())}addFeature(p,v,S,E,R,F,q,K,J){const le=this.layers[0].paint.get("fill-extrusion-flood-light-ground-radius").evaluate(v,{})/this.tileToMeter,fe=[new sn(0,0),new sn(sr,sr)],ye=K.projection,Te=ye.name==="globe",Pe=this.wallMode||yTe[v.type]==="Polygon",Ue=new bTe;Ue.centroidDataIndex=this.centroidData.length;const Qe=new vTe;Qe.buildingId=p,v.properties&&v.properties.hasOwnProperty("building_id")&&(Qe.buildingId=Number(v.properties.building_id)),Ue.buildingId=Qe.buildingId;const at=this.layers[0].paint.get("fill-extrusion-base").evaluate(v,{},R)<=0,pt=this.layers[0].paint.get("fill-extrusion-height").evaluate(v,{},R);let dt;if(Qe.height=pt,Qe.vertexArrayOffset=this.layoutVertexArray.length,Qe.groundVertexArrayOffset=this.groundEffect.vertexArray.length,Te&&!this.layoutVertexExtArray&&(this.layoutVertexExtArray=new vO),this.wallMode){if(Te)return void Er("Non zero fill-extrusion-line-width is not yet supported on globe.");if(S.length!==1)return;dt=function(rs){const is=rs[0].x===rs[rs.length-1].x&&rs[0].y===rs[rs.length-1].y;(function(gr){let ir=0;const Dr=gr.length;for(let Zr=0;Zr=0})(rs)||(rs=rs.reverse());const fn={geometry:[],joinNormals:[],indices:[]},_n=[],Sn=[],wn=[];let Un=rs.length;for(;Un>=2&&rs[Un-1].equals(rs[Un-2]);)Un--;if(Un<(is?3:2))return fn;let ln,Nn,Tn,Vn,ar,zr=0;for(;zr0;let ma="miter";const mi=2;ma==="miter"&&Zr>mi&&(ma="bevel"),ma==="bevel"&&(Zr>100&&(ma="flipbevel"),Zr{const Jo=new sn(pi.x,pi.y),Mo=new sn(pi.x,pi.y);Jo.x+=ko.x*kd,Jo.y+=ko.y*kd,Mo.x-=ko.x*Math.max(Ii,1),Mo.y-=ko.y*Math.max(Ii,1),wn.push(ko),_n.push(Jo),Sn.push(Mo)};if(ma==="miter")ir._mult(Zr),bo(ln,ir,0,0);else if(ma==="flipbevel")ir=ar.mult(-1),bo(ln,ir,0,0),bo(ln,ir.mult(-1),0,0);else{const pi=-Math.sqrt(Zr*Zr-1),ko=Aa?pi:0,Ii=Aa?0:pi;Nn&&bo(ln,Vn,ko,Ii),Tn&&bo(ln,ar,ko,Ii)}}fn.geometry=[..._n,...Sn.reverse(),_n[0]],fn.joinNormals=[...wn,...wn.reverse(),wn[wn.length-1]];const yr=fn.geometry.length-1;for(let gr=0;grrs<(is.length-1)/2||rs===is.length-1,Tt=this.wallMode?[S]:Lq(S,500);for(let rs=Tt.length-1;rs>=0;rs--){const is=Tt[rs];(is.length===0||AUt(is[0]))&&Tt.splice(rs,1)}let Lt;if(Te)Lt=tZe(Tt,fe,R);else{Lt=[];for(const rs of Tt)Lt.push({polygon:rs,bounds:fe})}const fs=Pe?this.edgeRadius:0,Jt=fs>0&&this.zoom<17,ps=(rs,is)=>{if(rs.length===0)return!1;const dn=rs[rs.length-1];return is.x===dn.x&&is.y===dn.y};for(const{polygon:rs,bounds:is}of Lt){let dn=0,fn=0;for(const Un of rs)Pe&&!Un[0].equals(Un[Un.length-1])&&Un.push(Un[0]),fn+=Pe?Un.length-1:Un.length;const _n=this.segments.prepareSegment((Pe?5:4)*fn,this.layoutVertexArray,this.indexArray);Qe.footprintSegIdx<0&&(Qe.footprintSegIdx=this.footprintSegments.length),Qe.polygonSegIdx<0&&(Qe.polygonSegIdx=this.polygonSegments.length);const Sn={triangleArrayOffset:this.indexArray.length,triangleCount:0,triangleSegIdx:this.segments.segments.length-1},wn=new WYe;if(wn.vertexOffset=this.footprintVertices.length,wn.indexOffset=3*this.footprintIndices.length,wn.ringIndices=[],Pe){const Un=[],ln=[];dn=_n.vertexLength;for(let Tn=0;Tn4&&QYe(ln[ln.length-2],ln[0],ln[1]),Tn=fs?CUt(ln[ln.length-2],ln[0],ln[1],fs):0;const Vn=[];let ar,zr,yr;zr=ln[1].sub(ln[0])._perp()._unit();let gr=!0;for(let ir=1,Dr=0;ir0?1:0,ko=Zr.dist(Aa);if(Dr+ko>32768&&(Dr=0),fs){yr=ma.sub(Aa)._perp()._unit();let Mo=ZYe(Zr,Aa,ma,YYe(zr,yr),fs);isNaN(Mo)&&(Mo=0);const Hl=Aa.sub(Zr)._unit();Zr=Zr.add(Hl.mult(Tn))._round(),Aa=Aa.add(Hl.mult(-Mo))._round(),Tn=Mo,zr=yr,at&&this.zoom>=17&&(ps(Vn,Zr)||Vn.push(Zr),ps(Vn,Aa)||Vn.push(Aa))}const Ii=_n.vertexLength,kd=ln.length>4&&QYe(Zr,Aa,ma);let Jo=JYe(Dr,Nn,gr);if(Rq(this.layoutVertexArray,Zr.x,Zr.y,bo,pi,0,0,Jo),Rq(this.layoutVertexArray,Zr.x,Zr.y,bo,pi,0,1,Jo),this.wallMode){const Mo=wt(ir-1,ln),Hl=dt.joinNormals[ir-1];Oq(this.wallVertexArray,Hl,Mo),Oq(this.wallVertexArray,Hl,Mo)}if(Dr+=ko,Jo=JYe(Dr,kd,!gr),Nn=kd,Rq(this.layoutVertexArray,Aa.x,Aa.y,bo,pi,0,0,Jo),Rq(this.layoutVertexArray,Aa.x,Aa.y,bo,pi,0,1,Jo),this.wallMode){const Mo=wt(ir,ln),Hl=dt.joinNormals[ir];Oq(this.wallVertexArray,Hl,Mo),Oq(this.wallVertexArray,Hl,Mo)}if(_n.vertexLength+=4,this.indexArray.emplaceBack(Ii+0,Ii+1,Ii+2),this.indexArray.emplaceBack(Ii+1,Ii+3,Ii+2),_n.primitiveLength+=2,fs){const Mo=dn+(ir===1?ln.length-2:ir-2),Hl=ir===1?dn:Mo+1;if(this.indexArray.emplaceBack(Ii+1,Mo,Ii+3),this.indexArray.emplaceBack(Mo,Hl,Ii+3),_n.primitiveLength+=2,ar===void 0&&(ar=Ii),!wTe(ma,ln[ir],is)){const pd=ir===ln.length-1?ar:_n.vertexLength;this.indexArray.emplaceBack(Ii+2,Ii+3,pd),this.indexArray.emplaceBack(Ii+3,pd+1,pd),this.indexArray.emplaceBack(Ii+3,Hl,pd+1),_n.primitiveLength+=3}gr=!gr}if(Te){const Mo=this.layoutVertexExtArray,Hl=ye.projectTilePoint(Zr.x,Zr.y,R),pd=ye.projectTilePoint(Aa.x,Aa.y,R),jm=ye.upVector(R,Zr.x,Zr.y),fd=ye.upVector(R,Aa.x,Aa.y);Fq(Mo,Hl,jm),Fq(Mo,Hl,jm),Fq(Mo,pd,fd),Fq(Mo,pd,fd)}}Pe&&(dn+=ln.length-1),at&&fs&&this.zoom>=17&&(Vn.length!==0&&ps(Vn,Vn[0])&&Vn.pop(),this.groundEffect.addData(Vn,is,le,fs>0))}this.footprintSegments.push(wn),Sn.triangleCount=this.indexArray.length-Sn.triangleArrayOffset,this.polygonSegments.push(Sn),++Qe.footprintSegLen,++Qe.polygonSegLen}if(Qe.vertexCount=this.layoutVertexArray.length-Qe.vertexArrayOffset,Qe.groundVertexCount=this.groundEffect.vertexArray.length-Qe.groundVertexArrayOffset,Qe.vertexCount!==0){if(Qe.centroidXY=Ue.borders?hee:this.encodeCentroid(Ue,Qe),v.properties&&v.properties.hasOwnProperty("building_id")){const rs=Qe.buildingId;let is=this.buildingGroups.get(rs);is||(is={accX:0,accY:0,accCount:0,mergedMin:new sn(Number.MAX_VALUE,Number.MAX_VALUE),mergedMax:new sn(-Number.MAX_VALUE,-Number.MAX_VALUE),partIndices:[]},this.buildingGroups.set(rs,is)),is.accX+=Ue.acc.x,is.accY+=Ue.acc.y,is.accCount+=Ue.accCount,is.mergedMin.x=Math.min(is.mergedMin.x,Qe.min.x),is.mergedMin.y=Math.min(is.mergedMin.y,Qe.min.y),is.mergedMax.x=Math.max(is.mergedMax.x,Qe.max.x),is.mergedMax.y=Math.max(is.mergedMax.y,Qe.max.y),is.partIndices.push(this.centroidData.length)}if(this.centroidData.push(Qe),Ue.borders){this.featuresOnBorder.push(Ue);const rs=this.featuresOnBorder.length-1;for(let is=0;isthis.featuresOnBorder[v].borders[p][0]-this.featuresOnBorder[S].borders[p][0])}splitToSubtiles(){const p=[];for(let q=0;qsr),le=2*J+(+(K.min.x+K.max.x>sr)^J);for(let fe=0;feq.triangleSegmentIdx===K.triangleSegmentIdx?q.subtile-K.subtile:q.triangleSegmentIdx-K.triangleSegmentIdx);let S=0,E=0,R=0;for(const q of p){if(q.triangleSegmentIdx!==S)break;R++}const F=p.length;for(;E!==p.length;){S=p[E].triangleSegmentIdx;let q=0,K=E,J=E;for(let le=K;le0&&this.triangleSubSegments.push({segment:Te,min:fe,max:ye}),K=J;for(let Pe=K;Pe[Ue[0]*(1-at[0])+Qe[0]*at[0],Ue[1]*(1-at[1])+Qe[1]*at[1]],Te=[],Pe=[];for(const Ue of this.triangleSubSegments){Te[0]=Ue.min.x/sr,Te[1]=Ue.min.y/sr,Pe[0]=Ue.max.x/sr,Pe[1]=Ue.max.y/sr;const Qe=ye(le,fe,Te),at=ye(le,fe,Pe);if(new sl([Qe[0],Qe[1],R],[at[0],at[1],F]).intersectsPrecise(S)===0){J&&(E.segments.push(J),J=void 0);continue}const pt=Ue.segment;J&&J.vertexOffset!==pt.vertexOffset&&(E.segments.push(J),J=void 0),J?(J.vertexLength+=pt.vertexLength,J.primitiveLength+=pt.primitiveLength):J={vertexOffset:pt.vertexOffset,primitiveLength:pt.primitiveLength,vertexLength:pt.vertexLength,primitiveOffset:pt.primitiveOffset,sortKey:void 0,vaos:{}}}return J&&E.segments.push(J),E}encodeCentroid(p,v){const S=p.centroid(),E=v.span(),R=Math.min(7,Math.round(E.x*this.tileToMeter/10)),F=Math.min(6,Math.round(E.y*this.tileToMeter/10));return new sn(it(S.x,1,8191)<<3|R,it(S.y,1,8191)<<3|F)}encodeBorderCentroid(p){if(!p.borders)return new sn(0,0);const v=p.borders,S=Number.MAX_VALUE;if(v[0][0]!==S||v[1][0]!==S){const E=v[0][0]!==S?0:1;return new sn(6|(v[0][0]!==S?0:65528),(v[E][0]+v[E][1])/2<<3|6)}{const E=v[2][0]!==S?2:3;return new sn((v[E][0]+v[E][1])/2<<3|6,6|(v[2][0]!==S?0:65528))}}showCentroid(p){const v=this.centroidData[p.centroidDataIndex];if(v.flags&=kS,v.groupCentroidPos.x!==0||v.groupCentroidPos.y!==0){const S=v.span(),E=Math.min(7,Math.round(S.x*this.tileToMeter/10)),R=Math.min(6,Math.round(S.y*this.tileToMeter/10));v.centroidXY=new sn(it(v.groupCentroidPos.x,1,8191)<<3|E,it(v.groupCentroidPos.y,1,8191)<<3|R)}else v.centroidXY=new sn(0,0);this.writeCentroidToBuffer(v)}writeCentroidToBuffer(p){this.groundEffect.updateHiddenByLandmark(p);const v=p.vertexArrayOffset,S=p.vertexCount+p.vertexArrayOffset,E=-1073741824&p.flags?hee:p.centroidXY,R=this.centroidVertexArray.geta_centroid_pos0(v);if(this.centroidVertexArray.geta_centroid_pos1(v)!==E.y||R!==E.x){for(let F=v;FK.max.x||K.min.x>F.max.x||F.min.y>K.max.y||K.min.y>F.max.y||F.footprint.buildingIds.has(K.buildingId)&&(K.flags|=F.clipMask!==uee.None?-1073741824:kS);else for(const K of this.centroidData)if(!(K.flags&kS||K.flags&mee||F.min.x>K.max.x||K.min.x>F.max.x||F.min.y>K.max.y||K.min.y>F.max.y))for(let J=0;Jv!=Te>v&&p<(this.footprintVertices.int16[2*(le+F.vertexOffset)+0]-fe)*(v-ye)/(Te-ye)+fe&&(E=!E)}q=K}}return E}getHeightAtTileCoord(p,v){let S=Number.NEGATIVE_INFINITY,E=!0;const R=4*(p+sr)*sr+(v+sr);if(this.partLookup.hasOwnProperty(R)){const F=this.partLookup[R];return F?{height:F.height,hidden:!!(F.flags&kS)}:void 0}for(const F of this.centroidData)p>F.max.x||F.min.x>p||v>F.max.y||F.min.y>v||F.height<=S||this.footprintContainsPoint(p,v,F)&&(S=F.height,this.partLookup[R]=F,E=!!(F.flags&kS));if(S!==Number.NEGATIVE_INFINITY)return{height:S,hidden:E};this.partLookup[R]=void 0}}function YYe(j,p){const v=j.add(p)._unit();return j.x*v.x+j.y*v.y}function CUt(j,p,v,S){const E=p.sub(j)._perp()._unit(),R=v.sub(p)._perp()._unit();return ZYe(j,p,v,YYe(E,R),S)}function ZYe(j,p,v,S,E){const R=Math.sqrt(1-S*S);return Math.min(j.dist(p)/3,p.dist(v)/3,E*R/S)}function wTe(j,p,v){return j.xv[1].x&&p.x>v[1].x||j.yv[1].y&&p.y>v[1].y}function XYe(j,p){return j.xp[1].x||j.yp[1].y}function AUt(j){return j.every(p=>p.x<=0)||j.every(p=>p.x>=sr)||j.every(p=>p.y<=0)||j.every(p=>p.y>=sr)}function QYe(j,p,v){if(j.x<0||j.x>=sr||p.x<0||p.x>=sr||v.x<0||v.x>=sr)return!1;const S=v.sub(p),E=S.perp(),R=j.sub(p);return(S.x*R.x+S.y*R.y)/Math.sqrt((S.x*S.x+S.y*S.y)*(R.x*R.x+R.y*R.y))>-.866&&E.x*R.x+E.y*R.y<0}function JYe(j,p,v){const S=p?2|j:-3&j;return v?1|S:-2&S}function eZe(){const j=Math.PI/32,p=Math.tan(j),v=hs;return v*Math.sqrt(1+2*p*p)-v}function tZe(j,p,v){const S=1<{for(const Jt of Lt)Pe.push({polygon:Jt,bounds:fs})},Qe=Math.ceil(Math.log2(le)),at=Math.ceil(Math.log2(fe)),pt=Qe-at,dt=[];for(let Lt=0;Lt0?0:1);for(let Lt=0;Ltfs+1?Tt.push({polygons:_n,bounds:wn,depth:fs+1}):Ue(_n,wn)}if(Sn.length){const wn=[new sn(Jt===0?fn:ps.x,Jt===1?fn:ps.y),rs];dt.length>fs+1?Tt.push({polygons:Sn,bounds:wn,depth:fs+1}):Ue(Sn,wn)}}return Pe}(j,p,Math.ceil((R-E)/11.25),Math.ceil((F-q)/11.25),1,(K,J,le)=>{if(K===0)return .5*(J+le);{const fe=cn((v.y+J/sr)/S);return(On(.5*(cn((v.y+le/sr)/S)+fe))*S-v.y)*sr}})}function TUt(j,p,v,S,E,R){const F=Math.pow(2,S.z-E.z);for(let q=0;q=K[F]&&(q=p,K=j),q[F]E&&aZe(q,K,F,E),q[F]R&&aZe(K,q,F,R)}}function gee(j,p,v,S,E,R){const F=[];for(let q=0;q=S&&Pe.x>=S||(Te.x>=S?Te=new sn(S,Te.y+(S-Te.x)/(Pe.x-Te.x)*(Pe.y-Te.y))._round():Pe.x>=S&&(Pe=new sn(S,Te.y+(S-Te.x)/(Pe.x-Te.x)*(Pe.y-Te.y))._round()),Te.y>=E&&Pe.y>=E||(Te.y>=E?Te=new sn(Te.x+(E-Te.y)/(Pe.y-Te.y)*(Pe.x-Te.x),E)._round():Pe.y>=E&&(Pe=new sn(Te.x+(E-Te.y)/(Pe.y-Te.y)*(Pe.x-Te.x),E)._round()),J&&Te.equals(J[J.length-1])||(J=[Te],F.push(J),R&&R.push({progress:{min:Qe+oZe(at,pt,Te)*Ue,max:1},parentIndex:q,prevPoint:at,nextPoint:pt})),J.push(Pe),R&&(R[R.length-1].progress.max=Qe+oZe(at,pt,Pe)*Ue,R[R.length-1].nextPoint=pt)))))}if(R&&fe>0)for(let ye=le;yeJ.t-le.t);let F=0,q=0,K=[];for(S.push(K);F!==j.length;){if(q===R.length){for(;F!==j.length;)K.length!==0&&K[K.length-1].equals(j[F])||K.push(j[F]),F++;break}R[q].t<=F?(K.length!==0&&K[K.length-1].equals(R[q].point)||K.push(R[q].point),Math.trunc(R[q].t),q++):(K.length!==0&&K[K.length-1].equals(j[F])||K.push(j[F]),F++)}}function oZe(j,p,v){return j.x!==p.x?(v.x-j.x)/(p.x-j.x):j.y!==p.y?(v.y-j.y)/(p.y-j.y):0}function zq(j,p){return j.x*p.x+j.y*p.y}function lZe(j,p){if(j.length===1){let v=0;const S=p[v++];let E;for(;!E||S.equals(E);)if(E=p[v++],!E)return 1/0;for(;v{fn[0]=_n,fn[1]=Sn,fn[2]=wn,fn[3]=1},dn=eZe();Te>0&&(Te+=dn),Pe+=dn;for(const fn of ye){const _n=[],Sn=[];for(const wn of fn){const Un=wn.x+Ue.x,ln=wn.y+Ue.y,Nn=fe.projection.projectTilePoint(Un,ln,Tt),Tn=fe.projection.upVector(Tt,wn.x,wn.y);let Vn=Te,ar=Pe;if(at){const zr=uZe(Un,ln,Te,Pe,at,pt,dt,wt);Vn+=zr.base,ar+=zr.top}Te!==0?is(ps,Nn.x+Tn[0]*Jt*Vn,Nn.y+Tn[1]*Jt*Vn,Nn.z+Tn[2]*Jt*Vn):is(ps,Nn.x,Nn.y,Nn.z),is(rs,Nn.x+Tn[0]*Jt*ar,Nn.y+Tn[1]*Jt*ar,Nn.z+Tn[2]*Jt*ar),Ge(ps,ps,Qe),Ge(rs,rs,Qe),_n.push(new k6(ps[0],ps[1],ps[2])),Sn.push(new k6(rs[0],rs[1],rs[2]))}Lt.push(_n),fs.push(Sn)}return[Lt,fs]}(j,p,v,S,E,R,F,q,K,J,le):F?function(fe,ye,Te,Pe,Ue,Qe,at,pt,dt){const wt=[],Tt=[],Lt=[0,0,0,1];for(const fs of fe){const Jt=[],ps=[];for(const rs of fs){const is=rs.x+Pe.x,dn=rs.y+Pe.y,fn=uZe(is,dn,ye,Te,Qe,at,pt,dt);Lt[0]=is,Lt[1]=dn,Lt[2]=fn.base,Lt[3]=1,ht(Lt,Lt,Ue),Lt[3]=Math.max(Lt[3],1e-5);const _n=new k6(Lt[0]/Lt[3],Lt[1]/Lt[3],Lt[2]/Lt[3]);Lt[0]=is,Lt[1]=dn,Lt[2]=fn.top,Lt[3]=1,ht(Lt,Lt,Ue),Lt[3]=Math.max(Lt[3],1e-5);const Sn=new k6(Lt[0]/Lt[3],Lt[1]/Lt[3],Lt[2]/Lt[3]);Jt.push(_n),ps.push(Sn)}wt.push(Jt),Tt.push(ps)}return[wt,Tt]}(p,v,S,E,R,F,q,K,J):function(fe,ye,Te,Pe,Ue){const Qe=[],at=[],pt=Ue[8]*ye,dt=Ue[9]*ye,wt=Ue[10]*ye,Tt=Ue[11]*ye,Lt=Ue[8]*Te,fs=Ue[9]*Te,Jt=Ue[10]*Te,ps=Ue[11]*Te;for(const rs of fe){const is=[],dn=[];for(const fn of rs){const _n=fn.x+Pe.x,Sn=fn.y+Pe.y,wn=Ue[0]*_n+Ue[4]*Sn+Ue[12],Un=Ue[1]*_n+Ue[5]*Sn+Ue[13],ln=Ue[2]*_n+Ue[6]*Sn+Ue[14],Nn=Ue[3]*_n+Ue[7]*Sn+Ue[15],Tn=wn+pt,Vn=Un+dt,ar=ln+wt,zr=Math.max(Nn+Tt,1e-5),yr=wn+Lt,gr=Un+fs,ir=ln+Jt,Dr=Math.max(Nn+ps,1e-5);is.push(new k6(Tn/zr,Vn/zr,ar/zr)),dn.push(new k6(yr/Dr,gr/Dr,ir/Dr))}Qe.push(is),at.push(dn)}return[Qe,at]}(p,v,S,E,R)}function uZe(j,p,v,S,E,R,F,q){const K=F*E.getElevationAt(j,p,!0,!0),J=R[0]!==0,le=J?R[1]===0?F*(R[0]/7-450):F*function(fe,ye,Te){const Pe=Math.floor(ye[0]/8),Ue=Math.floor(ye[1]/8),Qe=10*(ye[0]-8*Pe),at=10*(ye[1]-8*Ue),pt=fe.getElevationAt(Pe,Ue,!0,!0),dt=fe.getMeterToDEM(Te),wt=Math.floor(.5*(Qe*dt-1)),Tt=Math.floor(.5*(at*dt-1)),Lt=fe.tileCoordToPixel(Pe,Ue),fs=2*wt+1,Jt=2*Tt+1,ps=function(Sn,wn,Un,ln,Nn){return[Sn.getElevationAtPixel(wn,Un,!0),Sn.getElevationAtPixel(wn+Nn,Un,!0),Sn.getElevationAtPixel(wn,Un+Nn,!0),Sn.getElevationAtPixel(wn+ln,Un+Nn,!0)]}(fe,Lt.x-wt,Lt.y-Tt,fs,Jt),rs=Math.abs(ps[0]-ps[1]),is=Math.abs(ps[2]-ps[3]),dn=Math.abs(ps[0]-ps[2])+Math.abs(ps[1]-ps[3]),fn=Math.min(.25,.5*dt*(rs+is)/fs),_n=Math.min(.25,.5*dt*dn/Jt);return pt+Math.max(fn*Qe,_n*at)}(E,R,q):K;return{base:K+(v===0?-1:v),top:J?Math.max(le+S,K+v+2):K+S}}const jTe=4096;class MUt{constructor(p){this.module=p,this.memoryStack=this.module.malloc(jTe),this.memoryStackNextFree=this.memoryStack}createIntArray(p){const v=this.memoryStackNextFree;return this.memoryStackNextFree+=p.length*Int32Array.BYTES_PER_ELEMENT,this.memoryStackNextFree-this.memoryStack>jTe?-1:(new Int32Array(this.module.heap32.buffer,v,p.length).set(p),v)}createFloatArray(p){const v=this.memoryStackNextFree;return this.memoryStackNextFree+=p.length*Float32Array.BYTES_PER_ELEMENT,this.memoryStackNextFree-this.memoryStack>jTe?-1:(new Float32Array(this.module.heapF32.buffer,v,p.length).set(p),v)}readStringBuffer(p){let v="";for(;this.module.heapU8[p]!==0;)v+=String.fromCharCode(this.module.heapU8[p]),++p;return v}setStyle(p){const v=p.normalScale;this.module.setStyle(v[0],v[1],v[2],p.tileToMeters)}setAOOptions(p,v){this.module.setAOOptions(p?1:0,v)}setMetricOptions(p,v){this.module.setMetricOptions(p?1:0,v)}setStructuralOptions(p){this.module.setStructuralOptions(p?1:0)}setFacadeOptions(p,v){this.module.setFacadeOptions(p,v?1:0)}setFauxFacadeOptions(p,v,S){this.module.setFauxFacadeOptions(p?1:0,v?1:0,S)}setFacadeClassifierOptions(p){this.module.setFacadeClassifierOptions(p)}generateMesh(p,v){this.memoryStackNextFree=this.memoryStack;for(const q of p){const K=this.createIntArray(q.ringIndices),J=this.createFloatArray(q.coordinates);if(K===-1||J===-1)return`building_gen: Out of stack memory: ${this.memoryStackNextFree-this.memoryStack}/4096`;this.module.addFeature(q.id,q.sourceId,q.minHeight,q.height,q.roofType,J,K,q.ringIndices.length-1)}for(const q of v){let K;K=q.entrances?JSON.parse(q.entrances):[];const J=this.createFloatArray(K),le=this.createFloatArray(q.coordinates);if(J===-1||le===-1)return`building_gen: Out of stack memory: ${this.memoryStackNextFree-this.memoryStack}/4096`;this.module.addFacade(q.sourceId,q.crossPerc,q.distanceToRoad,J,K.length,le,q.coordinates.length)}if(!this.module.generateMesh()){const q=this.module.getLastError();return this.readStringBuffer(q)}const S=this.module.getMeshCount(),E=new Array(S);for(let q=0;q>2)-3,Qe=Te[Pe++]>>2;if(Pe++,E.json=JSON.parse(_Ze.decode(Te.subarray(Pe,Pe+Qe))),Pe+=Qe,Pe>>0,Math.ceil(1.2*wt)),Lt=Math.ceil((Tt-wt)/65536);try{return Ue.grow(Lt),Qe(),!0}catch{return!1}},b:at}};return(WebAssembly.instantiateStreaming?WebAssembly.instantiateStreaming(Te,pt):Te.then(dt=>dt.arrayBuffer()).then(dt=>WebAssembly.instantiate(dt,pt))).then(dt=>{const{Rb:wt,Qb:Tt,P:Lt,T:fs,X:Jt,Ja:ps,La:rs,Qa:is,Va:dn,Wa:fn,eb:_n,jb:Sn,f:wn,e:Un,yb:ln,zb:Nn,Ab:Tn,Bb:Vn,Db:ar,Gb:zr}=dt.instance.exports;Ue=Un;const yr=(()=>{let gr=0,ir=0,Dr=0,Zr=0;return Aa=>{Dr&&(wt(Zr),wt(gr),ir+=Dr,Dr=gr=0),gr||(ir+=128,gr=Tt(ir));const ma=Aa.length+7&-8;let mi=gr;ma>=ir&&(Dr=ma,mi=Zr=Tt(ma));for(let bo=0;bo{Kj=Te,Bq=void 0}))}()),ye&&le.push(function(){if(NTe)return;const Te=function(Pe){let Ue;const Qe=WebAssembly.instantiateStreaming(Pe,{}).then(dt=>{Ue=dt.instance,Ue.exports.__wasm_call_ctors()}),at={NONE:"",OCTAHEDRAL:"meshopt_decodeFilterOct",QUATERNION:"meshopt_decodeFilterQuat",EXPONENTIAL:"meshopt_decodeFilterExp"},pt={ATTRIBUTES:"meshopt_decodeVertexBuffer",TRIANGLES:"meshopt_decodeIndexBuffer",INDICES:"meshopt_decodeIndexSequence"};return{ready:Qe,supported:!0,decodeGltfBuffer(dt,wt,Tt,Lt,fs,Jt){(function(ps,rs,is,dn,fn,_n,Sn){const wn=ps.exports.sbrk,Un=dn+3&-4,ln=wn(Un*fn),Nn=wn(_n.length),Tn=new Uint8Array(ps.exports.memory.buffer);Tn.set(_n,Nn);const Vn=rs(ln,dn,fn,Nn,_n.length);if(Vn===0&&Sn&&Sn(ln,Un,fn),is.set(Tn.subarray(ln,ln+dn*fn)),wn(ln-wn(0)),Vn!==0)throw new Error(`Malformed buffer data: ${Vn}`)})(Ue,Ue.exports[pt[fs]],dt,wt,Tt,Lt,Ue.exports[at[Jt]])}}}(fetch(Ra()));return Te.ready.then(()=>{NTe=Te})}()),F)for(let Te=0;Te{const q=Ym(S,(K,J)=>{K?F(K):R(J)});E&&E.addEventListener("abort",()=>{q.cancel(),F(new DOMException("Aborted","AbortError"))},{once:!0})})}({url:j,type:"arrayBuffer"},p);return NZe(v,0,j,p)}function STe(j){switch(j){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 CTe(j){switch(j){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 ZN{constructor(p,v,S,E){this.context=p,this.format=S,this.useMipmap=E&&E.useMipmap,this.texture=p.gl.createTexture(),this.update(v,{premultiply:E&&E.premultiply})}update(p,v){const S=p&&p instanceof HTMLVideoElement&&p.width===0?p.videoWidth:p.width,E=p&&p instanceof HTMLVideoElement&&p.height===0?p.videoHeight:p.height,{context:R}=this,{gl:F}=R,{x:q,y:K}=v&&v.position?v.position:{x:0,y:0},J=q+S,le=K+E;this.size&&(this.size[0]!==J||this.size[1]!==le)&&(!v||v.recreateWhenResize===void 0||v.recreateWhenResize)&&(F.bindTexture(F.TEXTURE_2D,null),F.deleteTexture(this.texture),this.texture=F.createTexture(),this.size=null),F.bindTexture(F.TEXTURE_2D,this.texture),R.pixelStoreUnpackFlipY.set(!1),R.pixelStoreUnpack.set(1),R.pixelStoreUnpackPremultiplyAlpha.set(this.format===F.RGBA8&&(!v||v.premultiply!==!1));const fe=p instanceof HTMLImageElement||p instanceof HTMLCanvasElement||p instanceof HTMLVideoElement||p instanceof ImageData||ImageBitmap&&p instanceof ImageBitmap;if(!this.size&&J>0&&le>0){const ye=this.useMipmap?Math.floor(Math.log2(Math.max(J,le)))+1:1;F.texStorage2D(F.TEXTURE_2D,ye,this.format,J,le),this.size=[J,le]}this.size&&(fe?F.texSubImage2D(F.TEXTURE_2D,0,q,K,STe(this.format),CTe(this.format),p):"data"in p&&p.data&&F.texSubImage2D(F.TEXTURE_2D,0,q,K,S,E,STe(this.format),CTe(this.format),p.data)),this.useMipmap&&F.generateMipmap(F.TEXTURE_2D)}bind(p,v,S=!1){const{context:E}=this,{gl:R}=E;R.bindTexture(R.TEXTURE_2D,this.texture),p!==this.minFilter&&(R.texParameteri(R.TEXTURE_2D,R.TEXTURE_MAG_FILTER,p),R.texParameteri(R.TEXTURE_2D,R.TEXTURE_MIN_FILTER,this.useMipmap&&!S?p===R.NEAREST?R.NEAREST_MIPMAP_NEAREST:R.LINEAR_MIPMAP_LINEAR:p),this.minFilter=p),v!==this.wrapS&&(R.texParameteri(R.TEXTURE_2D,R.TEXTURE_WRAP_S,v),R.texParameteri(R.TEXTURE_2D,R.TEXTURE_WRAP_T,v),this.wrapS=v)}bindExtraParam(p,v,S,E,R){const{context:F}=this,{gl:q}=F;q.bindTexture(q.TEXTURE_2D,this.texture),v!==this.magFilter&&(q.texParameteri(q.TEXTURE_2D,q.TEXTURE_MAG_FILTER,v),this.magFilter=v),p!==this.minFilter&&(q.texParameteri(q.TEXTURE_2D,q.TEXTURE_MIN_FILTER,this.useMipmap?p===q.NEAREST?q.NEAREST_MIPMAP_NEAREST:q.LINEAR_MIPMAP_LINEAR:p),this.minFilter=p),S!==this.wrapS&&(q.texParameteri(q.TEXTURE_2D,q.TEXTURE_WRAP_S,S),this.wrapS=S),E!==this.wrapT&&(q.texParameteri(q.TEXTURE_2D,q.TEXTURE_WRAP_T,E),this.wrapT=E),R!==this.compareMode&&(R?(q.texParameteri(q.TEXTURE_2D,q.TEXTURE_COMPARE_MODE,q.COMPARE_REF_TO_TEXTURE),q.texParameteri(q.TEXTURE_2D,q.TEXTURE_COMPARE_FUNC,R)):q.texParameteri(q.TEXTURE_2D,q.TEXTURE_COMPARE_MODE,q.NONE),this.compareMode=R)}destroy(){const{gl:p}=this.context;p.deleteTexture(this.texture),this.texture=null}}class Uq{constructor(p,v){this.context=p,this.texture=v}bind(p,v){const{context:S}=this,{gl:E}=S;E.bindTexture(E.TEXTURE_2D,this.texture),p!==this.minFilter&&(E.texParameteri(E.TEXTURE_2D,E.TEXTURE_MAG_FILTER,p),E.texParameteri(E.TEXTURE_2D,E.TEXTURE_MIN_FILTER,p),this.minFilter=p),v!==this.wrapS&&(E.texParameteri(E.TEXTURE_2D,E.TEXTURE_WRAP_S,v),E.texParameteri(E.TEXTURE_2D,E.TEXTURE_WRAP_T,v),this.wrapS=v)}}const FUt=Pn([{name:"a_pos_3f",components:3,type:"Float32"}]),zUt=Pn([{name:"a_color_3f",components:3,type:"Float32"}]),BUt=Pn([{name:"a_color_4f",components:4,type:"Float32"}]),$Ut=Pn([{name:"a_uv_2f",components:2,type:"Float32"}]),UUt=Pn([{name:"a_normal_3f",components:3,type:"Float32"}]),qUt=Pn([{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"}]),VUt=Pn([{name:"a_pbr",components:4,type:"Uint16"},{name:"a_heightBasedEmissiveStrength",components:3,type:"Float32"}]);function SZe(j,p){const v=bee(j.projection,j.zoom,j.width,j.height),S=function(R,F,q,K,J){const le=new Cs(q.lng-180*lC,q.lat),fe=new Cs(q.lng+180*lC,q.lat),ye=R.project(le.lng,le.lat),Te=R.project(fe.lng,fe.lat),Pe=-Math.atan2(Te.y-ye.y,Te.x-ye.x),Ue=Yr.fromLngLat(q);Ue.y=it(Ue.y,-1+lC,1-lC);const Qe=Ue.toLngLat(),at=R.project(Qe.lng,Qe.lat),pt=Yr.fromLngLat(Qe);pt.x+=lC;const dt=pt.toLngLat(),wt=R.project(dt.lng,dt.lat),Tt=AZe(wt.x-at.x,wt.y-at.y,Pe),Lt=Yr.fromLngLat(Qe);Lt.y+=lC;const fs=Lt.toLngLat(),Jt=R.project(fs.lng,fs.lat),ps=AZe(Jt.x-at.x,Jt.y-at.y,Pe),rs=Math.abs(Tt.x)/Math.abs(ps.y),is=x([]);I(is,is,-Pe*(1-(J?0:K)));const dn=x([]);return A(dn,dn,[1,1-(1-rs)*K,1]),dn[4]=-ps.x/ps.y*K,I(dn,dn,Pe),b(dn,is,dn),dn}(j.projection,0,j.center,v,p),E=CZe(j);return A(S,S,[E,E,1]),S}function CZe(j){const p=j.projection,v=bee(j.projection,j.zoom,j.width,j.height),S=ATe(p,j.center),E=ATe(p,Cs.convert(p.center));return Math.pow(2,S*v+(1-v)*E)}function bee(j,p,v,S,E=1/0){const R=j.range;if(!R)return 0;const F=Math.min(E,Math.max(v,S)),q=Math.log2(F/1024);return ft(R[0]+q,R[1]+q,p)}const lC=1/4e4;function ATe(j,p){const v=it(p.lat,-85.051129,vn),S=new Cs(p.lng-180*lC,v),E=new Cs(p.lng+180*lC,v),R=j.project(S.lng,v),F=j.project(E.lng,v),q=Yr.fromLngLat(S),K=Yr.fromLngLat(E),J=F.x-R.x,le=F.y-R.y,fe=K.x-q.x,ye=K.y-q.y,Te=Math.sqrt((fe*fe+ye*ye)/(J*J+le*le));return Math.log2(Te)}function AZe(j,p,v){const S=Math.cos(v),E=Math.sin(v);return{x:j*S-p*E,y:j*E+p*S}}function TZe(j,p,v){x(j),I(j,j,Nr(p[2])),T(j,j,Nr(p[0])),P(j,j,Nr(p[1])),A(j,j,v),b(j,j,[1,0,0,0,0,0,1,0,0,1,0,0,0,0,0,1])}function _ee(j,p,v,S,E,R,F,q){const K=[v[0]-p[0],v[1]-p[1],0],J=[S[0]-p[0],S[1]-p[1],0];if(X(K)<1e-12||X(J)<1e-12)return Ct(j);const le=Be([],K,J);Me(le,le),ue(J,S,p),K[2]=(R-E)*q,J[2]=(F-E)*q;const fe=K;return Be(fe,K,J),Me(fe,fe),Os(j,le,fe)}function wee(j,p,v=!1){const S=jS(p.zoom),E=function(R,F,q){const K=F.worldSize,J=[R[12],R[13],R[14]],le=cn(J[1]/K),fe=Es(J[0]/K),ye=x([]),Te=Ks(1,le)*K,Pe=Ks(1,0)*K*nr(le,F.zoom),Ue=1/JAe(K);let Qe=Pe*Ue;if(q){const wt=bee(F.projection,F.zoom,F.width,F.height,1024);Qe=Ue*F.projection.pixelSpaceConversion(F.center.lat,K,wt)}const at=Zt(le,fe);me(at,at,xe([],Me([],at),Te*Qe*J[2]));const pt=function(wt){const Tt=[wt[0],wt[1],wt[2]];let Lt=[0,1,0];const fs=Be([],Lt,Tt);return Be(Lt,Tt,fs),Se(Lt)===0&&(Lt=[0,1,0],Be(fs,Tt,Lt)),Me(fs,fs),Me(Lt,Lt),Me(Tt,Tt),[fs[0],fs[1],fs[2],0,Lt[0],Lt[1],Lt[2],0,Tt[0],Tt[1],Tt[2],0,wt[0],wt[1],wt[2],1]}(at);A(ye,ye,[Qe,Qe,Qe*Te]),k(ye,ye,[-J[0],-J[1],-J[2]]);const dt=b([],F.globeMatrix,pt);return b(dt,dt,ye),b(dt,dt,R),dt}(j,p,v);if(S>0){const R=function(F,q){const K=q.worldSize,J=Ks(1,0)*K*nr(q.center.lat,q.zoom)/JAe(K),le=Ks(1,q.center.lat)*K,fe=x([]);P(fe,fe,Nr(q.center.lng)),T(fe,fe,Nr(q.center.lat)),k(fe,fe,[0,0,Ft]),A(fe,fe,[J,J,J*le]);const ye=q.point;return k(fe,fe,[-ye.x,-ye.y,0]),b(fe,fe,F),b(fe,q.globeMatrix,fe)}(j,p);return function(F,q,K){const J=(Pe,Ue,Qe)=>{const at=X(Pe),pt=X(Ue),dt=wS(Pe,Ue,Qe);return xe(dt,dt,1/X(dt)*mr(at,pt,Qe))},le=J([F[0],F[1],F[2]],[q[0],q[1],q[2]],K),fe=J([F[4],F[5],F[6]],[q[4],q[5],q[6]],K),ye=J([F[8],F[9],F[10]],[q[8],q[9],q[10]],K),Te=wS([F[12],F[13],F[14]],[q[12],q[13],q[14]],K);return[le[0],le[1],le[2],0,fe[0],fe[1],fe[2],0,ye[0],ye[1],ye[2],0,Te[0],Te[1],Te[2],1]}(E,R,S)}return E}function TTe(j,p,v,S){const E=sl.projectAabbCorners(S,v);let R=Number.MAX_VALUE;for(let q=0;q0||Qe===0&&Pe[0]*Ue[0]+Pe[1]*Ue[1]>=0&&Pe[0]*Pe[0]+Pe[1]*Pe[1]>Ue[0]*Ue[0]+Ue[1]*Ue[1])&&(le=Te)}fe=le}while(fe!==J);return K.length>0&&K.push(K[0]),K}(E);if(gu(j,F))return R}const S6=64,DO={CoordinateSpaceTile:1,HasMapboxMeshFeatures:4,HasMeshoptCompression:8};function jee(j,p,v,S,E,R,F,q,K,J=!1){const le=v.zoom,fe=v.project(S),ye=nr(S.lat,le),Te=1/ye;x(j),k(j,j,[fe.x+F[0]*Te,fe.y+F[1]*Te,F[2]]);let Pe=1,Ue=1;const Qe=v.worldSize;if(J){if(v.projection.name==="mercator"){let wt=0;v.elevation&&(wt=v.elevation.getAtPointOrZero(new Yr(fe.x/Qe,fe.y/Qe),0));const Tt=ht([],[fe.x,fe.y,wt,1],v.projMatrix)[3]/v.cameraToCenterDistance;Pe=Tt,Ue=Tt*nr(v.center.lat,le)}else if(v.projection.name==="globe"){const wt=wee(j,v),Tt=[0,0,0,1];ht(Tt,Tt,b([],v.projMatrix,wt));const Lt=Tt[3]/v.cameraToCenterDistance,fs=jS(le),Jt=v.projection.pixelsPerMeter(S.lat,Qe)*nr(S.lat,le),ps=v.projection.pixelsPerMeter(v.center.lat,Qe)*nr(v.center.lat,le);Pe=Lt/mr(Jt,fr(v.center.lat),fs),Ue=Lt*ye/Jt,Pe*=ps,Ue*=ps}}else Pe=Te;A(j,j,[Pe,Pe,Ue]);const at=[...j],pt=p.orientation,dt=[];if(TZe(dt,[pt[0]+(E?E[0]:0),pt[1]+(E?E[1]:0),pt[2]+(E?E[2]:0)],R),b(j,at,dt),q&&v.elevation){let wt=0;const Tt=[];if(K&&v.elevation){wt=function(fs,Jt,ps,rs,is){const dn=Jt.elevation;if(!dn)return 0;const fn=sl.projectAabbCorners(ps,rs),_n=Ks(1,is.lat)*Jt.worldSize,Sn=function(ir,Dr){const Zr=[0,0,1],Aa=[{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 ma of Aa){const mi=ir[ma.corners[0]],bo=ir[ma.corners[1]],pi=ir[ma.corners[2]],ko=[bo[0]-mi[0],bo[1]-mi[1],Dr*(bo[2]-mi[2])],Ii=Be(ko,ko,[pi[0]-mi[0],pi[1]-mi[1],Dr*(pi[2]-mi[2])]);Me(Ii,Ii),ma.dotProductWithUp=Re(Ii,Zr)}return Aa.sort((ma,mi)=>ma.dotProductWithUp-mi.dotProductWithUp),Aa[0].corners}(fn,_n),wn=fn[Sn[0]],Un=fn[Sn[1]],ln=fn[Sn[2]],Nn=fn[Sn[3]],Tn=dn.getAtPointOrZero(new Yr(wn[0]/Jt.worldSize,wn[1]/Jt.worldSize),0),Vn=dn.getAtPointOrZero(new Yr(Un[0]/Jt.worldSize,Un[1]/Jt.worldSize),0),ar=dn.getAtPointOrZero(new Yr(ln[0]/Jt.worldSize,ln[1]/Jt.worldSize),0),zr=dn.getAtPointOrZero(new Yr(Nn[0]/Jt.worldSize,Nn[1]/Jt.worldSize),0),yr=(Tn+zr)/2,gr=(Vn+ar)/2;return yr>gr?Vn=p.gl.NEAREST_MIPMAP_NEAREST}),j.uploaded=!0,j.image=null)}function HUt(j,p,v){j.indexBuffer=p.createIndexBuffer(j.indexArray,!1,!0),j.vertexBuffer=p.createVertexBuffer(j.vertexArray,FUt.members,!1,!0),j.normalArray&&(j.normalBuffer=p.createVertexBuffer(j.normalArray,UUt.members,!1,!0)),j.texcoordArray&&(j.texcoordBuffer=p.createVertexBuffer(j.texcoordArray,$Ut.members,!1,!0)),j.colorArray&&(j.colorBuffer=p.createVertexBuffer(j.colorArray,(j.colorArray.bytesPerElement===12?zUt:BUt).members,!1,!0)),j.featureArray&&(j.pbrBuffer=p.createVertexBuffer(j.featureArray,VUt.members,!0)),j.segments=Ul.simpleSegment(0,0,j.vertexArray.length,j.indexArray.length);const S=j.material;S.pbrMetallicRoughness.baseColorTexture&&qq(S.pbrMetallicRoughness.baseColorTexture,p),S.pbrMetallicRoughness.metallicRoughnessTexture&&qq(S.pbrMetallicRoughness.metallicRoughnessTexture,p),S.normalTexture&&qq(S.normalTexture,p),S.occlusionTexture&&qq(S.occlusionTexture,p,v),S.emissionTexture&&qq(S.emissionTexture,p)}function ETe(j,p,v){if(j.meshes)for(const S of j.meshes)HUt(S,p,v);if(j.children)for(const S of j.children)ETe(S,p,v)}function Nee(j){if(j.meshes)for(const p of j.meshes)p.indexArray.destroy(),p.vertexArray.destroy(),p.colorArray&&p.colorArray.destroy(),p.normalArray&&p.normalArray.destroy(),p.texcoordArray&&p.texcoordArray.destroy(),p.featureArray&&p.featureArray.destroy();if(j.children)for(const p of j.children)Nee(p)}function GUt(j){j.pbrMetallicRoughness.baseColorTexture&&j.pbrMetallicRoughness.baseColorTexture.gfxTexture&&j.pbrMetallicRoughness.baseColorTexture.gfxTexture.destroy(),j.pbrMetallicRoughness.metallicRoughnessTexture&&j.pbrMetallicRoughness.metallicRoughnessTexture.gfxTexture&&j.pbrMetallicRoughness.metallicRoughnessTexture.gfxTexture.destroy(),j.normalTexture&&j.normalTexture.gfxTexture&&j.normalTexture.gfxTexture.destroy(),j.emissionTexture&&j.emissionTexture.gfxTexture&&j.emissionTexture.gfxTexture.destroy(),j.occlusionTexture&&j.occlusionTexture.gfxTexture&&j.occlusionTexture.gfxTexture.destroy()}function MTe(j){if(j.meshes)for(const p of j.meshes)p.vertexBuffer&&(p.vertexBuffer.destroy(),p.indexBuffer.destroy(),p.normalBuffer&&p.normalBuffer.destroy(),p.texcoordBuffer&&p.texcoordBuffer.destroy(),p.colorBuffer&&p.colorBuffer.destroy(),p.pbrBuffer&&p.pbrBuffer.destroy(),p.segments.destroy(),p.material&&GUt(p.material));if(j.footprintDebugMesh&&(j.footprintDebugMesh.vertexBuffer.destroy(),j.footprintDebugMesh.indexBuffer.destroy(),j.footprintDebugMesh.segments.destroy()),j.children)for(const p of j.children)MTe(p)}function C6(j,p){const v=j.json.bufferViews[p.bufferView],S=yee[p.componentType];return new S(j.buffers[v.buffer],(p.byteOffset||0)+(v.byteOffset||0),p.count*(v.byteStride&&v.byteStride!==$q[p.type]*S.BYTES_PER_ELEMENT?v.byteStride/S.BYTES_PER_ELEMENT:$q[p.type]))}function LTe(j,p,v,S){const E=yee[p.componentType],R=function(le){switch(le){case Int8Array:return 1/127;case Uint8Array:return 1/255;case Int16Array:return 1/32767;case Uint16Array:return 1/65535;default:return 1}}(E),F=j.json.bufferViews[p.bufferView],q=F.byteStride?F.byteStride/E.BYTES_PER_ELEMENT:$q[p.type],K=v.float32,J=K.length/v.capacity;for(let le=0,fe=0;le0){for(let Qe=0;Qe0){R.texcoordArray=new yS;const ye=p.json.accessors[E.TEXCOORD_0];R.texcoordArray.resize(ye.count);const Te=C6(p,ye);LTe(p,ye,R.texcoordArray,Te)}if(E._FEATURE_ID_RGBA4444!==void 0){const ye=p.json.accessors[E._FEATURE_ID_RGBA4444];p.json.extensionsUsed&&p.json.extensionsUsed.includes("EXT_meshopt_compression")&&(R.featureData=C6(p,ye))}E._FEATURE_RGBA4444!==void 0&&(R.featureData=new Uint32Array(C6(p,p.json.accessors[E._FEATURE_RGBA4444]).buffer));const fe=j.material;return R.material=function(ye,Te){const{emissiveFactor:Pe=[0,0,0],alphaMode:Ue="OPAQUE",alphaCutoff:Qe=.5,normalTexture:at,occlusionTexture:pt,emissiveTexture:dt,doubleSided:wt,name:Tt}=ye,{baseColorFactor:Lt=[1,1,1,1],metallicFactor:fs=1,roughnessFactor:Jt=1,baseColorTexture:ps,metallicRoughnessTexture:rs}=ye.pbrMetallicRoughness||{},is=pt?Te[pt.index]:void 0;if(pt&&pt.extensions&&pt.extensions.KHR_texture_transform&&is){const dn=pt.extensions.KHR_texture_transform;is.offsetScale=[dn.offset[0],dn.offset[1],dn.scale[0],dn.scale[1]]}return{name:Tt,pbrMetallicRoughness:{baseColorFactor:new cs(...Lt),metallicFactor:fs,roughnessFactor:Jt,baseColorTexture:ps?Te[ps.index]:void 0,metallicRoughnessTexture:rs?Te[rs.index]:void 0},doubleSided:wt,emissiveFactor:new cs(...Pe),alphaMode:Ue,alphaCutoff:Qe,normalTexture:at?Te[at.index]:void 0,occlusionTexture:is,emissionTexture:dt?Te[dt.index]:void 0,defined:ye.defined===void 0}}(fe!==void 0?p.json.materials[fe]:{defined:!1},v),R}function MZe(j,p,v){const{matrix:S,rotation:E,translation:R,scale:F,mesh:q,extras:K,children:J,name:le}=j,fe={};if(fe.name=le,fe.localMatrix=S||function(ye,Te,Pe,Ue){var Qe=Te[0],at=Te[1],pt=Te[2],dt=Te[3],wt=Qe+Qe,Tt=at+at,Lt=pt+pt,fs=Qe*wt,Jt=Qe*Tt,ps=Qe*Lt,rs=at*Tt,is=at*Lt,dn=pt*Lt,fn=dt*wt,_n=dt*Tt,Sn=dt*Lt,wn=Ue[0],Un=Ue[1],ln=Ue[2];return ye[0]=(1-(rs+dn))*wn,ye[1]=(Jt+Sn)*wn,ye[2]=(ps-_n)*wn,ye[3]=0,ye[4]=(Jt-Sn)*Un,ye[5]=(1-(fs+dn))*Un,ye[6]=(is+fn)*Un,ye[7]=0,ye[8]=(ps+_n)*ln,ye[9]=(is-fn)*ln,ye[10]=(1-(fs+rs))*ln,ye[11]=0,ye[12]=Pe[0],ye[13]=Pe[1],ye[14]=Pe[2],ye[15]=1,ye}([],E||[0,0,0,1],R||[0,0,0],F||[1,1,1]),fe.globalMatrix=y(fe.localMatrix),q!==void 0){fe.meshes=v[q];const ye=fe.anchor=[0,0];for(const Te of fe.meshes){const{min:Pe,max:Ue}=Te.aabb;ye[0]+=Pe[0]+Ue[0],ye[1]+=Pe[1]+Ue[1]}ye[0]=Math.floor(ye[0]/fe.meshes.length/2),ye[1]=Math.floor(ye[1]/fe.meshes.length/2)}if(K&&(K.id&&(fe.id=K.id),K.lights&&(fe.lights=function(ye){if(!ye.length)return[];const Te=function(pt){const dt=atob(pt),wt=new Uint8Array(dt.length);for(let Tt=0;Tt1&&S[S.length-1].equals(S[0])&&S.pop();let E=0;for(let F=0;F0&&S.reverse();const R=EO(S.flatMap(F=>[F.x,F.y]),[]);return R.length===0?null:{vertices:S,indices:R}}function ZUt(j,p){const v=[],S=[];let E=0;const R=[];for(const F of j){E=v.length;const q=F.vertexArray.float32,K=F.indexArray.uint16;for(let J=0;J0&&([S[F+1],S[F+2]]=[S[F+2],S[F+1]])}return{vertices:v,indices:S}}function PTe(j){const p=function(K,J){const le=[],fe=WebGL2RenderingContext;if(K.json.textures)for(const ye of K.json.textures){const Te={magFilter:fe.LINEAR,minFilter:fe.NEAREST,wrapS:fe.REPEAT,wrapT:fe.REPEAT};ye.sampler!==void 0&&Object.assign(Te,K.json.samplers[ye.sampler]),le.push({image:J[ye.source],sampler:Te,uploaded:!1})}return le}(j,j.images),v=function(K,J){const le=[];for(const fe of K.json.meshes){const ye=[];for(const Te of fe.primitives)ye.push(WUt(Te,K,J));le.push(ye)}return le}(j,p),{scenes:S,scene:E,nodes:R}=j.json,F=S?S[E||0].nodes:[...R.keys()],q=[];for(const K of F)q.push(MZe(R[K],j,v));return function(K,J,le){const fe={},ye=new Set;for(let Te=0;Te0){const Te=Array.from(ye.values()).sort((Pe,Ue)=>Pe-Ue);for(let Pe=Te.length-1;Pe>=0;Pe--)K.splice(Te[Pe],1)}}(q,F,j.json.nodes),q}function XUt(j){j.heightmap=new Float32Array(4096),j.heightmap.fill(-1);const p=j.vertexArray.float32,v=j.aabb.min[0]-1,S=j.aabb.min[1]-1,E=S6/(j.aabb.max[0]-v+2),R=S6/(j.aabb.max[1]-S+2);for(let F=0;Fj.heightmap[J*S6+K]&&(j.heightmap[J*S6+K]=q)}}function LZe(j,p,v,S,E){v.reserve(v.length+4*j.length),S.reserve(S.length+10*j.length),E.reserve(E.length+10*j.length);let R=S.length;for(const F of j){const q=Math.min(10,Math.max(4,1.3*F.height))*p,K=[-F.normal[1],F.normal[0],0],J=Math.min(.29,.1*F.width/F.depth),le=F.width-2*F.depth*p*(J+.01),fe=ve([],F.pos,K,le/2),ye=ve([],F.pos,K,-le/2),Te=[fe[0],fe[1],fe[2]+F.height],Pe=[ye[0],ye[1],ye[2]+F.height],Ue=ve([],F.normal,K,J);xe(Ue,Ue,q);const Qe=ve([],F.normal,K,-J);xe(Qe,Qe,q),me(Ue,fe,Ue),me(Qe,ye,Qe),fe[2]+=.1,ye[2]+=.1,S.emplaceBack(Ue[0],Ue[1],Ue[2]),S.emplaceBack(Qe[0],Qe[1],Qe[2]),S.emplaceBack(fe[0],fe[1],fe[2]),S.emplaceBack(ye[0],ye[1],ye[2]),S.emplaceBack(Te[0],Te[1],Te[2]),S.emplaceBack(Pe[0],Pe[1],Pe[2]),S.emplaceBack(fe[0],fe[1],fe[2]),S.emplaceBack(ye[0],ye[1],ye[2]),S.emplaceBack(Ue[0],Ue[1],Ue[2]),S.emplaceBack(Qe[0],Qe[1],Qe[2]);const at=le/q/2;E.emplaceBack(-at-J,-1,at,.8),E.emplaceBack(at+J,-1,at,.8),E.emplaceBack(-at,0,at,1.3),E.emplaceBack(at,0,at,1.3),E.emplaceBack(at+J,-.8,at,.7),E.emplaceBack(at+J,-.8,at,.7),E.emplaceBack(0,0,at,1.3),E.emplaceBack(0,0,at,1.3),E.emplaceBack(at+J,-1.2,at,.8),E.emplaceBack(at+J,-1.2,at,.8),v.emplaceBack(6+R,4+R,8+R),v.emplaceBack(7+R,9+R,5+R),v.emplaceBack(0+R,1+R,2+R),v.emplaceBack(1+R,3+R,2+R),R+=10}}function QUt(j,p){const v={};v.indexArray=new Zd,v.vertexArray=new N1,v.colorArray=new Gj,LZe(j,p,v.indexArray,v.vertexArray,v.colorArray);const S={defined:!0};S.emissiveFactor=cs.black;const E={};return E.baseColorFactor=cs.white,S.pbrMetallicRoughness=E,v.material=S,v.aabb=new sl([1/0,1/0,1/0],[-1/0,-1/0,-1/0]),v}const PZe=Pn([{name:"a_pos_3f",components:3,type:"Float32"}]),JUt=Pn([{name:"a_normal_3",components:3,type:"Int16"}]),eqt=Pn([{name:"a_centroid_3",components:3,type:"Int16"}]),IZe=Pn([{name:"a_part_color_emissive",components:2,type:"Uint16"}]),tqt=Pn([{name:"a_faux_facade_color_emissive",components:2,type:"Uint16"}]),sqt=Pn([{name:"a_faux_facade_data",components:4,type:"Uint16"}]),nqt=Pn([{name:"a_faux_facade_vertical_range",components:2,type:"Uint16"}]),rqt=Pn([{name:"a_bloom_attenuation",components:4,type:"Float32"}]),aqt=Pn([{name:"a_flood_light_wall_radius_1i16",components:1,type:"Int16"}]),DZe=ti.types,kee=32767;function iqt(j,p){const v=sr+p;for(const S of j)for(const E of S)if(E.x<-p||E.x>v||E.y<-p||E.y>v)return!1;return!0}function oqt(j){switch(j){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: ${j}`)}}class ITe{constructor(){this.layoutVertexArray=new N1,this.layoutAttenuationArray=new Gj,this.layoutColorArray=new k1,this.indexArray=new Zd,this.indexArrayForConflation=new Zd,this.segmentsBucket=new Ul}}class DTe{constructor(p){this.layoutFacadePaintArray=null,this.layoutFacadeDataArray=null,this.layoutFacadeVerticalRangeArray=null,this.segmentsBucket=new Ul,this.entranceBloom=new ITe;const v=66560;this.layoutVertexArray=new N1,this.layoutVertexArray.reserve(v),this.layoutNormalArray=new Fo,this.layoutNormalArray.reserve(v),this.layoutCentroidArray=new Fo,this.layoutCentroidArray.reserve(v),this.layoutColorArray=new k1,this.layoutColorArray.reserve(v),this.layoutFloodLightDataArray=new NO,this.layoutFloodLightDataArray.reserve(v),this.layoutAOArray=new kO,this.layoutAOArray.reserve(v),this.indexArray=new Zd,this.indexArray.reserve(66560),this.indexArrayForConflation=new Zd,this.segmentsBucket=new Ul,this.entranceBloom=new ITe,p&&(this.layoutFacadePaintArray=new k1,this.layoutFacadeDataArray=new tC,this.layoutFacadeVerticalRangeArray=new k1)}reserve(p,v,S){this.layoutVertexArray.reserveForAdditional(p),this.layoutCentroidArray.reserveForAdditional(p),this.layoutFloodLightDataArray.reserveForAdditional(p),this.layoutNormalArray.reserveForAdditional(p),this.layoutAOArray.reserveForAdditional(p),this.layoutColorArray.reserveForAdditional(p),this.indexArray.reserveForAdditional(v),S&&(this.layoutFacadePaintArray.reserveForAdditional(p),this.layoutFacadeDataArray.reserveForAdditional(p),this.layoutFacadeVerticalRangeArray.reserveForAdditional(p))}}class RZe{constructor(p){this.colorBufferUploaded=!1,this.maxHeight=0,this.replacementUpdateTime=0,this.activeReplacements=[],this.footprints=[],this.footprintsVertices=new yS,this.footprintsIndices=new vS,this.footprintsMin=new sn(1/0,1/0),this.footprintsMax=new sn(-1/0,-1/0),this.featuresOnBorder=[],this.buildingWithoutFacade=new DTe(!1),this.buildingWithFacade=new DTe(!0),this.indexArrayForConflationUploaded=!1,this.featureFootprintLookup=new Map,this.buildingIds=new Set,this.footprintLookup={},this.zoom=p.zoom,this.canonical=p.canonical,this.layers=p.layers,this.layerIds=this.layers.map(v=>v.fqid),this.index=p.index,this.hasPattern=!1,this.worldview=p.worldview,this.lut=p.lut,this.programConfigurations=new et(p.layers,{zoom:p.zoom,lut:p.lut}),this.stateDependentLayerIds=this.layers.filter(v=>v.isStateDependent()).map(v=>v.id),this.projection=p.projection,this.groundEffect=new _Te(p),this.groundEffect.groundRadiusArray=new rl,this.hasAppearances=null}updateFootprints(p,v){const S=new lee([],[],1),E={vertices:[],indices:new Uint32Array(0),grid:S,min:this.footprintsMin,max:this.footprintsMax,buildingIds:this.buildingIds};v.push({footprint:E,id:p})}updateAppearances(p,v,S,E){return{hasLayoutChanges:!1,hasUboChanges:!1}}prepare(){return function(){if(xee!=null||hZe!=null)return null;if(IO!=null)return IO;const p=fetch(mo());return IO=function(v){let S,E,R,F,q;function K(){S=new Uint8Array(q.buffer),E=new Int16Array(q.buffer),R=new Int32Array(q.buffer),F=new Float32Array(q.buffer)}function J(){throw new Error("Unexpected BuildingGen error.")}const le=()=>{},fe={a:{a:J,f:function(ye){const Te=S.length,Pe=Math.max(ye>>>0,Math.ceil(1.2*Te)),Ue=Math.ceil((Pe-Te)/65536);try{return q.grow(Ue),K(),!0}catch{return!1}},g:J,b:le,c:le,d:le,e:le}};return(WebAssembly.instantiateStreaming?WebAssembly.instantiateStreaming(v,fe):v.then(ye=>ye.arrayBuffer()).then(ye=>WebAssembly.instantiate(ye,fe))).then(ye=>{const Te=ye.instance.exports;return(0,Te.g)(),q=Te.f,K(),new MUt({setStyle:Te.h,setAOOptions:Te.i,setMetricOptions:Te.j,setStructuralOptions:Te.k,setFacadeOptions:Te.l,setFauxFacadeOptions:Te.m,setFacadeClassifierOptions:Te.n,addFeature:Te.o,addFacade:Te.p,generateMesh:Te.q,getLastError:Te.r,getOuterRingLength:Te.s,getMeshCount:Te.t,getPositionsPtr:Te.u,getPositionsLength:Te.v,getNormalsPtr:Te.w,getNormalsLength:Te.x,getAOPtr:Te.y,getAOLength:Te.z,getUVPtr:Te.A,getUVLength:Te.B,getFauxFacadePtr:Te.C,getFauxFacadeLength:Te.D,getIndicesPtr:Te.E,getIndicesLength:Te.F,getBuildingPart:Te.G,getRingCount:Te.H,getRingPtr:Te.I,getRingLength:Te.J,malloc:Te.K,free:Te.L,heapU8:S,heap16:E,heap32:R,heapF32:F})})}(p).then(v=>(IO=null,xee=v,xee)).catch(v=>{Er("Could not load building-gen"),IO=null,hZe=v instanceof Error?v:new Error("Unknown error")}),IO}()}populate(p,v,S,E){const R=LUt();if(!R)return;const F=In(S);this.tileToMeter=F,this.brightness=v.brightness,R.setStyle({normalScale:[1,-1,F],tileToMeters:F}),R.setAOOptions(!1,.3),R.setMetricOptions(!1,16),R.setStructuralOptions(!0),R.setFacadeClassifierOptions(3);const q=new Map,K=new Map;let J=0;for(const{feature:at}of p){if(DZe[at.type]!=="LineString"){q.set(at.id,at.properties.source_id);continue}const pt=this.layers[0]._featureFilter.needGeometry;if(pt&&!this.layers[0]._featureFilter.filter(new xi(this.zoom),at,S))continue;const dt=Pi(at,pt);if(!pt&&!this.layers[0]._featureFilter.filter(new xi(this.zoom),dt,S))continue;const wt=pt?dt.geometry:Ea(at,S,E),Tt=[];for(const ps of wt)for(const rs of ps)Tt.push(rs.x),Tt.push(rs.y);const Lt={coordinates:Tt,crossPerc:at.properties.cross_perc,distanceToRoad:at.properties.distance_to_road,entrances:at.properties.entrances,sourceId:0},fs=at.properties.source_id;let Jt=K.get(fs);Jt||(Jt=[],K.set(fs,Jt)),Jt.push(Lt),++J}this.maxHeight=0;const le=new Array,fe=new Set,ye=at=>{at!=null&&fe.add(at)},Te=(at,pt)=>{at!=null&&le.push({buildingId:at,footprintIndex:pt})},Pe=64*(p.length-J),Ue=Pe/2;this.buildingWithFacade.reserve(Pe,Ue,!0),this.buildingWithoutFacade.reserve(2*Pe,2*Ue,!1),this.footprintsIndices.reserve(16*(p.length-J)),this.footprintsVertices.reserve(8*(p.length-J));for(const{feature:at,id:pt,index:dt,sourceLayerIndex:wt}of p){if(DZe[at.type]==="LineString")continue;const Tt=this.layers[0]._featureFilter.needGeometry;if(Tt&&!this.layers[0]._featureFilter.filter(new xi(this.zoom),at,S))continue;let Lt=null;if(at.properties&&at.properties.hasOwnProperty("building_id")&&(Lt=Number(at.properties.building_id),fe.has(Lt)))continue;const fs=Pi(at,Tt);if(!Tt&&!this.layers[0]._featureFilter.filter(new xi(this.zoom),fs,S))continue;const Jt=Tt?fs.geometry:Ea(at,S,E),ps=Lq(Jt,500);let rs=!1;for(const Zi of ps)if(Zi.length!==1){rs=!0;break}if(rs){ye(Lt);continue}if(!iqt(Jt,163)){ye(Lt);continue}const is=this.layers[0],dn=oqt(is.layout.get("building-roof-shape").evaluate(at,{},S)),fn=is.layout.get("building-base").evaluate(at,{},S),_n=is.layout.get("building-height").evaluate(at,{},S),Sn=is.layout.get("building-flood-light-ground-radius").evaluate(at,{},S),wn=is.paint.get("building-ambient-occlusion-intensity"),Un=Sn/this.tileToMeter;at.properties["building-part"]="roof";const ln=is.paint.get("building-color").evaluate(at,{},this.canonical).toPremultipliedRenderColor(this.lut),Nn=is.paint.get("building-emissive-strength").evaluate(at,{},this.canonical);at.properties["building-part"]="wall";const Tn=is.paint.get("building-color").evaluate(at,{},this.canonical).toPremultipliedRenderColor(this.lut),Vn=is.paint.get("building-emissive-strength").evaluate(at,{},this.canonical);at.properties["building-part"]="window";const ar=is.paint.get("building-color").evaluate(at,{},this.canonical).toPremultipliedRenderColor(this.lut),zr=is.paint.get("building-emissive-strength").evaluate(at,{},this.canonical);at.properties["building-part"]="door";const yr=is.paint.get("building-color").evaluate(at,{},this.canonical).toPremultipliedRenderColor(this.lut),gr=is.paint.get("building-emissive-strength").evaluate(at,{},this.canonical);let ir=is.layout.get("building-flood-light-wall-radius").evaluate(at,{},S);ir=it(ir,0,2048);const Dr=ir/2048*kee,Zr=q.get(pt),Aa=K.get(Zr)||[],ma=Aa.length!==0&&is.layout.get("building-facade").evaluate(at,{},S);R.setFacadeOptions(4,!0),R.setFauxFacadeOptions(ma,!1,1);let mi=0,bo=0,pi=0,ko=0,Ii=0,kd=0,Jo=0,Mo=0,Hl=0,pd=0,jm=0;if(ma){let Zi=Math.round(is.layout.get("building-facade-floors").evaluate(at,{},S));if(fn===0){Zi=Math.max(1,Zi-(Aa.length>0?1:0));let Jd=4;if(_n>100){const Xh=[10,13,15];Jd=Xh[at.id?at.id%Xh.length:0]}else _n<=10&&(Jd=3);R.setFacadeOptions(Jd,!0),Ii=(_n<15?1.3:1.61803)*Jd/F}else Ii=fn/F;kd=_n/F,Ii=Math.min(Ii,kd),pi=is.layout.get("building-facade-unit-width").evaluate(at,{},S)/F,ko=(kd-Ii)/Zi,R.setFauxFacadeOptions(!0,!0,pi);const dp=is.layout.get("building-facade-window").evaluate(at,{},S);mi=dp[0],bo=dp[1],Jo=Math.floor(65535*Math.min(1,Ii/sr)),Mo=Math.floor(65535*Math.min(1,kd/sr)),Hl=Math.floor(255*mi)<<8|Math.floor(255*bo),pd=Math.floor(65535*Math.min(1,pi/sr)),jm=Math.floor(65535*Math.min(1,ko/sr))}const fd=Array(ps.length),Xd={x:1/0,y:1/0},Xu={x:-1/0,y:-1/0},Qd={x:0,y:0};let Mf=0;for(let Zi=0;Zi0){const Jd=[],Xh=Array(dp.length+1);Xh[0]=0;for(let Bb=0;Bbsr||Xd.y<0||Xu.y>sr)&&this.featuresOnBorder.push({featureId:at.id,footprintIndex:this.footprints.length});{const Zi=EO(TS,null,2);this.footprintsIndices.resize(this.footprintsIndices.length+Zi.length),this.footprintsIndices.uint16.set(Zi,KO),this.buildingIds.add(Lt??at.id),this.footprintsMin.x=Math.min(this.footprintsMin.x,Fb.x),this.footprintsMin.y=Math.min(this.footprintsMin.y,Fb.y),this.footprintsMax.x=Math.max(this.footprintsMax.x,zb.x),this.footprintsMax.y=Math.max(this.footprintsMax.y,zb.y);const dp={footprintVertexOffset:AS,footprintVertexLength:this.footprintsVertices.length-AS,footprintIndexOffset:KO,footprintIndexLength:this.footprintsIndices.length-KO,min:Fb,max:zb,hiddenFlags:0,indicesOffset:ete,indicesLength:kEe,bloomIndicesOffset:Lf,bloomIndicesLength:Sd,groundEffectVertexOffset:I6,groundEffectVertexLength:YO,hasFauxFacade:ma,height:WO,promoteId:pt,feature:fs,parts:lp,buildingBloom:Nx},Jd=this.footprints.length;at.id!==void 0&&this.featureFootprintLookup.set(at.id,Jd),Te(Lt,Jd),this.footprints.push(dp)}this.programConfigurations.populatePaintArrays(Oi.layoutVertexArray.length,at,dt,{},v.availableImages,S,v.brightness),this.groundEffect.addPaintPropertiesData(at,dt,{},v.availableImages,S,v.brightness),v.featureIndex.insert(at,Jt,dt,wt,this.index,Dg)}le.forEach(({buildingId:at,footprintIndex:pt})=>{fe.has(at)&&(this.footprints[pt].hiddenFlags|=4)});const Qe=new Set;this.buildingIds.forEach((at,pt,dt)=>{fe.has(at)||Qe.add(at)}),this.buildingIds=Qe,this.groundEffect.prepareBorderSegments()}update(p,v,S,E,R,F,q){this.programConfigurations.updatePaintArrays(p,v,R,S,E,F,q),this.groundEffect.update(p,v,R,S,E,F,q),this.evaluate(this.layers[0],p),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(p){const v=S=>{S.layoutVertexBuffer=p.createVertexBuffer(S.layoutVertexArray,PZe.members),S.layoutNormalBuffer=p.createVertexBuffer(S.layoutNormalArray,JUt.members),S.layoutCentroidBuffer=p.createVertexBuffer(S.layoutCentroidArray,eqt.members),S.layoutFloodLightDataBuffer=p.createVertexBuffer(S.layoutFloodLightDataArray,aqt.members),S.layoutFacadeDataArray&&S.layoutFacadeDataArray.length&&(S.layoutFacadeDataBuffer=p.createVertexBuffer(S.layoutFacadeDataArray,sqt.members)),S.layoutFacadeVerticalRangeArray&&S.layoutFacadeVerticalRangeArray.length&&(S.layoutFacadeVerticalRangeBuffer=p.createVertexBuffer(S.layoutFacadeVerticalRangeArray,nqt.members)),S.entranceBloom.layoutVertexArray.length&&(S.entranceBloom.layoutVertexBuffer=p.createVertexBuffer(S.entranceBloom.layoutVertexArray,PZe.members),S.entranceBloom.layoutAttenuationBuffer=p.createVertexBuffer(S.entranceBloom.layoutAttenuationArray,rqt.members)),this.uploadUpdatedColorBuffer(p),this.uploadUpdatedIndexBuffer(p)};this.uploaded||(v(this.buildingWithoutFacade),v(this.buildingWithFacade),this.groundEffect.upload(p)),this.groundEffect.uploadPaintProperties(p),this.programConfigurations.upload(p),this.uploaded=!0}destroy(){const p=v=>{v.layoutVertexBuffer&&(v.layoutVertexBuffer.destroy(),v.layoutNormalBuffer.destroy(),v.layoutColorBuffer.destroy(),v.segmentsBucket.destroy(),v.indexBuffer&&v.indexBuffer.destroy(),v.entranceBloom.layoutVertexBuffer&&(v.entranceBloom.layoutVertexBuffer.destroy(),v.entranceBloom.layoutColorBuffer.destroy(),v.entranceBloom.layoutAttenuationBuffer.destroy(),v.entranceBloom.indexBuffer.destroy(),v.entranceBloom.segmentsBucket.destroy()))};p(this.buildingWithoutFacade),p(this.buildingWithFacade),this.groundEffect.destroy(),this.programConfigurations.destroy()}updateFootprintHiddenFlags(p,v,S=!0){let E=!1;const R=S?v:0,F=0|(S?-1:~v);this.groundEffect.hiddenByLandmarkVertexArray.length===0&&this.groundEffect.hiddenByLandmarkVertexArray.resize(this.groundEffect.vertexArray.length);for(const q of p){const K=this.footprints[q],J=K.hiddenFlags&F|R;K.hiddenFlags!==J&&(K.hiddenFlags=J,E=!0,this.groundEffect.updateHiddenByLandmarkRange(K.groundEffectVertexOffset,K.groundEffectVertexLength,K.hiddenFlags!==0))}return E&&(this.indexArrayForConflationUploaded=!1),E}uploadUpdatedIndexBuffer(p){if(this.groundEffect.uploadHiddenByLandmark(p),this.indexArrayForConflationUploaded)return;const v=E=>{E.indexArray.length!==0&&(E.indexArrayForConflation.resize(E.indexArray.length),E.indexArrayForConflation.uint16.set(E.indexArray.uint16),E.entranceBloom.indexArrayForConflation.resize(E.entranceBloom.indexArray.length),E.entranceBloom.indexArrayForConflation.uint16.set(E.entranceBloom.indexArray.uint16))};v(this.buildingWithoutFacade),v(this.buildingWithFacade);for(const E of this.footprints){const R=E.hasFauxFacade?this.buildingWithFacade:this.buildingWithoutFacade,F=E.indicesOffset+E.indicesLength;if(E.hiddenFlags!==0){for(let K=E.indicesOffset;K{E.indexArray.length!==0&&(E.indexBuffer?E.indexBuffer.updateData(E.indexArrayForConflation):E.indexBuffer=p.createIndexBuffer(E.indexArrayForConflation,!0),E.entranceBloom.indexBuffer?E.entranceBloom.indexBuffer.updateData(E.entranceBloom.indexArrayForConflation):E.entranceBloom.indexBuffer=p.createIndexBuffer(E.entranceBloom.indexArrayForConflation,!0))};S(this.buildingWithoutFacade),S(this.buildingWithFacade),this.indexArrayForConflationUploaded=!0}uploadUpdatedColorBuffer(p){const v=S=>{S.layoutColorBuffer?S.layoutColorBuffer.updateData(S.layoutColorArray):S.layoutColorBuffer=p.createVertexBuffer(S.layoutColorArray,IZe.members,!0),S.layoutFacadePaintArray&&(S.layoutFacadePaintBuffer?S.layoutFacadePaintBuffer.updateData(S.layoutFacadePaintArray):S.layoutFacadePaintBuffer=p.createVertexBuffer(S.layoutFacadePaintArray,tqt.members,!0)),S.entranceBloom.layoutColorBuffer?S.entranceBloom.layoutColorBuffer.updateData(S.entranceBloom.layoutColorArray):S.entranceBloom.layoutColorBuffer=p.createVertexBuffer(S.entranceBloom.layoutColorArray,IZe.members,!0)};v(this.buildingWithoutFacade),v(this.buildingWithFacade),this.colorBufferUploaded=!0}evaluate(p,v){const S=p.paint.get("building-ambient-occlusion-intensity");for(const E of this.footprints){if(4&E.hiddenFlags)continue;const R=v[E.promoteId],F=E.feature;F.properties["building-part"]="roof";const q=p.paint.get("building-color").evaluate(F,R,this.canonical).toPremultipliedRenderColor(this.lut),K=p.paint.get("building-emissive-strength").evaluate(F,R,this.canonical);F.properties["building-part"]="wall";const J=p.paint.get("building-color").evaluate(F,R,this.canonical).toPremultipliedRenderColor(this.lut),le=p.paint.get("building-emissive-strength").evaluate(F,R,this.canonical);F.properties["building-part"]="window";const fe=p.paint.get("building-color").evaluate(F,R,this.canonical).toPremultipliedRenderColor(this.lut),ye=p.paint.get("building-emissive-strength").evaluate(F,R,this.canonical);F.properties["building-part"]="door";const Te=p.paint.get("building-color").evaluate(F,R,this.canonical).toPremultipliedRenderColor(this.lut),Pe=p.paint.get("building-emissive-strength").evaluate(F,R,this.canonical),Ue=E.hasFauxFacade?this.buildingWithFacade:this.buildingWithoutFacade;for(const at of E.parts){let pt,dt=q;at.part===1?(dt=q,pt=K):at.part===0?(dt=J,pt=le):at.part===2?(dt=fe,pt=ye):at.part===3&&(dt=Te,pt=Pe),pt=it(pt,0,1);for(let wt=0;wtF.max.x||K.max.xF.max.y||K.max.yq.max.x||q.min.x>p||v>q.max.y||q.min.y>v||q.height<=S||lqt(F,this.footprintsVertices.float32.subarray(2*q.footprintVertexOffset,2*(q.footprintVertexOffset+q.footprintVertexLength)),this.footprintsIndices.uint16.subarray(q.footprintIndexOffset,q.footprintIndexOffset+q.footprintIndexLength))&&(S=q.height,this.footprintLookup[R]=q,E=q.hiddenFlags!==0);if(S!==Number.NEGATIVE_INFINITY)return{height:S,hidden:E};this.footprintLookup[R]=void 0}}function lqt(j,p,v){for(let S=0;S1&&(K=p[++q]);const le=Math.abs(J-K.left),fe=Math.abs(J-K.right),ye=Math.min(le,fe);let Te;const Pe=R/S*(E+1);if(K.isDash){const Ue=E-Math.abs(Pe);Te=Math.sqrt(ye*ye+Ue*Ue)}else Te=E-Math.sqrt(ye*ye+Pe*Pe);this.image.data[F+J]=Math.max(0,Math.min(255,Te+128))}}}addRegularDash(p,v){for(let K=p.length-1;K>=0;--K){const J=p[K],le=p[K+1];J.zeroLength?p.splice(K,1):le&&le.isDash===J.isDash&&(le.left=J.left,p.splice(K,1))}const S=p[0],E=p[p.length-1];S.isDash===E.isDash&&(S.left=E.left-this.width,E.right=S.right+this.width);const R=this.width*this.nextRow;let F=0,q=p[F];for(let K=0;K1&&(q=p[++F]);const J=Math.abs(K-q.left),le=Math.abs(K-q.right),fe=Math.min(J,le);this.image.data[R+K]=Math.max(0,Math.min(255,(q.isDash?fe:-fe)+v+128))}}addDash(p,v){const S=this.getKey(p,v);if(this.positions[S])return this.positions[S];const E=v==="round",R=E?7:0,F=2*R+1;if(this.nextRow+F>this.height)return Er("LineAtlas out of space"),null;p.length===0&&p.push(1);let q=0;for(let fe=0;fev.fqid),this.index=p.index,this.projection=p.projection,this.hasPattern=!1,this.hasCrossSlope=!1,this.patternFeatures=[],this.lineClipsArray=[],this.gradients={},this.layers.forEach(v=>{this.gradients[v.id]={}}),this.layoutVertexArray=new h6,this.layoutVertexArray2=new N1,this.patternVertexArray=new N1,this.indexArray=new Zd,this.programConfigurations=new et(p.layers,{zoom:p.zoom,lut:p.lut}),this.segments=new Ul,this.maxLineLength=0,this.zOffsetVertexArray=new N1,this.elevationGroundScaleVertexArray=new rl,this.stateDependentLayerIds=this.layers.filter(v=>v.isStateDependent()).map(v=>v.id),this.tessellationStep=p.tessellationStep?p.tessellationStep:128,this.worldview=p.worldview,this.hasAppearances=null}updateFootprints(p,v){}updateAppearances(p,v,S,E){return{hasLayoutChanges:!1,hasUboChanges:!1}}populate(p,v,S,E){this.hasPattern=rTe("line",this.layers,this.pixelRatio,v);const R=this.layers[0].layout.get("line-sort-key");this.tileToMeter=In(S);const F=this.layers[0].layout.get("line-elevation-reference");if(F==="hd-road-markup")this.elevationType="road";else{const ye=this.layers[0].layout.get("line-z-offset"),Te=ye.isConstant()&&!ye.constantOr(0);this.elevationType=F!=="sea"&&F!=="ground"&&Te?"none":"offset",this.elevationType==="offset"&&F==="none"&&Er(`line-elevation-reference: ground is used for the layer ${this.layerIds[0]} because non-zero line-z-offset value was found.`),this.isSeaLevelReference=F==="sea"}const q=this.layers[0].layout.get("line-cross-slope");this.hasCrossSlope=this.elevationType==="offset"&&q!==void 0;const K=[];for(const{feature:ye,id:Te,index:Pe,sourceLayerIndex:Ue}of p){const Qe=this.layers[0]._featureFilter.needGeometry,at=Pi(ye,Qe);if(!this.layers[0]._featureFilter.filter(new xi(this.zoom,{worldview:this.worldview,activeFloors:v.activeFloors}),at,S))continue;const pt=R?R.evaluate(at,{},S):void 0,dt={id:Te,properties:ye.properties,type:ye.type,sourceLayerIndex:Ue,index:Pe,geometry:Qe?at.geometry:Ea(ye,S,E),patterns:{},sortKey:pt};K.push(dt)}R&&K.sort((ye,Te)=>ye.sortKey-Te.sortKey);const{lineAtlas:J,featureIndex:le}=v,fe=this.addConstantDashes(J);for(const ye of K){const{geometry:Te,index:Pe,sourceLayerIndex:Ue}=ye;if(fe&&this.addFeatureDashes(ye,J),this.hasPattern){const Qe=aTe("line",this.layers,ye,this.zoom,this.pixelRatio,v);this.patternFeatures.push(Qe)}else this.addFeature(ye,Te,Pe,S,J.positions,v.availableImages,v.brightness,v.elevationFeatures);le.insert(p[Pe].feature,Te,Pe,Ue,this.index)}}addConstantDashes(p){let v=!1;for(const S of this.layers){const E=S.paint.get("line-dasharray").value,R=S.layout.get("line-cap").value;if(E.kind!=="constant"||R.kind!=="constant")v=!0;else{const F=R.value,q=E.value;if(!q)continue;p.addDash(q,F)}}return v}addFeatureDashes(p,v){const S=this.zoom;for(const E of this.layers){const R=E.paint.get("line-dasharray").value,F=E.layout.get("line-cap").value;if(R.kind==="constant"&&F.kind==="constant")continue;let q,K;if(R.kind==="constant"){if(q=R.value,!q)continue}else q=R.evaluate({zoom:S},p);K=F.kind==="constant"?F.value:F.evaluate({zoom:S},p),v.addDash(q,K),p.patterns[E.id]=[v.getKey(q,K)]}}update(p,v,S,E,R,F,q,K,J){this.programConfigurations.updatePaintArrays(p,v,R,S,E,F,q,J)}addFeatures(p,v,S,E,R,F){for(const q of this.patternFeatures)this.addFeature(q,q.geometry,q.index,v,S,E,F,p.elevationFeatures)}isEmpty(){return this.layoutVertexArray.length===0}uploadPending(){return!this.uploaded||this.programConfigurations.needsUpload}upload(p){this.uploaded||(this.layoutVertexArray2.length!==0&&(this.layoutVertexBuffer2=p.createVertexBuffer(this.layoutVertexArray2,fqt)),this.patternVertexArray.length!==0&&(this.patternVertexBuffer=p.createVertexBuffer(this.patternVertexArray,xqt)),!this.zOffsetVertexBuffer&&this.zOffsetVertexArray.length>0&&(this.zOffsetVertexBuffer=p.createVertexBuffer(this.zOffsetVertexArray,uqt.members,!0)),!this.elevationGroundScaleVertexBuffer&&this.elevationGroundScaleVertexArray.length>0&&(this.elevationGroundScaleVertexBuffer=p.createVertexBuffer(this.elevationGroundScaleVertexArray,hqt.members,!0)),this.layoutVertexBuffer=p.createVertexBuffer(this.layoutVertexArray,mqt),this.indexBuffer=p.createIndexBuffer(this.indexArray)),this.programConfigurations.upload(p),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(p,v){let S,E;if(v&&v>0?(S=`mapbox_clip_start_${v}`,E=`mapbox_clip_end_${v}`):(S="mapbox_clip_start",E="mapbox_clip_end"),p.properties&&p.properties.hasOwnProperty(S)&&p.properties.hasOwnProperty(E))return{start:+p.properties[S],end:+p.properties[E]}}addFeature(p,v,S,E,R,F,q,K){const J=this.layers[0].layout,le=J.get("line-join").evaluate(p,{}),fe=J.get("line-cap").evaluate(p,{}),ye=J.get("line-miter-limit"),Te=J.get("line-round-limit");this.lineClips=this.lineFeatureClips(p),this.lineFeature=p;const Pe=!(!p.properties||!p.properties.hasOwnProperty("mapbox_line_metrics"))&&p.properties.mapbox_line_metrics;this.zOffsetValue=J.get("line-z-offset").value;const Ue=this.layers[0].paint.get("line-width").value;if(Ue.kind!=="constant"&&Ue.isLineProgressConstant===!1&&(this.variableWidthValue=Ue),this.isSeaLevelReference){const Qe=J.get("line-elevation-ground-scale").value;Qe.kind==="constant"&&Qe.value===0||(this.elevationGroundScaleValue=Qe)}if(this.elevationType==="road"){const Qe=this.layoutVertexArray.length;if(!this.addElevatedRoadFeature(p,v,E,K,le,fe,ye,Te)){const[at,pt]=this.clipRuntimeLinesToTile(v,1);for(let dt=0;dt0?Tt.parentIndex:null)}this.fillNonElevatedRoadSegment(Qe)}}else for(let Qe=0;Qe0?Qe:null);this.programConfigurations.populatePaintArrays(this.layoutVertexArray.length,p,S,R,F,E,q,void 0,this.worldview)}computeSegNextDir(p,v){return p.nextPoint.sub(v.at(-2)).unit()}computeSegPrevDir(p,v){return v[1].sub(p.prevPoint).unit()}clipLinesToTile(p,v){return gee(p,-v,-v,sr+v,sr+v)}clipRuntimeLinesToTile(p,v){const S=[];return[gee(p,-v,-v,sr+v,sr+v,S),S]}addElevatedRoadFeature(p,v,S,E,R,F,q,K){const J=[],le=Ql.getElevationFeature(p,E);if(le){const fe=this.clipLinesToTile(v,1),ye=this.prepareElevatedLines(fe,le,S);for(const Te of ye)J.push({geometry:Te,elevation:le,elevationTileID:S,segment:{progress:{min:0,max:1},nextDir:void 0,prevDir:void 0}})}if(J.length===0)return!1;for(const fe of J){const ye=this.layoutVertexArray.length;this.addLine(fe.geometry,p,S,R,F,q,K);const Te=new uc(S,fe.elevationTileID);if(fe.elevation)for(let Pe=ye;Pe>1,this.layoutVertexArray.int16[6*Pe+1]>>1),Qe=Te.pointElevation(Ue,fe.elevation,.05);this.updateHeightRange(Qe),this.zOffsetVertexArray.emplaceBack(Qe,0,0)}else this.fillNonElevatedRoadSegment(ye)}return!0}prepareElevatedLines(p,v,S){if(v.constantHeight!=null)return p;const E=[],R=1/In(S);for(const F of p)EUt(F,new dv(v,R),0,E);return E}fillNonElevatedRoadSegment(p){for(let v=p;v0,ye=K&&K.progress.max<1;if(this.lineClips){let ps={min:this.lineClips.start,max:this.lineClips.end},rs=1;if(K){const fn=this.lineClips.end-this.lineClips.start;ps=function(_n,Sn,wn){return{min:$i(_n.min,Sn,wn),max:$i(_n.max,Sn,wn)}}(K.progress,{min:0,max:1},ps),fn>0&&(rs=(ps.max-ps.min)/fn)}const is=+v.properties.mapbox_clip_feature_len,dn=+v.properties.mapbox_clip_seg_len;if(Number.isNaN(is)||Number.isNaN(dn)){for(let _n=0;_n=2&&p[Pe-1].equals(p[Pe-2]);)Pe--;let Ue=0;for(;Ue0,Nn=this.overscaling<=16?122880/(512*this.overscaling):0;if(rs&&is==="round"){if(SnF&&(is="bevel"),is==="bevel"&&(Sn>2&&(is="flipbevel"),Sn2*Nn){const ar=at.sub(at.sub(pt)._mult(Nn/Tn)._round());this.updateDistance(pt,ar),this.addCurrentVertex(ar,wt,0,0,Qe,Jt),pt=ar}this.updateDistance(pt,at),fn._mult(Sn),this.addCurrentVertex(at,fn,0,0,Qe,Jt);const Vn=at.dist(dt);if(Vn>2*Nn){const ar=at.add(dt.sub(at)._mult(Nn/Vn)._round());this.updateDistance(at,ar),this.addCurrentVertex(ar,Tt,0,0,Qe,Jt),at=ar}}else fn._mult(Sn),this.addCurrentVertex(at,fn,0,0,Qe,Jt);else if(is==="flipbevel"){if(Sn>100)fn=Tt.mult(-1);else{const Tn=Sn*wt.add(Tt).mag()/wt.sub(Tt).mag();fn._perp()._mult(Tn*(ln?-1:1))}this.addCurrentVertex(at,fn,0,0,Qe,Jt),this.addCurrentVertex(at,fn.mult(-1),0,0,Qe,Jt)}else if(is==="bevel"||is==="fakeround"){const Tn=at.dist(pt);let Vn=1;if(this.elevationType==="offset"&&is==="bevel"&&this.currentLineJoinType!=="round"&&!this.patternJoinNone&&Jt!=null&&pt&&dt){const Dr=4*Nn;Tn1){this.lineSoFar=p.w;const Ue=(v.x-p.x)/fe,Qe=(v.y-p.y)/fe,at=(v.z-p.z)/fe,pt=(v.w-p.w)/fe,dt=v.x-p.x,wt=v.y-p.y,Tt=Math.sqrt(dt*dt+wt*wt);if(Tt===0)return;const Lt=-wt/Tt,fs=dt/Tt,Jt=Lt,ps=fs,rs=-Lt,is=-fs;for(let dn=1;dn=0&&this.e2>=0&&(this.indexArray.emplaceBack(this.e1,this.e2,le),K.primitiveLength++),F?this.e2=le:this.e1=le,J!=null&&this.zOffsetVertexArray.emplaceBack(J.zOffset,J.variableWidth,J.variableWidth),this.elevationGroundScaleValue){const fe=J?J.elevationGroundScale:this.evaluateElevationGroundScale();this.elevationGroundScaleVertexArray.emplaceBack(fe)}}updateScaledDistance(){this.lineClips?(this.scaledDistance=this.distance/this.totalDistance,this.lineSoFar=this.totalFeatureLength*this.lineClips.start+this.distance):this.lineSoFar=this.distance}updateDistance(p,v){this.prevDistance=this.distance,this.distance+=p.dist(v),this.updateScaledDistance()}}function RTe(j,p,v){return j.xv||j.yv}let BZe,$Ze;function UZe(j,p,v){return p*(sr/(j.tileSize*Math.pow(2,v-j.tileID.overscaledZ)))}pr(See,"LineBucket",{omit:["layers","patternFeatures","currentVertex","currentVertexIsOutside"]});const qZe=(j,p,v)=>(1-v)*j+v*p;function VZe(j,p){return 1/UZe(j,1,p.tileZoom)}function HZe(j,p,v,S){return j.translatePosMatrix(S||p.tileID.projMatrix,p,v.paint.get("line-translate"),v.paint.get("line-translate-anchor"))}const GZe=j=>{const p=[];WZe(j)&&p.push("RENDER_LINE_DASH"),j.paint.get("line-gradient")&&p.push("RENDER_LINE_GRADIENT"),j.paint.get("line-blend-mode")==="multiply"&&p.push("LINE_BLEND_MULTIPLY");const v=j.paint.get("line-trim-offset");v[0]===0&&v[1]===0||p.push("RENDER_LINE_TRIM_OFFSET"),j.paint.get("line-border-width").constantOr(1)!==0&&p.push("RENDER_LINE_BORDER");const S=j.layout.get("line-join").constantOr("miter")==="none",E=!!j.paint.get("line-pattern").constantOr(1);return S&&E&&p.push("LINE_JOIN_NONE"),p};function WZe(j){const p=j.paint.get("line-dasharray").value;return p.kind!=="constant"||p.value}let OTe;const KZe=()=>OTe||(OTe={layout:BZe||(BZe=new dc({"line-cap":new Qn(Is.layout_line["line-cap"]),"line-join":new Qn(Is.layout_line["line-join"]),"line-miter-limit":new er(Is.layout_line["line-miter-limit"]),"line-round-limit":new er(Is.layout_line["line-round-limit"]),"line-sort-key":new Qn(Is.layout_line["line-sort-key"]),"line-z-offset":new Qn(Is.layout_line["line-z-offset"]),"line-elevation-reference":new er(Is.layout_line["line-elevation-reference"]),"line-cross-slope":new er(Is.layout_line["line-cross-slope"]),visibility:new er(Is.layout_line.visibility),"line-width-unit":new er(Is.layout_line["line-width-unit"]),"line-elevation-ground-scale":new Qn(Is.layout_line["line-elevation-ground-scale"])})),paint:$Ze||($Ze=new dc({"line-opacity":new Qn(Is.paint_line["line-opacity"]),"line-color":new Qn(Is.paint_line["line-color"]),"line-translate":new er(Is.paint_line["line-translate"]),"line-translate-anchor":new er(Is.paint_line["line-translate-anchor"]),"line-width":new Qn(Is.paint_line["line-width"]),"line-gap-width":new Qn(Is.paint_line["line-gap-width"]),"line-offset":new Qn(Is.paint_line["line-offset"]),"line-blur":new Qn(Is.paint_line["line-blur"]),"line-dasharray":new Qn(Is.paint_line["line-dasharray"]),"line-pattern":new Qn(Is.paint_line["line-pattern"]),"line-pattern-cross-fade":new er(Is.paint_line["line-pattern-cross-fade"]),"line-gradient":new g0(Is.paint_line["line-gradient"]),"line-trim-offset":new er(Is.paint_line["line-trim-offset"]),"line-trim-fade-range":new er(Is.paint_line["line-trim-fade-range"]),"line-trim-color":new er(Is.paint_line["line-trim-color"]),"line-emissive-strength":new Qn(Is.paint_line["line-emissive-strength"]),"line-border-width":new Qn(Is.paint_line["line-border-width"]),"line-border-color":new Qn(Is.paint_line["line-border-color"]),"line-occlusion-opacity":new er(Is.paint_line["line-occlusion-opacity"]),"line-blend-mode":new er(Is.paint_line["line-blend-mode"]),"line-color-use-theme":new Qn({type:"string",default:"default","property-type":"data-driven"}),"line-gradient-use-theme":new Qn({type:"string",default:"default","property-type":"data-driven"}),"line-trim-color-use-theme":new Qn({type:"string",default:"default","property-type":"data-driven"}),"line-border-color-use-theme":new Qn({type:"string",default:"default","property-type":"data-driven"})}))},OTe);class _qt extends Qn{possiblyEvaluate(p,v){return v=new xi(Math.floor(v.zoom),{now:v.now,fadeDuration:v.fadeDuration,transition:v.transition,worldview:v.worldview}),super.possiblyEvaluate(p,v)}evaluate(p,v,S,E){return v=Object.assign({},v,{zoom:Math.floor(v.zoom)}),super.evaluate(p,v,S,E)}}let Vq;function YZe(j,p){return p>0?p+2*j:j}const wqt=Pn([{name:"a_pos_offset",components:4,type:"Int16"},{name:"a_tex_size",components:4,type:"Uint16"},{name:"a_pixeloffset",components:4,type:"Int16"}],4),jqt=Pn([{name:"a_globe_anchor",components:3,type:"Int16"},{name:"a_globe_normal",components:3,type:"Float32"}],4),Nqt=Pn([{name:"a_projected_pos",components:4,type:"Float32"}],4);Pn([{name:"a_fade_opacity",components:1,type:"Uint32"}],4);const kqt=Pn([{name:"a_auto_z_offset",components:1,type:"Float32"}],4),Sqt=Pn([{name:"a_feature_index",components:1,type:"Float32"}],4),Cqt=Pn([{name:"a_x_axis",components:3,type:"Float32"},{name:"a_y_axis",components:3,type:"Float32"}]),Aqt=Pn([{name:"a_texb",components:2,type:"Uint16"}]),Tqt=Pn([{name:"a_placed",components:2,type:"Uint8"},{name:"a_shift",components:2,type:"Float32"},{name:"a_elevation_from_sea",components:2,type:"Float32"}]),Eqt=Pn([{name:"a_size_scale",components:1,type:"Float32"},{name:"a_padding",components:2,type:"Float32"},{name:"a_auto_z_offset",components:1,type:"Float32"}]);Pn([{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 ZZe=Pn([{name:"a_pos",components:3,type:"Int16"},{name:"a_anchor_pos",components:2,type:"Int16"},{name:"a_extrude",components:2,type:"Int16"}],4),Mqt=Pn([{name:"a_pos_2f",components:2,type:"Float32"},{name:"a_radius",components:1,type:"Float32"},{name:"a_flags",components:2,type:"Int16"}],4);Pn([{name:"triangle",components:3,type:"Uint16"}]),Pn([{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"}]),Pn([{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"}]),Pn([{type:"Float32",name:"offsetX"}]),Pn([{type:"Int16",name:"x"},{type:"Int16",name:"y"}]);const FTe=class Cwe{constructor(p=null,v=0,S=4096){this.batchIndex=v,this.headerBuffer=null,this.propertiesBuffer=null,this.blockIndicesBuffer=null,this.context=p||null,this.propsDwords=S,this.totalBytes=4*this.propsDwords,this.headerData=new Uint32Array(Cwe.HEADER_DWORDS),this.propertiesData=new Float32Array(this.propsDwords),this.blockIndicesData=new Uint32Array(this.propsDwords);for(let E=0;Ep.maxUniformBlockSize)throw new Error(`UBO size ${this.totalBytes} exceeds device limit ${p.maxUniformBlockSize}`);if(this.headerBuffer=v.createBuffer(),!this.headerBuffer)throw new Error("Failed to create header UBO buffer");if(v.bindBuffer(v.UNIFORM_BUFFER,this.headerBuffer),v.bufferData(v.UNIFORM_BUFFER,Cwe.HEADER_BYTES,v.DYNAMIC_DRAW),this.propertiesBuffer=v.createBuffer(),!this.propertiesBuffer)throw new Error("Failed to create properties UBO buffer");if(v.bindBuffer(v.UNIFORM_BUFFER,this.propertiesBuffer),v.bufferData(v.UNIFORM_BUFFER,this.totalBytes,v.DYNAMIC_DRAW),this.blockIndicesBuffer=v.createBuffer(),!this.blockIndicesBuffer)throw new Error("Failed to create block-indices UBO buffer");v.bindBuffer(v.UNIFORM_BUFFER,this.blockIndicesBuffer),v.bufferData(v.UNIFORM_BUFFER,this.totalBytes,v.DYNAMIC_DRAW),v.bindBuffer(v.UNIFORM_BUFFER,null)}writeHeader(p){const v=this.headerData;v[0]=p.dataDrivenMask,v[1]=p.zoomDependentMask,v[2]=p.dataDrivenBlockSizeVec4,v[3]=p.offsets[0],v[4]=p.offsets[1],v[5]=p.offsets[2],v[6]=p.offsets[3],v[7]=p.offsets[4],v[8]=p.offsets[5],v[9]=p.offsets[6],v[10]=p.offsets[7],v[11]=p.offsets[8]}writeDataDrivenBlock(p,v,S){const E=4*S.dataDrivenBlockSizeVec4;if(E===0)return;const R=v*E;if(R+E>this.propertiesData.length)throw new Error(`UBO write out of bounds: feature index ${v} exceeds propertiesData capacity`);for(let F=0;F<9;F++)S.dataDrivenMask&1<{if(!q)return;const J=S.getUniformBlockIndex(v,F);J!==S.INVALID_INDEX&&(S.uniformBlockBinding(v,J,K),S.bindBufferBase(S.UNIFORM_BUFFER,K,q))},R=3*this.batchIndex;E("SymbolPaintPropertiesHeaderUniform",this.headerBuffer,R),E("SymbolPaintPropertiesUniform",this.propertiesBuffer,R+1),E("SymbolPaintPropertiesIndexUniform",this.blockIndicesBuffer,R+2)}destroy(){if(this.context){const p=this.context.gl;this.headerBuffer&&(p.deleteBuffer(this.headerBuffer),this.headerBuffer=null),this.propertiesBuffer&&(p.deleteBuffer(this.propertiesBuffer),this.propertiesBuffer=null),this.blockIndicesBuffer&&(p.deleteBuffer(this.blockIndicesBuffer),this.blockIndicesBuffer=null)}}};FTe.HEADER_DWORDS=12,FTe.HEADER_BYTES=48;let zTe=FTe;function BTe(j,p,v,S){return[SO(255*j,255*p),SO(255*v,255*S)]}function XZe(j,p,v,S,E,R,F,q){return!!j&&(j.kind==="constant"?j.value==="none":j.kind==="composite"||j.kind==="source"?j.evaluate({zoom:0,brightness:R,worldview:q},p,v,E,S,F)==="none":typeof j=="string"&&j==="none")}pr(zTe,"SymbolPropertiesUBO",{omit:["headerBuffer","propertiesBuffer","blockIndicesBuffer"]});class $Te{constructor(p,v,S,E,R="",F,q){this.layer=p,this.zoom=v,this.lut=S,this.isText=E,this.propDefs=this._getPropDefs(),this.worldview=R,this.maxUniformBufferBindings=F||24,this.uboSizeDwords=q||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(p,E),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 p=this.isText?"text":"icon";return[{name:`${p}-color`,useThemeName:`${p}-color-use-theme`,isColor:!0},{name:`${p}-halo-color`,useThemeName:`${p}-halo-color-use-theme`,isColor:!0},{name:`${p}-opacity`,useThemeName:null,isColor:!1},{name:`${p}-halo-width`,useThemeName:null,isColor:!1},{name:`${p}-halo-blur`,useThemeName:null,isColor:!1},{name:`${p}-emissive-strength`,useThemeName:null,isColor:!1},{name:`${p}-occlusion-opacity`,useThemeName:null,isColor:!1},{name:"symbol-z-offset",useThemeName:null,isColor:!1},{name:`${p}-translate`,useThemeName:null,isColor:!1,isVec2:!0}]}buildHeader(){const p=this.layer.paint,v=this.propDefs;let S=0,E=0,R=0,F=0;const q=[0,0,0,0,0,0,0,0,0];for(let K=0;K<9;K++){const{name:J,isColor:le,isVec2:fe}=v[K],ye=p.get(J),Te=!(!ye||typeof ye.isConstant!="function"||ye.isConstant()),Pe=this._appearancesHavePaintProperties(J),Ue=Te||Pe,Qe=!(!ye||!ye.value||ye.value.kind!=="composite"),at=this.layer._transitionablePaint._values[J],pt=!Ue&&(at&&at.value&&at.value.expression&&at.value.expression.kind)==="camera";Ue?(S|=1<v.hasPaintProperty(p):this.isText?v=>v.hasTextPaintProperties():v=>v.hasIconPaintProperties())}_checkIfAllPropertiesAreConstant(p,v){const S=p.paint,E=v?"text":"icon",R=[`${E}-color`,`${E}-halo-color`,`${E}-opacity`,`${E}-halo-width`,`${E}-halo-blur`,`${E}-emissive-strength`,`${E}-occlusion-opacity`,"symbol-z-offset",`${E}-translate`];for(const F of R){const q=S.get(F);if(q&&typeof q=="object"&&"isConstant"in q&&!q.isConstant())return!1}return!this._appearancesHavePaintProperties()}_hashDataDrivenValues(p,v){if(v.dataDrivenMask===0)return"";const S=[];for(let E=0;E<9;E++){if(!(v.dataDrivenMask&1<=Pe){Er(`Too many symbol features: batch ${ye} requires binding points up to ${3*ye+2}, device limit ${Pe}. Some features will render incorrectly.`);const Qe={batchIndex:0,localFeatureIndex:0,vtFeatureIndex:v,featureId:K};return this.allFeatures.push(Qe),K!=null&&(this.featureVertexRangesFromId.has(K)||this.featureVertexRangesFromId.set(K,[]),this.featureVertexRangesFromId.get(K).push(Qe)),0}this.ubos[ye]||(this.ubos[ye]=new zTe(q,ye,this.uboSizeDwords),this.ubos[ye].writeHeader(J)),this.ubos[ye].writeDataDrivenBlock(le,Te,J);const Ue={batchIndex:ye,localFeatureIndex:Te,vtFeatureIndex:v,featureId:K};return this.allFeatures.push(Ue),K!=null&&(this.featureVertexRangesFromId.has(K)||this.featureVertexRangesFromId.set(K,[]),this.featureVertexRangesFromId.get(K).push(Ue)),Te}updateFeatures(p,v,S,E,R,F,q){if(this.layer=v,this.cachedConstantUniforms=null,!this.cachedHeader)return;const K=this.cachedHeader;for(const J of p){const le=this.featureVertexRangesFromId.get(J);if(!le)continue;const fe=F[J]||{};for(const ye of le){if(!S)continue;const Te=S.feature(ye.vtFeatureIndex);if(!Te)continue;const Pe={type:Te.type,id:J,properties:Te.properties||{},geometry:[]},Ue=this.activeAppearanceByVtIndex?this.activeAppearanceByVtIndex.get(ye.vtFeatureIndex):void 0,Qe=this.evaluateAllProperties(Pe,fe,E,R,q,void 0,Ue);this.ubos[ye.batchIndex]&&this.ubos[ye.batchIndex].writeDataDrivenBlock(Qe,ye.localFeatureIndex,K)}}}updateDynamicExpressions(p,v,S,E,R,F){if(this.layer=p,this.cachedConstantUniforms=null,!this.cachedHeader)return;const q=this.cachedHeader;for(const K of this.allFeatures){if(!v)continue;const J=v.feature(K.vtFeatureIndex);if(!J)continue;const le=K.featureId!=null&&R[K.featureId]||{},fe={type:J.type,id:K.featureId,properties:J.properties||{},geometry:[]},ye=this.activeAppearanceByVtIndex?this.activeAppearanceByVtIndex.get(K.vtFeatureIndex):void 0,Te=this.evaluateAllProperties(fe,le,S,E,F,void 0,ye);this.ubos[K.batchIndex]&&this.ubos[K.batchIndex].writeDataDrivenBlock(Te,K.localFeatureIndex,q)}}updateFeaturePaintForAppearance(p,v,S,E,R,F,q){if(!this.layer||(this.activeAppearanceByVtIndex||(this.activeAppearanceByVtIndex=new Map),this.activeAppearanceByVtIndex.set(p,q||null),!this.cachedHeader))return!1;const K=this.cachedHeader;if(K.dataDrivenMask===0)return!1;let J=!1;for(const le of this.allFeatures){if(le.vtFeatureIndex!==p)continue;const fe=this.evaluateAllProperties(v,S,E,R,F,void 0,q);this.ubos[le.batchIndex]&&(this.ubos[le.batchIndex].writeDataDrivenBlock(fe,le.localFeatureIndex,K),J=!0)}return J}getConstantUniformValues(p,v){const S=this.cachedHeader,E=!(!S||!S.cameraMask);if(this.cachedConstantUniforms&&this.cachedConstantBrightness===v&&(!E||this.cachedConstantRenderZoom===p))return this.cachedConstantUniforms;const R=this.layer.paint,F=this.propDefs,q=E?new xi(p,{brightness:v,worldview:this.worldview}):null,K={type:1,id:void 0,properties:{},geometry:[]},J=ye=>{const Te=F[ye],Pe=R.get(Te.name);if(!Pe)return[0,0,0,1];const Ue=Te.useThemeName?R.get(Te.useThemeName):void 0,Qe=XZe(Ue&&typeof Ue!="string"?Ue.value:void 0,K,{},[],void 0,v,void 0,this.worldview)?null:this.lut;let at;at=S&&S.cameraMask&1<{const Pe=R.get(F[ye].name);if(!Pe)return Te;if(S&&S.cameraMask&1<{S.text=function(E,R,F){const q=R.layout.get("text-transform").evaluate(F,{});return q==="uppercase"?E=E.toLocaleUpperCase():q==="lowercase"&&(E=E.toLocaleLowerCase()),Ig.applyArabicShaping&&(E=Ig.applyArabicShaping(E)),E}(S.text,p,v)}),j}const Hq={"!":"︕","#":"#",$:"$","%":"%","&":"&","(":"︵",")":"︶","*":"*","+":"+",",":"︐","-":"︲",".":"・","/":"/",":":"︓",";":"︔","<":"︿","=":"=",">":"﹀","?":"︖","@":"@","[":"﹇","\\":"\","]":"﹈","^":"^",_:"︳","`":"`","{":"︷","|":"―","}":"︸","~":"~","¢":"¢","£":"£","¥":"¥","¦":"¦","¬":"¬","¯":" ̄","–":"︲","—":"︱","‘":"﹃","’":"﹄","“":"﹁","”":"﹂","…":"︙","‧":"・","₩":"₩","、":"︑","。":"︒","〈":"︿","〉":"﹀","《":"︽","》":"︾","「":"﹁","」":"﹂","『":"﹃","』":"﹄","【":"︻","】":"︼","〔":"︹","〕":"︺","〖":"︗","〗":"︘","!":"︕","(":"︵",")":"︶",",":"︐","-":"︲",".":"・",":":"︓",";":"︔","<":"︿",">":"﹀","?":"︖","[":"﹇","]":"﹈","_":"︳","{":"︷","|":"―","}":"︸","⦅":"︵","⦆":"︶","。":"︒","「":"﹁","」":"﹂","←":"↑","→":"↓"};function Pqt(j){return j==="︶"||j==="﹈"||j==="︸"||j==="﹄"||j==="﹂"||j==="︾"||j==="︼"||j==="︺"||j==="︘"||j==="﹀"||j==="︐"||j==="︓"||j==="︔"||j==="`"||j===" ̄"||j==="︑"||j==="︒"}function Iqt(j){return j==="︵"||j==="﹇"||j==="︷"||j==="﹃"||j==="﹁"||j==="︽"||j==="︻"||j==="︹"||j==="︗"||j==="︿"}const UTe=4294967296,QZe=1/UTe,JZe=typeof TextDecoder>"u"?null:new TextDecoder("utf-8");let Cee=class{constructor(j=new Uint8Array(16)){this.buf=ArrayBuffer.isView(j)?j:new Uint8Array(j),this.dataView=new DataView(this.buf.buffer),this.pos=0,this.type=0,this.length=this.buf.length}readFields(j,p,v=this.length){for(;this.pos>3,R=this.pos;this.type=7&S,j(E,p,this),this.pos===R&&this.skip(S)}return p}readMessage(j,p){return this.readFields(j,p,this.readVarint()+this.pos)}readFixed32(){const j=this.dataView.getUint32(this.pos,!0);return this.pos+=4,j}readSFixed32(){const j=this.dataView.getInt32(this.pos,!0);return this.pos+=4,j}readFixed64(){const j=this.dataView.getUint32(this.pos,!0)+this.dataView.getUint32(this.pos+4,!0)*UTe;return this.pos+=8,j}readSFixed64(){const j=this.dataView.getUint32(this.pos,!0)+this.dataView.getInt32(this.pos+4,!0)*UTe;return this.pos+=8,j}readFloat(){const j=this.dataView.getFloat32(this.pos,!0);return this.pos+=4,j}readDouble(){const j=this.dataView.getFloat64(this.pos,!0);return this.pos+=8,j}readVarint(j){const p=this.buf;let v,S;return S=p[this.pos++],v=127&S,S<128?v:(S=p[this.pos++],v|=(127&S)<<7,S<128?v:(S=p[this.pos++],v|=(127&S)<<14,S<128?v:(S=p[this.pos++],v|=(127&S)<<21,S<128?v:(S=p[this.pos],v|=(15&S)<<28,function(E,R,F){const q=F.buf;let K,J;if(J=q[F.pos++],K=(112&J)>>4,J<128||(J=q[F.pos++],K|=(127&J)<<3,J<128)||(J=q[F.pos++],K|=(127&J)<<10,J<128)||(J=q[F.pos++],K|=(127&J)<<17,J<128)||(J=q[F.pos++],K|=(127&J)<<24,J<128)||(J=q[F.pos++],K|=(1&J)<<31,J<128))return RO(E,K,R);throw new Error("Expected varint not more than 10 bytes")}(v,j,this)))))}readVarint64(){return this.readVarint(!0)}readSVarint(){const j=this.readVarint();return j%2==1?(j+1)/-2:j/2}readBoolean(){return!!this.readVarint()}readString(){const j=this.readVarint()+this.pos,p=this.pos;return this.pos=j,j-p>=12&&JZe?JZe.decode(this.buf.subarray(p,j)):function(v,S,E){let R="",F=S;for(;F239?4:q>223?3:q>191?2:1;if(F+ye>E)break;ye===1?q<128&&(fe=q):ye===2?(K=v[F+1],(192&K)==128&&(fe=(31&q)<<6|63&K,fe<=127&&(fe=null))):ye===3?(K=v[F+1],J=v[F+2],(192&K)==128&&(192&J)==128&&(fe=(15&q)<<12|(63&K)<<6|63&J,(fe<=2047||fe>=55296&&fe<=57343)&&(fe=null))):ye===4&&(K=v[F+1],J=v[F+2],le=v[F+3],(192&K)==128&&(192&J)==128&&(192&le)==128&&(fe=(15&q)<<18|(63&K)<<12|(63&J)<<6|63&le,(fe<=65535||fe>=1114112)&&(fe=null))),fe===null?(fe=65533,ye=1):fe>65535&&(fe-=65536,R+=String.fromCharCode(fe>>>10&1023|55296),fe=56320|1023&fe),R+=String.fromCharCode(fe),F+=ye}return R}(this.buf,p,j)}readBytes(){const j=this.readVarint()+this.pos,p=this.buf.subarray(this.pos,j);return this.pos=j,p}readPackedVarint(j=[],p){const v=this.readPackedEnd();for(;this.pos127;);else if(p===2)this.pos=this.readVarint()+this.pos;else if(p===5)this.pos+=4;else{if(p!==1)throw new Error(`Unimplemented type: ${p}`);this.pos+=8}}writeTag(j,p){this.writeVarint(j<<3|p)}realloc(j){let p=this.length||16;for(;p268435455||j<0?function(p,v){let S,E;if(p>=0?(S=p%4294967296|0,E=p/4294967296|0):(S=~(-p%4294967296),E=~(-p/4294967296),4294967295^S?S=S+1|0:(S=0,E=E+1|0)),p>=18446744073709552e3||p<-18446744073709552e3)throw new Error("Given varint doesn't fit into 10 bytes");v.realloc(10),function(R,F,q){q.buf[q.pos++]=127&R|128,R>>>=7,q.buf[q.pos++]=127&R|128,R>>>=7,q.buf[q.pos++]=127&R|128,R>>>=7,q.buf[q.pos++]=127&R|128,q.buf[q.pos]=127&(R>>>=7)}(S,0,v),function(R,F){const q=(7&R)<<4;F.buf[F.pos++]|=q|((R>>>=3)?128:0),R&&(F.buf[F.pos++]=127&R|((R>>>=7)?128:0),R&&(F.buf[F.pos++]=127&R|((R>>>=7)?128:0),R&&(F.buf[F.pos++]=127&R|((R>>>=7)?128:0),R&&(F.buf[F.pos++]=127&R|((R>>>=7)?128:0),R&&(F.buf[F.pos++]=127&R)))))}(E,v)}(j,this):(this.realloc(4),this.buf[this.pos++]=127&j|(j>127?128:0),j<=127||(this.buf[this.pos++]=127&(j>>>=7)|(j>127?128:0),j<=127||(this.buf[this.pos++]=127&(j>>>=7)|(j>127?128:0),j<=127||(this.buf[this.pos++]=j>>>7&127))))}writeSVarint(j){this.writeVarint(j<0?2*-j-1:2*j)}writeBoolean(j){this.writeVarint(+j)}writeString(j){j=String(j),this.realloc(4*j.length),this.pos++;const p=this.pos;this.pos=function(S,E,R){for(let F,q,K=0;K55295&&F<57344){if(!q){F>56319||K+1===E.length?(S[R++]=239,S[R++]=191,S[R++]=189):q=F;continue}if(F<56320){S[R++]=239,S[R++]=191,S[R++]=189,q=F;continue}F=q-55296<<10|F-56320|65536,q=null}else q&&(S[R++]=239,S[R++]=191,S[R++]=189,q=null);F<128?S[R++]=F:(F<2048?S[R++]=F>>6|192:(F<65536?S[R++]=F>>12|224:(S[R++]=F>>18|240,S[R++]=F>>12&63|128),S[R++]=F>>6&63|128),S[R++]=63&F|128)}return R}(this.buf,j,this.pos);const v=this.pos-p;v>=128&&eXe(p,v,this),this.pos=p-1,this.writeVarint(v),this.pos+=v}writeFloat(j){this.realloc(4),this.dataView.setFloat32(this.pos,j,!0),this.pos+=4}writeDouble(j){this.realloc(8),this.dataView.setFloat64(this.pos,j,!0),this.pos+=8}writeBytes(j){const p=j.length;this.writeVarint(p),this.realloc(p);for(let v=0;v=128&&eXe(v,S,this),this.pos=v-1,this.writeVarint(S),this.pos+=S}writeMessage(j,p,v){this.writeTag(j,2),this.writeRawMessage(p,v)}writePackedVarint(j,p){p.length&&this.writeMessage(j,Dqt,p)}writePackedSVarint(j,p){p.length&&this.writeMessage(j,Rqt,p)}writePackedBoolean(j,p){p.length&&this.writeMessage(j,zqt,p)}writePackedFloat(j,p){p.length&&this.writeMessage(j,Oqt,p)}writePackedDouble(j,p){p.length&&this.writeMessage(j,Fqt,p)}writePackedFixed32(j,p){p.length&&this.writeMessage(j,Bqt,p)}writePackedSFixed32(j,p){p.length&&this.writeMessage(j,$qt,p)}writePackedFixed64(j,p){p.length&&this.writeMessage(j,Uqt,p)}writePackedSFixed64(j,p){p.length&&this.writeMessage(j,qqt,p)}writeBytesField(j,p){this.writeTag(j,2),this.writeBytes(p)}writeFixed32Field(j,p){this.writeTag(j,5),this.writeFixed32(p)}writeSFixed32Field(j,p){this.writeTag(j,5),this.writeSFixed32(p)}writeFixed64Field(j,p){this.writeTag(j,1),this.writeFixed64(p)}writeSFixed64Field(j,p){this.writeTag(j,1),this.writeSFixed64(p)}writeVarintField(j,p){this.writeTag(j,0),this.writeVarint(p)}writeSVarintField(j,p){this.writeTag(j,0),this.writeSVarint(p)}writeStringField(j,p){this.writeTag(j,2),this.writeString(p)}writeFloatField(j,p){this.writeTag(j,5),this.writeFloat(p)}writeDoubleField(j,p){this.writeTag(j,1),this.writeDouble(p)}writeBooleanField(j,p){this.writeVarintField(j,+p)}};function RO(j,p,v){return v?4294967296*p+(j>>>0):4294967296*(p>>>0)+(j>>>0)}function eXe(j,p,v){const S=p<=16383?1:p<=2097151?2:p<=268435455?3:Math.floor(Math.log(p)/(7*Math.LN2));v.realloc(S);for(let E=v.pos-1;E>=j;E--)v.buf[E+S]=v.buf[E]}function Dqt(j,p){for(let v=0;v=0&&S>=p&&Aee[this.text.charCodeAt(S)];S--)v--;this.text=this.text.substring(p,v),this.sectionIndex=this.sectionIndex.slice(p,v)}substring(p,v){const S=new OO;return S.text=this.text.substring(p,v),S.sectionIndex=this.sectionIndex.slice(p,v),S.sections=this.sections,S}toString(){return this.text}getMaxScale(){return this.sectionIndex.reduce((p,v)=>Math.max(p,this.sections[v].scale),0)}addTextSection(p,v){this.text+=p.text,this.sections.push(Gq.forText(p.scale,p.fontStack||v));const S=this.sections.length-1;for(let E=0;E=63743?null:++this.imageSectionID:(this.imageSectionID=57344,this.imageSectionID)}}function qTe(j,p,v,S,E,R,F,q,K,J,le,fe,ye,Te,Pe,Ue=1,Qe=1){const at=OO.fromFeature(j,E,Ue,Qe);fe===pv.vertical&&at.verticalizePunctuation(ye);let pt=[];const dt=function(Jt,ps,rs,is,dn,fn,_n=1){if(!Jt)return[];const Sn=[],wn=function(Nn,Tn,Vn,ar,zr,yr,gr=1){let ir=0;for(let Dr=0;Dr=0;let ln=0;for(let Nn=0;Nn0&&Dg>Ii&&(Ii=Dg)}else{const lp=rs[pd.fontStack];if(!lp)continue;lp[fd]&&(Qd=lp[fd]);const Nx=ps[pd.fontStack];if(!Nx)continue;const Lf=Nx.glyphs[fd];if(!Lf)continue;if(Xu=Lf.metrics,Nm=fd!==8203?wm:0,gr){const Sd=Nx.ascender!==void 0?Math.abs(Nx.ascender):0,Dg=Nx.descender!==void 0?Math.abs(Nx.descender):0,cp=(Sd+Dg)*Xd;kd-v/2;){if(F--,F<0)return!1;q-=j[F].dist(R),R=j[F]}q+=j[F].dist(j[F+1]),F++;const K=[];let J=0;for(;qS;)J-=K.shift().angleDelta;if(J>E)return!1;F++,q+=le.dist(fe)}return!0}function dXe(j){let p=0;for(let v=0;vJ){const Pe=(J-K)/Te,Ue=mr(fe.x,ye.x,Pe),Qe=mr(fe.y,ye.y,Pe),at=new CS(Ue,Qe,0,ye.angleTo(fe),le);return!F||cXe(j,at,q,F,p)?at:void 0}K+=Te}}function Zqt(j,p,v,S,E,R,F,q,K){const J=uXe(S,R,F),le=hXe(S,E),fe=le*F,ye=j[0].x===0||j[0].x===K||j[0].y===0||j[0].y===K;return p-fe

=0&&wt=0&&Tt=0&&ye+J<=le){const Lt=new CS(wt,Tt,0,pt,Pe);S&&!cXe(j,Lt,R,S,E)||Te.push(Lt)}}fe+=at}return q||Te.length||F||(Te=mXe(j,fe/2,v,S,E,R,F,!0,K)),Te}function pXe(j){let p=0,v=0;for(const F of j)p+=F.w*F.h,v=Math.max(v,F.w);j.sort((F,q)=>q.h-F.h);const S=[{x:0,y:0,w:Math.max(Math.ceil(Math.sqrt(p/.95)),v),h:1/0}];let E=0,R=0;for(const F of j)for(let q=S.length-1;q>=0;q--){const K=S[q];if(!(F.w>K.w||F.h>K.h)){if(F.x=K.x,F.y=K.y,R=Math.max(R,F.y+F.h),E=Math.max(E,F.x+F.w),F.w===K.w&&F.h===K.h){const J=S.pop();J&&qp.id?1:j.versionp.version?1:j.sxp.sx?1:j.syp.sy?1:0}function KTe(j){let p=0;for(let v=0;v0,fXe(p,S,this.iconDescriptors,R),fXe(v,S,this.patternDescriptors,R),this.iconDescriptors.sort(Eee),this.patternDescriptors.sort(Eee);let F=0;const q=E?E.data:"";q&&(F=Yj(F,KTe(q))),F=Yj(F,1);for(const K of this.iconDescriptors)F=Yj(F,KTe(K.id)),F=Yj(F,K.version),F=Yj(F,K.sx),F=Yj(F,K.sy);F=Yj(F,1);for(const K of this.patternDescriptors)F=Yj(F,KTe(K.id)),F=Yj(F,K.version),F=Yj(F,K.sx),F=Yj(F,K.sy);this.hash=F}subsetOf(p){return this.isSubsetArray(this.iconDescriptors,p.iconDescriptors,Eee)&&this.isSubsetArray(this.patternDescriptors,p.patternDescriptors,Eee)}isSubsetArray(p,v,S){let E=0,R=0;if(p.length>v.length)return!1;for(;E{const F=E.variant.id.toString().localeCompare(R.variant.id.toString());return F!==0?F:E.variant.sx!==R.variant.sx?E.variant.sx-R.variant.sx:E.variant.sy!==R.variant.sy?E.variant.sy-R.variant.sy:0});const S=new Map;for(const E of v)S.set(E.key,E.value);return S}class gXe{constructor(p){this.sourceAtlasHash=p}}class xXe{constructor(p,v,S,E){const R=new Map,F=new Map;this.haveRenderCallbacks=[];const q=[],K=E!==void 0,J=K?new Map:void 0,le=K?XTe(p,J):p,fe=K?XTe(v,J):v;this.addImages(le,R,1,q),this.addImages(fe,F,2,q);const{w:ye,h:Te}=pXe(q),Pe=new rg({width:ye||1,height:Te||1});for(const[Ue,Qe]of le.entries()){const at=R.get(Ue).paddedRect;rg.copy(Qe.data,Pe,{x:0,y:0},{x:at.x+1,y:at.y+1},Qe.data,null,Qe.sdf)}for(const[Ue,Qe]of fe.entries()){const at=F.get(Ue),pt=at.paddedRect;let dt=at.padding;const wt=pt.x+dt,Tt=pt.y+dt,Lt=Qe.data.width,fs=Qe.data.height;dt=dt>1?dt-1:dt,rg.copy(Qe.data,Pe,{x:0,y:0},{x:wt,y:Tt},Qe.data,S),rg.copy(Qe.data,Pe,{x:0,y:fs-dt},{x:wt,y:Tt-dt},{width:Lt,height:dt},S),rg.copy(Qe.data,Pe,{x:0,y:0},{x:wt,y:Tt+fs},{width:Lt,height:dt},S),rg.copy(Qe.data,Pe,{x:Lt-dt,y:0},{x:wt-dt,y:Tt},{width:dt,height:fs},S),rg.copy(Qe.data,Pe,{x:0,y:0},{x:wt+Lt,y:Tt},{width:dt,height:fs},S),rg.copy(Qe.data,Pe,{x:Lt-dt,y:fs-dt},{x:wt-dt,y:Tt-dt},{width:dt,height:dt},S),rg.copy(Qe.data,Pe,{x:0,y:fs-dt},{x:wt+Lt,y:Tt-dt},{width:dt,height:dt},S),rg.copy(Qe.data,Pe,{x:0,y:0},{x:wt+Lt,y:Tt+fs},{width:dt,height:dt},S),rg.copy(Qe.data,Pe,{x:Lt-dt,y:0},{x:wt-dt,y:Tt+fs},{width:dt,height:dt},S)}this.lut=S,this.image=Pe,this.iconPositions=R,this.patternPositions=F,K&&(this.contentDescriptor=new YTe(le,fe,E,S,J))}addImages(p,v,S,E){for(const[R,F]of p.entries()){const{bin:q,imagePosition:K,imageVariant:J}=ZTe(R,F,S);v.set(R,K),E.push(q),F.hasRenderCallback&&this.haveRenderCallbacks.push(J.id)}}patchUpdatedImages(p,v,S,E){this.haveRenderCallbacks=this.haveRenderCallbacks.filter(R=>p.hasImage(R,S)),p.dispatchRenderCallbacks(this.haveRenderCallbacks,S);for(const R of p.getUpdatedImages(S)){for(const F of this.iconPositions.keys()){const q=ud.parse(F);if(Wt.isEqual(q.id,R)){const K=p.getImage(R,S);this.patchUpdatedImage(this.iconPositions.get(F),K,v,null)}}for(const F of this.patternPositions.keys()){const q=ud.parse(F);if(Wt.isEqual(q.id,R)){const K=p.getImage(R,S);this.patchUpdatedImage(this.patternPositions.get(F),K,v,E||this.lut)}}}}patchUpdatedImage(p,v,S,E=null){if(!p||!v||p.version===v.version)return;p.version=v.version;const[R,F]=p.tl,q=p.sdf;if(this.lut||q){const K={width:v.data.width,height:v.data.height},J=new rg(K);rg.copy(v.data,J,{x:0,y:0},{x:0,y:0},K,E,q),S.update(J,{position:{x:R,y:F},recreateWhenResize:!1})}else S.update(v.data,{position:{x:R,y:F},recreateWhenResize:!1})}}pr(Wq,"ImagePosition"),pr(xXe,"ImageAtlas",{omit:["lut"]}),pr(gXe,"ImageAtlasReference");class Kq{constructor(p){this.pendingRequests=new Map,this.cachedRanges=new Map,this.useServerFontComposition=!p||p.useServerFontComposition===void 0||p.useServerFontComposition}loadGlyphRange(p,v,S,E,R){if(this.useServerFontComposition)return void Kq.loadGlyphRange(p,v,S,E,R);const F=p.split(",").map(q=>q.trim()).filter(q=>q.length>0);F.length!==0?F.length!==1?this._loadMultipleFonts(F,v,S,E,R):this._loadFont(F[0],v,S,E,R):R(new Error("Empty fontstack"))}_loadMultipleFonts(p,v,S,E,R){const F=p.map(()=>null),q={completed:0,firstError:null,callbackCalled:!1},K=(J,le,fe)=>{if(!q.callbackCalled&&(le&&!q.firstError&&(q.firstError=le),fe&&(F[J]=fe),q.completed++,q.completed===p.length)){q.callbackCalled=!0;const ye=F.filter(Pe=>Pe!==null);if(ye.length===0)return void R(q.firstError||new Error("All fonts failed to load"));const Te=this._composeGlyphs(ye);R(null,Te)}};for(let J=0;J{K(J,le,fe)})}_loadFont(p,v,S,E,R){const F=`${p}:${v}`;if(this.cachedRanges.has(F)){const K=this.cachedRanges.get(F);return void Gd.frame(()=>R(null,K))}const q=this.pendingRequests.get(F);q?q.push(R):(this.pendingRequests.set(F,[R]),Kq.loadGlyphRange(p,v,S,E,(K,J)=>{K||this.cachedRanges.set(F,J||null);const le=this.pendingRequests.get(F);if(this.pendingRequests.delete(F),le)for(const fe of le)fe(K,J)}))}_composeGlyphs(p){const v={};let S,E;for(const R of p)if(S===void 0&&R.ascender!==void 0&&(S=R.ascender),E===void 0&&R.descender!==void 0&&(E=R.descender),R.glyphs)for(const F in R.glyphs)v[F]===void 0&&(v[F]=R.glyphs[F]);return{glyphs:v,ascender:S,descender:E}}}Kq.loadGlyphRange=function(j,p,v,S,E){const R=256*p,F=R+255,q=S.transformRequest(S.normalizeGlyphsURL(v).replace("{fontstack}",j).replace("{range}",`${R}-${F}`),n0.Glyphs);iy(q,(K,J)=>{if(K)E(K);else if(J){const le={},fe=function(ye){return new Cee(ye).readFields(Vqt,{})}(J);for(const ye of fe.glyphs)le[ye.id]=ye;E(null,{glyphs:le,ascender:fe.ascender,descender:fe.descender})}})};const Yq=1e20;function yXe(j,p,v,S,E,R,F,q,K){for(let J=p;J-1);K++,R[K]=q,F[K]=J,F[K+1]=Yq}for(let q=0,K=0;q{if(F){E.ascender=F.ascender,E.descender=F.descender;for(const q in F.glyphs)this._doesCharSupportLocalGlyph(+q)||(E.glyphs[+q]=F.glyphs[+q]);E.ranges[v]=!0}for(const q of E.requests[v]||[])q(R,F);delete E.requests[v]}))}getGlyphs(p,v){const S=[],E=this.url||Ta.GLYPHS_URL;for(const R in p)for(const F of p[R])S.push({stack:R,id:F});Ut(S,({stack:R,id:F},q)=>{let K=this.entries[R];K||(K=this.entries[R]={glyphs:{},requests:{},ranges:{},ascender:void 0,descender:void 0});let J=K.glyphs[F];if(J!==void 0)return void q(null,{stack:R,id:F,glyph:J});if(J=this._tinySDF(K,R,F),J)return K.glyphs[F]=J,void q(null,{stack:R,id:F,glyph:J});const le=Math.floor(F/256);if(256*le>65535)return Er("glyphs > 65535 not supported"),void q(null,{stack:R,id:F,glyph:J});if(K.ranges[le])return void q(null,{stack:R,id:F,glyph:J});let fe=K.requests[le];fe||(fe=K.requests[le]=[],this.glyphLoader.loadGlyphRange(R,le,E,this.requestManager,(ye,Te)=>{if(Te){K.ascender=Te.ascender,K.descender=Te.descender;for(const Pe in Te.glyphs)this._doesCharSupportLocalGlyph(+Pe)||(K.glyphs[+Pe]=Te.glyphs[+Pe]);K.ranges[le]=!0}for(const Pe of fe)Pe(ye,Te);delete K.requests[le]})),fe.push((ye,Te)=>{ye?q(ye):Te&&q(null,{stack:R,id:F,glyph:Te.glyphs[F]||null})})},(R,F)=>{if(R)v(R);else if(F){const q={};for(const{stack:K,id:J,glyph:le}of F)q[K]===void 0&&(q[K]={}),q[K].glyphs===void 0&&(q[K].glyphs={}),q[K].glyphs[J]=le&&{id:le.id,bitmap:le.bitmap.clone(),metrics:le.metrics},q[K].ascender=this.entries[K].ascender,q[K].descender=this.entries[K].descender;v(null,q)}})}_doesCharSupportLocalGlyph(p){return this.localGlyphMode!==QTe.none&&(this.localGlyphMode===QTe.all?!!this.localFontFamily:!!this.localFontFamily&&(tg(p)||Rb(p)||av(p)||vm(p)||y1(p)||mw(p)||(v=p)>=131072&&v<=173791||(S=>S>=66736&&S<=66815)(p)));var v}_tinySDF(p,v,S){const E=this.localFontFamily;if(!E||!this._doesCharSupportLocalGlyph(S))return;let R=p.tinySDF;if(!R){let Qe="400";/bold/i.test(v)?Qe="900":/medium/i.test(v)?Qe="500":/light/i.test(v)&&(Qe="200"),R=p.tinySDF=new Mee.TinySDF({fontFamily:E,fontWeight:Qe,fontSize:48,buffer:6,radius:16}),R.fontWeight=Qe}const F=R.fontWeight;if(this.localGlyphs[F][S])return this.localGlyphs[F][S];const q=String.fromCodePoint(S),{data:K,width:J,height:le,glyphWidth:fe,glyphHeight:ye,glyphLeft:Te,glyphTop:Pe,glyphAdvance:Ue}=R.draw(q);return this.localGlyphs[F][S]={id:S,bitmap:new aC({width:J,height:le},K),metrics:{width:fe/2,height:ye/2,left:Te/2,top:Pe/2-27,advance:Ue/2,localGlyph:!0}}}}function bXe(j,p){return j+p[1]-p[0]}function JTe(j,p,v,S,E=1){const R=[],F=j.imagePrimary,q=F.pixelRatio,K=F.paddedRect.w-2,J=F.paddedRect.h-2,le=(j.right-j.left)*E,fe=(j.bottom-j.top)*E,ye=F.stretchX||[[0,K]],Te=F.stretchY||[[0,J]],Pe=ye.reduce(bXe,0),Ue=Te.reduce(bXe,0),Qe=K-Pe,at=J-Ue;let pt=0,dt=Pe,wt=0,Tt=Ue,Lt=0,fs=Qe,Jt=0,ps=at;if(F.content&&S){const is=F.content;pt=Lee(ye,0,is[0]),wt=Lee(Te,0,is[1]),dt=Lee(ye,is[0],is[2]),Tt=Lee(Te,is[1],is[3]),Lt=is[0]-pt,Jt=is[1]-wt,fs=is[2]-is[0]-dt,ps=is[3]-is[1]-Tt}const rs=(is,dn,fn,_n)=>{const Sn=Pee(is.stretch-pt,dt,le,j.left*E),wn=Iee(is.fixed-Lt,fs,is.stretch,Pe),Un=Pee(dn.stretch-wt,Tt,fe,j.top*E),ln=Iee(dn.fixed-Jt,ps,dn.stretch,Ue),Nn=Pee(fn.stretch-pt,dt,le,j.left*E),Tn=Iee(fn.fixed-Lt,fs,fn.stretch,Pe),Vn=Pee(_n.stretch-wt,Tt,fe,j.top*E),ar=Iee(_n.fixed-Jt,ps,_n.stretch,Ue),zr=new sn(Sn,Un),yr=new sn(Nn,Un),gr=new sn(Nn,Vn),ir=new sn(Sn,Vn),Dr=new sn(wn/q,ln/q),Zr=new sn(Tn/q,ar/q),Aa=p*Math.PI/180;if(Aa){const Ii=Math.sin(Aa),kd=Math.cos(Aa),Jo=[kd,-Ii,Ii,kd];zr._matMult(Jo),yr._matMult(Jo),ir._matMult(Jo),gr._matMult(Jo)}const ma=is.stretch+is.fixed,mi=fn.stretch+fn.fixed,bo=dn.stretch+dn.fixed,pi=_n.stretch+_n.fixed,ko=j.imageSecondary;return{tl:zr,tr:yr,bl:ir,br:gr,texPrimary:{x:F.paddedRect.x+1+ma,y:F.paddedRect.y+1+bo,w:mi-ma,h:pi-bo},texSecondary:ko?{x:ko.paddedRect.x+1+ma,y:ko.paddedRect.y+1+bo,w:mi-ma,h:pi-bo}:void 0,writingMode:void 0,glyphOffset:[0,0],sectionIndex:0,pixelOffsetTL:Dr,pixelOffsetBR:Zr,minFontScaleX:fs/q/le,minFontScaleY:ps/q/fe,isSDF:v}};if(F.stretchX||F.stretchY){const is=_Xe(ye,Qe,Pe),dn=_Xe(Te,at,Ue);for(let fn=0;fn0?[pt,-dt]:wt<0?[-pt,dt]:pt===0?[dt,pt]:[dt,-pt]}(v);let Te=Math.abs(p.top-p.bottom);for(const at of p.positionedLines)Te-=at.lineOffset;const Pe=p.positionedLines.length,Ue=Te/Pe;let Qe=p.top-v[1];for(let at=0;atR)&&(R=Pe.x),(!Te||Pe.y>F)&&(F=Pe.y)}const K=Math.min(R-S,F-E);let J=K/2;const le=new ch([],eVt);if(K===0)return new sn(S,E);for(let Te=S;Tefe.d||!fe.d)&&(fe=Te,v&&console.log("found best %d after %d probes",Math.round(1e4*Te.d)/1e4,ye)),Te.max-fe.d<=p||(J=Te.h/2,le.push(new zO(Te.p.x-J,Te.p.y-J,J,j)),le.push(new zO(Te.p.x+J,Te.p.y-J,J,j)),le.push(new zO(Te.p.x-J,Te.p.y+J,J,j)),le.push(new zO(Te.p.x+J,Te.p.y+J,J,j)),ye+=4)}return v&&(console.log(`num probes: ${ye}`),console.log(`best distance: ${fe.d}`)),fe.p}function eVt(j,p){return p.max-j.max}Mee.TinySDF=class{constructor({fontSize:j=24,buffer:p=3,radius:v=8,cutoff:S=.25,fontFamily:E="sans-serif",fontWeight:R="normal",fontStyle:F="normal",lang:q=null}={}){this.buffer=p,this.cutoff=S,this.radius=v,this.lang=q;const K=this.size=j+4*p,J=this._createCanvas(K),le=this.ctx=J.getContext("2d",{willReadFrequently:!0});le.font=`${F} ${R} ${j}px ${E}`,le.textBaseline="alphabetic",le.textAlign="left",le.fillStyle="black",this.gridOuter=new Float64Array(K*K),this.gridInner=new Float64Array(K*K),this.f=new Float64Array(K),this.z=new Float64Array(K+1),this.v=new Uint16Array(K)}_createCanvas(j){const p=document.createElement("canvas");return p.width=p.height=j,p}draw(j){const{width:p,actualBoundingBoxAscent:v,actualBoundingBoxDescent:S,actualBoundingBoxLeft:E,actualBoundingBoxRight:R}=this.ctx.measureText(j),F=Math.ceil(v),q=Math.max(0,Math.min(this.size-this.buffer,Math.ceil(R-E))),K=Math.min(this.size-this.buffer,F+Math.ceil(S)),J=q+2*this.buffer,le=K+2*this.buffer,fe=Math.max(J*le,0),ye=new Uint8ClampedArray(fe),Te={data:ye,width:J,height:le,glyphWidth:q,glyphHeight:K,glyphTop:F,glyphLeft:0,glyphAdvance:p};if(q===0||K===0)return Te;const{ctx:Pe,buffer:Ue,gridInner:Qe,gridOuter:at}=this;this.lang&&(Pe.lang=this.lang),Pe.clearRect(Ue,Ue,q,K),Pe.fillText(j,Ue,Ue+F);const pt=Pe.getImageData(Ue,Ue,q,K);at.fill(Yq,0,fe),Qe.fill(0,0,fe);for(let dt=0;dt0?fs*fs:0,Qe[Lt]=fs<0?fs*fs:0}}yXe(at,0,0,J,le,J,this.f,this.v,this.z),yXe(Qe,Ue,Ue,q,K,J,this.f,this.v,this.z);for(let dt=0;dtR.y!=Ue.y>R.y&&R.x<(Ue.x-Pe.x)*(R.y-Pe.y)/(Ue.y-Pe.y)+Pe.x&&(q=!q),K=Math.min(K,gw(R,Pe,Ue))}}return(q?1:-1)*Math.sqrt(K)}(this.p,E),this.max=this.d+this.h*Math.SQRT2}}const tVt=Object.keys,eEe=Number.POSITIVE_INFINITY,sVt=Math.sqrt(2);function cC(j,p,v,S,E,R){const F=HTe(j)&&j.collisionPadding?j.collisionPadding:[0,0,0,0],q={top:j.top-F[1],bottom:j.bottom+F[3],left:j.left-F[0],right:j.right+F[2],scaled:!1};return S!==void 0&&function(K,J){K.top*=J,K.bottom*=J,K.left*=J,K.right*=J,K.scaled=!0}(q,S),R&&(q.left+=R[0],q.right+=R[0],q.top+=R[1],q.bottom+=R[1]),v&&function(K,J,le){if(!J)return;const fe=Nr(J),ye=new sn(le?le[0]:0,le?le[1]:0),Te=new sn(K.left,K.top),Pe=new sn(K.right,K.top),Ue=new sn(K.left,K.bottom),Qe=new sn(K.right,K.bottom);Te._rotateAround(fe,ye),Pe._rotateAround(fe,ye),Ue._rotateAround(fe,ye),Qe._rotateAround(fe,ye),K.left=Math.min(Te.x,Pe.x,Ue.x,Qe.x),K.right=Math.max(Te.x,Pe.x,Ue.x,Qe.x),K.top=Math.min(Te.y,Pe.y,Ue.y,Qe.y),K.bottom=Math.max(Te.y,Pe.y,Ue.y,Qe.y)}(q,v,E),p?{top:Math.min(p.top,q.top),bottom:Math.max(p.bottom,q.bottom),left:Math.min(p.left,q.left),right:Math.max(p.right,q.right),scaled:p.scaled||q.scaled}:q}function NXe(j,[p,v]){let S=0,E=0;if(v===eEe){p<0&&(p=0);const R=p/sVt;switch(j){case"top-right":case"top-left":E=R-7;break;case"bottom-right":case"bottom-left":E=7-R;break;case"bottom":E=7-p;break;case"top":E=p-7}switch(j){case"top-right":case"bottom-right":S=-R;break;case"top-left":case"bottom-left":S=R;break;case"left":S=p;break;case"right":S=-p}}else{switch(p=Math.abs(p),v=Math.abs(v),j){case"top-right":case"top-left":case"top":E=v-7;break;case"bottom-right":case"bottom-left":case"bottom":E=7-v}switch(j){case"top-right":case"bottom-right":case"right":S=-p;break;case"top-left":case"bottom-left":case"left":S=p}}return[S,E]}function nVt(j,p,v,S,E,R,F,q,K,J,le,fe,ye,Te,Pe){const Ue=j.layers[0],Qe=Ue.appearances;if(Qe.length===0)return{iconBBox:null,iconVerticalBBox:null,textBBox:null,textVerticalBBox:null};const at={iconBBox:null,iconVerticalBBox:null},pt={textBBox:null,textVerticalBBox:null},{baseIconRotate:dt,baseTextRotate:wt,iconScaleFactor:Tt}=function(fs,Jt,ps){const rs=fs.get("icon-rotate").evaluate(Jt,{},ps),is=fs.get("text-rotate").evaluate(Jt,{},ps),[dn,fn]=fs.get("icon-size-scale-range");return{baseIconRotate:rs,baseTextRotate:is,iconScaleFactor:it(1,dn,fn)}}(S,E,R);p&&(at.iconBBox=cC(p,at.iconBBox,dt),v)&&(at.iconVerticalBBox=cC(v,at.iconVerticalBBox,dt+90));const Lt=Ree(fe.horizontal);Lt&&(pt.textBBox=cC(Lt,pt.textBBox,wt,1,Te)),fe.vertical&&(pt.textVerticalBBox=cC(fe.vertical,pt.textVerticalBBox,wt+90,1,Te));for(const fs of Qe)fs.hasIconLayoutProperties()&&rVt(at,j,Ue,fs,E,R,q,dt,F,K,p,J,Tt,le,Pe),fs.hasTextLayoutProperties()&&aVt(pt,Ue,fs,E,R,Te,wt,ye,Lt,fe.vertical);return{iconBBox:at.iconBBox,iconVerticalBBox:at.iconVerticalBBox,textBBox:pt.textBBox,textVerticalBBox:pt.textVerticalBBox}}function rVt(j,p,v,S,E,R,F,q,K,J,le,fe,ye,Te,Pe){const{appearanceIconOffset:Ue,appearanceIconRotate:Qe,appearanceIconSize:at}=kXe(S,v,E,R,F,q,K,J.iconScaleFactor);let pt=null,dt=null,wt=null;S.hasLayoutProperty("icon-image")?wt=function(Lt,fs,Jt,ps,rs,is,dn,fn){let _n=null;const Sn=fs.getAppearanceValueAndResolveTokens(Jt,"icon-image",ps,rs,fn);if(Sn){const wn=Lt.getResolvedImageFromTokens(Sn),Un=Jt.hasLayoutProperty("icon-size")?Jt.getUnevaluatedLayoutProperty("icon-size"):fs._unevaluatedLayout._values["icon-size"],ln=Zq(wn,A6(Lt.zoom,Un,Lt.worldview,fn),Un,rs,Lt.zoom,ps,Lt.pixelRatio,dn,Lt.worldview,fn);_n=is.get(ln.iconPrimary.toString())}return _n}(p,v,S,E,R,fe,ye,Pe):le&&(wt=le.imagePrimary),wt&&(pt=Tee(wt,null,Ue,Te),p.allowVerticalPlacement&&(dt=Tee(wt,null,Ue,Te)));const Tt=K>0?at/K:1;pt&&(j.iconBBox=cC(pt,j.iconBBox,Qe,Tt!==1?Tt:void 0)),dt&&(j.iconVerticalBBox=cC(dt,j.iconVerticalBBox,Qe+90,Tt!==1?Tt:void 0))}function kXe(j,p,v,S,E,R,F,q){const K=j.hasLayoutProperty("icon-offset")?p.getAppearanceValueAndResolveTokens(j,"icon-offset",v,S,[]):null,J=K&&Array.isArray(K)?K:E,le=j.hasLayoutProperty("icon-rotate")?p.getAppearanceValueAndResolveTokens(j,"icon-rotate",v,S,[]):null,fe=typeof le=="number"?le:R,ye=j.hasLayoutProperty("icon-size")?p.getAppearanceValueAndResolveTokens(j,"icon-size",v,S,[]):null;return{appearanceIconOffset:J,appearanceIconRotate:fe,appearanceIconSize:typeof ye=="number"?ye*q:F}}function aVt(j,p,v,S,E,R,F,q,K,J){const{appearanceTextOffset:le,appearanceTextRotate:fe,appearanceTextSize:ye}=SXe(v,p,S,E,R,F,q),Te=ye/q,Pe=[(le[0]-R[0])*Te,(le[1]-R[1])*Te],Ue=Pe[0]!==0||Pe[1]!==0;K&&(j.textBBox=cC(K,j.textBBox,fe,Te,le,Ue?Pe:void 0)),J&&(j.textVerticalBBox=cC(J,j.textVerticalBBox,fe+90,Te,le,Ue?Pe:void 0))}function SXe(j,p,v,S,E,R,F){const q=j.hasLayoutProperty("text-offset")?p.getAppearanceValueAndResolveTokens(j,"text-offset",v,S,[]):null,K=q&&Array.isArray(q)?[q[0]*wm,q[1]*wm]:E,J=j.hasLayoutProperty("text-rotate")?p.getAppearanceValueAndResolveTokens(j,"text-rotate",v,S,[]):null,le=typeof J=="number"?J:R,fe=j.hasLayoutProperty("text-size")?p.getAppearanceValueAndResolveTokens(j,"text-size",v,S,[]):null;return{appearanceTextOffset:K,appearanceTextRotate:le,appearanceTextSize:typeof fe=="number"?fe:F}}function Dee(j,p,v,S,E,R,F,q,K){if(!p||!p.usvg)return;const J=lXe(S),le=lXe(E),fe=R!=="both"&&R!=="width"||!iXe(S)?1:le.width/J.width,ye=R!=="both"&&R!=="height"||!oXe(S)?1:le.height/J.height;v.scaleSelf(fe,ye);const Te=v.toString();F.set(Te,v),q.set(Te,p);const{imagePosition:Pe}=ZTe(Te,p,1);K.set(Te,Pe)}function CXe(j,p,v,S,E,R,F,q,K,J){if(!j)return;const le=function(fe,ye,Te,Pe,Ue,Qe,at){if(fe.kind==="camera")return fe.maxSize;if(fe.kind==="composite"){const pt=ye.possiblyEvaluate(new xi(fe.maxZoom,{worldview:Qe}),Te,at).evaluate(Ue,{},Te,at),dt=ye.possiblyEvaluate(new xi(fe.minZoom,{worldview:Qe}),Te,at).evaluate(Ue,{},Te,at);return Math.max(pt,dt)}return ye.possiblyEvaluate(new xi(Pe,{worldview:Qe}),Te,at).evaluate(Ue,{},Te,at)}(p,v,S,E,R,K,J);return j.scaleSelf(le*q*F)}function Zq(j,p,v,S,E,R,F,q,K,J){return{iconPrimary:CXe(j.getPrimary(),p,v,S,E,R,F,q,K,J),iconSecondary:CXe(j.getSecondary(),p,v,S,E,R,F,q,K,J)}}function iVt(j,p,v){if(!p)return;const S=v.get(j.toString()),E=v.get(p.toString());S&&E&&(S.paddedRect.w===E.paddedRect.w&&S.paddedRect.h===E.paddedRect.h||Er(`Mismatch in icon variant sizes: ${j.toString()} and ${p.toString()}`),S.usvg!==E.usvg&&Er(`Mismatch in icon variant image types: ${j.id} and ${p.id}`))}function AXe(j,p,v,S){if(!j)return;const E=p.get(v.toString());if(E&&(j.imagePrimary=E),S){const R=p.get(S.toString());j.imageSecondary=R}}function oVt(j,p){for(const v in j.horizontal)TXe(j.horizontal[v],p);TXe(j.vertical,p)}function TXe(j,p){if(j){for(const v of j.positionedLines)for(const S of v.positionedGlyphs)if(S.image!==null){const E=S.image.toString();S.rect=p.get(E).paddedRect}}}function tEe(j){switch(j){case"right":case"top-right":case"bottom-right":return"right";case"left":case"top-left":case"bottom-left":return"left"}return"center"}function lVt(j,p,v,S,E,R,F,q,K){const J=Ree(R.horizontal)||R.vertical,le=v.get("icon-text-fit-padding").evaluate(S,{},E);let fe,ye=p;return p&&K!=="none"&&(j.allowVerticalPlacement&&R.vertical&&(fe=GTe(p,R.vertical,K,le,q,F)),J&&(ye=GTe(p,J,K,le,q,F))),{defaultShapedIcon:ye,verticallyShapedIcon:fe}}function EXe(j,p){return j*p/24}function cVt(j,p,v,S,E,R,F,q,K,J,le,fe,ye,Te,Pe,Ue,Qe,at,pt,dt,wt,Tt,Lt,fs){let Jt=F.textMaxSize.evaluate(p,{},ye);Jt===void 0?Jt=q*F.textScaleFactor:Jt*=F.textScaleFactor;const ps=j.layers[0].layout,rs=EXe(q,F.textScaleFactor),is=Ree(v.horizontal)||v.vertical,dn=j.hasAnyAppearanceLayoutProperty(["text-size","text-offset","text-rotate"]),fn=j.getAppearanceFeatureData(p.index);(Qe!=="none"||dn)&&fn&&(fn.textShaping=is,fn.iconTextFitPadding=ps.get("icon-text-fit-padding").evaluate(p,{},ye),fn.fontScale=rs,fn.textScaleFactor=F.textScaleFactor);const _n=Te.name==="globe",Sn=j.tilePixelRatio*Jt/24,wn=(ar=j.overscaling,j.zoom>18&&ar>2&&(ar>>=1),Math.max(sr/(512*ar),1)*ps.get("symbol-spacing")),Un=ps.get("text-padding")*j.tilePixelRatio,ln=ps.get("icon-padding")*j.tilePixelRatio,Nn=Nr(ps.get("text-max-angle")),Tn=ps.get("icon-rotation-alignment")==="map"&&dt!=="point",Vn=wn/2;var ar;j.hasAnyIconTextFit===!1&&Qe!=="none"&&(j.hasAnyIconTextFit=!0);const zr=p.properties?+p.properties[Ni]:null,yr=zr&&j.elevationFeatureIdToIndex?j.elevationFeatureIdToIndex.get(zr):65535,gr=(ir,Dr,Zr)=>{if(Dr.x<0||Dr.x>=sr||Dr.y<0||Dr.y>=sr)return;let Aa=null;if(_n){const{x:ma,y:mi,z:bo}=Te.projectTilePoint(Dr.x,Dr.y,Zr);Aa={anchor:new CS(ma,mi,bo,0,void 0),up:Te.upVector(Zr,Dr.x,Dr.y)}}(function(ma,mi,bo,pi,ko,Ii,kd,Jo,Mo,Hl,pd,jm,fd,Xd,Xu,Qd,Mf,Nm,Oi,jx,xu,lp,Nx,Lf,Sd,Dg,cp,ete,WO,v0,kEe,KO){const AS=ma.addToLineVertexArray(mi,pi);let TS,Fb,zb,I6,YO,Zi,dp,Jd=0,Xh=0,Bb=0,fv=0,gv=-1,xv=-1;const vw={};let tte=Jc("");const Jj=bo?bo.anchor:mi,ZO=ete!=="none";let XO=0,Sh=0;if(Mo._unevaluatedLayout.getValue("text-radial-offset")===void 0){const yu=Mo.layout.get("text-offset").evaluate(xu,{},Sd);XO=yu[0]*wm,Sh=yu[1]*wm}else XO=Mo.layout.get("text-radial-offset").evaluate(xu,{},Sd)*wm,Sh=eEe;if(ma.allowVerticalPlacement&&ko.vertical){const yu=ko.vertical;if(Xu)Zi=rEe(yu),Jo&&(dp=rEe(Jo));else{const kx=Mo.layout.get("text-rotate").evaluate(xu,{},Sd)+90;zb=Oee(Hl,Jj,mi,pd,jm,fd,yu,Xd,kx,Qd,KO),Jo&&(I6=Oee(Hl,Jj,mi,pd,jm,fd,Jo,Nm,kx,null,kEe))}}if(Ii){const yu=Mo.layout.get("icon-rotate").evaluate(xu,{},Sd),kx=JTe(Ii,yu,Nx,ZO,lp.iconScaleFactor),b0=Jo?JTe(Jo,yu,Nx,ZO,lp.iconScaleFactor):void 0;Fb=Oee(Hl,Jj,mi,pd,jm,fd,Ii,Nm,yu,null,v0);const _w=function(e2,uV,QO,NHt,kHt,XQe,QQe,SHt,dOn,CEe){const JQe=e2.layers[0],eJe=JQe.appearances;let JO=uV.length;if(QO&&(JO=Math.max(JO,QO.length)),eJe.length===0)return JO;const[CHt,AHt]=NHt.get("icon-size-scale-range"),THt=it(1,CHt,AHt);for(const ate of eJe)if(ate.hasLayoutProperty("icon-image")){const tJe=JQe.getAppearanceValueAndResolveTokens(ate,"icon-image",XQe,QQe,CEe);if(tJe){const sJe=e2.getResolvedImageFromTokens(tJe);if(sJe){const nJe=ate.hasLayoutProperty("icon-size")?ate.getUnevaluatedLayoutProperty("icon-size"):kHt._values["icon-size"],EHt=Zq(sJe,A6(e2.zoom,nJe,e2.worldview,CEe),nJe,QQe,e2.zoom,XQe,e2.pixelRatio,THt,e2.worldview,CEe),rJe=SHt.get(EHt.iconPrimary.toString());rJe&&(JO=Math.max(JO,Xqt(rJe)))}}}return JO}(ma,kx,b0,Mo.layout,Mo._unevaluatedLayout,xu,Sd,ma.iconAtlasPositions,0,Lf);Jd=4*_w;const ste=Mo.layout.get("icon-size").evaluate(xu,{},Sd,Lf),nte=lp.compositeIconSizes?lp.compositeIconSizes[0].evaluate(xu,{},Sd,Lf):0,SEe=lp.compositeIconSizes?lp.compositeIconSizes[1].evaluate(xu,{},Sd,Lf):0,rte=nEe(ma.layerIds[0],ma.iconSizeData,ste,lp.iconScaleFactor,nte,SEe);ma.addSymbols(ma.icon,kx,rte,jx,Oi,xu,void 0,bo,mi,AS.lineStartIndex,AS.lineLength,-1,Lf,Sd,Dg,cp,ma.symbolInstances.length,_w),gv=ma.icon.placedSymbolArray.length-1,b0&&(Xh=4*_w,ma.addSymbols(ma.icon,b0,rte,jx,Oi,xu,pv.vertical,bo,mi,AS.lineStartIndex,AS.lineLength,-1,Lf,Sd,Dg,cp,ma.symbolInstances.length,_w),xv=ma.icon.placedSymbolArray.length-1)}for(const yu in ko.horizontal){const kx=yu,b0=ko.horizontal[kx];TS||(tte=Jc(b0.text),Xu?YO=rEe(b0):TS=Oee(Hl,Jj,mi,pd,jm,fd,b0,Xd,Mo.layout.get("text-rotate").evaluate(xu,{},Sd),Qd,KO));const _w=b0.positionedLines.length===1;if(Bb+=MXe(ma,bo,mi,b0,kd,Mo,Xu,xu,Qd,AS,ko.vertical?pv.horizontal:pv.horizontalOnly,_w?tVt(ko.horizontal):[kx],vw,gv,lp,Lf,Sd,ma.symbolInstances.length,Dg),_w)break}ko.vertical&&(fv+=MXe(ma,bo,mi,ko.vertical,kd,Mo,Xu,xu,Qd,AS,pv.vertical,["vertical"],vw,xv,lp,Lf,Sd,ma.symbolInstances.length,Dg));let hh=-1;const Qh=(yu,kx)=>yu?Math.max(yu,kx):kx;hh=Qh(YO,hh),hh=Qh(Zi,hh),hh=Qh(dp,hh);const bw=hh>-1?1:0;ma.glyphOffsetArray.length>=65535&&Er("Too many glyphs being rendered in a tile. See https://github.com/mapbox/mapbox-gl-js/issues/2907"),xu.sortKey!==void 0&&ma.addToSortKeyRanges(ma.symbolInstances.length,xu.sortKey),ma.symbolInstances.emplaceBack(mi.x,mi.y,Jj.x,Jj.y,Jj.z,vw.right>=0?vw.right:-1,vw.center>=0?vw.center:-1,vw.left>=0?vw.left:-1,vw.vertical>=0?vw.vertical:-1,gv,xv,tte,TS!==void 0?TS:ma.collisionBoxArray.length,TS!==void 0?TS+1:ma.collisionBoxArray.length,zb!==void 0?zb:ma.collisionBoxArray.length,zb!==void 0?zb+1:ma.collisionBoxArray.length,Fb!==void 0?Fb:ma.collisionBoxArray.length,Fb!==void 0?Fb+1:ma.collisionBoxArray.length,I6||ma.collisionBoxArray.length,I6?I6+1:ma.collisionBoxArray.length,pd,Bb,fv,Jd,Xh,bw,0,XO,Sh,hh,0,ZO?1:0,WO)})(j,Dr,Aa,ir,v,S,R,E,j.layers[0],j.collisionBoxArray,p.index,p.sourceLayerIndex,j.index,Un,pt,J,0,ln,Tn,at,p,F,le,fe,ye,Pe,Ue,Qe,yr,wt,Tt,Lt)};if(dt==="line")for(const ir of gee(p.geometry,0,0,sr,sr)){const Dr=Zqt(ir,wn,Nn,v.vertical||is,S,24,Sn,j.overscaling,sr);for(const Zr of Dr)is&&dVt(j,is.text,Vn,Zr)||gr(ir,Zr,ye)}else if(dt==="line-center"){for(const ir of p.geometry)if(ir.length>1){const Dr=Yqt(ir,Nn,v.vertical||is,S,24,Sn);Dr&&gr(ir,Dr,ye)}}else if(p.type==="Polygon")for(const ir of Lq(p.geometry,0)){const Dr=Jqt(ir,16);gr(ir[0],new CS(Dr.x,Dr.y,0,0,void 0),ye)}else if(p.type==="LineString")for(const ir of p.geometry)gr(ir,new CS(ir[0].x,ir[0].y,0,0,void 0),ye);else if(p.type==="Point")for(const ir of p.geometry)for(const Dr of ir)gr([Dr],new CS(Dr.x,Dr.y,0,0,void 0),ye)}const sEe=255,T6=sEe*SS;function MXe(j,p,v,S,E,R,F,q,K,J,le,fe,ye,Te,Pe,Ue,Qe,at,pt){const dt=jXe(0,S,K,R,F,q,E,j.allowVerticalPlacement,void 0,Pe.textScaleFactor),wt=R.layout.get("text-size").evaluate(q,{},Qe),Tt=Pe.compositeTextSizes?Pe.compositeTextSizes[0].evaluate(q,{},Qe):0,Lt=Pe.compositeTextSizes?Pe.compositeTextSizes[1].evaluate(q,{},Qe):0,fs=nEe(j.layerIds[0],j.textSizeData,wt,Pe.textScaleFactor,Tt,Lt);j.addSymbols(j.text,dt,fs,K,F,q,le,p,v,J.lineStartIndex,J.lineLength,Te,Ue,Qe,pt,!1,at,dt.length);for(const Jt of fe)ye[Jt]=j.text.placedSymbolArray.length-1;return 4*dt.length}function nEe(j,p,v,S,E,R){const F=p;let q=null;return F.kind==="source"?(q=[SS*v*S],q[0]>T6&&Er(`${j}: Value for "text-size" is >= ${sEe}. Reduce your "text-size".`)):F.kind==="composite"&&(q=[SS*E*S,SS*R*S],(q[0]>T6||q[1]>T6)&&Er(`${j}: Value for "text-size" is >= ${sEe}. Reduce your "text-size".`)),q}function Ree(j){for(const p in j)return j[p];return null}function Oee(j,p,v,S,E,R,F,q,K,J,le){let fe,ye,Te,Pe;if(fe=le?le.top:F.top,ye=le?le.bottom:F.bottom,Te=le?le.left:F.left,Pe=le?le.right:F.right,HTe(F)&&F.collisionPadding){const Ue=F.collisionPadding;Te-=Ue[0],fe-=Ue[1],Pe+=Ue[2],ye+=Ue[3]}if(K){const Ue=new sn(Te,fe),Qe=new sn(Pe,fe),at=new sn(Te,ye),pt=new sn(Pe,ye),dt=Nr(K);let wt=new sn(0,0);J&&(wt=new sn(J[0],J[1])),Ue._rotateAround(dt,wt),Qe._rotateAround(dt,wt),at._rotateAround(dt,wt),pt._rotateAround(dt,wt),Te=Math.min(Ue.x,Qe.x,at.x,pt.x),Pe=Math.max(Ue.x,Qe.x,at.x,pt.x),fe=Math.min(Ue.y,Qe.y,at.y,pt.y),ye=Math.max(Ue.y,Qe.y,at.y,pt.y)}return j.emplaceBack(p.x,p.y,p.z,v.x,v.y,Te,fe,Pe,ye,q,S,E,R),j.length-1}function rEe(j){HTe(j)&&j.collisionPadding&&(j.top-=j.collisionPadding[1],j.bottom+=j.collisionPadding[3]);const p=j.bottom-j.top;return p>0?Math.max(10,p):null}function dVt(j,p,v,S){const E=j.compareText;if(p in E){const R=E[p];for(let F=R.length-1;F>=0;F--)if(S.dist(R[F])dt&&(wt(Lt,_n,Jt,ps,dn,fn),wt(_n,fs,dn,fn,rs,is))}wt(fe,ye,S,R,E,R),wt(ye,Te,E,R,E,F),wt(Te,Pe,E,F,S,F),wt(Pe,fe,S,F,S,R),Ue-=dt,Qe-=dt,at+=dt,pt+=dt;const Tt=1/Math.max(at-Ue,pt-Qe);return{scale:Tt,x:Ue*Tt,y:Qe*Tt,x2:at*Tt,y2:pt*Tt,projection:p}}function PXe(j,{x:p,y:v},S=0){return new sn(((p-S)*j.scale-j.x)*sr,(v*j.scale-j.y)*sr)}const uVt=x(new Float32Array(16));class dC{constructor(p){this.spec=p,this.name=p.name,this.wrap=!1,this.requiresDraping=!1,this.supportsWorldCopies=!1,this.supportsTerrain=!1,this.supportsFog=!1,this.supportsFreeCamera=!1,this.zAxisUnit="meters",this.isReprojectedInTileSpace=!0,this.unsupportedLayers=["custom"],this.center=[0,0],this.range=[3.5,7]}project(p,v){return{x:0,y:0,z:0}}unproject(p,v){return new Cs(0,0)}projectTilePoint(p,v,S){return{x:p,y:v,z:0}}locationPoint(p,v,S,E=!0){return p._coordinatePoint(p.locationCoordinate(v,S),E)}pixelsPerMeter(p,v){return Ks(1,p)*v}pixelSpaceConversion(p,v,S){return 1}farthestPixelDistance(p){return LXe(p,p.pixelsPerMeter)}pointCoordinate(p,v,S,E){const R=p.horizonLineFromTop(!1),F=new sn(v,Math.max(R,S));return p.rayIntersectionCoordinate(p.pointRayIntersection(F,E))}pointCoordinate3D(p,v,S){const E=new sn(v,S);if(p.elevation)return p.elevation.pointCoordinate(E);{const R=this.pointCoordinate(p,E.x,E.y,0);return[R.x,R.y,R.z]}}isPointAboveHorizon(p,v){if(p.elevation&&p.elevation.visibleDemTiles.length)return!this.pointCoordinate3D(p,v.x,v.y);const S=p.horizonLineFromTop();return v.y0?v<-BO+S&&(v=-BO+S):v>BO-S&&(v=BO-S);const F=R/Math.pow(zee(v),E);let q=F*Math.sin(E*p),K=R-F*Math.cos(E*p);return q=.5*(q/Math.PI+.5),K=.5*(K/Math.PI+.5),{x:q,y:this.southernCenter?K:1-K,z:0}}unproject(p,v){p=(2*p-.5)*Math.PI,this.southernCenter&&(v=1-v),v=(2*(1-v)-.5)*Math.PI;const{n:S,f:E}=this,R=E-v,F=Math.sign(R),q=Math.sign(S)*Math.sqrt(p*p+R*R);let K=Math.atan2(p,Math.abs(R))*F;R*S<0&&(K-=Math.PI*Math.sign(p)*F);const J=it(rn(K/S)+this.center[0],-180,180),le=it(rn(2*Math.atan(Math.pow(E/q,1/S))-BO),-85.051129,vn);return new Cs(J,this.southernCenter?-le:le)}}class IXe extends dC{constructor(p){super(p),this.wrap=!0,this.supportsWorldCopies=!0,this.supportsTerrain=!0,this.supportsFog=!0,this.supportsFreeCamera=!0,this.isReprojectedInTileSpace=!1,this.unsupportedLayers=[],this.range=null}project(p,v){return{x:An(p),y:On(v),z:0}}unproject(p,v){const S=Es(p),E=cn(v);return new Cs(S,E)}}const DXe=Nr(vn);class gVt extends dC{project(p,v){const S=(v=Nr(v))*v,E=S*S;return{x:.5*((p=Nr(p))*(.8707-.131979*S+E*(E*(.003971*S-.001529*E)-.013791))/Math.PI+.5),y:1-.5*(v*(1.007226+S*(.015085+E*(.028874*S-.044475-.005916*E)))/Math.PI+1),z:0}}unproject(p,v){p=(2*p-.5)*Math.PI;let S=v=(2*(1-v)-1)*Math.PI,E=25,R=0,F=S*S;do{F=S*S;const J=F*F;R=(S*(1.007226+F*(.015085+J*(.028874*F-.044475-.005916*J)))-v)/(1.007226+F*(.045255+J*(.259866*F-.311325-.005916*11*J))),S=it(S-R,-DXe,DXe)}while(Math.abs(R)>1e-6&&--E>0);F=S*S;const q=it(rn(p/(.8707+F*(F*(F*F*F*(.003971-.001529*F)-.013791)-.131979))),-180,180),K=rn(S);return new Cs(q,K)}}const RXe=Nr(vn);class xVt extends dC{project(p,v){v=Nr(v),p=Nr(p);const S=Math.cos(v),E=2/Math.PI,R=Math.acos(S*Math.cos(p/2)),F=Math.sin(R)/R,q=.5*(p*E+2*S*Math.sin(p/2)/F)||0,K=.5*(v+Math.sin(v)/F)||0;return{x:.5*(q/Math.PI+.5),y:1-.5*(K/Math.PI+1),z:0}}unproject(p,v){let S=p=(2*p-.5)*Math.PI,E=v=(2*(1-v)-1)*Math.PI,R=25;const F=1e-6;let q=0,K=0;do{const J=Math.cos(E),le=Math.sin(E),fe=2*le*J,ye=le*le,Te=J*J,Pe=Math.cos(S/2),Ue=Math.sin(S/2),Qe=2*Pe*Ue,at=Ue*Ue,pt=1-Te*Pe*Pe,dt=pt?1/pt:0,wt=pt?Math.acos(J*Pe)*Math.sqrt(1/pt):0,Tt=.5*(2*wt*J*Ue+2*S/Math.PI)-p,Lt=.5*(wt*le+E)-v,fs=.5*dt*(Te*at+wt*J*Pe*ye)+1/Math.PI,Jt=dt*(Qe*fe/4-wt*le*Ue),ps=.125*dt*(fe*Ue-wt*le*Te*Qe),rs=.5*dt*(ye*Pe+wt*at*J)+.5,is=Jt*ps-rs*fs;q=(Lt*Jt-Tt*rs)/is,K=(Tt*ps-Lt*fs)/is,S=it(S-q,-Math.PI,Math.PI),E=it(E-K,-RXe,RXe)}while((Math.abs(q)>F||Math.abs(K)>F)&&--R>0);return new Cs(rn(S),rn(E))}}class OXe extends dC{constructor(p){super(p),this.center=p.center||[0,0],this.parallels=p.parallels||[0,0],this.cosPhi=Math.max(.01,Math.cos(Nr(this.parallels[0]))),this.scale=1/(2*Math.max(Math.PI*this.cosPhi,1/this.cosPhi)),this.wrap=!0,this.supportsWorldCopies=!0}project(p,v){const{scale:S,cosPhi:E}=this;return{x:Nr(p)*E*S+.5,y:-Math.sin(Nr(v))/E*S+.5,z:0}}unproject(p,v){const{scale:S,cosPhi:E}=this,R=-(v-.5)/S,F=it(rn((p-.5)/S)/E,-180,180),q=Math.asin(it(R*E,-1,1)),K=it(rn(q),-85.051129,vn);return new Cs(F,K)}}class yVt extends IXe{constructor(p){super(p),this.requiresDraping=!0,this.supportsWorldCopies=!1,this.supportsFog=!0,this.zAxisUnit="pixels",this.unsupportedLayers=["debug"],this.range=[3,5]}projectTilePoint(p,v,S){const E=kq(p,v,S);return Ge(E,E,Sq(WN(S))),{x:E[0],y:E[1],z:E[2]}}locationPoint(p,v,S){const E=Zt(v.lat,v.lng),R=Me([],E),F=S?p._centerAltitude+S:p.elevation?p.elevation.getAtPointOrZero(p.locationCoordinate(v),p._centerAltitude):p._centerAltitude;ve(E,E,R,Ks(1,0)*sr*F);const q=x(new Float64Array(16));return b(q,p.pixelMatrix,p.globeMatrix),Ge(E,E,q),new sn(E[0],E[1])}pixelsPerMeter(p,v){return Ks(1,0)*v}pixelSpaceConversion(p,v,S){const E=Ks(1,p)*v,R=mr(Ks(1,45)*v,E,S);return this.pixelsPerMeter(p,v)/R}createTileMatrix(p,v,S){const E=QAe(WN(S.canonical));return b(new Float64Array(16),p.globeMatrix,E)}createInversionMatrix(p,v){const{center:S}=p,E=Sq(WN(v));return P(E,E,Nr(S.lng)),T(E,E,Nr(S.lat)),A(E,E,[p._pixelsPerMercatorPixel,p._pixelsPerMercatorPixel,1]),Float32Array.from(E)}pointCoordinate(p,v,S,E){return JKe(p,v,S,!0)||new Yr(0,0)}pointCoordinate3D(p,v,S){const E=this.pointCoordinate(p,v,S,0);return[E.x,E.y,E.z]}isPointAboveHorizon(p,v){return!JKe(p,v.x,v.y,!1)}farthestPixelDistance(p){const v=function(E,R){const F=E.cameraToCenterDistance,q=E._centerAltitude*R,K=E._camera,J=E._camera.forward(),le=me([],xe([],J,-F),[0,0,q]),fe=E.worldSize/(2*Math.PI),ye=[0,0,-fe],Te=E.width/E.height,Pe=Math.tan(E.fovAboveCenter),Ue=xe([],K.up(),Pe),Qe=xe([],K.right(),Pe*Te),at=Me([],me([],me([],J,Ue),Qe)),pt=[];let dt;if(new Xi(le,at).closestPointOnSphere(ye,fe,pt)){const wt=me([],pt,ye),Tt=$e([],wt,le);dt=Math.cos(E.fovAboveCenter)*X(Tt)}else{const wt=$e([],le,ye),Tt=$e([],ye,le);Me(Tt,Tt);const Lt=X(wt)-fe;dt=Math.sqrt(Lt*(Lt+2*fe));const fs=Math.acos(dt/(fe+Lt))-Math.acos(Re(J,Tt));dt*=Math.cos(fs)}return 1.01*dt}(p,this.pixelsPerMeter(p.center.lat,p.worldSize)),S=jS(p.zoom);if(S>0){const E=LXe(p,Ks(1,p.center.lat)*p.worldSize),R=p.worldSize/(2*Math.PI),F=Math.max(p.width,p.height)/p.worldSize*Math.PI;return mr(v,E+R*(1-Math.cos(F)),Math.pow(S,10))}return v}upVector(p,v,S){return kq(v,S,p,1)}upVectorScale(p){return{metersToTile:QJ(eee(WN(p)))}}}function FXe(j){const p=j.parallels,v=!!p&&Math.abs(p[0]+p[1])<.01;switch(j.name){case"mercator":return new IXe(j);case"equirectangular":return new pVt(j);case"naturalEarth":return new gVt(j);case"equalEarth":return new mVt(j);case"winkelTripel":return new xVt(j);case"albers":return v?new OXe(j):new hVt(j);case"lambertConformalConic":return v?new OXe(j):new fVt(j);case"globe":return new yVt(j)}throw new Error(`Invalid projection name: ${j.name}`)}class vVt{constructor(p,v){this.lastParams=null,this.lastAllFeaturesIndex=-2,this.appearancesVersion=v,this.appearances=p;const S=p.map(E=>function(R){if(!R.condition)return{featureDependent:!1,stateDependent:!1,zoomDependent:!1,pitchDependent:!1,brightnessDependent:!1,worldviewDependent:!1};const F=R.condition.expression;return{featureDependent:!x1(F),stateDependent:!Cf(F),zoomDependent:!Wd(F,["zoom"]),pitchDependent:!Wd(F,["pitch"]),brightnessDependent:!Wd(F,["brightness","measure-light"]),worldviewDependent:!Wd(F,["worldview"])}}(E));this.anyFeatureDependent=S.some(E=>E.featureDependent),this.anyStateDependent=S.some(E=>E.stateDependent)}update(p,v){const S=this.lastParams,E=!S||S.zoom!==p.zoom||S.pitch!==(p.pitch||0)||S.brightness!==(p.brightness||0)||S.worldview!==p.worldview;this.lastParams={zoom:p.zoom,pitch:p.pitch||0,brightness:p.brightness||0,worldview:p.worldview};const R=v&&this.anyStateDependent;if(!E&&!R&&this.lastAllFeaturesIndex!==-2)return{kind:"no-changes"};if(!this.anyFeatureDependent&&!R){const F=this.evaluateAllFeatures(p);return F===this.lastAllFeaturesIndex?{kind:"no-changes"}:(this.lastAllFeaturesIndex=F,{kind:"all-features",appearanceIndex:F})}return{kind:"per-feature"}}evaluateAllFeatures(p){for(let v=0;v{for(let E=0;EF-q),R=new Map;for(const F of E){const q=S.get(F);R.set(F,new Ul(q))}return v&&(this.cachedBatchIndices=E,this.cachedBatchSegments=R),{batchIndices:E,batchSegments:R}}snapshotSymbolVertexData(p,v){const S=p*UO;return this.layoutVertexArray.uint16.slice(S,S+v*UO)}restoreSymbolVertexData(p,v){this.layoutVertexArray.uint16.set(v,p*UO)}updateSymbolVertexData(p,v,S,E,R,F,q,K,J,le,fe,ye,Te){const Pe=this.layoutVertexArray.uint16,Ue=p*UO;Pe[Ue]=v,Pe[Ue+1]=S,Pe[Ue+2]=E,Pe[Ue+3]=R,Pe[Ue+4]=F,Pe[Ue+5]=q,Pe[Ue+6]=K,Pe[Ue+7]=J,Pe[Ue+8]=le,Pe[Ue+9]=fe,Pe[Ue+10]=ye,Pe[Ue+11]=Te}upload(p,v,S,E,R,F){this.isEmpty()||(S&&(this.cachedBatchIndices=null,this.cachedBatchSegments=null,this.layoutVertexBuffer=p.createVertexBuffer(this.layoutVertexArray,wqt.members,!!F),this.indexBuffer=p.createIndexBuffer(this.indexArray,v),this.dynamicLayoutVertexBuffer=p.createVertexBuffer(this.dynamicLayoutVertexArray,Nqt.members,!0),this.opacityVertexBuffer=p.createVertexBuffer(this.opacityVertexArray,_Vt,!0),this.iconTransitioningVertexArray.length>0&&(this.iconTransitioningVertexBuffer=p.createVertexBuffer(this.iconTransitioningVertexArray,Aqt.members,!0)),this.globeExtVertexArray.length>0&&(this.globeExtVertexBuffer=p.createVertexBuffer(this.globeExtVertexArray,jqt.members,!0)),!this.zOffsetVertexBuffer&&(this.zOffsetVertexArray.length>0||R)&&(this.zOffsetVertexBuffer=p.createVertexBuffer(this.zOffsetVertexArray,kqt.members,!0)),!this.orientationVertexBuffer&&this.orientationVertexArray&&this.orientationVertexArray.length>0&&(this.orientationVertexBuffer=p.createVertexBuffer(this.orientationVertexArray,Cqt.members,!0)),this.opacityVertexBuffer.itemSize=1,this.featureIdArray&&this.featureIdArray.length>0&&(this.featureIdBuffer=p.createVertexBuffer(this.featureIdArray,Sqt.members,!1))),(S||E)&&(this.programConfigurations.upload(p),this.uboBinder&&this.uboBinder.upload(p)))}destroy(){this.layoutVertexBuffer&&(this.layoutVertexBuffer.destroy(),this.indexBuffer.destroy(),this.programConfigurations.destroy(),this.segments.destroy(),this.dynamicLayoutVertexBuffer.destroy(),this.opacityVertexBuffer.destroy(),this.iconTransitioningVertexBuffer&&this.iconTransitioningVertexBuffer.destroy(),this.globeExtVertexBuffer&&this.globeExtVertexBuffer.destroy(),this.zOffsetVertexBuffer&&this.zOffsetVertexBuffer.destroy(),this.orientationVertexBuffer&&this.orientationVertexBuffer.destroy(),this.featureIdBuffer&&this.featureIdBuffer.destroy(),this.uboBinder&&this.uboBinder.destroy())}}pr(aEe,"SymbolBuffers",{omit:["cachedBatchIndices","cachedBatchSegments"]});class iEe{constructor(p,v,S){this.layoutVertexArray=new p,this.layoutAttributes=v,this.indexArray=new S,this.segments=new Ul,this.collisionVertexArray=new f6,this.collisionVertexArrayExt=new Gj}upload(p){this.layoutVertexBuffer=p.createVertexBuffer(this.layoutVertexArray,this.layoutAttributes),this.indexBuffer=p.createIndexBuffer(this.indexArray),this.collisionVertexBuffer=p.createVertexBuffer(this.collisionVertexArray,Tqt.members,!0),this.collisionVertexBufferExt=p.createVertexBuffer(this.collisionVertexArrayExt,Eqt.members,!0)}destroy(){this.layoutVertexBuffer&&(this.layoutVertexBuffer.destroy(),this.indexBuffer.destroy(),this.segments.destroy(),this.collisionVertexBuffer.destroy(),this.collisionVertexBufferExt.destroy())}}pr(iEe,"CollisionBuffers");class Zj{constructor(p){this.collisionBoxArray=p.collisionBoxArray,this.zoom=p.zoom,this.overscaling=p.overscaling,this.layers=p.layers,this.layerIds=this.layers.map(F=>F.fqid),this.index=p.index,this.pixelRatio=p.pixelRatio,this.sourceLayerIndex=p.sourceLayerIndex,this.hasPattern=!1,this.hasRTLText=!1,this.fullyClipped=!1,this.hasAnyIconTextFit=!1,this.sortKeyRanges=[],this.collisionCircleArray=[],this.placementInvProjMatrix=x([]),this.placementViewportMatrix=x([]);const v=this.layers[0]._unevaluatedLayout._values;this.worldview=p.worldview,this.localizable=p.localizable,this.maxUniformBufferBindings=p.maxUniformBufferBindings,this.maxUniformBlockSizeDwords=p.maxUniformBlockSizeDwords,this.disableSymbolUBO=p.disableSymbolUBO,this.textSizeData=A6(this.zoom,v["text-size"],this.worldview,p.availableImages),this.iconSizeData=A6(this.zoom,v["icon-size"],this.worldview,p.availableImages);const S=this.layers[0].layout,E=S.get("symbol-sort-key"),R=S.get("symbol-z-order");this.lut=p.lut,this.canOverlap=S.get("text-allow-overlap")||S.get("icon-allow-overlap")||S.get("text-ignore-placement")||S.get("icon-ignore-placement"),this.sortFeaturesByKey=R!=="viewport-y"&&E.constantOr(1)!==void 0,this.sortFeaturesByY=(R==="viewport-y"||R==="auto"&&!this.sortFeaturesByKey)&&this.canOverlap,this.writingModes=S.get("text-writing-mode").map(F=>pv[F]),this.stateDependentLayerIds=this.layers.filter(F=>F.isStateDependent()).map(F=>F.id),this.sourceID=p.sourceID,this.projection=p.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(p){const v=this.layers[0].getAppearances();if(!v||v.length===0)return!1;const S=Array.isArray(p)?p:[p];return v.some(E=>S.some(R=>E.hasLayoutProperty(R)))}getAppearanceFeatureData(p){return this.featureAppearanceData.get(p)}createArrays(){this.text=new aEe(new et(this.layers,{zoom:this.zoom,lut:this.lut},p=>p.startsWith("text")||p.startsWith("symbol"))),this.icon=new aEe(new et(this.layers,{zoom:this.zoom,lut:this.lut},p=>p.startsWith("icon")||p.startsWith("symbol"))),this.disableSymbolUBO||(this.text.uboBinder=new $Te(this.layers[0],this.zoom,this.lut,!0,"",this.maxUniformBufferBindings,this.maxUniformBlockSizeDwords),this.icon.uboBinder=new $Te(this.layers[0],this.zoom,this.lut,!1,"",this.maxUniformBufferBindings,this.maxUniformBlockSizeDwords)),this.glyphOffsetArray=new GJ,this.lineVertexArray=new y6,this.symbolInstances=new HJ}calculateGlyphDependencies(p,v,S,E,R){for(const F of p){const q=F.codePointAt(0);if(q===void 0)break;if(v[q]=!0,E&&R&&q<=65535){const K=Hq[F];K&&(v[K.charCodeAt(0)]=!0)}}}calculateEffectiveAppearanceIconSize(p,v,S,E,R,F,q){if(!p.hasLayoutProperty("icon-size"))return q*F;let K=1;const J=p.getUnevaluatedLayoutProperty("icon-size"),le=A6(this.zoom,J,this.worldview,R),fe=FO(le,v);if(le.kind!=="constant"&&le.kind!=="camera"||(K=fe.uSize),le.kind==="composite"){const{minZoom:ye,maxZoom:Te}=le,Pe=J.possiblyEvaluate(new xi(ye,{worldview:this.worldview}),E),Ue=J.possiblyEvaluate(new xi(Te,{worldview:this.worldview}),E),Qe=Pe.evaluate(S,{},E,R);K=Qe+(Ue.evaluate(S,{},E,R)-Qe)*fe.uSizeT}return le.kind==="source"&&(K=J.possiblyEvaluate(new xi(this.zoom,{worldview:this.worldview}),E).evaluate(S,{},E,R)),K*F}updateFootprints(p,v){}updateReplacement(p,v){if(v.updateTime===this.replacementUpdateTime)return!1;this.replacementUpdateTime=v.updateTime;const S=v.getReplacementRegionsForTile(p.toUnwrapped(),!0);return!dee(this.activeReplacements,S)&&(this.activeReplacements=S,!0)}getResolvedImageFromTokens(p){return typeof p=="string"?Mu.build(p):p}populate(p,v,S,E){const R=this.layers[0],F=R.layout,q=this.projection.name==="globe",K=F.get("text-font"),J=F.get("text-field"),le=F.get("icon-image"),[fe,ye]=F.get("icon-size-scale-range"),Te=it(v.scaleFactor||1,fe,ye),[Pe,Ue]=F.get("text-size-scale-range"),Qe=it(v.scaleFactor||1,Pe,Ue),at=(J.value.kind!=="constant"||J.value.value instanceof ed&&!J.value.value.isEmpty()||J.value.value.toString().length>0)&&(K.value.kind!=="constant"||K.value.value.length>0),pt=le.value.kind!=="constant"||!!le.value.value||Object.keys(le.parameters).length>0,dt=this.hasAnyAppearanceLayoutProperty("icon-image"),wt=F.get("symbol-sort-key");if(this.features=[],this.featureAppearanceData=new Map,!at&&!pt&&!dt)return;const Tt=v.iconDependencies,Lt=v.glyphDependencies,fs=v.availableImages,Jt=new xi(this.zoom,{worldview:this.worldview,activeFloors:v.activeFloors}),ps=rs=>{const is=rs.id.toString();Tt.has(is)?Tt.get(is).push(rs):Tt.set(is,[rs])};for(const rs of p){const{feature:is,id:dn,index:fn,sourceLayerIndex:_n}=rs,Sn=R._featureFilter.needGeometry,wn=Pi(is,Sn);if(!R._featureFilter.filter(Jt,wn,S))continue;if(Sn||(wn.geometry=Ea(is,S,E)),q&&is.type!==1&&S.z<=5){const yr=wn.geometry,gr=.98078528056,ir=(Dr,Zr)=>Re(kq(Dr.x,Dr.y,S,1),kq(Zr.x,Zr.y,S,1)){if(!yr.getLayoutProperty("icon-image"))return;const gr=this.getCombinedIconPrimary(yr,Nn,wn,S,fs,ar,Te);gr&&ps(gr)}),Un){const yr=K.evaluate(wn,{},S).join(","),gr=F.get("text-rotation-alignment")==="map"&&F.get("symbol-placement")!=="point";this.allowVerticalPlacement=this.writingModes&&this.writingModes.indexOf(pv.vertical)>=0;for(const ir of Un.sections)if(ir.image){const Dr=ir.image.getPrimary().scaleSelf(this.pixelRatio*Qe),Zr=Dr.id.toString(),Aa=Tt.get(Zr)||[];Aa.push(Dr),Tt.set(Zr,Aa)}else{const Dr=Wp(Un.toString()),Zr=ir.fontStack||yr,Aa=Lt[Zr]=Lt[Zr]||{};this.calculateGlyphDependencies(ir.text,Aa,gr,this.allowVerticalPlacement,Dr)}}}if(F.get("symbol-placement")==="line"&&(this.features=function(rs){const is={},dn={},fn=[];let _n=0;function Sn(Nn){fn.push(rs[Nn]),_n++}function wn(Nn,Tn,Vn){const ar=dn[Nn];return delete dn[Nn],dn[Tn]=ar,fn[ar].geometry[0].pop(),fn[ar].geometry[0]=fn[ar].geometry[0].concat(Vn[0]),ar}function Un(Nn,Tn,Vn){const ar=is[Tn];return delete is[Tn],is[Nn]=ar,fn[ar].geometry[0].shift(),fn[ar].geometry[0]=Vn[0].concat(fn[ar].geometry[0]),ar}function ln(Nn,Tn,Vn){const ar=Vn?Tn[0][Tn[0].length-1]:Tn[0][0];return`${Nn}:${ar.x}:${ar.y}`}for(let Nn=0;NnNn.geometry)}(this.features)),F.get("symbol-elevation-reference")==="hd-road-markup"){if(this.elevationType="road",v.elevationFeatures){!this.elevationFeatures&&v.elevationFeatures.length>0&&(this.elevationFeatures=[],this.elevationFeatureIdToIndex=new Map);for(const rs of v.elevationFeatures)this.elevationFeatureIdToIndex.set(rs.id,this.elevationFeatures.length),this.elevationFeatures.push(rs)}}else F.get("symbol-z-elevate")&&(this.elevationType="offset");this.elevationType!=="none"&&(this.zOffsetBuffersNeedUpload=!0),this.sortFeaturesByKey&&this.features.sort((rs,is)=>rs.sortKey-is.sortKey)}getCombinedIconPrimary(p,v,S,E,R,F,q){let K,J;if(p.hasLayoutProperty("icon-image")){const le=v.getAppearanceValueAndResolveTokens(p,"icon-image",S,E,R);K=this.getResolvedImageFromTokens(le)}else{const le=v.getValueAndResolveTokens("icon-image",S,E,R);K=this.getResolvedImageFromTokens(le)}if(K){const le=p.hasLayoutProperty("icon-size")?p.getUnevaluatedLayoutProperty("icon-size"):v._unevaluatedLayout._values["icon-size"];J=Zq(K,A6(this.zoom,le,this.worldview,R),le,E,this.zoom,F,this.pixelRatio,q,this.worldview,R).iconPrimary}return J}updateSymbolInstanceIconVertices(p,v,S,E,R,F){const{canonical:q,availableImages:K,globalProperties:J,layer:le,iconScaleFactor:fe,featureState:ye,layoutIconOffset:Te,layoutIconSize:Pe,layoutIconRotate:Ue}=F;if(p.placedIconSymbolIndex<0)return{vertexOffsetDelta:0,hasChanges:!1};if(v.activeAppearanceIndex===S)return{vertexOffsetDelta:p.numIconVertices,hasChanges:!1};const Qe=S>=0?le.appearances[S]:null;if(Qe){const at=this.getCombinedIconPrimary(Qe,le,E,q,K,{sortKey:void 0,text:void 0,icon:null,index:p.featureIndex,sourceLayerIndex:p.featureIndex,geometry:[],properties:v.properties,type:"Point",id:v.id},fe);if(!at)return{vertexOffsetDelta:0,hasChanges:!1};const pt=at.toString(),dt=this.iconAtlasPositions&&this.iconAtlasPositions.get(pt);if(dt){const{appearanceIconOffset:wt,appearanceIconRotate:Tt}=kXe(Qe,le,E,q,Te,Ue,Pe,fe);let Lt=Tee(dt,void 0,wt,le.layout.get("icon-anchor").evaluate(E,ye,q));const fs=dt.sdf,Jt=le.layout.get("icon-text-fit").constantOr("none");Jt!=="none"&&v.textShaping&&v.iconTextFitPadding&&v.fontScale&&(Lt=GTe(Lt,v.textShaping,Jt,v.iconTextFitPadding,wt,v.fontScale));const ps=this.calculateEffectiveAppearanceIconSize(Qe,J.zoom,E,q,K,fe,Pe),rs=0,is=1+(Math.min(T6,Math.round(ps*SS))<<1),dn=JTe(Lt,Tt,fs,Jt!=="none",fe);v.isUsingAppearanceIconVertexData||(v.isUsingAppearanceIconVertexData=!0,v.layoutBasedIconVertexData=this.icon.snapshotSymbolVertexData(R,p.numIconVertices));const fn=Math.floor(p.numIconVertices/4),_n=Math.min(dn.length,fn);let Sn=R;for(let Un=0;Un<_n;++Un){const ln=dn[Un],Nn=v.layoutBasedIconVertexData[0]||p.tileAnchorX,Tn=v.layoutBasedIconVertexData[1]||p.tileAnchorY,Vn=16*ln.pixelOffsetTL.x,ar=16*ln.pixelOffsetTL.y,zr=16*ln.pixelOffsetBR.x,yr=16*ln.pixelOffsetBR.y,gr=16*ln.minFontScaleX,ir=16*ln.minFontScaleY;this.icon.updateSymbolVertexData(Sn,Nn,Tn,Math.round(32*ln.tl.x),Math.round(32*ln.tl.y),ln.texPrimary.x,ln.texPrimary.y,rs,is,Vn,ar,gr,ir),this.icon.updateSymbolVertexData(Sn+1,Nn,Tn,Math.round(32*ln.tr.x),Math.round(32*ln.tr.y),ln.texPrimary.x+ln.texPrimary.w,ln.texPrimary.y,rs,is,zr,ar,gr,ir),this.icon.updateSymbolVertexData(Sn+2,Nn,Tn,Math.round(32*ln.bl.x),Math.round(32*ln.bl.y),ln.texPrimary.x,ln.texPrimary.y+ln.texPrimary.h,rs,is,Vn,yr,gr,ir),this.icon.updateSymbolVertexData(Sn+3,Nn,Tn,Math.round(32*ln.br.x),Math.round(32*ln.br.y),ln.texPrimary.x+ln.texPrimary.w,ln.texPrimary.y+ln.texPrimary.h,rs,is,zr,yr,gr,ir),Sn+=4}const wn=p.numIconVertices-4*_n;for(let Un=0;Un0||p.numVerticalGlyphVertices>0;if(!wt)return{vertexOffsetDelta:wt?p.numHorizontalGlyphVertices+p.numVerticalGlyphVertices:0,hasChanges:!1};if(v.activeAppearanceIndex===S)return{vertexOffsetDelta:p.numHorizontalGlyphVertices+p.numVerticalGlyphVertices,hasChanges:!1};const Tt=S>=0?K.appearances[S]:null;if(Tt&&v.textShaping){const{appearanceTextOffset:Lt,appearanceTextRotate:fs,appearanceTextSize:Jt}=SXe(Tt,K,E,q,ye,Pe,Te);v.fontScale=EXe(Jt,v.textScaleFactor);const ps=Tt.getUnevaluatedLayoutProperty("text-size");let rs=this.textSizeData,is=at,dn=pt;Tt.hasLayoutProperty("text-size")&&(rs=A6(this.zoom,ps,this.worldview,dt),is=this.textSizeData.kind==="composite"?this.textSizeData.minZoom:0,dn=this.textSizeData.kind==="composite"?this.textSizeData.maxZoom:0);const fn=v.textShaping.bottom-ye[1],_n=v.textShaping.left-ye[0],Sn=v.textShaping.right-ye[0];v.textShaping.top=Lt[1]+(v.textShaping.top-ye[1]),v.textShaping.bottom=Lt[1]+fn,v.textShaping.left=Lt[0]+_n,v.textShaping.right=Lt[0]+Sn;const wn=jXe(0,v.textShaping,Lt,K,!1,E,le,this.allowVerticalPlacement,fs),Un=Jt&&rs.kind==="composite"?ps.possiblyEvaluate(new xi(is,{}),q).evaluate(E,fe,q):Ue,ln=Jt&&rs.kind==="composite"?ps.possiblyEvaluate(new xi(dn,{}),q).evaluate(E,fe,q):Qe,Nn=nEe(Tt.name,rs,Jt,J,Un,ln),Tn=Array.isArray(Nn)?Nn[1]:Jt,Vn=0,ar=1+(Math.min(T6,Math.round(Tn*SS))<<1);v.isUsingAppearanceTextVertexData||(v.isUsingAppearanceTextVertexData=!0,v.layoutBasedTextVertexData=this.text.snapshotSymbolVertexData(R,p.numHorizontalGlyphVertices+p.numVerticalGlyphVertices));for(let zr=0;zr0){const J=new Set(Object.keys(p).map(le=>{const fe=Number(le);return!isNaN(fe)&&Number.isSafeInteger(fe)&&String(fe)===le?fe:le}));this.text.uboBinder&&this.text.uboBinder.updateFeatures(J,R[0],v,K,S,p,q),this.icon.uboBinder&&this.icon.uboBinder.updateFeatures(J,R[0],v,K,S,p,q)}}}updateRoadElevation(p){if(this.elevationType!=="road"||!this.elevationFeatures||this.elevationStateComplete)return;this.elevationStateComplete=!0,this.hasAnyZOffset=!1;let v=!1;const S=In(p),E=1/S;let R=!1,F=!1;for(let q=0;q0||ye>0,Qe=Te>0,at=this.elevationFeatures[K.elevationFeatureIndex];if(at){const pt=new sn(K.tileAnchorX,K.tileAnchorY),dt=.075+at.pointElevation(pt);K.zOffset!==dt&&(v=!0,K.zOffset=dt),dt!==0&&(this.hasAnyZOffset=!0);const wt=at.computeSlopeNormal(pt,E),Tt=Os(Bt(),te(0,0,1),wt);Fe(J,J,Tt),Fe(le,le,Tt),J[2]*=S,le[2]*=S,J[0]===1&&J[1]===0&&J[2]===0&&le[0]===0&&le[1]===1&&le[2]===0||(R=R||Ue,F=F||Qe)}if(Ue&&(Bee(this.text.orientationVertexArray,fe,J,le),Bee(this.text.orientationVertexArray,ye,J,le)),Qe){const{placedIconSymbolIndex:pt,verticalPlacedIconSymbolIndex:dt}=K;pt>=0&&Bee(this.icon.orientationVertexArray,Te,J,le),dt>=0&&Bee(this.icon.orientationVertexArray,Pe,J,le)}}R||(this.text.orientationVertexArray=void 0),F||(this.icon.orientationVertexArray=void 0),v&&(this.zOffsetBuffersNeedUpload=!0,this.zOffsetSortDirty=!0)}updateZOffset(){const p=(R,F,q)=>{S+=F,S>R.length&&R.resize(S);for(let K=-F;K<0;K++)R.emplace(K+S,q)},v=(R,F,q)=>{E+=F,E>R.length&&R.resize(E);for(let K=-F;K<0;K++)R.emplace(K+E,q)};if(!this.zOffsetBuffersNeedUpload)return;this.zOffsetBuffersNeedUpload=!1;let S=0,E=0;for(let R=0;R0;if((q>0||K>0)&&(p(this.text.zOffsetVertexArray,q,le),p(this.text.zOffsetVertexArray,K,le)),fe){const{placedIconSymbolIndex:ye,verticalPlacedIconSymbolIndex:Te}=F;ye>=0&&v(this.icon.zOffsetVertexArray,J,le),Te>=0&&v(this.icon.zOffsetVertexArray,F.numVerticalIconVertices,le)}}this.text.zOffsetVertexBuffer&&this.text.zOffsetVertexBuffer.updateData(this.text.zOffsetVertexArray),this.icon.zOffsetVertexBuffer&&this.icon.zOffsetVertexBuffer.updateData(this.icon.zOffsetVertexArray)}isEmpty(){return this.symbolInstances.length===0&&!this.hasRTLText}uploadPending(){return!this.uploaded||this.text.programConfigurations.needsUpload||this.icon.programConfigurations.needsUpload}upload(p,v,S,E,R){!this.uploaded&&this.hasDebugData()&&(this.textCollisionBox.upload(p),this.iconCollisionBox.upload(p)),this.text.upload(p,this.sortFeaturesByY,!this.uploaded,this.text.programConfigurations.needsUpload,this.zOffsetBuffersNeedUpload,this.hasAppearances),this.hasAppearances===null&&(this.hasAppearances=this.layers.some(F=>F.appearances&&F.appearances.length>0)),this.icon.upload(p,this.sortFeaturesByY,!this.uploaded,this.icon.programConfigurations.needsUpload,this.zOffsetBuffersNeedUpload,this.hasAppearances),this.uploaded=!0}updateAppearances(p,v,S,E,R,F=!1){const q={hasLayoutChanges:!1,hasUboChanges:!1};if(!p||!S||!this.featureAppearanceData)return q;const K=v||{},J=this.icon.layoutVertexArray&&this.icon.layoutVertexArray.length>0&&this.icon.layoutVertexArray.arrayBuffer,le=this.text.layoutVertexArray&&this.text.layoutVertexArray.length>0&&this.text.layoutVertexArray.arrayBuffer;if(!J&&!le)return q;const fe=this.layers[0],ye=fe.layout;this.featureAppearances&&this.featureAppearances.appearancesVersion===fe.appearancesVersion||(this.featureAppearances=new vVt(fe.appearances,fe.appearancesVersion));const Te=this.featureAppearances.update(E,F);if(Te.kind==="no-changes")return q;let Pe=1,Ue=0,Qe=!1,at=!1;if(J){const[Lt,fs]=ye.get("icon-size-scale-range");Pe=it(1,Lt,fs)}let pt=1,dt=0,wt=!1;if(le){const[Lt,fs]=ye.get("text-size-scale-range");pt=it(1,Lt,fs)}const Tt=new Map;if(R&&S)for(const Lt of S){const fs=R.getImage(Lt,fe.scope);if(fs){const Jt=new ud(Lt.toString());Tt.set(Jt.toString(),fs)}}for(let Lt=0;LtSn.isActive({globals:E,feature:is,canonical:p,featureState:rs})):-1;dn=_n>=0?_n:-1}const fn=Jt.activeAppearanceIndex!==dn;if(le){const _n=ye.get("text-size"),Sn=this.textSizeData.kind==="composite"?this.textSizeData.minZoom:0,wn=this.textSizeData.kind==="composite"?this.textSizeData.maxZoom:0,Un={canonical:p,layer:fe,featureState:rs,availableImages:S,textScaleFactor:pt,imageMap:Tt,layoutTextOffset:ye.get("text-offset").evaluate(is,rs,p).map(Nn=>Nn*wm),layoutTextSize:_n.evaluate(is,rs,p),layoutTextRotate:ye.get("text-rotate").evaluate(is,rs,p),layoutMinZoomSize:_n.evaluate(is,{zoom:Sn},p),layoutMaxZoomSize:_n.evaluate(is,{zoom:wn},p),layoutTextSizeMinZoom:Sn,layoutTextSizeMaxZoom:wn},ln=this.updateSymbolInstanceTextVertices(fs,Jt,dn,is,dt,Un);dt+=ln.vertexOffsetDelta,wt=wt||ln.hasChanges}if(J){const _n={canonical:p,layer:fe,featureState:rs,availableImages:S,globalProperties:E,iconScaleFactor:Pe,layoutIconOffset:ye.get("icon-offset").evaluate(is,rs,p),layoutIconSize:ye.get("icon-size").evaluate(is,rs,p,S),layoutIconRotate:ye.get("icon-rotate").evaluate(is,rs,p)},Sn=this.updateSymbolInstanceIconVertices(fs,Jt,dn,is,Ue,_n);Ue+=Sn.vertexOffsetDelta,Qe=Qe||Sn.hasChanges}if(fn){const _n=fs.featureIndex,Sn=E?E.brightness:null,wn=rs||{},Un=dn>=0?fe.appearances[dn]:null;this.text.uboBinder&&(this.text.uboBinder.layer=fe,at=this.text.uboBinder.updateFeaturePaintForAppearance(_n,is,wn,p,S,Sn,Un)||at),this.icon.uboBinder&&(this.icon.uboBinder.layer=fe,at=this.icon.uboBinder.updateFeaturePaintForAppearance(_n,is,wn,p,S,Sn,Un)||at)}Jt.activeAppearanceIndex=dn}return Qe&&this.icon.layoutVertexBuffer&&this.icon.layoutVertexArray.arrayBuffer!==null&&this.icon.layoutVertexArray.length===this.icon.layoutVertexBuffer.length&&this.icon.layoutVertexBuffer.updateData(this.icon.layoutVertexArray),wt&&this.text.layoutVertexBuffer&&this.text.layoutVertexArray.arrayBuffer!==null&&this.text.layoutVertexArray.length===this.text.layoutVertexBuffer.length&&this.text.layoutVertexBuffer.updateData(this.text.layoutVertexArray),{hasLayoutChanges:Qe||wt,hasUboChanges:at}}destroyDebugData(){this.textCollisionBox.destroy(),this.iconCollisionBox.destroy()}getProjection(){return this.projectionInstance||(this.projectionInstance=FXe(this.projection)),this.projectionInstance}destroy(){this.text.destroy(),this.icon.destroy(),this.hasDebugData()&&this.destroyDebugData()}addToLineVertexArray(p,v){const S=this.lineVertexArray.length;if(p.segment!==void 0)for(const{x:E,y:R}of v)this.lineVertexArray.emplaceBack(E,R);return{lineStartIndex:S,lineLength:this.lineVertexArray.length-S}}addSymbols(p,v,S,E,R,F,q,K,J,le,fe,ye,Te,Pe,Ue,Qe,at,pt){const dt=p.indexArray,wt=p.layoutVertexArray,Tt=p.globeExtVertexArray,Lt=pt,fs=p.uboBinder?p.uboBinder.getCurrentBatchIndex():void 0,Jt=p.segments.prepareSegment(4*Lt,wt,dt,this.canOverlap?F.sortKey:void 0,fs),ps=this.glyphOffsetArray.length,rs=Jt.vertexLength,is=this.allowVerticalPlacement&&q===pv.vertical?Math.PI/2:0,dn=F.text&&F.text.sections;let fn=wt.length,_n=-1;for(let Un=0;Un=0)){const Un=4*Sn;for(let ln=0;ln=0?v.rightJustifiedTextSymbolIndex:v.centerJustifiedTextSymbolIndex>=0?v.centerJustifiedTextSymbolIndex:v.leftJustifiedTextSymbolIndex>=0?v.leftJustifiedTextSymbolIndex:v.verticalPlacedTextSymbolIndex>=0?v.verticalPlacedTextSymbolIndex:E),F=WTe(this.textSizeData,p,R)/wm;return this.tilePixelRatio*F}getSymbolInstanceIconSize(p,v,S){const E=this.icon.placedSymbolArray.get(S),R=WTe(this.iconSizeData,p,E);return this.tilePixelRatio*R}_commitDebugCollisionVertexUpdate(p,v,S,E){p.emplaceBack(v,-S,-S,E),p.emplaceBack(v,S,-S,E),p.emplaceBack(v,S,S,E),p.emplaceBack(v,-S,S,E)}_updateTextDebugCollisionBoxes(p,v,S,E,R,F,q){for(let K=E;K0}hasIconData(){return this.icon.segments.get().length>0}hasDebugData(){return this.textCollisionBox&&this.iconCollisionBox}hasTextCollisionBoxData(){return this.hasDebugData()&&this.textCollisionBox.segments.get().length>0}hasIconCollisionBoxData(){return this.hasDebugData()&&this.iconCollisionBox.segments.get().length>0}hasIconTextFit(){return this.hasAnyIconTextFit}addIndicesForPlacedSymbol(p,v){const S=p.placedSymbolArray.get(v),E=S.vertexStartIndex+4*S.numGlyphs;for(let R=S.vertexStartIndex;RE[q]-E[K]||R[K]-R[q]),F}getSortedIndexesByZOffset(){if(!this.zOffsetSortDirty)return this.symbolInstanceIndexesSortedZOffset;if(!this.symbolInstanceIndexesSortedZOffset){this.symbolInstanceIndexesSortedZOffset=[];for(let p=0;pthis.symbolInstances.get(v).zOffset-this.symbolInstances.get(p).zOffset)}addToSortKeyRanges(p,v){const S=this.sortKeyRanges[this.sortKeyRanges.length-1];S&&S.sortKey===v?S.symbolInstanceEnd=p+1:this.sortKeyRanges.push({sortKey:v,symbolInstanceStart:p,symbolInstanceEnd:p+1})}sortFeatures(p){if(this.sortFeaturesByY&&this.sortedAngle!==p)if(this.text.segments.get().length>1||this.icon.segments.get().length>1)this.sortFeaturesWithinSegments();else{this.symbolInstanceIndexes=this.getSortedSymbolIndexes(p),this.sortedAngle=p,this.text.indexArray.clear(),this.icon.indexArray.clear(),this.featureSortOrder=[];for(const v of this.symbolInstanceIndexes){const S=this.symbolInstances.get(v);this.featureSortOrder.push(S.featureIndex);const{rightJustifiedTextSymbolIndex:E,centerJustifiedTextSymbolIndex:R,leftJustifiedTextSymbolIndex:F,verticalPlacedTextSymbolIndex:q,placedIconSymbolIndex:K,verticalPlacedIconSymbolIndex:J}=S;E>=0&&this.addIndicesForPlacedSymbol(this.text,E),R>=0&&R!==E&&this.addIndicesForPlacedSymbol(this.text,R),F>=0&&F!==R&&F!==E&&this.addIndicesForPlacedSymbol(this.text,F),q>=0&&this.addIndicesForPlacedSymbol(this.text,q),K>=0&&this.addIndicesForPlacedSymbol(this.icon,K),J>=0&&this.addIndicesForPlacedSymbol(this.icon,J)}this.text.indexBuffer&&this.text.indexBuffer.updateData(this.text.indexArray),this.icon.indexBuffer&&this.icon.indexBuffer.updateData(this.icon.indexArray)}}getOrCreateSortedSymbolsByBatch(p,v){const S=(this.text.uboBinder&&this.text.uboBinder.maxFeaturesPerBatch>0?this.text.uboBinder:this.icon.uboBinder&&this.icon.uboBinder.maxFeaturesPerBatch>0?this.icon.uboBinder:null).maxFeaturesPerBatch;if(this.symbolsByBatch)for(const E of this.symbolsByBatch.values())for(const R of E){const F=this.symbolInstances.get(R.index);R.rotatedY=0|Math.round(p*F.tileAnchorX+v*F.tileAnchorY)}else{this.symbolsByBatch=new Map;for(let E=0;ER.rotatedY-F.rotatedY||F.featureIndex-R.featureIndex);return this.symbolsByBatch}rebuildTextSegmentIndices(p,v){for(const S of p){const E=S.batchIndex;if(E===void 0)continue;const R=v.get(E);if(!R){S.primitiveOffset=this.text.indexArray.length,S.primitiveLength=0;continue}S.primitiveOffset=this.text.indexArray.length;const F=this.text.indexArray.length;for(const{index:q}of R){const K=this.symbolInstances.get(q),{rightJustifiedTextSymbolIndex:J,centerJustifiedTextSymbolIndex:le,leftJustifiedTextSymbolIndex:fe,verticalPlacedTextSymbolIndex:ye}=K;J>=0&&this.addIndicesForPlacedSymbol(this.text,J),le>=0&&le!==J&&this.addIndicesForPlacedSymbol(this.text,le),fe>=0&&fe!==le&&fe!==J&&this.addIndicesForPlacedSymbol(this.text,fe),ye>=0&&this.addIndicesForPlacedSymbol(this.text,ye)}S.primitiveLength=this.text.indexArray.length-F}}rebuildIconSegmentIndices(p,v){for(const S of p){const E=S.batchIndex;if(E===void 0)continue;const R=v.get(E);if(!R){S.primitiveOffset=this.icon.indexArray.length,S.primitiveLength=0;continue}S.primitiveOffset=this.icon.indexArray.length;const F=this.icon.indexArray.length;for(const{index:q}of R){const K=this.symbolInstances.get(q),{placedIconSymbolIndex:J,verticalPlacedIconSymbolIndex:le}=K;J>=0&&this.addIndicesForPlacedSymbol(this.icon,J),le>=0&&this.addIndicesForPlacedSymbol(this.icon,le)}S.primitiveLength=this.icon.indexArray.length-F}}sortFeaturesWithinSegments(){this.featureSortOrder=[];const p=Math.sin(this.sortedAngle),v=Math.cos(this.sortedAngle),S=this.getOrCreateSortedSymbolsByBatch(p,v),E=Array.from(S.keys()).sort((R,F)=>R-F);for(const R of E){const F=S.get(R);for(const{index:q}of F){const K=this.symbolInstances.get(q);this.featureSortOrder.push(K.featureIndex)}}this.text.indexArray.clear(),this.icon.indexArray.clear(),this.rebuildTextSegmentIndices(this.text.segments.get(),S),this.rebuildIconSegmentIndices(this.icon.segments.get(),S),this.text.indexBuffer&&this.text.indexBuffer.updateData(this.text.indexArray),this.icon.indexBuffer&&this.icon.indexBuffer.updateData(this.icon.indexArray)}getElevationFeatureForText(p){const v=this.symbolInstances.get(this.text.symbolInstanceIndices[p]).elevationFeatureIndex;let S;return this.elevationFeatures&&vS in j?String(j[S]):"")}let BXe,$Xe,oEe;pr(Zj,"SymbolBucket",{omit:["layers","collisionBoxArray","compareText","features"]}),Zj.addDynamicAttributes=$O;class UXe{constructor(p){this.type=p.property.overrides?p.property.overrides.runtimeType:Mc,this.defaultValue=p}evaluate(p){if(p.formattedSection){const v=this.defaultValue.property.overrides;if(v&&v.hasOverride(p.formattedSection))return v.getOverride(p.formattedSection)}return p.feature&&p.featureState?this.defaultValue.evaluate(p.feature,p.featureState):this.defaultValue.property.specification.default}eachChild(p){this.defaultValue.isConstant()||p(this.defaultValue.value._styleExpression.expression)}outputDefined(){return!1}serialize(){return null}}pr(UXe,"FormatSectionOverride",{omit:["defaultValue"]});const lEe=()=>oEe||(oEe={layout:BXe||(BXe=new dc({"symbol-placement":new er(Is.layout_symbol["symbol-placement"]),"symbol-spacing":new er(Is.layout_symbol["symbol-spacing"]),"symbol-avoid-edges":new er(Is.layout_symbol["symbol-avoid-edges"]),"symbol-sort-key":new Qn(Is.layout_symbol["symbol-sort-key"]),"symbol-z-order":new er(Is.layout_symbol["symbol-z-order"]),"symbol-z-elevate":new er(Is.layout_symbol["symbol-z-elevate"]),"symbol-elevation-reference":new er(Is.layout_symbol["symbol-elevation-reference"]),"icon-allow-overlap":new er(Is.layout_symbol["icon-allow-overlap"]),"icon-ignore-placement":new er(Is.layout_symbol["icon-ignore-placement"]),"icon-optional":new er(Is.layout_symbol["icon-optional"]),"icon-rotation-alignment":new er(Is.layout_symbol["icon-rotation-alignment"]),"icon-size":new Qn(Is.layout_symbol["icon-size"]),"icon-size-scale-range":new er(Is.layout_symbol["icon-size-scale-range"]),"icon-text-fit":new Qn(Is.layout_symbol["icon-text-fit"]),"icon-text-fit-padding":new Qn(Is.layout_symbol["icon-text-fit-padding"]),"icon-image":new Qn(Is.layout_symbol["icon-image"]),"icon-image-use-theme":new er({type:"string",default:"default","property-type":"data-constant"}),"icon-rotate":new Qn(Is.layout_symbol["icon-rotate"]),"icon-padding":new er(Is.layout_symbol["icon-padding"]),"icon-keep-upright":new er(Is.layout_symbol["icon-keep-upright"]),"icon-offset":new Qn(Is.layout_symbol["icon-offset"]),"icon-anchor":new Qn(Is.layout_symbol["icon-anchor"]),"icon-pitch-alignment":new er(Is.layout_symbol["icon-pitch-alignment"]),"text-pitch-alignment":new er(Is.layout_symbol["text-pitch-alignment"]),"text-rotation-alignment":new er(Is.layout_symbol["text-rotation-alignment"]),"text-field":new Qn(Is.layout_symbol["text-field"]),"text-font":new Qn(Is.layout_symbol["text-font"]),"text-size":new Qn(Is.layout_symbol["text-size"]),"text-size-scale-range":new er(Is.layout_symbol["text-size-scale-range"]),"text-max-width":new Qn(Is.layout_symbol["text-max-width"]),"text-line-height":new Qn(Is.layout_symbol["text-line-height"]),"text-letter-spacing":new Qn(Is.layout_symbol["text-letter-spacing"]),"text-justify":new Qn(Is.layout_symbol["text-justify"]),"text-radial-offset":new Qn(Is.layout_symbol["text-radial-offset"]),"text-variable-anchor":new er(Is.layout_symbol["text-variable-anchor"]),"text-anchor":new Qn(Is.layout_symbol["text-anchor"]),"text-max-angle":new er(Is.layout_symbol["text-max-angle"]),"text-writing-mode":new er(Is.layout_symbol["text-writing-mode"]),"text-rotate":new Qn(Is.layout_symbol["text-rotate"]),"text-padding":new er(Is.layout_symbol["text-padding"]),"text-keep-upright":new er(Is.layout_symbol["text-keep-upright"]),"text-transform":new Qn(Is.layout_symbol["text-transform"]),"text-offset":new Qn(Is.layout_symbol["text-offset"]),"text-allow-overlap":new er(Is.layout_symbol["text-allow-overlap"]),"text-ignore-placement":new er(Is.layout_symbol["text-ignore-placement"]),"text-optional":new er(Is.layout_symbol["text-optional"]),visibility:new er(Is.layout_symbol.visibility)})),paint:$Xe||($Xe=new dc({"icon-opacity":new Qn(Is.paint_symbol["icon-opacity"]),"icon-occlusion-opacity":new Qn(Is.paint_symbol["icon-occlusion-opacity"]),"icon-emissive-strength":new Qn(Is.paint_symbol["icon-emissive-strength"]),"text-emissive-strength":new Qn(Is.paint_symbol["text-emissive-strength"]),"icon-color":new Qn(Is.paint_symbol["icon-color"]),"icon-halo-color":new Qn(Is.paint_symbol["icon-halo-color"]),"icon-halo-width":new Qn(Is.paint_symbol["icon-halo-width"]),"icon-halo-blur":new Qn(Is.paint_symbol["icon-halo-blur"]),"icon-translate":new er(Is.paint_symbol["icon-translate"]),"icon-translate-anchor":new er(Is.paint_symbol["icon-translate-anchor"]),"icon-image-cross-fade":new er(Is.paint_symbol["icon-image-cross-fade"]),"text-opacity":new Qn(Is.paint_symbol["text-opacity"]),"text-occlusion-opacity":new Qn(Is.paint_symbol["text-occlusion-opacity"]),"text-color":new Qn(Is.paint_symbol["text-color"],{runtimeType:jl,getOverride:j=>j.textColor,hasOverride:j=>!!j.textColor}),"text-halo-color":new Qn(Is.paint_symbol["text-halo-color"]),"text-halo-width":new Qn(Is.paint_symbol["text-halo-width"]),"text-halo-blur":new Qn(Is.paint_symbol["text-halo-blur"]),"text-translate":new er(Is.paint_symbol["text-translate"]),"text-translate-anchor":new er(Is.paint_symbol["text-translate-anchor"]),"icon-color-saturation":new er(Is.paint_symbol["icon-color-saturation"]),"icon-color-contrast":new er(Is.paint_symbol["icon-color-contrast"]),"icon-color-brightness-min":new er(Is.paint_symbol["icon-color-brightness-min"]),"icon-color-brightness-max":new er(Is.paint_symbol["icon-color-brightness-max"]),"symbol-z-offset":new Qn(Is.paint_symbol["symbol-z-offset"]),"icon-color-use-theme":new Qn({type:"string",default:"default","property-type":"data-driven"}),"icon-halo-color-use-theme":new Qn({type:"string",default:"default","property-type":"data-driven"}),"text-color-use-theme":new Qn({type:"string",default:"default","property-type":"data-driven"}),"text-halo-color-use-theme":new Qn({type:"string",default:"default","property-type":"data-driven"})}))},oEe);class $ee extends ll{constructor(p,v,S,E){super(p,lEe(),v,S,E,p.layout?p.layout["icon-image-use-theme"]:null),this._colorAdjustmentMatrix=x([]),this.hasOcclusionOpacityProperties=p.paint!==void 0&&("icon-occlusion-opacity"in p.paint||"text-occlusion-opacity"in p.paint)}_handleSpecialPaintPropertyUpdate(p){p!=="icon-occlusion-opacity"&&p!=="text-occlusion-opacity"||(this.hasOcclusionOpacityProperties=!0)}recalculate(p,v){super.recalculate(p,v),this.appearances&&this.appearances.forEach(E=>{E.recalculate(p,v,this.iconImageUseTheme)}),this.layout.get("icon-rotation-alignment")==="auto"&&(this.layout._values["icon-rotation-alignment"]=this.layout.get("symbol-placement")!=="point"?"map":"viewport"),this.layout.get("text-rotation-alignment")==="auto"&&(this.layout._values["text-rotation-alignment"]=this.layout.get("symbol-placement")!=="point"?"map":"viewport"),this.layout.get("text-pitch-alignment")==="auto"&&(this.layout._values["text-pitch-alignment"]=this.layout.get("text-rotation-alignment")),this.layout.get("icon-pitch-alignment")==="auto"&&(this.layout._values["icon-pitch-alignment"]=this.layout.get("icon-rotation-alignment"));const S=this.layout.get("text-writing-mode");if(S){const E=[];for(const R of S)E.indexOf(R)<0&&E.push(R);this.layout._values["text-writing-mode"]=E}else this.layout._values["text-writing-mode"]=this.layout.get("symbol-placement")==="point"?["horizontal"]:["horizontal","vertical"];this._setPaintOverrides()}getColorAdjustmentMatrix(p,v,S,E){return this._saturation===p&&this._contrast===v&&this._brightnessMin===S&&this._brightnessMax===E||(this._colorAdjustmentMatrix=function(R,F,q,K){R=Ha(R),F=oa(F);const J=g(),le=R/3,fe=1-2*le,ye=[fe,le,le,0,le,fe,le,0,le,le,fe,0,0,0,0,1],Te=.5-.5*F,Pe=K-q;return b(J,[Pe,0,0,0,0,Pe,0,0,0,0,Pe,0,q,q,q,1],[F,0,0,0,0,F,0,0,0,0,F,0,Te,Te,Te,1]),b(J,J,ye),J}(p,v,S,E),this._saturation=p,this._contrast=v,this._brightnessMin=S,this._brightnessMax=E),this._colorAdjustmentMatrix}getValueAndResolveTokens(p,v,S,E){const R=this.layout.get(p).evaluate(v,{},S,E),F=this._unevaluatedLayout._values[p];return F.isDataDriven()||gm(F.value)||!R?R:zXe(v.properties,R)}getAppearanceValueAndResolveTokens(p,v,S,E,R){const F=p.getLayoutProperty(v);if(!F)return;const q=F.evaluate(S,{},E,R),K=p.getUnevaluatedLayoutProperties()._values[v];return K.isDataDriven()||gm(K.value)||!q||typeof q!="string"?q:zXe(S.properties,q)}createBucket(p){return new Zj(p)}queryRadius(){return 0}queryIntersectsFeature(){return!1}_setPaintOverrides(){for(const p of lEe().paint.overridableProperties){if(!$ee.hasPaintOverride(this.layout,p))continue;const v=this.paint.get(p),S=new UXe(v),E=new Lu(S,v.property.specification,this.scope,this.options,this.layout.get("icon-image-use-theme"));let R=null;R=v.value.kind==="constant"||v.value.kind==="source"?new Zu("source",E):new Dl("composite",E,v.value.zoomStops,v.value.interpolationType),this.paint._values[p]=new Vj(v.property,R,v.parameters)}}_handleOverridablePaintPropertyUpdate(p,v,S){return!(!this.layout||v.isDataDriven()||S.isDataDriven())&&$ee.hasPaintOverride(this.layout,p)}static hasPaintOverride(p,v){const S=p.get("text-field"),E=lEe().paint.properties[v];let R=!1;const F=q=>{for(const K of q)if(E.overrides&&E.overrides.hasOverride(K))return void(R=!0)};if(S.value.kind==="constant"&&S.value.value instanceof ed)F(S.value.value.sections);else if(S.value.kind==="source"){const q=J=>{R||(J instanceof Ir&&il(J.value)===px?F(J.value.sections):J instanceof td?F(J.sections):J.eachChild(q))},K=S.value;K._styleExpression&&q(K._styleExpression.expression)}return R}getProgramIds(){return["symbol"]}getDefaultProgramParams(p,v,S){return{config:new qe(this,{zoom:v,lut:S}),overrideFog:!1}}hasElevation(){return this.layout&&this.layout.get("symbol-elevation-reference")==="hd-road-markup"}}let qXe,VXe,HXe,GXe;var Uee=Pn([{name:"a_pos",type:"Int16",components:2},{name:"a_texture_pos",type:"Uint16",components:2}]);function qee(j,p,v,S,E,R,F,q){const K=[j,p,1,v,S,1,E,R,1],J=[F,q,1],le=m([],K),[fe,ye,Te]=Ce(J,J,le);return f(K,K,[fe,0,0,0,ye,0,0,0,Te])}function WXe(j,p,v,S,E,R,F,q){const K=function(J,le,fe,ye,Te,Pe,Ue,Qe){const at=qee(0,0,1,0,1,1,0,1),pt=qee(J,le,fe,ye,Te,Pe,Ue,Qe);return f(pt,pt,m([],at))}(j,p,v,S,E,R,F,q);return[K[2]/K[8]/sr,K[5]/K[8]/sr]}function Vee(j){return[j[0],Math.min(Math.max(j[1],-85.051129),vn)]}class KXe extends Hh{constructor(p,v,S,E){super(),this.id=p,this.dispatcher=S,this.coordinates=v.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(E),this.options=v,this._dirty=!1}load(p,v){if(this._loaded=v||!1,this.fire(new Nc("dataloading",{dataType:"source"})),this.url=this.options.url,!this.url)return p&&(this.coordinates=p),this._loaded=!0,void this._finishLoading();this._imageRequest=mm(this.map._requestManager.transformRequest(this.url,n0.Image),(S,E)=>{this._imageRequest=null,this._loaded=!0,S?this.fire(new Qm(S)):E&&(this.image=E,this._dirty=!0,this.width=this.image.width,this.height=this.image.height,p&&(this.coordinates=p),this._finishLoading())})}loaded(){return this._loaded}updateImage(p){return p.url?(this._imageRequest&&p.url!==this.options.url&&(this._imageRequest.cancel(),this._imageRequest=null),this.options.url=p.url,this.load(p.coordinates,this._loaded),this):this}setTexture(p){if(!(p.handle instanceof WebGLTexture))throw new Error("The provided handle is not a WebGLTexture instance");return this.texture=new Uq(this.map.painter.context,p.handle),this.width=p.dimensions[0],this.height=p.dimensions[1],this._dirty=!1,this._loaded=!0,this._finishLoading(),this}_finishLoading(){this.map&&(this.setCoordinates(this.coordinates),this.fire(new Nc("data",{dataType:"source",sourceDataType:"metadata"})))}onAdd(p){this.map=p,this.load()}onRemove(p){this._imageRequest&&(this._imageRequest.cancel(),this._imageRequest=null),!this.texture||this.texture instanceof Uq||this.texture.destroy(),this.boundsBuffer&&(this.boundsBuffer.destroy(),this.elevatedGlobeVertexBuffer&&this.elevatedGlobeVertexBuffer.destroy(),this.elevatedGlobeIndexBuffer&&this.elevatedGlobeIndexBuffer.destroy())}setCoordinates(p){if(this.coordinates=p,this._boundsArray=void 0,this._unsupportedCoords=!1,!p.length)return this;this.onNorthPole=!1,this.onSouthPole=!1;let v=p[0][1],S=p[0][1];for(const R of p)R[1]>S&&(S=R[1]),R[1]vn?this.onNorthPole=!0:E<-85.051129&&(this.onSouthPole=!0),!this.onNorthPole&&!this.onSouthPole){const R=p.map(Yr.fromLngLat);this.tileID=function(F){let q=1/0,K=1/0,J=-1/0,le=-1/0;for(const Ue of F)q=Math.min(q,Ue.x),K=Math.min(K,Ue.y),J=Math.max(J,Ue.x),le=Math.max(le,Ue.y);const fe=Math.max(J-q,le-K),ye=Math.max(0,Math.floor(-Math.log2(fe))),Te=Math.pow(2,ye);let Pe=Math.floor((q+J)/2*Te);return Pe>1&&(Pe-=1),new j6(ye,Pe,Math.floor((K+le)/2*Te))}(R),this.minzoom=this.maxzoom=this.tileID.z}return this.fire(new Nc("data",{dataType:"source",sourceDataType:"content"})),this}_clear(){!this.texture||this.texture instanceof Uq||(this.texture.destroy(),this._dirty=!0),this.texture=null,this._boundsArray=void 0,this._unsupportedCoords=!1}_prepareData(p){for(const Qe in this.tiles){const at=this.tiles[Qe];at.state!=="loaded"&&(at.state="loaded",at.texture=this.texture)}if(this._boundsArray||this.onNorthPole||this.onSouthPole||this._unsupportedCoords)return;const v=E6(new j6(0,0,0),this.map.transform.projection),S=[v.projection.project(this.coordinates[0][0],this.coordinates[0][1]),v.projection.project(this.coordinates[1][0],this.coordinates[1][1]),v.projection.project(this.coordinates[2][0],this.coordinates[2][1]),v.projection.project(this.coordinates[3][0],this.coordinates[3][1])];if(!function(Qe){const at=Qe[1].x-Qe[0].x,pt=Qe[1].y-Qe[0].y,dt=Qe[2].x-Qe[1].x,wt=Qe[2].y-Qe[1].y,Tt=Qe[3].x-Qe[2].x,Lt=Qe[3].y-Qe[2].y,fs=Qe[0].x-Qe[3].x,Jt=Qe[0].y-Qe[3].y,ps=at*wt-dt*pt,rs=dt*Lt-Tt*wt,is=Tt*Jt-fs*Lt,dn=fs*pt-at*Jt;return ps>0&&rs>0&&is>0&&dn>0||ps<0&&rs<0&&is<0&&dn<0}(S))return console.warn("Image source coordinates are defining non-convex area in the Mercator projection"),void(this._unsupportedCoords=!0);const E=E6(this.tileID,this.map.transform.projection),[R,F,q,K]=this.coordinates.map(Qe=>{const at=E.projection.project(Qe[0],Qe[1]);return PXe(E,at)._round()});this.perspectiveTransform=WXe(R.x,R.y,F.x,F.y,q.x,q.y,K.x,K.y);const J=this._boundsArray=new Yi;J.emplaceBack(R.x,R.y,0,0),J.emplaceBack(F.x,F.y,sr,0),J.emplaceBack(K.x,K.y,0,sr),J.emplaceBack(q.x,q.y,sr,sr),this.boundsBuffer&&(this.boundsBuffer.destroy(),this.elevatedGlobeVertexBuffer&&this.elevatedGlobeVertexBuffer.destroy(),this.elevatedGlobeIndexBuffer&&this.elevatedGlobeIndexBuffer.destroy()),this.boundsBuffer=p.createVertexBuffer(J,Uee.members),this.boundsSegments=Ul.simpleSegment(0,0,4,2);const le=[],fe=function(Qe){return[Vee(Qe[0]),Vee(Qe[1]),Vee(Qe[2]),Vee(Qe[3])]}(this.coordinates),[ye,Te,Pe,Ue]=function(Qe){let at=Qe[0][0],pt=at,dt=Qe[0][1],wt=dt;for(let Tt=1;Ttpt&&(pt=Qe[Tt][0]),Qe[Tt][1]wt&&(wt=Qe[Tt][1]);return[at,dt,pt-at,wt-dt]}(fe);{const Qe=new Yi,[at,pt,dt,wt]=function(wn){let Un=wn[0].x,ln=Un,Nn=wn[0].y,Tn=Nn;for(let Vn=1;Vnln&&(ln=wn[Vn].x),wn[Vn].yTn&&(Tn=wn[Vn].y);return[Un,Nn,ln-Un,Tn-Nn]}(S),Tt=wn=>[(wn.x-at)/dt,(wn.y-pt)/wt],[Lt,fs,Jt,ps]=S.map(Tt),rs=function(wn,Un,ln,Nn,Tn,Vn,ar,zr){const yr=qee(0,0,1,0,1,1,0,1);return f(yr,yr,m([],qee(wn,Un,ln,Nn,Tn,Vn,ar,zr)))}(Lt[0],Lt[1],fs[0],fs[1],Jt[0],Jt[1],ps[0],ps[1]);this.elevatedGlobePerspectiveTransform=WXe(Lt[0],Lt[1],fs[0],fs[1],Jt[0],Jt[1],ps[0],ps[1]);const is=(wn,Un)=>{le.push(wn.lng);const ln=Math.round((wn.lng-ye)/Pe*sr),Nn=Math.round((wn.lat-Te)/Ue*sr),Tn=Tt(Un),Vn=Ce([],[Tn[0],Tn[1],1],rs),ar=Math.round(Vn[0]/Vn[2]*sr),zr=Math.round(Vn[1]/Vn[2]*sr);Qe.emplaceBack(ln,Nn,ar,zr)},dn=S[3].x-S[0].x,fn=S[3].y-S[0].y,_n=S[2].x-S[1].x,Sn=S[2].y-S[1].y;for(let wn=0;wn<65;wn++){const Un=wn/64,ln=[S[0].x+Un*dn,S[0].y+Un*fn],Nn=[S[1].x+Un*_n,S[1].y+Un*Sn],Tn=Nn[0]-ln[0],Vn=Nn[1]-ln[1];for(let ar=0;ar<65;ar++){const zr=ar/64,yr={x:ln[0]+Tn*zr,y:ln[1]+Vn*zr};is(v.projection.unproject(yr.x,yr.y),yr)}}this.elevatedGlobeVertexBuffer=p.createVertexBuffer(Qe,Uee.members)}{this.maxLongitudeTriangleSize=0;let Qe=[],at=new Zd;const pt=(dt,wt,Tt)=>{at.emplaceBack(dt,wt,Tt);const Lt=le[dt],fs=le[wt],Jt=le[Tt],ps=Math.min(Math.min(Lt,fs),Jt),rs=Math.max(Math.max(Lt,fs),Jt)-ps;rs>this.maxLongitudeTriangleSize&&(this.maxLongitudeTriangleSize=rs),Qe.push(ps+rs/2)};for(let dt=0;dt<64;dt++)for(let wt=0;wt<64;wt++){const Tt=65*dt+wt,Lt=Tt+1,fs=Tt+65,Jt=fs+1;pt(Tt,fs,Lt),pt(Lt,fs,Jt)}[Qe,at]=function(dt,wt){const Tt=Array.from({length:dt.length},(Jt,ps)=>ps);Tt.sort((Jt,ps)=>dt[Jt]-dt[ps]);const Lt=[],fs=new Zd;for(let Jt=0;Jt{F.segments.push({vertexOffset:0,primitiveOffset:fe,vertexLength:v.segments[0].vertexLength,primitiveLength:ye,sortKey:void 0,vaos:{}})},K=.51*this.maxLongitudeTriangleSize;if(Math.abs(S[0]-E)<=K){const fe=ho(S,0,S.length,E+K);return fe===S.length||q(fe,Wi(S,fe+1,S.length,E+360-K)-fe),F}E0}}let ZXe,XXe,QXe,JXe,eQe,tQe,sQe;class nQe extends ll{constructor(p,v,S,E){super(p,{layout:ZXe||(ZXe=new dc({visibility:new er(Is["layout_raster-particle"].visibility)})),paint:XXe||(XXe=new dc({"raster-particle-array-band":new er(Is["paint_raster-particle"]["raster-particle-array-band"]),"raster-particle-count":new er(Is["paint_raster-particle"]["raster-particle-count"]),"raster-particle-color":new g0(Is["paint_raster-particle"]["raster-particle-color"]),"raster-particle-max-speed":new er(Is["paint_raster-particle"]["raster-particle-max-speed"]),"raster-particle-speed-factor":new er(Is["paint_raster-particle"]["raster-particle-speed-factor"]),"raster-particle-fade-opacity-factor":new er(Is["paint_raster-particle"]["raster-particle-fade-opacity-factor"]),"raster-particle-reset-rate-factor":new er(Is["paint_raster-particle"]["raster-particle-reset-rate-factor"]),"raster-particle-elevation":new er(Is["paint_raster-particle"]["raster-particle-elevation"]),"raster-particle-color-use-theme":new Qn({type:"string",default:"default","property-type":"data-driven"})}))},v,S,E),this._updateColorRamp(),this.lastInvalidatedAt=Gd.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(p){this.colorRampTexture&&this.colorRampTexture.destroy(),this.tileFramebuffer&&this.tileFramebuffer.destroy(),this.particleFramebuffer&&this.particleFramebuffer.destroy()}hasColorMap(){return!!this._transitionablePaint._values["raster-particle-color"].value.value}getProgramIds(){return["rasterParticle"]}hasOffscreenPass(){return this.visibility!=="none"}isDraped(p){return!1}_handleSpecialPaintPropertyUpdate(p){p!=="raster-particle-color"&&p!=="raster-particle-max-speed"||(this._updateColorRamp(),this._invalidateAnimationState()),p==="raster-particle-count"&&this._invalidateAnimationState()}_updateColorRamp(){if(!this.hasColorMap())return;const p=this._transitionablePaint._values["raster-particle-color"].value.expression,v=this._transitionablePaint._values["raster-particle-max-speed"].value.expression.evaluate({zoom:0});this.colorRamp=Cq({expression:p,evaluationKey:"rasterParticleSpeed",image:this.colorRamp,clips:[{start:0,end:v}],resolution:256}),this.colorRampTexture=null}_invalidateAnimationState(){this.lastInvalidatedAt=Gd.now()}tileCoverLift(){return this.paint.get("raster-particle-elevation")}}class NVt extends ll{constructor(p,v){super(p,{},v,null),this.implementation=p,p.slot&&(this.slot=p.slot)}is3D(p){return this.implementation.renderingMode==="3d"}hasOffscreenPass(){return this.implementation.prerender!==void 0}isDraped(p){return this.implementation.renderToTile!==void 0}shouldRedrape(){return!!this.implementation.shouldRerenderTiles&&this.implementation.shouldRerenderTiles()}recalculate(){}updateTransitions(){}hasTransition(){return!1}serialize(){}onAdd(p){this.implementation.onAdd&&this.implementation.onAdd(p,p.painter.context.gl)}onRemove(p){this.implementation.onRemove&&this.implementation.onRemove(p,p.painter.context.gl)}}function dEe(j,p,v){const S=[0,0,1],E=Ct([]);return Kt(E,E,v?-Nr(j)+Math.PI:Nr(j)),Yt(E,E,-Nr(p)),Fe(S,S,E),Me(S,S)}class Hee{constructor(p,v,S,E){this.message=(p?`${p}: `:"")+S,E&&(this.identifier=E),v!=null&&v.__line__&&(this.line=v.__line__)}}function uEe(j,p){const v=j.indexOf("://")===-1;try{return new URL(j,v&&p?"http://example.com":void 0),!0}catch{return!1}}class rQe{constructor(p,v){this.feature=p,this.instancedDataOffset=v,this.instancedDataCount=0,this.rotation=[0,0,0],this.scale=[1,1,1],this.translation=[0,0,0]}}class aQe{constructor(){this.maxScale=1,this.maxXYTranslationDistance=0,this.instancedDataArray=new yq,this.instancesEvaluatedElevation=[],this.features=[],this.idToFeaturesIndex={}}colorForInstance(p){const v=16*p,S=this.instancedDataArray.float32;let E=Math.floor(S[v+2]);const R=1.05*(S[v+2]-E);return E/=100,[S[v]%1*1.05,S[v+1]%1*1.05,R,E]}tileCoordinatesForInstance(p){const v=16*p,S=this.instancedDataArray.float32;let E=S[v+0];return E=E>sr?E-sr:E,new sn(Math.trunc(E),Math.trunc(S[v+1]))}translationForInstance(p){const v=16*p,S=this.instancedDataArray.float32;return[S[v+4],S[v+5],S[v+6]]}rotationScaleForInstance(p){const v=16*p,S=this.instancedDataArray.float32;return[S[v+7],S[v+8],S[v+9],S[v+10],S[v+11],S[v+12],S[v+13],S[v+14],S[v+15]]}transformForInstance(p){const v=16*p,S=this.instancedDataArray.float32;return[S[v+7],S[v+8],S[v+9],S[v+4],S[v+10],S[v+11],S[v+12],S[v+5],S[v+13],S[v+14],S[v+15],S[v+6],0,0,0,1]}}class hEe{constructor(p){this.zoom=p.zoom,this.canonical=p.canonical,this.overscaledZ=this.canonical.z+Math.log2(p.overscaling),this.layers=p.layers,this.layerIds=this.layers.map(v=>v.fqid),this.projection=p.projection,this.index=p.index,this.worldview=p.worldview,this.hasZoomDependentProperties=this.layers[0].isZoomDependent(),this.stateDependentLayerIds=this.layers.filter(v=>v.isStateDependent()).map(v=>v.id),this.hasPattern=!1,this.instancesPerModel={},this.validForExaggeration=0,this.maxVerticalOffset=0,this.maxScale=0,this.maxHeight=0,this.lookupDim=this.zoom>this.canonical.z+1?0:this.zoom>this.canonical.z?256:this.zoom>15?75:100,this.instanceCount=0,this.terrainElevationMin=0,this.terrainElevationMax=0,this.validForDEMTile={id:null,timestamp:0},this.modelUris=[],this.modelsRequested=!1,this.activeReplacements=[],this.replacementUpdateTime=0,this.styleDefinedModelURLs=p.styleDefinedModelURLs,this.hasAppearances=null}updateFootprints(p,v){}updateAppearances(p,v,S,E){return{hasLayoutChanges:!1,hasUboChanges:!1}}populate(p,v,S,E){this.tileToMeter=In(S);const R=this.layers[0]._featureFilter.needGeometry;this.lookup=new Uint8Array(this.lookupDim*this.lookupDim);const F=this.layers[0].paint.get("model-elevation-reference")==="hd-road-markup"?v.elevationFeatures:void 0;for(const{feature:q,id:K,index:J,sourceLayerIndex:le}of p){const fe=K??(q.properties&&q.properties.hasOwnProperty("id")?q.properties.id:void 0),ye=Pi(q,R);if(!this.layers[0]._featureFilter.filter(new xi(this.zoom,{worldview:this.worldview,activeFloors:v.activeFloors}),ye,S))continue;const Te={id:fe,sourceLayerIndex:le,index:J,geometry:R?ye.geometry:Ea(q,S,E),properties:q.properties,type:q.type,patterns:{}},Pe=this.addFeature(Te,Te.geometry,ye,F,S);Pe&&v.featureIndex.insert(q,Te.geometry,J,le,this.index,this.instancesPerModel[Pe].instancedDataArray.length,256)}this.lookup=null}evaluateQueryRenderedFeaturePadding(){const p=this.layers[0].modelManager,v=this.layers[0].scope;let S=0;for(const E of this.modelUris){const R=p.getModel(E,v);if(!R)continue;const F=this.instancesPerModel[E];if(F){const q=.5*ge(R.aabb.max,R.aabb.min)*F.maxScale+F.maxXYTranslationDistance,K=Math.min(sr,Math.max(q/this.tileToMeter,256));S=Math.max(K,S)}}return S}update(p,v,S,E){for(const R in this.instancesPerModel){const F=this.instancesPerModel[R];for(const q in p)F.idToFeaturesIndex.hasOwnProperty(q)&&(this.evaluate(F.features[F.idToFeaturesIndex[q]],p[q],F,!0),this.uploaded=!1)}this.maxHeight=0}updateZoomBasedPaintProperties(){if(!this.hasZoomDependentProperties)return!1;let p=!1;for(const v in this.instancesPerModel){const S=this.instancesPerModel[v];for(const E of S.features){const R=this.layers[0],F=E.feature,q=this.canonical,K=R.paint.get("model-rotation").evaluate(F,{},q),J=R.paint.get("model-scale").evaluate(F,{},q),le=R.paint.get("model-translation").evaluate(F,{},q);Xe(E.rotation,K)&&Xe(E.scale,J)&&Xe(E.translation,le)||(this.evaluate(E,E.featureStates,S,!0),p=!0)}}return p}updateReplacement(p,v,S,E){if(v.updateTime===this.replacementUpdateTime)return!1;this.replacementUpdateTime=v.updateTime;const R=v.getReplacementRegionsForTile(p.toUnwrapped(),!0);if(dee(this.activeReplacements,R))return!1;this.activeReplacements=R;let F=!1;for(const q in this.instancesPerModel){const K=this.instancesPerModel[q],J=K.instancedDataArray;for(const le of K.features){const fe=le.instancedDataOffset,ye=le.instancedDataCount;for(let Te=0;Tesr;Ue=Qe?Ue-sr:Ue;const at=Math.floor(Ue),pt=Math.floor(J.float32[Pe+1]);let dt=!1;for(const wt of this.activeReplacements)if(!BYe(wt,S,uee.Model,E)&&!(wt.min.x>at||at>wt.max.x||wt.min.y>pt||pt>wt.max.y)&&(dt=HYe(VYe(at,pt,p.canonical,wt.footprintTileId.canonical),wt.footprint),dt))break;J.float32[Pe]=dt?Ue+sr:Ue,F=F||dt!==Qe}}}return F}isEmpty(){for(const p in this.instancesPerModel)if(this.instancesPerModel[p].instancedDataArray.length!==0)return!1;return!0}uploadPending(){return!this.uploaded}upload(p){if(!this.uploaded)for(const v in this.instancesPerModel){const S=this.instancesPerModel[v];S.instancedDataArray.length<0||S.instancedDataArray.length===0||(S.instancedDataBuffer?S.instancedDataBuffer.updateData(S.instancedDataArray):S.instancedDataBuffer=p.createVertexBuffer(S.instancedDataArray,qUt.members,!0,void 0,this.instanceCount))}this.uploaded=!0}destroy(p){for(const S in this.instancesPerModel){const E=this.instancesPerModel[S];E.instancedDataArray.length!==0&&E.instancedDataBuffer&&E.instancedDataBuffer.destroy()}const v=this.layers[0].modelManager;if(p&&v&&this.modelUris&&this.modelsRequested)for(const S of this.modelUris)v.removeModel(S,"",!0)}addFeature(p,v,S,E,R){const F=this.layers[0],q=F.layout.get("model-id"),K=F.layout.get("model-allow-density-reduction"),J=q.evaluate(S,{},this.canonical);if(!J)return Er(`modelId is not evaluated for layer ${F.id} and it is not going to get rendered.`),J;(uEe(J,!1)||this.styleDefinedModelURLs[J]!==void 0)&&(this.modelUris.includes(J)||this.modelUris.push(J)),this.instancesPerModel[J]||(this.instancesPerModel[J]=new aQe);const le=this.instancesPerModel[J],fe=le.instancedDataArray,ye=new rQe(S,fe.length);let Te;E&&(Te=Ql.getElevationFeature(p,E));for(const Pe of v)for(const Ue of Pe){if(Ue.x<0||Ue.x>=sr||Ue.y<0||Ue.y>=sr)continue;if(this.lookupDim!==0&&K){const at=(this.lookupDim-1)/sr,pt=this.lookupDim*(Ue.y*at|0)+Ue.x*at|0;if(this.lookup){if(this.lookup[pt]!==0)continue;this.lookup[pt]=1}}this.instanceCount++;const Qe=fe.length;if(fe.resize(Qe+1),E){le.instancesRoadElevation||(le.instancesRoadElevation=[]);const at=Te?Te.pointElevation(new sn(Ue.x,Ue.y)):0;le.instancesRoadElevation.push(at)}le.instancesEvaluatedElevation.push(0),fe.float32[16*Qe]=Ue.x,fe.float32[16*Qe+1]=Ue.y}return ye.instancedDataCount=le.instancedDataArray.length-ye.instancedDataOffset,ye.instancedDataCount>0&&(p.id&&(le.idToFeaturesIndex[p.id]=le.features.length),le.features.push(ye),this.evaluate(ye,{},le,!1)),J}getModelUris(){return this.modelUris}evaluate(p,v,S,E){const R=this.layers[0],F=p.feature,q=this.canonical,K=p.rotation=R.paint.get("model-rotation").evaluate(F,v,q),J=p.scale=R.paint.get("model-scale").evaluate(F,v,q),le=p.translation=R.paint.get("model-translation").evaluate(F,v,q),fe=Object.assign({},R.paint.get("model-color").evaluate(F,v,q));fe.a=R.paint.get("model-color-mix-intensity").evaluate(F,v,q);const ye=[];this.maxVerticalOffset0?Math.sqrt(Te):0;S.maxScale=Math.max(Math.max(S.maxScale,J[0]),Math.max(J[1],J[2])),S.maxXYTranslationDistance=Math.max(S.maxXYTranslationDistance,Pe),this.maxScale=Math.max(Math.max(this.maxScale,J[0]),Math.max(J[1],J[2])),TZe(ye,K,J);const Ue=Math.round(100*fe.a)+fe.b/1.05;for(let Qe=0;Qe10?this.tileToMeter:In(q,Tt)),dt[pt+4]=le[0],dt[pt+5]=le[1],dt[pt+6]=le[2]+(S.instancesRoadElevation?S.instancesRoadElevation[at]:0)+wt,dt[pt+7]=ye[0],dt[pt+8]=ye[1],dt[pt+9]=ye[2],dt[pt+10]=ye[4],dt[pt+11]=ye[5],dt[pt+12]=ye[6],dt[pt+13]=ye[8],dt[pt+14]=ye[9],dt[pt+15]=ye[10],S.instancesEvaluatedElevation[at]=le[2]}}}pr(hEe,"ModelBucket",{omit:["layers"]}),pr(aQe,"PerModelAttributes"),pr(rQe,"ModelFeature");class qO{constructor(p,v,S){this._demTile=p,this._dem=this._demTile.dem,this._scale=v,this._offset=S}static create(p,v,S){const E=S||p.findDEMTileFor(v);if(!E||!E.dem)return;const R=E.dem,F=E.tileID,q=1<J.fqid),this.stateDependentLayerIds=this.layers.filter(J=>J.isStateDependent()).map(J=>J.id),this.modelTraits|=DO.CoordinateSpaceTile,this.uploaded=!1,this.hasPattern=!1,E&&(this.modelTraits|=DO.HasMapboxMeshFeatures),R&&(this.modelTraits|=DO.HasMeshoptCompression),this.zoom=-1,this.terrainExaggeration=1,this.projection={name:"mercator"},this.replacementUpdateTime=0,this.elevationReadFromZ=255,this.brightness=F,this.worldview=K,this.dirty=!0,this.needsUpload=!1,this.filter=null,this.nodesInfo=[];for(const J of v)this.nodesInfo.push(new cQe(J)),oQe(J,q.featureIndexArray.length,q.grid),q.featureIndexArray.emplaceBack(this.nodesInfo.length-1,0,q.bucketLayerIDs.length-1,0);this.states={},this.hasAppearances=null}updateFootprints(p,v){for(const S of this.getNodesInfo()){const E=S.node;E.footprint&&v.push({footprint:E.footprint,id:p})}}updateAppearances(p,v,S,E){return{hasLayoutChanges:!1,hasUboChanges:!1}}update(p){const v=Object.keys(p).length!==0;if(v&&!this.stateDependentLayers.length)return;const S=v?this.stateDependentLayers:this.layers;if(!ki(p,this.states))for(const E of S)this.evaluate(E,p);this.states=structuredClone(p)}populate(){console.log("populate 3D model bucket")}uploadPending(){return!this.uploaded||this.needsUpload}upload(p){if(!this.needsUpload)return;const v=this.getNodesInfo();for(const S of v){const E=S.node;this.uploaded?this.updatePbrBuffer(E):ETe(E,p,!0)}for(const S of v)Nee(S.node);this.uploaded=!0,this.needsUpload=!1}updatePbrBuffer(p){let v=!1;if(!p.meshes)return v;for(const S of p.meshes)S.pbrBuffer&&(S.pbrBuffer.updateData(S.featureArray),v=!0);return v}needsReEvaluation(p,v,S){const E=p.transform.projectionOptions,R=p.style.getBrightness(),F=this.brightness!==R;if(!this.uploaded||this.dirty||E.name!==this.projection.name||rV(S.paint.get("model-color").value,F)||rV(S.paint.get("model-color-mix-intensity").value,F)||rV(S.paint.get("model-roughness").value,F)||rV(S.paint.get("model-emissive-strength").value,F)||rV(S.paint.get("model-height-based-emissive-strength-multiplier").value,F)){this.projection=E,this.brightness=R;const q=this.getNodesInfo();for(const K of q)K.state=null;return!0}return!1}evaluateTransform(p,v){if(p.transform.zoom===this.zoom)return;this.zoom=p.transform.zoom;const S=this.getNodesInfo(),E=this.id.canonical;for(const R of S){const F=R.feature;R.evaluatedTranslation=v.paint.get("model-translation").evaluate(F,{},E),R.evaluatedScale=v.paint.get("model-scale").evaluate(F,{},E)}}evaluate(p,v){const S=this.getNodesInfo();for(const E of S){if(!E.node.meshes)continue;const R=E.feature,F=v&&v[R.id];if(ki(F,E.state))continue;E.state=structuredClone(F);const q=E.node.meshes&&E.node.meshes[0].featureData,K=E.evaluatedColor[2],J=E.evaluatedRMEA[2],le=this.id.canonical;if(E.hasTranslucentParts=!1,q){for(let fe=0;fe=Lt)continue;const Un=mEe[wn],ln=Math.abs(Un);ln>is&&(rs=Un,is=ln,dn=Sn,fn=_n)}if(is>.1){const _n=1-(Lt+.5*Math.abs(dn*fn))/Pe;let Sn=v._dem.get(Jt,fs)+rs*_n;const wn=v._dem.get(Jt+dn,fs+fn),Un=v._dem.get(Jt-dn,fs-fn,!0);(Sn-wn)*(Sn-Un)>0&&(Sn=(wn+Un)/2),mEe[ps]=v._dem.set(Jt,fs,Sn),M6[ps]=Lt}}}}}q&&(v._demTile.needsDEMTextureUpload=!0,v._dem._timestamp=Gd.now())}setFilter(p){this.filter=p?Q3(p):null}getNodesInfo(){return this.filter?this.nodesInfo.filter(p=>this.filter.filter(new xi(this.id.overscaledZ,{worldview:this.worldview}),p.feature,this.id.canonical)):this.nodesInfo}destroy(){const p=this.getNodesInfo();for(const v of p)Nee(v.node),MTe(v.node)}isEmpty(){return!this.nodesInfo.length}updateReplacement(p,v){if(v.updateTime===this.replacementUpdateTime)return;this.replacementUpdateTime=v.updateTime;const S=v.getReplacementRegionsForTile(p.toUnwrapped());for(const E of this.getNodesInfo()){const R=E.node.footprint;E.hiddenByReplacement=!!R&&!S.find(F=>F.footprint===R)}}getHeightAtTileCoord(p,v){const S=[],E=[0,0,0],R=x([]);for(const F of this.getNodesInfo()){const q=F.node.meshes[0],K=q.transformedAabb;if(pK.max[0]||v>K.max[1])continue;if(F.node.hidden===!0)return{height:1/0,maxHeight:F.feature.properties.height,hidden:!1,verticalScale:F.evaluatedScale[2]};_(R,F.node.globalMatrix),E[0]=p,E[1]=v,Ge(E,E,R);const J=(E[0]-q.aabb.min[0])/(q.aabb.max[0]-q.aabb.min[0])*S6|0,le=Math.min(63,(E[1]-q.aabb.min[1])/(q.aabb.max[1]-q.aabb.min[1])*S6|0)*S6+Math.min(63,J),fe=q.heightmap[le];if(!(fe<0&&F.node.footprint))return F.hiddenByReplacement?void 0:{height:fe,maxHeight:F.feature.properties.height,hidden:!1,verticalScale:F.evaluatedScale[2]};if(F.node.footprint.grid.query(new sn(p,v),new sn(p,v),S),S.length>0)return{height:void 0,maxHeight:F.feature.properties.height,hidden:F.hiddenByReplacement,verticalScale:F.evaluatedScale[2]}}}}function rV(j,p){return j instanceof Zu&&!j.isLightConstant&&p}function kVt(j,p,v,S,E,R,F,q){let K=(61440&p|(61440&p)>>4)>>8,J=(3840&p|(3840&p)>>4)>>4,le=240&p|(240&p)>>4;v[3]>0&&(K=mr(K,255*v[0],v[3]),J=mr(J,255*v[1],v[3]),le=mr(le,255*v[2],v[3]));const fe=K<<8|J,ye=le<<8|Math.floor(255*S[3]),Te=function(Lt){const fs=it(Lt,0,2);return Math.min(Math.round(.5*fs*255),255)}(S[2])<<8|15*S[0]<<4|15*S[1],Pe=it(E[0],0,1),Ue=it(E[1],0,1),Qe=it(E[2],0,1),at=it(E[3],0,1);let pt,dt,wt,Tt;if(Pe!==Ue&&F!==R&&Ue!==Pe){const Lt=F-R;dt=1/(Lt*(Ue-Pe)),wt=-(R+Lt*Pe)/(Lt*(Ue-Pe));const fs=it(E[4],-1,1);Tt=Math.pow(10,fs),pt=255*Qe<<8|255*at}else pt=65535,dt=0,wt=1,Tt=1;if(j.emplaceBack(fe,ye,Te,pt,dt,wt,Tt),q){const Lt=q.length;q.clear();for(let fs=0;fs>16&65535,le=R?K>>16&65535:65535&K,fe=(15&le)<8?15&le:0,ye=j.evaluatedRMEA[fe],Te=j.evaluatedColor[fe],Pe=j.emissionHeightBasedParams[fe];let Ue;if(q&&fe===2&&S.lights&&(Ue=new jO,Ue.resize(10*S.lights.length)),kVt(F.featureArray,J,Te,ye,Pe,F.aabb.min[2],F.aabb.max[2],Ue),Ue&&q){q=!1;const Qe=S.meshes[S.lightMeshIndex];Qe.featureArray=Ue,Qe.featureArray._trim()}}F.featureArray._trim(),E++}}pr(Gee,"Tiled3dModelBucket",{omit:["layers"]}),pr(cQe,"Tiled3dModelFeature");const CVt=["id","tile","layer","source","sourceLayer","state"];class L6{constructor(p,v,S,E,R){this.type="Feature",this._vectorTileFeature=p,this._z=v,this._x=S,this._y=E,this.properties=p?p.properties:{},this.id=R}clone(){const p=new L6(this._vectorTileFeature,this._z,this._x,this._y,this.id);return this.state&&(p.state=Object.assign({},this.state)),this.layer&&(p.layer=Object.assign({},this.layer)),this.source&&(p.source=this.source),this.sourceLayer&&(p.sourceLayer=this.sourceLayer),p}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(p){this._geometry=p}toJSON(){const p={type:"Feature",state:void 0,geometry:this.geometry,properties:this.properties};for(const v of CVt)this[v]!==void 0&&(p[v]=this[v]);return p}}class P6 extends Hh{constructor(p,v,S,E){super(),this.id=p,this.type="model",this.models=[],this._options=v,this._modelsInfo=new Map,this._abortController=null}cancelModelRequests(){this._abortController&&(this._abortController.abort(),this._abortController=null)}loadGLTFFromURI(p,v){return kZe(this.map._requestManager.transformRequest(p,n0.Model).url,v)}async loadModel(p,v,S){try{const E=await this.loadGLTFFromURI(v.uri,S);if(S.aborted)return;const R=this._modelsInfo.get(p);if(!R)return;const F=PTe(E),q=R.modelSpec,K=new EZe(p,q.uri,q.position,q.orientation,F);P6.applyModelSpecification(K,q),K.computeBoundsAndApplyParent(),this.models.push(K),R.model=K}catch(E){if(E instanceof Error&&E.name==="AbortError")return;const R=E instanceof Error?E.message:"Unknown error";this.fire(new Qm(new Error(`Could not load model ${p} from ${v.uri}: ${R}`)))}}async load(){this._abortController||(this._abortController=new AbortController);const p=this._abortController.signal,v=[];for(const S in this._options.models){const E=this._options.models[S],R=this._modelsInfo.get(S);if(R&&R.model){R.modelSpec=E;const F=R.model;F.position=E.position!=null?new Cs(E.position[0],E.position[1]):new Cs(0,0),F.orientation=E.orientation!=null?E.orientation:[0,0,0],P6.applyModelSpecification(F,E),F.computeBoundsAndApplyParent(),this.models.push(F)}else R?R.modelSpec=E:(this._modelsInfo.set(S,{modelSpec:E,model:null}),v.push(this.loadModel(S,E,p)))}v.length!==0?(await Promise.allSettled(v),p.aborted||this.fire(new Nc("data",{dataType:"source",sourceDataType:"metadata"}))):this.loaded()&&this.fire(new Nc("data",{dataType:"source",sourceDataType:"metadata"}))}static applyModelSpecification(p,v){v.nodeOverrides&&P6.convertNodeOverrides(p,v.nodeOverrides),v.materialOverrides&&P6.convertMaterialOverrides(p,v.materialOverrides),v.nodeOverrideNames&&(p.nodeOverrideNames=[...v.nodeOverrideNames]),v.materialOverrideNames&&(p.materialOverrideNames=[...v.materialOverrideNames]),v.featureProperties&&(p.featureProperties=v.featureProperties)}static convertNodeOverrides(p,v){if(Array.isArray(v)&&v.every(S=>typeof S=="string")){p.nodeOverrideNames=[];for(const S of v)p.nodeOverrideNames.push(S)}else Object.entries(v).forEach(([S,E])=>{const R={orientation:[0,0,0]};if(E.hasOwnProperty("orientation")){const F=E.orientation;F&&(R.orientation=F)}p.nodeOverrides.set(S,R)})}static convertMaterialOverrides(p,v){if(Array.isArray(v)&&v.every(S=>typeof S=="string")){p.materialOverrideNames=[];for(const S of v)p.materialOverrideNames.push(S)}else Object.entries(v).forEach(([S,E])=>{const R={color:new cs(1,1,1),colorMix:0,emissionStrength:0,opacity:1},F=E["model-color"];F!==void 0&&(R.color.r=F[0],R.color.g=F[1],R.color.b=F[2]);const q=E["model-color-mix-intensity"];q!==void 0&&(R.colorMix=q);const K=E["model-emissive-strength"];K!==void 0&&(R.emissionStrength=K);const J=E["model-opacity"];J!==void 0&&(R.opacity=J),p.materialOverrides.set(S,R)})}onAdd(p){this.map=p,this.load()}hasTransition(){return!1}loaded(){if(this._modelsInfo.size===0)return!0;for(const p of this._modelsInfo.values())if(p.model==null)return!1;return!0}getModels(){return this.models}loadTile(p,v){}serialize(){return this._options}setProperty(p,v){return!1}reload(){this.cancelModelRequests();const p=St(this.id,this.scope);this.map.style.clearSource(p),this.models=[],this._modelsInfo.clear(),this.load()}onRemove(p){this.cancelModelRequests()}setModels(p){this.models=[];const v=new Map;for(const S in p){const E=p[S],R=this._modelsInfo.get(S);R&&R.modelSpec.uri===E.uri&&v.set(S,R)}if(this._modelsInfo.size!==v.size){this.cancelModelRequests();for(const[S,E]of v)E.model||v.delete(S)}this._modelsInfo=v,this._options.models=p,this.load()}}function pEe(j,p,v,S){const E=1<K>=Tt.vertexArrayOffset&&Kwt.polygon).flat());const Qe=Te?q:null,[at,pt]=dZe(R,S,fe,le,J,F,Qe,ye,Pe,R.center.lat,j.tileID.canonical),dt=j.queryGeometry;return cZe(at,pt,dt.isPointQuery()?dt.screenBounds:dt.screenGeometry)}},building:class extends ll{constructor(j,p,v,S){super(j,{layout:OZe||(OZe=new dc({visibility:new er(Is.layout_building.visibility),"building-facade":new Qn(Is.layout_building["building-facade"]),"building-facade-floors":new Qn(Is.layout_building["building-facade-floors"]),"building-facade-unit-width":new Qn(Is.layout_building["building-facade-unit-width"]),"building-facade-window":new Qn(Is.layout_building["building-facade-window"]),"building-roof-shape":new Qn(Is.layout_building["building-roof-shape"]),"building-height":new Qn(Is.layout_building["building-height"]),"building-base":new Qn(Is.layout_building["building-base"]),"building-flood-light-wall-radius":new Qn(Is.layout_building["building-flood-light-wall-radius"]),"building-flood-light-ground-radius":new Qn(Is.layout_building["building-flood-light-ground-radius"]),"building-flip-roof-orientation":new Qn(Is.layout_building["building-flip-roof-orientation"])})),paint:FZe||(FZe=new dc({"building-opacity":new er(Is.paint_building["building-opacity"]),"building-ambient-occlusion-intensity":new er(Is.paint_building["building-ambient-occlusion-intensity"]),"building-ambient-occlusion-ground-intensity":new er(Is.paint_building["building-ambient-occlusion-ground-intensity"]),"building-ambient-occlusion-ground-radius":new er(Is.paint_building["building-ambient-occlusion-ground-radius"]),"building-ambient-occlusion-ground-attenuation":new er(Is.paint_building["building-ambient-occlusion-ground-attenuation"]),"building-vertical-scale":new er(Is.paint_building["building-vertical-scale"]),"building-cast-shadows":new er(Is.paint_building["building-cast-shadows"]),"building-color":new Qn(Is.paint_building["building-color"]),"building-emissive-strength":new Qn(Is.paint_building["building-emissive-strength"]),"building-facade-emissive-chance":new er(Is.paint_building["building-facade-emissive-chance"]),"building-cutoff-fade-range":new er(Is.paint_building["building-cutoff-fade-range"]),"building-front-cutoff":new er(Is.paint_building["building-front-cutoff"]),"building-flood-light-color":new er(Is.paint_building["building-flood-light-color"]),"building-flood-light-intensity":new er(Is.paint_building["building-flood-light-intensity"]),"building-flood-light-ground-attenuation":new er(Is.paint_building["building-flood-light-ground-attenuation"]),"building-color-use-theme":new Qn({type:"string",default:"default","property-type":"data-driven"}),"building-flood-light-color-use-theme":new Qn({type:"string",default:"default","property-type":"data-driven"})}))},p,v,S),this._stats={numRenderedVerticesInShadowPass:0,numRenderedVerticesInTransparentPass:0}}createBucket(j){return new RZe(j)}cutoffRange(){return this.paint.get("building-cutoff-fade-range")}hasShadowPass(){return this.paint.get("building-cast-shadows")}hasLightBeamPass(){return!0}canCastShadows(){return!0}is3D(j){return!0}queryRadius(j){return 0}queryIntersectsFeature(j,p,v,S,E,R,F,q,K,J){let le=this.layout.get("building-height").evaluate(p,v);const fe=this.layout.get("building-base").evaluate(p,v),ye=j.tile.getBucket(this).getFootprint(p);if(ye){if(ye.hiddenFlags!==0)return!1;le=ye.height}const[Te,Pe]=dZe(R,S,fe,le,new sn(0,0),F,null,[0,0],1,R.center.lat,j.tileID.canonical),Ue=j.queryGeometry;return cZe(Te,Pe,Ue.isPointQuery()?Ue.screenBounds:Ue.screenGeometry)}},line:class extends ll{constructor(j,p,v,S){const E=KZe();super(j,E,p,v,S),E.layout&&(this.layout=new bm(E.layout)),this.gradientVersion=0,this.hasElevatedBuckets=!1,this.hasNonElevatedBuckets=!1}_handleSpecialPaintPropertyUpdate(j){if(j==="line-gradient"){const p=this._transitionablePaint._values["line-gradient"].value.expression;this.stepInterpolant=p._styleExpression&&p._styleExpression.expression instanceof rw,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(j,p){super.recalculate(j,p),this.paint._values["line-floorwidth"]=(()=>{if(Vq)return Vq;const v=KZe();return Vq=new _qt(v.paint.properties["line-width"].specification),Vq.useIntegerZoom=!0,Vq})().possiblyEvaluate(this._transitioningPaint._values["line-width"].value,j)}createBucket(j){return new See(j)}getProgramIds(){const j=[this.paint.get("line-pattern").constantOr(1)?"linePattern":"line"];return this.paint.get("line-blend-mode")!=="default"&&j.push("lineBlendComposite"),j}getDefaultProgramParams(j,p,v){if(j==="lineBlendComposite")return{};const S=GZe(this);return{config:new qe(this,{zoom:p,lut:v}),defines:S,overrideFog:!1}}queryRadius(j){const p=j,v=YZe(rC("line-width",this,p),rC("line-gap-width",this,p)),S=rC("line-offset",this,p);return v/2+Math.abs(S)+ZJ(this.paint.get("line-translate"))}queryIntersectsFeature(j,p,v,S,E,R){if(j.queryGeometry.isAboveHorizon)return!1;const F=WKe(j.tilespaceGeometry,this.paint.get("line-translate"),this.paint.get("line-translate-anchor"),R.angle,j.pixelToTileUnitsFactor),q=j.pixelToTileUnitsFactor/2*YZe(this.paint.get("line-width").evaluate(p,v),this.paint.get("line-gap-width").evaluate(p,v)),K=this.paint.get("line-offset").evaluate(p,v);return K&&(S=function(J,le){const fe=[],ye=new sn(0,0);for(let Te=0;Te=3){for(let Pe=0;Pe{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 dQe{constructor(p){this._stringToNumber={},this._numberToString=[];for(let v=0;v=0&&ye[3]>=0&&J.insert(K,ye[0],ye[1],ye[2],ye[3])}}loadVTLayers(){if(!this.vtLayers){this.vtLayers=new Bo(new Cee(this.rawTileData)).layers,this.sourceLayerCoder=new dQe(this.vtLayers?Object.keys(this.vtLayers).sort():["_geojsonTileLayer"]),this.vtFeatures={};for(const p in this.vtLayers)this.vtFeatures[p]=[]}return this.vtLayers}query(p,v){const{tilespaceGeometry:S,transform:E,tileTransform:R,pixelPosMatrix:F,availableImages:q,worldview:K}=v;this.loadVTLayers(),this.serializedLayersCache.clear();const J=v.queryRadius?v.queryRadius:0,le=S.bufferedTilespaceBounds,fe=this.grid.query(le.min.x,le.min.y,le.max.x,le.max.y,(Ue,Qe,at,pt)=>VN(S.bufferedTilespaceGeometry,Ue-J,Qe-J,at+J,pt+J));fe.sort(MVt);let ye=null;E.elevation&&fe.length>0&&(ye=qO.create(E.elevation,this.tileID));const Te={};let Pe;for(let Ue=0;Ue(pt||(pt=Ea(dt,this.tileID.canonical,R)),wt.queryIntersectsFeature(S,dt,Tt,pt,this.z,E,F,ye,Lt,v.scope)))}return Te}loadMatchingFeature(p,v,S,E,R,F){const{featureIndex:q,bucketIndex:K,sourceLayerIndex:J,layoutVertexArrayOffset:le}=v,fe=this.bucketLayerIDs[K],ye=S.layers,Te=Object.keys(ye);if(Te.length&&!Kr(Te,fe))return;const Pe=S.sourceCache,Ue=this.sourceLayerCoder.decode(J),Qe=this.vtLayers[Ue].feature(q),at=this.getId(Qe,Ue);for(let pt=0;pt`${q.key}: ${q.message}`).join(", ");return void Er(`Failed to create expression for promoteId: ${F}`)}this.promoteIdExpression=R.value}S=this.promoteIdExpression.evaluate({zoom:0},p)}else S=p.properties[E];typeof S=="boolean"&&(S=Number(S))}return S}}function hQe(j,p,v,S,E){return kn(j,(R,F)=>{const q=p instanceof bm?p.get(F):null;return q&&q.evaluate?q.evaluate(v,S,void 0,E):q})}function MVt(j,p){return p-j}function mQe(j,p){const v={};if(!p)return v;for(const S of j){const E=S.layerIds.map(R=>p.getLayer(R)).filter(Boolean);if(E.length!==0){S.layers=E,S.stateDependentLayerIds&&(S.stateDependentLayers=S.stateDependentLayerIds.map(R=>E.filter(F=>F.id===R)[0]));for(const R of E)v[R.fqid]=S}}return v}pr(uQe,"FeatureIndex",{omit:["rawTileData","sourceLayerCoder"]});const xw=32,XN=33,uC=new Uint16Array(8184);for(let j=0;j<2046;j++){let p=j+2,v=0,S=0,E=0,R=0,F=0,q=0;for(1&p?E=R=F=xw:v=S=q=xw;(p>>=1)>1;){const J=v+E>>1,le=S+R>>1;1&p?(E=v,R=S,v=F,S=q):(v=E,S=R,E=F,R=q),F=J,q=le}const K=4*j;uC[K+0]=v,uC[K+1]=S,uC[K+2]=E,uC[K+3]=R}const QN=new Uint16Array(2178),hC=new Uint8Array(1089),Wee=new Uint16Array(1089);function pQe(j){return j===0?-.03125:j===32?.03125:0}const fQe={Other:0,Symbol:1,FillExtrusion:2},gQe={type:2,extent:sr,loadGeometry:()=>[[new sn(0,0),new sn(8193,0),new sn(8193,8193),new sn(0,8193),new sn(0,0)]]};class LVt{constructor(){this.tasks={},this.taskQueue=[],Zs(["process"],this),this.invoker=new EVt(this.process),this.nextId=0}add(p,v){const S=this.nextId++,E=function({type:R,renderSourceType:F,zoom:q}){q=q||0;const K=F===fQe.Symbol;return R==="message"?0:R!=="maybePrepare"||K?R!=="parseTile"||K?R==="parseTile"&&K?300-q:R==="maybePrepare"&&K?400-q:500:200-q:100-q}(v);if(E===0){try{p()}finally{}return null}return this.tasks[S]={fn:p,metadata:v,priority:E,id:S},this.taskQueue.push(S),this.invoker.trigger(),{cancel:()=>{delete this.tasks[S]}}}process(){try{if(this.taskQueue=this.taskQueue.filter(S=>!!this.tasks[S]),!this.taskQueue.length)return;const p=this.pick();if(p===null)return;const v=this.tasks[p];if(delete this.tasks[p],this.taskQueue.length&&this.invoker.trigger(),!v)return;v.fn()}finally{}}pick(){let p=null,v=1/0;for(let E=0;E>16&255)/255,(j>>8&255)/255,(255&j)/255,1)}function VVt(j,p,v){j===1?(p.rgb_color=Zee(v.readVarint()),p.paint="rgb_color"):j===2?(p.linear_gradient_idx=v.readVarint(),p.paint="linear_gradient_idx"):j===3?(p.radial_gradient_idx=v.readVarint(),p.paint="radial_gradient_idx"):j===5?v.readPackedFloat(p.dasharray):j===6?p.dashoffset=v.readFloat():j===7?p.miterlimit=v.readFloat():j===8?p.opacity=v.readVarint():j===9?p.width=v.readFloat():j===10?p.linecap=v.readVarint():j===11&&(p.linejoin=v.readVarint())}function HVt(j,p,v){j===1?p.transform=Yee(v,v.readVarint()+v.pos):j===2?p.spread_method=v.readVarint():j===3?p.stops.push(vQe(v,v.readVarint()+v.pos)):j===4?p.x1=v.readFloat():j===5?p.y1=v.readFloat():j===6?p.x2=v.readFloat():j===7&&(p.y2=v.readFloat())}function vQe(j,p){return j.readFields(GVt,{offset:0,opacity:255,rgb_color:fEe},p)}function GVt(j,p,v){j===1?p.offset=v.readFloat():j===2?p.opacity=v.readVarint():j===3&&(p.rgb_color=Zee(v.readVarint()))}function WVt(j,p,v){j===1?p.transform=Yee(v,v.readVarint()+v.pos):j===2?p.spread_method=v.readVarint():j===3?p.stops.push(vQe(v,v.readVarint()+v.pos)):j===4?p.cx=v.readFloat():j===5?p.cy=v.readFloat():j===6?p.r=v.readFloat():j===7?p.fx=v.readFloat():j===8?p.fy=v.readFloat():j===9&&(p.fr=v.readFloat())}function KVt(j,p,v){j===1?p.transform=Yee(v,v.readVarint()+v.pos):j===2?p.clip_path_idx=v.readVarint():j===3&&p.children.push(Kee(v,v.readVarint()+v.pos))}function YVt(j,p,v){j===1?p.left=p.top=v.readFloat():j===2?p.width=p.height=v.readFloat():j===3?p.top=v.readFloat():j===4?p.height=v.readFloat():j===5?p.mask_type=v.readVarint():j===6?p.mask_idx=v.readVarint():j===7&&p.children.push(Kee(v,v.readVarint()+v.pos))}class ZVt{static calculate(p={},v=[]){const S=new Map,E=new Map;if(Object.keys(p).length===0)return S;v.forEach(R=>{E.set(R.name,R.rgb_color||new cs(0,0,0))});for(const[R,F]of Object.entries(p))E.has(R)?S.set(E.get(R).toString(),F):console.warn(`Ignoring unknown image variable "${R}"`);return S}}function VO(j,p=255,v){const S=p/255,E=j.toString(),R=v.has(E)?v.get(E).clone():j.clone();return R.a*=S,R.toString()}function aV(j,p){if(!Ec()){const v=document.createElement("canvas");return v.width=j,v.height=p,v}return new OffscreenCanvas(j,p)}let gEe,iV=null;function xEe(j,p,v,S,E){for(const R of S.children)bQe(j,p,v,R,E)}function bQe(j,p,v,S,E){S.group?(j.save(),function(R,F,q,K,J){const le=K.mask_idx!=null?q.masks[K.mask_idx]:null,fe=K.clip_path_idx!=null?q.clip_paths[K.clip_path_idx]:null;if(K.transform&&(F=HO(K.transform).preMultiplySelf(F)),!function(Pe,Ue,Qe){return Pe.opacity!==255||Ue||Qe}(K,fe!=null,le!=null))return void xEe(R,F,q,K,J);const ye=aV(R.canvas.width,R.canvas.height),Te=ye.getContext("2d");xEe(Te,F,q,K,J),fe&&CQe(Te,F,q,fe),le&&AQe(Te,F,q,le,J),R.globalAlpha=K.opacity/255,R.drawImage(ye,0,0)}(j,p,v,S.group,E),j.restore()):S.path&&(j.save(),function(R,F,q,K,J){R.setTransform(F),K.paint_order===1?(_Qe(R,q,K,J),jQe(R,q,K,J)):(jQe(R,q,K,J),_Qe(R,q,K,J))}(j,p,v,S.path,E),j.restore())}function _Qe(j,p,v,S){const E=v.fill;if(!E)return;const R=E.opacity/255;switch(j.save(),j.beginPath(),TQe(v,j),E.paint){case"rgb_color":j.fillStyle=VO(E.rgb_color,E.opacity,S);break;case"linear_gradient_idx":{const F=p.linear_gradients[E.linear_gradient_idx];F.transform&&j.setTransform(HO(F.transform).preMultiplySelf(j.getTransform())),j.fillStyle=NQe(j,F,R,S);break}case"radial_gradient_idx":{const F=p.radial_gradients[E.radial_gradient_idx];F.transform&&j.setTransform(HO(F.transform).preMultiplySelf(j.getTransform())),j.fillStyle=kQe(j,F,R,S)}}j.fill(wQe(v)),j.restore()}function wQe(j){return j.rule===1?"nonzero":j.rule===2?"evenodd":void 0}function jQe(j,p,v,S){const E=v.stroke;if(!E)return;const R=EQe(v);j.lineWidth=E.width,j.miterLimit=E.miterlimit,j.setLineDash(E.dasharray),j.lineDashOffset=E.dashoffset;const F=E.opacity/255;switch(E.paint){case"rgb_color":j.strokeStyle=VO(E.rgb_color,E.opacity,S);break;case"linear_gradient_idx":j.strokeStyle=NQe(j,p.linear_gradients[E.linear_gradient_idx],F,S,!0);break;case"radial_gradient_idx":j.strokeStyle=kQe(j,p.radial_gradients[E.radial_gradient_idx],F,S,!0)}switch(E.linejoin){case 2:case 1:j.lineJoin="miter";break;case 3:j.lineJoin="round";break;case 4:j.lineJoin="bevel"}switch(E.linecap){case 1:j.lineCap="butt";break;case 2:j.lineCap="round";break;case 3:j.lineCap="square"}j.stroke(R)}function NQe(j,p,v,S,E=!1){if(p.stops.length===1){const ye=p.stops[0];return VO(ye.rgb_color,ye.opacity*v,S)}const{x1:R,y1:F,x2:q,y2:K}=p;let J=new DOMPoint(R,F),le=new DOMPoint(q,K);if(E){const ye=HO(p.transform);J=ye.transformPoint(J),le=ye.transformPoint(le)}const fe=j.createLinearGradient(J.x,J.y,le.x,le.y);for(const ye of p.stops)fe.addColorStop(ye.offset,VO(ye.rgb_color,ye.opacity*v,S));return fe}function kQe(j,p,v,S,E=!1){if(p.stops.length===1){const at=p.stops[0];return VO(at.rgb_color,at.opacity*v,S)}const R=HO(p.transform),{fx:F,fy:q,fr:K,cx:J,cy:le,r:fe}=p;let ye=new DOMPoint(F,q),Te=new DOMPoint(J,le),Pe=K,Ue=fe;if(E){ye=R.transformPoint(ye),Te=R.transformPoint(Te);const at=(R.a+R.d)/2;Pe=K*at,Ue=p.r*at}const Qe=j.createRadialGradient(ye.x,ye.y,Pe,Te.x,Te.y,Ue);for(const at of p.stops)Qe.addColorStop(at.offset,VO(at.rgb_color,at.opacity*v,S));return Qe}function SQe(j,p,v,S){const E=S.transform?HO(S.transform).preMultiplySelf(p):p,R=aV(j.canvas.width,j.canvas.height),F=R.getContext("2d");for(const K of S.children)if(K.group)SQe(F,E,v,K.group);else if(K.path){const J=K.path,le=new Path2D;le.addPath(EQe(J),E),F.fill(le,wQe(J))}const q=S.clip_path_idx!=null?v.clip_paths[S.clip_path_idx]:null;q&&CQe(F,E,v,q),j.globalCompositeOperation="source-over",j.drawImage(R,0,0)}function CQe(j,p,v,S){const E=aV(j.canvas.width,j.canvas.height);SQe(E.getContext("2d"),p,v,S),j.globalCompositeOperation="destination-in",j.drawImage(E,0,0)}function AQe(j,p,v,S,E){if(S.children.length===0)return;const R=S.mask_idx!=null?v.masks[S.mask_idx]:null;R&&AQe(j,p,v,R,E);const F=j.canvas.width,q=j.canvas.height,K=aV(F,q),J=K.getContext("2d"),le=S.width,fe=S.height,ye=S.left,Te=S.top,Pe=new Path2D,Ue=new Path2D;Ue.rect(ye,Te,le,fe),Pe.addPath(Ue,p),J.clip(Pe);for(const pt of S.children)bQe(J,p,v,pt,E);const Qe=J.getImageData(0,0,F,q),at=Qe.data;if(S.mask_type===1)for(let pt=0;ptp[F])return null}else{const q=1/S[F];let K=(j[F]-v[F])*q,J=(p[F]-v[F])*q;if(K>J){const le=K;K=J,J=le}if(K>E&&(E=K),JR)return null}return E}function PQe(j,p,v,S,E,R,F,q,K,J,le){const fe=S-j,ye=E-p,Te=R-v,Pe=F-j,Ue=q-p,Qe=K-v,at=le[1]*Qe-le[2]*Ue,pt=le[2]*Pe-le[0]*Qe,dt=le[0]*Ue-le[1]*Pe,wt=fe*at+ye*pt+Te*dt;if(Math.abs(wt)<1e-15)return null;const Tt=1/wt,Lt=J[0]-j,fs=J[1]-p,Jt=J[2]-v,ps=(Lt*at+fs*pt+Jt*dt)*Tt;if(ps<0||ps>1)return null;const rs=fs*Te-Jt*ye,is=Jt*fe-Lt*Te,dn=Lt*ye-fs*fe,fn=(le[0]*rs+le[1]*is+le[2]*dn)*Tt;return fn<0||ps+fn>1?null:(Pe*rs+Ue*is+Qe*dn)*Tt}function IQe(j,p,v){return(j-p)/(v-p)}function DQe(j,p,v,S,E,R,F,q,K){const J=1<{const pt=Qe?1:0,dt=(Te+1)*Ue-pt,wt=Pe*Ue,Tt=(Pe+1)*Ue-pt;at[0]=Te*Ue,at[1]=wt,at[2]=dt,at[3]=Tt};let fe=new MQe(K);const ye=[];for(let Te=0;Te=1;K/=2){const Te=q[q.length-1];fe=new MQe(K);for(let Pe=0;Pe0;){const{idx:Pe,t:Ue,nodex:Qe,nodey:at,depth:pt}=Te.pop();if(this.leaves[Pe]){DQe(Qe,at,pt,p,v,S,E,fe,ye);const wt=1<=wn[2])return Ue}continue}let dt=0;for(let wt=0;wt=J[le[Jt]]&&(le.splice(Jt,0,wt),fs=!0);fs||(le[dt]=wt),dt++}}for(let wt=0;wt=this.dim+1||v<-1||v>=this.dim+1)throw new RangeError("out of range source coordinates for DEM data");return(v+1)*this.stride+(p+1)}static pack(p,v){const S=[0,0,0,0],E=Qee.getUnpackVector(v);let R=Math.floor((p+E[3])/E[2]);return S[2]=R%256,R=Math.floor(R/256),S[1]=R%256,R=Math.floor(R/256),S[0]=R,S}getPixels(){return new yYe({width:this.stride,height:this.stride},this.pixels)}backfillBorder(p,v,S){if(this.dim!==p.dim)throw new Error("dem dimension mismatch");let E=v*this.dim,R=v*this.dim+this.dim,F=S*this.dim,q=S*this.dim+this.dim;switch(v){case-1:E=R-1;break;case 1:R=E+1}switch(S){case-1:F=q-1;break;case 1:q=F+1}const K=-v*this.dim,J=-S*this.dim;for(let le=F;le=1;S--){const E=S===1?1:0,R=S===2?1:0;for(let F=0;F>>1^-(1&j[p]);return j}function dHt(j,p){switch(p){case"uint32":return j;case"uint16":for(let v=0;v>4|(61440&S)>>8|(240&E)<<4|61440&E,j[v+1]=15&S|(3840&S)>>4|(15&E)<<8|(3840&E)<<4}return j;case"uint8":for(let v=0;v>6|(192&E)>>4|(192&R)>>2|192&F,j[v+1]=(48&S)>>4|(48&E)>>2|48&R|(48&F)<<2,j[v+2]=(12&S)>>2|12&E|(12&R)<<2|(12&F)<<4,j[v+3]=3&S|(3&E)<<2|(3&R)<<4|(3&F)<<6}return j;default:throw new Error(`Invalid pixel format, "${p}"`)}}pr(Qee,"DEMData"),pr(RQe,"DemMinMaxQuadTree",{omit:["dem"]});var Ob=Uint8Array,oV=Uint16Array,uHt=Int32Array,FQe=new Ob([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]),zQe=new Ob([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]),hHt=new Ob([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),BQe=function(j,p){for(var v=new oV(31),S=0;S<31;++S)v[S]=p+=1<>1|(21845&Zh)<<1;qQe[Zh]=((65280&(GO=(61680&(GO=(52428&GO)>>2|(13107&GO)<<2))>>4|(3855&GO)<<4))>>8|(255&GO)<<8)>>1}var lV=function(j,p,v){for(var S=j.length,E=0,R=new oV(p);E>K]=J;return F},cV=new Ob(288);for(Zh=0;Zh<144;++Zh)cV[Zh]=8;for(Zh=144;Zh<256;++Zh)cV[Zh]=9;for(Zh=256;Zh<280;++Zh)cV[Zh]=7;for(Zh=280;Zh<288;++Zh)cV[Zh]=8;var VQe=new Ob(32);for(Zh=0;Zh<32;++Zh)VQe[Zh]=5;var fHt=lV(cV,9),gHt=lV(VQe,5),vEe=function(j){for(var p=j[0],v=1;vp&&(p=j[v]);return p},Xj=function(j,p,v){var S=p/8|0;return(j[S]|j[S+1]<<8)>>(7&p)&v},bEe=function(j,p){var v=p/8|0;return(j[v]|j[v+1]<<8|j[v+2]<<16)>>(7&p)},xHt=function(j){return(j+7)/8|0},yHt=["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"],Qj=function(j,p,v){var S=new Error(p||yHt[j]);if(S.code=j,Error.captureStackTrace&&Error.captureStackTrace(S,Qj),!v)throw S;return S},vHt=new Ob(0),bHt=typeof TextDecoder<"u"&&new TextDecoder;try{bHt.decode(vHt,{stream:!0})}catch{}const _Ht={gzip_data:"gzip"};class yw extends Error{constructor(p){super(p),this.name="MRTError"}}const wHt={0:"uint32",1:"uint32",2:"uint16",3:"uint8"},HQe={uint32:1,uint16:2,uint8:4},jHt={uint32:Uint32Array,uint16:Uint16Array,uint8:Uint8Array};let _Ee;class Jee{constructor(p=5){this.x=NaN,this.y=NaN,this.z=NaN,this.layers={},this._cacheSize=p}getLayer(p){const v=this.layers[p];if(!v)throw new yw(`Layer '${p}' not found`);return v}getHeaderLength(p){const v=new Uint8Array(p),S=new DataView(p);if(v[0]!==13)throw new yw("File is not a valid MRT.");return S.getUint32(1,!0)}parseHeader(p){const v=new Uint8Array(p),S=this.getHeaderLength(p);if(v.length= ${S} but got buffer of length ${v.length}`);const E=new _Ee(v.subarray(0,S)).readFields(eHt,{headerLength:0,x:0,y:0,z:0,layers:[]},void 0);if(!isNaN(this.x)&&(this.x!==E.x||this.y!==E.y||this.z!==E.z))throw new yw(`Invalid attempt to parse header ${E.z}/${E.x}/${E.y} for tile ${this.z}/${this.x}/${this.y}`);this.x=E.x,this.y=E.y,this.z=E.z;for(const R of E.layers)this.layers[R.name]=new GQe(R,{cacheSize:this._cacheSize});return this}createDecodingTask(p){const v=[],S=this.getLayer(p.layerName);for(let E of p.blockIndices){const R=S.dataIndex[E],F=R.firstByte-p.firstByte,q=R.lastByte-p.firstByte;if(S._blocksInProgress.has(E))continue;const K={layerName:S.name,firstByte:F,lastByte:q,pixelFormat:S.pixelFormat,blockIndex:E,blockShape:[R.bands.length].concat(S.bandShape),buffer:S.buffer,codec:R.codec.codec,filters:R.filters.map(J=>J.filter)};S._blocksInProgress.add(E),v.push(K)}return new WQe(v,()=>{v.forEach(E=>S._blocksInProgress.delete(E.blockIndex))},(E,R)=>{if(v.forEach(F=>S._blocksInProgress.delete(F.blockIndex)),E)throw E;R.forEach(F=>{this.getLayer(F.layerName).processDecodedData(F)})})}}class GQe{constructor({version:p,name:v,units:S,tileSize:E,pixelFormat:R,buffer:F,dataIndex:q},K){if(this.version=p,this.version!==1)throw new yw(`Cannot parse raster layer encoded with MRT version ${p}`);this.name=v,this.units=S,this.tileSize=E,this.buffer=F,this.pixelFormat=wHt[R],this.dataIndex=q,this.bandShape=[E+2*F,E+2*F,HQe[this.pixelFormat]],this._decodedBlocks=new Xee(K?K.cacheSize:5),this._blocksInProgress=new Set}get dimension(){return HQe[this.pixelFormat]}get cacheSize(){return this._decodedBlocks.capacity}getBandList(){return this.dataIndex.map(({bands:p})=>p).flat()}processDecodedData(p){const v=p.blockIndex.toString();this._decodedBlocks.get(v)||this._decodedBlocks.put(v,p.data)}getBlockForBand(p){let v=0;switch(typeof p){case"string":for(const[S,E]of this.dataIndex.entries()){for(const[R,F]of E.bands.entries())if(F===p)return{bandIndex:v+R,blockIndex:S,blockBandIndex:R};v+=E.bands.length}break;case"number":for(const[S,E]of this.dataIndex.entries()){if(p>=v&&pthis.cacheSize)throw new yw(`Number of blocks to decode (${R.size}) exceeds cache size (${this.cacheSize}).`);return{layerName:this.name,firstByte:v,lastByte:S,blockIndices:E}}hasBand(p){const{blockIndex:v}=this.getBlockForBand(p);return v>=0}hasDataForBand(p){const{blockIndex:v}=this.getBlockForBand(p);return v>=0&&!!this._decodedBlocks.get(v.toString())}getBandView(p){const{blockIndex:v,blockBandIndex:S}=this.getBlockForBand(p);if(v<0)throw new yw(`Band not found: ${JSON.stringify(p)}`);const E=this._decodedBlocks.get(v.toString());if(!E)throw new yw(`Data for band ${JSON.stringify(p)} of layer "${this.name}" not decoded.`);const R=this.dataIndex[v],F=this.bandShape.reduce((J,le)=>J*le,1),q=S*F,K=E.subarray(q,q+F);return{data:K,bytes:new Uint8Array(K.buffer).subarray(K.byteOffset,K.byteOffset+K.byteLength),tileSize:this.tileSize,buffer:this.buffer,pixelFormat:this.pixelFormat,dimension:this.dimension,offset:R.offset,scale:R.scale}}}Jee.setPbf=function(j){_Ee=j};class WQe{constructor(p,v,S){this.tasks=p,this._onCancel=v,this._onComplete=S,this._finalized=!1}cancel(){this._finalized||(this._onCancel(),this._finalized=!0)}complete(p,v){this._finalized||(this._onComplete(p,v),this._finalized=!0)}}Jee.performDecoding=function(j,p){const v=new Uint8Array(j);return Promise.all(p.tasks.map(S=>{const{layerName:E,firstByte:R,lastByte:F,pixelFormat:q,blockShape:K,blockIndex:J,filters:le,codec:fe}=S,ye=v.subarray(R,F+1),Te=new Uint32Array(K[0]*K[1]*K[2]);let Pe;if(fe!=="gzip_data")throw new yw(`Unhandled codec: ${fe}`);return Pe=function(Ue,Qe){if(!globalThis.DecompressionStream&&Qe==="gzip_data")return Promise.resolve((Tt=function(Jt){Jt[0]==31&&Jt[1]==139&&Jt[2]==8||Qj(6,"invalid gzip data");var ps=Jt[3],rs=10;4&ps&&(rs+=2+(Jt[10]|Jt[11]<<8));for(var is=(ps>>3&1)+(ps>>4&1);is>0;is-=!Jt[rs++]);return rs+(2&ps)}(at=Ue),Tt+8>at.length&&Qj(6,"invalid gzip data"),function(Jt,ps,rs,is){var dn=Jt.length;if(!dn||ps.f&&!ps.l)return rs||new Ob(0);var fn=!rs,_n=fn||ps.i!=2,Sn=ps.i;fn&&(rs=new Ob(3*dn));var wn=function(Sd){var Dg=rs.length;if(Sd>Dg){var cp=new Ob(Math.max(2*Dg,Sd));cp.set(rs),rs=cp}},Un=ps.f||0,ln=ps.p||0,Nn=ps.b||0,Tn=ps.l,Vn=ps.d,ar=ps.m,zr=ps.n,yr=8*dn;do{if(!Tn){Un=Xj(Jt,ln,1);var gr=Xj(Jt,ln+1,3);if(ln+=3,!gr){var ir=Jt[(Jo=xHt(ln)+4)-4]|Jt[Jo-3]<<8,Dr=Jo+ir;if(Dr>dn){Sn&&Qj(0);break}_n&&wn(Nn+ir),rs.set(Jt.subarray(Jo,Dr),Nn),ps.b=Nn+=ir,ps.p=ln=8*Dr,ps.f=Un;continue}if(gr==1)Tn=fHt,Vn=gHt,ar=9,zr=5;else if(gr==2){var Zr=Xj(Jt,ln,31)+257,Aa=Xj(Jt,ln+10,15)+4,ma=Zr+Xj(Jt,ln+5,31)+1;ln+=14;for(var mi=new Ob(ma),bo=new Ob(19),pi=0;pi>4)<16)mi[pi++]=Jo;else{var Hl=0,pd=0;for(Jo==16?(pd=3+Xj(Jt,ln,3),ln+=2,Hl=mi[pi-1]):Jo==17?(pd=3+Xj(Jt,ln,7),ln+=3):Jo==18&&(pd=11+Xj(Jt,ln,127),ln+=7);pd--;)mi[pi++]=Hl}}var jm=mi.subarray(0,Zr),fd=mi.subarray(Zr);ar=vEe(jm),zr=vEe(fd),Tn=lV(jm,ar),Vn=lV(fd,zr)}else Qj(1);if(ln>yr){Sn&&Qj(0);break}}_n&&wn(Nn+131072);for(var Xd=(1<>4;if((ln+=15&Hl)>yr){Sn&&Qj(0);break}if(Hl||Qj(2),Mf<256)rs[Nn++]=Mf;else{if(Mf==256){Qd=ln,Tn=null;break}var Nm=Mf-254;Mf>264&&(Nm=Xj(Jt,ln,(1<<(xu=FQe[pi=Mf-257]))-1)+UQe[pi],ln+=xu);var Oi=Vn[bEe(Jt,ln)&Xu],jx=Oi>>4;if(Oi||Qj(3),ln+=15&Oi,fd=pHt[jx],jx>3){var xu=zQe[jx];fd+=bEe(Jt,ln)&(1<yr){Sn&&Qj(0);break}_n&&wn(Nn+131072);var lp=Nn+Nm;if(NnSd.length)&&(cp=Sd.length),new Ob(Sd.subarray(0,cp))}(rs,0,Nn):rs.subarray(0,Nn)}(at.subarray(Tt,-8),{i:2},new Ob(((dt=at)[(wt=dt.length)-4]|dt[wt-3]<<8|dt[wt-2]<<16|dt[wt-1]<<24)>>>0),pt)));var at,pt,dt,wt,Tt;const Lt=_Ht[Qe];if(!Lt)throw new Error(`Unhandled codec: ${Qe}`);const fs=new globalThis.DecompressionStream(Lt);return new Response(new Blob([Ue]).stream().pipeThrough(fs)).arrayBuffer().then(Jt=>new Uint8Array(Jt))}(ye,fe).then(Ue=>(function(Qe,at){Qe.readFields(iHt,at)}(new _Ee(Ue),Te),new jHt[q](Te.buffer))),Pe.then(Ue=>{for(let Qe=le.length-1;Qe>=0;Qe--)switch(le[Qe]){case"delta_filter":lHt(Ue,K);break;case"zigzag_filter":cHt(Ue);break;case"bitshuffle_filter":dHt(Ue,q);break;default:throw new yw(`Unhandled filter "${le[Qe]}"`)}return{layerName:E,blockIndex:J,data:Ue}}).catch(Ue=>{throw Ue})}))},pr(WQe,"MRTDecodingBatch",{omit:["_onCancel","_onComplete"]}),pr(Jee,"MapboxRasterTile"),pr(GQe,"MapboxRasterLayer",{omit:["_blocksInProgress"]});const KQe=[Int8Array,Uint8Array,Uint8ClampedArray,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array];class wEe{static from(p){if(!(p instanceof ArrayBuffer))throw new Error("Data must be an instance of ArrayBuffer.");const[v,S]=new Uint8Array(p,0,2);if(v!==219)throw new Error("Data does not appear to be in a KDBush format.");const E=S>>4;if(E!==1)throw new Error(`Got v${E} data when expected v1.`);const R=KQe[15&S];if(!R)throw new Error("Unrecognized array type.");const[F]=new Uint16Array(p,2,1),[q]=new Uint32Array(p,4,1);return new wEe(q,F,R,p)}constructor(p,v=64,S=Float64Array,E){if(isNaN(p)||p<0)throw new Error(`Unpexpected numItems value: ${p}.`);this.numItems=+p,this.nodeSize=Math.min(Math.max(+v,2),65535),this.ArrayType=S,this.IndexArrayType=p<65536?Uint16Array:Uint32Array;const R=KQe.indexOf(this.ArrayType),F=2*p*this.ArrayType.BYTES_PER_ELEMENT,q=p*this.IndexArrayType.BYTES_PER_ELEMENT,K=(8-q%8)%8;if(R<0)throw new Error(`Unexpected typed array class: ${S}.`);E&&E instanceof ArrayBuffer?(this.data=E,this.ids=new this.IndexArrayType(this.data,8,p),this.coords=new this.ArrayType(this.data,8+q+K,2*p),this._pos=2*p,this._finished=!0):(this.data=new ArrayBuffer(8+F+q+K),this.ids=new this.IndexArrayType(this.data,8,p),this.coords=new this.ArrayType(this.data,8+q+K,2*p),this._pos=0,this._finished=!1,new Uint8Array(this.data,0,2).set([219,16+R]),new Uint16Array(this.data,2,1)[0]=v,new Uint32Array(this.data,4,1)[0]=p)}add(p,v){const S=this._pos>>1;return this.ids[S]=S,this.coords[this._pos++]=p,this.coords[this._pos++]=v,S}finish(){const p=this._pos>>1;if(p!==this.numItems)throw new Error(`Added ${p} items when expected ${this.numItems}.`);return jEe(this.ids,this.coords,this.nodeSize,0,this.numItems-1,0),this._finished=!0,this}range(p,v,S,E){if(!this._finished)throw new Error("Data not yet indexed - call index.finish().");const{ids:R,coords:F,nodeSize:q}=this,K=[0,R.length-1,0],J=[];for(;K.length;){const le=K.pop()||0,fe=K.pop()||0,ye=K.pop()||0;if(fe-ye<=q){for(let Qe=ye;Qe<=fe;Qe++){const at=F[2*Qe],pt=F[2*Qe+1];at>=p&&at<=S&&pt>=v&&pt<=E&&J.push(R[Qe])}continue}const Te=ye+fe>>1,Pe=F[2*Te],Ue=F[2*Te+1];Pe>=p&&Pe<=S&&Ue>=v&&Ue<=E&&J.push(R[Te]),(le===0?p<=Pe:v<=Ue)&&(K.push(ye),K.push(Te-1),K.push(1-le)),(le===0?S>=Pe:E>=Ue)&&(K.push(Te+1),K.push(fe),K.push(1-le))}return J}within(p,v,S){if(!this._finished)throw new Error("Data not yet indexed - call index.finish().");const{ids:E,coords:R,nodeSize:F}=this,q=[0,E.length-1,0],K=[],J=S*S;for(;q.length;){const le=q.pop()||0,fe=q.pop()||0,ye=q.pop()||0;if(fe-ye<=F){for(let Qe=ye;Qe<=fe;Qe++)ZQe(R[2*Qe],R[2*Qe+1],p,v)<=J&&K.push(E[Qe]);continue}const Te=ye+fe>>1,Pe=R[2*Te],Ue=R[2*Te+1];ZQe(Pe,Ue,p,v)<=J&&K.push(E[Te]),(le===0?p-S<=Pe:v-S<=Ue)&&(q.push(ye),q.push(Te-1),q.push(1-le)),(le===0?p+S>=Pe:v+S>=Ue)&&(q.push(Te+1),q.push(fe),q.push(1-le))}return K}}function jEe(j,p,v,S,E,R){if(E-S<=v)return;const F=S+E>>1;YQe(j,p,F,S,E,R),jEe(j,p,v,S,F-1,1-R),jEe(j,p,v,F+1,E,1-R)}function YQe(j,p,v,S,E,R){for(;E>S;){if(E-S>600){const J=E-S+1,le=v-S+1,fe=Math.log(J),ye=.5*Math.exp(2*fe/3),Te=.5*Math.sqrt(fe*ye*(J-ye)/J)*(le-J/2<0?-1:1);YQe(j,p,v,Math.max(S,Math.floor(v-le*ye/J+Te)),Math.min(E,Math.floor(v+(J-le)*ye/J+Te)),R)}const F=p[2*v+R];let q=S,K=E;for(dV(j,p,S,v),p[2*E+R]>F&&dV(j,p,S,E);qF;)K--}p[2*S+R]===F?dV(j,p,S,K):(K++,dV(j,p,K,E)),K<=v&&(S=K+1),v<=K&&(E=K-1)}}function dV(j,p,v,S){NEe(j,v,S),NEe(p,2*v,2*S),NEe(p,2*v+1,2*S+1)}function NEe(j,p,v){const S=j[p];j[p]=j[v],j[v]=S}function ZQe(j,p,v,S){const E=j-v,R=p-S;return E*E+R*R}o.$=Cf,o.A=class{constructor(j,p,v){this.target=j,this.parent=p,this.mapId=v,this.callbacks={},this.cancelCallbacks={},Zs(["receive"],this),this.target.addEventListener("message",this.receive,!1),this.scheduler=new LVt}send(j,p,v,S,E=!1,R){const F=Math.round(1e18*Math.random()).toString(36).substring(0,10);v&&(v.metadata=R,this.callbacks[F]=v);const q=new Set;return this.target.postMessage({id:F,type:j,hasCallback:!!v,targetMapId:S,mustQueue:E,sourceMapId:this.mapId,data:kc(p,q)},q),{cancel:()=>{v&&delete this.callbacks[F],this.target.postMessage({id:F,type:"",targetMapId:S,sourceMapId:this.mapId})}}}receive(j){const p=j.data;if(!p)return;const v=p.id;if(v&&(!p.targetMapId||this.mapId===p.targetMapId))if(p.type===""){const S=this.cancelCallbacks[v];delete this.cancelCallbacks[v],S&&S.cancel()}else if(p.mustQueue||Jr(self)){const S=this.callbacks[v],E=this.scheduler.add(()=>this.processTask(v,p),S&&S.metadata||{type:"message"});E&&(this.cancelCallbacks[v]=E)}else this.processTask(v,p)}processTask(j,p){if(delete this.cancelCallbacks[j],p.type===""){const v=this.callbacks[j];delete this.callbacks[j],v&&(p.error?v(Xl(p.error)):v(null,Xl(p.data)))}else{const v=new Set,S=p.hasCallback?(R,F)=>{this.target.postMessage({id:j,type:"",sourceMapId:this.mapId,error:R?kc(R):null,data:kc(F,v)},v)}:()=>{},E=Xl(p.data);if(this.parent[p.type])this.parent[p.type](p.sourceMapId,E,S);else if(this.parent.getWorkerSource){const R=p.type.split("."),{source:F,scope:q}=E;this.parent.getWorkerSource(p.sourceMapId,{type:R[0],source:F,scope:q,uid:0})[R[1]](E,S)}else S(new Error(`Could not find function ${p.type}`))}}remove(){this.scheduler.remove(),this.target.removeEventListener("message",this.receive,!1)}},o.B=Qm,o.C=Nc,o.D=ud,o.E=Hh,o.F=St,o.G=2,o.H=Wq,o.I=Wt,o.J=pXe,o.K=gx,o.L=fS,o.M=Eg,o.N=i0,o.O=md,o.P=sn,o.Q=zo,o.R=n0,o.S=jh,o.T=ZN,o.U=gm,o.V=Hee,o.W=UN,o.X=Pc,o.Y=Pu,o.Z=Wd,o._=x1,o.a=function(j){return Ta.API_CDN_URL_REGEX.test(j)},o.a$=Cee,o.a0=qc,o.a1=kf,o.a2=Jf,o.a3=ss,o.a4=gS,o.a5=class extends Hee{},o.a6=Kd,o.a7=hd,o.a8=Is,o.a9=function(j){const p=j.value;return p?Jf(p)?uEe(p,!0)?[]:[new Hee(j.key,p,`invalid url "${p}"`)]:[new Hee(j.key,p,`string expected, "${Eg(p)}" found`)]:[]},o.aA=UZe,o.aB=function(j){let p=1/0,v=1/0,S=-1/0,E=-1/0;for(const R of j)p=Math.min(p,R.x),v=Math.min(v,R.y),S=Math.max(S,R.x),E=Math.max(E,R.y);return{min:new sn(p,v),max:new sn(S,E)}},o.aC=it,o.aD=b,o.aE=ht,o.aF=Ft,o.aG=y0,o.aH=An,o.aI=Fr,o.aJ=function(j,p){const v={};for(let S=0;S=0?p.slice(v+1):""}catch{return""}},o.aN=class{constructor(j){this.entries={},this.scheduler=j}request(j,p,v,S){const E=this.entries[j]=this.entries[j]||{callbacks:[]};if(E.result){const[R,F]=E.result;return this.scheduler?this.scheduler.add(()=>{S(R,F)},p):S(R,F),()=>{}}return E.callbacks.push(S),E.cancel||(E.cancel=v((R,F)=>{E.result=[R,F];for(const q of E.callbacks)this.scheduler?this.scheduler.add(()=>{q(R,F)},p):q(R,F);setTimeout(()=>delete this.entries[j],3e3)})),()=>{E.result||(E.callbacks=E.callbacks.filter(R=>R!==S),E.callbacks.length||(E.cancel(),delete this.entries[j]))}}},o.aO=function(j,p,v){const S=JSON.stringify(j.request);return j.data&&(this.deduped.entries[S]={result:[null,j.data]}),this.deduped.request(S,{type:"parseTile",renderSourceType:j.renderSourceType,zoom:j.tileZoom},E=>{const R=iy(j.request,(F,q,K)=>{F?Km(F)?E(null,null):E(F):q&&E(null,{rawData:q,vectorTile:v?void 0:new Bo(new Cee(q)),responseHeaders:new Map(K.entries())})});return()=>{R.cancel(),E(null,null)}},p)},o.aP=function(j){return j?{cacheControl:j.get("cache-control"),expires:j.get("expires")}:{cacheControl:void 0,expires:void 0}},o.aQ=function(j){po++,po>wf&&(j.getActor().send("enforceCacheSizeLimit",ay),po=0)},o.aR=wx,o.aS=YXe,o.aT=nQe,o.aU=Cs,o.aV=KXe,o.aW=function(j,p){const v=document.createElement("video");v.muted=!0,v.onloadstart=function(){p(null,v)};for(let S=0;S{}}},o.aX=Uq,o.aY=P6,o.aZ=Zs,o.a_=Jee,o.aa=Y3,o.ab=dc,o.ac=er,o.ad=class{constructor(j){this.specification=j}possiblyEvaluate(j,p){return Gn(j.expression.evaluate(p))}interpolate(j,p,v){return{x:mr(j.x,p.x,v),y:mr(j.y,p.y,v),z:mr(j.z,p.z,v),azimuthal:mr(j.azimuthal,p.azimuthal,v),polar:mr(j.polar,p.polar,v)}}},o.ae=xi,o.af=Dl,o.ag=Yr,o.ah=Ge,o.ai=X,o.aj=ft,o.ak=bm,o.al=jS,o.am=mr,o.an=sr,o.ao=Ba,o.ap=Nr,o.aq=cs,o.ar=class{constructor(j){this.specification=j}possiblyEvaluate(j,p){return function([v,S]){const E=Gn([1,v,S]);return{x:E.x,y:E.y,z:E.z}}(j.expression.evaluate(p))}interpolate(j,p,v){return{x:mr(j.x,p.x,v),y:mr(j.y,p.y,v),z:mr(j.z,p.z,v)}}},o.as=function(j,p,v=0,S=!0){const E=new sn(v,v),R=j.sub(E),F=p.add(E),q=[R,new sn(F.x,R.y),F,new sn(R.x,F.y)];return S&&q.push(R.clone()),q},o.at=function(j,p){const v=[];for(let S=0;Sthis.buckets[fe].layers.some(ye=>F.has(ye.fqid))),K=Object.keys(this.buckets).some(fe=>this.buckets[fe].layers.some(ye=>ye.hasTransition&&ye.hasTransition())),J=this._firstPrepareComplete&&R!==this._lastAvailableImagesCount;this._hasAppearances===null&&(this._hasAppearances=this.hasAppearances(p));const le=this._lastUpdatedBrightness!==S;this._lastAvailableImagesCount=R,this._firstPrepareComplete=!0,(this._lastUpdatedBrightness||S||this._hasAppearances||q||K||J)&&(!(this._hasAppearances||q||K||J)&&this._lastUpdatedBrightness&&S&&Math.abs(this._lastUpdatedBrightness-S)<.001||(this.updateBuckets(p,le,void 0,J||q||K,F,E),this._lastUpdatedBrightness=S))}evaluateQueryRenderedFeaturePadding(){let j=0;for(const p in this.buckets){const v=this.buckets[p];v.evaluateQueryRenderedFeaturePadding&&(j=Math.max(j,v.evaluateQueryRenderedFeaturePadding()))}return j}queryRenderedFeatures(j,p,v,S,E,R,F){if(!this.latestFeatureIndex||!this.latestFeatureIndex.rawTileData&&!this.latestFeatureIndex.is3DTile)return{};const q=this.evaluateQueryRenderedFeaturePadding(),K=function(J,le){const fe=M([],[.5*J.width,.5*-J.height,1]);return k(fe,fe,[1,-1,0]),b(fe,fe,J.calculateProjMatrix(le.toUnwrapped())),Float32Array.from(fe)}(E,this.tileID);return this.latestFeatureIndex.query(j,{tilespaceGeometry:p,pixelPosMatrix:K,transform:S,availableImages:v,tileTransform:this.tileTransform,worldview:this.worldview,queryRadius:q,scope:F})}querySourceFeatures(j,p){const v=this.latestFeatureIndex;if(!v||!v.rawTileData)return;const S=v.loadVTLayers(),E=p?p.sourceLayer:"",R=S._geojsonTileLayer||S[E];if(!R)return;const F=Q3(p&&p.filter),{z:q,x:K,y:J}=this.tileID.canonical,le={z:q,x:K,y:J};for(let fe=0;fev)S=!1;else if(p)if(this.expirationTimev.appearances&&v.appearances.length>0))return!0;return!1}updateBuckets(j,p,v,S,E,R){if(!this.latestFeatureIndex||!j.style)return;const F=R||j.style.listImages(),q=j.style.getBrightness(),K=E||new Set;for(const J in this.buckets){if(!j.style.hasLayer(J))continue;const le=this.buckets[J],fe=le.layers[0],ye=fe.sourceLayer||"_geojsonTileLayer",Te=j.style.getLayerSourceCache(fe),Pe=le.layers.some(Tt=>K.has(Tt.fqid)),Ue=(S||Pe)&&le instanceof Zj?j.style.getOwnLayer(J):void 0;let Qe=v&&v[ye]||{};Te&&!v&&(Qe=Te._state.getState(ye,void 0));const at=this.imageAtlas?Object.fromEntries(this.imageAtlas.patternPositions):{},pt=Object.keys(Qe).length>0&&!p;le.hasAppearances=le.layers.some(Tt=>Tt.appearances&&Tt.appearances.length>0);const dt=pt?le.stateDependentLayers:le.layers;if(pt&&le.stateDependentLayers.length!==0||p||Pe||S){const Tt=this.latestFeatureIndex.loadVTLayers()[ye];if(le.update(Qe,Tt,F,at,dt,p,q,this.tileID.canonical),(S||Pe)&&!p&&le instanceof Zj&&Ue&&Ue.type==="symbol"){const Lt=le;Lt.text&&Lt.text.uboBinder&&Lt.text.uboBinder.updateDynamicExpressions(Ue,Tt,this.tileID.canonical,F,Qe,q),Lt.icon&&Lt.icon.uboBinder&&Lt.icon.uboBinder.updateDynamicExpressions(Ue,Tt,this.tileID.canonical,F,Qe,q)}if(le instanceof Zj){const Lt=le,fs=j.context;Lt.text&&Lt.text.uboBinder&&Lt.text.uboBinder.upload(fs),Lt.icon&&Lt.icon.uboBinder&&Lt.icon.uboBinder.upload(fs)}}if(pt&&le.stateDependentLayers.length!==0||p||le.hasAppearances){const Tt={zoom:j.transform.zoom,pitch:j.transform.pitch,brightness:j.style.getBrightness()||0,worldview:j.worldview},Lt=le.updateAppearances(this.tileID.canonical,Qe,F,Tt,j.imageManager,pt&&le.stateDependentLayers.length!==0);if(Lt&&Lt.hasUboChanges){const fs=j.context;le instanceof Zj&&le.text&&le.text.uboBinder&&le.text.uboBinder.upload(fs),le instanceof Zj&&le.icon&&le.icon.uboBinder&&le.icon.uboBinder.upload(fs)}}(le instanceof See||le instanceof oee)&&j._terrain&&j._terrain.enabled&&Te&&le.uploadPending()&&j._terrain._clearRenderCacheForTile(Te.id,this.tileID);const wt=j&&j.style&&j.style.getOwnLayer(J);wt&&(this.queryPadding=Math.max(this.queryPadding,wt.queryRadius(le)||0))}}holdingForFade(){return this.symbolFadeHoldUntil!==void 0}symbolFadeFinished(){return!this.symbolFadeHoldUntil||this.symbolFadeHoldUntil=0;Ue--){const Qe=4*Ue,at=uC[Qe+0],pt=uC[Qe+1],dt=uC[Qe+2],wt=uC[Qe+3],Tt=at+dt>>1,Lt=pt+wt>>1,fs=Tt+Lt-pt,Jt=Lt+at-Tt,ps=pt*XN+at,rs=wt*XN+dt,is=Lt*XN+Tt,dn=Math.hypot((QN[2*ps+0]+QN[2*rs+0])/2-QN[2*is+0],(QN[2*ps+1]+QN[2*rs+1])/2-QN[2*is+1])>=16;hC[is]=hC[is]||(dn?1:0),Ue<1022&&(hC[is]=hC[is]||hC[(pt+Jt>>1)*XN+(at+fs>>1)]||hC[(wt+Jt>>1)*XN+(dt+fs>>1)])}const le=new Yi,fe=new Zd;let ye=0;function Te(Ue,Qe){const at=Qe*XN+Ue;return Wee[at]===0&&(le.emplaceBack(QN[2*at+0],QN[2*at+1],Ue*sr/xw,Qe*sr/xw),Wee[at]=++ye),Wee[at]-1}function Pe(Ue,Qe,at,pt,dt,wt){const Tt=Ue+at>>1,Lt=Qe+pt>>1;if(Math.abs(Ue-dt)+Math.abs(Qe-wt)>1&&hC[Lt*XN+Tt])Pe(dt,wt,Ue,Qe,Tt,Lt),Pe(at,pt,dt,wt,Tt,Lt);else{const fs=Te(Ue,Qe),Jt=Te(at,pt),ps=Te(dt,wt);fe.emplaceBack(fs,Jt,ps)}}return Pe(0,0,xw,xw,xw,0),Pe(xw,xw,0,0,0,xw),{vertices:le,indices:fe}}(this.tileID.canonical,p);S=R.vertices,E=R.indices}else{S=new Yi,E=new Zd;for(const{x:F,y:q}of v)S.emplaceBack(F,q,0,0);const R=EO(S.int16.subarray(0,4*S.length),void 0,4);for(let F=0;F0&&(F=_(new Float64Array(16),p.globeMatrix)),this._makeGlobeTileDebugBorderBuffer(j,S,p,E,F,R),this._makeGlobeTileDebugTextBuffer(j,S,p,E,F,R)}_globePoint(j,p,v,S,E,R,F){let q=kq(j,p,v);if(R){const K=1<.5?ye=-1:fe<-.5&&(ye=1);let Te=(j/sr+v.x)/K+ye,Pe=(p/sr+v.y)/K;Te=(Te-J)*S._pixelsPerMercatorPixel+J,Pe=(Pe-le)*S._pixelsPerMercatorPixel+le;const Ue=[Te*S.worldSize,Pe*S.worldSize,0];Ge(Ue,Ue,R),q=wS(q,Ue,F)}return Ge(q,q,E)}_makeGlobeTileDebugBorderBuffer(j,p,v,S,E,R){const F=new Mi,q=new vS,K=new Fo,J=(fe,ye,Te,Pe,Ue)=>{const Qe=(Te-fe)/(Ue-1),at=(Pe-ye)/(Ue-1),pt=F.length;for(let dt=0;dtJ*fe+ye;for(let fe=0;fe1)return!1;const v=p.getSource().maxzoom,S=1<1)return p;const E=S.getSource().maxzoom,R=1<{const q=this.getAtTileOffset(j,E,R,F),K=S.upVector(j.canonical,E.x,E.y);return xe(K,K,q*S.upVectorScale(j.canonical,p,v).metersToTile),K}}getForTilePoints(j,p,v,S){if(this.isUsingMockSource())return!1;const E=qO.create(this,j,S);return!!E&&(p.forEach(R=>{R[2]=this.exaggeration()*E.getElevationAt(R[0],R[1],v)}),!0)}getMinMaxForTile(j){if(this.isUsingMockSource())return null;const p=this.findDEMTileFor(j);if(!p||!p.dem)return null;const v=p.dem.tree,S=p.tileID,E=1<0&&(S+=(j[E]-0)*(j[E]-0)),p[E]<0&&(S+=(0-p[E])*(0-p[E]));return S},o.cL=function(j){return j*j*j*j*j},o.cM=an,o.cN=45,o.cO=CO,o.cP=function(j,p,v){const S=Math.sqrt(j*j+p*p+v*v),E=S>0?Math.acos(v/S)*vr:0;let R=j!==0||p!==0?Math.atan2(-p,-j)*vr+90:0;return R<0&&(R+=360),[S,R,E]},o.cQ=te,o.cR=Gn,o.cS=In,o.cT=me,o.cU=sl,o.cV=ue,o.cW=function(j){return[Math.pow(j[0],1/2.2),Math.pow(j[1],1/2.2),Math.pow(j[2],1/2.2)]},o.cX=kZe,o.cY=PTe,o.cZ=EZe,o.c_=uEe,o.ca=2,o.cb=7,o.cc=6,o.cd=Ne,o.ce=W,o.cf=G,o.cg=0,o.ch=1,o.ci=4,o.cj=5,o.ck=TO,o.cl=my,o.cm=CZe,o.cn=j6,o.co=sYe,o.cp=function(j,p,v,S,E,R,F,q,K){if(K.name==="globe")return sYe(j,p,new j6(v,S,E),!1);const J=E6({z:v,x:S,y:E},K);return new sl([(R+J.x/J.scale)*p,p*(J.y/J.scale),F],[(R+J.x2/J.scale)*p,p*(J.y2/J.scale),q])},o.cq=function(j,p,v){return j[0]=Math.min(p[0],v[0]),j[1]=Math.min(p[1],v[1]),j[2]=Math.min(p[2],v[2]),j[3]=Math.min(p[3],v[3]),j},o.cr=function(j,p,v){return j[0]=Math.max(p[0],v[0]),j[1]=Math.max(p[1],v[1]),j[2]=Math.max(p[2],v[2]),j[3]=Math.max(p[3],v[3]),j},o.cs=function(j){const p=Math.round((j+45+360)%360/90)%4;return Zn[p]},o.ct=vn,o.cu=st,o.cv=6,o.cw=function(j){const p=x(new Float64Array(16));b(p,j.pixelMatrix,j.globeMatrix);const v=[0,Qt,0],S=[0,gs,0];return Ge(v,v,p),Ge(S,S,p),[v[0]>0&&v[0]<=j.width&&v[1]>0&&v[1]<=j.height&&!eTe(j,new Cs(j.center.lat,90)),S[0]>0&&S[0]<=j.width&&S[1]>0&&S[1]<=j.height&&!eTe(j,new Cs(j.center.lat,-90))]},o.cx=function(j,p){const{scale:v}=j.tileTransform,S=v*sr/(j.tileSize*Math.pow(2,p.zoom-j.tileID.overscaledZ+j.tileID.canonical.z));return function(E,R,F){var q=R[1],K=R[2],J=R[3],le=F[0],fe=F[1];return E[0]=R[0]*le,E[1]=q*le,E[2]=K*fe,E[3]=J*fe,E}(new Float32Array(4),p.inverseAdjustmentMatrix,[S,S])},o.cy=bee,o.cz=V,o.d=function(j){return Ta.API_TILEJSON_REGEX.test(j)},o.d$=L$t,o.d0=Nd,o.d1=class{static calculate(j,p,v){const S=new Set,E=new Map,R=new Set,F=new Set;for(const K of Object.values(j))for(const[J,le]of Object.entries(K.floors)){R.add(J),le.isDefault&&F.add(J),le.conflicts&&E.set(J,le.conflicts);const fe=J===p,ye=le.connections&&p&&le.connections.has(p);(fe||ye)&&S.add(J)}const q=K=>{const J=E.get(K)||new Set;for(const le of S)if((E.get(le)||new Set).has(K)||J.has(le))return!0;return!1};if(v)for(const K of v)R.has(K)&&(q(K)||S.add(K));for(const K of F)S.has(K)||q(K)||S.add(K);return S}},o.d2=Mee,o.d3=QTe,o.d4=_i,o.d5=function(){return{API_URL:Ta.API_URL,DRACO_URL:Ta.DRACO_URL,MESHOPT_URL:Ta.MESHOPT_URL,MESHOPT_SIMD_URL:Ta.MESHOPT_SIMD_URL,BUILDING_GEN_URL:Ta.BUILDING_GEN_URL}},o.d6=ON,o.d7=Nb,o.d8=Jc,o.d9=xr,o.dA=QJ,o.dB=Mi,o.dC=Zd,o.dD=function(j,p){return[Math.pow(j[0],2.2)*p,Math.pow(j[1],2.2)*p,Math.pow(j[2],2.2)*p]},o.dE=h,o.dF=function(j,p){var v=Math.sin(p),S=Math.cos(p);return j[0]=S,j[1]=v,j[2]=0,j[3]=-v,j[4]=S,j[5]=0,j[6]=0,j[7]=0,j[8]=1,j},o.dG=Ce,o.dH=rYe,o.dI=oa,o.dJ=Ha,o.dK=cEe,o.dL=function(j,p){const v=[0,0,0];return Ge(v,v,Sq(WN(p.canonical))),Ge(v,v,j),v},o.dM=j=>({u_matrix:new w(j),u_texsize:new C1(j),u_pixels_to_tile_units:new U(j),u_device_pixel_ratio:new Nh(j),u_width_scale:new Nh(j),u_floor_width_scale:new Nh(j),u_image:new _6(j),u_units_to_pixels:new C1(j),u_tile_units_to_pixels:new Nh(j),u_alpha_discard_threshold:new Nh(j),u_trim_offset:new C1(j),u_trim_fade_range:new C1(j),u_trim_gradient_mix_range:new C1(j),u_trim_color:new CO(j),u_zbias_factor:new Nh(j),u_tile_to_meter:new Nh(j),u_ground_shadow_factor:new w6(j),u_pattern_transition:new Nh(j)}),o.dN=j=>({u_matrix:new w(j),u_pixels_to_tile_units:new U(j),u_device_pixel_ratio:new Nh(j),u_width_scale:new Nh(j),u_floor_width_scale:new Nh(j),u_units_to_pixels:new C1(j),u_dash_image:new _6(j),u_gradient_image:new _6(j),u_image_height:new Nh(j),u_texsize:new C1(j),u_tile_units_to_pixels:new Nh(j),u_alpha_discard_threshold:new Nh(j),u_trim_offset:new C1(j),u_trim_fade_range:new C1(j),u_trim_gradient_mix_range:new C1(j),u_trim_color:new CO(j),u_zbias_factor:new Nh(j),u_tile_to_meter:new Nh(j),u_ground_shadow_factor:new w6(j)}),o.dO=j=>({u_camera_to_center_distance:new Nh(j),u_extrude_scale:new U(j),u_device_pixel_ratio:new Nh(j),u_matrix:new w(j),u_inv_rot_matrix:new w(j),u_merc_center:new C1(j),u_tile_id:new w6(j),u_zoom_transition:new Nh(j),u_up_dir:new w6(j),u_emissive_strength:new Nh(j)}),o.dP=mq,o.dQ=Mqt,o.dR=class{constructor(j,p,v,S){this.context=j,this.format=S,this.size=v,this.texture=j.gl.createTexture();const[E,R,F]=this.size,{gl:q}=j;q.bindTexture(q.TEXTURE_3D,this.texture),j.pixelStoreUnpackFlipY.set(!1),j.pixelStoreUnpack.set(1),j.pixelStoreUnpackPremultiplyAlpha.set(!1),"data"in p&&p.data&&q.texImage3D(q.TEXTURE_3D,0,this.format,E,R,F,0,STe(this.format),CTe(this.format),p.data)}bind(j,p){const{context:v}=this,{gl:S}=v;S.bindTexture(S.TEXTURE_3D,this.texture),j!==this.minFilter&&(S.texParameteri(S.TEXTURE_3D,S.TEXTURE_MAG_FILTER,j),S.texParameteri(S.TEXTURE_3D,S.TEXTURE_MIN_FILTER,j),this.minFilter=j),p!==this.wrapS&&(S.texParameteri(S.TEXTURE_3D,S.TEXTURE_WRAP_S,p),S.texParameteri(S.TEXTURE_3D,S.TEXTURE_WRAP_T,p),this.wrapS=p)}destroy(){const{gl:j}=this.context;j.deleteTexture(this.texture),this.texture=null}},o.dS=lYe,o.dT=(j,p,v,S,E,R)=>{const F=j.transform,q=F.projection.name==="globe";let K;if(R.paint.get("circle-pitch-alignment")==="map")if(q){const le=rYe(F.zoom,p.canonical)*F._pixelsPerMercatorPixel;K=Float32Array.from([le,0,0,le])}else K=F.calculatePixelsToTileUnitsMatrix(v);else K=new Float32Array([F.pixelsToGLUnits[0],0,0,F.pixelsToGLUnits[1]]);const J={u_camera_to_center_distance:j.transform.getCameraToCenterDistance(F.projection),u_matrix:j.translatePosMatrix(p.projMatrix,v,R.paint.get("circle-translate"),R.paint.get("circle-translate-anchor")),u_device_pixel_ratio:Gd.devicePixelRatio,u_extrude_scale:K,u_inv_rot_matrix:F$t,u_merc_center:[0,0],u_tile_id:[0,0,0],u_zoom_transition:0,u_up_dir:[0,0,0],u_emissive_strength:R.paint.get("circle-emissive-strength")};if(q){J.u_inv_rot_matrix=S,J.u_merc_center=E,J.u_tile_id=[p.canonical.x,p.canonical.y,1<{const le=j.transform,fe=le.pitch<15?qZe(.07,.7,it((14-le.zoom)/5,0,1)):.07,ye=v.paint.get("line-trim-color-use-theme").constantOr("default")==="none";return{u_matrix:HZe(j,p,v,S),u_texsize:p.imageAtlasTexture?p.imageAtlasTexture.size:[0,0],u_pixels_to_tile_units:le.calculatePixelsToTileUnitsMatrix(p),u_device_pixel_ratio:E,u_width_scale:R,u_floor_width_scale:F,u_image:0,u_tile_units_to_pixels:VZe(p,le),u_units_to_pixels:[1/le.pixelsToGLUnits[0],1/le.pixelsToGLUnits[1]],u_alpha_discard_threshold:0,u_trim_offset:q,u_trim_fade_range:v.paint.get("line-trim-fade-range"),u_trim_gradient_mix_range:[1,1],u_trim_color:v.paint.get("line-trim-color").toPremultipliedRenderColor(ye?null:v.lut).toArray01(),u_zbias_factor:fe,u_tile_to_meter:In(p.tileID.canonical,0),u_ground_shadow_factor:K,u_pattern_transition:J}},o.dX=(j,p,v,S,E,R,F,q,K,J)=>{const le=j.transform,fe=le.calculatePixelsToTileUnitsMatrix(p),ye=v.paint.get("line-trim-color-use-theme").constantOr("default")==="none",Te=le.pitch<15?qZe(.07,.7,it((14-le.zoom)/5,0,1)):.07;return{u_matrix:HZe(j,p,v,S),u_pixels_to_tile_units:fe,u_device_pixel_ratio:R,u_width_scale:F,u_floor_width_scale:q,u_units_to_pixels:[1/le.pixelsToGLUnits[0],1/le.pixelsToGLUnits[1]],u_dash_image:0,u_gradient_image:1,u_image_height:E,u_texsize:WZe(v)&&p.lineAtlasTexture?p.lineAtlasTexture.size:[0,0],u_tile_units_to_pixels:VZe(p,j.transform),u_alpha_discard_threshold:0,u_trim_offset:K,u_trim_fade_range:v.paint.get("line-trim-fade-range"),u_trim_gradient_mix_range:[1,1],u_trim_color:v.paint.get("line-trim-color").toPremultipliedRenderColor(ye?null:v.lut).toArray01(),u_zbias_factor:Te,u_tile_to_meter:In(p.tileID.canonical,0),u_ground_shadow_factor:J}},o.dY=bs,o.dZ=Cq,o.d_=pn,o.da=function(j){const p=j.indexOf(lt);return p>=0?j.slice(0,p):j},o.db=function(j){return j.indexOf(lt)>=0},o.dc=function(j){const p=j.lastIndexOf(lt);return p>=0?j.slice(p+1):""},o.dd=function(j){const p=[],v=j.id;return v===void 0&&p.push({message:`layers.${v}: missing required property "id"`}),j.render===void 0&&p.push({message:`layers.${v}: missing required method "render"`}),j.renderingMode&&j.renderingMode!=="2d"&&j.renderingMode!=="3d"&&p.push({message:`layers.${v}: property "renderingMode" must be either "2d" or "3d"`}),p},o.de=function(j,p,v,S){return j.type==="custom"?new NVt(j,p):new TVt[j.type](j,p,v,S)},o.df=gn,o.dg=Q3,o.dh=Ps,o.di=class extends L6{constructor(j,p){super(j._vectorTileFeature,j._z,j._x,j._y,j.id),j.state&&(this.state=Object.assign({},j.state)),this.target=p.target,this.namespace=p.namespace,p.properties&&(this.properties=p.properties),this.target&&("featuresetId"in this.target&&!this.target.importId||"layerId"in this.target)&&(this.source=j.source,this.sourceLayer=j.sourceLayer,this.layer=j.layer)}toJSON(){const j=super.toJSON();return j.target=this.target,j.namespace=this.namespace,j}},o.dj=FN,o.dk=function(j){return j({pluginStatus:jd,pluginURL:Kp}),FN.on("pluginStateChange",j),j},o.dl=YAe,o.dm=class extends S1{constructor(j){super(j),this.current=C}set(j,p,v){if(this.fetchUniformLocation(j,p)){for(let S=0;S<9;S++)if(v[S]!==this.current[S]){this.current=v,this.gl.uniformMatrix3fv(this.location,!1,v);break}}}},o.dn=sa,o.dp=function(j,p,v){const S=jS(v.zoom),E=j.style.map._antialias,R=j.terrain&&j.terrain.exaggeration()>0;return S===0&&!E&&!R},o.dq=function(j){const p=j.pixelsPerMeter,v=p/Ks(1,j.center.lat),S=x(new Float64Array(16));return k(S,S,[j.point.x,j.point.y,0]),A(S,S,[v,v,p]),Float32Array.from(S)},o.dr=JJ,o.ds=function(j){const p=80.051129;j=it(j,-80.051129,p)/p*90;const v=Math.pow(Math.abs(Math.sin(Nr(j))),3);return Math.round(v*(ys.length-1))},o.dt=function(j,p,v,S){const E=p.getNorth(),R=p.getSouth(),F=p.getWest(),q=p.getEast(),K=1<0){const Pe=180/S;f(Te,Te,[Pe/J+1,0,0,0,Pe/le+1,0,-.5*Pe/fe,.5*Pe/ye,1])}return Te[2]=K,Te[5]=j.x,Te[8]=j.y,Te},o.du=Sq,o.dv=WN,o.dw=function(j,p,v){const S=x(new Float64Array(16)),E=(p/(1<0&&++this._updateTime,this._activeRegions=[],this._prevRegions=[]}get updateTime(){return this._updateTime}getReplacementRegionsForTile(j,p=!1){const v=UYe(new sn(0,0),new sn(sr,sr),j),S=[];if(p&&!fTe(v,this._globalClipBounds))return S;for(const E of this._activeRegions){if(E.hiddenByOverlap||!fTe(v,E))continue;const R=bUt(E.min,E.max,j);S.push({min:R.min,max:R.max,sourceId:this._sourceIds[E.priority],footprint:E.footprint,footprintTileId:E.tileId,order:E.order,clipMask:E.clipMask,clipScope:E.clipScope})}return S}setSources(j){this._setSources(j.map(p=>({getSourceId:()=>p.cache.id,getFootprints:()=>{const v=[];for(const S of p.cache.getVisibleCoordinates()){const E=p.cache.getTile(S).buckets[p.layer];E&&E.updateFootprints(S.toUnwrapped(),v)}return v},getOrder:()=>p.order,getClipMask:()=>p.clipMask,getClipScope:()=>p.clipScope})))}_addSource(j){const p=j.getFootprints();if(p.length===0)return;const v=j.getOrder(),S=j.getClipMask(),E=j.getClipScope();for(const R of p){if(!R.footprint)continue;const F=UYe(R.footprint.min,R.footprint.max,R.id);this._activeRegions.push({min:F.min,max:F.max,hiddenByOverlap:!1,priority:this._sourceIds.length,tileId:R.id,footprint:R.footprint,order:v,clipMask:S,clipScope:E})}this._sourceIds.push(j.getSourceId())}_computeReplacement(){this._activeRegions.sort((p,v)=>p.priority-v.priority||cee(p.min,v.min)||cee(p.max,v.max)||p.order-v.order||p.clipMask-v.clipMask||function(S,E){const R=(F,q)=>F+q;return S.length-E.length||S.reduce(R,"").localeCompare(E.reduce(R,""))}(p.clipScope,v.clipScope));let j=this._activeRegions.length!==this._prevRegions.length;if(!j){let p=0;for(;!j&&p!==this._activeRegions.length;){const v=this._activeRegions[p],S=this._prevRegions[p];j=v.priority!==S.priority||!$Ye(v,S)||v.order!==S.order||v.clipMask!==S.clipMask||!ki(v.clipScope,S.clipScope),this._activeRegions[p].hiddenByOverlap=S.hiddenByOverlap,++p}}if(j){++this._updateTime;for(const v of this._activeRegions)v.order!==Dq&&(this._globalClipBounds.min.x=Math.min(this._globalClipBounds.min.x,v.min.x),this._globalClipBounds.min.y=Math.min(this._globalClipBounds.min.y,v.min.y),this._globalClipBounds.max.x=Math.max(this._globalClipBounds.max.x,v.max.x),this._globalClipBounds.max.y=Math.max(this._globalClipBounds.max.y,v.max.y));const p=v=>{const S=this._activeRegions;if(v>=S.length)return v;const E=S[v].priority;for(;v1){let v=0,S=p(v);for(;v!==S;){let E=v;const R=v;for(;E!==S;){const F=this._activeRegions[E];F.hiddenByOverlap=!1;for(let q=0;q=0;p--)this._addSource(j[p]);this._computeReplacement()}},o.eH=Yi,o.eI=Uee,o.eJ=vS,o.eK=Dq,o.eL=class{constructor(j){this._createGrid(j),this._createPoles(j)}destroy(){this._poleIndexBuffer.destroy(),this._gridBuffer.destroy(),this._gridIndexBuffer.destroy(),this._poleNorthVertexBuffer.destroy(),this._poleSouthVertexBuffer.destroy();for(const j of this._poleSegments)j.destroy();for(const j of this._gridSegments)j.withSkirts.destroy(),j.withoutSkirts.destroy()}_fillGridMeshWithLods(j,p){const v=new Mi,S=new Zd,E=[],R=j+1+2,F=p[0]+1,q=p[0]+1+(1+p.length),K=(J,le,fe)=>{let ye=J===R-1?J-2:J===0?J:J-1;return ye+=fe?24575:0,[ye,le]};for(let J=0;J>>=0,j=Math.imul(2747636419^j,2654435769)>>>0,j=Math.imul(j^j>>>16,2654435769)>>>0,(j=Math.imul(j^j>>>16,2654435769)>>>0)/4294967296},o.ec=eYe,o.ed=QAe,o.ee=N1,o.ef=P,o.eg=function(j,p){return j[0]=p[0],j[1]=p[1],j[2]=p[2],j[3]=p[4],j[4]=p[5],j[5]=p[6],j[6]=p[8],j[7]=p[9],j[8]=p[10],j},o.eh=xS,o.ei=g6,o.ej=function(j,p,v,S,E){return it((j-p)/(v-p)*(E-S)+S,S,E)},o.ek=Kt,o.el=function(j,p){var v=p[0],S=p[1],E=p[2],R=p[3],F=p[4],q=p[5],K=p[6],J=p[7],le=p[8],fe=le*F-q*J,ye=-le*R+q*K,Te=J*R-F*K,Pe=v*fe+S*ye+E*Te;return Pe?(j[0]=fe*(Pe=1/Pe),j[1]=(-le*S+E*J)*Pe,j[2]=(q*S-E*F)*Pe,j[3]=ye*Pe,j[4]=(le*v-E*K)*Pe,j[5]=(-q*v+E*R)*Pe,j[6]=Te*Pe,j[7]=(-J*v+S*K)*Pe,j[8]=(F*v-S*R)*Pe,j):null},o.em=aa,o.en=2,o.eo=Ie,o.ep=Bt,o.eq=z,o.er=function(j,p){var v=new d(3);z(v,p);var S=1/v[0],E=1/v[1],R=1/v[2],F=p[0]*S,q=p[1]*E,K=p[2]*R,J=p[4]*S,le=p[5]*E,fe=p[6]*R,ye=p[8]*S,Te=p[9]*E,Pe=p[10]*R,Ue=F+le+Pe,Qe=0;return Ue>0?(Qe=2*Math.sqrt(Ue+1),j[3]=.25*Qe,j[0]=(fe-Te)/Qe,j[1]=(ye-K)/Qe,j[2]=(q-J)/Qe):F>le&&F>Pe?(Qe=2*Math.sqrt(1+F-le-Pe),j[3]=(fe-Te)/Qe,j[0]=.25*Qe,j[1]=(q+J)/Qe,j[2]=(ye+K)/Qe):le>Pe?(Qe=2*Math.sqrt(1+le-F-Pe),j[3]=(ye-K)/Qe,j[0]=(q+J)/Qe,j[1]=.25*Qe,j[2]=(fe+Te)/Qe):(Qe=2*Math.sqrt(1+Pe-F-le),j[3]=(q-J)/Qe,j[0]=(ye+K)/Qe,j[1]=(fe+Te)/Qe,j[2]=.25*Qe),j},o.es=function(j,p){var v=2*Math.acos(p[3]),S=Math.sin(v/2);return S>c?(j[0]=p[0]/S,j[1]=p[1]/S,j[2]=p[2]/S):(j[0]=1,j[1]=0,j[2]=0),v},o.et=pEe,o.eu=jee,o.ev=wee,o.ew=[1,1,1],o.ex=qO,o.ey=function(j,p,v,S){var E=p[0],R=p[1],F=p[2],q=p[3];return j[0]=E+S*(v[0]-E),j[1]=R+S*(v[1]-R),j[2]=F+S*(v[2]-F),j[3]=q+S*(v[3]-q),j},o.ez=DO,o.f=Ho,o.f0=iYe,o.f1=function(j){const p=[0,0,0],v=x(new Float64Array(16));return b(v,j.pixelMatrix,j.globeMatrix),Ge(p,p,v),new sn(p[0],p[1])},o.f2=f0,o.f3=function(j,p,v=!1){if(jd===Iu.deferred||jd===Iu.loading||jd===Iu.loaded)throw new Error("setRTLTextPlugin cannot be called multiple times.");Kp=Gd.resolveURL(j),jd=Iu.deferred,Yh=p,qj(),v||zN()},o.f4=mo,o.f5=Ra,o.f6=Wn,o.f7=function(j){const p=Sg();if(!p)return;const v=p.delete(Hm);j&&v.then(()=>j()).catch(j)},o.f8=pr,o.f9=aC,o.fA=ti,o.fB=function(j){let p=0;if(new Uint32Array(j,0,1)[0]!==bZe){const v=new Uint32Array(j,0,7),[,,S,E,R,F]=v;p=v.byteLength+E+R+F+R,(S!==j.byteLength||p>=j.byteLength)&&Er("Invalid b3dm header information.")}return NZe(j,p)},o.fC=function(j,p){const v=PTe(j);for(const S of v){for(const E of S.meshes)XUt(E);S.lights&&(S.lightMeshIndex=S.meshes.length,S.meshes.push(QUt(S.lights,p)))}return v},o.fD=Gee,o.fE=Jr,o.fF=Ig,o.fG=Iu,o.fH=function(j){Eo(),cu!=null&&cu.then(p=>{p.keys().then(v=>{for(let S=0;SEr(E.message))}).catch(v=>Er(v.message))}).catch(p=>Er(p.message))},o.fa=2,o.fb=xx,o.fc=E6,o.fd=vq,o.fe=dQe,o.ff=uQe,o.fg=zZe,o.fh=Ni,o.fi="hd_road_elevation",o.fj=Ql,o.fk=kn,o.fl=oee,o.fm=NS,o.fn=ZTe,o.fo=1,o.fp=Zj,o.fq=function(j,p,v,S,E,R,F,q=1,K,J,le,fe){j.createArrays(),j.tilePixelRatio=sr/(512*j.overscaling),j.compareText={},j.iconsNeedLinear=!1;const ye=j.layers[0].layout,Te=j.layers[0]._unevaluatedLayout._values,Pe={};Pe.scaleFactor=q,Pe.textSizeScaleRange=ye.get("text-size-scale-range"),Pe.iconSizeScaleRange=ye.get("icon-size-scale-range");const[Ue,Qe]=Pe.textSizeScaleRange,[at,pt]=Pe.iconSizeScaleRange;Pe.textScaleFactor=it(Pe.scaleFactor,Ue,Qe),Pe.iconScaleFactor=it(Pe.scaleFactor,at,pt);const dt=Te["text-size"],wt=Te["icon-size"];if(j.textSizeData.kind==="composite"){const{minZoom:rs,maxZoom:is}=j.textSizeData;Pe.compositeTextSizes=[dt.possiblyEvaluate(new xi(rs,{worldview:le}),R),dt.possiblyEvaluate(new xi(is,{worldview:le}),R)]}if(j.iconSizeData.kind==="composite"){const{minZoom:rs,maxZoom:is}=j.iconSizeData;Pe.compositeIconSizes=[wt.possiblyEvaluate(new xi(rs,{worldview:le}),R,fe),wt.possiblyEvaluate(new xi(is,{worldview:le}),R,fe)]}Pe.layoutTextSize=dt.possiblyEvaluate(new xi(F+1,{worldview:le}),R),Pe.layoutIconSize=wt.possiblyEvaluate(new xi(F+1,{worldview:le}),R,fe),Pe.textMaxSize=dt.possiblyEvaluate(new xi(18,{worldview:le}),R);const Tt=ye.get("symbol-placement"),Lt=ye.get("text-rotation-alignment")==="map"&&Tt!=="point",fs=ye.get("text-size");let Jt=!1;const ps=[];for(const rs of j.features){const is=ye.get("text-font").evaluate(rs,{},R).join(","),dn=fs.evaluate(rs,{},R)*Pe.textScaleFactor,fn=Pe.layoutTextSize.evaluate(rs,{},R)*Pe.textScaleFactor,_n=Pe.layoutIconSize.evaluate(rs,{},R,fe)*Pe.iconScaleFactor,Sn={horizontal:{},vertical:void 0},wn=rs.text;let Un,ln=[0,0];if(wn){const Ii=wn.toString(),kd=ye.get("text-letter-spacing").evaluate(rs,{},R)*wm,Jo=ye.get("text-line-height").evaluate(rs,{},R)*wm,Mo=uS(Ii)?kd:0,Hl=ye.get("text-anchor").evaluate(rs,{},R),pd=ye.get("text-variable-anchor");if(!pd){const Qd=ye.get("text-radial-offset").evaluate(rs,{},R);if(Qd)ln=NXe(Hl,[Qd*wm,eEe]);else{const Mf=ye.get("text-offset").evaluate(rs,{},R);ln=[Mf[0]*wm,Mf[1]*wm]}}let jm=Lt?"center":ye.get("text-justify").evaluate(rs,{},R);const fd=Tt==="point",Xd=fd?ye.get("text-max-width").evaluate(rs,{},R)*wm:1/0,Xu=Qd=>{j.allowVerticalPlacement&&Wp(Ii)&&(Sn.vertical=qTe(wn,p,v,E,is,Xd,Jo,Hl,Qd,Mo,ln,pv.vertical,!0,fn,dn,K,Pe.textScaleFactor))};if(!Lt&&pd){const Qd=jm==="auto"?pd.map(Nm=>tEe(Nm)):[jm];let Mf=!1;for(let Nm=0;Nm=0||!Wp(Ii)){const Qd=qTe(wn,p,v,E,is,Xd,Jo,Hl,jm,Mo,ln,pv.horizontal,!1,fn,dn,K,Pe.textScaleFactor);Qd&&(Sn.horizontal[jm]=Qd)}Xu(fd?"left":jm)}}let Nn,Tn,Vn,ar,zr,yr,gr=!1;const ir=ye.get("icon-text-fit").evaluate(rs,{},R);if(rs.icon&&rs.icon.hasPrimary()){const Ii=Zq(rs.icon,j.iconSizeData,Te["icon-size"],R,j.zoom,rs,K,Pe.iconScaleFactor,le,fe);Nn=Ii.iconPrimary,Vn=Ii.iconSecondary;const kd=Nn.toString();if(Tn=S.get(kd),Tn&&(zr=ye.get("icon-offset").evaluate(rs,{},R),yr=ye.get("icon-anchor").evaluate(rs,{},R),Un=Tee(E.get(kd),Vn?E.get(Vn.toString()):void 0,zr,yr),gr=Tn.sdf,j.sdfIcons===void 0?j.sdfIcons=Tn.sdf:j.sdfIcons!==Tn.sdf&&Er("Style sheet warning: Cannot mix SDF and non-SDF icons in one buffer"),(Tn.pixelRatio!==j.pixelRatio||ye.get("icon-rotate").constantOr(1)!==0)&&(j.iconsNeedLinear=!0)),Vn){const Jo=Vn.toString();ar=S.get(Jo)}}Jt=Jt||!(!rs.icon||!rs.icon.hasSecondary());const Dr=Ree(Sn.horizontal)||Sn.vertical;j.iconsInText||(j.iconsInText=!!Dr&&Dr.iconsInText);const Zr=fn*Pe.textScaleFactor/wm,{defaultShapedIcon:Aa,verticallyShapedIcon:ma}=lVt(j,Un,ye,rs,R,Sn,Zr,zr,ir);ir!=="none"&&Un&&(iXe(Un)||oXe(Un))&&(Dee(0,Tn,Nn,Un,Aa,ir,J,S,E),Dee(0,ar,Vn,Un,Aa,ir,J,S,E),ma&&(Dee(0,Tn,Nn,Un,ma,ir,J,S,E),Dee(0,ar,Vn,Un,ma,ir,J,S,E))),Un=Aa;const{iconBBox:mi,iconVerticalBBox:bo,textBBox:pi,textVerticalBBox:ko}=nVt(j,Un,ma,ye,rs,R,_n,zr,Pe,E,yr,Sn,fn,ln,fe);ps.push({feature:rs,shapedTextOrientations:Sn,shapedText:Dr,shapedIcon:Un,iconPrimary:Nn,iconSecondary:Vn,iconOffset:zr,iconAnchor:yr,verticallyShapedIcon:ma,layoutTextSize:fn,layoutIconSize:_n,textOffset:ln,isSDFIcon:gr,iconTextFit:ir,iconCollisionBounds:mi,iconVerticalCollisionBounds:bo,textCollisionBounds:pi,textVerticalCollisionBounds:ko})}return{featureData:ps,sizes:Pe,hasAnySecondaryIcon:Jt,textAlongLine:Lt,symbolPlacement:Tt}},o.fr=XTe,o.fs=YTe,o.ft=gXe,o.fu=xXe,o.fv=function(j,p,v,S,E,R,F,q,K,J){j.iconAtlasPositions=J.iconPositions;const{featureData:le,hasAnySecondaryIcon:fe,sizes:ye,textAlongLine:Te,symbolPlacement:Pe}=p;for(const Ue of le){const{shapedIcon:Qe,verticallyShapedIcon:at,feature:pt,shapedTextOrientations:dt,shapedText:wt,layoutTextSize:Tt,textOffset:Lt,isSDFIcon:fs,iconPrimary:Jt,iconSecondary:ps,iconTextFit:rs,iconOffset:is,iconCollisionBounds:dn,iconVerticalCollisionBounds:fn,textCollisionBounds:_n}=Ue;AXe(Qe,J.iconPositions,Jt,ps),AXe(at,J.iconPositions,Jt,ps),oVt(dt,J.iconPositions),iVt(Jt,ps,J.iconPositions),(wt||Qe)&&cVt(j,pt,dt,Qe,at,K,ye,Tt,0,Lt,fs,S,E,F,q,fe,rs,is,Te,Pe,dn,fn,_n)}v&&j.generateCollisionDebugBuffers(R,j.collisionBoxArray,ye.textScaleFactor)},o.fw=See,o.fx=Bo,o.fy=function(j){return j<=1?1:Math.pow(2,Math.floor(Math.log2(j)))},o.fz=Qee,o.g=Ta,o.h=function(j,p){return Ym(Object.assign(j,{method:"GET"}),p)},o.i=function(j){return Ta.API_STYLE_REGEX.test(j)&&!No(j)},o.j=function(j){return btoa(encodeURIComponent(j).replace(/%([0-9A-F]{2})/g,(p,v)=>String.fromCharCode(+("0x"+v))))},o.k=Gm,o.l=function(j){return decodeURIComponent(atob(j).split("").map(p=>"%"+("00"+p.charCodeAt(0).toString(16)).slice(-2)).join(""))},o.m=function(j,p){return Ym(Object.assign(j,{type:"json"}),p)},o.n=mm,o.o=Gd,o.p=function(j,p){return Ym(Object.assign(j,{method:"POST"}),p)},o.q=rg,o.r=Ms,o.s=function(j){try{const p=self[j];return p.setItem("_mapbox_test_",1),p.removeItem("_mapbox_test_"),!0}catch{return!1}},o.t=Ut,o.u=function(){return function j(p){return p?(p^Math.random()*(16>>p/4)).toString(16):([1e7]+-[1e3]+-4e3+-8e3+-1e11).replace(/[018]/g,j)}()},o.v=function(j){return!!j&&/^[0-9a-f]{8}-[0-9a-f]{4}-[4][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(j)},o.w=Er,o.x=class{constructor(j){this.cache=new Map,this.textures=new Map,this.textureAccessTimes=new Map,this.textureMemoryUsed=0,this.maxTextureMemory=1024*(j&&j.maxTextureMemoryMB?j.maxTextureMemoryMB:256)*1024,this.finalizationRegistry=new FinalizationRegistry(p=>{this.cache.delete(p),this.clearExpiredTextures()})}calculateTextureMemory(j){return j.image?Math.ceil(j.image.width*j.image.height*4*(j.patternPositions.size>0?1.33:1)):0}evictTexture(j){const p=this.textures.get(j);if(p){const v=this.calculateTextureMemory(j);p.destroy(),this.textures.delete(j),this.textureAccessTimes.delete(j),this.textureMemoryUsed-=v}}evictTexturesIfNeeded(j){for(;this.textureMemoryUsed+j>this.maxTextureMemory&&this.textures.size>0;){let p=null,v=1/0;for(const[S]of this.textures.entries()){const E=this.textureAccessTimes.get(S)||0;Ethis._layers[xr.id]),Ms=es[0];if(Ms.visibility==="none")continue;const bs=Ms.source||"";let Zs=this.familiesBySource[bs];Zs||(Zs=this.familiesBySource[bs]=Object.create(null));const kn=Ms.sourceLayer||"_geojsonTileLayer";let gn=Zs[kn];gn||(gn=Zs[kn]=[]),gn.push(es)}}}const g=1*c.fa;class y{constructor(Ve){const it={},ft=[];for(const Ms in Ve){const bs=Ve[Ms],Zs=it[Ms]={};for(const kn in bs.glyphs){const gn=bs.glyphs[+kn];if(!gn||gn.bitmap.width===0||gn.bitmap.height===0)continue;const xr=gn.metrics.localGlyph?g:1,Kr={x:0,y:0,w:gn.bitmap.width+2*xr,h:gn.bitmap.height+2*xr};ft.push(Kr),Zs[kn]=Kr}}const{w:kt,h:Ut}=c.J(ft),es=new c.f9({width:kt||1,height:Ut||1});for(const Ms in Ve){const bs=Ve[Ms];for(const Zs in bs.glyphs){const kn=bs.glyphs[+Zs];if(!kn||kn.bitmap.width===0||kn.bitmap.height===0)continue;const gn=it[Ms][Zs],xr=kn.metrics.localGlyph?g:1;c.f9.copy(kn.bitmap,es,{x:0,y:0},{x:gn.x+xr,y:gn.y+xr},kn.bitmap)}}this.image=es,this.positions=it}}function x(xs,Ve,it){xs[Ve]?it&&(xs[Ve].center=it):xs[Ve]={floorIds:new Set,center:it||[0,0],floors:{}}}function _(xs,Ve,it,ft){for(const kt of Ve)x(xs,kt),xs[kt].floors[it]=ft,xs[kt].floorIds.add(it)}function b(xs){return{id:xs.properties.id.toString(),center:[xs.properties.center_lon||0,xs.properties.center_lat||0]}}function k(xs,Ve){const it=xs.properties.id.toString(),ft=!!xs.properties.is_default&&xs.properties.is_default,kt=xs.properties.connected_floor_ids?new Set(xs.properties.connected_floor_ids.toString().split(";")):new Set,Ut=xs.properties.conflicted_floor_ids?new Set(xs.properties.conflicted_floor_ids.toString().split(";")):new Set,es=xs.properties.structure_ids?new Set(xs.properties.structure_ids.toString().split(";")):new Set,Ms=xs.properties.name.toString(),bs=xs.properties.z_index,Zs=function(kn,gn){const xr=kn.loadGeometry();if(!xr||xr.length===0)return;const Kr=xr.map(ca=>ca.map(Er=>c.fb(Er,gn,kn.extent)));return Kr.length===0?void 0:{type:"Polygon",coordinates:[Kr[0]]}}(xs,Ve);return{id:it,isDefault:ft,connections:kt,conflicts:Ut,buildings:es,name:Ms,zIndex:bs,geometry:Zs}}function A(xs,Ve){return Ve.every(it=>xs.properties&&xs.properties[it]!=null)}function T(xs){return A(xs,["type","id","name"])&&xs.properties.type==="structure"}function P(xs){return A(xs,["type","id","name","z_index"])&&xs.properties.type==="floor"}c.f8(y,"GlyphAtlas");class I{constructor(Ve){this.tileID=new c.aR(Ve.tileID.overscaledZ,Ve.tileID.wrap,Ve.tileID.canonical.z,Ve.tileID.canonical.x,Ve.tileID.canonical.y),this.tileZoom=Ve.tileZoom,this.uid=Ve.uid,this.zoom=Ve.zoom,this.lut=Ve.lut,this.canonical=Ve.tileID.canonical,this.pixelRatio=Ve.pixelRatio,this.tileSize=Ve.tileSize,this.source=Ve.source,this.scope=Ve.scope,this.overscaling=this.tileID.overscaleFactor(),this.showCollisionBoxes=Ve.showCollisionBoxes,this.collectResourceTiming=!!Ve.request&&Ve.request.collectResourceTiming,this.promoteId=Ve.promoteId,this.renderSourceType=Ve.renderSourceType,this.tileTransform=c.fc(Ve.tileID.canonical,Ve.projection),this.projection=Ve.projection,this.worldview=Ve.worldview,this.localizableLayerIds=Ve.localizableLayerIds,this.brightness=Ve.brightness,this.extraShadowCaster=!!Ve.extraShadowCaster,this.tessellationStep=Ve.tessellationStep,this.scaleFactor=Ve.scaleFactor,this.worldview=Ve.worldview,this.indoor=Ve.indoor}parse(Ve,it,ft,kt,Ut,es){this.status="parsing",this.data=Ve,this.collisionBoxArray=new c.fd;const Ms=new c.fe(Object.keys(Ve.layers).sort()),bs=new c.ff(this.tileID,this.promoteId);bs.bucketLayerIDs=[];const Zs={},kn=new c.fg(256,256),gn={featureIndex:bs,iconDependencies:new Map,patternDependencies:new Map,glyphDependencies:{},lineAtlas:kn,availableImages:ft,brightness:this.brightness,scaleFactor:this.scaleFactor,elevationFeatures:void 0,activeFloors:void 0};this.indoor&&(gn.activeFloors=function(Er,qr,Xt,Gn){const Jr=qr.indoorState.activeFloorsVisible;if(!qr.sourceLayers)return Jr?qr.indoorState.activeFloors:void 0;const Or=function(dr,Wi){if(!dr)return c.w("No source layers defined in indoor specification"),Wi;if(dr.size===0)return Wi;const ho=dr.difference(Wi);for(const oa of ho)c.w(`Missing source layer required in indoor specification: ${oa}`);return Wi.intersection(Wi)}(qr.sourceLayers,new Set(Object.keys(Er.layers))),ja=qr.indoorState,ea=function(dr,Wi,ho,oa,Ha){const $i={};for(const Ta of Wi){const Wn=dr.layers[Ta];if(Wn)for(let Ra=0;Ra=oa.maxzoom||oa.visibility==="none")continue;M(ho,this.zoom,gn.brightness,ft,this.worldview,gn.activeFloors);const Ha=Zs[oa.id]=oa.createBucket({index:bs.bucketLayerIDs.length,layers:ho,zoom:this.zoom,lut:this.lut,canonical:this.canonical,pixelRatio:this.pixelRatio,overscaling:this.overscaling,collisionBoxArray:this.collisionBoxArray,sourceLayerIndex:ja,sourceID:this.source,projection:this.projection.spec,tessellationStep:this.tessellationStep,styleDefinedModelURLs:kt,worldview:this.worldview,localizable:dr,availableImages:ft,maxUniformBufferBindings:this.maxUniformBufferBindings,maxUniformBlockSizeDwords:this.maxUniformBlockSizeDwords,disableSymbolUBO:this.disableSymbolUBO});bs.bucketLayerIDs.push(ho.map(Ta=>c.F(Ta.id,Ta.scope)));let $i=Ha.prepare?Ha.prepare():null;$i!=null?($i=$i.then(()=>Ha.populate(ea,gn,this.tileID.canonical,this.tileTransform)),xr.push($i)):Ha.populate(ea,gn,this.tileID.canonical,this.tileTransform)}}const ca=()=>{kn.trim();const Er=!(!gn.elevationFeatures||!gn.elevationFeatures.some(oa=>oa.heightRange.min<0));let qr,Xt,Gn,Jr,Or,ja,ea;const dr={type:"maybePrepare",renderSourceType:this.renderSourceType,zoom:this.zoom},Wi=()=>{if(qr)return this.status="done",es(qr);if(this.extraShadowCaster)this.status="done",es(null,{buckets:Object.values(Zs).filter(oa=>!oa.isEmpty()),featureIndex:bs,collisionBoxArray:null,hasTunnelGeometry:Er,glyphAtlasImage:null,lineAtlas:null,imageAtlas:null,brightness:gn.brightness,glyphMap:null,iconMap:null,glyphPositions:null});else if(Xt&&Gn&&Jr&&ea){const Ha=new y(Xt),$i=new Map;for(const[Ra,mo]of Gn.entries()){const{imagePosition:Ho}=c.fn(Ra,mo,c.fo);$i.set(Ra,Ho)}const Ta={};for(const Ra in Zs){const mo=Zs[Ra];mo instanceof c.fp&&(M(mo.layers,this.zoom,gn.brightness,ft,this.worldview,gn.activeFloors),Ta[Ra]=c.fq(mo,Xt,Ha.positions,Gn,$i,this.tileID.canonical,this.tileZoom,this.scaleFactor,this.pixelRatio,Or,this.worldview,ft))}const Wn={iconsPending:!0,patternsPending:!0};this.rasterizeIfNeeded(Ut,Gn,Or,()=>{Wn.iconsPending=!1,ho(Ta,Ha,Wn,void 0,ea)}),this.rasterizeIfNeeded(Ut,Jr,ja,()=>{Wn.patternsPending=!1,ho(Ta,Ha,Wn,void 0,ea)})}},ho=(oa,Ha,$i,Ta,Wn)=>{if($i.iconsPending||$i.patternsPending)return;const Ra=Gn.size>0||Jr.size>0,mo=Object.keys(oa).length>0;if(!Ra&&!mo)return this.status="done",void es(null,{buckets:Object.values(Zs).filter(No=>!No.isEmpty()),featureIndex:bs,collisionBoxArray:this.collisionBoxArray,hasTunnelGeometry:Er,glyphAtlasImage:Ha.image,lineAtlas:kn,imageAtlas:null,brightness:gn.brightness});const Ho=(No,Go)=>{for(const Dd in Zs){const Tu=Zs[Dd];if(Dd in oa)c.fv(Tu,oa[Dd],this.showCollisionBoxes,ft,this.tileID.canonical,this.tileZoom,this.projection,this.brightness,Gn,Go);else if(Tu.hasPattern&&(Tu instanceof c.fw||Tu instanceof c.fl||Tu instanceof c.e0)){M(Tu.layers,this.zoom,gn.brightness,ft,this.worldview,gn.activeFloors);const Vm=Object.fromEntries(Go.patternPositions);Tu.addFeatures(gn,this.tileID.canonical,Vm,ft,this.tileTransform,this.brightness)}}this.status="done",es(null,{buckets:Object.values(Zs).filter(Dd=>!Dd.isEmpty()),featureIndex:bs,collisionBoxArray:this.collisionBoxArray,hasTunnelGeometry:Er,glyphAtlasImage:Ha.image,lineAtlas:kn,imageAtlas:No,brightness:gn.brightness})};if(Ra){const No=new Map,Go=c.fr(Gn,No),Dd=c.fr(Jr,No),Tu=new c.fs(Go,Dd,Wn,this.lut,No);Ut.send("checkAtlasCache",{descriptor:Tu,scope:this.scope},(Vm,Uc)=>{let Eu,Ec;if(Vm&&c.w(`[Worker] Error checking atlas cache: ${Vm.message}`),Uc)Eu=new c.ft(Uc.sourceHash),Ec=Uc;else{const Gd=new c.fu(Gn,Jr,this.lut,Wn);Eu=Gd,Ec=Gd}Ho(Eu,Ec)})}else Ho(null,{iconPositions:new Map,patternPositions:new Map})};if(!this.extraShadowCaster){const oa=c.fk(gn.glyphDependencies,Ta=>Object.keys(Ta).map(Number));Object.keys(oa).length?Ut.send("getGlyphs",{uid:this.uid,stacks:oa},(Ta,Wn)=>{qr||(qr=Ta,Xt=Wn,Wi())},void 0,!1,dr):Xt={},ea=new Map;const Ha=Array.from(gn.iconDependencies.keys()).map(Ta=>c.I.parse(Ta));Ha.length?Ut.send("getImages",{images:Ha,source:this.source,scope:this.scope,tileID:this.tileID,type:"icons"},(Ta,Wn)=>{if(!qr){qr=Ta,Gn=new Map,Or=this.updateImageMapAndGetImageTaskQueue(Gn,Wn.images,gn.iconDependencies);for(const[Ra,mo]of Wn.versions.entries())ea.set(Ra,mo);Wi()}},void 0,!1,dr):(Gn=new Map,Or=new Map);const $i=Array.from(gn.patternDependencies.keys()).map(Ta=>c.I.parse(Ta));$i.length?Ut.send("getImages",{images:$i,source:this.source,scope:this.scope,tileID:this.tileID,type:"patterns"},(Ta,Wn)=>{if(!qr){qr=Ta,Jr=new Map,ja=this.updateImageMapAndGetImageTaskQueue(Jr,Wn.images,gn.patternDependencies);for(const[Ra,mo]of Wn.versions.entries())ea.set(Ra,mo);Wi()}},void 0,!1,dr):(Jr=new Map,ja=new Map)}if(gn.elevationFeatures&&gn.elevationFeatures.length>0){const oa=[];for(const $i of Object.values(Zs))if($i instanceof c.fl){const Ta=$i.getUnevaluatedPortalGraph();Ta&&oa.push(Ta)}const Ha=c.fm.evaluate(oa);for(const $i of Object.values(Zs))if($i instanceof c.fl){const Ta=Ve.layers[Ms.decode($i.sourceLayerIndex)];$i.setEvaluatedPortalGraph(Ha,Ta,this.tileID.canonical,gn.availableImages,gn.brightness)}}Wi()};xr.length>0?Promise.allSettled(xr).then(ca).catch(es):ca()}updateParameters(Ve){this.scaleFactor=Ve.scaleFactor,this.showCollisionBoxes=Ve.showCollisionBoxes,this.projection=Ve.projection,this.brightness=Ve.brightness,this.tileTransform=c.fc(Ve.tileID.canonical,Ve.projection),this.extraShadowCaster=Ve.extraShadowCaster,this.lut=Ve.lut,this.worldview=Ve.worldview,this.indoor=Ve.indoor}rasterizeIfNeeded(Ve,it,ft,kt){Array.from(it.values()).some(Ut=>Ut.usvg)?this.rasterize(Ve,it,ft,kt):kt()}updateImageMapAndGetImageTaskQueue(Ve,it,ft){const kt=new Map;for(const Ut of it.keys()){const es=ft.get(Ut)||[];for(const Ms of es){const bs=Ms.toString(),Zs=it.get(Ms.id.toString());Zs.usvg?kt.has(bs)||(kt.set(bs,Ms),Ve.set(bs,Object.assign({},Zs))):Ve.set(bs,Zs)}}return kt}rasterize(Ve,it,ft,kt){this.rasterizeTask=Ve.send("rasterizeImages",{scope:this.scope,tasks:ft},(Ut,es)=>{if(!Ut)for(const[Ms,bs]of es.entries()){const Zs=Object.assign(it.get(Ms),{data:bs});it.set(Ms,Zs)}kt()})}cancelRasterize(){this.rasterizeTask&&this.rasterizeTask.cancel()}}function M(xs,Ve,it,ft,kt,Ut){const es=new c.ae(Ve,{brightness:it,worldview:kt,activeFloors:Ut});for(const Ms of xs)Ms.recalculate(es,ft)}class L extends c.E{constructor({actor:Ve,layerIndex:it,availableImages:ft,availableModels:kt,isSpriteLoaded:Ut,tileProvider:es,brightness:Ms,maxUniformBufferBindings:bs,maxUniformBlockSizeDwords:Zs,disableSymbolUBO:kn}){super(),this.actor=Ve,this.layerIndex=it,this.availableImages=ft,this.availableModels=kt,this.loadVectorData=c.aO,this.tileProvider=es,this.loading={},this.loaded={},this.deduped=new c.aN(Ve.scheduler),this.isSpriteLoaded=Ut,this.scheduler=Ve.scheduler,this.brightness=Ms,this.maxUniformBufferBindings=bs,this.maxUniformBlockSizeDwords=Zs,this.disableSymbolUBO=kn}loadTileData(Ve,it){if(!this.tileProvider)return this.loadVectorData(Ve,it);const ft=new AbortController,{z:kt,x:Ut,y:es}=Ve.tileID.canonical;return this.tileProvider.loadTile({z:kt,x:Ut,y:es},{request:Ve.request,signal:ft.signal}).then(Ms=>{if(ft.signal.aborted)return;if(Ms==null){const Zs=new Error("Tile not found");return Zs.status=404,it(Zs)}if(Ms.data===null)return it(null,null);const bs=new Map;Ms.expires&&bs.set("expires",Ms.expires),Ms.cacheControl&&bs.set("cache-control",Ms.cacheControl),it(null,{rawData:Ms.data,responseHeaders:bs})}).catch(Ms=>{ft.signal.aborted||it(Ms instanceof Error?Ms:new Error(String(Ms)))}),()=>ft.abort()}loadTile(Ve,it){const ft=Ve.uid,kt=Ve&&Ve.request,Ut=kt&&kt.collectResourceTiming,es=this.loading[ft]=new I(Ve);es.maxUniformBufferBindings=this.maxUniformBufferBindings,es.maxUniformBlockSizeDwords=this.maxUniformBlockSizeDwords,es.disableSymbolUBO=this.disableSymbolUBO,es.abort=this.loadTileData(Ve,(Ms,bs)=>{const Zs=!this.loading[ft];if(delete this.loading[ft],es.cancelRasterize(),Zs||Ms||!bs)return es.status="done",Zs||(this.loaded[ft]=es),it(Ms);const kn=bs.rawData,gn={},xr=c.aP(bs.responseHeaders);xr&&xr.expires&&(gn.expires=xr.expires),xr&&xr.cacheControl&&(gn.cacheControl=xr.cacheControl),es.vectorTile=bs.vectorTile||new c.fx(new c.a$(kn));const Kr=()=>{es.parse(es.vectorTile,this.layerIndex,this.availableImages,this.availableModels,this.actor,(ca,Er)=>{if(ca||!Er)return it(ca);const qr={};if(Ut){const Xt=d(kt);Xt.length>0&&(qr.resourceTiming=JSON.parse(JSON.stringify(Xt)))}it(null,Object.assign({rawTileData:kn.slice(0),responseHeaders:bs.responseHeaders},Er,gn,qr))})};this.isSpriteLoaded?Kr():this.once("isSpriteLoaded",()=>{this.scheduler?this.scheduler.add(Kr,{type:"parseTile",renderSourceType:Ve.renderSourceType,zoom:Ve.tileZoom}):Kr()}),this.loaded=this.loaded||{},this.loaded[ft]=es})}reloadTile(Ve,it){const ft=this.loaded,kt=Ve.uid;if(ft&&ft[kt]){const Ut=ft[kt];Ut.updateParameters(Ve);const es=(Ms,bs)=>{const Zs=Ut.reloadCallback;Zs&&(delete Ut.reloadCallback,Ut.parse(Ut.vectorTile,this.layerIndex,this.availableImages,this.availableModels,this.actor,Zs)),it(Ms,bs)};Ut.status==="parsing"?Ut.reloadCallback=es:Ut.status==="done"&&(Ut.vectorTile?Ut.parse(Ut.vectorTile,this.layerIndex,this.availableImages,this.availableModels,this.actor,es):es())}else it(null,void 0)}abortTile(Ve,it){const ft=Ve.uid,kt=this.loading[ft];kt&&(kt.abort&&kt.abort(),delete this.loading[ft]),it()}removeTile(Ve,it){const ft=this.loaded,kt=Ve.uid;ft&&ft[kt]&&delete ft[kt],it()}}class z{constructor(Ve){this.loading={}}loadTile(Ve,it){const ft=Ve.uid,{cancel:kt}=c.b1(Ve.request,(Ut,es,Ms)=>{const bs=!this.loading[ft];if(delete this.loading[ft],bs||Ut||!es)return it(Ut);this.decodeTile(ft,es,Ve.encoding).then(Zs=>{const{expires:kn,cacheControl:gn}=c.aP(Ms);it(null,Object.assign(Zs,{expires:kn,cacheControl:gn}))}).catch(Zs=>it(Zs))});this.loading[ft]={cancel:kt}}async decodeTile(Ve,it,ft){const kt=await createImageBitmap(new Blob([new Uint8Array(it)],{type:"image/png"})),Ut=1-(kt.width-c.fy(kt.width))/2,es=Ut<1,Ms=this.getImageData(kt,Ut);return kt.close(),{dem:new c.fz(Ve,Ms,ft,es),borderReady:es}}reloadTile(Ve,it){it(null,null)}abortTile(Ve,it){const ft=Ve.uid,kt=this.loading[ft];kt&&(kt.cancel(),delete this.loading[ft]),it()}removeTile(Ve,it){it()}getImageData(Ve,it){this.offscreenCanvas&&this.offscreenCanvasContext||(this.offscreenCanvas=new OffscreenCanvas(Ve.width,Ve.height),this.offscreenCanvasContext=this.offscreenCanvas.getContext("2d",{willReadFrequently:!0})),this.offscreenCanvas.width=Ve.width,this.offscreenCanvas.height=Ve.height,this.offscreenCanvasContext.drawImage(Ve,0,0,Ve.width,Ve.height);const ft=this.offscreenCanvasContext.getImageData(-it,-it,Ve.width+2*it,Ve.height+2*it);return this.offscreenCanvasContext.clearRect(0,0,this.offscreenCanvas.width,this.offscreenCanvas.height),ft}}c.a_.setPbf(c.a$);class ${constructor(Ve){this._mrt=new c.a_(Ve.partial?30:1/0),this._isHeaderLoaded=!1,this.uid=Ve.uid,this.tileID=Ve.tileID,this.source=Ve.source}parse(Ve,it){const ft=this._mrt;this.status="parsing",this._entireBuffer=Ve;try{ft.parseHeader(Ve),this._isHeaderLoaded=!0;const kt=[];for(const Ut in ft.layers){const es=ft.getLayer(Ut),Ms=es.getDataRange(es.getBandList()),bs=ft.createDecodingTask(Ms),Zs=Ve.slice(Ms.firstByte,Ms.lastByte+1),kn=c.a_.performDecoding(Zs,bs).then(gn=>bs.complete(null,gn)).catch(gn=>bs.complete(gn,null));kt.push(kn)}Promise.allSettled(kt).then(()=>it(null,ft)).catch(Ut=>it(Ut))}catch(kt){it(kt)}}}class V{constructor({actor:Ve}){this.actor=Ve,this.loading={},this.loaded={}}loadTile(Ve,it){const ft=Ve.uid,kt=Ve.request,Ut=this.loading[ft]=new $(Ve),{cancel:es}=c.b1(kt,(Ms,bs,Zs)=>{const kn=!this.loading[ft];if(delete this.loading[ft],kn||Ms||!bs)return Ut.status="done",kn||(this.loaded[ft]=Ut),it(Ms);Ut.parse(bs,(gn,xr)=>{if(gn||!xr)return it(gn);it(null,xr,Zs)}),this.loaded[ft]=Ut});Ut.abort=es}reloadTile(Ve,it){it(null,void 0)}abortTile(Ve,it){const ft=Ve.uid,kt=this.loading[ft];kt&&(kt.abort&&kt.abort(),delete this.loading[ft]),it()}removeTile(Ve,it){const ft=Ve.uid;this.loaded[ft]&&delete this.loaded[ft],it()}decodeRasterArray(Ve,it){c.a_.performDecoding(Ve.buffer,Ve.task).then(ft=>it(null,ft)).catch(ft=>it(ft))}}const W=c.fA.prototype.toGeoJSON;class G{constructor(Ve){this._feature=Ve,this.extent=c.an,this.type=Ve.type,this.properties=Ve.tags,"id"in Ve&&!isNaN(Ve.id)&&(this.id=parseInt(Ve.id,10))}loadGeometry(){if(this._feature.type===1){const Ve=[];for(const it of this._feature.geometry)Ve.push([new c.P(it[0],it[1])]);return Ve}{const Ve=[];for(const it of this._feature.geometry){const ft=[];for(const kt of it)ft.push(new c.P(kt[0],kt[1]));Ve.push(ft)}return Ve}}toGeoJSON(Ve,it,ft){return W.call(this,Ve,it,ft)}}class X{constructor(Ve,it){this.name=Ve,this.extent=c.an,this.length=it.length,this._jsonFeatures=it}feature(Ve){return new G(this._jsonFeatures[Ve])}}class te{constructor(Ve){this.layers={},this.extent=c.an;for(const it of Object.keys(Ve))this.layers[it]=new X(it,Ve[it])}}const ne=64/4096;class me{constructor(){this.features=new Map}clear(){this.features.clear()}load(Ve=[],it){for(const ft of Ve){const kt=ft.id;if(kt==null)continue;let Ut=this.features.get(kt);Ut&&this.updateCache(Ut,it),ft.geometry?(Ut=ce(ft),this.updateCache(Ut,it),this.features.set(kt,Ut)):this.features.delete(kt),this.updateCache(Ut,it)}}updateCache(Ve,it){for(const{canonical:ft,uid:kt}of Object.values(it)){const{z:Ut,x:es,y:Ms}=ft;ue(Ve,Math.pow(2,Ut),es,Ms)&&delete it[kt]}}getTile(Ve,it,ft){const kt=Math.pow(2,Ve),Ut=[];for(const es of this.features.values())ue(es,kt,it,ft)&&Ut.push(ve(es,kt,it,ft));return{features:Ut}}getFeatures(){return[...this.features.values()]}}function ue({minX:xs,minY:Ve,maxX:it,maxY:ft},kt,Ut,es){return xs<(Ut+1+ne)/kt&&Ve<(es+1+ne)/kt&&it>(Ut-ne)/kt&&ft>(es-ne)/kt}function ce(xs){const{id:Ve,geometry:it,properties:ft}=xs;if(!it)return;if(it.type==="GeometryCollection")throw new Error("GeometryCollection not supported in dynamic mode.");const{type:kt,coordinates:Ut}=it,es={id:Ve,type:1,geometry:[],tags:ft,minX:1/0,minY:1/0,maxX:-1/0,maxY:-1/0},Ms=es.geometry;if(kt==="Point")ae(Ut,Ms,es);else if(kt==="MultiPoint")for(const bs of Ut)ae(bs,Ms,es);else if(kt==="LineString")es.type=2,he(Ut,Ms,es);else if(kt==="MultiLineString")es.type=2,xe(Ut,Ms,es);else if(kt==="Polygon")es.type=3,xe(Ut,Ms,es,!0);else{if(kt!=="MultiPolygon")throw new Error("Input data is not a valid GeoJSON object.");es.type=3;for(const bs of Ut)xe(bs,Ms,es,!0)}return es}function ae([xs,Ve],it,ft){const kt=c.aH(xs);let Ut=c.aL(Ve);Ut=Ut<0?0:Ut>1?1:Ut,it.push(kt,Ut),ft.minX=Math.min(ft.minX,kt),ft.minY=Math.min(ft.minY,Ut),ft.maxX=Math.max(ft.maxX,kt),ft.maxY=Math.max(ft.maxY,Ut)}function he(xs,Ve,it,ft=!1,kt=!1){const Ut=[];for(const es of xs)ae(es,Ut,it);Ve.push(Ut),ft&&function(es,Ms){let bs=0;for(let Zs=0,kn=es.length,gn=kn-2;Zs0===Ms)for(let Zs=0,kn=es.length;Zs=es&&gn>=es||(Zs>=es?(kn+=Math.round(ca*((es-Zs)/Kr)),Zs=es):gn>=es&&(xr=kn+Math.round(ca*((es-Zs)/Kr)),gn=es),kn>=es&&xr>=es||(kn>=es?(Zs+=Math.round(Kr*((es-kn)/ca)),kn=es):xr>=es&&(gn=Zs+Math.round(Kr*((es-kn)/ca)),xr=es),Ms&&Zs===Ms[Ms.length-1][0]&&kn===Ms[Ms.length-1][1]||(Ms=[[Zs,kn]],kt.push(Ms)),Ms.push([gn,xr])))))}}function be(xs,Ve,it,ft,kt){const Ut=(it-ne)/Ve,es=(ft-ne)/Ve,Ms=(it+1+ne)/Ve,bs=(ft+1+ne)/Ve;function Zs(xr,Kr){let ca=0;return xrMs&&(ca|=2),Krbs&&(ca|=8),ca}let kn=[];for(let xr=1;xr<=8;xr*=2){let Kr=xs[xs.length-2],ca=xs[xs.length-1],Er=!(Zs(Kr,ca)&xr);for(let qr=0;qr>31}function Ne(xs,Ve){const{geometry:it,type:ft}=xs;let kt=0,Ut=0;if(ft===1){Ve.writeVarint(Re(1,it.length));for(const es of it){const Ms=es[0]-kt,bs=es[1]-Ut;Ve.writeVarint(Be(Ms)),Ve.writeVarint(Be(bs)),kt+=Ms,Ut+=bs}}else for(const es of it){if(es.length===0)continue;Ve.writeVarint(Re(1,1));const Ms=es.length-(ft===3?1:0);for(let bs=0;bsxs},Fe=Math.fround||(Ae=new Float32Array(1),xs=>(Ae[0]=+xs,Ae[0]));var Ae;class Xe{constructor(Ve){this.options=Object.assign(Object.create(Ce),Ve),this.trees=new Array(this.options.maxZoom+1),this.stride=this.options.reduce?7:6,this.clusterProps=[]}load(Ve){const{log:it,minZoom:ft,maxZoom:kt}=this.options;it&&console.time("total time");const Ut=`prepare ${Ve.length} points`;it&&console.time(Ut),this.points=Ve;const es=[];for(let bs=0;bs=ft;bs--){const Zs=+Date.now();Ms=this.trees[bs]=this._createTree(this._cluster(Ms,bs)),it&&console.log("z%d: %d clusters in %dms",bs,Ms.numItems,+Date.now()-Zs)}return it&&console.timeEnd("total time"),this}getClusters(Ve,it){let ft=((Ve[0]+180)%360+360)%360-180;const kt=Math.max(-90,Math.min(90,Ve[1]));let Ut=Ve[2]===180?180:((Ve[2]+180)%360+360)%360-180;const es=Math.max(-90,Math.min(90,Ve[3]));if(Ve[2]-Ve[0]>=360)ft=-180,Ut=180;else if(ft>Ut){const gn=this.getClusters([ft,kt,180,es],it),xr=this.getClusters([-180,kt,Ut,es],it);return gn.concat(xr)}const Ms=this.trees[this._limitZoom(it)],bs=Ms.range(Je(ft),Ke(es),Je(Ut),Ke(kt)),Zs=Ms.data,kn=[];for(const gn of bs){const xr=this.stride*gn;kn.push(Zs[xr+5]>1?$e(Zs,xr,this.clusterProps):this.points[Zs[xr+3]])}return kn}getChildren(Ve){const it=this._getOriginId(Ve),ft=this._getOriginZoom(Ve),kt="No cluster with the specified id.",Ut=this.trees[ft];if(!Ut)throw new Error(kt);const es=Ut.data;if(it*this.stride>=es.length)throw new Error(kt);const Ms=this.options.radius/(this.options.extent*Math.pow(2,ft-1)),bs=Ut.within(es[it*this.stride],es[it*this.stride+1],Ms),Zs=[];for(const kn of bs){const gn=kn*this.stride;es[gn+4]===Ve&&Zs.push(es[gn+5]>1?$e(es,gn,this.clusterProps):this.points[es[gn+3]])}if(Zs.length===0)throw new Error(kt);return Zs}getLeaves(Ve,it,ft){const kt=[];return this._appendLeaves(kt,Ve,it=it||10,ft=ft||0,0),kt}getTile(Ve,it,ft){const kt=this.trees[this._limitZoom(Ve)],Ut=Math.pow(2,Ve),{extent:es,radius:Ms}=this.options,bs=Ms/es,Zs=(ft-bs)/Ut,kn=(ft+1+bs)/Ut,gn={features:[]};return this._addTileFeatures(kt.range((it-bs)/Ut,Zs,(it+1+bs)/Ut,kn),kt.data,it,ft,Ut,gn),it===0&&this._addTileFeatures(kt.range(1-bs/Ut,Zs,1,kn),kt.data,Ut,ft,Ut,gn),it===Ut-1&&this._addTileFeatures(kt.range(0,Zs,bs/Ut,kn),kt.data,-1,ft,Ut,gn),gn.features.length?gn:null}getClusterExpansionZoom(Ve){let it=this._getOriginZoom(Ve)-1;for(;it<=this.options.maxZoom;){const ft=this.getChildren(Ve);if(it++,ft.length!==1)break;Ve=ft[0].properties.cluster_id}return it}_appendLeaves(Ve,it,ft,kt,Ut){const es=this.getChildren(it);for(const Ms of es){const bs=Ms.properties;if(bs&&bs.cluster?Ut+bs.point_count<=kt?Ut+=bs.point_count:Ut=this._appendLeaves(Ve,bs.cluster_id,ft,kt,Ut):Ut1;let kn,gn,xr;if(Zs)kn=Ye(it,bs,this.clusterProps),gn=it[bs],xr=it[bs+1];else{const Er=this.points[it[bs+3]];kn=Er.properties;const[qr,Xt]=Er.geometry.coordinates;gn=Je(qr),xr=Ke(Xt)}const Kr={type:1,geometry:[[Math.round(this.options.extent*(gn*Ut-ft)),Math.round(this.options.extent*(xr*Ut-kt))]],tags:kn};let ca;ca=Zs||this.options.generateId?it[bs+3]:this.points[it[bs+3]].id,ca!==void 0&&(Kr.id=ca),es.features.push(Kr)}}_limitZoom(Ve){return Math.max(this.options.minZoom,Math.min(Math.floor(+Ve),this.options.maxZoom+1))}_cluster(Ve,it){const{radius:ft,extent:kt,reduce:Ut,minPoints:es}=this.options,Ms=ft/(kt*Math.pow(2,it)),bs=Ve.data,Zs=[],kn=this.stride;for(let gn=0;gnit&&(qr+=bs[Gn+5])}if(qr>Er&&qr>=es){let Xt,Gn=xr*Er,Jr=Kr*Er,Or=-1;const ja=(gn/kn<<5)+(it+1)+this.points.length;for(const ea of ca){const dr=ea*kn;if(bs[dr+2]<=it)continue;bs[dr+2]=it;const Wi=bs[dr+5];Gn+=bs[dr]*Wi,Jr+=bs[dr+1]*Wi,bs[dr+4]=ja,Ut&&(Xt||(Xt=this._map(bs,gn,!0),Or=this.clusterProps.length,this.clusterProps.push(Xt)),Ut(Xt,this._map(bs,dr)))}bs[gn+4]=ja,Zs.push(Gn/qr,Jr/qr,1/0,ja,-1,qr),Ut&&Zs.push(Or)}else{for(let Xt=0;Xt1)for(const Xt of ca){const Gn=Xt*kn;if(!(bs[Gn+2]<=it)){bs[Gn+2]=it;for(let Jr=0;Jr>5}_getOriginZoom(Ve){return(Ve-this.points.length)%32}_map(Ve,it,ft){if(Ve[it+5]>1){const es=this.clusterProps[Ve[it+6]];return ft?Object.assign({},es):es}const kt=this.points[Ve[it+3]].properties,Ut=this.options.map(kt);return ft&&Ut===kt?Object.assign({},Ut):Ut}}function $e(xs,Ve,it){return{type:"Feature",id:xs[Ve+3],properties:Ye(xs,Ve,it),geometry:{type:"Point",coordinates:[(ft=xs[Ve],360*(ft-.5)),st(xs[Ve+1])]}};var ft}function Ye(xs,Ve,it){const ft=xs[Ve+5],kt=ft>=1e4?`${Math.round(ft/1e3)}k`:ft>=1e3?Math.round(ft/100)/10+"k":ft,Ut=xs[Ve+6],es=Ut===-1?{}:Object.assign({},it[Ut]);return Object.assign(es,{cluster:!0,cluster_id:xs[Ve+3],point_count:ft,point_count_abbreviated:kt})}function Je(xs){return xs/360+.5}function Ke(xs){const Ve=Math.sin(xs*Math.PI/180),it=.5-.25*Math.log((1+Ve)/(1-Ve))/Math.PI;return it<0?0:it>1?1:it}function st(xs){const Ve=(180-360*xs)*Math.PI/180;return 360*Math.atan(Math.exp(Ve))/Math.PI-90}function rt(xs,Ve,it,ft){let kt=ft;const Ut=Ve+(it-Ve>>1);let es,Ms=it-Ve;const bs=xs[Ve],Zs=xs[Ve+1],kn=xs[it],gn=xs[it+1];for(let xr=Ve+3;xrkt)es=xr,kt=Kr;else if(Kr===kt){const ca=Math.abs(xr-Ut);caft&&(es-Ve>3&&rt(xs,Ve,es,ft),xs[es+2]=kt,it-es>3&&rt(xs,es,it,ft))}function Ze(xs,Ve,it,ft,kt,Ut){let es=kt-it,Ms=Ut-ft;if(es!==0||Ms!==0){const bs=((xs-it)*es+(Ve-ft)*Ms)/(es*es+Ms*Ms);bs>1?(it=kt,ft=Ut):bs>0&&(it+=es*bs,ft+=Ms*bs)}return es=xs-it,Ms=Ve-ft,es*es+Ms*Ms}function ht(xs,Ve,it,ft){const kt={id:xs??null,type:Ve,geometry:it,tags:ft,minX:1/0,minY:1/0,maxX:-1/0,maxY:-1/0};if(Ve==="Point"||Ve==="MultiPoint"||Ve==="LineString")Bt(kt,it);else if(Ve==="Polygon")Bt(kt,it[0]);else if(Ve==="MultiLineString")for(const Ut of it)Bt(kt,Ut);else if(Ve==="MultiPolygon")for(const Ut of it)Bt(kt,Ut[0]);return kt}function Bt(xs,Ve){for(let it=0;it0&&(es+=ft?(kt*kn-Zs*Ut)/2:Math.sqrt(Math.pow(Zs-kt,2)+Math.pow(kn-Ut,2))),kt=Zs,Ut=kn}const Ms=Ve.length-3;Ve[2]=1,rt(Ve,0,Ms,it),Ve[Ms+2]=1,Ve.size=Math.abs(es),Ve.start=0,Ve.end=Ve.size}function Xs(xs,Ve,it,ft){for(let kt=0;kt1?1:it}function At(xs,Ve,it,ft,kt,Ut,es,Ms){if(ft/=Ve,Ut>=(it/=Ve)&&es=ft)return null;const bs=[];for(const Zs of xs){const kn=Zs.geometry;let gn=Zs.type;const xr=kt===0?Zs.minX:Zs.minY,Kr=kt===0?Zs.maxX:Zs.maxY;if(xr>=it&&Kr=ft)continue;let ca=[];if(gn==="Point"||gn==="MultiPoint")Os(kn,ca,it,ft,kt);else if(gn==="LineString")Nt(kn,ca,it,ft,kt,!1,Ms.lineMetrics);else if(gn==="MultiLineString")Ys(kn,ca,it,ft,kt,!1);else if(gn==="Polygon")Ys(kn,ca,it,ft,kt,!0);else if(gn==="MultiPolygon")for(const Er of kn){const qr=[];Ys(Er,qr,it,ft,kt,!0),qr.length&&ca.push(qr)}if(ca.length){if(Ms.lineMetrics&&gn==="LineString"){for(const Er of ca)bs.push(ht(Zs.id,gn,Er,Zs.tags));continue}gn!=="LineString"&&gn!=="MultiLineString"||(ca.length===1?(gn="LineString",ca=ca[0]):gn="MultiLineString"),gn!=="Point"&&gn!=="MultiPoint"||(gn=ca.length===3?"Point":"MultiPoint"),bs.push(ht(Zs.id,gn,ca,Zs.tags))}}return bs.length?bs:null}function Os(xs,Ve,it,ft,kt){for(let Ut=0;Ut=it&&es<=ft&&It(Ve,xs[Ut],xs[Ut+1],xs[Ut+2])}}function Nt(xs,Ve,it,ft,kt,Ut,es){let Ms=ms(xs);const bs=kt===0?Ds:As;let Zs,kn,gn=xs.start;for(let qr=0;qrit&&(kn=bs(Ms,Xt,Gn,Or,ja,it),es&&(Ms.start=gn+Zs*kn)):ea>ft?dr=it&&(kn=bs(Ms,Xt,Gn,Or,ja,it),Wi=!0),dr>ft&&ea<=ft&&(kn=bs(Ms,Xt,Gn,Or,ja,ft),Wi=!0),!Ut&&Wi&&(es&&(Ms.end=gn+Zs*kn),Ve.push(Ms),Ms=ms(xs)),es&&(gn+=Zs)}let xr=xs.length-3;const Kr=xs[xr],ca=xs[xr+1],Er=kt===0?Kr:ca;Er>=it&&Er<=ft&&It(Ms,Kr,ca,xs[xr+2]),xr=Ms.length-3,Ut&&xr>=3&&(Ms[xr]!==Ms[0]||Ms[xr+1]!==Ms[1])&&It(Ms,Ms[0],Ms[1],Ms[2]),Ms.length&&Ve.push(Ms)}function ms(xs){const Ve=[];return Ve.size=xs.size,Ve.start=xs.start,Ve.end=xs.end,Ve}function Ys(xs,Ve,it,ft,kt,Ut){for(const es of xs)Nt(es,Ve,it,ft,kt,Ut,!1)}function It(xs,Ve,it,ft){xs.push(Ve,it,ft)}function Ds(xs,Ve,it,ft,kt,Ut){const es=(Ut-Ve)/(ft-Ve);return It(xs,Ut,it+(kt-it)*es,1),es}function As(xs,Ve,it,ft,kt,Ut){const es=(Ut-it)/(kt-it);return It(xs,Ve+(ft-Ve)*es,Ut,1),es}function Hs(xs,Ve){const it=[];for(let ft=0;ft0&&Ve.size<(kt?es:ft))return void(it.numPoints+=Ve.length/3);const Ms=[];for(let bs=0;bses)&&(it.numSimplified++,Ms.push(Ve[bs],Ve[bs+1])),it.numPoints++;kt&&function(bs,Zs){let kn=0;for(let gn=0,xr=bs.length,Kr=xr-2;gn0===Zs)for(let gn=0,xr=bs.length;gn24)throw new Error("maxZoom should be in the 0-24 range");if(it.promoteId&&it.generateId)throw new Error("promoteId and generateId cannot be used together.");let kt=function(Ut,es){const Ms=[];if(Ut.type==="FeatureCollection")for(let bs=0;bs1&&console.time("creation"),Kr=this.tiles[xr]=Bn(Ve,it,ft,kt,Zs),this.tileCoords.push({z:it,x:ft,y:kt}),kn)){kn>1&&(console.log("tile z%d-%d-%d (features: %d, points: %d, simplified: %d)",it,ft,kt,Kr.numFeatures,Kr.numPoints,Kr.numSimplified),console.timeEnd("creation"));const Wi=`z${it}`;this.stats[Wi]=(this.stats[Wi]||0)+1,this.total++}if(Kr.source=Ve,Ut==null){if(it===Zs.indexMaxZoom||Kr.numPoints<=Zs.indexMaxPoints)continue}else{if(it===Zs.maxZoom||it===Ut)continue;if(Ut!=null){const Wi=Ut-it;if(ft!==es>>Wi||kt!==Ms>>Wi)continue}}if(Kr.source=null,Ve.length===0)continue;kn>1&&console.time("clipping");const ca=.5*Zs.buffer/Zs.extent,Er=.5-ca,qr=.5+ca,Xt=1+ca;let Gn=null,Jr=null,Or=null,ja=null,ea=At(Ve,gn,ft-ca,ft+qr,0,Kr.minX,Kr.maxX,Zs),dr=At(Ve,gn,ft+Er,ft+Xt,0,Kr.minX,Kr.maxX,Zs);Ve=null,ea&&(Gn=At(ea,gn,kt-ca,kt+qr,1,Kr.minY,Kr.maxY,Zs),Jr=At(ea,gn,kt+Er,kt+Xt,1,Kr.minY,Kr.maxY,Zs),ea=null),dr&&(Or=At(dr,gn,kt-ca,kt+qr,1,Kr.minY,Kr.maxY,Zs),ja=At(dr,gn,kt+Er,kt+Xt,1,Kr.minY,Kr.maxY,Zs),dr=null),kn>1&&console.timeEnd("clipping"),bs.push(Gn||[],it+1,2*ft,2*kt),bs.push(Jr||[],it+1,2*ft,2*kt+1),bs.push(Or||[],it+1,2*ft+1,2*kt),bs.push(ja||[],it+1,2*ft+1,2*kt+1)}}getTile(Ve,it,ft){Ve=+Ve,it=+it,ft=+ft;const kt=this.options,{extent:Ut,debug:es}=kt;if(Ve<0||Ve>24)return null;const Ms=1<1&&console.log("drilling down to z%d-%d-%d",Ve,it,ft);let Zs,kn=Ve,gn=it,xr=ft;for(;!Zs&&kn>0;)kn--,gn>>=1,xr>>=1,Zs=this.tiles[sn(kn,gn,xr)];return Zs&&Zs.source?(es>1&&(console.log("found parent tile z%d-%d-%d",kn,gn,xr),console.time("drilling down")),this.splitTile(Zs.source,kn,gn,xr,Ve,it,ft),es>1&&console.timeEnd("drilling down"),this.tiles[bs]?en(this.tiles[bs],Ut):null):null}}function sn(xs,Ve,it){return 32*((1<Zs.tags&&"3d_elevation_id"in Zs.tags&&"source"in Zs.tags&&Zs.tags.source==="elevation",Ut=ft.features.filter(Zs=>kt(Zs));let es={_geojsonTileLayer:ft.features};Ut.length>0&&(es={_geojsonTileLayer:ft.features.filter(Zs=>!kt(Zs)),hd_road_elevation:Ut});const Ms=new te(es),bs=function(Zs){const kn=new c.a$;for(const gn of Object.keys(Zs))kn.writeMessage(3,Se,{name:gn,features:Zs[gn]});return kn.finish()}(es).buffer;Ve(null,{vectorTile:Ms,rawData:bs})}class ia extends L{constructor(Ve){super(Ve),this.loadVectorData=ki,this._dynamicIndex=new me}loadData(Ve,it){const ft=Ve&&Ve.request,kt=ft&&ft.collectResourceTiming;this._geoJSONIndex=null,this.loadGeoJSON(Ve,(Ut,es)=>{if(Ut||!es)return it(Ut);if(typeof es!="object")return it(new Error(`Input data given to '${Ve.source}' is not a valid GeoJSON object.`));{try{if(Ve.filter){const bs=c.X(Ve.filter,{type:"boolean","property-type":"data-driven",overridable:!1,transition:!1});if(bs.result==="error")throw new Error(bs.value.map(Zs=>`${Zs.key}: ${Zs.message}`).join(", "));es.features=es.features.filter(Zs=>bs.value.evaluate({zoom:0},Zs))}Ve.dynamic?(es.type==="Feature"&&(es={type:"FeatureCollection",features:[es]}),Ve.append||(this._dynamicIndex.clear(),this.loaded={}),this._dynamicIndex.load(es.features,this.loaded),Ve.cluster&&(es.features=this._dynamicIndex.getFeatures())):this.loaded={},this._geoJSONIndex=Ve.cluster?new Xe(function({superclusterOptions:bs,clusterProperties:Zs}){if(!Zs||!bs)return bs;const kn={},gn={},xr={accumulated:null,zoom:0},Kr={properties:null},ca=Object.keys(Zs);for(const Er of ca){const[qr,Xt]=Zs[Er],Gn=c.X(Xt),Jr=c.X(typeof qr=="string"?[qr,["accumulated"],["get",Er]]:qr);kn[Er]=Gn.value,gn[Er]=Jr.value}return bs.map=Er=>{Kr.properties=Er;const qr={};for(const Xt of ca)qr[Xt]=kn[Xt].evaluate(xr,Kr);return qr},bs.reduce=(Er,qr)=>{Kr.properties=qr;for(const Xt of ca)xr.accumulated=Er[Xt],Er[Xt]=gn[Xt].evaluate(xr,Kr)},bs}(Ve)).load(es.features):Ve.dynamic?this._dynamicIndex:function(bs,Zs){return new Mr(bs,Zs)}(es,Ve.geojsonVtOptions)}catch(bs){return it(bs)}const Ms={};if(kt){const bs=d(ft);bs&&(Ms.resourceTiming={},Ms.resourceTiming[Ve.source]=JSON.parse(JSON.stringify(bs)))}it(null,Ms)}})}reloadTile(Ve,it){const ft=this.loaded;return ft&&ft[Ve.uid]?Ve.partial?it(null,void 0):super.reloadTile(Ve,it):this.loadTile(Ve,it)}loadGeoJSON(Ve,it){if(Ve.request)c.m(Ve.request,it);else{if(typeof Ve.data!="string")return it(new Error(`Input data given to '${Ve.source}' is not a valid GeoJSON object.`));setTimeout(()=>{try{return it(null,JSON.parse(Ve.data))}catch{return it(new Error(`Input data given to '${Ve.source}' is not a valid GeoJSON object.`))}},0)}}getClusterExpansionZoom(Ve,it){try{it(null,this._geoJSONIndex.getClusterExpansionZoom(Ve.clusterId))}catch(ft){it(ft)}}getClusterChildren(Ve,it){try{it(null,this._geoJSONIndex.getChildren(Ve.clusterId))}catch(ft){it(ft)}}getClusterLeaves(Ve,it){try{it(null,this._geoJSONIndex.getLeaves(Ve.clusterId,Ve.limit,Ve.offset))}catch(ft){it(ft)}}}class vr{constructor(Ve,it,ft){this.tileID=new c.aR(Ve.tileID.overscaledZ,Ve.tileID.wrap,Ve.tileID.canonical.z,Ve.tileID.canonical.x,Ve.tileID.canonical.y),this.tileZoom=Ve.tileZoom,this.uid=Ve.uid,this.zoom=Ve.zoom,this.canonical=Ve.tileID.canonical,this.pixelRatio=Ve.pixelRatio,this.tileSize=Ve.tileSize,this.source=Ve.source,this.overscaling=this.tileID.overscaleFactor(),this.projection=Ve.projection,this.brightness=it,this.worldview=ft}parse(Ve,it,ft,kt){this.status="parsing";const Ut=new c.aR(ft.tileID.overscaledZ,ft.tileID.wrap,ft.tileID.canonical.z,ft.tileID.canonical.x,ft.tileID.canonical.y),es=[],Ms=it.familiesBySource[ft.source],bs=new c.ff(Ut,ft.promoteId);bs.bucketLayerIDs=[],bs.is3DTile=!0,c.fB(Ve).then(Zs=>{const kn=Zs.json.extensionsUsed&&Zs.json.extensionsUsed.includes("MAPBOX_mesh_features")||Zs.json.asset.extras&&Zs.json.asset.extras.MAPBOX_mesh_features,gn=Zs.json.extensionsUsed&&Zs.json.extensionsUsed.includes("EXT_meshopt_compression"),xr=new c.ae(this.zoom,{brightness:this.brightness,worldview:this.worldview});for(const Kr in Ms)for(const ca of Ms[Kr]){const Er=ca[0];bs.bucketLayerIDs.push(ca.map(Gn=>c.F(Gn.id,Gn.scope))),Er.recalculate(xr,[]);const qr=c.fC(Zs,1/c.cS(ft.tileID.canonical)),Xt=new c.fD(ca,qr,Ut,kn,gn,this.brightness,bs,this.worldview);kn||(Xt.needsUpload=!0),es.push(Xt),Xt.evaluate(Er)}this.status="done",kt(null,{buckets:es,featureIndex:bs,collisionBoxArray:null,glyphAtlasImage:null,lineAtlas:null,imageAtlas:null,brightness:null})}).catch(Zs=>kt(new Error(Zs.message)))}}class Nr{constructor({actor:Ve,layerIndex:it,availableImages:ft,availableModels:kt,brightness:Ut,worldview:es}){this.actor=Ve,this.layerIndex=it,this.availableImages=ft,this.availableModels=kt,this.brightness=Ut,this.loading={},this.loaded={},this.worldview=es}loadTile(Ve,it){const ft=Ve.uid,kt=this.loading[ft]=new vr(Ve,this.brightness,this.worldview);c.b1(Ve.request,(Ut,es)=>{const Ms=!this.loading[ft];return delete this.loading[ft],Ms||Ut?(kt.status="done",Ms||(this.loaded[ft]=kt),it(Ut)):es&&es.byteLength!==0?void kt.parse(es,this.layerIndex,Ve,(bs,Zs)=>{kt.status="done",this.loaded=this.loaded||{},this.loaded[ft]=kt,bs||!Zs?it(bs):it(null,Zs)}):(kt.status="done",this.loaded[ft]=kt,it())})}reloadTile(Ve,it){const ft=this.loaded,kt=Ve.uid;if(ft&&ft[kt]){const Ut=ft[kt];Ut.projection=Ve.projection,Ut.brightness=Ve.brightness;const es=(Ms,bs)=>{Ut.reloadCallback&&(delete Ut.reloadCallback,this.loadTile(Ve,it)),it(Ms,bs)};Ut.status==="parsing"?Ut.reloadCallback=es:Ut.status==="done"&&this.loadTile(Ve,it)}}abortTile(Ve,it){const ft=Ve.uid;this.loading[ft]&&delete this.loading[ft],it()}removeTile(Ve,it){const ft=this.loaded,kt=Ve.uid;ft&&ft[kt]&&delete ft[kt],it()}}const rn=new Map,Zn=new Map;class sa{constructor(Ve){this.self=Ve,this.actor=new c.A(Ve,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:L,geojson:ia,"raster-dem":z,"raster-array":V,"batched-model":Nr},this.workerSources={},this.self.registerWorkerSource=(it,ft)=>{if(this.workerSourceTypes[it])throw new Error(`Worker source with name "${it}" already registered.`);this.workerSourceTypes[it]=ft},this.self.registerRTLTextPlugin=it=>{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=it.applyArabicShaping,c.fF.processBidirectionalText=it.processBidirectionalText,c.fF.processStyledBidirectionalText=it.processStyledBidirectionalText;for(const ft of this.rtlPluginParsingListeners)ft(null,!0);this.rtlPluginParsingListeners=[]}}clearCaches(Ve,it,ft){delete this.layerIndexes[Ve],delete this.availableImages[Ve],delete this.availableModels[Ve],delete this.workerSources[Ve],ft()}checkIfReady(Ve,it,ft){ft()}setReferrer(Ve,it){this.referrer=it}spriteLoaded(Ve,it){this.isSpriteLoaded[Ve]||(this.isSpriteLoaded[Ve]={});const{scope:ft,isLoaded:kt}=it;if(this.isSpriteLoaded[Ve][ft]=kt,this.workerSources[Ve]&&this.workerSources[Ve][ft])for(const Ut in this.workerSources[Ve][ft]){const es=this.workerSources[Ve][ft][Ut];for(const Ms in es){const bs=es[Ms];bs instanceof L&&(bs.isSpriteLoaded=kt,bs.fire(new c.C("isSpriteLoaded")))}}}setImages(Ve,it,ft){this.availableImages[Ve]||(this.availableImages[Ve]={});const{scope:kt,images:Ut}=it;if(this.availableImages[Ve][kt]=Ut,this.workerSources[Ve]&&this.workerSources[Ve][kt]){for(const es in this.workerSources[Ve][kt]){const Ms=this.workerSources[Ve][kt][es];for(const bs in Ms)Ms[bs].availableImages=Ut}ft()}else ft()}setModels(Ve,{scope:it,models:ft},kt){if(this.availableModels[Ve]||(this.availableModels[Ve]={}),this.availableModels[Ve][it]=ft,this.workerSources[Ve]&&this.workerSources[Ve][it]){for(const Ut in this.workerSources[Ve][it]){const es=this.workerSources[Ve][it][Ut];for(const Ms in es)es[Ms].availableModels=ft}kt()}else kt()}setProjection(Ve,it){this.projections[Ve]=c.c0(it)}setBrightness(Ve,it,ft){this.brightness=it,ft()}setContextParams(Ve,it,ft){this.maxUniformBufferBindings=it.maxBindingPoints,this.maxUniformBlockSizeDwords=it.maxUniformBlockSizeDwords,this.disableSymbolUBO=it.disableSymbolUBO,ft()}setWorldview(Ve,it,ft){this.worldview=it,ft()}setLayers(Ve,it,ft){this.getLayerIndex(Ve,it.scope).replace(it.layers,it.options),ft()}updateLayers(Ve,it,ft){this.getLayerIndex(Ve,it.scope).update(it.layers,it.removedIds,it.options),ft()}loadTile(Ve,it,ft){it.projection=this.projections[Ve]||this.defaultProjection,this.getWorkerSource(Ve,it).loadTile(it,ft)}decodeRasterArray(Ve,it,ft){this.getWorkerSource(Ve,it).decodeRasterArray(it,ft)}reloadTile(Ve,it,ft){it.projection=this.projections[Ve]||this.defaultProjection,this.getWorkerSource(Ve,it).reloadTile(it,ft)}abortTile(Ve,it,ft){this.getWorkerSource(Ve,it).abortTile(it,ft)}removeTile(Ve,it,ft){this.getWorkerSource(Ve,it).removeTile(it,ft)}removeSource(Ve,it,ft){if(!(this.workerSources[Ve]&&this.workerSources[Ve][it.scope]&&this.workerSources[Ve][it.scope][it.type]&&this.workerSources[Ve][it.scope][it.type][it.source]))return;const kt=this.workerSources[Ve][it.scope][it.type][it.source];delete this.workerSources[Ve][it.scope][it.type][it.source],kt.removeSource!==void 0?kt.removeSource(it,ft):ft()}loadTileProvider(Ve,it,ft){(async function(kt,Ut){const es=Zn.get(kt);if(es)return es;const Ms=rn.get(kt);if(Ms!==void 0)return Ms;const bs=import(Ut).then(Zs=>{const kn=Zs.default;if(typeof kn!="function")throw new Error(`TileProvider "${kt}" module must default-export a class`);if(typeof kn.prototype.loadTile!="function")throw new Error(`TileProvider "${kt}" class must have a loadTile method`);return Zn.set(kt,kn),kn}).finally(()=>{rn.delete(kt)});return rn.set(kt,bs),bs})(it.name,it.url).then(kt=>{const Ut=new kt(it.options);return this.getWorkerSource(Ve,{type:it.type,source:it.source,scope:it.scope},Ut),Ut.load&&it.request?Ut.load({request:it.request}):null}).then(kt=>ft(null,kt)).catch(kt=>ft(kt instanceof Error?kt:new Error(typeof kt=="string"?kt:"Unknown error")))}loadWorkerSource(Ve,it,ft){try{this.self.importScripts(it.url),ft()}catch(kt){ft(kt)}}syncRTLPluginState(Ve,it,ft){if(c.fF.isParsed())ft(null,!0);else if(c.fF.isParsing())this.rtlPluginParsingListeners.push(ft);else try{c.fF.setState(it);const kt=c.fF.getPluginURL();!c.fF.isLoaded()||c.fF.isParsed()||c.fF.isParsing()||kt==null||(c.fF.setState({pluginStatus:c.fG.parsing,pluginURL:c.fF.getPluginURL()}),this.self.importScripts(kt),c.fF.isParsed()?ft(null,!0):this.rtlPluginParsingListeners.push(ft))}catch(kt){ft(kt)}}setConfig(Ve,it){Object.assign(c.g,it)}getAvailableImages(Ve,it){this.availableImages[Ve]||(this.availableImages[Ve]={});let ft=this.availableImages[Ve][it];return ft||(ft=[]),ft}getAvailableModels(Ve,it){this.availableModels[Ve]||(this.availableModels[Ve]={});let ft=this.availableModels[Ve][it];return ft||(ft={}),ft}getLayerIndex(Ve,it){this.layerIndexes[Ve]||(this.layerIndexes[Ve]={});let ft=this.layerIndexes[Ve][it];return ft||(ft=this.layerIndexes[Ve][it]=new f,ft.scope=it),ft}getWorkerSource(Ve,it,ft){const{type:kt,source:Ut,scope:es}=it,Ms=this.workerSources;if(Ms[Ve]||(Ms[Ve]={}),Ms[Ve][es]||(Ms[Ve][es]={}),Ms[Ve][es][kt]||(Ms[Ve][es][kt]={}),this.isSpriteLoaded[Ve]||(this.isSpriteLoaded[Ve]={}),!Ms[Ve][es][kt][Ut]){const bs={send:(kn,gn,xr,Kr,ca,Er)=>this.actor.send(kn,gn,xr,Ve,ca,Er),scheduler:this.actor.scheduler},Zs=this.workerSourceTypes[kt];if(!Zs)throw new Error(`Unknown worker source type "${kt}".`);Ms[Ve][es][kt][Ut]=new Zs({actor:bs,layerIndex:this.getLayerIndex(Ve,es),availableImages:this.getAvailableImages(Ve,es),availableModels:this.getAvailableModels(Ve,es),isSpriteLoaded:this.isSpriteLoaded[Ve][es],tileProvider:ft,brightness:this.brightness,worldview:this.worldview,maxUniformBufferBindings:this.maxUniformBufferBindings,maxUniformBlockSizeDwords:this.maxUniformBlockSizeDwords,disableSymbolUBO:this.disableSymbolUBO})}return Ms[Ve][es][kt][Ut]}rasterizeImagesWorker(Ve,it,ft){const kt=new Map;for(const[Ut,{image:es,imageVariant:Ms}]of it.tasks.entries()){const bs=this.imageRasterizer.rasterize(Ms,es,it.scope,Ve);kt.set(Ut,bs)}ft(void 0,kt)}removeRasterizedImages(Ve,it,ft){this.imageRasterizer.removeImagesFromCacheByIds(it.imageIds,it.scope,Ve),ft()}enforceCacheSizeLimit(Ve,it){c.fH(it)}getWorkerPerformanceMetrics(Ve,it,ft){ft(void 0,void 0)}}return c.fE(self)&&(self.worker=new sa(self)),sa}),i(["./shared"],function(o){var c="3.22.0";const d={create:"create",load:"load",fullLoad:"fullLoad"},u={mark(D){performance.mark(D)},measure(D,w,C){performance.measure(D,w,C)}};function h(D){const w=D.name.split("?")[0];return o.a(w)&&w.includes("mapbox-gl.js")?"javascript":o.a(w)&&w.includes("mapbox-gl.css")?"css":o.b(w)?"fontRange":o.c(w)?"sprite":o.i(w)?"style":o.d(w)?"tilejson":"other"}var m,f={},g=function(){if(m)return f;function D(O){return!w(O)}function w(O){return typeof window>"u"||typeof document>"u"?"not a browser":function(){if(!("Worker"in window&&"Blob"in window&&"URL"in window))return!1;var Y,Z,se=new Blob([""],{type:"text/javascript"}),pe=URL.createObjectURL(se);try{Z=new Worker(pe),Y=!0}catch{Y=!1}return Z&&Z.terminate(),URL.revokeObjectURL(pe),Y}()?function(){var Y=document.createElement("canvas");Y.width=Y.height=1;var Z=Y.getContext("2d");if(!Z)return!1;var se=Z.getImageData(0,0,1,1);return se&&se.width===Y.width}()?(C[U=O&&O.failIfMajorPerformanceCaveat]===void 0&&(C[U]=function(Y){var Z,se=function(pe){var je=document.createElement("canvas"),Ee=Object.create(D.webGLContextAttributes);return Ee.failIfMajorPerformanceCaveat=pe,je.getContext("webgl2",Ee)}(Y);if(!se)return!1;try{Z=se.createShader(se.VERTEX_SHADER)}catch{return!1}return!(!Z||se.isContextLost())&&(se.shaderSource(Z,"void main() {}"),se.compileShader(Z),se.getShaderParameter(Z,se.COMPILE_STATUS)===!0)}(U)),C[U]?document.documentMode?"insufficient ECMAScript 6 support":void 0:"insufficient WebGL2 support"):"insufficient Canvas/getImageData support":"insufficient worker support";var U}m=1,f.supported=D,f.notSupportedReason=w;var C={};return D.webGLContextAttributes={antialias:!1,alpha:!0,stencil:!0,depth:!0},f}();function y(D,w,C){const O=document.createElement(D);return w!=null&&(O.className=w),C&&C.appendChild(O),O}function x(D,w,C){const O=document.createElementNS("http://www.w3.org/2000/svg",D);for(const U of Object.keys(w))O.setAttributeNS(null,U,String(w[U]));return C&&C.appendChild(O),O}const _=typeof document<"u"?document.documentElement&&document.documentElement.style:null,b=_&&_.userSelect!==void 0?"userSelect":"WebkitUserSelect";let k;function A(){_&&b&&(k=_[b],_[b]="none")}function T(){_&&b&&(_[b]=k)}function P(D){D.preventDefault(),D.stopPropagation(),window.removeEventListener("click",P,!0)}function I(){window.addEventListener("click",P,!0),window.setTimeout(()=>{window.removeEventListener("click",P,!0)},0)}function M(D,w){const C=D.getBoundingClientRect();return $(D,C,w)}function L(D,w){const C=D.getBoundingClientRect(),O=[];for(let U=0;Uthis._skuTokenExpiresAt}transformRequest(w,C){return this._transformRequestFn&&this._transformRequestFn(w,C)||{url:w}}normalizeStyleURL(w,C){if(!o.e(w))return w;const O=te(w);return O.params.push(`sdk=js-${c}`),O.path=`/styles/v1${O.path}`,this._makeAPIURL(O,this._customAccessToken||C)}normalizeGlyphsURL(w,C){if(!o.e(w))return w;const O=te(w);return O.path=`/fonts/v1${O.path}`,this._makeAPIURL(O,this._customAccessToken||C)}normalizeModelURL(w,C){if(!o.e(w))return w;const O=te(w);return O.path=`/models/v1${O.path}`,this._makeAPIURL(O,this._customAccessToken||C)}normalizeSourceURL(w,C,O,U){if(!o.e(w))return w;const Y=te(w);return Y.path=`/v4/${Y.authority}.json`,Y.params.push("secure"),O&&Y.params.push(`language=${O}`),U&&Y.params.push(`worldview=${U}`),this._makeAPIURL(Y,this._customAccessToken||C)}normalizeIconsetURL(w,C){const O=te(w);return o.e(w)?(O.path=`/styles/v1${O.path}/iconset.pbf`,this._makeAPIURL(O,this._customAccessToken||C)):ne(O)}normalizeSpriteURL(w,C,O,U){const Y=te(w);return o.e(w)?(Y.path=`/styles/v1${Y.path}/sprite${C}${O}`,this._makeAPIURL(Y,this._customAccessToken||U)):(Y.path+=`${C}${O}`,ne(Y))}normalizeTileURL(w,C,O){if(this._isSkuTokenExpired()&&this._createSkuToken(),w&&!o.e(w))return w;const U=te(w);U.path=U.path.replace(/(\.(png|jpg)\d*)(?=$)/,`${C||O&&U.authority!=="raster"&&O===512?"@2x":""}${o.k.supported?".webp":"$1"}`),U.authority==="raster"?U.path=`/${o.g.RASTER_URL_PREFIX}${U.path}`:U.authority==="rasterarrays"?U.path=`/${o.g.RASTERARRAYS_URL_PREFIX}${U.path}`:U.authority==="3dtiles"?U.path=`/${o.g.TILES3D_URL_PREFIX}${U.path}`:(U.path=U.path.replace(/^.+\/v4\//,"/"),U.path=`/${o.g.TILE_URL_VERSION}${U.path}`);const Y=this._customAccessToken||function(Z){for(const se of Z){const pe=se.match(/^access_token=(.*)$/);if(pe)return pe[1]}return null}(U.params)||o.g.ACCESS_TOKEN;return o.g.REQUIRE_ACCESS_TOKEN&&Y&&this._skuToken&&U.params.push(`sku=${this._skuToken}`),this._makeAPIURL(U,Y)}canonicalizeTileURL(w,C){const O=te(w);if(!O.path.match(/^(\/v4\/|\/(raster|rasterarrays)\/v1\/)/)||!O.path.match(/\.[\w]+$/))return w;let U="mapbox://";O.path.match(/^\/raster\/v1\//)?U+=`raster/${O.path.replace(`/${o.g.RASTER_URL_PREFIX}/`,"")}`:O.path.match(/^\/rasterarrays\/v1\//)?U+=`rasterarrays/${O.path.replace(`/${o.g.RASTERARRAYS_URL_PREFIX}/`,"")}`:U+=`tiles/${O.path.replace(`/${o.g.TILE_URL_VERSION}/`,"")}`;let Y=O.params;return C&&(Y=Y.filter(Z=>!Z.match(/^access_token=/))),Y.length&&(U+=`?${Y.join("&")}`),U}canonicalizeTileset(w,C){const O=!!C&&o.e(C),U=[];for(const Y of w.tiles||[])o.f(Y)?U.push(this.canonicalizeTileURL(Y,O)):U.push(Y);return U}_makeAPIURL(w,C){const O="See https://docs.mapbox.com/api/overview/#access-tokens-and-token-scopes",U=te(o.g.API_URL);if(w.protocol=U.protocol,w.authority=U.authority,w.protocol==="http"){const Y=w.params.indexOf("secure");Y>=0&&w.params.splice(Y,1)}if(U.path!=="/"&&(w.path=`${U.path}${w.path}`),!o.g.REQUIRE_ACCESS_TOKEN)return ne(w);if(C=C||o.g.ACCESS_TOKEN,!this._silenceAuthErrors){if(!C)throw new Error(`An API access token is required to use Mapbox GL. ${O}`);if(C[0]==="s")throw new Error(`Use a public access token (pk.*) with Mapbox GL, not a secret access token (sk.*). ${O}`)}return w.params=w.params.filter(Y=>Y.indexOf("access_token")===-1),w.params.push(`access_token=${C||""}`),ne(w)}}const X=/^(\w+):\/\/([^/?]*)(\/[^?]+)?\??(.+)?/;function te(D){const w=D.match(X);if(!w)throw new Error("Unable to parse URL object");return{protocol:w[1],authority:w[2],path:w[3]||"/",params:w[4]?w[4].split("&"):[]}}function ne(D){const w=D.params.length?`?${D.params.join("&")}`:"";return`${D.protocol}://${D.authority}${D.path}${w}`}const me="mapbox.eventData";function ue(D){if(!D)return null;const w=D.split(".");if(!w||w.length!==3)return null;try{return JSON.parse(o.l(w[1]))}catch{return null}}function ce(D){return!(!o.g.EVENTS_URL||!D&&!o.g.ACCESS_TOKEN)}class ae{constructor(w){this.type=w,this.anonId=null,this.anonIdTimestamp=null,this.eventData={},this.queue=[],this.pendingRequest=null}getStorageKey(w){const C=ue(o.g.ACCESS_TOKEN);let O="";return O=C&&C.u?o.j(C.u):o.g.ACCESS_TOKEN||"",w?`${me}.${w}:${O}`:`${me}:${O}`}fetchEventData(){const w=o.s("localStorage"),C=this.getStorageKey(),O=this.getStorageKey("uuid"),U=this.getStorageKey("uuidTimestamp");if(w)try{const Y=localStorage.getItem(C);Y&&(this.eventData=JSON.parse(Y));const Z=localStorage.getItem(O);Z&&(this.anonId=Z);const se=localStorage.getItem(U);se&&(this.anonIdTimestamp=Number(se));const pe=Date.now()-864e5;(!this.anonIdTimestamp||this.anonIdTimestamp=1&&localStorage.setItem(C,JSON.stringify(this.eventData)),Z&&localStorage.setItem(U,Z.toString())}catch{o.w("Unable to write to LocalStorage")}}processRequests(w){}postEvent(w,C,O,U){if(!o.g.EVENTS_URL)return;const Y=te(o.g.EVENTS_URL);Y.params.push(`access_token=${U||o.g.ACCESS_TOKEN||""}`);const Z={event:this.type,created:new Date(w).toISOString()},se=C?Object.assign(Z,C):Z,pe={url:ne(Y),headers:{"Content-Type":"text/plain"},body:JSON.stringify([se])};this.pendingRequest=o.p(pe,je=>{this.pendingRequest=null,O(je),this.saveEventData(),this.processRequests(U)})}queueRequest(w,C){this.queue.push(w),this.processRequests(C)}}class he extends ae{constructor(w){super("metrics"),w&&(this.data=w)}postMetricsEvent(w){if(!ce(w))return;this.anonId||this.fetchEventData(),o.v(this.anonId)||this.refreshUUID();const C=Object.assign({},this.data,{sessionId:this.anonId});this.queueRequest({timestamp:Date.now(),payload:C},w)}processRequests(w){if(this.pendingRequest||this.queue.length===0)return;const{timestamp:C,payload:O}=this.queue.shift();this.postEvent(C,O,()=>{},w)}}const xe=new class extends ae{constructor(D){super("appUserTurnstile"),this._customAccessToken=D}postTurnstileEvent(D,w){ce(w)&&Array.isArray(D)&&D.some(C=>o.e(C)||o.f(C))&&this.queueRequest(Date.now(),w)}processRequests(D){if(this.pendingRequest||this.queue.length===0)return;this.anonId&&this.anonIdTimestamp&&this.eventData.lastSuccess&&this.eventData.tokenU||this.fetchEventData();const w=ue(o.g.ACCESS_TOKEN),C=w?w.u:o.g.ACCESS_TOKEN;let O=C!==this.eventData.tokenU;o.v(this.anonId)||(this.refreshUUID(),O=!0);const U=this.queue.shift();if(this.eventData.lastSuccess){const Y=new Date(this.eventData.lastSuccess),Z=new Date(U),se=(U-this.eventData.lastSuccess)/864e5;O=O||se>=1||se<-1||Y.getDate()!==Z.getDate()}else O=!0;O?this.postEvent(U,{sdkIdentifier:"mapbox-gl-js",sdkVersion:c,skuId:V,"enabled.telemetry":!1,userId:this.anonId},Y=>{Y||(this.eventData.lastSuccess=U,this.eventData.tokenU=C)},D):this.processRequests()}},ve=xe.postTurnstileEvent.bind(xe),ge=new class extends ae{constructor(){super("map.load"),this.success={},this.skuToken=""}postMapLoadEvent(D,w,C,O){this.skuToken=w,this.errorCb=O,o.g.EVENTS_URL&&(C||o.g.ACCESS_TOKEN?this.queueRequest({id:D,timestamp:Date.now()},C):this.errorCb(new Error(W)))}processRequests(D){if(this.pendingRequest||this.queue.length===0)return;const{id:w,timestamp:C}=this.queue.shift();w&&this.success[w]||(this.anonId&&this.anonIdTimestamp||this.fetchEventData(),o.v(this.anonId)||this.refreshUUID(),this.postEvent(C,{sdkIdentifier:"mapbox-gl-js",sdkVersion:c,skuId:V,skuToken:this.skuToken,userId:this.anonId},O=>{O?this.errorCb(O):w&&(this.success[w]=!0)},D))}remove(){this.errorCb=null}},be=ge.postMapLoadEvent.bind(ge),Se=new class extends ae{constructor(){super("style.load"),this.eventIdPerMapInstanceMap=new Map,this.mapInstanceIdMap=new WeakMap}getMapInstanceId(D){let w=this.mapInstanceIdMap.get(D);return w||(w=o.u(),this.mapInstanceIdMap.set(D,w)),w}getEventId(D){const w=this.eventIdPerMapInstanceMap.get(D)||0;return this.eventIdPerMapInstanceMap.set(D,w+1),w}postStyleLoadEvent(D,w){const{map:C,style:O,importedStyles:U}=w;if(!ce(D))return;const Y=this.getMapInstanceId(C),Z={mapInstanceId:Y,eventId:this.getEventId(Y),style:O};U.length&&(Z.importedStyles=U),this.queueRequest({timestamp:Date.now(),payload:Z},D)}processRequests(D){if(this.pendingRequest||this.queue.length===0)return;const{timestamp:w,payload:C}=this.queue.shift();this.postEvent(w,C,()=>{},D)}},Ie=Se.postStyleLoadEvent.bind(Se),Me=new he({attributes:[{name:"maps/js/layer-animations/style-with-appearances"}]}),Re=Me.postMetricsEvent.bind(Me),Be=new he({attributes:[{name:"maps/js/layer-animations/runtime-appearances"}]}),Ne=Be.postMetricsEvent.bind(Be),Ge=new class extends ae{constructor(){super("gljs.performance")}postPerformanceEvent(D,w){ce(D)&&this.queueRequest({timestamp:Date.now(),performanceData:w},D)}processRequests(D){if(this.pendingRequest||this.queue.length===0)return;const{timestamp:w,performanceData:C}=this.queue.shift(),O=function(U){const Y=performance.getEntriesByType("resource"),Z=performance.getEntriesByType("mark"),se=function(et){const ct={};if(et){for(const ot in et)if(ot!=="other")for(const bt of et[ot]){const vt=`${ot}ResolveRangeMin`,Pt=`${ot}ResolveRangeMax`,Ft=`${ot}RequestCount`,jt=`${ot}RequestCachedCount`;ct[vt]=Math.min(ct[vt]||1/0,bt.startTime),ct[Pt]=Math.max(ct[Pt]||-1/0,bt.responseEnd);const ys=Qt=>{ct[Qt]===void 0&&(ct[Qt]=0),++ct[Qt]};bt.transferSize!==void 0&&bt.transferSize===0&&ys(jt),ys(Ft)}}return ct}(function(et,ct){const ot={};if(et)for(const bt of et){const vt=ct(bt);ot[vt]===void 0&&(ot[vt]=[]),ot[vt].push(bt)}return ot}(Y,h)),pe=window.devicePixelRatio,je=navigator.connection||navigator.mozConnection||navigator.webkitConnection,Ee=je?je.effectiveType:void 0,He={counters:[],metadata:[],attributes:[]},qe=(et,ct,ot)=>{ot!=null&&et.push({name:ct,value:ot.toString()})};for(const et in se)qe(He.counters,et,se[et]);if(U.interactionRange[0]!==1/0&&U.interactionRange[1]!==-1/0&&(qe(He.counters,"interactionRangeMin",U.interactionRange[0]),qe(He.counters,"interactionRangeMax",U.interactionRange[1])),Z)for(const et of Object.values(d)){const ct=Z.find(ot=>ot.name===et);ct&&qe(He.counters,et,ct.startTime)}return qe(He.counters,"visibilityHidden",U.visibilityHidden),qe(He.attributes,"style",function(et){if(et)for(const ct of et){const ot=ct.name.split("?")[0];if(o.i(ot)){const bt=ot.split("/").slice(-2);if(bt.length===2)return`mapbox://styles/${bt[0]}/${bt[1]}`}}}(Y)),qe(He.attributes,"terrainEnabled",U.terrainEnabled?"true":"false"),qe(He.attributes,"fogEnabled",U.fogEnabled?"true":"false"),qe(He.attributes,"projection",U.projection),qe(He.attributes,"zoom",U.zoom),qe(He.metadata,"devicePixelRatio",pe),qe(He.metadata,"connectionEffectiveType",Ee),qe(He.metadata,"navigatorUserAgent",navigator.userAgent),qe(He.metadata,"screenWidth",window.screen.width),qe(He.metadata,"screenHeight",window.screen.height),qe(He.metadata,"windowWidth",window.innerWidth),qe(He.metadata,"windowHeight",window.innerHeight),qe(He.metadata,"mapWidth",U.width/pe),qe(He.metadata,"mapHeight",U.height/pe),qe(He.metadata,"webglRenderer",U.renderer),qe(He.metadata,"webglVendor",U.vendor),qe(He.metadata,"sdkVersion",c),qe(He.metadata,"sdkIdentifier","mapbox-gl-js"),He}(C);for(const U of O.metadata);for(const U of O.counters);for(const U of O.attributes);this.postEvent(w,O,()=>{},D)}},Ce=Ge.postPerformanceEvent.bind(Ge),Fe=new class extends ae{constructor(){super("map.auth"),this.success={},this.skuToken=""}getSession(D,w,C,O){if(!o.g.API_URL||!o.g.SESSION_PATH)return;const U=te(o.g.API_URL+o.g.SESSION_PATH);U.params.push(`sku=${w||""}`),U.params.push(`access_token=${O||o.g.ACCESS_TOKEN||""}`);const Y={url:ne(U),headers:{"Content-Type":"text/plain"}};this.pendingRequest=o.h(Y,Z=>{this.pendingRequest=null,C(Z),this.saveEventData(),this.processRequests(O)})}getSessionAPI(D,w,C,O){this.skuToken=w,this.errorCb=O,o.g.EVENTS_URL&&o.g.SESSION_PATH&&o.g.API_URL&&(C||o.g.ACCESS_TOKEN?this.queueRequest({id:D,timestamp:Date.now()},C):this.errorCb(new Error(W)))}processRequests(D){if(this.pendingRequest||this.queue.length===0)return;const{id:w,timestamp:C}=this.queue.shift();w&&this.success[w]||this.getSession(C,this.skuToken,O=>{O?this.errorCb(O):w&&(this.success[w]=!0)},D)}remove(){this.errorCb=null}},Ae=Fe.getSessionAPI.bind(Fe),Xe=new Set;function $e(D,w){w?Xe.add(D):Xe.delete(D)}class Ye{constructor(){this._changed=!1,this._updatedLayers={},this._removedLayers={},this._updatedSourceCaches={},this._updatedPaintProps=new Set,this._updatedImages={}}isDirty(){return this._changed}setDirty(){this._changed=!0}getUpdatedSourceCaches(){return this._updatedSourceCaches}updateSourceCache(w,C){this._updatedSourceCaches[w]=C,this.setDirty()}discardSourceCacheUpdate(w){delete this._updatedSourceCaches[w]}updateLayer(w){const C=w.scope;this._updatedLayers[C]=this._updatedLayers[C]||new Set,this._updatedLayers[C].add(w.id),this.setDirty()}removeLayer(w){const C=w.scope;this._removedLayers[C]=this._removedLayers[C]||{},this._updatedLayers[C]=this._updatedLayers[C]||new Set,this._removedLayers[C][w.id]=w,this._updatedLayers[C].delete(w.id),this._updatedPaintProps.delete(w.fqid),this.setDirty()}getRemovedLayer(w){return this._removedLayers[w.scope]?this._removedLayers[w.scope][w.id]:null}discardLayerRemoval(w){this._removedLayers[w.scope]&&delete this._removedLayers[w.scope][w.id]}getLayerUpdatesByScope(){const w={};for(const C in this._updatedLayers)w[C]=w[C]||{},w[C].updatedIds=Array.from(this._updatedLayers[C].values());for(const C in this._removedLayers)w[C]=w[C]||{},w[C].removedIds=Object.keys(this._removedLayers[C]);return w}getUpdatedPaintProperties(){return this._updatedPaintProps}updatePaintProperties(w){this._updatedPaintProps.add(w.fqid),this.setDirty()}getUpdatedImages(w){return this._updatedImages[w]?Array.from(this._updatedImages[w].values()):[]}updateImage(w,C){this._updatedImages[C]=this._updatedImages[C]||new Set,this._updatedImages[C].add(o.I.toString(w)),this.setDirty()}resetUpdatedImages(w){this._updatedImages[w]&&this._updatedImages[w].clear()}reset(){this._changed=!1,this._updatedLayers={},this._removedLayers={},this._updatedSourceCaches={},this._updatedPaintProps.clear(),this._updatedImages={}}}function Je(D){const{userImage:w}=D;return!!(w&&w.render&&w.render())&&(D.data.replace(new Uint8Array(w.data.buffer)),!0)}const Ke={workerUrl:"",workerClass:null,workerParams:void 0};function st(D){return Ke.workerClass!=null?new Ke.workerClass:new self.Worker(Ke.workerUrl,Object.assign({name:D},Ke.workerParams))}const rt="mapboxgl_preloaded_worker_pool";class Ze{constructor(w){this.active={},this.name=w}acquire(w,C=Ze.workerCount){if(!this.workers)for(this.workers=[];this.workers.length{C.terminate()}),this.workers=null)}isPreloaded(){return!!this.active[rt]}numActive(){return Object.keys(this.active).length}}Ze.workerCount=2;class ht{constructor(w,C,O="Worker",U=Ze.workerCount){this.workerPool=w,this.actors=[],this.currentActor=0,this.id=o.r();const Y=this.workerPool.acquire(this.id,U);for(let Z=0;Z{this.ready=!0})}broadcast(w,C,O){o.t(this.actors,(U,Y)=>{U.send(w,C,Y)},O=O||function(){})}getActor(){return this.currentActor=(this.currentActor+1)%this.actors.length,this.actors[this.currentActor]}remove(){this.actors.forEach(w=>{w.remove()}),this.actors=[],this.workerPool.release(this.id)}}let Bt,Ct;function Yt(){return Bt||(Bt=new Ze),Bt}ht.Actor=o.A;class Kt extends o.E{constructor(w){super(),this.imageProviders=new Map,this.images=new Map,this.updatedImages=new Map,this.callbackDispatchedThisFrame=new Map,this.imageVersions=new Map,this.loaded=new Map,this.requestors=[],this.patterns=new Map,this.patternsInFlight=new Set,this.atlasImage=new Map,this.atlasTexture=new Map,this.imageAtlasCache=new o.x,this.dirty=!0,this.spriteFormat=w,w!=="raster"&&o.y()&&(this.imageRasterizerDispatcher=new ht((Ct||(Ct=new Ze("ImageRasterizer")),Ct),this,"Image Rasterizer Worker",1))}addScope(w){this.loaded.set(w,!1),this.imageProviders.set(w,new Map),this.images.set(w,new Map),this.updatedImages.set(w,new Set),this.callbackDispatchedThisFrame.set(w,new Set),this.imageVersions.set(w,new Map),this.patterns.set(w,new Map),this.atlasImage.set(w,new o.q({width:1,height:1}))}removeScope(w){this.loaded.delete(w),this.imageProviders.delete(w),this.images.delete(w),this.updatedImages.delete(w),this.callbackDispatchedThisFrame.delete(w),this.imageVersions.delete(w),this.patterns.delete(w),this.atlasImage.delete(w);const C=this.atlasTexture.get(w);C&&(C.destroy(),this.atlasTexture.delete(w))}addImageProvider(w,C){this.imageProviders.has(C)||this.imageProviders.set(C,new Map),this.imageProviders.get(C).set(w.id,w)}removeImageProvider(w,C){this.imageProviders.has(C)&&this.imageProviders.get(C).delete(w)}getPendingImageProviders(){const w=[];for(const C of this.imageProviders.values())for(const O of C.values())O.hasPendingRequests()&&w.push(O);return w}get imageRasterizer(){return this._imageRasterizer||(this._imageRasterizer=new o.z),this._imageRasterizer}isLoaded(){for(const w of this.loaded.keys())if(!this.loaded.get(w))return!1;return!0}setLoaded(w,C){if(this.loaded.get(C)!==w&&(this.loaded.set(C,w),w)){for(const{ids:O,callback:U}of this.requestors)this._notify(O,C,U);this.requestors=[]}}hasImage(w,C){return!!this.getImage(w,C)}getImage(w,C){return this.images.get(C).get(w.toString())}addImage(w,C,O){if(this._validate(w,O)){this.images.get(C).set(w.toString(),O);const U=this.imageVersions.get(C),Y=U.get(w.toString())||0;U.set(w.toString(),Y+1)}}_validate(w,C){let O=!0;return this._validateStretch(C.stretchX,C.data&&C.data.width)||(this.fire(new o.B(new Error(`Image "${w.name}" has invalid "stretchX" value`))),O=!1),this._validateStretch(C.stretchY,C.data&&C.data.height)||(this.fire(new o.B(new Error(`Image "${w.name}" has invalid "stretchY" value`))),O=!1),this._validateContent(C.content,C)||(this.fire(new o.B(new Error(`Image "${w.name}" has invalid "content" value`))),O=!1),O}_validateStretch(w,C){if(!w)return!0;let O=0;for(const U of w){if(U[0]o.I.from(C))}getImageVersions(w){const C=this.imageVersions.get(w);if(C)return C}getImages(w,C,O){const U=[],Y=[],Z=this.imageProviders.get(C);for(const Ee of w){if(!Ee.iconsetId){U.push(Ee);continue}const He=Z.get(Ee.iconsetId);He&&(this.getImage(Ee,C)?Y.push(Ee):He.addPendingRequest(Ee))}if(U.length===0)return void this._notify(Y,C,O);let se=!0;const pe=!!this.loaded.get(C),je=this.images.get(C);if(!pe)for(const Ee of U)je.has(Ee.toString())||(se=!1);pe||se?this._notify(U,C,O):this.requestors.push({ids:U,scope:C,callback:O})}rasterizeImages(w,C){const O=new Map,{tasks:U,scope:Y}=w;for(const[Z,se]of U.entries()){const pe=this.getImage(se.id,Y);pe&&O.set(Z,{image:pe,imageVariant:se})}this._rasterizeImages(Y,O,C)}_rasterizeImages(w,C,O){if(o.y())this.imageRasterizerDispatcher.getActor().send("rasterizeImagesWorker",{tasks:C,scope:w},O);else{const U=new Map;for(const[Y,{image:Z,imageVariant:se}]of C.entries())U.set(Y,this.imageRasterizer.rasterize(se,Z,w,0));O(void 0,U)}}getUpdatedImages(w){return this.updatedImages.get(w)||new Set}_notify(w,C,O){const U=this.images.get(C),Y=new Map;for(const Z of w){if(!U.get(Z.toString())){if(Z.iconsetId)continue;this.fire(new o.C("styleimagemissing",{id:Z.name}))}const se=U.get(Z.toString());if(!se){o.w(`Image "${Z.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 pe={data:se.usvg?null:se.data.clone(),pixelRatio:se.pixelRatio,sdf:se.sdf,usvg:se.usvg,stretchX:se.stretchX,stretchY:se.stretchY,content:se.content,hasRenderCallback:!!(se.userImage&&se.userImage.render)};se.usvg&&Object.assign(pe,{width:se.icon.usvg_tree.width,height:se.icon.usvg_tree.height}),Y.set(o.I.toString(Z),pe)}O(null,{images:Y,versions:this.getImageVersions(C)})}getPixelSize(w){const{width:C,height:O}=this.atlasImage.get(w);return{width:C,height:O}}getPattern(w,C,O){const U=w.toString(),Y=this.patterns.get(C),Z=Y.get(U),se=this.getImage(w,C);if(!se)return null;if(Z){if(Z.position.version===se.version)return Z.position;Z.position.version=se.version}else{if(se.usvg&&!se.data){const pe=this.getPatternInFlightId(U,C);if(this.patternsInFlight.has(pe))return null;this.patternsInFlight.add(pe);const je=new o.D(w).scaleSelf(o.o.devicePixelRatio),Ee=new Map([[je.toString(),{image:se,imageVariant:je}]]);return this._rasterizeImages(C,Ee,(He,qe)=>this.storePatternImage(je,C,se,O,qe)),null}this.storePattern(w,C,se)}return this._updatePatternAtlas(C,O),Y.get(U).position}getPatternInFlightId(w,C){return o.F(w,C)}hasPatternsInFlight(){return this.patternsInFlight.size!==0}storePatternImage(w,C,O,U,Y){const Z=w.toString(),se=Y?Y.get(Z):void 0;se&&(O.data=se,this.storePattern(w.id,C,O),this._updatePatternAtlas(C,U),this.patternsInFlight.delete(this.getPatternInFlightId(w.id.toString(),C)))}storePattern(w,C,O){const U={w:O.data.width+2*o.G,h:O.data.height+2*o.G,x:0,y:0},Y=new o.H(U,O,o.G);this.patterns.get(C).set(w.toString(),{bin:U,position:Y})}destroyAtlasTextures(){for(const w of this.atlasTexture.values())w&&w.destroy();this.atlasTexture.clear()}bind(w,C){const O=w.gl;let U=this.atlasTexture.get(C);U?this.dirty&&(U.update(this.atlasImage.get(C)),this.dirty=!1):(U=new o.T(w,this.atlasImage.get(C),O.RGBA8),this.atlasTexture.set(C,U)),U.bind(O.LINEAR,O.CLAMP_TO_EDGE)}_updatePatternAtlas(w,C){const O=this.patterns.get(w),U=Array.from(O.values()).map(({bin:je})=>je),{w:Y,h:Z}=o.J(U),se=this.atlasImage.get(w);se.resize({width:Y||1,height:Z||1});const pe=this.images.get(w);for(const[je,{bin:Ee,position:He}]of O.entries()){let qe=He.padding;const et=Ee.x+qe,ct=Ee.y+qe,ot=pe.get(je).data,bt=ot.width,vt=ot.height;qe=qe>1?qe-1:qe,o.q.copy(ot,se,{x:0,y:0},{x:et,y:ct},{width:bt,height:vt},C),o.q.copy(ot,se,{x:0,y:vt-qe},{x:et,y:ct-qe},{width:bt,height:qe},C),o.q.copy(ot,se,{x:0,y:0},{x:et,y:ct+vt},{width:bt,height:qe},C),o.q.copy(ot,se,{x:bt-qe,y:0},{x:et-qe,y:ct},{width:qe,height:vt},C),o.q.copy(ot,se,{x:0,y:0},{x:et+bt,y:ct},{width:qe,height:vt},C),o.q.copy(ot,se,{x:bt-qe,y:vt-qe},{x:et-qe,y:ct-qe},{width:qe,height:qe},C),o.q.copy(ot,se,{x:0,y:vt-qe},{x:et+bt,y:ct-qe},{width:qe,height:qe},C),o.q.copy(ot,se,{x:0,y:0},{x:et+bt,y:ct+vt},{width:qe,height:qe},C),o.q.copy(ot,se,{x:bt-qe,y:0},{x:et-qe,y:ct+vt},{width:qe,height:qe},C)}this.dirty=!0}beginFrame(){for(const w of this.images.keys())this.callbackDispatchedThisFrame.set(w,new Set)}dispatchRenderCallbacks(w,C){const O=this.images.get(C);for(const U of w){if(this.callbackDispatchedThisFrame.get(C).has(U.toString()))continue;this.callbackDispatchedThisFrame.get(C).add(U.toString());const Y=O.get(U.toString());Je(Y)&&this.updateImage(U,C,Y)}}destroy(){this.imageRasterizerDispatcher&&this.imageRasterizerDispatcher.remove()}}function Xs(D){const w=D.value,C=D.valueSpec,O=D.style,U=D.styleSpec,Y=D.key,Z=D.arrayElementValidator||ia;if(!Array.isArray(w))return[new o.V(Y,w,`array expected, ${o.M(w)} found`)];if(C.length&&w.length!==C.length)return[new o.V(Y,w,`array length ${C.length} expected, length ${w.length} found`)];if(C["min-length"]&&w.lengthU)return[new o.V(w,C,`${C} is greater than the maximum value ${U}`)]}return[]}function Vt(D){const w=D.key,C=D.value;if(!o.K(C))return[new o.V(w,C,`object expected, ${o.M(C)} found`)];const O=D.valueSpec,U=o.L(C.type);let Y,Z,se,pe={};const je=U!=="categorical"&&C.property===void 0,Ee=!je,He=function(ot){const bt=ot.stops;return Array.isArray(bt)&&Array.isArray(bt[0])&&o.K(bt[0][0])}(C),qe=vr({key:D.key,value:D.value,valueSpec:D.styleSpec.function,style:D.style,styleSpec:D.styleSpec,objectElementValidators:{stops:function(ot){if(U==="identity")return[new o.V(ot.key,ot.value,'identity function may not have a "stops" property')];let bt=[];const vt=ot.value;return bt=bt.concat(Xs({key:ot.key,value:vt,valueSpec:ot.valueSpec,style:ot.style,styleSpec:ot.styleSpec,arrayElementValidator:et})),Array.isArray(vt)&&vt.length===0&&bt.push(new o.V(ot.key,vt,"array must have at least one stop")),bt},default:function(ot){return ia({key:ot.key,value:ot.value,valueSpec:O,style:ot.style,styleSpec:ot.styleSpec})}}});return U==="identity"&&je&&qe.push(new o.V(D.key,D.value,'missing required property "property"')),U==="identity"||C.stops||qe.push(new o.V(D.key,D.value,'missing required property "stops"')),U==="exponential"&&O.expression&&!o.O(O)&&qe.push(new o.V(D.key,D.value,"exponential functions not supported")),D.styleSpec.$version>=8&&(Ee&&!o.Q(O)?qe.push(new o.V(D.key,D.value,"property functions not supported")):je&&!o.S(O)&&qe.push(new o.V(D.key,D.value,"zoom functions not supported"))),U!=="categorical"&&!He||C.property!==void 0||qe.push(new o.V(D.key,D.value,'"property" property is required')),qe;function et(ot){let bt=[];const vt=ot.value,Pt=ot.key;if(!Array.isArray(vt))return[new o.V(Pt,vt,`array expected, ${o.M(vt)} found`)];if(vt.length!==2)return[new o.V(Pt,vt,`array length 2 expected, length ${vt.length} found`)];if(He){if(!o.K(vt[0]))return[new o.V(Pt,vt,`object expected, ${o.M(vt[0])} found`)];const Ft=vt[0];if(Ft.zoom===void 0)return[new o.V(Pt,vt,"object stop key must have zoom")];if(Ft.value===void 0)return[new o.V(Pt,vt,"object stop key must have value")];const jt=o.L(Ft.zoom);if(typeof jt!="number")return[new o.V(Pt,Ft.zoom,"stop zoom values must be numbers")];if(se&&se>jt)return[new o.V(Pt,Ft.zoom,"stop zoom values must appear in ascending order")];jt!==se&&(se=jt,Z=void 0,pe={}),bt=bt.concat(vr({key:`${Pt}[0]`,value:vt[0],valueSpec:{zoom:{}},style:ot.style,styleSpec:ot.styleSpec,objectElementValidators:{zoom:zs,value:ct}}))}else bt=bt.concat(ct({key:`${Pt}[0]`,value:vt[0],style:ot.style,styleSpec:ot.styleSpec},vt));return o.U(o.W(vt[1]))?bt.concat([new o.V(`${Pt}[1]`,vt[1],"expressions are not allowed in function stops.")]):bt.concat(ia({key:`${Pt}[1]`,value:vt[1],valueSpec:O,style:ot.style,styleSpec:ot.styleSpec}))}function ct(ot,bt){const vt=o.M(ot.value),Pt=o.L(ot.value),Ft=ot.value!==null?ot.value:bt;if(Y){if(vt!==Y)return[new o.V(ot.key,Ft,`${vt} stop domain type must match previous stop domain type ${Y}`)]}else Y=vt;if(vt!=="number"&&vt!=="string"&&vt!=="boolean"&&typeof Pt!="number"&&typeof Pt!="string"&&typeof Pt!="boolean")return[new o.V(ot.key,Ft,"stop domain value must be a number, string, or boolean")];if(vt!=="number"&&U!=="categorical"){let jt=`number expected, ${vt} found`;return o.Q(O)&&U===void 0&&(jt+='\nIf you intended to use a categorical function, specify `"type": "categorical"`.'),[new o.V(ot.key,Ft,jt)]}return U!=="categorical"||vt!=="number"||typeof Pt=="number"&&isFinite(Pt)&&Math.floor(Pt)===Pt?U!=="categorical"&&vt==="number"&&typeof Pt=="number"&&typeof Z=="number"&&Z!==void 0&&Ptnew o.V(`${D.key}${O.key}`,D.value,O.message));const C=w.value.expression||w.value._styleExpression.expression;if(D.expressionContext==="property"&&D.propertyKey==="text-font"&&!C.outputDefined())return[new o.V(D.key,D.value,`Invalid data expression for "${D.propertyKey}". Output values must be contained as literals within the expression.`)];if(D.expressionContext==="property"&&D.propertyType==="layout"&&!o.$(C))return[new o.V(D.key,D.value,'"feature-state" data expressions are not supported with layout properties.')];if(D.expressionContext==="filter")return Os(C,D);if(D.expressionContext==="appearance")return Nt(C,D);if(D.expressionContext&&D.expressionContext.indexOf("cluster")===0){if(!o.Z(C,["zoom","feature-state"]))return[new o.V(D.key,D.value,'"zoom" and "feature-state" expressions are not supported with cluster properties.')];if(D.expressionContext==="cluster-initial"&&!o._(C))return[new o.V(D.key,D.value,"Feature data expressions are not supported with initial expression part of cluster properties.")]}return[]}function Os(D,w){const C=new Set(["zoom","feature-state","pitch","distance-from-center"]);if(w.valueSpec&&w.valueSpec.expression)for(const U of w.valueSpec.expression.parameters)C.delete(U);if(C.size===0)return[];const O=[];return D instanceof o.a0&&C.has(D.name)?[new o.V(w.key,w.value,`["${D.name}"] expression is not supported in a filter for a ${w.object.type} layer with id: ${w.object.id}`)]:(D.eachChild(U=>{O.push(...Os(U,w))}),O)}function Nt(D,w){const C=new Set;if(w.valueSpec&&w.valueSpec.expression)for(const U of w.valueSpec.expression.parameters)C.add(U);if(C.size===0)return[];const O=[];return D instanceof o.a0&&!C.has(D.name)?[new o.V(w.key,w.value,`["${D.name}"] is not an allowed parameter`)]:(D.eachChild(U=>{O.push(...Nt(U,w))}),O)}function ms(D){const w=D.key,C=D.value,O=D.valueSpec,U=[];return Array.isArray(O.values)?O.values.indexOf(o.L(C))===-1&&U.push(new o.V(w,C,`expected one of [${O.values.join(", ")}], ${JSON.stringify(C)} found`)):Object.keys(O.values).indexOf(o.L(C))===-1&&U.push(new o.V(w,C,`expected one of [${Object.keys(O.values).join(", ")}], ${JSON.stringify(C)} found`)),U}function Ys(D){return o.a4(o.W(D.value))?At(Object.assign({},D,{expressionContext:"filter",valueSpec:D.styleSpec[`filter_${D.layerType||"fill"}`]})):It(D)}function It(D){const w=D.value,C=D.key;if(!Array.isArray(w))return[new o.V(C,w,`array expected, ${o.M(w)} found`)];if(w.length<1)return[new o.V(C,w,"filter array must have at least 1 element")];const O=D.styleSpec;let U=ms({key:`${C}[0]`,value:w[0],valueSpec:O.filter_operator});const Y=()=>{w.length>=2&&(o.a2(w[1])||U.push(new o.V(`${C}[1]`,w[1],`string expected, ${o.M(w[1])} found`)));for(let Z=2;Z":case">=":w.length>=2&&o.L(w[1])==="$type"&&U.push(new o.V(C,w,`"$type" cannot be use with operator "${w[0]}"`)),w.length!==3&&U.push(new o.V(C,w,`filter array for operator "${w[0]}" must have 3 elements`)),Y();break;case"==":case"!=":w.length!==3&&U.push(new o.V(C,w,`filter array for operator "${w[0]}" must have 3 elements`)),Y();break;case"in":case"!in":Y();break;case"any":case"all":case"none":for(let Z=1;Z{je in C&&w.push(new o.V(O,C[je],`"${je}" is prohibited for ref layers`))}),U.layers.forEach(je=>{o.L(je.id)===se&&(pe=je)}),pe?pe.ref?w.push(new o.V(O,C.ref,"ref cannot reference another ref layer")):Z=o.L(pe.type):typeof se=="string"&&w.push(new o.V(O,C.ref,`ref layer "${se}" not found`))}else if(Z!=="background"&&Z!=="sky"&&Z!=="slot")if(C.source)if(o.a2(C.source)){const pe=U.sources&&U.sources[C.source],je=pe&&o.L(pe.type);pe?je==="vector"&&Z==="raster"?w.push(new o.V(O,C.source,`layer "${C.id}" requires a raster source`)):je==="raster"&&Z!=="raster"?w.push(new o.V(O,C.source,`layer "${C.id}" requires a vector source`)):je!=="vector"||C["source-layer"]?je==="raster-dem"&&Z!=="hillshade"?w.push(new o.V(O,C.source,"raster-dem source can only be used with layer type 'hillshade'.")):je!=="raster-array"||["raster","raster-particle"].includes(Z)?Z==="line"&&C.paint&&(C.paint["line-gradient"]||C.paint["line-trim-offset"])&&je==="geojson"&&!pe.lineMetrics?w.push(new o.V(O,C,`layer "${C.id}" specifies a line-gradient, which requires the GeoJSON source to have \`lineMetrics\` enabled.`)):Z==="raster-particle"&&je!=="raster-array"&&w.push(new o.V(O,C.source,`layer "${C.id}" requires a 'raster-array' source.`)):w.push(new o.V(O,C.source,"raster-array source can only be used with layer type 'raster'.")):w.push(new o.V(O,C,`layer "${C.id}" must specify a "source-layer"`)):w.push(new o.V(O,C.source,`source "${C.source}" not found`))}else w.push(new o.V(`${O}.source`,C.source,'"source" must be a string'));else w.push(new o.V(O,C,'missing required property "source"'));return w=w.concat(vr({key:O,value:C,valueSpec:Y.layer,style:D.style,styleSpec:D.styleSpec,objectElementValidators:{"*":()=>[],type:()=>ia({key:`${O}.type`,value:C.type,valueSpec:Y.layer.type,style:D.style,styleSpec:D.styleSpec,object:C,objectKey:"type"}),filter:pe=>Ys(Object.assign({layerType:Z},pe)),layout:pe=>vr({layer:C,key:pe.key,value:pe.value,valueSpec:{},style:pe.style,styleSpec:pe.styleSpec,objectElementValidators:{"*":je=>Hs(Object.assign({layerType:Z},je))}}),paint:pe=>vr({layer:C,key:pe.key,value:pe.value,valueSpec:{},style:pe.style,styleSpec:pe.styleSpec,objectElementValidators:{"*":je=>As(Object.assign({layerType:Z,layer:C},je))}}),appearances(pe){const je=Xs({key:pe.key,value:pe.value,valueSpec:pe.valueSpec,style:pe.style,styleSpec:pe.styleSpec,arrayElementValidator:qe=>function(et){const{key:ct,layer:ot,layerType:bt}=et,vt=o.L(et.value),Pt=o.L(vt.name),Ft=o.L(vt.condition),jt=vr({key:ct,value:vt,valueSpec:et.styleSpec.appearance,style:et.style,styleSpec:et.styleSpec,objectElementValidators:{condition:ys=>function(Qt){const gs=[];return gs.push(...At({key:Qt.key,value:Qt.object.condition,valueSpec:o.a8.appearance.condition,expressionContext:"appearance"})),gs}(Object.assign({layer:ot,layerType:bt},ys)),properties:ys=>function(Qt){const gs=[],{styleSpec:$t,layer:Zt,layerType:hs}=Qt,Us=$t[`paint_${hs}`],Cs=$t[`layout_${hs}`],hn=Qt.object[Qt.objectKey];for(const an in hn){const An=an in Us?"paint":an in Cs?"layout":void 0;if(!An){gs.push(new o.V(Qt.key,an,`unknown property "${an}" for layer type "${hs}"`));continue}const On=Object.assign({},Qt,{key:`${Qt.key}.${an}`,object:hn,objectKey:an,layer:Zt,layerType:hs,value:hn[an],valueSpec:An==="paint"?Us[an]:Cs[an]});gs.push(...Ds(On,An))}return gs}(Object.assign({layer:ot,layerType:bt},ys))}});return Pt!=="hidden"&&Ft===void 0&&jt.push(new o.V(et.key,"name",'Appearance with name different than "hidden" must have a condition')),jt}(Object.assign({layerType:Z,layer:C},qe))}),Ee=Array.isArray(pe.value)?pe.value:[],He=new Set;return Ee.forEach((qe,et)=>{const ct=o.L(qe.name);if(ct)if(He.has(ct)){const ot=o.L(C.id);je.push(new o.V(pe.key,ct,`Duplicated appearance name "${ct}" for layer "${ot}"`))}else He.add(ct)}),je}}})),w}function en({key:D,value:w}){return o.a2(w)?[]:[new o.V(D,w,`string expected, ${o.M(w)} found`)]}const Rn={promoteId:function D({key:w,value:C}){if(o.a2(C))return en({key:w,value:C});if(Array.isArray(C)){const U=[],Y=o.W(C),Z=o.X(Y);return Z.result==="error"?(Z.value.forEach(se=>{U.push(new o.V(`${w}${se.key}`,null,`${se.message}`))}),U):(o.Z(Z.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"])||U.push(new o.V(`${w}`,null,"promoteId expression should be only feature dependent")),U)}if(!o.K(C))return[new o.V(w,C,`string, expression or object expected, "${o.M(C)}" found`)];const O=[];for(const U in C)O.push(...D({key:`${w}.${U}`,value:C[U]}));return O}};function Bn(D){const w=D.value,C=D.key,O=D.styleSpec,U=D.style;if(!o.K(w))return[new o.V(C,w,`object expected, ${o.M(w)} found`)];if(!("type"in w))return[new o.V(C,w,'"type" is required')];const Y=o.L(w.type);let Z=[];switch(["vector","raster","raster-dem","raster-array"].includes(Y)&&("url"in w||"tiles"in w||Z.push(new o.a5(C,w,'Either "url" or "tiles" is required.'))),Y){case"vector":case"raster":case"raster-dem":case"raster-array":return Z=Z.concat(vr({key:C,value:w,valueSpec:O[`source_${Y.replace("-","_")}`],style:D.style,styleSpec:O,objectElementValidators:Rn})),Z;case"geojson":if(Z=vr({key:C,value:w,valueSpec:O.source_geojson,style:U,styleSpec:O,objectElementValidators:Rn}),"cluster"in w&&"clusterProperties"in w){if(!o.K(w.clusterProperties))return[new o.V(`${C}.clusterProperties`,w,`object expected, ${o.M(w)} found`)];for(const se in w.clusterProperties){const pe=w.clusterProperties[se];if(!Array.isArray(pe))return[new o.V(`${C}.clusterProperties.${se}`,pe,"array expected")];const[je,Ee]=pe,He=typeof je=="string"?[je,["accumulated"],["get",se]]:je;Z.push(...At({key:`${C}.${se}.map`,value:Ee,expressionContext:"cluster-map"})),Z.push(...At({key:`${C}.${se}.reduce`,value:He,expressionContext:"cluster-reduce"}))}}return Z;case"video":return vr({key:C,value:w,valueSpec:O.source_video,style:U,styleSpec:O});case"image":return vr({key:C,value:w,valueSpec:O.source_image,style:U,styleSpec:O});case"canvas":return[new o.V(C,null,"Please use runtime APIs to add canvas sources, rather than including them in stylesheets.","source.canvas")];default:return ms({key:`${C}.type`,value:w.type,valueSpec:{values:Dn(O)}})}}function Dn(D){return D.source.reduce((w,C)=>{const O=D[C];return O.type.type==="enum"&&(w=w.concat(Object.keys(O.type.values||{}))),w},[])}function Jn(D){const w=D.value,C=D.styleSpec,O=C.light,U=D.style;if(w===void 0)return[];if(!o.K(w))return[new o.V("light",w,`object expected, ${o.M(w)} found`)];let Y=[];for(const Z in w){const se=Z.match(/^(.*)-transition$/),pe=Z.match(/^(.*)-use-theme$/);Y=Y.concat(pe&&O[pe[1]]?ia({key:Z,value:w[Z],valueSpec:{type:"string"},style:U,styleSpec:C}):se&&O[se[1]]&&O[se[1]].transition?ia({key:Z,value:w[Z],valueSpec:C.transition,style:U,styleSpec:C}):O[Z]?ia({key:Z,value:w[Z],valueSpec:O[Z],style:U,styleSpec:C}):[new o.V(Z,w[Z],`unknown property "${Z}"`)])}return Y}function ua(D){const w=D.value;if(!w)return[];const C=D.key;if(!o.K(w))return[new o.V(C,w,`object expected, ${o.M(w)} found`)];let O=[];const U=D.styleSpec,Y=U["light-3d"],Z=D.style,se=D.style.lights;for(const Ee of["type","id"])if(!(Ee in w))return O=O.concat([new o.V(C,w,`missing property "${Ee}"`)]),O;if(!o.a2(w.type))return O=O.concat([new o.V(`${C}.type`,w.type,"string expected")]),O;if(se)for(let Ee=0;Ee[],array:Xs,boolean:function(D){const w=D.value,C=D.key;return o.a1(w)?[]:[new o.V(C,w,`boolean expected, ${o.M(w)} found`)]},number:zs,color:function({key:D,value:w}){return o.a2(w)?o.a3.parseCSSColor(w)===null?[new o.V(D,w,`color expected, "${w}" found`)]:[]:[new o.V(D,w,`color expected, ${o.M(w)} found`)]},enum:ms,filter:Ys,function:Vt,layer:Rs,object:vr,source:Bn,model:o.a9,light:Jn,"light-3d":ua,terrain:Mr,fog:sn,string:en,formatted:function(D){return en(D).length===0?[]:At(D)},resolvedImage:function(D){return en(D).length===0?[]:At(D)},projection:function(D){const w=D.value,C=D.styleSpec,O=C.projection,U=D.style;if(o.K(w)){let Y=[];for(const Z in w)Y=Y.concat(ia({key:Z,value:w[Z],valueSpec:O[Z],style:U,styleSpec:C}));return Y}return o.a2(w)?[]:[new o.V("projection",w,`object or string expected, ${o.M(w)} found`)]},import:function(D){const w=D.key,{value:C,styleSpec:O}=D;if(!o.K(C))return[new o.V(w,C,"import must be an object")];const{data:U,...Y}=C;Object.defineProperty(Y,"__line__",{value:C.__line__,enumerable:!1});let Z=vr(Object.assign({},D,{value:Y,valueSpec:O.import}));return o.L(Y.id)===""&&Z.push(new o.V(`${D.key}.id`,Y,"import id can't be an empty string")),U&&(Z=Z.concat(rn(U,O,{key:`${D.key}.data`}))),Z},iconset:function(D){const w=D.value,C=D.key,O=D.styleSpec,U=D.style;if(!o.K(w))return[new o.V(C,w,"object expected")];if(!w.type)return[new o.V(C,w,'"type" is required')];const Y=o.L(w.type);let Z=[];if(Z=Z.concat(vr({key:C,value:w,valueSpec:O[`iconset_${Y}`],style:U,styleSpec:O})),function(se,pe){return!(se!=="source"||!pe.source)}(Y,w)){const se=U.sources&&U.sources[w.source],pe=se&&o.L(se.type);se?pe!=="raster-array"&&Z.push(new o.V(C,w.source,`iconset cannot be used with a source of type ${String(pe)}, it only be used with a "raster-array" source type`)):Z.push(new o.V(C,w.source,`source "${w.source}" not found`))}return Z}};function ia(D,w=!1){const C=D.value,O=D.valueSpec,U=D.styleSpec;if(O.expression){if(o.a6(o.L(C)))return Vt(D);if(o.U(o.W(C)))return At(D)}if(O.type&&ki[O.type]){const Y=ki[O.type](D);return w===!0&&Y.length>0&&Array.isArray(D.value)?At(D):Y}return vr(Object.assign({},D,{valueSpec:O.type?U[O.type]:O}))}function vr(D){const w=D.key,C=D.value,O=D.valueSpec||{},U=D.objectElementValidators||{},Y=D.style,Z=D.styleSpec;if(!o.K(C))return[new o.V(w,C,`object expected, ${o.M(C)} found`)];let se=[];for(const pe in C){const je=pe.split(".")[0];let Ee;U[je]?Ee=U[je]:O[je]?Ee=ia:U["*"]?Ee=U["*"]:O["*"]&&(Ee=ia),Ee?se=se.concat(Ee({key:(w&&`${w}.`)+pe,value:C[pe],valueSpec:O[je]||O["*"],style:Y,styleSpec:Z,object:C,objectKey:pe},C)):se.push(new o.a5(w,C[pe],`unknown property "${pe}"`))}for(const pe in O){if(U[pe])continue;const je=O[pe];je.required&&je.default===void 0&&C[pe]===void 0&&se.push(new o.V(w,C,`missing required property "${pe}"`))}return se}function Nr({key:D,value:w}){const C=en({key:D,value:w});if(C.length)return C;const O=w;return O.indexOf("{fontstack}")===-1&&C.push(new o.V(D,w,'"glyphs" url must include a "{fontstack}" token')),O.indexOf("{range}")===-1&&C.push(new o.V(D,w,'"glyphs" url must include a "{range}" token')),C}function rn(D,w=o.a8,C={}){return vr({key:C.key||"",value:D,valueSpec:Object.assign(w.$root,{"*":{type:"*"}}),styleSpec:w,style:D,objectElementValidators:{glyphs:Nr}})}function Zn(D,w=o.a8){return gn(rn(D,w))}const sa=D=>gn(Bn(D)),xs=D=>gn(Jn(D)),Ve=D=>gn(ua(D)),it=D=>gn(Mr(D)),ft=D=>gn(sn(D)),kt=D=>gn(function(w){const C=w.value,O=w.style,U=w.styleSpec,Y=U.snow;if(C===void 0)return[];if(!o.K(C))return[new o.V("snow",C,`object expected, ${o.M(C)} found`)];let Z=[];for(const se in C){const pe=se.match(/^(.*)-transition$/);Z=Z.concat(pe&&Y[pe[1]]&&Y[pe[1]].transition?ia({key:se,value:C[se],valueSpec:U.transition,style:O,styleSpec:U}):Y[se]?ia({key:se,value:C[se],valueSpec:Y[se],style:O,styleSpec:U}):[new o.a5(se,C[se],`unknown property "${se}"`)])}return Z}(D)),Ut=D=>gn(function(w){const C=w.value,O=w.style,U=w.styleSpec,Y=U.rain;if(C===void 0)return[];if(!o.K(C))return[new o.V("rain",C,`object expected, ${o.M(C)} found`)];let Z=[];for(const se in C){const pe=se.match(/^(.*)-transition$/);Z=Z.concat(pe&&Y[pe[1]]&&Y[pe[1]].transition?ia({key:se,value:C[se],valueSpec:U.transition,style:O,styleSpec:U}):Y[se]?ia({key:se,value:C[se],valueSpec:Y[se],style:O,styleSpec:U}):[new o.a5(se,C[se],`unknown property "${se}"`)])}return Z}(D)),es=D=>gn(Rs(D)),Ms=D=>gn(Ys(D)),bs=D=>gn(As(D)),Zs=D=>gn(Hs(D)),kn=D=>gn(o.a9(D));function gn(D){return D.slice().sort((w,C)=>w.line&&C.line?w.line-C.line:0)}function xr(D,w){let C=!1;if(w&&w.length)for(const O of w)O instanceof o.a5?o.w(O.message):(D.fire(new o.B(new Error(O.message))),C=!0);return C}const Kr=o.a8.light;let ca;class Er extends o.E{constructor(w,C="flat"){super(),this._transitionable=new o.aa(ca||(ca=new o.ab({anchor:new o.ac(Kr.anchor),position:new o.ad(Kr.position),color:new o.ac(Kr.color),intensity:new o.ac(Kr.intensity)}))),this.setLight(w,C),this._transitioning=this._transitionable.untransitioned()}getLight(){return this._transitionable.serialize()}setLight(w,C,O={}){this._validate(xs,w,O)||(this._transitionable.setTransitionOrValue(w),this.id=C)}updateTransitions(w){this._transitioning=this._transitionable.transitioned(w,this._transitioning)}hasTransition(){return this._transitioning.hasTransition()}recalculate(w){this.properties=this._transitioning.possiblyEvaluate(w)}_validate(w,C,O){return(!O||O.validate!==!1)&&xr(this,w.call(Zn,Object.assign({value:C,style:{glyphs:!0,sprite:!0},styleSpec:o.a8})))}}const qr=o.a8.terrain;let Xt=class extends o.E{constructor(D,w,C,O,U){super(),this.scope=C,this._transitionable=new o.aa(new o.ab({source:new o.ac(qr.source),exaggeration:new o.ac(qr.exaggeration)}),C,O),this._transitionable.setTransitionOrValue(D,O),this._transitioning=this._transitionable.untransitioned(),this.drapeRenderMode=w,this.worldview=U}get(){return this._transitionable.serialize()}set(D,w){this._transitionable.setTransitionOrValue(D,w)}updateTransitions(D){this._transitioning=this._transitionable.transitioned(D,this._transitioning)}hasTransition(){return this._transitioning.hasTransition()}recalculate(D){this.properties=this._transitioning.possiblyEvaluate(D)}getExaggeration(D){return this._transitioning.possiblyEvaluate(new o.ae(D,{worldview:this.worldview})).get("exaggeration")}getAttenuationRange(){if(!this.isZoomDependent())return null;const D=this._transitionable._values.exaggeration;if(!D)return null;const w=D.value.expression;if(!w)return null;let C=-1,O=-1,U=1;for(const Y of w.zoomStops)U=w.evaluate(new o.ae(Y,{worldview:this.worldview})),U>.01?(C=Y,O=-1):O=Y;return U<.01&&C>0&&O>C?[C,O]:null}isZoomDependent(){const D=this._transitionable._values.exaggeration;return D!=null&&D.value!=null&&D.value.expression!=null&&D.value.expression instanceof o.af}};const Gn=.05;function Jr(D,w,C,O){const U=o.aj(45,65,C),[Y,Z]=Or(D,O);let se=1-Math.min(1,Math.exp((w-Y)/(Z-Y)*-6));return se*=se*se,se=Math.min(1,1.00747*se),se*U*D.alpha}function Or(D,w){const C=.5/Math.tan(.5*w);return[D.range[0]+C,D.range[1]+C]}function ja(D,w,C,O,U){const Y=o.ah([],[w,C,O],U.mercatorFogMatrix);return Jr(D,o.ai(Y),U.pitch,U._fov)}function ea(D,w,C,O,U,Y,Z){const se=[[C,O,0],[U,O,0],[U,Y,0],[C,Y,0]];let pe=Number.MAX_VALUE,je=-Number.MAX_VALUE;for(const Ee of se){const He=o.ah([],Ee,w),qe=o.ai(He);pe=Math.min(pe,qe),je=Math.max(je,qe)}return[Jr(D,pe,Z.pitch,Z._fov),Jr(D,je,Z.pitch,Z._fov)]}const dr=o.a8.fog;class Wi extends o.E{constructor(w,C,O,U){super();const Y=new o.ab({range:new o.ac(dr.range),color:new o.ac(dr.color),"color-use-theme":new o.ac({type:"string","property-type":"data-constant",default:"default"}),"high-color":new o.ac(dr["high-color"]),"high-color-use-theme":new o.ac({type:"string","property-type":"data-constant",default:"default"}),"space-color":new o.ac(dr["space-color"]),"space-color-use-theme":new o.ac({type:"string","property-type":"data-constant",default:"default"}),"horizon-blend":new o.ac(dr["horizon-blend"]),"star-intensity":new o.ac(dr["star-intensity"]),"vertical-range":new o.ac(dr["vertical-range"])});this._transitionable=new o.aa(Y,O,new Map(U)),this.set(w,U),this._transitioning=this._transitionable.untransitioned(),this._transform=C,this.properties=new o.ak(Y),this.scope=O}get state(){const w=this._transform,C=w.projection.name==="globe",O=o.al(w.zoom),U=this.properties.get("range"),Y=[.5,3];return{range:C?[o.am(Y[0],U[0],O),o.am(Y[1],U[1],O)]:U,horizonBlend:this.properties.get("horizon-blend"),alpha:this.properties.get("color").a}}get(){return this._transitionable.serialize()}set(w,C,O={}){if(this._validate(ft,w,O))return;const U=Object.assign({},w);for(const Y of Object.keys(dr))U[Y]===void 0&&(U[Y]=dr[Y].default);this._options=U,this._transitionable.setTransitionOrValue(this._options,C)}getOpacity(w){if(!this._transform.projection.supportsFog)return 0;const C=this.properties&&this.properties.get("color")||1;return(this._transform.projection.name==="globe"?1:o.aj(45,65,w))*C.a}getOpacityAtLatLng(w,C){return this._transform.projection.supportsFog?function(O,U,Y){const Z=o.ag.fromLngLat(U),se=Y.elevation?Y.elevation.getAtPointOrZero(Z):0;return ja(O,Z.x,Z.y,se,Y)}(this.state,w,C):0}getOpacityForTile(w){if(!this._transform.projection.supportsFog)return[1,1];const C=this._transform.calculateFogTileMatrix(w.toUnwrapped());return ea(this.state,C,0,0,o.an,o.an,this._transform)}getOpacityForBounds(w,C,O,U,Y){return this._transform.projection.supportsFog?ea(this.state,w,C,O,U,Y,this._transform):[1,1]}getFovAdjustedRange(w){return this._transform.projection.supportsFog?Or(this.state,w):[0,1]}isVisibleOnFrustum(w){if(!this._transform.projection.supportsFog)return!1;const C=[4,5,6,7];for(const O of C){const U=w.points[O];let Y;if(U[2]>=0)Y=U;else{const Z=w.points[O-4];Y=o.ao(Z,U,Z[2]/(Z[2]-U[2]))}if(ja(this.state,Y[0],Y[1],0,this._transform)>=Gn)return!0}return!1}updateConfig(w){this._transitionable.setTransitionOrValue(this._options,new Map(w))}updateTransitions(w){this._transitioning=this._transitionable.transitioned(w,this._transitioning)}hasTransition(){return this._transitioning.hasTransition()}recalculate(w){this.properties=this._transitioning.possiblyEvaluate(w)}_validate(w,C,O){return(!O||O.validate!==!1)&&xr(this,w.call(Zn,Object.assign({value:C,style:{glyphs:!0,sprite:!0},styleSpec:o.a8})))}}let ho,oa,Ha,$i=class extends o.E{constructor(D,w,C,O){super();const U=ho||(ho=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(U,C,new Map(O)),this.set(D,O),this._transitioning=this._transitionable.untransitioned(),this.properties=new o.ak(U),this.scope=C}get state(){const D=this.properties.get("opacity"),w=this.properties.get("color"),C=this.properties.get("direction"),O=o.ap(C[0]),U=-Math.max(o.ap(C[1]),.01),Y=[Math.cos(O)*Math.cos(U),Math.sin(O)*Math.cos(U),Math.sin(U)],Z=this.properties.get("vignette"),se=this.properties.get("vignette-color");return se.a=Z,{density:this.properties.get("density"),intensity:this.properties.get("intensity"),color:new o.aq(w.r,w.g,w.b,w.a*D),direction:Y,centerThinning:this.properties.get("center-thinning"),flakeSize:this.properties.get("flake-size"),vignetteColor:se}}get(){return this._transitionable.serialize()}set(D,w,C={}){if(this._validate(kt,D,C))return;const O=Object.assign({},D),U=o.a8.snow;for(const Y of Object.keys(U))O[Y]===void 0&&(O[Y]=U[Y].default);this._options=O,this._transitionable.setTransitionOrValue(this._options,w)}updateConfig(D){this._transitionable.setTransitionOrValue(this._options,new Map(D))}updateTransitions(D){this._transitioning=this._transitionable.transitioned(D,this._transitioning)}hasTransition(){return this._transitioning.hasTransition()}recalculate(D){this.properties=this._transitioning.possiblyEvaluate(D)}_validate(D,w,C){return(!C||C.validate!==!1)&&xr(this,D.call(Zn,Object.assign({value:w,style:{glyphs:!0,sprite:!0},styleSpec:o.a8})))}},Ta=class extends o.E{constructor(D,w,C,O){super();const U=oa||(oa=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(U,C,new Map(O)),this.set(D,O),this._transitioning=this._transitionable.untransitioned(),this.properties=new o.ak(U),this.scope=C}get state(){const D=this.properties.get("opacity"),w=this.properties.get("color"),C=this.properties.get("direction"),O=o.ap(C[0]),U=-Math.max(o.ap(C[1]),.01),Y=[Math.cos(O)*Math.cos(U),Math.sin(O)*Math.cos(U),Math.sin(U)],Z=this.properties.get("vignette-color");return Z.a=this.properties.get("vignette"),{density:this.properties.get("density"),intensity:this.properties.get("intensity"),color:new o.aq(w.r,w.g,w.b,w.a*D),direction:Y,centerThinning:this.properties.get("center-thinning"),dropletSize:this.properties.get("droplet-size"),distortionStrength:this.properties.get("distortion-strength"),vignetteColor:Z}}get(){return this._transitionable.serialize()}set(D,w,C={}){if(this._validate(Ut,D,C))return;const O=Object.assign({},D),U=o.a8.rain;for(const Y of Object.keys(U))O[Y]===void 0&&(O[Y]=U[Y].default);this._options=O,this._transitionable.setTransitionOrValue(this._options,w)}updateConfig(D){this._transitionable.setTransitionOrValue(this._options,new Map(D))}updateTransitions(D){this._transitioning=this._transitionable.transitioned(D,this._transitioning)}hasTransition(){return this._transitioning.hasTransition()}recalculate(D){this.properties=this._transitioning.possiblyEvaluate(D)}_validate(D,w,C){return(!C||C.validate!==!1)&&xr(this,D.call(Zn,Object.assign({value:w,style:{glyphs:!0,sprite:!0},styleSpec:o.a8})))}};class Wn extends o.E{constructor(w,C,O,U){super(),this.scope=O,this._options=w,this.properties=new o.ak(C),this._transitionable=new o.aa(C,O,new Map(U)),this._transitionable.setTransitionOrValue(w.properties),this._transitioning=this._transitionable.untransitioned()}updateConfig(w){this._transitionable.setTransitionOrValue(this._options.properties,new Map(w))}updateTransitions(w){this._transitioning=this._transitionable.transitioned(w,this._transitioning)}hasTransition(){return this._transitioning.hasTransition()}recalculate(w){this.properties=this._transitioning.possiblyEvaluate(w)}get(){return this._options.properties=this._transitionable.serialize(),this._options}set(w,C){this._options=w,this._transitionable.setTransitionOrValue(w.properties,C)}shadowsEnabled(){return!!this.properties&&this.properties.get("cast-shadows")===!0}}const Ra=()=>Ha||(Ha=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 mo;const Ho=()=>mo||(mo=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 No{constructor(w,C,O){this.screenBounds=w,this.cameraPoint=O.getCameraPoint(),this._screenRaycastCache={},this._cameraRaycastCache={},this.isAboveHorizon=C,this.screenGeometry=this.bufferedScreenGeometry(0),this.screenGeometryMercator=this._bufferedScreenMercator(0,O)}static createFromScreenPoints(w,C){let O,U;if(w instanceof o.P||typeof w[0]=="number"){const Y=o.P.convert(w);O=[Y],U=C.isPointAboveHorizon(Y)}else{const Y=o.P.convert(w[0]),Z=o.P.convert(w[1]),se=Y.add(Z)._div(2);O=[Y,Z],U=o.as(Y,Z).every(pe=>C.isPointAboveHorizon(pe))&&C.isPointAboveHorizon(se)}return new No(O,U,C)}isPointQuery(){return this.screenBounds.length===1}bufferedScreenGeometry(w){return o.as(this.screenBounds[0],this.screenBounds.length===1?this.screenBounds[0]:this.screenBounds[1],w)}bufferedCameraGeometry(w){const C=this.screenBounds[0],O=this.screenBounds.length===1?this.screenBounds[0].add(new o.P(1,1)):this.screenBounds[1],U=o.as(C,O,0,!1);return this.cameraPoint.y>O.y&&(this.cameraPoint.x>C.x&&this.cameraPoint.x=O.x?U[2]=this.cameraPoint:this.cameraPoint.x<=C.x&&(U[3]=this.cameraPoint)),o.at(U,w)}bufferedCameraGeometryGlobe(w){const C=this.screenBounds[0],O=this.screenBounds.length===1?this.screenBounds[0].add(new o.P(1,1)):this.screenBounds[1],U=o.as(C,O,w),Y=this.cameraPoint.clone(),Z=+(Y.x>C.x)+ +(Y.x>O.x);switch(3*(+(Y.y>C.y)+ +(Y.y>O.y))+Z){case 0:U[0]=Y,U[4]=Y.clone();break;case 1:U.splice(1,0,Y);break;case 2:U[1]=Y;break;case 3:U.splice(4,0,Y);break;case 5:U.splice(2,0,Y);break;case 6:U[3]=Y;break;case 7:U.splice(3,0,Y);break;case 8:U[2]=Y}return U}containsTile(w,C,O,U=0){const Y=Math.max(w.queryPadding,w.evaluateQueryRenderedFeaturePadding())/C._pixelsPerMercatorPixel+1,Z=O?this._bufferedCameraMercator(Y,C):this._bufferedScreenMercator(Y,C);let se=w.tileID.wrap+(Z.unwrapped?U:0);const pe=Z.polygon.map(bt=>o.au(w.tileTransform,bt,se));if(!o.av(pe,0,0,o.an,o.an))return;se=w.tileID.wrap+(this.screenGeometryMercator.unwrapped?U:0);const je=this.screenGeometryMercator.polygon.map(bt=>o.aw(w.tileTransform,bt,se)),Ee=je.map(bt=>new o.P(bt[0],bt[1])),He=C.getFreeCameraOptions().position||new o.ag(0,0,0),qe=o.aw(w.tileTransform,He,se),et=je.map(bt=>{const vt=o.ax(bt,bt,qe);return o.ay(vt,vt),new o.az(qe,vt)}),ct=o.aA(w,1,C.zoom)*C._pixelsPerMercatorPixel;return{queryGeometry:this,tilespaceGeometry:Ee,tilespaceRays:et,bufferedTilespaceGeometry:pe,bufferedTilespaceBounds:(ot=o.aB(pe),ot.min.x=o.aC(ot.min.x,0,o.an),ot.min.y=o.aC(ot.min.y,0,o.an),ot.max.x=o.aC(ot.max.x,0,o.an),ot.max.y=o.aC(ot.max.y,0,o.an),ot),tile:w,tileID:w.tileID,pixelToTileUnitsFactor:ct};var ot}_bufferedScreenMercator(w,C){const O=Tu(w);if(this._screenRaycastCache[O])return this._screenRaycastCache[O];{let U;return U=C.projection.name==="globe"?this._projectAndResample(this.bufferedScreenGeometry(w),C):{polygon:this.bufferedScreenGeometry(w).map(Y=>C.pointCoordinate3D(Y)),unwrapped:!0},this._screenRaycastCache[O]=U,U}}_bufferedCameraMercator(w,C){const O=Tu(w);if(this._cameraRaycastCache[O])return this._cameraRaycastCache[O];{let U;return U=C.projection.name==="globe"?this._projectAndResample(this.bufferedCameraGeometryGlobe(w),C):{polygon:this.bufferedCameraGeometry(w).map(Y=>C.pointCoordinate3D(Y)),unwrapped:!0},this._cameraRaycastCache[O]=U,U}}_projectAndResample(w,C){const O=function(Y,Z){const se=o.aD([],Z.pixelMatrix,Z.globeMatrix),pe=[0,-o.aF,0,1],je=[0,o.aF,0,1],Ee=[0,0,0,1];o.aE(pe,pe,se),o.aE(je,je,se),o.aE(Ee,Ee,se);const He=new o.P(pe[0]/pe[3],pe[1]/pe[3]),qe=new o.P(je[0]/je[3],je[1]/je[3]),et=o.aG(Y,He)&&pe[3]1?Go(Y.slice(0,bt),Z):[],Ft=btnew o.P(Dd(gs.x),gs.y)),Ft=Ft.map(gs=>new o.P(Dd(gs.x),gs.y));const jt=[...Pt];jt.length===0&&jt.push(Ft[Ft.length-1]);const ys=o.am(jt[jt.length-1].y,(Ft.length===0?Pt[0]:Ft[0]).y,vt);let Qt;return Qt=et?[new o.P(0,ys),new o.P(0,0),new o.P(1,0),new o.P(1,ys)]:[new o.P(1,ys),new o.P(1,1),new o.P(0,1),new o.P(0,ys)],jt.push(...Qt),Ft.length===0?jt.push(Pt[0]):jt.push(...Ft),{polygon:jt.map(gs=>new o.ag(gs.x,gs.y)),unwrapped:!1}}(w,C);if(O)return O;const U=function(Y,Z){let se=!1,pe=-1/0,je=0;for(let He=0;Hepe&&(pe=Y[He].x,je=He);for(let He=0;He.5&&(et.x{He.x-=1}),{polygon:Y,unwrapped:se}}(Go(w,C).map(Y=>new o.P(Dd(Y.x),Y.y)),C);return{polygon:U.polygon.map(Y=>new o.ag(Y.x,Y.y)),unwrapped:U.unwrapped}}}function Go(D,w){return o.aI(D,C=>{const O=w.pointCoordinate3D(C);C.x=O.x,C.y=O.y},1/256)}function Dd(D){return D<0?1+D%1:D%1}function Tu(D){return 100*D|0}function Vm(D,w,C){try{w=function(U){if(!U.variants)return U;if(!Array.isArray(U.variants))throw new Error("variants must be an array");for(const Y of U.variants){if(Y==null||typeof Y!="object"||Y.constructor!==Object)throw new Error("variant must be an object");if(!Array.isArray(Y.capabilities))throw new Error("capabilities must be an array");if(Y.capabilities.length===1&&Y.capabilities[0]==="meshopt")return Object.assign(U,Y)}return U}(w)}catch(U){return new Error("Failed to process TileJSON variants",{cause:U})}const O=o.aJ(Object.assign({},w,D),["tilejson","tiles","minzoom","maxzoom","attribution","mapbox_logo","bounds","extra_bounds","scheme","tileSize","encoding","vector_layers","raster_layers","worldview_options","worldview_default","worldview"]);return D.url&&w.tiles&&D.tiles&&(O.tiles=w.tiles),O.tiles=C.canonicalizeTileset(O,D.url),O}function Uc(D,w,C,O,U){const Y=function(se,pe){if(se)return U(se);if(pe){D.url&&pe.tiles&&D.tiles&&delete D.tiles;const je=Vm(D,pe,w);if(je instanceof Error)return U(je);U(null,je)}},Z=function(se,pe,je){if(!se)return null;if(!pe&&!je)return se;je=je||se.worldview_default;const Ee=Object.values(se.language||{});if(Ee.length===0)return null;const He=Object.values(se.worldview||{});if(He.length===0)return null;const qe=Ee.every(ct=>ct===pe),et=He.every(ct=>ct===je);return qe&&et?se:pe in(se.language_options||{})||je in(se.worldview_options||{})?null:se.language_options&&se.worldview_options?se:null}(D.data,C,O);return Z?o.o.frame(()=>Y(null,Z)):D.url?o.m(w.transformRequest(w.normalizeSourceURL(D.url,null,C,O),o.R.Source),Y):o.o.frame(()=>{const{data:se,...pe}=D;Y(null,pe)})}function Eu(D,w){const C=Math.pow(2,w.z),O=Math.floor(o.aH(D.getWest())*C),U=Math.floor(o.aL(D.getNorth())*C),Y=Math.ceil(o.aH(D.getEast())*C),Z=Math.ceil(o.aL(D.getSouth())*C);return w.x>=O&&w.x=U&&w.ythis.maxzoom||w.z{this._tileJSONRequest=null,this._loaded=!0,Z?(C&&console.warn(`Ensure that your requested language string is a valid BCP-47 code or list of codes. Found: ${C}`),O&&console.warn(`Requested worldview strings must be a valid ISO alpha-2 code. Found: ${O}`),this.fire(new o.B(Z))):se&&(this._setTileJSON(se),ve(se.tiles,this.map._requestManager._customAccessToken),this.fire(new o.C("data",{dataType:"source",sourceDataType:"metadata"})),this.fire(new o.C("data",{dataType:"source",sourceDataType:"content"}))),w&&w(Z)};this.provider=this._options.provider;const Y=function(Z){if("provider"in Z&&!Z.provider)return null;let se=Z.provider;if(!se&&"url"in Z&&Z.url&&(se=o.aM(Z.url)),!se)return null;const pe=o.g.TILE_PROVIDER_URLS[se];if(!pe)return null;let je;try{je=new URL(pe,o.g.API_URL).href}catch{return o.w(`TileProvider "${se}" has an invalid URL: "${pe}"`),null}return{name:se,url:je}}(this._options);if(this.provider&&!Y)return this._loaded=!0,this.fire(new o.B(new Error(`TileProvider "${this.provider}" is not registered`))),void(w&&w());this._tileJSONRequest=Y?this._loadWithProvider(Y,U):Uc(this._options,this.map._requestManager,C,O,U)}_loadWithProvider(w,C){this.provider=w.name;const O=new AbortController,U=this._options.url&&!this._options.tiles?this.map._requestManager.transformRequest(this._options.url,o.R.Source):void 0,Y=U?Object.assign({},this._options,{url:U.url}):this._options;return this.dispatcher.broadcast("loadTileProvider",{name:w.name,url:w.url,source:this.id,scope:this.scope,type:this.type,options:Y,request:U},(Z,se)=>{if(O.signal.aborted)return;if(Z)return void C(Z);const pe=se?se.find(je=>je!=null):null;if(pe){const je=Vm(this._options,pe,this.map._requestManager);je instanceof Error?C(je):C(null,je)}else C(null,{tiles:this._options.tiles})}),{cancel:()=>{O.abort()}}}_setTileJSON(w){if(Object.assign(this,w),this.hasWorldviews=!!w.worldview_options,w.worldview_default&&(this.worldviewDefault=w.worldview_default),w.vector_layers){this.vectorLayers=w.vector_layers,this.vectorLayerIds=[],this.localizableLayerIds=new Set;for(const C of w.vector_layers)this.vectorLayerIds.push(C.id),w.worldview&&w.worldview[C.source]&&this.localizableLayerIds.add(C.id)}this.tileBounds=Ec.fromTileJSON(w)}loaded(){return this._loaded}hasTile(w){return!this.tileBounds||this.tileBounds.contains(w.canonical)}onAdd(w){this.map=w,this.load()}reload(){this.cancelTileJSONRequest();const w=o.F(this.id,this.scope);this.load(()=>this.map.style.clearSource(w))}setTiles(w){return this._options.tiles=w,this.reload(),this}setUrl(w){return this.url=w,this._options.url=w,this.reload(),this}onRemove(w){this.cancelTileJSONRequest()}serialize(){return Object.assign({},this._options)}loadTile(w,C){const O=w.tileID.canonical.url(this.tiles,this.scheme),U=this.map._requestManager.normalizeTileURL(O),Y=this.map._requestManager.transformRequest(U,o.R.Tile),Z=this.map.style?this.map.style.getLut(this.scope):null,se=Z?{image:Z.image.clone()}:null,pe={request:Y,data:void 0,uid:w.uid,tileID:w.tileID,tileZoom:w.tileZoom,zoom:w.tileID.overscaledZ,maxZoom:this.maxzoom,lut:se,tileSize:this.tileSize*w.tileID.overscaleFactor(),type:this.type,source:this.id,scope:this.scope,pixelRatio:o.o.devicePixelRatio,showCollisionBoxes:this.map.showCollisionBoxes,promoteId:this.promoteId,renderSourceType:w.renderSourceType,brightness:this.map.style&&this.map.style.getBrightness()||0,extraShadowCaster:w.isExtraShadowCaster,tessellationStep:this.map._tessellationStep,scaleFactor:this.map.getScaleFactor(),worldview:this.map.getWorldview()||this.worldviewDefault,indoor:this.map.getIndoorTileOptions(this.id,this.scope)};if(this.hasWorldviews&&o.e(O)&&(pe.localizableLayerIds=this.localizableLayerIds),pe.request.collectResourceTiming=this._collectResourceTiming,w.actor&&w.state!=="expired")w.state==="loading"?w.reloadCallback=C:w.request=w.actor.send("reloadTile",pe,je.bind(this));else if(w.actor=this._tileWorkers[U]=this._tileWorkers[U]||this.dispatcher.getActor(),this.dispatcher.ready||this.provider)w.request=w.actor.send("loadTile",pe,je.bind(this),void 0,!0);else{const Ee=o.aO.call({deduped:this._deduped},pe,(He,qe)=>{if(He||!qe)je.call(this,He);else{const et=o.aP(qe.responseHeaders);pe.data={rawData:qe.rawData.slice(0),expires:et.expires,cacheControl:et.cacheControl},w.actor&&w.actor.send("loadTile",pe,je.bind(this),void 0,!0)}},!0);w.request={cancel:Ee}}function je(Ee,He){return delete w.request,w.aborted?C(null):Ee?C(Ee):(He&&He.resourceTiming&&(w.resourceTiming=He.resourceTiming),this.map._refreshExpiredTiles&&He&&w.setExpiryData(He),w.loadVectorData(He,this.map.painter),o.aQ(this.dispatcher),C(null,He),void(w.reloadCallback&&(this.loadTile(w,w.reloadCallback),w.reloadCallback=null)))}}abortTile(w){w.request&&(w.request.cancel(),delete w.request),w.actor&&w.actor.send("abortTile",{uid:w.uid,type:this.type,source:this.id,scope:this.scope})}unloadTile(w,C){w.actor&&w.actor.send("removeTile",{uid:w.uid,type:this.type,source:this.id,scope:this.scope}),w.destroy()}hasTransition(){return!1}afterUpdate(){this._tileWorkers={}}cancelTileJSONRequest(){this._tileJSONRequest&&(this._tileJSONRequest.cancel(),this._tileJSONRequest=null)}}class s0 extends o.E{constructor(w,C,O,U){super(),this.id=w,this.dispatcher=O,this.setEventedParent(U),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"},C),Object.assign(this,o.aJ(C,["url","scheme","tileSize"]))}load(w){this._loaded=!1,this.fire(new o.C("dataloading",{dataType:"source"}));const C=this.map.getWorldview();this._tileJSONRequest=Uc(this._options,this.map._requestManager,null,C,(O,U)=>{this._tileJSONRequest=null,this._loaded=!0,O?this.fire(new o.B(O)):U&&(Object.assign(this,U),U.raster_layers&&(this.rasterLayers=U.raster_layers,this.rasterLayerIds=this.rasterLayers.map(Y=>Y.id)),this.tileBounds=Ec.fromTileJSON(U),ve(U.tiles),this.fire(new o.C("data",{dataType:"source",sourceDataType:"metadata"})),this.fire(new o.C("data",{dataType:"source",sourceDataType:"content"}))),w&&w(O)})}loaded(){return this._loaded}onAdd(w){this.map=w,this.load()}reload(){this.cancelTileJSONRequest();const w=o.F(this.id,this.scope);this.load(()=>this.map.style.clearSource(w))}setTiles(w){return this._options.tiles=w,this.reload(),this}setUrl(w){return this.url=w,this._options.url=w,this.reload(),this}onRemove(w){this.cancelTileJSONRequest()}serialize(){return Object.assign({},this._options)}hasTile(w){return!this.tileBounds||this.tileBounds.contains(w.canonical)}loadTile(w,C){const O=o.o.devicePixelRatio>=2,U=this.map._requestManager.normalizeTileURL(w.tileID.canonical.url(this.tiles,this.scheme),O,this.tileSize);w.request=o.n(this.map._requestManager.transformRequest(U,o.R.Tile),(Y,Z,se)=>{if(delete w.request,w.aborted)return w.state="unloaded",C(null);if(Y)return w.state="errored",C(Y);if(!Z)return C(null);const pe=o.aP(se);this.map._refreshExpiredTiles&&w.setExpiryData(pe),w.setTexture(Z,this.map.painter),w.state="loaded",o.aQ(this.dispatcher),C(null)})}abortTile(w,C){w.request&&(w.request.cancel(),delete w.request),C&&C()}unloadTile(w,C){w.texture&&w.texture instanceof o.T?(w.destroy(!1),w.texture&&w.texture instanceof o.T&&this.map.painter.saveTileTexture(w.texture)):w.destroy(),C&&C()}hasTransition(){return!1}cancelTileJSONRequest(){this._tileJSONRequest&&(this._tileJSONRequest.cancel(),this._tileJSONRequest=null)}}function Nb([D,w],C,O,{scaled:U=!0}={}){const{tileSize:Y,buffer:Z}=O,{x:se,y:pe,z:je}=C;if(!isFinite(se)||!isFinite(pe)||!isFinite(je))throw new Error("Invalid MRT header");const Ee=2**je,He=Ee*o.aH(D),qe=Ee*o.aL(w);return function([et,ct],ot,{scaled:bt=!0}={}){if(!ot)throw new Error("bandView is undefined");const{data:vt,tileSize:Pt,buffer:Ft,offset:jt,scale:ys,dimension:Qt}=ot;if(et<-Ft||et>Pt+Ft||ct<-Ft||ct>Pt+Ft)throw new Error(`Point (${et}, ${ct}) out of bounds for tileSize=${Pt}, buffer=${Ft}`);const gs=(ct+Ft)*(Pt+2*Ft)+(et+Ft);if(new Uint32Array(vt.buffer)[gs]===4294967295)return null;let $t=[];$t=bt?[]:new ot.data.constructor(Qt);for(let Zt=0;Zt{if(delete w.request,w.aborted)return w.state="unloaded",C(null);if(se)return se.name==="AbortError"?void 0:(w.state="errored",C(se));if(this.map._refreshExpiredTiles&&pe){const Ee=o.aP(je);w.setExpiryData(Ee)}if(this.partial&&w.state!=="expired")w.state="empty";else if(!this.partial){if(!pe)return C(null);w.state="loaded",w._isHeaderLoaded=!0,w._mrt=pe}C(null)};w.request=this.partial?w.fetchHeader(void 0,Z.bind(this)):w.actor.send("loadTile",Y,Z.bind(this),void 0,!0)}abortTile(w){w.request&&(w.request.cancel(),delete w.request),w.actor&&w.actor.send("abortTile",{uid:w.uid,type:this.type,source:this.id,scope:this.scope})}unloadTile(w,C){const O=w.texturePerLayer;if(w.flushAllQueues(),O.size){w.destroy(!1);for(const U of O.values())this.map.painter.saveTileTexture(U)}else w.destroy()}prepareTile(w,C,O,U){w._isHeaderLoaded&&(w.state!=="empty"&&(w.state="reloading"),w.fetchBandForRender(C,O,U,(Y,Z)=>{Y?(w.state="errored",this.fire(new o.B(Y))):Z&&(w._isHeaderLoaded=!0,w.setTexturePerLayer(O,Z,this.map.painter),w.state="loaded"),this.triggerRepaint(w)}))}getInitialBand(w){if(!this.rasterLayers)return 0;const C=this.rasterLayers.find(({id:Y})=>Y===w),O=C&&C.fields,U=O&&O.bands&&O.bands;return U?U[0]:0}getTextureDescriptor(w,C,O){if(!w)return;const U=C.sourceLayer||this.rasterLayerIds&&this.rasterLayerIds[0];if(!U)return;let Y=null;C instanceof o.aS?Y=C.paint.get("raster-array-band"):C instanceof o.aT&&(Y=C.paint.get("raster-particle-array-band"));const Z=Y||this.getInitialBand(U);if(Z==null)return;if(!w.textureDescriptorPerLayer.get(C.id))return void this.prepareTile(w,U,C.id,Z);if(w.updateNeeded(C.id,Z)&&!O)return;const se=w.textureDescriptorPerLayer.get(C.id);return Object.assign({},se,{texture:w.texturePerLayer.get(C.id)})}getImages(w,C){const O=new Map;for(const U of w)for(const Y of C){const[Z,se]=Y.split("/"),pe=U.getLayer(Z);if(!pe||!pe.hasBand(se)||!pe.hasDataForBand(se))continue;const{bytes:je,tileSize:Ee,buffer:He}=pe.getBandView(se),qe=Ee+2*He,et={data:new o.q({width:qe,height:qe},je),pixelRatio:2,sdf:!1,usvg:!1,version:0};O.set(Y,et)}return O}queryRasterArrayValueByBandId(w,C,O){const U=C._mrt;return new Promise(Y=>{const Z={},se=new Set;for(const[pe,je]of Object.entries(U.layers)){if(O.layerName&&pe!==O.layerName)continue;const Ee={};Z[pe]=Ee;for(const{bands:He}of je.dataIndex)for(const qe of He)O.bands&&!O.bands.includes(qe)||(se.add(o.F(pe,qe)),C.fetchBand(pe,null,qe,et=>{o.o.frame(()=>{Ee[qe]=et?null:Nb([w.lng,w.lat],U,je.getBandView(qe)),se.delete(o.F(pe,qe)),se.size===0&&Y(Z)})},!1))}se.size===0&&Y(Z)})}_loadTileForQuery(w,C){if(this._loadTileLoaded[w.uid])return void C(null,w._mrt);if(this._loadTilePending[w.uid])return void this._loadTilePending[w.uid].push(C);this._loadTilePending[w.uid]=[C];const O=this.map._requestManager.normalizeTileURL(w.tileID.canonical.url(this.tiles,this.scheme),!1,this.tileSize),U=this.map._requestManager.transformRequest(O,o.R.Tile);w.actor.send("loadTile",{request:U,uid:w.uid,tileID:w.tileID,type:this.type,source:this.id,scope:this.scope,partial:!1},(Y,Z,se)=>{if(Y)return this._loadTilePending[w.uid].forEach(pe=>pe(Y,null)),void delete this._loadTilePending[w.uid];if(!Z)return this._loadTilePending[w.uid].forEach(pe=>pe(null,null)),void delete this._loadTilePending[w.uid];if(this.map._refreshExpiredTiles&&Z){const pe=o.aP(se);w.setExpiryData(pe)}w._mrt=Z,w._isHeaderLoaded=!0,w.state="loaded",this._loadTilePending[w.uid].forEach(pe=>pe(null,Z)),this._loadTileLoaded[w.uid]=!0,delete this._loadTilePending[w.uid]},void 0,!0)}queryRasterArrayValueByAllBands(w,C,O){return new Promise((U,Y)=>{this._loadTileForQuery(C,(Z,se)=>{Z?Y(Z):U(se?this.queryRasterArrayValueByBandId(w,C,O):null)})})}queryRasterArrayValue(w,C){const O=o.aU.convert(w),U=this.findLoadedParent(O);return U&&U._mrt?C.bands||!this.partial?this.queryRasterArrayValueByBandId(O,U,C):this.queryRasterArrayValueByAllBands(O,U,C):Promise.resolve(null)}findLoadedParent(w){const C=o.ag.fromLngLat(w,this.map.transform.tileSize),O=this.maxzoom+1,U=1<0&&(se[new o.aR(D.overscaledZ,U,w.z,O,w.y-1).key]={backfilled:!1},se[new o.aR(D.overscaledZ,D.wrap,w.z,w.x,w.y-1).key]={backfilled:!1},se[new o.aR(D.overscaledZ,Z,w.z,Y,w.y-1).key]={backfilled:!1}),w.y+1{if(this._loaded=!0,this._pendingLoad=null,O)this.fire(new o.B(O));else{const Y={dataType:"source",sourceDataType:this._metadataFired?"content":"metadata"};this._collectResourceTiming&&U&&U.resourceTiming&&U.resourceTiming[this.id]&&(Y.resourceTiming=U.resourceTiming[this.id]),D&&(this._partialReload=!0),this.fire(new o.C("data",Y)),this._partialReload=!1,this._metadataFired=!0}this._coalesce&&(this._updateWorkerData(D),this._coalesce=!1)})}loaded(){return this._loaded}reload(){const D=o.F(this.id,this.scope);this.map.style.clearSource(D),this._updateWorkerData()}loadTile(D,w){const C=D.actor?"reloadTile":"loadTile";D.actor=this.actor;const O=this.map.style?this.map.style.getLut(this.scope):null,U=O?{image:O.image.clone()}:null,Y=this._partialReload,Z={type:this.type,uid:D.uid,tileID:D.tileID,tileZoom:D.tileZoom,zoom:D.tileID.overscaledZ,maxZoom:this.maxzoom,tileSize:this.tileSize,source:this.id,lut:U,scope:this.scope,pixelRatio:o.o.devicePixelRatio,showCollisionBoxes:this.map.showCollisionBoxes,promoteId:this.promoteId,brightness:this.map.style&&this.map.style.getBrightness()||0,extraShadowCaster:D.isExtraShadowCaster,scaleFactor:this.map.getScaleFactor(),partial:Y,worldview:this.map.getWorldview(),indoor:this.map.getIndoorTileOptions(this.id,this.scope)};D.request=this.actor.send(C,Z,(se,pe)=>Y&&!pe?(D.state="loaded",w(null)):(delete D.request,D.destroy(!1),D.aborted?w(null):se?w(se):(D.loadVectorData(pe,this.map.painter,C==="reloadTile"),w(null))),void 0,C==="loadTile")}abortTile(D){D.request&&(D.request.cancel(),delete D.request),D.aborted=!0}unloadTile(D,w){this.actor.send("removeTile",{uid:D.uid,type:this.type,source:this.id,scope:this.scope}),D.destroy()}onRemove(D){this._pendingLoad&&this._pendingLoad.cancel()}serialize(){return Object.assign({},this._options,{type:this.type,data:this._data})}hasTransition(){return!1}},video:class extends o.aV{constructor(D,w,C,O){super(D,w,C,O),this.roundZoom=!0,this.type="video",this.options=w}load(){this._loaded=!1;const D=this.options;this.urls=[];for(const w of D.urls)this.urls.push(this.map._requestManager.transformRequest(w,o.R.Source).url);o.aW(this.urls,(w,C)=>{this._loaded=!0,w?this.fire(new o.B(w)):C&&(this.video=C,this.video.loop=!0,this.video.setAttribute("playsinline",""),this.video.addEventListener("playing",()=>{this.map.triggerRepaint()}),this.map&&this.video.play(),this._finishLoading())})}pause(){this.video&&this.video.pause()}play(){this.video&&this.video.play()}seek(D){if(this.video){const w=this.video.seekable;Dw.end(0)?this.fire(new o.B(new o.V(`sources.${this.id}`,null,`Playback for this video can be set only between the ${w.start(0)} and ${w.end(0)}-second mark.`))):this.video.currentTime=D}}getVideo(){return this.video}onAdd(D){this.map||(this.map=D,this.load(),this.video&&(this.video.play(),this.setCoordinates(this.coordinates)))}prepare(){if(Object.keys(this.tiles).length===0||this.video.readyState<2)return;const D=this.map.painter.context,w=D.gl;this.texture?this.video.paused||(this.texture.bind(w.LINEAR,w.CLAMP_TO_EDGE),w.texSubImage2D(w.TEXTURE_2D,0,0,0,w.RGBA,w.UNSIGNED_BYTE,this.video)):(this.texture=new o.T(D,this.video,w.RGBA8),this.texture.bind(w.LINEAR,w.CLAMP_TO_EDGE),this.width=this.video.videoWidth,this.height=this.video.videoHeight),this._prepareData(D)}serialize(){return{type:"video",urls:this.urls,coordinates:this.coordinates}}hasTransition(){return this.video&&!this.video.paused}},image:o.aV,model:o.aY,"batched-model":class extends o.E{constructor(D,w,C,O){super(),this.type="batched-model",this.id=D,this.tileSize=512,this._options=w,this.tiles=this._options.tiles,this.maxzoom=w.maxzoom||19,this.minzoom=w.minzoom||0,this.roundZoom=!0,this.usedInConflation=!0,this.dispatcher=C,this.reparseOverscaled=!1,this.scheme="xyz",this._loaded=!1,this.setEventedParent(O)}onAdd(D){this.map=D,this.load()}reload(){this.cancelTileJSONRequest();const D=o.F(this.id,this.scope);this.load(()=>this.map.style.clearSource(D))}cancelTileJSONRequest(){this._tileJSONRequest&&(this._tileJSONRequest.cancel(),this._tileJSONRequest=null)}load(D){this._loaded=!1,this.fire(new o.C("dataloading",{dataType:"source"}));const w=Array.isArray(this.map._language)?this.map._language.join():this.map._language,C=this.map.getWorldview();this._tileJSONRequest=Uc(this._options,this.map._requestManager,w,C,(O,U)=>{this._tileJSONRequest=null,this._loaded=!0,O?(w&&console.warn(`Ensure that your requested language string is a valid BCP-47 code or list of codes. Found: ${w}`),C&&C.length!==2&&console.warn(`Requested worldview strings must be a valid ISO alpha-2 code. Found: ${C}`),this.fire(new o.B(O))):U&&(Object.assign(this,U),U.bounds&&(this.tileBounds=new Ec(U.bounds,this.minzoom,this.maxzoom)),ve(U.tiles,this.map._requestManager._customAccessToken),this.fire(new o.C("data",{dataType:"source",sourceDataType:"metadata"})),this.fire(new o.C("data",{dataType:"source",sourceDataType:"content"}))),D&&D(O)})}hasTransition(){return!1}hasTile(D){return!this.tileBounds||this.tileBounds.contains(D.canonical)}loaded(){return this._loaded}loadTile(D,w){const C=this.map._requestManager.normalizeTileURL(D.tileID.canonical.url(this.tiles,this.scheme)),O={request:this.map._requestManager.transformRequest(C,o.R.Tile),data:void 0,uid:D.uid,tileID:D.tileID,tileZoom:D.tileZoom,zoom:D.tileID.overscaledZ,tileSize:this.tileSize*D.tileID.overscaleFactor(),type:this.type,source:this.id,scope:this.scope,showCollisionBoxes:this.map.showCollisionBoxes,renderSourceType:D.renderSourceType,brightness:this.map.style&&this.map.style.getBrightness()||0,pixelRatio:o.o.devicePixelRatio,promoteId:this.promoteId};if(D.actor&&D.state!=="expired")if(D.state==="loading")D.reloadCallback=w;else{if(D.buckets){const Y=Object.values(D.buckets);for(const Z of Y)Z.dirty=!0;return void(D.state="loaded")}D.request=D.actor.send("reloadTile",O,U.bind(this))}else D.actor=this.dispatcher.getActor(),D.request=D.actor.send("loadTile",O,U.bind(this),void 0,!0);function U(Y,Z){return D.aborted?w(null):Y&&Y.status!==404?w(Y):(this.map._refreshExpiredTiles&&Z&&D.setExpiryData(Z),D.loadModelData(Z,this.map.painter),D.state="loaded",void w(null))}}serialize(){return Object.assign({},this._options)}},canvas:class extends o.aV{constructor(D,w,C,O){super(D,w,C,O),w.coordinates?Array.isArray(w.coordinates)&&w.coordinates.length===4&&!w.coordinates.some(U=>!Array.isArray(U)||U.length!==2||U.some(Y=>typeof Y!="number"))||this.fire(new o.B(new o.V(`sources.${D}`,null,'"coordinates" property must be an array of 4 longitude/latitude array pairs'))):this.fire(new o.B(new o.V(`sources.${D}`,null,'missing required property "coordinates"'))),w.animate&&typeof w.animate!="boolean"&&this.fire(new o.B(new o.V(`sources.${D}`,null,'optional "animate" property must be a boolean value'))),w.canvas?typeof w.canvas=="string"||w.canvas instanceof HTMLCanvasElement||this.fire(new o.B(new o.V(`sources.${D}`,null,'"canvas" must be either a string representing the ID of the canvas element from which to read, or an HTMLCanvasElement instance'))):this.fire(new o.B(new o.V(`sources.${D}`,null,'missing required property "canvas"'))),this.options=w,this.animate=w.animate===void 0||w.animate}load(){this._loaded=!0,this.canvas||(this.canvas=this.options.canvas instanceof HTMLCanvasElement?this.options.canvas:document.getElementById(this.options.canvas)),this.width=this.canvas.width,this.height=this.canvas.height,this._hasInvalidDimensions()?this.fire(new o.B(new Error("Canvas dimensions cannot be less than or equal to zero."))):(this.play=function(){this._playing=!0,this.map.triggerRepaint()},this.pause=function(){this._playing&&(this.prepare(),this._playing=!1)},this._finishLoading())}getCanvas(){return this.canvas}onAdd(D){this.map=D,this.load(),this.canvas&&this.animate&&this.play()}onRemove(D){this.pause()}prepare(){let D=!1;if(this.canvas.width!==this.width&&(this.width=this.canvas.width,D=!0),this.canvas.height!==this.height&&(this.height=this.canvas.height,D=!0),this._hasInvalidDimensions()||Object.keys(this.tiles).length===0)return;const w=this.map.painter.context;this.texture?!D&&!this._playing||this.texture instanceof o.aX||this.texture.update(this.canvas,{premultiply:!0}):this.texture=new o.T(w,this.canvas,w.gl.RGBA8,{premultiply:!0}),this._prepareData(w)}serialize(){return{type:"canvas",coordinates:this.coordinates}}hasTransition(){return this._playing}_hasInvalidDimensions(){for(const D of[this.canvas.width,this.canvas.height])if(isNaN(D)||D<=0)return!0;return!1}},custom:class extends o.E{constructor(D,w,C,O){super(),this.id=D,this.type="custom",this._dataType="raster",this._dispatcher=C,this._implementation=w,this.setEventedParent(O),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 Ec(this._implementation.bounds,this.minzoom,this.maxzoom));const U=w;U.update=this._update.bind(this),U.clearTiles=this._clearTiles.bind(this),U.coveringTiles=this._coveringTiles.bind(this),Object.assign(this,o.aJ(w,["dataType","scheme","minzoom","maxzoom","tileSize","attribution","minTileCacheSize","maxTileCacheSize"]))}serialize(){return o.aJ(this,["type","scheme","minzoom","maxzoom","tileSize","attribution"])}load(){this._loaded=!0,this.fire(new o.C("data",{dataType:"source",sourceDataType:"metadata"})),this.fire(new o.C("data",{dataType:"source",sourceDataType:"content"}))}loaded(){return this._loaded}onAdd(D){this.map=D,this._loaded=!1,this.fire(new o.C("dataloading",{dataType:"source"})),this._implementation.onAdd&&this._implementation.onAdd(D),this.load()}onRemove(D){this._implementation.onRemove&&this._implementation.onRemove(D)}hasTile(D){if(this._implementation.hasTile){const{x:w,y:C,z:O}=D.canonical;return this._implementation.hasTile({x:w,y:C,z:O})}return!this.tileBounds||this.tileBounds.contains(D.canonical)}loadTile(D,w){const{x:C,y:O,z:U}=D.tileID.canonical,Y=new AbortController,Z=Promise.resolve(this._implementation.loadTile({x:C,y:O,z:U},{signal:Y.signal})).then((function(se){return delete D.request,D.aborted?(D.state="unloaded",w(null)):se===void 0?(D.state="errored",w(null)):se===null?(this.loadTileData(D,{width:this.tileSize,height:this.tileSize,data:null}),D.state="loaded",w(null)):function(pe){return pe instanceof ImageData||pe instanceof HTMLCanvasElement||pe instanceof ImageBitmap||pe instanceof HTMLImageElement}(se)?(this.loadTileData(D,se),D.state="loaded",void w(null)):(D.state="errored",w(new Error(`Can't infer data type for ${this.id}, only raster data supported at the moment`)))}).bind(this)).catch(se=>{se.name!=="AbortError"&&(D.state="errored",w(se))});Z.cancel=()=>Y.abort(),D.request=Z}loadTileData(D,w){D.setTexture(w,this.map.painter)}unloadTile(D,w){if(D.texture&&D.texture instanceof o.T?(D.destroy(!1),D.texture&&D.texture instanceof o.T&&this.map.painter.saveTileTexture(D.texture)):D.destroy(),this._implementation.unloadTile){const{x:C,y:O,z:U}=D.tileID.canonical;this._implementation.unloadTile({x:C,y:O,z:U})}w&&w()}abortTile(D,w){D.request&&D.request.cancel&&(D.request.cancel(),delete D.request),w&&w()}hasTransition(){return!1}_coveringTiles(){return this.map.transform.coveringTiles({tileSize:this.tileSize,minzoom:this.minzoom,maxzoom:this.maxzoom,roundZoom:this.roundZoom}).map(D=>({x:D.canonical.x,y:D.canonical.y,z:D.canonical.z}))}_clearTiles(){const D=o.F(this.id,this.scope);this.map.style.clearSource(D)}_update(){this.fire(new o.C("data",{dataType:"source",sourceDataType:"content"}))}}},wf=function(D,w,C,O){const U=new ay[w.type](D,w,C,O);if(U.id!==D)throw new Error(`Expected Source id to be ${D} instead of ${U.id}`);return o.aZ(["load","abort","unload","serialize","prepare"],U),U};function jf(D,w,C=""){return`${C}:${w.id||""}:${w.layer.id}:${function(O){if("layerId"in O)return`layer:${O.layerId}`;{const{featuresetId:U,importId:Y}=O;return`featureset:${U}${Y?`:import:${Y}`:""}`}}(D.target)}`}function cu(D,w,C,O=""){if(D.uniqueFeatureID){const U=jf(D,w,O);if(C.has(U))return!0;C.add(U)}return!1}function Sg(D,w,C,O,U=!1,Y=void 0){const Z=w.sourceCache.transform,se=w.sourceCache.tilesIn(D,w.has3DLayers,U);se.sort(Gm);const pe=[];for(const je of se){const Ee=je.tile.queryRenderedFeatures(w,je,C,O,Z,U,Y);Object.keys(Ee).length&&pe.push({wrappedTileID:je.tile.tileID.wrapped().key,queryResults:Ee})}for(const je in w.layers){const Ee=w.layers[je];if(Ee.styleLayer){const He=Ee.styleLayer.queryRenderedFeatures(D,w.sourceCache,O);Object.keys(He).length&&pe.push({wrappedTileID:0,queryResults:He})}}return pe.length===0?{}:function(je){const Ee={},He={};for(const qe of je){const et=qe.queryResults,ct=qe.wrappedTileID,ot=He[ct]=He[ct]||{};for(const bt in et){const vt=et[bt],Pt=ot[bt]=ot[bt]||{},Ft=Ee[bt]=Ee[bt]||[];for(const jt of vt)Pt[jt.featureIndex]||(Pt[jt.featureIndex]=!0,Ft.push(jt))}}return Ee}(pe)}function Eo(D,w,C,O,U,Y){const Z={},se=O.queryRenderedSymbols(D),pe=[];for(const je of Object.keys(se).map(Number))pe.push(U[je]);pe.sort(Gm);for(const je of pe){const Ee=je.featureIndex.lookupSymbolFeatures(se[je.bucketInstanceId],je.bucketIndex,je.sourceLayerIndex,w,C,Y);for(const He in Ee){const qe=Z[He]=Z[He]||[],et=Ee[He];et.sort((ct,ot)=>{const bt=je.featureSortOrder;if(bt){const vt=bt.indexOf(ct.featureIndex);return bt.indexOf(ot.featureIndex)-vt}return ot.featureIndex-ct.featureIndex});for(const ct of et)qe.push(ct)}}return Z}function po(D,w){const C=D.getRenderableIds().map(Y=>D.getTileByID(Y)),O=[],U={};for(let Y=0;Y{if(Y)C(Y);else try{const pe=O.getHeaderLength(Z);if(pe>w)return void(this.request=this.fetchHeader(pe,C));O.parseHeader(Z),this._isHeaderLoaded=!0;let je=0;for(const Ee of Object.values(O.layers))je=Math.max(je,Ee.dataIndex[Ee.dataIndex.length-1].lastByte);Z.byteLength>=je&&(this.entireBuffer=Z),C(null,this.entireBuffer||Z,se)}catch(pe){C(pe)}}),this.request}fetchBandForRender(w,C,O,U){this.fetchBand(w,C,O,Y=>{if(Y)return void U(Y);this.updateTextureDescriptor(w,C,O);const Z=this.textureDescriptorPerLayer.get(C);U(null,Z?Z.img:null)})}fetchBand(w,C,O,U,Y=!0){const Z=this._mrt;if(!this._isHeaderLoaded||!Z)return void U(new Error("Tile header is not ready"));const se=this.actor;if(!se)return void U(new Error("Can't fetch tile band without an actor"));let pe;const je=o.F(String(O),o.F(this.tileID.key,w));let Ee=this._taskQueue.get(je);Ee?Ee.add(U):(Ee=new Set,Ee.add(U),this._taskQueue.set(je,Ee));const He=(ot,bt)=>{pe.complete(ot,bt),ot?U(ot):(Ee.forEach(vt=>vt(null,bt)),this._taskQueue.delete(je))},qe=(ot,bt)=>{if(ot)return U(ot);const vt=se.send("decodeRasterArray",{type:"raster-array",source:this.source,scope:this.scope,tileID:this.tileID,uid:this.uid,buffer:bt,task:pe},He,void 0,!0);if(C!==null){const Pt=this._workQueuePerLayer.get(C)||[];Pt.push(()=>{vt&&vt.cancel(),pe.cancel()}),this._workQueuePerLayer.has(C)||this._workQueuePerLayer.set(C,Pt)}};let et;try{et=Z.getLayer(w)}catch(ot){if(this.state==="reloading")return;throw ot}if(!et)return void U(new Error(`Unknown sourceLayer "${w}"`));if(et.hasDataForBand(O))return Ee.forEach(ot=>ot(null,null)),void this._taskQueue.delete(je);const ct=et.getDataRange([O]);if(pe=Z.createDecodingTask(ct),!pe||pe.tasks.length)if(C!==null&&this.flushQueues(C),this.entireBuffer)qe(null,this.entireBuffer.slice(ct.firstByte,ct.lastByte+1));else{const ot=Object.assign({},this.requestParams,{headers:{Range:`bytes=${ct.firstByte}-${ct.lastByte}`}}),bt=o.b1(ot,qe);if(C!==null){const vt=this._fetchQueuePerLayer.get(C)||[];vt.push(()=>{bt.cancel(),pe.cancel()}),this._fetchQueuePerLayer.has(C)||this._fetchQueuePerLayer.set(C,vt)}}}updateNeeded(w,C){return(!this.textureDescriptorPerLayer.get(w)||this.textureDescriptorPerLayer.get(w).band!==C||this.refreshedUponExpiration)&&this.state!=="errored"}updateTextureDescriptor(w,C,O){if(!this._mrt)return;const U=this._mrt.getLayer(w);if(!U||!U.hasBand(O)||!U.hasDataForBand(O))return;const{bytes:Y,tileSize:Z,buffer:se,offset:pe,scale:je}=U.getBandView(O),Ee=Z+2*se,He=new o.q({width:Ee,height:Ee},Y),qe=this.texturePerLayer.get(C);qe&&qe instanceof o.T&&qe.update(He,{premultiply:!1}),this.textureDescriptorPerLayer.set(C,{layer:w,band:O,img:He,buffer:se,offset:pe,tileSize:Z,format:U.pixelFormat,mix:[je,256*je,65536*je,16777216*je]})}destroy(w=!1){if(super.destroy(w),delete this._mrt,!w)for(const C of this.texturePerLayer.values())C&&C instanceof o.T&&C.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 Cg{constructor(w,C){this.max=w,this.onRemove=C,this.reset()}reset(){for(const w in this.data)for(const C of this.data[w])C.timeout&&clearTimeout(C.timeout),this.onRemove(C.value);return this.data={},this.order=[],this}add(w,C,O){const U=w.wrapped().key;this.data[U]===void 0&&(this.data[U]=[]);const Y={value:C,timeout:void 0};if(O!==void 0&&(Y.timeout=setTimeout(()=>{this.remove(w,Y)},O)),this.data[U].push(Y),this.order.push(U),this.order.length>this.max){const Z=this._getAndRemoveByKey(this.order[0]);Z&&this.onRemove(Z)}return this}has(w){return w.wrapped().key in this.data}getAndRemove(w){return this.has(w)?this._getAndRemoveByKey(w.wrapped().key):null}_getAndRemoveByKey(w){const C=this.data[w].shift();return C.timeout&&clearTimeout(C.timeout),this.data[w].length===0&&delete this.data[w],this.order.splice(this.order.indexOf(w),1),C.value}getByKey(w){const C=this.data[w];return C?C[0].value:null}get(w){return this.has(w)?this.data[w.wrapped().key][0].value:null}remove(w,C){if(!this.has(w))return this;const O=w.wrapped().key,U=C===void 0?0:this.data[O].indexOf(C),Y=this.data[O][U];return this.data[O].splice(U,1),Y.timeout&&clearTimeout(Y.timeout),this.data[O].length===0&&delete this.data[O],this.onRemove(Y.value),this.order.splice(this.order.indexOf(O),1),this}setMaxSize(w){for(this.max=w;this.order.length>this.max;){const C=this._getAndRemoveByKey(this.order[0]);C&&this.onRemove(C)}return this}filter(w){const C=[];for(const O in this.data)for(const U of this.data[O])w(U.value)||C.push(U);for(const O of C)this.remove(O.value.tileID,O)}}class wh{constructor(){this.state={},this.stateChanges={},this.deletedStates={}}updateState(w,C,O){const U=String(C);if(this.stateChanges[w]=this.stateChanges[w]||{},this.stateChanges[w][U]=this.stateChanges[w][U]||{},Object.assign(this.stateChanges[w][U],O),this.deletedStates[w]===null){this.deletedStates[w]={};for(const Y in this.state[w])Y!==U&&(this.deletedStates[w][Y]=null)}else if(this.deletedStates[w]&&this.deletedStates[w][U]===null){this.deletedStates[w][U]={};for(const Y in this.state[w][U])O[Y]||(this.deletedStates[w][U][Y]=null)}else for(const Y in O)this.deletedStates[w]&&this.deletedStates[w][U]&&this.deletedStates[w][U][Y]===null&&delete this.deletedStates[w][U][Y]}removeFeatureState(w,C,O){if(this.deletedStates[w]===null)return;const U=String(C);if(this.deletedStates[w]=this.deletedStates[w]||{},O&&C!==void 0)this.deletedStates[w][U]!==null&&(this.deletedStates[w][U]=this.deletedStates[w][U]||{},this.deletedStates[w][U][O]=null);else if(C!==void 0)if(this.stateChanges[w]&&this.stateChanges[w][U])for(O in this.deletedStates[w][U]={},this.stateChanges[w][U])this.deletedStates[w][U][O]=null;else this.deletedStates[w][U]=null;else this.deletedStates[w]=null}getState(w,C){const O=this.state[w]||{},U=this.stateChanges[w]||{},Y=this.deletedStates[w];if(Y===null)return{};if(C!==void 0){const se=String(C),pe=Object.assign({},O[se],U[se]);if(Y){const je=Y[C];if(je===null)return{};for(const Ee in je)delete pe[Ee]}return pe}const Z=Object.assign({},O,U);if(Y)for(const se in Y)delete Z[se];return Z}initializeTileState(w,C){w.refreshFeatureState(C)}coalesceChanges(w,C){const O={};for(const U in this.stateChanges){this.state[U]=this.state[U]||{};const Y={};for(const Z in this.stateChanges[U])this.state[U][Z]||(this.state[U][Z]={}),Object.assign(this.state[U][Z],this.stateChanges[U][Z]),Y[Z]=this.state[U][Z];O[U]=Y}for(const U in this.deletedStates){this.state[U]=this.state[U]||{};const Y={};if(this.deletedStates[U]===null)for(const Z in this.state[U])Y[Z]={},this.state[U][Z]={};else for(const Z in this.deletedStates[U]){if(this.deletedStates[U][Z]===null)this.state[U][Z]={};else if(this.state[U][Z])for(const se of Object.keys(this.deletedStates[U][Z]))delete this.state[U][Z][se];Y[Z]=this.state[U][Z]}O[U]=O[U]||{},Object.assign(O[U],Y)}if(this.stateChanges={},this.deletedStates={},Object.keys(O).length!==0)for(const U in w)w[U].refreshFeatureState(C,O)}}class Bl extends o.E{constructor(w,C,O){super(),this.id=w,this._renderSourceType=O,this._maxzoomOverride=null,C.on("data",U=>{U.dataType==="source"&&U.sourceDataType==="metadata"&&(this._sourceLoaded=!0),this._sourceLoaded&&!this._paused&&U.dataType==="source"&&U.sourceDataType==="content"&&(this.reload(),this.transform&&this.update(this.transform))}),C.on("error",()=>{this._sourceErrored=!0}),this._source=C,this._tiles={},this._cache=new Cg(0,this._unloadTile.bind(this)),this._timers={},this._cacheTimers={},this._minTileCacheSize=C.minTileCacheSize,this._maxTileCacheSize=C.maxTileCacheSize,this._loadedParentTiles={},this.castsShadows=!1,this.tileCoverLift=0,this._coveredTiles={},this._shadowCasterTiles={},this._state=new wh,this._isRaster=this._source.type==="raster"||this._source.type==="raster-dem"||this._source.type==="raster-array"||this._source.type==="custom"&&"_dataType"in this._source&&this._source._dataType==="raster",this._supportsFading=this._source.type==="raster"||this._source.type==="raster-array"||this._source.type==="image"||this._source.type==="video"||this._source.type==="custom",this._isRasterElevatedOverTerrain=!1}onAdd(w){this.map=w,this._minTileCacheSize=this._minTileCacheSize===void 0&&w?w._minTileCacheSize:this._minTileCacheSize,this._maxTileCacheSize=this._maxTileCacheSize===void 0&&w?w._maxTileCacheSize:this._maxTileCacheSize}loaded(){if(this._sourceErrored)return!0;if(!this._sourceLoaded||!this._source.loaded())return!1;for(const w in this._tiles)if(!this._tiles[w].loaded())return!1;return!0}getSource(){return this._source}pause(){this._paused=!0}resume(){if(!this._paused)return;const w=this._shouldReloadOnResume;this._paused=!1,this._shouldReloadOnResume=!1,w&&this.reload(),this.transform&&this.update(this.transform)}setMaxzoomOverride(w){this._maxzoomOverride=w}_loadTile(w,C){return w.renderSourceType=this._renderSourceType,w.isExtraShadowCaster=this._shadowCasterTiles[w.tileID.key],this._source.loadTile(w,C)}_unloadTile(w){if(this._source.unloadTile)return this._source.unloadTile(w)}_abortTile(w){if(this._source.abortTile)return this._source.abortTile(w)}serialize(){return this._source.serialize()}prepare(w){this._source.prepare&&this._source.prepare(),this._state.coalesceChanges(this._tiles,this.map?this.map.painter:null);for(const C in this._tiles){const O=this._tiles[C];O.upload(w,this.map?this.map.painter:void 0),O.prepare(this.map.style.imageManager,this.map?this.map.painter:null,this._source.scope)}}getIds(){return Object.values(this._tiles).map(w=>w.tileID).sort(Wm).map(w=>w.key)}getRenderableIds(w,C){const O=[];for(const U in this._tiles)this._isIdRenderable(+U,w,C)&&O.push(this._tiles[U]);return w?O.sort((U,Y)=>{const Z=U.tileID,se=Y.tileID,pe=new o.P(Z.canonical.x,Z.canonical.y)._rotate(this.transform.angle),je=new o.P(se.canonical.x,se.canonical.y)._rotate(this.transform.angle);return Z.overscaledZ-se.overscaledZ||je.y-pe.y||je.x-pe.x}).map(U=>U.tileID.key):O.map(U=>U.tileID).sort(Wm).map(U=>U.key)}hasRenderableParent(w){const C=this.findLoadedParent(w,0);return!!C&&this._isIdRenderable(C.tileID.key)}_isIdRenderable(w,C,O){return this._tiles[w]&&this._tiles[w].hasData()&&!this._coveredTiles[w]&&(C||!this._tiles[w].holdingForFade())&&(O||!this._shadowCasterTiles[w])}reload(){if(this._paused)this._shouldReloadOnResume=!0;else{this._cache.reset();for(const w in this._tiles)this._tiles[w].state!=="errored"&&this._reloadTile(+w,"reloading")}}_reloadTile(w,C){const O=this._tiles[w];O&&(O.state!=="loading"&&(O.state=C),this._loadTile(O,this._tileLoaded.bind(this,O,w,C)))}_tileLoaded(w,C,O,U,Y){if(U){if(w.state="errored",o.b2(U)){if(this._source.fire(new o.C("data",{dataType:"source",sourceDataType:"error",sourceId:this._source.id,tile:w})),!(w.tileID.key in this._loadedParentTiles))return;if(this._source.type==="raster-dem"&&this.usedForTerrain&&this.map.painter.terrain){const se=this.map.painter.terrain;this.update(this.transform,se.getScaledDemTileSize(),!0),se.resetTileLookupCache(this.id)}else this.update(this.transform)}else this._source.fire(new o.B(U,{tile:w}));return}w.timeAdded=o.o.now(),O==="expired"&&(w.refreshedUponExpiration=!0),this._setTileReloadTimer(C,w),this._source.type==="raster-dem"&&w.dem&&this._backfillDEM(w),this._state.initializeTileState(w,this.map?this.map.painter:null);let Z=new Map;Y&&Y.responseHeaders&&(Z=Y.responseHeaders),this._source.fire(new o.C("data",{dataType:"source",tile:w,coord:w.tileID,sourceCacheId:this.id,responseHeaders:Z}))}_hasTunnelGeometry(){for(const w in this._tiles){const C=this._tiles[w];if(C&&C.hasTunnelGeometry)return!0}return!1}_backfillDEM(w){const C=this.getRenderableIds();for(let U=0;U1||(Math.abs(Z)>1&&(Math.abs(Z+pe)===1?Z+=pe:Math.abs(Z-pe)===1&&(Z-=pe)),Y.dem&&U.dem&&(U.dem.backfillBorder(Y.dem,Z,se),U.neighboringTiles&&U.neighboringTiles[je]&&(U.neighboringTiles[je].backfilled=!0)))}}getTile(w){return this.getTileByID(w.key)}getTileByID(w){return this._tiles[w]}_retainLoadedChildren(w,C,O,U){for(const Y in this._tiles){let Z=this._tiles[Y];if(U[Y]||!Z.hasData()||Z.tileID.overscaledZ<=C||Z.tileID.overscaledZ>O)continue;let se=Z.tileID;for(;Z&&Z.tileID.overscaledZ>C+1;){const je=Z.tileID.scaledTo(Z.tileID.overscaledZ-1);Z=this._tiles[je.key],Z&&Z.hasData()&&(se=je)}let pe=se;for(;pe.overscaledZ>C;)if(pe=pe.scaledTo(pe.overscaledZ-1),w[pe.key]){U[se.key]=se;break}}}findLoadedParent(w,C){if(w.key in this._loadedParentTiles){const O=this._loadedParentTiles[w.key];return O&&O.tileID.overscaledZ>=C?O:null}for(let O=w.overscaledZ-1;O>=C;O--){const U=w.scaledTo(O),Y=this._getLoadedTile(U);if(Y)return Y}}_getLoadedTile(w){const C=this._tiles[w.key];return C&&C.hasData()?C:this._cache.getByKey(this._source.reparseOverscaled?w.wrapped().key:w.canonical.key)}updateCacheSize(w,C){C=C||this._source.tileSize;const O=Math.ceil(w.width/C)+1,U=Math.ceil(w.height/C)+1,Y=Math.floor(O*U*5),Z=typeof this._minTileCacheSize=="number"?Math.max(this._minTileCacheSize,Y):Y,se=typeof this._maxTileCacheSize=="number"?Math.min(this._maxTileCacheSize,Z):Z;this._cache.setMaxSize(se)}handleWrapJump(w){const C=Math.round((w-(this._prevLng===void 0?w:this._prevLng))/360);if(this._prevLng=w,C){const O={};for(const U in this._tiles){const Y=this._tiles[U];Y.tileID=Y.tileID.unwrapTo(Y.tileID.wrap+C),O[Y.tileID.key]=Y}this._tiles=O;for(const U in this._timers)clearTimeout(this._timers[U]),delete this._timers[U];for(const U in this._tiles)this._setTileReloadTimer(+U,this._tiles[U])}}update(w,C,O,U,Y){if(this.transform=w,!this._sourceLoaded||this._paused||this.transform.freezeTileCoverage||this.usedForTerrain&&!O)return;this.updateCacheSize(w,C),this.transform.projection.name!=="globe"&&this.handleWrapJump(this.transform.center.lng),this._shadowCasterTiles={},this._coveredTiles={};const Z=this._source.type==="batched-model";let se,pe=this._source.maxzoom;this._maxzoomOverride!==null&&(pe=Math.min(pe,this._maxzoomOverride));const je=this.map&&this.map.painter?this.map.painter._terrain:null;if(je&&je.sourceCache===this&&je.attenuationRange()){const et=je.attenuationRange()[0],ct=Math.floor(et)-Math.log2(je.getDemUpscale());pe>ct&&(pe=ct)}const Ee=this._maxzoomOverride===null&&this._source.reparseOverscaled;if(this.used||this.usedForTerrain){if(this._source.tileID)se=w.getVisibleUnwrappedCoordinates(this._source.tileID).map(et=>new o.aR(et.canonical.z,et.wrap,et.canonical.z,et.canonical.x,et.canonical.y));else if(this.tileCoverLift!==0){const et=w.clone();et.tileCoverLift=this.tileCoverLift,se=et.coveringTiles({tileSize:C||this._source.tileSize,minzoom:this._source.minzoom,maxzoom:pe,roundZoom:this._source.roundZoom&&!O,reparseOverscaled:Ee,isTerrainDEM:this.usedForTerrain,calculateQuadrantVisibility:Z}),this._source.minzoom<=1&&w.projection.name==="globe"&&(se.push(new o.aR(1,0,1,0,0)),se.push(new o.aR(1,0,1,1,0)),se.push(new o.aR(1,0,1,0,1)),se.push(new o.aR(1,0,1,1,1)))}else if(se=w.coveringTiles({tileSize:C||this._source.tileSize,minzoom:this._source.minzoom,maxzoom:pe,roundZoom:this._source.roundZoom&&!O,reparseOverscaled:Ee,isTerrainDEM:this.usedForTerrain,calculateQuadrantVisibility:Z}),this._source.hasTile){const et=this._source.hasTile.bind(this._source);se=se.filter(ct=>et(ct))}}else se=[];if(se.length>0&&this.transform.projection.name!=="globe"&&!this.usedForTerrain&&!this._supportsFading){const et=w.coveringZoomLevel({tileSize:C||this._source.tileSize,roundZoom:this._source.roundZoom&&!O}),ct=Math.min(et,pe);if(Z){const ot=w.extendTileCover(se,ct);for(const bt of ot)se.push(bt)}else if(Y){const ot=this.transform.getFrustum(ct),bt=w.extendTileCoverToNearPlane(se,ot,ct);for(const vt of bt)se.push(vt);if(ct>=18&&this._hasTunnelGeometry()){const vt=w.extendTileCoverForTunnels(se,ot,ct,20);for(const Pt of vt)se.push(Pt)}}else if(this.castsShadows&&U){const ot=w.extendTileCover(se,ct,U,16);for(const bt of ot)this._shadowCasterTiles[bt.key]=!0,se.push(bt)}}const He=this._updateRetainedTiles(se);if(this._supportsFading&&se.length!==0){const et={},ct={},ot=o.o.now(),bt=Object.keys(He);for(const Pt of bt){const Ft=He[Pt],jt=this._tiles[Pt];if(!jt||jt.fadeEndTime!==void 0&&jt.fadeEndTime<=ot)continue;const ys=this.findLoadedParent(Ft,Math.max(Ft.overscaledZ-Bl.maxOverzooming,this._source.minzoom));ys&&(this._addTile(ys.tileID),et[ys.tileID.key]=ys.tileID),ct[Pt]=Ft}const vt=se[se.length-1].overscaledZ;for(const Pt in this._tiles){const Ft=this._tiles[Pt];if(He[Pt]||!Ft.hasData())continue;let jt=Ft.tileID;for(;jt.overscaledZ>vt;){jt=jt.scaledTo(jt.overscaledZ-1);const ys=this._tiles[jt.key];if(ys&&ys.hasData()&&ct[jt.key]){He[Pt]=Ft.tileID;break}}}for(const Pt in et)He[Pt]||(this._coveredTiles[Pt]=!0,He[Pt]=et[Pt])}for(const et in He)this._tiles[et].clearFadeHold();const qe=o.b3(this._tiles,He);for(const et of qe){const ct=this._tiles[et];ct.hasSymbolBuckets&&!ct.holdingForFade()?ct.setHoldDuration(this.map._fadeDuration):ct.hasSymbolBuckets&&!ct.symbolFadeFinished()||this._removeTile(+et)}this._updateLoadedParentTileCache(),this._renderSourceType===o.b4.Symbol&&this._source.afterUpdate&&this._source.afterUpdate()}releaseSymbolFadeTiles(){for(const w in this._tiles)this._tiles[w].holdingForFade()&&this._removeTile(+w)}_updateRetainedTiles(w){const C={};if(w.length===0)return C;const O={},U=w.reduce((je,Ee)=>Math.min(je,Ee.overscaledZ),1/0),Y=w[0].overscaledZ,Z=Math.max(Y-Bl.maxOverzooming,this._source.minzoom),se=Math.max(Y+Bl.maxUnderzooming,this._source.minzoom),pe={};for(const je of w){const Ee=this._addTile(je);C[je.key]=je,Ee.hasData()||U=this._source.maxzoom){const qe=je.children(this._source.maxzoom)[0],et=this.getTile(qe);if(et&&et.hasData()){C[qe.key]=qe;continue}}else{const qe=je.children(this._source.maxzoom);if(C[qe[0].key]&&C[qe[1].key]&&C[qe[2].key]&&C[qe[3].key])continue}let He=Ee.wasRequested();for(let qe=je.overscaledZ-1;qe>=Z;--qe){const et=je.scaledTo(qe);if(O[et.key]||(O[et.key]=!0,Ee=this.getTile(et),!Ee&&He&&(Ee=this._addTile(et)),Ee&&(C[et.key]=et,He=Ee.wasRequested(),Ee.hasData())))break}}return C}_updateLoadedParentTileCache(){this._loadedParentTiles={};for(const w in this._tiles){const C=[];let O,U=this._tiles[w].tileID;for(;U.overscaledZ>0;){if(U.key in this._loadedParentTiles){O=this._loadedParentTiles[U.key];break}C.push(U.key);const Y=U.scaledTo(U.overscaledZ-1);if(O=this._getLoadedTile(Y),O)break;U=Y}for(const Y of C)this._loadedParentTiles[Y]=O}}_addTile(w){let C=this._tiles[w.key];if(C)return C.isExtraShadowCaster!==!0||this._shadowCasterTiles[w.key]||this._reloadTile(w.key,"reloading"),C;C=this._cache.getAndRemove(w),C&&(this._setTileReloadTimer(w.key,C),C.tileID=w,this._state.initializeTileState(C,this.map?this.map.painter:null),this._cacheTimers[w.key]&&(clearTimeout(this._cacheTimers[w.key]),delete this._cacheTimers[w.key],this._setTileReloadTimer(w.key,C)));const O=!!C;if(!O){const U=this.map?this.map.painter:null,Y=this._source.tileSize*w.overscaleFactor();C=this._source.type==="raster-array"?new hm(w,Y,this.transform.tileZoom,U,this._isRaster):new o.b0(w,Y,this.transform.tileZoom,U,this._isRaster,this._source.worldview),this._loadTile(C,this._tileLoaded.bind(this,C,w.key,C.state))}return C.uses++,this._tiles[w.key]=C,O||this._source.fire(new o.C("dataloading",{tile:C,coord:C.tileID,dataType:"source"})),C}_setTileReloadTimer(w,C){w in this._timers&&(clearTimeout(this._timers[w]),delete this._timers[w]);const O=C.getExpiryTimeout();O&&(this._timers[w]=setTimeout(()=>{this._reloadTile(w,"expired"),delete this._timers[w]},O))}_removeTile(w){const C=this._tiles[w];C&&(C.uses--,delete this._tiles[w],this._timers[w]&&(clearTimeout(this._timers[w]),delete this._timers[w]),C.uses>0||(C.hasData()&&C.state!=="reloading"||C.state==="empty"?this._cache.add(C.tileID,C,C.getExpiryTimeout()):(C.aborted=!0,this._abortTile(C),this._unloadTile(C))))}clearTiles(){this._shouldReloadOnResume=!1,this._paused=!1;for(const w in this._tiles)this._removeTile(+w);this._source._clear&&this._source._clear(),this._cache.reset(),this.map&&this.usedForTerrain&&this.map.painter.terrain&&this.map.painter.terrain.resetTileLookupCache(this.id)}tilesIn(w,C,O){const U=[],Y=this.transform;if(!Y)return U;const Z=Y.projection.name==="globe",se=o.aH(Y.center.lng);for(const pe in this._tiles){const je=this._tiles[pe];if(O&&je.clearQueryDebugViz(),je.holdingForFade())continue;let Ee;if(Z){const He=je.tileID.canonical;if(He.z===0){const qe=[Math.abs(o.aC(se,...bd(He,-1))-se),Math.abs(o.aC(se,...bd(He,1))-se)];Ee=[0,2*qe.indexOf(Math.min(...qe))-1]}else{const qe=[Math.abs(o.aC(se,...bd(He,-1))-se),Math.abs(o.aC(se,...bd(He,0))-se),Math.abs(o.aC(se,...bd(He,1))-se)];Ee=[qe.indexOf(Math.min(...qe))-1]}}else Ee=[0];for(const He of Ee){const qe=w.containsTile(je,Y,C,He);qe&&U.push(qe)}}return U}getShadowCasterCoordinates(){return this._getRenderableCoordinates(!1,!0)}getVisibleCoordinates(w){return this._getRenderableCoordinates(w)}_getRenderableCoordinates(w,C){const O=this.getRenderableIds(w,C).map(Y=>this._tiles[Y].tileID),U=this.transform.projection.name==="globe";for(const Y of O)Y.projMatrix=this.transform.calculateProjMatrix(Y.toUnwrapped()),Y.expandedProjMatrix=U?this.transform.calculateProjMatrix(Y.toUnwrapped(),!1,!0):Y.projMatrix;return O}sortCoordinatesByDistance(w){const C=w.slice(),O=this.transform._camera.position,U=this.transform._camera.forward(),Y={};for(const Z of C){const se=1/(1<Y[Z.key]-Y[se.key]),C}hasTransition(){if(this._source.hasTransition())return!0;if(this._supportsFading){const w=o.o.now();for(const C in this._tiles){const O=this._tiles[C];if(O.fadeEndTime!==void 0&&O.fadeEndTime>=w)return!0}}return!1}setFeatureState(w,C,O){this._state.updateState(w=w||"_geojsonTileLayer",C,O)}removeFeatureState(w,C,O){this._state.removeFeatureState(w=w||"_geojsonTileLayer",C,O)}getFeatureState(w,C){return this._state.getState(w=w||"_geojsonTileLayer",C)}setDependencies(w,C,O){const U=this._tiles[w];U&&U.setDependencies(C,O)}reloadTilesForDependencies(w,C){for(const O in this._tiles)this._tiles[O].hasDependency(w,C)&&this._reloadTile(+O,"reloading");this._cache.filter(O=>!O.hasDependency(w,C))}_preloadTiles(w,C){if(!this._sourceLoaded){const pe=()=>{this._sourceLoaded&&(this._source.off("data",pe),this._preloadTiles(w,C))};return void this._source.on("data",pe)}const O=new Map,U=Array.isArray(w)?w:[w],Y=this.map.painter.terrain,Z=this.usedForTerrain&&Y?Y.getScaledDemTileSize():this._source.tileSize;for(const pe of U){const je=pe.coveringTiles({tileSize:Z,minzoom:this._source.minzoom,maxzoom:this._source.maxzoom,roundZoom:this._source.roundZoom&&!this.usedForTerrain,reparseOverscaled:this._source.reparseOverscaled,isTerrainDEM:this.usedForTerrain});for(const Ee of je)O.set(Ee.key,Ee);this.usedForTerrain&&pe.updateElevation(!1)}const se=Array.from(O.values());o.t(se,(pe,je)=>{const Ee=new o.b0(pe,this._source.tileSize*pe.overscaleFactor(),this.transform.tileZoom,this.map.painter,this._isRaster,this._source.worldview);this._loadTile(Ee,He=>{this._source.type==="raster-dem"&&Ee.dem&&this._backfillDEM(Ee),je(He,Ee)})},C)}}function Wm(D,w){const C=Math.abs(2*D.wrap)-+(D.wrap<0),O=Math.abs(2*w.wrap)-+(w.wrap<0);return D.overscaledZ-w.overscaledZ||O-C||w.canonical.y-D.canonical.y||w.canonical.x-D.canonical.x}function bd(D,w){const C=1<0:O.type==="building"?U=!O.isHidden(w)&&O.paint.get("building-opacity")>0:O.type==="model"&&(U=!O.isHidden(w)&&O.paint.get("model-opacity").constantOr(1)>0),this.layersGotHidden=this.layersGotHidden||!U&&C.visible,C.visible=U}}updateZOffset(w,C){this.currentBuildingBuckets=[];for(const U of this.layers){const Y=U.layer,Z=this.style.getLayerSourceCache(Y);let se=1;Y.type==="fill-extrusion"?se=U.visible?Y.paint.get("fill-extrusion-vertical-scale"):0:Y.type==="building"&&(se=U.visible?Y.paint.get("building-vertical-scale"):0);let pe=Z?Z.getTile(C):null;if(!pe&&Z)for(const je in Z._tiles){const Ee=Z._tiles[je];if(C.canonical.isChildOf(Ee.tileID.canonical)){pe=Ee;break}}this.currentBuildingBuckets.push({bucket:pe?pe.getBucket(Y):null,tileID:pe?pe.tileID:C,verticalScale:se})}w.hasAnyZOffset=!1;let O=!1;for(let U=0;U{O in w&&(C[O]=w[O])}),C}function Km(D){D=D.slice();const w=Object.create(null);for(const C of D)w[C.id]=C;for(let C=0;C0?(U-Z)/se:0;return this.points[Y].mult(1-pe).add(this.points[C].mult(pe))}}class Ag{constructor(w,C,O){const U=this.boxCells=[],Y=this.circleCells=[];this.xCellCount=Math.ceil(w/O),this.yCellCount=Math.ceil(C/O);for(let Z=0;Zthis.width||U<0||C>this.height)return!Y&&[];const se=[];if(w<=0&&C<=0&&this.width<=O&&this.height<=U){if(Y)return!0;for(let pe=0;pe0:se}_queryCircle(w,C,O,U,Y){const Z=w-O,se=w+O,pe=C-O,je=C+O;if(se<0||Z>this.width||je<0||pe>this.height)return!U&&[];const Ee=[];return this._forEachCell(Z,pe,se,je,this._queryCellCircle,Ee,{hitTest:U,circle:{x:w,y:C,radius:O},seenUids:{box:{},circle:{}}},Y),U?Ee.length>0:Ee}query(w,C,O,U,Y){return this._query(w,C,O,U,!1,Y)}hitTest(w,C,O,U,Y){return this._query(w,C,O,U,!0,Y)}hitTestCircle(w,C,O,U){return this._queryCircle(w,C,O,!0,U)}_queryCell(w,C,O,U,Y,Z,se,pe){const je=se.seenUids,Ee=this.boxCells[Y];if(Ee!==null){const qe=this.bboxes;for(const et of Ee)if(!je.box[et]){je.box[et]=!0;const ct=4*et;if(w<=qe[ct+2]&&C<=qe[ct+3]&&O>=qe[ct+0]&&U>=qe[ct+1]&&(!pe||pe(this.boxKeys[et]))){if(se.hitTest)return Z.push(!0),!0;Z.push({key:this.boxKeys[et],x1:qe[ct],y1:qe[ct+1],x2:qe[ct+2],y2:qe[ct+3]})}}}const He=this.circleCells[Y];if(He!==null){const qe=this.circles;for(const et of He)if(!je.circle[et]){je.circle[et]=!0;const ct=3*et;if(this._circleAndRectCollide(qe[ct],qe[ct+1],qe[ct+2],w,C,O,U)&&(!pe||pe(this.circleKeys[et]))){if(se.hitTest)return Z.push(!0),!0;{const ot=qe[ct],bt=qe[ct+1],vt=qe[ct+2];Z.push({key:this.circleKeys[et],x1:ot-vt,y1:bt-vt,x2:ot+vt,y2:bt+vt})}}}}}_queryCellCircle(w,C,O,U,Y,Z,se,pe){const je=se.circle,Ee=se.seenUids,He=this.boxCells[Y];if(He!==null){const et=this.bboxes;for(const ct of He)if(!Ee.box[ct]){Ee.box[ct]=!0;const ot=4*ct;if(this._circleAndRectCollide(je.x,je.y,je.radius,et[ot+0],et[ot+1],et[ot+2],et[ot+3])&&(!pe||pe(this.boxKeys[ct])))return Z.push(!0),!0}}const qe=this.circleCells[Y];if(qe!==null){const et=this.circles;for(const ct of qe)if(!Ee.circle[ct]){Ee.circle[ct]=!0;const ot=3*ct;if(this._circlesCollide(et[ot],et[ot+1],et[ot+2],je.x,je.y,je.radius)&&(!pe||pe(this.circleKeys[ct])))return Z.push(!0),!0}}}_forEachCell(w,C,O,U,Y,Z,se,pe){const je=this._convertToXCellCoord(w),Ee=this._convertToYCellCoord(C),He=this._convertToXCellCoord(O),qe=this._convertToYCellCoord(U);for(let et=je;et<=He;et++)for(let ct=Ee;ct<=qe;ct++)if(Y.call(this,w,C,O,U,this.xCellCount*ct+et,Z,se,pe))return}_convertToXCellCoord(w){return Math.max(0,Math.min(this.xCellCount-1,Math.floor(w*this.xScale)))}_convertToYCellCoord(w){return Math.max(0,Math.min(this.yCellCount-1,Math.floor(w*this.yScale)))}_circlesCollide(w,C,O,U,Y,Z){const se=U-w,pe=Y-C,je=O+Z;return je*je>se*se+pe*pe}_circleAndRectCollide(w,C,O,U,Y,Z,se){const pe=(Z-U)/2,je=Math.abs(w-(U+pe));if(je>pe+O)return!1;const Ee=(se-Y)/2,He=Math.abs(C-(Y+Ee));if(He>Ee+O)return!1;if(je<=pe||He<=Ee)return!0;const qe=je-pe,et=He-Ee;return qe*qe+et*et<=O*O}}const Jy=Math.tan(85*Math.PI/180);function Jc(D,w,C,O,U,Y,Z){const se=o.bb();if(C)if(Y.name==="globe"){const pe=o.bc(U,w);o.aD(se,se,pe)}else{const pe=o.bd([],Z);se[0]=pe[0],se[1]=pe[1],se[4]=pe[2],se[5]=pe[3],O||o.ba(se,se,U.angle)}else o.aD(se,U.labelPlaneMatrix,D);return se}function Nc(D,w,C,O,U,Y,Z){const se=Jc(D,w,C,O,U,Y,Z);return Y.name==="globe"&&C||(se[2]=se[6]=se[10]=se[14]=0),se}function Qm(D,w,C,O,U,Y,Z){if(C){if(Y.name==="globe"){const se=Jc(D,w,C,O,U,Y,Z);return o.b7(se,se),o.aD(se,D,se),se}{const se=o.b8(D),pe=o.b9([]);return pe[0]=Z[0],pe[1]=Z[1],pe[4]=Z[2],pe[5]=Z[3],o.aD(se,se,pe),O||o.ba(se,se,-U.angle),se}}return U.glCoordMatrix}function Rd(D,w,C,O){const U=[D,w,C,1];C?o.aE(U,U,O):mr(U,U,O);const Y=U[3];return U[0]/=Y,U[1]/=Y,U[2]/=Y,U}function Jm(D,w){return Math.min(.5+D/w*.5,1.5)}function Hh(D,w){const C=D[0]/D[3],O=D[1]/D[3];return C>=-w[0]&&C<=w[0]&&O>=-w[1]&&O<=w[1]}function Wt(D,w,C,O,U,Y,Z,se,pe,je,Ee=1){const He=C.transform,qe=O?D.textSizeData:D.iconSizeData,et=o.bj(qe,C.transform.zoom,Ee),ct=He.projection.name==="globe",ot=[256/C.width*2+1,256/C.height*2+1],bt=O?D.text.dynamicLayoutVertexArray:D.icon.dynamicLayoutVertexArray;bt.clear();let vt=null;ct&&(vt=O?D.text.globeExtVertexArray:D.icon.globeExtVertexArray);const Pt=D.lineVertexArray,Ft=O?D.text.placedSymbolArray:D.icon.placedSymbolArray,jt=C.transform.width/C.transform.height;let ys,Qt=!1;for(let gs=0;gsMath.abs(C)?{useVertical:!0}:D===o.bk.vertical?O>0?{needsFlipping:!0}:null:w!==0&&function(U,Y){return U===0||Math.abs(Y/U)>Jy}(C,O)?w===1?{needsFlipping:!0}:null:C<0?{needsFlipping:!0}:null}function ss(D,w,C,O,U,Y,Z,se,pe,je,Ee,He,qe,et,ct,ot,bt,vt,Pt,Ft){const jt=w/24,ys=D.lineOffsetX*jt,Qt=D.lineOffsetY*jt,{lineStartIndex:gs,glyphStartIndex:$t,numGlyphs:Zt,segment:hs,writingMode:Us,flipState:Cs}=D,hn=gs+D.lineLength,an=An=>{if(Ee){const[cn,pn,vn]=An.up,fr=je.length;o.bm(Ee,fr+0,cn,pn,vn),o.bm(Ee,fr+1,cn,pn,vn),o.bm(Ee,fr+2,cn,pn,vn),o.bm(Ee,fr+3,cn,pn,vn)}const[On,Ks,Es]=An.point;o.bn(je,On,Ks,Es,An.angle)};if(Zt>1){const An=ze(jt,se,ys,Qt,C,He,qe,D,pe,Y,et,ot,!1,bt,vt,Pt,Ft);if(!An)return{notEnoughRoom:!0};if(O&&!C){let[On,Ks,Es]=An.first.point,[cn,pn,vn]=An.last.point;[On,Ks]=Rd(On,Ks,Es,Z),[cn,pn]=Rd(cn,pn,vn,Z);const fr=xt(Us,Cs,(cn-On)*ct,pn-Ks);if(D.flipState=fr&&fr.needsFlipping?1:2,fr)return fr}an(An.first);for(let On=$t+1;On<$t+Zt-1;On++){const Ks=Mn(jt*se.getoffsetX(On),ys,Qt,C,He,qe,hs,gs,hn,pe,Y,et,ot,!1,!1,bt,vt,Pt,Ft);if(!Ks)return je.length-=4*(On-$t),{notEnoughRoom:!0};an(Ks)}an(An.last)}else{if(O&&!C){const On=Rd(qe.x,qe.y,0,U),Ks=gs+hs+1,Es=new o.P(pe.getx(Ks),pe.gety(Ks)),cn=Rd(Es.x,Es.y,0,U),pn=cn[3]>0?cn:tn(qe,Es,On,1,U,void 0,bt,vt.canonical),vn=xt(Us,Cs,(pn[0]-On[0])*ct,pn[1]-On[1]);if(D.flipState=vn&&vn.needsFlipping?1:2,vn)return vn}const An=Mn(jt*se.getoffsetX($t),ys,Qt,C,He,qe,hs,gs,hn,pe,Y,et,ot,!1,!1,bt,vt,Pt,Ft);if(!An)return{notEnoughRoom:!0};an(An)}return{}}function cs(D,w,C,O,U){const{x:Y,y:Z,z:se}=O.projectTilePoint(D.x,D.y,w);if(!U)return Rd(Y,Z,se,C);const[pe,je,Ee]=U.getElevation(D,U.elevation,U.elevationFeature);return Rd(Y+pe,Z+je,se+Ee,C)}function tn(D,w,C,O,U,Y,Z,se){const pe=cs(D.sub(w)._unit()._add(D),se,U,Z,Y);return o.ax(pe,C,pe),o.ay(pe,pe),o.bg(pe,C,pe,O)}function Mn(D,w,C,O,U,Y,Z,se,pe,je,Ee,He,qe,et,ct,ot,bt,vt,Pt){const Ft=O?D-w:D+w;let jt=Ft>0?1:-1,ys=0;O&&(jt*=-1,ys=Math.PI),jt<0&&(ys+=Math.PI);let Qt=se+Z+(jt>0?0:1)|0,gs=U,$t=U,Zt=0,hs=0;const Us=Math.abs(Ft),Cs=[],hn=[];let an=Y,An=an,On=o.be([]);const Ks=()=>tn(An,an,$t,Us-Zt+1,Ee,qe,ot,bt.canonical);for(;Zt+hs<=Us;){if(Qt+=jt,Qt=pe)return null;if($t=gs,An=an,Cs.push($t),et&&hn.push(An),an=new o.P(je.getx(Qt),je.gety(Qt)),gs=He[Qt],!gs){const fa=cs(an,bt.canonical,Ee,ot,qe);gs=fa[3]>0?He[Qt]=fa:Ks()}Zt+=hs;const In=o.ax([],gs,$t),Yr=o.bf($t,gs);if(C&&Yr>0&&hs>0&&o.bi(On,In)/(hs*Yr)0,Ft),gs=je*Qt.perspectiveRatio,$t=(O.x1*C+se.x-O.padding)*gs+Qt.point.x,Zt=(O.y1*C+se.y-O.padding)*gs+Qt.point.y,hs=(O.x2*C+se.x+O.padding)*gs+Qt.point.x,Us=(O.y2*C+se.y+O.padding)*gs+Qt.point.y,Cs=Qt.perspectiveRatio<=.55||Qt.occluded;return!this.isInsideGrid($t,Zt,hs,Us)||!pe&&this.grid.hitTest($t,Zt,hs,Us,He)||Cs?{box:[],offscreen:!1,occluded:Qt.occluded}:{box:[$t,Zt,hs,Us],offscreen:this.isOffscreen($t,Zt,hs,Us),occluded:!1}}placeCollisionCircles(w,C,O,U,Y,Z,se,pe,je,Ee,He,qe,et,ct,ot,bt){const vt=[],Pt=this.transform.elevation,Ft=w.getProjection(),jt=w.elevationType==="road",ys=!!Pt||jt,Qt=o.bu.getAtTileOffsetFunc(bt,this.transform.center.lat,this.transform.worldSize,Ft),gs=new o.P(O.tileAnchorX,O.tileAnchorY),$t=new o.P(O.tileAnchorX,O.tileAnchorY);let{x:Zt,y:hs,z:Us}=Ft.projectTilePoint($t.x,$t.y,bt.canonical),Cs=null;if(ys){const Yr=jt?w.getElevationFeatureForText(U):null;Cs={getElevation:Qt,elevation:Pt,elevationFeature:Yr};const[fa,Fr,Vr]=Qt(gs,Pt,Yr);Zt+=fa,hs+=Fr,Us+=Vr}const hn=Ft.name==="globe",an=this.projectAndGetPerspectiveRatio(pe,Zt,hs,Us,bt,hn||!!Pt||this.transform.pitch>0,Ft),{perspectiveRatio:An}=an,On=(qe?se/An:se*An)/o.by,Ks=Rd(Zt,hs,Us,je),Es=O.lineOffsetX*On,cn=O.lineOffsetY*On,pn=o.ap(w.layers[0].layout.get("text-max-angle")),vn=Math.cos(pn),fr=an.signedDistanceFromCamera>0?ze(On,Z,Es,cn,jt&&O.flipState===1,Ks,$t,O,Y,je,{},ys&&!qe?Cs:null,qe&&ys,Ft,bt,qe,vn):null;let nr=!1,rr=!1,In=!0;if(fr&&!an.occluded){const Yr=.5*ct*An+ot,fa=new o.P(-100,-100),Fr=new o.P(this.screenRightBoundary,this.screenBottomBoundary),Vr=new zp,{first:$a,last:ri}=fr,ei=$a.path.length;let Li=[];for(let ti=ei-1;ti>=1;ti--)Li.push($a.path[ti]);for(let ti=1;ti(ys&&!hn&&(yl=Qt(Gcti[3]<=0)&&(Li=[]));let Pi=[];if(Li.length>0){let ti=1/0,So=-1/0,yl=1/0,Gc=-1/0;for(const ql of Li)ti=Math.min(ti,ql[0]),yl=Math.min(yl,ql[1]),So=Math.max(So,ql[0]),Gc=Math.max(Gc,ql[1]);So>=fa.x&&ti<=Fr.x&&Gc>=fa.y&&yl<=Fr.y&&(Pi=[Li.map(ql=>new o.P(ql[0],ql[1]))],(tiFr.x||ylFr.y)&&(Pi=o.bv(Pi,fa.x,fa.y,Fr.x,Fr.y)))}for(const ti of Pi){Vr.reset(ti,.25*Yr);let So=0;So=Vr.length<=.5*Yr?1:Math.ceil(Vr.paddedLength/Ea)+1;for(let yl=0;yl0?(o.aE(pe,pe,w),this.fogState&&Y&&se.name!=="globe"&&(je=function(qe,et,ct,ot,bt,vt){const Pt=vt.calculateFogTileMatrix(bt),Ft=[et,ct,ot];return o.ah(Ft,Ft,Pt),Jr(qe,o.ai(Ft),vt.pitch,vt._fov)}(this.fogState,C,O,U,Y.toUnwrapped(),this.transform)>.9)):mr(pe,pe,w);const Ee=pe[3];return{point:new o.P((pe[0]/Ee+1)/2*this.transform.width+Ba,(-pe[1]/Ee+1)/2*this.transform.height+Ba),perspectiveRatio:Math.min(.5+this.transform.getCameraToCenterDistance(se)/Ee*.5,1.5),signedDistanceFromCamera:Ee,occluded:Z&&pe[2]>Ee||je}}isOffscreen(w,C,O,U){return O=this.screenRightBoundary||Uthis.screenBottomBoundary}isInsideGrid(w,C,O,U){return O>=0&&w=0&&CO.collisionGroupID===C}}return this.collisionGroups[w]}}function jl(D,w,C,O,U){const{horizontalAlign:Y,verticalAlign:Z}=o.bF(D),se=-(Y-.5)*w,pe=-(Z-.5)*C,je=o.bG(D,O);return new o.P(se+je[0]*U,pe+je[1]*U)}function xc(D,w,C,O,U){const Y=new o.P(D,w);return C&&Y._rotate(O?U:-U),Y}class qi{constructor(w,C,O,U,Y,Z){this.transform=w.clone(),this.projection=w.projection.name,this.collisionIndex=new Ki(this.transform,Y),this.buildingIndex=Z,this.frontCutoffStart=0,this.placements={},this.opacities={},this.variableOffsets={},this.stale=!1,this.commitTime=0,this.fadeDuration=C,this.retainedQueryData={},this.collisionGroups=new ci(O),this.collisionCircleArrays={},this.prevPlacement=U,U&&(U.prevPlacement=void 0),this.placedOrientations={},this.lastReplacementSourceUpdateTime=0}getBucketParts(w,C,O,U,Y=1){const Z=O.getBucket(C),se=O.latestFeatureIndex;if(!Z||!se||C.fqid!==Z.layerIds[0])return;const pe=Z.layers[0].layout,je=Z.layers[0].paint,Ee=O.collisionBoxArray,He=Math.pow(2,this.transform.zoom-O.tileID.overscaledZ),qe=O.tileSize/o.an,et=O.tileID.toUnwrapped();this.transform.setProjection(Z.projection);const ct=(ot=O.tileID,bt=Z.getProjection(),vt=this.transform,bt.name===this.projection?vt.calculateProjMatrix(ot.toUnwrapped()):mx(vt,bt,ot));var ot,bt,vt;const Pt=pe.get("text-pitch-alignment")==="map",Ft=pe.get("text-rotation-alignment")==="map";C.compileFilter(C.options);const jt=C.dynamicFilter(),ys=C.dynamicFilterNeedsFeature(),Qt=C.dynamicFilterNeedsGeometry(),gs=this.transform.calculatePixelsToTileUnitsMatrix(O),$t=Nc(ct,O.tileID.canonical,Pt,Ft,this.transform,Z.getProjection(),gs);let Zt=null;const hs=Z.getProjection().createInversionMatrix(this.transform,O.tileID.canonical);if(Pt){const cn=Qm(ct,O.tileID.canonical,Pt,Ft,this.transform,Z.getProjection(),gs);Zt=o.aD([],this.transform.labelPlaneMatrix,cn)}let Us=null;jt&&O.latestFeatureIndex&&(Us={unwrappedTileID:et,dynamicFilter:jt,dynamicFilterNeedsFeature:ys,needGeometry:Qt}),this.retainedQueryData[Z.bucketInstanceId]=new Za(Z.bucketInstanceId,se,Z.sourceLayerIndex,Z.index,O.tileID);const[Cs,hn]=Z.layers[0].layout.get("text-size-scale-range"),an=o.aC(Y,Cs,hn),[An,On]=pe.get("icon-size-scale-range"),Ks=o.aC(Y,An,On),Es={bucket:Z,layout:pe,paint:je,posMatrix:ct,invMatrix:hs,mercatorCenter:[o.aH(this.transform.center.lng),o.aL(this.transform.center.lat)],textLabelPlaneMatrix:$t,labelToScreenMatrix:Zt,clippingData:Us,scale:He,textPixelRatio:qe,holdingForFade:O.holdingForFade(),collisionBoxArray:Ee,partiallyEvaluatedTextSize:o.bj(Z.textSizeData,this.transform.zoom,an),partiallyEvaluatedIconSize:o.bj(Z.iconSizeData,this.transform.zoom,Ks),collisionGroup:this.collisionGroups.get(Z.sourceID),latestFeatureIndex:O.latestFeatureIndex};if(U)for(const cn of Z.sortKeyRanges){const{sortKey:pn,symbolInstanceStart:vn,symbolInstanceEnd:fr}=cn;w.push({sortKey:pn,symbolInstanceStart:vn,symbolInstanceEnd:fr,parameters:Es})}else w.push({symbolInstanceStart:0,symbolInstanceEnd:Z.symbolInstances.length,parameters:Es})}attemptAnchorPlacement(w,C,O,U,Y,Z,se,pe,je,Ee,He,qe,et,ct,ot,bt,vt,Pt,Ft,jt,ys){const{textOffset0:Qt,textOffset1:gs,crossTileID:$t}=ot,Zt=[Qt,gs],hs=jl(w,Z,se,Zt,pe),Us=this.collisionIndex.placeCollisionBox(vt,pe,C,O,U,Y,xc(hs.x,hs.y,je,Ee,this.transform.angle),ct,He,qe,et.predicate);if(Ft){const Cs=vt.getSymbolInstanceIconSize(ys,this.transform.zoom,ot.placedIconSymbolIndex);if(this.collisionIndex.placeCollisionBox(vt,Cs,Ft,O,U,Y,xc(hs.x,hs.y,je,Ee,this.transform.angle),ct,He,qe,et.predicate).box.length===0)return}if(Us.box.length>0){let Cs;return this.prevPlacement&&this.prevPlacement.variableOffsets[$t]&&this.prevPlacement.placements[$t]&&this.prevPlacement.placements[$t].text&&(Cs=this.prevPlacement.variableOffsets[$t].anchor),this.variableOffsets[$t]={textOffset:Zt,width:Z,height:se,anchor:w,textScale:pe,prevAnchor:Cs},this.markUsedJustification(vt,w,ot,Pt),vt.allowVerticalPlacement&&(this.markUsedOrientation(vt,Pt,ot),this.placedOrientations[$t]=Pt),{shift:hs,placedGlyphBoxes:Us}}}placeLayerBucketPart(w,C,O,U,Y=1){const{bucket:Z,layout:se,paint:pe,posMatrix:je,textLabelPlaneMatrix:Ee,labelToScreenMatrix:He,clippingData:qe,textPixelRatio:et,mercatorCenter:ct,invMatrix:ot,holdingForFade:bt,collisionBoxArray:vt,partiallyEvaluatedTextSize:Pt,partiallyEvaluatedIconSize:Ft,collisionGroup:jt,latestFeatureIndex:ys}=w.parameters,Qt=se.get("text-optional"),gs=se.get("icon-optional"),$t=se.get("text-allow-overlap"),Zt=se.get("icon-allow-overlap"),hs=se.get("text-rotation-alignment")==="map",Us=se.get("icon-rotation-alignment")==="map",Cs=se.get("text-pitch-alignment")==="map",hn=pe.get("symbol-z-offset"),an=se.get("symbol-elevation-reference")==="sea",An=se.get("symbol-placement"),[On,Ks]=se.get("text-size-scale-range"),[Es,cn]=se.get("icon-size-scale-range"),pn=o.aC(Y,On,Ks),vn=o.aC(Y,Es,cn),fr=se.get("text-variable-anchor"),nr=hs&&An!=="point",rr=Us&&An!=="point",In=fr&&Z.hasTextData(),Yr=Z.hasIconTextFit()&&In&&Z.hasIconData();this.transform.setProjection(Z.projection);const fa=In||nr,Fr=rr||Yr;let Vr=$t&&(Zt||!Z.hasIconData()||gs),$a=Zt&&($t||!Z.hasTextData()||Qt);const ri=!hn.isConstant();!Z.collisionArrays&&vt&&Z.deserializeCollisionBoxes(vt),O&&U&&Z.updateCollisionDebugBuffers(this.transform.zoom,vt,pn,vn);const ei=(Ea,Pi,ti)=>{const{crossTileID:So,numVerticalGlyphVertices:yl}=Ea;let Gc=null;if(qe&&qe.dynamicFilterNeedsFeature||ri){const Ql=this.retainedQueryData[Z.bucketInstanceId],uc=ys.loadFeature({featureIndex:Ea.featureIndex,bucketIndex:Ql.bucketIndex,sourceLayerIndex:Ql.sourceLayerIndex,layoutVertexArrayOffset:0}),cl=uc.properties?uc.properties.worldview:null;if(Z.localizable&&Z.worldview&&typeof cl=="string")if(cl==="all")uc.properties.$localized=!0;else{if(!cl.split(",").includes(Z.worldview))return;uc.properties.$localized=!0,uc.properties.worldview=Z.worldview}Gc=qe&&qe.needGeometry?o.bD(uc,!0):uc}if(qe&&!(0,qe.dynamicFilter)({zoom:this.transform.zoom,pitch:this.transform.pitch,worldview:Z.worldview},Gc,this.retainedQueryData[Z.bucketInstanceId].tileID.canonical,new o.P(Ea.tileAnchorX,Ea.tileAnchorY),this.transform.calculateDistanceTileData(qe.unwrappedTileID)))return this.placements[So]=new Mc(!1,!1,!1,!0),void C.add(So);const ql=hn.evaluate(Gc,{});if((Ea.zOffset||0)+(ql||0)>0&&this.frontCutoffStart>0){const Ql=2*this.frontCutoffStart-1,uc=[Ea.tileAnchorX,Ea.tileAnchorY,0,1],cl=o.aE(o.bE(),uc,je);if(cl[1]/cl[3]{Ql.tileID=this.retainedQueryData[Z.bucketInstanceId].tileID;const uc=this.transform.elevation;Ql.elevation=an?ql:ql+o.bu.getAtTileOffset(Ql.tileID,new o.P(Ql.tileAnchorX,Ql.tileAnchorY),uc,kh),Ql.elevation+=Ea.zOffset},my=ti.textBox;if(my){ip(my);const Ql=cl=>{let gu=o.bk.horizontal;if(Z.allowVerticalPlacement&&!cl&&this.prevPlacement){const ng=this.prevPlacement.placedOrientations[So];ng&&(this.placedOrientations[So]=ng,gu=ng,this.markUsedOrientation(Z,gu,Ea))}return gu},uc=(cl,gu)=>{if(Z.allowVerticalPlacement&&yl>0&&ti.verticalTextBox){for(const ng of Z.writingModes)if(ng===o.bk.vertical?(ui=gu(),Ic=ui):ui=cl(),ui&&ui.box&&ui.box.length)break}else ui=cl()};if(fr){let cl=fr;if(this.prevPlacement&&this.prevPlacement.variableOffsets[So]){const Nd=this.prevPlacement.variableOffsets[So];cl.indexOf(Nd.anchor)>0&&(cl=cl.filter(py=>py!==Nd.anchor),cl.unshift(Nd.anchor))}const gu=(Nd,py,qN)=>{const bS=Z.getSymbolInstanceTextSize(Pt,Ea,this.transform.zoom,Pi),_S=(Nd.x2-Nd.x1)*bS+2*Nd.padding,sC=(Nd.y2-Nd.y1)*bS+2*Nd.padding,Wj=Ea.hasIconTextFit&&!Zt?py:null;Wj&&ip(Wj);let gw={box:[],offscreen:!1,occluded:!1};const nC=$t?2*cl.length:cl.length;for(let y0=0;y0=cl.length,Ea,Pi,Z,qN,Wj,Pt,Ft);if(VN&&(gw=VN.placedGlyphBoxes,gw&&gw.box&&gw.box.length)){Bo=!0,$o=VN.shift;break}}return gw};uc(()=>gu(my,ti.iconBox,o.bk.horizontal),()=>{const Nd=ti.verticalTextBox;return Nd&&ip(Nd),Z.allowVerticalPlacement&&!(ui&&ui.box&&ui.box.length)&&yl>0&&Nd?gu(Nd,ti.verticalIconBox,o.bk.vertical):{box:null,offscreen:null,occluded:null}}),ui&&(Bo=ui.box,Ni=ui.offscreen,Vl=ui.occluded);const ng=Ql(!(!ui||!ui.box));if(!Bo&&this.prevPlacement){const Nd=this.prevPlacement.variableOffsets[So];Nd&&(this.variableOffsets[So]=Nd,this.markUsedJustification(Z,Nd.anchor,Ea,ng))}}else{const cl=(gu,ng)=>{const Nd=Z.getSymbolInstanceTextSize(Pt,Ea,this.transform.zoom,Pi),py=this.collisionIndex.placeCollisionBox(Z,Nd,gu,ct,ot,fa,new o.P(0,0),$t,et,je,jt.predicate);return py&&py.box&&py.box.length&&(this.markUsedOrientation(Z,ng,Ea),this.placedOrientations[So]=ng),py};uc(()=>cl(my,o.bk.horizontal),()=>{const gu=ti.verticalTextBox;return Z.allowVerticalPlacement&&yl>0&&gu?(ip(gu),cl(gu,o.bk.vertical)):{box:null,offscreen:null,occluded:null}}),Ql(!!(ui&&ui.box&&ui.box.length))}}if(vl=ui,Bo=vl&&vl.box&&vl.box.length>0,Ni=vl&&vl.offscreen,Vl=vl&&vl.occluded,Ea.useRuntimeCollisionCircles){const Ql=Ea.centerJustifiedTextSymbolIndex>=0?Ea.centerJustifiedTextSymbolIndex:Ea.verticalPlacedTextSymbolIndex,uc=Z.text.placedSymbolArray.get(Ql),cl=o.bl(Z.textSizeData,Pt,uc),gu=se.get("text-padding");Ru=this.collisionIndex.placeCollisionCircles(Z,$t,uc,Ql,Z.lineVertexArray,Z.glyphOffsetArray,cl,je,Ee,He,O,Cs,jt.predicate,Ea.collisionCircleDiameter*cl/o.by,gu,this.retainedQueryData[Z.bucketInstanceId].tileID),Bo=$t||Ru.circles.length>0&&!Ru.collisionDetected,Ni=Ni&&Ru.offscreen,Vl=Ru.occluded}if(ti.iconFeatureIndex&&(Ef=ti.iconFeatureIndex),ti.iconBox){const Ql=uc=>{ip(uc);const cl=Ea.hasIconTextFit&&$o?xc($o.x,$o.y,hs,Cs,this.transform.angle):new o.P(0,0),gu=Z.getSymbolInstanceIconSize(Ft,this.transform.zoom,Ea.placedIconSymbolIndex);return this.collisionIndex.placeCollisionBox(Z,gu,uc,ct,ot,Fr,cl,Zt,et,je,jt.predicate)};Ic&&Ic.box&&Ic.box.length&&ti.verticalIconBox?(Xi=Ql(ti.verticalIconBox),ji=Xi.box.length>0):(Xi=Ql(ti.iconBox),ji=Xi.box.length>0),Ni=Ni&&Xi.offscreen,nd=Xi.occluded}const sl=Qt||Ea.numHorizontalGlyphVertices===0&&yl===0,dv=gs||Ea.numIconVertices===0;if(sl||dv?dv?sl||(ji=ji&&Bo):Bo=ji&&Bo:ji=Bo=ji&&Bo,Bo&&vl&&vl.box&&this.collisionIndex.insertCollisionBox(vl.box,se.get("text-ignore-placement"),Z.bucketInstanceId,Ic&&Ic.box&&uh?uh:Rl,jt.ID),ji&&Xi&&this.collisionIndex.insertCollisionBox(Xi.box,se.get("icon-ignore-placement"),Z.bucketInstanceId,Ef,jt.ID),Ru&&(Bo&&this.collisionIndex.insertCollisionCircles(Ru.circles,se.get("text-ignore-placement"),Z.bucketInstanceId,Rl,jt.ID),O)){const Ql=Z.bucketInstanceId;let uc=this.collisionCircleArrays[Ql];uc===void 0&&(uc=this.collisionCircleArrays[Ql]=new Lr);for(let cl=0;cl=0;--Pi){const ti=Ea[Pi];ei(Z.symbolInstances.get(ti),ti,Z.collisionArrays[ti])}Z.hasAnyZOffset&&o.w(`${Z.layerIds[0]} layer symbol-z-elevate: symbols are not sorted by elevation if symbol-z-order is evaluated to viewport-y`)}else if(Z.hasAnyZOffset){const Ea=Z.getSortedIndexesByZOffset();for(let Pi=0;Pi=0&&(w.text.placedSymbolArray.get(Y).crossTileID=He>=0&&Y!==He?0:je),Z>=0&&(w.text.placedSymbolArray.get(Z).crossTileID=He>=0&&Z!==He?0:je),se>=0&&(w.text.placedSymbolArray.get(se).crossTileID=He>=0&&se!==He?0:je),pe>=0&&(w.text.placedSymbolArray.get(pe).crossTileID=He>=0&&pe!==He?0:je)}markUsedOrientation(w,C,O){const U=C===o.bk.horizontal||C===o.bk.horizontalOnly?C:0,Y=C===o.bk.vertical?C:0,{leftJustifiedTextSymbolIndex:Z,centerJustifiedTextSymbolIndex:se,rightJustifiedTextSymbolIndex:pe,verticalPlacedTextSymbolIndex:je}=O,Ee=w.text.placedSymbolArray;Z>=0&&(Ee.get(Z).placedOrientation=U),se>=0&&(Ee.get(se).placedOrientation=U),pe>=0&&(Ee.get(pe).placedOrientation=U),je>=0&&(Ee.get(je).placedOrientation=Y)}commit(w){this.commitTime=w,this.zoomAtLastRecencyCheck=this.transform.zoom;const C=this.prevPlacement;let O=!1;this.prevZoomAdjustment=C?C.zoomAdjustment(this.transform.zoom):0;const U=C?C.symbolFadeChange(w):1,Y=C?C.opacities:{},Z=C?C.variableOffsets:{},se=C?C.placedOrientations:{};for(const pe in this.placements){const je=this.placements[pe],Ee=Y[pe];Ee?(this.opacities[pe]=new tl(Ee,U,je.text,je.icon,null,je.clipped),O=O||je.text!==Ee.text.placed||je.icon!==Ee.icon.placed):(this.opacities[pe]=new tl(null,U,je.text,je.icon,je.skipFade,je.clipped),O=O||je.text||je.icon)}for(const pe in Y){const je=Y[pe];if(!this.opacities[pe]){const Ee=new tl(je,U,!1,!1);Ee.isHidden()||(this.opacities[pe]=Ee,O=O||je.text.placed||je.icon.placed)}}for(const pe in Z)this.variableOffsets[pe]||!this.opacities[pe]||this.opacities[pe].isHidden()||(this.variableOffsets[pe]=Z[pe]);for(const pe in se)this.placedOrientations[pe]||!this.opacities[pe]||this.opacities[pe].isHidden()||(this.placedOrientations[pe]=se[pe]);O?this.lastPlacementChangeTime=w:typeof this.lastPlacementChangeTime!="number"&&(this.lastPlacementChangeTime=C?C.lastPlacementChangeTime:w)}updateLayerOpacities(w,C,O,U){U&&(this.lastReplacementSourceUpdateTime=U.updateTime);const Y=new Set;for(const Z of C){const se=Z.getBucket(w);se&&Z.latestFeatureIndex&&w.fqid===se.layerIds[0]&&(this.updateBucketOpacities(se,Y,Z,Z.collisionBoxArray,O,U,Z.tileID,w.scope),se.elevationType==="offset"&&this.buildingIndex&&this.buildingIndex.updateZOffset(se,Z.tileID),se.elevationType==="road"&&se.updateRoadElevation(Z.tileID.canonical),se.updateZOffset())}}updateBucketOpacities(w,C,O,U,Y,Z,se,pe){w.hasTextData()&&w.text.opacityVertexArray.clear(),w.hasIconData()&&w.icon.opacityVertexArray.clear(),w.hasIconCollisionBoxData()&&w.iconCollisionBox.collisionVertexArray.clear(),w.hasTextCollisionBoxData()&&w.textCollisionBox.collisionVertexArray.clear();const je=w.layers[0].layout,Ee=w.layers[0].paint,He=!!w.layers[0].dynamicFilter(),qe=new tl(null,0,!1,!1,!0),et=je.get("text-allow-overlap"),ct=je.get("icon-allow-overlap"),ot=je.get("text-variable-anchor"),bt=je.get("text-rotation-alignment")==="map",vt=je.get("text-pitch-alignment")==="map",Pt=Ee.get("symbol-z-offset"),Ft=je.get("symbol-elevation-reference")==="sea",jt=!Pt.isConstant(),ys=new tl(null,0,et&&(ct||!w.hasIconData()||je.get("icon-optional")),ct&&(et||!w.hasTextData()||je.get("text-optional")),!0);!w.collisionArrays&&U&&(w.hasIconCollisionBoxData()||w.hasTextCollisionBoxData())&&w.deserializeCollisionBoxes(U);const Qt=($t,Zt,hs)=>{for(let Us=0;Us0||Us>0,fr=hn>0,nr=this.placedOrientations[Cs],rr=nr===o.bk.vertical,In=nr===o.bk.horizontal||nr===o.bk.horizontalOnly;!vn&&!fr||pn.isHidden()||gs++;let Yr=!1;if((vn||fr)&&Z)for(const fa of w.activeReplacements){if(o.bz(fa,Y,o.bA.Symbol,pe)||fa.min.x>an||an>fa.max.x||fa.min.y>An||An>fa.max.y)continue;const Fr=o.bB(an,An,se.canonical,fa.footprintTileId.canonical);if(Yr=o.bC(Fr,fa.footprint),Yr)break}if(Yr&&this.collisionIndex.markSymbolAsClipped(w.bucketInstanceId,Zt.featureIndex),vn){const fa=Yr?ep:Od(pn.text);Qt(w.text,hs,rr?ep:fa),Qt(w.text,Us,In?ep:fa);const Fr=pn.text.isHidden(),{leftJustifiedTextSymbolIndex:Vr,centerJustifiedTextSymbolIndex:$a,rightJustifiedTextSymbolIndex:ri,verticalPlacedTextSymbolIndex:ei}=Zt,Li=w.text.placedSymbolArray,Ea=Fr||rr?1:0;Vr>=0&&(Li.get(Vr).hidden=Ea),$a>=0&&(Li.get($a).hidden=Ea),ri>=0&&(Li.get(ri).hidden=Ea),ei>=0&&(Li.get(ei).hidden=Fr||In?1:0);const Pi=this.variableOffsets[Cs];Pi&&this.markUsedJustification(w,Pi.anchor,Zt,nr);const ti=this.placedOrientations[Cs];ti&&(this.markUsedJustification(w,"left",Zt,ti),this.markUsedOrientation(w,ti,Zt))}if(fr){const fa=Yr?ep:Od(pn.icon),{placedIconSymbolIndex:Fr,verticalPlacedIconSymbolIndex:Vr}=Zt,$a=w.icon.placedSymbolArray,ri=pn.icon.isHidden()?1:0;Fr>=0&&(Qt(w.icon,hn,rr?ep:fa),$a.get(Fr).hidden=ri),Vr>=0&&(Qt(w.icon,Zt.numVerticalIconVertices,In?ep:fa),$a.get(Vr).hidden=ri)}if(w.hasIconCollisionBoxData()||w.hasTextCollisionBoxData()){const fa=w.collisionArrays[$t];if(fa){let Fr=new o.P(0,0),Vr=!0;if(fa.textBox||fa.verticalTextBox){if(ot){const ri=this.variableOffsets[Cs];ri?(Fr=jl(ri.anchor,ri.width,ri.height,ri.textOffset,ri.textScale),bt&&Fr._rotate(vt?this.transform.angle:-this.transform.angle)):Vr=!1}He&&(Vr=!pn.clipped),fa.textBox&&Gh(w.textCollisionBox.collisionVertexArray,pn.text.placed,!Vr||rr,Es,Ft,Fr.x,Fr.y),fa.verticalTextBox&&Gh(w.textCollisionBox.collisionVertexArray,pn.text.placed,!Vr||In,Es,Ft,Fr.x,Fr.y)}const $a=Vr&&!!(!In&&fa.verticalIconBox);fa.iconBox&&Gh(w.iconCollisionBox.collisionVertexArray,pn.icon.placed,$a,Es,Ft,Zt.hasIconTextFit?Fr.x:0,Zt.hasIconTextFit?Fr.y:0),fa.verticalIconBox&&Gh(w.iconCollisionBox.collisionVertexArray,pn.icon.placed,!$a,Es,Ft,Zt.hasIconTextFit?Fr.x:0,Zt.hasIconTextFit?Fr.y:0)}}}if(w.fullyClipped=gs===0,w.sortFeatures(this.transform.angle),this.retainedQueryData[w.bucketInstanceId]&&(this.retainedQueryData[w.bucketInstanceId].featureSortOrder=w.featureSortOrder),w.hasTextData()&&w.text.opacityVertexBuffer&&w.text.opacityVertexBuffer.updateData(w.text.opacityVertexArray),w.hasIconData()&&w.icon.opacityVertexBuffer&&w.icon.opacityVertexBuffer.updateData(w.icon.opacityVertexArray),w.hasIconCollisionBoxData()&&w.iconCollisionBox.collisionVertexBuffer&&w.iconCollisionBox.collisionVertexBuffer.updateData(w.iconCollisionBox.collisionVertexArray),w.hasTextCollisionBoxData()&&w.textCollisionBox.collisionVertexBuffer&&w.textCollisionBox.collisionVertexBuffer.updateData(w.textCollisionBox.collisionVertexArray),w.bucketInstanceId in this.collisionCircleArrays){const $t=this.collisionCircleArrays[w.bucketInstanceId];w.placementInvProjMatrix=$t.invProjMatrix,w.placementViewportMatrix=$t.viewportMatrix,w.collisionCircleArray=$t.circles,delete this.collisionCircleArrays[w.bucketInstanceId]}}symbolFadeChange(w){return this.fadeDuration===0?1:(w-this.commitTime)/this.fadeDuration+this.prevZoomAdjustment}zoomAdjustment(w){return Math.max(0,(this.transform.zoom-w)/1.5)}hasTransitions(w){return w-this.lastPlacementChangeTimew}isStale(){return this.stale}setStale(){this.stale=!0}}function Gh(D,w,C,O,U,Y,Z){D.emplaceBack(w?1:0,C?1:0,Y||0,Z||0,O,U?1:0),D.emplaceBack(w?1:0,C?1:0,Y||0,Z||0,O,U?1:0),D.emplaceBack(w?1:0,C?1:0,Y||0,Z||0,O,U?1:0),D.emplaceBack(w?1:0,C?1:0,Y||0,Z||0,O,U?1:0)}const px=Math.pow(2,25),fx=Math.pow(2,24),du=Math.pow(2,17),$l=Math.pow(2,16),c1=Math.pow(2,9),Tg=Math.pow(2,8),r0=Math.pow(2,1);function Od(D){if(D.opacity===0&&!D.placed)return 0;if(D.opacity===1&&D.placed)return 4294967295;const w=D.placed?1:0,C=Math.floor(127*D.opacity);return C*px+w*fx+C*du+w*$l+C*c1+w*Tg+C*r0+w}const ep=0;class a0{constructor(w){this._sortAcrossTiles=w.layout.get("symbol-z-order")!=="viewport-y"&&w.layout.get("symbol-sort-key").constantOr(1)!==void 0,this._currentTileIndex=0,this._currentPartIndex=0,this._seenCrossTileIDs=new Set,this._bucketParts=[]}continuePlacement(w,C,O,U,Y,Z){const se=this._bucketParts;for(;this._currentTileIndexpe.sortKey-je.sortKey));this._currentPartIndex{const pe=o.o.now()-Z;return!this.isFullPlacementRequested()&&this._fadeDuration!==0&&pe>2};for(;this._currentPlacementIndex>=0;){const pe=C[w[this._currentPlacementIndex]],je=this.placement.collisionIndex.transform.zoom;if(pe.type==="symbol"&&pe.visibility!=="none"&&(!pe.minzoom||pe.minzoom<=je)&&(!pe.maxzoom||pe.maxzoom>je)){const Ee=pe,He=Ee.layout.get("symbol-z-elevate"),qe=Ee.layout.get("symbol-sort-key").constantOr(1)!==void 0,et=Ee.layout.get("symbol-z-order"),ct=et==="viewport-y"||et==="auto"&&!(et!=="viewport-y"&&qe),ot=Ee.layout.get("text-allow-overlap")||Ee.layout.get("icon-allow-overlap")||Ee.layout.get("text-ignore-placement")||Ee.layout.get("icon-ignore-placement"),bt=ct&&ot,vt=this._inProgressLayer=this._inProgressLayer||new a0(Ee),Pt=o.F(pe.source,pe.scope);if(vt.continuePlacement(He||bt?U[Pt]:O[Pt],this.placement,this._showCollisionBoxes,pe,se,Y))return;delete this._inProgressLayer}this._currentPlacementIndex--}this._forceFullPlacement=!1,this._done=!0}commit(w){return this.placement.commit(w),this.placement}}const ed=512/o.an/2;class ud{constructor(w,C,O){this.tileID=w,this.bucketInstanceId=O,this.index=new o.bI(C.length,16,Int32Array),this.keys=[],this.crossTileIDs=[];const U=w.canonical.x*o.an,Y=w.canonical.y*o.an;for(let Z=0;Zbt-vt);for(const bt of ot){const vt=this.crossTileIDs[bt];if(this.keys[bt]===Ee&&!O.has(vt)){O.add(vt),je.crossTileID=vt;break}}}}}class Mu{constructor(){this.maxCrossTileID=0}generate(){return++this.maxCrossTileID}}class pm{constructor(){this.indexes={},this.usedCrossTileIDs={},this.lng=0}handleWrapJump(w){const C=Math.round((w-this.lng)/360);if(C!==0)for(const O in this.indexes){const U=this.indexes[O],Y={};for(const Z in U){const se=U[Z];se.tileID=se.tileID.unwrapTo(se.tileID.wrap+C),Y[se.tileID.key]=se}this.indexes[O]=Y}this.lng=w}addBucket(w,C,O){if(this.indexes[w.overscaledZ]&&this.indexes[w.overscaledZ][w.key]){if(this.indexes[w.overscaledZ][w.key].bucketInstanceId===C.bucketInstanceId)return!1;this.removeBucketCrossTileIDs(w.overscaledZ,this.indexes[w.overscaledZ][w.key])}for(let Y=0;Yw.overscaledZ)for(const se in Z){const pe=Z[se];pe.tileID.isChildOf(w)&&pe.findMatches(C.symbolInstances,w,U)}else{const se=Z[w.scaledTo(Number(Y)).key];se&&se.findMatches(C.symbolInstances,w,U)}}for(let Y=0;Y{C[O]=!0});for(const O in this.layerIndexes)C[O]||delete this.layerIndexes[O]}}const il=771;class wa{constructor(w,C,O,U){this.blendFunction=w,this.blendColor=C.toNonPremultipliedRenderColor(null),this.mask=O,this.blendEquation=U}}wa.Replace=[1,0,1,0],wa.disabled=new wa(wa.Replace,o.aq.transparent,[!1,!1,!1,!1]),wa.unblended=new wa(wa.Replace,o.aq.transparent,[!0,!0,!0,!0]),wa.alphaBlended=new wa([1,il,1,il],o.aq.transparent,[!0,!0,!0,!0]),wa.alphaBlendedNonPremultiplied=new wa([770,il,770,il],o.aq.transparent,[!0,!0,!0,!0]),wa.multiply=new wa([774,0,774,0],o.aq.transparent,[!0,!0,!0,!0]),wa.multiplyAccumulateAlpha=new wa([774,0,1,il],o.aq.transparent,[!0,!0,!0,!0]),wa.additive=new wa([1,1,1,1],o.aq.transparent,[!0,!0,!0,!0]);class Ir{constructor(w,C,O){this.func=w,this.mask=C,this.range=O}}Ir.ReadOnly=!1,Ir.ReadWrite=!0,Ir.disabled=new Ir(519,Ir.ReadOnly,[0,1]);const Pl=7680;class Na{constructor(w,C,O,U,Y,Z){this.test=w,this.ref=C,this.mask=O,this.fail=U,this.depthFail=Y,this.pass=Z}}Na.disabled=new Na({func:519,mask:0},0,0,Pl,Pl,Pl);const fm=1029,td=2305;class ra{constructor(w,C,O){this.enable=w,this.mode=C,this.frontFace=O}}function Eg(D,w){const C=o.bO(D,3);o.bR(D,w),o.bW(D,3,C)}function gx(D,w){const C=o.bL([]);return o.bM(C,C,-w),o.bN(C,C,-D),C}function Jf(D,w){const C=[D[0],D[1],0],O=[w[0],w[1],0];if(o.ai(C)>=1e-15){const Z=o.ay([],C);o.bJ(O,Z,o.bi(O,Z)),w[0]=O[0],w[1]=O[1]}const U=o.bh([],w,D);if(o.bK(U)<1e-15)return null;const Y=Math.atan2(-U[1],U[0]);return gx(Math.atan2(Math.sqrt(D[0]*D[0]+D[1]*D[1]),-D[2]),Y)}ra.disabled=new ra(!1,fm,td),ra.backCCW=new ra(!0,fm,td),ra.backCW=new ra(!0,fm,2304),ra.frontCW=new ra(!0,1028,2304),ra.frontCCW=new ra(!0,1028,td);class i0{constructor(w,C){this.position=w,this.orientation=C}get position(){return this._position}set position(w){if(w){const C=w instanceof o.ag?w:new o.ag(w[0],w[1],w[2]);this._renderWorldCopies&&(C.x=o.bs(C.x,0,1)),this._position=C}else this._position=null}lookAtPoint(w,C,O){if(this.orientation=null,!this.position)return;const U=this.position,Y=O||(this._elevation?this._elevation.getAtPointOrZero(o.ag.fromLngLat(w)):0),Z=o.ag.fromLngLat(w,Y),se=[Z.x-U.x,Z.y-U.y,Z.z-U.z];C||(C=[0,0,1]),C[2]=Math.abs(C[2]),this.orientation=Jf(se,C)}setPitchBearing(w,C){this.orientation=gx(o.ap(w),o.ap(-C))}}class kf{constructor(w,C){this._transform=o.b9([]),this.orientation=C,this.position=w}get mercatorPosition(){const w=this.position;return new o.ag(w[0],w[1],w[2])}get position(){const w=o.bO(this._transform,3);return[w[0],w[1],w[2]]}set position(w){var C;w&&o.bW(this._transform,3,[(C=w)[0],C[1],C[2],1])}get orientation(){return this._orientation}set orientation(w){this._orientation=w||o.bL([]),w&&Eg(this._transform,this._orientation)}getPitchBearing(){const w=this.forward(),C=this.right();return{bearing:Math.atan2(-C[1],C[0]),pitch:Math.atan2(Math.sqrt(w[0]*w[0]+w[1]*w[1]),-w[2])}}setPitchBearing(w,C){this._orientation=gx(w,C),Eg(this._transform,this._orientation)}forward(){const w=o.bO(this._transform,2);return[-w[0],-w[1],-w[2]]}up(){const w=o.bO(this._transform,1);return[-w[0],-w[1],-w[2]]}right(){const w=o.bO(this._transform,0);return[w[0],w[1],w[2]]}getCameraToWorld(w,C){const O=new Float64Array(16);return o.b7(O,this.getWorldToCamera(w,C)),O}getCameraToWorldMercator(){return this._transform}getWorldToCameraPosition(w,C,O){const U=this.position;o.bJ(U,U,-w);const Y=new Float64Array(16);return o.bP(Y,[O,O,O]),o.bx(Y,Y,U),Y[10]*=C,Y}getWorldToCamera(w,C){const O=new Float64Array(16),U=new Float64Array(4),Y=this.position;return o.bQ(U,this._orientation),o.bJ(Y,Y,-w),o.bR(O,U),o.bx(O,O,Y),O[1]*=-1,O[5]*=-1,O[9]*=-1,O[13]*=-1,O[8]*=C,O[9]*=C,O[10]*=C,O[11]*=C,O}getCameraToClipPerspective(w,C,O,U){const Y=new Float64Array(16);return o.bS(Y,w,C,O,U),Y}getCameraToClipOrthographic(w,C,O,U,Y,Z){const se=new Float64Array(16);return o.bT(se,w,C,O,U,Y,Z),se}getDistanceToElevation(w,C=!1){const O=w===0?0:o.bU(w,C?o.bV(this.position[1]):this.position[1]),U=this.forward();return(O-this.position[2])/U[2]}clone(){return new kf([...this.position],[...this.orientation])}}const Lc=(D,w)=>({u_matrix:D,u_ground_shadow_factor:w});class tp{constructor(w=0,C=0,O=0,U=0){if(isNaN(w)||w<0||isNaN(C)||C<0||isNaN(O)||O<0||isNaN(U)||U<0)throw new Error("Invalid value for edge-insets, top, bottom, left and right must all be numbers");this.top=w,this.bottom=C,this.left=O,this.right=U}interpolate(w,C,O){return C.top!=null&&w.top!=null&&(this.top=o.am(w.top,C.top,O)),C.bottom!=null&&w.bottom!=null&&(this.bottom=o.am(w.bottom,C.bottom,O)),C.left!=null&&w.left!=null&&(this.left=o.am(w.left,C.left,O)),C.right!=null&&w.right!=null&&(this.right=o.am(w.right,C.right,O)),this}getCenter(w,C){const O=o.aC((this.left+w-this.right)/2,0,w),U=o.aC((this.top+C-this.bottom)/2,0,C);return new o.P(O,U)}equals(w){return this.top===w.top&&this.bottom===w.bottom&&this.left===w.left&&this.right===w.right}clone(){return new tp(this.top,this.bottom,this.left,this.right)}toJSON(){return{top:this.top,bottom:this.bottom,left:this.left,right:this.right}}}const ih=15;class uu{constructor(w,C,O,U,Y,Z,se){this.tileSize=512,this._renderWorldCopies=Y===void 0||Y,this._minZoom=w||0,this._maxZoom=C||22,this._minPitch=O??0,this._maxPitch=U??60,this.setProjection(Z),this.setMaxBounds(se),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 tp,this._projMatrixCache={},this._alignedProjMatrixCache={},this._fogTileMatrixCache={},this._expandedProjMatrixCache={},this._distanceTileDataCache={},this._camera=new kf,this._centerAltitude=0,this._averageElevation=0,this.cameraElevationReference="ground",this._pixelsPerMercatorPixel=1,this.globeRadius=0,this.globeCenterInViewSpace=[0,0,0],this._tileCoverLift=0,this.freezeTileCoverage=!1,this._horizonShift=.1,this._orthographicProjectionAtLowPitch=!1,this._allowWorldUnderZoom=!1}clone(){const w=new uu(this._minZoom,this._maxZoom,this._minPitch,this.maxPitch,this._renderWorldCopies,this.getProjection(),this.maxBounds);return w._elevation=this._elevation,w._centerAltitude=this._centerAltitude,w._centerAltitudeValidForExaggeration=this._centerAltitudeValidForExaggeration,w.tileSize=this.tileSize,w.mercatorFromTransition=this.mercatorFromTransition,w.width=this.width,w.height=this.height,w.cameraElevationReference=this.cameraElevationReference,w._center=this._center,w._setZoom(this.zoom),w._seaLevelZoom=this._seaLevelZoom,w.angle=this.angle,w._fov=this._fov,w._pitch=this._pitch,w._nearZ=this._nearZ,w._farZ=this._farZ,w._nearClipOffset=this._nearClipOffset,w._averageElevation=this._averageElevation,w._orthographicProjectionAtLowPitch=this._orthographicProjectionAtLowPitch,w._unmodified=this._unmodified,w._edgeInsets=this._edgeInsets.clone(),w._camera=this._camera.clone(),w._calcMatrices(),w.freezeTileCoverage=this.freezeTileCoverage,w.frustumCorners=this.frustumCorners,w._allowWorldUnderZoom=this._allowWorldUnderZoom,w}get isOrthographic(){return this.projection.name!=="globe"&&this._orthographicProjectionAtLowPitch&&this.pitch0&&this.elevation.exaggeration()>0&&this._centerAltitudeValidForExaggeration;if(!this._elevation||w===Number.NEGATIVE_INFINITY&&(!C||!this._centerAltitude))return this._centerAltitude=0,this._seaLevelZoom=null,void(this._centerAltitudeValidForExaggeration=void 0);const O=this._elevation;C||this._centerAltitude&&this._centerAltitudeValidForExaggeration&&O.exaggeration()&&this._centerAltitudeValidForExaggeration!==O.exaggeration()?(this._centerAltitude=this._centerAltitude/this._centerAltitudeValidForExaggeration*O.exaggeration(),this._centerAltitudeValidForExaggeration=O.exaggeration()):(this._centerAltitude=w||0,this._centerAltitudeValidForExaggeration=O.exaggeration()),this._updateSeaLevelZoom()}_updateSeaLevelZoom(){if(this._centerAltitudeValidForExaggeration===void 0)return;const w=Math.max(0,(this.pixelsPerMeter*this._centerAltitude+this.cameraToCenterDistance)/this.worldSize);this._seaLevelZoom=this._zoomFromMercatorZ(w)}sampleAverageElevation(){if(!this._elevation)return 0;const w=this._elevation,C=[[.5,.2],[.3,.5],[.5,.5],[.7,.5],[.5,.8]],O=this.horizonLineFromTop();let U=0,Y=0;for(let Z=0;Z{const bt=o.ck(qe,He,et,ct,ot);pe.has(bt)||(Y.push(new o.aR(He,qe,et,ct,ot)),pe.add(bt))};for(let He=0;Heqe.canonical.z)continue;const et=qe.canonical,ct=qe.overscaledZ,ot=qe.wrap,bt=1<0,Ft=et.y+10,ys=qe.wrap-(Pt?0:1),Qt=qe.wrap+(vt?0:1),gs=Pt?et.x-1:bt-1,$t=vt?et.x+1:0;if(Z)O[0]<0?(je(ct,Qt,et.z,$t,et.y),O[1]<0&&Ft&&(je(ct,ot,et.z,et.x,et.y+1),je(ct,Qt,et.z,$t,et.y+1)),O[1]>0&&jt&&(je(ct,ot,et.z,et.x,et.y-1),je(ct,Qt,et.z,$t,et.y-1))):O[0]>0?(je(ct,ys,et.z,gs,et.y),O[1]<0&&Ft&&(je(ct,ot,et.z,et.x,et.y+1),je(ct,ys,et.z,gs,et.y+1)),O[1]>0&&jt&&(je(ct,ot,et.z,et.x,et.y-1),je(ct,ys,et.z,gs,et.y-1))):O[1]<0&&Ft?je(ct,ot,et.z,et.x,et.y+1):jt&&je(ct,ot,et.z,et.x,et.y-1);else{const Zt=qe.visibleQuadrants;1&Zt&&(je(ct,ys,et.z,gs,et.y),jt&&(je(ct,ot,et.z,et.x,et.y-1),je(ct,ys,et.z,gs,et.y-1))),2&Zt&&(je(ct,Qt,et.z,$t,et.y),jt&&(je(ct,ot,et.z,et.x,et.y-1),je(ct,Qt,et.z,$t,et.y-1))),4&Zt&&(je(ct,ys,et.z,gs,et.y),Ft&&(je(ct,ot,et.z,et.x,et.y+1),je(ct,ys,et.z,gs,et.y+1))),8&Zt&&(je(ct,Qt,et.z,$t,et.y),Ft&&(je(ct,ot,et.z,et.x,et.y+1),je(ct,Qt,et.z,$t,et.y+1)))}}const Ee=[];for(const He of Y)Y.some(qe=>He.isChildOf(qe))||Ee.push(He);if(Y=Ee.filter(He=>!w.some(qe=>!!(He.overscaledZ{const vt=bt.canonical.x+.5-et[0],Pt=bt.canonical.y+.5-et[1];return vt*vt+Pt*Pt{const gs=o.ck(Ft,Pt,jt,ys,Qt);Y.has(gs)||(U.push(new o.aR(Pt,Ft,jt,ys,Qt)),Y.add(gs))},se=w.reduce((Pt,Ft)=>Math.max(Pt,Ft.overscaledZ),O),pe=1<{const jt=Math.floor(Pt[0]),ys=Math.floor(Pt[1]),Qt=(Pt[0]-jt)*o.an,gs=(Pt[1]-ys)*o.an,$t=Math.floor(Ft[0]),Zt=Math.floor(Ft[1]),hs=(Ft[0]-$t)*o.an,Us=(Ft[1]-Zt)*o.an;for(let Cs=-1;Cs<=1;Cs++){const hn=jt+Cs;if(!(hn<0||hn>=pe)){Ee.x=Qt-Cs*o.an,He.x=hs-(hn-$t)*o.an;for(let an=-1;an<=1;an++){const An=ys+an;Ee.y=gs-an*o.an,He.y=Us-(An-Zt)*o.an,o.cI(Ee,He,je)&&Z(se,0,O,hn,An)}}}},et=C.points,ct=et[o.c9],ot=et[o.ca],bt=this._projectToGround(ct,et[o.cb]),vt=this._projectToGround(ot,et[o.cc]);return qe(ct,bt),qe(ot,vt),U}_projectToGround(w,C){return o.cd(o.ce(),w,C,w[2]/(w[2]-C[2]))}_projectToZ(w,C,O){const U=w[2]-C[2];return Math.abs(U)<1e-6?o.cf(w):o.cd(o.ce(),w,C,(w[2]-O)/U)}extendTileCoverForTunnels(w,C,O,U){if(O<18)return[];const Y=C.points,Z=Y[o.cg],se=Y[o.ch],pe=Y[o.ci],je=Y[o.cj];if(pe[2]>=0&&je[2]>=0||Z[2]<=0||se[2]<=0)return[];const Ee=pe[2]<0?this._projectToZ(Z,pe,0):pe,He=je[2]<0?this._projectToZ(se,je,0):je,qe=-U,et=pe[2]3&&(ot.length=3),ot}_findExtensionTilesInQuad(w,C,O,U){const Y=[],Z=new Set;for(const $t of w)Z.add($t.key);const se=w.reduce(($t,Zt)=>Math.max($t,Zt.overscaledZ),C),pe=1<{const hs=$t.canonical.x+.5-Qt,Us=$t.canonical.y+.5-gs,Cs=Zt.canonical.x+.5-Qt,hn=Zt.canonical.y+.5-gs;return hs*hs+Us*Us-(Cs*Cs+hn*hn)||$t.canonical.x-Zt.canonical.x||$t.canonical.y-Zt.canonical.y}),Y}coveringTiles(w){let C=this.coveringZoomLevel(w);const O=C,U=this.elevation&&this.elevation.exaggeration(),Y=U&&!w.isTerrainDEM,Z=this.projection.name==="mercator";if(w.minzoom!==void 0&&Cw.maxzoom&&(C=w.maxzoom);const se=this.locationCoordinate(this.center),pe=this.center.lat,je=1<{const pn=new o.ag(Es.x+25e-6,Es.y,Es.z),vn=new o.ag(Es.x,Es.y+25e-6,Es.z),fr=Es.toLngLat(),nr=pn.toLngLat(),rr=vn.toLngLat(),In=this.locationCoordinate(fr),Yr=this.locationCoordinate(nr),fa=this.locationCoordinate(rr),Fr=Math.hypot(Yr.x-In.x,Yr.y-In.y),Vr=Math.hypot(fa.x-In.x,fa.y-In.y);return Math.sqrt(Fr*Vr)*gs/25e-6},Zt=Es=>{const cn=ys,pn=Qt;return{aabb:o.cp(this,je,0,0,0,Es,pn,cn,this.projection),zoom:0,x:0,y:0,minZ:pn,maxZ:cn,wrap:Es,fullyVisible:!1}},hs=[];let Us=[];const Cs=C,hn=w.reparseOverscaled?O:C,an=(bt-this._centerAltitude)*ot,An=Es=>{if(!this._elevation||!Es.tileID||!Z)return;const cn=this._elevation.getMinMaxForTile(Es.tileID),pn=Es.aabb;cn?(pn.min[2]=cn.min,pn.max[2]=cn.max,pn.center[2]=(pn.min[2]+pn.max[2])/2):(Es.shouldSplit=Ks(Es),Es.shouldSplit||(pn.min[2]=pn.max[2]=pn.center[2]=this._centerAltitude))},On=(Es,cn)=>{if(.707*cn{if(Es.zoom=.9)return!0}else if(Y&&(vn=Es.aabb.distanceZ(vt)*ot),this.projection.isReprojectedInTileSpace&&O<=5){const Vr=Math.pow(2,Es.zoom),$a=$t(new o.ag((Es.x+.5)/Vr,(Es.y+.5)/Vr));fr=$a>.85?1:$a}if(!Z&&!He){const Vr=Math.sqrt(cn*cn+pn*pn+vn*vn);let $a=(1<0;){const Es=hs.pop(),cn=Es.x,pn=Es.y;let vn=Es.fullyVisible;const fr=()=>this.projection.name==="globe"&&(Es.y===0||Es.y===(1<nr)continue;let rr=0;if(!vn){let Fr=Pt?Es.aabb.intersectsPrecise(et):Es.aabb.intersectsPreciseFlat(et);if(Fr===0&&fr()){const Vr=new o.cn(Es.zoom,cn,pn);Fr=o.co(this,je,Vr,!0).intersectsPrecise(et)}if(Fr===0)continue;if(w.calculateQuadrantVisibility)if(et.containsPoint(Es.aabb.center))rr=15;else for(let Vr=0;Vr<4;Vr++)Es.aabb.quadrant(Vr).intersects(et)!==0&&(rr|=1<>1),Yr={aabb:Z?Es.aabb.quadrant(nr):o.cp(this,je,Es.zoom+1,rr,In,Es.wrap,Es.minZ,Es.maxZ,this.projection),zoom:Es.zoom+1,x:rr,y:In,wrap:Es.wrap,fullyVisible:vn,tileID:void 0,shouldSplit:void 0,minZ:Es.minZ,maxZ:Es.maxZ};Y&&!He&&(Yr.tileID=new o.aR(Es.zoom+1===Cs?hn:Es.zoom+1,Es.wrap,Es.zoom+1,rr,In),An(Yr)),hs.push(Yr)}}if(this.fogCullDistSq){const Es=this.fogCullDistSq,cn=this.horizonLineFromTop();Us=Us.filter(pn=>{const vn=[0,0,0,1],fr=[o.an,o.an,0,1],nr=this.calculateFogTileMatrix(pn.tileID.toUnwrapped());o.aE(vn,vn,nr),o.aE(fr,fr,nr);const rr=o.cq([],vn,fr),In=o.cr([],vn,fr),Yr=o.cK(rr,In);if(Yr===0)return!0;let fa=!1;const Fr=this._elevation;if(Fr&&Yr>Es&&cn!==0){const Vr=this.calculateProjMatrix(pn.tileID.toUnwrapped());let $a;w.isTerrainDEM||($a=Fr.getMinMaxForTile(pn.tileID)),$a||($a={min:Qt,max:ys});const ri=o.cs(this.rotation),ei=[ri[0]*o.an,ri[1]*o.an,$a.max];o.ah(ei,ei,Vr),fa=(1-ei[1])*this.height*.5Es.distanceSq-cn.distanceSq).map(Es=>Es.tileID)}resize(w,C){this.width=w,this.height=C,this.pixelsToGLUnits=[2/w,-2/C],this._constrain(),this._calcMatrices()}get unmodified(){return this._unmodified}zoomScale(w){return Math.pow(2,w)}scaleZoom(w){return Math.log2(w)}project(w){const C=o.aC(w.lat,-o.ct,o.ct),O=this.projection.project(w.lng,C);return new o.P(O.x*this.worldSize,O.y*this.worldSize)}unproject(w){return this.projection.unproject(w.x/this.worldSize,w.y/this.worldSize)}get point(){return this.project(this.center)}get pointMerc(){return this.point._div(this.worldSize)}get pixelsPerMeterRatio(){return this.pixelsPerMeter/o.bU(1,this.center.lat)/this.worldSize}setLocationAtPoint(w,C){let O,U;const Y=this.centerPoint;if(this.projection.name==="globe"){const se=this.worldSize;O=(C.x-Y.x)/se,U=(C.y-Y.y)/se}else{const se=this.pointCoordinate(C),pe=this.pointCoordinate(Y);O=se.x-pe.x,U=se.y-pe.y}const Z=this.locationCoordinate(w);this.setLocation(new o.ag(Z.x-O,Z.y-U))}setLocation(w){this.center=this.coordinateLocation(w),this.projection.wrap&&(this.center=this.center.wrap())}locationPoint(w,C){return this.projection.locationPoint(this,w,C)}locationPoint3D(w,C){return this.projection.locationPoint(this,w,C,!0)}pointLocation(w){return this.coordinateLocation(this.pointCoordinate(w))}pointLocation3D(w,C){return this.coordinateLocation(this.pointCoordinate3D(w,C))}locationCoordinate(w,C){const O=C?o.bU(C,w.lat):void 0,U=this.projection.project(w.lng,w.lat);return new o.ag(U.x,U.y,O)}coordinateLocation(w){return this.projection.unproject(w.x,w.y)}pointRayIntersection(w,C){const O=C??this._centerAltitude,U=[w.x,w.y,0,1],Y=[w.x,w.y,1,1];o.aE(U,U,this.pixelMatrixInverse),o.aE(Y,Y,this.pixelMatrixInverse);const Z=Y[3];o.cu(U,U,1/U[3]),o.cu(Y,Y,1/Z);const se=U[2],pe=Y[2];return{p0:U,p1:Y,t:se===pe?0:(O-se)/(pe-se)}}screenPointToMercatorRay(w){const C=[w.x,w.y,0,1],O=[w.x,w.y,1,1];return o.aE(C,C,this.pixelMatrixInverse),o.aE(O,O,this.pixelMatrixInverse),o.cu(C,C,1/C[3]),o.cu(O,O,1/O[3]),C[2]=o.bU(C[2],this._center.lat)*this.worldSize,O[2]=o.bU(O[2],this._center.lat)*this.worldSize,o.cu(C,C,1/this.worldSize),o.cu(O,O,1/this.worldSize),new o.az([C[0],C[1],C[2]],o.ay([],o.ax([],O,C)))}rayIntersectionCoordinate(w){const{p0:C,p1:O,t:U}=w,Y=o.bU(C[2],this._center.lat),Z=o.bU(O[2],this._center.lat);return new o.ag(o.am(C[0],O[0],U)/this.worldSize,o.am(C[1],O[1],U)/this.worldSize,o.am(Y,Z,U))}pointCoordinate(w,C=this._centerAltitude){return this.projection.pointCoordinate(this,w.x,w.y,C)}pointCoordinate3D(w,C){if(!this.elevation)return this.pointCoordinate(w,C);let O=this.projection.pointCoordinate3D(this,w.x,w.y);if(O)return new o.ag(O[0],O[1],O[2]);let U=0,Y=this.horizonLineFromTop();if(w.y>Y)return this.pointCoordinate(w,C);const Z=.02*Y,se=w.clone();for(let pe=0;pe<10&&Y-U>Z;pe++){se.y=o.am(U,Y,.66);const je=this.projection.pointCoordinate3D(this,se.x,se.y);je?(Y=se.y,O=je):U=se.y}return O?new o.ag(O[0],O[1],O[2]):this.pointCoordinate(w)}isPointAboveHorizon(w){return this.projection.isPointAboveHorizon(this,w)}isPointOnSurface(w){if(w.y<0||w.y>this.height||w.x<0||w.x>this.width)return!1;if(this.elevation||this.zoom>=o.cv)return!this.isPointAboveHorizon(w);const C=this.pointCoordinate(w);return C.y>=0&&C.y<=1}_coordinatePoint(w,C){const O=C&&this.elevation?this.elevation.getAtPointOrZero(w,this._centerAltitude):this._centerAltitude,U=[w.x*this.worldSize,w.y*this.worldSize,O+w.toAltitude(),1];return o.aE(U,U,this.pixelMatrix),U[3]>0?new o.P(U[0]/U[3],U[1]/U[3]):new o.P(Number.MAX_VALUE,Number.MAX_VALUE)}_getBoundsNonRectangular(){const{top:w,left:C}=this._edgeInsets,O=this.height-this._edgeInsets.bottom,U=this.width-this._edgeInsets.right,Y=this.pointLocation3D(new o.P(C,w)),Z=this.pointLocation3D(new o.P(U,w)),se=this.pointLocation3D(new o.P(U,O)),pe=this.pointLocation3D(new o.P(C,O));let je=Math.min(Y.lng,Z.lng,se.lng,pe.lng),Ee=Math.max(Y.lng,Z.lng,se.lng,pe.lng),He=Math.min(Y.lat,Z.lat,se.lat,pe.lat),qe=Math.max(Y.lat,Z.lat,se.lat,pe.lat);const et=Math.pow(2,-this.zoom)/16*270,ct=this.projection.name==="globe"?1:4,ot=(bt,vt,Pt,Ft,jt)=>{const ys=(bt+Pt)/2,Qt=(vt+Ft)/2,gs=new o.P(ys,Qt),{lng:$t,lat:Zt}=this.pointLocation3D(gs),hs=Math.max(0,je-$t,He-Zt,$t-Ee,Zt-qe);je=Math.min(je,$t),Ee=Math.max(Ee,$t),He=Math.min(He,Zt),qe=Math.max(qe,Zt),(jtet)&&(ot(bt,vt,ys,Qt,jt+1),ot(ys,Qt,Pt,Ft,jt+1))};if(ot(C,w,U,w,1),ot(U,w,U,O,1),ot(U,O,C,O,1),ot(C,O,C,w,1),this.projection.name==="globe"){const[bt,vt]=o.cw(this);bt?(qe=90,Ee=180,je=-180):vt&&(He=-90,Ee=180,je=-180)}return new o.aK(new o.aU(je,He),new o.aU(Ee,qe))}_getBoundsRectangular(w,C){const{top:O,left:U}=this._edgeInsets,Y=this.height-this._edgeInsets.bottom,Z=this.width-this._edgeInsets.right,se=new o.P(U,O),pe=new o.P(Z,O),je=new o.P(Z,Y),Ee=new o.P(U,Y);let He=this.pointCoordinate(se,w),qe=this.pointCoordinate(pe,w);const et=this.pointCoordinate(je,C),ct=this.pointCoordinate(Ee,C),ot=(bt,vt)=>(vt.y-bt.y)/(vt.x-bt.x);return He.y>1&&qe.y>=0?He=new o.ag((1-ct.y)/ot(ct,He)+ct.x,1):He.y<0&&qe.y<=1&&(He=new o.ag(-ct.y/ot(ct,He)+ct.x,0)),qe.y>1&&He.y>=0?qe=new o.ag((1-et.y)/ot(et,qe)+et.x,1):qe.y<0&&He.y<=1&&(qe=new o.ag(-et.y/ot(et,qe)+et.x,0)),new o.aK().extend(this.coordinateLocation(He)).extend(this.coordinateLocation(qe)).extend(this.coordinateLocation(ct)).extend(this.coordinateLocation(et))}_getBoundsRectangularTerrain(){const w=this.elevation;if(!w.visibleDemTiles.length||w.isUsingMockSource())return this._getBoundsRectangular(0,0);const C=w.visibleDemTiles.reduce((O,U)=>{if(U.dem){const Y=U.dem.tree;O.min=Math.min(O.min,Y.minimums[0]),O.max=Math.max(O.max,Y.maximums[0])}return O},{min:Number.MAX_VALUE,max:0});return this._getBoundsRectangular(C.min*w.exaggeration(),C.max*w.exaggeration())}getBounds(){return this.projection.name==="mercator"||this.projection.name==="equirectangular"?this._terrainEnabled()?this._getBoundsRectangularTerrain():this._getBoundsRectangular(0,0):this._getBoundsNonRectangular()}horizonLineFromTop(w=!0){const C=this.height/2/Math.tan(this._fov/2)/Math.tan(Math.max(this._pitch,.1))-this.centerOffset.y,O=this.height/2-C*(1-this._horizonShift);return w?Math.max(0,O):O}getMaxBounds(){return this.maxBounds}setMaxBounds(w){this.maxBounds=w,this.minLat=-o.ct,this.maxLat=o.ct,this.minLng=-180,this.maxLng=180,w&&(this.minLat=w.getSouth(),this.maxLat=w.getNorth(),this.minLng=w.getWest(),this.maxLng=w.getEast(),this.maxLngHe&&(se=He-je),He-Eeet&&(Z=et-pe),et-qe{for(let Ks=0;Ks<16;Ks++)hn[Ks]=o.am(an[Ks],An[Ks],On)})(se,se,pe,o.cL(this.pitch>=ih?1:this.pitch/ih))}else se=pe;const je=o.cz([],pe,Z);let Ee=o.cz([],se,Z);if(this.projection.isReprojectedInTileSpace){const Zt=this.locationCoordinate(this.center),hs=o.b9([]);o.bx(hs,hs,[Zt.x*this.worldSize,Zt.y*this.worldSize,0]),o.aD(hs,hs,o.cA(this)),o.bx(hs,hs,[-Zt.x*this.worldSize,-Zt.y*this.worldSize,0]),o.aD(Ee,Ee,hs),o.aD(je,je,hs),this.inverseAdjustmentMatrix=o.cB(this)}else this.inverseAdjustmentMatrix=[1,0,0,1];if(this.mercatorMatrix=o.cC([],Ee,[this.worldSize,this.worldSize,this.worldSize/Y,1]),this.projMatrix=Ee,this.invProjMatrix=o.b7(new Float64Array(16),this.projMatrix),C){const Zt=this._camera.getCameraToClipPerspective(this._fov,this.width/this.height,this._nearZ,1/0);Zt[8]=2*-w.x/this.width,Zt[9]=2*w.y/this.height,this.expandedFarZProjMatrix=o.cz([],Zt,Z)}else this.expandedFarZProjMatrix=this.projMatrix;const He=o.b7([],se);this.frustumCorners=o.cD.fromInvProjectionMatrix(He,this.horizonLineFromTop(),this.height),this.cameraFrustum=o.cl.fromInvProjectionMatrix(this.invProjMatrix,this.worldSize,0,!C);const qe=new Float32Array(16);o.b9(qe),o.cC(qe,qe,[1,-1,1]),o.cE(qe,qe,this._pitch),o.ba(qe,qe,this.angle);const et=o.bS(new Float32Array(16),this._fov,this.width/this.height,this._nearZ,this._farZ);this.starsProjMatrix=o.b8(et);const ct=(Math.PI/2-this._pitch)*(this.height/this._fov)*this._horizonShift;et[8]=2*-w.x/this.width,et[9]=2*(w.y+ct)/this.height,this.skyboxMatrix=o.aD(qe,et,qe);const ot=this.point,bt=ot.x,vt=ot.y,Pt=this.width%2/2,Ft=this.height%2/2,jt=Math.cos(this.angle),ys=Math.sin(this.angle),Qt=bt-Math.round(bt)+jt*Pt+ys*Ft,gs=vt-Math.round(vt)+jt*Ft+ys*Pt,$t=new Float64Array(Ee);if(o.bx($t,$t,[Qt>.5?Qt-1:Qt,gs>.5?gs-1:gs,0]),this.alignedProjMatrix=$t,Ee=o.bb(),o.cC(Ee,Ee,[this.width/2,-this.height/2,1]),o.bx(Ee,Ee,[1,-1,0]),this.labelPlaneMatrix=Ee,Ee=o.bb(),o.cC(Ee,Ee,[1,-1,1]),o.bx(Ee,Ee,[-1,-1,0]),o.cC(Ee,Ee,[2/this.width,2/this.height,1]),this.glCoordMatrix=Ee,this.pixelMatrix=o.aD(new Float64Array(16),this.labelPlaneMatrix,je),this._calcFogMatrices(),this._distanceTileDataCache={},Ee=o.b7(new Float64Array(16),this.pixelMatrix),!Ee)throw new Error("failed to invert matrix");if(this.pixelMatrixInverse=Ee,this.projection.name==="globe"||this.mercatorFromTransition){this.globeMatrix=o.cF(this);const Zt=[this.globeMatrix[12],this.globeMatrix[13],this.globeMatrix[14]];this.globeCenterInViewSpace=o.ah(Zt,Zt,Z),this.globeRadius=this.worldSize/2/Math.PI-1}else this.globeMatrix=Ee;this._projMatrixCache={},this._alignedProjMatrixCache={},this._pixelsToTileUnitsCache={},this._expandedProjMatrixCache={}}_calcFogMatrices(){this._fogTileMatrixCache={};const w=this.cameraWorldSizeForFog,C=this.cameraPixelsPerMeter,O=this._camera.position,U=1/this.height/this._pixelsPerMercatorPixel,Y=[w,w,C];o.bJ(Y,Y,U),o.bJ(O,O,-1),o.cG(O,O,Y);const Z=o.bb();o.bx(Z,Z,O),o.cC(Z,Z,Y),this.mercatorFogMatrix=Z,this.worldToFogMatrix=this._camera.getWorldToCameraPosition(w,C,U)}_computeCameraPosition(w){const C=(w=w||this.pixelsPerMeter)/this.pixelsPerMeter,O=this._camera.forward(),U=this.point,Y=this._mercatorZfromZoom(this._seaLevelZoom?this._seaLevelZoom:this._zoom)*C-w/this.worldSize*this._centerAltitude;return[U.x/this.worldSize-O[0]*Y,U.y/this.worldSize-O[1]*Y,w/this.worldSize*this._centerAltitude-O[2]*Y]}_updateCameraState(){this.height&&(this._camera.setPitchBearing(this._pitch,this.angle),this._camera.position=this._computeCameraPosition())}_translateCameraConstrained(w){const C=this._maxCameraBoundsDistance()*Math.cos(this._pitch),O=this._camera.position[2],U=w[2];let Y=1;this.projection.wrap&&(this.center=this.center.wrap()),U>0&&(Y=Math.min((C-O)/U,1)),this._camera.position=o.bg([],this._camera.position,w,Y),this._updateStateFromCamera()}_updateStateFromCamera(){const w=this._camera.position,C=this._camera.forward(),{pitch:O,bearing:U}=this._camera.getPitchBearing(),Y=o.bU(this._centerAltitude,this.center.lat)*this._pixelsPerMercatorPixel,Z=this._mercatorZfromZoom(this._maxZoom)*Math.cos(o.ap(this._maxPitch)),se=Math.max((w[2]-Y)/Math.cos(O),Z),pe=this._zoomFromMercatorZ(se);o.bg(w,w,C,se),this._pitch=o.aC(O,o.ap(this.minPitch),o.ap(this.maxPitch)),this.angle=o.bs(U,-Math.PI,Math.PI),this._setZoom(o.aC(pe,this._minZoom,this._maxZoom)),this._updateSeaLevelZoom(),this._center=this.coordinateLocation(new o.ag(w[0],w[1],w[2])),this._unmodified=!1,this._constrain(),this._calcMatrices()}_worldSizeFromZoom(w){return Math.pow(2,w)*this.tileSize}_mercatorZfromZoom(w){return this.cameraToCenterDistance/this._worldSizeFromZoom(w)}_minimumHeightOverTerrain(){const w=Math.min(this._seaLevelZoom!=null?this._seaLevelZoom:this._zoom,this._maxZoom)+4;return this._mercatorZfromZoom(w)}_zoomFromMercatorZ(w){return this.scaleZoom(this.cameraToCenterDistance/(Math.max(0,w)*this.tileSize))}zoomFromMercatorZAdjusted(w){let C=0,O=o.cv,U=0,Y=1/0;for(;O-C>1e-6&&O>C;){const Z=C+.5*(O-C),se=this.tileSize*Math.pow(2,Z),pe=this.getCameraToCenterDistance(this.projection,Z,se),je=this.scaleZoom(pe/(Math.max(0,w)*this.tileSize)),Ee=Math.abs(Z-je);Eeje||qe.y>1)return!0}return!1}isHorizonVisible(){return this.pitch+o.cH(this.fovAboveCenter)>88||this.anyCornerOffEdge(new o.P(0,0),new o.P(this.width,this.height))}zoomDeltaToMovement(w,C){const O=o.ai(o.ax([],this._camera.position,w)),U=this._zoomFromMercatorZ(O)+C;return O-this._mercatorZfromZoom(U)}getCameraPoint(){if(this.projection.name==="globe"){const w=function([C,O,U],Y){const Z=[C,O,U,1];o.aE(Z,Z,Y);const se=Z[3]=Math.max(Z[3],1e-6);return Z[0]/=se,Z[1]/=se,Z[2]/=se,Z}([this.globeMatrix[12],this.globeMatrix[13],this.globeMatrix[14]],this.pixelMatrix);return new o.P(w[0],w[1])}{const w=Math.tan(this._pitch)*(this.cameraToCenterDistance||1);return this.centerPoint.add(new o.P(0,w))}}getCameraToCenterDistance(w,C=this.zoom,O=this.worldSize){const U=o.cy(w,C,this.width,this.height,1024),Y=w.pixelSpaceConversion(this.center.lat,O,U);let Z=.5/Math.tan(.5*this._fov)*this.height*Y;return this.isOrthographic&&(Z=o.am(1,Z,o.cL(this.pitch>=ih?1:this.pitch/ih))),Z}getWorldToCameraMatrix(){const w=this._camera.getWorldToCamera(this.worldSize,this.projection.zAxisUnit==="meters"?this.pixelsPerMeter:1);return this.projection.name==="globe"&&o.aD(w,w,this.globeMatrix),w}getFrustum(w){return o.cl.fromInvProjectionMatrix(this.invProjMatrix,this.worldSize,w,this.projection.zAxisUnit==="meters")}}const qc=(D,w)=>{if(w>0&&D.terrain&&o.w("Cutoff is currently disabled on terrain"),w<=0||D.terrain)return{shouldRenderCutoff:!1,uniformValues:{u_cutoff_params:[0,0,0,1]}};const C=D.transform,O=C.pitch,U=C.isLODDisabled(!1)?60:30;if(O0,uniformValues:{u_cutoff_params:[C._nearZ,C._farZ,(Ee-C._nearZ)/Y,(Ee-qe-C._nearZ)/Y]}}},sp=2048;class ev{constructor(w,C){this.aabb=w,this.lastCascade=C}}class tv{add(w,C){const O=this.receivers[w.key];O!==void 0?(O.aabb.min[0]=Math.min(O.aabb.min[0],C.min[0]),O.aabb.min[1]=Math.min(O.aabb.min[1],C.min[1]),O.aabb.min[2]=Math.min(O.aabb.min[2],C.min[2]),O.aabb.max[0]=Math.max(O.aabb.max[0],C.max[0]),O.aabb.max[1]=Math.max(O.aabb.max[1],C.max[1]),O.aabb.max[2]=Math.max(O.aabb.max[2],C.max[2])):this.receivers[w.key]=new ev(C,null)}clear(){this.receivers={}}get(w){return this.receivers[w.key]}computeRequiredCascades(w,C,O){const U=o.cU.fromPoints(w.points);let Y=0;for(const Z in this.receivers){const se=this.receivers[Z];if(!se||!U.intersectsAabb(se.aabb))continue;se.aabb.min=U.closestPoint(se.aabb.min),se.aabb.max=U.closestPoint(se.aabb.max);const pe=se.aabb.getCorners();for(let je=0;je1||qe[1]<-1||qe[1]>1){Ee=!1;break}}if(se.lastCascade=je,Y=Math.max(Y,je),Ee)break}}return Y+1}}class yc{constructor(w){this.painter=w,this._enabled=!1,this._drawShadowAfterLayer=-1,this._numCascadesToRender=0,this._cascades=[],this._groundShadowTiles=[],this._receivers=new tv,this._depthMode=new Ir(w.context.gl.LEQUAL,Ir.ReadWrite,[0,1]),this._uniformValues={u_light_matrix_0:new Float32Array(16),u_light_matrix_1:new Float32Array(16),u_shadow_intensity:0,u_fade_range:[0,0],u_shadow_normal_offset:[1,1,1],u_shadow_texel_size:1,u_shadow_map_resolution:1,u_shadow_direction:[0,0,1],u_shadow_bias:[36e-5,.0012,.012],u_shadowmap_0:0,u_shadowmap_1:0},this._forceDisable=!1,this.useNormalOffset=!1}destroy(){for(const w of this._cascades)w.texture.destroy(),w.framebuffer.destroy();this._cascades=[]}updateShadowParameters(w,C){const O=this.painter;if(this._enabled=!1,this._drawShadowAfterLayer=-1,this._receivers.clear(),!C||!C.properties)return;const U=C.properties.get("shadow-intensity"),Y=C.properties.get("shadow-draw-before-layer");if(!C.shadowsEnabled()||U<=0)return;let Z=-1,se=0;for(const vt of O.style.order){const Pt=O.style._mergedLayers[vt];Pt.hasShadowPass()&&!Pt.isHidden(w.zoom)&&(Z=se),!Y||Y!==vt&&Y!==Pt.slot||(this._drawShadowAfterLayer=se>0?se-1:0),se+=1}if(this._enabled=Z>=0,!this.enabled)return;this._drawShadowAfterLayer<0&&(this._drawShadowAfterLayer=Z);const pe=O.context,je=sp,Ee=sp;if(this._cascades.length===0||sp!==this._cascades[0].texture.size[0]){this._cascades=[];for(let vt=0;vt<2;++vt){const Pt=pe.gl,Ft=pe.createFramebuffer(je,Ee,0,"texture"),jt=new o.T(pe,{width:je,height:Ee,data:null},Pt.DEPTH_COMPONENT16);Ft.depthAttachment.set(jt.texture),this._cascades.push({framebuffer:Ft,texture:jt,matrix:[],far:0,boundingSphereRadius:0,frustum:new o.cl,scale:0})}}this.shadowDirection=o0(C);let He=0;if(w.elevation){const vt=w.elevation,Pt=[1e4,-1e4];vt.visibleDemTiles.filter(Ft=>Ft.dem).forEach(Ft=>{const jt=Ft.dem.tree;Pt[0]=Math.min(Pt[0],jt.minimums[0]),Pt[1]=Math.max(Pt[1],jt.maximums[0])}),Pt[0]!==1e4&&(He=(Pt[1]-Pt[0])*vt.exaggeration())}const qe=1.5*w.cameraToCenterDistance,et=3*qe,ct=new Float64Array(16);for(let vt=0;vt=0)return{};const Y=function(pe,je,Ee){const He=Ee/(1<0&&(o.cT(Y[1],Y[1],[U[0]*Z,0,0]),o.cT(Y[2],Y[2],[U[0]*Z,0,0])),U[1]<0?(o.cT(Y[0],Y[0],[0,U[1]*Z,0]),o.cT(Y[1],Y[1],[0,U[1]*Z,0])):U[1]>0&&(o.cT(Y[2],Y[2],[0,U[1]*Z,0]),o.cT(Y[3],Y[3],[0,U[1]*Z,0]));const se={};return se.vertices=Y,se.planes=[Mg(Y[1],Y[0],Y[4]),Mg(Y[2],Y[1],Y[5]),Mg(Y[3],Y[2],Y[6]),Mg(Y[0],Y[3],Y[7])],se}addShadowReceiver(w,C,O){this._receivers.add(w,o.cU.fromTileIdAndHeight(w,C,O))}getMaxCascadeForTile(w){const C=this._receivers.get(w);return C&&C.lastCascade?C.lastCascade:0}}function Mg(D,w,C){const O=o.ax([],C,w),U=o.ax([],D,w),Y=o.bh([],O,U),Z=o.ai(Y);return Z===0?[0,0,1,0]:(o.bJ(Y,Y,1/Z),[Y[0],Y[1],Y[2],-o.bi(Y,w)])}function o0(D){const w=D.properties.get("direction"),C=o.cP(w.x,w.y,w.z);C[2]=o.aC(C[2],0,75);const O=o.cR([C[0],C[1],C[2]]);return o.cQ(O.x,O.y,O.z)}function oh(D,w,C){const O=w.properties.get("color-use-theme")==="none",U=w.properties.get("color"),Y=w.properties.get("intensity"),Z=w.properties.get("direction"),se=[Z.x,Z.y,Z.z],pe=C.properties.get("color-use-theme")==="none",je=C.properties.get("color"),Ee=C.properties.get("intensity"),He=Math.max(o.bi([0,0,1],se),0),qe=[0,0,0];o.bJ(qe,je.toPremultipliedRenderColor(pe?null:D.getLut(w.scope)).toArray01Linear().slice(0,3),Ee);const et=[0,0,0];return o.bJ(et,U.toPremultipliedRenderColor(O?null:D.getLut(C.scope)).toArray01Linear().slice(0,3),He*Y),o.cW([qe[0]>0?qe[0]/(qe[0]+et[0]):0,qe[1]>0?qe[1]/(qe[1]+et[1]):0,qe[2]>0?qe[2]/(qe[2]+et[2]):0])}function Sf(D,w,C,O,U,Y){const Z=D.zoom,se=D.scale,pe=D.worldSize,je=1/pe,Ee=D.aspect,He=Math.sqrt(1+Ee*Ee)*Math.tan(.5*D.fovX),qe=He*He,et=O-C,ct=O+C;let ot,bt;qe>et/ct?(ot=O,bt=O*He):(ot=.5*ct*(1+qe),bt=.5*Math.sqrt(et*et+2*(O*O+C*C)*qe+ct*ct*qe*qe));const vt=D.projection.pixelsPerMeter(D.center.lat,pe),Pt=D._camera.getCameraToWorldMercator(),Ft=[0,0,-ot*je];o.ah(Ft,Ft,Pt);let jt=bt*je;const ys=function(vn){return vn[0]/=se,vn[1]/=se,vn[2]=o.bU(vn[2],D._center.lat),vn},Qt=D._edgeInsets;if(!(Qt.left===0&&Qt.top===0&&Qt.right===0&&Qt.bottom===0||Qt.left===Qt.right&&Qt.top===Qt.bottom)){const vn=D._camera.getWorldToCamera(D.worldSize,D.projection.zAxisUnit==="meters"?vt:1),fr=D._camera.getCameraToClipPerspective(D._fov,D.width/D.height,C,O);fr[8]=2*-D.centerOffset.x/D.width,fr[9]=2*D.centerOffset.y/D.height;const nr=new Float64Array(16);o.cz(nr,fr,vn);const rr=new Float64Array(16);o.b7(rr,nr);const In=o.cl.fromInvProjectionMatrix(rr,pe,Z,!0);for(const Yr of In.points){const fa=ys(Yr);jt=Math.max(jt,o.bK(o.cV([],Ft,fa)))}}jt*=U/(U-1);const gs=Math.acos(w[2]),$t=Math.atan2(-w[0],-w[1]),Zt=new kf;Zt.position=Ft,Zt.setPitchBearing(gs,$t);const hs=Zt.getWorldToCamera(pe,vt),Us=jt*pe,Cs=Math.min(D._mercatorZfromZoom(17)*pe*-2,-2*Us),hn=Zt.getCameraToClipOrthographic(-Us,Us,-Us,Us,Cs,(Us+Y*vt)/w[2]),an=new Float64Array(16);o.aD(an,hn,hs);const An=o.cQ(Math.floor(1e6*Ft[0])/1e6*pe,Math.floor(1e6*Ft[1])/1e6*pe,0),On=.5*U,Ks=[0,0,0];o.ah(Ks,An,an),o.bJ(Ks,Ks,On);const Es=[Math.floor(Ks[0]),Math.floor(Ks[1]),Math.floor(Ks[2])],cn=[0,0,0];o.ax(cn,Ks,Es),o.bJ(cn,cn,-1/On);const pn=new Float64Array(16);return o.b9(pn),o.bx(pn,pn,cn),o.aD(an,pn,an),[an,Us]}class d1 extends o.E{constructor(w){super(),this.requestManager=w,this.models={"":{}},this.modelUris={"":{}},this.modelByURL={},this.numModelsLoading={}}loadModel(w,C){return o.cX(this.requestManager.transformRequest(C,o.R.Model).url).then(O=>{const U=o.cY(O),Y=new o.cZ(w,C,void 0,void 0,U);return Y.computeBoundsAndApplyParent(),Y}).catch(O=>{if(O&&O.status===404)return null;this.fire(new o.B(new Error(`Could not load model ${w} from ${C}: ${O.message}`)))})}load(w,C,O={forceReload:!1}){this.models[C]||(this.models[C]={});const U=Object.keys(w),Y=[],Z=[];for(const se of U){const pe=w[se];this.hasURLBeenRequested(pe)&&!O.forceReload||(this.modelByURL[pe]={modelId:se,scope:C},Y.push(this.loadModel(se,pe)),Z.push(se)),this.models[C][se]||(this.models[C][se]={model:null,numReferences:1})}this.numModelsLoading[C]=(this.numModelsLoading[C]||0)+Z.length,Promise.allSettled(Y).then(se=>{for(let pe=0;pe{this.fire(new o.B(new Error(`Could not load models: ${se.message}`)))})}isLoaded(){for(const w in this.numModelsLoading)if(this.numModelsLoading[w]>0)return!1;return!0}hasModel(w,C,O={exactIdMatch:!1}){return!!(O.exactIdMatch?this.getModel(w,C):this.getModelByURL(this.modelUris[C][w]))}getModel(w,C){return this.models[C]||(this.models[C]={}),this.models[C][w]?this.models[C][w].model:void 0}getModelByURL(w){if(!w)return null;const C=this.modelByURL[w];return C?this.models[C.scope][C.modelId].model:null}hasModelBeenAdded(w,C){return this.models[C]&&this.models[C][w]!==void 0}getModelURIs(w){return this.modelUris[w]||{}}addModel(w,C,O){this.models[O]||(this.models[O]={}),this.modelUris[O]||(this.modelUris[O]={});const U=this.requestManager.normalizeModelURL(C);if((this.hasModel(w,O,{exactIdMatch:!0})||this.hasModelBeenAdded(w,O))&&this.modelUris[O][w]===U)this.models[O][w].numReferences++;else if(this.hasURLBeenRequested(U)){const{scope:Y,modelId:Z}=this.modelByURL[U];this.models[Y][Z].numReferences++}else this.modelUris[O][w]=U,this.load({[w]:this.modelUris[O][w]},O)}addModelURLs(w,C){this.models[C]||(this.models[C]={}),this.modelUris[C]||(this.modelUris[C]={});const O=this.modelUris[C];for(const U in w)O[U]=this.requestManager.normalizeModelURL(w[U])}reloadModels(w){this.load(this.modelUris[w],w,{forceReload:!0})}addModelsFromBucket(w,C){this.models[C]||(this.models[C]={}),this.modelUris[C]||(this.modelUris[C]={});const O={};for(const U of w)this.hasModel(U,C,{exactIdMatch:!0})||this.hasURLBeenRequested(U)?this.models[C][U].numReferences++:this.modelUris[C][U]&&!this.hasURLBeenRequested(U)?O[U]=this.modelUris[C][U]:!this.hasURLBeenRequested(U)&&o.c_(U,!1)&&(this.modelUris[C][U]=this.requestManager.normalizeModelURL(U),O[U]=this.modelUris[C][U]);this.load(O,C)}hasURLBeenRequested(w){return this.modelByURL[w]!==void 0}removeModel(w,C,O=!1,U=!1){if(this.models[C]&&this.models[C][w]&&(this.models[C][w].numReferences--,this.models[C][w].numReferences===0||U)){const Y=this.modelUris[C][w];O||delete this.modelUris[C][w],delete this.modelByURL[Y];const Z=this.models[C][w].model;if(!Z)return;delete this.models[C][w],Z.destroy()}}destroy(){for(const w of Object.keys(this.models))for(const C of Object.keys(this.models[w])){const O=this.models[w][C].model;delete this.models[w][C],O&&O.destroy()}this.models={"":{}},this.modelUris={"":{}},this.modelByURL={},this.numModelsLoading={}}listModels(w){return this.models[w]||(this.models[w]={}),Object.keys(this.models[w])}upload(w,C){this.models[C]||(this.models[C]={});for(const O in this.models[C])this.models[C][O].model&&this.models[C][O].model.upload(w.context)}}const hu=o.a8.colorTheme,Il=new o.ab({data:new o.ac(hu.data)});function Wo(D){if(!D.metadata||!D.metadata.content_area)return;const w=o.o.devicePixelRatio,{left:C,top:O,width:U,height:Y}=D.metadata.content_area,Z=C*w,se=O*w;return[Z,se,Z+U*w,se+Y*w]}function Oo(D){if(D)return D.map(([w,C])=>[w*o.o.devicePixelRatio,C*o.o.devicePixelRatio])}class Fd{constructor(w,C,O){this.id=w,this.scope=C,this.sourceCache=O,this.pendingRequests=new Set,this.missingRequests=new Set}addPendingRequest(w){this.missingRequests.has(w.name)||this.pendingRequests.has(w.name)||this.pendingRequests.add(w.name)}hasPendingRequests(){return this.pendingRequests.size>0}resolvePendingRequests(){const w=new Map;if(!this.sourceCache.loaded())return w;const C=this.sourceCache.getVisibleCoordinates();if(C.length===0)return w;const O=this.sourceCache.getSource();if(!(O instanceof Hm))return w;const U=C.map(Z=>this.sourceCache.getTile(Z)),Y=O.getImages(U,Array.from(this.pendingRequests));for(const[Z,se]of Y)w.set(o.I.from({name:Z,iconsetId:this.id}),se),this.pendingRequests.delete(Z);for(const Z of this.pendingRequests)this.missingRequests.add(Z);return this.pendingRequests.clear(),w}}class Vc{constructor(){this._previousClosestBuildingId=null,this._hysteresisRatio=.8,this._indoorMinimumZoom=16}findClosestBuilding(w,C,O,U,Y){if(Ope*this._hysteresisRatio&&(Z=this._previousClosestBuildingId):je&&!Z&&(Z=this._previousClosestBuildingId),this._previousClosestBuildingId=Z,Z}_calculateDistance(w,C){if(!C.center)return Number.MAX_VALUE;const O=w.lat-C.center[1],U=w.lng-C.center[0];return O*O+U*U}_isBuildingVisible(w,C,O){if(!O)return!1;for(const U of w.floorIds){const Y=w.floors[U];if(!Y.geometry)continue;const Z=Y.geometry;if(Z.type==="Polygon"){const se=this._convertRingToPoints(Z.coordinates[0]);if(o.bw(se,O))return!0}else if(Z.type==="MultiPolygon"){const se=this._convertMultiPolygonToPoints(Z.coordinates);if(o.d0(O,se))return!0}}return!1}_convertRingToPoints(w){return w.map(C=>new o.P(C[0],C[1]))}_convertMultiPolygonToPoints(w){return w.map(C=>C.length===0?[]:C[0].map(O=>new o.P(O[0],O[1])))}}class Lg extends o.E{constructor(w){super(),this._style=w,this._buildings={},this._activeFloors=new Set,this._closestBuildingId=null,this._indoorState={selectedFloorId:null,activeFloorsVisible:!0,activeFloors:this._activeFloors},this._buildingDetectionStrategy=new Vc,this._initialLoadDone=!1,o.aZ(["_updateUI"],this),this._style.on("style.load",()=>{this._style.isIndoorEnabled()&&(this._style.map.on("load",()=>{this._initialLoadDone=!0,this._indoorState&&this._indoorState.needsUpdate&&(this._indoorState.needsUpdate=!1,this._style.updateIndoorDependentLayers()),this._updateUI()}),this._style.map.on("move",this._updateUI),this._style.map.on("idle",this._updateUI))})}destroy(){this._buildings={},this._activeFloors=new Set,this._indoorState=null}selectFloor(w){w===this._selectedFloorId&&this._indoorState&&this._indoorState.activeFloorsVisible||(this._selectedFloorId=w,this._recalculateActiveFloors())}setActiveFloorsVisibility(w){this._updateActiveFloors(w),this._updateIndoorSelector()}setIndoorData(w){let C=!1;for(const[O,U]of Object.entries(w.buildings))if(this._buildings[O])for(const Y of U.floorIds)this._buildings[O].floorIds.add(Y),this._buildings[O].floors[Y]?this._mergeFloors(this._buildings[O].floors[Y],U.floors[Y]):(this._buildings[O].floors[Y]=U.floors[Y],C=!0);else this._buildings[O]=U,C=!0;C&&this._recalculateActiveFloors()}getIndoorTileOptions(w,C){return this._indoorState?{sourceLayers:this._style.getIndoorSourceLayers(w,C),indoorState:this._indoorState}:null}getControlState(){const w=this._buildings,C=this._closestBuildingId,O=C&&w?w[C]:void 0;if(!O)return{selectedFloorId:null,activeFloorsVisible:!!this._indoorState&&this._indoorState.activeFloorsVisible,floors:[]};let U=null;for(const Z of O.floorIds)if(this._activeFloors&&this._activeFloors.has(Z)){U=Z;break}const Y=Array.from(O.floorIds).map(Z=>({id:Z,name:O.floors[Z].name,zIndex:O.floors[Z].zIndex})).sort((Z,se)=>se.zIndex-Z.zIndex).filter((Z,se,pe)=>se===0||Z.zIndex!==pe[se-1].zIndex);return{selectedFloorId:U,activeFloorsVisible:!!this._indoorState&&this._indoorState.activeFloorsVisible,floors:Y}}_updateUI(){this._initialLoadDone=!0;const w=this._style.map.transform,C=this._buildingDetectionStrategy.findClosestBuilding(this._buildings,w.center,w.zoom,w.getBounds(),this._makeViewportPolygon());if(C!==this._closestBuildingId){const O=this._closestBuildingId;this._closestBuildingId=C,this._onBuildingTransition(O,C),this._updateIndoorSelector()}}_onBuildingTransition(w,C){if(!this._indoorState)return;!C&&w?(this._indoorState.activeFloors=new Set,this._indoorState.activeFloorsVisible=!1,this._style.updateIndoorDependentLayers()):!!C&&!w&&(this._recalculateActiveFloors(),this._updateActiveFloors(!0))}_updateIndoorSelector(){this.fire(new o.C("selector-update",this.getControlState()))}_updateActiveFloors(w){this._indoorState={selectedFloorId:this._selectedFloorId,activeFloorsVisible:w,activeFloors:this._activeFloors},this._initialLoadDone?this._style.updateIndoorDependentLayers():this._indoorState.needsUpdate=!0}_recalculateActiveFloors(){if(!this._buildings)return;const w=o.d1.calculate(this._buildings,this._selectedFloorId,this._activeFloors);(function(C,O){if(C===O)return!0;if(!C||!O||C.size!==O.size)return!1;for(const U of C)if(!O.has(U))return!1;return!0})(w,this._activeFloors)||(this._activeFloors=w,this._updateActiveFloors(!!this._indoorState&&this._indoorState.activeFloorsVisible),this._updateIndoorSelector())}_mergeFloors(w,C){C.geometry&&(w.geometry?(w.geometry.type==="Polygon"&&(w.geometry={type:"MultiPolygon",coordinates:[w.geometry.coordinates]}),C.geometry.type==="Polygon"?w.geometry.coordinates.push(C.geometry.coordinates):C.geometry.type==="MultiPolygon"&&w.geometry.coordinates.push(...C.geometry.coordinates)):w.geometry=C.geometry)}_makeViewportPolygon(){const w=this._style.map.transform,C=w.width,O=w.height;return[w.pointLocation(new o.P(0,0)),w.pointLocation(new o.P(C,0)),w.pointLocation(new o.P(C,O)),w.pointLocation(new o.P(0,O))].map(U=>new o.P(U.lng,U.lat))}}const l0=(D,w)=>xr(D,w&&w.filter(C=>C.identifier!=="source.canvas")),lh=o.aJ(_i,["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"]),Sb=o.aJ(_i,["setCenter","setZoom","setBearing","setPitch"]),J_=new Set(["background","sky","slot","custom"]),Cb={version:8,layers:[],sources:{}},Pg={duration:300,delay:0};class mu extends o.E{constructor(w,C={}){if(super(),this.map=w,this.scope=C.scope||"",this.globalId=null,this.fragments=[],this.importDepth=C.importDepth||0,this.importsCache=C.importsCache||new Map,this.resolvedImports=C.resolvedImports||new Set,this.transition=Object.assign({},Pg),this._buildingIndex=new n0(this),this.crossTileSymbolIndex=new Nf,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=C.styleChanges||new Ye,this._hasDataDrivenEmissive=!1,this.indoorManager=new Lg(this),this.dispatcher=C.dispatcher?C.dispatcher:new ht(Yt(),this),this.map.painter&&this.map.painter.context){const U=this.map.painter.context.maxUniformBufferBindings,Y=Math.floor(this.map.painter.context.maxUniformBlockSize/4);this.dispatcher.broadcast("setContextParams",{maxBindingPoints:U,maxUniformBlockSizeDwords:Y,disableSymbolUBO:this.map.painter.context.disableSymbolUBO})}C.imageManager?this.imageManager=C.imageManager:(this.imageManager=new Kt(this.map._spriteFormat),this.imageManager.setEventedParent(this)),this.imageManager.addScope(this.scope),this.glyphManager=C.glyphManager?C.glyphManager:new o.d2(w._requestManager,C.localFontFamily?o.d3.all:C.localIdeographFontFamily?o.d3.ideographs:o.d3.none,C.localFontFamily||C.localIdeographFontFamily,C.useServerFontComposition),C.modelManager?this.modelManager=C.modelManager:(this.modelManager=new d1(w._requestManager),this.modelManager.setEventedParent(this)),this._layers={},this._sourceCaches={},this._otherSourceCaches={},this._symbolSourceCaches={},this._fillExtrusionSourceCaches={},this._loaded=!1,this._precompileDone=!1,this._shouldPrecompile=!1,this._availableImages=[],this._availableModels={},this._order=[],this._markersNeedUpdate=!1,this.options=C.configOptions?C.configOptions:new Map,this._configDependentLayers=C.configDependentLayers?C.configDependentLayers:new Set,this._indoorDependentLayers=C.indoorDependentLayers?C.indoorDependentLayers:new Set,this._config=C.config,this._styleColorTheme={lut:null,lutLoading:!1,lutLoadingCorrelationID:0,colorTheme:null,colorThemeOverride:C.colorThemeOverride},this._styleColorThemeForScope={},this._initialConfig=C.initialConfig,this.dispatcher.broadcast("setReferrer",o.d4()),this.dispatcher.broadcast("setConfig",o.d5());const O=this;this._rtlTextPluginCallback=mu.registerForPluginStateChange(U=>{O.dispatcher.broadcast("syncRTLPluginState",{pluginStatus:U.pluginStatus,pluginURL:U.pluginURL},(Y,Z)=>{if(o.d6(Y),Z&&Z.every(se=>se))for(const se in O._sourceCaches){const pe=O._sourceCaches[se],je=pe.getSource().type;je!=="vector"&&je!=="geojson"||pe.reload()}})}),this.on("data",U=>{if(U.dataType!=="source"||U.sourceDataType!=="metadata")return;const Y=this.getOwnSource(U.sourceId);if(Y&&Y.vectorLayerIds)for(const Z in this._layers){const se=this._layers[Z];se.source===Y.id&&this._validateLayer(se)}})}load(w){return w?(typeof w=="string"?this.loadURL(w):this.loadJSON(w),this):this}_getGlobalId(w){if(!w)return null;if(typeof w=="string"){if(o.e(w))return w;const C=o.d7(w);if(!C.startsWith("http"))try{return new URL(C,location.href).toString()}catch{return C}return C}return`json://${o.d8(JSON.stringify(w))}`}_diffStyle(w,C,O){this.globalId=this._getGlobalId(w);const U=(Y,Z)=>{try{Z(null,this.setState(Y,O))}catch(se){Z(se,!1)}};if(typeof w=="string"){const Y=this.map._requestManager.normalizeStyleURL(w),Z=this.map._requestManager.transformRequest(Y,o.R.Style);o.m(Z,(se,pe)=>{se?this.fire(new o.B(se)):pe&&U(pe,C)})}else typeof w=="object"&&U(w,C)}loadURL(w,C={}){this.fire(new o.C("dataloading",{dataType:"style"}));const O=typeof C.validate=="boolean"?C.validate:!o.e(w);this.globalId=this._getGlobalId(w),w=this.map._requestManager.normalizeStyleURL(w,C.accessToken),this.resolvedImports.add(w);const U=this.importsCache.get(w);if(U)return this._load(U,O);const Y=this.map._requestManager.transformRequest(w,o.R.Style);this._request=o.m(Y,(Z,se)=>{if(this._request=null,Z)this.fire(new o.B(Z));else if(se)return this.importsCache.set(w,se),this._load(se,O)})}loadJSON(w,C={}){this.fire(new o.C("dataloading",{dataType:"style"})),this.globalId=this._getGlobalId(w),this._request=o.o.frame(()=>{this._request=null,this._load(w,C.validate!==!1)})}loadEmpty(){this.fire(new o.C("dataloading",{dataType:"style"})),this._load(Cb,!1)}_loadImports(w,C,O){if(this.importDepth>=4)return o.w("Style doesn't support nesting deeper than 5"),Promise.resolve();const U=[];for(const Y of w){const Z=this._createFragmentStyle(Y),se=new Promise(Ee=>{Z.once("style.import.load",Ee),Z.once("error",Ee)}).then(()=>{this.mergeAll(),this.fire(new o.C("data",{dataType:"style"}))});if(U.push(se),this.resolvedImports.has(Y.url)){Z.loadEmpty();continue}const pe=Y.data||this.importsCache.get(Y.url);pe?(Y.data?(Z.fire(new o.C("dataloading",{dataType:"style"})),Z.globalId=Z._getGlobalId(pe),queueMicrotask(()=>Z._load(pe,C))):Z.loadJSON(pe,{validate:C}),this._isInternalStyle(pe)&&(Z.globalId=null)):Y.url?Z.loadURL(Y.url,{validate:C}):Z.loadEmpty();const je={style:Z,id:Y.id,config:Y.config};if(O){const Ee=this.fragments.findIndex(({id:He})=>He===O);this.fragments=this.fragments.slice(0,Ee).concat(je).concat(this.fragments.slice(Ee))}else this.fragments.push(je)}return Promise.allSettled(U)}getImportGlobalIds(w=this,C=new Set){for(const O of w.fragments)O.style.globalId&&C.add(O.style.globalId),this.getImportGlobalIds(O.style,C);return[...C.values()]}_createFragmentStyle(w){const C=this.scope?o.F(w.id,this.scope):w.id;let O;const U=this._initialConfig&&this._initialConfig[C];(w.config||U)&&(O=Object.assign({},w.config,U));const Y=new mu(this.map,{scope:C,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:O,configOptions:this.options,colorThemeOverride:w["color-theme"],configDependentLayers:this._configDependentLayers,indoorDependentLayers:this._indoorDependentLayers});return Y.setEventedParent(this.map,{style:Y}),Y}_reloadImports(){this.mergeAll(),this._updateMapProjection(),this.updateConfigDependencies(),this._updateLayers(this._indoorDependentLayers),this.map._triggerCameraUpdate(this.camera),this.dispatcher.broadcast("setLayers",{layers:this._serializeLayers(this._order),scope:this.scope,options:this.options}),this._shouldPrecompile=this.map._precompilePrograms&&this.isRootStyle()}_isInternalStyle(w){return this.isRootStyle()&&(w.fragment||!!w.schema&&w.fragment!==!1)}_load(w,C){if(this._isInternalStyle(w)){const Y=Object.assign({},Cb,{imports:[{id:"basemap",data:w,url:""}]},w.center?{center:w.center}:{},w.bearing?{bearing:w.bearing}:{},w.pitch?{pitch:w.pitch}:{},w.zoom?{zoom:w.zoom}:{},w.light?{light:w.light}:{});return this._importedAsBasemap=!0,void this._load(Y,C)}if(this.updateConfig(this._config,w.schema),C&&l0(this,Zn(w)))return;this._loaded=!0;for(const Y in w.sources)this.addSource(Y,w.sources[Y],{validate:!1,isInitialLoad:!0});this.stylesheet=o.d9(w);const O=()=>{if(w.iconsets)for(const pe in w.iconsets)this.addIconset(pe,w.iconsets[pe]);w.sprite?this._loadIconset(w.sprite):(this.imageManager.setLoaded(!0,this.scope),this.dispatcher.broadcast("spriteLoaded",{scope:this.scope,isLoaded:!0})),!this.glyphManager.url&&w.glyphs&&this.glyphManager.setURL(w.glyphs);const Y=Km(this.stylesheet.layers);if(this._order=Y.map(pe=>pe.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 pe=this.stylesheet.lights[0];this.light=new Er(pe.properties,pe.id)}else this.setLights(this.stylesheet.lights);this.light||(this.light=new Er(this.stylesheet.light)),this._layers={};for(const pe of Y){const je=o.de(pe,this.scope,this._styleColorTheme.lut,this.options);je.expressionDependencies.configDependencies.size!==0&&this._configDependentLayers.add(je.fqid),je.expressionDependencies.isIndoorDependent&&this._indoorDependentLayers.add(je.fqid),this._hasAppearances=this._hasAppearances||je.getAppearances().length!==0,je.setEventedParent(this,{layer:{id:je.id}}),this._layers[je.id]=je;const Ee=this.getOwnLayerSourceCache(je),He=!!this.directionalLight&&this.directionalLight.shadowsEnabled();Ee&&je.canCastShadows()&&He&&(Ee.castsShadows=!0)}if(this.glyphManager.url){const pe=new Set;for(const je in this._layers){const Ee=this._layers[je];if(Ee.type==="symbol"&&Ee.layout){const He=Ee.layout.get("text-font");He&&He.value&&He.value.kind==="constant"&&pe.add(He.value.value.join(","))}}for(const je of pe)this.glyphManager.prefetchRange(je,0)}this.stylesheet.featuresets&&this.setFeaturesetSelectors(this.stylesheet.featuresets),this.stylesheet.models&&this.addModelURLs(this.stylesheet.models);const Z=this.stylesheet.terrain;Z&&(this.checkCanvasFingerprintNoise(),this.disableElevatedTerrain||this.terrainSetForDrapingOnly()||this._createTerrain(Z,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 se=this.isRootStyle();w.imports?this._loadImports(w.imports,C).then(()=>{this._reloadImports(),this.fire(new o.C(se?"style.load":"style.import.load"))}).catch(pe=>{this.fire(new o.B(new Error("Failed to load imports",pe))),this.fire(new o.C(se?"style.load":"style.import.load"))}):(this._reloadImports(),this.fire(new o.C(se?"style.load":"style.import.load")))};this._styleColorTheme.colorTheme=this.stylesheet["color-theme"];const U=this._styleColorTheme.colorThemeOverride?this._styleColorTheme.colorThemeOverride:this._styleColorTheme.colorTheme;if(U){const Y=this._evaluateColorThemeData(U);this._loadColorTheme(Y).then(()=>{O()}).catch(Z=>{o.w(`Couldn't load color theme from the stylesheet: ${Z}`),O()})}else this._styleColorTheme.lut=null,O()}isRootStyle(){return this.importDepth===0}hasAppearances(){return this._hasAppearances||this.fragments.some(w=>w.style.hasAppearances())}mergeAll(){let w,C,O,U,Y,Z,se,pe,je,Ee;const He={};this.terrain&&this.terrain.scope!==this.scope&&delete this.terrain,this.forEachFragmentStyle(qe=>{if(qe.stylesheet){if(qe.light!=null&&(w=qe.light),qe.stylesheet.lights)for(const et of qe.stylesheet.lights)et.type==="ambient"&&qe.ambientLight!=null&&(C=qe.ambientLight),et.type==="directional"&&qe.directionalLight!=null&&(O=qe.directionalLight);U=this._prioritizeTerrain(U,qe.terrain,qe.stylesheet.terrain),qe.stylesheet.fog&&qe.fog!=null&&(Y=qe.fog),qe.stylesheet.snow&&qe.snow!=null&&(Z=qe.snow),qe.stylesheet.rain&&qe.rain!=null&&(se=qe.rain),qe.stylesheet.camera!=null&&(Ee=qe.stylesheet.camera),qe.stylesheet.projection!=null&&(pe=qe.stylesheet.projection),qe.stylesheet.transition!=null&&(je=qe.stylesheet.transition),He[qe.scope]=qe._styleColorTheme}}),this.light=w,this.ambientLight=C,this.directionalLight=O,this.fog=Y,this.snow=Z,this.rain=se,this._styleColorThemeForScope=He,U===null?delete this.terrain:this.terrain=U,this.camera=Ee||{"camera-projection":"perspective"},this.projection=pe||{name:"mercator"},this.transition=Object.assign({},Pg,je),this.mergeSources(),this.mergeLayers(),this.mergeIndoor()}forEachFragmentStyle(w){const C=O=>{for(const U of O.fragments)C(U.style);w(O)};C(this)}_prioritizeTerrain(w,C,O){const U=w&&w.drapeRenderMode===0;return O===null?C&&C.drapeRenderMode===0?C:U?w:null:C!=null&&(!w||U||C&&C.drapeRenderMode===1)?C:w}mergeTerrain(){let w;this.terrain&&this.terrain.scope!==this.scope&&delete this.terrain,this.forEachFragmentStyle(C=>{w=this._prioritizeTerrain(w,C.terrain,C.stylesheet.terrain)}),w===null?delete this.terrain:this.terrain=w}mergeProjection(){let w;this.forEachFragmentStyle(C=>{C.stylesheet.projection!=null&&(w=C.stylesheet.projection)}),this.projection=w||{name:"mercator"}}mergeSources(){const w={},C={},O={},U={};this.forEachFragmentStyle(Y=>{for(const Z in Y._sourceCaches){const se=o.F(Z,Y.scope);w[se]=Y._sourceCaches[Z]}for(const Z in Y._otherSourceCaches){const se=o.F(Z,Y.scope);C[se]=Y._otherSourceCaches[Z]}for(const Z in Y._symbolSourceCaches){const se=o.F(Z,Y.scope);O[se]=Y._symbolSourceCaches[Z]}for(const Z in Y._fillExtrusionSourceCaches){const se=o.F(Z,Y.scope);U[se]=Y._fillExtrusionSourceCaches[Z]}}),this._mergedSourceCaches=w,this._mergedOtherSourceCaches=C,this._mergedSymbolSourceCaches=O,this._mergedFillExtrusionSourceCaches=U}mergeIndoor(){this.forEachFragmentStyle(w=>{if(w.stylesheet&&w.stylesheet.indoor)for(const C of Object.values(w.stylesheet.indoor)){const O=C,U=o.F(O.sourceId,w.scope);this._mergedIndoor[U]=new Set(O.sourceLayers||[])}})}mergeLayers(){const w={},C=[],O={};this._mergedSlots=[],this._has3DLayers=!1,this._hasCircleLayers=!1,this._hasSymbolLayers=!1,this.forEachFragmentStyle(Z=>{for(const se of Z._order){const pe=Z._layers[se];if(pe.type==="slot"){const je=o.da(se);if(w[je])continue;w[je]=[]}pe.slot&&w[pe.slot]?w[pe.slot].push(pe):C.push(pe)}}),this._mergedOrder=[];let U=-1;const Y=(Z=[])=>{for(const se of Z)if(se.type==="slot"){const pe=o.da(se.id);w[pe]&&Y(w[pe]),this._mergedSlots.push(pe)}else{const pe=o.F(se.id,se.scope);this._mergedOrder.push(pe),O[pe]=se,se.is3D(!!this.terrain)&&(this._has3DLayers=!0,U=this._mergedOrder.length-1),se.type==="circle"&&(this._hasCircleLayers=!0),se.type==="symbol"&&(this._hasSymbolLayers=!0),se.type==="clip"&&(this._clipLayerPresent=!0)}};if(Y(C),this._has3DLayers){const Z={};for(let se=0;seZ[se]-Z[pe])}this._mergedLayers=O,this.updateDrapeFirstLayers(),this._buildingIndex.processLayersChanged(),this._updateDataDrivenEmissiveStrength()}terrainSetForDrapingOnly(){return!!this.terrain&&this.terrain.drapeRenderMode===0}getCamera(){return this.stylesheet.camera}setCamera(w){return this.stylesheet.camera=Object.assign({},this.stylesheet.camera,w),this.camera=this.stylesheet.camera,this}_evaluateColorThemeData(w){return w.data?function(C,O,U){const Y=Object.assign({},O);for(const se of Object.keys(hu))Y[se]===void 0&&(Y[se]=hu[se].default);const Z=new o.aa(Il,C,new Map(U));return Z.setTransitionOrValue(Y,U),Z.untransitioned().possiblyEvaluate(new o.ae(0,{worldview:void 0}))}(this.scope,w,this.options).get("data"):null}_loadColorTheme(w){this._styleColorTheme.lutLoading=!0,this._styleColorTheme.lutLoadingCorrelationID+=1;const C=this._styleColorTheme.lutLoadingCorrelationID;return new Promise((O,U)=>{const Y="data:image/png;base64,";if(!w||w.length===0)return this._styleColorTheme.lut=null,this._styleColorTheme.lutLoading=!1,void O();let Z=w;Z.startsWith(Y)||(Z=Y+Z);const se=o.I.from("mapbox-reserved-lut"),pe=new Image;pe.src=Z,pe.onerror=()=>{this._styleColorTheme.lutLoading=!1,U(new Error("Failed to load image data"))},pe.onload=()=>{if(this._styleColorTheme.lutLoadingCorrelationID!==C)return void O();this._styleColorTheme.lutLoading=!1;const{width:je,height:Ee,data:He}=o.o.getImageData(pe);if(Ee>32)return void U(new Error("The height of the image must be less than or equal to 32 pixels."));if(je!==Ee*Ee)return void U(new Error("The width of the image must be equal to the height squared."));this.getImage(se)&&this.removeImage(se),this.addImage(se,{data:new o.q({width:je,height:Ee},He),pixelRatio:1,sdf:!1,usvg:!1,version:0});const qe=this.imageManager.getImage(se,this.scope);qe?(this._styleColorTheme.lut={image:qe.data,data:w},O()):U(new Error("Missing LUT image."))}})}getLut(w){const C=this._styleColorThemeForScope[w];return C?C.lut:null}setProjection(w){w?this.stylesheet.projection=w:delete this.stylesheet.projection,this.mergeProjection(),this._updateMapProjection()}applyProjectionUpdate(){this._loaded&&(this.dispatcher.broadcast("setProjection",this.map.transform.projectionOptions),this.map.transform.projection.requiresDraping?(this.getTerrain()||this.stylesheet.terrain)&&!this.disableElevatedTerrain||this.setTerrainForDraping():this.terrainSetForDrapingOnly()&&this.setTerrain(null,0))}_updateMapProjection(){this.isRootStyle()&&(this.map._useExplicitProjection?this.applyProjectionUpdate():this.map._prioritizeAndUpdateProjection(null,this.projection))}_loadSprite(w){this._spriteRequest=function(C,O,U){let Y,Z,se;const pe=o.o.devicePixelRatio>1?"@2x":"";let je=o.m(O.transformRequest(O.normalizeSpriteURL(C,pe,".json"),o.R.SpriteJSON),(qe,et)=>{je=null,se||(se=qe,Y=et,He())}),Ee=o.n(O.transformRequest(O.normalizeSpriteURL(C,pe,".png"),o.R.SpriteImage),(qe,et)=>{Ee=null,se||(se=qe,Z=et,He())});function He(){if(se)U(se);else if(Y&&Z){const qe=o.o.getImageData(Z),et={};for(const ct in Y){const{width:ot,height:bt,x:vt,y:Pt,sdf:Ft,pixelRatio:jt,stretchX:ys,stretchY:Qt,content:gs}=Y[ct],$t=new o.q({width:ot,height:bt});o.q.copy(qe,$t,{x:vt,y:Pt},{x:0,y:0},{width:ot,height:bt},null),et[ct]={data:$t,pixelRatio:jt!==void 0?jt:1,sdf:Ft!==void 0&&Ft,stretchX:ys,stretchY:Qt,content:gs,usvg:!1,version:0}}U(null,et)}}return{cancel(){je&&(je.cancel(),je=null),Ee&&(Ee.cancel(),Ee=null)}}}(w,this.map._requestManager,(C,O)=>{if(this._spriteRequest=null,C)this.fire(new o.B(C));else if(O){const U=new Map;for(const Y in O)U.set(o.I.from(Y),O[Y]);this.addImages(U)}this.imageManager.setLoaded(!0,this.scope),this.dispatcher.broadcast("spriteLoaded",{scope:this.scope,isLoaded:!0}),this.fire(new o.C("data",{dataType:"style"}))})}addIconset(w,C){if(C.type==="sprite")return void this._loadSprite(C.url);const O=this.getOwnSourceCache(C.source);if(!O)return void this.fire(new o.B(new Error(`Source "${C.source}" as specified by iconset "${w}" does not exist and cannot be used as an iconset source`)));const U=O.getSource();if(U.type!=="raster-array")return void this.fire(new o.B(new Error(`Source "${C.source}" as specified by iconset "${w}" is not a "raster-array" source and cannot be used as an iconset source`)));U.partial=!1;const Y=new Fd(w,this.scope,O);this.imageManager.addImageProvider(Y,this.scope)}removeIconset(w){this.imageManager.removeImageProvider(w,this.scope)}_loadIconset(w){if(!o.e(w)&&this.map._spriteFormat!=="icon_set"||this.map._spriteFormat==="raster")return void this._loadSprite(w);const C=this.map._spriteFormat==="auto";var O,U;this._spriteRequest=(U=(Y,Z)=>{if(this._spriteRequest=null,Y)C?this._loadSprite(w):this.fire(new o.B(Y));else if(Z){const se=new Map;for(const pe in Z)se.set(o.I.from(pe),Z[pe]);this.addImages(se)}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((O=this.map._requestManager).transformRequest(O.normalizeIconsetURL(w),o.R.Iconset),(Y,Z)=>{if(Y)return void U(Y);const se={},pe=o.c$(new o.a$(Z));for(const je of pe.icons){const Ee={version:1,pixelRatio:o.o.devicePixelRatio,content:Wo(je),stretchX:je.metadata?Oo(je.metadata.stretch_x_areas):void 0,stretchY:je.metadata?Oo(je.metadata.stretch_y_areas):void 0,sdf:!1,usvg:!0,icon:je};se[je.name]=Ee}U(null,se)}))}_validateLayer(w){const C=this.getOwnSource(w.source);if(!C)return;const O=w.sourceLayer;O&&(C.type==="geojson"||C.vectorLayerIds&&C.vectorLayerIds.indexOf(O)===-1)&&this.fire(new o.B(new Error(`Source layer "${O}" does not exist on source "${C.id}" as specified by style layer "${w.id}"`)))}loaded(){if(!this._loaded||Object.keys(this._changes.getUpdatedSourceCaches()).length)return!1;for(const w in this._sourceCaches)if(!this._sourceCaches[w].loaded())return!1;if(!this.imageManager.isLoaded()||this.imageManager.hasPatternsInFlight()||!this.modelManager.isLoaded()||this._styleColorTheme.lutLoading)return!1;for(const{style:w}of this.fragments)if(!w.loaded())return!1;return!0}_serializeImports(){if(this.stylesheet.imports)return this.stylesheet.imports.map((w,C)=>{const O=this.fragments[C];return O&&O.style&&(w.data=O.style.serialize()),w})}_serializeSources(){const w={};for(const C in this._sourceCaches){const O=this._sourceCaches[C].getSource();w[O.id]||(w[O.id]=O.serialize())}return w}_serializeLayers(w){const C=[];for(const O of w){const U=this._layers[O];U&&U.type!=="custom"&&C.push(U.serialize())}return C}hasLightTransitions(){return!(!this.light||!this.light.hasTransition())||!(!this.ambientLight||!this.ambientLight.hasTransition())||!(!this.directionalLight||!this.directionalLight.hasTransition())}hasFogTransition(){return!!this.fog&&this.fog.hasTransition()}hasSnowTransition(){return!!this.snow&&this.snow.hasTransition()}hasRainTransition(){return!!this.rain&&this.rain.hasTransition()}hasTransitions(){if(this.hasLightTransitions()||this.hasFogTransition()||this.hasSnowTransition()||this.hasRainTransition())return!0;for(const w in this._sourceCaches)if(this._sourceCaches[w].hasTransition())return!0;for(const w in this._layers)if(this._layers[w].hasTransition())return!0;return!1}_updateDataDrivenEmissiveStrength(){for(const w in this._mergedLayers){const C=this._mergedLayers[w];if(C._transitionablePaint&&C._transitionablePaint._values){const O=C._transitionablePaint._values["line-emissive-strength"];if(O&&O.value&&O.value.isDataDriven())return void(this._hasDataDrivenEmissive=!0)}}this._hasDataDrivenEmissive=!1}hasDataDrivenEmissiveStrength(){return this._hasDataDrivenEmissive}get order(){return this.terrain?this._drapedFirstOrder:this._mergedOrder}_getOrder(w){return w?this.order:this._mergedOrder}isLayerDraped(w){return!!this.terrain&&w.isDraped(this.getLayerSourceCache(w))}_checkLoaded(){if(!this._loaded)throw new Error("Style is not done loading")}_checkLayer(w){const C=this.getOwnLayer(w);if(C)return C;this.fire(new o.B(new Error(`The layer '${w}' does not exist in the map's style.`)))}_checkSource(w){const C=this.getOwnSource(w);if(C)return C;this.fire(new o.B(new Error(`The source '${w}' does not exist in the map's style.`)))}precompilePrograms(w,C){const O=this.map.painter;if(O)for(let U=w.minzoom||0;U<(w.maxzoom||25.5);U++){const Y=w.getProgramIds();if(Y)for(const Z of Y){const se=w.getDefaultProgramParams(Z,C.zoom,this._styleColorTheme.lut);se&&(O.style=this,this.fog&&(O._fogVisible=!0,se.overrideFog=!0,O.getOrCreateProgram(Z,se)),O._fogVisible=!1,se.overrideFog=!1,O.getOrCreateProgram(Z,se),(this.stylesheet.terrain||this.stylesheet.projection&&this.stylesheet.projection.name==="globe")&&(se.overrideRtt=!0,O.getOrCreateProgram(Z,se)))}}}update(w){if(!this._loaded)return;this.ambientLight&&this.ambientLight.recalculate(w),this.directionalLight&&this.directionalLight.recalculate(w);const C=this.calculateLightsBrightness();w.brightness=C||0,C!==this._brightness&&(this._brightness=C,this.dispatcher.broadcast("setBrightness",C)),w.worldview!==this._worldview&&(this._worldview=w.worldview,this.dispatcher.broadcast("setWorldview",this._worldview));const O=this._changes.isDirty();let U=!1;if(this._changes.isDirty()){const pe=this._changes.getLayerUpdatesByScope();for(const je in pe){const{updatedIds:Ee,removedIds:He}=pe[je];(Ee||He)&&(this._updateWorkerLayers(je,Ee,He),U=!0)}this.updateSourceCaches(),this._updateTilesForChangedImages(),this.updateLayers(w),this.light&&this.light.updateTransitions(w),this.ambientLight&&this.ambientLight.updateTransitions(w),this.directionalLight&&this.directionalLight.updateTransitions(w),this.fog&&this.fog.updateTransitions(w),this.snow&&this.snow.updateTransitions(w),this.rain&&this.rain.updateTransitions(w),this._changes.reset()}const Y={};for(const pe in this._mergedSourceCaches){const je=this._mergedSourceCaches[pe];Y[pe]=je.used,je.used=!1,je.tileCoverLift=0}const Z={};for(const pe of this._mergedOrder){const je=this._mergedLayers[pe];if((je.visibility!=="none"||je.hasTransition())&&je.recalculate(w,this._availableImages),!je.isHidden(w.zoom)){const Ee=this.getLayerSourceCache(je);Ee&&(Ee.used=!0,Ee.tileCoverLift=Math.max(Ee.tileCoverLift,je.tileCoverLift()))}if(je.type==="fill-extrusion"){const Ee=o.F(je.source,je.scope);if(Ee in this._mergedFillExtrusionSourceCaches){const He=je.layout&&je.layout.get("source-max-zoom");if(He!=null){const qe=Z[Ee];Z[Ee]=qe==null?He:Math.min(qe,He)}}}!this._precompileDone&&this._shouldPrecompile&&("requestIdleCallback"in window?requestIdleCallback(()=>{this.precompilePrograms(je,w)}):this.precompilePrograms(je,w))}this._shouldPrecompile&&(this._precompileDone=!0);for(const pe in this._mergedFillExtrusionSourceCaches)this._mergedFillExtrusionSourceCaches[pe].setMaxzoomOverride(Z[pe]!=null?Z[pe]:null);this.terrain&&U&&this.mergeLayers();const se=this.imageManager.getPendingImageProviders();for(const pe of se)pe.sourceCache.used=!0;for(const pe in Y){const je=this._mergedSourceCaches[pe];Y[pe]!==je.used&&je.getSource().fire(new o.C("data",{sourceDataType:"visibility",dataType:"source",sourceId:je.getSource().id}))}this.light&&this.light.recalculate(w),this.terrain&&this.terrain.recalculate(w),this.fog&&this.fog.recalculate(w),this.snow&&this.snow.recalculate(w),this.rain&&this.rain.recalculate(w),this.z=w.zoom,this._markersNeedUpdate&&(this._updateMarkersOpacity(),this._markersNeedUpdate=!1),this.imageManager.clearUpdatedImages(this.scope),O&&this.fire(new o.C("data",{dataType:"style"}))}updateImageProviders(){const w=this.imageManager.getPendingImageProviders();for(const C of w){const O=C.resolvePendingRequests(),U=this.getFragmentStyle(C.scope);U&&U.addImages(O)}}_updateTilesForChangedImages(){const w={};for(const C in this._mergedSourceCaches){const O=this._mergedSourceCaches[C].getSource().scope;w[O]=w[O]||this._changes.getUpdatedImages(O),w[O].length!==0&&this._mergedSourceCaches[C].reloadTilesForDependencies(["icons","patterns"],w[O])}for(const C in w)this._changes.resetUpdatedImages(C)}_updateWorkerLayers(w,C,O){const U=this.getFragmentStyle(w);U&&this.dispatcher.broadcast("updateLayers",{layers:C?U._serializeLayers(C):[],scope:w,removedIds:O||[],options:U.options})}setState(w,C){if(this._checkLoaded(),l0(this,Zn(w)))return!1;(w=o.d9(w)).layers=Km(w.layers);const O=function(Z,se){if(!Z)return[{command:_i.setStyle,args:[se]}];let pe=[];try{if(!o.b6(Z.version,se.version))return[{command:_i.setStyle,args:[se]}];if(o.b6(Z.center,se.center)||pe.push({command:_i.setCenter,args:[se.center]}),o.b6(Z.zoom,se.zoom)||pe.push({command:_i.setZoom,args:[se.zoom]}),o.b6(Z.bearing,se.bearing)||pe.push({command:_i.setBearing,args:[se.bearing]}),o.b6(Z.pitch,se.pitch)||pe.push({command:_i.setPitch,args:[se.pitch]}),o.b6(Z.sprite,se.sprite)||pe.push({command:_i.setSprite,args:[se.sprite]}),o.b6(Z.glyphs,se.glyphs)||pe.push({command:_i.setGlyphs,args:[se.glyphs]}),o.b6(Z.imports,se.imports)||function(et=[],ct=[],ot){ct=ct||[];const bt=(et=et||[]).map(mm),vt=ct.map(mm),Pt=et.reduce(Qf,{}),Ft=ct.reduce(Qf,{}),jt=bt.slice();let ys,Qt,gs,$t;for(ys=0,Qt=0;ys{et.source&&je[et.source]?pe.push({command:_i.removeLayer,args:[et.id]}):He.push(et)});let qe=Z.terrain;qe&&je[qe.source]&&(pe.push({command:_i.setTerrain,args:[void 0]}),qe=void 0),pe=pe.concat(Ee),o.b6(qe,se.terrain)||pe.push({command:_i.setTerrain,args:[se.terrain]}),function(et,ct,ot){ct=ct||[];const bt=(et=et||[]).map(mm),vt=ct.map(mm),Pt=et.reduce(Qf,{}),Ft=ct.reduce(Qf,{}),jt=bt.slice(),ys=Object.create(null);let Qt,gs,$t,Zt,hs,Us,Cs;for(Qt=0,gs=0;Qt!(Z.command in Sb));if(O.length===0)return!1;const U=O.filter(Z=>!(Z.command in lh));if(U.length>0)throw new Error(`Unimplemented: ${U.map(Z=>Z.command).join(", ")}.`);const Y=[];return O.forEach(Z=>{Y.push(this[Z.command](...Z.args))}),C&&Promise.all(Y).then(C).catch(C),this.stylesheet=w,this.mergeAll(),this.dispatcher.broadcast("setLayers",{layers:this._serializeLayers(this._order),scope:this.scope,options:this.options}),!0}_updateWorkerImages(){this._availableImages=this.imageManager.listImages(this.scope),this.dispatcher.broadcast("setImages",{scope:this.scope,images:this._availableImages})}_updateWorkerModels(){this._availableModels=this.modelManager.getModelURIs(this.scope),this.dispatcher.broadcast("setModels",{scope:this.scope,models:this._availableModels})}addImages(w){if(w.size===0)return this;for(const[C,O]of w.entries()){if(this.getImage(C))return this.fire(new o.B(new Error(`An image with the name "${C.name}" already exists.`)));this.imageManager.addImage(C,this.scope,O),this._changes.updateImage(C,this.scope)}return this._updateWorkerImages(),this.fire(new o.C("data",{dataType:"style"})),this}addImage(w,C){return this.getImage(w)?this.fire(new o.B(new Error(`An image with the name "${w.name}" already exists.`))):(this.imageManager.addImage(w,this.scope,C),this._changes.updateImage(w,this.scope),this._updateWorkerImages(),this.fire(new o.C("data",{dataType:"style"})),this)}updateImage(w,C,O=!1){this.imageManager.updateImage(w,this.scope,C),O&&(this._changes.updateImage(w,this.scope),this._updateWorkerImages(),this.fire(new o.C("data",{dataType:"style"})))}getImage(w){return this.imageManager.getImage(w,this.scope)}removeImage(w){return this.getImage(w)?(this.imageManager.removeImage(w,this.scope),this._changes.updateImage(w,this.scope),this._updateWorkerImages(),this.fire(new o.C("data",{dataType:"style"})),this):this.fire(new o.B(new Error("No image with this name exists.")))}listImages(){return this._checkLoaded(),this._availableImages.slice()}getActualScope(){return this._importedAsBasemap?"basemap":this.scope}addModelURLs(w){return this.modelManager.addModelURLs(w,this.getActualScope()),this._updateWorkerModels(),this.fire(new o.C("data",{dataType:"style"})),this}addModel(w,C,O={}){return this._checkLoaded(),this._validate(kn,`models.${w}`,C,null,O)||(this.modelManager.addModel(w,C,this.getActualScope()),this.fire(new o.C("data",{dataType:"style"}))),this}hasModel(w){return this.modelManager.hasModel(w,this.getActualScope())}removeModel(w){return this.hasModel(w)?(this.modelManager.removeModel(w,this.getActualScope(),!1,!0),this.fire(new o.C("data",{dataType:"style"})),this):this.fire(new o.B(new Error("No model with this ID exists.")))}listModels(){return this._checkLoaded(),this.modelManager.listModels(this.getActualScope())}addSource(w,C,O={}){if(this._checkLoaded(),this.getOwnSource(w)!==void 0)throw new Error(`There is already a source with ID "${w}".`);if(!C.type)throw new Error(`The type property must be defined, but only the following properties were given: ${Object.keys(C).join(", ")}.`);if(["vector","raster","geojson","video","image"].indexOf(C.type)>=0&&this._validate(sa,`sources.${w}`,C,null,O))return;this.map&&this.map._collectResourceTiming&&(C.collectResourceTiming=!0);const U=wf(w,C,this.dispatcher,this);U.scope=this.scope,U.setEventedParent(this,()=>({isSourceLoaded:this._isSourceCacheLoaded(U.id),source:U.serialize(),sourceId:U.id}));const Y=Z=>{const se=(Z===o.b4.Symbol?"symbol:":Z===o.b4.FillExtrusion?"fill-extrusion:":"other:")+U.id,pe=o.F(se,this.scope),je=this._sourceCaches[se]=new Bl(pe,U,Z);Z===o.b4.Symbol?this._symbolSourceCaches[U.id]=je:Z===o.b4.FillExtrusion?this._fillExtrusionSourceCaches[U.id]=je:this._otherSourceCaches[U.id]=je,je.onAdd(this.map)};Y(o.b4.Other),C.type!=="vector"&&C.type!=="geojson"||(Y(o.b4.Symbol),C.type==="vector"&&Y(o.b4.FillExtrusion)),U.onAdd&&U.onAdd(this.map),O.isInitialLoad||(this.mergeSources(),this._changes.setDirty())}removeSource(w){this._checkLoaded();const C=this.getOwnSource(w);if(!C)throw new Error("There is no source with this ID");for(const U in this._layers)if(this._layers[U].source===w)return this.fire(new o.B(new Error(`Source "${w}" cannot be removed while layer "${U}" is using it.`)));if(this.terrain&&this.terrain.scope===this.scope&&this.terrain.get().source===w)return this.fire(new o.B(new Error(`Source "${w}" cannot be removed while terrain is using it.`)));if(this.stylesheet.iconsets){const U=Object.entries(this.stylesheet.iconsets).find(([Y,Z])=>Z.type==="source"&&Z.source===w);if(U)return this.fire(new o.B(new Error(`Source "${w}" cannot be removed while iconset "${U[0]}" is using it.`)))}const O=this.getOwnSourceCaches(w);for(const U of O){const Y=o.da(U.id);delete this._sourceCaches[Y],this._changes.discardSourceCacheUpdate(U.id),U.fire(new o.C("data",{sourceDataType:"metadata",dataType:"source",sourceId:U.getSource().id})),U.setEventedParent(null),U.clearTiles()}return delete this._otherSourceCaches[w],delete this._symbolSourceCaches[w],delete this._fillExtrusionSourceCaches[w],this.mergeSources(),C.setEventedParent(null),C.onRemove&&C.onRemove(this.map),this._changes.setDirty(),this}setGeoJSONSourceData(w,C){this._checkLoaded(),this.getOwnSource(w).setData(C),this._changes.setDirty()}getOwnSource(w){const C=this.getOwnSourceCache(w);return C&&C.getSource()}getOwnSources(){const w=[];for(const C in this._otherSourceCaches){const O=this.getOwnSourceCache(C);O&&w.push(O.getSource())}return w}areTilesLoaded(){const w=this._mergedSourceCaches;for(const C in w){const O=w[C]._tiles;for(const U in O){const Y=O[U];if(Y.state!=="loaded"&&Y.state!=="errored")return!1}}return!0}setLights(w){if(this._checkLoaded(),!w)return delete this.ambientLight,void delete this.directionalLight;const C=this._getTransitionParameters();for(const Y of w){if(this._validate(Ve,"lights",Y))return;switch(Y.type){case"ambient":if(this.ambientLight){const Z=this.ambientLight;Z.set(Y),Z.updateTransitions(C)}else this.ambientLight=new Wn(Y,Ra(),this.scope,this.options);break;case"directional":if(this.directionalLight){const Z=this.directionalLight;Z.set(Y),Z.updateTransitions(C)}else this.directionalLight=new Wn(Y,Ho(),this.scope,this.options)}}const O=Object.assign(C,{worldview:this.map.getWorldview()}),U=new o.ae(this.z||0,O);this.ambientLight&&this.ambientLight.recalculate(U),this.directionalLight&&this.directionalLight.recalculate(U),this._brightness=this.calculateLightsBrightness(),this.dispatcher.broadcast("setBrightness",this._brightness)}calculateLightsBrightness(){const w=this.directionalLight,C=this.ambientLight;if(!w||!C)return;const O=qe=>.2126*(qe[0]<=.03928?qe[0]/12.92:Math.pow((qe[0]+.055)/1.055,2.4))+.7152*(qe[1]<=.03928?qe[1]/12.92:Math.pow((qe[1]+.055)/1.055,2.4))+.0722*(qe[2]<=.03928?qe[2]/12.92:Math.pow((qe[2]+.055)/1.055,2.4)),U=w.properties.get("color").toNonPremultipliedRenderColor(null).toArray01(),Y=w.properties.get("intensity"),Z=w.properties.get("direction"),se=1-o.cP(Z.x,Z.y,Z.z)[2]/90,pe=O(U)*Y*se,je=C.properties.get("color").toNonPremultipliedRenderColor(null).toArray01(),Ee=C.properties.get("intensity"),He=O(je)*Ee;return Number(((pe+He)/2).toFixed(6))}getBrightness(){return this._brightness}getLights(){if(!this.enable3dLights())return null;const w=[];return this.directionalLight&&w.push(this.directionalLight.get()),this.ambientLight&&w.push(this.ambientLight.get()),w}enable3dLights(){return!!this.ambientLight&&!!this.directionalLight}getFragmentStyle(w){if(w==null||w===""&&this.isRootStyle())return this;if(o.db(w)){const C=o.dc(w),O=this.fragments.find(({id:Y})=>Y===C);if(!O)return;const U=o.da(w);return O.style.getFragmentStyle(U)}{const C=this.fragments.find(({id:O})=>O===w);return C?C.style:void 0}}setFeaturesetSelectors(w){if(!w)return;const C=(O,U="")=>`${O}::${U}`;this._featuresetSelectors={};for(const O in w){const U={},Y=this._featuresetSelectors[O]=[];for(const Z of w[O].selectors){if(Z.featureNamespace){const pe=this.getOwnLayer(Z.layer);if(!pe){o.w(`Layer is undefined for selector: ${Z.layer}`);continue}const je=C(pe.source,pe.sourceLayer);if(je in U&&U[je]!==Z.featureNamespace){o.w(`"featureNamespace ${Z.featureNamespace} of featureset ${O}'s selector is not associated to the same source, skip this selector`);continue}U[je]=Z.featureNamespace}let se;if(Z.properties)for(const pe in Z.properties){const je=o.X(Z.properties[pe]);je.result==="success"&&(se=se||{},se[pe]=je.value)}Y.push({layerId:Z.layer,namespace:Z.featureNamespace,properties:se,uniqueFeatureID:Z._uniqueFeatureID})}}}getFeaturesetDescriptors(w){const C=this.getFragmentStyle(w);if(!C||!C.stylesheet.featuresets)return[];const O=[];for(const U in C.stylesheet.featuresets)O.push({featuresetId:U,importId:C.scope?C.scope:void 0});return O}getFeaturesetLayers(w,C){const O=this.getFragmentStyle(C),U=O.stylesheet.featuresets;if(!U||!U[w])return this.fire(new o.B(new Error(`The featureset '${w}' does not exist in the map's style and cannot be queried.`))),[];const Y=[];for(const Z of U[w].selectors){const se=O.getOwnLayer(Z.layer);se&&Y.push(se)}return Y}getConfigProperty(w,C){const O=this.getFragmentStyle(w);if(!O)return null;const U=o.F(C,O.scope),Y=O.options.get(U),Z=Y?Y.value||Y.default:null;return Z?Z.serialize():null}isIndoorEnabled(){return Object.keys(this._mergedIndoor).length>0}getIndoorSourceLayers(w,C){const O=o.F(w,C);return this._mergedIndoor[O]}setIndoorData(w,C){this.indoorManager.setIndoorData(C)}updateIndoorDependentLayers(){this._updateLayers(this._indoorDependentLayers),this.map._styleDirty=!0,this.map.triggerRepaint()}setConfigProperty(w,C,O){const U=this.getFragmentStyle(w);if(!U)return;const Y=U.stylesheet.schema;if(!Y||!Y[C])return;const Z=o.X(O);if(Z.result!=="success")return void l0(this,Z.value);const se=Z.value.expression,pe=o.F(C,U.scope),je=U.options.get(pe);if(!je)return;let Ee;const{minValue:He,maxValue:qe,stepValue:et,type:ct,values:ot}=Y[C],bt=o.X(Y[C].default);bt.result==="success"&&(Ee=bt.value.expression),Ee?(this.options.set(pe,Object.assign({},je,{value:se,default:Ee,minValue:He,maxValue:qe,stepValue:et,type:ct,values:ot})),this.updateConfigDependencies(C)):this.fire(new o.B(new Error(`No schema defined for the config option "${C}" in the "${w}" fragment.`)))}getConfig(w){const C=this.getFragmentStyle(w);if(!C)return null;const O=C.stylesheet.schema;if(!O)return null;const U={};for(const Y in O){const Z=o.F(Y,C.scope),se=C.options.get(Z),pe=se?se.value||se.default:null;U[Y]=pe?pe.serialize():null}return U}setConfig(w,C){const O=this.getFragmentStyle(w);O&&(O.updateConfig(C,O.stylesheet.schema),this.updateConfigDependencies())}getSchema(w){const C=this.getFragmentStyle(w);return C?C.stylesheet.schema:null}setSchema(w,C){const O=this.getFragmentStyle(w);O&&(O.stylesheet.schema=C,O.updateConfig(O._config,C),this.updateConfigDependencies())}updateConfig(w,C){if(this._config=w,w||C)if(C)for(const O in C){let U,Y;const Z=o.X(C[O].default);if(Z.result==="success"&&(U=Z.value.expression),w&&w[O]!==void 0){const qe=o.X(w[O]);qe.result==="success"&&(Y=qe.value.expression)}const{minValue:se,maxValue:pe,stepValue:je,type:Ee,values:He}=C[O];if(U){const qe=o.F(O,this.scope);this.options.set(qe,{default:U,value:Y,minValue:se,maxValue:pe,stepValue:je,type:Ee,values:He})}else this.fire(new o.B(new Error(`No schema defined for config option "${O}".`)))}else this.fire(new o.B(new Error("Attempting to set config for a style without schema.")))}_updateLayers(w,C=()=>!0){for(const O of w){const U=this.getLayer(O);U&&C(U)&&(U.possiblyEvaluateVisibility(),this._updateLayer(U),this._changes.setDirty())}}updateConfigDependencies(w){this._updateLayers(this._configDependentLayers,C=>!w||C.expressionDependencies.configDependencies.has(w)),this.ambientLight&&this.ambientLight.updateConfig(this.options),this.directionalLight&&this.directionalLight.updateConfig(this.options),this.fog&&this.fog.updateConfig(this.options),this.snow&&this.snow.updateConfig(this.options),this.rain&&this.rain.updateConfig(this.options),this.forEachFragmentStyle(C=>{const O=C._styleColorTheme.colorThemeOverride?C._styleColorTheme.colorThemeOverride:C._styleColorTheme.colorTheme;if(O){const U=C._evaluateColorThemeData(O);(!C._styleColorTheme.lut&&U!==""||C._styleColorTheme.lut&&U!==C._styleColorTheme.lut.data)&&C.setColorTheme(O)}}),this._changes.setDirty()}addLayer(w,C,O={}){this._checkLoaded();const U=w.id;if(this._layers[U])return void this.fire(new o.B(new Error(`Layer with id "${U}" already exists on this map`)));let Y;if(w.type==="custom"){if(l0(this,o.dd(w)))return;Y=o.de(w,this.scope,this._styleColorTheme.lut,this.options)}else{if(typeof w.source=="object"&&(this.addSource(U,w.source),w=o.d9(w),w=Object.assign(w,{source:U})),this._validate(es,`layers.${U}`,w,{arrayIndex:-1},O))return;Y=o.de(w,this.scope,this._styleColorTheme.lut,this.options),this._validateLayer(Y),Y.setEventedParent(this,{layer:{id:U}})}const Z=o.F(Y.source,Y.scope);Y.expressionDependencies.configDependencies.size!==0&&this._configDependentLayers.add(Z),Y.expressionDependencies.isIndoorDependent&&this._indoorDependentLayers.add(Z);let se=this._order.length;if(C){const He=this._order.indexOf(C);if(He===-1)return void this.fire(new o.B(new Error(`Layer with id "${C}" does not exist on this map.`)));Y.slot&&Y.slot!==this._layers[C].slot?o.w(`Layer with id "${C}" has a different slot. Layers can only be rearranged within the same slot.`):se=He}this._order.splice(se,0,U),this._handleLayerOrderChange(),this._layers[U]=Y;const pe=this.getOwnLayerSourceCache(Y),je=!!this.directionalLight&&this.directionalLight.shadowsEnabled();pe&&Y.canCastShadows()&&je&&(pe.castsShadows=!0);const Ee=this._changes.getRemovedLayer(Y);if(Ee&&Y.source&&pe&&Y.type!=="custom"){this._changes.discardLayerRemoval(Y);const He=o.F(Y.source,Y.scope);Ee.type!==Y.type?this._changes.updateSourceCache(He,"clear"):(this._changes.updateSourceCache(He,"reload"),pe.pause())}this._updateLayer(Y),Y.onAdd&&Y.onAdd(this.map),Y.scope=this.scope,this.mergeLayers()}moveLayer(w,C){this._checkLoaded();const O=this._checkLayer(w);if(!O||w===C)return;const U=this._order.indexOf(w);this._order.splice(U,1);let Y=this._order.length;if(C){const Z=this._order.indexOf(C);if(Z===-1)return void this.fire(new o.B(new Error(`Layer with id "${C}" does not exist on this map.`)));O.slot&&O.slot!==this._layers[C].slot?o.w(`Layer with id "${C}" has a different slot. Layers can only be rearranged within the same slot.`):Y=Z}this._order.splice(Y,0,w),this._changes.setDirty(),this._handleLayerOrderChange(),this.mergeLayers()}removeLayer(w){this._checkLoaded();const C=this._checkLayer(w);if(!C)return;C.setEventedParent(null);const O=this._order.indexOf(w);this._order.splice(O,1),delete this._layers[w],this._changes.setDirty(),this._handleLayerOrderChange(),this._configDependentLayers.delete(C.fqid),this._indoorDependentLayers.delete(C.fqid),this._changes.removeLayer(C);const U=this.getOwnLayerSourceCache(C);if(U&&U.castsShadows){let Y=!1;for(const Z in this._layers)if(this._layers[Z].source===C.source&&this._layers[Z].canCastShadows()){Y=!0;break}U.castsShadows=Y}C.onRemove&&C.onRemove(this.map),this.mergeLayers()}getOwnLayer(w){return this._layers[w]}hasLayer(w){return w in this._mergedLayers}hasLayerType(w){for(const C in this._layers)if(this._layers[C].type===w)return!0;return!1}setLayerZoomRange(w,C,O){this._checkLoaded();const U=this._checkLayer(w);U&&(U.minzoom===C&&U.maxzoom===O||(C!=null&&(U.minzoom=C),O!=null&&(U.maxzoom=O),this._updateLayer(U)))}getSlots(){return this._checkLoaded(),this._mergedSlots}setSlot(w,C){this._checkLoaded();const O=this._checkLayer(w);O&&O.slot!==C&&(O.slot=C,this._updateLayer(O))}setFilter(w,C,O={}){this._checkLoaded();const U=this._checkLayer(w);if(U&&!o.b6(U.filter,C))return C==null?(U.filter=void 0,void this._updateLayer(U)):void(this._validate(Ms,`layers.${U.id}.filter`,C,{layerType:U.type},O)||(U.filter=o.d9(C),this._updateLayer(U)))}getFilter(w){const C=this._checkLayer(w);if(C)return o.d9(C.filter)}setLayoutProperty(w,C,O,U={}){this._checkLoaded();const Y=this._checkLayer(w);if(Y&&!o.b6(Y.getLayoutProperty(C),O)){if(O!=null&&(!U||U.validate!==!1)&&l0(Y,Zs.call(Zn,{key:`layers.${w}.layout.${C}`,layerType:Y.type,objectKey:C,value:O,styleSpec:o.a8,style:{glyphs:!0,sprite:!0}})))return;Y.setLayoutProperty(C,O),Y.expressionDependencies.configDependencies.size!==0&&this._configDependentLayers.add(Y.fqid),Y.expressionDependencies.isIndoorDependent&&this._indoorDependentLayers.add(Y.fqid),this._updateLayer(Y)}}setLayerProperty(w,C,O,U={}){this._checkLoaded();const Y=this._checkLayer(w);Y&&(C==="appearances"?(Y.setAppearances(O),this._updateLayer(Y)):Y.isPaintProperty(C)?this.setPaintProperty(w,C,O,U):this.setLayoutProperty(w,C,O,U))}getLayoutProperty(w,C){const O=this._checkLayer(w);if(O)return O.getLayoutProperty(C)}setPaintProperty(w,C,O,U={}){this._checkLoaded();const Y=this._checkLayer(w);if(!Y||o.b6(Y.getPaintProperty(C),O)||O!=null&&(!U||U.validate!==!1)&&l0(Y,bs.call(Zn,{key:`layers.${w}.paint.${C}`,layerType:Y.type,objectKey:C,value:O,styleSpec:o.a8})))return;const Z=Y.setPaintProperty(C,O);Y.expressionDependencies.configDependencies.size!==0&&this._configDependentLayers.add(Y.fqid),Y.expressionDependencies.isIndoorDependent&&this._indoorDependentLayers.add(Y.fqid),Z&&this._updateLayer(Y),this._changes.updatePaintProperties(Y)}getPaintProperty(w,C){const O=this._checkLayer(w);if(O)return O.getPaintProperty(C)}setFeatureState(w,C){if(this._checkLoaded(),"target"in w){if("featuresetId"in w.target){const{featuresetId:pe,importId:je}=w.target,Ee=this.getFragmentStyle(je),He=Ee.getFeaturesetLayers(pe);for(const{source:qe,sourceLayer:et}of He)Ee.setFeatureState({id:w.id,source:qe,sourceLayer:et},C)}else if("layerId"in w.target){const{layerId:pe}=w.target,je=this.getLayer(pe);this.setFeatureState({id:w.id,source:je.source,sourceLayer:je.sourceLayer},C)}return}const O=w.source,U=w.sourceLayer,Y=this._checkSource(O);if(!Y)return;const Z=Y.type;if(Z==="geojson"&&U)return void this.fire(new o.B(new Error("GeoJSON sources cannot have a sourceLayer parameter.")));if(Z==="vector"&&!U)return void this.fire(new o.B(new Error("The sourceLayer parameter must be provided for vector source types.")));w.id===void 0&&this.fire(new o.B(new Error("The feature id parameter must be provided.")));const se=this.getOwnSourceCaches(O);for(const pe of se)pe.setFeatureState(U,w.id,C)}removeFeatureState(w,C){if(this._checkLoaded(),"target"in w){if("featuresetId"in w.target){const{featuresetId:pe,importId:je}=w.target,Ee=this.getFragmentStyle(je),He=Ee.getFeaturesetLayers(pe);for(const{source:qe,sourceLayer:et}of He)Ee.removeFeatureState({id:w.id,source:qe,sourceLayer:et},C)}else if("layerId"in w.target){const{layerId:pe}=w.target,je=this.getLayer(pe);this.removeFeatureState({id:w.id,source:je.source,sourceLayer:je.sourceLayer},C)}return}const O=w.source,U=this._checkSource(O);if(!U)return;const Y=U.type,Z=Y==="vector"?w.sourceLayer:void 0;if(Y==="vector"&&!Z)return void this.fire(new o.B(new Error("The sourceLayer parameter must be provided for vector source types.")));if(C&&typeof w.id!="string"&&typeof w.id!="number")return void this.fire(new o.B(new Error("A feature id is required to remove its specific state property.")));const se=this.getOwnSourceCaches(O);for(const pe of se)pe.removeFeatureState(Z,w.id,C)}getFeatureState(w){if(this._checkLoaded(),"target"in w){let Y;if("featuresetId"in w.target){const{featuresetId:Z,importId:se}=w.target,pe=this.getFragmentStyle(se),je=pe.getFeaturesetLayers(Z);for(const{source:Ee,sourceLayer:He}of je){const qe=pe.getFeatureState({id:w.id,source:Ee,sourceLayer:He});if(qe&&!Y)Y=qe;else if(!o.b6(Y,qe))return void this.fire(new o.B(new Error("The same feature id exists in multiple sources in the featureset, but their feature states are not consistent through the sources.")))}}else if("layerId"in w.target){const{layerId:Z}=w.target,se=this.getLayer(Z);Y=this.getFeatureState({id:w.id,source:se.source,sourceLayer:se.sourceLayer})}return Y}const C=w.source,O=w.sourceLayer,U=this._checkSource(C);if(U){if(U.type!=="vector"||O)return w.id===void 0&&this.fire(new o.B(new Error("The feature id parameter must be provided."))),this.getOwnSourceCaches(C)[0].getFeatureState(O,w.id);this.fire(new o.B(new Error("The sourceLayer parameter must be provided for vector source types.")))}}setTransition(w){return this.stylesheet.transition=Object.assign({},this.stylesheet.transition,w),this.transition=this.stylesheet.transition,this}getTransition(){return Object.assign({},this.stylesheet.transition)}setWorldview(w){w!==this._worldview&&(this._worldview=w,this.dispatcher.broadcast("setWorldview",this._worldview),this.reloadSources())}serialize(){this._checkLoaded();const w=this.getTerrain(),C=w&&this.terrain&&this.terrain.scope===this.scope?w:this.stylesheet.terrain;return o.df({version:this.stylesheet.version,name:this.stylesheet.name,metadata:this.stylesheet.metadata,fragment:this.stylesheet.fragment,iconsets:this.stylesheet.iconsets,featuresets:this.stylesheet.featuresets,imports:this._serializeImports(),schema:this.stylesheet.schema,camera:this.stylesheet.camera,light:this.stylesheet.light,lights:this.stylesheet.lights,terrain:C,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)},O=>O!==void 0)}_updateFilteredLayers(w){for(const C of Object.values(this._mergedLayers))w(C)&&this._updateLayer(C)}_updateLayer(w){this._changes.updateLayer(w);const C=this.getLayerSourceCache(w),O=o.F(w.source,w.scope),U=this._changes.getUpdatedSourceCaches();w.source&&!U[O]&&C&&C.getSource().type!=="raster"&&(this._changes.updateSourceCache(O,"reload"),C.pause()),w.invalidateCompiledFilter()}_flattenAndSortRenderedFeatures(w){const C=se=>this._mergedLayers[se].is3D(!!this.terrain),O=this.order,U={},Y=[];for(let se=O.length-1;se>=0;se--){const pe=O[se];if(C(pe)){U[pe]=se;for(const je of w){const Ee=je[pe];if(Ee)for(const He of Ee)Y.push(He)}}}Y.sort((se,pe)=>pe.intersectionZ-se.intersectionZ);const Z=[];for(let se=O.length-1;se>=0;se--){const pe=O[se];if(C(pe))for(let je=Y.length-1;je>=0;je--){const Ee=Y[je].feature;if(Ee.layer&&U[Ee.layer.id]{if(J_.has(Ee.type))return;const He=this.getOwnLayerSourceCache(Ee),qe=Y[He.id]=Y[He.id]||{sourceCache:He,layers:{},has3DLayers:!1};Ee.is3D(!!this.terrain)&&(qe.has3DLayers=!0),qe.layers[Ee.fqid]=qe.layers[Ee.fqid]||{styleLayer:Ee,targets:[]},qe.layers[Ee.fqid].targets.push({filter:U})};if(C&&C.layers){if(!Array.isArray(C.layers))return this.fire(new o.B(new Error("parameters.layers must be an Array."))),[];for(const Ee of C.layers){const He=this._layers[Ee];if(!He)return this.fire(new o.B(new Error(`The layer '${Ee}' does not exist in the map's style and cannot be queried for features.`))),[];Z(He)}}else for(const Ee in this._layers)Z(this._layers[Ee]);const se=this._queryRenderedFeatures(w,Y,O),pe=this._flattenAndSortRenderedFeatures(se),je=[];for(const Ee of pe)o.dh(Ee.layer.id)===this.scope&&je.push(Ee);return je}queryRenderedFeatureset(w,C,O){let U;C&&!Array.isArray(C)&&C.filter&&(this._validate(Ms,"queryRenderedFeatures.filter",C.filter,null,C),U=o.dg(C.filter));const Y="mock",Z=[];if(C&&C.target)Z.push(Object.assign({},C,{targetId:Y,filter:U}));else{const Ee=this.getFeaturesetDescriptors();for(const He of Ee)Z.push({targetId:Y,filter:U,target:He});for(const{style:He}of this.fragments){const qe=He.getFeaturesetDescriptors();for(const et of qe)Z.push({targetId:Y,filter:U,target:et})}}const se=this.queryRenderedTargets(w,Z,O),pe=[],je=new Set;for(const Ee of se)for(const He of Ee.variants[Y])cu(He,Ee,je)||pe.push(new o.di(Ee,He));return pe}queryRenderedTargets(w,C,O){const U={},Y=(se,pe,je,Ee)=>{const He=U[pe.id]=U[pe.id]||{sourceCache:pe,layers:{},has3DLayers:!1};if(He.layers[se.fqid]=He.layers[se.fqid]||{styleLayer:se,targets:[]},se.is3D(!!this.terrain)&&(He.has3DLayers=!0),!Ee)return je.uniqueFeatureID=!1,void He.layers[se.fqid].targets.push(je);He.layers[se.fqid].targets.push(Object.assign({},je,{namespace:Ee.namespace,properties:Ee.properties,uniqueFeatureID:Ee.uniqueFeatureID}))};for(const se of C)if("featuresetId"in se.target){const{featuresetId:pe,importId:je}=se.target,Ee=this.getFragmentStyle(je);if(!Ee||!Ee._featuresetSelectors)continue;const He=Ee._featuresetSelectors[pe];if(!He){this.fire(new o.B(new Error(`The featureset '${pe}' does not exist in the map's style and cannot be queried for features.`)));continue}for(const qe of He){const et=Ee.getOwnLayer(qe.layerId);et&&!J_.has(et.type)&&Y(et,Ee.getOwnLayerSourceCache(et),se,qe)}}else if("layerId"in se.target){const{layerId:pe}=se.target,je=this.getLayer(pe);if(!je||J_.has(je.type))continue;Y(je,this.getLayerSourceCache(je),se)}const Z=this._queryRenderedFeatures(w,U,O);return this._flattenAndSortRenderedFeatures(Z)}_queryRenderedFeatures(w,C,O){const U=[],Y=!!this.map._showQueryGeometry,Z=No.createFromScreenPoints(w,O);for(const se in C){const pe=Sg(Z,C[se],this._availableImages,O,Y,this.getActualScope());Object.keys(pe).length&&U.push(pe)}if(this.placement)for(const se in C){if(C[se].sourceCache._renderSourceType!==o.b4.Symbol)continue;const pe=Eo(Z.screenGeometry,C[se],this._availableImages,this.placement.collisionIndex,this.placement.retainedQueryData,this.map.getWorldview());Object.keys(pe).length&&U.push(pe)}return U}querySourceFeatures(w,C){const O=C&&C.filter;O&&this._validate(Ms,"querySourceFeatures.filter",O,null,C);let U=[];const Y=this.getOwnSourceCaches(w);for(const Z of Y)U=U.concat(po(Z,C));return U}addSourceType(w,C,O){return mu.getSourceType(w)?O(new Error(`A source type called "${w}" already exists.`)):(mu.setSourceType(w,C),C.workerSourceURL?void this.dispatcher.broadcast("loadWorkerSource",{name:w,url:C.workerSourceURL},O):O(null,null))}getFlatLight(){return this.light.getLight()}setFlatLight(w,C,O={}){this._checkLoaded();const U=this.light.getLight();let Y=!1;for(const se in w)if(!o.b6(w[se],U[se])){Y=!0;break}if(!Y)return;const Z=this._getTransitionParameters();this.light.setLight(w,C,O),this.light.updateTransitions(Z)}getTerrain(){return this.terrain&&this.terrain.drapeRenderMode===1?this.terrain.get():null}setTerrainForDraping(){this.setTerrain({source:"",exaggeration:0},0)}checkCanvasFingerprintNoise(){this.disableElevatedTerrain===void 0&&(this.disableElevatedTerrain=o.o.hasCanvasFingerprintNoise(),this.disableElevatedTerrain&&o.w("Terrain and hillshade are disabled because of Canvas2D limitations when fingerprinting protection is enabled (e.g. in private browsing mode)."))}setTerrain(w,C=1){if(this._checkLoaded(),!w)return this.terrainSetForDrapingOnly()||(delete this.terrain,this.map.transform.projection.requiresDraping&&this.setTerrainForDraping()),C===0&&delete this.terrain,w===null?this.stylesheet.terrain=null:delete this.stylesheet.terrain,this._force3DLayerUpdate(),void(this._markersNeedUpdate=!0);this.checkCanvasFingerprintNoise();let O=w;const U=!("source"in w)||w.source==null;if(C===1){if(this.disableElevatedTerrain)return;if("source"in O&&typeof O.source=="object"){const se="terrain-dem-src";this.addSource(se,O.source),O=o.d9(O),O=Object.assign(O,{source:se})}const Y=Object.assign({},O),Z={};if(this.terrain&&U){Y.source=this.terrain.get().source;const se=this.terrain?this.getFragmentStyle(this.terrain.scope):null;se&&(Z.style=se.serialize())}if(this._validate(it,"terrain",Y,Z))return}if(!this.terrain||this.terrain.scope!==this.scope&&!U||this.terrain&&C!==this.terrain.drapeRenderMode){if(!O)return;this._createTerrain(O,C),this.fire(new o.C("data",{dataType:"style"}))}else{const Y=this.terrain,Z=Y.get();for(const se of Object.keys(o.a8.terrain))!O.hasOwnProperty(se)&&o.a8.terrain[se].default&&(O[se]=o.a8.terrain[se].default);for(const se in w)if(!o.b6(w[se],Z[se])){Y.set(w,this.options),this.stylesheet.terrain=w;const pe=this._getTransitionParameters({duration:0});Y.updateTransitions(pe),this.fire(new o.C("data",{dataType:"style"}));break}}this.mergeTerrain(),this.updateDrapeFirstLayers(),this._markersNeedUpdate=!0}_createFog(w){const C=this.fog=new Wi(w,this.map.transform,this.scope,this.options);this.stylesheet.fog=C.get();const O=this._getTransitionParameters({duration:0});C.updateTransitions(O)}_createSnow(w){const C=this.snow=new $i(w,this.map.transform,this.scope,this.options);this.stylesheet.snow=C.get();const O=this._getTransitionParameters({duration:0});C.updateTransitions(O)}_createRain(w){const C=this.rain=new Ta(w,this.map.transform,this.scope,this.options);this.stylesheet.rain=C.get();const O=this._getTransitionParameters({duration:0});C.updateTransitions(O)}_updateMarkersOpacity(){this.map._markers.length!==0&&this.map._requestDomTask(()=>{for(const w of this.map._markers)w._evaluateOpacity()})}getFog(){return this.fog?this.fog.get():null}setFog(w){if(this._checkLoaded(),!w)return delete this.fog,delete this.stylesheet.fog,void(this._markersNeedUpdate=!0);if(this.fog){const C=this.fog;if(!o.b6(C.get(),w)){C.set(w,this.options),this.stylesheet.fog=C.get();const O=this._getTransitionParameters({duration:0});C.updateTransitions(O)}}else this._createFog(w);this._markersNeedUpdate=!0}getSnow(){return this.snow?this.snow.get():null}setSnow(w){if(this._checkLoaded(),!w)return delete this.snow,void delete this.stylesheet.snow;if(this.snow){const C=this.snow;if(!o.b6(C.get(),w)){C.set(w,this.options),this.stylesheet.snow=C.get();const O=this._getTransitionParameters({duration:0});C.updateTransitions(O)}}else this._createSnow(w);this._markersNeedUpdate=!0}getRain(){return this.rain?this.rain.get():null}setRain(w){if(this._checkLoaded(),!w)return delete this.rain,void delete this.stylesheet.rain;if(this.rain){const C=this.rain;if(!o.b6(C.get(),w)){C.set(w,this.options),this.stylesheet.rain=C.get();const O=this._getTransitionParameters({duration:0});C.updateTransitions(O)}}else this._createRain(w);this._markersNeedUpdate=!0}_reloadColorTheme(){const w=()=>{for(const U in this._layers)this._layers[U].lut=this._styleColorTheme.lut;for(const U in this._sourceCaches)this._sourceCaches[U].clearTiles()},C=this._styleColorTheme.colorThemeOverride?this._styleColorTheme.colorThemeOverride:this._styleColorTheme.colorTheme;if(!C)return this._styleColorTheme.lut=null,void w();const O=this._evaluateColorThemeData(C);this._loadColorTheme(O).then(()=>{this.fire(new o.C("colorthemeset")),w()}).catch(U=>{o.w(`Couldn't set color theme: ${U}`)})}setColorTheme(w){this._checkLoaded(),this._styleColorTheme.colorThemeOverride&&o.w("Note: setColorTheme is called on a style with a color-theme override, the passed color-theme won't be visible."),this._styleColorTheme.colorTheme=w,this._reloadColorTheme()}setImportColorTheme(w,C){const O=this.getFragmentStyle(w);O&&(O._styleColorTheme.colorThemeOverride=C,O._reloadColorTheme())}_getTransitionParameters(w){return{now:o.o.now(),transition:Object.assign(this.transition,w)}}updateDrapeFirstLayers(){if(!this.terrain)return;const w=[],C=[];for(const O of this._mergedOrder)this.isLayerDraped(this._mergedLayers[O])?w.push(O):C.push(O);this._drapedFirstOrder=[],this._drapedFirstOrder.push(...w),this._drapedFirstOrder.push(...C)}_createTerrain(w,C){const O=this.terrain=new Xt(w,C,this.scope,this.options,this.map.getWorldview());C===1&&(this.stylesheet.terrain=w),this.mergeTerrain(),this.updateDrapeFirstLayers(),this._force3DLayerUpdate();const U=this._getTransitionParameters({duration:0});O.updateTransitions(U)}_force3DLayerUpdate(){for(const w in this._layers){const C=this._layers[w];C.type==="fill-extrusion"&&this._updateLayer(C)}}_forceSymbolLayerUpdate(){for(const w in this._layers){const C=this._layers[w];C.type==="symbol"&&this._updateLayer(C)}}_validate(w,C,O,U,Y={}){if(Y&&Y.validate===!1)return!1;const Z=Object.assign({},this.serialize());return l0(this,w.call(Zn,Object.assign({key:C,style:Z,value:O,styleSpec:o.a8},U)))}_remove(){this._request&&(this._request.cancel(),this._request=null),this._spriteRequest&&(this._spriteRequest.cancel(),this._spriteRequest=null),o.dj.off("pluginStateChange",this._rtlTextPluginCallback);for(const w in this._mergedLayers)this._mergedLayers[w].setEventedParent(null);for(const w in this._mergedSourceCaches)this._mergedSourceCaches[w].clearTiles(),this._mergedSourceCaches[w].setEventedParent(null);this.imageManager.removeScope(this.scope),this.imageManager.imageAtlasCache.clear(),this.setEventedParent(null),delete this.fog,delete this.snow,delete this.rain,delete this.terrain,delete this.ambientLight,delete this.directionalLight,this.indoorManager.destroy(),this.isRootStyle()&&(this.imageManager.setEventedParent(null),this.imageManager.destroy(),this.modelManager.setEventedParent(null),this.modelManager.destroy(),this.dispatcher.remove())}clearSource(w){const C=this.getSourceCaches(w);for(const O of C)O.clearTiles()}clearSources(){for(const w in this._mergedSourceCaches)this._mergedSourceCaches[w].clearTiles()}clearLayers(){for(const w in this._mergedLayers){const C=this._mergedLayers[w];C._clear&&C._clear()}}reloadSource(w){const C=this.getSourceCaches(w);for(const O of C)O.resume(),O.reload()}reloadSources(){for(const w of this.getSources())w.reload&&w.reload()}reloadModels(){this.modelManager.reloadModels(""),this.forEachFragmentStyle(w=>{w.modelManager.reloadModels(w.scope)})}updateSources(w){let C;this.directionalLight&&(C=o0(this.directionalLight));const O=new Set,U=new Set,Y=new Set;for(const Z in this._mergedLayers){const se=this._mergedLayers[Z];se.type==="building"?O.add(se.source):se.type==="raster"&&se.paint&&se.paint.get("raster-elevation-reference")==="ground"&&Y.add(se.source),se.hasElevation()&&!U.has(se.source)&&U.add(se.source)}for(const Z in this._mergedSourceCaches){const se=this._mergedSourceCaches[Z],pe=U.has(se._source.id);se._isRasterElevatedOverTerrain=Y.has(se._source.id),O.has(se._source.id)&&(se._source.reparseOverscaled=!1),se.update(w,void 0,void 0,C,pe)}}_generateCollisionBoxes(){for(const w in this._sourceCaches){const C=this._sourceCaches[w];C.resume(),C.reload()}}_handleLayerOrderChange(){this._requestFullLabelPlacement(),this.fire(new o.C("neworder"))}_requestFullLabelPlacement(){this.pauseablePlacement||(this.pauseablePlacement=new oy),this.pauseablePlacement.requestFullPlacement()}_setLabelPlacementStale(){this.placement&&this.placement.setStale()}_updatePlacement(w,C,O,U,Y){this.pauseablePlacement||(this.pauseablePlacement=new oy);let Z=!1,se=!1;const pe={},je={};for(const ot of this._mergedOrder){const bt=this._mergedLayers[ot];if(bt.type!=="symbol")continue;const vt=o.F(bt.source,bt.scope);let Pt=pe[vt];if(!Pt){const jt=this.getLayerSourceCache(bt);if(!jt)continue;const ys=jt.getRenderableIds(!0).map(Qt=>jt.getTileByID(Qt));je[vt]=ys.slice(),Pt=pe[vt]=ys.sort((Qt,gs)=>gs.tileID.overscaledZ-Qt.tileID.overscaledZ||(Qt.tileID.isLessThan(gs.tileID)?-1:1))}const Ft=this.crossTileSymbolIndex.addLayer(bt,Pt,w.center.lng,w.projection);Z=Z||Ft}this.crossTileSymbolIndex.pruneUnusedLayers(this._mergedOrder);const Ee=!!(this.placement&&!w.equals(this.placement.transform)),He=!!(this.placement&&(this.placement.lastReplacementSourceUpdateTime!==0&&!Y||this.placement.lastReplacementSourceUpdateTime!==Y.updateTime)),qe=Ee||He||Z,et=(qe||this.pauseablePlacement.isStale())&&O===0,ct=this.pauseablePlacement.isDone()&&!this.placement.stillRecent(o.o.now(),w.zoom)&&O!==0;if((this.pauseablePlacement.isFullPlacementRequested()||!this.pauseablePlacement.placement||et||ct)&&(this.pauseablePlacement=this.pauseablePlacement.startNewPlacement(w,this._mergedOrder,C,O,U,this.placement,this.fog&&w.projection.supportsFog?this.fog.state:null,this._buildingIndex),this.map.painter)){const ot=this.map.painter.maxFrontCutoffRawStart;if(ot>0){const bt=180*w.pitch/Math.PI;if(bt>=15){const vt=Math.min(1,Math.max(0,(bt-15)/5)),Pt=vt*vt*(3-2*vt);this.pauseablePlacement.placement.frontCutoffStart=-.5*(1-Pt)+ot*Pt}}}if(this.pauseablePlacement.isDone()?qe&&O!==0&&this.pauseablePlacement.setStale():(this.pauseablePlacement.continuePlacement(this._mergedOrder,this._mergedLayers,pe,je,this.map.painter.scaleFactor),this.pauseablePlacement.isDone()&&(this.placement=this.pauseablePlacement.commit(o.o.now()),se=!0),Z&&this.pauseablePlacement.setStale()),se||Z){this._buildingIndex.onNewFrame(w.zoom);for(let ot=0;otY===w.id)!==-1)return void this.fire(new o.B(new Error(`Import with id '${w.id}' already exists in the map's style.`)));if(!C)return O.push(w),this._loadImports([w],!0);const U=O.findIndex(({id:Y})=>Y===C);return U===-1&&this.fire(new o.B(new Error(`Import with id "${C}" does not exist on this map.`))),this.stylesheet.imports=O.slice(0,U).concat(w).concat(O.slice(U)),this._loadImports([w],!0,C)}updateImport(w,C){this._checkLoaded();const O=this.stylesheet.imports||[],U=this.getImportIndex(w);return U===-1?this:typeof C=="string"?(this.setImportUrl(w,C),this):(C.url&&C.url!==O[U].url&&this.setImportUrl(w,C.url),o.b6(C.config,O[U].config)||this.setImportConfig(w,C.config,C.data.schema),o.b6(C.data,O[U].data)||this.setImportData(w,C.data),this)}moveImport(w,C){this._checkLoaded();let O=this.stylesheet.imports||[];const U=this.getImportIndex(w);if(U===-1)return this;const Y=this.getImportIndex(C);if(Y===-1)return this;const Z=O[U],se=this.fragments[U];return O=O.filter(({id:pe})=>pe!==w),this.fragments=this.fragments.filter(({id:pe})=>pe!==w),this.stylesheet.imports=O.slice(0,Y).concat(Z).concat(O.slice(Y)),this.fragments=this.fragments.slice(0,Y).concat(se).concat(this.fragments.slice(Y)),this.mergeLayers(),this}setImportUrl(w,C){this._checkLoaded();const O=this.stylesheet.imports||[],U=this.getImportIndex(w);if(U===-1)return this;O[U].url=C;const Y=this.fragments[U];return Y.style=this._createFragmentStyle(O[U]),Y.style.on("style.import.load",()=>this.mergeAll()),Y.style.loadURL(C),this}setImportData(w,C){this._checkLoaded();const O=this.getImportIndex(w),U=this.stylesheet.imports||[];return O===-1?this:C?(this.fragments[O].style.setState(C),this._reloadImports(),this):(delete U[O].data,this.setImportUrl(w,U[O].url))}setImportConfig(w,C,O){this._checkLoaded();const U=this.getImportIndex(w),Y=this.stylesheet.imports||[];if(U===-1)return this;C?Y[U].config=C:delete Y[U].config;const Z=this.fragments[U];O&&Z.style.stylesheet&&(Z.style.stylesheet.schema=O);const se=Z.style.stylesheet&&Z.style.stylesheet.schema;return Z.config=C,Z.style.updateConfig(C,se),this.updateConfigDependencies(),this}removeImport(w){this._checkLoaded();const C=this.stylesheet.imports||[],O=this.getImportIndex(w);O!==-1&&(C.splice(O,1),this.fragments[O].style._remove(),this.fragments.splice(O,1),this._reloadImports())}getImportIndex(w){const C=(this.stylesheet.imports||[]).findIndex(O=>O.id===w);return C===-1&&this.fire(new o.B(new Error(`Import '${w}' does not exist in the map's style and cannot be updated.`))),C}getLayer(w){return this._mergedLayers[w]}getSources(){const w=[];for(const C in this._mergedOtherSourceCaches){const O=this._mergedOtherSourceCaches[C];O&&w.push(O.getSource())}return w}getSource(w,C){const O=this.getSourceCache(w,C);return O&&O.getSource()}getLayerSource(w){const C=this.getLayerSourceCache(w);return C&&C.getSource()}getSourceCache(w,C){const O=o.F(w,C);return this._mergedOtherSourceCaches[O]}getLayerSourceCache(w){const C=o.F(w.source,w.scope);return w.type==="symbol"?this._mergedSymbolSourceCaches[C]:w.type==="fill-extrusion"&&this._mergedFillExtrusionSourceCaches[C]||this._mergedOtherSourceCaches[C]}getSourceCaches(w){if(w==null)return Object.values(this._mergedSourceCaches);const C=[];return this._mergedOtherSourceCaches[w]&&C.push(this._mergedOtherSourceCaches[w]),this._mergedSymbolSourceCaches[w]&&C.push(this._mergedSymbolSourceCaches[w]),this._mergedFillExtrusionSourceCaches[w]&&C.push(this._mergedFillExtrusionSourceCaches[w]),C}updateSourceCaches(){const w=this._changes.getUpdatedSourceCaches();for(const C in w){const O=w[C];O==="reload"?this.reloadSource(C):O==="clear"&&this.clearSource(C)}}updateLayers(w){const C=this._changes.getUpdatedPaintProperties();for(const O of C){const U=this.getLayer(O);U&&U.updateTransitions(w)}}getGlyphsUrl(){return this.stylesheet.glyphs}setGlyphsUrl(w){this.stylesheet.glyphs=w,this.glyphManager.setURL(w)}getImages(w,C,O){this.imageManager.getImages(C.images,C.scope,O),this._updateTilesForChangedImages();const U=Z=>{if(Z){const se=C.images.map(pe=>o.I.toString(pe));Z.setDependencies(C.tileID.key,C.type,se)}},Y=o.F(C.source,C.scope);U(this._mergedOtherSourceCaches[Y]),U(this._mergedSymbolSourceCaches[Y]),C.images.some(Z=>Z.iconsetId)&&this.fire(new o.C("data",{dataType:"style"}))}rasterizeImages(w,C,O){this.imageManager.rasterizeImages(C,O)}checkAtlasCache(w,C,O){const U=this.imageManager.imageAtlasCache.findCachedAtlas(C.descriptor);O(null,U&&U.contentDescriptor?{iconPositions:U.iconPositions,patternPositions:U.patternPositions,sourceHash:U.contentDescriptor.hash}:null)}getGlyphs(w,C,O){this.glyphManager.getGlyphs(C.stacks,O)}getOwnSourceCache(w){return this._otherSourceCaches[w]}getOwnLayerSourceCache(w){return w.type==="symbol"?this._symbolSourceCaches[w.source]:w.type==="fill-extrusion"&&this._fillExtrusionSourceCaches[w.source]||this._otherSourceCaches[w.source]}getOwnSourceCaches(w){const C=[];return this._otherSourceCaches[w]&&C.push(this._otherSourceCaches[w]),this._symbolSourceCaches[w]&&C.push(this._symbolSourceCaches[w]),this._fillExtrusionSourceCaches[w]&&C.push(this._fillExtrusionSourceCaches[w]),C}_isSourceCacheLoaded(w){const C=this.getOwnSourceCaches(w);return C.length===0?(this.fire(new o.B(new Error(`There is no source with ID '${w}'`))),!1):C.every(O=>O.loaded())}has3DLayers(){return this._has3DLayers}hasSymbolLayers(){return this._hasSymbolLayers}hasCircleLayers(){return this._hasCircleLayers}isLayerClipped(w,C){if(!this._clipLayerPresent&&w.type!=="fill-extrusion"&&w.type!=="building")return!1;const O=w.type==="fill-extrusion"&&(w.sourceLayer==="building"||w.sourceLayer==="procedural_buildings"),U=w.type==="building";if(w.is3D(!!this.terrain)){if(O||U||C&&C.type==="batched-model"||w.type==="model")return!0}else if(w.type==="symbol")return!0;return!1}_clearWorkerCaches(){this.dispatcher.broadcast("clearCaches")}getBOMObject(){}destroy(){this._clearWorkerCaches(),this.imageManager.imageAtlasCache.clear(),this.fragments.forEach(w=>{w.style._remove()}),this.terrainSetForDrapingOnly()&&(delete this.terrain,delete this.stylesheet.terrain)}}mu.getSourceType=function(D){return ay[D]},mu.setSourceType=function(D,w){ay[D]=w},mu.registerForPluginStateChange=o.dk;var c0=` #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`,ew=` #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;}`,d0=` #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`,Ab="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;}",Dj=` #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`,Rj=`#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`,u1=`#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`,h1=`#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`,Oj=`#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;}`,Tb=`#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`,np=`#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 ch=/#include\s+"([^"]+)"/g,sr=/#pragma mapbox: ([\w\-]+) ([\w]+) ([\w]+) ([\w]+)/g,m1=/\b[A-Za-z_][A-Za-z0-9_]*\b/g,p1=new Set(["ifdef","ifndef","elif","if","defined"]),sv=new Set;xx(c0,sv),xx(d0,sv),xx(ew,sv);const Bp={"_prelude_fog.vertex.glsl":Rj,"_prelude_terrain.vertex.glsl":Dj,"_prelude_shadow.vertex.glsl":Tb,"_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":u1,"_prelude_shadow.fragment.glsl":np,"_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":h1,"_prelude_raster_particle.glsl":Oj},ly={};no("",Dj),no(u1,Rj),no(np,Tb),no(h1,""),no(Oj,"");const u0=no(ew,d0),Eb=c0,nv=[` #if defined(GL_EXT_blend_func_extended) && defined(DUAL_SOURCE_BLENDING) #extension GL_EXT_blend_func_extended : require #endif`,"precision mediump float;",Eb,u0.fragmentSource].join(` `),Fj=["precision highp float;",Eb,u0.vertexSource].join(` `);var tw={background:no(`#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:no(`#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:no(`#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:no(`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:no("void main() {}","in vec3 a_pos_3f;uniform mat4 u_matrix;void main() {gl_Position=u_matrix*vec4(a_pos_3f,1.0);}"),circle:no(`#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:no("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:no(`#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:no(`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:no("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:no("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:no("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:no("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:no(`#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:no(`#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:no(`#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:no(`#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:no(`#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:no(`#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:no(`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:no(`#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:no("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:no(`#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:no(`#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:no(`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:no(`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:no(`#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:no(`#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:no(`#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:no(`#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:no(`#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:no("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:no("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:no(`#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:no(`#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:no(`#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:no("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:no(`#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 }`,Ab),skyboxGradient:no(`#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 }`,Ab),skyboxCapture:no(` 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:no(`#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:no(`#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:no(`#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:no("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:no(`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:no("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:no("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:no("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:no("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 xx(D,w){const C=D.split(` `);for(let O of C){if(O=O.trimStart(),O[0]!=="#"||!O.includes("if")||O.startsWith("#endif"))continue;const U=O.match(m1);if(U)for(const Y of U)p1.has(Y)||w.add(Y)}}function aS(D){return new Set(["uint","int","uvec2","ivec2","uvec3","ivec3","uvec4","ivec4"]).has(D)}function no(D,w){const C=new Set,O=[],U=[];D=D.replace(ch,(Z,se)=>(U.push(se),"")),w=w.replace(ch,(Z,se)=>(O.push(se),""));let Y=new Set(sv);xx(D,Y),xx(w,Y);for(const Z of[...O,...U])ly[Z]||(ly[Z]=new Set,xx(Bp[Z],ly[Z])),Y=new Set([...Y,...ly[Z]]);return{fragmentSource:D=D.replace(sr,(Z,se,pe,je,Ee)=>(C.add(Ee),se==="define"?` #ifndef HAS_UNIFORM_u_${Ee} ${aS(je)?"flat ":""}in ${pe} ${je} ${Ee}; #else uniform ${pe} ${je} u_${Ee}; #endif `:se==="initialize"?` #ifdef HAS_UNIFORM_u_${Ee} ${pe} ${je} ${Ee} = u_${Ee}; #endif `:se==="define-attribute"?` #ifdef HAS_ATTRIBUTE_a_${Ee} in ${pe} ${je} ${Ee}; #endif `:se==="initialize-attribute"?"":void 0)),vertexSource:w=w.replace(sr,(Z,se,pe,je,Ee)=>{const He=`MATERIAL_ATTRIBUTE_OFFSET_${Ee}`,qe=je==="float"?"vec2":je,et=`GET_ATTRIBUTE_${qe}(a_${Ee}, materialInfo, ${He})`,ct=Ee.match(/color/)?"color":qe;return se==="define-attribute-vertex-shader-only"?` #ifdef HAS_ATTRIBUTE_a_${Ee} in ${pe} ${je} a_${Ee}; #endif `:C.has(Ee)?se==="define"?` #ifndef HAS_UNIFORM_u_${Ee} uniform lowp float u_${Ee}_t; #if !defined(${He}) in ${pe} ${qe} a_${Ee}; #endif ${aS(je)?"flat ":""}out ${pe} ${je} ${Ee}; #else uniform ${pe} ${je} u_${Ee}; #endif `:se==="initialize"?ct==="vec4"||ct==="uvec4"?` #ifndef HAS_UNIFORM_u_${Ee} ${Ee} = a_${Ee}; #else ${pe} ${je} ${Ee} = u_${Ee}; #endif `:` #if !defined(HAS_UNIFORM_u_${Ee}) #ifdef ${He} ${Ee} = unpack_mix_${ct}(${et}, u_${Ee}_t); #else ${Ee} = unpack_mix_${ct}(a_${Ee}, u_${Ee}_t); #endif #else ${pe} ${je} ${Ee} = u_${Ee}; #endif `:se==="define-attribute"?` #ifdef HAS_ATTRIBUTE_a_${Ee} in ${pe} ${je} a_${Ee}; out ${pe} ${je} ${Ee}; #endif `:se==="initialize-attribute"?` #ifdef HAS_ATTRIBUTE_a_${Ee} ${Ee} = a_${Ee}; #endif `:void 0:se==="define"?` #ifndef HAS_UNIFORM_u_${Ee} uniform lowp float u_${Ee}_t; #if !defined(${He}) in ${pe} ${qe} a_${Ee}; #endif #else uniform ${pe} ${je} u_${Ee}; #endif `:se==="define-instanced"?ct==="mat4"?` #ifdef INSTANCED_ARRAYS in vec4 a_${Ee}0; in vec4 a_${Ee}1; in vec4 a_${Ee}2; in vec4 a_${Ee}3; #else uniform ${pe} ${je} u_${Ee}; #endif `:` #ifdef INSTANCED_ARRAYS in ${pe} ${qe} a_${Ee}; #else uniform ${pe} ${je} u_${Ee}; #endif `:se==="initialize-attribute-custom"?` #ifdef HAS_ATTRIBUTE_a_${Ee} ${pe} ${je} ${Ee} = a_${Ee}; #endif `:ct==="vec4"||ct==="uvec4"?` #ifndef HAS_UNIFORM_u_${Ee} #ifdef ${He} ${pe} ${je} ${Ee} = ${et}; #else ${pe} ${je} ${Ee} = a_${Ee}; #endif #else ${pe} ${je} ${Ee} = u_${Ee}; #endif `:` #ifndef HAS_UNIFORM_u_${Ee} #ifdef ${He} ${pe} ${je} ${Ee} = unpack_mix_${ct}(${et}, u_${Ee}_t); #else ${pe} ${je} ${Ee} = unpack_mix_${ct}(a_${Ee}, u_${Ee}_t); #endif #else ${pe} ${je} ${Ee} = u_${Ee}; #endif `}),usedDefines:Y,vertexIncludes:O,fragmentIncludes:U}}class TN{constructor(){this.boundProgram=null,this.boundLayoutVertexBuffer=null,this.boundPaintVertexBuffers=[],this.boundIndexBuffer=null,this.boundVertexOffset=null,this.boundDynamicVertexBuffers=[],this.vao=null}bind(w,C,O,U,Y,Z,se,pe){this.context=w;let je=this.boundPaintVertexBuffers.length!==U.length;for(let He=0;!je&&He{const ys=Ft.paint.get("hillshade-shadow-color"),Qt=Ft.paint.get("hillshade-shadow-color-use-theme").constantOr("default")==="none",gs=Ft.paint.get("hillshade-highlight-color"),$t=Ft.paint.get("hillshade-highlight-color-use-theme").constantOr("default")==="none",Zt=Ft.paint.get("hillshade-accent-color"),hs=Ft.paint.get("hillshade-accent-color-use-theme").constantOr("default")==="none",Us=Ft.paint.get("hillshade-emissive-strength");let Cs=o.ap(Ft.paint.get("hillshade-illumination-direction"));if(Ft.paint.get("hillshade-illumination-anchor")==="viewport")Cs-=vt.transform.angle;else if(vt.style&&vt.style.enable3dLights()&&vt.style.directionalLight){const an=vt.style.directionalLight.properties.get("direction"),An=o.cP(an.x,an.y,an.z);Cs=o.ap(An[1])}const hn=!vt.options.moving;return{u_matrix:jt||vt.transform.calculateProjMatrix(Pt.tileID.toUnwrapped(),hn),u_image:0,u_latrange:iS(0,Pt.tileID),u_light:[Ft.paint.get("hillshade-exaggeration"),Cs],u_shadow:ys.toPremultipliedRenderColor(Qt?null:Ft.lut),u_highlight:gs.toPremultipliedRenderColor($t?null:Ft.lut),u_emissive_strength:Us,u_accent:Zt.toPremultipliedRenderColor(hs?null:Ft.lut)}})(D,C,O,D.terrain?w.projMatrix:null);D.uploadCommonUniforms(se,qe,w.toUnwrapped());const{tileBoundsBuffer:ct,tileBoundsIndexBuffer:ot,tileBoundsSegments:bt}=D.getTileBoundsBuffers(C);qe.draw(D,pe.TRIANGLES,U,Y,Z,ra.disabled,et,O.id,ct,ot,bt)}function oS(D,w,C){if(!w.needsDEMTextureUpload)return;const O=D.context,U=O.gl;O.pixelStoreUnpackPremultiplyAlpha.set(!1),w.demTexture=w.demTexture||D.getTileTexture(C.stride);const Y=C.getPixels();w.demTexture?w.demTexture.update(Y,{premultiply:!1}):w.demTexture=new o.T(O,Y,U.R32F,{premultiply:!1}),w.needsDEMTextureUpload=!1}function W3(D,w,C){const O=D.context,U=O.gl;if(!w.dem)return;const Y=w.dem;if(O.activeTexture.set(U.TEXTURE1),oS(D,w,Y),!w.demTexture)return;w.demTexture.bind(U.NEAREST,U.CLAMP_TO_EDGE);const Z=Y.dim;O.activeTexture.set(U.TEXTURE0);let se=w.hillshadeFBO;if(!se){const qe=new o.T(O,{width:Z,height:Z,data:null},U.RGBA8);qe.bind(U.LINEAR,U.CLAMP_TO_EDGE),se=w.hillshadeFBO=O.createFramebuffer(Z,Z,1,"renderbuffer"),se.colorAttachment0.set(qe.texture)}O.bindFramebuffer.set(se.framebuffer),O.viewport.set([0,0,Z,Z]);const{tileBoundsBuffer:pe,tileBoundsIndexBuffer:je,tileBoundsSegments:Ee}=D.getMercatorTileBoundsBuffers(),He=[];D.linearFloatFilteringSupported()&&He.push("TERRAIN_DEM_FLOAT_FORMAT"),D.terrain&&D.terrain.renderingToTexture&&D.emissiveMode==="mrt-fallback"&&He.push("USE_MRT1"),D.getOrCreateProgram("hillshadePrepare",{defines:He}).draw(D,U.TRIANGLES,Ir.disabled,Na.disabled,wa.unblended,ra.disabled,((qe,et)=>{const ct=et.stride,ot=o.bb();return o.bT(ot,0,o.an,-o.an,0,0,1),o.bx(ot,ot,[0,-o.an,0]),{u_matrix:ot,u_image:1,u_dimension:[ct,ct],u_zoom:qe.overscaledZ}})(w.tileID,Y),C.id,pe,je,Ee),w.needsHillshadePrepare=!1}class vc{constructor(w){this.gl=w.gl,this.default=this.getDefault(),this.current=this.default,this.dirty=!1}get(){return this.current}set(w){}getDefault(){return this.default}setDefault(){this.set(this.default)}}class Mb extends vc{getDefault(){return o.aq.transparent.toNonPremultipliedRenderColor(null)}set(w){const C=this.current;(w.r!==C.r||w.g!==C.g||w.b!==C.b||w.a!==C.a||this.dirty)&&(this.gl.clearColor(w.r,w.g,w.b,w.a),this.current=w,this.dirty=!1)}}class lS extends vc{getDefault(){return 1}set(w){(w!==this.current||this.dirty)&&(this.gl.clearDepth(w),this.current=w,this.dirty=!1)}}class f1 extends vc{getDefault(){return 0}set(w){(w!==this.current||this.dirty)&&(this.gl.clearStencil(w),this.current=w,this.dirty=!1)}}class i6 extends vc{getDefault(){return[!0,!0,!0,!0]}set(w){const C=this.current;(w[0]!==C[0]||w[1]!==C[1]||w[2]!==C[2]||w[3]!==C[3]||this.dirty)&&(this.gl.colorMask(w[0],w[1],w[2],w[3]),this.current=w,this.dirty=!1)}}class yx extends vc{getDefault(){return!0}set(w){(w!==this.current||this.dirty)&&(this.gl.depthMask(w),this.current=w,this.dirty=!1)}}class sw extends vc{getDefault(){return 255}set(w){(w!==this.current||this.dirty)&&(this.gl.stencilMask(w),this.current=w,this.dirty=!1)}}class Lb extends vc{getDefault(){return{func:this.gl.ALWAYS,ref:0,mask:255}}set(w){const C=this.current;(w.func!==C.func||w.ref!==C.ref||w.mask!==C.mask||this.dirty)&&(this.gl.stencilFunc(w.func,w.ref,w.mask),this.current=w,this.dirty=!1)}}class EN extends vc{getDefault(){const w=this.gl;return[w.KEEP,w.KEEP,w.KEEP]}set(w){const C=this.current;(w[0]!==C[0]||w[1]!==C[1]||w[2]!==C[2]||this.dirty)&&(this.gl.stencilOp(w[0],w[1],w[2]),this.current=w,this.dirty=!1)}}class g1 extends vc{getDefault(){return!1}set(w){if(w===this.current&&!this.dirty)return;const C=this.gl;w?C.enable(C.STENCIL_TEST):C.disable(C.STENCIL_TEST),this.current=w,this.dirty=!1}}class x1 extends vc{getDefault(){return[0,1]}set(w){const C=this.current;(w[0]!==C[0]||w[1]!==C[1]||this.dirty)&&(this.gl.depthRange(w[0],w[1]),this.current=w,this.dirty=!1)}}class Cf extends vc{getDefault(){return!1}set(w){if(w===this.current&&!this.dirty)return;const C=this.gl;w?C.enable(C.DEPTH_TEST):C.disable(C.DEPTH_TEST),this.current=w,this.dirty=!1}}class Wd extends vc{getDefault(){return this.gl.LESS}set(w){(w!==this.current||this.dirty)&&(this.gl.depthFunc(w),this.current=w,this.dirty=!1)}}class vx extends vc{getDefault(){return!1}set(w){if(w===this.current&&!this.dirty)return;const C=this.gl;w?C.enable(C.BLEND):C.disable(C.BLEND),this.current=w,this.dirty=!1}}class zj extends vc{getDefault(){const w=this.gl;return[w.ONE,w.ZERO,w.ONE,w.ZERO]}set(w){const C=this.current;(w[0]!==C[0]||w[1]!==C[1]||w[2]!==C[2]||w[3]!==C[3]||this.dirty)&&(this.gl.blendFuncSeparate(w[0],w[1],w[2],w[3]),this.current=w,this.dirty=!1)}}class cS extends vc{getDefault(){return o.aq.transparent.toNonPremultipliedRenderColor(null)}set(w){const C=this.current;(w.r!==C.r||w.g!==C.g||w.b!==C.b||w.a!==C.a||this.dirty)&&(this.gl.blendColor(w.r,w.g,w.b,w.a),this.current=w,this.dirty=!1)}}class eg extends vc{getDefault(){return this.gl.FUNC_ADD}set(w){(w!==this.current||this.dirty)&&(this.gl.blendEquationSeparate(w,w),this.current=w,this.dirty=!1)}}class $p extends vc{getDefault(){return!1}set(w){if(w===this.current&&!this.dirty)return;const C=this.gl;w?C.enable(C.CULL_FACE):C.disable(C.CULL_FACE),this.current=w,this.dirty=!1}}class Bj extends vc{getDefault(){return this.gl.BACK}set(w){(w!==this.current||this.dirty)&&(this.gl.cullFace(w),this.current=w,this.dirty=!1)}}class MN extends vc{getDefault(){return this.gl.CCW}set(w){(w!==this.current||this.dirty)&&(this.gl.frontFace(w),this.current=w,this.dirty=!1)}}let nw=class extends vc{getDefault(){return null}set(D){(D!==this.current||this.dirty)&&(this.gl.useProgram(D),this.current=D,this.dirty=!1)}};class rw extends vc{getDefault(){return this.gl.TEXTURE0}set(w){(w!==this.current||this.dirty)&&(this.gl.activeTexture(w),this.current=w,this.dirty=!1)}}class Up extends vc{getDefault(){const w=this.gl;return[0,0,w.drawingBufferWidth,w.drawingBufferHeight]}set(w){const C=this.current;(w[0]!==C[0]||w[1]!==C[1]||w[2]!==C[2]||w[3]!==C[3]||this.dirty)&&(this.gl.viewport(w[0],w[1],w[2],w[3]),this.current=w,this.dirty=!1)}}class rp extends vc{getDefault(){return null}set(w){if(w===this.current&&!this.dirty)return;const C=this.gl;C.bindFramebuffer(C.FRAMEBUFFER,w),this.current=w,this.dirty=!1}}class dS extends vc{getDefault(){return null}set(w){if(w===this.current&&!this.dirty)return;const C=this.gl;C.bindRenderbuffer(C.RENDERBUFFER,w),this.current=w,this.dirty=!1}}class cy extends vc{getDefault(){return null}set(w){if(w===this.current&&!this.dirty)return;const C=this.gl;C.bindTexture(C.TEXTURE_2D,w),this.current=w,this.dirty=!1}}class aw extends vc{getDefault(){return null}set(w){if(w===this.current&&!this.dirty)return;const C=this.gl;C.bindBuffer(C.ARRAY_BUFFER,w),this.current=w,this.dirty=!1}}class iw extends vc{getDefault(){return null}set(w){const C=this.gl;C.bindBuffer(C.ELEMENT_ARRAY_BUFFER,w),this.current=w,this.dirty=!1}}class LN extends vc{getDefault(){return null}set(w){this.gl&&(w!==this.current||this.dirty)&&(this.gl.bindVertexArray(w),this.current=w,this.dirty=!1)}}class PN extends vc{getDefault(){return 4}set(w){if(w===this.current&&!this.dirty)return;const C=this.gl;C.pixelStorei(C.UNPACK_ALIGNMENT,w),this.current=w,this.dirty=!1}}class IN extends vc{getDefault(){return!1}set(w){if(w===this.current&&!this.dirty)return;const C=this.gl;C.pixelStorei(C.UNPACK_PREMULTIPLY_ALPHA_WEBGL,w),this.current=w,this.dirty=!1}}class ow extends vc{getDefault(){return!1}set(w){if(w===this.current&&!this.dirty)return;const C=this.gl;C.pixelStorei(C.UNPACK_FLIP_Y_WEBGL,w),this.current=w,this.dirty=!1}}class lw extends vc{constructor(w,C){super(w),this.context=w,this.parent=C}getDefault(){return null}}class Pb extends lw{constructor(w,C,O=0){super(w,C),this.attachmentPoint=w.gl.COLOR_ATTACHMENT0+O}setDirty(){this.dirty=!0}set(w){if(w===this.current&&!this.dirty)return;this.context.bindFramebuffer.set(this.parent);const C=this.gl;C.framebufferTexture2D(C.FRAMEBUFFER,this.attachmentPoint,C.TEXTURE_2D,w,0),this.current=w,this.dirty=!1}}class $j extends lw{attachment(){return this.gl.DEPTH_ATTACHMENT}set(w){if(w===this.current&&!this.dirty)return;this.context.bindFramebuffer.set(this.parent);const C=this.gl;C.framebufferRenderbuffer(C.FRAMEBUFFER,this.attachment(),C.RENDERBUFFER,w),this.current=w,this.dirty=!1}}class DN extends lw{attachment(){return this.gl.DEPTH_ATTACHMENT}set(w){if(w===this.current&&!this.dirty)return;this.context.bindFramebuffer.set(this.parent);const C=this.gl;C.framebufferTexture2D(C.FRAMEBUFFER,this.attachment(),C.TEXTURE_2D,w,0),this.current=w,this.dirty=!1}}class K3 extends $j{attachment(){return this.gl.DEPTH_STENCIL_ATTACHMENT}}const Ib=(D,w,C,O)=>({u_matrix:D,u_image0:0,u_image1:1,u_skirt_height:w,u_ground_shadow_factor:C,u_emissive_texture_available:O}),dy=(D,w,C,O,U,Y,Z,se,pe,je,Ee,He,qe,et,ct,ot,bt)=>({u_proj_matrix:Float32Array.from(D),u_globe_matrix:w,u_normalize_matrix:Float32Array.from(O),u_merc_matrix:C,u_zoom_transition:U,u_merc_center:Y,u_image0:0,u_image1:1,u_frustum_tl:Z,u_frustum_tr:se,u_frustum_br:pe,u_frustum_bl:je,u_globe_pos:Ee,u_globe_radius:He,u_viewport:qe,u_grid_matrix:bt?Float32Array.from(bt):new Float32Array(9),u_skirt_height:et,u_far_z_cutoff:ct,u_emissive_texture_available:ot});function cw(D,w){return D!=null&&w!=null&&!(!D.hasData()||!w.hasData())&&D.demTexture!=null&&w.demTexture!=null&&D.tileID.key!==w.tileID.key}const Wh=new class{constructor(){this.operations={}}newMorphing(D,w,C,O,U){if(D in this.operations){const Y=this.operations[D];Y.to.tileID.key!==C.tileID.key&&(Y.queued=C)}else this.operations[D]={startTime:O,phase:0,duration:U,from:w,to:C,queued:null}}getMorphValuesForProxy(D){if(!(D in this.operations))return null;const w=this.operations[D];return{from:w.from,to:w.to,phase:w.phase}}update(D){for(const w in this.operations){const C=this.operations[w];for(C.phase=(D-C.startTime)/C.duration;C.phase>=1||!this._validOp(C);)if(!this._nextOp(C,D)){delete this.operations[w];break}}}_nextOp(D,w){return!!D.queued&&(D.from=D.to,D.to=D.queued,D.queued=null,D.phase=0,D.startTime=w,!0)}_validOp(D){return D.from.hasData()&&D.to.hasData()}},dw={0:null,1:"TERRAIN_VERTEX_MORPHING"};function Db(D,w,C){if(w===0)return 0;const O=w<1&&C===514?.25/w:1;return 6*Math.pow(1.5,22-D)*Math.max(w,1)*O}function ke(D,w){const C=1<({u_matrix:D});function yt(D,w,C,O,U){if(U>0){const Y=o.o.now(),Z=(Y-D.timeAdded)/U,se=w?(Y-w.timeAdded)/U:-1,pe=C.getSource(),je=O.coveringZoomLevel({tileSize:pe.tileSize,roundZoom:pe.roundZoom}),Ee=!w||Math.abs(w.tileID.overscaledZ-je)>Math.abs(D.tileID.overscaledZ-je),He=Ee&&D.refreshedUponExpiration?1:o.aC(Ee?Z:1-se,0,1);return w?{opacity:1,mix:1-He,isFading:Z<1}:{opacity:He,mix:0,isFading:Z<1}}return{opacity:1,mix:0,isFading:!1}}class Gt extends Bl{constructor(w){const C={type:"raster-dem",maxzoom:Math.ceil(w.transform.maxZoom)},O=wf("mock-dem",C,w.style.dispatcher,w.style);super("mock-dem",O,null),O.setEventedParent(this),this._sourceLoaded=!0}_loadTile(w,C){w.state="loaded",C(null)}}class ns extends Bl{constructor(w){const C=wf("proxy",{type:"geojson",maxzoom:Math.ceil(w.transform.maxZoom)},w.style.dispatcher,w.style);super("proxy",C,null),C.setEventedParent(this),this.map=this.getSource().map=w,this.used=this._sourceLoaded=!0,this.renderCache=[],this.renderCachePool=[],this.proxyCachedFBO={}}update(w,C,O){if(w.freezeTileCoverage)return;this.transform=w;const U=w.coveringTiles({tileSize:this._source.tileSize,minzoom:this._source.minzoom,maxzoom:this._source.maxzoom,roundZoom:this._source.roundZoom,reparseOverscaled:this._source.reparseOverscaled}).reduce((Y,Z)=>{if(Y[Z.key]="",!this._tiles[Z.key]){const se=new o.b0(Z,this._source.tileSize*Z.overscaleFactor(),w.tileZoom,void 0,void 0,this._source.worldview);se.state="loaded",this._tiles[Z.key]=se}return Y},{});for(const Y in this._tiles)Y in U||(this.freeFBO(Y),this._tiles[Y].unloadVectorData(),delete this._tiles[Y])}freeFBO(w){const C=this.proxyCachedFBO[w];if(C!==void 0){const O=Object.values(C);this.renderCachePool.push(...O),delete this.proxyCachedFBO[w]}}deallocRenderCache(){this.renderCache.forEach(w=>w.fb.destroy()),this.renderCache=[],this.renderCachePool=[],this.proxyCachedFBO={}}}class ds extends o.aR{constructor(w,C,O){super(w.overscaledZ,w.wrap,w.canonical.z,w.canonical.x,w.canonical.y),this.proxyTileKey=C,this.projMatrix=O}}class vs extends o.bu{constructor(w,C){super(),this._debugParams={sortTilesHiZFirst:!0,disableRenderCache:!1},this.painter=w,this.terrainTileForTile={},this.prevTerrainTileForTile={};const[O,U,Y]=function(){const pe=new o.dB,je=new o.dC,Ee=131;pe.reserve(17161),je.reserve(33800);const He=o.an/128,qe=o.an+He/2,et=qe+He;for(let ot=-He;otqe||ot<0||ot>qe?24575:0,Pt=o.aC(Math.round(bt),0,o.an),Ft=o.aC(Math.round(ot),0,o.an);pe.emplaceBack(Pt+vt,Ft)}const ct=(ot,bt)=>{const vt=bt*Ee+ot;je.emplaceBack(vt+1,vt,vt+Ee),je.emplaceBack(vt+Ee,vt+Ee+1,vt+1)};for(let ot=1;ot<129;ot++)for(let bt=1;bt<129;bt++)ct(bt,ot);return[0,129].forEach(ot=>{for(let bt=0;bt<130;bt++)ct(bt,ot),ct(ot,bt)}),[pe,je,32768]}(),Z=w.context;this.gridBuffer=Z.createVertexBuffer(O,o.dx.members),this.gridIndexBuffer=Z.createIndexBuffer(U),this.gridSegments=o.dy.simpleSegment(0,0,O.length,U.length),this.gridNoSkirtSegments=o.dy.simpleSegment(0,0,O.length,Y),this.proxyCoords=[],this.proxiedCoords={},this._visibleDemTiles=[],this._drapedRenderBatches=[],this._sourceTilesOverlap={},this.proxySourceCache=new ns(C.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 se=Z.gl;this._overlapStencilMode=new Na({func:se.GEQUAL,mask:255},0,255,se.KEEP,se.KEEP,se.REPLACE),this._previousZoom=w.transform.zoom,this.pool=[],this._findCoveringTileCache={},this._tilesDirty={},this.style=C,this._useVertexMorphing=!0,this._exaggeration=1,this._mockSourceCache=new Gt(C.map),this._pendingGroundEffectLayers=[],this._emissiveTexture=!1}set style(w){w.on("data",this._onStyleDataEvent.bind(this)),this._style=w,this._style.map.on("moveend",()=>{this._clearLineLayersFromRenderCache()})}update(w,C,O){if(w&&w.terrain){this._style!==w&&(this.style=w,this._evaluationZoom=void 0);const U=w.terrain.properties,Y=w.terrain.drapeRenderMode===0,Z=w.terrain.isZoomDependent();this._previousUpdateTimestamp=this.enabled?this._updateTimestamp:void 0,this._updateTimestamp=o.o.now();const se=w.terrain&&w.terrain.scope,pe=U.get("source"),je=Y?this._mockSourceCache:w.getSourceCache(pe,se);if(!je)return void o.w(`Couldn't find terrain source "${pe}".`);if(this.sourceCache=je,this._attenuationRange=w.terrain.getAttenuationRange(),this._exaggeration=Z?this.calculateExaggeration(C):U.get("exaggeration"),!C.projection.requiresDraping&&Z&&this._exaggeration===0)return void this._disable();this.enabled=!0;const Ee=()=>{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 He=this.getScaledDemTileSize();this.sourceCache.update(C,He,!0),this.resetTileLookupCache(this.sourceCache.id)};this.sourceCache.usedForTerrain||(this.resetTileLookupCache(this.sourceCache.id),this.sourceCache.usedForTerrain=!0,Ee(),this._initializing=!0),Ee(),C.updateElevation(!0,O),this.resetTileLookupCache(this.proxySourceCache.id),this.proxySourceCache.update(C),this._emptyDEMTextureDirty=!0,this._previousZoom=C.zoom}else this._disable()}calculateExaggeration(w){if(this._attenuationRange&&w.zoom>=Math.ceil(this._attenuationRange[1]))return this._style.terrain.getExaggeration(w.zoom);const C=this._previousCameraAltitude,O=w.getFreeCameraOptions().position.z/w.pixelsPerMeter*w.worldSize;this._previousCameraAltitude=O;const U=C!=null?O-C:Number.MAX_VALUE;if(Math.abs(U)<2)return this._exaggeration;const Y=w.zoom,Z=this._style.terrain;if(!this._previousUpdateTimestamp)return Z.getExaggeration(Y);let se=Y-this._previousZoom;const pe=this._previousUpdateTimestamp;let je=Y;this._evaluationZoom!=null&&(je=this._evaluationZoom,Math.abs(Y-je)>.5&&(se=.5*(Y-je+se)),se*U<0&&(je+=se)),this._evaluationZoom=je;const Ee=Z.getExaggeration(je),He=Ee===Z.getExaggeration(Math.max(0,je-.1));if(He&&Math.abs(Ee-this._exaggeration)<.01)return Ee;let qe=Math.min(.1,.00375*(this._updateTimestamp-pe));return(He||Ee<.1||Math.abs(se)<1e-4)&&(qe=Math.min(.2,4*qe)),o.am(this._exaggeration,Ee,qe)}resetTileLookupCache(w){this._findCoveringTileCache[w]={}}attenuationRange(){return this._attenuationRange}getDemUpscale(){return this.proxySourceCache.getSource().tileSize/128}getScaledDemTileSize(){return this.sourceCache.getSource().tileSize/128*this.proxySourceCache.getSource().tileSize}_onStyleDataEvent(w){w.dataType==="source"&&w.coord?this._clearRenderCacheForTile(w.sourceCacheId,w.coord):w.dataType==="style"&&(this.invalidateRenderCache=!0,this._evaluationZoom=void 0,this._previousUpdateTimestamp=void 0,this._previousCameraAltitude=void 0)}_disable(){if(this.enabled&&(this.enabled=!1,this._emptyDEMTextureDirty=!0,this._sharedDepthStencil=void 0,this._evaluationZoom=void 0,this._previousUpdateTimestamp=void 0,this.proxySourceCache.deallocRenderCache(),this._style))for(const w in this._style._mergedSourceCaches)this._style._mergedSourceCaches[w].usedForTerrain=!1}destroy(){this._disable(),this._emptyDEMTexture&&this._emptyDEMTexture.destroy(),this.pool.forEach(w=>w.fb.destroy()),this.pool=[],this.framebufferCopyTexture&&this.framebufferCopyTexture.destroy()}_source(){return this.enabled?this.sourceCache:null}isUsingMockSource(){return this.sourceCache===this._mockSourceCache}exaggeration(){return this.enabled?this._exaggeration:0}get visibleDemTiles(){return this._visibleDemTiles}get drapeBufferSize(){const w=2*this.proxySourceCache.getSource().tileSize;return[w,w]}set useVertexMorphing(w){this._useVertexMorphing=w}updateTileBinding(w){if(!this.enabled)return;this.prevTerrainTileForTile=this.terrainTileForTile;const C=this.proxySourceCache,O=this.painter.transform;this._initializing&&(this._initializing=O._centerAltitude===0&&this.getAtPointOrZero(o.ag.fromLngLat(O.center),-1)===-1,this._emptyDEMTextureDirty=!this._initializing);const U=this.proxyCoords=C.getIds().map(pe=>{const je=C.getTileByID(pe).tileID;return je.projMatrix=O.calculateProjMatrix(je.toUnwrapped()),je});(function(pe,je){const Ee=je.transform.pointCoordinate(je.transform.getCameraPoint()),He=new o.P(Ee.x,Ee.y);pe.sort((qe,et)=>{if(et.overscaledZ-qe.overscaledZ)return et.overscaledZ-qe.overscaledZ;const ct=new o.P(qe.canonical.x+(1<{this.proxyToSource[pe.key]={}}),this.terrainTileForTile={};const Z=this._style._mergedSourceCaches;for(const pe in Z){const je=Z[pe];if(!je.used||(je!==this.sourceCache&&this.resetTileLookupCache(je.id),this._setupProxiedCoordsForOrtho(je,w[pe],Y),je.usedForTerrain))continue;const Ee=w[pe];(je.getSource().reparseOverscaled||je._isRasterElevatedOverTerrain)&&this._assignTerrainTiles(Ee)}this.proxiedCoords[C.id]=U.map(pe=>new ds(pe,pe.key,this.orthoMatrix)),this._assignTerrainTiles(U),this._prepareDEMTextures(),this._setupDrapedRenderBatches(),this._initFBOPool(),this._setupRenderCache(Y),this.renderingToTexture=!1;const se={};this._visibleDemTiles=[];for(const pe of this.proxyCoords){const je=this.terrainTileForTile[pe.key];if(!je)continue;const Ee=je.tileID.key;Ee in se||(this._visibleDemTiles.push(je),se[Ee]=Ee)}}_assignTerrainTiles(w){this._initializing||w.forEach(C=>{if(this.terrainTileForTile[C.key])return;const O=this._findTileCoveringTileID(C,this.sourceCache);O&&(this.terrainTileForTile[C.key]=O)})}_prepareDEMTextures(){const w=this.painter.context,C=w.gl;for(const O in this.terrainTileForTile){const U=this.terrainTileForTile[O],Y=U.dem;!Y||U.demTexture&&!U.needsDEMTextureUpload||(w.activeTexture.set(C.TEXTURE1),oS(this.painter,U,Y))}}_prepareDemTileUniforms(w,C,O,U){if(!C||C.demTexture==null)return!1;const Y=w.tileID.canonical,Z=Math.pow(2,C.tileID.canonical.z-Y.z),se=U||"";return O[`u_dem_tl${se}`]=[Y.x*Z%1,Y.y*Z%1],O[`u_dem_scale${se}`]=Z,!0}get emptyDEMTexture(){return!this._emptyDEMTextureDirty&&this._emptyDEMTexture?this._emptyDEMTexture:this._updateEmptyDEMTexture()}_getLoadedAreaMinimum(){if(!this.enabled)return 0;let w=0;const C=this._visibleDemTiles.reduce((O,U)=>{if(!U.dem)return O;const Y=U.dem.tree.minimums[0];return Y>0&&w++,O+Y},0);return w?C/w:0}_updateEmptyDEMTexture(){const w=this.painter.context,C=w.gl;w.activeTexture.set(C.TEXTURE2);const O=this._getLoadedAreaMinimum(),U=new o.dz({width:1,height:1},new Float32Array([O]));this._emptyDEMTextureDirty=!1;let Y=this._emptyDEMTexture;return Y?Y.update(U,{premultiply:!1}):Y=this._emptyDEMTexture=new o.T(w,U,C.R32F,{premultiply:!1}),Y}setupElevationDraw(w,C,O){const U=this.painter.context,Y=U.gl,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};Z.u_exaggeration=this.exaggeration();let se=null,pe=null,je=1;if(O&&O.morphing&&this._useVertexMorphing){const et=O.morphing.srcDemTile,ct=O.morphing.dstDemTile;je=O.morphing.phase,et&&ct&&(this._prepareDemTileUniforms(w,et,Z,"_prev")&&(pe=et),this._prepareDemTileUniforms(w,ct,Z)&&(se=ct))}const Ee=et=>et&&et.demTexture&&this.painter.linearFloatFilteringSupported()?Y.LINEAR:Y.NEAREST;let He=null;var qe;if(this.enabled?pe&&se?(He=se.demTexture,U.activeTexture.set(Y.TEXTURE4),pe.demTexture.bind(Ee(pe),Y.CLAMP_TO_EDGE),Z.u_dem_lerp=je):(se=this.terrainTileForTile[w.tileID.key],He=this._prepareDemTileUniforms(w,se,Z)?se.demTexture:this.emptyDEMTexture):He=this.emptyDEMTexture,U.activeTexture.set(Y.TEXTURE2),He&&(Z.u_dem_size=(qe=He).size[0]===1?1:qe.size[0]-2,He.bind(Ee(se),Y.CLAMP_TO_EDGE)),this.painter.setupDepthForOcclusion(O&&O.useDepthForOcclusion,C,Z),O&&O.useMeterToDem&&se){const et=(1<{if(vt===an)return;const An=[dw[an],"PROJECTION_GLOBE_VIEW"];Ft&&An.push("CUSTOM_ANTIALIASING");const On=je.isTileAffectedByFog(hn);bt=je.getOrCreateProgram("globeRaster",{defines:An,overrideFog:On}),vt=an},ys=je.colorModeForRenderPass(),Qt=new Ir(ot.LEQUAL,Ir.ReadWrite,je.depthRangeFor3D);Wh.update(et);const gs=o.dq(Pt),$t=[o.aH(Pt.center.lng),o.aL(Pt.center.lat)],Zt=je.globeSharedBuffers,hs=[Pt.width*o.o.devicePixelRatio,Pt.height*o.o.devicePixelRatio],Us=Float32Array.from(Pt.globeMatrix),Cs={useDenormalizedUpVectorScale:!0};{const hn=je.transform,an=Db(hn.zoom,Ee.exaggeration(),Ee.sourceCache._source.tileSize);vt=-1;const An=ot.TRIANGLES;for(const On of qe){const Ks=He.getTile(On),Es=Na.disabled,cn=Ee.prevTerrainTileForTile[On.key],pn=Ee.terrainTileForTile[On.key];cw(cn,pn)&&Wh.newMorphing(On.key,cn,pn,et,250),Oe(je,Ks.emissiveTexture),ct.activeTexture.set(ot.TEXTURE0),Ks.texture&&Ks.texture.bind(ot.LINEAR,ot.CLAMP_TO_EDGE);const vn=Wh.getMorphValuesForProxy(On.key),fr=vn?1:0;vn&&Object.assign(Cs,{morphing:{srcDemTile:vn.from,dstDemTile:vn.to,phase:o.dn(vn.phase)}});const nr=o.dr(On.canonical),rr=o.ds(nr.getCenter().lat),In=o.dt(On.canonical,nr,rr,hn.worldSize/hn._pixelsPerMercatorPixel),Yr=o.du(o.dv(On.canonical)),fa=je.emissiveMode==="mrt-fallback"?1:0,Fr=dy(hn.expandedFarZProjMatrix,Us,gs,Yr,o.al(hn.zoom),$t,hn.frustumCorners.TL,hn.frustumCorners.TR,hn.frustumCorners.BR,hn.frustumCorners.BL,hn.globeCenterInViewSpace,hn.globeRadius,hs,an,hn._farZ,fa,In);if(jt(On,fr),bt&&(Ee.setupElevationDraw(Ks,bt,Cs),je.uploadCommonUniforms(ct,bt,On.toUnwrapped()),Zt)){const[Vr,$a,ri]=Zt.getGridBuffers(rr,an!==0);bt.draw(je,An,Qt,Es,ys,ra.backCCW,Fr,"globe_raster",Vr,$a,ri)}}}if(Zt&&(je.renderDefaultNorthPole||je.renderDefaultSouthPole)){const hn=["GLOBE_POLES","PROJECTION_GLOBE_VIEW"];Ft&&hn.push("CUSTOM_ANTIALIASING"),bt=je.getOrCreateProgram("globeRaster",{defines:hn});for(const an of qe){const{x:An,y:On,z:Ks}=an.canonical,Es=On===0,cn=On===(1<Vr.draw(je,ot.TRIANGLES,Qt,Na.disabled,ys,ra.disabled,dy(Pt.expandedFarZProjMatrix,In,In,Yr,0,$t,Pt.frustumCorners.TL,Pt.frustumCorners.TR,Pt.frustumCorners.BR,Pt.frustumCorners.BL,Pt.globeCenterInViewSpace,Pt.globeRadius,hs,0,Pt._farZ,fa),"globe_pole_raster",$a,fr,nr);Ee.setupElevationDraw(rr,bt,Cs),je.uploadCommonUniforms(ct,bt,an.toUnwrapped()),Es&&je.renderDefaultNorthPole&&Fr(bt,pn),cn&&je.renderDefaultSouthPole&&(In=o.cC(o.bb(),In,[1,-1,1]),Fr(bt,vn))}}}})(U,Y,Z,se,pe);else{const je=U.context,Ee=je.gl;let He,qe;const et=U.shadowRenderer,ct=qc(U,U.longestCutoffRange),ot=ys=>{if(qe===ys)return;const Qt=[];Qt.push(dw[ys]),ct.shouldRenderCutoff&&Qt.push("RENDER_CUTOFF"),et&&(Qt.push("RENDER_SHADOWS"),et.useNormalOffset&&Qt.push("NORMAL_OFFSET")),He=U.getOrCreateProgram("terrainRaster",{defines:Qt}),qe=ys},bt=U.colorModeForRenderPass(),vt=new Ir(Ee.LEQUAL,Ir.ReadWrite,U.depthRangeFor3D);Wh.update(pe);const Pt=U.transform,Ft=Db(Pt.zoom,Y.exaggeration(),Y.sourceCache._source.tileSize);let jt=[0,0,0];if(et){const ys=U.style.directionalLight,Qt=U.style.ambientLight;ys&&Qt&&(jt=oh(U.style,ys,Qt))}{qe=-1;const ys=Ee.TRIANGLES,[Qt,gs]=[Y.gridIndexBuffer,Y.gridSegments];for(const $t of se){const Zt=Z.getTile($t),hs=Na.disabled,Us=Y.prevTerrainTileForTile[$t.key],Cs=Y.terrainTileForTile[$t.key];cw(Us,Cs)&&Wh.newMorphing($t.key,Us,Cs,pe,250),Oe(U,Zt.emissiveTexture),je.activeTexture.set(Ee.TEXTURE0),Zt.texture&&Zt.texture.bind(Ee.LINEAR,Ee.CLAMP_TO_EDGE);const hn=Wh.getMorphValuesForProxy($t.key),an=hn?1:0;let An;hn&&(An={morphing:{srcDemTile:hn.from,dstDemTile:hn.to,phase:o.dn(hn.phase)}});const On=U.emissiveMode==="mrt-fallback"?1:0,Ks=Ib($t.projMatrix,ke($t.canonical,Pt.renderWorldCopies)?Ft/10:Ft,jt,On);if(ot(an),!He)continue;Y.setupElevationDraw(Zt,He,An);const Es=$t.toUnwrapped();et&&et.setupShadows(Es,He),U.uploadCommonUniforms(je,He,Es,null,ct),He.draw(U,ys,vt,hs,bt,ra.backCCW,Ks,"terrain_raster",Y.gridBuffer,Qt,gs)}}}}(C,this,this.proxySourceCache,w,this._updateTimestamp),this.renderingToTexture=!0,C.gpuTimingDeferredRenderEnd(),w.splice(0,w.length))}renderBatch(w){if(this._drapedRenderBatches.length===0)return w+1;this.renderingToTexture=!0;const C=this.painter,O=this.painter.context,U=this.proxySourceCache,Y=this.proxiedCoords[U.id],Z=this._drapedRenderBatches.shift(),se=C.style.order,pe=[];this._updateFBOs(C.emissiveMode==="mrt-fallback");let je=0;for(const Ee of Y){const He=U.getTileByID(Ee.proxyTileKey),qe=U.proxyCachedFBO[Ee.key]?U.proxyCachedFBO[Ee.key][w]:void 0,et=qe!==void 0?U.renderCache[qe]:this.pool[je++],ct=qe!==void 0;if(He.texture=et.tex,He.emissiveTexture=et.emissiveTex,ct&&!et.dirty){pe.push(He.tileID);continue}O.bindFramebuffer.set(et.fb.framebuffer);const ot=O.gl;let bt;ot.drawBuffers(C.emissiveMode==="mrt-fallback"?[ot.COLOR_ATTACHMENT0,ot.COLOR_ATTACHMENT1]:[ot.COLOR_ATTACHMENT0]),this.renderedToTile=!1,et.dirty&&(O.clear({color:o.aq.transparent,stencil:0}),et.dirty=!1);for(let vt=Z.start;vt<=Z.end;++vt){const Pt=C.style._mergedLayers[se[vt]];if(Pt.isHidden(C.transform.zoom))continue;const Ft=C.style.getLayerSourceCache(Pt),jt=Ft?this.proxyToSource[Ee.key][Ft.id]:[Ee];if(!jt)continue;const ys=jt;O.viewport.set([0,0,et.fb.width,et.fb.height]),bt!==(Ft?Ft.id:null)&&(this._setupStencil(et,jt,Pt,Ft),bt=Ft?Ft.id:null),C.renderLayer(C,Ft,Pt,ys)}if(ot.drawBuffers([ot.COLOR_ATTACHMENT0]),this._drapedRenderBatches.length===0)for(const vt of this._pendingGroundEffectLayers){const Pt=C.style._mergedLayers[se[vt]];if(Pt.isHidden(C.transform.zoom))continue;const Ft=C.style.getLayerSourceCache(Pt),jt=Ft?this.proxyToSource[Ee.key][Ft.id]:[Ee];if(!jt)continue;const ys=jt;O.viewport.set([0,0,et.fb.width,et.fb.height]),bt!==(Ft?Ft.id:null)&&(this._setupStencil(et,jt,Pt,Ft),bt=Ft?Ft.id:null),C.renderLayer(C,Ft,Pt,ys)}this.renderedToTile?(et.dirty=!0,pe.push(He.tileID)):ct||--je,je===5&&(je=0,this.renderToBackBuffer(pe))}return this.renderToBackBuffer(pe),this.renderingToTexture=!1,O.bindFramebuffer.set(null),O.viewport.set([0,0,C.width,C.height]),Z.end+1}postRender(){}isLayerOrderingCorrect(w){const C=w.order.length;let O=-1,U=C;for(let Y=0;YO}getMinElevationBelowMSL(){let w=0;return this._visibleDemTiles.filter(C=>C.dem).forEach(C=>{w=Math.min(w,C.dem.tree.minimums[0])}),w===0?w:(w-30)*this._exaggeration}raycast(w,C,O){if(!this._visibleDemTiles)return null;const U=this._visibleDemTiles.filter(Y=>Y.dem).map(Y=>{const Z=Y.tileID,se=1<(Y.t!==null?Y.t:Number.MAX_VALUE)-(Z.t!==null?Z.t:Number.MAX_VALUE));for(const Y of U){if(Y.t==null)return null;const Z=Y.tile.dem.tree.raycast(Y.minx,Y.miny,Y.maxx,Y.maxy,w,C,O);if(Z!=null)return Z}return null}_createFBO(){const w=this.painter.context,C=w.gl,O=this.drapeBufferSize;w.activeTexture.set(C.TEXTURE0);const U=new o.T(w,{width:O[0],height:O[1],data:null},C.RGBA8);U.bind(C.LINEAR,C.CLAMP_TO_EDGE);const Y=w.createFramebuffer(O[0],O[1],1,null);let Z;return Y.colorAttachment0.set(U.texture),this._emissiveTexture&&(Z=new o.T(w,{width:O[0],height:O[1],data:null},C.R8),Z.bind(C.LINEAR,C.CLAMP_TO_EDGE),Y.createColorAttachment(w,1),Y.colorAttachment1.set(Z.texture)),Y.depthAttachment=new K3(w,Y.framebuffer),this._sharedDepthStencil===void 0?(this._sharedDepthStencil=w.createRenderbuffer(w.gl.DEPTH_STENCIL,O[0],O[1]),this._stencilRef=0,Y.depthAttachment.set(this._sharedDepthStencil),w.clear({stencil:0})):Y.depthAttachment.set(this._sharedDepthStencil),w.extTextureFilterAnisotropic&&C.texParameterf(C.TEXTURE_2D,w.extTextureFilterAnisotropic.TEXTURE_MAX_ANISOTROPY_EXT,w.extTextureFilterAnisotropicMax),{fb:Y,tex:U,emissiveTex:Z,dirty:!1}}_updateFBOs(w){if(this._emissiveTexture!==w){for(const C of this.pool)this._updateFBO(C,w);for(const C of this.proxySourceCache.renderCache)this._updateFBO(C,w);this._emissiveTexture=w}}_updateFBO(w,C){const O=w.fb,U=this.painter.context,Y=U.gl,Z=this.drapeBufferSize;if(C){const se=new o.T(U,{width:Z[0],height:Z[1],data:null},Y.R8);se.bind(Y.LINEAR,Y.CLAMP_TO_EDGE),w.emissiveTex=se,O.createColorAttachment(U,1),O.colorAttachment1.set(se.texture)}else w.emissiveTex=void 0,O.removeColorAttachment(U,1);w.dirty=!0}_initFBOPool(){for(;this.pool.length{const C=this._style._mergedLayers[w],O=C.isHidden(this.painter.transform.zoom);return C.type==="hillshade"||C.type==="custom"?!O&&C.shouldRedrape():!O&&C.hasTransition()})}_clearLineLayersFromRenderCache(){let w=!1;for(const O of this._style.getSources())if(O instanceof Gd){w=!0;break}if(!w)return;const C={};for(let O=0;Ope>se.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=O}_setupRenderCache(w){const C=this.proxySourceCache;if(this._shouldDisableRenderCache()||this.invalidateRenderCache){if(this.invalidateRenderCache=!1,C.renderCache.length>C.renderCachePool.length){const Z=Object.values(C.proxyCachedFBO);C.proxyCachedFBO={};for(let se=0;se=0;Z--){const se=O[Z];if(C.getTileByID(se.key),C.proxyCachedFBO[se.key]!==void 0){const pe=w[se.key],je=this.proxyToSource[se.key];let Ee=0;for(const He in je){const qe=je[He],et=pe[He];if(!et||et.length!==qe.length||qe.some((ct,ot)=>ct!==et[ot]||U[He]&&U[He].hasOwnProperty(ct.key))){Ee=-1;break}++Ee}for(const He in C.proxyCachedFBO[se.key])C.renderCache[C.proxyCachedFBO[se.key][He]].dirty=Ee<0||Ee!==Object.values(pe).length}}const Y=[...this._drapedRenderBatches];Y.sort((Z,se)=>se.end-se.start-(Z.end-Z.start));for(const Z of Y)for(const se of O){if(C.proxyCachedFBO[se.key])continue;let pe=C.renderCachePool.pop();pe===void 0&&C.renderCache.length<50&&(pe=C.renderCache.length,C.renderCache.push(this._createFBO())),pe!==void 0&&(C.proxyCachedFBO[se.key]={},C.proxyCachedFBO[se.key][Z.start]=pe,C.renderCache[pe].dirty=!0)}this._tilesDirty={}}_setupStencil(w,C,O,U){if(!U||!this._sourceTilesOverlap[U.id])return void(this._overlapStencilType&&(this._overlapStencilType=!1));const Y=this.painter.context,Z=Y.gl;if(C.length<=1)return void(this._overlapStencilType=!1);let se;if(O.isTileClipped())se=C.length,this._overlapStencilMode.test={func:Z.EQUAL,mask:255},this._overlapStencilType="Clip";else{if(!(C[0].overscaledZ>C[C.length-1].overscaledZ))return void(this._overlapStencilType=!1);se=1,this._overlapStencilMode.test={func:Z.GREATER,mask:255},this._overlapStencilType="Mask"}this._stencilRef+se>255&&(Y.clear({stencil:0}),this._stencilRef=0),this._stencilRef+=se,this._overlapStencilMode.ref=this._stencilRef,O.isTileClipped()&&this._renderTileClippingMasks(C,this._overlapStencilMode.ref)}clipOrMaskOverlapStencilType(){return this._overlapStencilType==="Clip"||this._overlapStencilType==="Mask"}stencilModeForRTTOverlap(w){return this.renderingToTexture&&this._overlapStencilType?(this._overlapStencilType==="Clip"&&(this._overlapStencilMode.ref=this.painter._tileClippingMaskIDs[w.key]),this._overlapStencilMode):Na.disabled}_renderTileClippingMasks(w,C){const O=this.painter,U=this.painter.context,Y=U.gl;O._tileClippingMaskIDs={},U.setColorMode(wa.disabled),U.setDepthMode(Ir.disabled);const Z=O.getOrCreateProgram("clippingMask");for(const se of w){const pe=O._tileClippingMaskIDs[se.key]=--C;Z.draw(O,Y.TRIANGLES,Ir.disabled,new Na({func:Y.ALWAYS,mask:0},pe,255,Y.KEEP,Y.KEEP,Y.REPLACE),wa.disabled,ra.disabled,ut(se.projMatrix),"$clipping",O.tileExtentBuffer,O.quadTriangleIndexBuffer,O.tileExtentSegments)}}pointCoordinate(w){const C=this.painter.transform;if(w.x<0||w.x>C.width||w.y<0||w.y>C.height)return null;const O=[w.x,w.y,1,1];o.aE(O,O,C.pixelMatrixInverse),o.cu(O,O,1/O[3]),O[0]/=C.worldSize,O[1]/=C.worldSize;const U=C._camera.position,Y=o.bU(1,C.center.lat),Z=[U[0],U[1],U[2]/Y,0],se=o.cV([],O.slice(0,3),Z);o.ay(se,se);const pe=this.raycast(Z,se,this._exaggeration);return pe!==null&&pe?(o.bg(Z,Z,se,pe),Z[3]=Z[2],Z[2]*=Y,Z):null}_setupProxiedCoordsForOrtho(w,C,O){if(w.getSource()instanceof o.aV)return this._setupProxiedCoordsForImageSource(w,C,O);this._findCoveringTileCache[w.id]=this._findCoveringTileCache[w.id]||{};const U=this.proxiedCoords[w.id]=[],Y=this.proxyCoords;for(let pe=0;peEe.overscaledZ-je.overscaledZ)}_setupProxiedCoordsForImageSource(w,C,O){if(!w.getSource().loaded())return;const U=this.proxiedCoords[w.id]=[],Y=this.proxyCoords,Z=w.getSource(),se=Z.tileID;if(!se)return;const pe=new o.P(se.x,se.y)._div(1<(He.min.x=Math.min(He.min.x,qe.x-pe.x),He.min.y=Math.min(He.min.y,qe.y-pe.y),He.max.x=Math.max(He.max.x,qe.x-pe.x),He.max.y=Math.max(He.max.y,qe.y-pe.y),He),{min:new o.P(Number.MAX_VALUE,Number.MAX_VALUE),max:new o.P(-Number.MAX_VALUE,-Number.MAX_VALUE)}),Ee=(He,qe)=>{const et=He.wrap+He.canonical.x/(1<bt+je.max.x||ct+otvt+je.max.y};for(let He=0;HeZ.key===C.tileID.key);if(Y)return Y}if(C.tileID.key!==w.key){const Y=w.canonical.z-C.tileID.canonical.z;let Z,se,pe;U=o.bb();const je=C.tileID.wrap-w.wrap<0?(Z=o.an>>Y,se=Z*((C.tileID.canonical.x<=He){const qe=w.canonical.z-He;C.getSource().reparseOverscaled?(se=Math.max(w.canonical.z+2,C.transform.tileZoom),Z=new o.aR(se,w.wrap,He,w.canonical.x>>qe,w.canonical.y>>qe)):qe!==0&&(se=He,Z=new o.aR(se,w.wrap,He,w.canonical.x>>qe,w.canonical.y>>qe))}Z.key!==w.key&&(je.push(Z.key),O=C.getTile(Z))}const Ee=He=>{je.forEach(qe=>{U[qe]=He}),je.length=0};for(se-=1;se>=pe&&(!O||!O.hasData());se--){O&&Ee(O.tileID.key);const He=Z.calculateScaledKey(se);if(O=C.getTileByID(He),O&&O.hasData())break;const qe=U[He];if(qe===null)break;qe===void 0?je.push(He):O=C.getTileByID(qe)}return Ee(O?O.tileID.key:null),O&&O.hasData()?O:null}findDEMTileFor(w){return this.enabled?this._findTileCoveringTileID(w,this.sourceCache):null}prepareDrawTile(){this.renderedToTile=!0}_clearRenderCacheForTile(w,C){let O=this._tilesDirty[w];O||(O=this._tilesDirty[w]={}),O[C.key]=!0}}function Ts(D,w,C){const O=function(se,pe,je){const Ee=o.bi(pe,se),He=o.bi(je,[.2126,.7152,.0722]),qe=(ct,ot,bt)=>(1-bt)*ct+bt*ot,et=qe(1-.3*Math.min(He,1),1,Math.min(Ee+1,1));return qe(.92,1,Math.asin(o.aC(pe[2],-1,1))/Math.PI+.5)*et}(D,[0,0,1],w),U=[0,0,0];o.bJ(U,C.slice(0,3),O);const Y=[0,0,0];o.bJ(Y,w.slice(0,3),D[2]);const Z=[0,0,0];return o.cT(Z,U,Y),o.cW(Z)}const Vs=["fill","fillOutline","fillPattern","line","linePattern","background","backgroundPattern","hillshade","raster"],bn=["stars","rainParticle","snowParticle","fillExtrusion","fillExtrusionGroundEffect","building","buildingBloom","elevatedStructures","model","symbol"];class $n{static cacheKey(w,C,O,U){const Y=[C];U&&Y.push(U.cacheKey);for(const Z of O)(typeof Z=="string"&&Z.includes(" ")||w.usedDefines.has(Z))&&Y.push(Z);return Y.join("/")}constructor(w,C,O,U,Y,Z){const se=w.gl;this.program=se.createProgram(),this.configuration=U,this.name=C,this.fixedDefines=[...Z];const pe=`#version 300 es ${(U?U.defines():[]).concat(Z.map(ot=>`#define ${ot}`)).join(` `)}`,je=[pe,nv];for(const ot of O.fragmentIncludes)je.push(Bp[ot]);je.push(O.fragmentSource);const Ee=je.join(` `),He=[pe,Fj];for(const ot of O.vertexIncludes)He.push(Bp[ot]);this.forceManualRenderingForInstanceIDShaders=w.forceManualRenderingForInstanceIDShaders&&O.vertexSource.includes("gl_InstanceID"),this.forceManualRenderingForInstanceIDShaders&&He.push("uniform int u_instanceID;"),He.push(O.vertexSource);let qe=He.join(` `);this.forceManualRenderingForInstanceIDShaders&&(qe=qe.replaceAll("gl_InstanceID","u_instanceID"));const et=se.createShader(se.FRAGMENT_SHADER);if(se.isContextLost())return void(this.failedToCreate=!0);se.shaderSource(et,Ee),se.compileShader(et),se.attachShader(this.program,et);const ct=se.createShader(se.VERTEX_SHADER);se.isContextLost()?this.failedToCreate=!0:(se.shaderSource(ct,qe),se.compileShader(ct),se.attachShader(this.program,ct),this.attributes={},se.linkProgram(this.program),se.deleteShader(ct),se.deleteShader(et),this.fixedUniforms=Y(w),this.fixedUniformsEntries=Object.entries(this.fixedUniforms),this.binderUniforms=U?U.getUniforms(w):[],this.forceManualRenderingForInstanceIDShaders&&(this.instancingUniforms=(ot=>({u_instanceID:new o.bX(ot)}))(w)),(Z.includes("TERRAIN")||Z.includes("ELEVATED")||C.includes("symbol")||C.includes("circle"))&&(this.terrainUniforms=(ot=>({u_dem:new o.bX(ot),u_dem_prev:new o.bX(ot),u_dem_tl:new o.b_(ot),u_dem_scale:new o.bZ(ot),u_dem_tl_prev:new o.b_(ot),u_dem_scale_prev:new o.bZ(ot),u_dem_size:new o.bZ(ot),u_dem_lerp:new o.bZ(ot),u_exaggeration:new o.bZ(ot),u_depth:new o.bX(ot),u_depth_size_inv:new o.b_(ot),u_depth_range_unpack:new o.b_(ot),u_occluder_half_size:new o.bZ(ot),u_occlusion_depth_offset:new o.bZ(ot),u_meter_to_dem:new o.bZ(ot),u_label_plane_matrix_inv:new o.b$(ot)}))(w)),Z.includes("GLOBE")&&(this.globeUniforms=(ot=>({u_tile_tl_up:new o.bY(ot),u_tile_tr_up:new o.bY(ot),u_tile_br_up:new o.bY(ot),u_tile_bl_up:new o.bY(ot),u_tile_up_scale:new o.bZ(ot)}))(w)),Z.includes("FOG")&&(this.fogUniforms=(ot=>({u_fog_matrix:new o.b$(ot),u_fog_range:new o.b_(ot),u_fog_color:new o.cO(ot),u_fog_horizon_blend:new o.bZ(ot),u_fog_vertical_limit:new o.b_(ot),u_fog_temporal_offset:new o.bZ(ot),u_frustum_tl:new o.bY(ot),u_frustum_tr:new o.bY(ot),u_frustum_br:new o.bY(ot),u_frustum_bl:new o.bY(ot),u_globe_pos:new o.bY(ot),u_globe_radius:new o.bZ(ot),u_globe_transition:new o.bZ(ot),u_is_globe:new o.bX(ot),u_viewport:new o.b_(ot)}))(w)),Z.includes("RENDER_CUTOFF")&&(this.cutoffUniforms=(ot=>({u_cutoff_params:new o.cO(ot)}))(w)),Z.includes("LIGHTING_3D_MODE")&&(this.lightsUniforms=(ot=>({u_lighting_ambient_color:new o.bY(ot),u_lighting_directional_dir:new o.bY(ot),u_lighting_directional_color:new o.bY(ot),u_ground_radiance:new o.bY(ot)}))(w)),Z.includes("RENDER_SHADOWS")&&(this.shadowUniforms=(ot=>({u_light_matrix_0:new o.b$(ot),u_light_matrix_1:new o.b$(ot),u_fade_range:new o.b_(ot),u_shadow_normal_offset:new o.bY(ot),u_shadow_intensity:new o.bZ(ot),u_shadow_texel_size:new o.bZ(ot),u_shadow_map_resolution:new o.bZ(ot),u_shadow_direction:new o.bY(ot),u_shadow_bias:new o.bY(ot),u_shadowmap_0:new o.bX(ot),u_shadowmap_1:new o.bX(ot)}))(w)))}getAttributeLocation(w,C){let O=this.attributes[C];return O===void 0&&(O=this.attributes[C]=w.getAttribLocation(this.program,C)),O}setTerrainUniformValues(w,C){if(!this.terrainUniforms)return;const O=this.terrainUniforms;if(!this.failedToCreate){w.program.set(this.program);for(const U in C)O[U]&&O[U].set(this.program,U,C[U])}}setGlobeUniformValues(w,C){if(!this.globeUniforms)return;const O=this.globeUniforms;if(!this.failedToCreate){w.program.set(this.program);for(const U in C)O[U]&&O[U].set(this.program,U,C[U])}}setFogUniformValues(w,C){if(!this.fogUniforms)return;const O=this.fogUniforms;if(!this.failedToCreate){w.program.set(this.program);for(const U in C)O[U].set(this.program,U,C[U])}}setCutoffUniformValues(w,C){if(!this.cutoffUniforms)return;const O=this.cutoffUniforms;if(!this.failedToCreate){w.program.set(this.program);for(const U in C)O[U].set(this.program,U,C[U])}}setLightsUniformValues(w,C){if(!this.lightsUniforms)return;const O=this.lightsUniforms;if(!this.failedToCreate){w.program.set(this.program);for(const U in C)O[U].set(this.program,U,C[U])}}setShadowUniformValues(w,C){if(this.failedToCreate||!this.shadowUniforms)return;const O=this.shadowUniforms;w.program.set(this.program);for(const U in C)O[U].set(this.program,U,C[U])}_drawDebugWireframe(w,C,O,U,Y,Z,se,pe,je,Ee){const He=w.options.wireframe;if(He.terrain===!1&&He.layers2D===!1&&He.layers3D===!1)return;const qe=w.context;if(!(!(!He.terrain||this.name!=="terrainRaster"&&this.name!=="globeRaster")||!(!He.layers2D||w._terrain&&w._terrain.renderingToTexture||!Vs.includes(this.name))||!(!He.layers3D||!bn.includes(this.name))))return;const et=qe.gl,ct=w.wireframeDebugCache.getLinesFromTrianglesBuffer(w.frameCounter,Y,qe);if(!ct)return;const ot=[...this.fixedDefines,"DEBUG_WIREFRAME"],bt=w.getOrCreateProgram(this.name,{config:this.configuration,defines:ot});qe.program.set(bt.program);const vt=(jt,ys,Qt)=>{if(ys[jt]&&Qt[jt])for(const gs in ys[jt])Qt[jt][gs]&&Qt[jt][gs].set(Qt.program,gs,ys[jt][gs].current)};je&&je.setUniforms(bt.program,qe,bt.binderUniforms,se,{zoom:pe}),vt("fixedUniforms",this,bt),vt("terrainUniforms",this,bt),vt("globeUniforms",this,bt),vt("fogUniforms",this,bt),vt("lightsUniforms",this,bt),vt("shadowUniforms",this,bt),ct.bind(),qe.setColorMode(new wa([et.ONE,et.ONE_MINUS_SRC_ALPHA,et.ZERO,et.ONE],o.aq.transparent,[!0,!0,!0,!1])),qe.setDepthMode(new Ir(C.func===et.LESS?et.LEQUAL:C.func,Ir.ReadOnly,C.range)),qe.setStencilMode(Na.disabled);const Pt=3*Z.primitiveLength*2,Ft=3*Z.primitiveOffset*2*2;if(this.forceManualRenderingForInstanceIDShaders){const jt=Ee||1;for(let ys=0;ys1?et.drawElementsInstanced(et.LINES,Pt,et.UNSIGNED_SHORT,Ft,Ee):et.drawElements(et.LINES,Pt,et.UNSIGNED_SHORT,Ft);Y.bind(),qe.program.set(this.program),qe.setDepthMode(C),qe.setStencilMode(O),qe.setColorMode(U)}checkUniforms(w,C,O){if(this.fixedDefines.includes(C)){for(const U of Object.keys(O))if(!O[U].initialized)throw new Error(`Program '${this.name}', from draw '${w}': uniform ${U} not set but required by ${C} being defined`)}}draw(w,C,O,U,Y,Z,se,pe,je,Ee,He,qe,et,ct,ot,bt){const vt=w.context,Pt=vt.gl;if(this.failedToCreate)return;vt.program.set(this.program),vt.setDepthMode(O),vt.setStencilMode(U),vt.setColorMode(Y),vt.setCullFace(Z);for(const[$t,Zt]of this.fixedUniformsEntries)Zt.set(this.program,$t,se[$t]);ct&&ct.setUniforms(this.program,vt,this.binderUniforms,qe,{zoom:et});const Ft={[Pt.POINTS]:1,[Pt.LINES]:2,[Pt.TRIANGLES]:3,[Pt.LINE_STRIP]:1}[C];this.checkUniforms(pe,"RENDER_SHADOWS",this.shadowUniforms);const jt=ot||[],ys=ct?ct.getPaintVertexBuffers():[],Qt=C===Pt.TRIANGLES&&Ee,gs=bt&&bt>0?1:void 0;for(const $t of He.get()){const Zt=$t.vaos||($t.vaos={});if((Zt[pe]||(Zt[pe]=new TN)).bind(vt,this,je,ys,Ee,$t.vertexOffset,jt,gs),this.forceManualRenderingForInstanceIDShaders){const hs=bt||1;for(let Us=0;Us1?Pt.drawElementsInstanced(C,$t.primitiveLength*Ft,Pt.UNSIGNED_SHORT,$t.primitiveOffset*Ft*2,bt):Ee?Pt.drawElements(C,$t.primitiveLength*Ft,Pt.UNSIGNED_SHORT,$t.primitiveOffset*Ft*2):Pt.drawArrays(C,$t.vertexOffset,$t.vertexLength);Qt&&this._drawDebugWireframe(w,O,U,Y,Ee,$t,qe,et,ct,bt)}}}function Gs(D,w,C=0){const O=Math.pow(2,w.tileID.overscaledZ),U=w.tileSize*Math.pow(2,D.transform.tileZoom)/O,Y=U*(w.tileID.canonical.x+w.tileID.wrap*O),Z=U*w.tileID.canonical.y;return{u_image:0,u_texsize:w.imageAtlasTexture?w.imageAtlasTexture.size:[0,0],u_tile_units_to_pixels:1/o.aA(w,1,D.transform.tileZoom),u_pixel_coord_upper:[Y>>16,Z>>16],u_pixel_coord_lower:[65535&Y,65535&Z],u_pattern_transition:C}}const En={terrain:0,flat:1},Kn=o.bb(),wr=(D,w,C,O,U,Y,Z,se,pe,je,Ee,He,qe,et,ct,ot,bt,vt,Pt=[0,0,1])=>{const Ft=w.style.light,jt=Ft.properties.get("position"),ys=[jt.x,jt.y,jt.z],Qt=o.dE();Ft.properties.get("anchor")==="viewport"&&(o.dF(Qt,-w.transform.angle),o.dG(ys,ys,Qt));const gs=Ft.properties.get("color").toPremultipliedRenderColor(null),$t=w.transform,Zt={u_matrix:D,u_lightpos:ys,u_lightintensity:Ft.properties.get("intensity"),u_lightcolor:[gs.r,gs.g,gs.b],u_vertical_gradient:+C,u_opacity:O,u_tile_id:[0,0,0],u_zoom_transition:0,u_inv_rot_matrix:Kn,u_merc_center:[0,0],u_up_dir:[0,0,0],u_height_lift:0,u_height_type:En[je],u_base_type:En[Ee],u_ao:U,u_edge_radius:Y,u_width_scale:Z,u_flood_light_color:ct,u_vertical_scale:ot,u_flood_light_intensity:bt,u_ground_shadow_factor:vt,u_front_cutoff_params:Pt};return $t.projection.name==="globe"&&(Zt.u_tile_id=[se.canonical.x,se.canonical.y,1<({u_matrix:D,u_edge_radius:w,u_width_scale:C,u_vertical_scale:O,u_height_type:En[U],u_base_type:En[Y]}),Ln=(D,w,C,O,U,Y,Z,se,pe,je,Ee,He,qe,et,ct,ot,bt,vt)=>{const Pt=wr(D,w,C,O,U,Y,Z,se,je,Ee,He,qe,et,ct,ot,bt,1,[0,0,0]),Ft={u_height_factor:-Math.pow(2,se.overscaledZ)/pe.tileSize/8};return Object.assign(Pt,Gs(w,pe,vt),Ft)},Pr=(D,w,C)=>({u_matrix:D,u_emissive_strength:w,u_ground_shadow_factor:C}),ha=(D,w,C,O,U,Y=0)=>Object.assign(Pr(D,w,U),Gs(C,O,Y)),aa=(D,w,C,O)=>({u_matrix:D,u_world:C,u_emissive_strength:w,u_ground_shadow_factor:O}),Ei=(D,w,C,O,U,Y,Z=0)=>Object.assign(ha(D,w,C,O,Y,Z),{u_world:U}),hi=(D,w)=>({u_matrix:D,u_depth_bias:w}),Ko=(D,w)=>({u_matrix:D,u_ground_shadow_factor:w}),wi=(D,w,C,O,U)=>({u_matrix:D,u_camera_pos:[w[0],w[1],w[2]],u_depth_bias:C,u_height_scale:O,u_reset_depth:U}),xl=(D,w,C)=>({u_image:D,u_opacity:w,u_blend_mode:C}),_d=(D,w,C,O,U,Y,Z,se,pe,je=[0,0,1])=>({u_matrix:D,u_normal_matrix:w,u_opacity:C,u_faux_facade_ao_intensity:O,u_camera_pos:U,u_tile_to_meter:Y,u_facade_emissive_chance:Z,u_flood_light_color:se,u_flood_light_intensity:pe,u_front_cutoff_params:je}),Yo=D=>({u_matrix:D}),Si=D=>({u_matrix:D}),Ga=(D,w,C,O,U,Y,Z,se)=>{const pe=o.an/Y.tileSize;return{u_matrix:D,u_inv_rot_matrix:w,u_camera_to_center_distance:C.getCameraToCenterDistance(se),u_extrude_scale:[C.pixelsToGLUnits[0]/pe,C.pixelsToGLUnits[1]/pe],u_zoom_transition:O,u_tile_id:Z,u_merc_center:U}},Qo=(D,w,C,O)=>({u_matrix:D,u_inv_matrix:w,u_camera_to_center_distance:C.getCameraToCenterDistance(O),u_viewport_size:[C.width,C.height]}),so=(D,w,C=1)=>({u_matrix:D,u_color:w,u_overlay:0,u_overlay_scale:C}),zo=o.bb(),hd=(D,w,C,O,U,Y,Z)=>{const se=D.transform,pe=se.projection.name==="globe",je=pe?o.dH(se.zoom,w.canonical)*se._pixelsPerMercatorPixel:o.aA(C,1,Y),Ee={u_matrix:w.projMatrix,u_extrude_scale:je,u_intensity:Z,u_inv_rot_matrix:zo,u_merc_center:[0,0],u_tile_id:[0,0,0],u_zoom_transition:0,u_up_dir:[0,0,0]};if(pe){Ee.u_inv_rot_matrix=O,Ee.u_merc_center=U,Ee.u_tile_id=[w.canonical.x,w.canonical.y,1<({u_matrix:w,u_normalize_matrix:C,u_globe_matrix:O,u_merc_matrix:U,u_grid_matrix:Y,u_tl_parent:Z,u_scale_parent:Ee,u_fade_t:He.mix,u_opacity:He.opacity*qe.paint.get("raster-opacity"),u_image0:0,u_image1:1,u_brightness_low:qe.paint.get("raster-brightness-min"),u_brightness_high:qe.paint.get("raster-brightness-max"),u_saturation_factor:o.dJ(qe.paint.get("raster-saturation")),u_contrast_factor:o.dI(qe.paint.get("raster-contrast")),u_spin_weights:qp(qe.paint.get("raster-hue-rotate")),u_perspective_transform:et,u_raster_elevation:ct,u_zoom_transition:se,u_merc_center:pe,u_cutoff_params:je,u_colorization_mix:jh(o.dK,bt,Pt),u_colorization_offset:md(o.dK,vt,Pt),u_color_ramp:ot,u_texture_offset:[jt/(Ft+2*jt),Ft/(Ft+2*jt)],u_texture_res:[Ft+2*jt,Ft+2*jt],u_emissive_strength:ys,u_zbias_factor:Kd(D)});function qp(D){D*=Math.PI/180;const w=Math.sin(D),C=Math.cos(D);return[(2*C+1)/3,(-Math.sqrt(3)*w-C+1)/3,(Math.sqrt(3)*w-C+1)/3]}const sd=.05,oc=(D,w,C,O,U,Y,Z,se,pe,je,Ee,He)=>({u_matrix:D,u_normalize_matrix:w,u_globe_matrix:C,u_merc_matrix:O,u_grid_matrix:U,u_tl_parent:Y,u_scale_parent:je,u_fade_t:Ee.mix,u_opacity:Ee.opacity,u_image0:0,u_image1:1,u_raster_elevation:He,u_zoom_transition:Z,u_merc_center:se,u_cutoff_params:pe}),Hc=(D,w,C,O,U,Y,Z,se,pe,je)=>({u_particle_texture:D,u_particle_texture_side_len:w,u_tile_offset:C,u_velocity:O,u_color_ramp:Y,u_velocity_res:U,u_max_speed:Z,u_uv_offset:se,u_data_scale:[255*pe[0],255*pe[1]],u_data_offset:je,u_particle_pos_scale:1.1,u_particle_pos_offset:[sd,sd]}),pu=(D,w,C,O,U,Y,Z,se,pe,je)=>({u_particle_texture:D,u_particle_texture_side_len:w,u_velocity:C,u_velocity_res:O,u_max_speed:U,u_speed_factor:Y,u_reset_rate:Z,u_rand_seed:Math.random(),u_uv_offset:se,u_data_scale:[255*pe[0],255*pe[1]],u_data_offset:je,u_particle_pos_scale:1.1,u_particle_pos_offset:[sd,sd]}),bc=o.bb(),Lu=(D,w,C,O,U,Y,Z,se,pe,je,Ee,He,qe,et,ct,ot,bt,vt,Pt,Ft,jt,ys,Qt,gs)=>{const $t=U.transform,Zt={u_is_size_zoom_constant:+(D==="constant"||D==="source"),u_is_size_feature_constant:+(D==="constant"||D==="camera"),u_size_t:w?w.uSizeT:0,u_size:w?w.uSize:0,u_camera_to_center_distance:$t.getCameraToCenterDistance(Pt),u_rotate_symbol:+C,u_aspect_ratio:$t.width/$t.height,u_fade_change:U.options.fadeDuration?U.symbolFadeChange:1,u_matrix:Y,u_label_plane_matrix:Z,u_coord_matrix:se,u_is_text:+je,u_elevation_from_sea:pe?1:0,u_pitch_with_map:+O,u_texsize:Ee,u_texsize_icon:He,u_texture:0,u_texture_icon:1,u_tile_id:[0,0,0],u_zoom_transition:0,u_inv_rot_matrix:bc,u_merc_center:[0,0],u_camera_forward:[0,0,0],u_ecef_origin:[0,0,0],u_tile_matrix:bc,u_up_vector:[0,-1,0],u_color_adj_mat:ys,u_icon_transition:Qt||0,u_gamma_scale:O?U.transform.getCameraToCenterDistance(Pt)*Math.cos(U.terrain?0:U.transform._pitch):1,u_device_pixel_ratio:o.o.devicePixelRatio,u_is_halo:1,u_scale_factor:gs||1,u_ground_shadow_factor:Ft,u_inv_matrix:o.b7(o.bb(),Z),u_normal_scale:jt,u_lutTexture:10,u_zoom:$t.zoom-Math.floor($t.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 Pt.name==="globe"&&(Zt.u_tile_id=[et.canonical.x,et.canonical.y,1<({u_matrix:D,u_emissive_strength:w,u_opacity:C,u_color:O}),Pc=(D,w,C,O,U,Y,Z,se,pe)=>Object.assign(function(je,Ee,He,qe,et,ct){const{width:ot,height:bt}=qe.imageManager.getPixelSize(Ee),vt=Math.pow(2,ct.tileID.overscaledZ),Pt=ct.tileSize*Math.pow(2,qe.transform.tileZoom)/vt,Ft=Pt*(ct.tileID.canonical.x+ct.tileID.wrap*vt),jt=Pt*ct.tileID.canonical.y;return{u_image:0,u_pattern_tl:He.tl,u_pattern_br:He.br,u_texsize:[ot,bt],u_pattern_size:He.displaySize,u_pattern_units_to_pixels:et?[qe.transform.width,-1*qe.transform.height]:[1/o.aA(ct,1,qe.transform.tileZoom),1/o.aA(ct,1,qe.transform.tileZoom)],u_pixel_coord_upper:[Ft>>16,jt>>16],u_pixel_coord_lower:[65535&Ft,65535&jt]}}(0,Y,Z,O,se,pe),{u_matrix:D,u_emissive_strength:w,u_opacity:C}),Zu=new Float32Array(o.b9([])),Dl=(D,w,C,O,U,Y,Z,se,pe,je,Ee,He,qe,et=[0,0,0],ct,ot,bt)=>{const vt=U.style.light,Pt=vt.properties.get("position"),Ft=[-Pt.x,-Pt.y,Pt.z],jt=o.dE();vt.properties.get("anchor")==="viewport"&&(o.dF(jt,-U.transform.angle),o.dG(Ft,Ft,jt));const ys=Ee.alphaMode==="MASK",Qt=vt.properties.get("color").toNonPremultipliedRenderColor(null),gs=qe.paint.get("model-ambient-occlusion-intensity"),$t=qe.paint.get("model-color").constantOr(o.aq.white).toNonPremultipliedRenderColor(null);return $t.a=qe.paint.get("model-color-mix-intensity").constantOr(0),bt&&($t.r=bt[0],$t.g=bt[1],$t.b=bt[2],$t.a=bt[3]),ot&&($t.r=ot.color.r,$t.g=ot.color.g,$t.b=ot.color.b,$t.a=ot.colorMix,He=ot.emissionStrength,Y*=ot.opacity),{u_matrix:D,u_lighting_matrix:w,u_normal_matrix:C,u_node_matrix:O||Zu,u_lightpos:Ft,u_lightintensity:vt.properties.get("intensity"),u_lightcolor:[Qt.r,Qt.g,Qt.b],u_camera_pos:et,u_opacity:Y,u_baseTextureIsAlpha:0,u_alphaMask:+ys,u_alphaCutoff:Ee.alphaCutoff,u_baseColorFactor:Z.toNonPremultipliedRenderColor(null).toArray01(),u_emissiveFactor:se.toNonPremultipliedRenderColor(null).toArray01(),u_metallicFactor:pe,u_roughnessFactor:je,u_baseColorTexture:5,u_metallicRoughnessTexture:6,u_normalTexture:7,u_occlusionTexture:8,u_emissionTexture:9,u_lutTexture:10,u_color_mix:$t.toArray01(),u_aoIntensity:gs,u_emissive_strength:He,u_occlusionTextureTransform:ct||[0,0,0,0]}},Pu=(D,w=Zu,C=Zu)=>({u_matrix:D,u_instance:w,u_node_matrix:C}),xm={fillExtrusion:D=>({u_matrix:new o.b$(D),u_lightpos:new o.bY(D),u_lightintensity:new o.bZ(D),u_lightcolor:new o.bY(D),u_vertical_gradient:new o.bZ(D),u_opacity:new o.bZ(D),u_edge_radius:new o.bZ(D),u_width_scale:new o.bZ(D),u_ao:new o.b_(D),u_height_type:new o.bX(D),u_base_type:new o.bX(D),u_tile_id:new o.bY(D),u_zoom_transition:new o.bZ(D),u_inv_rot_matrix:new o.b$(D),u_merc_center:new o.b_(D),u_up_dir:new o.bY(D),u_height_lift:new o.bZ(D),u_flood_light_color:new o.bY(D),u_vertical_scale:new o.bZ(D),u_flood_light_intensity:new o.bZ(D),u_ground_shadow_factor:new o.bY(D),u_front_cutoff_params:new o.bY(D)}),fillExtrusionDepth:D=>({u_matrix:new o.b$(D),u_edge_radius:new o.bZ(D),u_width_scale:new o.bZ(D),u_vertical_scale:new o.bZ(D),u_height_type:new o.bX(D),u_base_type:new o.bX(D)}),fillExtrusionPattern:D=>({u_matrix:new o.b$(D),u_lightpos:new o.bY(D),u_lightintensity:new o.bZ(D),u_lightcolor:new o.bY(D),u_vertical_gradient:new o.bZ(D),u_height_factor:new o.bZ(D),u_edge_radius:new o.bZ(D),u_width_scale:new o.bZ(D),u_ao:new o.b_(D),u_height_type:new o.bX(D),u_base_type:new o.bX(D),u_tile_id:new o.bY(D),u_zoom_transition:new o.bZ(D),u_inv_rot_matrix:new o.b$(D),u_merc_center:new o.b_(D),u_up_dir:new o.bY(D),u_height_lift:new o.bZ(D),u_image:new o.bX(D),u_texsize:new o.b_(D),u_pixel_coord_upper:new o.b_(D),u_pixel_coord_lower:new o.b_(D),u_tile_units_to_pixels:new o.bZ(D),u_opacity:new o.bZ(D),u_pattern_transition:new o.bZ(D)}),fillExtrusionGroundEffect:D=>({u_matrix:new o.b$(D),u_opacity:new o.bZ(D),u_ao_pass:new o.bZ(D),u_meter_to_tile:new o.bZ(D),u_ao:new o.b_(D),u_flood_light_intensity:new o.bZ(D),u_flood_light_color:new o.bY(D),u_attenuation:new o.bZ(D),u_edge_radius:new o.bZ(D),u_fb:new o.bX(D),u_fb_size:new o.bZ(D),u_dynamic_offset:new o.bZ(D)}),fill:D=>({u_matrix:new o.b$(D),u_emissive_strength:new o.bZ(D),u_ground_shadow_factor:new o.bY(D)}),fillPattern:D=>({u_matrix:new o.b$(D),u_emissive_strength:new o.bZ(D),u_image:new o.bX(D),u_texsize:new o.b_(D),u_pixel_coord_upper:new o.b_(D),u_pixel_coord_lower:new o.b_(D),u_tile_units_to_pixels:new o.bZ(D),u_ground_shadow_factor:new o.bY(D),u_pattern_transition:new o.bZ(D)}),fillOutline:D=>({u_matrix:new o.b$(D),u_emissive_strength:new o.bZ(D),u_world:new o.b_(D),u_ground_shadow_factor:new o.bY(D)}),fillOutlinePattern:D=>({u_matrix:new o.b$(D),u_emissive_strength:new o.bZ(D),u_world:new o.b_(D),u_image:new o.bX(D),u_texsize:new o.b_(D),u_pixel_coord_upper:new o.b_(D),u_pixel_coord_lower:new o.b_(D),u_tile_units_to_pixels:new o.bZ(D),u_ground_shadow_factor:new o.bY(D),u_pattern_transition:new o.bZ(D)}),lineBlendComposite:D=>({u_image:new o.bX(D),u_opacity:new o.bZ(D),u_blend_mode:new o.bX(D)}),building:D=>({u_matrix:new o.b$(D),u_normal_matrix:new o.b$(D),u_opacity:new o.bZ(D),u_faux_facade_ao_intensity:new o.bZ(D),u_camera_pos:new o.bY(D),u_tile_to_meter:new o.bZ(D),u_facade_emissive_chance:new o.bZ(D),u_flood_light_color:new o.bY(D),u_flood_light_intensity:new o.bZ(D),u_front_cutoff_params:new o.bY(D)}),buildingBloom:D=>({u_matrix:new o.b$(D)}),buildingDepth:D=>({u_matrix:new o.b$(D)}),elevatedStructuresDepth:D=>({u_matrix:new o.b$(D),u_depth_bias:new o.bZ(D)}),elevatedStructures:D=>({u_matrix:new o.b$(D),u_ground_shadow_factor:new o.bY(D)}),elevatedStructuresDepthReconstruct:D=>({u_matrix:new o.b$(D),u_camera_pos:new o.bY(D),u_depth_bias:new o.bZ(D),u_height_scale:new o.bZ(D),u_reset_depth:new o.bZ(D)}),circle:o.dO,collisionBox:D=>({u_matrix:new o.b$(D),u_inv_rot_matrix:new o.b$(D),u_camera_to_center_distance:new o.bZ(D),u_extrude_scale:new o.b_(D),u_zoom_transition:new o.bZ(D),u_merc_center:new o.b_(D),u_tile_id:new o.bY(D)}),collisionCircle:D=>({u_matrix:new o.b$(D),u_inv_matrix:new o.b$(D),u_camera_to_center_distance:new o.bZ(D),u_viewport_size:new o.b_(D)}),debug:D=>({u_color:new o.dl(D),u_matrix:new o.b$(D),u_overlay:new o.bX(D),u_overlay_scale:new o.bZ(D)}),clippingMask:D=>({u_matrix:new o.b$(D)}),heatmap:D=>({u_extrude_scale:new o.bZ(D),u_intensity:new o.bZ(D),u_matrix:new o.b$(D),u_inv_rot_matrix:new o.b$(D),u_merc_center:new o.b_(D),u_tile_id:new o.bY(D),u_zoom_transition:new o.bZ(D),u_up_dir:new o.bY(D)}),heatmapTexture:D=>({u_image:new o.bX(D),u_color_ramp:new o.bX(D),u_opacity:new o.bZ(D)}),hillshade:D=>({u_matrix:new o.b$(D),u_image:new o.bX(D),u_latrange:new o.b_(D),u_light:new o.b_(D),u_shadow:new o.dl(D),u_highlight:new o.dl(D),u_emissive_strength:new o.bZ(D),u_accent:new o.dl(D)}),hillshadePrepare:D=>({u_matrix:new o.b$(D),u_image:new o.bX(D),u_dimension:new o.b_(D),u_zoom:new o.bZ(D)}),line:o.dN,linePattern:o.dM,raster:D=>({u_matrix:new o.b$(D),u_normalize_matrix:new o.b$(D),u_globe_matrix:new o.b$(D),u_merc_matrix:new o.b$(D),u_grid_matrix:new o.dm(D),u_tl_parent:new o.b_(D),u_scale_parent:new o.bZ(D),u_fade_t:new o.bZ(D),u_opacity:new o.bZ(D),u_image0:new o.bX(D),u_image1:new o.bX(D),u_brightness_low:new o.bZ(D),u_brightness_high:new o.bZ(D),u_saturation_factor:new o.bZ(D),u_contrast_factor:new o.bZ(D),u_spin_weights:new o.bY(D),u_perspective_transform:new o.b_(D),u_raster_elevation:new o.bZ(D),u_zoom_transition:new o.bZ(D),u_merc_center:new o.b_(D),u_cutoff_params:new o.cO(D),u_colorization_mix:new o.cO(D),u_colorization_offset:new o.bZ(D),u_color_ramp:new o.bX(D),u_texture_offset:new o.b_(D),u_texture_res:new o.b_(D),u_emissive_strength:new o.bZ(D),u_zbias_factor:new o.bZ(D)}),rasterParticle:D=>({u_matrix:new o.b$(D),u_normalize_matrix:new o.b$(D),u_globe_matrix:new o.b$(D),u_merc_matrix:new o.b$(D),u_grid_matrix:new o.dm(D),u_tl_parent:new o.b_(D),u_scale_parent:new o.bZ(D),u_fade_t:new o.bZ(D),u_opacity:new o.bZ(D),u_image0:new o.bX(D),u_image1:new o.bX(D),u_raster_elevation:new o.bZ(D),u_zoom_transition:new o.bZ(D),u_merc_center:new o.b_(D),u_cutoff_params:new o.cO(D)}),rasterParticleTexture:D=>({u_texture:new o.bX(D),u_opacity:new o.bZ(D)}),rasterParticleDraw:D=>({u_particle_texture:new o.bX(D),u_particle_texture_side_len:new o.bZ(D),u_tile_offset:new o.b_(D),u_velocity:new o.bX(D),u_color_ramp:new o.bX(D),u_velocity_res:new o.b_(D),u_max_speed:new o.bZ(D),u_uv_offset:new o.b_(D),u_data_scale:new o.b_(D),u_data_offset:new o.bZ(D),u_particle_pos_scale:new o.bZ(D),u_particle_pos_offset:new o.b_(D)}),rasterParticleUpdate:D=>({u_particle_texture:new o.bX(D),u_particle_texture_side_len:new o.bZ(D),u_velocity:new o.bX(D),u_velocity_res:new o.b_(D),u_max_speed:new o.bZ(D),u_speed_factor:new o.bZ(D),u_reset_rate:new o.bZ(D),u_rand_seed:new o.bZ(D),u_uv_offset:new o.b_(D),u_data_scale:new o.b_(D),u_data_offset:new o.bZ(D),u_particle_pos_scale:new o.bZ(D),u_particle_pos_offset:new o.b_(D)}),symbol:D=>({u_is_size_zoom_constant:new o.bX(D),u_is_size_feature_constant:new o.bX(D),u_size_t:new o.bZ(D),u_size:new o.bZ(D),u_camera_to_center_distance:new o.bZ(D),u_rotate_symbol:new o.bX(D),u_aspect_ratio:new o.bZ(D),u_fade_change:new o.bZ(D),u_matrix:new o.b$(D),u_label_plane_matrix:new o.b$(D),u_coord_matrix:new o.b$(D),u_is_text:new o.bX(D),u_elevation_from_sea:new o.bX(D),u_pitch_with_map:new o.bX(D),u_texsize:new o.b_(D),u_texsize_icon:new o.b_(D),u_texture:new o.bX(D),u_texture_icon:new o.bX(D),u_gamma_scale:new o.bZ(D),u_device_pixel_ratio:new o.bZ(D),u_tile_id:new o.bY(D),u_zoom_transition:new o.bZ(D),u_inv_rot_matrix:new o.b$(D),u_merc_center:new o.b_(D),u_camera_forward:new o.bY(D),u_tile_matrix:new o.b$(D),u_up_vector:new o.bY(D),u_ecef_origin:new o.bY(D),u_is_halo:new o.bX(D),u_icon_transition:new o.bZ(D),u_color_adj_mat:new o.b$(D),u_scale_factor:new o.bZ(D),u_ground_shadow_factor:new o.bY(D),u_inv_matrix:new o.b$(D),u_normal_scale:new o.bZ(D),u_lutTexture:new o.bX(D),u_zoom:new o.bZ(D),u_spp_fill_np_color:new o.cO(D),u_spp_halo_np_color:new o.cO(D),u_spp_opacity:new o.bZ(D),u_spp_halo_width:new o.bZ(D),u_spp_halo_blur:new o.bZ(D),u_spp_emissive_strength:new o.bZ(D),u_spp_occlusion_opacity:new o.bZ(D),u_spp_z_offset:new o.bZ(D),u_spp_translate_rotation:new o.b_(D)}),background:D=>({u_matrix:new o.b$(D),u_emissive_strength:new o.bZ(D),u_opacity:new o.bZ(D),u_color:new o.dl(D)}),backgroundPattern:D=>({u_matrix:new o.b$(D),u_emissive_strength:new o.bZ(D),u_opacity:new o.bZ(D),u_image:new o.bX(D),u_pattern_tl:new o.b_(D),u_pattern_br:new o.b_(D),u_texsize:new o.b_(D),u_pattern_size:new o.b_(D),u_pixel_coord_upper:new o.b_(D),u_pixel_coord_lower:new o.b_(D),u_pattern_units_to_pixels:new o.b_(D)}),terrainRaster:D=>({u_matrix:new o.b$(D),u_image0:new o.bX(D),u_image1:new o.bX(D),u_skirt_height:new o.bZ(D),u_ground_shadow_factor:new o.bY(D),u_emissive_texture_available:new o.bZ(D)}),skybox:D=>({u_matrix:new o.b$(D),u_sun_direction:new o.bY(D),u_cubemap:new o.bX(D),u_opacity:new o.bZ(D),u_temporal_offset:new o.bZ(D)}),skyboxGradient:D=>({u_matrix:new o.b$(D),u_color_ramp:new o.bX(D),u_center_direction:new o.bY(D),u_radius:new o.bZ(D),u_opacity:new o.bZ(D),u_temporal_offset:new o.bZ(D)}),skyboxCapture:D=>({u_matrix_3f:new o.dm(D),u_sun_direction:new o.bY(D),u_sun_intensity:new o.bZ(D),u_color_tint_r:new o.cO(D),u_color_tint_m:new o.cO(D),u_luminance:new o.bZ(D)}),globeRaster:D=>({u_proj_matrix:new o.b$(D),u_globe_matrix:new o.b$(D),u_normalize_matrix:new o.b$(D),u_merc_matrix:new o.b$(D),u_zoom_transition:new o.bZ(D),u_merc_center:new o.b_(D),u_image0:new o.bX(D),u_image1:new o.bX(D),u_grid_matrix:new o.dm(D),u_skirt_height:new o.bZ(D),u_far_z_cutoff:new o.bZ(D),u_frustum_tl:new o.bY(D),u_frustum_tr:new o.bY(D),u_frustum_br:new o.bY(D),u_frustum_bl:new o.bY(D),u_globe_pos:new o.bY(D),u_globe_radius:new o.bZ(D),u_viewport:new o.b_(D),u_emissive_texture_available:new o.bZ(D)}),globeAtmosphere:D=>({u_frustum_tl:new o.bY(D),u_frustum_tr:new o.bY(D),u_frustum_br:new o.bY(D),u_frustum_bl:new o.bY(D),u_horizon:new o.bZ(D),u_transition:new o.bZ(D),u_fadeout_range:new o.bZ(D),u_atmosphere_fog_color:new o.cO(D),u_high_color:new o.cO(D),u_space_color:new o.cO(D),u_temporal_offset:new o.bZ(D),u_horizon_angle:new o.bZ(D)}),model:D=>({u_matrix:new o.b$(D),u_lighting_matrix:new o.b$(D),u_normal_matrix:new o.b$(D),u_node_matrix:new o.b$(D),u_lightpos:new o.bY(D),u_lightintensity:new o.bZ(D),u_lightcolor:new o.bY(D),u_camera_pos:new o.bY(D),u_opacity:new o.bZ(D),u_baseColorFactor:new o.cO(D),u_emissiveFactor:new o.cO(D),u_metallicFactor:new o.bZ(D),u_roughnessFactor:new o.bZ(D),u_baseTextureIsAlpha:new o.bX(D),u_alphaMask:new o.bX(D),u_alphaCutoff:new o.bZ(D),u_baseColorTexture:new o.bX(D),u_metallicRoughnessTexture:new o.bX(D),u_normalTexture:new o.bX(D),u_occlusionTexture:new o.bX(D),u_emissionTexture:new o.bX(D),u_lutTexture:new o.bX(D),u_color_mix:new o.cO(D),u_aoIntensity:new o.bZ(D),u_emissive_strength:new o.bZ(D),u_occlusionTextureTransform:new o.cO(D)}),modelDepth:D=>({u_matrix:new o.b$(D),u_instance:new o.b$(D),u_node_matrix:new o.b$(D)}),groundShadow:D=>({u_matrix:new o.b$(D),u_ground_shadow_factor:new o.bY(D)}),stars:D=>({u_matrix:new o.b$(D),u_up:new o.bY(D),u_right:new o.bY(D),u_intensity_multiplier:new o.bZ(D)}),snowParticle:D=>({u_modelview:new o.b$(D),u_projection:new o.b$(D),u_time:new o.bZ(D),u_cam_pos:new o.bY(D),u_velocityConeAperture:new o.bZ(D),u_velocity:new o.bZ(D),u_horizontalOscillationRadius:new o.bZ(D),u_horizontalOscillationRate:new o.bZ(D),u_boxSize:new o.bZ(D),u_billboardSize:new o.bZ(D),u_simpleShapeParameters:new o.b_(D),u_screenSize:new o.b_(D),u_thinningCenterPos:new o.b_(D),u_thinningShape:new o.bY(D),u_thinningAffectedRatio:new o.bZ(D),u_thinningParticleOffset:new o.bZ(D),u_particleColor:new o.cO(D),u_direction:new o.bY(D)}),rainParticle:D=>({u_modelview:new o.b$(D),u_projection:new o.b$(D),u_time:new o.bZ(D),u_cam_pos:new o.bY(D),u_texScreen:new o.bX(D),u_velocityConeAperture:new o.bZ(D),u_velocity:new o.bZ(D),u_boxSize:new o.bZ(D),u_rainDropletSize:new o.b_(D),u_distortionStrength:new o.bZ(D),u_rainDirection:new o.bY(D),u_color:new o.cO(D),u_screenSize:new o.b_(D),u_thinningCenterPos:new o.b_(D),u_thinningShape:new o.bY(D),u_thinningAffectedRatio:new o.bZ(D),u_thinningParticleOffset:new o.bZ(D),u_shapeDirectionalPower:new o.bZ(D),u_shapeNormalPower:new o.bZ(D),u_mode:new o.bZ(D)}),vignette:D=>({u_vignetteShape:new o.bY(D),u_vignetteColor:new o.cO(D)}),occlusion:D=>({u_matrix:new o.b$(D),u_anchorPos:new o.bY(D),u_screenSizePx:new o.b_(D),u_occluderSizePx:new o.b_(D),u_color:new o.cO(D)})};class wd{constructor(w,C,O,U){this.id=wd.uniqueIdxCounter,wd.uniqueIdxCounter++,this.context=w;const Y=w.gl;this.buffer=Y.createBuffer(),this.dynamicDraw=!!O,this.context.unbindVAO(),w.bindElementBuffer.set(this.buffer),Y.bufferData(Y.ELEMENT_ARRAY_BUFFER,C.arrayBuffer,this.dynamicDraw?Y.DYNAMIC_DRAW:Y.STATIC_DRAW),this.dynamicDraw||U||C.destroy()}bind(){this.context.bindElementBuffer.set(this.buffer)}updateData(w){this.id=wd.uniqueIdxCounter,wd.uniqueIdxCounter++;const C=this.context.gl;this.context.unbindVAO(),this.bind(),C.bufferSubData(C.ELEMENT_ARRAY_BUFFER,0,w.arrayBuffer)}destroy(){this.buffer&&(this.context.gl.deleteBuffer(this.buffer),delete this.buffer)}}wd.uniqueIdxCounter=0;const Vp={Int8:"BYTE",Uint8:"UNSIGNED_BYTE",Int16:"SHORT",Uint16:"UNSIGNED_SHORT",Int32:"INT",Uint32:"UNSIGNED_INT",Float32:"FLOAT"};class Hp{constructor(w,C,O,U,Y,Z){this.length=C.length,this.attributes=O,this.itemSize=C.bytesPerElement,this.dynamicDraw=U,this.instanceCount=Z,this.context=w;const se=w.gl;this.buffer=se.createBuffer(),w.bindVertexBuffer.set(this.buffer),se.bufferData(se.ARRAY_BUFFER,C.arrayBuffer,this.dynamicDraw?se.DYNAMIC_DRAW:se.STATIC_DRAW),this.dynamicDraw||Y||C.destroy()}bind(){this.context.bindVertexBuffer.set(this.buffer)}updateData(w){const C=this.context.gl;this.bind(),C.bufferSubData(C.ARRAY_BUFFER,0,w.arrayBuffer)}enableAttributes(w,C){for(const O of this.attributes){const U=C.getAttributeLocation(w,O.name);U!==-1&&w.enableVertexAttribArray(U)}}setVertexAttribPointers(w,C,O){for(const U of this.attributes){const Y=C.getAttributeLocation(w,U.name);if(Y!==-1){const Z=U.offset+this.itemSize*(O||0);U.type==="Float32"?w.vertexAttribPointer(Y,U.components,w.FLOAT,!1,this.itemSize,Z):w.vertexAttribIPointer(Y,U.components,w[Vp[U.type]],this.itemSize,Z)}}}setVertexAttribDivisor(w,C,O){for(let U=0;U0&&w.vertexAttribDivisor(Y,O)}}destroy(){this.buffer&&(this.context.gl.deleteBuffer(this.buffer),delete this.buffer)}}class ym{constructor(w,C,O,U,Y){this.context=w,this.width=C,this.height=O;const Z=this.framebuffer=w.gl.createFramebuffer();U>0&&(this.colorAttachment0=new Pb(w,Z,0)),U>1&&(this.colorAttachment1=new Pb(w,Z,1)),Y&&(this.depthAttachmentType=Y,this.depthAttachment=Y==="renderbuffer"?new $j(w,Z):new DN(w,Z))}static createWithTexture(w,C,O,U,Y){const Z=w.gl;if(w.activeTexture.set(Z.TEXTURE1),w.viewport.set([0,0,O,U]),C&&C.width===O&&C.height===U)return Z.bindTexture(Z.TEXTURE_2D,C.colorAttachment0.get()),w.bindFramebuffer.set(C.framebuffer),C;C&&C.destroy();const se=new o.T(w,{width:O,height:U,data:null},w.extRenderToTextureHalfFloat?w.gl.RGBA16F:w.gl.RGBA8);se.bind(Z.LINEAR,Z.CLAMP_TO_EDGE);const pe=w.createFramebuffer(O,U,1,null);if(pe.colorAttachment0.set(se.texture),Y){const je=w.createRenderbuffer(Z.DEPTH24_STENCIL8,O,U);w.bindFramebuffer.set(pe.framebuffer),Z.framebufferRenderbuffer(Z.FRAMEBUFFER,Z.DEPTH_STENCIL_ATTACHMENT,Z.RENDERBUFFER,je),pe._stencilRbo=je}return pe}createColorAttachment(w,C){C===0?this.colorAttachment0=new Pb(w,this.framebuffer,0):C===1&&(this.colorAttachment1=new Pb(w,this.framebuffer,1))}removeColorAttachment(w,C){const O=this.context.gl;let U;C===0?(U=this.colorAttachment0.get(),this.colorAttachment0=void 0):C===1&&(U=this.colorAttachment1.get(),this.colorAttachment1=void 0),U&&O.deleteTexture(U)}destroy(){const w=this.context.gl;if(this.colorAttachment0){const C=this.colorAttachment0.get();C&&w.deleteTexture(C)}if(this.colorAttachment1){const C=this.colorAttachment1.get();C&&w.deleteTexture(C)}if(this.depthAttachment&&this.depthAttachmentType)if(this.depthAttachmentType==="renderbuffer"){const C=this.depthAttachment.get();C&&w.deleteRenderbuffer(C)}else{const C=this.depthAttachment.get();C&&w.deleteTexture(C)}this._stencilRbo&&(w.deleteRenderbuffer(this._stencilRbo),this._stencilRbo=null),w.deleteFramebuffer(this.framebuffer)}}class dh{constructor(w,C){this.gl=w,this.clearColor=new Mb(this),this.clearDepth=new lS(this),this.clearStencil=new f1(this),this.colorMask=new i6(this),this.depthMask=new yx(this),this.stencilMask=new sw(this),this.stencilFunc=new Lb(this),this.stencilOp=new EN(this),this.stencilTest=new g1(this),this.depthRange=new x1(this),this.depthTest=new Cf(this),this.depthFunc=new Wd(this),this.blend=new vx(this),this.blendFunc=new zj(this),this.blendColor=new cS(this),this.blendEquation=new eg(this),this.cullFace=new $p(this),this.cullFaceSide=new Bj(this),this.frontFace=new MN(this),this.program=new nw(this),this.activeTexture=new rw(this),this.viewport=new Up(this),this.bindFramebuffer=new rp(this),this.bindRenderbuffer=new dS(this),this.bindTexture=new cy(this),this.bindVertexBuffer=new aw(this),this.bindElementBuffer=new iw(this),this.bindVertexArrayOES=new LN(this),this.pixelStoreUnpack=new PN(this),this.pixelStoreUnpackPremultiplyAlpha=new IN(this),this.pixelStoreUnpackFlipY=new ow(this),this.options=C?Object.assign({},C):{},this.options.extTextureFilterAnisotropicForceOff||(this.extTextureFilterAnisotropic=w.getExtension("EXT_texture_filter_anisotropic")||w.getExtension("MOZ_EXT_texture_filter_anisotropic")||w.getExtension("WEBKIT_EXT_texture_filter_anisotropic"),this.extTextureFilterAnisotropic&&(this.extTextureFilterAnisotropicMax=w.getParameter(this.extTextureFilterAnisotropic.MAX_TEXTURE_MAX_ANISOTROPY_EXT))),this.extDebugRendererInfo=w.getExtension("WEBGL_debug_renderer_info"),this.extDebugRendererInfo&&(this.renderer=w.getParameter(this.extDebugRendererInfo.UNMASKED_RENDERER_WEBGL),this.vendor=w.getParameter(this.extDebugRendererInfo.UNMASKED_VENDOR_WEBGL)),this.forceManualRenderingForInstanceIDShaders=C&&!!C.forceManualRenderingForInstanceIDShaders||this.renderer&&this.renderer.indexOf("PowerVR")!==-1,this.disableSymbolUBO=C&&!!C.forceDisableSymbolUBO,this.options.extTextureFloatLinearForceOff||(this.extTextureFloatLinear=w.getExtension("OES_texture_float_linear")),this.extRenderToTextureHalfFloat=w.getExtension("EXT_color_buffer_half_float"),this.extTimerQuery=w.getExtension("EXT_disjoint_timer_query_webgl2"),this.maxTextureSize=w.getParameter(w.MAX_TEXTURE_SIZE),this.maxUniformBlockSize=Math.min(w.getParameter(w.MAX_UNIFORM_BLOCK_SIZE),32768),this.maxUniformBufferBindings=w.getParameter(w.MAX_UNIFORM_BUFFER_BINDINGS),this.extBlendFuncExtended=w.getExtension("WEBGL_blend_func_extended")}setDefault(){this.unbindVAO(),this.clearColor.setDefault(),this.clearDepth.setDefault(),this.clearStencil.setDefault(),this.colorMask.setDefault(),this.depthMask.setDefault(),this.stencilMask.setDefault(),this.stencilFunc.setDefault(),this.stencilOp.setDefault(),this.stencilTest.setDefault(),this.depthRange.setDefault(),this.depthTest.setDefault(),this.depthFunc.setDefault(),this.blend.setDefault(),this.blendFunc.setDefault(),this.blendColor.setDefault(),this.blendEquation.setDefault(),this.cullFace.setDefault(),this.cullFaceSide.setDefault(),this.frontFace.setDefault(),this.program.setDefault(),this.activeTexture.setDefault(),this.bindFramebuffer.setDefault(),this.pixelStoreUnpack.setDefault(),this.pixelStoreUnpackPremultiplyAlpha.setDefault(),this.pixelStoreUnpackFlipY.setDefault()}setDirty(){this.clearColor.dirty=!0,this.clearDepth.dirty=!0,this.clearStencil.dirty=!0,this.colorMask.dirty=!0,this.depthMask.dirty=!0,this.stencilMask.dirty=!0,this.stencilFunc.dirty=!0,this.stencilOp.dirty=!0,this.stencilTest.dirty=!0,this.depthRange.dirty=!0,this.depthTest.dirty=!0,this.depthFunc.dirty=!0,this.blend.dirty=!0,this.blendFunc.dirty=!0,this.blendColor.dirty=!0,this.blendEquation.dirty=!0,this.cullFace.dirty=!0,this.cullFaceSide.dirty=!0,this.frontFace.dirty=!0,this.program.dirty=!0,this.activeTexture.dirty=!0,this.viewport.dirty=!0,this.bindFramebuffer.dirty=!0,this.bindRenderbuffer.dirty=!0,this.bindTexture.dirty=!0,this.bindVertexBuffer.dirty=!0,this.bindElementBuffer.dirty=!0,this.bindVertexArrayOES.dirty=!0,this.pixelStoreUnpack.dirty=!0,this.pixelStoreUnpackPremultiplyAlpha.dirty=!0,this.pixelStoreUnpackFlipY.dirty=!0}createIndexBuffer(w,C,O){return new wd(this,w,C,O)}createVertexBuffer(w,C,O,U,Y){return new Hp(this,w,C,O,U,Y)}createRenderbuffer(w,C,O){const U=this.gl,Y=U.createRenderbuffer();return this.bindRenderbuffer.set(Y),U.renderbufferStorage(U.RENDERBUFFER,w,C,O),this.bindRenderbuffer.set(null),Y}createFramebuffer(w,C,O,U){return new ym(this,w,C,O,U)}clear({color:w,depth:C,stencil:O,colorMask:U}){const Y=this.gl;let Z=0;w&&(Z|=Y.COLOR_BUFFER_BIT,this.clearColor.set(w.toNonPremultipliedRenderColor(null)),this.colorMask.set(U||[!0,!0,!0,!0])),C!==void 0&&(Z|=Y.DEPTH_BUFFER_BIT,this.depthRange.set([0,1]),this.clearDepth.set(C),this.depthMask.set(!0)),O!==void 0&&(Z|=Y.STENCIL_BUFFER_BIT,this.clearStencil.set(O),this.stencilMask.set(255)),Y.clear(Z)}setCullFace(w){w.enable===!1?this.cullFace.set(!1):(this.cullFace.set(!0),this.cullFaceSide.set(w.mode),this.frontFace.set(w.frontFace))}setDepthMode(w){w.func!==this.gl.ALWAYS||w.mask?(this.depthTest.set(!0),this.depthFunc.set(w.func),this.depthMask.set(w.mask),this.depthRange.set(w.range)):this.depthTest.set(!1)}setStencilMode(w){w.test.func!==this.gl.ALWAYS||w.mask?(this.stencilTest.set(!0),this.stencilMask.set(w.mask),this.stencilOp.set([w.fail,w.depthFail,w.pass]),this.stencilFunc.set({func:w.test.func,ref:w.ref,mask:w.test.mask})):this.stencilTest.set(!1)}setColorMode(w){o.b6(w.blendFunction,wa.Replace)?this.blend.set(!1):(this.blend.set(!0),this.blendFunc.set(w.blendFunction),this.blendColor.set(w.blendColor),w.blendEquation?this.blendEquation.set(w.blendEquation):this.blendEquation.setDefault()),this.colorMask.set(w.mask)}unbindVAO(){this.bindVertexArrayOES.set(null)}}let lc;function pr(D,w,C,O,U,Y,Z){const se=D.context,pe=se.gl,je=D.transform,Ee=[o.aH(je.center.lng),o.aL(je.center.lat)],He=C.layout.get("symbol-placement"),qe=C.layout.get("text-variable-anchor"),et=C.layout.get("icon-rotation-alignment")==="map",ct=C.layout.get("text-rotation-alignment")==="map",ot=He!=="point",bt=[];let vt=0,Pt=0;for(let $t=0;$t0){const fa=o.bb(),Fr=nr;o.cz(fa,Us.placementInvProjMatrix,je.glCoordMatrix),o.cz(fa,fa,Us.placementViewportMatrix),bt.push({circleArray:In,circleOffset:Pt,transform:Fr,invTransform:fa,projection:Us.getProjection()}),vt+=In.length/4,Pt=vt}if(!rr)continue;D.terrain&&D.terrain.setupElevationDraw(hs,fr);const Yr=pn?[Zt.canonical.x,Zt.canonical.y,1<=0&&(et[Ft.associatedIconIndex]={x:Cs,y:hn,z:an,angle:cn})}else Xn(Qt,He)}if(je){qe.clear();const Pt=D.icon.placedSymbolArray;for(let Ft=0;Ft{let ui=[0,0,0];if($o){const Ic=D.style.directionalLight,vl=D.style.ambientLight;Ic&&vl&&(ui=oh(D.style,Ic,vl))}return ui},Pi=$o=>{if(D.context.disableSymbolUBO)return;$o.push("USE_PAINT_PROPERTIES_UBO");const ui=Math.floor(D.context.maxUniformBlockSize/4),Ic=Math.floor(ui/4);$o.push(`MAX_UBO_SIZE_VEC4 ${Ic}u`)},ti=$o=>{Zt.depthOcclusionForSymbolsAndCircles&&(C.hasOcclusionOpacityProperties||D.terrain)&&($o.push("DEPTH_D24"),$o.push("DEPTH_OCCLUSION"))},So=$o=>{C.lut&&!Qt&&(C.lut.texture||(C.lut.texture=new o.dR(D.context,C.lut.image,[C.lut.image.height,C.lut.image.height,C.lut.image.height],gs.gl.RGBA8)),gs.activeTexture.set(gs.gl.TEXTURE0+10),C.lut.texture&&C.lut.texture.bind(gs.gl.LINEAR,gs.gl.CLAMP_TO_EDGE),$o.push("APPLY_LUT_ON_GPU"))},yl=()=>{const $o=hs&&C.layout.get("symbol-placement")!=="point",ui=[];ti(ui),So(ui);const Ic=$o||ri,vl=In.elevationType==="road",Ru=D.shadowRenderer,Xi=vl&&Cs&&!!Ru&&Ru.enabled,Rl=Ea(Xi),uh=vl&&Cs&&!D.terrain?Ks:On,Ef=C.paint.get("icon-image-cross-fade");D.terrainRenderModeElevated()&&Cs&&ui.push("PITCH_WITH_MAP_TERRAIN"),Yr&&(ui.push("PROJECTION_GLOBE_VIEW"),Ic&&ui.push("PROJECTED_POS_ON_VIEWPORT")),Ef>0&&In.hasAnySecondaryIcon&&ui.push("ICON_TRANSITION"),!In.icon.zOffsetVertexBuffer||vl&&D.terrain||ui.push("Z_OFFSET"),vt===0&&Pt===0&&Ft===0&&jt===1||ui.push("COLOR_ADJUSTMENT"),In.sdfIcons&&ui.push("RENDER_SDF"),Xi&&ui.push("RENDER_SHADOWS","NORMAL_OFFSET"),vl&&Cs&&!D.terrain&&In.icon.orientationVertexBuffer&&ui.push("ELEVATED_ROADS"),Pi(ui);const kh=gs.disableSymbolUBO?In.icon.programConfigurations.get(C.id):null,ip=D.getOrCreateProgram("symbol",{config:kh,defines:ui}),my=rr.imageAtlasTexture?rr.imageAtlasTexture.size:[0,0],sl=In.iconSizeData,dv=o.bj(sl,Zt.zoom),uv=Cs||!Zt.isOrthographic,Ql=Jc(Fr,rr.tileID.canonical,Cs,hs,Zt,In.getProjection(),Vr),uc=Qm(Fr,rr.tileID.canonical,Cs,hs,Zt,In.getProjection(),Vr),cl=In.icon.uboBinder&&In.icon.uboBinder.cachedHeader&&256&In.icon.uboBinder.cachedHeader.dataDrivenMask?[0,0]:se,gu=D.translatePosMatrix(uc,rr,cl,je,!0),ng=D.translatePosMatrix(Fr,rr,cl,je),Nd=Ic?fo:Ql,py=hs&&!Cs&&!$o;let qN=fr;!pn&&!Zt.mercatorFromTransition||hs||(qN=kc(Zt));const bS=Yr?qN:fr,_S=C.getColorAdjustmentMatrix(vt,Pt,Ft,jt),sC=Lu(sl.kind,dv,py,Cs,D,ng,Nd,gu,ys,!1,my,[0,0],0,nr,fa,Es,ei,bS,In.getProjection(),Rl,Li,_S,Ef,null),Wj=rr.imageAtlasTexture?rr.imageAtlasTexture:null,gw=C.layout.get("icon-size").constantOr(0)!==1||In.iconsNeedLinear,nC=In.sdfIcons||D.options.rotating||D.options.zooming||gw||uv?$t.LINEAR:$t.NEAREST,y0=In.sdfIcons&&C.paint.get("icon-halo-width").constantOr(1)!==0,VN=D.terrain&&Cs&&$o?o.b7(o.bb(),Ql):fo;if($o&&In.icon){const HN=o.bu.getAtTileOffsetFunc(nr,Zt.center.lat,Zt.worldSize,In.getProjection()),GN=Nc(Fr,rr.tileID.canonical,Cs,hs,Zt,In.getProjection(),Vr),AO=C.layout.get("icon-size-scale-range"),rC=o.aC(D.scaleFactor,AO[0],AO[1]);Wt(In,Fr,D,!1,GN,uc,Cs,ot,HN,nr,rC)}return{program:ip,buffers:In.icon,uniformValues:sC,atlasTexture:Wj,atlasTextureIcon:null,atlasInterpolation:nC,atlasInterpolationIcon:null,isSDF:In.sdfIcons,hasHalo:y0,depthMode:uh,tile:rr,renderWithShadows:Xi,labelPlaneMatrixInv:VN}},Gc=()=>{const $o=Us&&C.layout.get("symbol-placement")!=="point",ui=[],Ic=$o||cn||ri,vl=In.elevationType==="road",Ru=D.shadowRenderer,Xi=vl&&hn&&!!Ru&&Ru.enabled,Rl=Ea(Xi),uh=vl&&hn&&!D.terrain?Ks:On;D.terrainRenderModeElevated()&&hn&&ui.push("PITCH_WITH_MAP_TERRAIN"),Yr&&(ui.push("PROJECTION_GLOBE_VIEW"),Ic&&ui.push("PROJECTED_POS_ON_VIEWPORT")),!In.text.zOffsetVertexBuffer||vl&&D.terrain||ui.push("Z_OFFSET"),In.iconsInText&&ui.push("RENDER_TEXT_AND_SYMBOL"),ui.push("RENDER_SDF"),Xi&&ui.push("RENDER_SHADOWS","NORMAL_OFFSET"),vl&&hn&&!D.terrain&&In.text.orientationVertexBuffer&&ui.push("ELEVATED_ROADS"),ti(ui),Pi(ui);const Ef=gs.disableSymbolUBO?In.text.programConfigurations.get(C.id):null,kh=D.getOrCreateProgram("symbol",{config:Ef,defines:ui});let ip,my=[0,0],sl=null;const dv=In.textSizeData;In.iconsInText&&(my=rr.imageAtlasTexture?rr.imageAtlasTexture.size:[0,0],sl=rr.imageAtlasTexture?rr.imageAtlasTexture:null,ip=hn||!Zt.isOrthographic||D.options.rotating||D.options.zooming||dv.kind==="composite"||dv.kind==="camera"?$t.LINEAR:$t.NEAREST);const uv=rr.glyphAtlasTexture?rr.glyphAtlasTexture.size:[0,0],Ql=C.layout.get("text-size-scale-range"),uc=o.aC(D.scaleFactor,Ql[0],Ql[1]),cl=o.bj(dv,Zt.zoom,uc),gu=Jc(Fr,rr.tileID.canonical,hn,Us,Zt,In.getProjection(),Vr),ng=Qm(Fr,rr.tileID.canonical,hn,Us,Zt,In.getProjection(),Vr),Nd=In.text.uboBinder&&In.text.uboBinder.cachedHeader&&256&In.text.uboBinder.cachedHeader.dataDrivenMask?[0,0]:pe,py=D.translatePosMatrix(ng,rr,Nd,Ee,!0),qN=D.translatePosMatrix(Fr,rr,Nd,Ee),bS=Ic?fo:gu,_S=Us&&!hn&&!$o;let sC=fr;!pn&&!Zt.mercatorFromTransition||Us||(sC=kc(Zt));const Wj=Lu(dv.kind,cl,_S,hn,D,qN,bS,py,ys,!0,uv,my,0,nr,fa,Es,ei,Yr?sC:fr,In.getProjection(),Rl,Li,null,null,uc),gw=rr.glyphAtlasTexture?rr.glyphAtlasTexture:null,nC=$t.LINEAR,y0=C.paint.get("text-halo-width").constantOr(1)!==0,VN=D.terrain&&hn&&$o?o.b7(o.bb(),gu):fo;if($o&&In.text){const HN=o.bu.getAtTileOffsetFunc(nr,Zt.center.lat,Zt.worldSize,In.getProjection()),GN=Nc(Fr,rr.tileID.canonical,hn,Us,Zt,In.getProjection(),Vr);Wt(In,Fr,D,!0,GN,ng,hn,bt,HN,nr,uc)}return{program:kh,buffers:In.text,uniformValues:Wj,atlasTexture:gw,atlasTextureIcon:sl,atlasInterpolation:nC,atlasInterpolationIcon:ip,isSDF:!0,hasHalo:y0,depthMode:uh,tile:rr,renderWithShadows:Xi,labelPlaneMatrixInv:VN}},ql=In.icon.segments.get().length,Bo=In.text.segments.get().length,ji=ql&&!Z.onlyText?yl():null,Ni=Bo&&!Z.onlyIcons?Gc():null,Vl=C.paint.get("icon-opacity").constantOr(1),nd=C.paint.get("text-opacity").constantOr(1);if(an&&In.canOverlap){An=!0;const $o=Vl&&!Z.onlyText?In.icon.segments.get():[],ui=nd&&!Z.onlyIcons?In.text.segments.get():[];for(const Ic of $o)vn.push({segments:new o.dy([Ic]),sortKey:Ic.sortKey,state:ji});for(const Ic of ui)vn.push({segments:new o.dy([Ic]),sortKey:Ic.sortKey,state:Ni})}else Z.onlyText||vn.push({segments:Vl?In.icon.segments:new o.dy([]),sortKey:0,state:ji}),Z.onlyIcons||vn.push({segments:nd?In.text.segments:new o.dy([]),sortKey:0,state:Ni})}An&&vn.sort((nr,rr)=>nr.sortKey-rr.sortKey);for(const nr of vn){const rr=nr.state;if(rr)if(D.terrain?D.terrain.setupElevationDraw(rr.tile,rr.program,{useDepthForOcclusion:Zt.depthOcclusionForSymbolsAndCircles,labelPlaneMatrixInv:rr.labelPlaneMatrixInv}):D.setupDepthForOcclusion(Zt.depthOcclusionForSymbolsAndCircles,rr.program),gs.activeTexture.set($t.TEXTURE0),rr.atlasTexture&&rr.atlasTexture.bind(rr.atlasInterpolation,$t.CLAMP_TO_EDGE,!0),rr.atlasTextureIcon&&(gs.activeTexture.set($t.TEXTURE1),rr.atlasTextureIcon&&rr.atlasTextureIcon.bind(rr.atlasInterpolationIcon,$t.CLAMP_TO_EDGE,!0)),rr.renderWithShadows&&D.shadowRenderer.setupShadows(rr.tile.tileID.toUnwrapped(),rr.program,"vector-tile"),D.uploadCommonLightUniforms(D.context,rr.program),rr.hasHalo){const In=rr.uniformValues;In.u_is_halo=1,h0(rr.buffers,nr.segments,C,D,rr.program,rr.depthMode,U,Y,In,2),In.u_is_halo=0}else{if(rr.isSDF){const In=rr.uniformValues;rr.hasHalo&&(In.u_is_halo=1,h0(rr.buffers,nr.segments,C,D,rr.program,rr.depthMode,U,Y,In,1)),In.u_is_halo=0}h0(rr.buffers,nr.segments,C,D,rr.program,rr.depthMode,U,Y,rr.uniformValues,1)}}}function h0(D,w,C,O,U,Y,Z,se,pe,je){const Ee=O.context,He=Ee.gl,qe=[D.dynamicLayoutVertexBuffer,D.opacityVertexBuffer,D.iconTransitioningVertexBuffer,D.globeExtVertexBuffer,D.zOffsetVertexBuffer,D.orientationVertexBuffer];D.featureIdBuffer&&qe.push(D.featureIdBuffer);const et=D.uboBinder?null:D.programConfigurations.get(C.id);if(D.uboBinder){D.uboBinder.layer=C;const bt=O.transform.zoom,vt=O.style.getBrightness?O.style.getBrightness():null,Pt=D.uboBinder.getConstantUniformValues(bt,vt);pe.u_spp_fill_np_color=Pt.fill_np_color,pe.u_spp_halo_np_color=Pt.halo_np_color,pe.u_spp_opacity=Pt.opacity,pe.u_spp_halo_width=Pt.halo_width,pe.u_spp_halo_blur=Pt.halo_blur,pe.u_spp_emissive_strength=Pt.emissive_strength,pe.u_spp_occlusion_opacity=Pt.occlusion_opacity,pe.u_spp_z_offset=Pt.z_offset;const Ft=C.paint.get(D.uboBinder.isText?"text-translate-anchor":"icon-translate-anchor"),jt=D.uboBinder.cachedHeader&&256&D.uboBinder.cachedHeader.dataDrivenMask&&Ft==="map"?O.transform.angle:0;pe.u_spp_translate_rotation=[Math.cos(jt),Math.sin(jt)]}const{batchIndices:ct,batchSegments:ot}=D.getBatchGrouping(w);for(const bt of ct){const vt=ot.get(bt);D.uboBinder&&D.uboBinder.bind(Ee,U.program,bt),U.draw(O,He.TRIANGLES,Y,Z,se,ra.disabled,pe,C.id,D.layoutVertexBuffer,D.indexBuffer,vt,C.paint,O.transform.zoom,et,qe,je)}}function Yd(D,w,C,O,U,Y){const Z=C.paint.get("line-width"),se=C.paint.get("line-emissive-strength").isConstant(),pe=C.paint.get("line-emissive-strength").constantOr(0),je=C.paint.get("line-occlusion-opacity"),Ee=C.layout.get("line-elevation-reference"),He=C.layout.get("line-width-unit")==="meters",qe=Ee==="sea",et=!(!D.terrain||!D.terrain.enabled),ct=D.context,ot=ct.gl;if(C.hasElevatedBuckets&&D.transform.projection.name==="globe")return;const bt=C.layout.get("line-cross-slope"),vt=bt!==void 0,Pt=bt<1,Ft=U||D.colorModeForDrapableLayerRenderPass(se?pe:null),jt=D.terrain&&D.terrain.renderingToTexture||Y,ys=jt?1:o.o.devicePixelRatio,Qt=C.paint.get("line-dasharray"),gs=Qt.constantOr(1),$t=C.layout.get("line-cap"),Zt=Qt.constantOr(null),hs=$t.constantOr(null),Us=C.paint.get("line-pattern"),Cs=Us.constantOr(1),hn=C.paint.get("line-pattern-cross-fade"),an=Us.constantOr(null),An=C.paint.get("line-opacity").constantOr(1);let On=!Cs&&An!==1||D.depthOcclusion&&je>0&&je<1;const Ks=C.paint.get("line-gradient"),Es=Cs?"linePattern":"line",cn=o.dU(C);let pn;if(jt&&D.terrain&&D.terrain.clipOrMaskOverlapStencilType()&&(On=!1),je!==0&&D.depthOcclusion){const In=C.paint._values["line-opacity"];In&&In.value&&In.value.kind==="constant"?pn=In.value:o.w(`Occlusion opacity for layer ${C.id} is supported only when line-opacity isn't data-driven.`)}Z.value.kind!=="constant"&&Z.value.isLineProgressConstant===!1&&cn.push("VARIABLE_LINE_WIDTH"),jt&&(D.emissiveMode!=="dual-source-blending"||se?D.emissiveMode==="mrt-fallback"&&cn.push("USE_MRT1"):cn.push("DUAL_SOURCE_BLENDING"));const vn={},fr=(In,Yr,fa,Fr,Vr,$a)=>{for(const ri of In){const ei=w.getTile(ri);if(Cs&&!ei.patternsLoaded())continue;const Li=ei.getBucket(C);if(!Li||Li.elevationType!=="none"&&!Vr||Li.elevationType==="none"&&Vr)continue;D.prepareDrawTile();const Ea=[...Yr],Pi=D.shadowRenderer,ti=Li.elevationType==="road"&&!!Pi&&Pi.enabled;let So=[0,0,0];if(ti){const Xi=D.style.directionalLight,Rl=D.style.ambientLight;Xi&&Rl&&(So=oh(D.style,Xi,Rl)),Ea.push("RENDER_SHADOWS","NORMAL_OFFSET")}const yl=Li.programConfigurations.get(C.id);let Gc=!1;if(an&&ei.imageAtlas){const Xi=o.dV.from(an),Rl=Xi.getPrimary().scaleSelf(ys).toString(),uh=ei.imageAtlas.patternPositions.get(Rl),Ef=Xi.getSecondary(),kh=Ef?ei.imageAtlas.patternPositions.get(Ef.scaleSelf(ys).toString()):null;Gc=!!uh&&!!kh,uh&&yl.setConstantPatternPositions(uh,kh)}hn>0&&(Gc||yl.getPatternTransitionVertexBuffer("line-pattern"))&&Ea.push("LINE_PATTERN_TRANSITION"),Li.elevationGroundScaleVertexBuffer&&Ea.push("ELEVATION_GROUND_SCALE");const ql=D.isTileAffectedByFog(ri),Bo=D.getOrCreateProgram(Es,{config:yl,defines:Ea,overrideFog:ql});if(!Cs&&Zt&&hs&&ei.lineAtlas){const Xi=ei.lineAtlas.getDash(Zt,hs);Xi&&yl.setConstantPatternPositions(Xi)}ti&&Pi.setupShadows(ei.tileID.toUnwrapped(),Bo,"vector-tile");let[ji,Ni]=C.paint.get("line-trim-offset");(hs==="round"||hs==="square")&&ji!==Ni&&(ji===0&&(ji-=1),Ni===1&&(Ni+=1));const Vl=jt?ri.projMatrix:null,nd=He?1/Li.tileToMeter/o.aA(ei,1,D.transform.zoom):1,$o=He?1/Li.tileToMeter/o.aA(ei,1,Math.floor(D.transform.zoom)):1,ui=gs?C.paint._values["line-floorwidth"]:null;let Ic;if(ui&&ui.value.kind==="constant"){const Xi=Li.zoom;Xi in vn||(vn[Xi]=Math.max(.01,C.widthExpression().evaluate({zoom:Xi}))),Ic=ui.value.value;const Rl=Math.floor(D.transform.zoom);ui.value.value=vn[Xi]*Math.pow(2,Rl-ei.tileID.overscaledZ)}const vl=Cs?o.dW(D,ei,C,Vl,ys,nd,$o,[ji,Ni],So,hn):o.dX(D,ei,C,Vl,Li.lineClipsArray.length,ys,nd,$o,[ji,Ni],So);if(Ks){const Xi=Li.gradients[C.id];let Rl=Xi.texture;if(C.gradientVersion!==Xi.version){let uh=256;if(C.stepInterpolant){const Ef=w.getSource().maxzoom,kh=ri.canonical.z===Ef?Math.ceil(1<{pn!=null&&(pn.value=An*je),Bo.draw(D,ot.TRIANGLES,fa,Xi,Ft,ra.disabled,vl,C.id,Li.layoutVertexBuffer,Li.indexBuffer,Li.segments,C.paint,D.transform.zoom,yl,[Li.layoutVertexBuffer2,Li.patternVertexBuffer,Li.zOffsetVertexBuffer,Li.elevationGroundScaleVertexBuffer]),pn!=null&&(pn.value=An)};if(On&&!Vr){const Xi=D.stencilModeForClipping(ri).ref;Xi===0&&jt&&ct.clear({stencil:0});const Rl={func:ot.EQUAL,mask:255};vl.u_alpha_discard_threshold=.8,Ru(new Na(Rl,Xi,255,ot.KEEP,ot.KEEP,ot.INVERT)),vl.u_alpha_discard_threshold=0,Ru(new Na(Rl,Xi,255,ot.KEEP,ot.KEEP,ot.KEEP))}else vl.u_alpha_discard_threshold=On&&Vr&&$a?.8:0,Ru(Vr?Fr:D.stencilModeForClipping(ri));Ic!==void 0&&(ui.value.value=Ic)}};let nr=D.depthModeForSublayer(0,Ir.ReadOnly);const rr=new Ir(D.depthOcclusion?ot.GREATER:ot.LEQUAL,Ir.ReadOnly,D.depthRangeFor3D);if(C.hasNonElevatedBuckets){const In=!jt&&D.terrain;je!==0&&In?o.w(`Occlusion opacity for layer ${C.id} is supported on terrain only if the layer has line-z-offset enabled.`):In?o.w(`Cannot render non-elevated lines in immediate mode when terrain is enabled. Layer: ${C.id}.`):fr(O,cn,nr,Na.disabled,!1,!0)}if(C.hasElevatedBuckets){Ee==="hd-road-markup"?et||(nr=rr,cn.push("ELEVATED_ROADS")):(cn.push("ELEVATED"),nr=rr,vt&&cn.push(Pt?"CROSS_SLOPE_HORIZONTAL":"CROSS_SLOPE_VERTICAL"),qe&&cn.push("ELEVATION_REFERENCE_SEA"));const In=On?D.stencilModeFor3D():Na.disabled;D.forceTerrainMode=!0,fr(O,cn,nr,In,!0,!0),On&&fr(O,cn,nr,In,!0,!1),D.forceTerrainMode=!1}On&&(D.resetStencilClippingMasks(),jt&&ct.clear({stencil:0})),je===0||D.depthOcclusion||jt||D.layersWithOcclusionOpacity.push(D.currentLayer)}const ap={additive:{clearColor:new o.aq(0,0,0,0),colorMode:wa.additive,compositeUniformValue:1},multiply:{clearColor:new o.aq(1,1,1,1),colorMode:wa.multiply,compositeUniformValue:0}};function rv(D,w){const C=1<=ih?1:et.pitch/ih))),2*ct}(D.transform),je=D.transform.getFreeCameraOptions().position,Ee="elevatedStructuresDepthReconstruct",He=D.getOrCreateProgram(Ee,{defines:["DEPTH_RECONSTRUCTION"]}),qe=D.getOrCreateProgram(Ee);for(const et of O){const ct=w.getTile(et),ot=ct.getBucket(C);if(!ot)continue;const bt=ot.elevatedStructures;if(!bt)continue;const vt=ot.elevationBufferData.heightRange,Pt=rv(et.toUnwrapped(),je),Ft=D.translatePosMatrix(et.projMatrix,ct,C.paint.get("fill-translate"),C.paint.get("fill-translate-anchor"));let jt,ys,Qt,gs;if(U==="initialize"){if(!vt||vt.min>=1||bt.depthSegments.segments[0].primitiveLength===0)continue;jt=wi(Ft,Pt,pe,1,0),ys=Z,Qt=bt.depthSegments,gs=He}else if(U==="reset"){if(!vt||vt.min>=0||bt.maskSegments.segments[0].primitiveLength===0)continue;jt=wi(Ft,Pt,0,0,1),ys=se,Qt=bt.maskSegments,gs=He}else if(U==="geometry"){if(bt.depthSegments.segments[0].primitiveLength===0)continue;jt=wi(Ft,Pt,pe,1,0),ys=Z,Qt=bt.depthSegments,gs=qe}gs.draw(D,Y.TRIANGLES,ys,Na.disabled,wa.disabled,ra.disabled,jt,C.id,bt.vertexBuffer,bt.indexBuffer,Qt,C.paint,D.transform.zoom)}}function av(D,w,C,O){const{painter:U,sourceCache:Y,layer:Z,coords:se,colorMode:pe,elevationType:je,terrainEnabled:Ee,pass:He}=D,qe=U.context.gl,et=Z.paint.get("fill-pattern"),ct=Z.paint.get("fill-pattern-cross-fade"),ot=et.constantOr(null);let bt=je;je!=="road"||w&&!Ee||(bt="none");const vt=bt==="road",Pt=D.painter.shadowRenderer,Ft=vt&&!!Pt&&Pt.enabled,jt=new Ir(U.context.gl.LEQUAL,Ir.ReadOnly,U.depthRangeFor3D);let ys=[0,0,0];if(Ft){const Zt=U.style.directionalLight,hs=U.style.ambientLight;Zt&&hs&&(ys=oh(U.style,Zt,hs))}const Qt=et&&et.constantOr(1),gs=U.terrain&&U.terrain.renderingToTexture,$t=(Zt,hs)=>{let Us,Cs,hn,an,An;hs?(Us=Qt&&!Z.getPaintProperty("fill-outline-color")?"fillOutlinePattern":"fillOutline",hn=qe.LINES):(Us=Qt?"fillPattern":"fill",hn=qe.TRIANGLES);for(const On of se){const Ks=Y.getTile(On);if(Qt&&!Ks.patternsLoaded())continue;const Es=Ks.getBucket(Z);if(!Es)continue;const cn=w?Es.elevationBufferData:Es.bufferData;if(cn.isEmpty())continue;U.prepareDrawTile();const pn=cn.programConfigurations.get(Z.id),vn=U.isTileAffectedByFog(On),fr=[],nr=[];vt&&(fr.push("ELEVATED_ROADS"),nr.push(cn.elevatedLayoutVertexBuffer)),Ft&&fr.push("RENDER_SHADOWS","NORMAL_OFFSET"),gs&&C&&fr.push("USE_MRT1"),Qt&&(U.context.activeTexture.set(qe.TEXTURE0),Ks.imageAtlasTexture&&Ks.imageAtlasTexture.bind(qe.LINEAR,qe.CLAMP_TO_EDGE),pn.updatePaintBuffers());let rr=!1;if(ot&&Ks.imageAtlas){const Vr=Ks.imageAtlas,$a=o.dV.from(ot),ri=$a.getPrimary().scaleSelf(o.o.devicePixelRatio).toString(),ei=$a.getSecondary(),Li=Vr.patternPositions.get(ri),Ea=ei?Vr.patternPositions.get(ei.scaleSelf(o.o.devicePixelRatio).toString()):null;rr=!!Li&&!!Ea,Li&&pn.setConstantPatternPositions(Li,Ea)}ct>0&&(rr||pn.getPatternTransitionVertexBuffer("fill-pattern"))&&fr.push("FILL_PATTERN_TRANSITION");const In=U.getOrCreateProgram(Us,{config:pn,overrideFog:vn,defines:fr}),Yr=U.translatePosMatrix(On.projMatrix,Ks,Z.paint.get("fill-translate"),Z.paint.get("fill-translate-anchor"));Ft&&Pt.setupShadows(Ks.tileID.toUnwrapped(),In,"vector-tile");const fa=Z.paint.get("fill-emissive-strength");if(hs){an=cn.lineIndexBuffer,An=cn.lineSegments;const Vr=U.terrain&&U.terrain.renderingToTexture?U.terrain.drapeBufferSize:[qe.drawingBufferWidth,qe.drawingBufferHeight];Cs=Us==="fillOutlinePattern"&&Qt?Ei(Yr,fa,U,Ks,Vr,ys,ct):aa(Yr,fa,Vr,ys)}else an=cn.indexBuffer,An=cn.triangleSegments,Cs=Qt?ha(Yr,fa,U,Ks,ys,ct):Pr(Yr,fa,ys);U.uploadCommonUniforms(U.context,In,On.toUnwrapped());let Fr=Zt;(je==="road"&&!Ee||je==="offset")&&(Fr=jt),In.draw(U,hn,Fr,O||U.stencilModeForClipping(On),pe,ra.disabled,Cs,Z.id,cn.layoutVertexBuffer,an,An,Z.paint,U.transform.zoom,pn,nr)}};U.renderPass===He&&$t(U.depthModeForSublayer(1,U.renderPass==="opaque"?Ir.ReadWrite:Ir.ReadOnly),!1),bt==="none"&&U.renderPass==="translucent"&&Z.paint.get("fill-antialias")&&$t(U.depthModeForSublayer(Z.getPaintProperty("fill-outline-color")?2:0,Ir.ReadOnly),!0)}function vm(D,w,C,O,U,Y,Z,se){C.resetLayerRenderingStats(D);const pe=D.context,je=pe.gl,Ee=D.transform,He=C.paint.get("fill-extrusion-pattern"),qe=C.paint.get("fill-extrusion-pattern-cross-fade"),et=He.constantOr(null),ct=He.constantOr(1),ot=C.paint.get("fill-extrusion-opacity"),bt=D.style.enable3dLights(),vt=C.paint.get(bt&&!ct?"fill-extrusion-ambient-occlusion-wall-radius":"fill-extrusion-ambient-occlusion-radius"),Pt=[C.paint.get("fill-extrusion-ambient-occlusion-intensity"),vt],Ft=C.layout.get("fill-extrusion-edge-radius"),jt=Ft>0&&!C.paint.get("fill-extrusion-rounded-roof"),ys=jt?0:Ft,Qt=Ee.projection.name==="globe"?o.e1():0,gs=Ee.projection.name==="globe",$t=gs?o.al(Ee.zoom):0,Zt=[o.aH(Ee.center.lng),o.aL(Ee.center.lat)],hs=C.paint.get("fill-extrusion-flood-light-color-use-theme").constantOr("default")==="none",Us=C.paint.get("fill-extrusion-flood-light-color").toNonPremultipliedRenderColor(hs?null:C.lut).toArray01().slice(0,3),Cs=C.paint.get("fill-extrusion-flood-light-intensity"),hn=C.paint.get("fill-extrusion-vertical-scale"),an=C.paint.get("fill-extrusion-line-width").constantOr(1)!==0,An=C.paint.get("fill-extrusion-height-alignment"),On=C.paint.get("fill-extrusion-base-alignment"),Ks=qc(D,C.paint.get("fill-extrusion-cutoff-fade-range")),Es=C.paint.get("fill-extrusion-front-cutoff"),cn=uw(Ee.pitch,Es,!!D.terrain),pn=cn[2]<1;pn&&(D.maxFrontCutoffRawStart=Math.max(D.maxFrontCutoffRawStart,Es[0]));const vn=[];let fr;gs&&vn.push("PROJECTION_GLOBE_VIEW"),Pt[0]>0&&vn.push("FAUX_AO"),jt&&vn.push("ZERO_ROOF_RADIUS"),se&&vn.push("HAS_CENTROID"),Cs>0&&vn.push("FLOOD_LIGHT"),Ks.shouldRenderCutoff&&vn.push("RENDER_CUTOFF"),pn&&vn.push("RENDER_FRONT_CUTOFF"),an&&vn.push("RENDER_WALL_MODE");const nr=D.renderPass==="shadow",rr=D.shadowRenderer,In=nr&&!!rr,Yr=nr?ra.disabled:ra.backCCW;D.shadowRenderer&&(D.shadowRenderer.useNormalOffset=!0);let fa=[0,0,0];if(rr){const $a=D.style.directionalLight,ri=D.style.ambientLight;$a&&ri&&(fa=oh(D.style,$a,ri)),nr||(vn.push("RENDER_SHADOWS"),rr.useNormalOffset&&vn.push("NORMAL_OFFSET")),fr=vn.concat(["SHADOWS_SINGLE_CASCADE"])}const Fr=In?"fillExtrusionDepth":ct?"fillExtrusionPattern":"fillExtrusion",Vr=C.getLayerRenderingStats();for(const $a of O){const ri=w.getTile($a),ei=ri.getBucket(C);if(!ei||ei.projection.name!==Ee.projection.name)continue;let Li=!1;rr&&(Li=rr.getMaxCascadeForTile($a.toUnwrapped())===0);const Ea=D.isTileAffectedByFog($a),Pi=ei.programConfigurations.get(C.id);let ti=!1;if(et&&ri.imageAtlas){const Ni=ri.imageAtlas,Vl=o.dV.from(et),nd=Vl.getPrimary().scaleSelf(o.o.devicePixelRatio).toString(),$o=Vl.getSecondary(),ui=Ni.patternPositions.get(nd),Ic=$o?Ni.patternPositions.get($o.scaleSelf(o.o.devicePixelRatio).toString()):null;ti=!!ui&&!!Ic,ui&&Pi.setConstantPatternPositions(ui,Ic)}qe>0&&(ti||Pi.getPatternTransitionVertexBuffer("fill-extrusion-pattern"))&&vn.push("FILL_EXTRUSION_PATTERN_TRANSITION");const So=D.getOrCreateProgram(Fr,{config:Pi,defines:Li?fr:vn,overrideFog:Ea});if(D.terrain&&D.terrain.setupElevationDraw(ri,So,{useMeterToDem:!0}),!ei.centroidVertexBuffer){const Ni=So.getAttributeLocation(je,"a_centroid_pos");Ni!==-1&&je.vertexAttribI4ui(Ni,0,0,0,0)}!nr&&rr&&rr.setupShadows(ri.tileID.toUnwrapped(),So,"vector-tile"),ct&&(D.context.activeTexture.set(je.TEXTURE0),ri.imageAtlasTexture&&ri.imageAtlasTexture.bind(je.LINEAR,je.CLAMP_TO_EDGE),Pi.updatePaintBuffers());const yl=C.paint.get("fill-extrusion-vertical-gradient"),Gc=1/ei.tileToMeter;let ql;if(nr&&rr){if(tg(ri.tileID,ei.maxHeight,D))continue;const Ni=rr.calculateShadowPassMatrixFromTile(ri.tileID.toUnwrapped());ql=ur(Ni,ys,Gc,hn,An,On)}else{const Ni=D.translatePosMatrix($a.expandedProjMatrix,ri,C.paint.get("fill-extrusion-translate"),C.paint.get("fill-extrusion-translate-anchor")),Vl=Ee.projection.createInversionMatrix(Ee,$a.canonical);ql=ct?Ln(Ni,D,yl,ot,Pt,ys,Gc,$a,ri,Qt,An,On,$t,Zt,Vl,Us,hn,qe):wr(Ni,D,yl,ot,Pt,ys,Gc,$a,Qt,An,On,$t,Zt,Vl,Us,hn,Cs,fa,cn)}D.uploadCommonUniforms(pe,So,$a.toUnwrapped(),null,Ks);let Bo=ei.segments;if(Ee.projection.name==="mercator"&&!nr&&(Bo=ei.getVisibleSegments(ri.tileID,D.terrain,D.transform.getFrustum(0)),!Bo.get().length))continue;if(Vr)if(nr)for(const Ni of Bo.get())Vr.numRenderedVerticesInShadowPass+=Ni.primitiveLength;else for(const Ni of Bo.get())Vr.numRenderedVerticesInTransparentPass+=Ni.primitiveLength;const ji=[];(D.terrain||se)&&ji.push(ei.centroidVertexBuffer),gs&&ji.push(ei.layoutVertexExtBuffer),an&&ji.push(ei.wallVertexBuffer),So.draw(D,pe.gl.TRIANGLES,U,Y,Z,Yr,ql,C.id,ei.layoutVertexBuffer,ei.indexBuffer,Bo,C.paint,D.transform.zoom,Pi,ji)}D.shadowRenderer&&(D.shadowRenderer.useNormalOffset=!1)}class Gp{constructor(){this.translate=[0,0],this.translateAnchor="map",this.edgeRadius=0,this.cutoffFadeRange=0}}function uw(D,w,C){if(!(w[2]<1)||C)return[0,0,1];const O=180*D/Math.PI;if(O<15)return[-.5,w[1],w[2]];const U=Math.min(1,Math.max(0,(O-15)/5)),Y=U*U*(3-2*U);return[-.5*(1-Y)+w[0]*Y,w[1],w[2]]}function bx(D,w,C,O,U,Y,Z,se,pe,je,Ee,He,qe,et,ct,ot,bt,vt,Pt,Ft,jt){const ys=w.context,Qt=ys.gl,gs=w.transform,$t=w.transform.zoom,Zt=[],hs=D.translate,Us=D.translateAnchor,Cs=D.edgeRadius,hn=qc(w,D.cutoffFadeRange);Ee==="clear"?(Zt.push("CLEAR_SUBPASS"),Ft&&(Zt.push("CLEAR_FROM_TEXTURE"),ys.activeTexture.set(Qt.TEXTURE0),Ft.bind(Qt.LINEAR,Qt.CLAMP_TO_EDGE))):Ee==="sdf"?Zt.push("SDF_SUBPASS"):Ee==="emissive"&&(Zt.push("USE_MRT1"),ys.activeTexture.set(Qt.TEXTURE0),Ft.bind(Qt.LINEAR,Qt.CLAMP_TO_EDGE)),vt&&Zt.push("HAS_CENTROID"),hn.shouldRenderCutoff&&Zt.push("RENDER_CUTOFF");const an=(An,On,Ks,Es,cn)=>{let pn=Zt;On.groundRadiusBuffer!=null&&(pn=Zt.concat("HAS_ATTRIBUTE_a_flood_light_ground_radius"));const vn=On.programConfigurations.get(O.id),fr=w.isTileAffectedByFog(An),nr=w.getOrCreateProgram("fillExtrusionGroundEffect",{config:vn,defines:pn,overrideFog:fr}),rr=((Yr,fa,Fr,Vr,$a,ri,ei,Li,Ea,Pi,ti)=>({u_matrix:fa,u_opacity:Fr,u_ao_pass:Vr?1:0,u_meter_to_tile:$a,u_ao:ri,u_flood_light_intensity:ei,u_flood_light_color:Li,u_attenuation:Ea,u_edge_radius:Pi,u_fb:0,u_fb_size:ti,u_dynamic_offset:1}))(0,Es,He,je,cn,[qe,et*cn],ct,ot,bt,$t>=17?0:Cs*cn,Ft?Ft.size[0]:0),In=[];vt&&In.push(On.hiddenByLandmarkVertexBuffer),On.groundRadiusBuffer!=null&&In.push(On.groundRadiusBuffer),w.uploadCommonUniforms(ys,nr,An.toUnwrapped(),null,hn),nr.draw(w,ys.gl.TRIANGLES,Y,Z,se,pe,rr,O.id,On.vertexBuffer,On.indexBuffer,Ks,O.paint,$t,vn,In)};for(const An of U){const On=C.getTile(An),Ks=On.getBucket(O);if(!Ks||Ks.projection.name!==gs.projection.name||!Ks.groundEffect||Ks.groundEffect&&!Ks.groundEffect.hasData())continue;const Es=Ks.groundEffect,cn=1/Ks.tileToMeter;{const pn=w.translatePosMatrix(An.projMatrix,On,hs,Us),vn=Es.getDefaultSegment();an(An,Es,vn,pn,cn)}if(Pt)for(let pn=0;pn<4;pn++){const vn=o.d$[pn](An),fr=C.getTile(vn);if(!fr)continue;const nr=fr.getBucket(O);if(!nr||nr.projection.name!==gs.projection.name||!nr.groundEffect||nr.groundEffect&&!nr.groundEffect.hasData())continue;const rr=nr.groundEffect;let In,Yr;pn===0?(In=[-o.an,0,0],Yr=1):pn===1?(In=[o.an,0,0],Yr=0):pn===2?(In=[0,-o.an,0],Yr=3):(In=[0,o.an,0],Yr=2);const fa=rr.regionSegments[Yr];if(!fa)continue;const Fr=new Float32Array(16);o.bx(Fr,An.projMatrix,In),an(An,rr,fa,w.translatePosMatrix(Fr,On,hs,Us),cn)}}}function m0(D,w,C,O,U,Y,Z){O.centroidVertexArray.length===0&&O.createCentroidsBuffer();const se=Y?Y.findDEMTileFor(C):null;if(!(se&&se.dem||Z))return;Y&&se&&se.dem&&O.selfDEMTileTimestamp!==se.dem._timestamp&&(O.borderDoneWithNeighborZ=[-1,-1,-1,-1],O.selfDEMTileTimestamp=se.dem._timestamp);const pe=(vt,Pt)=>{(vt.flags|Pt.flags)&o.e3?(vt.flags|=o.e3,Pt.flags|=o.e3):(vt.flags&=~o.e3,Pt.flags&=~o.e3)},je=vt=>new o.P(Math.ceil((vt+o.e4)*o.e5),0),Ee=(vt,Pt,Ft)=>{const jt=Math.ceil((vt+o.e4)*o.e5),ys=Math.floor(Math.max(0,Math.min(o.an-1,Ft))/4);return new o.P(jt,ys<<5|(3&Pt)<<3|7)},He=vt=>{const Pt=w.getSource().minzoom,Ft=ys=>{const Qt=w.getTileByID(ys);if(Qt&&Qt.hasData())return Qt.getBucket(U)},jt=[0,-1,1];for(const ys of jt){if(vt.overscaledZ+ys(qe[0]=Math.min(vt.min.y,Pt.min.y),qe[1]=Math.max(vt.max.y,Pt.max.y),qe[2]=o.an-Pt.min.x>vt.max.x?Pt.min.x-o.an:vt.max.x,qe),ct=(vt,Pt)=>(qe[0]=Math.min(vt.min.x,Pt.min.x),qe[1]=Math.max(vt.max.x,Pt.max.x),qe[2]=o.an-Pt.min.y>vt.max.y?Pt.min.y-o.an:vt.max.y,qe),ot=[(vt,Pt)=>et(vt,Pt),(vt,Pt)=>et(Pt,vt),(vt,Pt)=>ct(vt,Pt),(vt,Pt)=>ct(Pt,vt)],bt=(vt,Pt,Ft,jt,ys,Qt,gs)=>{if(!Y)return 0;const $t=[[Qt?Ft:vt,Qt?vt:Ft,0],[Qt?Ft:Pt,Qt?Pt:Ft,0]],Zt=gs<0?o.an+gs:gs,hs=[Qt?Zt:(vt+Pt)/2,Qt?(vt+Pt)/2:Zt,0];return Ft===0&&gs<0||Ft!==0&&gs>0?Y.getForTilePoints(ys,[hs],!0,jt):$t.push(hs),Y.getForTilePoints(C,$t,!0,se),Math.max($t[0][2],$t[1][2],hs[2])/Y.exaggeration()};for(let vt=0;vt<4;vt++){const Pt=O.borderFeatureIndices[vt];if(Pt.length===0)continue;const Ft=o.d$[vt](C),jt=He(Ft);if(!(jt&&jt instanceof o.e0))continue;const ys=Y?Y.findDEMTileFor(Ft):null;if(!(ys&&ys.dem||Z)||(Y&&ys&&ys.dem&&O.borderDEMTileTimestamp[vt]!==ys.dem._timestamp&&(O.borderDoneWithNeighborZ[vt]=-1,O.borderDEMTileTimestamp[vt]=ys.dem._timestamp),O.borderDoneWithNeighborZ[vt]===jt.canonical.z))continue;jt.centroidVertexArray.length===0&&jt.createCentroidsBuffer();const Qt=(vt<2?1:5)-vt,gs=jt.borderDoneWithNeighborZ[Qt]!==O.canonical.z,$t=jt.borderFeatureIndices[Qt];let Zt=0;if(O.canonical.z!==jt.canonical.z){for(const hn of Pt)O.showCentroid(O.featuresOnBorder[hn]);if(gs)for(const hn of $t)jt.showCentroid(jt.featuresOnBorder[hn]);O.borderDoneWithNeighborZ[vt]=jt.canonical.z,jt.borderDoneWithNeighborZ[Qt]=O.canonical.z;continue}const hs=new Map,Us=new Set,Cs=new Set;for(let hn=0;hn<$t.length;hn++){const an=jt.featuresOnBorder[$t[hn]];an.buildingId!==void 0&&hs.set(an.buildingId,hn)}for(const hn of Pt){const an=O.featuresOnBorder[hn],An=O.centroidData[an.centroidDataIndex];if(an.buildingId===void 0)continue;const On=hs.get(an.buildingId);if(On===void 0)continue;const Ks=jt.featuresOnBorder[$t[On]],Es=jt.centroidData[Ks.centroidDataIndex];Us.add(hn),Cs.add(On),Z&&pe(An,Es);const cn=An.groupCentroidPos.x!==0||An.groupCentroidPos.y!==0?An.groupCentroidPos:an.centroid(),pn=Es.groupCentroidPos.x!==0||Es.groupCentroidPos.y!==0?Es.groupCentroidPos:Ks.centroid(),vn=vt<2?Math.round((cn.y+pn.y)/2):Math.round((cn.x+pn.x)/2),fr=an.intersectsCount()>1||Ks.intersectsCount()>1;{let nr=0;if(ys&&ys.dem&&!fr){const rr=ot[vt](An,Es),In=vt%2?o.an-1:0;nr=bt(rr[0],Math.min(o.an-1,rr[1]),In,ys,Ft,vt<2,rr[2])}An.centroidXY=Ee(nr,vt,vn),Es.centroidXY=Ee(nr,Qt,vn)}if(O.writeCentroidToBuffer(An),jt.writeCentroidToBuffer(Es),an.buildingId!==void 0){for(const nr of O.centroidData)nr.buildingId===an.buildingId&&nr!==An&&(nr.centroidXY=An.centroidXY,O.writeCentroidToBuffer(nr));for(const nr of jt.centroidData)nr.buildingId===an.buildingId&&nr!==Es&&(nr.centroidXY=Es.centroidXY,jt.writeCentroidToBuffer(nr))}}for(const hn of Pt){if(Us.has(hn))continue;const an=O.featuresOnBorder[hn],An=O.centroidData[an.centroidDataIndex],On=an.borders[vt];let Ks;for(;Zt<$t.length;){if(Cs.has(Zt)){Zt++;continue}Ks=jt.featuresOnBorder[$t[Zt]];const Es=Ks.borders[Qt];if(Es[1]>On[0]+3||Es[0]>On[0]-3)break;jt.showCentroid(Ks),Zt++}if(Ks&&Zt<$t.length){let Es=Zt,cn=0;for(;;)if(Cs.has(Zt)){if(++Zt===$t.length)break;Ks=jt.featuresOnBorder[$t[Zt]]}else{if(Ks.borders[Qt][0]>On[1]-3||(cn++,++Zt===$t.length))break;Ks=jt.featuresOnBorder[$t[Zt]]}for(;Es<$t.length&&Cs.has(Es);)Es++;if(Es>=$t.length){O.showCentroid(an);continue}Ks=jt.featuresOnBorder[$t[Es]];let pn=!1;if(cn>=1){const nr=Ks.borders[Qt];Math.abs(On[0]-nr[0])<3&&Math.abs(On[1]-nr[1])<3&&(cn=1,pn=!0,Zt=Es+1)}else if(cn===0){O.showCentroid(an);continue}const vn=jt.centroidData[Ks.centroidDataIndex];Z&&pn&&pe(An,vn);const fr=an.intersectsCount()>1||Ks.intersectsCount()>1;if(cn>1)Zt=Es,An.centroidXY=vn.centroidXY=new o.P(0,0);else if(ys&&ys.dem&&!fr){const nr=ot[vt](An,vn),rr=vt%2?o.an-1:0,In=bt(nr[0],Math.min(o.an-1,nr[1]),rr,ys,Ft,vt<2,nr[2]);An.centroidXY=vn.centroidXY=je(In)}else fr?An.centroidXY=vn.centroidXY=new o.P(0,0):(An.centroidXY=O.encodeBorderCentroid(an),vn.centroidXY=jt.encodeBorderCentroid(Ks));O.writeCentroidToBuffer(An),jt.writeCentroidToBuffer(vn)}else O.showCentroid(an)}O.borderDoneWithNeighborZ[vt]=jt.canonical.z,jt.borderDoneWithNeighborZ[Qt]=O.canonical.z}(O.needsCentroidUpdate||!O.centroidVertexBuffer&&O.centroidVertexArray.length!==0)&&O.uploadCentroid(D)}const uy=[1,0,0],hw=[0,1,0],mw=[0,0,1];function tg(D,w,C){const O=C.transform,U=C.shadowRenderer;if(!U)return!0;const Y=D.toUnwrapped(),Z=O.tileSize*U._cascades[C.currentShadowCascade].scale;let se=w;if(O.elevation){const ct=O.elevation.getMinMaxForTile(D);ct&&(se+=ct.max)}const pe=O.scaleZoom(Z);se/=o.e2(O.center.lat,pe);const je=[...U.shadowDirection];je[2]=-je[2];const Ee=U.computeSimplifiedTileShadowVolume(Y,se,Z,je);if(!Ee)return!1;const He=[uy,hw,mw,je,[je[0],0,je[2]],[0,je[1],je[2]]],qe=o.cl.fromInvProjectionMatrix(O.invProjMatrix,O.worldSize,pe,O.projection.name!=="globe"),et=U.getCurrentCascadeFrustum();return qe.intersectsPrecise(Ee.vertices,Ee.planes,He)===0||et.intersectsPrecise(Ee.vertices,Ee.planes,He)===0}function hy(D){const{painter:w,source:C,layer:O,coords:U}=D;let Y=D.defines;const Z=w.context,se=w.renderPass==="shadow",pe=w.renderPass==="light-beam",je=w.shadowRenderer,Ee=o.e2(w.transform.center.lat,w.transform.zoom),He=qc(w,O.paint.get("building-cutoff-fade-range"));He.shouldRenderCutoff&&(Y=Y.concat("RENDER_CUTOFF"));const qe=O.paint.get("building-front-cutoff"),et=qe[2]<1&&!w.terrain,ct=uw(w.transform.pitch,qe,!!w.terrain);et&&(Y=Y.concat("RENDER_FRONT_CUTOFF"),w.maxFrontCutoffRawStart=Math.max(w.maxFrontCutoffRawStart,qe[0])),D.floodLightIntensity>0&&(Y=Y.concat("FLOOD_LIGHT"));for(const ot of U){const bt=C.getTile(ot),vt=bt.getBucket(O);if(!vt)continue;je&&je.getMaxCascadeForTile(ot.toUnwrapped())===0&&(Y=Y.concat("SHADOWS_SINGLE_CASCADE"));const Pt=vt.programConfigurations.get(O.id);let Ft,jt,ys,Qt=w.translatePosMatrix(ot.expandedProjMatrix,bt,[0,0],"map");if(Qt=o.cC(o.bb(),Qt,[1,1,D.verticalScale]),se&&je){if(tg(bt.tileID,vt.maxHeight*Ee,w))continue;let $t=je.calculateShadowPassMatrixFromTile(bt.tileID.toUnwrapped());$t=o.cC(o.bb(),$t,[1,1,D.verticalScale]),ys=Si($t),Ft=jt=w.getOrCreateProgram("buildingDepth",{config:Pt,defines:Y,overrideFog:!1})}else if(pe)Ft=jt=w.getOrCreateProgram("buildingBloom",{config:Pt,defines:Y,overrideFog:!1}),ys=Yo(Qt);else{const $t=w.transform.calculatePosMatrix(ot.toUnwrapped(),w.transform.worldSize);o.cC($t,$t,[1,1,D.verticalScale]);const Zt=o.bb();o.cC(Zt,$t,[1,-1,1/Ee]),o.b7(Zt,Zt),o.e6(Zt,Zt);const hs=w.transform.getFreeCameraOptions().position,Us=1<{if(pe){const hs=$t.entranceBloom;Zt.draw(w,Z.gl.TRIANGLES,D.depthMode,Na.disabled,D.blendMode,ra.disabled,ys,O.id,hs.layoutVertexBuffer,hs.indexBuffer,hs.segmentsBucket,O.paint,w.transform.zoom,Pt,[hs.layoutAttenuationBuffer,hs.layoutColorBuffer])}else{const hs=$t.segmentsBucket;let Us=[$t.layoutNormalBuffer,$t.layoutCentroidBuffer,$t.layoutColorBuffer,$t.layoutFloodLightDataBuffer];$t.layoutFacadePaintBuffer&&(Us=Us.concat([$t.layoutFacadeDataBuffer,$t.layoutFacadeVerticalRangeBuffer,$t.layoutFacadePaintBuffer])),Zt.draw(w,Z.gl.TRIANGLES,D.depthMode,Na.disabled,D.blendMode,se?ra.disabled:ra.backCW,ys,O.id,$t.layoutVertexBuffer,$t.indexBuffer,hs,O.paint,w.transform.zoom,Pt,Us)}};w.uploadCommonUniforms(Z,jt,ot.toUnwrapped(),null,He),vt.buildingWithoutFacade&&gs(vt.buildingWithoutFacade,jt),vt.buildingWithFacade&&(Ft!==jt&&w.uploadCommonUniforms(Z,Ft,ot.toUnwrapped(),null,He),gs(vt.buildingWithFacade,Ft))}}function sg(D,w,C,O,U,Y,Z,se,pe,je,Ee,He,qe,et){const ct=D.context.gl,ot=D.depthModeForSublayer(1,Ir.ReadOnly,ct.LEQUAL,!0),bt=.1*(1-(vt=Ee))+3*vt;var vt;const Pt=D._showOverdrawInspector,Ft=He,jt=new Gp;Pt||bx(jt,D,w,C,O,ot,new Na({func:ct.ALWAYS,mask:255},255,255,ct.KEEP,ct.KEEP,ct.REPLACE),new wa([ct.ONE,ct.ONE,ct.ONE,ct.ONE],o.aq.transparent,[!1,!1,!1,!0],ct.MIN),ra.disabled,U,"sdf",Y,Z,se,pe,je,bt,Ft,!1,void 0);{const ys=Pt?Na.disabled:new Na({func:ct.EQUAL,mask:255},255,255,ct.KEEP,ct.DECR,ct.DECR),Qt=Pt?D.colorModeForRenderPass():new wa([ct.ONE_MINUS_DST_ALPHA,ct.DST_ALPHA,ct.ONE,ct.ONE],o.aq.transparent,[!0,!0,!0,!0]);bx(jt,D,w,C,O,ot,ys,Qt,ra.disabled,U,"color",Y,Z,se,pe,je,bt,Ft,!1,void 0)}}function Rb(D){return[D[0]*o.e7,D[1]*o.e7,D[2]*o.e7,0]}function v1(D,w,C,O,U,Y,Z,se,pe){const je=O.getSource(),Ee=C.globeSharedBuffers;if(!Ee)return;let He,qe,et;if(w&&(He=O.getTile(w)),je instanceof o.aV?(qe=je.texture,et=o.dw(0,0,C.transform)):He&&w&&(qe=He.texture,et=o.dw(w.canonical.z,w.canonical.x,C.transform)),!qe||!et)return;D||(et=o.cC(o.bb(),et,[1,-1,1]));const ct=C.context,ot=ct.gl,bt=U.paint.get("raster-resampling")==="nearest"?ot.NEAREST:ot.LINEAR,vt=C.colorModeForDrapableLayerRenderPass(Y),Pt=Z.defines;Pt.push("GLOBE_POLES");const Ft=new Ir(ot.LEQUAL,Ir.ReadWrite,C.depthRangeFor3D),jt=Float32Array.from(C.transform.expandedFarZProjMatrix),ys=Float32Array.from(o.du(o.dv(new o.cn(0,0,0))));C.terrain&&C.terrain.prepareDrawTile(),ct.activeTexture.set(ot.TEXTURE0),qe.bind(bt,ot.CLAMP_TO_EDGE),ct.activeTexture.set(ot.TEXTURE1),qe.bind(bt,ot.CLAMP_TO_EDGE),"useMipmap"in qe&&ct.extTextureFilterAnisotropic&&C.transform.pitch>20&&ot.texParameterf(ot.TEXTURE_2D,ct.extTextureFilterAnisotropic.TEXTURE_MAX_ANISOTROPY_EXT,ct.extTextureFilterAnisotropicMax);const[Qt,gs,$t,Zt]=w?Ee.getPoleBuffers(w.canonical.z,!1):Ee.getPoleBuffers(0,!0),hs=U.paint.get("raster-elevation");let Us;D?(Us=Qt,C.renderDefaultNorthPole=hs!==0):(Us=gs,C.renderDefaultSouthPole=hs!==0);const Cs=Rb(Z.mix),hn=((An,On,Ks,Es,cn,pn,vn,fr,nr,rr,In,Yr,fa,Fr)=>zd(An,On,Ks,Es,new Float32Array(16),new Float32Array(9),[0,0],cn,[0,0],[0,0,0,0],1,{opacity:1,mix:0},vn,[0,0],nr,2,In,Yr,fa,1,0,Fr))(C,jt,ys,et,o.al(C.transform.zoom),0,U,0,hs,0,Cs,Z.offset,Z.range,Y),an=C.getOrCreateProgram("raster",{defines:Pt});C.uploadCommonUniforms(ct,an,null),an.draw(C,ot.TRIANGLES,Ft,pe,vt,se,hn,U.id,Us,$t,Zt)}function b1(D){if(D.isOrthographic)return[0,0,0,0];const w=D._nearZ,C=D.projection.farthestPixelDistance(D),O=C-w,U=.2*D.height,Y=w+U;return[w,C,(Y-U-w)/O,(Y-w)/O]}function pw(D,w,C,O){if(D)return w instanceof Hm&&D instanceof hm?w.getTextureDescriptor(D,C,!0):{texture:D.texture,mix:Rb(O.mix),offset:O.offset,buffer:0,tileSize:1}}var _1=o.e8([{name:"a_index",type:"Int16",components:1}]);class fu{constructor(w,C,O,U){const Y={width:O[0],height:O[1],data:null},Z=w.gl;this.targetColorTexture=new o.T(w,Y,Z.RGBA8,{useMipmap:!1}),this.backgroundColorTexture=new o.T(w,Y,Z.RGBA8,{useMipmap:!1}),this.context=w,this.updateParticleTexture(C,U),this.lastInvalidatedAt=0}updateParticleTexture(w,C){if(this.particleTextureDimension===C.width)return;(this.particleTexture0||this.particleTexture1||this.particleIndexBuffer||this.particleSegment)&&(this.particleTexture0.destroy(),this.particleTexture1.destroy(),this.particleIndexBuffer.destroy(),this.particleSegment.destroy());const O=this.context.gl,U=C.width*C.height;this.particleTexture0=new o.T(this.context,C,O.RGBA8,{premultiply:!1,useMipmap:!1}),this.particleTexture1=new o.T(this.context,C,O.RGBA8,{premultiply:!1,useMipmap:!1});const Y=new o.e9;Y.reserve(U);for(let Z=0;Z0){const Cs=o.ec(C.canonical,pe),hn=o.ed(Cs);qe=o.aD(new Float32Array(16),pe.globeMatrix,hn),o.aD(qe,pe.projMatrix,qe)}const et=o.bb();et[12]+=2*U/(o.o.devicePixelRatio*pe.width),et[13]+=2*Y/(o.o.devicePixelRatio*pe.height),o.aD(qe,et,qe);const ct=D.getOrCreateProgram("debug",{defines:He}),ot=w.getTileByID(C.key);D.terrain&&D.terrain.setupElevationDraw(ot,ct);const bt=Ir.disabled,vt=Na.disabled,Pt=D.colorModeForRenderPass(),Ft="$debug";se.activeTexture.set(je.TEXTURE0),D.emptyTexture.bind(je.LINEAR,je.CLAMP_TO_EDGE),Ee?ot._makeGlobeTileDebugBuffers(D.context,pe):ot._makeDebugTileBoundsBuffers(D.context,pe.projection);const jt=ot._tileDebugBuffer||D.debugBuffer,ys=ot._tileDebugIndexBuffer||D.debugIndexBuffer,Qt=ot._tileDebugSegments||D.debugSegments;if(ct.draw(D,je.LINE_STRIP,bt,vt,Pt,ra.disabled,so(qe,O.toPremultipliedRenderColor(null)),Ft,jt,ys,Qt,null,null,null,[ot._globeTileDebugBorderBuffer]),Z){const Cs=ot.latestRawTileData,hn=Math.floor((Cs&&Cs.byteLength||0)/1024);let an=C.canonical.toString();C.overscaledZ!==C.canonical.z&&(an+=` => ${C.overscaledZ}`),an+=` ${ot.state}`,an+=` ${hn}kb`,function(An,On){An.initDebugOverlayCanvas();const Ks=An.debugOverlayCanvas,Es=An.context.gl,cn=An.debugOverlayCanvas.getContext("2d");cn.clearRect(0,0,Ks.width,Ks.height),cn.shadowColor="white",cn.shadowBlur=2,cn.lineWidth=1.5,cn.strokeStyle="white",cn.textBaseline="top",cn.font="bold 36px Open Sans, sans-serif",cn.fillText(On,5,5),cn.strokeText(On,5,5),An.debugOverlayTexture.update(Ks),An.debugOverlayTexture.bind(Es.LINEAR,Es.CLAMP_TO_EDGE)}(D,an)}const gs=w.getTile(C).tileSize,$t=512/Math.min(gs,512)*(C.overscaledZ/pe.zoom)*.5,Zt=ot._tileDebugTextBuffer||D.debugBuffer,hs=ot._tileDebugTextIndexBuffer||D.quadTriangleIndexBuffer,Us=ot._tileDebugTextSegments||D.debugSegments;ct.draw(D,je.TRIANGLES,bt,vt,wa.alphaBlended,ra.disabled,so(qe,o.aq.transparent.toPremultipliedRenderColor(null),$t),Ft,Zt,hs,Us,null,null,null,[ot._globeTileDebugTextBuffer])}function mS(D,w,C,O){_x(D,0,w+C/2,D.transform.width,C,O)}function lv(D,w,C,O){_x(D,w-C/2,0,C,D.transform.height,O)}function _x(D,w,C,O,U,Y){const Z=D.context,se=Z.gl;se.enable(se.SCISSOR_TEST),se.scissor(w*o.o.devicePixelRatio,C*o.o.devicePixelRatio,O*o.o.devicePixelRatio,U*o.o.devicePixelRatio),Z.clear({color:Y}),se.disable(se.SCISSOR_TEST)}const Uj=o.e8([{name:"a_pos_3f",components:3,type:"Float32"}]),{members:Iu}=Uj;function Yh(D,w,C,O){D.emplaceBack(w,C,O)}class jd{constructor(w){this.vertexArray=new o.ee,this.indices=new o.dC,Yh(this.vertexArray,-1,-1,1),Yh(this.vertexArray,1,-1,1),Yh(this.vertexArray,-1,1,1),Yh(this.vertexArray,1,1,1),Yh(this.vertexArray,-1,-1,-1),Yh(this.vertexArray,1,-1,-1),Yh(this.vertexArray,-1,1,-1),Yh(this.vertexArray,1,1,-1),this.indices.emplaceBack(5,1,3),this.indices.emplaceBack(3,7,5),this.indices.emplaceBack(6,2,0),this.indices.emplaceBack(0,4,6),this.indices.emplaceBack(2,6,7),this.indices.emplaceBack(7,3,2),this.indices.emplaceBack(5,4,0),this.indices.emplaceBack(0,1,5),this.indices.emplaceBack(0,2,3),this.indices.emplaceBack(3,1,0),this.indices.emplaceBack(7,6,4),this.indices.emplaceBack(4,5,7),this.vertexBuffer=w.createVertexBuffer(this.vertexArray,Iu),this.indexBuffer=w.createIndexBuffer(this.indices),this.segment=o.dy.simpleSegment(0,0,36,12)}}function Kp(D,w,C,O,U,Y){const Z=D.context.gl,se=w.paint.get("sky-atmosphere-color"),pe=w.paint.get("sky-atmosphere-halo-color"),je=w.paint.get("sky-atmosphere-sun-intensity"),Ee=((He,qe,et,ct,ot)=>({u_matrix_3f:He,u_sun_direction:qe,u_sun_intensity:et,u_color_tint_r:[ct.r,ct.g,ct.b,ct.a],u_color_tint_m:[ot.r,ot.g,ot.b,ot.a],u_luminance:5e-5}))(o.eg(o.dE(),O),U,je,se.toPremultipliedRenderColor(null),pe.toPremultipliedRenderColor(null));Z.framebufferTexture2D(Z.FRAMEBUFFER,Z.COLOR_ATTACHMENT0,Z.TEXTURE_CUBE_MAP_POSITIVE_X+Y,w.skyboxTexture,0),C.draw(D,Z.TRIANGLES,Ir.disabled,Na.disabled,wa.unblended,ra.frontCW,Ee,"skyboxCapture",w.skyboxGeometry.vertexBuffer,w.skyboxGeometry.indexBuffer,w.skyboxGeometry.segment)}const ON=o.e8([{type:"Float32",name:"a_pos",components:3},{type:"Float32",name:"a_uv",components:2}]);class qj{constructor(w){const C=new o.eh;C.emplaceBack(-1,1,1,0,0),C.emplaceBack(1,1,1,1,0),C.emplaceBack(1,-1,1,1,1),C.emplaceBack(-1,-1,1,0,1);const O=new o.dC;O.emplaceBack(0,1,2),O.emplaceBack(2,3,0),this.vertexBuffer=w.createVertexBuffer(C,ON.members),this.indexBuffer=w.createIndexBuffer(O),this.segments=o.dy.simpleSegment(0,0,4,2)}destroy(){this.vertexBuffer.destroy(),this.indexBuffer.destroy(),this.segments.destroy()}}const FN=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 f0{constructor(){this.starsCount=16e3,this.sizeMultiplier=.15,this.sizeRange=100,this.intensityRange=200}}class zN{constructor(w){this.colorModeAlphaBlendedWriteRGB=new wa([1,il,1,il],o.aq.transparent,[!0,!0,!0,!1]),this.colorModeWriteAlpha=new wa([1,0,1,0],o.aq.transparent,[!1,!1,!1,!0]),this.params=new f0,this.updateNeeded=!0}update(w){const C=w.context;if(!this.atmosphereBuffer||this.updateNeeded){this.updateNeeded=!1,this.atmosphereBuffer=new qj(C);const O=this.params.sizeRange,U=this.params.intensityRange,Y=function(Ee){const He=o.em(30),qe=[];for(let et=0;et{const $t=Y.projection.name==="globe"?["PROJECTION_GLOBE_VIEW","FOG"]:["FOG"];gs&&$t.push("ALPHA_PASS");const Zt=w.getOrCreateProgram("globeAtmosphere",{defines:$t}),hs=((Cs,hn,an,An,On,Ks,Es,cn,pn,vn,fr,nr)=>({u_frustum_tl:Cs,u_frustum_tr:hn,u_frustum_br:an,u_frustum_bl:An,u_horizon:On,u_transition:Ks,u_fadeout_range:Es,u_atmosphere_fog_color:cn.toArray01(),u_high_color:pn.toArray01(),u_space_color:vn.toArray01(),u_temporal_offset:fr,u_horizon_angle:nr}))(Y.frustumCorners.TL,Y.frustumCorners.TR,Y.frustumCorners.BR,Y.frustumCorners.BL,Y.frustumCorners.horizon,se,bt,Ee,qe,ct,Pt,ys);w.uploadCommonUniforms(O,Zt);const Us=this.atmosphereBuffer;Us&&Zt.draw(w,U.TRIANGLES,Z,Na.disabled,gs?this.colorModeWriteAlpha:this.colorModeAlphaBlendedWriteRGB,ra.backCW,hs,gs?"atmosphere_glow_alpha":"atmosphere_glow",Us.vertexBuffer,Us.indexBuffer,Us.segments)};Qt(!1),Qt(!0)}drawStars(w,C){const O=o.aC(C.properties.get("star-intensity"),0,1);if(O===0)return;const U=w.context,Y=U.gl,Z=w.transform,se=w.getOrCreateProgram("stars"),pe=o.bL([]);o.bN(pe,pe,-Z._pitch),o.bM(pe,pe,-Z.angle),o.bN(pe,pe,o.ap(Z._center.lat)),o.ek(pe,pe,-o.ap(Z._center.lng));const je=o.bR(new Float32Array(16),pe),Ee=o.aD([],Z.starsProjMatrix,je),He=o.eg([],je),qe=o.el([],He),et=[0,1,0];o.dG(et,et,qe),o.bJ(et,et,this.params.sizeMultiplier);const ct=[1,0,0];o.dG(ct,ct,qe),o.bJ(ct,ct,this.params.sizeMultiplier);const ot=(bt=et,vt=ct,Pt=O,{u_matrix:Float32Array.from(Ee),u_up:bt,u_right:vt,u_intensity_multiplier:Pt});var bt,vt,Pt;w.uploadCommonUniforms(U,se),this.starsVx&&this.starsIdx&&se.draw(w,Y.TRIANGLES,Ir.disabled,Na.disabled,this.colorModeAlphaBlendedWriteRGB,ra.disabled,ot,"atmosphere_stars",this.starsVx,this.starsIdx,this.starsSegments)}}class Ig{constructor(){this.visibleTiles=[]}updateBorders(w,C){const O=[],U=[],Y=w._getRenderableCoordinates(!1,!0);for(const pe of Y){const je=w.getTile(pe);if(!je.hasData())continue;const Ee=je.getBucket(C);Ee&&(Ee.isEmpty()||(O.push(pe.key),U.push({bucket:Ee,tileID:pe.canonical})))}let Z=O.length!==this.visibleTiles.length;if(!Z){O.sort();for(let pe=0;pepe.tileID.z-je.tileID.z||pe.tileID.x-je.tileID.x||pe.tileID.y-je.tileID.y);for(const pe of U){const je=new Array,Ee=new Array,He=pe.bucket;for(const qe of He.featuresOnBorder)se.has(qe.featureId)?Ee.push(qe.footprintIndex):(se.add(qe.featureId),je.push(qe.footprintIndex));He.updateFootprintHiddenFlags(je,o.en,!1),He.updateFootprintHiddenFlags(Ee,o.en,!0)}}}function o6(D,w){const C=[...D],O=w.cameraWorldSizeForFog/w.worldSize,U=o.b9([]);return o.cC(U,U,[O,O,1]),o.aD(C,U,C),o.aD(C,w.worldToFogMatrix,C),C}function xi(D,w,C,O,U){const Y=C.material,Z=O.context,{baseColorTexture:se,metallicRoughnessTexture:pe}=Y.pbrMetallicRoughness,{normalTexture:je,occlusionTexture:Ee,emissionTexture:He}=Y;function qe(ct,ot,bt){if(ct&&(D.push(ot),Z.activeTexture.set(Z.gl.TEXTURE0+bt),ct.gfxTexture)){const{minFilter:vt,magFilter:Pt,wrapS:Ft,wrapT:jt}=ct.sampler;ct.gfxTexture.bindExtraParam(vt,Pt,Ft,jt)}}qe(se,"HAS_TEXTURE_u_baseColorTexture",5),qe(pe,"HAS_TEXTURE_u_metallicRoughnessTexture",6),qe(je,"HAS_TEXTURE_u_normalTexture",7),qe(Ee,"HAS_TEXTURE_u_occlusionTexture",8),qe(He,"HAS_TEXTURE_u_emissionTexture",9),U&&(U.texture||(U.texture=new o.dR(O.context,U.image,[U.image.height,U.image.height,U.image.height],Z.gl.RGBA8)),Z.activeTexture.set(Z.gl.TEXTURE0+10),U.texture&&U.texture.bind(Z.gl.LINEAR,Z.gl.CLAMP_TO_EDGE),D.push("APPLY_LUT_ON_GPU")),C.texcoordBuffer&&(D.push("HAS_ATTRIBUTE_a_uv_2f"),w.push(C.texcoordBuffer)),C.colorBuffer&&(D.push(C.colorBuffer.itemSize===12?"HAS_ATTRIBUTE_a_color_3f":"HAS_ATTRIBUTE_a_color_4f"),w.push(C.colorBuffer)),C.normalBuffer&&(D.push("HAS_ATTRIBUTE_a_normal_3f"),w.push(C.normalBuffer)),C.pbrBuffer&&(D.push("HAS_ATTRIBUTE_a_pbr"),D.push("HAS_ATTRIBUTE_a_heightBasedEmissiveStrength"),w.push(C.pbrBuffer)),Y.alphaMode!=="OPAQUE"&&Y.alphaMode!=="MASK"||D.push("UNPREMULT_TEXTURE_IN_SHADER"),Y.defined||D.push("DIFFUSE_SHADED");const et=O.shadowRenderer;et&&(D.push("RENDER_SHADOWS"),et.useNormalOffset&&D.push("NORMAL_OFFSET"))}function BN(D,w,C,O,U,Y){const Z=D.modelOpacity,se=w.context,pe=new Ir(w.context.gl.LEQUAL,D.isLightMesh?Ir.ReadOnly:Ir.ReadWrite,w.depthRangeFor3D),je=w.transform,Ee=D.mesh,He=Ee.material,qe=He.pbrMetallicRoughness,et=w.style.fog;let ct;ct=w.transform.projection.zAxisUnit==="pixels"?[...D.nodeModelMatrix]:o.aD([],O.zScaleMatrix,D.nodeModelMatrix),o.aD(ct,O.negCameraPosMatrix,ct);const ot=o.b7([],ct);o.e6(ot,ot);const bt=C.paint.get("model-color-use-theme").constantOr("default")==="none",vt=C.paint.get("model-emissive-strength").constantOr(0),Pt=Dl(new Float32Array(D.worldViewProjection),new Float32Array(ct),new Float32Array(ot),null,w,Z,qe.baseColorFactor,He.emissiveFactor,qe.metallicFactor,qe.roughnessFactor,He,vt,C,void 0,void 0,D.materialOverride,D.modelColor),Ft={defines:[]},jt=[],ys=w.shadowRenderer;ys&&(ys.useNormalOffset=!1),xi(Ft.defines,jt,Ee,w,bt?null:C.lut);let Qt=null;if(et){const Zt=o6(D.nodeModelMatrix,w.transform);if(Qt=new Float32Array(Zt),je.projection.name!=="globe"){const hs=Ee.aabb.min,Us=Ee.aabb.max,[Cs,hn]=et.getOpacityForBounds(Zt,hs[0],hs[1],Us[0],Us[1]);Ft.overrideFog=Cs>=Gn||hn>=Gn}}const gs=qc(w,C.paint.get("model-cutoff-fade-range"));gs.shouldRenderCutoff&&Ft.defines.push("RENDER_CUTOFF");const $t=w.getOrCreateProgram("model",Ft);w.uploadCommonUniforms(se,$t,null,Qt,gs),w.renderPass!=="shadow"&&ys&&ys.setupShadowsFromMatrix(D.nodeModelMatrix,$t),$t.draw(w,se.gl.TRIANGLES,pe,U,Y,Ee.material.doubleSided?ra.disabled:ra.backCCW,Pt,C.id,Ee.vertexBuffer,Ee.indexBuffer,Ee.segments,C.paint,w.transform.zoom,void 0,jt)}function pS(D,w){return D.style._importedAsBasemap?"basemap":w.scope}function Y3(D,w,C,O,U,Y,Z,se,pe,je){const Ee=D.transform,He=!!w.isGeometryBloom&&w.isGeometryBloom;if(He&&D.renderPass==="shadow")return;const qe=Ee.projection.name==="globe"?o.ev(C,Ee):[...C];o.aD(qe,qe,w.globalMatrix);const et=o.aD([],O,qe);if(w.meshes)for(const ct of w.meshes){const ot=se.get(ct.material.name);if(ot&&ot.opacity<=0)continue;if(ct.material.alphaMode!=="BLEND"){Z.push({mesh:ct,depth:0,modelIndex:U,worldViewProjection:et,nodeModelMatrix:qe,isLightMesh:He,materialOverride:ot,modelOpacity:pe,modelColor:je,node:w,modelMatrix:C});continue}const bt=o.ah([],ct.centroid,et);!Ee.isOrthographic&&bt[2]<=0||Y.push({mesh:ct,depth:bt[2],modelIndex:U,worldViewProjection:et,nodeModelMatrix:qe,isLightMesh:He,materialOverride:ot,modelOpacity:pe,modelColor:je,node:w,modelMatrix:C})}if(w.children)for(const ct of w.children)Y3(D,ct,C,O,U,Y,Z,se,pe,je)}function $N(D,w,C,O){const U=C.shadowRenderer;if(!U)return;const Y=U.getShadowPassDepthMode(),Z=U.calculateShadowPassMatrixFromMatrix(w),se=Pu(Z);C.getOrCreateProgram("modelDepth").draw(C,C.context.gl.TRIANGLES,Y,Na.disabled,wa.disabled,ra.disabled,se,O.id,D.vertexBuffer,D.indexBuffer,D.segments,O.paint,C.transform.zoom,void 0,void 0)}function Z3(D,w,C,O){const U=function(Ee,He){if(He.footprintDebugMesh)return He.footprintDebugMesh;if(!He.footprint)return null;const qe=Ee.context,et=He.footprint.vertices,ct=He.footprint.indices,ot=new o.dB;ot.reserve(et.length);for(const hs of et)ot.emplaceBack(hs.x,hs.y);const bt=new o.dC;bt.reserve(ct.length);for(let hs=0;hs0){const qe=Y.terrain,et=qe.findDEMTileFor(se);et&&et.dem?pe=o.ex.create(qe,se,et):He=0}if(He===0&&(Z.terrainElevationMin=0,Z.terrainElevationMax=0),He===Z.validForExaggeration&&(He===0||pe&&pe._demTile&&pe._demTile.tileID===Z.validForDEMTile.id&&pe._dem._timestamp===Z.validForDEMTile.timestamp))return!1;for(const qe in Z.instancesPerModel){const et=Z.instancesPerModel[qe];for(let ct=0;ctje&&(je=et.max)}const Ee=o.aC(O.x,Y,Z)-O.x,He=o.aC(O.y,se,pe)-O.y,qe=o.bU(je,w.center.lat)-O.z;return w._zoomFromMercatorZ(Math.sqrt(Ee*Ee+He*He+qe*qe))}function dc(D,w,C,O,U,Y,Z){const se=D.context,pe=D.renderPass==="shadow",je=D.shadowRenderer,Ee=pe&&je?je.getShadowPassDepthMode():new Ir(se.gl.LEQUAL,Ir.ReadWrite,D.depthRangeFor3D),He=D.isTileAffectedByFog(Y),qe=D.transform.projection.name==="globe";if(C.meshes)for(const et of C.meshes){const ct=qe?[]:["MODEL_POSITION_ON_GPU"],ot=[];let bt,vt,Pt;const Ft=!qe&&O.instancedDataArray.length>20;Ft&&ct.push("INSTANCED_ARRAYS");const jt=qc(D,w.paint.get("model-cutoff-fade-range"));if(jt.shouldRenderCutoff&&ct.push("RENDER_CUTOFF"),pe&&je)bt=D.getOrCreateProgram("modelDepth",{defines:ct}),vt=Pu(Z.shadowTileMatrix,Z.shadowTileMatrix,Float32Array.from(C.globalMatrix)),Pt=wa.disabled;else{xi(ct,ot,et,D,w.paint.get("model-color-use-theme").constantOr("default")==="none"?null:w.lut),bt=D.getOrCreateProgram("model",{defines:ct,overrideFog:He});const Qt=et.material,gs=Qt.pbrMetallicRoughness,$t=w.paint.get("model-opacity").constantOr(1),Zt=w.paint.get("model-emissive-strength").constantOr(0);vt=Dl(Y.expandedProjMatrix,Float32Array.from(C.globalMatrix),new Float32Array(16),null,D,$t,gs.baseColorFactor,Qt.emissiveFactor,gs.metallicFactor,gs.roughnessFactor,Qt,Zt,w,U),je&&(Z.shadowUniformsInitialized?bt.setShadowUniformValues(se,je.getShadowUniformValues()):(je.setupShadows(Y.toUnwrapped(),bt,"model-tile"),Z.shadowUniformsInitialized=!0)),Pt=jt.shouldRenderCutoff||$t<1||Qt.alphaMode!=="OPAQUE"?wa.alphaBlended:wa.unblended}D.uploadCommonUniforms(se,bt,Y.toUnwrapped(),null,jt);const ys=et.material.doubleSided?ra.disabled:ra.backCCW;if(Ft)ot.push(O.instancedDataBuffer),bt.draw(D,se.gl.TRIANGLES,Ee,Na.disabled,Pt,ys,vt,w.id,et.vertexBuffer,et.indexBuffer,et.segments,w.paint,D.transform.zoom,void 0,ot,O.instancedDataArray.length);else{const Qt=pe?"u_instance":"u_normal_matrix";for(let gs=0;gspe[1]?Z:pe,Y[0]=C.max[0],Z=o.aE(o.bE(),Y,U),se=Z[1]pe[1]?Z:pe,Y[1]=C.min[1],Z=o.aE(o.bE(),Y,U),se=Z[1]pe[1]?Z:pe;const je=o.aC(O[0],0,1),Ee=100*w.pixelsPerMeter*o.aC(O[1],0,1),He=o.aC(O[2],0,1),qe=o.ey(o.bE(),se,pe,je),et=Math.tan(.5*w.fovX),ct=-qe[2]*et;if(Ee===0)return qe[1]<-Math.abs(ct)?He:1;const ot=(-Math.abs(ct)-qe[1])/Ee,bt=(Pt,Ft,jt)=>(1-jt)*Pt+jt*Ft,vt=o.aC(bt(1,He,ot),He,1);return bt(1,vt,o.aC((w.pitch-20)/20,0,1))}class Q3{}class l6{constructor(){this._storage=new Map}getLinesFromTrianglesBuffer(w,C,O){{const He=this._storage.get(C.id);if(He)return He.lastUsedFrameIdx=w,He.buf}const U=O.gl,Y=U.getBufferParameter(U.ELEMENT_ARRAY_BUFFER,U.BUFFER_SIZE),Z=new ArrayBuffer(Y),se=new Int16Array(Z);U.getBufferSubData(U.ELEMENT_ARRAY_BUFFER,0,new Int16Array(Z));const pe=new o.eA;for(let He=0;He30&&(O.buf.destroy(),this._storage.delete(C))}destroy(){for(const[w,C]of this._storage)C.buf.destroy(),this._storage.delete(w)}}class c6{constructor(){this.occluderSize=30,this.depthOffset=-1e-4}}const Hj=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 d6{constructor(w){this.revealStart=11,this.revealRange=2}}const J3=o.e8([{type:"Float32",name:"a_pos_2f",components:2}]);class yO{destroy(){this.vignetteVx&&this.vignetteVx.destroy(),this.vignetteIdx&&this.vignetteIdx.destroy()}draw(w,C){const O=w.getOrCreateProgram("vignette");if(!this.vignetteVx||!this.vignetteIdx){const Z=new o.eB,se=new o.dC;Z.emplaceBack(-1,-1),Z.emplaceBack(1,-1),Z.emplaceBack(1,1),Z.emplaceBack(-1,1),se.emplaceBack(0,1,2),se.emplaceBack(0,2,3),this.vignetteVx=w.context.createVertexBuffer(Z,J3.members),this.vignetteIdx=w.context.createIndexBuffer(se)}const U=o.dy.simpleSegment(0,0,4,6);if(this.vignetteVx&&this.vignetteIdx){w.uploadCommonUniforms(w.context,O);const Z={u_vignetteShape:(Y={vignetteShape:[C.start,C.range,Math.pow(10,C.fadePower)],vignetteColor:[C.color.r,C.color.g,C.color.b,C.color.a*C.strength]}).vignetteShape,u_vignetteColor:Y.vignetteColor};O.draw(w,w.context.gl.TRIANGLES,Ir.disabled,Na.disabled,wa.alphaBlended,ra.disabled,Z,"vignette",this.vignetteVx,this.vignetteIdx,U)}var Y}}class eC{constructor(){this._accumulatedOffsetX=0,this._accumulatedOffsetY=0,this._accumulatedElevation=0}update(w,C){const O=w.getFreeCameraOptions().position,U=O.toAltitude(),Y=O.toLngLat(),Z=o.ap(Y.lng),se=o.ap(Y.lat),pe=w.pixelsPerMeter/C,je=Z*o.eD,Ee=o.eD*Math.log(Math.tan(Math.PI/4+se/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 He=-this._offsetYPrev+Ee,qe=-this._elevationPrev+U;this._accumulatedOffsetX+=(-this._offsetXPrev+je)*pe,this._accumulatedOffsetY+=He*pe,this._accumulatedElevation+=qe*pe,this._offsetXPrev=je,this._offsetYPrev=Ee,this._elevationPrev=U}}getPosition(){return[this._accumulatedOffsetX,this._accumulatedOffsetY,this._accumulatedElevation]}}function Q(D,w){return[-(D[0]-Math.floor(D[0]/w)*w),-(D[1]-Math.floor(D[1]/w)*w),-(D[2]-Math.floor(D[2]/w)*w)]}function ee(D){const w=o.em(1323123451230),C=[];for(let O=0;O Rain"),this._vignetteParams={strength:1,start:.7,range:1,fadePower:.4,color:{r:.27,g:.27,b:.27,a:1}},this.particlesCount=16e3}update(w){const C=w.context;if(!this.particlesVx){const O=ee(this.particlesCount),U=new o.eE,Y=new o.dC;let Z=0;const se=o.em(1323123451230);for(let pe=0;peO)return;const U=Le(0,1,C.revealStart,C.revealStart+C.revealRange,O);if(!this.particlesVx||!this.particlesIdx)return;const Y=structuredClone(this._params);let Z=[-Y.direction.x,Y.direction.y,-100];o.ay(Z,Z);const se=structuredClone(this._vignetteParams);se.strength*=U,Y.overrideStyleParameters||(Y.intensity=w.style.rain.state.density,Y.timeFactor=w.style.rain.state.intensity,Y.color=structuredClone(w.style.rain.state.color),Z=structuredClone(w.style.rain.state.direction),Y.screenThinning.intensity=w.style.rain.state.centerThinning,Y.dropletSizeX=w.style.rain.state.dropletSize[0],Y.dropletSizeYScale=w.style.rain.state.dropletSize[1]/w.style.rain.state.dropletSize[0],Y.distortionStrength=100*w.style.rain.state.distortionStrength,se.strength=1,se.color=structuredClone(w.style.rain.state.vignetteColor));const pe=this.updateOnRender(w,Y.timeFactor),je=w.context,Ee=je.gl,He=w.transform;this.screenTexture&&this.screenTexture.size[0]===w.width&&this.screenTexture.size[1]===w.height||(this.screenTexture=new o.T(je,{width:w.width,height:w.height,data:null},Ee.RGBA8)),Y.distortionStrength>0&&(je.activeTexture.set(Ee.TEXTURE0),this.screenTexture.bind(Ee.LINEAR,Ee.CLAMP_TO_EDGE),Ee.copyTexSubImage2D(Ee.TEXTURE_2D,0,0,0,0,0,w.width,w.height));const qe=w.getOrCreateProgram("rainParticle");w.uploadCommonUniforms(je,qe),je.activeTexture.set(Ee.TEXTURE0),this.screenTexture.bind(Ee.LINEAR,Ee.CLAMP_TO_EDGE);const et=[Y.color.r,Y.color.g,Y.color.b,Y.color.a],ct=(ot,bt)=>{const vt=Q(this._movement.getPosition(),ot),Pt=Y.dropletSizeX,Ft=Y.dropletSizeX*Y.dropletSizeYScale,jt=w.width/2,ys=w.height/2,Qt=Le(0,Y.screenThinning.start,0,1,Y.screenThinning.intensity),gs=Le(.001,Y.screenThinning.range,0,1,Y.screenThinning.intensity),$t=Le(0,Y.screenThinning.particleOffset,0,1,Y.screenThinning.intensity),Zt=(hs={modelview:pe.modelviewMatrix,projection:pe.projectionMatrix,time:this._accumulatedTimeFromStart,camPos:vt,velocityConeAperture:Y.velocityConeAperture,velocity:Y.velocity,boxSize:ot,rainDropletSize:[Pt,Ft],distortionStrength:Y.distortionStrength,rainDirection:Z,color:et,screenSize:[He.width,He.height],thinningCenterPos:[jt,ys],thinningShape:[Qt,gs,Math.pow(10,Y.screenThinning.fadePower)],thinningAffectedRatio:Y.screenThinning.affectedRatio,thinningParticleOffset:$t,shapeDirectionalPower:Y.shapeDirPower,shapeNormalPower:Y.shapeNormalPower,mode:bt?0:1},{u_modelview:Float32Array.from(hs.modelview),u_projection:Float32Array.from(hs.projection),u_time:hs.time,u_cam_pos:hs.camPos,u_texScreen:0,u_velocityConeAperture:hs.velocityConeAperture,u_velocity:hs.velocity,u_boxSize:hs.boxSize,u_rainDropletSize:hs.rainDropletSize,u_distortionStrength:hs.distortionStrength,u_rainDirection:hs.rainDirection,u_color:hs.color,u_screenSize:hs.screenSize,u_thinningCenterPos:hs.thinningCenterPos,u_thinningShape:hs.thinningShape,u_thinningAffectedRatio:hs.thinningAffectedRatio,u_thinningParticleOffset:hs.thinningParticleOffset,u_shapeDirectionalPower:hs.shapeDirectionalPower,u_shapeNormalPower:hs.shapeNormalPower,u_mode:hs.mode});var hs;const Us=Math.round(Y.intensity*this.particlesCount),Cs=o.dy.simpleSegment(0,0,4*Us,2*Us);qe.draw(w,Ee.TRIANGLES,Ir.disabled,Na.disabled,wa.alphaBlended,ra.disabled,Zt,"rain_particles",this.particlesVx,this.particlesIdx,Cs)};Y.distortionStrength>0&&ct(Y.boxSize,!0),ct(Y.boxSize,!1),this._vignette.draw(w,se)}}const St=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 Ps extends tt{constructor(w){super(2.25),this._params={overrideStyleParameters:!1,intensity:.85,timeFactor:.75,velocityConeAperture:70,velocity:40,horizontalOscillationRadius:4,horizontalOscillationRate:1.5,boxSize:2e3,billboardSize:2,shapeFadeStart:.27,shapeFadePower:.21,screenThinning:{intensity:.4,start:.15,range:1.4,fadePower:.24,affectedRatio:1,particleOffset:-.2},color:{r:1,g:1,b:1,a:1},direction:{x:-50,y:-35}},this._revealParams=new d6("Precipitation > Snow"),this._vignetteParams={strength:.3,start:.78,range:.46,fadePower:.2,color:{r:1,g:1,b:1,a:1}},this.particlesCount=16e3}update(w){const C=w.context;if(!this.particlesVx){const O=ee(this.particlesCount),U=new o.eF,Y=new o.dC;let Z=0;const se=o.em(1323123451230);for(let pe=0;peZ)return;const se=Le(0,1,Y.revealStart,Y.revealStart+Y.revealRange,Z);U.strength*=se,C.overrideStyleParameters||(C.intensity=w.style.snow.state.density,C.timeFactor=w.style.snow.state.intensity,C.color=structuredClone(w.style.snow.state.color),O=structuredClone(w.style.snow.state.direction),C.screenThinning.intensity=w.style.snow.state.centerThinning,C.billboardSize=2.79*w.style.snow.state.flakeSize,U.strength=1,U.color=structuredClone(w.style.snow.state.vignetteColor));const pe=this.updateOnRender(w,C.timeFactor);if(!this.particlesVx||!this.particlesIdx)return;const je=w.context,Ee=je.gl,He=w.transform,qe=w.getOrCreateProgram("snowParticle");w.uploadCommonUniforms(je,qe),((et,ct,ot)=>{const bt=Q(this._movement.getPosition(),et),vt=He.width/2,Pt=He.height/2,Ft=Le(0,ot.screenThinning.start,0,1,ot.screenThinning.intensity),jt=Le(.001,ot.screenThinning.range,0,1,ot.screenThinning.intensity),ys=Le(0,ot.screenThinning.particleOffset,0,1,ot.screenThinning.intensity),Qt=(gs={modelview:pe.modelviewMatrix,projection:pe.projectionMatrix,time:this._accumulatedTimeFromStart,camPos:bt,velocityConeAperture:ot.velocityConeAperture,velocity:ot.velocity,horizontalOscillationRadius:ot.horizontalOscillationRadius,horizontalOscillationRate:ot.horizontalOscillationRate,boxSize:et,billboardSize:1*ot.billboardSize,simpleShapeParameters:[ot.shapeFadeStart,ot.shapeFadePower],screenSize:[He.width,He.height],thinningCenterPos:[vt,Pt],thinningShape:[Ft,jt,Math.pow(10,ot.screenThinning.fadePower)],thinningAffectedRatio:ot.screenThinning.affectedRatio,thinningParticleOffset:ys,color:[ot.color.r,ot.color.g,ot.color.b,ot.color.a],direction:O},{u_modelview:Float32Array.from(gs.modelview),u_projection:Float32Array.from(gs.projection),u_time:gs.time,u_cam_pos:gs.camPos,u_velocityConeAperture:gs.velocityConeAperture,u_velocity:gs.velocity,u_horizontalOscillationRadius:gs.horizontalOscillationRadius,u_horizontalOscillationRate:gs.horizontalOscillationRate,u_boxSize:gs.boxSize,u_billboardSize:gs.billboardSize,u_simpleShapeParameters:gs.simpleShapeParameters,u_screenSize:gs.screenSize,u_thinningCenterPos:gs.thinningCenterPos,u_thinningShape:gs.thinningShape,u_thinningAffectedRatio:gs.thinningAffectedRatio,u_thinningParticleOffset:gs.thinningParticleOffset,u_particleColor:gs.color,u_direction:gs.direction});var gs;const $t=Math.round(ot.intensity*this.particlesCount),Zt=o.dy.simpleSegment(0,0,4*$t,2*$t);this.particlesVx&&this.particlesIdx&&qe.draw(w,Ee.TRIANGLES,Ir.disabled,Na.disabled,wa.alphaBlended,ra.disabled,Qt,"snow_particles",this.particlesVx,this.particlesIdx,Zt)})(C.boxSize,0,C),this._vignette.draw(w,U)}}const Fn={symbol:function(D,w,C,O,U){if(D.renderPass!=="translucent")return;const Y=Na.disabled,Z=D.colorModeForRenderPass(),se=C.layout.get("text-variable-anchor"),pe=C.layout.get("text-size-scale-range"),je=o.aC(D.scaleFactor,pe[0],pe[1]);se&&function(qe,et,ct,ot,bt,vt,Pt,Ft){const jt=et.transform,ys=bt==="map",Qt=vt==="map";for(const gs of qe){const $t=ot.getTile(gs),Zt=$t.getBucket(ct);if(!Zt||!Zt.text||!Zt.text.segments.get().length)continue;const hs=o.bj(Zt.textSizeData,jt.zoom,Ft),Us=Vh(gs,Zt.getProjection(),jt),Cs=jt.calculatePixelsToTileUnitsMatrix($t),hn=Jc(Us,$t.tileID.canonical,Qt,ys,jt,Zt.getProjection(),Cs),an=Zt.hasIconTextFit()&&Zt.hasIconData();hs&&cc(Zt,ys,Qt,Pt,jt,hn,gs,Math.pow(2,jt.zoom-$t.tileID.overscaledZ),hs,an)}}(O,D,C,w,C.layout.get("text-rotation-alignment"),C.layout.get("text-pitch-alignment"),U,je);const Ee=C.paint.get("icon-opacity").constantOr(1)!==0,He=C.paint.get("text-opacity").constantOr(1)!==0;C.layout.get("symbol-sort-key").constantOr(1)!==void 0&&(Ee||He)?Kh(D,w,C,O,Y,Z):(Ee&&Kh(D,w,C,O,Y,Z,{onlyIcons:!0}),He&&Kh(D,w,C,O,Y,Z,{onlyText:!0})),w.map.showCollisionBoxes&&(pr(D,w,C,O,C.paint.get("text-translate"),C.paint.get("text-translate-anchor"),!0),pr(D,w,C,O,C.paint.get("icon-translate"),C.paint.get("icon-translate-anchor"),!1))},circle:function(D,w,C,O){if(D.renderPass!=="translucent")return;const U=C.paint.get("circle-opacity"),Y=C.paint.get("circle-stroke-width"),Z=C.paint.get("circle-stroke-opacity"),se=C.layout.get("circle-sort-key").constantOr(1)!==void 0,pe=C.paint.get("circle-emissive-strength");if(U.constantOr(1)===0&&(Y.constantOr(1)===0||Z.constantOr(1)===0))return;const je=D.context,Ee=je.gl,He=D.transform,qe=!(!D.terrain||!D.terrain.enabled),et=C.layout.get("circle-elevation-reference"),ct=D.depthModeForSublayer(0,Ir.ReadOnly),ot=new Ir(D.context.gl.LEQUAL,Ir.ReadOnly,D.depthRangeFor3D),bt=et==="none"||qe?ct:ot,vt=Na.disabled,Pt=D.colorModeForDrapableLayerRenderPass(pe),Ft=He.projection.name==="globe",jt=[o.aH(He.center.lng),o.aL(He.center.lat)],ys=[];for(let gs=0;gsgs.sortKey-$t.sortKey);const Qt={useDepthForOcclusion:He.depthOcclusionForSymbolsAndCircles};for(const gs of ys){const{programConfiguration:$t,program:Zt,layoutVertexBuffer:hs,dynamicBuffers:Us,indexBuffer:Cs,uniformValues:hn,tile:an}=gs.state,An=gs.segments;D.terrain&&D.terrain.setupElevationDraw(an,Zt,Qt),D.uploadCommonUniforms(je,Zt,an.tileID.toUnwrapped()),Zt.draw(D,Ee.TRIANGLES,bt,vt,Pt,ra.disabled,hn,C.id,hs,Cs,An,C.paint,He.zoom,$t,Us)}},heatmap:function(D,w,C,O){if(C.paint.get("heatmap-opacity")!==0)if(D.renderPass==="offscreen"){const U=D.context,Y=U.gl,Z=Na.disabled,se=new wa([Y.ONE,Y.ONE,Y.ONE,Y.ONE],o.aq.transparent,[!0,!0,!0,!0]),pe=D.transform.projection.name==="globe"?.5:.25;C.heatmapFbo=ym.createWithTexture(U,C.heatmapFbo,D.width*pe,D.height*pe),U.clear({color:o.aq.transparent});const je=D.transform,Ee=je.projection.name==="globe",He=Ee?["PROJECTION_GLOBE_VIEW"]:[],qe=Ee?ra.frontCCW:ra.disabled,et=[o.aH(je.center.lng),o.aL(je.center.lat)];for(let ct=0;ct({u_image:0,u_color_ramp:1,u_opacity:He.paint.get("heatmap-opacity")}))(0,Y),Y.id,U.viewportBuffer,U.quadTriangleIndexBuffer,U.viewportSegments,Y.paint,U.transform.zoom)}(D,C))},line:function(D,w,C,O){const U=C.paint.get("line-opacity"),Y=C.paint.get("line-width");if(U.constantOr(1)===0||Y.constantOr(1)===0)return;const Z=C.paint.get("line-blend-mode");if(Z!=="default"&&D.transform.projection.name!=="globe")return D.terrain&&D.terrain.renderingToTexture?void function(se,pe,je,Ee,He){if(se.renderPass!=="translucent")return;const qe=se.context,et=qe.gl,ct=se.terrain;if(!ct)return;const ot=qe.bindFramebuffer.current,bt=se.emissiveMode==="mrt-fallback";je.lineBlendDrapeFbo=ym.createWithTexture(qe,je.lineBlendDrapeFbo,ct.drapeBufferSize[0],ct.drapeBufferSize[1],!0),je.lineBlendDrapeStencil=je.lineBlendDrapeFbo._stencilRbo,bt&&et.drawBuffers([et.COLOR_ATTACHMENT0]),qe.clear({color:ap[He].clearColor,depth:1,stencil:0});const vt=se.currentStencilSource,Pt=se._tileClippingMaskIDs,Ft=se.nextStencilID;se.currentStencilSource=void 0,se._tileClippingMaskIDs={},se.nextStencilID=1;const jt=se._terrain;se._terrain=null,se._renderTileClippingMasks(je,pe,Ee),Yd(se,pe,je,Ee,ap[He].colorMode,!0),se._terrain=jt,se.currentStencilSource=vt,se._tileClippingMaskIDs=Pt,se.nextStencilID=Ft,qe.bindFramebuffer.set(ot),bt&&et.drawBuffers([et.COLOR_ATTACHMENT0,et.COLOR_ATTACHMENT1]);const ys=ct.drapeBufferSize;qe.viewport.set([0,0,ys[0],ys[1]]);const Qt=je.lineBlendDrapeFbo;if(!Qt)return;qe.activeTexture.set(et.TEXTURE0),et.bindTexture(et.TEXTURE_2D,Qt.colorAttachment0.get());const gs=He==="additive"?1:je.paint.get("line-opacity").constantOr(1),$t=je.paint.get("line-emissive-strength").constantOr(0),Zt=He==="additive"?se.colorModeForDrapableLayerRenderPass($t):ap[He].colorMode;se.getOrCreateProgram("lineBlendComposite").draw(se,et.TRIANGLES,Ir.disabled,Na.disabled,Zt,ra.disabled,xl(0,gs,ap[He].compositeUniformValue),je.id,se.viewportBuffer,se.quadTriangleIndexBuffer,se.viewportSegments,je.paint,se.transform.zoom)}(D,w,C,O,Z):D.renderPass==="offscreen"?void function(se,pe,je,Ee,He){const qe=se.context,et=Math.ceil(se.width),ct=Math.ceil(se.height);je.lineBlendFbo=ym.createWithTexture(qe,je.lineBlendFbo,et,ct,!0),je.lineBlendStencil=je.lineBlendFbo._stencilRbo,qe.clear({color:ap[He].clearColor,depth:1,stencil:0});const ot=se.currentStencilSource,bt=se._tileClippingMaskIDs,vt=se.nextStencilID;se.currentStencilSource=void 0,se._tileClippingMaskIDs={},se.nextStencilID=1,se._renderTileClippingMasks(je,pe,Ee);const Pt=se.renderPass;se.renderPass="translucent",Yd(se,pe,je,Ee,ap[He].colorMode),se.renderPass=Pt,se.currentStencilSource=ot,se._tileClippingMaskIDs=bt,se.nextStencilID=vt,qe.viewport.set([0,0,se.width,se.height])}(D,w,C,O,Z):D.renderPass==="translucent"?void function(se,pe,je){const Ee=se.context,He=Ee.gl,qe=pe.lineBlendFbo;if(!qe)return;Ee.activeTexture.set(He.TEXTURE0),He.bindTexture(He.TEXTURE_2D,qe.colorAttachment0.get());const et=je==="additive"?1:pe.paint.get("line-opacity").constantOr(1),ct=je==="additive"?se.colorModeForDrapableLayerRenderPass(pe.paint.get("line-emissive-strength").constantOr(0)):ap[je].colorMode;se.getOrCreateProgram("lineBlendComposite").draw(se,He.TRIANGLES,Ir.disabled,Na.disabled,ct,ra.disabled,xl(0,et,ap[je].compositeUniformValue),pe.id,se.viewportBuffer,se.quadTriangleIndexBuffer,se.viewportSegments,pe.paint,se.transform.zoom)}(D,C,Z):void 0;D.renderPass==="translucent"&&Yd(D,w,C,O)},fill:function(D,w,C,O){const U=C.paint.get("fill-color"),Y=C.paint.get("fill-opacity");if(Y.constantOr(1)===0)return;const Z=C.paint.get("fill-emissive-strength"),se=D.colorModeForDrapableLayerRenderPass(Z),pe=C.paint.get("fill-pattern"),je=D.opaquePassEnabledForLayer()&&!pe.constantOr(1)&&U.constantOr(o.aq.transparent).a===1&&Y.constantOr(0)===1?"opaque":"translucent";let Ee="none";C.layout.get("fill-elevation-reference")!=="none"?Ee="road":C.paint.get("fill-z-offset").constantOr(1)!==0&&(Ee="offset");const He=!(!D.terrain||!D.terrain.enabled),qe={painter:D,sourceCache:w,layer:C,coords:O,colorMode:se,elevationType:Ee,terrainEnabled:He,pass:je};if(D.renderPass==="shadow")return void(D.shadowRenderer&&Ee==="road"&&!He&&function(ct){const{painter:ot,sourceCache:bt,layer:vt,coords:Pt}=ct,Ft=ot.context.gl,jt=ct.painter.shadowRenderer;for(const ys of Pt){const Qt=bt.getTile(ys),gs=Qt.getBucket(vt);if(!gs)continue;const $t=gs.elevatedStructures;if(!$t||!$t.shadowCasterSegments||$t.shadowCasterSegments.segments[0].primitiveLength===0)continue;ot.prepareDrawTile();const Zt=gs.bufferData.programConfigurations.get(vt.id),hs=ot.isTileAffectedByFog(ys),Us=ot.getOrCreateProgram("elevatedStructuresDepth",{config:Zt,overrideFog:hs}),Cs=jt.calculateShadowPassMatrixFromTile(Qt.tileID.toUnwrapped());ot.uploadCommonUniforms(ot.context,Us,ys.toUnwrapped());const hn=hi(Cs,0);Us.draw(ot,Ft.TRIANGLES,jt.getShadowPassDepthMode(),Na.disabled,wa.disabled,ra.disabled,hn,vt.id,$t.vertexBuffer,$t.indexBuffer,$t.shadowCasterSegments,vt.paint,ot.transform.zoom,Zt)}}(qe));const et=D.emissiveMode==="mrt-fallback";if(Ee!=="offset"){if(av(qe,!1,et),Ee==="road"){const ct=!He&&D.renderPass==="translucent";ct&&y1(D,w,C,O,"geometry"),av(qe,!0,et,Na.disabled),ct&&function(ot){const{painter:bt,sourceCache:vt,layer:Pt,coords:Ft,colorMode:jt}=ot,ys=bt.context.gl,Qt=ot.painter.shadowRenderer,gs=!!Qt&&Qt.enabled,$t=new Ir(bt.context.gl.LEQUAL,Ir.ReadOnly,bt.depthRangeFor3D);let Zt=[0,0,0];if(gs){const Us=bt.style.directionalLight,Cs=bt.style.ambientLight;Us&&Cs&&(Zt=oh(bt.style,Us,Cs))}const hs=Us=>{for(const Cs of Ft){const hn=vt.getTile(Cs),an=hn.getBucket(Pt);if(!an)continue;const An=an.elevatedStructures;if(!An)continue;let On,Ks;if(Us?(On=An.renderableBridgeSegments,Ks=An.bridgeProgramConfigurations.get(Pt.id)):(On=An.renderableTunnelSegments,Ks=An.tunnelProgramConfigurations.get(Pt.id)),!On||On.segments[0].primitiveLength===0)continue;Ks.updatePaintBuffers(),bt.prepareDrawTile();const Es=bt.isTileAffectedByFog(Cs),cn=[];gs&&cn.push("RENDER_SHADOWS","NORMAL_OFFSET");const pn=bt.getOrCreateProgram("elevatedStructures",{config:Ks,overrideFog:Es,defines:cn}),vn=bt.translatePosMatrix(Cs.projMatrix,hn,Pt.paint.get("fill-translate"),Pt.paint.get("fill-translate-anchor"));gs&&Qt.setupShadows(hn.tileID.toUnwrapped(),pn,"vector-tile");const fr=Ko(vn,Zt);bt.uploadCommonUniforms(bt.context,pn,Cs.toUnwrapped()),pn.draw(bt,ys.TRIANGLES,$t,Na.disabled,jt,ra.backCCW,fr,Pt.id,An.vertexBuffer,An.indexBuffer,On,Pt.paint,bt.transform.zoom,Ks,[An.vertexBufferNormal])}};hs(!0),hs(!1)}(qe)}}else av(qe,!1,et,D.stencilModeFor3D())},"fill-extrusion":function(D,w,C,O){const U=C.paint.get("fill-extrusion-opacity"),Y=D.context,Z=Y.gl,se=D.terrain,pe=se&&se.renderingToTexture;if(U===0)return;const je=D.emissiveMode==="mrt-fallback",Ee=D.conflationActive&&D.style.isLayerClipped(C,w.getSource()),He=D.style.order.indexOf(C.fqid);if(Ee&&function(qe,et,ct,ot,bt){for(const vt of ot){const Pt=et.getTile(vt).getBucket(ct);Pt&&(Pt.updateReplacement(vt,qe.replacementSource,bt),Pt.uploadCentroid(qe.context))}}(D,w,C,O,He),se||Ee)for(const qe of O){const et=w.getTile(qe).getBucket(C);et&&m0(D.context,w,qe,et,C,se,Ee)}if(D.renderPass==="shadow"&&D.shadowRenderer){if(se&&U<.65&&C._transitionablePaint._values["fill-extrusion-opacity"].value.expression instanceof o.af)return;const qe=D.shadowRenderer.getShadowPassDepthMode();vm(D,w,C,O,qe,Na.disabled,wa.disabled,Ee)}else if(D.renderPass==="translucent"){const qe=!C.paint.get("fill-extrusion-pattern").constantOr(1),et=C.paint.get("fill-extrusion-color").constantOr(o.aq.white);if(!pe&&et.a!==0){const ct=new Ir(D.context.gl.LEQUAL,Ir.ReadWrite,D.depthRangeFor3D);U===1&&qe?vm(D,w,C,O,ct,Na.disabled,wa.unblended,Ee):(vm(D,w,C,O,ct,Na.disabled,wa.disabled,Ee),vm(D,w,C,O,ct,D.stencilModeFor3D(),D.colorModeForRenderPass(),Ee),D.resetStencilClippingMasks())}if(D.style.enable3dLights()&&qe&&(!se&&D.transform.projection.name!=="globe"||pe)){const ct=C.paint.get("fill-extrusion-opacity"),ot=C.paint.get("fill-extrusion-ambient-occlusion-intensity"),bt=C.paint.get("fill-extrusion-ambient-occlusion-ground-radius"),vt=C.paint.get("fill-extrusion-flood-light-intensity"),Pt=C.paint.get("fill-extrusion-flood-light-color-use-theme").constantOr("default")==="none",Ft=C.paint.get("fill-extrusion-flood-light-color").toNonPremultipliedRenderColor(Pt?null:C.lut).toArray01().slice(0,3),jt=ot>0&&bt>0,ys=vt>0,Qt=(Zt,hs,Us)=>(1-Us)*Zt+Us*hs,gs=new Gp;gs.translate=C.paint.get("fill-extrusion-translate"),gs.translateAnchor=C.paint.get("fill-extrusion-translate-anchor"),gs.edgeRadius=C.layout.get("fill-extrusion-edge-radius"),gs.cutoffFadeRange=C.paint.get("fill-extrusion-cutoff-fade-range");const $t=Zt=>{const hs=D.depthModeForSublayer(1,Ir.ReadOnly,Z.LEQUAL,!0),Us=C.paint.get(Zt?"fill-extrusion-ambient-occlusion-ground-attenuation":"fill-extrusion-flood-light-ground-attenuation"),Cs=Qt(.1,3,Us),hn=D._showOverdrawInspector;if(!hn){const an=new Na({func:Z.ALWAYS,mask:255},255,255,Z.KEEP,Z.KEEP,Z.REPLACE),An=new wa([Z.ONE,Z.ONE,Z.ONE,Z.ONE],o.aq.transparent,[!1,!1,!1,!0],Z.MIN);bx(gs,D,w,C,O,hs,an,An,ra.disabled,Zt,"sdf",ct,ot,bt,vt,Ft,Cs,Ee,!1)}{const an=hn?Na.disabled:new Na({func:Z.EQUAL,mask:255},255,255,Z.KEEP,Z.DECR,Z.DECR),An=hn?D.colorModeForRenderPass():new wa([Z.ONE_MINUS_DST_ALPHA,Z.DST_ALPHA,Z.ONE,Z.ONE],o.aq.transparent,[!0,!0,!0,!0]);bx(gs,D,w,C,O,hs,an,An,ra.disabled,Zt,"color",ct,ot,bt,vt,Ft,Cs,Ee,!1)}};if(pe){const Zt=()=>{const Us=se.drapeBufferSize[0],Cs=se.drapeBufferSize[1];let hn=se.framebufferCopyTexture;return hn&&(!hn||hn.size[0]===Us&&hn.size[1]===Cs)||(hn&&hn.destroy(),hn=se.framebufferCopyTexture=new o.T(Y,new o.q({width:Us,height:Cs}),Z.RGBA8)),hn.bind(Z.LINEAR,Z.CLAMP_TO_EDGE),Z.copyTexSubImage2D(Z.TEXTURE_2D,0,0,0,0,0,Us,Cs),hn},hs=(Us,Cs,hn)=>{const an=D.depthModeForSublayer(1,Ir.ReadOnly,Z.LEQUAL,!1),An=C.paint.get(Us?"fill-extrusion-ambient-occlusion-ground-attenuation":"fill-extrusion-flood-light-ground-attenuation"),On=Qt(.1,3,An);{const Ks=new wa([Z.ONE,Z.ONE,Z.ONE,Z.ONE],o.aq.transparent,[!1,!1,!1,!0]);bx(gs,D,w,C,O,an,Na.disabled,Ks,ra.disabled,Us,"clear",ct,ot,bt,vt,Ft,On,Ee,Cs)}{const Ks=new Na({func:Z.ALWAYS,mask:255},255,255,Z.KEEP,Z.KEEP,Z.REPLACE),Es=new wa([Z.ONE,Z.ONE,Z.ONE,Z.ONE],o.aq.transparent,[!1,!1,!1,!0],Z.MIN);bx(gs,D,w,C,O,an,Ks,Es,ra.disabled,Us,"sdf",ct,ot,bt,vt,Ft,On,Ee,Cs)}je&&!Us&&(hn=Zt());{const Ks=Us?Z.ZERO:Z.ONE_MINUS_DST_ALPHA,Es=new Na({func:Z.EQUAL,mask:255},255,255,Z.KEEP,Z.DECR,Z.DECR),cn=new wa([Ks,Z.DST_ALPHA,Z.ONE_MINUS_DST_ALPHA,Z.ZERO],o.aq.transparent,[!0,!0,!0,!0]);bx(gs,D,w,C,O,an,Es,cn,ra.disabled,Us,"color",ct,ot,bt,vt,Ft,On,Ee,Cs)}if(!je||Us){const Ks=new wa([Z.ONE,Z.ONE,Z.ONE,Us?Z.ZERO:Z.ONE],o.aq.transparent,[!1,!1,!1,!0],Us?Z.FUNC_ADD:Z.MAX);bx(gs,D,w,C,O,an,Na.disabled,Ks,ra.disabled,Us,"clear",ct,ot,bt,vt,Ft,On,Ee,Cs,hn)}else{Z.drawBuffers([Z.NONE,Z.COLOR_ATTACHMENT1]);const Ks=new Na({func:Z.EQUAL,mask:255},254,255,Z.KEEP,Z.DECR,Z.DECR),Es=new wa([Z.ONE,Z.ONE,Z.ONE,Z.ONE],o.aq.transparent,[!0,!1,!1,!1],Z.MAX);bx(gs,D,w,C,O,an,Ks,Es,ra.disabled,Us,"emissive",ct,ot,bt,vt,Ft,On,Ee,Cs,hn),Z.drawBuffers([Z.COLOR_ATTACHMENT0])}};if(jt||ys){let Us;D.prepareDrawTile(),je&&!jt||(Us=Zt()),jt&&hs(!0,!1,Us),ys&&hs(!1,!0,Us)}}else jt&&$t(!0),ys&&$t(!1),(jt||ys)&&D.resetStencilClippingMasks()}}},building:function(D,w,C,O){D.currentLayer0&&Y>0,je=!0;const Ee=C.paint.get("building-vertical-scale");if(Ee<=0)return;D.shadowRenderer||(je=!1);const He=D.conflationActive&&D.style.isLayerClipped(C,w.getSource()),qe=D.style.order.indexOf(C.fqid);if(function(et,ct,ot,bt,vt,Pt){for(const Ft of Pt){const jt=ct.getTile(Ft).getBucket(ot);jt&&(vt&&jt.updateReplacement(Ft,et.replacementSource,bt),jt.uploadUpdatedIndexBuffer(et.context))}}(D,w,C,qe,He,O),function(et,ct,ot,bt){for(const vt of bt){const Pt=ct.getTile(vt).getBucket(ot);Pt&&Pt.needsEvaluation()&&Pt.uploadUpdatedColorBuffer(et.context)}}(D,w,C,O),C.resetLayerRenderingStats(D),D.shadowRenderer&&(D.shadowRenderer.useNormalOffset=!0),D.renderPass==="shadow"&&D.shadowRenderer){const et=[],ct=D.shadowRenderer.getShadowPassDepthMode();hy({painter:D,source:w,layer:C,coords:O,defines:et,blendMode:wa.disabled,depthMode:ct,opacity:se,verticalScale:Ee,facadeEmissiveChance:0,facadeAOIntensity:0,floodLightIntensity:0,floodLightColor:[0,0,0]})}else if(D.renderPass==="translucent"){let et=["HAS_ATTRIBUTE_a_part_color_emissive","LIGHTING_3D_MODE"];je&&(et=et.concat("RENDER_SHADOWS")),D.shadowRenderer&&D.shadowRenderer.useNormalOffset&&(et=et.concat("NORMAL_OFFSET"));const ct=C.paint.get("building-facade-emissive-chance"),ot=C.paint.get("building-ambient-occlusion-intensity"),bt=C.paint.get("building-flood-light-intensity"),vt=C.paint.get("building-flood-light-color-use-theme").constantOr("default")==="none",Pt=C.paint.get("building-flood-light-color").toNonPremultipliedRenderColor(vt?null:C.lut).toArray01().slice(0,3),Ft=C.paint.get("building-flood-light-ground-attenuation"),jt=bt>0,ys=new Ir(D.context.gl.LEQUAL,Ir.ReadWrite,D.depthRangeFor3D);se<1&&hy({painter:D,source:w,layer:C,coords:O,defines:et,blendMode:wa.disabled,depthMode:ys,opacity:se,verticalScale:Ee,facadeEmissiveChance:ct,facadeAOIntensity:ot,floodLightIntensity:bt,floodLightColor:Pt,depthOnly:!0});const Qt=D.colorModeForRenderPass();hy({painter:D,source:w,layer:C,coords:O,defines:et,blendMode:Qt,depthMode:ys,opacity:se,verticalScale:Ee,facadeEmissiveChance:ct,facadeAOIntensity:ot,floodLightIntensity:bt,floodLightColor:Pt});const gs=C.paint.get("building-front-cutoff");uw(D.transform.pitch,gs,!!D.terrain),pe&&sg(D,w,C,O,!0,se,U,Y,bt,Pt,Z,He),jt&&sg(D,w,C,O,!1,se,U,Y,bt,Pt,Ft,He)}else if(D.renderPass==="light-beam"){const et=["HAS_ATTRIBUTE_a_part_color_emissive","HAS_ATTRIBUTE_a_bloom_attenuation"],ct=new Ir(D.context.gl.LEQUAL,Ir.ReadOnly,D.depthRangeFor3D);hy({painter:D,source:w,layer:C,coords:O,defines:et,blendMode:wa.alphaBlended,depthMode:ct,opacity:se,verticalScale:Ee,facadeEmissiveChance:0,facadeAOIntensity:0,floodLightIntensity:0,floodLightColor:[0,0,0]})}D.shadowRenderer&&(D.shadowRenderer.useNormalOffset=!1),D.resetStencilClippingMasks()},hillshade:function(D,w,C,O){if(D.renderPass!=="offscreen"&&D.renderPass!=="translucent"||D.style.disableElevatedTerrain)return;const U=D.context,Y=D.terrain&&D.terrain.renderingToTexture,[Z,se]=D.renderPass!=="translucent"||Y?[{},O]:D.stencilConfigForOverlap(O);for(const pe of se){const je=w.getTile(pe);if(je.needsHillshadePrepare&&D.renderPass==="offscreen")W3(D,je,C);else if(D.renderPass==="translucent"){const Ee=D.depthModeForSublayer(0,Ir.ReadOnly),He=C.paint.get("hillshade-emissive-strength"),qe=D.colorModeForDrapableLayerRenderPass(He),et=Y&&D.terrain?D.terrain.stencilModeForRTTOverlap(pe):Z[pe.overscaledZ];a6(D,pe,je,C,Ee,et,qe)}}U.viewport.set([0,0,D.width,D.height]),D.resetStencilClippingMasks()},raster:function(D,w,C,O,U,Y){if(D.renderPass!=="translucent")return;const Z=C.paint.get("raster-opacity");if(Z===0)return;const se=D.transform.projection.name==="globe",pe=C.paint.get("raster-elevation")!==0,je=pe&&se,Ee=D.terrain&&D.terrain.exaggeration()>0&&pe&&C.paint.get("raster-elevation-reference")==="ground",He=!se&&Ee;if(D.renderElevatedRasterBackface&&!je)return;const qe=D.context,et=qe.gl,ct=w.getSource(),ot=function(Zt,hs,Us,Cs,hn){const an=hs.paint.get("raster-color"),An=Zt.type==="raster-array",On=[],Ks=hs.paint.get("raster-resampling"),Es=hs.paint.get("raster-color-mix");let cn=hs.paint.get("raster-color-range");const pn=[Es[0],Es[1],Es[2],0],vn=Es[3];let fr=Ks==="nearest"?Cs.NEAREST:Cs.LINEAR;if(An&&(On.push("RASTER_ARRAY"),an||On.push("RASTER_COLOR"),Ks==="linear"&&On.push("RASTER_ARRAY_LINEAR"),fr=Cs.NEAREST,!cn&&Zt.rasterLayers)){const nr=Zt.rasterLayers.find(({id:rr})=>rr===hs.sourceLayer);nr&&nr.fields&&nr.fields.range&&(cn=nr.fields.range)}if(cn=cn||[0,1],an){On.push("RASTER_COLOR"),Us.activeTexture.set(Cs.TEXTURE2),hs.updateColorRamp(cn);let nr=hs.colorRampTexture;nr||(nr=hs.colorRampTexture=new o.T(Us,hs.colorRamp,Cs.RGBA8)),nr.bind(fr,Cs.CLAMP_TO_EDGE)}return hn&&On.push("USE_MRT1"),{mix:pn,range:cn,offset:vn,defines:On,resampling:fr}}(ct,C,qe,et,D.terrain&&D.terrain.renderingToTexture&&D.emissiveMode==="mrt-fallback");if(ct instanceof o.aV&&!O.length&&!se)return;const bt=C.paint.get("raster-emissive-strength"),vt=D.colorModeForDrapableLayerRenderPass(bt),Pt=D.terrain&&D.terrain.renderingToTexture,Ft=!D.options.moving,jt=C.paint.get("raster-resampling")==="nearest"?et.NEAREST:et.LINEAR;if(ct instanceof o.aV&&!O.length&&(ct.onNorthPole||ct.onSouthPole)){const Zt=pe?D.stencilModeFor3D():Na.disabled;return void v1(!!ct.onNorthPole,null,D,w,C,bt,ot,ra.disabled,Zt)}if(!O.length)return;const[ys,Qt]=ct instanceof o.aV||Pt?[{},O]:D.stencilConfigForOverlap(O),gs=Qt[Qt.length-1].overscaledZ;je&&ot.defines.push("PROJECTION_GLOBE_VIEW"),pe&&ot.defines.push("RENDER_CUTOFF","ELEVATED"),Ee&&ot.defines.push("ELEVATION_REFERENCE_GROUND");const $t=(Zt,hs,Us)=>{for(const Cs of Zt){const hn=Cs.toUnwrapped(),an=w.getTile(Cs);if(Pt&&(!an||!an.hasData()))continue;qe.activeTexture.set(et.TEXTURE0);const An=pw(an,ct,C,ot);if(!An||!An.texture)continue;const{texture:On,mix:Ks,offset:Es,tileSize:cn,buffer:pn}=An;let vn,fr;Pt?(vn=Ir.disabled,fr=Cs.projMatrix):pe?(vn=new Ir(et.LEQUAL,Ir.ReadWrite,D.depthRangeFor3D),fr=se?Float32Array.from(D.transform.expandedFarZProjMatrix):D.transform.calculateProjMatrix(hn,Ft)):(vn=D.depthModeForSublayer(Cs.overscaledZ-gs,Z===1?Ir.ReadWrite:Ir.ReadOnly,et.LESS),fr=D.transform.calculateProjMatrix(hn,Ft));const nr=D.terrain&&Pt?D.terrain.stencilModeForRTTOverlap(Cs):ys[Cs.overscaledZ],rr=Y?0:C.paint.get("raster-fade-duration");an.registerFadeDuration(rr);const In=w.findLoadedParent(Cs,0),Yr=yt(an,In,w,D.transform,rr);let fa,Fr;!Yr.isFading&&an.refreshedUponExpiration&&(an.refreshedUponExpiration=!1),D.terrain&&D.terrain.prepareDrawTile(),qe.activeTexture.set(et.TEXTURE0),On.bind(jt,et.CLAMP_TO_EDGE),qe.activeTexture.set(et.TEXTURE1),In?(In.texture&&In.texture.bind(jt,et.CLAMP_TO_EDGE),fa=Math.pow(2,In.tileID.overscaledZ-an.tileID.overscaledZ),Fr=[an.tileID.canonical.x*fa%1,an.tileID.canonical.y*fa%1]):On.bind(jt,et.CLAMP_TO_EDGE),"useMipmap"in On&&qe.extTextureFilterAnisotropic&&D.transform.pitch>20&&et.texParameterf(et.TEXTURE_2D,qe.extTextureFilterAnisotropic.TEXTURE_MAX_ANISOTROPY_EXT,qe.extTextureFilterAnisotropicMax);const Vr=D.transform;let $a;const ri=pe?b1(Vr):[0,0,0,0];let ei,Li,Ea,Pi,ti,So=0;if(je&&ct instanceof o.aV&&ct.coordinates.length>3)ei=Float32Array.from(o.du(o.dv(new o.cn(0,0,0)))),Li=Float32Array.from(Vr.globeMatrix),Ea=Float32Array.from(o.dq(Vr)),Pi=[o.aH(Vr.center.lng),o.aL(Vr.center.lat)],$a=ct.elevatedGlobePerspectiveTransform,ti=ct.elevatedGlobeGridMatrix||new Float32Array(9);else if(je){const Bo=o.dr(Cs.canonical);So=o.ds(Bo.getCenter().lat),ei=Float32Array.from(o.du(o.dv(Cs.canonical))),Li=Float32Array.from(Vr.globeMatrix),Ea=Float32Array.from(o.dq(Vr)),Pi=[o.aH(Vr.center.lng),o.aL(Vr.center.lat)],$a=[0,0],ti=Float32Array.from(o.dt(Cs.canonical,Bo,So,Vr.worldSize/Vr._pixelsPerMercatorPixel))}else $a=ct instanceof o.aV?ct.perspectiveTransform:[0,0],ei=new Float32Array(16),Li=new Float32Array(9),Ea=new Float32Array(16),Pi=[0,0],ti=new Float32Array(9);const yl=zd(D,fr,ei,Li,Ea,ti,Fr||[0,0],o.al(D.transform.zoom),Pi,ri,fa||1,Yr,C,$a,pe?C.paint.get("raster-elevation"):0,2,Ks,Es,ot.range,cn,pn,bt),Gc=D.isTileAffectedByFog(Cs),ql=D.getOrCreateProgram("raster",{defines:ot.defines,overrideFog:Gc});if(D.uploadCommonUniforms(qe,ql,hn),ct instanceof o.aV){const Bo=ct.elevatedGlobeVertexBuffer,ji=ct.elevatedGlobeIndexBuffer;if(Pt||!se)ct.boundsBuffer&&ct.boundsSegments&&ql.draw(D,et.TRIANGLES,vn,Na.disabled,vt,ra.disabled,yl,C.id,ct.boundsBuffer,D.quadTriangleIndexBuffer,ct.boundsSegments);else if(Bo&&ji){const Ni=Vr.zoom<=o.cJ?ct.elevatedGlobeSegments:ct.getSegmentsForLongitude(Vr.center.lng);Ni&&ql.draw(D,et.TRIANGLES,vn,Na.disabled,vt,hs,yl,C.id,Bo,ji,Ni)}}else if(je){vn=new Ir(et.LEQUAL,Ir.ReadOnly,D.depthRangeFor3D);const Bo=D.globeSharedBuffers;if(Bo){Ee&&(D.terrain.setupElevationDraw(an,ql),D.uploadCommonUniforms(qe,ql,an.tileID.toUnwrapped()));const[ji,Ni,Vl]=Bo.getGridBuffers(So,!1),nd=ql.getAttributeLocation(et,"a_texture_pos");nd!==-1&&et.vertexAttribI4ui(nd,0,0,0,0),ql.draw(D,et.TRIANGLES,vn,Us||nr,D.colorModeForRenderPass(),hs,yl,C.id,ji,Ni,Vl)}}else if(He)vn=new Ir(et.LEQUAL,Ir.ReadWrite,D.depthRangeFor3D),D.terrain.setupElevationDraw(an,ql),D.uploadCommonUniforms(qe,ql,an.tileID.toUnwrapped()),Vr.pitch>20&&ql.draw(D,et.TRIANGLES,vn,Na.disabled,wa.disabled,ra.frontCCW,yl,C.id,D.terrain.gridBuffer,D.terrain.gridIndexBuffer,D.terrain.gridSegments),ql.draw(D,et.TRIANGLES,vn,nr,vt,ra.backCCW,yl,C.id,D.terrain.gridBuffer,D.terrain.gridIndexBuffer,D.terrain.gridSegments);else{const{tileBoundsBuffer:Bo,tileBoundsIndexBuffer:ji,tileBoundsSegments:Ni}=D.getTileBoundsBuffers(an);ql.draw(D,et.TRIANGLES,vn,nr,vt,ra.disabled,yl,C.id,Bo,ji,Ni)}}if(!(ct instanceof o.aV)&&je)for(const Cs of Zt){const hn=Cs.canonical.y===(1<o.d$[pn](hn));Ks.push(hn);const Es=hn.canonical.x,cn=hn.canonical.y;for(const pn of Ks){const vn=jt.getTile(hs?pn.wrapped():pn);if(!vn)continue;const fr=vn.rasterParticleState;if(!fr)continue;const nr=pn.canonical.x+(1<gs.tileID)),et&&(je.activeTexture.set(Ee.TEXTURE0),D.imageManager.bind(D.context,C.scope));const Qt=[];if(D.terrain&&D.terrain.renderingToTexture&&D.emissiveMode==="mrt-fallback"&&Qt.push("USE_MRT1"),pe){const gs=D.getOrCreateProgram(Ft,{overrideFog:!1,overrideRtt:!0,defines:Qt}),$t=new Float32Array(o.b9([])),Zt=new o.aR(0,0,0,0,0),hs=et?Pc($t,se,Z,D,0,C.scope,ct,pe,{tileID:Zt,tileSize:qe}):gm($t,se,Z,U.toPremultipliedRenderColor(Y?null:C.lut));return void gs.draw(D,Ee.TRIANGLES,vt,bt,Pt,ra.disabled,hs,C.id,D.viewportBuffer,D.quadTriangleIndexBuffer,D.viewportSegments)}for(const gs of ys){const $t=D.isTileAffectedByFog(gs),Zt=D.getOrCreateProgram(Ft,{overrideFog:$t,defines:Qt}),hs=gs.toUnwrapped(),Us=O?gs.projMatrix:D.transform.calculateProjMatrix(hs);D.prepareDrawTile();const Cs=w?w.getTile(gs):jt?jt[gs.key]:new o.b0(gs,qe,He.zoom,D),hn=et?Pc(Us,se,Z,D,0,C.scope,ct,pe,{tileID:gs,tileSize:qe}):gm(Us,se,Z,U.toPremultipliedRenderColor(Y?null:C.lut));D.uploadCommonUniforms(je,Zt,hs);const{tileBoundsBuffer:an,tileBoundsIndexBuffer:An,tileBoundsSegments:On}=D.getTileBoundsBuffers(Cs);Zt.draw(D,Ee.TRIANGLES,vt,bt,Pt,ra.disabled,hn,C.id,an,An,On)}},sky:function(D,w,C){const O=D._atmosphere?o.al(D.transform.zoom):1,U=C.paint.get("sky-opacity")*O;if(U===0)return;const Y=D.context,Z=C.paint.get("sky-type"),se=new Ir(Y.gl.LEQUAL,Ir.ReadOnly,[0,1]),pe=D.frameCounter/1e3%1;Z==="atmosphere"?D.renderPass==="offscreen"?C.needsSkyboxCapture(D)&&(function(je,Ee){const He=je.context,qe=He.gl;let et=Ee.skyboxFbo;if(!et){et=Ee.skyboxFbo=He.createFramebuffer(32,32,1,null),Ee.skyboxGeometry=new jd(He),Ee.skyboxTexture=He.gl.createTexture(),qe.bindTexture(qe.TEXTURE_CUBE_MAP,Ee.skyboxTexture),qe.texParameteri(qe.TEXTURE_CUBE_MAP,qe.TEXTURE_WRAP_S,qe.CLAMP_TO_EDGE),qe.texParameteri(qe.TEXTURE_CUBE_MAP,qe.TEXTURE_WRAP_T,qe.CLAMP_TO_EDGE),qe.texParameteri(qe.TEXTURE_CUBE_MAP,qe.TEXTURE_MIN_FILTER,qe.LINEAR),qe.texParameteri(qe.TEXTURE_CUBE_MAP,qe.TEXTURE_MAG_FILTER,qe.LINEAR);for(let vt=0;vt<6;++vt)qe.texImage2D(qe.TEXTURE_CUBE_MAP_POSITIVE_X+vt,0,qe.RGBA,32,32,0,qe.RGBA,qe.UNSIGNED_BYTE,null)}He.bindFramebuffer.set(et.framebuffer),He.viewport.set([0,0,32,32]);const ct=Ee.getCenter(je,!0),ot=je.getOrCreateProgram("skyboxCapture"),bt=new Float64Array(16);o.b9(bt),o.ef(bt,bt,.5*-Math.PI),Kp(je,Ee,ot,bt,ct,0),o.b9(bt),o.ef(bt,bt,.5*Math.PI),Kp(je,Ee,ot,bt,ct,1),o.b9(bt),o.cE(bt,bt,.5*-Math.PI),Kp(je,Ee,ot,bt,ct,2),o.b9(bt),o.cE(bt,bt,.5*Math.PI),Kp(je,Ee,ot,bt,ct,3),o.b9(bt),Kp(je,Ee,ot,bt,ct,4),o.b9(bt),o.ef(bt,bt,Math.PI),Kp(je,Ee,ot,bt,ct,5),He.viewport.set([0,0,je.width,je.height])}(D,C),C.markSkyboxValid(D)):D.renderPass==="sky"&&function(je,Ee,He,qe,et){const ct=je.context,ot=ct.gl,bt=je.transform,vt=je.getOrCreateProgram("skybox");ct.activeTexture.set(ot.TEXTURE0),ot.bindTexture(ot.TEXTURE_CUBE_MAP,Ee.skyboxTexture);const Pt=((Ft,jt,ys,Qt,gs)=>({u_matrix:Ft,u_sun_direction:jt,u_cubemap:0,u_opacity:Qt,u_temporal_offset:gs}))(bt.skyboxMatrix,Ee.getCenter(je,!1),0,qe,et);je.uploadCommonUniforms(ct,vt),vt.draw(je,ot.TRIANGLES,He,Na.disabled,je.colorModeForRenderPass(),ra.backCW,Pt,"skybox",Ee.skyboxGeometry.vertexBuffer,Ee.skyboxGeometry.indexBuffer,Ee.skyboxGeometry.segment)}(D,C,se,U,pe):Z==="gradient"&&D.renderPass==="sky"&&function(je,Ee,He,qe,et){const ct=je.context,ot=ct.gl,bt=je.transform,vt=je.getOrCreateProgram("skyboxGradient");Ee.skyboxGeometry||(Ee.skyboxGeometry=new jd(ct)),ct.activeTexture.set(ot.TEXTURE0);let Pt=Ee.colorRampTexture;Pt||(Pt=Ee.colorRampTexture=new o.T(ct,Ee.colorRamp,ot.RGBA8)),Pt.bind(ot.LINEAR,ot.CLAMP_TO_EDGE);const Ft=((jt,ys,Qt,gs,$t)=>({u_matrix:jt,u_color_ramp:0,u_center_direction:ys,u_radius:o.ap(Qt),u_opacity:gs,u_temporal_offset:$t}))(bt.skyboxMatrix,Ee.getCenter(je,!1),Ee.paint.get("sky-gradient-radius"),qe,et);je.uploadCommonUniforms(ct,vt),vt.draw(je,ot.TRIANGLES,He,Na.disabled,je.colorModeForRenderPass(),ra.backCW,Ft,"skyboxGradient",Ee.skyboxGeometry.vertexBuffer,Ee.skyboxGeometry.indexBuffer,Ee.skyboxGeometry.segment)}(D,C,se,U,pe)},custom:function(D,w,C,O){const U=D.context,Y=C.implementation;if(!D.transform.projection.unsupportedLayers||!D.transform.projection.unsupportedLayers.includes("custom")||D.terrain&&(D.terrain.renderingToTexture||D.renderPass==="offscreen")&&C.isDraped(w)){if(D.renderPass==="offscreen"){const Z=Y.prerender;if(Z){if(D.setCustomLayerDefaults(),U.setColorMode(D.colorModeForRenderPass()),D.transform.projection.name==="globe"){const se=D.transform.pointMerc;Z.call(Y,U.gl,D.transform.customLayerMatrix(),D.transform.getProjection(),D.transform.globeToMercatorMatrix(),o.al(D.transform.zoom),[se.x,se.y],D.transform.pixelsPerMeterRatio)}else Z.call(Y,U.gl,D.transform.customLayerMatrix());U.setDirty(),D.setBaseState()}}else if(D.renderPass==="translucent"){if(D.terrain&&D.terrain.renderingToTexture){const se=Y.renderToTile;if(se){const pe=O[0].canonical,je={x:pe.x+O[0].wrap*(Y.wrapTileId?0:1<{je&&(je.useNormalOffset=!0,Ee||(je.enabled=!0))},qe=w.getSource();if(D.renderPass==="light-beam"&&qe.type!=="batched-model")return;if(qe.type==="vector"||qe.type==="geojson")return function(jt,ys,Qt,gs,$t){const Zt=jt.transform,hs=Zt.projection.name==="globe",Us=Zt.getFreeCameraOptions().position;if(!jt.modelManager)return;const Cs=jt.modelManager;Qt.modelManager=Cs;const hn=jt.shadowRenderer;if(!Qt._unevaluatedLayout._values.hasOwnProperty("model-id"))return;const an=Qt._unevaluatedLayout._values["model-id"],An=Object.assign({},Qt.layout.get("model-id").parameters),On=jt.style.order.indexOf(Qt.fqid),Ks=Qt.paint.get("model-opacity").constantOr(1);for(const Es of gs){const cn=ys.getTile(Es).getBucket(Qt);if(!cn||cn.projection.name!==Zt.projection.name)continue;const pn=cn.getModelUris();if(pn&&!cn.modelsRequested&&(Cs.addModelsFromBucket(pn,$t),cn.modelsRequested=!0),hs)An.zoom=Es.overscaledZ;else{const Fr=g0(Es,Zt);An.zoom=Fr}const vn=an.possiblyEvaluate(An);if(er(jt,cn,Es),Qn.shadowUniformsInitialized=!1,Qn.useSingleShadowCascade=!!hn&&hn.getMaxCascadeForTile(Es.toUnwrapped())===0,jt.renderPass==="shadow"&&hn){if(jt.currentShadowCascade===1&&cn.isInsideFirstShadowMapFrustum)continue;const Fr=Zt.calculatePosMatrix(Es.toUnwrapped(),Zt.worldSize);if(Qn.tileMatrix.set(Fr),Qn.shadowTileMatrix=Float32Array.from(hn.calculateShadowPassMatrixFromMatrix(Fr)),Qn.aabb.min=[0,0,0],Qn.aabb.max[0]=Qn.aabb.max[1]=o.an,Qn.aabb.max[2]=0,fS(cn,Qn,jt,Qt.scope))continue}const fr=1<0&&jt.style.isLayerClipped(Qt,ys.getSource())&&cn.updateReplacement(Es,jt.replacementSource,On,Qt.scope)&&(cn.uploaded=!1,cn.upload(jt.context));let rr=0;const In=new Array,Yr=new Array,fa=new Array;for(let Fr in cn.instancesPerModel){const Vr=cn.instancesPerModel[Fr];Vr.features.length>0&&!hs&&(Fr=vn.evaluate(Vr.features[0].feature,{}));const $a=Cs.getModel(Fr,$t);if($a||Cs.hasURLBeenRequested(Fr)||cn.modelUris.includes(Fr)||(cn.modelUris.push(Fr),cn.modelsRequested=!1),$a&&$a.uploaded)if(hs){const ri=o.bJ([],[Us.x,Us.y,Us.z],jt.transform.worldSize);o.eo(ri,ri);for(let ei=0;ei0&&Pi.elevationUpdate(Fr.terrain,ei,Ea,$a.source),Pi.needsReEvaluation(Fr,Li,$a)&&Pi.evaluate($a))}})(jt,ys,Qt,gs),function(){const Fr=new Map;let Vr,$a,ri;In?(Vr=gs.length-1,$a=-1,ri=-1):(Vr=0,$a=gs.length,ri=1);const ei=new Float64Array(16),Li=o.ce(),Ea=new o.P(0,0);for(let Pi=Vr;Pi!==$a;Pi+=ri){const ti=gs[Pi],So=ys.getTile(ti).getBucket(Qt);if(!So||!So.uploaded)continue;let yl=!1;Us&&(yl=Us.getMaxCascadeForTile(ti.toUnwrapped())===0);const Gc=Zt.calculatePosMatrix(ti.toUnwrapped(),Zt.worldSize),ql=So.modelTraits;!fr&&In&&(o.b7(ei,Gc),o.ah(Li,hn,ei),Ea.x=Li[0],Ea.y=Li[1]);const Bo=[];So.setFilter(Qt.filter);for(const ji of So.getNodesInfo()){if(ji.hiddenByReplacement||!ji.node.meshes)continue;const Ni=ji.node;let Vl=0;jt.terrain&&Ni.elevation&&(Vl=Ni.elevation*jt.terrain.exaggeration());const nd=(()=>{const ip=ji.aabb;return vn.min=[...ip.min],vn.max=[...ip.max],vn.min[2]+=Vl,vn.max[2]+=Vl,o.ah(vn.min,vn.min,Gc),o.ah(vn.max,vn.max,Gc),vn})(),$o=ji.evaluatedScale;if($o[0]<=1&&$o[1]<=1&&$o[2]<=1&&nd.intersects(nr)===0)continue;if(!fr&&In){const ip=.16666666666666666;ji.cameraCollisionOpacity=hn[0]>nd.min[0]&&hn[0]nd.min[1]&&hn[1]!In||ji.opacity===1&&Ni.opacity===1?ji.depthNi.depth?-1:1);for(const ji of Bo){const Ni=ji.nodeInfo,Vl=Ni.node;if(jt._debugParams.show3DModelFootprints&&Vl.footprint){const Xi=Vl.id||Vl.name||"footprint";Fr.has(Xi)||Fr.set(Xi,{node:Vl,mvp:ji.wvpForTile})}let nd=o.aD([],Ks,ji.tileModelMatrix);o.aD(nd,An,nd);const $o=o.b7([],nd);o.e6($o,$o),o.cC($o,$o,Is),nd=o.aD(nd,nd,Vl.globalMatrix);const ui=jt.renderPass==="light-beam",Ic=Qt.paint.get("model-color-use-theme").constantOr("default")==="none",vl=ql&o.ez.HasMapboxMeshFeatures,Ru=vl?0:Ni.evaluatedRMEA[0][2];for(let Xi=0;Xi=Gn||py>=Gn}}const sl=Rl.material;let dv;sl.occlusionTexture&&sl.occlusionTexture.offsetScale&&(dv=sl.occlusionTexture.offsetScale,kh.defines.push("OCCLUSION_TEXTURE_TRANSFORM"));const uv=jt.getOrCreateProgram("model",kh);!fr&&Us&&Us.setupShadowsFromMatrix(ji.tileModelMatrix,uv,Us.useNormalOffset),jt.uploadCommonUniforms($t,uv,null,my);const Ql=sl.pbrMetallicRoughness;Ql.metallicFactor=.9,Ql.roughnessFactor=.5;const uc=Dl(new Float32Array(Ef),new Float32Array(nd),new Float32Array($o),new Float32Array(Vl.globalMatrix),jt,ji.opacity,Ql.baseColorFactor,sl.emissiveFactor,Ql.metallicFactor,Ql.roughnessFactor,sl,Ru,Qt,[0,0,0],dv);!uh&&(Ni.hasTranslucentParts||ji.opacity<1)&&uv.draw(jt,$t.gl.TRIANGLES,cn,Na.disabled,wa.disabled,ra.backCCW,uc,Qt.id,Rl.vertexBuffer,Rl.indexBuffer,Rl.segments,Qt.paint,jt.transform.zoom,void 0,ip),uv.draw(jt,$t.gl.TRIANGLES,uh?pn:cn,Na.disabled,uh||ji.opacity<1||Ni.hasTranslucentParts?wa.alphaBlended:wa.unblended,ra.backCCW,uc,Qt.id,Rl.vertexBuffer,Rl.indexBuffer,Rl.segments,Qt.paint,jt.transform.zoom,void 0,ip)}}}if(jt._debugParams.show3DModelFootprints&&Fr.size>0){const Pi=Array.from(Fr.keys()).sort();for(const ti of Pi){const{node:So,mvp:yl}=Fr.get(ti);Z3(jt,0,So,yl)}}}()}(D,w,C,O),void He();if(qe.type!=="model")return;const et=qe.getModels(),ct=[],ot=D.transform.getFreeCameraOptions().position,bt=o.bJ([],[ot.x,ot.y,ot.z],D.transform.worldSize);o.eo(bt,bt);const vt=[],Pt=[];let Ft=0;for(const jt of et){const ys=w.getFeatureState("",jt.id),Qt={type:"Unknown",id:jt.id,properties:jt.featureProperties},gs=C.paint.get("model-rotation").evaluate(Qt,ys),$t=C.paint.get("model-scale").evaluate(Qt,ys),Zt=C.paint.get("model-translation").evaluate(Qt,ys),hs=C.paint.get("model-opacity").evaluate(Qt,ys);X3(C,jt.id,ys,jt.featureProperties,jt.nodeOverrideNames,jt.nodeOverrides),Vj(C,jt.id,ys,jt.featureProperties,jt.materialOverrideNames,jt.materialOverrides),jt.nodeOverrides.size>0&&jt.computeBoundsAndApplyParent(),jt.computeModelMatrix(D,gs,$t,Zt,se,Z,!1);const Us=o.b9([]),Cs=o.e2(jt.position.lat,D.transform.zoom),hn=o.bP([],[1,1,1/Cs]);o.bx(Us,Us,bt),ct.push({zScaleMatrix:hn,negCameraPosMatrix:Us});for(const an of jt.nodes)Y3(D,an,jt.matrix,D.transform.expandedFarZProjMatrix,Ft,vt,Pt,jt.materialOverrides,hs);Ft++}if(vt.sort((jt,ys)=>ys.depth-jt.depth),D.renderPass!=="shadow"){if(D._debugParams.show3DModelFootprints){const jt=D.transform.projMatrix,ys=new Map,Qt=($t,Zt)=>{if($t.footprint){const hs=$t.id||$t.name||"footprint";if(!ys.has(hs)){const Us=o.aD([],jt,Zt);ys.set(hs,{node:$t,mvp:Us})}}};for(const $t of Pt)Qt($t.node,$t.modelMatrix);for(const $t of vt)Qt($t.node,$t.modelMatrix);const gs=Array.from(ys.keys()).sort();for(const $t of gs){const{node:Zt,mvp:hs}=ys.get($t);Z3(D,0,Zt,hs)}}bm(D,C,vt,Pt,ct),He()}else{for(const jt of Pt)$N(jt.mesh,jt.nodeModelMatrix,D,C);for(const jt of vt)$N(jt.mesh,jt.nodeModelMatrix,D,C);He()}}},kr={line:function(D,w,C){if(D.hasElevatedBuckets=!1,D.hasNonElevatedBuckets=!1,D._unevaluatedLayout.getValue("line-elevation-reference")!==void 0||D._unevaluatedLayout.getValue("line-z-offset")!==void 0){if(w){const O=w.getVisibleCoordinates();for(const U of O){const Y=w.getTile(U).getBucket(D);if(Y&&(Y.elevationType!=="none"?D.hasElevatedBuckets=!0:D.hasNonElevatedBuckets=!0,D.hasElevatedBuckets&&D.hasNonElevatedBuckets))break}}}else D.hasNonElevatedBuckets=!0},model:function(D,w,C){const O=w.getSource();if(!O.loaded())return;if(O.type==="vector"||O.type==="geojson")return void(C.modelManager&&C.modelManager.upload(C,pS(C,D)));if(O.type==="batched-model"||O.type!=="model")return;const U=O.getModels();for(const Y of U)Y.upload(C.context)},raster:function(D,w,C){const O=w.getSource();if(!(O instanceof Hm&&O.loaded()))return;const U=D.sourceLayer||O.rasterLayerIds&&O.rasterLayerIds[0];if(!U)return;const Y=D.paint.get("raster-array-band")||O.getInitialBand(U);if(Y==null)return;const Z=w.getIds().map(se=>w.getTileByID(se));for(const se of Z)se.updateNeeded(D.id,Y)&&O.prepareTile(se,U,D.id,Y)},"raster-particle":function(D,w,C){const O=w.getSource();if(!(O instanceof Hm&&O.loaded()))return;const U=D.sourceLayer||O.rasterLayerIds&&O.rasterLayerIds[0];if(!U)return;const Y=D.paint.get("raster-particle-array-band")||O.getInitialBand(U);if(Y==null)return;const Z=w.getIds().map(se=>w.getTileByID(se));for(const se of Z)se.updateNeeded(D.id,Y)&&O.prepareTile(se,U,D.id,Y)}},Sa={fill:y1},Ai={fill:function(D,w,C,O){if(!C.layout||C.layout.get("fill-elevation-reference")==="none"||C.paint.get("fill-opacity").constantOr(1)===0)return;const U=D.context.gl,Y=new Ir(U.LEQUAL,Ir.ReadOnly,D.depthRangeFor3D),Z=new Na({func:U.ALWAYS,mask:255},255,255,U.KEEP,U.KEEP,U.REPLACE),se=D.transform.getFreeCameraOptions().position,pe=D.getOrCreateProgram("elevatedStructuresDepthReconstruct");for(const je of O){const Ee=w.getTile(je),He=Ee.getBucket(C);if(!He)continue;const qe=He.elevatedStructures;if(!qe||qe.depthSegments.segments[0].primitiveLength===0)continue;const et=rv(je.toUnwrapped(),se),ct=D.translatePosMatrix(je.projMatrix,Ee,C.paint.get("fill-translate"),C.paint.get("fill-translate-anchor")),ot=wi(ct,et,0,1,0);pe.draw(D,U.TRIANGLES,Y,Z,wa.disabled,ra.disabled,ot,C.id,qe.vertexBuffer,qe.indexBuffer,qe.depthSegments,C.paint,D.transform.zoom)}}};class ol{constructor(w,C,O,U,Y){this.context=new dh(w,C),this.transform=O,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 Z=["fill","line","symbol","circle","heatmap","fill-extrusion","building","raster","raster-particle","hillshade","model","background","sky"];for(const pe of Z)this._debugParams.enabledLayers[pe]=!0;for(const pe of Z);this.occlusionParams=new c6,this.setup(),this.numSublayers=Bl.maxUnderzooming+Bl.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 yc(this),this._wireframeDebugCache=new l6,this.renderDefaultNorthPole=!0,this.renderDefaultSouthPole=!0,this.layersWithOcclusionOpacity=[];const se=new o.q({width:1,height:1},Uint8Array.of(0,0,0,0));this.emptyDepthTexture=new o.T(this.context,se,w.RGBA8),this._clippingActiveLastFrame=!1,this.scaleFactor=U,this.maxFrontCutoffRawStart=0,this.worldview=Y,this._forceEmissiveMode=!1,this.emissiveMode="constant"}updateTerrain(w,C){const O=!!w&&!!w.terrain&&this.transform.projection.supportsTerrain;if(!(O||this._terrain&&this._terrain.enabled))return;this._terrain||(this._terrain=new vs(this,w));const U=this._terrain;this.transform.elevation=O?U:null,U.update(w,this.transform,C),this.transform.elevation&&!U.enabled&&(this.transform.elevation=null)}_updateFog(w){const C=w.fog;if(!C||this.transform.projection.name==="globe"||C.getOpacity(this.transform.pitch)<1||C.properties.get("horizon-blend")<.03)return void(this.transform.fogCullDistSq=null);const[O,U]=C.getFovAdjustedRange(this.transform._fov);if(O>U)return void(this.transform.fogCullDistSq=null);const Y=O+.78*(U-O);this.transform.fogCullDistSq=Y*Y}get terrain(){return this.transform._terrainEnabled()&&this._terrain&&this._terrain.enabled||this._forceTerrainMode?this._terrain:null}get forceTerrainMode(){return this._forceTerrainMode}set forceTerrainMode(w){w&&!this._terrain&&(this._terrain=new vs(this,this.style)),this._forceTerrainMode=w}get shadowRenderer(){return this._shadowRenderer&&this._shadowRenderer.enabled?this._shadowRenderer:null}get wireframeDebugCache(){return this._wireframeDebugCache}resize(w,C){if(this.width=w*o.o.devicePixelRatio,this.height=C*o.o.devicePixelRatio,this.context.viewport.set([0,0,this.width,this.height]),this.style)for(const O of this.style.order)this.style._mergedLayers[O].resize()}setup(){const w=this.context,C=new o.dB;C.emplaceBack(0,0),C.emplaceBack(o.an,0),C.emplaceBack(0,o.an),C.emplaceBack(o.an,o.an),this.tileExtentBuffer=w.createVertexBuffer(C,o.dx.members),this.tileExtentSegments=o.dy.simpleSegment(0,0,4,2);const O=new o.dB;O.emplaceBack(0,0),O.emplaceBack(o.an,0),O.emplaceBack(0,o.an),O.emplaceBack(o.an,o.an),this.debugBuffer=w.createVertexBuffer(O,o.dx.members),this.debugSegments=o.dy.simpleSegment(0,0,4,5);const U=new o.dB;U.emplaceBack(-1,-1),U.emplaceBack(1,-1),U.emplaceBack(-1,1),U.emplaceBack(1,1),this.viewportBuffer=w.createVertexBuffer(U,o.dx.members),this.viewportSegments=o.dy.simpleSegment(0,0,4,2);const Y=new o.eH;Y.emplaceBack(0,0,0,0),Y.emplaceBack(o.an,0,o.an,0),Y.emplaceBack(0,o.an,0,o.an),Y.emplaceBack(o.an,o.an,o.an,o.an),this.mercatorBoundsBuffer=w.createVertexBuffer(Y,o.eI.members),this.mercatorBoundsSegments=o.dy.simpleSegment(0,0,4,2);const Z=new o.dC;Z.emplaceBack(0,1,2),Z.emplaceBack(2,1,3),this.quadTriangleIndexBuffer=w.createIndexBuffer(Z);const se=new o.eJ;for(const je of[0,1,3,2,0])se.emplaceBack(je);this.debugIndexBuffer=w.createIndexBuffer(se),this.emptyTexture=new o.T(w,new o.q({width:1,height:1},Uint8Array.of(0,0,0,0)),w.gl.RGBA8),this.identityMat=o.bb();const pe=this.context.gl;this.stencilClearMode=new Na({func:pe.ALWAYS,mask:0},0,255,pe.ZERO,pe.ZERO,pe.ZERO),this.loadTimeStamps.push(performance.now())}getMercatorTileBoundsBuffers(){return{tileBoundsBuffer:this.mercatorBoundsBuffer,tileBoundsIndexBuffer:this.quadTriangleIndexBuffer,tileBoundsSegments:this.mercatorBoundsSegments}}getTileBoundsBuffers(w){return w._makeTileBoundsBuffers(this.context,this.transform.projection),w._tileBoundsBuffer?{tileBoundsBuffer:w._tileBoundsBuffer,tileBoundsIndexBuffer:w._tileBoundsIndexBuffer,tileBoundsSegments:w._tileBoundsSegments}:this.getMercatorTileBoundsBuffers()}clearStencil(){const w=this.context.gl;this.nextStencilID=1,this.currentStencilSource=void 0,this._tileClippingMaskIDs={},this.getOrCreateProgram("clippingMask").draw(this,w.TRIANGLES,Ir.disabled,this.stencilClearMode,wa.disabled,ra.disabled,ut(this.identityMat),"$clipping",this.viewportBuffer,this.quadTriangleIndexBuffer,this.viewportSegments)}resetStencilClippingMasks(){this.terrain||(this.currentStencilSource=void 0,this._tileClippingMaskIDs={})}_renderTileClippingMasks(w,C,O){if(!C||this.currentStencilSource===C.id||!w.isTileClipped()||!O||O.length===0)return;if(this._tileClippingMaskIDs&&!this.terrain){let se=!1;for(const pe of O)if(this._tileClippingMaskIDs[pe.key]===void 0){se=!0;break}if(!se)return}this.currentStencilSource=C.id;const U=this.context,Y=U.gl;this.nextStencilID+O.length>256&&this.clearStencil(),U.setColorMode(wa.disabled),U.setDepthMode(Ir.disabled);const Z=this.getOrCreateProgram("clippingMask");this._tileClippingMaskIDs={};for(const se of O){const pe=C.getTile(se),je=this._tileClippingMaskIDs[se.key]=this.nextStencilID++,{tileBoundsBuffer:Ee,tileBoundsIndexBuffer:He,tileBoundsSegments:qe}=this.getTileBoundsBuffers(pe);Z.draw(this,Y.TRIANGLES,Ir.disabled,new Na({func:Y.ALWAYS,mask:0},je,255,Y.KEEP,Y.KEEP,Y.REPLACE),wa.disabled,ra.disabled,ut(se.projMatrix),"$clipping",Ee,He,qe)}}stencilModeFor3D(){this.currentStencilSource=void 0,this.nextStencilID+1>256&&this.clearStencil();const w=this.nextStencilID++,C=this.context.gl;return new Na({func:C.NOTEQUAL,mask:255},w,255,C.KEEP,C.KEEP,C.REPLACE)}stencilModeForClipping(w){if(this.terrain)return this.terrain.stencilModeForRTTOverlap(w);const C=this.context.gl;return new Na({func:C.EQUAL,mask:255},this._tileClippingMaskIDs[w.key],0,C.KEEP,C.KEEP,C.REPLACE)}stencilConfigForOverlap(w){const C=this.context.gl,O=w.sort((Z,se)=>se.overscaledZ-Z.overscaledZ),U=O[O.length-1].overscaledZ,Y=O[0].overscaledZ-U+1;if(Y>1){this.currentStencilSource=void 0,this.nextStencilID+Y>256&&this.clearStencil();const Z={};for(let se=0;sethis._debugParams.fpsWindow&&this._fpsHistory.splice(0,this._fpsHistory.length-this._debugParams.fpsWindow),this._averageFPS=Math.round(this._fpsHistory.reduce((w,C)=>w+C/this._fpsHistory.length,0))}render(w,C){const O=o.o.now();this._dt=O-this._timeStamp,this._timeStamp=O,this._wireframeDebugCache.update(this.frameCounter),this._debugParams.continousRedraw=w.map.repaint,this.style=w,this.options=C;const U=this.style._mergedLayers,Y=!(!this.terrain||!this.terrain.enabled),Z=()=>this.style._getOrder(Y).filter(Ks=>{const Es=U[Ks];return!(Es.type in this._debugParams.enabledLayers)||this._debugParams.enabledLayers[Es.type]});let se=Z(),pe=!1,je=!1,Ee=null,He=0,qe=!1;for(const Ks of se){const Es=U[Ks];Es.visibility!=="none"&&(Es.type==="circle"?pe=!0:Es.type==="building"?(Ee=Es,++He):Es.type==="symbol"&&(Es.hasOcclusionOpacityProperties?je=!0:pe=!0))}this.updateEmissiveMode();let et=se.map(Ks=>U[Ks]);const ct=this.style._mergedSourceCaches;this.imageManager=w.imageManager,this.modelManager=w.modelManager,this.symbolFadeChange=w.placement.symbolFadeChange(o.o.now()),this.imageManager.beginFrame();for(const Ks in ct){const Es=ct[Ks];Es.used&&(Es.prepare(this.context),Es.getSource().usedInConflation&&++He)}let ot=!1;for(const Ks of et)Ks.isHidden(this.transform.zoom)||(Ks.type==="clip"&&(ot=!0),this.prepareLayer(Ks));const bt={},vt={},Pt={},Ft={},jt={};for(const Ks in ct){const Es=ct[Ks];bt[Ks]=Es.getVisibleCoordinates(),vt[Ks]=bt[Ks].slice().reverse(),Pt[Ks]=Es.getVisibleCoordinates(!0).reverse(),Ft[Ks]=Es.getShadowCasterCoordinates(),jt[Ks]=Es.sortCoordinatesByDistance(bt[Ks])}const ys=Ks=>{const Es=this.style.getLayerSourceCache(Ks);return Es&&Es.used?Es.getSource():null};if(He||ot||this._clippingActiveLastFrame){const Ks=[],Es=[];let cn=0;for(const pn of et)this.isSourceForClippingOrConflation(pn,ys(pn))&&(Ks.push(pn),Es.push(cn)),cn++;if(Ks&&(ot||Ks.length>1)||this._clippingActiveLastFrame){ot=!1;const pn=[];for(let vn=0;vn0){const pn=ys(Es);pn&&(this.minCutoffZoom=Math.max(pn.minzoom,this.minCutoffZoom)),Es.minzoom&&(this.minCutoffZoom=Math.max(Es.minzoom,this.minCutoffZoom))}Es.is3D(Y)&&(this.opaquePassCutoff===1/0&&(this.opaquePassCutoff=Ks),this._lastOcclusionLayer=Ks)}const Qt=this.style&&this.style.fog;Qt?(this._fogVisible=Qt.getOpacity(this.transform.pitch)!==0,this._fogVisible&&this.transform.projection.name!=="globe"&&(this._fogVisible=Qt.isVisibleOnFrustum(this.transform.cameraFrustum))):this._fogVisible=!1,this._cachedTileFogOpacities={},this.terrain&&(this.terrain.updateTileBinding(Pt),this.opaquePassCutoff=0,se=Z(),et=se.map(Ks=>U[Ks]));const gs=this._shadowRenderer;if(gs){gs.updateShadowParameters(this.transform,this.style.directionalLight);for(const Ks in ct)for(const Es of bt[Ks]){let cn={min:0,max:0};this.terrain&&(cn=this.terrain.getMinMaxForTile(Es)||cn),gs.addShadowReceiver(Es.toUnwrapped(),cn.min,cn.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 zN(this)),this._atmosphere.update(this)):this._atmosphere&&(this._atmosphere.destroy(),this._atmosphere=void 0);const $t=this._debugParams.forceEnablePrecipitation||!(!this.style||!this.style.snow),Zt=this._debugParams.forceEnablePrecipitation||!(!this.style||!this.style.rain);if($t&&!this._snow&&(this._snow=new Ps(this)),!$t&&this._snow&&(this._snow.destroy(),delete this._snow),Zt&&!this._rain&&(this._rain=new lt(this)),!Zt&&this._rain&&(this._rain.destroy(),delete this._rain),this._snow&&this._snow.update(this),this._rain&&this._rain.update(this),Ee){this.buildingTileBorderManager||(this.buildingTileBorderManager=new Ig);const Ks=this.style.getLayerSourceCache(Ee);this.buildingTileBorderManager.updateBorders(Ks,Ee)}if(!Xe.has(this.context.gl))return;this.renderPass="offscreen";for(const Ks of et){const Es=w.getLayerSourceCache(Ks);if(!Ks.hasOffscreenPass()||Ks.isHidden(this.transform.zoom))continue;const cn=Es?vt[Es.id]:void 0;(Ks.type==="custom"||Ks.type==="raster"||Ks.type==="raster-particle"||Ks.isSky()||cn&&cn.length)&&this.renderLayer(this,Es,Ks,cn)}this.depthRangeFor3D=[0,1-(et.length+2)*this.numSublayers*this.depthEpsilon],this._shadowRenderer&&(this.renderPass="shadow",this._shadowRenderer.drawShadowPass(this.style,Ft)),this.context.bindFramebuffer.set(null),this.context.viewport.set([0,0,this.width,this.height]);const hs=this.transform.projection.name==="globe"||this.transform.isHorizonVisible(),Us=(()=>{if(C.showOverdrawInspector)return o.aq.black;const Ks=this.style.fog;if(Ks&&this.transform.projection.supportsFog){const Es=this.style.getLut(Ks.scope);if(!hs){const cn=Ks.properties.get("color-use-theme")==="none",pn=Ks.properties.get("color").toNonPremultipliedRenderColor(cn?null:Es).toArray01();return new o.aq(...pn)}if(hs){const cn=Ks.properties.get("space-color-use-theme")==="none",pn=Ks.properties.get("space-color").toNonPremultipliedRenderColor(cn?null:Es).toArray01();return new o.aq(...pn)}}return o.aq.transparent})();if(this.context.clear({color:Us,depth:1}),this.clearStencil(),this._showOverdrawInspector=C.showOverdrawInspector,this.renderPass="opaque",this.style.fog&&this.transform.projection.supportsFog&&this._atmosphere&&!this._showOverdrawInspector&&hs&&this._atmosphere.drawStars(this,this.style.fog),!this.terrain)for(this.currentLayer=se.length-1;this.currentLayer>=0;this.currentLayer--){const Ks=et[this.currentLayer],Es=w.getLayerSourceCache(Ks);if(Ks.isSky())continue;const cn=Es?(Ks.is3D(Y)?jt:vt)[Es.id]:void 0;this._renderTileClippingMasks(Ks,Es,cn),this.renderLayer(this,Es,Ks,cn)}if(this.style.fog&&this.transform.projection.supportsFog&&this._atmosphere&&!this._showOverdrawInspector&&hs&&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 cn=this.currentLayer;this.depthOcclusion=!0;for(const pn of this.layersWithOcclusionOpacity){this.currentLayer=pn;const vn=et[this.currentLayer],fr=w.getLayerSourceCache(vn),nr=fr?vt[fr.id]:void 0;this.terrain||this._renderTileClippingMasks(vn,fr,fr?bt[fr.id]:void 0),this.renderLayer(this,fr,vn,nr)}this.depthOcclusion=!1,this.currentLayer=cn,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 Ks=null;et.forEach(Es=>{const cn=w.getLayerSourceCache(Es);cn&&!Es.isHidden(this.transform.zoom)&&cn.getVisibleCoordinates().length&&(!Ks||Ks.getSource().maxzoom0?C.pop():null}terrainRenderModeElevated(){return this.style&&!!this.style.getTerrain()&&!!this.terrain&&!this.terrain.renderingToTexture||this.forceTerrainMode}linearFloatFilteringSupported(){return this.context.extTextureFloatLinear!=null}currentGlobalDefines(w,C,O){const U=O===void 0?this.terrain&&this.terrain.renderingToTexture:O,Y=[];return this.style&&this.style.enable3dLights()&&(w==="globeRaster"||w==="terrainRaster"?(Y.push("LIGHTING_3D_MODE"),Y.push("LIGHTING_3D_ALPHA_EMISSIVENESS")):U||Y.push("LIGHTING_3D_MODE")),this.terrainRenderModeElevated()&&(Y.push("TERRAIN"),this.linearFloatFilteringSupported()&&Y.push("TERRAIN_DEM_FLOAT_FORMAT")),this.transform.projection.name==="globe"&&Y.push("GLOBE"),!this._fogVisible||U||C!==void 0&&!C||Y.push("FOG"),U&&Y.push("RENDER_TO_TEXTURE"),this._showOverdrawInspector&&Y.push("OVERDRAW_INSPECTOR"),Y}getOrCreateProgram(w,C){this.cache=this.cache||{};const O=C&&C.defines||[],U=C&&C.config,Y=this.currentGlobalDefines(w,C&&C.overrideFog,C&&C.overrideRtt).concat(O),Z=$n.cacheKey(tw[w],w,Y,U);return this.cache[Z]||(this.cache[Z]=new $n(this.context,w,tw[w],U,xm[w],Y)),this.cache[Z]}setCustomLayerDefaults(){this.context.unbindVAO(),this.context.cullFace.setDefault(),this.context.frontFace.setDefault(),this.context.cullFaceSide.setDefault(),this.context.activeTexture.setDefault(),this.context.pixelStoreUnpack.setDefault(),this.context.pixelStoreUnpackPremultiplyAlpha.setDefault(),this.context.pixelStoreUnpackFlipY.setDefault()}setBaseState(){const w=this.context.gl;this.context.cullFace.set(!1),this.context.viewport.set([0,0,this.width,this.height]),this.context.blendEquation.set(w.FUNC_ADD)}initDebugOverlayCanvas(){this.debugOverlayCanvas==null&&(this.debugOverlayCanvas=document.createElement("canvas"),this.debugOverlayCanvas.width=512,this.debugOverlayCanvas.height=512,this.debugOverlayTexture=new o.T(this.context,this.debugOverlayCanvas,this.context.gl.RGBA8))}destroy(){this._terrain&&this._terrain.destroy(),this._atmosphere&&(this._atmosphere.destroy(),this._atmosphere=void 0),this.globeSharedBuffers&&this.globeSharedBuffers.destroy(),this.emptyTexture.destroy(),this.debugOverlayTexture&&this.debugOverlayTexture.destroy(),this._wireframeDebugCache.destroy(),this.depthFBO&&(this.depthFBO.destroy(),this.depthFBO=void 0,this.depthTexture=void 0),this.emptyDepthTexture&&this.emptyDepthTexture.destroy()}prepareDrawTile(){this.terrain&&this.terrain.prepareDrawTile()}uploadCommonLightUniforms(w,C){if(this.style.enable3dLights()){const O=this.style.directionalLight,U=this.style.ambientLight;if(O&&U){const Y=((Z,se,pe)=>{const je=Z.properties.get("direction"),Ee=Z.properties.get("color-use-theme")==="none",He=Z.properties.get("color").toNonPremultipliedRenderColor(Ee?null:pe.getLut(Z.scope)).toArray01(),qe=Z.properties.get("intensity"),et=se.properties.get("color-use-theme")==="none",ct=se.properties.get("color").toNonPremultipliedRenderColor(et?null:pe.getLut(se.scope)).toArray01(),ot=se.properties.get("intensity"),bt=[je.x,je.y,je.z],vt=o.dD(ct,ot),Pt=o.dD(He,qe);return{u_lighting_ambient_color:vt,u_lighting_directional_dir:bt,u_lighting_directional_color:Pt,u_ground_radiance:Ts(bt,Pt,vt)}})(O,U,this.style);C.setLightsUniformValues(w,Y)}}}uploadCommonUniforms(w,C,O,U,Y){if(this.uploadCommonLightUniforms(w,C),this.terrain&&this.terrain.renderingToTexture)return;const Z=this.style.fog;if(Z){const se=Z.getOpacity(this.transform.pitch),pe=((je,Ee,He,qe,et,ct,ot,bt,vt,Pt,Ft,jt)=>{const ys=je.transform,Qt=Ee.properties.get("color-use-theme")==="none",gs=Ee.properties.get("color").toNonPremultipliedRenderColor(Qt?null:je.style.getLut(Ee.scope)).toArray01();gs[3]=qe;const $t=je.frameCounter/1e3%1,[Zt,hs]=Ee.properties.get("vertical-range");return{u_fog_matrix:He?ys.calculateFogTileMatrix(He):jt||je.identityMat,u_fog_range:Ee.getFovAdjustedRange(ys._fov),u_fog_color:gs,u_fog_horizon_blend:Ee.properties.get("horizon-blend"),u_fog_vertical_limit:[Math.min(Zt,hs),hs],u_fog_temporal_offset:$t,u_frustum_tl:et,u_frustum_tr:ct,u_frustum_br:ot,u_frustum_bl:bt,u_globe_pos:vt,u_globe_radius:Pt,u_viewport:Ft,u_globe_transition:o.al(ys.zoom),u_is_globe:+(ys.projection.name==="globe")}})(this,Z,O,se,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],U);C.setFogUniformValues(w,pe)}Y&&C.setCutoffUniformValues(w,Y.uniformValues)}setTileLoadedFlag(w){this.tileLoaded=w}saveCanvasCopy(){const w=this.canvasCopy();w&&(this.frameCopies.push(w),this.tileLoaded=!1)}canvasCopy(){const w=this.context.gl,C=w.createTexture();return w.bindTexture(w.TEXTURE_2D,C),w.copyTexImage2D(w.TEXTURE_2D,0,w.RGBA,0,0,w.drawingBufferWidth,w.drawingBufferHeight,0),C}getCanvasCopiesAndTimestamps(){return{canvasCopies:this.frameCopies,timeStamps:this.loadTimeStamps}}averageElevationNeedsEasing(){if(!this.transform._elevation)return!1;const w=this.style&&this.style.fog;return!!w&&w.getOpacity(this.transform.pitch)!==0}getBackgroundTiles(){const w=this._backgroundTiles,C=this._backgroundTiles={},O=this.transform.coveringTiles({tileSize:512});for(const U of O)C[U.key]=w[U.key]||new o.b0(U,512,this.transform.tileZoom,this,void 0,this.worldview);return C}clearBackgroundTiles(){this._backgroundTiles={}}isSourceForClippingOrConflation(w,C){return!(!w.is3D(!(!this.terrain||!this.terrain.enabled))||w.type!=="clip"&&w.type!=="building"&&(w.minzoom&&w.minzoom>this.transform.zoom||(this.style._clipLayerPresent||w.sourceLayer!=="building"&&w.sourceLayer!=="procedural_buildings")&&(!C||C.type!=="batched-model")))}isTileAffectedByFog(w){if(!this.style||!this.style.fog)return!1;if(this.transform.projection.name==="globe")return!0;let C=this._cachedTileFogOpacities[w.key];return C||(this._cachedTileFogOpacities[w.key]=C=this.style.fog.getOpacityForTile(w)),C[0]>=Gn||C[1]>=Gn}setupDepthForOcclusion(w,C,O){const U=this.context,Y=U.gl,Z=!!O;var se;O||(O={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}),U.activeTexture.set(Y.TEXTURE3),w&&this.depthFBO&&this.depthTexture?(this.depthTexture.bind(Y.NEAREST,Y.CLAMP_TO_EDGE),O.u_depth_size_inv=[1/this.depthFBO.width,1/this.depthFBO.height],O.u_depth_range_unpack=[2/((se=this.depthRangeFor3D)[1]-se[0]),-1-2*se[0]/(se[1]-se[0])],O.u_occluder_half_size=.5*this.occlusionParams.occluderSize,O.u_occlusion_depth_offset=this.occlusionParams.depthOffset):this.emptyDepthTexture.bind(Y.NEAREST,Y.CLAMP_TO_EDGE),U.activeTexture.set(Y.TEXTURE0),Z||C.setTerrainUniformValues(U,O)}updateEmissiveMode(){if(this._forceEmissiveMode)return;const w=this.style.hasDataDrivenEmissiveStrength();this.emissiveMode=w?this.context.extBlendFuncExtended?"dual-source-blending":"mrt-fallback":"constant"}}function di(D,w){let C=!1,O=null;const U=()=>{O=null,C&&(D(),O=setTimeout(U,w),C=!1)};return()=>(C=!0,O||U(),O)}class Du{constructor(w){this._hashName=w&&encodeURIComponent(w),o.aZ(["_getCurrentHash","_onHashChange","_updateHash"],this),this._updateHash=di(this._updateHashUnthrottled.bind(this),300)}addTo(w){return this._map=w,window.addEventListener("hashchange",this._onHashChange,!1),w.on("moveend",this._updateHash),this}remove(){return this._map?(this._map.off("moveend",this._updateHash),window.removeEventListener("hashchange",this._onHashChange,!1),clearTimeout(this._updateHash()),this._map=void 0,this):this}getHashString(){const w=this._map;if(!w)return"";const C=ll(w);if(this._hashName){const O=this._hashName;let U=!1;const Y=location.hash.slice(1).split("&").map(Z=>{const se=Z.split("=")[0];return se===O?(U=!0,`${se}=${C}`):Z}).filter(Z=>Z);return U||Y.push(`${O}=${C}`),`#${Y.join("&")}`}return`#${C}`}_getCurrentHash(){const w=location.hash.replace("#","");if(this._hashName){let C;return w.split("&").map(O=>O.split("=")).forEach(O=>{O[0]===this._hashName&&(C=O)}),(C&&C[1]||"").split("/")}return w.split("/")}_onHashChange(){const w=this._map;if(!w)return!1;const C=this._getCurrentHash();if(C.length>=3&&!C.some(O=>isNaN(Number(O)))){const O=w.dragRotate.isEnabled()&&w.touchZoomRotate.isEnabled()?+(C[3]||0):w.getBearing();return w.jumpTo({center:[+C[2],+C[1]],zoom:+C[0],bearing:O,pitch:+(C[4]||0)}),!0}return!1}_updateHashUnthrottled(){history.replaceState(history.state,"",location.href.replace(/(#.+)?$/,this.getHashString()))}}function ll(D,w){const C=D.getCenter(),O=Math.round(100*D.getZoom())/100,U=Math.ceil((O*Math.LN2+Math.log(512/360/.5))/Math.LN10),Y=Math.pow(10,U),Z=Math.round(C.lng*Y)/Y,se=Math.round(C.lat*Y)/Y,pe=D.getBearing(),je=D.getPitch();let Ee=w?`/${Z}/${se}/${O}`:`${O}/${se}/${Z}`;return(pe||je)&&(Ee+="/"+Math.round(10*pe)/10),je&&(Ee+=`/${Math.round(je)}`),Ee}const Tf={linearity:.3,easing:o.eN(0,0,.3,1)},x0=Object.assign({deceleration:2500,maxSpeed:1400},Tf),br=Object.assign({deceleration:20,maxSpeed:1400},Tf),yn=Object.assign({deceleration:1e3,maxSpeed:360},Tf),Pn=Object.assign({deceleration:1e3,maxSpeed:90},Tf);class yi{constructor(w){this._map=w,this.clear()}clear(){this._inertiaBuffer=[]}record(w){this._drainInertiaBuffer(),this._inertiaBuffer.push({time:o.o.now(),settings:w})}_drainInertiaBuffer(){const w=this._inertiaBuffer,C=o.o.now();for(;w.length>0&&C-w[0].time>160;)w.shift()}_onMoveEnd(w){if(this._map._prefersReducedMotion()||(this._drainInertiaBuffer(),this._inertiaBuffer.length<2))return;const C={zoom:0,bearing:0,pitch:0,pan:new o.P(0,0),pinchAround:void 0,around:void 0};for(const{settings:Y}of this._inertiaBuffer)C.zoom+=Y.zoomDelta||0,C.bearing+=Y.bearingDelta||0,C.pitch+=Y.pitchDelta||0,Y.panDelta&&C.pan._add(Y.panDelta),Y.around&&(C.around=Y.around),Y.pinchAround&&(C.pinchAround=Y.pinchAround);const O=this._inertiaBuffer[this._inertiaBuffer.length-1].time-this._inertiaBuffer[0].time,U={};if(C.pan.mag()){const Y=Fo(C.pan.mag(),O,Object.assign({},x0,w||{}));U.offset=C.pan.mult(Y.amount/C.pan.mag()),U.center=this._map.transform.center,Mi(U,Y)}if(C.zoom){const Y=Fo(C.zoom,O,br);U.zoom=this._map.transform.zoom+Y.amount,Mi(U,Y)}if(C.bearing){const Y=Fo(C.bearing,O,yn);U.bearing=this._map.transform.bearing+o.aC(Y.amount,-179,179),Mi(U,Y)}if(C.pitch){const Y=Fo(C.pitch,O,Pn);U.pitch=this._map.transform.pitch+Y.amount,Mi(U,Y)}if(U.zoom||U.bearing){const Y=C.pinchAround===void 0?C.around:C.pinchAround;U.around=Y?this._map.unproject(Y):this._map.getCenter()}return this.clear(),U.noMoveStart=!0,U}}function Mi(D,w){(!D.duration||D.durationC.unproject(pe)),se=Y.reduce((pe,je,Ee,He)=>pe.add(je.div(He.length)),new o.P(0,0));super(w,{points:Y,point:se,lngLats:Z,lngLat:C.unproject(se),originalEvent:O}),this._defaultPrevented=!1}}class _m extends o.C{preventDefault(){this._defaultPrevented=!0}get defaultPrevented(){return this._defaultPrevented}constructor(w,C){super("wheel",{originalEvent:C}),this._defaultPrevented=!1}}class Sc{constructor(w,C){this._map=w,this._clickTolerance=C.clickTolerance}reset(){this._mousedownPos=void 0}wheel(w){return this._firePreventable(new _m(this._map,w))}mousedown(w,C){return this._mousedownPos=C,this._firePreventable(new Yi(w.type,this._map,w))}mouseup(w){this._map.fire(new Yi(w.type,this._map,w))}preclick(w){const C=new MouseEvent("preclick",w);this._map.fire(new Yi(C.type,this._map,C))}click(w,C){this._mousedownPos&&this._mousedownPos.dist(C)>=this._clickTolerance||(this.preclick(w),this._map.fire(new Yi(w.type,this._map,w)))}dblclick(w){return this._firePreventable(new Yi(w.type,this._map,w))}mouseover(w){this._map.fire(new Yi(w.type,this._map,w))}mouseout(w){this._map.fire(new Yi(w.type,this._map,w))}touchstart(w){return this._firePreventable(new rl(w.type,this._map,w))}touchmove(w){this._map.fire(new rl(w.type,this._map,w))}touchend(w){this._map.fire(new rl(w.type,this._map,w))}touchcancel(w){this._map.fire(new rl(w.type,this._map,w))}_firePreventable(w){if(this._map.fire(w),w.defaultPrevented)return{}}isEnabled(){return!0}isActive(){return!1}enable(){}disable(){}}class j1{constructor(w){this._map=w}reset(){this._delayContextMenu=!1,this._contextMenuEvent=void 0}mousemove(w){this._map.fire(new Yi(w.type,this._map,w))}mousedown(){this._delayContextMenu=!0}mouseup(){this._delayContextMenu=!1,this._contextMenuEvent&&(this._map.fire(new Yi("contextmenu",this._map,this._contextMenuEvent)),delete this._contextMenuEvent)}contextmenu(w){this._delayContextMenu?this._contextMenuEvent=w:this._map.fire(new Yi(w.type,this._map,w)),this._map.listens("contextmenu")&&w.preventDefault()}isEnabled(){return!0}isActive(){return!1}enable(){}disable(){}}class u6{constructor(w,C){this._map=w,this._el=w.getCanvasContainer(),this._container=w.getContainer(),this._clickTolerance=C.clickTolerance||1}isEnabled(){return!!this._enabled}isActive(){return!!this._active}enable(){this.isEnabled()||(this._enabled=!0)}disable(){this.isEnabled()&&(this._enabled=!1)}mousedown(w,C){this.isEnabled()&&w.shiftKey&&w.button===0&&(A(),this._startPos=this._lastPos=C,this._active=!0)}mousemoveWindow(w,C){if(!this._active)return;const O=C,U=this._startPos,Y=this._lastPos;if(!U||!Y||Y.equals(O)||!this._box&&O.dist(U){this._box&&(this._box.style.transform=`translate(${Z}px,${pe}px)`,this._box.style.width=se-Z+"px",this._box.style.height=je-pe+"px")})}mouseupWindow(w,C){if(!this._active)return;const O=this._startPos,U=C;if(O&&w.button===0){if(this.reset(),I(),O.x!==U.x||O.y!==U.y)return this._map.fire(new o.C("boxzoomend",{originalEvent:w})),{cameraAnimation:Y=>Y.fitScreenCoordinates(O,U,this._map.getBearing(),{linear:!1})};this._fireEvent("boxzoomcancel",w)}}keydown(w){this._active&&w.keyCode===27&&(this.reset(),this._fireEvent("boxzoomcancel",w))}blur(){this.reset()}reset(){this._active=!1,this._container.classList.remove("mapboxgl-crosshair"),this._box&&(this._box.remove(),this._box=null),T(),delete this._startPos,delete this._lastPos}_fireEvent(w,C){return this._map.fire(new o.C(w,{originalEvent:C}))}}function h6(D,w){const C={};for(let O=0;Othis.numTouches)&&(this.aborted=!0),this.aborted||(this.startTime===0&&(this.startTime=w.timeStamp),O.length===this.numTouches&&(this.centroid=function(U){const Y=new o.P(0,0);for(const Z of U)Y._add(Z);return Y.div(U.length)}(C),this.touches=h6(O,C)))}touchmove(w,C,O){if(this.aborted||!this.centroid)return;const U=h6(O,C);for(const Y in this.touches){const Z=U[Y];(!Z||Z.dist(this.touches[Y])>30)&&(this.aborted=!0)}}touchend(w,C,O){if((!this.centroid||w.timeStamp-this.startTime>500)&&(this.aborted=!0),O.length===0){const U=!this.aborted&&this.centroid;if(this.reset(),U)return U}}}class fw{constructor(w){this.singleTap=new N1(w),this.numTaps=w.numTaps,this.reset()}reset(){this.lastTime=1/0,this.lastTap=void 0,this.count=0,this.singleTap.reset()}touchstart(w,C,O){this.singleTap.touchstart(w,C,O)}touchmove(w,C,O){this.singleTap.touchmove(w,C,O)}touchend(w,C,O){const U=this.singleTap.touchend(w,C,O);if(U){const Y=w.timeStamp-this.lastTime<500,Z=!this.lastTap||this.lastTap.dist(U)<30;if(Y&&Z||this.reset(),this.count++,this.lastTime=w.timeStamp,this.lastTap=U,this.count===this.numTaps)return this.reset(),U}}}class tC{constructor(){this._zoomIn=new fw({numTouches:1,numTaps:2}),this._zoomOut=new fw({numTouches:2,numTaps:1}),this.reset()}reset(){this._active=!1,this._zoomIn.reset(),this._zoomOut.reset()}touchstart(w,C,O){this._zoomIn.touchstart(w,C,O),this._zoomOut.touchstart(w,C,O)}touchmove(w,C,O){this._zoomIn.touchmove(w,C,O),this._zoomOut.touchmove(w,C,O)}touchend(w,C,O){const U=this._zoomIn.touchend(w,C,O),Y=this._zoomOut.touchend(w,C,O);return U?(this._active=!0,w.preventDefault(),setTimeout(()=>this.reset(),0),{cameraAnimation:Z=>Z.easeTo({duration:300,zoom:Z.getZoom()+1,around:Z.unproject(U)},{originalEvent:w})}):Y?(this._active=!0,w.preventDefault(),setTimeout(()=>this.reset(),0),{cameraAnimation:Z=>Z.easeTo({duration:300,zoom:Z.getZoom()-1,around:Z.unproject(Y)},{originalEvent:w})}):void 0}touchcancel(){this.reset()}enable(){this._enabled=!0}disable(){this._enabled=!1,this.reset()}isEnabled(){return this._enabled}isActive(){return this._active}}const vO=0,uq=2,hq={[vO]:1,[uq]:2},Gj={Control:"ctrlKey",Alt:"altKey",Shift:"shiftKey",Meta:"metaKey"};class m6{constructor(w){this.reset(),this._clickTolerance=w.clickTolerance||1}blur(){this.reset()}reset(){this._active=!1,this._moved=!1,this._lastPoint=void 0,this._eventButton=void 0}_correctButton(w,C){return!1}_move(w,C){return{}}mousedown(w,C){if(this._lastPoint)return;const O=z(w);this._correctButton(w,O)&&(this._lastPoint=C,this._eventButton=O)}mousemoveWindow(w,C){const O=this._lastPoint;if(O){if(w.preventDefault(),this._eventButton!=null&&function(U,Y){const Z=hq[Y];return U.buttons===void 0||(U.buttons&Z)!==Z}(w,this._eventButton))this.reset();else if(this._moved||!(C.dist(O)0&&(this._active=!0);const U=h6(O,C),Y=new o.P(0,0),Z=new o.P(0,0);let se=0;for(const je in U){const Ee=U[je],He=this._touches[je];He&&(Y._add(Ee),Z._add(Ee.sub(He)),se++,U[je]=Ee)}if(this._touches=U,se{this._alertContainer.classList.remove("mapboxgl-touch-pan-blocker-show"),this._alertContainer.removeAttribute("role")},500)}}class f6{constructor(){this.reset()}reset(){this._active=!1,this._firstTwoTouches=void 0}_start(w){}_move(w,C,O){return{}}touchstart(w,C,O){this._firstTwoTouches||O.length<2||(this._firstTwoTouches=[O[0].identifier,O[1].identifier],this._start([C[0],C[1]]))}touchmove(w,C,O){const U=this._firstTwoTouches;if(!U)return;w.preventDefault();const[Y,Z]=U,se=Zd(O,C,Y),pe=Zd(O,C,Z);if(!se||!pe)return;const je=this._aroundCenter?null:se.add(pe).div(2);return this._move([se,pe],je,w)}touchend(w,C,O){if(!this._firstTwoTouches)return;const[U,Y]=this._firstTwoTouches,Z=Zd(O,C,U),se=Zd(O,C,Y);Z&&se||(this._active&&I(),this.reset())}touchcancel(){this.reset()}enable(w){this._enabled=!0,this._aroundCenter=!!w&&w.around==="center"}disable(){this._enabled=!1,this.reset()}isEnabled(){return this._enabled}isActive(){return this._active}}function Zd(D,w,C){for(let O=0;OMath.abs(D.x)}class fq extends f6{constructor(w){super(),this._map=w}reset(){super.reset(),this._valid=void 0,this._firstMove=void 0,this._lastPoints=void 0}_start(w){this._lastPoints=w,g6(w[0].sub(w[1]))&&(this._valid=!1)}_move(w,C,O){const U=this._lastPoints;if(!U)return;const Y=w[0].sub(U[0]),Z=w[1].sub(U[1]);return this._map._cooperativeGestures&&!o.eO()&&O.touches.length<3||(this._valid=this.gestureBeginsVertically(Y,Z,O.timeStamp),!this._valid)?void 0:(this._lastPoints=w,this._active=!0,{pitchDelta:(Y.y+Z.y)/2*-.5})}gestureBeginsVertically(w,C,O){if(this._valid!==void 0)return this._valid;const U=w.mag()>=2,Y=C.mag()>=2;if(!U&&!Y)return;if(!U||!Y)return this._firstMove==null&&(this._firstMove=O),O-this._firstMove<100&&void 0;const Z=w.y>0==C.y>0;return g6(w)&&g6(C)&&Z}}const gq={panStep:100,bearingStep:15,pitchStep:10};class yS{constructor(){const w=gq;this._panStep=w.panStep,this._bearingStep=w.bearingStep,this._pitchStep=w.pitchStep,this._rotationDisabled=!1}blur(){this.reset()}reset(){this._active=!1}keydown(w){if(w.altKey||w.ctrlKey||w.metaKey)return;let C=0,O=0,U=0,Y=0,Z=0;switch(w.keyCode){case 61:case 107:case 171:case 187:C=1;break;case 189:case 109:case 173:C=-1;break;case 37:w.shiftKey?O=-1:(w.preventDefault(),Y=-1);break;case 39:w.shiftKey?O=1:(w.preventDefault(),Y=1);break;case 38:w.shiftKey?U=1:(w.preventDefault(),Z=-1);break;case 40:w.shiftKey?U=-1:(w.preventDefault(),Z=1);break;default:return}return this._rotationDisabled&&(O=0,U=0),{cameraAnimation:se=>{const pe=se.getZoom();se.easeTo({duration:300,easeId:"keyboardHandler",easing:xq,zoom:C?Math.round(pe)+C*(w.shiftKey?2:1):pe,bearing:se.getBearing()+O*this._bearingStep,pitch:se.getPitch()+U*this._pitchStep,offset:[-Y*this._panStep,-Z*this._panStep],center:se.getCenter()},{originalEvent:w})}}}enable(){this._enabled=!0}disable(){this._enabled=!1,this.reset()}isEnabled(){return this._enabled}isActive(){return this._active}disableRotation(){this._rotationDisabled=!0}enableRotation(){this._rotationDisabled=!1}}function xq(D){return D*(2-D)}const vS=4.000244140625,yq=1/450;class jO{constructor(w,C){this._map=w,this._el=w.getCanvasContainer(),this._handler=C,this._delta=0,this._lastDelta=0,this._defaultZoomRate=.01,this._wheelZoomRate=yq,o.aZ(["_onTimeout","_addScrollZoomBlocker","_showBlockerAlert"],this)}setZoomRate(w){this._defaultZoomRate=w}setWheelZoomRate(w){this._wheelZoomRate=w}isEnabled(){return!!this._enabled}isActive(){return this._active||this._finishTimeout!==void 0}isZooming(){return!!this._zooming}enable(w){this.isEnabled()||(this._enabled=!0,this._aroundCenter=!!w&&w.around==="center",this._map._cooperativeGestures&&this._addScrollZoomBlocker())}disable(){this.isEnabled()&&(this._enabled=!1,this._map._cooperativeGestures&&(clearTimeout(this._alertTimer),this._alertContainer.remove()))}wheel(w){if(!this.isEnabled())return;if(this._map._cooperativeGestures){if(!(w.ctrlKey||w.metaKey||this.isZooming()||o.eO()))return void this._showBlockerAlert();this._alertContainer.style.visibility!=="hidden"&&(this._alertContainer.style.visibility="hidden",clearTimeout(this._alertTimer))}let C=w.deltaMode===WheelEvent.DOM_DELTA_LINE?40*w.deltaY:w.deltaY;const O=o.o.now(),U=O-(this._lastWheelEventTime||0);this._lastWheelEventTime=O,C!==0&&C%vS===0?this._type="wheel":C!==0&&Math.abs(C)<4?this._type="trackpad":U>400?(this._type=null,this._lastValue=C,this._timeout=window.setTimeout(this._onTimeout,40,w)):this._type||(this._type=Math.abs(U*C)<200?"trackpad":"wheel",this._timeout&&(clearTimeout(this._timeout),this._timeout=null,C+=this._lastValue)),w.shiftKey&&C&&(C/=4),this._type&&(this._lastWheelEvent=w,this._delta-=C,this._active||this._start(w)),w.preventDefault()}_onTimeout(w){this._type="wheel",this._delta-=this._lastValue,this._active||this._start(w)}_start(w){if(!this._delta)return;this._frameId&&(this._frameId=null),this._active=!0,this.isZooming()||(this._zooming=!0),this._finishTimeout&&(clearTimeout(this._finishTimeout),delete this._finishTimeout);const C=M(this._el,w);this._aroundPoint=this._aroundCenter?this._map.transform.centerPoint:C,this._aroundCoord=this._map.transform.pointCoordinate3D(this._aroundPoint),this._targetZoom=void 0,this._frameId||(this._frameId=!0,this._handler._triggerRenderFrame())}renderFrame(){if(!this._frameId||(this._frameId=null,!this.isActive()))return;const w=this._map.transform;this._type==="wheel"&&w.projection.wrap&&(w._center.lng>=180||w._center.lng<=-180)&&(this._prevEase=null,this._easing=null,this._lastWheelEvent=null,this._lastWheelEventTime=0);const C=()=>w._terrainEnabled()&&this._aroundCoord?w.computeZoomRelativeTo(this._aroundCoord):w.zoom;if(this._delta!==0){const je=this._type==="wheel"&&Math.abs(this._delta)>vS?this._wheelZoomRate:this._defaultZoomRate;let Ee=2/(1+Math.exp(-Math.abs(this._delta*je)));this._delta<0&&Ee!==0&&(Ee=1/Ee);const He=C(),qe=Math.pow(2,He),et=typeof this._targetZoom=="number"?w.zoomScale(this._targetZoom):qe;this._targetZoom=Math.min(w.maxZoom,Math.max(w.minZoom,w.scaleZoom(et*Ee))),this._type==="wheel"&&(this._startZoom=He,this._easing=this._smoothOutEasing(200)),this._lastDelta=this._delta,this._delta=0}const O=typeof this._targetZoom=="number"?this._targetZoom:C(),U=this._startZoom,Y=this._easing;let Z,se=!1;if(this._type==="wheel"&&U&&Y){const je=Math.min((o.o.now()-this._lastWheelEventTime)/200,1),Ee=Y(je);Z=o.am(U,O,Ee),je<1?this._frameId||(this._frameId=!0):se=!0}else Z=O,se=!0;this._active=!0,se&&(this._active=!1,this._finishTimeout=window.setTimeout(()=>{this._zooming=!1,this._handler._triggerRenderFrame(),delete this._targetZoom,delete this._finishTimeout},200));let pe=Z-C();return pe*this._lastDelta<0&&(pe=0),{noInertia:!0,needsRenderFrame:!se,zoomDelta:pe,around:this._aroundPoint,aroundCoord:this._aroundCoord,originalEvent:this._lastWheelEvent}}_smoothOutEasing(w){let C=o.eP;if(this._prevEase){const O=this._prevEase,U=(o.o.now()-O.start)/O.duration,Y=O.easing(U+.01)-O.easing(U),Z=.27/Math.sqrt(Y*Y+1e-4)*.01,se=Math.sqrt(.0729-Z*Z);C=o.eN(Z,se,.25,1)}return this._prevEase={start:o.o.now(),duration:w,easing:C},C}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 NO{constructor(w,C){this._clickZoom=w,this._tapZoom=C}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 kO{constructor(){this.reset()}reset(){this._active=!1}blur(){this.reset()}dblclick(w,C){return w.preventDefault(),{cameraAnimation:O=>{O.easeTo({duration:300,zoom:O.getZoom()+(w.shiftKey?-1:1),around:O.unproject(C)},{originalEvent:w})}}}enable(){this._enabled=!0}disable(){this._enabled=!1,this.reset()}isEnabled(){return this._enabled}isActive(){return this._active}}class UJ{constructor(){this._tap=new fw({numTouches:1,numTaps:1}),this.reset()}reset(){this._active=!1,this._swipePoint=void 0,this._swipeTouch=0,this._tapTime=0,this._tap.reset()}touchstart(w,C,O){this._swipePoint||(this._tapTime&&w.timeStamp-this._tapTime>500&&this.reset(),this._tapTime?O.length>0&&(this._swipePoint=C[0],this._swipeTouch=O[0].identifier):this._tap.touchstart(w,C,O))}touchmove(w,C,O){if(this._tapTime){if(this._swipePoint){if(O[0].identifier!==this._swipeTouch)return;const U=C[0],Y=U.y-this._swipePoint.y;return this._swipePoint=U,w.preventDefault(),this._active=!0,{zoomDelta:Y/128}}}else this._tap.touchmove(w,C,O)}touchend(w,C,O){this._tapTime?this._swipePoint&&O.length===0&&this.reset():this._tap.touchend(w,C,O)&&(this._tapTime=w.timeStamp)}touchcancel(){this.reset()}enable(){this._enabled=!0}disable(){this._enabled=!1,this.reset()}isEnabled(){return this._enabled}isActive(){return this._active}}class vq{constructor(w,C,O){this._el=w,this._mousePan=C,this._touchPan=O}enable(w){this._inertiaOptions=w||{},this._mousePan.enable(),this._touchPan.enable(),this._el.classList.add("mapboxgl-touch-drag-pan")}disable(){this._mousePan.disable(),this._touchPan.disable(),this._el.classList.remove("mapboxgl-touch-drag-pan")}isEnabled(){return this._mousePan.isEnabled()&&this._touchPan.isEnabled()}isActive(){return this._mousePan.isActive()||this._touchPan.isActive()}}class qJ{constructor(w,C,O){this._pitchWithRotate=w.pitchWithRotate,this._mouseRotate=C,this._mousePitch=O}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 VJ{constructor(w,C,O,U){this._el=w,this._touchZoom=C,this._touchRotate=O,this._tapDragZoom=U,this._rotationDisabled=!1,this._enabled=!0}enable(w){this._touchZoom.enable(w),this._rotationDisabled||this._touchRotate.enable(w),this._tapDragZoom.enable(),this._el.classList.add("mapboxgl-touch-zoom-rotate")}disable(){this._touchZoom.disable(),this._touchRotate.disable(),this._tapDragZoom.disable(),this._el.classList.remove("mapboxgl-touch-zoom-rotate")}isEnabled(){return this._touchZoom.isEnabled()&&(this._rotationDisabled||this._touchRotate.isEnabled())&&this._tapDragZoom.isEnabled()}isActive(){return this._touchZoom.isActive()||this._touchRotate.isActive()||this._tapDragZoom.isActive()}disableRotation(){this._rotationDisabled=!0,this._touchRotate.disable()}enableRotation(){this._rotationDisabled=!1,this._touchZoom.isEnabled()&&this._touchRotate.enable()}}const x6=D=>D.zoom||D.drag||D.pitch||D.rotate;class HJ extends o.C{}class GJ{constructor(){this.constants=[1,1,.01],this.radius=0}setup(w,C){const O=o.ax([],C,w);this.radius=o.ai(O[2]<0?o.eR([],O,this.constants):[O[0],O[1],0])}projectRay(w){o.eR(w,w,this.constants),o.ay(w,w),o.eS(w,w,this.constants);const C=o.bJ([],w,this.radius);if(C[2]>0){const O=o.bJ([],[0,0,1],o.bi(C,[0,0,1])),U=o.bJ([],o.ay([],[C[0],C[1],0]),this.radius),Y=o.cT([],C,o.bJ([],o.ax([],o.cT([],U,O),C),2));C[0]=Y[0],C[1]=Y[1]}return C}}function y6(D){return D.panDelta&&D.panDelta.mag()||D.zoomDelta||D.bearingDelta||D.pitchDelta}class WJ{constructor(w,C){this._map=w,this._el=this._map.getCanvasContainer(),this._handlers=[],this._handlersById={},this._changes=[],this._inertia=new yi(w),this._bearingSnap=C.bearingSnap,this._previousActiveHandlers={},this._trackingEllipsoid=new GJ,this._dragOrigin=null,this._eventsInProgress={},this._addDefaultHandlers(C),o.aZ(["handleEvent","handleWindowEvent"],this);const O=this._el;this._listeners=[[O,"touchstart",{passive:!0}],[O,"touchmove",{passive:!1}],[O,"touchend",void 0],[O,"touchcancel",void 0],[O,"mousedown",void 0],[O,"mousemove",void 0],[O,"mouseup",void 0],[document,"mousemove",{capture:!0}],[document,"mouseup",void 0],[O,"mouseover",void 0],[O,"mouseout",void 0],[O,"dblclick",void 0],[O,"click",void 0],[O,"keydown",{capture:!1}],[O,"keyup",void 0],[O,"wheel",{passive:!1}],[O,"contextmenu",void 0],[window,"blur",void 0]];for(const[U,Y,Z]of this._listeners){const se=U===document?this.handleWindowEvent:this.handleEvent;U.addEventListener(Y,se,Z)}}destroy(){for(const[w,C,O]of this._listeners){const U=w===document?this.handleWindowEvent:this.handleEvent;w.removeEventListener(C,U,O)}}_addDefaultHandlers(w){const C=this._map,O=C.getCanvasContainer();this._add("mapEvent",new Sc(C,w));const U=C.boxZoom=new u6(C,w);this._add("boxZoom",U);const Y=new tC,Z=new kO;C.doubleClickZoom=new NO(Z,Y),this._add("tapZoom",Y),this._add("clickZoom",Z);const se=new UJ;this._add("tapDragZoom",se);const pe=C.touchPitch=new fq(C);this._add("touchPitch",pe);const je=new bO(w),Ee=new p6(w);C.dragRotate=new qJ(w,je,Ee),this._add("mouseRotate",je,["mousePitch"]),this._add("mousePitch",Ee,["mouseRotate"]);const He=new k1(w),qe=new mq(C,w);C.dragPan=new vq(O,He,qe),this._add("mousePan",He),this._add("touchPan",qe,["touchZoom","touchRotate"]);const et=new xS,ct=new pq;C.touchZoomRotate=new VJ(O,ct,et,se),this._add("touchRotate",et,["touchPan","touchZoom"]),this._add("touchZoom",ct,["touchPan","touchRotate"]),this._add("blockableMapEvent",new j1(C));const ot=C.scrollZoom=new jO(C,this);this._add("scrollZoom",ot,["mousePan"]);const bt=C.keyboard=new yS;this._add("keyboard",bt);for(const vt of["boxZoom","doubleClickZoom","tapDragZoom","touchPitch","dragRotate","dragPan","touchZoomRotate","scrollZoom","keyboard"])w.interactive&&w[vt]&&C[vt].enable(w[vt])}_add(w,C,O){this._handlers.push({handlerName:w,handler:C,allowed:O}),this._handlersById[w]=C}stop(w){if(!this._updatingCamera){for(const{handler:C}of this._handlers)C.reset();this._inertia.clear(),this._fireEvents({},{},w),this._changes=[],this._originalZoom=void 0}}isActive(){for(const{handler:w}of this._handlers)if(w.isActive())return!0;return!1}isZooming(){return!!this._eventsInProgress.zoom||this._map.scrollZoom.isZooming()}isRotating(){return!!this._eventsInProgress.rotate}isMoving(){return!!x6(this._eventsInProgress)||this.isZooming()}_isDragging(){return!!this._eventsInProgress.drag}_blockedByActive(w,C,O){for(const U in w)if(U!==O&&(!C||C.indexOf(U)<0))return!0;return!1}handleWindowEvent(w){this.handleEvent(w,`${w.type}Window`)}_getMapTouches(w){const C=[];for(const O of w)this._el.contains(O.target)&&C.push(O);return C}handleEvent(w,C){this._updatingCamera=!0;const O=w.type==="renderFrame",U=O?void 0:w,Y={needsRenderFrame:!1},Z={},se={},pe=w.touches?this._getMapTouches(w.touches):void 0,je=pe?L(this._el,pe):O?void 0:M(this._el,w);for(const{handlerName:qe,handler:et,allowed:ct}of this._handlers){if(!et.isEnabled())continue;let ot;this._blockedByActive(se,ct,qe)?et.reset():et[C||w.type]&&(ot=et[C||w.type](w,je,pe),this.mergeHandlerResult(Y,Z,ot,qe,U),ot&&ot.needsRenderFrame&&this._triggerRenderFrame()),(ot||et.isActive())&&(se[qe]=et)}const Ee={};for(const qe in this._previousActiveHandlers)se[qe]||(Ee[qe]=U);this._previousActiveHandlers=se,(Object.keys(Ee).length||y6(Y))&&(this._changes.push([Y,Z,Ee]),this._triggerRenderFrame()),(Object.keys(se).length||y6(Y))&&this._map._stop(!0),this._updatingCamera=!1;const{cameraAnimation:He}=Y;He&&(this._inertia.clear(),this._fireEvents({},{},!0),this._changes=[],He(this._map))}mergeHandlerResult(w,C,O,U,Y){if(!O)return;Object.assign(w,O);const Z={handlerName:U,originalEvent:O.originalEvent||Y};O.zoomDelta!==void 0&&(C.zoom=Z),O.panDelta!==void 0&&(C.drag=Z),O.pitchDelta!==void 0&&(C.pitch=Z),O.bearingDelta!==void 0&&(C.rotate=Z)}_applyChanges(){const w={},C={},O={};for(const[U,Y,Z]of this._changes)U.panDelta&&(w.panDelta=(w.panDelta||new o.P(0,0))._add(U.panDelta)),U.zoomDelta&&(w.zoomDelta=(w.zoomDelta||0)+U.zoomDelta),U.bearingDelta&&(w.bearingDelta=(w.bearingDelta||0)+U.bearingDelta),U.pitchDelta&&(w.pitchDelta=(w.pitchDelta||0)+U.pitchDelta),U.around!==void 0&&(w.around=U.around),U.aroundCoord!==void 0&&(w.aroundCoord=U.aroundCoord),U.pinchAround!==void 0&&(w.pinchAround=U.pinchAround),U.noInertia&&(w.noInertia=U.noInertia),Object.assign(C,Y),Object.assign(O,Z);this._updateMapTransform(w,C,O),this._changes=[]}_updateMapTransform(w,C,O){const U=this._map,Y=U.transform,Z=Pt=>[Pt.x,Pt.y,Pt.z];if((()=>{const Pt=this._eventsInProgress.drag;return Pt&&!this._handlersById[Pt.handlerName].isActive()})()&&!y6(w)){const Pt=Y.zoom;Y.cameraElevationReference="sea",this._originalZoom!=null&&Y._orthographicProjectionAtLowPitch&&Y.projection.name!=="globe"&&Y.pitch===0?(Y.cameraElevationReference="ground",Y.zoom=this._originalZoom):(Y.recenterOnTerrain(),Y.cameraElevationReference="ground"),Pt!==Y.zoom&&this._map._update(!0)}if(Y._isCameraConstrained&&U._stop(!0),!y6(w))return void this._fireEvents(C,O,!0);let{panDelta:se,zoomDelta:pe,bearingDelta:je,pitchDelta:Ee,around:He,aroundCoord:qe,pinchAround:et}=w;Y._isCameraConstrained&&(pe>0&&(pe=0),Y._isCameraConstrained=!1),et!==void 0&&(He=et),(pe||(Pt=>C[Pt]&&!this._eventsInProgress[Pt])("drag"))&&He&&(this._dragOrigin=Z(Y.pointCoordinate3D(He)),this._originalZoom=Y.zoom,this._trackingEllipsoid.setup(Y._camera.position,this._dragOrigin)),Y.cameraElevationReference="sea",U._stop(!0),He=He||U.transform.centerPoint,je&&(Y.bearing+=je),Ee&&(Y.pitch+=Ee),Y._updateCameraState();const ct=[0,0,0];if(se)if(Y.projection.name==="mercator"){const Pt=this._trackingEllipsoid.projectRay(Y.screenPointToMercatorRay(He).dir),Ft=this._trackingEllipsoid.projectRay(Y.screenPointToMercatorRay(He.sub(se)).dir);ct[0]=Ft[0]-Pt[0],ct[1]=Ft[1]-Pt[1]}else{const Pt=Y.pointCoordinate(He);if(Y.projection.name==="globe"){se=se.rotate(-Y.angle);const Ft=Y._pixelsPerMercatorPixel/Y.worldSize;ct[0]=-se.x*o.eQ(o.bV(Pt.y))*Ft,ct[1]=-se.y*o.eQ(Y.center.lat)*Ft}else{const Ft=Y.pointCoordinate(He.sub(se));Pt&&Ft&&(ct[0]=Ft.x-Pt.x,ct[1]=Ft.y-Pt.y)}}const ot=Y.zoom,bt=[0,0,0];if(pe){const Pt=Z(qe||Y.pointCoordinate3D(He)),Ft={dir:o.ay([],o.ax([],Pt,Y._camera.position))};if(Ft.dir[2]<0){const jt=Y.zoomDeltaToMovement(Pt,pe);o.bJ(bt,Ft.dir,jt)}}const vt=o.cT(ct,ct,bt);Y._translateCameraConstrained(vt),pe&&Math.abs(Y.zoom-ot)>1e-4&&Y.recenterOnTerrain(),Y.cameraElevationReference="ground",this._map._update(),w.noInertia||this._inertia.record(w),this._fireEvents(C,O,!0)}_fireEvents(w,C,O){const U=x6(this._eventsInProgress),Y=x6(w),Z={};for(const Ee in w){const{originalEvent:He}=w[Ee];this._eventsInProgress[Ee]||(Z[`${Ee}start`]=He),this._eventsInProgress[Ee]=w[Ee]}!U&&Y&&this._fireEvent("movestart",Y.originalEvent);for(const Ee in Z)this._fireEvent(Ee,Z[Ee]);Y&&this._fireEvent("move",Y.originalEvent);for(const Ee in w){const{originalEvent:He}=w[Ee];this._fireEvent(Ee,He)}const se={};let pe;for(const Ee in this._eventsInProgress){const{handlerName:He,originalEvent:qe}=this._eventsInProgress[Ee];this._handlersById[He].isActive()||(delete this._eventsInProgress[Ee],pe=C[He]||qe,se[`${Ee}end`]=pe)}for(const Ee in se)this._fireEvent(Ee,se[Ee]);const je=x6(this._eventsInProgress);if(O&&(U||Y)&&!je){this._updatingCamera=!0;const Ee=this._inertia._onMoveEnd(this._map.dragPan._inertiaOptions),He=qe=>qe!==0&&-this._bearingSnap{this._frameId=void 0,this.handleEvent(new HJ("renderFrame",{timeStamp:w})),this._applyChanges()})}_triggerRenderFrame(){this._frameId===void 0&&(this._frameId=this._requestFrame())}}const bq="map.setFreeCameraOptions(...) and map.getFreeCameraOptions() are not yet supported for non-mercator projections.";class KJ extends o.E{constructor(w,C){super(),this._moving=!1,this._zooming=!1,this.transform=w,this._bearingSnap=C.bearingSnap,this._respectPrefersReducedMotion=C.respectPrefersReducedMotion!==!1,o.aZ(["_renderFrameCallback"],this)}getCenter(){return new o.aU(this.transform.center.lng,this.transform.center.lat)}setCenter(w,C){return this.jumpTo({center:w},C)}panBy(w,C,O){return w=o.P.convert(w).mult(-1),this.panTo(this.transform.center,Object.assign({offset:w},C),O)}panTo(w,C,O){return this.easeTo(Object.assign({center:w},C),O)}getZoom(){return this.transform.zoom}setZoom(w,C){return this.jumpTo({zoom:w},C),this}zoomTo(w,C,O){return this.easeTo(Object.assign({zoom:w},C),O)}zoomIn(w,C){return this.zoomTo(this.getZoom()+1,w,C),this}zoomOut(w,C){return this.zoomTo(this.getZoom()-1,w,C),this}getBearing(){return this.transform.bearing}setBearing(w,C){return this.jumpTo({bearing:w},C),this}getPadding(){return this.transform.padding}setPadding(w,C){return this.jumpTo({padding:w},C),this}rotateTo(w,C,O){return this.easeTo(Object.assign({bearing:w},C),O)}resetNorth(w,C){return this.rotateTo(0,Object.assign({duration:1e3},w),C),this}resetNorthPitch(w,C){return this.easeTo(Object.assign({bearing:0,pitch:0,duration:1e3},w),C),this}snapToNorth(w,C){return Math.abs(this.getBearing())w.aspect?O/(2*Math.tan(.5*w.fovX)*w.aspect):U/(2*Math.tan(.5*w.fovY)*w.aspect)}_cameraForBoundsOnGlobe(w,C,O,U,Y,Z){const se=w.clone(),pe=this._extendCameraOptions(Z);se.bearing=U,se.pitch=Y;const je=o.aU.convert(C),Ee=o.aU.convert(O),He=.5*(je.lat+Ee.lat),qe=.5*(je.lng+Ee.lng),et=o.eT(He,qe),ct=o.ay([],et),ot=o.ay([],o.bh([],ct,[0,1,0])),bt=o.bh([],ot,ct),vt=[ot[0],ot[1],ot[2],0,bt[0],bt[1],bt[2],0,ct[0],ct[1],ct[2],0,0,0,0,1],Pt=[et,o.eT(je.lat,je.lng),o.eT(Ee.lat,je.lng),o.eT(Ee.lat,Ee.lng),o.eT(je.lat,Ee.lng),o.eT(He,je.lng),o.eT(He,Ee.lng),o.eT(je.lat,qe),o.eT(Ee.lat,qe)];let Ft=o.cU.fromPoints(Pt.map(pn=>[o.bi(ot,pn),o.bi(bt,pn),o.bi(ct,pn)]));const jt=o.ah([],Ft.center,vt);o.eU(jt)===0&&o.eV(jt,0,0,1),o.ay(jt,jt),o.bJ(jt,jt,o.aF),se.center=o.eW(jt);const ys=se.getWorldToCameraMatrix(),Qt=o.b7(new Float64Array(16),ys);Ft=o.cU.applyTransform(Ft,o.aD([],ys,vt));const gs=this._extendAABB(Ft,se,pe,U);if(!gs)return void o.w("Map cannot fit within canvas with the given bounds, padding, and/or offset.");Ft=gs,o.ah(jt,jt,ys);const $t=.5*(Ft.max[2]-Ft.min[2]),Zt=this._minimumAABBFrustumDistance(se,Ft),hs=o.bJ([],[0,0,1],$t),Us=o.cT(hs,jt,hs),Cs=Zt+(se.pitch===0?0:o.bf(jt,Us)),hn=se.globeCenterInViewSpace,an=o.ax([],jt,[hn[0],hn[1],hn[2]]);o.ay(an,an),o.bJ(an,an,Cs);const An=o.cT([],jt,an);o.ah(An,An,Qt);const On=o.eD/o.aF,Ks=o.ai(An),Es=o.bU(Math.max(Ks*On-o.eD,Number.EPSILON),0),cn=Math.min(se.zoomFromMercatorZAdjusted(Es),pe.maxZoom);return cn>.5*(o.cJ+o.cv)?(se.setProjection({name:"mercator"}),se.zoom=cn,this._cameraForBounds(se,C,O,U,Y,Z)):{center:se.center,zoom:cn,bearing:U,pitch:Y}}_extendAABB(w,C,O,U){const Y=.5*((O.padding.left||0)+(O.padding.right||0)),Z=.5*((O.padding.top||0)+(O.padding.bottom||0)),se=Z,pe=Y,je=Y,Ee=Z,He=C.width-(pe+je),qe=C.height-(se+Ee),et=o.ax([],w.max,w.min),ct=Math.min(He/et[0],qe/et[1]),ot=Math.min(C.scaleZoom(C.scale*ct),O.maxZoom);if(isNaN(ot))return null;const bt=C.scale/C.zoomScale(ot),vt=new o.cU([w.min[0]-pe*bt,w.min[1]-Ee*bt,w.min[2]],[w.max[0]+je*bt,w.max[1]+se*bt,w.max[2]]),Pt=(typeof O.offset.x=="number"&&typeof O.offset.y=="number"?new o.P(O.offset.x,O.offset.y):o.P.convert(O.offset)).rotate(-o.ap(U));return vt.center[0]-=Pt.x*bt,vt.center[1]+=Pt.y*bt,vt}queryTerrainElevation(w,C){const O=this.transform.elevation;return O?(C=Object.assign({},{exaggerated:!0},C),O.getAtPoint(o.ag.fromLngLat(w),null,C.exaggerated)):null}_cameraForBounds(w,C,O,U,Y,Z){if(w.projection.name==="globe")return this._cameraForBoundsOnGlobe(w,C,O,U,Y,Z);const se=w.clone(),pe=this._extendCameraOptions(Z);se.bearing=U,se.pitch=Y;const je=o.aU.convert(C),Ee=o.aU.convert(O),He=new o.aU(je.lng,Ee.lat),qe=new o.aU(Ee.lng,je.lat),et=se.project(je),ct=se.project(Ee),ot=this.queryTerrainElevation(je),bt=this.queryTerrainElevation(Ee),vt=this.queryTerrainElevation(He),Pt=this.queryTerrainElevation(qe),Ft=[[et.x,et.y,Math.min(ot||0,bt||0,vt||0,Pt||0)],[ct.x,ct.y,Math.max(ot||0,bt||0,vt||0,Pt||0)]];let jt=o.cU.fromPoints(Ft);const ys=se.getWorldToCameraMatrix(),Qt=o.b7(new Float64Array(16),ys);jt=o.cU.applyTransform(jt,ys);const gs=this._extendAABB(jt,se,pe,U);if(!gs)return void o.w("Map cannot fit within canvas with the given bounds, padding, and/or offset.");jt=gs;const $t=.5*o.ax([],jt.max,jt.min)[2],Zt=this._minimumAABBFrustumDistance(se,jt),hs=[0,0,1,0];o.aE(hs,hs,ys),o.eX(hs,hs);const Us=o.bJ([],hs,Zt+$t),Cs=o.cT([],jt.center,Us);o.ah(jt.center,jt.center,Qt),o.ah(Cs,Cs,Qt);const hn=se.unproject(new o.P(jt.center[0],jt.center[1])),an=o.eY(se.projection,hn),An=Math.pow(2,an),On=Math.min(se._zoomFromMercatorZ(Cs[2]*se.pixelsPerMeter*An/se.worldSize),pe.maxZoom);return se.mercatorFromTransition&&On<.5*(o.cJ+o.cv)?(se.setProjection({name:"globe"}),se.zoom=On,this._cameraForBounds(se,C,O,U,Y,Z)):{center:hn,zoom:On,bearing:U,pitch:Y}}fitBounds(w,C,O){const U=this.cameraForBounds(w,C);return this._fitInternal(U,C,O)}fitScreenCoordinates(w,C,O,U,Y){const Z=o.P.convert(w),se=o.P.convert(C),pe=new o.P(Math.min(Z.x,se.x),Math.min(Z.y,se.y)),je=new o.P(Math.max(Z.x,se.x),Math.max(Z.y,se.y));if(this.transform.projection.name==="mercator"&&this.transform.anyCornerOffEdge(Z,se))return this;const Ee=this.transform.pointLocation3D(pe),He=this.transform.pointLocation3D(je),qe=this.transform.pointLocation3D(new o.P(pe.x,je.y)),et=this.transform.pointLocation3D(new o.P(je.x,pe.y)),ct=[Math.min(Ee.lng,He.lng,qe.lng,et.lng),Math.min(Ee.lat,He.lat,qe.lat,et.lat)],ot=[Math.max(Ee.lng,He.lng,qe.lng,et.lng),Math.max(Ee.lat,He.lat,qe.lat,et.lat)],bt=U&&U.pitch?U.pitch:this.getPitch(),vt=this._cameraForBounds(this.transform,ct,ot,O,bt,U);return this._fitInternal(vt,U,Y)}_fitInternal(w,C,O){return w?(C=Object.assign(w,C)).linear?this.easeTo(C,O):this.flyTo(C,O):this}jumpTo(w,C){this.stop();const O=w.preloadOnly?this.transform.clone():this.transform;let U=!1,Y=!1,Z=!1;"zoom"in w&&O.zoom!==+w.zoom&&(U=!0,O.zoom=+w.zoom),w.center!==void 0&&(O.center=o.aU.convert(w.center)),"bearing"in w&&O.bearing!==+w.bearing&&(Y=!0,O.bearing=+w.bearing),"pitch"in w&&O.pitch!==+w.pitch&&(Z=!0,O.pitch=+w.pitch);const se=typeof w.padding=="number"?this._extendPadding(w.padding):w.padding;if(w.padding!=null&&!O.isPaddingEqual(se))if(w.retainPadding===!1){const pe=O.clone();pe.padding=se,O.setLocationAtPoint(O.center,pe.centerPoint)}else O.padding=se;return w.preloadOnly?(this._preloadTiles(O),this):(this.fire(new o.C("movestart",C)).fire(new o.C("move",C)),U&&this.fire(new o.C("zoomstart",C)).fire(new o.C("zoom",C)).fire(new o.C("zoomend",C)),Y&&this.fire(new o.C("rotatestart",C)).fire(new o.C("rotate",C)).fire(new o.C("rotateend",C)),Z&&this.fire(new o.C("pitchstart",C)).fire(new o.C("pitch",C)).fire(new o.C("pitchend",C)),this.fire(new o.C("moveend",C)))}getFreeCameraOptions(){return this.transform.projection.supportsFreeCamera||o.w(bq),this.transform.getFreeCameraOptions()}setFreeCameraOptions(w,C){const O=this.transform;if(!O.projection.supportsFreeCamera)return o.w(bq),this;this.stop();const U=O.zoom,Y=O.pitch,Z=O.bearing;O.setFreeCameraOptions(w);const se=U!==O.zoom,pe=Y!==O.pitch,je=Z!==O.bearing;return this.fire(new o.C("movestart",C)).fire(new o.C("move",C)),se&&this.fire(new o.C("zoomstart",C)).fire(new o.C("zoom",C)).fire(new o.C("zoomend",C)),je&&this.fire(new o.C("rotatestart",C)).fire(new o.C("rotate",C)).fire(new o.C("rotateend",C)),pe&&this.fire(new o.C("pitchstart",C)).fire(new o.C("pitch",C)).fire(new o.C("pitchend",C)),this.fire(new o.C("moveend",C)),this}easeTo(w,C){this._stop(!1,w.easeId),((w=Object.assign({offset:[0,0],duration:500,easing:o.eP},w)).animate===!1||this._prefersReducedMotion(w))&&(w.duration=0);const O=this.transform,U=this.getZoom(),Y=this.getBearing(),Z=this.getPitch(),se=this.getPadding(),pe="zoom"in w?+w.zoom:U,je="bearing"in w?this._normalizeBearing(w.bearing,Y):Y,Ee="pitch"in w?+w.pitch:Z,He=this._extendPadding(w.padding),qe=o.P.convert(w.offset);let et,ct,ot;if(O.projection.name==="globe"){const hs=o.ag.fromLngLat(O.center),Us=qe.rotate(-O.angle);hs.x+=Us.x/O.worldSize,hs.y+=Us.y/O.worldSize;const Cs=hs.toLngLat(),hn=o.aU.convert(w.center||Cs);this._normalizeCenter(hn),et=O.centerPoint.add(Us),ct=new o.P(hs.x,hs.y).mult(O.worldSize),ot=new o.P(o.aH(hn.lng),o.aL(hn.lat)).mult(O.worldSize).sub(ct)}else{et=O.centerPoint.add(qe);const hs=O.pointLocation(et),Us=o.aU.convert(w.center||hs);this._normalizeCenter(Us),ct=O.project(hs),ot=O.project(Us).sub(ct)}const bt=O.zoomScale(pe-U);let vt,Pt;w.around&&(vt=o.aU.convert(w.around),Pt=O.locationPoint(vt));const Ft=this._zooming||pe!==U,jt=this._rotating||Y!==je,ys=this._pitching||Ee!==Z,Qt=!O.isPaddingEqual(He),gs=w.retainPadding===!1?O.clone():O,$t=hs=>Us=>{if(Ft&&(hs.zoom=o.am(U,pe,Us)),jt&&(hs.bearing=o.am(Y,je,Us)),ys&&(hs.pitch=o.am(Z,Ee,Us)),Qt&&(gs.interpolatePadding(se,He,Us),et=gs.centerPoint.add(qe)),vt)hs.setLocationAtPoint(vt,Pt);else{const Cs=hs.zoomScale(hs.zoom-U),hn=pe>U?Math.min(2,bt):Math.max(.5,bt),an=Math.pow(hn,1-Us),An=hs.unproject(ct.add(ot.mult(Us*an)).mult(Cs));hs.setLocationAtPoint(hs.renderWorldCopies?An.wrap():An,et)}return w.preloadOnly||this._fireMoveEvents(C),hs};if(w.preloadOnly){const hs=this._emulate($t,w.duration,O);return this._preloadTiles(hs),this}const Zt={moving:this._moving,zooming:this._zooming,rotating:this._rotating,pitching:this._pitching};return this._zooming=Ft,this._rotating=jt,this._pitching=ys,this._padding=Qt,this._easeId=w.easeId,this._prepareEase(C,w.noMoveStart,Zt),this._ease($t(O),hs=>{O.cameraElevationReference==="sea"&&O.recenterOnTerrain(),this._afterEase(C,hs)},w),this}_prepareEase(w,C,O={}){this._moving=!0,this.transform.cameraElevationReference="sea",this.transform._orthographicProjectionAtLowPitch&&this.transform.pitch===0&&this.transform.projection.name!=="globe"&&(this.transform.cameraElevationReference="ground"),C||O.moving||this.fire(new o.C("movestart",w)),this._zooming&&!O.zooming&&this.fire(new o.C("zoomstart",w)),this._rotating&&!O.rotating&&this.fire(new o.C("rotatestart",w)),this._pitching&&!O.pitching&&this.fire(new o.C("pitchstart",w))}_fireMoveEvents(w){this.fire(new o.C("move",w)),this._zooming&&this.fire(new o.C("zoom",w)),this._rotating&&this.fire(new o.C("rotate",w)),this._pitching&&this.fire(new o.C("pitch",w))}_afterEase(w,C){if(this._easeId&&C&&this._easeId===C)return;this._easeId=void 0,this.transform.cameraElevationReference="ground";const O=this._zooming,U=this._rotating,Y=this._pitching;this._moving=!1,this._zooming=!1,this._rotating=!1,this._pitching=!1,this._padding=!1,O&&this.fire(new o.C("zoomend",w)),U&&this.fire(new o.C("rotateend",w)),Y&&this.fire(new o.C("pitchend",w)),this.fire(new o.C("moveend",w))}flyTo(w,C){if(this._prefersReducedMotion(w)){const pn=o.aJ(w,["center","zoom","bearing","pitch","around","padding","retainPadding"]);return this.jumpTo(pn,C)}this.stop(),w=Object.assign({offset:[0,0],speed:1.2,curve:1.42,easing:o.eP},w);const O=this.transform,U=this.getZoom(),Y=this.getBearing(),Z=this.getPitch(),se=this.getPadding(),pe="zoom"in w?o.aC(+w.zoom,O.minZoom,O.maxZoom):U,je="bearing"in w?this._normalizeBearing(w.bearing,Y):Y,Ee="pitch"in w?+w.pitch:Z,He=this._extendPadding(w.padding),qe=O.zoomScale(pe-U),et=o.P.convert(w.offset);let ct=O.centerPoint.add(et);const ot=O.pointLocation(ct),bt=o.aU.convert(w.center||ot);this._normalizeCenter(bt);const vt=O.project(ot),Pt=O.project(bt).sub(vt);let Ft=w.curve;const jt=Math.max(O.width,O.height),ys=jt/qe,Qt=Pt.mag();if("minZoom"in w){const pn=o.aC(Math.min(w.minZoom,U,pe),O.minZoom,O.maxZoom),vn=jt/O.zoomScale(pn-U);Ft=Math.sqrt(vn/Qt*2)}const gs=Ft*Ft;function $t(pn){const vn=(ys*ys-jt*jt+(pn?-1:1)*gs*gs*Qt*Qt)/(2*(pn?ys:jt)*gs*Qt);return Math.log(Math.sqrt(vn*vn+1)-vn)}function Zt(pn){return(Math.exp(pn)-Math.exp(-pn))/2}function hs(pn){return(Math.exp(pn)+Math.exp(-pn))/2}const Us=$t(0);let Cs=function(pn){return hs(Us)/hs(Us+Ft*pn)},hn=function(pn){return jt*((hs(Us)*(Zt(vn=Us+Ft*pn)/hs(vn))-Zt(Us))/gs)/Qt;var vn},an=($t(1)-Us)/Ft;if(Math.abs(Qt)<1e-6||!isFinite(an)){if(Math.abs(jt-ys)<1e-6)return this.easeTo(w,C);const pn=ysw.maxDuration&&(w.duration=0);const An=Y!==je,On=Ee!==Z,Ks=!O.isPaddingEqual(He),Es=w.retainPadding===!1?O.clone():O,cn=pn=>vn=>{const fr=vn*an,nr=1/Cs(fr);pn.zoom=vn===1?pe:U+pn.scaleZoom(nr),An&&(pn.bearing=o.am(Y,je,vn)),On&&(pn.pitch=o.am(Z,Ee,vn)),Ks&&(Es.interpolatePadding(se,He,vn),ct=Es.centerPoint.add(et));const rr=vn===1?bt:pn.unproject(vt.add(Pt.mult(hn(fr))).mult(nr));return pn.setLocationAtPoint(pn.renderWorldCopies?rr.wrap():rr,ct),pn._updateCameraOnTerrain(),w.preloadOnly||this._fireMoveEvents(C),pn};if(w.preloadOnly){const pn=this._emulate(cn,w.duration,O);return this._preloadTiles(pn),this}return this._zooming=!0,this._rotating=An,this._pitching=On,this._padding=Ks,this._prepareEase(C,!1),this._ease(cn(O),()=>this._afterEase(C),w),this}isEasing(){return!!this._easeFrameId}stop(){return this._stop()}_requestRenderFrame(w){}_cancelRenderFrame(w){}_stop(w,C){if(this._easeFrameId&&(this._cancelRenderFrame(this._easeFrameId),this._easeFrameId=void 0,this._onEaseFrame=void 0),this._onEaseEnd){const O=this._onEaseEnd;this._onEaseEnd=void 0,O.call(this,C)}if(!w){const O=this.handlers;O&&O.stop(!1)}return this}_ease(w,C,O){O.animate===!1||O.duration===0?(w(1),C()):(this._easeStart=o.o.now(),this._easeOptions=O,this._onEaseFrame=w,this._onEaseEnd=C,this._easeFrameId=this._requestRenderFrame(this._renderFrameCallback))}_renderFrameCallback(){const w=Math.min((o.o.now()-this._easeStart)/this._easeOptions.duration,1),C=this._onEaseFrame;C&&C(this._easeOptions.easing(w)),w<1?this._easeFrameId=this._requestRenderFrame(this._renderFrameCallback):this.stop()}_normalizeBearing(w,C){w=o.bs(w,-180,180);const O=Math.abs(w-C);return Math.abs(w-360-C)180?-360:O<-180?360:0}_prefersReducedMotion(w){return this._respectPrefersReducedMotion&&o.o.prefersReducedMotion&&!(w&&w.essential)}_emulate(w,C,O){const U=Math.ceil(15*C/1e3),Y=[],Z=w(O.clone());for(let se=0;se<=U;se++){const pe=Z(se/U);Y.push(pe.clone())}return Y}_preloadTiles(w,C){}}class _q{constructor(w={}){this.options=w,o.aZ(["_toggleAttribution","_updateEditLink","_updateData","_updateCompact"],this)}getDefaultPosition(){return"bottom-right"}onAdd(w){const C=this.options&&this.options.compact,O=w._getUIString("AttributionControl.ToggleAttribution");this._map=w,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",O);const U=y("span","mapboxgl-ctrl-icon",this._compactButton);return U.setAttribute("aria-hidden","true"),U.setAttribute("title",O),this._innerContainer=y("div","mapboxgl-ctrl-attrib-inner",this._container),C&&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),C===void 0&&(this._map.on("resize",this._updateCompact),this._updateCompact()),this._container}onRemove(){this._container.remove(),this._map.off("styledata",this._updateData),this._map.off("sourcedata",this._updateData),this._map.off("moveend",this._updateEditLink),this._map.off("resize",this._updateCompact),this._map=void 0,this._attribHTML=void 0}_toggleAttribution(){this._container.classList.contains("mapboxgl-compact-show")?(this._container.classList.remove("mapboxgl-compact-show"),this._compactButton.setAttribute("aria-expanded","false")):(this._container.classList.add("mapboxgl-compact-show"),this._compactButton.setAttribute("aria-expanded","true"))}_updateEditLink(){let w=this._editLink;w||(w=this._editLink=this._container.querySelector(".mapbox-improve-map"));const C=[{key:"owner",value:this.styleOwner},{key:"id",value:this.styleId},{key:"access_token",value:this._map._requestManager._customAccessToken||o.g.ACCESS_TOKEN}];if(w){const O=C.reduce((U,Y,Z)=>(Y.value&&(U+=`${Y.key}=${Y.value}${ZU.length-Y.length),w=w.filter((U,Y)=>{for(let Z=Y+1;Z=0)return!1;return!0}),this.options.customAttribution&&(Array.isArray(this.options.customAttribution)?w=[...this.options.customAttribution,...w]:w.unshift(this.options.customAttribution));const O=w.map(U=>function(Y){const Z=new DOMParser().parseFromString(Y,"text/html");return Array.from(Z.body.querySelectorAll("*")).reverse().forEach(se=>{const pe=se.textContent||"";if(se.tagName!=="A")return void se.replaceWith(...se.childNodes);const je=se.getAttribute("href");if(!je||!/^(https?:|mailto:)/i.test(je))return void se.replaceWith(Z.createTextNode(pe));const Ee=Z.createElement("a");Ee.href=je,Ee.textContent=pe,Ee.rel="noopener nofollow";const He=se.getAttribute("class");He&&(Ee.className=He),se.replaceWith(Ee)}),Z.body.innerHTML}(U)).join(" | ");O!==this._attribHTML&&(this._attribHTML=O,w.length?(this._innerContainer.innerHTML=O,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 wq{constructor(){o.aZ(["_updateLogo","_updateCompact"],this)}onAdd(w){this._map=w,this._container=y("div","mapboxgl-ctrl");const C=y("a","mapboxgl-ctrl-logo");return C.target="_blank",C.rel="noopener nofollow",C.href="https://www.mapbox.com/",C.setAttribute("aria-label",this._map._getUIString("LogoControl.Title")),C.setAttribute("rel","noopener nofollow"),this._container.appendChild(C),this._container.style.display="none",this._map.on("sourcedata",this._updateLogo),this._updateLogo(),this._map.on("resize",this._updateCompact),this._updateCompact(),this._container}onRemove(){this._container.remove(),this._map.off("sourcedata",this._updateLogo),this._map.off("resize",this._updateCompact)}getDefaultPosition(){return"bottom-left"}_updateLogo(w){w&&w.sourceDataType!=="metadata"||(this._container.style.display=this._logoRequired()?"block":"none")}_logoRequired(){if(!this._map.style)return!0;const w=this._map.style._sourceCaches;if(Object.entries(w).length===0)return!0;for(const C in w){const O=w[C].getSource();if(O.hasOwnProperty("mapbox_logo")&&!O.mapbox_logo)return!1}return!0}_updateCompact(){const w=this._container.children;if(w.length){const C=w[0];this._map.getCanvasContainer().offsetWidth<250?C.classList.add("mapboxgl-compact"):C.classList.remove("mapboxgl-compact")}}}class YJ{constructor(){this._queue=[],this._id=0,this._cleared=!1,this._currentlyRunning=!1}add(w){const C=++this._id;return this._queue.push({callback:w,id:C,cancelled:!1}),C}remove(w){const C=this._currentlyRunning,O=C?this._queue.concat(C):this._queue;for(const U of O)if(U.id===w)return void(U.cancelled=!0)}run(w=0){const C=this._currentlyRunning=this._queue;this._queue=[];for(const O of C)if(!O.cancelled&&(O.callback(w),this._cleared))break;this._cleared=!1,this._currentlyRunning=!1}clear(){this._currentlyRunning&&(this._cleared=!0),this._queue=[]}}class qAe{constructor(w){this.jumpTo(w)}getValue(w){if(w<=this._startTime)return this._start;if(w>=this._endTime)return this._end;const C=o.dn((w-this._startTime)/(this._endTime-this._startTime));return this._start*(1-C)+this._end*C}isEasing(w){return w>=this._startTime&&w<=this._endTime}jumpTo(w){this._startTime=-1/0,this._endTime=-1/0,this._start=w,this._end=w}easeTo(w,C,O){this._start=this.getValue(C),this._end=w,this._startTime=C,this._endTime=C+O}}const VAe={"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 Ul extends o.C{constructor(w,C,O,U){const{point:Y,lngLat:Z,originalEvent:se,target:pe}=w;super(w.type,{point:Y,lngLat:Z,originalEvent:se,target:pe}),this.preventDefault=()=>{w.preventDefault()},this.id=C,this.interaction=O,this.feature=U}}class SO{constructor(w){this.map=w,this.interactionsByType=new Map,this.delegatedInteractions=new Map,this.typeById=new Map,this.filters=new Map,this.handleType=this.handleType.bind(this),this.handleMove=this.handleMove.bind(this),this.handleOut=this.handleOut.bind(this),this.hoveredFeatures=new Map,this.prevHoveredFeatures=new Map}add(w,C){if(this.typeById.has(w))throw new Error(`Interaction id "${w}" already exists.`);const O=C.filter;let U=C.type;O&&this.filters.set(w,o.dg(O)),U==="mouseover"&&(U="mouseenter"),U==="mouseout"&&(U="mouseleave");const Y=this.interactionsByType.get(U)||new Map;U==="mouseenter"||U==="mouseleave"?(this.delegatedInteractions.size===0&&(this.map.on("mousemove",this.handleMove),this.map.on("mouseout",this.handleOut)),this.delegatedInteractions.set(w,C)):Y.size===0&&this.map.on(U,this.handleType),Y.size===0&&this.interactionsByType.set(U,Y),Y.set(w,C),this.typeById.set(w,U)}get(w){const C=this.typeById.get(w);if(!C)return;const O=this.interactionsByType.get(C);return O?O.get(w):void 0}remove(w){const C=this.typeById.get(w);if(!C)return;this.typeById.delete(w),this.filters.delete(w);const O=this.interactionsByType.get(C);O&&(O.delete(w),C==="mouseenter"||C==="mouseleave"?(this.delegatedInteractions.delete(w),this.delegatedInteractions.size===0&&(this.map.off("mousemove",this.handleMove),this.map.off("mouseout",this.handleOut))):O.size===0&&this.map.off(C,this.handleType))}queryTargets(w,C){const O=[];for(const[U,Y]of C)Y.target&&O.push({targetId:U,target:Y.target,filter:this.filters.get(U)});return this.map.style.queryRenderedTargets(w,O,this.map.transform)}handleMove(w){this.prevHoveredFeatures=this.hoveredFeatures,this.hoveredFeatures=new Map;const C=this.queryTargets(w.point,Array.from(this.delegatedInteractions).reverse());C.length&&(w.type="mouseenter",this.handleType(w,C));const O=new Map;for(const[U,{feature:Y}]of this.prevHoveredFeatures)this.hoveredFeatures.has(U)||O.set(Y.id,Y);O.size&&(w.type="mouseleave",this.handleType(w,Array.from(O.values())))}handleOut(w){const C=Array.from(this.hoveredFeatures.values()).map(({feature:O})=>O);C.length&&(w.type="mouseleave",this.handleType(w,C)),this.hoveredFeatures.clear()}handleType(w,C){const O=w.type==="mouseenter";if(O&&!this.interactionsByType.has(w.type))return void o.w("mouseenter interaction required for mouseleave to work.");const U=Array.from(this.interactionsByType.get(w.type)).reverse(),Y=!!C;C=C||this.queryTargets(w.point,U);let Z=!1;const se=new Set;for(const pe of C){for(const[je,Ee]of U){if(!Ee.target)continue;const He=pe.variants?pe.variants[je]:null;if(He){for(const qe of He){if(cu(qe,pe,se,je))continue;const et=new o.di(pe,qe),ct=jf(qe,pe,je);Y&&et.id!==void 0&&(et.state=this.map.getFeatureState(et));const ot=O?this.prevHoveredFeatures.get(ct):null,bt=new Ul(w,je,Ee,et),vt=ot?ot.stop:Ee.handler(bt);if(O&&this.hoveredFeatures.set(ct,{feature:pe,stop:vt}),vt!==!1){Z=!0;break}}if(Z)break}}if(Z)break}if(!Z)for(const[pe,je]of U){const{handler:Ee,target:He}=je;if(!He&&Ee(new Ul(w,pe,je,null))!==!1)break}}}function HAe(D,w){if(Array.isArray(D)&&Array.isArray(w)){const C=new Set(D),O=new Set(w);return C.size===O.size&&D.every(U=>O.has(U))}return o.b6(D,w)}const GAe={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},WAe={showCompass:!0,showZoom:!0,visualizePitch:!1};class v6{constructor(w,C,O=!1){this._clickTolerance=10,this.element=C,this.mouseRotate=new bO({clickTolerance:w.dragRotate._mouseRotate._clickTolerance}),this.map=w,O&&(this.mousePitch=new p6({clickTolerance:w.dragRotate._mousePitch._clickTolerance})),o.aZ(["mousedown","mousemove","mouseup","touchstart","touchmove","touchend","reset"],this),C.addEventListener("mousedown",this.mousedown),C.addEventListener("touchstart",this.touchstart,{passive:!1}),C.addEventListener("touchmove",this.touchmove),C.addEventListener("touchend",this.touchend),C.addEventListener("touchcancel",this.reset)}down(w,C){this.mouseRotate.mousedown(w,C),this.mousePitch&&this.mousePitch.mousedown(w,C),A()}move(w,C){const O=this.map,U=this.mouseRotate.mousemoveWindow(w,C),Y=U&&U.bearingDelta;if(Y&&O.setBearing(O.getBearing()+Y),this.mousePitch){const Z=this.mousePitch.mousemoveWindow(w,C),se=Z&&Z.pitchDelta;se&&O.setPitch(O.getPitch()+se)}}off(){const w=this.element;w.removeEventListener("mousedown",this.mousedown),w.removeEventListener("touchstart",this.touchstart),w.removeEventListener("touchmove",this.touchmove),w.removeEventListener("touchend",this.touchend),w.removeEventListener("touchcancel",this.reset),this.offTemp()}offTemp(){T(),window.removeEventListener("mousemove",this.mousemove),window.removeEventListener("mouseup",this.mouseup)}mousedown(w){this.down(Object.assign({},w,{button:w.button,type:w.type,ctrlKey:!0,preventDefault:()=>w.preventDefault()}),M(this.element,w)),window.addEventListener("mousemove",this.mousemove),window.addEventListener("mouseup",this.mouseup)}mousemove(w){this.move(w,M(this.element,w))}mouseup(w){this.mouseRotate.mouseupWindow(w),this.mousePitch&&this.mousePitch.mouseupWindow(w),this.offTemp()}touchstart(w){w.targetTouches.length!==1?this.reset():(this._startPos=this._lastPos=L(this.element,w.targetTouches)[0],this.down({type:"mousedown",button:0,ctrlKey:!0,preventDefault:()=>w.preventDefault()},this._startPos))}touchmove(w){w.targetTouches.length!==1?this.reset():(this._lastPos=L(this.element,w.targetTouches)[0],this.move({buttons:1,preventDefault:()=>w.preventDefault()},this._lastPos))}touchend(w){w.targetTouches.length===0&&this._startPos&&this._lastPos&&this._startPos.dist(this._lastPos)C.width||w.y>C.height;C.locationPoint3D(O).distSqr(w)180;){const O=C.locationPoint3D(D);if(O.x>=0&&O.y>=0&&O.x<=C.width&&O.y<=C.height)break;D.lng>C.center.lng?D.lng-=360:D.lng+=360}return D}const b6={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%)"},cv={rotation:0,rotationAlignment:"auto",pitchAlignment:"auto",occludedOpacity:.2,altitude:0};class S1 extends o.E{constructor(w,C){super(),(w instanceof HTMLElement||C)&&(w=Object.assign({element:w},C)),o.aZ(["_update","_onMove","_onUp","_addDragHandler","_onMapClick","_onKeyPress","_clearFadeTimer"],this);const{anchor:O="center",color:U="#3FB1CE",scale:Y=1,draggable:Z=!1,clickTolerance:se=0,rotation:pe=cv.rotation,rotationAlignment:je=cv.rotationAlignment,pitchAlignment:Ee=cv.pitchAlignment,occludedOpacity:He=cv.occludedOpacity,altitude:qe=cv.altitude}=w||{};this._anchor=O,this._color=U,this._scale=Y,this._draggable=Z,this._clickTolerance=se,this._rotation=pe,this._rotationAlignment=je,this._pitchAlignment=Ee,this._occludedOpacity=He,this._altitude=qe,this._state="inactive",this._isDragging=!1,this._updateMoving=()=>this._update(!0),w&&w.element?(this._element=w.element,this._offset=o.P.convert(w&&w.offset||[0,0])):(this._defaultMarker=!0,this._element=this._createDefaultMarker(),this._offset=o.P.convert(w&&w.offset||[0,-14])),this._element.hasAttribute("aria-label")||this._element.setAttribute("aria-label","Map marker"),this._element.hasAttribute("role")||this._element.setAttribute("role","img"),this._element.classList.add("mapboxgl-marker"),this._element.addEventListener("dragstart",ot=>{ot.preventDefault()}),this._element.addEventListener("mousedown",ot=>{ot.preventDefault()});const et=this._element.classList;for(const ot in b6)et.remove(`mapboxgl-marker-anchor-${ot}`);et.add(`mapboxgl-marker-anchor-${this._anchor}`);const ct=w&&w.className?w.className.trim().split(/\s+/):[];et.add(...ct),this._popup=null}_createDefaultMarker(){const w=y("div"),C=x("svg",{display:"block",height:41*this._scale+"px",width:27*this._scale+"px",viewBox:"0 0 27 41"},w);if(this._altitude===0){const O=x("radialGradient",{id:"shadowGradient"},x("defs",{},C));x("stop",{offset:"10%","stop-opacity":.4},O),x("stop",{offset:"100%","stop-opacity":.05},O),x("ellipse",{cx:13.5,cy:34.8,rx:10.5,ry:5.25,fill:"url(#shadowGradient)"},C)}return x("path",{fill:this._color,d:"M27,13.5C27,19.07 20.25,27 14.75,34.5C14.02,35.5 12.98,35.5 12.25,34.5C6.75,27 0,19.22 0,13.5C0,6.04 6.04,0 13.5,0C20.96,0 27,6.04 27,13.5Z"},C),x("path",{opacity:.25,d:"M13.5,0C6.04,0 0,6.04 0,13.5C0,19.22 6.75,27 12.25,34.5C13,35.52 14.02,35.5 14.75,34.5C20.25,27 27,19.07 27,13.5C27,6.04 20.96,0 13.5,0ZM13.5,1C20.42,1 26,6.58 26,13.5C26,15.9 24.5,19.18 22.22,22.74C19.95,26.3 16.71,30.14 13.94,33.91C13.74,34.18 13.61,34.32 13.5,34.44C13.39,34.32 13.26,34.18 13.06,33.91C10.28,30.13 7.41,26.31 5.02,22.77C2.62,19.23 1,15.95 1,13.5C1,6.58 6.58,1 13.5,1Z"},C),x("circle",{fill:"white",cx:13.5,cy:13.5,r:5.5},C),w}addTo(w){return w===this._map||(this.remove(),this._map=w,w.getCanvasContainer().appendChild(this._element),w.on("move",this._updateMoving),w.on("moveend",this._update),w.on("remove",this._clearFadeTimer),w._addMarker(this),this.setDraggable(this._draggable),this._update(),w.on("click",this._onMapClick)),this}remove(){const w=this._map;return w&&(w.off("click",this._onMapClick),w.off("move",this._updateMoving),w.off("moveend",this._update),w.off("mousedown",this._addDragHandler),w.off("touchstart",this._addDragHandler),w.off("mouseup",this._onUp),w.off("touchend",this._onUp),w.off("mousemove",this._onMove),w.off("touchmove",this._onMove),w.off("remove",this._clearFadeTimer),w._removeMarker(this),this._map=void 0),this._clearFadeTimer(),this._element.remove(),this._popup&&this._popup.remove(),this}getLngLat(){return this._lngLat}setLngLat(w){return this._lngLat=o.aU.convert(w),this._pos=null,this._popup&&this._popup.setLngLat(this._lngLat),this._update(!0),this}setAltitude(w){return w===this._altitude||(this._defaultMarker&&(this._altitude===0&&w!==0||this._altitude!==0&&w===0)&&(this._element=this._createDefaultMarker()),this._altitude=w||cv.altitude,this._update()),this}getAltitude(){return this._altitude}getElement(){return this._element}setPopup(w){if(this._popup&&(this._popup.remove(),this._popup=null,this._element.removeAttribute("role"),this._element.removeEventListener("keypress",this._onKeyPress),this._originalTabIndex||this._element.removeAttribute("tabindex")),w){if(!("offset"in w.options)){const U=Math.sqrt(Math.pow(13.5,2)/2);w.options.offset=this._defaultMarker?{top:[0,0],"top-left":[0,0],"top-right":[0,0],bottom:[0,-38.1],"bottom-left":[U,-1*(38.1-13.5+U)],"bottom-right":[-U,-1*(38.1-13.5+U)],left:[13.5,-1*(38.1-13.5)],right:[-13.5,-1*(38.1-13.5)]}:this._offset}this._popup=w,w._marker=this,w._altitude=this._altitude,this._lngLat&&this._popup.setLngLat(this._lngLat),this._element.setAttribute("role","button"),this._originalTabIndex=this._element.getAttribute("tabindex"),this._originalTabIndex||this._element.setAttribute("tabindex","0"),this._element.addEventListener("keypress",this._onKeyPress),this._element.setAttribute("aria-expanded","false")}return this}_onKeyPress(w){const C=w.code,O=w.charCode||w.keyCode;C!=="Space"&&C!=="Enter"&&O!==32&&O!==13||this.togglePopup()}_onMapClick(w){const C=w.originalEvent.target,O=this._element;this._popup&&(C===O||O.contains(C))&&this.togglePopup()}getPopup(){return this._popup}togglePopup(){const w=this._popup;return w?(w.isOpen()?(w.remove(),this._element.setAttribute("aria-expanded","false")):this._map&&(w.addTo(this._map),this._element.setAttribute("aria-expanded","true")),this):this}_behindTerrain(){const w=this._map,C=this._pos;if(!w||!C)return!1;const O=w.unproject(C,this._altitude),U=w.getFreeCameraOptions();if(!U.position)return!1;const Y=U.position.toLngLat();return Y.distanceTo(O)<.9*Y.distanceTo(this._lngLat)}_evaluateOpacity(){const w=this._map;if(!w)return;const C=this._pos;if(!C||C.x<0||C.x>w.transform.width||C.y<0||C.y>w.transform.height)return void this._clearFadeTimer();const O=w.unproject(C,this._altitude);let U;w._showingGlobe()&&o.e$(w.transform,this._lngLat)?U=0:(U=1-w._queryFogOpacity(O),w.transform._terrainEnabled()&&w.getTerrain()&&this._behindTerrain()&&(U*=this._occludedOpacity)),this._element.style.opacity=`${U}`,this._element.style.pointerEvents=U>0?"auto":"none",this._popup&&this._popup._setOpacity(U),this._fadeTimer=null}_clearFadeTimer(){this._fadeTimer&&(clearTimeout(this._fadeTimer),this._fadeTimer=null)}_updateDOM(){const w=this._pos;if(!w||!this._map)return;const C=this._offset.mult(this._scale);this._element.style.transform=` translate(${w.x}px,${w.y}px) ${b6[this._anchor]} ${this._calculateXYTransform()} ${this._calculateZTransform()} translate(${C.x}px,${C.y}px) `}_calculateXYTransform(){const w=this._pos,C=this._map,O=this.getPitchAlignment();if(!C||!w||O!=="map")return"";if(!C._showingGlobe()){const pe=C.getPitch();return pe?`rotateX(${pe}deg)`:""}const U=o.cH(o.f0(C.transform,this._lngLat)),Y=w.sub(o.f1(C.transform)),Z=Math.abs(Y.x)+Math.abs(Y.y);if(Z===0)return"";const se=U/Z;return`rotateX(${-Y.y*se}deg) rotateY(${Y.x*se}deg)`}_calculateZTransform(){const w=this._pos,C=this._map;if(!C||!w)return"";let O=0;const U=this.getRotationAlignment();if(U==="map")if(C._showingGlobe()){const Y=C.project(new o.aU(this._lngLat.lng,this._lngLat.lat+.001),this._altitude),Z=C.project(new o.aU(this._lngLat.lng,this._lngLat.lat-.001),this._altitude).sub(Y);O=o.cH(Math.atan2(Z.y,Z.x))-90}else O=-C.getBearing();else if(U==="horizon"){const Y=o.aj(4,6,C.getZoom()),Z=o.f1(C.transform);Z.y+=Y*C.transform.height;const se=w.sub(Z),pe=o.cH(Math.atan2(se.y,se.x));O=(pe>90?pe-270:pe+90)*(1-Y)}return O+=this._rotation,O?`rotateZ(${O}deg)`:""}_update(w){cancelAnimationFrame(this._updateFrameId);const C=this._map;C&&(C.transform.renderWorldCopies&&(this._lngLat=jq(this._lngLat,this._pos,C.transform)),this._pos=C.project(this._lngLat,this._altitude),w===!0?this._updateFrameId=requestAnimationFrame(()=>{this._element&&this._pos&&this._anchor&&(this._pos=this._pos.round(),this._updateDOM())}):this._pos=this._pos.round(),C._requestDomTask(()=>{this._map&&(this._element&&this._pos&&this._anchor&&this._updateDOM(),(C._showingGlobe()||C.getTerrain()||C.getFog())&&!this._fadeTimer&&(this._fadeTimer=window.setTimeout(this._evaluateOpacity.bind(this),60)))}))}getOffset(){return this._offset}setOffset(w){return this._offset=o.P.convert(w),this._update(),this}addClassName(w){return this._element.classList.add(w),this}removeClassName(w){return this._element.classList.remove(w),this}toggleClassName(w){return this._element.classList.toggle(w)}_onMove(w){const C=this._map;if(!C)return;const O=this._pointerdownPos,U=this._positionDelta;if(O&&U){if(!this._isDragging){const Y=this._clickTolerance||C._clickTolerance;if(w.point.dist(O)D.maxZoom)throw new Error("maxZoom must be greater than or equal to minZoom");if(D.minPitch!=null&&D.maxPitch!=null&&D.minPitch>D.maxPitch)throw new Error("maxPitch must be greater than or equal to minPitch");if(D.minPitch!=null&&D.minPitch<0)throw new Error("minPitch must be greater than or equal to 0");if(D.maxPitch!=null&&D.maxPitch>85)throw new Error("maxPitch must be less than or equal to 85");D.antialias&&o.eZ(window)&&(D.antialias=!1,o.w("Antialiasing is disabled for this WebGL context to avoid browser bug: https://github.com/mapbox/mapbox-gl-js/issues/11609")),super(new uu(D.minZoom,D.maxZoom,D.minPitch,D.maxPitch,D.renderWorldCopies,null,null),D),this._repaint=!!D.repaint,this._interactive=D.interactive,this._minTileCacheSize=D.minTileCacheSize,this._maxTileCacheSize=D.maxTileCacheSize,this._failIfMajorPerformanceCaveat=D.failIfMajorPerformanceCaveat,this._preserveDrawingBuffer=D.preserveDrawingBuffer,this._antialias=D.antialias,this._trackResize=D.trackResize,this._bearingSnap=D.bearingSnap,this._refreshExpiredTiles=D.refreshExpiredTiles,this._fadeDuration=D.fadeDuration,this._isInitialLoad=!0,this._crossSourceCollisions=D.crossSourceCollisions,this._collectResourceTiming=D.collectResourceTiming,this._language=this._parseLanguage(D.language),this._worldview=D.worldview,this._renderTaskQueue=new YJ,this._domRenderTaskQueue=new YJ,this._controls=[],this._markers=[],this._popups=[],this._mapId=o.r(),this._locale=Object.assign({},VAe,D.locale),this._clickTolerance=D.clickTolerance,this._cooperativeGestures=D.cooperativeGestures,this._performanceMetricsCollection=D.performanceMetricsCollection,this._tessellationStep=D.tessellationStep,this._containerWidth=0,this._containerHeight=0,this._showParseStatus=!0,this._precompilePrograms=D.precompilePrograms,this._averageElevationLastSampledAt=-1/0,this._averageElevationExaggeration=0,this._averageElevation=new qAe(0),this._interactionRange=[1/0,-1/0],this._visibilityHidden=0,this._useExplicitProjection=!1,this._frameId=0,this._scaleFactor=D.scaleFactor,this._requestManager=new G(D.transformRequest,D.accessToken,D.testMode);const C=ue(D.accessToken||o.g.ACCESS_TOKEN);if(C&&"atlas"in C&&typeof C.atlas=="number"&&(this._tokenExpiration=C.atlas),this._silenceAuthErrors=!!D.testMode,this._contextCreateOptions=D.contextCreateOptions?Object.assign({},D.contextCreateOptions):{},typeof D.container=="string"){const O=document.getElementById(D.container);if(!O)throw new Error(`Container '${D.container.toString()}' not found.`);this._container=O}else{if(!(D.container instanceof HTMLElement))throw new Error("Invalid type: 'container' must be a String or HTMLElement.");this._container=D.container}if(this._container.childNodes.length>0&&o.w("The map container element should be empty, otherwise the map's interactivity will be negatively impacted. If you want to display a message when WebGL is not supported, use the Mapbox GL Supported plugin instead."),D.maxBounds&&this.setMaxBounds(D.maxBounds),this._spriteFormat="auto",o.aZ(["_onWindowOnline","_onWindowResize","_onVisibilityChange","_onMapScroll","_contextLost","_contextRestored"],this),this._setupContainer(),this._setupPainter(),this.painter===void 0)throw new Error("Failed to initialize WebGL.");if(this.on("move",()=>this._update(!1)),this.on("moveend",()=>this._update(!1)),this.on("zoom",()=>this._update(!0)),this._fullscreenchangeEvent="onfullscreenchange"in document?"fullscreenchange":"webkitfullscreenchange",window.addEventListener("online",this._onWindowOnline,!1),window.addEventListener("resize",this._onWindowResize,!1),window.addEventListener("orientationchange",this._onWindowResize,!1),window.addEventListener(this._fullscreenchangeEvent,this._onWindowResize,!1),window.addEventListener("visibilitychange",this._onVisibilityChange,!1),this.handlers=new WJ(this,D),this._localFontFamily=D.localFontFamily,this._localIdeographFontFamily=D.localIdeographFontFamily,this._useServerFontComposition=D.useServerFontComposition,(D.style||!D.testMode)&&this.setStyle(D.style||o.g.DEFAULT_STYLE,{config:D.config,localFontFamily:this._localFontFamily,localIdeographFontFamily:this._localIdeographFontFamily,useServerFontComposition:this._useServerFontComposition}),D.projection&&this.setProjection(D.projection),D.hash&&(this._hash=new Du(typeof D.hash=="string"&&D.hash||void 0).addTo(this)),!this._hash||!this._hash._onHashChange()){w.center==null&&w.zoom==null||(this.transform._unmodified=!1),this.jumpTo({center:D.center,zoom:D.zoom,bearing:D.bearing,pitch:D.pitch});const O=D.bounds;O&&(this.resize(),this.fitBounds(O,Object.assign({},D.fitBoundsOptions,{duration:0})))}this.resize(),D.attributionControl&&this.addControl(new _q({customAttribution:D.customAttribution})),this._logoControl=new wq,this.addControl(this._logoControl,D.logoPosition),this.on("style.load",()=>{this.transform.unmodified&&this.jumpTo(this.style.stylesheet),this._postStyleLoadEvent(),this._postStyleWithAppearanceEvent()}),this.on("data",O=>{this._update(O.dataType==="style"),this.fire(new o.C(`${O.dataType}data`,O))}),this.on("dataloading",O=>{this.fire(new o.C(`${O.dataType}dataloading`,O))}),this._interactions=new SO(this)}_getMapId(){return this._mapId}addControl(D,w){if(w===void 0&&(w=D.getDefaultPosition?D.getDefaultPosition():"top-right"),!D||!D.onAdd)return this.fire(new o.B(new Error("Invalid argument to map.addControl(). Argument must be a control with onAdd and onRemove methods.")));const C=D.onAdd(this);this._controls.push(D);const O=this._controlPositions[w];return w.indexOf("bottom")!==-1?O.insertBefore(C,O.firstChild):O.appendChild(C),this}removeControl(D){if(!D||!D.onRemove)return this.fire(new o.B(new Error("Invalid argument to map.removeControl(). Argument must be a control with onAdd and onRemove methods.")));const w=this._controls.indexOf(D);return w>-1&&this._controls.splice(w,1),D.onRemove(this),this}hasControl(D){return this._controls.indexOf(D)>-1}getContainer(){return this._container}getCanvasContainer(){return this._canvasContainer}getCanvas(){return this._canvas}resize(D){if(this._updateContainerDimensions(),this._containerWidth===this.transform.width&&this._containerHeight===this.transform.height)return this;this._resizeCanvas(this._containerWidth,this._containerHeight),this.transform.resize(this._containerWidth,this._containerHeight),this.painter.resize(Math.ceil(this._containerWidth),Math.ceil(this._containerHeight));const w=!this._moving;return w&&this.fire(new o.C("movestart",D)).fire(new o.C("move",D)),this.fire(new o.C("resize",D)),w&&this.fire(new o.C("moveend",D)),this}getBounds(){return this.transform.getBounds()}getMaxBounds(){return this.transform.getMaxBounds()||null}setMaxBounds(D){return this.transform.setMaxBounds(o.aK.convert(D)),this._update()}setMinZoom(D){if((D=D??-2)>=-2&&D<=this.transform.maxZoom)return this.transform.minZoom=D,this._update(),this.getZoom()=this.transform.minZoom)return this.transform.maxZoom=D,this._update(),this.getZoom()>D?this.setZoom(D):this.fire(new o.C("zoomstart")).fire(new o.C("zoom")).fire(new o.C("zoomend")),this;throw new Error("maxZoom must be greater than the current minZoom")}getMaxZoom(){return this.transform.maxZoom}setMinPitch(D){if((D=D??0)<0)throw new Error("minPitch must be greater than or equal to 0");if(D>=0&&D<=this.transform.maxPitch)return this.transform.minPitch=D,this._update(),this.getPitch()85)throw new Error("maxPitch must be less than or equal to 85");if(D>=this.transform.minPitch)return this.transform.maxPitch=D,this._update(),this.getPitch()>D?this.setPitch(D):this.fire(new o.C("pitchstart")).fire(new o.C("pitch")).fire(new o.C("pitchend")),this;throw new Error("maxPitch must be greater than or equal to minPitch")}getMaxPitch(){return this.transform.maxPitch}getScaleFactor(){return this._scaleFactor}setScaleFactor(D){return this._scaleFactor=D,this.painter.scaleFactor=D,this.style&&this.style._setLabelPlacementStale(),this.style._updateFilteredLayers(w=>w.type==="symbol"),this._update(!0),this}getRenderWorldCopies(){return this.transform.renderWorldCopies}setRenderWorldCopies(D){return this.transform.renderWorldCopies=D,this.transform.renderWorldCopies||this._forceMarkerAndPopupUpdate(!0),this._update()}getLanguage(){return this._language}_parseLanguage(D){return D==="auto"?navigator.language:Array.isArray(D)?D.length===0?void 0:D.map(w=>w==="auto"?navigator.language:w):D}setLanguage(D){const w=this._parseLanguage(D);if(!this.style||w===this._language)return this;this._language=w,this.style.reloadSources();for(const C of this._controls)C._setLanguage&&C._setLanguage(this._language);return this}getWorldview(){return this._worldview}setWorldview(D){return this.style&&D!==this._worldview?(this._worldview=D,this._styleDirty=!0,this.style.setWorldview(D),this):this}getProjection(){return this.transform.mercatorFromTransition?{name:"globe",center:[0,0]}:this.transform.getProjection()}_showingGlobe(){return this.transform.projection.name==="globe"}setProjection(D){return this._lazyInitEmptyStyle(),D?typeof D=="string"&&(D={name:D}):D=null,this._useExplicitProjection=!!D,this._prioritizeAndUpdateProjection(D,this.style.projection)}_updateProjectionTransition(){if(this.getProjection().name!=="globe")return;const D=this.transform,w=D.projection.name;let C;w==="globe"&&D.zoom>=o.cv?(D.setMercatorFromTransition(),C=!0):w==="mercator"&&D.zoom=o.cv?this.transform.setMercatorFromTransition():this.transform.setProjection(D),this.style.applyProjectionUpdate();const O=this.transform.getProjection().name==="mercator"&&C!==this.transform.mercatorFromTransition;return(w||O)&&(this.painter.clearBackgroundTiles(),this.style.clearSources(),this._update(!0),this._forceMarkerAndPopupUpdate(!0)),this}project(D,w){return this.transform.locationPoint3D(o.aU.convert(D),w)}unproject(D,w){return this.transform.pointLocation3D(o.P.convert(D),w)}isMoving(){return this._moving||this.handlers&&this.handlers.isMoving()||!1}isZooming(){return this._zooming||this.handlers&&this.handlers.isZooming()||!1}isRotating(){return this._rotating||this.handlers&&this.handlers.isRotating()||!1}_isDragging(){return this.handlers&&this.handlers._isDragging()||!1}_createDelegatedListener(D,w,C){const O=U=>{let Y=[];if(Array.isArray(w)){const Z=w.filter(se=>this.getLayer(se));Y=Z.length?this.queryRenderedFeatures(U,{layers:Z}):[]}else Y=this.queryRenderedFeatures(U,{target:w});return Y};if(D==="mouseenter"||D==="mouseover"){let U=!1;return{listener:C,targets:w,delegates:{mousemove:Z=>{const se=O(Z.point);se.length?U||(U=!0,C.call(this,new Yi(D,this,Z.originalEvent,{features:se}))):U=!1},mouseout:()=>{U=!1}}}}if(D==="mouseleave"||D==="mouseout"){let U=!1;return{listener:C,targets:w,delegates:{mousemove:se=>{O(se.point).length?U=!0:U&&(U=!1,C.call(this,new Yi(D,this,se.originalEvent)))},mouseout:se=>{U&&(U=!1,C.call(this,new Yi(D,this,se.originalEvent)))}}}}{const U=Y=>{const Z=O(Y.point);Z.length&&(Y.features=Z,C.call(this,Y),delete Y.features)};return{listener:C,targets:w,delegates:{[D]:U}}}}on(D,w,C){if(typeof w=="function"||C===void 0)return super.on(D,w);if(typeof w=="string"&&(w=[w]),!this._areTargetsValid(w))return this;const O=this._createDelegatedListener(D,w,C);this._delegatedListeners=this._delegatedListeners||{},this._delegatedListeners[D]=this._delegatedListeners[D]||[],this._delegatedListeners[D].push(O);for(const U in O.delegates)this.on(U,O.delegates[U]);return this}once(D,w,C){if(typeof w=="function"||C===void 0)return super.once(D,w);if(typeof w=="string"&&(w=[w]),!this._areTargetsValid(w))return this;const O=this._createDelegatedListener(D,w,C);for(const U in O.delegates)this.once(U,O.delegates[U]);return this}off(D,w,C){if(typeof w=="function"||C===void 0)return super.off(D,w);if(typeof w=="string"&&(w=[w]),!this._areTargetsValid(w))return this;const O=this._delegatedListeners?this._delegatedListeners[D]:void 0;return O&&(U=>{for(let Y=0;Y{if(C){const U=typeof C=="string"?C:C instanceof Error?C.message:C.error;o.w(`Unable to perform style diff: ${U}. Rebuilding the style from scratch.`),this._updateStyle(D,w)}else O&&this._update(!0)},()=>this._postStyleLoadEvent()),this):(this._localIdeographFontFamily=w.localIdeographFontFamily,this._localFontFamily=w.localFontFamily,this._updateStyle(D,w))}_getUIString(D){const w=this._locale[D];if(w==null)throw new Error(`Missing UI string '${D}'`);return w}_updateStyle(D,w){if(this.style&&(this.style.setEventedParent(null),this.style._remove(),this.style=void 0),D){const C=Object.assign({},w);w&&w.config&&(C.initialConfig=w.config,delete C.config),this.style=new mu(this,C).load(D),this.style.setEventedParent(this,{style:this.style})}return this._updateTerrain(),this}_lazyInitEmptyStyle(){this.style||(this.style=new mu(this,{}),this.style.setEventedParent(this,{style:this.style}),this.style.loadEmpty())}getStyle(){if(this.style)return this.style.serialize()}isStyleLoaded(){return this.style?this.style.loaded():(o.w("There is no style added to the map."),!1)}_isValidId(D){return D==null?(this.fire(new o.B(new Error("IDs can't be empty."))),!1):!o.db(D)||(this.fire(new o.B(new Error(`IDs can't contain special symbols: "${D}".`))),!1)}_isTargetValid(D){return"featuresetId"in D?this._isValidId("importId"in D?D.importId:D.featuresetId):"layerId"in D&&this._isValidId(D.layerId)}_areTargetsValid(D){if(Array.isArray(D)){for(const w of D)if(!this._isValidId(w))return!1;return!0}return this._isTargetValid(D)}addSource(D,w){return this._isValidId(D)?(this._lazyInitEmptyStyle(),this.style.addSource(D,w),this._update(!0)):this}isSourceLoaded(D){return!!this._isValidId(D)&&!!this.style&&this.style._isSourceCacheLoaded(D)}areTilesLoaded(){return this.style.areTilesLoaded()}addSourceType(D,w,C){this._lazyInitEmptyStyle(),this.style.addSourceType(D,w,C)}removeSource(D){return this._isValidId(D)?(this.style.removeSource(D),this._updateTerrain(),this._update(!0)):this}getSource(D){return this._isValidId(D)?this.style.getOwnSource(D):null}addImage(D,w,{pixelRatio:C=1,sdf:O=!1,stretchX:U,stretchY:Y,content:Z}={}){this._lazyInitEmptyStyle();const se=o.I.from(D);if(w instanceof HTMLImageElement||ImageBitmap&&w instanceof ImageBitmap){const{width:pe,height:je,data:Ee}=o.o.getImageData(w);this.style.addImage(se,{data:new o.q({width:pe,height:je},Ee),pixelRatio:C,stretchX:U,stretchY:Y,content:Z,sdf:O,version:0,usvg:!1})}else if(w.width===void 0||w.height===void 0)this.fire(new o.B(new Error("Invalid arguments to map.addImage(). The second argument must be an `HTMLImageElement`, `ImageData`, `ImageBitmap`, or object with `width`, `height`, and `data` properties with the same format as `ImageData`")));else{const{width:pe,height:je}=w,Ee=w;this.style.addImage(se,{data:new o.q({width:pe,height:je},new Uint8Array(Ee.data)),pixelRatio:C,stretchX:U,stretchY:Y,content:Z,sdf:O,usvg:!1,version:0,userImage:Ee}),Ee.onAdd&&Ee.onAdd(this,D)}}updateImage(D,w){this._lazyInitEmptyStyle();const C=o.I.from(D),O=this.style.getImage(C);if(!O)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 U=w instanceof HTMLImageElement||ImageBitmap&&w instanceof ImageBitmap?o.o.getImageData(w):w,{width:Y,height:Z,data:se}=U;if(Y===void 0||Z===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(Y!==(O.usvg?O.icon.usvg_tree.width:O.data.width)||Z!==(O.usvg?O.icon.usvg_tree.height:O.data.height))return void this.fire(new o.B(new Error(`The width and height of the updated image (${Y}, ${Z}) must be that same as the previous version of the image (${O.data.width}, ${O.data.height})`)));const pe=!(w instanceof HTMLImageElement||ImageBitmap&&w instanceof ImageBitmap);let je=!1;O.usvg?(O.data=new o.q({width:Y,height:Z},new Uint8Array(se)),O.usvg=!1,O.icon=void 0,je=!0):O.data.replace(se,pe),this.style.updateImage(C,O,je)}hasImage(D){return D?!!this.style&&!!this.style.getImage(o.I.from(D)):(this.fire(new o.B(new Error("Missing required image id"))),!1)}removeImage(D){this.style.removeImage(o.I.from(D))}loadImage(D,w){o.n(this._requestManager.transformRequest(D,o.R.Image),(C,O)=>{w(C,O)})}listImages(){return this.style.listImages().map(D=>D.name)}addModel(D,w){this._lazyInitEmptyStyle(),this.style.addModel(D,w)}hasModel(D){return D?this.style.hasModel(D):(this.fire(new o.B(new Error("Missing required model id"))),!1)}removeModel(D){this.style.removeModel(D)}listModels(){return this.style.listModels()}addLayer(D,w){return this._isValidId(D.id)?(this._lazyInitEmptyStyle(),this.style.addLayer(D,w),this._update(!0)):this}getSlot(D){const w=this.getLayer(D);return w&&w.slot||null}setSlot(D,w){return this.style.setSlot(D,w),this.style.mergeLayers(),this._update(!0)}addImport(D,w){return this.style.addImport(D,w).catch(C=>this.fire(new o.B(new Error("Failed to add import",C)))),this}updateImport(D,w){return typeof w!="string"&&w.id!==D?(this.removeImport(D),this.addImport(w)):(this.style.updateImport(D,w),this._update(!0))}removeImport(D){return this.style.removeImport(D),this}moveImport(D,w){return this.style.moveImport(D,w),this._update(!0)}moveLayer(D,w){return this._isValidId(D)?(this.style.moveLayer(D,w),this._update(!0)):this}removeLayer(D){return this._isValidId(D)?(this.style.removeLayer(D),this._update(!0)):this}getLayer(D){if(!this._isValidId(D))return null;const w=this.style.getOwnLayer(D);return w?w.type==="custom"?w.implementation:w.serialize():void 0}getSlots(){return this.style.getSlots()}setLayerZoomRange(D,w,C){return this._isValidId(D)?(this.style.setLayerZoomRange(D,w,C),this._update(!0)):this}setFilter(D,w,C={}){return this._isValidId(D)?(this.style.setFilter(D,w,C),this._update(!0)):this}getFilter(D){return this._isValidId(D)?this.style.getFilter(D):null}setPaintProperty(D,w,C,O={}){return this._isValidId(D)?(this.style.setPaintProperty(D,w,C,O),this._update(!0)):this}getPaintProperty(D,w){return this._isValidId(D)?this.style.getPaintProperty(D,w):null}setLayoutProperty(D,w,C,O={}){return this._isValidId(D)?(this.style.setLayoutProperty(D,w,C,O),this._update(!0)):this}getLayoutProperty(D,w){return this._isValidId(D)?this.style.getLayoutProperty(D,w):null}setLayerProperty(D,w,C,O={}){return this._isValidId(D)?(w==="appearances"&&this._postAddingAppearancesToStyleEvent(),this.style.setLayerProperty(D,w,C,O),this._update(!0)):this}getGlyphsUrl(){return this.style.getGlyphsUrl()}setGlyphsUrl(D){return this.style.setGlyphsUrl(D),this._update(!0)}getSchema(D){return this.style.getSchema(D)}setSchema(D,w){return this.style.setSchema(D,w),this._update(!0)}getConfig(D){return this.style.getConfig(D)}setConfig(D,w){return this.style.setConfig(D,w),this._update(!0)}getConfigProperty(D,w){return this.style.getConfigProperty(D,w)}setConfigProperty(D,w,C){return this.style.setConfigProperty(D,w,C),this._update(!0)}getFeaturesetDescriptors(D){return this.style.getFeaturesetDescriptors(D)}setLights(D){if(this._lazyInitEmptyStyle(),D&&D.length===1&&D[0].type==="flat"){const w=D[0];w.properties?this.style.setFlatLight(w.properties,w.id,{}):this.style.setFlatLight({},"flat")}else this.style.setLights(D),this.painter.terrain&&(this.painter.terrain.invalidateRenderCache=!0);return this._update(!0)}getLights(){const D=this.style.getLights()||[];return D.length===0&&D.push({id:this.style.light.id,type:"flat",properties:this.style.getFlatLight()}),D}setLight(D,w={}){return console.log("The `map.setLight` function is deprecated, prefer using `map.setLights` with `flat` light type instead."),this.setLights([{id:"flat",type:"flat",properties:D}])}getLight(){return console.log("The `map.getLight` function is deprecated, prefer using `map.getLights` instead."),this.style.getFlatLight()}setTerrain(D){return this._lazyInitEmptyStyle(),!D&&this.transform.projection.requiresDraping?this.style.setTerrainForDraping():this.style.setTerrain(D),this._averageElevationLastSampledAt=-1/0,this._update(!0)}getTerrain(){return this.style?this.style.getTerrain():null}setFog(D){return this._lazyInitEmptyStyle(),this.style.setFog(D),this._update(!0)}getFog(){return this.style?this.style.getFog():null}setSnow(D){return this._lazyInitEmptyStyle(),this.style.setSnow(D),this._update(!0)}getSnow(){return this.style?this.style.getSnow():null}setRain(D){return this._lazyInitEmptyStyle(),this.style.setRain(D),this._update(!0)}getRain(){return this.style?this.style.getRain():null}setColorTheme(D){return this._lazyInitEmptyStyle(),this.style.setColorTheme(D),this._update(!0)}setImportColorTheme(D,w){return this._lazyInitEmptyStyle(),this.style.setImportColorTheme(D,w),this._update(!0)}setCamera(D){return this.style.setCamera(D),this._triggerCameraUpdate(D)}getNearClipOffset(){return this.transform.nearClipOffset}setNearClipOffset(D){const w=this.transform.nearClipOffset!==D;return this.transform.nearClipOffset=D,this._update(w)}_triggerCameraUpdate(D){return this._update(this.transform.setOrthographicProjectionAtLowPitch(D["camera-projection"]==="orthographic"))}getCamera(){return this.style.camera}_queryFogOpacity(D){return this.style&&this.style.fog?this.style.fog.getOpacityAtLatLng(o.aU.convert(D),this.transform):0}setFeatureState(D,w){return D.source&&!this._isValidId(D.source)?this:(this.style.setFeatureState(D,w),this._update())}removeFeatureState(D,w){return D.source&&!this._isValidId(D.source)?this:(this.style.removeFeatureState(D,w),this._update())}getFeatureState(D){return D.source&&!this._isValidId(D.source)?null:this.style.getFeatureState(D)}_selectIndoorFloor(D){this.style.indoorManager.selectFloor(D)}_setIndoorActiveFloorsVisibility(D){this.style.indoorManager.setActiveFloorsVisibility(D)}getIndoorTileOptions(D,w){return this.style.isIndoorEnabled()?this.style.indoorManager.getIndoorTileOptions(D,w):null}_updateContainerDimensions(){if(!this._container)return;const D=this._container.getBoundingClientRect().width||400,w=this._container.getBoundingClientRect().height||300;let C,O,U,Y=this._container;for(;Y&&(!O||!U);){const Z=window.getComputedStyle(Y).transform;Z&&Z!=="none"&&(C=Z.match(/matrix.*\((.+)\)/)[1].split(", "),C[0]&&C[0]!=="0"&&C[0]!=="1"&&(O=C[0]),C[3]&&C[3]!=="0"&&C[3]!=="1"&&(U=C[3])),Y=Y.parentElement}this._containerWidth=O?Math.abs(D/O):D,this._containerHeight=U?Math.abs(w/U):w}_detectMissingCSS(){window.getComputedStyle(this._missingCSSCanary).getPropertyValue("background-color")!=="rgb(250, 128, 114)"&&o.w("This page appears to be missing CSS declarations for Mapbox GL JS, which may cause the map to display incorrectly. Please ensure your page includes mapbox-gl.css, as described in https://www.mapbox.com/mapbox-gl-js/api/.")}_setupContainer(){const D=this._container;D.classList.add("mapboxgl-map"),(this._missingCSSCanary=y("div","mapboxgl-canary",D)).style.visibility="hidden",this._detectMissingCSS();const w=this._canvasContainer=y("div","mapboxgl-canvas-container",D);this._canvas=y("canvas","mapboxgl-canvas",w),this._interactive&&(w.classList.add("mapboxgl-interactive"),this._canvas.setAttribute("tabindex","0")),this._canvas.addEventListener("webglcontextlost",this._contextLost,!1),this._canvas.addEventListener("webglcontextrestored",this._contextRestored,!1),this._canvas.setAttribute("aria-label",this._getUIString("Map.Title")),this._canvas.setAttribute("role","region"),this._updateContainerDimensions(),this._resizeCanvas(this._containerWidth,this._containerHeight);const C=this._controlContainer=y("div","mapboxgl-control-container",D),O=this._controlPositions={};["top-left","top","top-right","right","bottom-right","bottom","bottom-left","left"].forEach(U=>{O[U]=y("div",`mapboxgl-ctrl-${U}`,C)}),this._container.addEventListener("scroll",this._onMapScroll,!1)}_resizeCanvas(D,w){const C=o.o.devicePixelRatio||1;this._canvas.width=C*Math.ceil(D),this._canvas.height=C*Math.ceil(w),this._canvas.style.width=`${D}px`,this._canvas.style.height=`${w}px`}_addMarker(D){this._markers.push(D)}_removeMarker(D){const w=this._markers.indexOf(D);w!==-1&&this._markers.splice(w,1)}_addPopup(D){this._popups.push(D)}_removePopup(D){const w=this._popups.indexOf(D);w!==-1&&this._popups.splice(w,1)}_setupPainter(){const D=Object.assign({},g.supported.webGLContextAttributes,{failIfMajorPerformanceCaveat:this._failIfMajorPerformanceCaveat,preserveDrawingBuffer:this._preserveDrawingBuffer,antialias:this._antialias||!1}),w=this._canvas.getContext("webgl2",D);w?($e(w,!0),this.painter=new ol(w,this._contextCreateOptions,this.transform,this._scaleFactor,this._worldview),this.on("data",C=>{if(C.dataType==="source"){const O=this.transform.elevation?this.transform.elevation._source():null;O&&C.sourceCacheId===O.id&&this.style&&this.style._setLabelPlacementStale(),this.painter.setTileLoadedFlag(!0)}}),o.k.testSupport(w)):this.fire(new o.B(new Error("Failed to initialize WebGL")))}_contextLost(D){D.preventDefault(),this._frame&&(this._frame.cancel(),this._frame=null),this.fire(new o.C("webglcontextlost",{originalEvent:D}))}_contextRestored(D){this._setupPainter(),this.painter.resize(Math.ceil(this._containerWidth),Math.ceil(this._containerHeight)),this._updateTerrain(),this.style&&(this.style.clearLayers(),this.style.imageManager.destroyAtlasTextures(),this.style.imageManager.imageAtlasCache.destroyTextures(),this.style.reloadModels(),this.style.clearSources()),this._update(),this.fire(new o.C("webglcontextrestored",{originalEvent:D}))}_onMapScroll(D){if(D.target===this._container)return this._container.scrollTop=0,this._container.scrollLeft=0,!1}idle(){return!this.isMoving()&&this.loaded()}loaded(){return!this._styleDirty&&!this._sourcesDirty&&!!this.style&&this.style.loaded()}frameReady(){return this.loaded()&&!this._placementDirty}_update(D){return this.style?(this._styleDirty=this._styleDirty||D,this._sourcesDirty=!0,this.triggerRepaint(),this):this}_requestRenderFrame(D){return this._update(),this._renderTaskQueue.add(D)}_cancelRenderFrame(D){this._renderTaskQueue.remove(D)}_requestDomTask(D){!this.loaded()||this.loaded()&&!this.isMoving()?D():this._domRenderTaskQueue.add(D)}_render(D){let w;this.fire(new o.C("renderstart")),++this._frameId;const C=this.painter.context.extTimerQuery,O=o.o.now(),U=this.painter.context.gl;if(this.listens("gpu-timing-frame")&&(w=U.createQuery(),U.beginQuery(C.TIME_ELAPSED_EXT,w)),this.painter.context.setDirty(),this.painter.setBaseState(),(this.isMoving()||this.isRotating()||this.isZooming())&&(this._interactionRange[0]=Math.min(this._interactionRange[0],performance.now()),this._interactionRange[1]=Math.max(this._interactionRange[1],performance.now())),this._renderTaskQueue.run(D),this._domRenderTaskQueue.run(D),this._removed)return;this._updateProjectionTransition();const Y=this._isInitialLoad?0:this._fadeDuration;if(this.style&&this._styleDirty){this._styleDirty=!1;const pe=this.transform.zoom,je=this.transform.pitch,Ee=o.o.now(),He=new o.ae(pe,{now:Ee,fadeDuration:Y,pitch:je,transition:this.style.transition,worldview:this._worldview});this.style.update(He)}this.style&&this.style.hasFogTransition()&&(this.style._markersNeedUpdate=!0,this._sourcesDirty=!0);let Z=!1;if(this.style&&this._sourcesDirty?(this._sourcesDirty=!1,this.painter._updateFog(this.style),this._updateTerrain(),Z=this._updateAverageElevation(O),this.style.updateSources(this.transform),this.style.updateImageProviders(),this.isMoving()||this._forceMarkerAndPopupUpdate()):Z=this._updateAverageElevation(O),this.style&&(this._placementDirty=this.style._updatePlacement(this.painter.transform,this.showCollisionBoxes,Y,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:Y,isInitialLoad:this._isInitialLoad,showPadding:this.showPadding,gpuTiming:!!this.listens("gpu-timing-layer"),gpuTimingDeferredRender:!!this.listens("gpu-timing-deferred-render"),speedIndexTiming:this.speedIndexTiming}),this.fire(new o.C("render")),this.loaded()&&!this._loaded&&(this._loaded=!0,u.mark(d.load),this.fire(new o.C("load"))),this.style&&this.style.hasTransitions()&&(this._styleDirty=!0),this.style&&(this.style.snow||this.style.rain)&&(this._styleDirty=!0),this.style&&this.style.imageManager.hasPatternsInFlight()&&(this._styleDirty=!0),this.style&&!this.style.modelManager.isLoaded()&&(this._styleDirty=!0),this.style&&!this._placementDirty&&this.style._releaseSymbolFadeTiles(),w){const pe=o.o.now()-O;U.endQuery(C.TIME_ELAPSED_EXT),setTimeout(()=>{const je=U.getQueryParameter(w,U.QUERY_RESULT)/1e6;U.deleteQuery(w),this.fire(new o.C("gpu-timing-frame",{cpuTime:pe,gpuTime:je}))},50)}if(this.listens("gpu-timing-layer")){const pe=this.painter.collectGpuTimers();setTimeout(()=>{const je=this.painter.queryGpuTimers(pe);this.fire(new o.C("gpu-timing-layer",{layerTimes:je}))},50)}if(this.listens("gpu-timing-deferred-render")){const pe=this.painter.collectDeferredRenderGpuQueries();setTimeout(()=>{const je=this.painter.queryGpuTimeDeferredRender(pe);this.fire(new o.C("gpu-timing-deferred-render",{gpuTime:je}))},50)}const se=this._sourcesDirty||this._styleDirty||this._placementDirty||Z;if(se||this._repaint)this.triggerRepaint();else{const pe=this.idle();if(pe&&(Z=this._updateAverageElevation(O,!0)),Z)this.triggerRepaint();else if(this._triggerFrame(!1),pe&&(this.fire(new o.C("idle")),this._isInitialLoad=!1,this.speedIndexTiming)){const je=this._calculateSpeedIndex();this.fire(new o.C("speedindexcompleted",{speedIndex:je})),this.speedIndexTiming=!1}}!this._loaded||this._fullyLoaded||se||(this._fullyLoaded=!0,u.mark(d.fullLoad),this._performanceMetricsCollection&&Ce(this._requestManager._customAccessToken,{width:this.painter.width,height:this.painter.height,interactionRange:this._interactionRange,visibilityHidden:this._visibilityHidden,terrainEnabled:!!this.painter.style.getTerrain(),fogEnabled:!!this.painter.style.getFog(),projection:this.getProjection().name,zoom:this.transform.zoom,renderer:this.painter.context.renderer,vendor:this.painter.context.vendor}),this._authenticate())}_forceMarkerAndPopupUpdate(D){for(const w of this._markers)D&&!this.getRenderWorldCopies()&&(w._lngLat=w._lngLat.wrap()),w._update();for(const w of this._popups)!D||this.getRenderWorldCopies()||w._trackPointer||(w._lngLat=w._lngLat.wrap()),w._update()}_updateAverageElevation(D,w=!1){const C=U=>(this.transform.averageElevation=U,this._update(!1),!0);if(!this.painter.averageElevationNeedsEasing())return this.transform.averageElevation!==0&&C(0);const O=this.transform.elevation&&this.transform.elevation.exaggeration()!==this._averageElevationExaggeration;if(O||(w||D-this._averageElevationLastSampledAt>500)&&!this._averageElevation.isEasing(D)){const U=this.transform.averageElevation;let Y=this.transform.sampleAverageElevation();this.transform.elevation!=null&&(this._averageElevationExaggeration=this.transform.elevation.exaggeration()),isNaN(Y)?Y=0:this._averageElevationLastSampledAt=D;const Z=Math.abs(U-Y);if(Z>1){if(this._isInitialLoad||O)return this._averageElevation.jumpTo(Y),C(Y);this._averageElevation.easeTo(Y,D,300)}else if(Z>1e-4)return this._averageElevation.jumpTo(Y),C(Y)}return!!this._averageElevation.isEasing(D)&&C(this._averageElevation.getValue(D))}_isTokenExpired(){return this._tokenExpiration!=null&&Date.now()>this._tokenExpiration}_revokeAuth(){const D=this.painter.context.gl;$e(D,!1),this._logoControl instanceof wq&&this._logoControl._updateLogo(),D&&D.clear(D.DEPTH_BUFFER_BIT|D.COLOR_BUFFER_BIT|D.STENCIL_BUFFER_BIT),this._silenceAuthErrors||this.fire(new o.B(new Error("A valid Mapbox access token is required to use Mapbox GL JS. To create an account or a new access token, visit https://account.mapbox.com/")))}_authenticate(){Ae(this._getMapId(),this._requestManager._skuToken,this._requestManager._customAccessToken,D=>{D&&(D.message!==W&&D.status!==401||this._revokeAuth())}),this._isTokenExpired()&&this._revokeAuth(),be(this._getMapId(),this._requestManager._skuToken,this._requestManager._customAccessToken,()=>{})}_postStyleLoadEvent(){this.style.globalId&&Ie(this._requestManager._customAccessToken,{map:this,style:this.style.globalId,importedStyles:this.style.getImportGlobalIds()})}_postStyleWithAppearanceEvent(){this.style.globalId&&this.style.hasAppearances()&&Re(this._requestManager._customAccessToken)}_postAddingAppearancesToStyleEvent(){Ne(this._requestManager._customAccessToken)}_updateTerrain(){const D=this._isDragging();this.painter.updateTerrain(this.style,D)}_calculateSpeedIndex(){const D=this.painter.canvasCopy(),w=this.painter.getCanvasCopiesAndTimestamps();w.timeStamps.push(performance.now());const C=this.painter.context.gl,O=C.createFramebuffer();function U(Y){C.framebufferTexture2D(C.FRAMEBUFFER,C.COLOR_ATTACHMENT0,C.TEXTURE_2D,Y,0);const Z=new Uint8Array(C.drawingBufferWidth*C.drawingBufferHeight*4);return C.readPixels(0,0,C.drawingBufferWidth,C.drawingBufferHeight,C.RGBA,C.UNSIGNED_BYTE,Z),Z}return C.bindFramebuffer(C.FRAMEBUFFER,O),this._canvasPixelComparison(U(D),w.canvasCopies.map(U),w.timeStamps)}_canvasPixelComparison(D,w,C){let O=C[1]-C[0];const U=D.length/4;for(let Y=0;Y{const C=!!this._renderNextFrame;this._frame=null,this._renderNextFrame=null,C&&this._render(w)}))}_preloadTiles(D){const w=this.style?this.style.getSourceCaches():[];return o.t(w,(C,O)=>C._preloadTiles(D,O),()=>{this.triggerRepaint()}),this}_onWindowOnline(){this._update()}_onWindowResize(D){this._trackResize&&this.resize({originalEvent:D})._update()}_onVisibilityChange(){document.visibilityState==="hidden"&&this._visibilityHidden++}get showTileBoundaries(){return!!this._showTileBoundaries}set showTileBoundaries(D){this._showTileBoundaries!==D&&(this._showTileBoundaries=D,this._update())}get showParseStatus(){return!!this._showParseStatus}set showParseStatus(D){this._showParseStatus!==D&&(this._showParseStatus=D,this._update())}get showTerrainWireframe(){return!!this._showTerrainWireframe}set showTerrainWireframe(D){this._showTerrainWireframe!==D&&(this._showTerrainWireframe=D,this._update())}get showLayers2DWireframe(){return!!this._showLayers2DWireframe}set showLayers2DWireframe(D){this._showLayers2DWireframe!==D&&(this._showLayers2DWireframe=D,this._update())}get showLayers3DWireframe(){return!!this._showLayers3DWireframe}set showLayers3DWireframe(D){this._showLayers3DWireframe!==D&&(this._showLayers3DWireframe=D,this._update())}get speedIndexTiming(){return!!this._speedIndexTiming}set speedIndexTiming(D){this._speedIndexTiming!==D&&(this._speedIndexTiming=D,this._update())}get showPadding(){return!!this._showPadding}set showPadding(D){this._showPadding!==D&&(this._showPadding=D,this._update())}get showCollisionBoxes(){return!!this._showCollisionBoxes}set showCollisionBoxes(D){this._showCollisionBoxes!==D&&(this._showCollisionBoxes=D,this.style&&D?this.style._generateCollisionBoxes():this._update())}get showOverdrawInspector(){return!!this._showOverdrawInspector}set showOverdrawInspector(D){this._showOverdrawInspector!==D&&(this._showOverdrawInspector=D,this._update())}get repaint(){return!!this._repaint}set repaint(D){this._repaint!==D&&(this._repaint=D,this.triggerRepaint())}get vertices(){return!!this._vertices}set vertices(D){this._vertices=D,this._update()}get showTileAABBs(){return!!this._showTileAABBs}set showTileAABBs(D){this._showTileAABBs!==D&&(this._showTileAABBs=D,D&&this._update())}_setCacheLimits(D,w){o.e_(D,w)}get version(){return c}},NavigationControl:class{constructor(D={}){this.options=Object.assign({},WAe,D),this._container=y("div","mapboxgl-ctrl mapboxgl-ctrl-group"),this._container.addEventListener("contextmenu",w=>w.preventDefault()),this.options.showZoom&&(o.aZ(["_setButtonTitle","_updateZoomButtons"],this),this._zoomInButton=this._createButton("mapboxgl-ctrl-zoom-in",w=>{this._map&&this._map.zoomIn({},{originalEvent:w})}),y("span","mapboxgl-ctrl-icon",this._zoomInButton).setAttribute("aria-hidden","true"),this._zoomOutButton=this._createButton("mapboxgl-ctrl-zoom-out",w=>{this._map&&this._map.zoomOut({},{originalEvent:w})}),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",w=>{const C=this._map;C&&(this.options.visualizePitch?C.resetNorthPitch({},{originalEvent:w}):C.resetNorth({},{originalEvent:w}))}),this._compassIcon=y("span","mapboxgl-ctrl-icon",this._compass),this._compassIcon.setAttribute("aria-hidden","true"))}_updateZoomButtons(){const D=this._map;if(!D)return;const w=D.getZoom(),C=w===D.getMaxZoom(),O=w===D.getMinZoom();this._zoomInButton.disabled=C,this._zoomOutButton.disabled=O,this._zoomInButton.setAttribute("aria-disabled",C.toString()),this._zoomOutButton.setAttribute("aria-disabled",O.toString())}_rotateCompassArrow(){const D=this._map;if(!D)return;const w=this.options.visualizePitch?`scale(${1/Math.pow(Math.cos(D.transform.pitch*(Math.PI/180)),.5)}) rotateX(${D.transform.pitch}deg) rotateZ(${D.transform.angle*(180/Math.PI)}deg)`:`rotate(${D.transform.angle*(180/Math.PI)}deg)`;D._requestDomTask(()=>{this._compassIcon&&(this._compassIcon.style.transform=w)})}onAdd(D){return this._map=D,this.options.showZoom&&(this._setButtonTitle(this._zoomInButton,"ZoomIn"),this._setButtonTitle(this._zoomOutButton,"ZoomOut"),D.on("zoom",this._updateZoomButtons),this._updateZoomButtons()),this.options.showCompass&&(this._setButtonTitle(this._compass,"ResetBearing"),this.options.visualizePitch&&D.on("pitch",this._rotateCompassArrow),D.on("rotate",this._rotateCompassArrow),this._rotateCompassArrow(),this._handler=new v6(D,this._compass,this.options.visualizePitch)),this._container}onRemove(){const D=this._map;D&&(this._container.remove(),this.options.showZoom&&D.off("zoom",this._updateZoomButtons),this.options.showCompass&&(this.options.visualizePitch&&D.off("pitch",this._rotateCompassArrow),D.off("rotate",this._rotateCompassArrow),this._handler&&this._handler.off(),this._handler=void 0),this._map=void 0)}_createButton(D,w){const C=y("button",D,this._container);return C.type="button",C.addEventListener("click",w),C}_setButtonTitle(D,w){if(!this._map)return;const C=this._map._getUIString(`NavigationControl.${w}`);D.setAttribute("aria-label",C),D.firstElementChild&&D.firstElementChild.setAttribute("title",C)}},GeolocateControl:class extends o.E{constructor(D={}){super();const w=navigator.geolocation;this.options=Object.assign({geolocation:w},_6,D),o.aZ(["_onSuccess","_onError","_onZoom","_finish","_setupUI","_updateCamera","_updateMarker","_updateMarkerRotation","_onDeviceOrientation"],this),this._updateMarkerRotationThrottled=di(this._updateMarkerRotation,20),this._numberOfWatches=0}onAdd(D){return this._map=D,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(D){const w=(C=!!this.options.geolocation)=>{this._supportsGeolocation=C,D(C)};this._supportsGeolocation!==void 0?D(this._supportsGeolocation):navigator.permissions!==void 0?navigator.permissions.query({name:"geolocation"}).then(C=>w(C.state!=="denied")).catch(()=>w()):w()}_isOutOfMapMaxBounds(D){const w=this._map.getMaxBounds(),C=D.coords;return!!w&&(C.longitudew.getEast()||C.latitudew.getNorth())}_setErrorState(){switch(this._watchState){case"WAITING_ACTIVE":this._watchState="ACTIVE_ERROR",this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-active"),this._geolocateButton.classList.add("mapboxgl-ctrl-geolocate-active-error");break;case"ACTIVE_LOCK":this._watchState="ACTIVE_ERROR",this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-active"),this._geolocateButton.classList.add("mapboxgl-ctrl-geolocate-active-error"),this._geolocateButton.classList.add("mapboxgl-ctrl-geolocate-waiting");break;case"BACKGROUND":this._watchState="BACKGROUND_ERROR",this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-background"),this._geolocateButton.classList.add("mapboxgl-ctrl-geolocate-background-error"),this._geolocateButton.classList.add("mapboxgl-ctrl-geolocate-waiting")}}_onSuccess(D){if(this._map){if(this._clearRequestTimeout(),this._isOutOfMapMaxBounds(D))return this._setErrorState(),this.fire(new o.C("outofmaxbounds",D)),this._updateMarker(),void this._finish();if(this.options.trackUserLocation)switch(this._lastKnownPosition=D,this._watchState){case"WAITING_ACTIVE":case"ACTIVE_LOCK":case"ACTIVE_ERROR":this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-waiting"),this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-active-error"),this.options.followUserLocation?(this._watchState="ACTIVE_LOCK",this._geolocateButton.classList.add("mapboxgl-ctrl-geolocate-active")):(this._watchState="BACKGROUND",this._geolocateButton.classList.add("mapboxgl-ctrl-geolocate-background"));break;case"BACKGROUND":case"BACKGROUND_ERROR":this._watchState="BACKGROUND",this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-waiting"),this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-background-error"),this._geolocateButton.classList.add("mapboxgl-ctrl-geolocate-background")}this.options.showUserLocation&&this._watchState!=="OFF"&&this._updateMarker(D),this.options.followUserLocation&&(!this.options.trackUserLocation||this._watchState==="ACTIVE_LOCK")&&this._updateCamera(D),this.options.showUserLocation&&this._userLocationDotMarker.removeClassName("mapboxgl-user-location-dot-stale"),this.fire(new o.C("geolocate",Object.assign({coords:D.coords,timestamp:D.timestamp},D.toJSON?{toJSON:D.toJSON.bind(D)}:{}))),this._finish()}}_updateCamera(D){const w=new o.aU(D.coords.longitude,D.coords.latitude),C=D.coords.accuracy,O=this._map.getBearing(),U=Object.assign({bearing:O},this.options.fitBoundsOptions);this._map.fitBounds(w.toBounds(C),U,{geolocateSource:!0})}_updateMarker(D){if(D){const w=new o.aU(D.coords.longitude,D.coords.latitude);this._accuracyCircleMarker.setLngLat(w).addTo(this._map),this._userLocationDotMarker.setLngLat(w).addTo(this._map),this._accuracy=D.coords.accuracy,this.options.showUserLocation&&this.options.showAccuracyCircle&&this._updateCircleRadius()}else this._userLocationDotMarker.remove(),this._accuracyCircleMarker.remove()}_updateCircleRadius(){const D=this._map.transform,w=o.bU(1,D._center.lat)*D.worldSize,C=Math.ceil(2*this._accuracy*w);this._circleElement.style.width=`${C}px`,this._circleElement.style.height=`${C}px`}_onZoom(){this.options.showUserLocation&&this.options.showAccuracyCircle&&this._updateCircleRadius()}_updateMarkerRotation(){this._userLocationDotMarker&&typeof this._heading=="number"?(this._userLocationDotMarker.setRotation(this._heading),this._userLocationDotMarker.addClassName("mapboxgl-user-location-show-heading")):(this._userLocationDotMarker.removeClassName("mapboxgl-user-location-show-heading"),this._userLocationDotMarker.setRotation(0))}_onError(D){if(this._map){if(this._clearRequestTimeout(),this.options.trackUserLocation)if(D.code===1){this._watchState="OFF",this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-waiting"),this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-active"),this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-active-error"),this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-background"),this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-background-error"),this._geolocateButton.disabled=!0;const w=this._map._getUIString("GeolocateControl.LocationNotAvailable");this._geolocateButton.setAttribute("aria-label",w),this._geolocateButton.firstElementChild&&this._geolocateButton.firstElementChild.setAttribute("title",w),this._geolocationWatchID!==void 0&&this._clearWatch()}else{if(D.code===3&&this._noTimeout)return;this._setErrorState()}this._watchState!=="OFF"&&this.options.showUserLocation&&this._userLocationDotMarker.addClassName("mapboxgl-user-location-dot-stale"),this.fire(new o.C("error",{code:D.code,message:D.message,PERMISSION_DENIED:D.PERMISSION_DENIED,POSITION_UNAVAILABLE:D.POSITION_UNAVAILABLE,TIMEOUT:D.TIMEOUT})),this._finish()}}_finish(){this._timeoutId&&clearTimeout(this._timeoutId),this._timeoutId=void 0}_startRequestTimeout(){this._clearRequestTimeout();const D=this.options.positionOptions.timeout;D&&(this._requestTimeoutId=window.setTimeout(()=>{this._onError({code:3,message:"Geolocation request timed out"})},D))}_clearRequestTimeout(){this._requestTimeoutId!==void 0&&(clearTimeout(this._requestTimeoutId),this._requestTimeoutId=void 0)}_setupUI(D){if(this._map!==void 0){if(this._container.addEventListener("contextmenu",w=>w.preventDefault()),this._geolocateButton=y("button","mapboxgl-ctrl-geolocate",this._container),y("span","mapboxgl-ctrl-icon",this._geolocateButton).setAttribute("aria-hidden","true"),this._geolocateButton.type="button",D===!1){o.w("Geolocation support is not available so the GeolocateControl will be disabled.");const w=this._map._getUIString("GeolocateControl.LocationNotAvailable");this._geolocateButton.disabled=!0,this._geolocateButton.setAttribute("aria-label",w),this._geolocateButton.firstElementChild&&this._geolocateButton.firstElementChild.setAttribute("title",w)}else{const w=this._map._getUIString("GeolocateControl.FindMyLocation");this._geolocateButton.setAttribute("aria-label",w),this._geolocateButton.firstElementChild&&this._geolocateButton.firstElementChild.setAttribute("title",w)}this.options.trackUserLocation&&(this._geolocateButton.setAttribute("aria-pressed","false"),this._watchState="OFF"),this.options.showUserLocation&&(this._dotElement=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 S1({element:this._dotElement,rotationAlignment:"map",pitchAlignment:"map"}),this._circleElement=y("div","mapboxgl-user-location-accuracy-circle"),this._accuracyCircleMarker=new S1({element:this._circleElement,pitchAlignment:"map"}),this.options.trackUserLocation&&(this._watchState="OFF"),this._map.on("zoom",this._onZoom)),this._geolocateButton.addEventListener("click",this.trigger.bind(this)),this._setup=!0,this.options.showButton||(this._container.style.display="none"),this.options.trackUserLocation&&this._map.on("movestart",w=>{w.geolocateSource||this._watchState!=="ACTIVE_LOCK"||w.originalEvent&&w.originalEvent.type==="resize"||(this._watchState="BACKGROUND",this._geolocateButton.classList.add("mapboxgl-ctrl-geolocate-background"),this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-active"),this.fire(new o.C("trackuserlocationend")))})}}_onDeviceOrientation(D){this._userLocationDotMarker&&(D.webkitCompassHeading?this._heading=D.webkitCompassHeading:D.absolute===!0&&(this._heading=-1*D.alpha),this._updateMarkerRotationThrottled())}trigger(){if(!this._setup)return o.w("Geolocate control triggered before added to a map"),!1;if(this.options.trackUserLocation){switch(this._watchState){case"OFF":this._watchState="WAITING_ACTIVE",this.fire(new o.C("trackuserlocationstart"));break;case"WAITING_ACTIVE":case"ACTIVE_LOCK":case"ACTIVE_ERROR":case"BACKGROUND_ERROR":this._numberOfWatches--,this._noTimeout=!1,this._watchState="OFF",this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-waiting"),this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-active"),this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-active-error"),this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-background"),this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-background-error"),this.fire(new o.C("trackuserlocationend"));break;case"BACKGROUND":this._watchState="ACTIVE_LOCK",this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-background"),this._lastKnownPosition&&this._updateCamera(this._lastKnownPosition),this.fire(new o.C("trackuserlocationstart"))}switch(this._watchState){case"WAITING_ACTIVE":this._geolocateButton.classList.add("mapboxgl-ctrl-geolocate-waiting"),this._geolocateButton.classList.add("mapboxgl-ctrl-geolocate-active");break;case"ACTIVE_LOCK":this._geolocateButton.classList.add("mapboxgl-ctrl-geolocate-active");break;case"ACTIVE_ERROR":this._geolocateButton.classList.add("mapboxgl-ctrl-geolocate-waiting"),this._geolocateButton.classList.add("mapboxgl-ctrl-geolocate-active-error");break;case"BACKGROUND":this._geolocateButton.classList.add("mapboxgl-ctrl-geolocate-background");break;case"BACKGROUND_ERROR":this._geolocateButton.classList.add("mapboxgl-ctrl-geolocate-waiting"),this._geolocateButton.classList.add("mapboxgl-ctrl-geolocate-background-error")}if(this._watchState==="OFF"&&this._geolocationWatchID!==void 0)this._clearWatch();else if(this._geolocationWatchID===void 0){let D;this._geolocateButton.classList.add("mapboxgl-ctrl-geolocate-waiting"),this._geolocateButton.setAttribute("aria-pressed","true"),this._numberOfWatches++,this._numberOfWatches>1?(D={maximumAge:6e5,timeout:0},this._noTimeout=!0):(D=this.options.positionOptions,this._noTimeout=!1),this._geolocationWatchID=this.options.geolocation.watchPosition(this._onSuccess,this._onError,D),this._startRequestTimeout(),this.options.showUserHeading&&this._addDeviceOrientationListener()}}else this.options.geolocation.getCurrentPosition(this._onSuccess,this._onError,this.options.positionOptions),this._startRequestTimeout(),this._timeoutId=window.setTimeout(this._finish,1e4);return!0}setFollowUserLocation(D){return this.options.followUserLocation=D??_6.followUserLocation,this.options.trackUserLocation&&this._watchState!=="OFF"&&(this.options.followUserLocation?this._watchState!=="BACKGROUND"&&this._watchState!=="BACKGROUND_ERROR"||(this._watchState="ACTIVE_LOCK",this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-background"),this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-background-error"),this._geolocateButton.classList.add("mapboxgl-ctrl-geolocate-active"),this._lastKnownPosition&&this._updateCamera(this._lastKnownPosition),this.fire(new o.C("trackuserlocationstart"))):this._watchState!=="ACTIVE_LOCK"&&this._watchState!=="ACTIVE_ERROR"||(this._watchState="BACKGROUND",this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-active"),this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-active-error"),this._geolocateButton.classList.add("mapboxgl-ctrl-geolocate-background"),this.fire(new o.C("trackuserlocationend")))),this}_addDeviceOrientationListener(){const D=()=>{const w="ondeviceorientationabsolute"in window?"deviceorientationabsolute":"deviceorientation";window.addEventListener(w,this._onDeviceOrientation)};typeof DeviceOrientationEvent.requestPermission=="function"?DeviceOrientationEvent.requestPermission().then(w=>{w==="granted"&&D()}).catch(console.error):D()}_clearWatch(){this._clearRequestTimeout(),this.options.geolocation.clearWatch(this._geolocationWatchID),window.removeEventListener("deviceorientation",this._onDeviceOrientation),window.removeEventListener("deviceorientationabsolute",this._onDeviceOrientation),this._geolocationWatchID=void 0,this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-waiting"),this._geolocateButton.setAttribute("aria-pressed","false"),this.options.showUserLocation&&this._updateMarker(null)}},AttributionControl:_q,ScaleControl:class{constructor(D={}){this.options=Object.assign({},Nh,D),o.aZ(["_update","_setScale","setUnit"],this)}getDefaultPosition(){return"bottom-left"}_update(){const D=this.options.maxWidth||100,w=this._map,C=w._containerHeight/2,O=w._containerWidth/2-D/2,U=w.unproject([O,C]),Y=w.unproject([O+D,C]),Z=U.distanceTo(Y);if(this.options.unit==="imperial"){const se=3.2808*Z;se>5280?this._setScale(D,se/5280,"mile"):this._setScale(D,se,"foot")}else this.options.unit==="nautical"?this._setScale(D,Z/1852,"nautical-mile"):Z>=1e3?this._setScale(D,Z/1e3,"kilometer"):this._setScale(D,Z,"meter")}_setScale(D,w,C){this._map._requestDomTask(()=>{const O=function(Y){const Z=Math.pow(10,`${Math.floor(Y)}`.length-1);let se=Y/Z;return se=se>=10?10:se>=5?5:se>=3?3:se>=2?2:se>=1?1:function(pe){const je=Math.pow(10,Math.ceil(-Math.log(pe)/Math.LN10));return Math.round(pe*je)/je}(se),Z*se}(w),U=O/w;this._container.innerHTML=C!=="nautical-mile"?new Intl.NumberFormat(this._language,{style:"unit",unitDisplay:"short",unit:C}).format(O):`${O} ${C1[C]}`,this._container.style.width=D*U+"px"})}onAdd(D){return this._map=D,this._language=D.getLanguage(),this._container=y("div","mapboxgl-ctrl mapboxgl-ctrl-scale",D.getContainer()),this._container.dir="auto",this._map.on("move",this._update),this._update(),this._container}onRemove(){this._container.remove(),this._map.off("move",this._update),this._map=void 0}_setLanguage(D){this._language=D,this._update()}setUnit(D){this.options.unit=D,this._update()}},FullscreenControl:class{constructor(D={}){this._fullscreen=!1,D&&D.container&&(D.container instanceof HTMLElement?this._container=D.container:o.w("Full screen control 'container' must be a DOM element.")),o.aZ(["_onClickFullscreen","_changeIcon"],this),"onfullscreenchange"in document?this._fullscreenchange="fullscreenchange":"onwebkitfullscreenchange"in document&&(this._fullscreenchange="webkitfullscreenchange")}onAdd(D){return this._map=D,this._container||(this._container=this._map.getContainer()),this._controlContainer=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 D=this._fullscreenButton=y("button","mapboxgl-ctrl-fullscreen",this._controlContainer);y("span","mapboxgl-ctrl-icon",D).setAttribute("aria-hidden","true"),D.type="button",this._updateTitle(),this._fullscreenButton.addEventListener("click",this._onClickFullscreen),document.addEventListener(this._fullscreenchange,this._changeIcon)}_updateTitle(){const D=this._getTitle();this._fullscreenButton.setAttribute("aria-label",D),this._fullscreenButton.firstElementChild&&this._fullscreenButton.firstElementChild.setAttribute("title",D)}_getTitle(){return this._map._getUIString(this._isFullscreen()?"FullscreenControl.Exit":"FullscreenControl.Enter")}_isFullscreen(){return this._fullscreen}_changeIcon(){(document.fullscreenElement||document.webkitFullscreenElement)===this._container!==this._fullscreen&&(this._fullscreen=!this._fullscreen,this._fullscreenButton.classList.toggle("mapboxgl-ctrl-shrink"),this._fullscreenButton.classList.toggle("mapboxgl-ctrl-fullscreen"),this._updateTitle())}_onClickFullscreen(){this._isFullscreen()?document.exitFullscreen?document.exitFullscreen():document.webkitCancelFullScreen&&document.webkitCancelFullScreen():this._container.requestFullscreen?this._container.requestFullscreen():this._container.webkitRequestFullscreen&&this._container.webkitRequestFullscreen()}},IndoorControl:class{constructor(){o.aZ(["_onIndoorUpdate","_onStyleData","_scrollUp","_scrollDown","_toggleIndoor"],this),this._visibleFloorStart=0,this._lastSelectedFloorId=null}onAdd(D){return this._map=D,this._container=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 D=this._map.style.indoorManager;D.off("selector-update",this._onIndoorUpdate),D.on("selector-update",this._onIndoorUpdate),this._onIndoorUpdate(D.getControlState())}}_createButton(D,w){const C=y("button",D,this._container);return C.type="button",C.addEventListener("click",w),C}_setButtonTitle(D,w){D.setAttribute("aria-label",w),D.textContent=w}onRemove(){this._container&&this._container.remove(),this._map&&(this._map.off("styledata",this._onStyleData),this._map.style&&this._map.style.indoorManager.off("selector-update",this._onIndoorUpdate),this._map=null)}getDefaultPosition(){return"top-right"}_onIndoorUpdate(D){if(!D||!D.floors||D.floors.length===0)return this._model=D,void(this._container.style.display="none");const w=this._model;this._model=D,this._container.style.display="inline-block";const C=!w||w.floors.length!==D.floors.length||w.floors.some((O,U)=>O.id!==D.floors[U].id);if(C&&(this._visibleFloorStart=0,this._lastSelectedFloorId=null),D.selectedFloorId){if(D.selectedFloorId!==this._lastSelectedFloorId||C){const O=D.floors.findIndex(U=>U.id===D.selectedFloorId);if(O!==-1){const U=D.floors.length;let Y,Z;U<=5?(Y=0,Z=U-1):this._visibleFloorStart===0?(Y=0,Z=3):this._visibleFloorStart>=U-3?(Y=U-3-1,Z=U-1):(Y=this._visibleFloorStart,Z=this._visibleFloorStart+3-1),OZ&&(this._visibleFloorStart=O-2)}}this._lastSelectedFloorId=D.selectedFloorId}this._render()}_render(){if(!this._container||!this._model||!this._model.floors)return;this._container.innerHTML="";const D=this._createButton("mapboxgl-ctrl-indoor-toggle",this._toggleIndoor);y("span","mapboxgl-ctrl-icon",D).setAttribute("aria-hidden","true"),this._model.activeFloorsVisible||D.classList.add("mapboxgl-ctrl-level-button-selected"),this._container.appendChild(D);const w=this._model.floors,C=w.length;if(C<=5)return void w.forEach(Z=>this._createFloorButton(Z));const O=this._visibleFloorStart===0,U=this._visibleFloorStart>=C-3;if(O)this._createFloorButton(w[0]);else{const Z=this._createButton("mapboxgl-ctrl-arrow-up",this._scrollUp);y("span","mapboxgl-ctrl-icon",Z).setAttribute("aria-hidden","true"),this._container.appendChild(Z)}let Y=[];if(Y=O?w.slice(1,4):U?w.slice(this._visibleFloorStart-1,this._visibleFloorStart+3-1):w.slice(this._visibleFloorStart,this._visibleFloorStart+3),Y.forEach(Z=>this._createFloorButton(Z)),U)this._createFloorButton(w[C-1]);else{const Z=this._createButton("mapboxgl-ctrl-arrow-down",this._scrollDown);y("span","mapboxgl-ctrl-icon",Z).setAttribute("aria-hidden","true"),this._container.appendChild(Z)}}_createFloorButton(D){const w=this._createButton("mapboxgl-ctrl-level-button",()=>{const Y=D.id;this._model&&this._model.selectedFloorId===Y&&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(Y))}),C=(D.name||"").trim(),O=D.zIndex.toString(),U=C?Array.from(C).slice(0,3).join(""):O;this._setButtonTitle(w,U),this._model&&this._model.activeFloorsVisible&&D.id===this._model.selectedFloorId&&w.classList.add("mapboxgl-ctrl-level-button-selected"),this._container&&this._container.appendChild(w)}_toggleIndoor(){this._map&&this._map.style&&this._map.style.indoorManager&&this._model&&this._model.activeFloorsVisible&&this._map.style.indoorManager.setActiveFloorsVisibility(!1)}_scrollUp(){if(this._visibleFloorStart>0){this._visibleFloorStart--,this._visibleFloorStart===1&&(this._visibleFloorStart=0);const D=this._model&&this._model.floors||[];if(D.length>3){const w=D.length-3;this._visibleFloorStart===w-1&&(this._visibleFloorStart=w-2)}this._render()}}_scrollDown(){if(this._model&&this._model.floors){const D=this._model.floors.length-3;this._visibleFloorStartD&&(this._visibleFloorStart=D),this._render())}}},Popup:class extends o.E{constructor(D){super(),this.options=Object.assign(Object.create(w6),D),this._altitude=this.options.altitude,o.aZ(["_update","_onClose","remove","_onMouseEvent"],this),this._classList=new Set(D&&D.className?D.className.trim().split(/\s+/):[])}addTo(D){return this._map&&this.remove(),this._map=D,this.options.closeOnClick&&D.on("preclick",this._onClose),this.options.closeOnMove&&D.on("move",this._onClose),D.on("remove",this.remove),this._update(),D._addPopup(this),this._focusFirstElement(),this._trackPointer?(D.on("mousemove",this._onMouseEvent),D.on("mouseup",this._onMouseEvent),D._canvasContainer.classList.add("mapboxgl-track-pointer")):D.on("move",this._update),this.fire(new o.C("open")),this}isOpen(){return!!this._map}remove(){this._content&&this._content.remove(),this._container&&(this._container.remove(),this._container=void 0);const D=this._map;return D&&(D.off("move",this._update),D.off("move",this._onClose),D.off("preclick",this._onClose),D.off("click",this._onClose),D.off("remove",this.remove),D.off("mousemove",this._onMouseEvent),D.off("mouseup",this._onMouseEvent),D.off("drag",this._onMouseEvent),D._canvasContainer&&D._canvasContainer.classList.remove("mapboxgl-track-pointer"),D._removePopup(this),this._map=void 0),this.fire(new o.C("close")),this}getLngLat(){return this._lngLat}setLngLat(D){this._lngLat=o.aU.convert(D),this._pos=null,this._trackPointer=!1,this._update();const w=this._map;return w&&(w.on("move",this._update),w.off("mousemove",this._onMouseEvent),w._canvasContainer.classList.remove("mapboxgl-track-pointer")),this}getAltitude(){return this._altitude}setAltitude(D){return this._altitude=D,this._update(),this}trackPointer(){this._trackPointer=!0,this._pos=null,this._update();const D=this._map;return D&&(D.off("move",this._update),D.on("mousemove",this._onMouseEvent),D.on("drag",this._onMouseEvent),D._canvasContainer.classList.add("mapboxgl-track-pointer")),this}getElement(){return this._container}setText(D){return this.setDOMContent(document.createTextNode(D))}setHTML(D){const w=document.createDocumentFragment(),C=document.createElement("body");let O;for(C.innerHTML=D;O=C.firstChild,O;)w.appendChild(O);return this.setDOMContent(w)}getMaxWidth(){return this._container&&this._container.style.maxWidth}setMaxWidth(D){return this.options.maxWidth=D,this._update(),this}setDOMContent(D){let w=this._content;if(w)for(;w.hasChildNodes();)w.firstChild&&w.removeChild(w.firstChild);else w=this._content=y("div","mapboxgl-popup-content",this._container||void 0);if(w.appendChild(D),this.options.closeButton){const C=this._closeButton=y("button","mapboxgl-popup-close-button",w);C.type="button",C.setAttribute("aria-label","Close popup"),C.innerHTML='',C.addEventListener("click",this._onClose)}return this._update(),this._focusFirstElement(),this}addClassName(D){return this._classList.add(D),this._updateClassList(),this}removeClassName(D){return this._classList.delete(D),this._updateClassList(),this}setOffset(D){return this.options.offset=D,this._update(),this}toggleClassName(D){let w;return this._classList.delete(D)?w=!1:(this._classList.add(D),w=!0),this._updateClassList(),w}_onMouseEvent(D){this._update(D.point)}_getAnchor(D){if(this.options.anchor)return this.options.anchor;const w=this._map,C=this._container,O=this._pos;if(!w||!C||!O)return"bottom";const U=C.offsetWidth,Y=C.offsetHeight,Z=O.xw.transform.width-U/2;if(O.y+Dw.transform.height-Y){if(Z)return"bottom-left";if(se)return"bottom-right"}return Z?"left":se?"right":"bottom"}_updateClassList(){const D=this._container;if(!D)return;const w=[...this._classList];w.push("mapboxgl-popup"),this._anchor&&w.push(`mapboxgl-popup-anchor-${this._anchor}`),this._trackPointer&&w.push("mapboxgl-popup-track-pointer"),D.className=w.join(" ")}_update(D){const w=this._map,C=this._content;if(!w||!this._lngLat&&!this._trackPointer||!C)return;let O=this._container;if(O||(O=this._container=y("div","mapboxgl-popup",w.getContainer()),this._tip=y("div","mapboxgl-popup-tip",O),O.appendChild(C)),this.options.maxWidth&&O.style.maxWidth!==this.options.maxWidth&&(O.style.maxWidth=this.options.maxWidth),w.transform.renderWorldCopies&&!this._trackPointer&&(this._lngLat=jq(this._lngLat,this._pos,w.transform)),!this._trackPointer||D){const U=this._pos=this._trackPointer&&D instanceof o.P?D:w.project(this._lngLat,this._altitude),Y=CO(this.options.offset),Z=this._anchor=this._getAnchor(Y.y),se=CO(this.options.offset,Z),pe=U.add(se).round();w._requestDomTask(()=>{this._container&&Z&&(this._container.style.transform=`${b6[Z]} translate(${pe.x}px,${pe.y}px)`)})}if(!this._marker&&w._showingGlobe()){const U=o.e$(w.transform,this._lngLat)?0:1;this._setOpacity(U)}this._updateClassList()}_focusFirstElement(){if(!this.options.focusAfterOpen||!this._container)return;const D=this._container.querySelector(KAe);D&&D.focus()}_onClose(){this.remove()}_setOpacity(D){this._container&&(this._container.style.opacity=`${D}`),this._content&&(this._content.style.pointerEvents=D?"auto":"none")}},Marker:S1,Style:mu,LngLat:o.aU,LngLatBounds:o.aK,Point:o.P,MercatorCoordinate:o.ag,FreeCameraOptions:i0,Evented:o.E,config:o.g,prewarm:function(){Yt().acquire(rt)},clearPrewarmedResources:function(){const D=Bt;D&&(D.isPreloaded()&&D.numActive()===1?(D.release(rt),Bt=null):console.warn("Could not clear WebWorkers since there are active Map instances that still reference it. The pre-warmed WebWorker pool can only be cleared when all map instances have been removed with map.remove()"))},get accessToken(){return o.g.ACCESS_TOKEN},set accessToken(D){o.g.ACCESS_TOKEN=D},get baseApiUrl(){return o.g.API_URL},set baseApiUrl(D){o.g.API_URL=D},get workerCount(){return Ze.workerCount},set workerCount(D){Ze.workerCount=D},get maxParallelImageRequests(){return o.g.MAX_PARALLEL_IMAGE_REQUESTS},set maxParallelImageRequests(D){o.g.MAX_PARALLEL_IMAGE_REQUESTS=D},clearStorage(D){o.f7(D)},get workerUrl(){return Ke.workerUrl},set workerUrl(D){Ke.workerUrl=D},get workerClass(){return Ke.workerClass},set workerClass(D){Ke.workerClass=D},get workerParams(){return Ke.workerParams},set workerParams(D){Ke.workerParams=D},get dracoUrl(){return o.f6()},set dracoUrl(D){o.g.DRACO_URL=o.o.resolveURL(D)},get meshoptUrl(){return o.f5()},set meshoptUrl(D){const w=o.o.resolveURL(D);o.g.MESHOPT_URL=w,o.g.MESHOPT_SIMD_URL=w},get buildingGenUrl(){return o.f4()},set buildingGenUrl(D){o.g.BUILDING_GEN_URL=o.o.resolveURL(D)},setNow:o.o.setNow,restoreNow:o.o.restoreNow}});var l=a;return l})})($2t);var Ais=$2t.exports;const Rc=Xc(Ais),Ott={coming_soon:"#3B82F6",office_exclusive:"#6366F1",pre_market:"#06B6D4",active:"#10B981",price_improvement:"#F97316",under_contract:"#8B5CF6",sold:"#6B7280"},Ftt={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 Tis(s){return s>=1e6?`$${(s/1e6).toFixed(1)}M`:`$${(s/1e3).toFixed(0)}K`}function Eis({listings:s,isLoading:t}){const n=tr(),r=N.useRef(null),a=N.useRef(null),i=N.useRef([]),[l,o]=N.useState(""),[c,d]=N.useState(!0);return N.useEffect(()=>{(async()=>{d(!0);try{const{data:m}=await H.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)})()},[]),N.useEffect(()=>{if(!r.current||!l||a.current)return;Rc.accessToken=l;const h=s.filter(g=>g.latitude!=null&&g.longitude!=null);let m=[-98.5795,39.8283],f=4;if(h.length>0){const g=h.reduce((x,_)=>x+_.longitude,0)/h.length,y=h.reduce((x,_)=>x+_.latitude,0)/h.length;m=[g,y],f=h.length===1?12:10}return a.current=new Rc.Map({container:r.current,style:"mapbox://styles/mapbox/light-v11",zoom:f,center:m}),a.current.addControl(new Rc.NavigationControl,"top-right"),()=>{var g;(g=a.current)==null||g.remove(),a.current=null}},[l]),N.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 A,T,P;const f=Ott[m.status]||"#10B981",g=((A=m.photos)==null?void 0:A.find(I=>I.is_primary))||((T=m.photos)==null?void 0:T[0]),x=window.location.hostname==="listings.relevelup.com"||window.location.hostname.startsWith("listings.")?`/${m.slug||m.id}`:`/public/listing/${m.slug||m.id}`,_=document.createElement("div");_.className="cursor-pointer",_.innerHTML=`

`;const b=new Rc.Popup({offset:25,closeButton:!0,maxWidth:"280px"}).setHTML(`
${g!=null&&g.photo_url?``:""}
${Tis(m.price)}
${m.property_address||""}
${m.city}, ${m.state}
${Ftt[m.status]||m.status} ${m.bedrooms?`${m.bedrooms} bed`:""} ${m.bathrooms?`${m.bathrooms} bath`:""}
${(P=m.agent)!=null&&P.name?`
Listed by ${m.agent.name}
`:""}
Click to view details →
`),k=new Rc.Marker(_).setLngLat([m.longitude,m.latitude]).setPopup(b).addTo(a.current);i.current.push(k)}),h.length>1){const m=new Rc.LngLatBounds;h.forEach(f=>m.extend([f.longitude,f.latitude])),a.current.fitBounds(m,{padding:60,maxZoom:13})}else h.length===1&&a.current.flyTo({center:[h[0].longitude,h[0].latitude],zoom:12})},[s,l]),N.useEffect(()=>(window.__navigateToPublicListing__=h=>{n(h)},()=>{delete window.__navigateToPublicListing__}),[n]),c||t?e.jsx(xn,{className:"w-full h-[500px] rounded-lg"}):!l||s.filter(h=>h.latitude!=null&&h.longitude!=null).length===0?null:e.jsxs("div",{className:"space-y-3",children:[e.jsx("div",{className:"flex flex-wrap items-center gap-3 text-sm",children:Object.entries(Ott).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:Ftt[h]})]},h))}),e.jsx("div",{ref:r,className:"w-full h-[500px] rounded-lg shadow-lg border border-gray-200"})]})}const A6e={active:"Active",coming_soon:"Coming Soon",office_exclusive:"Office Exclusive",pre_market:"Pre-Market",price_improvement:"Price Improvement",under_contract:"Under Contract",sold:"Sold"},Mis={single_family:"Single Family",condo:"Condo",townhouse:"Townhouse",land:"Land",multi_family:"Multi-Family",luxury:"Luxury",commercial:"Commercial",other:"Other"},cF="#0d0d0d",ztt="#1a1a1a",Wc="#c9a84c",yC="#f0d78c";function q2t(){const[s,t]=N.useState(""),[n,r]=N.useState(!1),[a,i]=N.useState(!1),[l,o]=N.useState(!1),[c,d]=N.useState(-1),u=N.useRef(null),[h,m]=N.useState({status:"",propertyType:"",minPrice:"",maxPrice:""}),{data:f}=_is(),g=N.useMemo(()=>{if(!f)return[];const $=s.trim().toLowerCase(),V=[...f.cities.map(G=>({label:G.label,value:G.city,type:"city",count:G.count})),...f.neighborhoods.map(G=>({label:G.label,value:G.neighborhood,type:"neighborhood",count:G.count})),...f.zips.map(G=>({label:`ZIP ${G.label}`,value:G.zip,type:"zip",count:G.count}))];return($?V.filter(G=>G.label.toLowerCase().includes($)||G.value.toLowerCase().includes($)):V).slice(0,8)},[f,s]);N.useEffect(()=>{const $=V=>{u.current&&!u.current.contains(V.target)&&o(!1)};return document.addEventListener("mousedown",$),()=>document.removeEventListener("mousedown",$)},[]);const{data:y,isLoading:x}=bis({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}),_=$=>new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:0}).format($),b=()=>{m({status:"",propertyType:"",minPrice:"",maxPrice:""}),t("")},k=s||h.status||h.propertyType||h.minPrice||h.maxPrice,A=typeof window<"u"&&(window.location.hostname==="listings.relevelup.com"||window.location.hostname.startsWith("listings.")),T=$=>A?`/${$.slug||$.id}`:`/public/listing/${$.slug||$.id}`,{featured:P,restListings:I,luxeCount:M,cities:L,activeCount:z}=N.useMemo(()=>{const $=y||[],V=$.filter(ve=>ve.status==="active"),W=V.length>0?V:$,G=new Intl.DateTimeFormat("en-CA",{timeZone:"America/New_York",year:"numeric",month:"2-digit",day:"2-digit"}).format(new Date),[X,te,ne]=G.split("-").map(Number),me=Math.floor(Date.UTC(X,te-1,ne)/864e5),ue=W.length>0?W[me%W.length]:void 0,ce=$.filter(ve=>!ue||ve.id!==ue.id),ae=Array.from(new Set($.map(ve=>ve.city).filter(Boolean))).slice(0,8),he=$.filter(ve=>(ve.price||0)>=1e6).length,xe=V.length;return{featured:ue,restListings:ce,luxeCount:he,cities:ae,activeCount:xe}},[y]);return e.jsxs(e.Fragment,{children:[e.jsxs(ic,{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:cF,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: ${Wc}; } .lu-gold-line { background: linear-gradient(90deg, transparent, ${Wc}, 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(cr,{to:"/",className:"flex items-center gap-3",children:[e.jsx("img",{src:U2e,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(cr,{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 ${Wc}`,color:Wc},children:"About LevelUp"})]}),e.jsx("button",{type:"button",onClick:()=>i($=>!$),className:"md:hidden inline-flex items-center justify-center w-10 h-10 rounded-full",style:{border:`1px solid ${Wc}`,color:Wc},"aria-label":"Toggle menu","aria-expanded":a,children:a?e.jsx(hr,{className:"w-5 h-5"}):e.jsx(MT,{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(cr,{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 ${Wc}`,color:Wc},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:Cis,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:Wc}}),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:yC},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 ${Wc}`,backdropFilter:"blur(12px)"},children:[e.jsxs("div",{className:"relative flex-1",children:[e.jsx(Gr,{className:"absolute left-6 top-1/2 -translate-y-1/2 h-5 w-5",style:{color:Wc}}),e.jsx(we,{placeholder:"City, neighborhood, or ZIP",value:s,onChange:$=>{t($.target.value),o(!0),d(-1)},onFocus:()=>o(!0),onKeyDown:$=>{if(!(!l||g.length===0))if($.key==="ArrowDown")$.preventDefault(),d(V=>Math.min(V+1,g.length-1));else if($.key==="ArrowUp")$.preventDefault(),d(V=>Math.max(V-1,0));else if($.key==="Enter"&&c>=0){$.preventDefault();const V=g[c];t(V.value),o(!1)}else $.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(OT,{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:Wc,color:cF},onClick:()=>o(!1),children:[e.jsx(Gr,{className:"h-5 w-5"}),e.jsx("span",{className:"hidden md:inline",children:"Search"})]})]}),l&&g.length>0&&e.jsxs("div",{className:"mt-2 rounded-2xl overflow-hidden shadow-2xl animate-fade-in",style:{background:"rgba(13,13,13,0.96)",border:"1px solid rgba(201,168,76,0.35)",backdropFilter:"blur(12px)"},children:[e.jsx("div",{className:"px-5 pt-3 pb-2 text-[10px] tracking-[0.2em] uppercase",style:{color:Wc},children:"Suggestions"}),e.jsx("ul",{className:"max-h-80 overflow-y-auto",children:g.map(($,V)=>e.jsx("li",{children:e.jsxs("button",{type:"button",onMouseEnter:()=>d(V),onClick:()=>{t($.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:[$.type==="city"&&e.jsx(ii,{className:"h-4 w-4 shrink-0",style:{color:Wc}}),$.type==="neighborhood"&&e.jsx(Ti,{className:"h-4 w-4 shrink-0",style:{color:Wc}}),$.type==="zip"&&e.jsx(_a,{className:"h-4 w-4 shrink-0",style:{color:Wc}}),e.jsx("span",{className:"text-white/90 truncate",children:$.label})]}),e.jsxs("span",{className:"text-xs text-white/50 shrink-0",children:[$.count," ",$.count===1?"listing":"listings"]})]})},`${$.type}-${$.value}-${V}`))})]}),l&&s.trim()&&g.length===0&&e.jsx("div",{className:"mt-2 rounded-2xl px-5 py-4 text-sm text-white/70",style:{background:"rgba(13,13,13,0.96)",border:"1px solid rgba(201,168,76,0.25)"},children:"No matches yet — try a nearby city or ZIP."}),n&&e.jsxs("div",{className:"mt-4 p-6 rounded-2xl grid sm:grid-cols-2 md:grid-cols-4 gap-4 animate-fade-in",style:{background:"rgba(26,26,26,0.9)",border:"1px solid rgba(201,168,76,0.25)"},children:[e.jsxs("div",{children:[e.jsx("label",{className:"lu-eyebrow text-white/60 mb-2 block",children:"Status"}),e.jsxs(Ns,{value:h.status||"all",onValueChange:$=>m({...h,status:$==="all"?"":$}),children:[e.jsx(ws,{className:"lu-input-dark",children:e.jsx(ks,{})}),e.jsxs(js,{children:[e.jsx(nt,{value:"all",children:"Any status"}),Object.entries(A6e).map(([$,V])=>e.jsx(nt,{value:$,children:V},$))]})]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"lu-eyebrow text-white/60 mb-2 block",children:"Type"}),e.jsxs(Ns,{value:h.propertyType||"all",onValueChange:$=>m({...h,propertyType:$==="all"?"":$}),children:[e.jsx(ws,{className:"lu-input-dark",children:e.jsx(ks,{})}),e.jsxs(js,{children:[e.jsx(nt,{value:"all",children:"Any type"}),Object.entries(Mis).map(([$,V])=>e.jsx(nt,{value:$,children:V},$))]})]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"lu-eyebrow text-white/60 mb-2 block",children:"Min Price"}),e.jsx(we,{type:"number",placeholder:"No min",value:h.minPrice,onChange:$=>m({...h,minPrice:$.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(we,{type:"number",placeholder:"No max",value:h.maxPrice,onChange:$=>m({...h,maxPrice:$.target.value}),className:"lu-input-dark"})]}),k&&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(hr,{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:z.toString()},{label:"Luxury $1M+",value:M.toString()}].map($=>e.jsxs("div",{children:[e.jsx("div",{className:"lu-serif text-4xl md:text-5xl",style:{color:yC},children:$.value}),e.jsx("div",{className:"lu-eyebrow text-white/60 mt-1",children:$.label})]},$.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(Xo,{className:"h-4 w-4 animate-bounce"})]})]})]}),L.length>0&&e.jsx("section",{className:"py-8 overflow-hidden",style:{background:ztt,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:[...L,...L,...L].map(($,V)=>e.jsxs("span",{className:"flex items-center gap-3 lu-serif text-2xl md:text-3xl text-white/40",children:[$,e.jsx("span",{className:"h-1.5 w-1.5 rounded-full",style:{background:Wc}})]},V))})}),P&&e.jsx("section",{id:"featured",className:"py-20 md:py-28",children:e.jsxs("div",{className:"max-w-7xl mx-auto px-6",children:[e.jsxs("div",{className:"flex items-end justify-between mb-10 md:mb-14",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-3 mb-4",children:[e.jsx(Cn,{className:"h-4 w-4",style:{color:Wc}}),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:yC},children:"standout"}),"."]})]}),e.jsx("div",{className:"hidden md:block h-px flex-1 mx-8 lu-gold-line"})]}),e.jsx(cr,{to:T(P),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,W;const $=((V=P.photos)==null?void 0:V.find(G=>G.is_primary))||((W=P.photos)==null?void 0:W[0]);return $?e.jsx("img",{src:$.photo_url,alt:P.property_address||P.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(_a,{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:Wc,color:cF},children:A6e[P.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(ii,{className:"h-3.5 w-3.5",style:{color:Wc}}),P.city,P.state?`, ${P.state}`:""]}),P.property_address&&e.jsx("h3",{className:"lu-serif text-3xl md:text-4xl mb-4 leading-tight",children:P.property_address}),e.jsx("div",{className:"lu-serif text-5xl md:text-6xl mb-6",style:{color:yC},children:_(P.price)}),e.jsxs("div",{className:"flex items-center gap-6 text-white/70 mb-8",children:[P.bedrooms&&e.jsxs("span",{className:"flex items-center gap-2",children:[e.jsx(A_,{className:"h-4 w-4",style:{color:Wc}}),P.bedrooms," bd"]}),P.bathrooms&&e.jsxs("span",{className:"flex items-center gap-2",children:[e.jsx(Wx,{className:"h-4 w-4",style:{color:Wc}}),P.bathrooms," ba"]}),P.square_footage&&e.jsxs("span",{className:"flex items-center gap-2",children:[e.jsx(L_,{className:"h-4 w-4",style:{color:Wc}}),P.square_footage.toLocaleString()," sf"]})]}),P.description&&e.jsx("p",{className:"text-white/60 leading-relaxed mb-8 line-clamp-4",children:P.description}),e.jsxs("div",{className:"inline-flex items-center gap-3 lu-eyebrow group-hover:gap-5 transition-all",style:{color:Wc},children:["View Residence ",e.jsx(vi,{className:"h-4 w-4"})]})]})]})})]})}),e.jsx("section",{id:"collection",className:"py-20 md:py-28",style:{background:ztt},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:Wc}}),e.jsx("span",{className:"lu-eyebrow lu-gold",children:"The Collection"}),e.jsx("span",{className:"h-px w-10",style:{background:Wc}})]}),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:yC},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."})]}),x?e.jsx("div",{className:"grid sm:grid-cols-2 lg:grid-cols-3 gap-8",children:[...Array(6)].map(($,V)=>e.jsxs("div",{className:"space-y-3",children:[e.jsx(xn,{className:"aspect-[4/5] bg-white/5"}),e.jsx(xn,{className:"h-6 w-32 bg-white/5"}),e.jsx(xn,{className:"h-4 w-full bg-white/5"})]},V))}):I.length>0?e.jsx("div",{className:"grid sm:grid-cols-2 lg:grid-cols-3 gap-x-8 gap-y-14",children:I.map($=>{var W,G,X,te,ne;const V=((W=$.photos)==null?void 0:W.find(me=>me.is_primary))||((G=$.photos)==null?void 0:G[0]);return e.jsxs(cr,{to:T($),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:$.property_address||$.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(_a,{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:Wc,border:`1px solid ${Wc}`},children:A6e[$.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:[$.bedrooms&&e.jsxs("span",{children:[$.bedrooms," bd"]}),$.bathrooms&&e.jsxs("span",{children:[$.bathrooms," ba"]}),$.square_footage&&e.jsxs("span",{children:[$.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(ii,{className:"h-3 w-3",style:{color:Wc}}),$.city,$.state?`, ${$.state}`:""]}),e.jsx("div",{className:"lu-serif text-2xl md:text-3xl mb-1",style:{color:yC},children:_($.price)}),$.property_address&&e.jsx("p",{className:"text-white/70 text-sm truncate",children:$.property_address}),((X=$.agent)==null?void 0:X.name)&&e.jsxs("p",{className:"text-white/40 text-xs mt-3 flex items-center gap-2",children:[e.jsx(Ti,{className:"h-3 w-3"}),$.agent.name,(((te=$.agent.brokerage)==null?void 0:te.name)||$.agent.brokerage_name)&&e.jsxs("span",{className:"truncate",children:["· ",((ne=$.agent.brokerage)==null?void 0:ne.name)||$.agent.brokerage_name]})]})]})]},$.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 ${Wc}`},children:e.jsx(_a,{className:"h-8 w-8",style:{color:Wc}})}),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."}),k&&e.jsx(B,{onClick:b,style:{background:Wc,color:cF},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:Wc}}),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:yC},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(Eis,{listings:y,isLoading:x})})]})}),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%, ${cF} 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:Wc}}),e.jsx("span",{className:"lu-eyebrow lu-gold",children:"For Agents"}),e.jsx("span",{className:"h-px w-10",style:{background:Wc}})]}),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:yC},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:Wc,color:cF},children:["Explore LevelUp",e.jsx(vi,{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:U2e,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(_as,{}),e.jsx(was,{})]})}const Lis=N.lazy(()=>Fi(()=>import("./PublicHomeValue-COg9DGBc.js"),[]));function Pis(){const s=Id(),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(q2t,{}):r==="home-value"||r==="whats-my-home-worth"?e.jsx(N.Suspense,{fallback:e.jsx("div",{}),children:e.jsx(Lis,{})}):r.startsWith("public/")?null:e.jsx(B2t,{slugOverride:r})}function _4e({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 V2t=s=>mt({queryKey:["agent-card-public",s],queryFn:async()=>{if(!s)throw new Error("No slug provided");const{data:t,error:n}=await H.from("agent_cards").select("*").eq("slug",s).eq("is_published",!0).single();if(n)throw n;const{data:r}=await H.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 H.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 H.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 H.storage.from("avatars").list(`${t.user_id}`);if(c&&c.length>0){const{data:d}=H.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}),Iis=()=>mt({queryKey:["agent-cards-admin"],queryFn:async()=>{const{data:s,error:t}=await H.from("agent_cards").select("*").order("created_at",{ascending:!1});if(t)throw t;return s}}),Dis=s=>mt({queryKey:["agent-card",s],queryFn:async()=>{if(!s)return null;const{data:t,error:n}=await H.from("agent_cards").select("*").eq("user_id",s).maybeSingle();if(n)throw n;return t},enabled:!!s}),H2t=()=>{const s=as();return _t({mutationFn:async t=>{const{data:n,error:r}=await H.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"]}),ie.success("Agent card created")},onError:t=>ie.error(t.message)})},G2t=()=>{const s=as();return _t({mutationFn:async({id:t,...n})=>{const{data:r,error:a}=await H.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"]}),ie.success("Agent card updated")},onError:t=>ie.error(t.message)})},Oc=async(s,t,n,r)=>{const a=new URLSearchParams(window.location.search);await H.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:{}})},Ris=async(s,t)=>{const{error:n}=await H.from("agent_card_leads").insert({card_id:s,...t});if(n)throw n},W2t=s=>mt({queryKey:["agent-card-analytics",s],queryFn:async()=>{if(!s)return null;const{data:t,error:n}=await H.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 H.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 w4e({open:s,onOpenChange:t,cardId:n,type:r,agentName:a}){const[i,l]=N.useState(""),[o,c]=N.useState(""),[d,u]=N.useState(""),[h,m]=N.useState(""),[f,g]=N.useState(""),[y,x]=N.useState(!1),_=async b=>{if(b.preventDefault(),!i.trim()){ie.error("Please enter your name");return}x(!0);try{await Ris(n,{lead_type:r,name:i.trim(),email:o.trim()||void 0,phone:d.trim()||void 0,message:f.trim()||void 0,intent:h||void 0}),Oc(n,"lead_submitted",r),H.functions.invoke("card-lead-notify",{body:{cardId:n,leadType:r,name:i.trim(),email:o.trim()||void 0,phone:d.trim()||void 0,message:f.trim()||void 0,intent:h||void 0}}).catch(k=>console.error("Card lead notify failed:",k)),ie.success(r==="booking"?"Request sent! They'll be in touch soon.":r==="connect"?"Info shared! They'll be in touch soon.":"Referral submitted! Thank you."),t(!1),l(""),c(""),u(""),m(""),g("")}catch{ie.error("Something went wrong. Please try again.")}finally{x(!1)}};return e.jsx(Bs,{open:s,onOpenChange:t,children:e.jsxs(Fs,{className:"sm:max-w-md rounded-2xl",children:[e.jsxs(qs,{children:[e.jsx($s,{children:r==="booking"?"Book a Call":r==="connect"?"Connect with Me":"Refer a Friend"}),e.jsx(Ar,{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:_,className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(re,{htmlFor:"lead-name",children:"Name *"}),e.jsx(we,{id:"lead-name",value:i,onChange:b=>l(b.target.value),placeholder:"Your name",required:!0})]}),e.jsxs("div",{children:[e.jsx(re,{htmlFor:"lead-phone",children:"Phone"}),e.jsx(we,{id:"lead-phone",type:"tel",value:d,onChange:b=>u(b.target.value),placeholder:"(555) 123-4567"})]}),e.jsxs("div",{children:[e.jsx(re,{htmlFor:"lead-email",children:"Email"}),e.jsx(we,{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(re,{htmlFor:"lead-intent",children:"I'm looking to..."}),e.jsxs(Ns,{value:h,onValueChange:m,children:[e.jsx(ws,{children:e.jsx(ks,{placeholder:"Select one"})}),e.jsxs(js,{children:[e.jsx(nt,{value:"buy",children:"Buy a home"}),e.jsx(nt,{value:"sell",children:"Sell my home"}),e.jsx(nt,{value:"both",children:"Buy & Sell"}),e.jsx(nt,{value:"other",children:"Something else"})]})]})]}),r!=="connect"&&e.jsxs("div",{children:[e.jsx(re,{htmlFor:"lead-message",children:r==="referral"?"Tell us about them":"Message (optional)"}),e.jsx(we,{id:"lead-message",value:f,onChange:b=>g(b.target.value),placeholder:r==="referral"?"Their name, phone, situation...":"Anything you'd like us to know"})]}),e.jsx(B,{type:"submit",className:"w-full rounded-2xl",disabled:y,children:y?"Sending...":"Submit"})]})]})})}const Ois=s=>mt({queryKey:["card-blocks",s],queryFn:async()=>{if(!s)return[];const{data:t,error:n}=await H.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}),Fis=s=>mt({queryKey:["card-blocks-all",s],queryFn:async()=>{if(!s)return[];const{data:t,error:n}=await H.from("card_blocks").select("*").eq("card_id",s).order("sort_order",{ascending:!0});if(n)throw n;return t||[]},enabled:!!s}),zis=()=>{const s=as();return _t({mutationFn:async t=>{const{data:n,error:r}=await H.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]}),ie.success("Block added")},onError:t=>ie.error(t.message)})},Bis=()=>{const s=as();return _t({mutationFn:async({id:t,...n})=>{const{data:r,error:a}=await H.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"]}),ie.success("Block updated")},onError:t=>ie.error(t.message)})},$is=()=>{const s=as();return _t({mutationFn:async t=>{const{error:n}=await H.from("card_blocks").delete().eq("id",t);if(n)throw n},onSuccess:()=>{s.invalidateQueries({queryKey:["card-blocks"]}),s.invalidateQueries({queryKey:["card-blocks-all"]}),ie.success("Block removed")},onError:t=>ie.error(t.message)})};function Uis(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 qis(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 Vis={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 His({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=qis(n.video_url),i=r||!!a,l=r?Uis(n.video_url):a||n.video_url;return e.jsx("div",{className:Vis[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 Gis={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 Wis({block:s,variant:t}){const r=s.config.testimonials||[],[a,i]=N.useState(0);if(r.length===0)return null;const l=Gis[t],o=r[a];return e.jsxs("div",{className:l.container,children:[e.jsxs("div",{className:l.card,children:[e.jsx(Q2,{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(Fc,{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(Qa,{className:"h-4 w-4"})})]})]})}const Kis={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 Yis({block:s,variant:t}){const r=s.config.tags||[];if(r.length===0)return null;const a=Kis[t];return e.jsx("div",{className:a.container,children:r.map((i,l)=>e.jsx("span",{className:a.tag,children:i},l))})}const Zis={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 Xis({block:s,cardId:t,variant:n}){const a=s.config.links||[];if(a.length===0)return null;const i=Zis[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:()=>Oc(t,"button_click",`custom_link_${l.label}`),className:i.link,children:[e.jsx("span",{children:l.label}),e.jsx(Tr,{className:`h-4 w-4 ${i.icon}`})]},o))})}const BDe={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 Qis({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 Jis={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 eos({block:s,cardId:t,variant:n}){const a=s.config.platforms||[],i=Jis[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=BDe[l.platform.toLowerCase()];return!c||!l.url?null:e.jsx("a",{href:l.url,target:"_blank",rel:"noopener noreferrer",onClick:()=>Oc(t,"button_click",`social_${l.platform}`),className:i.linkClass,title:c.label,children:e.jsx(Qis,{path:c.icon,color:c.color})},o)})})]})}function j4e({cardId:s,variant:t}){const{data:n}=Ois(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(His,{block:l,variant:t},l.id);case"testimonials":return e.jsx(Wis,{block:l,variant:t},l.id);case"specialties":return e.jsx(Yis,{block:l,variant:t},l.id);case"custom_links":return e.jsx(Xis,{block:l,cardId:s,variant:t},l.id);default:return null}}),i&&e.jsx(eos,{block:i,cardId:s,variant:t})]})}async function tos(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 sos(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 N4e(s){const{first:t,last:n}=sos(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 tos(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),ie.success("Contact saved!")}function nos({card:s}){var _;const[t,n]=N.useState(!1),[r,a]=N.useState("booking"),i=((_=s.profile)==null?void 0:_.name)||"Agent",l=i.split(" ").map(b=>b[0]).join("").toUpperCase().slice(0,2),o=(b,k)=>{Oc(s.id,"button_click",b),k()},c=()=>o("call",()=>{var b;(b=s.profile)!=null&&b.phone?window.location.href=`tel:${s.profile.phone}`:ie.error("Phone number not available")}),d=()=>o("text",()=>{var b;(b=s.profile)!=null&&b.phone?window.location.href=`sms:${s.profile.phone}`:ie.error("Phone number not available")}),u=()=>o("email",()=>{var b;(b=s.profile)!=null&&b.email?window.location.href=`mailto:${s.profile.email}`:ie.error("Email not available")}),h=()=>{s.booking_url?o("book",()=>window.open(s.booking_url,"_blank")):(a("booking"),n(!0),Oc(s.id,"button_click","book"))},m=()=>{var b,k;Oc(s.id,"contact_saved"),N4e({name:i,phone:(b=s.profile)==null?void 0:b.phone,email:(k=s.profile)==null?void 0:k.email,brokerage:s.brokerage_name,avatarUrl:s.avatar_url,cardUrl:window.location.href})},f=async()=>{Oc(s.id,"share_event");const b=`https://cards.relevelup.com/${s.slug}`,k="Here's my contact card — save it so we can stay in touch.";if(navigator.share)try{await navigator.share({title:`${i}`,text:k,url:b})}catch{}else await navigator.clipboard.writeText(b),ie.success("Link copied!")},g=()=>{a("referral"),n(!0),Oc(s.id,"button_click","refer")},y=()=>{a("connect"),n(!0),Oc(s.id,"button_click","connect")},x={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(Ua,{className:"h-28 w-28 mx-auto mb-4 ring-4 ring-white shadow-lg",children:[e.jsx(Gi,{src:s.avatar_url||void 0,alt:i}),e.jsx(qa,{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(ga,{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(xo,{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(mn,{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(ta,{className:"h-5 w-5 mr-2"}),s.custom_cta_label||"Book a Call"]}),s.show_credentials&&s.review_snippet&&e.jsx("div",{className:"flex items-center justify-center gap-4 mb-6 text-sm text-slate-600",children:e.jsxs("div",{className:"text-center flex items-center gap-1",children:[e.jsx(Wa,{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(_4e,{card:s,variant:"standard"}),e.jsx(j4e,{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(oi,{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:()=>{Oc(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(Wa,{className:"h-4 w-4 mr-3 text-amber-500"}),"Leave a Review"]}),s.show_refer_friend&&e.jsxs(B,{variant:"ghost",onClick:g,className:"w-full justify-start h-12 rounded-2xl text-slate-700 hover:bg-slate-100",children:[e.jsx(Yn,{className:"h-4 w-4 mr-3 text-primary"}),"Refer a Friend"]}),e.jsxs(B,{variant:"ghost",onClick:y,className:"w-full justify-start h-12 rounded-2xl text-slate-700 hover:bg-slate-100",children:[e.jsx(Yl,{className:"h-4 w-4 mr-3 text-primary"}),"Connect with Me"]}),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(Md,{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,k)=>e.jsx("a",{href:b.url,target:"_blank",rel:"noopener noreferrer",onClick:()=>Oc(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:x[b.platform.toLowerCase()]||"🔗"},k))}),e.jsx("div",{className:"text-center",children:e.jsx("p",{className:"text-xs text-slate-400",children:"Powered by LevelUp"})})]}),e.jsx(w4e,{open:t,onOpenChange:n,cardId:s.id,type:r,agentName:i})]})}function ros({card:s}){var _;const[t,n]=N.useState(!1),[r,a]=N.useState("booking"),i=((_=s.profile)==null?void 0:_.name)||"Agent",l=i.split(" ").map(b=>b[0]).join("").toUpperCase().slice(0,2),o=(b,k)=>{Oc(s.id,"button_click",b),k()},c=()=>o("call",()=>{var b;(b=s.profile)!=null&&b.phone?window.location.href=`tel:${s.profile.phone}`:ie.error("Phone number not available")}),d=()=>o("text",()=>{var b;(b=s.profile)!=null&&b.phone?window.location.href=`sms:${s.profile.phone}`:ie.error("Phone number not available")}),u=()=>o("email",()=>{var b;(b=s.profile)!=null&&b.email?window.location.href=`mailto:${s.profile.email}`:ie.error("Email not available")}),h=()=>{s.booking_url?o("book",()=>window.open(s.booking_url,"_blank")):(a("booking"),n(!0),Oc(s.id,"button_click","book"))},m=()=>{var b,k;Oc(s.id,"contact_saved"),N4e({name:i,phone:(b=s.profile)==null?void 0:b.phone,email:(k=s.profile)==null?void 0:k.email,brokerage:s.brokerage_name,avatarUrl:s.avatar_url,cardUrl:window.location.href})},f=async()=>{Oc(s.id,"share_event");const b=`https://cards.relevelup.com/${s.slug}`,k="Here's my contact card — save it so we can stay in touch.";if(navigator.share)try{await navigator.share({title:`${i}`,text:k,url:b})}catch{}else await navigator.clipboard.writeText(b),ie.success("Link copied!")},g=()=>{a("referral"),n(!0),Oc(s.id,"button_click","refer")},y=()=>{a("connect"),n(!0),Oc(s.id,"button_click","connect")},x={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(Ua,{className:"h-32 w-32 mx-auto mb-5 ring-2 ring-[#c9a84c]/40 shadow-2xl",children:[e.jsx(Gi,{src:s.avatar_url||void 0,alt:i}),e.jsx(qa,{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:ga,label:"Call",handler:c},{icon:xo,label:"Text",handler:d},{icon:mn,label:"Email",handler:u}].map(({icon:b,label:k,handler:A})=>e.jsxs("button",{onClick:A,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:k})]},k))}),e.jsxs("button",{onClick:h,className:"w-full h-12 text-base font-semibold rounded-xl mb-6 bg-gradient-to-r from-[#c9a84c] to-[#e8d48b] text-[#0f1419] hover:opacity-90 transition-opacity flex items-center justify-center gap-2",children:[e.jsx(ta,{className:"h-5 w-5"}),s.custom_cta_label||"Book a Call"]}),s.show_credentials&&s.review_snippet&&e.jsx("div",{className:"flex items-center justify-center gap-4 mb-6 text-sm",children:e.jsxs("div",{className:"text-center flex items-center gap-1",children:[e.jsx(Wa,{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(_4e,{card:s,variant:"luxury"}),e.jsx(j4e,{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(oi,{className:"h-4 w-4 text-[#c9a84c]"})," Save Contact"]}),s.show_leave_review&&s.review_source_url&&e.jsxs("button",{onClick:()=>{Oc(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(Wa,{className:"h-4 w-4 text-[#c9a84c]"})," Leave a Review"]}),s.show_refer_friend&&e.jsxs("button",{onClick:g,className:"w-full flex items-center gap-3 h-12 px-4 rounded-xl text-[#e2e8f0] hover:bg-[#1e2636] transition-colors text-sm",children:[e.jsx(Yn,{className:"h-4 w-4 text-[#c9a84c]"})," Refer a Friend"]}),e.jsxs("button",{onClick: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(Yl,{className:"h-4 w-4 text-[#c9a84c]"})," Connect with Me"]}),e.jsxs("button",{onClick:f,className:"w-full flex items-center gap-3 h-12 px-4 rounded-xl text-[#e2e8f0] hover:bg-[#1e2636] transition-colors text-sm",children:[e.jsx(Md,{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,k)=>e.jsx("a",{href:b.url,target:"_blank",rel:"noopener noreferrer",onClick:()=>Oc(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:x[b.platform.toLowerCase()]||"🔗"},k))}),e.jsx("div",{className:"text-center",children:e.jsx("p",{className:"text-xs text-[#4a5568]",children:"Powered by LevelUp"})})]}),e.jsx(w4e,{open:t,onOpenChange:n,cardId:s.id,type:r,agentName:i})]})}function aos({card:s}){var k,A,T,P;const[t,n]=N.useState(!1),[r,a]=N.useState("booking"),i=((k=s.profile)==null?void 0:k.name)||"Agent",l=i.split(" ").map(I=>I[0]).join("").toUpperCase().slice(0,2),o={accent:((A=s.bold_theme_colors)==null?void 0:A.accent)||"#ff5722",dark:((T=s.bold_theme_colors)==null?void 0:T.dark)||"#1a1a2e",button:((P=s.bold_theme_colors)==null?void 0:P.button)||"#ff5722"},c=(I,M)=>{const L=parseInt(I.replace("#",""),16),z=Math.max(0,(L>>16)-M),$=Math.max(0,(L>>8&255)-M),V=Math.max(0,(L&255)-M);return`#${(z<<16|$<<8|V).toString(16).padStart(6,"0")}`};c(o.accent,25),c(o.dark,-20),c(o.button,25);const d=(I,M)=>{Oc(s.id,"button_click",I),M()},u=()=>d("call",()=>{var I;(I=s.profile)!=null&&I.phone?window.location.href=`tel:${s.profile.phone}`:ie.error("Phone number not available")}),h=()=>d("text",()=>{var I;(I=s.profile)!=null&&I.phone?window.location.href=`sms:${s.profile.phone}`:ie.error("Phone number not available")}),m=()=>d("email",()=>{var I;(I=s.profile)!=null&&I.email?window.location.href=`mailto:${s.profile.email}`:ie.error("Email not available")}),f=()=>{s.booking_url?d("book",()=>window.open(s.booking_url,"_blank")):(a("booking"),n(!0),Oc(s.id,"button_click","book"))},g=()=>{var I,M;Oc(s.id,"contact_saved"),N4e({name:i,phone:(I=s.profile)==null?void 0:I.phone,email:(M=s.profile)==null?void 0:M.email,brokerage:s.brokerage_name,avatarUrl:s.avatar_url,cardUrl:window.location.href})},y=async()=>{Oc(s.id,"share_event");const I=`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:I})}catch{}else await navigator.clipboard.writeText(I),ie.success("Link copied!")},x=()=>{a("referral"),n(!0),Oc(s.id,"button_click","refer")},_=()=>{a("connect"),n(!0),Oc(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(Ua,{className:"h-28 w-28 mx-auto mb-4 shadow-2xl",style:{boxShadow:`0 0 0 4px ${o.accent}`},children:[e.jsx(Gi,{src:s.avatar_url||void 0,alt:i}),e.jsx(qa,{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:ga,label:"Call",handler:u},{icon:xo,label:"Text",handler:h},{icon:mn,label:"Email",handler:m}].map(({icon:I,label:M,handler:L})=>e.jsxs("button",{onClick:L,className:"flex flex-col items-center gap-1.5 py-4 text-white rounded-2xl transition-opacity font-bold hover:opacity-85",style:{backgroundColor:o.dark},children:[e.jsx(I,{className:"h-5 w-5"}),e.jsx("span",{className:"text-xs",children:M})]},M))}),e.jsxs("button",{onClick:f,className:"w-full h-14 text-base font-black rounded-2xl mb-6 text-white transition-opacity hover:opacity-90 flex items-center justify-center gap-2 uppercase tracking-wide",style:{backgroundColor:o.button},children:[e.jsx(ta,{className:"h-5 w-5"}),s.custom_cta_label||"Book a Call"]}),s.show_credentials&&s.review_snippet&&e.jsx("div",{className:"flex items-center justify-center gap-5 mb-6",children:s.review_snippet&&e.jsxs("div",{className:"text-center flex items-center gap-1",children:[e.jsx(Wa,{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(_4e,{card:s,variant:"bold"}),e.jsx(j4e,{cardId:s.id,variant:"bold"}),e.jsxs("div",{className:"space-y-1 mb-6",children:[s.show_save_contact&&e.jsxs("button",{onClick:g,className:"w-full flex items-center gap-3 h-12 px-4 rounded-2xl hover:bg-gray-100 transition-colors text-sm font-bold",style:{color:o.dark},children:[e.jsx(oi,{className:"h-4 w-4",style:{color:o.accent}})," Save Contact"]}),s.show_leave_review&&s.review_source_url&&e.jsxs("button",{onClick:()=>{Oc(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(Wa,{className:"h-4 w-4",style:{color:o.accent}})," Leave a Review"]}),s.show_refer_friend&&e.jsxs("button",{onClick:x,className:"w-full flex items-center gap-3 h-12 px-4 rounded-2xl hover:bg-gray-100 transition-colors text-sm font-bold",style:{color:o.dark},children:[e.jsx(Yn,{className:"h-4 w-4",style:{color:o.accent}})," Refer a Friend"]}),e.jsxs("button",{onClick:_,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(Yl,{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(Md,{className:"h-4 w-4",style:{color:o.accent}})," Share My Card"]})]}),s.show_social_links&&s.social_links&&s.social_links.length>0&&e.jsx("div",{className:"flex justify-center gap-4 mb-6",children:s.social_links.slice(0,3).map((I,M)=>e.jsx("a",{href:I.url,target:"_blank",rel:"noopener noreferrer",onClick:()=>Oc(s.id,"button_click",`social_${I.platform}`),className:"h-10 w-10 rounded-full flex items-center justify-center text-lg transition-opacity hover:opacity-85",style:{backgroundColor:o.dark},children:b[I.platform.toLowerCase()]||"🔗"},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(w4e,{open:t,onOpenChange:n,cardId:s.id,type:r,agentName:i})]})}function ios({card:s}){var _;const[t,n]=N.useState(!1),[r,a]=N.useState("booking"),i=((_=s.profile)==null?void 0:_.name)||"Agent",l=i.split(" ").map(b=>b[0]).join("").toUpperCase().slice(0,2),o=(b,k)=>{Oc(s.id,"button_click",b),k()},c=()=>o("call",()=>{var b;(b=s.profile)!=null&&b.phone?window.location.href=`tel:${s.profile.phone}`:ie.error("Phone number not available")}),d=()=>o("text",()=>{var b;(b=s.profile)!=null&&b.phone?window.location.href=`sms:${s.profile.phone}`:ie.error("Phone number not available")}),u=()=>o("email",()=>{var b;(b=s.profile)!=null&&b.email?window.location.href=`mailto:${s.profile.email}`:ie.error("Email not available")}),h=()=>{s.booking_url?o("book",()=>window.open(s.booking_url,"_blank")):(a("booking"),n(!0),Oc(s.id,"button_click","book"))},m=()=>{var b,k;Oc(s.id,"contact_saved"),N4e({name:i,phone:(b=s.profile)==null?void 0:b.phone,email:(k=s.profile)==null?void 0:k.email,brokerage:s.brokerage_name,avatarUrl:s.avatar_url,cardUrl:window.location.href})},f=async()=>{Oc(s.id,"share_event");const b=`https://cards.relevelup.com/${s.slug}`,k="Here's my contact card — save it so we can stay in touch.";if(navigator.share)try{await navigator.share({title:`${i}`,text:k,url:b})}catch{}else await navigator.clipboard.writeText(b),ie.success("Link copied!")},g=()=>{a("referral"),n(!0),Oc(s.id,"button_click","refer")},y=()=>{a("connect"),n(!0),Oc(s.id,"button_click","connect")},x={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(Ua,{className:"h-28 w-28 mx-auto mb-4 ring-4 ring-white shadow-lg",children:[e.jsx(Gi,{src:s.avatar_url||void 0,alt:i}),e.jsx(qa,{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:ga,label:"Call",handler:c},{icon:xo,label:"Text",handler:d},{icon:mn,label:"Email",handler:u}].map(({icon:b,label:k,handler:A})=>e.jsxs("button",{onClick:A,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:k})]},k))}),e.jsxs("button",{onClick:h,className:"w-full h-12 text-base font-semibold rounded-lg mb-6 bg-[#1b3a4b] hover:bg-[#264d61] text-white transition-colors flex items-center justify-center gap-2 shadow-sm",children:[e.jsx(ta,{className:"h-5 w-5"}),s.custom_cta_label||"Book a Call"]}),s.show_credentials&&s.review_snippet&&e.jsx("div",{className:"bg-white rounded-lg border border-[#d4cfc5] p-4 mb-6 shadow-sm",children:e.jsx("div",{className:"flex items-center justify-center gap-6",children:e.jsxs("div",{className:"text-center flex items-center gap-1",children:[e.jsx(Wa,{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(_4e,{card:s,variant:"classic"}),e.jsx(j4e,{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(oi,{className:"h-4 w-4 text-[#5a7a6f]"})," Save Contact"]}),s.show_leave_review&&s.review_source_url&&e.jsxs("button",{onClick:()=>{Oc(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(Wa,{className:"h-4 w-4 text-[#d4a843]"})," Leave a Review"]}),s.show_refer_friend&&e.jsxs("button",{onClick:g,className:"w-full flex items-center gap-3 h-12 px-4 text-[#1b3a4b] hover:bg-[#f5f1eb] transition-colors text-sm font-medium",children:[e.jsx(Yn,{className:"h-4 w-4 text-[#5a7a6f]"})," Refer a Friend"]}),e.jsxs("button",{onClick: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(Yl,{className:"h-4 w-4 text-[#5a7a6f]"})," Connect with Me"]}),e.jsxs("button",{onClick:f,className:"w-full flex items-center gap-3 h-12 px-4 text-[#1b3a4b] hover:bg-[#f5f1eb] transition-colors text-sm font-medium",children:[e.jsx(Md,{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,k)=>e.jsx("a",{href:b.url,target:"_blank",rel:"noopener noreferrer",onClick:()=>Oc(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:x[b.platform.toLowerCase()]||"🔗"},k))}),e.jsx("div",{className:"text-center",children:e.jsx("p",{className:"text-xs text-[#a0aec0]",children:"Powered by LevelUp"})})]}),e.jsx(w4e,{open:t,onOpenChange:n,cardId:s.id,type:r,agentName:i})]})}function W$e({card:s}){switch(s.theme){case"luxury":return e.jsx(ros,{card:s});case"bold":return e.jsx(aos,{card:s});case"classic":return e.jsx(ios,{card:s});case"standard":default:return e.jsx(nos,{card:s})}}function oos(){const s=Id();N.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(los,{slug:t})}function los({slug:s}){return e.jsx(cos,{slug:s})}function cos({slug:s}){var i;const{data:t,isLoading:n,error:r}=V2t(s);if(N.useEffect(()=>{t!=null&&t.id&&Oc(t.id,"card_view")},[t==null?void 0:t.id]),n)return e.jsx("div",{className:"min-h-screen bg-gradient-to-b from-slate-50 to-white flex items-center justify-center",children:e.jsxs("div",{className:"w-full max-w-md mx-auto p-6 space-y-6",children:[e.jsxs("div",{className:"flex flex-col items-center gap-4",children:[e.jsx(xn,{className:"h-28 w-28 rounded-full"}),e.jsx(xn,{className:"h-6 w-48"}),e.jsx(xn,{className:"h-4 w-36"})]}),e.jsx(xn,{className:"h-12 w-full"}),e.jsx(xn,{className:"h-12 w-full"})]})});if(r||!t)return e.jsx("div",{className:"min-h-screen bg-gradient-to-b from-slate-50 to-white flex items-center justify-center p-6",children:e.jsxs("div",{className:"text-center",children:[e.jsx("h1",{className:"text-2xl font-bold text-slate-800 mb-2",children:"Card Not Found"}),e.jsx("p",{className:"text-slate-500",children:"This agent card doesn't exist or isn't published yet."})]})});const a=((i=t.profile)==null?void 0:i.name)||"Agent";return e.jsxs(e.Fragment,{children:[e.jsxs(ic,{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(W$e,{card:t})]})}function K2t({presentationId:s,ctaLabel:t,agentName:n,prefillName:r,prefillEmail:a,prefillPhone:i}){const[l,o]=N.useState(r||""),[c,d]=N.useState(a||""),[u,h]=N.useState(i||""),[m,f]=N.useState(""),[g,y]=N.useState(""),[x,_]=N.useState(!1),[b,k]=N.useState(!1),A=async T=>{if(T.preventDefault(),!l.trim()){ie.error("Please enter your name");return}_(!0);try{const{error:P}=await H.from("smart_presentation_leads").insert({presentation_id:s,name:l.trim(),email:c.trim()||null,phone:u.trim()||null,intent:m||null,message:g.trim()||null});if(P)throw P;try{await H.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{}H.functions.invoke("presentation-lead-notify",{body:{presentationId:s,name:l.trim(),email:c.trim()||void 0,phone:u.trim()||void 0,intent:m||void 0,message:g.trim()||void 0}}).catch(I=>console.error("Presentation lead notify failed:",I)),k(!0)}catch{ie.error("Something went wrong. Please try again.")}finally{_(!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(pa,{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:A,className:"space-y-4 max-w-md mx-auto",children:[e.jsxs("div",{children:[e.jsx(re,{htmlFor:"pres-lead-name",children:"Name *"}),e.jsx(we,{id:"pres-lead-name",value:l,onChange:T=>o(T.target.value),placeholder:"Your name",required:!0})]}),e.jsxs("div",{children:[e.jsx(re,{htmlFor:"pres-lead-phone",children:"Phone"}),e.jsx(we,{id:"pres-lead-phone",type:"tel",value:u,onChange:T=>h(T.target.value),placeholder:"(555) 123-4567"})]}),e.jsxs("div",{children:[e.jsx(re,{htmlFor:"pres-lead-email",children:"Email"}),e.jsx(we,{id:"pres-lead-email",type:"email",value:c,onChange:T=>d(T.target.value),placeholder:"you@example.com"})]}),e.jsxs("div",{children:[e.jsx(re,{htmlFor:"pres-lead-intent",children:"I'm looking to..."}),e.jsxs(Ns,{value:m,onValueChange:f,children:[e.jsx(ws,{children:e.jsx(ks,{placeholder:"Select one"})}),e.jsxs(js,{children:[e.jsx(nt,{value:"buy",children:"Buy a home"}),e.jsx(nt,{value:"sell",children:"Sell my home"}),e.jsx(nt,{value:"both",children:"Buy & Sell"}),e.jsx(nt,{value:"other",children:"Something else"})]})]})]}),e.jsxs("div",{children:[e.jsx(re,{htmlFor:"pres-lead-message",children:"Message (optional)"}),e.jsx(we,{id:"pres-lead-message",value:g,onChange:T=>y(T.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:x,children:x?"Sending...":t})]})}function dos(){const s=Id();N.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(uos,{shareToken:t})}function uos({shareToken:s}){var g;const[t,n]=N.useState(null),[r,a]=N.useState(!0),[i,l]=N.useState(0),[o,c]=N.useState(!1);N.useEffect(()=>{d()},[s]);const d=async()=>{const{data:y,error:x}=await H.from("smart_presentations").select("*").eq("share_token",s).eq("status","published").single();if(x||!y){c(!0),a(!1);return}const{data:_}=await H.from("profiles").select("name, email, phone, avatar_url, title, brokerage_id").eq("id",y.owner_user_id).single();let b;if(_!=null&&_.brokerage_id){const{data:A}=await H.from("brokerages").select("name").eq("id",_.brokerage_id).single();b=(A==null?void 0:A.name)||void 0}let k=null;if(y.contact_id){const{data:A}=await H.from("innercircle_contacts").select("first_name, last_name, email, phone").eq("id",y.contact_id).single();k=A}n({...y,owner_name:_==null?void 0:_.name,owner_email:_==null?void 0:_.email,owner_phone:_==null?void 0:_.phone,owner_avatar:_==null?void 0:_.avatar_url,owner_title:(_==null?void 0:_.title)||void 0,brokerage_name:b,contact_name:k?[k.first_name,k.last_name].filter(Boolean).join(" "):void 0,contact_email:(k==null?void 0:k.email)||void 0,contact_phone:(k==null?void 0:k.phone)||void 0}),a(!1);try{await H.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 H.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 x=y.match(/(?:youtube\.com\/watch\?v=|youtu\.be\/)([a-zA-Z0-9_-]+)/);if(x)return`https://www.youtube.com/embed/${x[1]}?rel=0`;if(y.includes("iframe.mediadelivery.net/play/")){const k=y.replace("/play/","/embed/"),A=k.includes("?")?"&":"?";return`${k}${A}responsive=true`}if(y.includes("iframe.mediadelivery.net")){const k=y.includes("?")?"&":"?";return`${y}${k}responsive=true`}const _=y.match(/loom\.com\/share\/([a-zA-Z0-9]+)/);if(_)return`https://www.loom.com/embed/${_[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(xn,{className:"h-12 w-3/4 mx-auto"}),e.jsx(xn,{className:"h-64 w-full"}),e.jsx(xn,{className:"h-8 w-1/2 mx-auto"})]})});if(o||!t)return e.jsx("div",{className:"min-h-screen bg-white flex items-center justify-center",children:e.jsxs("div",{className:"text-center",children:[e.jsx("h1",{className:"text-2xl font-bold mb-2",children:"Presentation Not Found"}),e.jsx("p",{className:"text-gray-500",children:"This presentation may have been removed or is no longer available."})]})});const m=t.sections.filter(y=>y.is_visible!==!1),f=m[i];return e.jsxs("div",{className:"min-h-screen bg-gradient-to-b from-slate-50 to-white",children:[e.jsx("header",{className:"bg-white border-b border-gray-100 sticky top-0 z-10",children:e.jsx("div",{className:"max-w-5xl mx-auto px-4 py-3 flex items-center justify-end",children:e.jsxs("div",{className:"flex items-center gap-3",children:[t.owner_avatar&&e.jsx("img",{src:t.owner_avatar,alt:t.owner_name||"Agent",className:"h-10 w-10 rounded-full object-cover border border-gray-200"}),e.jsxs("div",{className:"text-right text-sm",children:[e.jsx("p",{className:"font-semibold text-gray-900",children:t.owner_name}),t.owner_title&&e.jsx("p",{className:"text-gray-500 text-xs",children:t.owner_title}),t.brokerage_name&&!t.owner_title&&e.jsx("p",{className:"text-gray-500 text-xs",children:t.brokerage_name})]})]})})}),e.jsxs("main",{className:"max-w-5xl mx-auto px-4 py-8",children:[e.jsxs("div",{className:"text-center mb-8",children:[e.jsx("h1",{className:"text-3xl md:text-4xl font-bold text-gray-900 mb-2",children:t.heading||(t.client_name?`Welcome, ${t.client_name}!`:t.title)}),t.property_address&&e.jsxs("p",{className:"text-lg text-gray-600",children:["Here's the plan for your home at ",e.jsx("strong",{children:t.property_address}),"."]})]}),e.jsxs("div",{className:"grid md:grid-cols-5 gap-8",children:[e.jsxs("div",{className:"md:col-span-3",children:[f!=null&&f.video_url?e.jsx("div",{className:"relative w-full rounded-xl overflow-hidden shadow-lg bg-gray-900",style:{paddingTop:"56.25%"},children:e.jsx("iframe",{src:h(f.video_url),className:"absolute inset-0 w-full h-full border-0",allow:"accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture",allowFullScreen:!0,loading:"lazy"})}):f!=null&&f.image_url?e.jsx("div",{className:"rounded-xl overflow-hidden shadow-lg",children:e.jsx("img",{src:f.image_url,alt:f.title,className:"w-full h-auto object-cover",loading:"lazy"})}):e.jsxs("div",{className:"aspect-video bg-gradient-to-br from-blue-50 to-slate-100 rounded-xl flex flex-col items-center justify-center shadow-lg",children:[e.jsx("span",{className:"text-5xl mb-3",children:f==null?void 0:f.icon}),e.jsx("h3",{className:"text-xl font-semibold text-gray-800",children:f==null?void 0:f.title}),e.jsx("p",{className:"text-gray-500 mt-1 text-sm",children:f==null?void 0:f.description})]}),(f==null?void 0:f.text)&&e.jsx("div",{className:"mt-4 p-4 bg-white rounded-lg border text-gray-700 text-sm leading-relaxed prose prose-sm max-w-none",dangerouslySetInnerHTML:{__html:f.text}})]}),e.jsx("div",{className:"md:col-span-2 space-y-3",children:m.map((y,x)=>e.jsx("button",{onClick:()=>l(x),className:Ot("w-full text-left p-4 rounded-xl border transition-all",i===x?"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(x+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})]})]})},x))})]}),e.jsxs("div",{className:"mt-12 max-w-md mx-auto bg-white rounded-2xl border border-gray-200 shadow-sm p-6 text-center",children:[t.owner_avatar&&e.jsx("img",{src:t.owner_avatar,alt:t.owner_name||"Agent",className:"h-20 w-20 rounded-full object-cover mx-auto mb-3 border-2 border-gray-100"}),e.jsx("h3",{className:"text-lg font-bold text-gray-900",children:t.owner_name}),t.owner_title&&e.jsx("p",{className:"text-sm text-gray-500",children:t.owner_title}),t.brokerage_name&&e.jsx("p",{className:"text-sm text-gray-500",children:t.brokerage_name}),e.jsxs("div",{className:"mt-3 flex flex-col items-center gap-1 text-sm text-gray-600",children:[t.owner_phone&&e.jsx("a",{href:`tel:${t.owner_phone}`,className:"hover:text-blue-600 transition-colors",children:t.owner_phone}),t.owner_email&&e.jsx("a",{href:`mailto:${t.owner_email}`,className:"hover:text-blue-600 transition-colors",children:t.owner_email})]})]}),t.cta_label&&e.jsxs("div",{className:"text-center mt-8 py-8",children:[e.jsx("h2",{className:"text-2xl font-bold text-gray-900 mb-4",children:"Ready to Get Started?"}),(g=t.cta_url)!=null&&g.trim()?e.jsxs(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(Tr,{className:"h-5 w-5 ml-2"})]}):e.jsx("div",{className:"max-w-md mx-auto bg-white rounded-2xl border border-gray-200 shadow-sm p-6",children:e.jsx(K2t,{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"})]})}const Cj=()=>{const s=Ya();return mt({queryKey:["user-team",s],queryFn:async()=>{const{data:t,error:n}=await H.from("team_members").select("id, team_id, role").eq("user_id",s).maybeSingle();if(console.log("[useUserTeam] membership query:",{userId:s,membership:t,error:n}),n)throw n;if(!t)return null;const{data:r,error:a}=await H.from("teams").select("*").eq("id",t.team_id).single();if(a)throw a;return{membershipId:t.id,teamId:t.team_id,role:t.role,team:r}},enabled:!!s,staleTime:5*60*1e3})};function hos(){const{user:s}=Ls(),t=Ya(),{data:n}=Cj();return mt({queryKey:["open-houses",t,n==null?void 0:n.teamId,n==null?void 0:n.role],queryFn:async()=>{const{data:r,error:a}=await H.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 H.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 H.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 IOn(s){const{user:t}=Ls();return mt({queryKey:["open-house",s],queryFn:async()=>{const{data:n,error:r}=await H.from("open_houses").select("*").eq("id",s).single();if(r)throw r;return n},enabled:!!t&&!!s})}function Y2t(s){const{user:t}=Ls(),n=as();return N.useEffect(()=>{if(!s)return;const r=`visitors-${s}-${Math.random().toString(36).slice(2,10)}`,a=H.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()=>{H.removeChannel(a)}},[s,n]),mt({queryKey:["open-house-visitors",s],queryFn:async()=>{const{data:r,error:a}=await H.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 mos(){const s=as(),t=Ya();return _t({mutationFn:async n=>{const{data:r,error:a}=await H.from("open_houses").insert({...n,agent_id:t}).select().single();if(a)throw a;return r},onSuccess:()=>{s.invalidateQueries({queryKey:["open-houses"]}),xa({title:"Open house created!"})},onError:n=>{xa({title:"Error",description:n.message,variant:"destructive"})}})}function Z2t(){const s=as();return _t({mutationFn:async({id:t,...n})=>{const{error:r}=await H.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 pos(){const s=as();return _t({mutationFn:async t=>{const{error:n}=await H.from("open_houses").delete().eq("id",t);if(n)throw n},onSuccess:()=>{s.invalidateQueries({queryKey:["open-houses"]}),xa({title:"Open house deleted"})}})}function fos(s){return mt({queryKey:["public-open-house",s],queryFn:async()=>{const{data:t,error:n}=await H.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 H.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 gos(s){const{user:t}=Ls();return mt({queryKey:["survey-questions",s],queryFn:async()=>{const{data:n,error:r}=await H.from("open_house_survey_questions").select("*").eq("open_house_id",s).order("sort_order");if(r)throw r;return n},enabled:!!t&&!!s})}function xos(s){return mt({queryKey:["public-survey-questions",s],queryFn:async()=>{const{data:t,error:n}=await H.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 yos(){return _t({mutationFn:async s=>{const{error:t}=await H.from("open_house_survey_responses").insert(s);if(t)throw t}})}function vos(s){const{user:t}=Ls();return mt({queryKey:["survey-responses",s],queryFn:async()=>{const{data:n,error:r}=await H.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 H.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 bos(){const s=as();return _t({mutationFn:async t=>{const{data:n,error:r}=await H.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 _os(){const s=as();return _t({mutationFn:async({id:t,open_house_id:n,...r})=>{const{error:a}=await H.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 wos(){const s=as();return _t({mutationFn:async({id:t,open_house_id:n})=>{const{error:r}=await H.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 jos(){const s=as();return _t({mutationFn:async t=>{const{error:n}=await H.rpc("seed_default_survey_questions",{_open_house_id:t});if(n)throw n},onSuccess:(t,n)=>{s.invalidateQueries({queryKey:["survey-questions",n]})}})}function Nos(){return _t({mutationFn:async s=>{const{data:t,error:n}=await H.from("open_house_visitors").insert(s).select("id").single();if(n)throw n;return t}})}function kos(){return _t({mutationFn:async({visitor_id:s,...t})=>{const{error:n}=await H.from("open_house_visitors").update(t).eq("id",s);if(n)throw n}})}function Sos(){return _t({mutationFn:async s=>{await H.rpc("increment_open_house_scan",{_slug:s})}})}async function X2t(s){const{data:t,error:n}=await H.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 H.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 Cos(s){const{user:t}=Ls();return mt({queryKey:["open-house-rooms",s],queryFn:()=>X2t(s),enabled:!!t&&!!s})}function Aos(s){return mt({queryKey:["public-open-house-rooms",s],queryFn:()=>X2t(s),enabled:!!s})}function Tos(){const s=as();return _t({mutationFn:async t=>{const{data:n,error:r}=await H.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 Eos(){const s=as();return _t({mutationFn:async({id:t,open_house_id:n,...r})=>{const{error:a}=await H.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 Mos(){const s=as();return _t({mutationFn:async({id:t,open_house_id:n})=>{const{error:r}=await H.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 Los(){const s=as();return _t({mutationFn:async({open_house_id:t,...n})=>{const{data:r,error:a}=await H.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 Pos(){const s=as();return _t({mutationFn:async({id:t,open_house_id:n})=>{const{error:r}=await H.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 Ios(s){const{user:t}=Ls();return mt({queryKey:["open-house-leads",s],queryFn:async()=>{const{data:n,error:r}=await H.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 Dos(){const s=as();return _t({mutationFn:async({id:t,status:n,open_house_id:r})=>{const{error:a}=await H.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 k4e="Switch",[Ros,DOn]=Um(k4e),[Oos,Fos]=Ros(k4e),Q2t=N.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,f]=N.useState(null),g=jo(t,k=>f(k)),y=N.useRef(!1),x=m?u||!!m.closest("form"):!0,[_,b]=Ng({prop:a,defaultProp:i??!1,onChange:d,caller:k4e});return e.jsxs(Oos,{scope:n,checked:_,disabled:o,children:[e.jsx(Da.button,{type:"button",role:"switch","aria-checked":_,"aria-required":l,"data-state":sNt(_),"data-disabled":o?"":void 0,disabled:o,value:c,...h,ref:g,onClick:la(s.onClick,k=>{b(A=>!A),x&&(y.current=k.isPropagationStopped(),y.current||k.stopPropagation())})}),x&&e.jsx(tNt,{control:m,bubbles:!y.current,name:r,value:c,checked:_,required:l,disabled:o,form:u,style:{transform:"translateX(-100%)"}})]})});Q2t.displayName=k4e;var J2t="SwitchThumb",eNt=N.forwardRef((s,t)=>{const{__scopeSwitch:n,...r}=s,a=Fos(J2t,n);return e.jsx(Da.span,{"data-state":sNt(a.checked),"data-disabled":a.disabled?"":void 0,...r,ref:t})});eNt.displayName=J2t;var zos="SwitchBubbleInput",tNt=N.forwardRef(({__scopeSwitch:s,control:t,checked:n,bubbles:r=!0,...a},i)=>{const l=N.useRef(null),o=jo(l,i),c=EQ(n),d=fQ(t);return N.useEffect(()=>{const u=l.current;if(!u)return;const h=window.HTMLInputElement.prototype,f=Object.getOwnPropertyDescriptor(h,"checked").set;if(c!==n&&f){const g=new Event("click",{bubbles:r});f.call(u,n),u.dispatchEvent(g)}},[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}})});tNt.displayName=zos;function sNt(s){return s?"checked":"unchecked"}var nNt=Q2t,Bos=eNt;const zn=N.forwardRef(({className:s,...t},n)=>e.jsx(nNt,{className:Ot("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(Bos,{className:Ot("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")})}));zn.displayName=nNt.displayName;function zi(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 qu(s,t){return s instanceof Date?new s.constructor(t):new Date(t)}function Ad(s,t){const n=zi(s);return isNaN(t)?qu(s,NaN):(t&&n.setDate(n.getDate()+t),n)}function J0(s,t){const n=zi(s);if(isNaN(t))return qu(s,NaN);if(!t)return n;const r=n.getDate(),a=qu(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 rNt(s,t){const n=+zi(s);return qu(s,n+t)}const K$e=6048e5,$os=864e5,S4e=6e4,C4e=36e5,Uos=1e3,zte=43200,Btt=1440;function $tt(s,t){return rNt(s,t*C4e)}let qos={};function IE(){return qos}function lx(s,t){var o,c,d,u;const n=IE(),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=zi(s),i=a.getDay(),l=(i=a.getTime()?n+1:t.getTime()>=l.getTime()?n:n-1}function ey(s){const t=zi(s);return t.setHours(0,0,0,0),t}function dE(s){const t=zi(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 Iv(s,t){const n=ey(s),r=ey(t),a=+n-dE(n),i=+r-dE(r);return Math.round((a-i)/$os)}function Vos(s){const t=aNt(s),n=qu(s,0);return n.setFullYear(t,0,4),n.setHours(0,0,0,0),S3(n)}function E7(s,t){return rNt(s,t*S4e)}function H4(s,t){const n=t*7;return Ad(s,n)}function Hos(s,t){return J0(s,t*12)}function Gos(s){let t;return s.forEach(function(n){const r=zi(n);(t===void 0||t{const r=zi(n);(!t||t>r||isNaN(+r))&&(t=r)}),t||new Date(NaN)}function Awe(s,t){const n=zi(s),r=zi(t),a=n.getTime()-r.getTime();return a<0?-1:a>0?1:a}function A4e(s){return qu(s,Date.now())}function yd(s,t){const n=ey(s),r=ey(t);return+n==+r}function Y$e(s){return s instanceof Date||typeof s=="object"&&Object.prototype.toString.call(s)==="[object Date]"}function $De(s){if(!Y$e(s)&&typeof s!="number")return!1;const t=zi(s);return!isNaN(Number(t))}function OB(s,t){const n=zi(s),r=zi(t),a=n.getFullYear()-r.getFullYear(),i=n.getMonth()-r.getMonth();return a*12+i}function Kos(s,t,n){const r=lx(s,n),a=lx(t,n),i=+r-dE(r),l=+a-dE(a);return Math.round((i-l)/K$e)}function wj(s,t){const n=zi(s),r=zi(t),a=Utt(n,r),i=Math.abs(Iv(n,r));n.setDate(n.getDate()-a*i);const l=+(Utt(n,r)===-a),o=a*(i-l);return o===0?0:o}function Utt(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 Yos(s){return t=>{const r=(s?Math[s]:Math.trunc)(t);return r===0?0:r}}function Zos(s,t){return+zi(s)-+zi(t)}function Xos(s){const t=zi(s);return t.setHours(23,59,59,999),t}function m_(s){const t=zi(s),n=t.getMonth();return t.setFullYear(t.getFullYear(),n+1,0),t.setHours(23,59,59,999),t}function Qos(s){const t=zi(s);return+Xos(t)==+m_(t)}function Jos(s,t){const n=zi(s),r=zi(t),a=Awe(n,r),i=Math.abs(OB(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=Awe(n,r)===-a;Qos(zi(s))&&i===1&&Awe(s,r)===1&&(o=!1),l=a*(i-Number(o))}return l===0?0:l}function els(s,t,n){const r=Zos(s,t)/1e3;return Yos(n==null?void 0:n.roundingMethod)(r)}function UDe(s,t){const n=zi(s.start),r=zi(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(zi(l)),l.setDate(l.getDate()+o),l.setHours(0,0,0,0);return a?c.reverse():c}function am(s){const t=zi(s);return t.setDate(1),t.setHours(0,0,0,0),t}function iNt(s){const t=zi(s),n=qu(s,0);return n.setFullYear(t.getFullYear(),0,1),n.setHours(0,0,0,0),n}function FB(s,t){var o,c,d,u;const n=IE(),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=zi(s),i=a.getDay(),l=(i{let r;const a=tls[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 T6e(s){return(t={})=>{const n=t.width?String(t.width):s.defaultWidth;return s.formats[n]||s.formats[s.defaultWidth]}}const nls={full:"EEEE, MMMM do, y",long:"MMMM do, y",medium:"MMM d, y",short:"MM/dd/yyyy"},rls={full:"h:mm:ss a zzzz",long:"h:mm:ss a z",medium:"h:mm:ss a",short:"h:mm a"},als={full:"{{date}} 'at' {{time}}",long:"{{date}} 'at' {{time}}",medium:"{{date}}, {{time}}",short:"{{date}}, {{time}}"},ils={date:T6e({formats:nls,defaultWidth:"full"}),time:T6e({formats:rls,defaultWidth:"full"}),dateTime:T6e({formats:als,defaultWidth:"full"})},ols={lastWeek:"'last' eeee 'at' p",yesterday:"'yesterday at' p",today:"'today at' p",tomorrow:"'tomorrow at' p",nextWeek:"eeee 'at' p",other:"P"},lls=(s,t,n,r)=>ols[s];function CV(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 cls={narrow:["B","A"],abbreviated:["BC","AD"],wide:["Before Christ","Anno Domini"]},dls={narrow:["1","2","3","4"],abbreviated:["Q1","Q2","Q3","Q4"],wide:["1st quarter","2nd quarter","3rd quarter","4th quarter"]},uls={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"]},hls={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"]},mls={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"}},pls={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"}},fls=(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"},gls={ordinalNumber:fls,era:CV({values:cls,defaultWidth:"wide"}),quarter:CV({values:dls,defaultWidth:"wide",argumentCallback:s=>s-1}),month:CV({values:uls,defaultWidth:"wide"}),day:CV({values:hls,defaultWidth:"wide"}),dayPeriod:CV({values:mls,defaultWidth:"wide",formattingValues:pls,defaultFormattingWidth:"wide"})};function AV(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)?yls(o,h=>h.test(l)):xls(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 xls(s,t){for(const n in s)if(Object.prototype.hasOwnProperty.call(s,n)&&t(s[n]))return n}function yls(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 bls=/^(\d+)(th|st|nd|rd)?/i,_ls=/\d+/i,wls={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},jls={any:[/^b/i,/^(a|c)/i]},Nls={narrow:/^[1234]/i,abbreviated:/^q[1234]/i,wide:/^[1234](th|st|nd|rd)? quarter/i},kls={any:[/1/i,/2/i,/3/i,/4/i]},Sls={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},Cls={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]},Als={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},Tls={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]},Els={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},Mls={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}},Lls={ordinalNumber:vls({matchPattern:bls,parsePattern:_ls,valueCallback:s=>parseInt(s,10)}),era:AV({matchPatterns:wls,defaultMatchWidth:"wide",parsePatterns:jls,defaultParseWidth:"any"}),quarter:AV({matchPatterns:Nls,defaultMatchWidth:"wide",parsePatterns:kls,defaultParseWidth:"any",valueCallback:s=>s+1}),month:AV({matchPatterns:Sls,defaultMatchWidth:"wide",parsePatterns:Cls,defaultParseWidth:"any"}),day:AV({matchPatterns:Als,defaultMatchWidth:"wide",parsePatterns:Tls,defaultParseWidth:"any"}),dayPeriod:AV({matchPatterns:Els,defaultMatchWidth:"any",parsePatterns:Mls,defaultParseWidth:"any"})},T4e={code:"en-US",formatDistance:sls,formatLong:ils,formatRelative:lls,localize:gls,match:Lls,options:{weekStartsOn:0,firstWeekContainsDate:1}};function Pls(s){const t=zi(s);return Iv(t,iNt(t))+1}function Z$e(s){const t=zi(s),n=+S3(t)-+Vos(t);return Math.round(n/K$e)+1}function X$e(s,t){var u,h,m,f;const n=zi(s),r=n.getFullYear(),a=IE(),i=(t==null?void 0:t.firstWeekContainsDate)??((h=(u=t==null?void 0:t.locale)==null?void 0:u.options)==null?void 0:h.firstWeekContainsDate)??a.firstWeekContainsDate??((f=(m=a.locale)==null?void 0:m.options)==null?void 0:f.firstWeekContainsDate)??1,l=qu(s,0);l.setFullYear(r+1,0,i),l.setHours(0,0,0,0);const o=lx(l,t),c=qu(s,0);c.setFullYear(r,0,i),c.setHours(0,0,0,0);const d=lx(c,t);return n.getTime()>=o.getTime()?r+1:n.getTime()>=d.getTime()?r:r-1}function Ils(s,t){var o,c,d,u;const n=IE(),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=X$e(s,t),i=qu(s,0);return i.setFullYear(a,0,r),i.setHours(0,0,0,0),lx(i,t)}function Q$e(s,t){const n=zi(s),r=+lx(n,t)-+Ils(n,t);return Math.round(r/K$e)+1}function Bu(s,t){const n=s<0?"-":"",r=Math.abs(s).toString().padStart(t,"0");return n+r}const vC={y(s,t){const n=s.getFullYear(),r=n>0?n:1-n;return Bu(t==="yy"?r%100:r,t.length)},M(s,t){const n=s.getMonth();return t==="M"?String(n+1):Bu(n+1,2)},d(s,t){return Bu(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 Bu(s.getHours()%12||12,t.length)},H(s,t){return Bu(s.getHours(),t.length)},m(s,t){return Bu(s.getMinutes(),t.length)},s(s,t){return Bu(s.getSeconds(),t.length)},S(s,t){const n=t.length,r=s.getMilliseconds(),a=Math.trunc(r*Math.pow(10,n-3));return Bu(a,t.length)}},dF={am:"am",pm:"pm",midnight:"midnight",noon:"noon",morning:"morning",afternoon:"afternoon",evening:"evening",night:"night"},qtt={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 vC.y(s,t)},Y:function(s,t,n,r){const a=X$e(s,r),i=a>0?a:1-a;if(t==="YY"){const l=i%100;return Bu(l,2)}return t==="Yo"?n.ordinalNumber(i,{unit:"year"}):Bu(i,t.length)},R:function(s,t){const n=aNt(s);return Bu(n,t.length)},u:function(s,t){const n=s.getFullYear();return Bu(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 Bu(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 Bu(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 vC.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 Bu(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=Q$e(s,r);return t==="wo"?n.ordinalNumber(a,{unit:"week"}):Bu(a,t.length)},I:function(s,t,n){const r=Z$e(s);return t==="Io"?n.ordinalNumber(r,{unit:"week"}):Bu(r,t.length)},d:function(s,t,n){return t==="do"?n.ordinalNumber(s.getDate(),{unit:"date"}):vC.d(s,t)},D:function(s,t,n){const r=Pls(s);return t==="Do"?n.ordinalNumber(r,{unit:"dayOfYear"}):Bu(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 Bu(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 Bu(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 Bu(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=dF.noon:r===0?a=dF.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=dF.evening:r>=12?a=dF.afternoon:r>=4?a=dF.morning:a=dF.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 vC.h(s,t)},H:function(s,t,n){return t==="Ho"?n.ordinalNumber(s.getHours(),{unit:"hour"}):vC.H(s,t)},K:function(s,t,n){const r=s.getHours()%12;return t==="Ko"?n.ordinalNumber(r,{unit:"hour"}):Bu(r,t.length)},k:function(s,t,n){let r=s.getHours();return r===0&&(r=24),t==="ko"?n.ordinalNumber(r,{unit:"hour"}):Bu(r,t.length)},m:function(s,t,n){return t==="mo"?n.ordinalNumber(s.getMinutes(),{unit:"minute"}):vC.m(s,t)},s:function(s,t,n){return t==="so"?n.ordinalNumber(s.getSeconds(),{unit:"second"}):vC.s(s,t)},S:function(s,t){return vC.S(s,t)},X:function(s,t,n){const r=s.getTimezoneOffset();if(r===0)return"Z";switch(t){case"X":return Htt(r);case"XXXX":case"XX":return aI(r);case"XXXXX":case"XXX":default:return aI(r,":")}},x:function(s,t,n){const r=s.getTimezoneOffset();switch(t){case"x":return Htt(r);case"xxxx":case"xx":return aI(r);case"xxxxx":case"xxx":default:return aI(r,":")}},O:function(s,t,n){const r=s.getTimezoneOffset();switch(t){case"O":case"OO":case"OOO":return"GMT"+Vtt(r,":");case"OOOO":default:return"GMT"+aI(r,":")}},z:function(s,t,n){const r=s.getTimezoneOffset();switch(t){case"z":case"zz":case"zzz":return"GMT"+Vtt(r,":");case"zzzz":default:return"GMT"+aI(r,":")}},t:function(s,t,n){const r=Math.trunc(s.getTime()/1e3);return Bu(r,t.length)},T:function(s,t,n){const r=s.getTime();return Bu(r,t.length)}};function Vtt(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+Bu(i,2)}function Htt(s,t){return s%60===0?(s>0?"-":"+")+Bu(Math.abs(s)/60,2):aI(s,t)}function aI(s,t=""){const n=s>0?"-":"+",r=Math.abs(s),a=Bu(Math.trunc(r/60),2),i=Bu(r%60,2);return n+a+t+i}const Gtt=(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"})}},lNt=(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"})}},Dls=(s,t)=>{const n=s.match(/(P+)(p+)?/)||[],r=n[1],a=n[2];if(!a)return Gtt(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}}",Gtt(r,t)).replace("{{time}}",lNt(a,t))},qDe={p:lNt,P:Dls},Rls=/^D+$/,Ols=/^Y+$/,Fls=["D","DD","YY","YYYY"];function cNt(s){return Rls.test(s)}function dNt(s){return Ols.test(s)}function VDe(s,t,n){const r=zls(s,t,n);if(console.warn(r),Fls.includes(s))throw new RangeError(r)}function zls(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 Bls=/[yYQqMLwIdDecihHKkms]o|(\w)\1*|''|'(''|[^'])+('|$)|./g,$ls=/P+p+|P+|p+|''|'(''|[^'])+('|$)|./g,Uls=/^'([^]*?)'?$/,qls=/''/g,Vls=/[a-zA-Z]/;function Js(s,t,n){var u,h,m,f,g,y,x,_;const r=IE(),a=(n==null?void 0:n.locale)??r.locale??T4e,i=(n==null?void 0:n.firstWeekContainsDate)??((h=(u=n==null?void 0:n.locale)==null?void 0:u.options)==null?void 0:h.firstWeekContainsDate)??r.firstWeekContainsDate??((f=(m=r.locale)==null?void 0:m.options)==null?void 0:f.firstWeekContainsDate)??1,l=(n==null?void 0:n.weekStartsOn)??((y=(g=n==null?void 0:n.locale)==null?void 0:g.options)==null?void 0:y.weekStartsOn)??r.weekStartsOn??((_=(x=r.locale)==null?void 0:x.options)==null?void 0:_.weekStartsOn)??0,o=zi(s);if(!$De(o))throw new RangeError("Invalid time value");let c=t.match($ls).map(b=>{const k=b[0];if(k==="p"||k==="P"){const A=qDe[k];return A(b,a.formatLong)}return b}).join("").match(Bls).map(b=>{if(b==="''")return{isToken:!1,value:"'"};const k=b[0];if(k==="'")return{isToken:!1,value:Hls(b)};if(qtt[k])return{isToken:!0,value:b};if(k.match(Vls))throw new RangeError("Format string contains an unescaped latin alphabet character `"+k+"`");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 k=b.value;(!(n!=null&&n.useAdditionalWeekYearTokens)&&dNt(k)||!(n!=null&&n.useAdditionalDayOfYearTokens)&&cNt(k))&&VDe(k,t,String(s));const A=qtt[k[0]];return A(o,k,a.localize,d)}).join("")}function Hls(s){const t=s.match(Uls);return t?t[1].replace(qls,"'"):s}function Gls(s,t,n){const r=IE(),a=(n==null?void 0:n.locale)??r.locale??T4e,i=2520,l=Awe(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=zi(t),d=zi(s)):(c=zi(s),d=zi(t));const u=els(d,c),h=(dE(d)-dE(c))/1e3,m=Math.round((u-h)/60);let f;if(m<2)return n!=null&&n.includeSeconds?u<5?a.formatDistance("lessThanXSeconds",5,o):u<10?a.formatDistance("lessThanXSeconds",10,o):u<20?a.formatDistance("lessThanXSeconds",20,o):u<40?a.formatDistance("halfAMinute",0,o):u<60?a.formatDistance("lessThanXMinutes",1,o):a.formatDistance("xMinutes",1,o):m===0?a.formatDistance("lessThanXMinutes",1,o):a.formatDistance("xMinutes",m,o);if(m<45)return a.formatDistance("xMinutes",m,o);if(m<90)return a.formatDistance("aboutXHours",1,o);if(mr.getTime()}function rN(s,t){const n=zi(s),r=zi(t);return+n<+r}function Jls(s){return+zi(s)>Date.now()}function ecs(s,t){const n=t instanceof Date?qu(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 tcs=10;class uNt{constructor(){jr(this,"subPriority",0)}validate(t,n){return!0}}class scs extends uNt{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 ncs extends uNt{constructor(){super(...arguments);jr(this,"priority",tcs);jr(this,"subPriority",-1)}set(n,r){return r.timestampIsSet?n:qu(n,ecs(n,Date))}}class lu{run(t,n,r,a){const i=this.parse(t,n,r,a);return i?{setter:new scs(i.value,this.validate,this.set,this.priority,this.subPriority),rest:i.rest}:null}validate(t,n,r){return!0}}class rcs extends lu{constructor(){super(...arguments);jr(this,"priority",140);jr(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 Vf={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}/},Kk={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 Hf(s,t){return s&&{value:t(s.value),rest:s.rest}}function kp(s,t){const n=t.match(s);return n?{value:parseInt(n[0],10),rest:t.slice(n[0].length)}:null}function Yk(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*C4e+i*S4e+l*Uos),rest:t.slice(n[0].length)}}function hNt(s){return kp(Vf.anyDigitsSigned,s)}function xf(s,t){switch(s){case 1:return kp(Vf.singleDigit,t);case 2:return kp(Vf.twoDigits,t);case 3:return kp(Vf.threeDigits,t);case 4:return kp(Vf.fourDigits,t);default:return kp(new RegExp("^\\d{1,"+s+"}"),t)}}function q2e(s,t){switch(s){case 1:return kp(Vf.singleDigitSigned,t);case 2:return kp(Vf.twoDigitsSigned,t);case 3:return kp(Vf.threeDigitsSigned,t);case 4:return kp(Vf.fourDigitsSigned,t);default:return kp(new RegExp("^-?\\d{1,"+s+"}"),t)}}function J$e(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 mNt(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 pNt(s){return s%400===0||s%4===0&&s%100!==0}class acs extends lu{constructor(){super(...arguments);jr(this,"priority",130);jr(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 Hf(xf(4,n),i);case"yo":return Hf(a.ordinalNumber(n,{unit:"year"}),i);default:return Hf(xf(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=mNt(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 ics extends lu{constructor(){super(...arguments);jr(this,"priority",130);jr(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 Hf(xf(4,n),i);case"Yo":return Hf(a.ordinalNumber(n,{unit:"year"}),i);default:return Hf(xf(r.length,n),i)}}validate(n,r){return r.isTwoDigitYear||r.year>0}set(n,r,a,i){const l=X$e(n,i);if(a.isTwoDigitYear){const c=mNt(a.year,l);return n.setFullYear(c,0,i.firstWeekContainsDate),n.setHours(0,0,0,0),lx(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),lx(n,i)}}class ocs extends lu{constructor(){super(...arguments);jr(this,"priority",130);jr(this,"incompatibleTokens",["G","y","Y","u","Q","q","M","L","w","d","D","e","c","t","T"])}parse(n,r){return q2e(r==="R"?4:r.length,n)}set(n,r,a){const i=qu(n,0);return i.setFullYear(a,0,4),i.setHours(0,0,0,0),S3(i)}}class lcs extends lu{constructor(){super(...arguments);jr(this,"priority",130);jr(this,"incompatibleTokens",["G","y","Y","R","w","I","i","e","c","t","T"])}parse(n,r){return q2e(r==="u"?4:r.length,n)}set(n,r,a){return n.setFullYear(a,0,1),n.setHours(0,0,0,0),n}}class ccs extends lu{constructor(){super(...arguments);jr(this,"priority",120);jr(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 xf(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 dcs extends lu{constructor(){super(...arguments);jr(this,"priority",120);jr(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 xf(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 ucs extends lu{constructor(){super(...arguments);jr(this,"incompatibleTokens",["Y","R","q","Q","L","w","I","D","i","e","c","t","T"]);jr(this,"priority",110)}parse(n,r,a){const i=l=>l-1;switch(r){case"M":return Hf(kp(Vf.month,n),i);case"MM":return Hf(xf(2,n),i);case"Mo":return Hf(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 hcs extends lu{constructor(){super(...arguments);jr(this,"priority",110);jr(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 Hf(kp(Vf.month,n),i);case"LL":return Hf(xf(2,n),i);case"Lo":return Hf(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 mcs(s,t,n){const r=zi(s),a=Q$e(r,n)-t;return r.setDate(r.getDate()-a*7),r}class pcs extends lu{constructor(){super(...arguments);jr(this,"priority",100);jr(this,"incompatibleTokens",["y","R","u","q","Q","M","L","I","d","D","i","t","T"])}parse(n,r,a){switch(r){case"w":return kp(Vf.week,n);case"wo":return a.ordinalNumber(n,{unit:"week"});default:return xf(r.length,n)}}validate(n,r){return r>=1&&r<=53}set(n,r,a,i){return lx(mcs(n,a,i),i)}}function fcs(s,t){const n=zi(s),r=Z$e(n)-t;return n.setDate(n.getDate()-r*7),n}class gcs extends lu{constructor(){super(...arguments);jr(this,"priority",100);jr(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 kp(Vf.week,n);case"Io":return a.ordinalNumber(n,{unit:"week"});default:return xf(r.length,n)}}validate(n,r){return r>=1&&r<=53}set(n,r,a){return S3(fcs(n,a))}}const xcs=[31,28,31,30,31,30,31,31,30,31,30,31],ycs=[31,29,31,30,31,30,31,31,30,31,30,31];class vcs extends lu{constructor(){super(...arguments);jr(this,"priority",90);jr(this,"subPriority",1);jr(this,"incompatibleTokens",["Y","R","q","Q","w","I","D","i","e","c","t","T"])}parse(n,r,a){switch(r){case"d":return kp(Vf.date,n);case"do":return a.ordinalNumber(n,{unit:"date"});default:return xf(r.length,n)}}validate(n,r){const a=n.getFullYear(),i=pNt(a),l=n.getMonth();return i?r>=1&&r<=ycs[l]:r>=1&&r<=xcs[l]}set(n,r,a){return n.setDate(a),n.setHours(0,0,0,0),n}}class bcs extends lu{constructor(){super(...arguments);jr(this,"priority",90);jr(this,"subpriority",1);jr(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 kp(Vf.dayOfYear,n);case"Do":return a.ordinalNumber(n,{unit:"date"});default:return xf(r.length,n)}}validate(n,r){const a=n.getFullYear();return pNt(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 eUe(s,t,n){var h,m,f,g;const r=IE(),a=(n==null?void 0:n.weekStartsOn)??((m=(h=n==null?void 0:n.locale)==null?void 0:h.options)==null?void 0:m.weekStartsOn)??r.weekStartsOn??((g=(f=r.locale)==null?void 0:f.options)==null?void 0:g.weekStartsOn)??0,i=zi(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 Ad(i,u)}class _cs extends lu{constructor(){super(...arguments);jr(this,"priority",90);jr(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=eUe(n,a,i),n.setHours(0,0,0,0),n}}class wcs extends lu{constructor(){super(...arguments);jr(this,"priority",90);jr(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 Hf(xf(r.length,n),l);case"eo":return Hf(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=eUe(n,a,i),n.setHours(0,0,0,0),n}}class jcs extends lu{constructor(){super(...arguments);jr(this,"priority",90);jr(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 Hf(xf(r.length,n),l);case"co":return Hf(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=eUe(n,a,i),n.setHours(0,0,0,0),n}}function Ncs(s,t){const n=zi(s),r=Yls(n),a=t-r;return Ad(n,a)}class kcs extends lu{constructor(){super(...arguments);jr(this,"priority",90);jr(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 xf(r.length,n);case"io":return a.ordinalNumber(n,{unit:"day"});case"iii":return Hf(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 Hf(a.day(n,{width:"narrow",context:"formatting"}),i);case"iiiiii":return Hf(a.day(n,{width:"short",context:"formatting"})||a.day(n,{width:"narrow",context:"formatting"}),i);case"iiii":default:return Hf(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=Ncs(n,a),n.setHours(0,0,0,0),n}}class Scs extends lu{constructor(){super(...arguments);jr(this,"priority",80);jr(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(J$e(a),0,0,0),n}}class Ccs extends lu{constructor(){super(...arguments);jr(this,"priority",80);jr(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(J$e(a),0,0,0),n}}class Acs extends lu{constructor(){super(...arguments);jr(this,"priority",80);jr(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(J$e(a),0,0,0),n}}class Tcs extends lu{constructor(){super(...arguments);jr(this,"priority",70);jr(this,"incompatibleTokens",["H","K","k","t","T"])}parse(n,r,a){switch(r){case"h":return kp(Vf.hour12h,n);case"ho":return a.ordinalNumber(n,{unit:"hour"});default:return xf(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 Ecs extends lu{constructor(){super(...arguments);jr(this,"priority",70);jr(this,"incompatibleTokens",["a","b","h","K","k","t","T"])}parse(n,r,a){switch(r){case"H":return kp(Vf.hour23h,n);case"Ho":return a.ordinalNumber(n,{unit:"hour"});default:return xf(r.length,n)}}validate(n,r){return r>=0&&r<=23}set(n,r,a){return n.setHours(a,0,0,0),n}}class Mcs extends lu{constructor(){super(...arguments);jr(this,"priority",70);jr(this,"incompatibleTokens",["h","H","k","t","T"])}parse(n,r,a){switch(r){case"K":return kp(Vf.hour11h,n);case"Ko":return a.ordinalNumber(n,{unit:"hour"});default:return xf(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 Lcs extends lu{constructor(){super(...arguments);jr(this,"priority",70);jr(this,"incompatibleTokens",["a","b","h","H","K","t","T"])}parse(n,r,a){switch(r){case"k":return kp(Vf.hour24h,n);case"ko":return a.ordinalNumber(n,{unit:"hour"});default:return xf(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 Pcs extends lu{constructor(){super(...arguments);jr(this,"priority",60);jr(this,"incompatibleTokens",["t","T"])}parse(n,r,a){switch(r){case"m":return kp(Vf.minute,n);case"mo":return a.ordinalNumber(n,{unit:"minute"});default:return xf(r.length,n)}}validate(n,r){return r>=0&&r<=59}set(n,r,a){return n.setMinutes(a,0,0),n}}class Ics extends lu{constructor(){super(...arguments);jr(this,"priority",50);jr(this,"incompatibleTokens",["t","T"])}parse(n,r,a){switch(r){case"s":return kp(Vf.second,n);case"so":return a.ordinalNumber(n,{unit:"second"});default:return xf(r.length,n)}}validate(n,r){return r>=0&&r<=59}set(n,r,a){return n.setSeconds(a,0),n}}class Dcs extends lu{constructor(){super(...arguments);jr(this,"priority",30);jr(this,"incompatibleTokens",["t","T"])}parse(n,r){const a=i=>Math.trunc(i*Math.pow(10,-r.length+3));return Hf(xf(r.length,n),a)}set(n,r,a){return n.setMilliseconds(a),n}}class Rcs extends lu{constructor(){super(...arguments);jr(this,"priority",10);jr(this,"incompatibleTokens",["t","T","x"])}parse(n,r){switch(r){case"X":return Yk(Kk.basicOptionalMinutes,n);case"XX":return Yk(Kk.basic,n);case"XXXX":return Yk(Kk.basicOptionalSeconds,n);case"XXXXX":return Yk(Kk.extendedOptionalSeconds,n);case"XXX":default:return Yk(Kk.extended,n)}}set(n,r,a){return r.timestampIsSet?n:qu(n,n.getTime()-dE(n)-a)}}class Ocs extends lu{constructor(){super(...arguments);jr(this,"priority",10);jr(this,"incompatibleTokens",["t","T","X"])}parse(n,r){switch(r){case"x":return Yk(Kk.basicOptionalMinutes,n);case"xx":return Yk(Kk.basic,n);case"xxxx":return Yk(Kk.basicOptionalSeconds,n);case"xxxxx":return Yk(Kk.extendedOptionalSeconds,n);case"xxx":default:return Yk(Kk.extended,n)}}set(n,r,a){return r.timestampIsSet?n:qu(n,n.getTime()-dE(n)-a)}}class Fcs extends lu{constructor(){super(...arguments);jr(this,"priority",40);jr(this,"incompatibleTokens","*")}parse(n){return hNt(n)}set(n,r,a){return[qu(n,a*1e3),{timestampIsSet:!0}]}}class zcs extends lu{constructor(){super(...arguments);jr(this,"priority",20);jr(this,"incompatibleTokens","*")}parse(n){return hNt(n)}set(n,r,a){return[qu(n,a),{timestampIsSet:!0}]}}const Bcs={G:new rcs,y:new acs,Y:new ics,R:new ocs,u:new lcs,Q:new ccs,q:new dcs,M:new ucs,L:new hcs,w:new pcs,I:new gcs,d:new vcs,D:new bcs,E:new _cs,e:new wcs,c:new jcs,i:new kcs,a:new Scs,b:new Ccs,B:new Acs,h:new Tcs,H:new Ecs,K:new Mcs,k:new Lcs,m:new Pcs,s:new Ics,S:new Dcs,X:new Rcs,x:new Ocs,t:new Fcs,T:new zcs},$cs=/[yYQqMLwIdDecihHKkms]o|(\w)\1*|''|'(''|[^'])+('|$)|./g,Ucs=/P+p+|P+|p+|''|'(''|[^'])+('|$)|./g,qcs=/^'([^]*?)'?$/,Vcs=/''/g,Hcs=/\S/,Gcs=/[a-zA-Z]/;function tUe(s,t,n,r){var y,x,_,b;const a=Kls(),i=a.locale??T4e,l=a.firstWeekContainsDate??((x=(y=a.locale)==null?void 0:y.options)==null?void 0:x.firstWeekContainsDate)??1,o=a.weekStartsOn??((b=(_=a.locale)==null?void 0:_.options)==null?void 0:b.weekStartsOn)??0;if(t==="")return s===""?zi(n):qu(n,NaN);const c={firstWeekContainsDate:l,weekStartsOn:o,locale:i},d=[new ncs],u=t.match(Ucs).map(k=>{const A=k[0];if(A in qDe){const T=qDe[A];return T(k,i.formatLong)}return k}).join("").match($cs),h=[];for(let k of u){dNt(k)&&VDe(k,t,s),cNt(k)&&VDe(k,t,s);const A=k[0],T=Bcs[A];if(T){const{incompatibleTokens:P}=T;if(Array.isArray(P)){const M=h.find(L=>P.includes(L.token)||L.token===A);if(M)throw new RangeError(`The format string mustn't contain \`${M.fullToken}\` and \`${k}\` at the same time`)}else if(T.incompatibleTokens==="*"&&h.length>0)throw new RangeError(`The format string mustn't contain \`${k}\` and any other token at the same time`);h.push({token:A,fullToken:k});const I=T.run(s,k,i.match,c);if(!I)return qu(n,NaN);d.push(I.setter),s=I.rest}else{if(A.match(Gcs))throw new RangeError("Format string contains an unescaped latin alphabet character `"+A+"`");if(k==="''"?k="'":A==="'"&&(k=Wcs(k)),s.indexOf(k)===0)s=s.slice(k.length);else return qu(n,NaN)}}if(s.length>0&&Hcs.test(s))return qu(n,NaN);const m=d.map(k=>k.priority).sort((k,A)=>A-k).filter((k,A,T)=>T.indexOf(k)===A).map(k=>d.filter(A=>A.priority===k).sort((A,T)=>T.subPriority-A.subPriority)).map(k=>k[0]);let f=zi(n);if(isNaN(f.getTime()))return qu(n,NaN);const g={};for(const k of m){if(!k.validate(f,c))return qu(n,NaN);const A=k.set(f,g,c);Array.isArray(A)?(f=A[0],Object.assign(g,A[1])):f=A}return qu(n,f)}function Wcs(s){return s.match(qcs)[1].replace(Vcs,"'")}function x5(s){return+zi(s)i-l);return n>=r&&n<=a}function zW(s,t){return Ad(s,-t)}function jp(s,t){const r=tds(s);let a;if(r.date){const c=sds(r.date,2);a=nds(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=rds(r.time),isNaN(l)))return new Date(NaN);if(r.timezone){if(o=ads(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 Bte={dateTimeDelimiter:/[T ]/,timeZoneDelimiter:/[Z ]/i,timezone:/([Z+-].*)$/},Qcs=/^-?(?:(\d{3})|(\d{2})(?:-?(\d{2}))?|W(\d{2})(?:-?(\d{1}))?|)$/,Jcs=/^(\d{2}(?:[.,]\d*)?)(?::?(\d{2}(?:[.,]\d*)?))?(?::?(\d{2}(?:[.,]\d*)?))?$/,eds=/^([+-])(\d{2})(?::?(\d{2}))?$/;function tds(s){const t={},n=s.split(Bte.dateTimeDelimiter);let r;if(n.length>2)return t;if(/:/.test(n[0])?r=n[0]:(t.date=n[0],r=n[1],Bte.timeZoneDelimiter.test(t.date)&&(t.date=s.split(Bte.timeZoneDelimiter)[0],r=s.substr(t.date.length,s.length))),r){const a=Bte.timezone.exec(r);a?(t.time=r.replace(a[1],""),t.timezone=a[1]):t.time=r}return t}function sds(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 nds(s,t){if(t===null)return new Date(NaN);const n=s.match(Qcs);if(!n)return new Date(NaN);const r=!!n[4],a=TV(n[1]),i=TV(n[2])-1,l=TV(n[3]),o=TV(n[4]),c=TV(n[5])-1;if(r)return dds(t,o,c)?ids(t,o,c):new Date(NaN);{const d=new Date(0);return!lds(t,i,l)||!cds(t,a)?new Date(NaN):(d.setUTCFullYear(t,i,Math.max(a,l)),d)}}function TV(s){return s?parseInt(s):1}function rds(s){const t=s.match(Jcs);if(!t)return NaN;const n=E6e(t[1]),r=E6e(t[2]),a=E6e(t[3]);return uds(n,r,a)?n*C4e+r*S4e+a*1e3:NaN}function E6e(s){return s&&parseFloat(s.replace(",","."))||0}function ads(s){if(s==="Z")return 0;const t=s.match(eds);if(!t)return 0;const n=t[1]==="+"?-1:1,r=parseInt(t[2]),a=t[3]&&parseInt(t[3])||0;return hds(r,a)?n*(r*C4e+a*S4e):NaN}function ids(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 ods=[31,null,31,30,31,30,31,31,30,31,30,31];function fNt(s){return s%400===0||s%4===0&&s%100!==0}function lds(s,t,n){return t>=0&&t<=11&&n>=1&&n<=(ods[t]||(fNt(s)?29:28))}function cds(s,t){return t>=1&&t<=(fNt(s)?366:365)}function dds(s,t,n){return t>=1&&t<=53&&n>=0&&n<=6}function uds(s,t,n){return s===24?t===0&&n===0:n>=0&&n<60&&t>=0&&t<60&&s>=0&&s<25}function hds(s,t){return t>=0&&t<=59}function M6e(s,t){const n=zi(s),r=n.getFullYear(),a=n.getDate(),i=qu(s,0);i.setFullYear(r,t,15),i.setHours(0,0,0,0);const l=Wls(i);return n.setMonth(t,Math.min(a,l)),n}function BW(s,t){const n=zi(s);return n.setHours(t),n}function $W(s,t){const n=zi(s);return n.setMinutes(t),n}function Ktt(s,t){const n=zi(s);return isNaN(+n)?qu(s,NaN):(n.setFullYear(t),n)}function TI(s,t){return J0(s,-t)}var Ytt;function Qr(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 U9 extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}}class gNt extends Error{constructor(t){super(`Encountered unidirectional transform during encode: ${t}`),this.name="ZodEncodeError"}}(Ytt=globalThis).__zod_globalConfig??(Ytt.__zod_globalConfig={});const sUe=globalThis.__zod_globalConfig;function sR(s){return sUe}function xNt(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 HDe(s,t){return typeof t=="bigint"?t.toString():t}function nUe(s){return{get value(){{const t=s();return Object.defineProperty(this,"value",{value:t}),t}}}}function rUe(s){return s==null}function aUe(s){const t=s.startsWith("^")?1:0,n=s.endsWith("$")?s.length-1:s.length;return s.slice(t,n)}function mds(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 V2e(s){return typeof s=="object"&&s!==null&&!Array.isArray(s)}const fds=nUe(()=>{var s;if(sUe.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 hY(s){if(V2e(s)===!1)return!1;const t=s.constructor;if(t===void 0||typeof t!="function")return!0;const n=t.prototype;return!(V2e(n)===!1||Object.prototype.hasOwnProperty.call(n,"isPrototypeOf")===!1)}function vNt(s){return hY(s)?{...s}:Array.isArray(s)?[...s]:s instanceof Map?new Map(s):s instanceof Set?new Set(s):s}const gds=new Set(["string","number","symbol"]);function zB(s){return s.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function RE(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 To(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 xds(s){return Object.keys(s).filter(t=>s[t]._zod.optin==="optional"&&s[t]._zod.optout==="optional")}const yds={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 vds(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=DE(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 BR(this,"shape",l),l},checks:[]});return RE(s,i)}function bds(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=DE(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 BR(this,"shape",l),l},checks:[]});return RE(s,i)}function _ds(s,t){if(!hY(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=DE(s._zod.def,{get shape(){const i={...s._zod.def.shape,...t};return BR(this,"shape",i),i}});return RE(s,a)}function wds(s,t){if(!hY(t))throw new Error("Invalid input to safeExtend: expected a plain object");const n=DE(s._zod.def,{get shape(){const r={...s._zod.def.shape,...t};return BR(this,"shape",r),r}});return RE(s,n)}function jds(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=DE(s._zod.def,{get shape(){const a={...s._zod.def.shape,...t._zod.def.shape};return BR(this,"shape",a),a},get catchall(){return t._zod.def.catchall},checks:t._zod.def.checks??[]});return RE(s,n)}function Nds(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=DE(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 BR(this,"shape",c),c},checks:[]});return RE(t,l)}function kds(s,t,n){const r=DE(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 BR(this,"shape",i),i}});return RE(t,r)}function M7(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 $te(s){return typeof s=="string"?s:s==null?void 0:s.message}function nR(s,t,n){var c,d,u,h,m,f;const r=s.message?s.message:$te((u=(d=(c=s.inst)==null?void 0:c._zod.def)==null?void 0:d.error)==null?void 0:u.call(d,s))??$te((h=t==null?void 0:t.error)==null?void 0:h.call(t,s))??$te((m=n.customError)==null?void 0:m.call(n,s))??$te((f=n.localeError)==null?void 0:f.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 iUe(s){return Array.isArray(s)?"array":typeof s=="string"?"string":"unknown"}function mY(...s){const[t,n,r]=s;return typeof t=="string"?{message:t,code:"custom",input:n,inst:r}:{...t}}const _Nt=(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,HDe,2),Object.defineProperty(s,"toString",{value:()=>s.message,enumerable:!1})},wNt=Qr("$ZodError",_Nt),jNt=Qr("$ZodError",_Nt,{Parent:Error});function Cds(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 Ads(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 U9;if(l.issues.length){const o=new((a==null?void 0:a.Err)??s)(l.issues.map(c=>nR(c,i,sR())));throw yNt(o,a==null?void 0:a.callee),o}return l.value},lUe=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=>nR(c,i,sR())));throw yNt(o,a==null?void 0:a.callee),o}return l.value},E4e=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 U9;return i.issues.length?{success:!1,error:new(s??wNt)(i.issues.map(l=>nR(l,a,sR())))}:{success:!0,data:i.value}},Tds=E4e(jNt),M4e=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=>nR(l,a,sR())))}:{success:!0,data:i.value}},Eds=M4e(jNt),Mds=s=>(t,n,r)=>{const a=r?{...r,direction:"backward"}:{direction:"backward"};return oUe(s)(t,n,a)},Lds=s=>(t,n,r)=>oUe(s)(t,n,r),Pds=s=>async(t,n,r)=>{const a=r?{...r,direction:"backward"}:{direction:"backward"};return lUe(s)(t,n,a)},Ids=s=>async(t,n,r)=>lUe(s)(t,n,r),Dds=s=>(t,n,r)=>{const a=r?{...r,direction:"backward"}:{direction:"backward"};return E4e(s)(t,n,a)},Rds=s=>(t,n,r)=>E4e(s)(t,n,r),Ods=s=>async(t,n,r)=>{const a=r?{...r,direction:"backward"}:{direction:"backward"};return M4e(s)(t,n,a)},Fds=s=>async(t,n,r)=>M4e(s)(t,n,r),zds=/^[cC][0-9a-z]{6,}$/,Bds=/^[0-9a-z]+$/,$ds=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,Uds=/^[0-9a-vA-V]{20}$/,qds=/^[A-Za-z0-9]{27}$/,Vds=/^[a-zA-Z0-9_-]{21}$/,Hds=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,Gds=/^([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})$/,Qtt=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)$/,Wds=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,Kds="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";function Yds(){return new RegExp(Kds,"u")}const Zds=/^(?:(?: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])$/,Xds=/^(([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}|:))$/,Qds=/^((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])$/,Jds=/^(([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])$/,eus=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,NNt=/^[A-Za-z0-9_-]*$/,tus=/^https?$/,sus=/^\+[1-9]\d{6,14}$/,kNt="(?:(?:\\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])))",nus=new RegExp(`^${kNt}$`);function SNt(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 rus(s){return new RegExp(`^${SNt(s)}$`)}function aus(s){const t=SNt({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(`^${kNt}T(?:${r})$`)}const ius=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}$`)},ous=/^-?\d+$/,lus=/^-?\d+(?:\.\d+)?$/,cus=/^(?:true|false)$/i,dus=/^[^A-Z]*$/,uus=/^[^a-z]*$/,fb=Qr("$ZodCheck",(s,t)=>{var n;s._zod??(s._zod={}),s._zod.def=t,(n=s._zod).onattach??(n.onattach=[])}),CNt={number:"number",bigint:"bigint",object:"date"},ANt=Qr("$ZodCheckLessThan",(s,t)=>{fb.init(s,t);const n=CNt[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{fb.init(s,t);const n=CNt[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})}}),hus=Qr("$ZodCheckMultipleOf",(s,t)=>{fb.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):mds(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})}}),mus=Qr("$ZodCheckNumberFormat",(s,t)=>{var l;fb.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]=yds[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=ous)}),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})}}),pus=Qr("$ZodCheckMaxLength",(s,t)=>{var n;fb.init(s,t),(n=s._zod.def).when??(n.when=r=>{const a=r.value;return!rUe(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=iUe(a);r.issues.push({origin:l,code:"too_big",maximum:t.maximum,inclusive:!0,input:a,inst:s,continue:!t.abort})}}),fus=Qr("$ZodCheckMinLength",(s,t)=>{var n;fb.init(s,t),(n=s._zod.def).when??(n.when=r=>{const a=r.value;return!rUe(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=iUe(a);r.issues.push({origin:l,code:"too_small",minimum:t.minimum,inclusive:!0,input:a,inst:s,continue:!t.abort})}}),gus=Qr("$ZodCheckLengthEquals",(s,t)=>{var n;fb.init(s,t),(n=s._zod.def).when??(n.when=r=>{const a=r.value;return!rUe(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=iUe(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})}}),L4e=Qr("$ZodCheckStringFormat",(s,t)=>{var n,r;fb.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=()=>{})}),xus=Qr("$ZodCheckRegex",(s,t)=>{L4e.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})}}),yus=Qr("$ZodCheckLowerCase",(s,t)=>{t.pattern??(t.pattern=dus),L4e.init(s,t)}),vus=Qr("$ZodCheckUpperCase",(s,t)=>{t.pattern??(t.pattern=uus),L4e.init(s,t)}),bus=Qr("$ZodCheckIncludes",(s,t)=>{fb.init(s,t);const n=zB(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})}}),_us=Qr("$ZodCheckStartsWith",(s,t)=>{fb.init(s,t);const n=new RegExp(`^${zB(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})}}),wus=Qr("$ZodCheckEndsWith",(s,t)=>{fb.init(s,t);const n=new RegExp(`.*${zB(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})}}),jus=Qr("$ZodCheckOverwrite",(s,t)=>{fb.init(s,t),s._zod.check=n=>{n.value=t.tx(n.value)}});class Nus{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 kus={major:4,minor:4,patch:3},vf=Qr("$ZodType",(s,t)=>{var a;var n;s??(s={}),s._zod.def=t,s._zod.bag=s._zod.bag||{},s._zod.version=kus;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=M7(o),h;for(const m of c){if(m._zod.def.when){if(Sds(o)||!m._zod.def.when(o))continue}else if(u)continue;const f=o.issues.length,g=m._zod.check(o);if(g instanceof Promise&&(d==null?void 0:d.async)===!1)throw new U9;if(h||g instanceof Promise)h=(h??Promise.resolve()).then(async()=>{await g,o.issues.length!==f&&(u||(u=M7(o,f)))});else{if(o.issues.length===f)continue;u||(u=M7(o,f))}}return h?h.then(()=>o):o},l=(o,c,d)=>{if(M7(o))return o.aborted=!0,o;const u=i(c,r,d);if(u instanceof Promise){if(d.async===!1)throw new U9;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 U9;return d.then(u=>i(u,r,c))}return i(d,r,c)}}nh(s,"~standard",()=>({validate:i=>{var l;try{const o=Tds(s,i);return o.success?{value:o.data}:{issues:(l=o.error)==null?void 0:l.issues}}catch{return Eds(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}))}),cUe=Qr("$ZodString",(s,t)=>{var n;vf.init(s,t),s._zod.pattern=[...((n=s==null?void 0:s._zod.bag)==null?void 0:n.patterns)??[]].pop()??ius(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}}),qm=Qr("$ZodStringFormat",(s,t)=>{L4e.init(s,t),cUe.init(s,t)}),Sus=Qr("$ZodGUID",(s,t)=>{t.pattern??(t.pattern=Gds),qm.init(s,t)}),Cus=Qr("$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=Qtt(r))}else t.pattern??(t.pattern=Qtt());qm.init(s,t)}),Aus=Qr("$ZodEmail",(s,t)=>{t.pattern??(t.pattern=Wds),qm.init(s,t)}),Tus=Qr("$ZodURL",(s,t)=>{qm.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)===tus.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})}}}),Eus=Qr("$ZodEmoji",(s,t)=>{t.pattern??(t.pattern=Yds()),qm.init(s,t)}),Mus=Qr("$ZodNanoID",(s,t)=>{t.pattern??(t.pattern=Vds),qm.init(s,t)}),Lus=Qr("$ZodCUID",(s,t)=>{t.pattern??(t.pattern=zds),qm.init(s,t)}),Pus=Qr("$ZodCUID2",(s,t)=>{t.pattern??(t.pattern=Bds),qm.init(s,t)}),Ius=Qr("$ZodULID",(s,t)=>{t.pattern??(t.pattern=$ds),qm.init(s,t)}),Dus=Qr("$ZodXID",(s,t)=>{t.pattern??(t.pattern=Uds),qm.init(s,t)}),Rus=Qr("$ZodKSUID",(s,t)=>{t.pattern??(t.pattern=qds),qm.init(s,t)}),Ous=Qr("$ZodISODateTime",(s,t)=>{t.pattern??(t.pattern=aus(t)),qm.init(s,t)}),Fus=Qr("$ZodISODate",(s,t)=>{t.pattern??(t.pattern=nus),qm.init(s,t)}),zus=Qr("$ZodISOTime",(s,t)=>{t.pattern??(t.pattern=rus(t)),qm.init(s,t)}),Bus=Qr("$ZodISODuration",(s,t)=>{t.pattern??(t.pattern=Hds),qm.init(s,t)}),$us=Qr("$ZodIPv4",(s,t)=>{t.pattern??(t.pattern=Zds),qm.init(s,t),s._zod.bag.format="ipv4"}),Uus=Qr("$ZodIPv6",(s,t)=>{t.pattern??(t.pattern=Xds),qm.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})}}}),qus=Qr("$ZodCIDRv4",(s,t)=>{t.pattern??(t.pattern=Qds),qm.init(s,t)}),Vus=Qr("$ZodCIDRv6",(s,t)=>{t.pattern??(t.pattern=Jds),qm.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 ENt(s){if(s==="")return!0;if(/\s/.test(s)||s.length%4!==0)return!1;try{return atob(s),!0}catch{return!1}}const Hus=Qr("$ZodBase64",(s,t)=>{t.pattern??(t.pattern=eus),qm.init(s,t),s._zod.bag.contentEncoding="base64",s._zod.check=n=>{ENt(n.value)||n.issues.push({code:"invalid_format",format:"base64",input:n.value,inst:s,continue:!t.abort})}});function Gus(s){if(!NNt.test(s))return!1;const t=s.replace(/[-_]/g,r=>r==="-"?"+":"/"),n=t.padEnd(Math.ceil(t.length/4)*4,"=");return ENt(n)}const Wus=Qr("$ZodBase64URL",(s,t)=>{t.pattern??(t.pattern=NNt),qm.init(s,t),s._zod.bag.contentEncoding="base64url",s._zod.check=n=>{Gus(n.value)||n.issues.push({code:"invalid_format",format:"base64url",input:n.value,inst:s,continue:!t.abort})}}),Kus=Qr("$ZodE164",(s,t)=>{t.pattern??(t.pattern=sus),qm.init(s,t)});function Yus(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 Zus=Qr("$ZodJWT",(s,t)=>{qm.init(s,t),s._zod.check=n=>{Yus(n.value,t.alg)||n.issues.push({code:"invalid_format",format:"jwt",input:n.value,inst:s,continue:!t.abort})}}),MNt=Qr("$ZodNumber",(s,t)=>{vf.init(s,t),s._zod.pattern=s._zod.bag.pattern??lus,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}}),Xus=Qr("$ZodNumberFormat",(s,t)=>{mus.init(s,t),MNt.init(s,t)}),Qus=Qr("$ZodBoolean",(s,t)=>{vf.init(s,t),s._zod.pattern=cus,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}}),Jus=Qr("$ZodUnknown",(s,t)=>{vf.init(s,t),s._zod.parse=n=>n}),ehs=Qr("$ZodNever",(s,t)=>{vf.init(s,t),s._zod.parse=(n,r)=>(n.issues.push({expected:"never",code:"invalid_type",input:n.value,inst:s}),n)});function Jtt(s,t,n){s.issues.length&&t.issues.push(...bNt(n,s.issues)),t.value[n]=s.value}const ths=Qr("$ZodArray",(s,t)=>{vf.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;lJtt(d,n,l))):Jtt(c,n,l)}return i.length?Promise.all(i).then(()=>n):n}});function H2e(s,t,n,r,a,i){const l=n in r;if(s.issues.length){if(a&&i&&!l)return;t.issues.push(...bNt(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 LNt(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=xds(s.shape);return{...s,keys:t,keySet:new Set(t),numKeys:t.length,optionalKeys:new Set(n)}}function PNt(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 f=c.run({value:t[m],issues:[]},r);f instanceof Promise?s.push(f.then(g=>H2e(g,n,m,t,u,h))):H2e(f,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 shs=Qr("$ZodObject",(s,t)=>{vf.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=nUe(()=>LNt(t));nh(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=V2e,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 f=h[m],g=f._zod.optin==="optional",y=f._zod.optout==="optional",x=f._zod.run({value:d[m],issues:[]},c);x instanceof Promise?u.push(x.then(_=>H2e(_,o,m,d,g,y))):H2e(x,o,m,d,g,y)}return i?PNt(u,d,o,c,r.value,s):u.length?Promise.all(u).then(()=>o):o}}),nhs=Qr("$ZodObjectJIT",(s,t)=>{shs.init(s,t);const n=s._zod.parse,r=nUe(()=>LNt(t)),a=m=>{var k,A;const f=new Nus(["shape","payload","ctx"]),g=r.value,y=T=>{const P=Xtt(T);return`shape[${P}]._zod.run({ value: input[${P}], issues: [] }, ctx)`};f.write("const input = payload.value;");const x=Object.create(null);let _=0;for(const T of g.keys)x[T]=`key_${_++}`;f.write("const newResult = {};");for(const T of g.keys){const P=x[T],I=Xtt(T),M=m[T],L=((k=M==null?void 0:M._zod)==null?void 0:k.optin)==="optional",z=((A=M==null?void 0:M._zod)==null?void 0:A.optout)==="optional";f.write(`const ${P} = ${y(T)};`),L&&z?f.write(` if (${P}.issues.length) { if (${I} in input) { payload.issues = payload.issues.concat(${P}.issues.map(iss => ({ ...iss, path: iss.path ? [${I}, ...iss.path] : [${I}] }))); } } if (${P}.value === undefined) { if (${I} in input) { newResult[${I}] = undefined; } } else { newResult[${I}] = ${P}.value; } `):L?f.write(` if (${P}.issues.length) { payload.issues = payload.issues.concat(${P}.issues.map(iss => ({ ...iss, path: iss.path ? [${I}, ...iss.path] : [${I}] }))); } if (${P}.value === undefined) { if (${I} in input) { newResult[${I}] = undefined; } } else { newResult[${I}] = ${P}.value; } `):f.write(` const ${P}_present = ${I} in input; if (${P}.issues.length) { payload.issues = payload.issues.concat(${P}.issues.map(iss => ({ ...iss, path: iss.path ? [${I}, ...iss.path] : [${I}] }))); } if (!${P}_present && !${P}.issues.length) { payload.issues.push({ code: "invalid_type", expected: "nonoptional", input: undefined, path: [${I}] }); } if (${P}_present) { if (${P}.value === undefined) { newResult[${I}] = undefined; } else { newResult[${I}] = ${P}.value; } } `)}f.write("payload.value = newResult;"),f.write("return payload;");const b=f.compile();return(T,P)=>b(m,T,P)};let i;const l=V2e,o=!sUe.jitless,d=o&&fds.value,u=t.catchall;let h;s._zod.parse=(m,f)=>{h??(h=r.value);const g=m.value;return l(g)?o&&d&&(f==null?void 0:f.async)===!1&&f.jitless!==!0?(i||(i=a(t.shape)),m=i(m,f),u?PNt([],g,m,f,h,s):m):n(m,f):(m.issues.push({expected:"object",code:"invalid_type",input:g,inst:s}),m)}});function est(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=>!M7(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=>nR(l,r,sR())))}),t)}const rhs=Qr("$ZodUnion",(s,t)=>{vf.init(s,t),nh(s._zod,"optin",()=>t.options.some(r=>r._zod.optin==="optional")?"optional":void 0),nh(s._zod,"optout",()=>t.options.some(r=>r._zod.optout==="optional")?"optional":void 0),nh(s._zod,"values",()=>{if(t.options.every(r=>r._zod.values))return new Set(t.options.flatMap(r=>Array.from(r._zod.values)))}),nh(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=>aUe(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=>est(o,r,s,a)):est(l,r,s,a)}}),ahs=Qr("$ZodIntersection",(s,t)=>{vf.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])=>tst(n,c,d)):tst(n,i,l)}});function GDe(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(hY(s)&&hY(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=GDe(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}),M7(s))return s;const l=GDe(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 ihs=Qr("$ZodEnum",(s,t)=>{vf.init(s,t);const n=xNt(t.entries),r=new Set(n);s._zod.values=r,s._zod.pattern=new RegExp(`^(${n.filter(a=>gds.has(typeof a)).map(a=>typeof a=="string"?zB(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}}),ohs=Qr("$ZodLiteral",(s,t)=>{if(vf.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"?zB(r):r?zB(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}}),lhs=Qr("$ZodTransform",(s,t)=>{vf.init(s,t),s._zod.optin="optional",s._zod.parse=(n,r)=>{if(r.direction==="backward")throw new gNt(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 U9;return n.value=a,n.fallback=!0,n}});function sst(s,t){return t===void 0&&(s.issues.length||s.fallback)?{issues:[],value:void 0}:s}const INt=Qr("$ZodOptional",(s,t)=>{vf.init(s,t),s._zod.optin="optional",s._zod.optout="optional",nh(s._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,void 0]):void 0),nh(s._zod,"pattern",()=>{const n=t.innerType._zod.pattern;return n?new RegExp(`^(${aUe(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=>sst(l,a)):sst(i,a)}return n.value===void 0?n:t.innerType._zod.run(n,r)}}),chs=Qr("$ZodExactOptional",(s,t)=>{INt.init(s,t),nh(s._zod,"values",()=>t.innerType._zod.values),nh(s._zod,"pattern",()=>t.innerType._zod.pattern),s._zod.parse=(n,r)=>t.innerType._zod.run(n,r)}),dhs=Qr("$ZodNullable",(s,t)=>{vf.init(s,t),nh(s._zod,"optin",()=>t.innerType._zod.optin),nh(s._zod,"optout",()=>t.innerType._zod.optout),nh(s._zod,"pattern",()=>{const n=t.innerType._zod.pattern;return n?new RegExp(`^(${aUe(n.source)}|null)$`):void 0}),nh(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)}),uhs=Qr("$ZodDefault",(s,t)=>{vf.init(s,t),s._zod.optin="optional",nh(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=>nst(i,t)):nst(a,t)}});function nst(s,t){return s.value===void 0&&(s.value=t.defaultValue),s}const hhs=Qr("$ZodPrefault",(s,t)=>{vf.init(s,t),s._zod.optin="optional",nh(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))}),mhs=Qr("$ZodNonOptional",(s,t)=>{vf.init(s,t),nh(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=>rst(i,s)):rst(a,s)}});function rst(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 phs=Qr("$ZodCatch",(s,t)=>{vf.init(s,t),s._zod.optin="optional",nh(s._zod,"optout",()=>t.innerType._zod.optout),nh(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=>nR(l,r,sR()))},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=>nR(i,r,sR()))},input:n.value}),n.issues=[],n.fallback=!0),n)}}),fhs=Qr("$ZodPipe",(s,t)=>{vf.init(s,t),nh(s._zod,"values",()=>t.in._zod.values),nh(s._zod,"optin",()=>t.in._zod.optin),nh(s._zod,"optout",()=>t.out._zod.optout),nh(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=>Ute(l,t.in,r)):Ute(i,t.in,r)}const a=t.in._zod.run(n,r);return a instanceof Promise?a.then(i=>Ute(i,t.out,r)):Ute(a,t.out,r)}});function Ute(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 ghs=Qr("$ZodReadonly",(s,t)=>{vf.init(s,t),nh(s._zod,"propValues",()=>t.innerType._zod.propValues),nh(s._zod,"values",()=>t.innerType._zod.values),nh(s._zod,"optin",()=>{var n,r;return(r=(n=t.innerType)==null?void 0:n._zod)==null?void 0:r.optin}),nh(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(ast):ast(a)}});function ast(s){return s.value=Object.freeze(s.value),s}const xhs=Qr("$ZodCustom",(s,t)=>{fb.init(s,t),vf.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=>ist(i,n,r,s));ist(a,n,r,s)}});function ist(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(mY(a))}}var ost;class yhs{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 vhs(){return new yhs}(ost=globalThis).__zod_globalRegistry??(ost.__zod_globalRegistry=vhs());const $H=globalThis.__zod_globalRegistry;function bhs(s,t){return new s({type:"string",...To(t)})}function _hs(s,t){return new s({type:"string",format:"email",check:"string_format",abort:!1,...To(t)})}function lst(s,t){return new s({type:"string",format:"guid",check:"string_format",abort:!1,...To(t)})}function whs(s,t){return new s({type:"string",format:"uuid",check:"string_format",abort:!1,...To(t)})}function jhs(s,t){return new s({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...To(t)})}function Nhs(s,t){return new s({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...To(t)})}function khs(s,t){return new s({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...To(t)})}function Shs(s,t){return new s({type:"string",format:"url",check:"string_format",abort:!1,...To(t)})}function Chs(s,t){return new s({type:"string",format:"emoji",check:"string_format",abort:!1,...To(t)})}function Ahs(s,t){return new s({type:"string",format:"nanoid",check:"string_format",abort:!1,...To(t)})}function Ths(s,t){return new s({type:"string",format:"cuid",check:"string_format",abort:!1,...To(t)})}function Ehs(s,t){return new s({type:"string",format:"cuid2",check:"string_format",abort:!1,...To(t)})}function Mhs(s,t){return new s({type:"string",format:"ulid",check:"string_format",abort:!1,...To(t)})}function Lhs(s,t){return new s({type:"string",format:"xid",check:"string_format",abort:!1,...To(t)})}function Phs(s,t){return new s({type:"string",format:"ksuid",check:"string_format",abort:!1,...To(t)})}function Ihs(s,t){return new s({type:"string",format:"ipv4",check:"string_format",abort:!1,...To(t)})}function Dhs(s,t){return new s({type:"string",format:"ipv6",check:"string_format",abort:!1,...To(t)})}function Rhs(s,t){return new s({type:"string",format:"cidrv4",check:"string_format",abort:!1,...To(t)})}function Ohs(s,t){return new s({type:"string",format:"cidrv6",check:"string_format",abort:!1,...To(t)})}function Fhs(s,t){return new s({type:"string",format:"base64",check:"string_format",abort:!1,...To(t)})}function zhs(s,t){return new s({type:"string",format:"base64url",check:"string_format",abort:!1,...To(t)})}function Bhs(s,t){return new s({type:"string",format:"e164",check:"string_format",abort:!1,...To(t)})}function $hs(s,t){return new s({type:"string",format:"jwt",check:"string_format",abort:!1,...To(t)})}function Uhs(s,t){return new s({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...To(t)})}function qhs(s,t){return new s({type:"string",format:"date",check:"string_format",...To(t)})}function Vhs(s,t){return new s({type:"string",format:"time",check:"string_format",precision:null,...To(t)})}function Hhs(s,t){return new s({type:"string",format:"duration",check:"string_format",...To(t)})}function Ghs(s,t){return new s({type:"number",checks:[],...To(t)})}function Whs(s,t){return new s({type:"number",check:"number_format",abort:!1,format:"safeint",...To(t)})}function Khs(s,t){return new s({type:"boolean",...To(t)})}function Yhs(s){return new s({type:"unknown"})}function Zhs(s,t){return new s({type:"never",...To(t)})}function cst(s,t){return new ANt({check:"less_than",...To(t),value:s,inclusive:!1})}function L6e(s,t){return new ANt({check:"less_than",...To(t),value:s,inclusive:!0})}function dst(s,t){return new TNt({check:"greater_than",...To(t),value:s,inclusive:!1})}function P6e(s,t){return new TNt({check:"greater_than",...To(t),value:s,inclusive:!0})}function ust(s,t){return new hus({check:"multiple_of",...To(t),value:s})}function DNt(s,t){return new pus({check:"max_length",...To(t),maximum:s})}function G2e(s,t){return new fus({check:"min_length",...To(t),minimum:s})}function RNt(s,t){return new gus({check:"length_equals",...To(t),length:s})}function Xhs(s,t){return new xus({check:"string_format",format:"regex",...To(t),pattern:s})}function Qhs(s){return new yus({check:"string_format",format:"lowercase",...To(s)})}function Jhs(s){return new vus({check:"string_format",format:"uppercase",...To(s)})}function ems(s,t){return new bus({check:"string_format",format:"includes",...To(t),includes:s})}function tms(s,t){return new _us({check:"string_format",format:"starts_with",...To(t),prefix:s})}function sms(s,t){return new wus({check:"string_format",format:"ends_with",...To(t),suffix:s})}function cU(s){return new jus({check:"overwrite",tx:s})}function nms(s){return cU(t=>t.normalize(s))}function rms(){return cU(s=>s.trim())}function ams(){return cU(s=>s.toLowerCase())}function ims(){return cU(s=>s.toUpperCase())}function oms(){return cU(s=>pds(s))}function lms(s,t,n){return new s({type:"array",element:t,...To(n)})}function cms(s,t,n){return new s({type:"custom",check:"custom",fn:t,...To(n)})}function dms(s,t){const n=ums(r=>(r.addIssue=a=>{if(typeof a=="string")r.issues.push(mY(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(mY(i))}},s(r.value,r)),t);return n}function ums(s,t){const n=new fb({check:"custom",...To(t)});return n._zod.check=s,n}function ONt(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)??$H,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 ty(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 g=l.schema,y=t.processors[a.type];if(!y)throw new Error(`[toJSONSchema]: Non-representable type encountered: ${a.type}`);y(s,t,g,m)}const f=s._zod.parent;f&&(l.ref||(l.ref=f),ty(f,t,m),t.seen.get(f).isParent=!0)}const c=t.metadataRegistry.get(s);return c&&Object.assign(l.schema,c),t.io==="input"&&vv(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 FNt(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 x=(y=s.external.registry.get(u[0]))==null?void 0:y.id,_=s.external.uri??(k=>k);if(x)return{ref:_(x)};const b=u[1].defId??u[1].schema.id??`schema${s.counter++}`;return u[1].defId=b,{defId:b,ref:`${_("__shared")}#/${h}/${b}`}}if(u[1]===n)return{ref:"#"};const f=`#/${h}/`,g=u[1].schema.id??`__schema${s.counter++}`;return{defId:g,ref:f+g}},i=u=>{if(u[1].schema.$ref)return;const h=u[1],{ref:m,defId:f}=a(u);h.def={...h.schema},f&&(h.defId=f);const g=h.schema;for(const y in g)delete g[y];g.$ref=m};if(s.cycles==="throw")for(const u of s.seen.entries()){const h=u[1];if(h.cycle)throw new Error(`Cycle detected: #/${(o=h.cycle)==null?void 0:o.join("/")}/ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(const u of s.seen.entries()){const h=u[1];if(t===u[0]){i(u);continue}if(s.external){const f=(c=s.external.registry.get(u[0]))==null?void 0:c.id;if(t!==u[0]&&f){i(u);continue}}if((d=s.metadataRegistry.get(u[0]))==null?void 0:d.id){i(u);continue}if(h.cycle){i(u);continue}if(h.count>1&&s.reused==="ref"){i(u);continue}}}function zNt(s,t){var o,c,d,u;const n=s.seen.get(t);if(!n)throw new Error("Unprocessed schema. This is a bug in Zod.");const r=h=>{const m=s.seen.get(h);if(m.ref===null)return;const f=m.def??m.schema,g={...f},y=m.ref;if(m.ref=null,y){r(y);const _=s.seen.get(y),b=_.schema;if(b.$ref&&(s.target==="draft-07"||s.target==="draft-04"||s.target==="openapi-3.0")?(f.allOf=f.allOf??[],f.allOf.push(b)):Object.assign(f,b),Object.assign(f,g),h._zod.parent===y)for(const A in f)A==="$ref"||A==="allOf"||A in g||delete f[A];if(b.$ref&&_.def)for(const A in f)A==="$ref"||A==="allOf"||A in _.def&&JSON.stringify(f[A])===JSON.stringify(_.def[A])&&delete f[A]}const x=h._zod.parent;if(x&&x!==y){r(x);const _=s.seen.get(x);if(_!=null&&_.schema.$ref&&(f.$ref=_.schema.$ref,_.def))for(const b in f)b==="$ref"||b==="allOf"||b in _.def&&JSON.stringify(f[b])===JSON.stringify(_.def[b])&&delete f[b]}s.override({zodSchema:h,jsonSchema:f,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:W2e(t,"input",s.processors),output:W2e(t,"output",s.processors)}},enumerable:!1,writable:!1}),h}catch{throw new Error("Error converting schema to JSON.")}}function vv(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 vv(r.element,n);if(r.type==="set")return vv(r.valueType,n);if(r.type==="lazy")return vv(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 vv(r.innerType,n);if(r.type==="intersection")return vv(r.left,n)||vv(r.right,n);if(r.type==="record"||r.type==="map")return vv(r.keyType,n)||vv(r.valueType,n);if(r.type==="pipe")return s._zod.traits.has("$ZodCodec")?!0:vv(r.in,n)||vv(r.out,n);if(r.type==="object"){for(const a in r.shape)if(vv(r.shape[a],n))return!0;return!1}if(r.type==="union"){for(const a of r.options)if(vv(a,n))return!0;return!1}if(r.type==="tuple"){for(const a of r.items)if(vv(a,n))return!0;return!!(r.rest&&vv(r.rest,n))}return!1}const hms=(s,t={})=>n=>{const r=ONt({...n,processors:t});return ty(s,r),FNt(r,s),zNt(r,s)},W2e=(s,t,n={})=>r=>{const{libraryOptions:a,target:i}=r??{},l=ONt({...a??{},target:i,io:t,processors:n});return ty(s,l),FNt(l,s),zNt(l,s)},mms={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},pms=(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=mms[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}))])}},fms=(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),f=t.target==="draft-04"||t.target==="openapi-3.0";h?f?(a.minimum=u,a.exclusiveMinimum=!0):a.exclusiveMinimum=u:typeof i=="number"&&(a.minimum=i),m?f?(a.maximum=d,a.exclusiveMaximum=!0):a.exclusiveMaximum=d:typeof l=="number"&&(a.maximum=l),typeof c=="number"&&(a.multipleOf=c)},gms=(s,t,n,r)=>{n.type="boolean"},xms=(s,t,n,r)=>{n.not={}},yms=(s,t,n,r)=>{},vms=(s,t,n,r)=>{const a=s._zod.def,i=xNt(a.entries);i.every(l=>typeof l=="number")&&(n.type="number"),i.every(l=>typeof l=="string")&&(n.type="string"),n.enum=i},bms=(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},_ms=(s,t,n,r)=>{if(t.unrepresentable==="throw")throw new Error("Custom types cannot be represented in JSON Schema")},wms=(s,t,n,r)=>{if(t.unrepresentable==="throw")throw new Error("Transforms cannot be represented in JSON Schema")},jms=(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=ty(i.element,t,{...r,path:[...r.path,"items"]})},Nms=(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]=ty(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=ty(i.catchall,t,{...r,path:[...r.path,"additionalProperties"]})):t.io==="output"&&(a.additionalProperties=!1)},kms=(s,t,n,r)=>{const a=s._zod.def,i=a.inclusive===!1,l=a.options.map((o,c)=>ty(o,t,{...r,path:[...r.path,i?"oneOf":"anyOf",c]}));i?n.oneOf=l:n.anyOf=l},Sms=(s,t,n,r)=>{const a=s._zod.def,i=ty(a.left,t,{...r,path:[...r.path,"allOf",0]}),l=ty(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},Cms=(s,t,n,r)=>{const a=s._zod.def,i=ty(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"}]},Ams=(s,t,n,r)=>{const a=s._zod.def;ty(a.innerType,t,r);const i=t.seen.get(s);i.ref=a.innerType},Tms=(s,t,n,r)=>{const a=s._zod.def;ty(a.innerType,t,r);const i=t.seen.get(s);i.ref=a.innerType,n.default=JSON.parse(JSON.stringify(a.defaultValue))},Ems=(s,t,n,r)=>{const a=s._zod.def;ty(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)))},Mms=(s,t,n,r)=>{const a=s._zod.def;ty(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},Lms=(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;ty(l,t,r);const o=t.seen.get(s);o.ref=l},Pms=(s,t,n,r)=>{const a=s._zod.def;ty(a.innerType,t,r);const i=t.seen.get(s);i.ref=a.innerType,n.readOnly=!0},BNt=(s,t,n,r)=>{const a=s._zod.def;ty(a.innerType,t,r);const i=t.seen.get(s);i.ref=a.innerType},Ims=Qr("ZodISODateTime",(s,t)=>{Ous.init(s,t),Dp.init(s,t)});function Dms(s){return Uhs(Ims,s)}const Rms=Qr("ZodISODate",(s,t)=>{Fus.init(s,t),Dp.init(s,t)});function Oms(s){return qhs(Rms,s)}const Fms=Qr("ZodISOTime",(s,t)=>{zus.init(s,t),Dp.init(s,t)});function zms(s){return Vhs(Fms,s)}const Bms=Qr("ZodISODuration",(s,t)=>{Bus.init(s,t),Dp.init(s,t)});function $ms(s){return Hhs(Bms,s)}const $Nt=(s,t)=>{wNt.init(s,t),s.name="ZodError",Object.defineProperties(s,{format:{value:n=>Ads(s,n)},flatten:{value:n=>Cds(s,n)},addIssue:{value:n=>{s.issues.push(n),s.message=JSON.stringify(s.issues,HDe,2)}},addIssues:{value:n=>{s.issues.push(...n),s.message=JSON.stringify(s.issues,HDe,2)}},isEmpty:{get(){return s.issues.length===0}}})},Ums=Qr("ZodError",$Nt),Aj=Qr("ZodError",$Nt,{Parent:Error}),qms=oUe(Aj),Vms=lUe(Aj),Hms=E4e(Aj),Gms=M4e(Aj),Wms=Mds(Aj),Kms=Lds(Aj),Yms=Pds(Aj),Zms=Ids(Aj),Xms=Dds(Aj),Qms=Rds(Aj),Jms=Ods(Aj),eps=Fds(Aj),hst=new WeakMap;function LQ(s,t,n){const r=Object.getPrototypeOf(s);let a=hst.get(r);if(a||(a=new Set,hst.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 bf=Qr("ZodType",(s,t)=>(vf.init(s,t),Object.assign(s["~standard"],{jsonSchema:{input:W2e(s,"input"),output:W2e(s,"output")}}),s.toJSONSchema=hms(s,{}),s.def=t,s.type=t.type,Object.defineProperty(s,"_def",{value:t}),s.parse=(n,r)=>qms(s,n,r,{callee:s.parse}),s.safeParse=(n,r)=>Hms(s,n,r),s.parseAsync=async(n,r)=>Vms(s,n,r,{callee:s.parseAsync}),s.safeParseAsync=async(n,r)=>Gms(s,n,r),s.spa=s.safeParseAsync,s.encode=(n,r)=>Wms(s,n,r),s.decode=(n,r)=>Kms(s,n,r),s.encodeAsync=async(n,r)=>Yms(s,n,r),s.decodeAsync=async(n,r)=>Zms(s,n,r),s.safeEncode=(n,r)=>Xms(s,n,r),s.safeDecode=(n,r)=>Qms(s,n,r),s.safeEncodeAsync=async(n,r)=>Jms(s,n,r),s.safeDecodeAsync=async(n,r)=>eps(s,n,r),LQ(s,"ZodType",{check(...n){const r=this.def;return this.clone(DE(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 RE(this,n,r)},brand(){return this},register(n,r){return n.add(this,r),this},refine(n,r){return this.check(Yps(n,r))},superRefine(n,r){return this.check(Zps(n,r))},overwrite(n){return this.check(cU(n))},optional(){return gst(this)},exactOptional(){return Rps(this)},nullable(){return xst(this)},nullish(){return gst(xst(this))},nonoptional(n){return Ups(this,n)},array(){return Sps(this)},or(n){return Tps([this,n])},and(n){return Mps(this,n)},transform(n){return yst(this,Ips(n))},default(n){return zps(this,n)},prefault(n){return $ps(this,n)},catch(n){return Vps(this,n)},pipe(n){return yst(this,n)},readonly(){return Wps(this)},describe(n){const r=this.clone();return $H.add(r,{description:n}),r},meta(...n){if(n.length===0)return $H.get(this);const r=this.clone();return $H.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=$H.get(s))==null?void 0:n.description},configurable:!0}),s)),UNt=Qr("_ZodString",(s,t)=>{cUe.init(s,t),bf.init(s,t),s._zod.processJSONSchema=(r,a,i)=>pms(s,r,a);const n=s._zod.bag;s.format=n.format??null,s.minLength=n.minimum??null,s.maxLength=n.maximum??null,LQ(s,"_ZodString",{regex(...r){return this.check(Xhs(...r))},includes(...r){return this.check(ems(...r))},startsWith(...r){return this.check(tms(...r))},endsWith(...r){return this.check(sms(...r))},min(...r){return this.check(G2e(...r))},max(...r){return this.check(DNt(...r))},length(...r){return this.check(RNt(...r))},nonempty(...r){return this.check(G2e(1,...r))},lowercase(r){return this.check(Qhs(r))},uppercase(r){return this.check(Jhs(r))},trim(){return this.check(rms())},normalize(...r){return this.check(nms(...r))},toLowerCase(){return this.check(ams())},toUpperCase(){return this.check(ims())},slugify(){return this.check(oms())}})}),tps=Qr("ZodString",(s,t)=>{cUe.init(s,t),UNt.init(s,t),s.email=n=>s.check(_hs(sps,n)),s.url=n=>s.check(Shs(nps,n)),s.jwt=n=>s.check($hs(yps,n)),s.emoji=n=>s.check(Chs(rps,n)),s.guid=n=>s.check(lst(mst,n)),s.uuid=n=>s.check(whs(qte,n)),s.uuidv4=n=>s.check(jhs(qte,n)),s.uuidv6=n=>s.check(Nhs(qte,n)),s.uuidv7=n=>s.check(khs(qte,n)),s.nanoid=n=>s.check(Ahs(aps,n)),s.guid=n=>s.check(lst(mst,n)),s.cuid=n=>s.check(Ths(ips,n)),s.cuid2=n=>s.check(Ehs(ops,n)),s.ulid=n=>s.check(Mhs(lps,n)),s.base64=n=>s.check(Fhs(fps,n)),s.base64url=n=>s.check(zhs(gps,n)),s.xid=n=>s.check(Lhs(cps,n)),s.ksuid=n=>s.check(Phs(dps,n)),s.ipv4=n=>s.check(Ihs(ups,n)),s.ipv6=n=>s.check(Dhs(hps,n)),s.cidrv4=n=>s.check(Rhs(mps,n)),s.cidrv6=n=>s.check(Ohs(pps,n)),s.e164=n=>s.check(Bhs(xps,n)),s.datetime=n=>s.check(Dms(n)),s.date=n=>s.check(Oms(n)),s.time=n=>s.check(zms(n)),s.duration=n=>s.check($ms(n))});function pl(s){return bhs(tps,s)}const Dp=Qr("ZodStringFormat",(s,t)=>{qm.init(s,t),UNt.init(s,t)}),sps=Qr("ZodEmail",(s,t)=>{Aus.init(s,t),Dp.init(s,t)}),mst=Qr("ZodGUID",(s,t)=>{Sus.init(s,t),Dp.init(s,t)}),qte=Qr("ZodUUID",(s,t)=>{Cus.init(s,t),Dp.init(s,t)}),nps=Qr("ZodURL",(s,t)=>{Tus.init(s,t),Dp.init(s,t)}),rps=Qr("ZodEmoji",(s,t)=>{Eus.init(s,t),Dp.init(s,t)}),aps=Qr("ZodNanoID",(s,t)=>{Mus.init(s,t),Dp.init(s,t)}),ips=Qr("ZodCUID",(s,t)=>{Lus.init(s,t),Dp.init(s,t)}),ops=Qr("ZodCUID2",(s,t)=>{Pus.init(s,t),Dp.init(s,t)}),lps=Qr("ZodULID",(s,t)=>{Ius.init(s,t),Dp.init(s,t)}),cps=Qr("ZodXID",(s,t)=>{Dus.init(s,t),Dp.init(s,t)}),dps=Qr("ZodKSUID",(s,t)=>{Rus.init(s,t),Dp.init(s,t)}),ups=Qr("ZodIPv4",(s,t)=>{$us.init(s,t),Dp.init(s,t)}),hps=Qr("ZodIPv6",(s,t)=>{Uus.init(s,t),Dp.init(s,t)}),mps=Qr("ZodCIDRv4",(s,t)=>{qus.init(s,t),Dp.init(s,t)}),pps=Qr("ZodCIDRv6",(s,t)=>{Vus.init(s,t),Dp.init(s,t)}),fps=Qr("ZodBase64",(s,t)=>{Hus.init(s,t),Dp.init(s,t)}),gps=Qr("ZodBase64URL",(s,t)=>{Wus.init(s,t),Dp.init(s,t)}),xps=Qr("ZodE164",(s,t)=>{Kus.init(s,t),Dp.init(s,t)}),yps=Qr("ZodJWT",(s,t)=>{Zus.init(s,t),Dp.init(s,t)}),qNt=Qr("ZodNumber",(s,t)=>{MNt.init(s,t),bf.init(s,t),s._zod.processJSONSchema=(r,a,i)=>fms(s,r,a),LQ(s,"ZodNumber",{gt(r,a){return this.check(dst(r,a))},gte(r,a){return this.check(P6e(r,a))},min(r,a){return this.check(P6e(r,a))},lt(r,a){return this.check(cst(r,a))},lte(r,a){return this.check(L6e(r,a))},max(r,a){return this.check(L6e(r,a))},int(r){return this.check(pst(r))},safe(r){return this.check(pst(r))},positive(r){return this.check(dst(0,r))},nonnegative(r){return this.check(P6e(0,r))},negative(r){return this.check(cst(0,r))},nonpositive(r){return this.check(L6e(0,r))},multipleOf(r,a){return this.check(ust(r,a))},step(r,a){return this.check(ust(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 UW(s){return Ghs(qNt,s)}const vps=Qr("ZodNumberFormat",(s,t)=>{Xus.init(s,t),qNt.init(s,t)});function pst(s){return Whs(vps,s)}const bps=Qr("ZodBoolean",(s,t)=>{Qus.init(s,t),bf.init(s,t),s._zod.processJSONSchema=(n,r,a)=>gms(s,n,r)});function _ps(s){return Khs(bps,s)}const wps=Qr("ZodUnknown",(s,t)=>{Jus.init(s,t),bf.init(s,t),s._zod.processJSONSchema=(n,r,a)=>yms()});function fst(){return Yhs(wps)}const jps=Qr("ZodNever",(s,t)=>{ehs.init(s,t),bf.init(s,t),s._zod.processJSONSchema=(n,r,a)=>xms(s,n,r)});function Nps(s){return Zhs(jps,s)}const kps=Qr("ZodArray",(s,t)=>{ths.init(s,t),bf.init(s,t),s._zod.processJSONSchema=(n,r,a)=>jms(s,n,r,a),s.element=t.element,LQ(s,"ZodArray",{min(n,r){return this.check(G2e(n,r))},nonempty(n){return this.check(G2e(1,n))},max(n,r){return this.check(DNt(n,r))},length(n,r){return this.check(RNt(n,r))},unwrap(){return this.element}})});function Sps(s,t){return lms(kps,s,t)}const Cps=Qr("ZodObject",(s,t)=>{nhs.init(s,t),bf.init(s,t),s._zod.processJSONSchema=(n,r,a)=>Nms(s,n,r,a),nh(s,"shape",()=>t.shape),LQ(s,"ZodObject",{keyof(){return dUe(Object.keys(this._zod.def.shape))},catchall(n){return this.clone({...this._zod.def,catchall:n})},passthrough(){return this.clone({...this._zod.def,catchall:fst()})},loose(){return this.clone({...this._zod.def,catchall:fst()})},strict(){return this.clone({...this._zod.def,catchall:Nps()})},strip(){return this.clone({...this._zod.def,catchall:void 0})},extend(n){return _ds(this,n)},safeExtend(n){return wds(this,n)},merge(n){return jds(this,n)},pick(n){return vds(this,n)},omit(n){return bds(this,n)},partial(...n){return Nds(VNt,this,n[0])},required(...n){return kds(HNt,this,n[0])}})});function H5(s,t){const n={type:"object",shape:s??{},...To(t)};return new Cps(n)}const Aps=Qr("ZodUnion",(s,t)=>{rhs.init(s,t),bf.init(s,t),s._zod.processJSONSchema=(n,r,a)=>kms(s,n,r,a),s.options=t.options});function Tps(s,t){return new Aps({type:"union",options:s,...To(t)})}const Eps=Qr("ZodIntersection",(s,t)=>{ahs.init(s,t),bf.init(s,t),s._zod.processJSONSchema=(n,r,a)=>Sms(s,n,r,a)});function Mps(s,t){return new Eps({type:"intersection",left:s,right:t})}const WDe=Qr("ZodEnum",(s,t)=>{ihs.init(s,t),bf.init(s,t),s._zod.processJSONSchema=(r,a,i)=>vms(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 WDe({...t,checks:[],...To(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 WDe({...t,checks:[],...To(a),entries:i})}});function dUe(s,t){const n=Array.isArray(s)?Object.fromEntries(s.map(r=>[r,r])):s;return new WDe({type:"enum",entries:n,...To(t)})}const Lps=Qr("ZodLiteral",(s,t)=>{ohs.init(s,t),bf.init(s,t),s._zod.processJSONSchema=(n,r,a)=>bms(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 qx(s,t){return new Lps({type:"literal",values:Array.isArray(s)?s:[s],...To(t)})}const Pps=Qr("ZodTransform",(s,t)=>{lhs.init(s,t),bf.init(s,t),s._zod.processJSONSchema=(n,r,a)=>wms(s,n),s._zod.parse=(n,r)=>{if(r.direction==="backward")throw new gNt(s.constructor.name);n.addIssue=i=>{if(typeof i=="string")n.issues.push(mY(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(mY(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 Ips(s){return new Pps({type:"transform",transform:s})}const VNt=Qr("ZodOptional",(s,t)=>{INt.init(s,t),bf.init(s,t),s._zod.processJSONSchema=(n,r,a)=>BNt(s,n,r,a),s.unwrap=()=>s._zod.def.innerType});function gst(s){return new VNt({type:"optional",innerType:s})}const Dps=Qr("ZodExactOptional",(s,t)=>{chs.init(s,t),bf.init(s,t),s._zod.processJSONSchema=(n,r,a)=>BNt(s,n,r,a),s.unwrap=()=>s._zod.def.innerType});function Rps(s){return new Dps({type:"optional",innerType:s})}const Ops=Qr("ZodNullable",(s,t)=>{dhs.init(s,t),bf.init(s,t),s._zod.processJSONSchema=(n,r,a)=>Cms(s,n,r,a),s.unwrap=()=>s._zod.def.innerType});function xst(s){return new Ops({type:"nullable",innerType:s})}const Fps=Qr("ZodDefault",(s,t)=>{uhs.init(s,t),bf.init(s,t),s._zod.processJSONSchema=(n,r,a)=>Tms(s,n,r,a),s.unwrap=()=>s._zod.def.innerType,s.removeDefault=s.unwrap});function zps(s,t){return new Fps({type:"default",innerType:s,get defaultValue(){return typeof t=="function"?t():vNt(t)}})}const Bps=Qr("ZodPrefault",(s,t)=>{hhs.init(s,t),bf.init(s,t),s._zod.processJSONSchema=(n,r,a)=>Ems(s,n,r,a),s.unwrap=()=>s._zod.def.innerType});function $ps(s,t){return new Bps({type:"prefault",innerType:s,get defaultValue(){return typeof t=="function"?t():vNt(t)}})}const HNt=Qr("ZodNonOptional",(s,t)=>{mhs.init(s,t),bf.init(s,t),s._zod.processJSONSchema=(n,r,a)=>Ams(s,n,r,a),s.unwrap=()=>s._zod.def.innerType});function Ups(s,t){return new HNt({type:"nonoptional",innerType:s,...To(t)})}const qps=Qr("ZodCatch",(s,t)=>{phs.init(s,t),bf.init(s,t),s._zod.processJSONSchema=(n,r,a)=>Mms(s,n,r,a),s.unwrap=()=>s._zod.def.innerType,s.removeCatch=s.unwrap});function Vps(s,t){return new qps({type:"catch",innerType:s,catchValue:typeof t=="function"?t:()=>t})}const Hps=Qr("ZodPipe",(s,t)=>{fhs.init(s,t),bf.init(s,t),s._zod.processJSONSchema=(n,r,a)=>Lms(s,n,r,a),s.in=t.in,s.out=t.out});function yst(s,t){return new Hps({type:"pipe",in:s,out:t})}const Gps=Qr("ZodReadonly",(s,t)=>{ghs.init(s,t),bf.init(s,t),s._zod.processJSONSchema=(n,r,a)=>Pms(s,n,r,a),s.unwrap=()=>s._zod.def.innerType});function Wps(s){return new Gps({type:"readonly",innerType:s})}const Kps=Qr("ZodCustom",(s,t)=>{xhs.init(s,t),bf.init(s,t),s._zod.processJSONSchema=(n,r,a)=>_ms(s,n)});function Yps(s,t={}){return cms(Kps,s,t)}function Zps(s,t){return dms(s,t)}const Xps=["Excellent","Good","Neutral","Bad","Very Bad"],Qps=[5,4,3,2,1];function Jps({questions:s,visitorId:t,onComplete:n,onSkip:r}){const a=yos(),[i,l]=N.useState({}),o=s.filter(m=>m.question_type==="rating"),c=s.filter(m=>m.question_type!=="rating"),d=(m,f)=>{l(g=>({...g,[m]:{rating_value:f}}))},u=(m,f)=>{l(g=>({...g,[m]:{text_value:f}}))},h=async()=>{const m=Object.entries(i).filter(([,f])=>f.rating_value!=null||f.text_value&&f.text_value.trim()).map(([f,g])=>{var y;return{visitor_id:t,question_id:f,rating_value:g.rating_value??null,text_value:((y=g.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"}),Xps.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}),Qps.map(f=>{var g;return e.jsx("div",{className:"w-12 flex justify-center",children:e.jsx("button",{type:"button",onClick:()=>d(m.id,f),className:`w-6 h-6 rounded-full border-2 transition-all ${((g=i[m.id])==null?void 0:g.rating_value)===f?"bg-slate-900 border-slate-900":"border-slate-300 hover:border-slate-500"}`})},f)})]},m.id))]}),c.map(m=>{var f;return e.jsxs("div",{children:[e.jsx("label",{className:"text-sm font-medium text-slate-700 block mb-1",children:m.question_text}),e.jsx(Ws,{value:((f=i[m.id])==null?void 0:f.text_value)||"",onChange:g=>u(m.id,g.target.value),placeholder:"Your thoughts...",className:"h-16 text-sm resize-none rounded-xl border-slate-200"})]},m.id)}),e.jsx(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(us,{className:"h-5 w-5 animate-spin"}):"Submit Feedback"})]})}var P4e="Checkbox",[efs,ROn]=Um(P4e),[tfs,uUe]=efs(P4e);function sfs(s){const{__scopeCheckbox:t,checked:n,children:r,defaultChecked:a,disabled:i,form:l,name:o,onCheckedChange:c,required:d,value:u="on",internal_do_not_use_render:h}=s,[m,f]=Ng({prop:n,defaultProp:a??!1,onChange:c,caller:P4e}),[g,y]=N.useState(null),[x,_]=N.useState(null),b=N.useRef(!1),k=g?!!l||!!g.closest("form"):!0,A={checked:m,disabled:i,setChecked:f,control:g,setControl:y,name:o,form:l,value:u,hasConsumerStoppedPropagationRef:b,required:d,defaultChecked:VT(a)?!1:a,isFormControl:k,bubbleInput:x,setBubbleInput:_};return e.jsx(tfs,{scope:t,...A,children:nfs(h)?h(A):r})}var GNt="CheckboxTrigger",WNt=N.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:f,bubbleInput:g}=uUe(GNt,s),y=jo(a,u),x=N.useRef(c);return N.useEffect(()=>{const _=i==null?void 0:i.form;if(_){const b=()=>h(x.current);return _.addEventListener("reset",b),()=>_.removeEventListener("reset",b)}},[i,h]),e.jsx(Da.button,{type:"button",role:"checkbox","aria-checked":VT(c)?"mixed":c,"aria-required":d,"data-state":QNt(c),"data-disabled":o?"":void 0,disabled:o,value:l,...r,ref:y,onKeyDown:la(t,_=>{_.key==="Enter"&&_.preventDefault()}),onClick:la(n,_=>{h(b=>VT(b)?!0:!b),g&&f&&(m.current=_.isPropagationStopped(),m.current||_.stopPropagation())})})});WNt.displayName=GNt;var hUe=N.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(sfs,{__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(WNt,{...h,ref:t,__scopeCheckbox:n}),m&&e.jsx(XNt,{__scopeCheckbox:n})]})})});hUe.displayName=P4e;var KNt="CheckboxIndicator",YNt=N.forwardRef((s,t)=>{const{__scopeCheckbox:n,forceMount:r,...a}=s,i=uUe(KNt,n);return e.jsx(Xf,{present:r||VT(i.checked)||i.checked===!0,children:e.jsx(Da.span,{"data-state":QNt(i.checked),"data-disabled":i.disabled?"":void 0,...a,ref:t,style:{pointerEvents:"none",...s.style}})})});YNt.displayName=KNt;var ZNt="CheckboxBubbleInput",XNt=N.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:f}=uUe(ZNt,s),g=jo(n,f),y=EQ(i),x=fQ(r);N.useEffect(()=>{const b=m;if(!b)return;const k=window.HTMLInputElement.prototype,T=Object.getOwnPropertyDescriptor(k,"checked").set,P=!a.current;if(y!==i&&T){const I=new Event("click",{bubbles:P});b.indeterminate=VT(i),T.call(b,VT(i)?!1:i),b.dispatchEvent(I)}},[m,y,i,a]);const _=N.useRef(VT(i)?!1:i);return e.jsx(Da.input,{type:"checkbox","aria-hidden":!0,defaultChecked:l??_.current,required:o,disabled:c,name:d,value:u,form:h,...t,tabIndex:-1,ref:g,style:{...t.style,...x,position:"absolute",pointerEvents:"none",opacity:0,margin:0,transform:"translateX(-100%)"}})});XNt.displayName=ZNt;function nfs(s){return typeof s=="function"}function VT(s){return s==="indeterminate"}function QNt(s){return VT(s)?"indeterminate":s?"checked":"unchecked"}const Bi=N.forwardRef(({className:s,...t},n)=>e.jsx(hUe,{ref:n,className:Ot("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(YNt,{className:Ot("flex items-center justify-center text-current"),children:e.jsx(pa,{className:"h-4 w-4"})})}));Bi.displayName=hUe.displayName;const l1=m4e,PQ=F$e,rfs=p4e,JNt=N.forwardRef(({className:s,...t},n)=>e.jsx(aU,{className:Ot("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}));JNt.displayName=aU.displayName;const afs=RR("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"}}),Gy=N.forwardRef(({side:s="right",className:t,children:n,...r},a)=>e.jsxs(rfs,{children:[e.jsx(JNt,{}),e.jsxs(iU,{ref:a,className:Ot(afs({side:s}),t),...r,children:[n,e.jsxs(AQ,{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(hr,{className:"h-4 w-4"}),e.jsx("span",{className:"sr-only",children:"Close"})]})]})]}));Gy.displayName=iU.displayName;const gb=({className:s,...t})=>e.jsx("div",{className:Ot("flex flex-col space-y-2 text-center sm:text-left",s),...t});gb.displayName="SheetHeader";const ekt=({className:s,...t})=>e.jsx("div",{className:Ot("flex flex-col-reverse sm:flex-row sm:justify-end sm:space-x-2",s),...t});ekt.displayName="SheetFooter";const xb=N.forwardRef(({className:s,...t},n)=>e.jsx(SQ,{ref:n,className:Ot("text-lg font-semibold text-foreground",s),...t}));xb.displayName=SQ.displayName;const IQ=N.forwardRef(({className:s,...t},n)=>e.jsx(CQ,{ref:n,className:Ot("text-sm text-muted-foreground",s),...t}));IQ.displayName=CQ.displayName;function KDe(s){return/iframe\.mediadelivery\.net\/embed\//.test(s)}function ifs({rooms:s}){var h;const[t,n]=N.useState(((h=s[0])==null?void 0:h.id)||""),[r,a]=N.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 N.useEffect(()=>{if(r===null)return;const m=f=>{f.key==="Escape"?c():f.key==="ArrowLeft"?d():f.key==="ArrowRight"&&u()};return window.addEventListener("keydown",m),()=>window.removeEventListener("keydown",m)},[r,o]),s.length?e.jsxs("div",{className:"hidden md:block",children:[e.jsx("div",{className:"sticky top-0 z-20 -mx-5 px-5 py-3 bg-slate-950/80 backdrop-blur-md border-b border-white/10 overflow-x-auto",children:e.jsx("div",{className:"flex gap-2 min-w-max",children:s.map(m=>e.jsxs("button",{onClick:()=>n(m.id),className:Ot("px-4 py-2 rounded-full text-sm font-medium whitespace-nowrap transition",t===m.id?"bg-white text-slate-900":"bg-white/5 text-white/70 hover:bg-white/10"),children:[m.name,e.jsx("span",{className:"ml-1.5 text-xs opacity-60",children:m.media.length})]},m.id))})}),i&&e.jsxs("div",{className:"mt-6",children:[e.jsx("h3",{className:"text-2xl font-bold",children:i.name}),i.description&&e.jsx("p",{className:"text-white/60 mt-1.5 text-sm max-w-2xl",children:i.description}),i.media.length===0?e.jsx("p",{className:"text-white/40 text-sm mt-6 italic",children:"No media yet for this room."}):e.jsx("div",{className:"mt-5 grid grid-cols-2 lg:grid-cols-3 gap-3",children:i.media.map((m,f)=>e.jsx("button",{onClick:()=>a(f),className:"relative aspect-[4/3] rounded-xl overflow-hidden bg-white/5 group",children:m.kind==="video"?e.jsxs(e.Fragment,{children:[KDe(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(na,{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(Fc,{className:"h-6 w-6"})}),l.kind==="video"?KDe(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(Qa,{className:"h-6 w-6"})})]})]}):null}function ofs({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=N.useRef(null),[r,a]=N.useState(0);N.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:Ot("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"?KDe(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(Fc,{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(Qa,{className:"h-4 w-4"})]})]})]})}const I6e={question:{label:"Ask a Question",title:"Ask the agent",placeholder:"What would you like to know about the home?",icon:xo},showing:{label:"Schedule a Showing",title:"Request a private showing",placeholder:"Anything specific to focus on during the showing? (optional)",icon:ta},disclosure:{label:"Request Disclosures",title:"Request seller disclosures",placeholder:"Any specific documents? (optional)",icon:Wr},offer:{label:"I'm Interested — Let's Talk",title:"Express interest / make an offer",placeholder:"Tell the agent about your interest or any offer thoughts.",icon:Ed}},lfs=["Seller's Property Disclosure","HOA Documents & Bylaws","Inspection Reports","Title / CC&Rs","Utility & Tax History"];function cfs(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 dfs({openHouse:s,visitorId:t,visitorName:n,visitorEmail:r,visitorPhone:a,previewMode:i=!1}){var Be;const l=s.profiles,o=((Be=l==null?void 0:l.name)==null?void 0:Be.split(" ").map(Ne=>Ne[0]).join("").slice(0,2))||"?",c=s.brand_color_override||null,[d,u]=N.useState(null),[h,m]=N.useState(""),[f,g]=N.useState(r||""),[y,x]=N.useState(a||""),[_,b]=N.useState(!1),[k,A]=N.useState(null),[T,P]=N.useState(""),[I,M]=N.useState(""),[L,z]=N.useState(""),[$,V]=N.useState([]),[W,G]=N.useState(""),[X,te]=N.useState(""),[ne,me]=N.useState(""),[ue,ce]=N.useState(""),ae=cfs(s.price),he=s.tour_mode==="rooms",{data:xe=[]}=Aos(he?s.id:void 0),ve=[s.enable_question&&"question",s.enable_showing&&"showing",s.enable_disclosures&&"disclosure",s.enable_offer&&"offer"].filter(Boolean),ge=Ne=>{u(Ne),m(""),P(""),M(""),z(""),V([]),G(""),te(""),me(""),ce("")},be=()=>{u(null)},Se=Ne=>{V(Ge=>Ge.includes(Ne)?Ge.filter(Ce=>Ce!==Ne):[...Ge,Ne])},Ie=Ne=>Ne==="showing"?{preferred_date:T||null,preferred_time:I||null,alternate_date:L||null}:Ne==="disclosure"?{requested_documents:$}:Ne==="offer"?{offer_amount:W||null,financing:X||null,timeline:ne||null,pre_approved:ue||null}:{},Me=d?d==="showing"?!!T:d==="question"?h.trim().length>0:!0:!1,Re=async()=>{if(d){if(i){xa({title:"Preview mode",description:"Lead not sent — this is just a preview."}),A(d),setTimeout(()=>{u(null),A(null)},1500);return}b(!0);try{const Ne=Ie(d),{error:Ge}=await H.from("open_house_leads").insert({open_house_id:s.id,visitor_id:t,action_type:d,payload:{message:h.trim()||null,email:f.trim()||null,phone:y.trim()||null,visitor_name:n,...Ne}});if(Ge)throw Ge;H.functions.invoke("send-virtual-open-house-lead",{body:{open_house_id:s.id,visitor_id:t,action_type:d,message:h.trim()||null,visitor_name:n,visitor_email:f.trim()||null,visitor_phone:y.trim()||null,extras:Ne}}).catch(()=>{}),A(d),xa({title:"Sent!",description:"The agent has been notified."}),setTimeout(()=>{be(),A(null)},1400)}catch(Ne){xa({title:"Something went wrong",description:Ne.message,variant:"destructive"})}finally{b(!1)}}};return e.jsxs("div",{className:"min-h-screen bg-slate-950 text-white",children:[e.jsxs("div",{className:"relative w-full aspect-video bg-slate-900 md:max-h-[70vh]",children:[s.hero_video_url?e.jsx("video",{src:s.hero_video_url,poster:s.hero_video_thumbnail_url||s.photo_url||void 0,controls:!0,playsInline:!0,className:"w-full h-full object-cover"}):s.photo_url?e.jsx("img",{src:s.photo_url,alt:s.property_address,className:"w-full h-full object-cover"}):e.jsx("div",{className:"w-full h-full flex items-center justify-center text-white/40",children:"No tour video yet"}),e.jsx("div",{className:"absolute inset-x-0 bottom-0 h-32 bg-gradient-to-t from-slate-950 to-transparent pointer-events-none"})]}),e.jsxs("div",{className:"max-w-3xl mx-auto px-5 pb-32 -mt-10 relative z-10",children:[e.jsxs("div",{className:"bg-slate-900/80 backdrop-blur-md border border-white/10 rounded-2xl p-6 shadow-2xl",children:[e.jsx("h1",{className:"text-2xl font-bold leading-tight",children:s.property_address}),s.city&&e.jsxs("p",{className:"text-sm text-white/60 mt-1 flex items-center gap-1",children:[e.jsx(ii,{className:"h-3.5 w-3.5"}),s.city,s.state?`, ${s.state}`:""," ",s.zip]}),ae&&e.jsx("p",{className:"text-3xl font-bold text-white mt-3",children:ae}),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(A_,{className:"h-4 w-4"}),s.beds," bd"]}),s.baths!=null&&e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx(Wx,{className:"h-4 w-4"}),s.baths," ba"]}),s.sqft!=null&&e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx(L_,{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(Ua,{className:"h-12 w-12 ring-2 ring-white/20",style:c?{boxShadow:`0 0 0 2px ${c}`}:void 0,children:[e.jsx(Gi,{src:l.avatar_url||"",alt:l.name||""}),e.jsx(qa,{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(ga,{className:"h-4 w-4"})}),l.email&&e.jsx("a",{href:`mailto:${l.email}`,"aria-label":`Email ${l.name}`,className:"h-10 w-10 rounded-full bg-white/10 hover:bg-white/20 transition-colors flex items-center justify-center text-white",style:c?{backgroundColor:`${c}33`,color:"white"}:void 0,children:e.jsx(mn,{className:"h-4 w-4"})})]})]}),he&&xe.length>0&&e.jsxs("div",{className:"mt-8",children:[e.jsx(ifs,{rooms:xe}),e.jsx(ofs,{rooms:xe})]}),ve.length>0&&e.jsx("div",{className:"mt-5 grid grid-cols-1 sm:grid-cols-2 gap-3",children:ve.map(Ne=>{const Ge=I6e[Ne],Ce=Ge.icon;return e.jsxs("button",{onClick:()=>ge(Ne),className:"flex items-center gap-3 p-4 rounded-xl bg-white text-slate-900 hover:bg-white/90 transition-colors text-left",children:[e.jsx("div",{className:"w-10 h-10 rounded-lg flex items-center justify-center shrink-0",style:c?{backgroundColor:`${c}1a`,color:c}:{backgroundColor:"#f1f5f9",color:"#334155"},children:e.jsx(Ce,{className:"h-5 w-5"})}),e.jsx("span",{className:"font-medium text-sm",children:Ge.label})]},Ne)})}),e.jsx("p",{className:"text-center text-white/30 text-xs mt-8",children:"Powered by LevelUp Virtual Open House"})]}),e.jsx(l1,{open:!!d,onOpenChange:Ne=>!Ne&&be(),children:e.jsx(Gy,{side:"bottom",className:"rounded-t-2xl max-h-[92vh] overflow-y-auto",children:d&&e.jsxs(e.Fragment,{children:[e.jsxs(gb,{className:"text-left",children:[e.jsx(xb,{children:I6e[d].title}),e.jsxs(IQ,{children:[(l==null?void 0:l.name)||"The agent"," will be notified by email."]})]}),k===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(Hr,{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(re,{className:"text-xs",children:"Email"}),e.jsx(we,{type:"email",value:f,onChange:Ne=>g(Ne.target.value),placeholder:"you@example.com",className:"mt-1"})]}),e.jsxs("div",{children:[e.jsx(re,{className:"text-xs",children:"Phone"}),e.jsx(we,{type:"tel",value:y,onChange:Ne=>x(Ne.target.value),placeholder:"(555) 123-4567",className:"mt-1"})]})]}),d==="showing"&&e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(re,{className:"text-xs",children:"Preferred date *"}),e.jsx(we,{type:"date",value:T,onChange:Ne=>P(Ne.target.value),className:"mt-1"})]}),e.jsxs("div",{children:[e.jsx(re,{className:"text-xs",children:"Preferred time"}),e.jsx(we,{type:"time",value:I,onChange:Ne=>M(Ne.target.value),className:"mt-1"})]})]}),e.jsxs("div",{children:[e.jsx(re,{className:"text-xs",children:"Alternate date (optional)"}),e.jsx(we,{type:"date",value:L,onChange:Ne=>z(Ne.target.value),className:"mt-1"})]})]}),d==="disclosure"&&e.jsxs("div",{children:[e.jsx(re,{className:"text-xs",children:"Which documents? (select all that apply)"}),e.jsx("div",{className:"mt-2 space-y-2",children:lfs.map(Ne=>e.jsxs("label",{className:"flex items-center gap-2 text-sm cursor-pointer",children:[e.jsx(Bi,{checked:$.includes(Ne),onCheckedChange:()=>Se(Ne)}),e.jsx("span",{children:Ne})]},Ne))})]}),d==="offer"&&e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(re,{className:"text-xs",children:"Estimated offer"}),e.jsx(we,{value:W,onChange:Ne=>G(Ne.target.value),placeholder:"$",className:"mt-1"})]}),e.jsxs("div",{children:[e.jsx(re,{className:"text-xs",children:"Financing"}),e.jsxs(Ns,{value:X,onValueChange:te,children:[e.jsx(ws,{className:"mt-1",children:e.jsx(ks,{placeholder:"Select..."})}),e.jsxs(js,{children:[e.jsx(nt,{value:"Cash",children:"Cash"}),e.jsx(nt,{value:"Conventional",children:"Conventional"}),e.jsx(nt,{value:"FHA",children:"FHA"}),e.jsx(nt,{value:"VA",children:"VA"}),e.jsx(nt,{value:"Other",children:"Other"})]})]})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(re,{className:"text-xs",children:"Timeline"}),e.jsxs(Ns,{value:ne,onValueChange:me,children:[e.jsx(ws,{className:"mt-1",children:e.jsx(ks,{placeholder:"Select..."})}),e.jsxs(js,{children:[e.jsx(nt,{value:"ASAP",children:"ASAP"}),e.jsx(nt,{value:"30 days",children:"30 days"}),e.jsx(nt,{value:"60 days",children:"60 days"}),e.jsx(nt,{value:"90+ days",children:"90+ days"})]})]})]}),e.jsxs("div",{children:[e.jsx(re,{className:"text-xs",children:"Pre-approved?"}),e.jsxs(Ns,{value:ue,onValueChange:ce,children:[e.jsx(ws,{className:"mt-1",children:e.jsx(ks,{placeholder:"Select..."})}),e.jsxs(js,{children:[e.jsx(nt,{value:"Yes",children:"Yes"}),e.jsx(nt,{value:"No",children:"No"}),e.jsx(nt,{value:"In progress",children:"In progress"})]})]})]})]})]}),e.jsxs("div",{children:[e.jsxs(re,{className:"text-xs",children:["Message",d==="question"?" *":" (optional)"]}),e.jsx(Ws,{value:h,onChange:Ne=>m(Ne.target.value),placeholder:I6e[d].placeholder,rows:4,className:"mt-1"})]}),e.jsx(B,{onClick:Re,disabled:_||!Me,className:"w-full h-12 text-white hover:opacity-90",style:c?{backgroundColor:c}:void 0,children:_?e.jsx(us,{className:"h-4 w-4 animate-spin"}):"Send to agent"})]})]})})})]})}const ufs=H5({first_name:pl().trim().min(1,"First name is required").max(50),last_name:pl().trim().max(50).optional(),email:pl().trim().email("Please enter a valid email").max(255).optional().or(qx("")),phone:pl().trim().max(20).optional().or(qx(""))}),hfs=[{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 tkt({slug:s}={}){var $e;const t=uo(),n=s||t.slug,[r]=$c(),a=r.get("kiosk")==="1"||r.get("mode")==="kiosk",i=8,{data:l,isLoading:o,error:c}=fos(n),d=Nos(),u=kos(),h=Sos(),m=N.useRef(!1),[f,g]=N.useState("welcome"),[y,x]=N.useState(null),[_,b]=N.useState({first_name:"",last_name:"",email:"",phone:"",visitor_address:""}),[k,A]=N.useState(""),[T,P]=N.useState(!1),[I,M]=N.useState(!1),[L,z]=N.useState(""),[$,V]=N.useState(""),[W,G]=N.useState(i),X=N.useCallback(()=>{x(null),b({first_name:"",last_name:"",email:"",phone:"",visitor_address:""}),A(""),P(!1),M(!1),z(""),V(""),G(i),g(a?"info":"welcome")},[a]),te=N.useCallback((Ye,Je)=>{l!=null&&l.id&&H.functions.invoke("guestbook-lead-notify",{body:{open_house_id:l.id,visitor_id:Ye,first_name:Je.first_name??_.first_name,last_name:Je.last_name??_.last_name,email:Je.email??_.email,phone:Je.phone??_.phone,visitor_intent:Je.visitor_intent??k,message:Je.message,wants_market_updates:Je.wants_market_updates??T,has_agent:Je.has_agent??I,working_with_agent_name:Je.working_with_agent_name??L,visitor_address:Je.visitor_address??_.visitor_address}}).catch(Ke=>console.error("Guest book lead notify failed:",Ke))},[l==null?void 0:l.id,_,k,T,I,L]);N.useEffect(()=>{if(!a||f!=="done")return;G(i);const Ye=setInterval(()=>{G(Je=>Je<=1?(clearInterval(Ye),X(),0):Je-1)},1e3);return()=>clearInterval(Ye)},[a,f,X]),N.useEffect(()=>{if(!a)return;g(Je=>Je==="welcome"?"info":Je);let Ye=null;return(async()=>{var Je,Ke;try{Ye=await((Ke=(Je=navigator.wakeLock)==null?void 0:Je.request)==null?void 0:Ke.call(Je,"screen"))}catch{}})(),()=>{var Je;try{(Je=Ye==null?void 0:Ye.release)==null||Je.call(Ye)}catch{}}},[a]);const ne=N.useCallback(()=>{var Je;const Ye=document.documentElement;document.fullscreenElement||(Je=Ye.requestFullscreen||Ye.webkitRequestFullscreen)==null||Je.call(Ye).catch(()=>{})},[]),{data:me,isLoading:ue}=xos(l==null?void 0:l.id),ce=!!(l!=null&&l.enable_survey),ae=(l==null?void 0:l.ask_visitor_intent)!==!1,he=(l==null?void 0:l.ask_visitor_address)===!0;N.useEffect(()=>{if(!n||!(l!=null&&l.id)||m.current)return;const Ye=`oh_scan_${l.id}`;if(sessionStorage.getItem(Ye)){m.current=!0;return}m.current=!0,sessionStorage.setItem(Ye,"1"),h.mutate(n)},[n,l==null?void 0:l.id]),N.useEffect(()=>{f==="pending_survey"&&(ue||g(ce&&((me==null?void 0:me.length)??0)>0?"survey":"done"))},[f,ue,ce,me]);const xe=Ye=>{if(!Ye)return"";const[Je,Ke]=Ye.split(":"),st=parseInt(Je),rt=st>=12?"PM":"AM";return`${st>12?st-12:st||12}:${Ke} ${rt}`},ve=async()=>{V("");const Ye=ufs.safeParse(_);if(!Ye.success){V(Ye.error.issues[0].message);return}if(!_.email&&!_.phone){V("Please provide either an email or phone number");return}const Je=(l==null?void 0:l.kind)==="virtual";let Ke=null;if(!y&&(l!=null&&l.id))try{const st=await d.mutateAsync({open_house_id:l.id,first_name:_.first_name.trim(),last_name:_.last_name.trim()||void 0,email:_.email.trim()||void 0,phone:_.phone.trim()||void 0,visitor_address:he&&_.visitor_address.trim()?_.visitor_address.trim():void 0,wants_market_updates:T,has_agent:I,working_with_agent_name:I&&L.trim()?L.trim():void 0,partial_signin:Je?!1:ae});Ke=st.id,x(st.id)}catch{if(Je){V("We could not start the virtual tour. Please try again.");return}}if(Je){ae?g("intent"):(Ke&&te(Ke,{}),g("done"));return}if(!ae){Ke&&te(Ke,{}),ce?!ue&&me&&me.length>0?g("survey"):g("pending_survey"):g("done");return}g("intent")},ge=async Ye=>{A(Ye);try{let Je=y;if(Je?await u.mutateAsync({visitor_id:Je,visitor_intent:Ye,wants_market_updates:T,has_agent:I,working_with_agent_name:I&&L.trim()?L.trim():null,partial_signin:!1}):(Je=(await d.mutateAsync({open_house_id:l.id,first_name:_.first_name.trim(),last_name:_.last_name.trim()||void 0,email:_.email.trim()||void 0,phone:_.phone.trim()||void 0,visitor_address:he&&_.visitor_address.trim()?_.visitor_address.trim():void 0,visitor_intent:Ye,wants_market_updates:T,has_agent:I,working_with_agent_name:I&&L.trim()?L.trim():void 0,partial_signin:!1})).id,x(Je)),Je&&te(Je,{visitor_intent:Ye,wants_market_updates:T,has_agent:I,working_with_agent_name:I&&L.trim()?L.trim():null}),(l==null?void 0:l.kind)==="virtual"){g("done");return}ce?!ue&&me&&me.length>0?g("survey"):g("pending_survey"):g("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(_a,{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 be=l.profiles,Se=(($e=be==null?void 0:be.name)==null?void 0:$e.split(" ").map(Ye=>Ye[0]).join("").slice(0,2))||"?",Ie=l.event_type==="community",Me=l.kind==="virtual",Re=typeof window<"u"&&new URLSearchParams(window.location.search).get("preview")==="1";if(Me&&(Re||f==="done"))return!Re&&!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(ic,{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"})]}),Re&&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(dfs,{openHouse:l,visitorId:Re?"preview":y,visitorName:Re?"Preview Visitor":`${_.first_name} ${_.last_name}`.trim(),visitorEmail:Re?"":_.email,visitorPhone:Re?"":_.phone,previewMode:Re})]});const Ne=`${Me?"Virtual Open House":Ie?"Community Event":"Open House"} — ${l.property_address}`,Ce=[[l.city,l.state].filter(Boolean).join(", "),l.event_date?Js(new Date(l.event_date+"T00:00:00"),"EEE, MMM d"):null,be!=null&&be.name?`Hosted by ${be.name}`:null].filter(Boolean).join(" · "),Fe=l.photo_url||"",Ae=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",Xe=typeof window<"u"?window.location.href:`https://guestbook.relevelup.com/${n}`;return e.jsxs(e.Fragment,{children:[e.jsxs(ic,{children:[e.jsx("title",{children:Ne}),e.jsx("meta",{name:"description",content:Ce||`Sign in to ${l.property_address}`}),e.jsx("meta",{property:"og:type",content:"website"}),e.jsx("meta",{property:"og:title",content:Ne}),e.jsx("meta",{property:"og:description",content:Ce||`Sign in to ${l.property_address}`}),e.jsx("meta",{property:"og:image",content:Ae}),e.jsx("meta",{property:"og:image:width",content:"1200"}),e.jsx("meta",{property:"og:image:height",content:"630"}),e.jsx("meta",{property:"og:url",content:Xe}),e.jsx("meta",{property:"og:site_name",content:"ReLevel Up"}),e.jsx("meta",{name:"twitter:card",content:"summary_large_image"}),e.jsx("meta",{name:"twitter:title",content:Ne}),e.jsx("meta",{name:"twitter:description",content:Ce||`Sign in to ${l.property_address}`}),e.jsx("meta",{name:"twitter:image",content:Ae}),e.jsx("meta",{name:"robots",content:"noindex, nofollow"})]}),e.jsx("div",{className:"min-h-screen bg-gradient-to-br from-slate-900 via-slate-800 to-slate-900 flex items-center justify-center p-4",children:e.jsxs("div",{className:"w-full max-w-md",children:[e.jsxs("div",{className:"text-center mb-6",children:[e.jsxs(Ua,{className:"h-16 w-16 mx-auto mb-3 ring-2 ring-white/20",children:[e.jsx(Gi,{src:(be==null?void 0:be.avatar_url)||"",alt:(be==null?void 0:be.name)||""}),e.jsx(qa,{className:"bg-white/10 text-white text-lg",children:Se})]}),e.jsx("p",{className:"text-white/60 text-sm",children:be==null?void 0:be.name}),(be==null?void 0:be.title)&&e.jsx("p",{className:"text-white/40 text-xs",children:be.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(ii,{className:"h-3 w-3"}),l.city,l.state?`, ${l.state}`:""," ",l.zip]}),!Me&&e.jsxs(e.Fragment,{children:[e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(ta,{className:"h-3 w-3"}),Js(new Date(l.event_date+"T00:00:00"),"MMM d, yyyy")]}),l.start_time&&e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Xr,{className:"h-3 w-3"}),xe(l.start_time),l.end_time?` – ${xe(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:Ie?e.jsx(Ti,{className:"h-5 w-5 text-white"}):e.jsx(_a,{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(ii,{className:"h-3 w-3"}),l.city,l.state?`, ${l.state}`:""," ",l.zip]}),!Me&&e.jsxs(e.Fragment,{children:[e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(ta,{className:"h-3 w-3"}),Js(new Date(l.event_date+"T00:00:00"),"MMM d, yyyy")]}),l.start_time&&e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Xr,{className:"h-3 w-3"}),xe(l.start_time),l.end_time?` – ${xe(l.end_time)}`:""]})]})]})]})]})}),e.jsxs("div",{className:"p-6",children:[f==="welcome"&&e.jsxs("div",{className:"text-center space-y-6",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"text-xl font-bold text-slate-900 mb-2",children:"Welcome!"}),e.jsx("p",{className:"text-slate-500 text-sm",children:l.agent_greeting||"Please sign in below."})]}),e.jsxs(B,{onClick:()=>g("info"),className:"w-full h-14 text-base bg-slate-900 hover:bg-slate-800 text-white rounded-xl",children:["Sign In ",e.jsx(vi,{className:"h-5 w-5 ml-2"})]}),e.jsx("p",{className:"text-xs text-slate-400",children:"Quick & easy — takes 30 seconds"})]}),f==="info"&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[e.jsx("button",{onClick:()=>g("welcome"),className:"text-slate-400 hover:text-slate-600",children:e.jsx(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(re,{className:"text-slate-600 text-xs",children:"First Name *"}),e.jsx(we,{value:_.first_name,onChange:Ye=>b(Je=>({...Je,first_name:Ye.target.value})),placeholder:"First",className:"mt-1 h-12 rounded-xl border-slate-200 text-base",autoFocus:!0})]}),e.jsxs("div",{children:[e.jsx(re,{className:"text-slate-600 text-xs",children:"Last Name"}),e.jsx(we,{value:_.last_name,onChange:Ye=>b(Je=>({...Je,last_name:Ye.target.value})),placeholder:"Last",className:"mt-1 h-12 rounded-xl border-slate-200 text-base"})]})]}),e.jsxs("div",{children:[e.jsx(re,{className:"text-slate-600 text-xs",children:"Email"}),e.jsx(we,{type:"email",value:_.email,onChange:Ye=>b(Je=>({...Je,email:Ye.target.value})),placeholder:"your@email.com",className:"mt-1 h-12 rounded-xl border-slate-200 text-base"})]}),e.jsxs("div",{children:[e.jsx(re,{className:"text-slate-600 text-xs",children:"Phone"}),e.jsx(we,{type:"tel",value:_.phone,onChange:Ye=>b(Je=>({...Je,phone:Ye.target.value})),placeholder:"(555) 123-4567",className:"mt-1 h-12 rounded-xl border-slate-200 text-base"})]}),he&&e.jsxs("div",{children:[e.jsx(re,{className:"text-slate-600 text-xs",children:"Your Home Address"}),e.jsx(we,{value:_.visitor_address,onChange:Ye=>b(Je=>({...Je,visitor_address:Ye.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:T,onChange:Ye=>P(Ye.target.checked),className:"rounded border-slate-300 text-slate-900 focus:ring-slate-500"}),e.jsx("span",{className:"text-sm text-slate-600",children:"Send me market updates for this area"})]}),e.jsxs("div",{className:"space-y-2 pt-1",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"text-sm text-slate-600",children:"Already working with an agent?"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-xs font-medium text-slate-400",children:I?"Yes":"No"}),e.jsx(zn,{checked:I,onCheckedChange:M})]})]}),I&&e.jsx(we,{value:L,onChange:Ye=>z(Ye.target.value),placeholder:"Agent's name",className:"mt-1 h-10 rounded-xl border-slate-200 text-sm"})]}),$&&e.jsx("p",{className:"text-destructive text-sm",children:$}),e.jsxs(B,{onClick:ve,className:"w-full h-14 text-base bg-slate-900 hover:bg-slate-800 text-white rounded-xl",children:["Continue ",e.jsx(vi,{className:"h-5 w-5 ml-2"})]})]}),f==="intent"&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[e.jsx("button",{onClick:()=>g("info"),className:"text-slate-400 hover:text-slate-600",children:e.jsx(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:hfs.map(Ye=>e.jsxs("button",{onClick:()=>ge(Ye.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:Ye.emoji}),e.jsx("span",{className:"text-sm font-medium text-slate-700 group-hover:text-slate-900",children:Ye.label})]},Ye.value))}),$&&e.jsx("p",{className:"text-destructive text-sm text-center",children:$})]}),f==="pending_survey"&&e.jsxs("div",{className:"flex flex-col items-center justify-center py-8 gap-3",children:[e.jsx("div",{className:"w-8 h-8 border-[3px] border-slate-200 border-t-slate-900 rounded-full animate-spin"}),e.jsx("p",{className:"text-sm text-slate-500",children:"Loading survey..."})]}),f==="survey"&&y&&me&&e.jsx(Jps,{questions:me,visitorId:y,onComplete:()=>g("done"),onSkip:()=>g("done")}),f==="done"&&e.jsxs("div",{className:"text-center space-y-4 py-4",children:[e.jsx("div",{className:"w-16 h-16 rounded-full bg-green-100 flex items-center justify-center mx-auto",children:e.jsx(Hr,{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, ",_.first_name,". ",Ie?"Enjoy the event!":"Enjoy the open house!"]})]}),(l==null?void 0:l.disclosure_pdf_url)&&e.jsxs("a",{href:`https://docs.google.com/gview?url=${encodeURIComponent(l.disclosure_pdf_url)}&embedded=true`,target:"_blank",rel:"noopener noreferrer",className:"inline-flex items-center gap-2 px-5 py-3 rounded-xl bg-slate-100 hover:bg-slate-200 text-slate-800 font-medium text-sm transition-colors",children:[e.jsx(Wr,{className:"h-4 w-4"}),"View Seller's Disclosures"]}),(be==null?void 0:be.name)&&e.jsxs("p",{className:"text-sm text-slate-400",children:["Your host today: ",e.jsx("strong",{className:"text-slate-600",children:be.name})]}),a&&e.jsxs("div",{className:"pt-4 space-y-3",children:[e.jsx(B,{onClick:X,className:"w-full h-14 text-base font-semibold rounded-xl",children:"Sign in next visitor"}),e.jsxs("p",{className:"text-xs text-slate-400",children:["Ready for the next visitor in ",W,"s…"]})]})]})]})]}),e.jsx("p",{className:"text-center text-white/30 text-xs mt-6",children:"Powered by LevelUp Guest Book"}),a&&e.jsxs("div",{className:"fixed top-3 right-3 flex items-center gap-2 z-50",children:[e.jsxs("span",{className:"inline-flex items-center gap-1.5 rounded-full bg-white/10 backdrop-blur-sm text-white/80 text-[11px] px-2.5 py-1 border border-white/10",children:[e.jsx(M9,{className:"h-3 w-3"})," Tablet Mode"]}),e.jsx("button",{onClick:ne,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(rW,{className:"h-3 w-3"})})]})]})})]})}function OOn(s){const{user:t}=Ls();return mt({queryKey:["cohost-tokens",s],queryFn:async()=>{const{data:n,error:r}=await H.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 FOn(){const s=as(),{user:t}=Ls();return _t({mutationFn:async({openHouseId:n,label:r})=>{const{data:a,error:i}=await H.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 zOn(){const s=as();return _t({mutationFn:async({id:t,openHouseId:n})=>{const{error:r}=await H.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 mfs(s){return mt({queryKey:["cohost-validate",s],queryFn:async()=>{const{data:t,error:n}=await H.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)t[n][r]??n,s)}var mUe="ScrollArea",[skt,BOn]=Um(mUe),[ffs,Tj]=skt(mUe),nkt=N.forwardRef((s,t)=>{const{__scopeScrollArea:n,type:r="hover",dir:a,scrollHideDelay:i=600,...l}=s,[o,c]=N.useState(null),[d,u]=N.useState(null),[h,m]=N.useState(null),[f,g]=N.useState(null),[y,x]=N.useState(null),[_,b]=N.useState(0),[k,A]=N.useState(0),[T,P]=N.useState(!1),[I,M]=N.useState(!1),L=jo(t,$=>c($)),z=F3(a);return e.jsx(ffs,{scope:n,type:r,dir:z,scrollHideDelay:i,scrollArea:o,viewport:d,onViewportChange:u,content:h,onContentChange:m,scrollbarX:f,onScrollbarXChange:g,scrollbarXEnabled:T,onScrollbarXEnabledChange:P,scrollbarY:y,onScrollbarYChange:x,scrollbarYEnabled:I,onScrollbarYEnabledChange:M,onCornerWidthChange:b,onCornerHeightChange:A,children:e.jsx(Da.div,{dir:z,...l,ref:L,style:{position:"relative","--radix-scroll-area-corner-width":_+"px","--radix-scroll-area-corner-height":k+"px",...s.style}})})});nkt.displayName=mUe;var rkt="ScrollAreaViewport",akt=N.forwardRef((s,t)=>{const{__scopeScrollArea:n,children:r,nonce:a,...i}=s,l=Tj(rkt,n),o=N.useRef(null),c=jo(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(Da.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})})]})});akt.displayName=rkt;var G5="ScrollAreaScrollbar",pUe=N.forwardRef((s,t)=>{const{forceMount:n,...r}=s,a=Tj(G5,s.__scopeScrollArea),{onScrollbarXEnabledChange:i,onScrollbarYEnabledChange:l}=a,o=s.orientation==="horizontal";return N.useEffect(()=>(o?i(!0):l(!0),()=>{o?i(!1):l(!1)}),[o,i,l]),a.type==="hover"?e.jsx(gfs,{...r,ref:t,forceMount:n}):a.type==="scroll"?e.jsx(xfs,{...r,ref:t,forceMount:n}):a.type==="auto"?e.jsx(ikt,{...r,ref:t,forceMount:n}):a.type==="always"?e.jsx(fUe,{...r,ref:t}):null});pUe.displayName=G5;var gfs=N.forwardRef((s,t)=>{const{forceMount:n,...r}=s,a=Tj(G5,s.__scopeScrollArea),[i,l]=N.useState(!1);return N.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(Xf,{present:n||i,children:e.jsx(ikt,{"data-state":i?"visible":"hidden",...r,ref:t})})}),xfs=N.forwardRef((s,t)=>{const{forceMount:n,...r}=s,a=Tj(G5,s.__scopeScrollArea),i=s.orientation==="horizontal",l=D4e(()=>c("SCROLL_END"),100),[o,c]=pfs("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 N.useEffect(()=>{if(o==="idle"){const d=window.setTimeout(()=>c("HIDE"),a.scrollHideDelay);return()=>window.clearTimeout(d)}},[o,a.scrollHideDelay,c]),N.useEffect(()=>{const d=a.viewport,u=i?"scrollLeft":"scrollTop";if(d){let h=d[u];const m=()=>{const f=d[u];h!==f&&(c("SCROLL"),l()),h=f};return d.addEventListener("scroll",m),()=>d.removeEventListener("scroll",m)}},[a.viewport,i,c,l]),e.jsx(Xf,{present:n||o!=="hidden",children:e.jsx(fUe,{"data-state":o==="hidden"?"hidden":"visible",...r,ref:t,onPointerEnter:la(s.onPointerEnter,()=>c("POINTER_ENTER")),onPointerLeave:la(s.onPointerLeave,()=>c("POINTER_LEAVE"))})})}),ikt=N.forwardRef((s,t)=>{const n=Tj(G5,s.__scopeScrollArea),{forceMount:r,...a}=s,[i,l]=N.useState(!1),o=s.orientation==="horizontal",c=D4e(()=>{if(n.viewport){const d=n.viewport.offsetWidth{const{orientation:n="vertical",...r}=s,a=Tj(G5,s.__scopeScrollArea),i=N.useRef(null),l=N.useRef(0),[o,c]=N.useState({content:0,viewport:0,scrollbar:{size:0,paddingStart:0,paddingEnd:0}}),d=ukt(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,f){return jfs(m,l.current,o,f)}return n==="horizontal"?e.jsx(yfs,{...u,ref:t,onThumbPositionChange:()=>{if(a.viewport&&i.current){const m=a.viewport.scrollLeft,f=vst(m,o,a.dir);i.current.style.transform=`translate3d(${f}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(vfs,{...u,ref:t,onThumbPositionChange:()=>{if(a.viewport&&i.current){const m=a.viewport.scrollTop,f=vst(m,o);i.current.style.transform=`translate3d(0, ${f}px, 0)`}},onWheelScroll:m=>{a.viewport&&(a.viewport.scrollTop=m)},onDragScroll:m=>{a.viewport&&(a.viewport.scrollTop=h(m))}}):null}),yfs=N.forwardRef((s,t)=>{const{sizes:n,onSizesChange:r,...a}=s,i=Tj(G5,s.__scopeScrollArea),[l,o]=N.useState(),c=N.useRef(null),d=jo(t,c,i.onScrollbarXChange);return N.useEffect(()=>{c.current&&o(getComputedStyle(c.current))},[c]),e.jsx(lkt,{"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":I4e(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),mkt(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:Y2e(l.paddingLeft),paddingEnd:Y2e(l.paddingRight)}})}})}),vfs=N.forwardRef((s,t)=>{const{sizes:n,onSizesChange:r,...a}=s,i=Tj(G5,s.__scopeScrollArea),[l,o]=N.useState(),c=N.useRef(null),d=jo(t,c,i.onScrollbarYChange);return N.useEffect(()=>{c.current&&o(getComputedStyle(c.current))},[c]),e.jsx(lkt,{"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":I4e(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),mkt(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:Y2e(l.paddingTop),paddingEnd:Y2e(l.paddingBottom)}})}})}),[bfs,okt]=skt(G5),lkt=N.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,f=Tj(G5,n),[g,y]=N.useState(null),x=jo(t,L=>y(L)),_=N.useRef(null),b=N.useRef(""),k=f.viewport,A=r.content-r.viewport,T=cf(u),P=cf(c),I=D4e(h,10);function M(L){if(_.current){const z=L.clientX-_.current.left,$=L.clientY-_.current.top;d({x:z,y:$})}}return N.useEffect(()=>{const L=z=>{const $=z.target;(g==null?void 0:g.contains($))&&T(z,A)};return document.addEventListener("wheel",L,{passive:!1}),()=>document.removeEventListener("wheel",L,{passive:!1})},[k,g,A,T]),N.useEffect(P,[r,P]),BB(g,I),BB(f.content,I),e.jsx(bfs,{scope:n,scrollbar:g,hasThumb:a,onThumbChange:cf(i),onThumbPointerUp:cf(l),onThumbPositionChange:P,onThumbPointerDown:cf(o),children:e.jsx(Da.div,{...m,ref:x,style:{position:"absolute",...m.style},onPointerDown:la(s.onPointerDown,L=>{L.button===0&&(L.target.setPointerCapture(L.pointerId),_.current=g.getBoundingClientRect(),b.current=document.body.style.webkitUserSelect,document.body.style.webkitUserSelect="none",f.viewport&&(f.viewport.style.scrollBehavior="auto"),M(L))}),onPointerMove:la(s.onPointerMove,M),onPointerUp:la(s.onPointerUp,L=>{const z=L.target;z.hasPointerCapture(L.pointerId)&&z.releasePointerCapture(L.pointerId),document.body.style.webkitUserSelect=b.current,f.viewport&&(f.viewport.style.scrollBehavior=""),_.current=null})})})}),K2e="ScrollAreaThumb",ckt=N.forwardRef((s,t)=>{const{forceMount:n,...r}=s,a=okt(K2e,s.__scopeScrollArea);return e.jsx(Xf,{present:n||a.hasThumb,children:e.jsx(_fs,{ref:t,...r})})}),_fs=N.forwardRef((s,t)=>{const{__scopeScrollArea:n,style:r,...a}=s,i=Tj(K2e,n),l=okt(K2e,n),{onThumbPositionChange:o}=l,c=jo(t,h=>l.onThumbChange(h)),d=N.useRef(void 0),u=D4e(()=>{d.current&&(d.current(),d.current=void 0)},100);return N.useEffect(()=>{const h=i.viewport;if(h){const m=()=>{if(u(),!d.current){const f=Nfs(h,o);d.current=f,o()}};return o(),h.addEventListener("scroll",m),()=>h.removeEventListener("scroll",m)}},[i.viewport,u,o]),e.jsx(Da.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:la(s.onPointerDownCapture,h=>{const f=h.target.getBoundingClientRect(),g=h.clientX-f.left,y=h.clientY-f.top;l.onThumbPointerDown({x:g,y})}),onPointerUp:la(s.onPointerUp,l.onThumbPointerUp)})});ckt.displayName=K2e;var gUe="ScrollAreaCorner",dkt=N.forwardRef((s,t)=>{const n=Tj(gUe,s.__scopeScrollArea),r=!!(n.scrollbarX&&n.scrollbarY);return n.type!=="scroll"&&r?e.jsx(wfs,{...s,ref:t}):null});dkt.displayName=gUe;var wfs=N.forwardRef((s,t)=>{const{__scopeScrollArea:n,...r}=s,a=Tj(gUe,n),[i,l]=N.useState(0),[o,c]=N.useState(0),d=!!(i&&o);return BB(a.scrollbarX,()=>{var h;const u=((h=a.scrollbarX)==null?void 0:h.offsetHeight)||0;a.onCornerHeightChange(u),c(u)}),BB(a.scrollbarY,()=>{var h;const u=((h=a.scrollbarY)==null?void 0:h.offsetWidth)||0;a.onCornerWidthChange(u),l(u)}),d?e.jsx(Da.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 Y2e(s){return s?parseInt(s,10):0}function ukt(s,t){const n=s/t;return isNaN(n)?0:n}function I4e(s){const t=ukt(s.viewport,s.content),n=s.scrollbar.paddingStart+s.scrollbar.paddingEnd,r=(s.scrollbar.size-n)*t;return Math.max(r,18)}function jfs(s,t,n,r="ltr"){const a=I4e(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 hkt([c,d],h)(s)}function vst(s,t,n="ltr"){const r=I4e(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=uY(s,c);return hkt([0,l],[0,o])(d)}function hkt(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 mkt(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 D4e(s,t){const n=cf(s),r=N.useRef(0);return N.useEffect(()=>()=>window.clearTimeout(r.current),[]),N.useCallback(()=>{window.clearTimeout(r.current),r.current=window.setTimeout(n,t)},[n,t])}function BB(s,t){const n=cf(t);gf(()=>{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 pkt=nkt,kfs=akt,Sfs=dkt;const lo=N.forwardRef(({className:s,children:t,...n},r)=>e.jsxs(pkt,{ref:r,className:Ot("relative overflow-hidden",s),...n,children:[e.jsx(kfs,{className:"h-full w-full rounded-[inherit]",children:t}),e.jsx(DQ,{}),e.jsx(Sfs,{})]}));lo.displayName=pkt.displayName;const DQ=N.forwardRef(({className:s,orientation:t="vertical",...n},r)=>e.jsx(pUe,{ref:r,orientation:t,className:Ot("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(ckt,{className:"relative flex-1 rounded-full bg-border"})}));DQ.displayName=pUe.displayName;const xUe=N.createContext({});function yUe(s){const t=N.useRef(null);return t.current===null&&(t.current=s()),t.current}const Cfs=typeof window<"u",fkt=Cfs?N.useLayoutEffect:N.useEffect,R4e=N.createContext(null);function vUe(s,t){s.indexOf(t)===-1&&s.push(t)}function Z2e(s,t){const n=s.indexOf(t);n>-1&&s.splice(n,1)}const T5=(s,t,n)=>n>t?t:n{},$B=()=>{};const uE={},gkt=s=>/^-?(?:\d+(?:\.\d+)?|\.\d+)$/u.test(s);function xkt(s){return typeof s=="object"&&s!==null}const ykt=s=>/^0[^.\s]+$/u.test(s);function vkt(s){let t;return()=>(t===void 0&&(t=s()),t)}const fj=s=>s,Afs=(s,t)=>n=>t(s(n)),RQ=(...s)=>s.reduce(Afs),pY=(s,t,n)=>{const r=t-s;return r===0?1:(n-s)/r};class bUe{constructor(){this.subscriptions=[]}add(t){return vUe(this.subscriptions,t),()=>Z2e(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,rj=s=>s/1e3;function bkt(s,t){return t?s*(1e3/t):0}const _kt=(s,t,n)=>(((1-3*n+3*t)*s+(3*n-6*t))*s+3*t)*s,Tfs=1e-7,Efs=12;function Mfs(s,t,n,r,a){let i,l,o=0;do l=t+(n-t)/2,i=_kt(l,r,a)-s,i>0?n=l:t=l;while(Math.abs(i)>Tfs&&++oMfs(i,0,1,s,n);return i=>i===0||i===1?i:_kt(a(i),t,r)}const wkt=s=>t=>t<=.5?s(2*t)/2:(2-s(2*(1-t)))/2,jkt=s=>t=>1-s(1-t),Nkt=OQ(.33,1.53,.69,.99),_Ue=jkt(Nkt),kkt=wkt(_Ue),Skt=s=>s>=1?1:(s*=2)<1?.5*_Ue(s):.5*(2-Math.pow(2,-10*(s-1))),wUe=s=>1-Math.sin(Math.acos(s)),Ckt=jkt(wUe),Akt=wkt(wUe),Lfs=OQ(.42,0,1,1),Pfs=OQ(0,0,.58,1),Tkt=OQ(.42,0,.58,1),Ifs=s=>Array.isArray(s)&&typeof s[0]!="number",Ekt=s=>Array.isArray(s)&&typeof s[0]=="number",bst={linear:fj,easeIn:Lfs,easeInOut:Tkt,easeOut:Pfs,circIn:wUe,circInOut:Akt,circOut:Ckt,backIn:_Ue,backInOut:kkt,backOut:Nkt,anticipate:Skt},Dfs=s=>typeof s=="string",_st=s=>{if(Ekt(s)){$B(s.length===4,"Cubic bezier arrays must contain four numerical values.","cubic-bezier-length");const[t,n,r,a]=s;return OQ(t,n,r,a)}else if(Dfs(s))return $B(bst[s]!==void 0,`Invalid easing type '${s}'`,"invalid-easing-type"),bst[s];return s},Vte=["setup","read","resolveKeyframes","preUpdate","update","preRender","render","postRender"],wst={value:null,addProjectionMetrics:null};function Rfs(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,f=!1)=>{const y=f&&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&&wst.value&&wst.value.frameloop[t].push(c),c=0,n.clear(),a=!1,i&&(i=!1,u.process(h))}};return u}const Ofs=40;function Mkt(s,t){let n=!1,r=!0;const a={delta:0,timestamp:0,isProcessing:!1},i=()=>n=!0,l=Vte.reduce((k,A)=>(k[A]=Rfs(i,t?A:void 0),k),{}),{setup:o,read:c,resolveKeyframes:d,preUpdate:u,update:h,preRender:m,render:f,postRender:g}=l,y=()=>{const k=uE.useManualTiming,A=k?a.timestamp:performance.now();n=!1,k||(a.delta=r?1e3/60:Math.max(Math.min(A-a.timestamp,Ofs),1)),a.timestamp=A,a.isProcessing=!0,o.process(a),c.process(a),d.process(a),u.process(a),h.process(a),m.process(a),f.process(a),g.process(a),a.isProcessing=!1,n&&t&&(r=!1,s(y))},x=()=>{n=!0,r=!0,a.isProcessing||s(y)};return{schedule:Vte.reduce((k,A)=>{const T=l[A];return k[A]=(P,I=!1,M=!1)=>(n||x(),T.schedule(P,I,M)),k},{}),cancel:k=>{for(let A=0;A(Twe===void 0&&Dv.set(E0.isProcessing||uE.useManualTiming?E0.timestamp:performance.now()),Twe),set:s=>{Twe=s,queueMicrotask(Ffs)}},Lkt=s=>t=>typeof t=="string"&&t.startsWith(s),Pkt=Lkt("--"),zfs=Lkt("var(--"),jUe=s=>zfs(s)?Bfs.test(s.split("/*")[0].trim()):!1,Bfs=/var\(--(?:[\w-]+\s*|[\w-]+\s*,(?:\s*[^)(\s]|\s*\((?:[^)(]|\([^)(]*\))*\))+\s*)\)$/iu;function jst(s){return typeof s!="string"?!1:s.split("/*")[0].includes("var(--")}const dU={test:s=>typeof s=="number",parse:parseFloat,transform:s=>s},fY={...dU,transform:s=>T5(0,1,s)},Hte={...dU,default:1},qW=s=>Math.round(s*1e5)/1e5,NUe=/-?(?:\d+(?:\.\d+)?|\.\d+)/gu;function $fs(s){return s==null}const Ufs=/^(?:#[\da-f]{3,8}|(?:rgb|hsl)a?\((?:-?[\d.]+%?[,\s]+){2}-?[\d.]+%?\s*(?:[,/]\s*)?(?:\b\d+(?:\.\d+)?|\.\d+)?%?\))$/iu,kUe=(s,t)=>n=>!!(typeof n=="string"&&Ufs.test(n)&&n.startsWith(s)||t&&!$fs(n)&&Object.prototype.hasOwnProperty.call(n,t)),Ikt=(s,t,n)=>r=>{if(typeof r!="string")return r;const[a,i,l,o]=r.match(NUe);return{[s]:parseFloat(a),[t]:parseFloat(i),[n]:parseFloat(l),alpha:o!==void 0?parseFloat(o):1}},qfs=s=>T5(0,255,s),R6e={...dU,transform:s=>Math.round(qfs(s))},EI={test:kUe("rgb","red"),parse:Ikt("red","green","blue"),transform:({red:s,green:t,blue:n,alpha:r=1})=>"rgba("+R6e.transform(s)+", "+R6e.transform(t)+", "+R6e.transform(n)+", "+qW(fY.transform(r))+")"};function Vfs(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 YDe={test:kUe("#"),parse:Vfs,transform:EI.transform},FQ=s=>({test:t=>typeof t=="string"&&t.endsWith(s)&&t.split(" ").length===1,parse:parseFloat,transform:t=>`${t}${s}`}),RC=FQ("deg"),y5=FQ("%"),Qi=FQ("px"),Hfs=FQ("vh"),Gfs=FQ("vw"),Nst={...y5,parse:s=>y5.parse(s)/100,transform:s=>y5.transform(s*100)},L7={test:kUe("hsl","hue"),parse:Ikt("hue","saturation","lightness"),transform:({hue:s,saturation:t,lightness:n,alpha:r=1})=>"hsla("+Math.round(s)+", "+y5.transform(qW(t))+", "+y5.transform(qW(n))+", "+qW(fY.transform(r))+")"},cg={test:s=>EI.test(s)||YDe.test(s)||L7.test(s),parse:s=>EI.test(s)?EI.parse(s):L7.test(s)?L7.parse(s):YDe.parse(s),transform:s=>typeof s=="string"?s:s.hasOwnProperty("red")?EI.transform(s):L7.transform(s),getAnimatableNone:s=>{const t=cg.parse(s);return t.alpha=0,cg.transform(t)}},Wfs=/(?:#[\da-f]{3,8}|(?:rgb|hsl)a?\((?:-?[\d.]+%?[,\s]+){2}-?[\d.]+%?\s*(?:[,/]\s*)?(?:\b\d+(?:\.\d+)?|\.\d+)?%?\))/giu;function Kfs(s){var t,n;return isNaN(s)&&typeof s=="string"&&(((t=s.match(NUe))==null?void 0:t.length)||0)+(((n=s.match(Wfs))==null?void 0:n.length)||0)>0}const Dkt="number",Rkt="color",Yfs="var",Zfs="var(",kst="${}",Xfs=/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 UB(s){const t=s.toString(),n=[],r={color:[],number:[],var:[]},a=[];let i=0;const o=t.replace(Xfs,c=>(cg.test(c)?(r.color.push(i),a.push(Rkt),n.push(cg.parse(c))):c.startsWith(Zfs)?(r.var.push(i),a.push(Yfs),n.push(c)):(r.number.push(i),a.push(Dkt),n.push(parseFloat(c))),++i,kst)).split(kst);return{values:n,split:o,indexes:r,types:a}}function Qfs(s){return UB(s).values}function Okt({split:s,types:t}){const n=s.length;return r=>{let a="";for(let i=0;itypeof s=="number"?0:cg.test(s)?cg.getAnimatableNone(s):s,tgs=(s,t)=>typeof s=="number"?t!=null&&t.trim().endsWith("/")?s:0:egs(s);function sgs(s){const t=UB(s);return Okt(t)(t.values.map((r,a)=>tgs(r,t.split[a])))}const aN={test:Kfs,parse:Qfs,createTransformer:Jfs,getAnimatableNone:sgs};function O6e(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 ngs({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=O6e(c,o,s+1/3),i=O6e(c,o,s),l=O6e(c,o,s-1/3)}return{red:Math.round(a*255),green:Math.round(i*255),blue:Math.round(l*255),alpha:r}}function X2e(s,t){return n=>n>0?t:s}const im=(s,t,n)=>s+(t-s)*n,F6e=(s,t,n)=>{const r=s*s,a=n*(t*t-r)+r;return a<0?0:Math.sqrt(a)},rgs=[YDe,EI,L7],ags=s=>rgs.find(t=>t.test(s));function Sst(s){const t=ags(s);if(O4e(!!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===L7&&(n=ngs(n)),n}const Cst=(s,t)=>{const n=Sst(s),r=Sst(t);if(!n||!r)return X2e(s,t);const a={...n};return i=>(a.red=F6e(n.red,r.red,i),a.green=F6e(n.green,r.green,i),a.blue=F6e(n.blue,r.blue,i),a.alpha=im(n.alpha,r.alpha,i),EI.transform(a))},ZDe=new Set(["none","hidden"]);function igs(s,t){return ZDe.has(s)?n=>n<=0?s:t:n=>n>=1?t:s}function ogs(s,t){return n=>im(s,t,n)}function SUe(s){return typeof s=="number"?ogs:typeof s=="string"?jUe(s)?X2e:cg.test(s)?Cst:dgs:Array.isArray(s)?Fkt:typeof s=="object"?cg.test(s)?Cst:lgs:X2e}function Fkt(s,t){const n=[...s],r=n.length,a=s.map((i,l)=>SUe(i)(i,t[l]));return i=>{for(let l=0;l{for(const i in r)n[i]=r[i](a);return n}}function cgs(s,t){const n=[],r={color:0,var:0,number:0};for(let a=0;a{const n=aN.createTransformer(t),r=UB(s),a=UB(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?ZDe.has(s)&&!a.values.length||ZDe.has(t)&&!r.values.length?igs(s,t):RQ(Fkt(cgs(r,a),a.values),n):(O4e(!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"),X2e(s,t))};function zkt(s,t,n){return typeof s=="number"&&typeof t=="number"&&typeof n=="number"?im(s,t,n):SUe(s)(s,t)}const ugs=s=>{const t=({timestamp:n})=>s(n);return{start:(n=!0)=>yh.update(t,n),stop:()=>hE(t),now:()=>E0.isProcessing?E0.timestamp:Dv.now()}},Bkt=(s,t,n=10)=>{let r="";const a=Math.max(Math.round(t/n),2);for(let i=0;i=Q2e?1/0:t}function hgs(s,t=100,n){const r=n({...s,keyframes:[0,t]}),a=Math.min(CUe(r),Q2e);return{type:"keyframes",ease:i=>r.next(a*i).value/t,duration:rj(a)}}const yp={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 XDe(s,t){return s*Math.sqrt(1-t*t)}const mgs=12;function pgs(s,t,n){let r=n;for(let a=1;a{const u=d*l,h=u*s,m=u-n,f=XDe(d,l),g=Math.exp(-h);return z6e-m/f*g},i=d=>{const h=d*l*s,m=h*n+n,f=Math.pow(l,2)*Math.pow(d,2)*s,g=Math.exp(-h),y=XDe(Math.pow(d,2),l);return(-a(d)+z6e>0?-1:1)*((m-f)*g)/y}):(a=d=>{const u=Math.exp(-d*s),h=(d-n)*s+1;return-z6e+u*h},i=d=>{const u=Math.exp(-d*s),h=(n-d)*(s*s);return u*h});const o=5/s,c=pgs(a,i,o);if(s=ib(s),isNaN(c))return{stiffness:yp.stiffness,damping:yp.damping,duration:s};{const d=Math.pow(c,2)*r;return{stiffness:d,damping:l*2*Math.sqrt(r*d),duration:s}}}const ggs=["duration","bounce"],xgs=["stiffness","damping","mass"];function Ast(s,t){return t.some(n=>s[n]!==void 0)}function ygs(s){let t={velocity:yp.velocity,stiffness:yp.stiffness,damping:yp.damping,mass:yp.mass,isResolvedFromDuration:!1,...s};if(!Ast(s,xgs)&&Ast(s,ggs))if(t.velocity=0,s.visualDuration){const n=s.visualDuration,r=2*Math.PI/(n*1.2),a=r*r,i=2*T5(.05,1,1-(s.bounce||0))*Math.sqrt(a);t={...t,mass:yp.mass,stiffness:a,damping:i}}else{const n=fgs({...s,velocity:0});t={...t,...n,mass:yp.mass},t.isResolvedFromDuration=!0}return t}function J2e(s=yp.visualDuration,t=yp.bounce){const n=typeof s!="object"?{visualDuration:s,keyframes:[0,1],bounce:t}:s;let{restSpeed:r,restDelta:a}=n;const i=n.keyframes[0],l=n.keyframes[n.keyframes.length-1],o={done:!1,value:i},{stiffness:c,damping:d,mass:u,duration:h,velocity:m,isResolvedFromDuration:f}=ygs({...n,velocity:-rj(n.velocity||0)}),g=m||0,y=d/(2*Math.sqrt(c*u)),x=l-i,_=rj(Math.sqrt(c/u)),b=Math.abs(x)<5;r||(r=b?yp.restSpeed.granular:yp.restSpeed.default),a||(a=b?yp.restDelta.granular:yp.restDelta.default);let k,A,T,P,I,M;if(y<1)T=XDe(_,y),P=(g+y*_*x)/T,k=z=>{const $=Math.exp(-y*_*z);return l-$*(P*Math.sin(T*z)+x*Math.cos(T*z))},I=y*_*P+x*T,M=y*_*x-P*T,A=z=>Math.exp(-y*_*z)*(I*Math.sin(T*z)+M*Math.cos(T*z));else if(y===1){k=$=>l-Math.exp(-_*$)*(x+(g+_*x)*$);const z=g+_*x;A=$=>Math.exp(-_*$)*(_*z*$-g)}else{const z=_*Math.sqrt(y*y-1);k=G=>{const X=Math.exp(-y*_*G),te=Math.min(z*G,300);return l-X*((g+y*_*x)*Math.sinh(te)+z*x*Math.cosh(te))/z};const $=(g+y*_*x)/z,V=y*_*$-x*z,W=y*_*x-$*z;A=G=>{const X=Math.exp(-y*_*G),te=Math.min(z*G,300);return X*(V*Math.sinh(te)+W*Math.cosh(te))}}const L={calculatedDuration:f&&h||null,velocity:z=>ib(A(z)),next:z=>{if(!f&&y<1){const V=Math.exp(-y*_*z),W=Math.sin(T*z),G=Math.cos(T*z),X=l-V*(P*W+x*G),te=ib(V*(I*W+M*G));return o.done=Math.abs(te)<=r&&Math.abs(l-X)<=a,o.value=o.done?l:X,o}const $=k(z);if(f)o.done=z>=h;else{const V=ib(A(z));o.done=Math.abs(V)<=r&&Math.abs(l-$)<=a}return o.value=o.done?l:$,o},toString:()=>{const z=Math.min(CUe(L),Q2e),$=Bkt(V=>L.next(z*V).value,z,30);return z+"ms "+$},toTransition:()=>{}};return L}J2e.applyToOptions=s=>{const t=hgs(s,100,J2e);return s.ease=t.ease,s.duration=ib(t.duration),s.type="keyframes",s};const vgs=5;function $kt(s,t,n){const r=Math.max(t-vgs,0);return bkt(n-s(r),t-r)}function QDe({keyframes:s,velocity:t=0,power:n=.8,timeConstant:r=325,bounceDamping:a=10,bounceStiffness:i=500,modifyTarget:l,min:o,max:c,restDelta:d=.5,restSpeed:u}){const h=s[0],m={done:!1,value:h},f=M=>o!==void 0&&Mc,g=M=>o===void 0?c:c===void 0||Math.abs(o-M)-y*Math.exp(-M/r),k=M=>_+b(M),A=M=>{const L=b(M),z=k(M);m.done=Math.abs(L)<=d,m.value=m.done?_:z};let T,P;const I=M=>{f(m.value)&&(T=M,P=J2e({keyframes:[m.value,g(m.value)],velocity:$kt(k,M,m.value),damping:a,stiffness:i,restDelta:d,restSpeed:u}))};return I(0),{calculatedDuration:null,next:M=>{let L=!1;return!P&&T===void 0&&(L=!0,A(M),I(M)),T!==void 0&&M>=T?P.next(M-T):(!L&&A(M),m)}}}function bgs(s,t,n){const r=[],a=n||uE.mix||zkt,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=bgs(t,r,a),c=o.length,d=u=>{if(l&&u1)for(;hd(T5(s[0],s[i-1],u)):d}function wgs(s,t){const n=s[s.length-1];for(let r=1;r<=t;r++){const a=pY(0,t,r);s.push(im(n,1,a))}}function jgs(s){const t=[0];return wgs(t,s.length-1),t}function Ngs(s,t){return s.map(n=>n*t)}function kgs(s,t){return s.map(()=>t||Tkt).splice(0,s.length-1)}function VW({duration:s=300,keyframes:t,times:n,ease:r="easeInOut"}){const a=Ifs(r)?r.map(_st):_st(r),i={done:!1,value:t[0]},l=Ngs(n&&n.length===t.length?n:jgs(t),s),o=_gs(l,t,{ease:Array.isArray(a)?a:kgs(t,a)});return{calculatedDuration:s,next:c=>(i.value=o(c),i.done=c>=s,i)}}const Sgs=s=>s!==null;function F4e(s,{repeat:t,repeatType:n="loop"},r,a=1){const i=s.filter(Sgs),o=a<0||t&&n!=="loop"&&t%2===1?0:i.length-1;return!o||r===void 0?i[o]:r}const Cgs={decay:QDe,inertia:QDe,tween:VW,keyframes:VW,spring:J2e};function Ukt(s){typeof s.type=="string"&&(s.type=Cgs[s.type])}class AUe{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 Ags=s=>s/100;class eNe extends AUe{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!==Dv.now()&&this.tick(Dv.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;Ukt(t);const{type:n=VW,repeat:r=0,repeatDelay:a=0,repeatType:i,velocity:l=0}=t;let{keyframes:o}=t;const c=n||VW;c!==VW&&typeof o[0]!="number"&&(this.mixKeyframes=RQ(Ags,zkt(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=CUe(d));const{calculatedDuration:u}=d;this.calculatedDuration=u,this.resolvedDuration=u+a,this.totalDuration=this.resolvedDuration*(r+1)-a,this.generator=d}updateTime(t){const n=Math.round(t-this.startTime)*this.playbackSpeed;this.holdTime!==null?this.currentTime=this.holdTime:this.currentTime=n}tick(t,n=!1){const{generator:r,totalDuration:a,mixKeyframes:i,mirroredGenerator:l,resolvedDuration:o,calculatedDuration:c}=this;if(this.startTime===null)return r.next(0);const{delay:d=0,keyframes:u,repeat:h,repeatType:m,repeatDelay:f,type:g,onUpdate:y,finalKeyframe:x}=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 _=this.currentTime-d*(this.playbackSpeed>=0?1:-1),b=this.playbackSpeed>=0?_<0:_>a;this.currentTime=Math.max(_,0),this.state==="finished"&&this.holdTime===null&&(this.currentTime=a);let k=this.currentTime,A=r;if(h){const M=Math.min(this.currentTime,a)/o;let L=Math.floor(M),z=M%1;!z&&M>=1&&(z=1),z===1&&L--,L=Math.min(L,h+1),!!(L%2)&&(m==="reverse"?(z=1-z,f&&(z-=f/o)):m==="mirror"&&(A=l)),k=T5(0,1,z)*o}let T;b?(this.delayState.value=u[0],T=this.delayState):T=A.next(k),i&&!b&&(T.value=i(T.value));let{done:P}=T;!b&&c!==null&&(P=this.playbackSpeed>=0?this.currentTime>=a:this.currentTime<=0);const I=this.holdTime===null&&(this.state==="finished"||this.state==="running"&&P);return I&&g!==QDe&&(T.value=F4e(u,this.options,x,this.speed)),y&&y(T.value),I&&this.finish(),T}then(t,n){return this.finished.then(t,n)}get duration(){return rj(this.calculatedDuration)}get iterationDuration(){const{delay:t=0}=this.options||{};return this.duration+rj(t)}get time(){return rj(this.currentTime)}set time(t){t=ib(t),this.currentTime=t,this.startTime===null||this.holdTime!==null||this.playbackSpeed===0?this.holdTime=t:this.driver&&(this.startTime=this.driver.now()-t/this.playbackSpeed),this.driver?this.driver.start(!1):(this.startTime=0,this.state="paused",this.holdTime=t,this.tick(t))}getGeneratorVelocity(){const t=this.currentTime;if(t<=0)return this.options.velocity||0;if(this.generator.velocity)return this.generator.velocity(t);const n=this.generator.next(t).value;return $kt(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(Dv.now()),this.playbackSpeed=t,n&&this.driver&&(this.time=rj(this.currentTime))}play(){var a,i;if(this.isStopped)return;const{driver:t=ugs,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(Dv.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 Tgs(s){for(let t=1;ts*180/Math.PI,JDe=s=>{const t=MI(Math.atan2(s[1],s[0]));return eRe(t)},Egs={x:4,y:5,translateX:4,translateY:5,scaleX:0,scaleY:3,scale:s=>(Math.abs(s[0])+Math.abs(s[3]))/2,rotate:JDe,rotateZ:JDe,skewX:s=>MI(Math.atan(s[1])),skewY:s=>MI(Math.atan(s[2])),skew:s=>(Math.abs(s[1])+Math.abs(s[2]))/2},eRe=s=>(s=s%360,s<0&&(s+=360),s),Tst=JDe,Est=s=>Math.sqrt(s[0]*s[0]+s[1]*s[1]),Mst=s=>Math.sqrt(s[4]*s[4]+s[5]*s[5]),Mgs={x:12,y:13,z:14,translateX:12,translateY:13,translateZ:14,scaleX:Est,scaleY:Mst,scale:s=>(Est(s)+Mst(s))/2,rotateX:s=>eRe(MI(Math.atan2(s[6],s[5]))),rotateY:s=>eRe(MI(Math.atan2(-s[2],s[0]))),rotateZ:Tst,rotate:Tst,skewX:s=>MI(Math.atan(s[4])),skewY:s=>MI(Math.atan(s[1])),skew:s=>(Math.abs(s[1])+Math.abs(s[4]))/2};function tRe(s){return s.includes("scale")?1:0}function sRe(s,t){if(!s||s==="none")return tRe(t);const n=s.match(/^matrix3d\(([-\d.e\s,]+)\)$/u);let r,a;if(n)r=Mgs,a=n;else{const o=s.match(/^matrix\(([-\d.e\s,]+)\)$/u);r=Egs,a=o}if(!a)return tRe(t);const i=r[t],l=a[1].split(",").map(Pgs);return typeof i=="function"?i(l):l[i]}const Lgs=(s,t)=>{const{transform:n="none"}=getComputedStyle(s);return sRe(n,t)};function Pgs(s){return parseFloat(s.trim())}const uU=["transformPerspective","x","y","z","translateX","translateY","translateZ","scale","scaleX","scaleY","rotate","rotateX","rotateY","rotateZ","skew","skewX","skewY"],hU=new Set(uU),Lst=s=>s===dU||s===Qi,Igs=new Set(["x","y","z"]),Dgs=uU.filter(s=>!Igs.has(s));function Rgs(s){const t=[];return Dgs.forEach(n=>{const r=s.getValue(n);r!==void 0&&(t.push([n,r.get()]),r.set(n.startsWith("scale")?1:0))}),t}const rT={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})=>sRe(t,"x"),y:(s,{transform:t})=>sRe(t,"y")};rT.translateX=rT.x;rT.translateY=rT.y;const SD=new Set;let nRe=!1,rRe=!1,aRe=!1;function qkt(){if(rRe){const s=Array.from(SD).filter(r=>r.needsMeasurement),t=new Set(s.map(r=>r.element)),n=new Map;t.forEach(r=>{const a=Rgs(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)})}rRe=!1,nRe=!1,SD.forEach(s=>s.complete(aRe)),SD.clear()}function Vkt(){SD.forEach(s=>{s.readKeyframes(),s.needsMeasurement&&(rRe=!0)})}function Ogs(){aRe=!0,Vkt(),qkt(),aRe=!1}class TUe{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?(SD.add(this),nRe||(nRe=!0,yh.read(Vkt),yh.resolveKeyframes(qkt))):(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])}Tgs(t)}setFinalKeyframe(){}measureInitialState(){}renderEndStyles(){}measureEndState(){}complete(t=!1){this.state="complete",this.onComplete(this.unresolvedKeyframes,this.finalKeyframe,t),SD.delete(this)}cancel(){this.state==="scheduled"&&(SD.delete(this),this.state="pending")}resume(){this.state==="pending"&&this.scheduleResolve()}}const Fgs=s=>s.startsWith("--");function Hkt(s,t,n){Fgs(t)?s.style.setProperty(t,n):s.style[t]=n}const zgs={};function Gkt(s,t){const n=vkt(s);return()=>zgs[t]??n()}const Bgs=Gkt(()=>window.ScrollTimeline!==void 0,"scrollTimeline"),Wkt=Gkt(()=>{try{document.createElement("div").animate({opacity:0},{easing:"linear(0, 1)"})}catch{return!1}return!0},"linearEasing"),UH=([s,t,n,r])=>`cubic-bezier(${s}, ${t}, ${n}, ${r})`,Pst={linear:"linear",ease:"ease",easeIn:"ease-in",easeOut:"ease-out",easeInOut:"ease-in-out",circIn:UH([0,.65,.55,1]),circOut:UH([.55,0,1,.45]),backIn:UH([.31,.01,.66,-.59]),backOut:UH([.33,1.53,.69,.99])};function Kkt(s,t){if(s)return typeof s=="function"?Wkt()?Bkt(s,t):"ease-out":Ekt(s)?UH(s):Array.isArray(s)?s.map(n=>Kkt(n,t)||Pst.easeOut):Pst[s]}function $gs(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=Kkt(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 Ykt(s){return typeof s=="function"&&"applyToOptions"in s}function Ugs({type:s,...t}){return Ykt(s)&&Wkt()?s.applyToOptions(t):(t.duration??(t.duration=300),t.ease??(t.ease="easeOut"),t)}class Zkt extends AUe{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,$B(typeof t.type!="string",`Mini animate() doesn't support "type" as a string.`,"mini-spring");const d=Ugs(t);this.animation=$gs(n,r,a,d,i),d.autoplay===!1&&this.animation.pause(),this.animation.onfinish=()=>{if(this.finishedTime=this.time,!i){const u=F4e(a,this.options,o,this.speed);this.updateMotionValue&&this.updateMotionValue(u),Hkt(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 rj(Number(t))}get iterationDuration(){const{delay:t=0}=this.options||{};return this.duration+rj(t)}get time(){return rj(Number(this.animation.currentTime)||0)}set time(t){const n=this.finishedTime!==null;this.manualStartTime=null,this.finishedTime=null,this.animation.currentTime=ib(t),n&&this.animation.pause()}get speed(){return this.animation.playbackRate}set speed(t){t<0&&(this.finishedTime=null),this.animation.playbackRate=t}get state(){return this.finishedTime!==null?"finished":this.animation.playState}get startTime(){return this.manualStartTime??Number(this.animation.startTime)}set startTime(t){this.manualStartTime=this.animation.startTime=t}attachTimeline({timeline:t,rangeStart:n,rangeEnd:r,observe:a}){var i;return this.allowFlatten&&((i=this.animation.effect)==null||i.updateTiming({easing:"linear"})),this.animation.onfinish=null,t&&Bgs()?(this.animation.timeline=t,n&&(this.animation.rangeStart=n),r&&(this.animation.rangeEnd=r),fj):a(this)}}const Xkt={anticipate:Skt,backInOut:kkt,circInOut:Akt};function qgs(s){return s in Xkt}function Vgs(s){typeof s.ease=="string"&&qgs(s.ease)&&(s.ease=Xkt[s.ease])}const B6e=10;class Hgs extends Zkt{constructor(t){Vgs(t),Ukt(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 eNe({...l,autoplay:!1}),c=Math.max(B6e,Dv.now()-this.startTime),d=T5(0,B6e,c-B6e),u=o.sample(c).value,{name:h}=this.options;i&&h&&Hkt(i,h,u),n.setWithVelocity(o.sample(Math.max(0,c-d)).value,u,d),o.stop()}}const Ist=(s,t)=>t==="zIndex"?!1:!!(typeof s=="number"||Array.isArray(s)||typeof s=="string"&&(aN.test(s)||s==="0")&&!s.startsWith("url("));function Ggs(s){const t=s[0];if(s.length===1)return!0;for(let n=0;nObject.hasOwnProperty.call(Element.prototype,"animate"));function Qgs(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 Xgs()&&n&&(Qkt.has(n)||Zgs.has(n)&&Ygs(o))&&(n!=="transform"||!u)&&!d&&!r&&a!=="mirror"&&i!==0&&l!=="inertia"}const Jgs=40;class exs extends AUe{constructor({autoplay:t=!0,delay:n=0,type:r="keyframes",repeat:a=0,repeatDelay:i=0,repeatType:l="loop",keyframes:o,name:c,motionValue:d,element:u,...h}){var g;super(),this.stop=()=>{var y,x;this._animation&&(this._animation.stop(),(y=this.stopTimeline)==null||y.call(this)),(x=this.keyframeResolver)==null||x.cancel()},this.createdAt=Dv.now();const m={autoplay:t,delay:n,type:r,repeat:a,repeatDelay:i,repeatType:l,name:c,motionValue:d,element:u,...h},f=(u==null?void 0:u.KeyframeResolver)||TUe;this.keyframeResolver=new f(o,(y,x,_)=>this.onKeyframesResolved(y,x,m,!_),c,d,u),(g=this.keyframeResolver)==null||g.scheduleResolve()}onKeyframesResolved(t,n,r,a){var _,b;this.keyframeResolver=void 0;const{name:i,type:l,velocity:o,delay:c,isHandoff:d,onUpdate:u}=r;this.resolvedAt=Dv.now();let h=!0;Wgs(t,i,l,o)||(h=!1,(uE.instantAnimations||!c)&&(u==null||u(F4e(t,r,n))),t[0]=t[t.length-1],iRe(r),r.repeat=0);const f={startTime:a?this.resolvedAt?this.resolvedAt-this.createdAt>Jgs?this.resolvedAt:this.createdAt:this.createdAt:void 0,finalKeyframe:n,...r,keyframes:t},g=h&&!d&&Qgs(f),y=(b=(_=f.motionValue)==null?void 0:_.owner)==null?void 0:b.current;let x;if(g)try{x=new Hgs({...f,element:y})}catch{x=new eNe(f)}else x=new eNe(f);x.finished.then(()=>{this.notifyFinished()}).catch(fj),this.pendingTimeline&&(this.stopTimeline=x.attachTimeline(this.pendingTimeline),this.pendingTimeline=void 0),this._animation=x}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(),Ogs()),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 Jkt(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 txs=/^var\(--(?:([\w-]+)|([\w-]+), ?([a-zA-Z\d ()%#.,-]+))\)/u;function sxs(s){const t=txs.exec(s);if(!t)return[,];const[,n,r,a]=t;return[`--${n??r}`,a]}const nxs=4;function e5t(s,t,n=1){$B(n<=nxs,`Max CSS variable fallback depth detected in property "${s}". This may indicate a circular fallback dependency.`,"max-css-var-depth");const[r,a]=sxs(s);if(!r)return;const i=window.getComputedStyle(t).getPropertyValue(r);if(i){const l=i.trim();return gkt(l)?parseFloat(l):l}return jUe(a)?e5t(a,t,n+1):a}const rxs={type:"spring",stiffness:500,damping:25,restSpeed:10},axs=s=>({type:"spring",stiffness:550,damping:s===0?2*Math.sqrt(550):30,restSpeed:10}),ixs={type:"keyframes",duration:.8},oxs={type:"keyframes",ease:[.25,.1,.35,1],duration:.3},lxs=(s,{keyframes:t})=>t.length>2?ixs:hU.has(s)?s.startsWith("scale")?axs(t[1]):rxs:oxs;function t5t(s,t){if(s!=null&&s.inherit&&t){const{inherit:n,...r}=s;return{...t,...r}}return s}function EUe(s,t){const n=(s==null?void 0:s[t])??(s==null?void 0:s.default)??s;return n!==s?t5t(n,s):n}const cxs=new Set(["when","delay","delayChildren","staggerChildren","staggerDirection","repeat","repeatType","repeatDelay","from","elapsed"]);function dxs(s){for(const t in s)if(!cxs.has(t))return!0;return!1}const MUe=(s,t,n,r={},a,i)=>l=>{const o=EUe(r,s)||{},c=o.delay||r.delay||0;let{elapsed:d=0}=r;d=d-ib(c);const u={keyframes:Array.isArray(n)?n:[null,n],ease:"easeOut",velocity:t.getVelocity(),...o,delay:-d,onUpdate:m=>{t.set(m),o.onUpdate&&o.onUpdate(m)},onComplete:()=>{l(),o.onComplete&&o.onComplete()},name:s,motionValue:t,element:i?void 0:a};dxs(o)||Object.assign(u,lxs(s,u)),u.duration&&(u.duration=ib(u.duration)),u.repeatDelay&&(u.repeatDelay=ib(u.repeatDelay)),u.from!==void 0&&(u.keyframes[0]=u.from);let h=!1;if((u.type===!1||u.duration===0&&!u.repeatDelay)&&(iRe(u),u.delay===0&&(h=!0)),(uE.instantAnimations||uE.skipAnimations||a!=null&&a.shouldSkipAnimations)&&(h=!0,iRe(u),u.delay=0),u.allowFlatten=!o.type&&!o.ease,h&&!i&&t.get()!==void 0){const m=F4e(u.keyframes,o);if(m!==void 0){yh.update(()=>{u.onUpdate(m),u.onComplete()});return}}return o.isSync?new eNe(u):new exs(u)};function Dst(s){const t=[{},{}];return s==null||s.values.forEach((n,r)=>{t[0][r]=n.get(),t[1][r]=n.getVelocity()}),t}function LUe(s,t,n,r){if(typeof t=="function"){const[a,i]=Dst(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]=Dst(r);t=t(n!==void 0?n:s.custom,a,i)}return t}function CD(s,t,n){const r=s.getProps();return LUe(r,t,n!==void 0?n:r.custom,s)}const s5t=new Set(["width","height","top","left","right","bottom",...uU]),Rst=30,uxs=s=>!isNaN(parseFloat(s));class hxs{constructor(t,n={}){this.canTrackVelocity=null,this.events={},this.updateAndNotify=r=>{var i;const a=Dv.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=Dv.now(),this.canTrackVelocity===null&&t!==void 0&&(this.canTrackVelocity=uxs(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 bUe);const r=this.events[t].add(n);return t==="change"?()=>{r(),yh.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=Dv.now();if(!this.canTrackVelocity||this.prevFrameValue===void 0||t-this.updatedAt>Rst)return 0;const n=Math.min(this.updatedAt-this.prevUpdatedAt,Rst);return bkt(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 qB(s,t){return new hxs(s,t)}const oRe=s=>Array.isArray(s);function mxs(s,t,n){s.hasValue(t)?s.getValue(t).set(n):s.addValue(t,qB(n))}function pxs(s){return oRe(s)?s[s.length-1]||0:s}function fxs(s,t){const n=CD(s,t);let{transitionEnd:r={},transition:a={},...i}=n||{};i={...i,...r};for(const l in i){const o=pxs(i[l]);mxs(s,l,o)}}const F0=s=>!!(s&&s.getVelocity);function gxs(s){return!!(F0(s)&&s.add)}function lRe(s,t){const n=s.getValue("willChange");if(gxs(n))return n.add(t);if(!n&&uE.WillChange){const r=new uE.WillChange("auto");s.addValue("willChange",r),r.add(t)}}function PUe(s){return s.replace(/([A-Z])/g,t=>`-${t.toLowerCase()}`)}const xxs="framerAppearId",n5t="data-"+PUe(xxs);function r5t(s){return s.props[n5t]}function yxs({protectedKeys:s,needsAnimating:t},n){const r=s.hasOwnProperty(n)&&t[n]!==!0;return t[n]=!1,r}function a5t(s,t,{delay:n=0,transitionOverride:r,type:a}={}){let{transition:i,transitionEnd:l,...o}=t;const c=s.getDefaultTransition();i=i?t5t(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 f=s.getValue(m,s.latestValues[m]??null),g=o[m];if(g===void 0||h&&yxs(h,m))continue;const y={delay:n,...EUe(i||{},m)},x=f.get();if(x!==void 0&&!f.isAnimating()&&!Array.isArray(g)&&g===x&&!y.velocity){yh.update(()=>f.set(g));continue}let _=!1;if(window.MotionHandoffAnimation){const A=r5t(s);if(A){const T=window.MotionHandoffAnimation(A,m,yh);T!==null&&(y.startTime=T,_=!0)}}lRe(s,m);const b=d??s.shouldReduceMotion;f.start(MUe(m,f,g,b&&s5t.has(m)?{type:!1}:y,s,_));const k=f.animation;k&&u.push(k)}if(l){const m=()=>yh.update(()=>{l&&fxs(s,l)});u.length?Promise.all(u).then(m):m()}return u}function cRe(s,t,n={}){var c;const r=CD(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(a5t(s,r,n)):()=>Promise.resolve(),l=s.variantChildren&&s.variantChildren.size?(d=0)=>{const{delayChildren:u=0,staggerChildren:h,staggerDirection:m}=a;return vxs(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 vxs(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(cRe(c,t,{...l,delay:n+(typeof r=="function"?0:r)+Jkt(s.variantChildren,c,r,a,i)}).then(()=>c.notify("AnimationComplete",t)));return Promise.all(o)}function bxs(s,t,n={}){s.notify("AnimationStart",t);let r;if(Array.isArray(t)){const a=t.map(i=>cRe(s,i,n));r=Promise.all(a)}else if(typeof t=="string")r=cRe(s,t,n);else{const a=typeof t=="function"?CD(s,t,n.custom):t;r=Promise.all(a5t(s,a,n))}return r.then(()=>{s.notify("AnimationComplete",t)})}const _xs={test:s=>s==="auto",parse:s=>s},i5t=s=>t=>t.test(s),o5t=[dU,Qi,y5,RC,Gfs,Hfs,_xs],Ost=s=>o5t.find(i5t(s));function wxs(s){return typeof s=="number"?s===0:s!==null?s==="none"||s==="0"||ykt(s):!0}const jxs=new Set(["brightness","contrast","saturate","opacity"]);function Nxs(s){const[t,n]=s.slice(0,-1).split("(");if(t==="drop-shadow")return s;const[r]=n.match(NUe)||[];if(!r)return s;const a=n.replace(r,"");let i=jxs.has(t)?1:0;return r!==n&&(i*=100),t+"("+i+a+")"}const kxs=/\b([a-z-]*)\(.*?\)/gu,dRe={...aN,getAnimatableNone:s=>{const t=s.match(kxs);return t?t.map(Nxs).join(" "):s}},uRe={...aN,getAnimatableNone:s=>{const t=aN.parse(s);return aN.createTransformer(s)(t.map(r=>typeof r=="number"?0:typeof r=="object"?{...r,alpha:1}:r))}},Fst={...dU,transform:Math.round},Sxs={rotate:RC,rotateX:RC,rotateY:RC,rotateZ:RC,scale:Hte,scaleX:Hte,scaleY:Hte,scaleZ:Hte,skew:RC,skewX:RC,skewY:RC,distance:Qi,translateX:Qi,translateY:Qi,translateZ:Qi,x:Qi,y:Qi,z:Qi,perspective:Qi,transformPerspective:Qi,opacity:fY,originX:Nst,originY:Nst,originZ:Qi},IUe={borderWidth:Qi,borderTopWidth:Qi,borderRightWidth:Qi,borderBottomWidth:Qi,borderLeftWidth:Qi,borderRadius:Qi,borderTopLeftRadius:Qi,borderTopRightRadius:Qi,borderBottomRightRadius:Qi,borderBottomLeftRadius:Qi,width:Qi,maxWidth:Qi,height:Qi,maxHeight:Qi,top:Qi,right:Qi,bottom:Qi,left:Qi,inset:Qi,insetBlock:Qi,insetBlockStart:Qi,insetBlockEnd:Qi,insetInline:Qi,insetInlineStart:Qi,insetInlineEnd:Qi,padding:Qi,paddingTop:Qi,paddingRight:Qi,paddingBottom:Qi,paddingLeft:Qi,paddingBlock:Qi,paddingBlockStart:Qi,paddingBlockEnd:Qi,paddingInline:Qi,paddingInlineStart:Qi,paddingInlineEnd:Qi,margin:Qi,marginTop:Qi,marginRight:Qi,marginBottom:Qi,marginLeft:Qi,marginBlock:Qi,marginBlockStart:Qi,marginBlockEnd:Qi,marginInline:Qi,marginInlineStart:Qi,marginInlineEnd:Qi,fontSize:Qi,backgroundPositionX:Qi,backgroundPositionY:Qi,...Sxs,zIndex:Fst,fillOpacity:fY,strokeOpacity:fY,numOctaves:Fst},Cxs={...IUe,color:cg,backgroundColor:cg,outlineColor:cg,fill:cg,stroke:cg,borderColor:cg,borderTopColor:cg,borderRightColor:cg,borderBottomColor:cg,borderLeftColor:cg,filter:dRe,WebkitFilter:dRe,mask:uRe,WebkitMask:uRe},l5t=s=>Cxs[s],Axs=new Set([dRe,uRe]);function c5t(s,t){let n=l5t(s);return Axs.has(n)||(n=aN),n.getAnimatableNone?n.getAnimatableNone(t):void 0}const Txs=new Set(["auto","none","0"]);function Exs(s,t,n){let r=0,a;for(;r{t.getValue(c).set(d)}),this.resolveNoneKeyframes()}}function DUe(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 d5t=(s,t)=>t&&typeof s=="number"?t.transform(s):s;function Ewe(s){return xkt(s)&&"offsetHeight"in s&&!("ownerSVGElement"in s)}const{schedule:RUe,cancel:$On}=Mkt(queueMicrotask,!1),c2={x:!1,y:!1};function u5t(){return c2.x||c2.y}function Lxs(s){return s==="x"||s==="y"?c2[s]?null:(c2[s]=!0,()=>{c2[s]=!1}):c2.x||c2.y?null:(c2.x=c2.y=!0,()=>{c2.x=c2.y=!1})}function h5t(s,t){const n=DUe(s),r=new AbortController,a={passive:!0,...t,signal:r.signal};return[n,a,()=>r.abort()]}function Pxs(s){return!(s.pointerType==="touch"||u5t())}function Ixs(s,t,n={}){const[r,a,i]=h5t(s,n);return r.forEach(l=>{let o=!1,c=!1,d;const u=()=>{l.removeEventListener("pointerleave",g)},h=x=>{d&&(d(x),d=void 0),u()},m=x=>{o=!1,window.removeEventListener("pointerup",m),window.removeEventListener("pointercancel",m),c&&(c=!1,h(x))},f=()=>{o=!0,window.addEventListener("pointerup",m,a),window.addEventListener("pointercancel",m,a)},g=x=>{if(x.pointerType!=="touch"){if(o){c=!0;return}h(x)}},y=x=>{if(!Pxs(x))return;c=!1;const _=t(l,x);typeof _=="function"&&(d=_,l.addEventListener("pointerleave",g,a))};l.addEventListener("pointerenter",y,a),l.addEventListener("pointerdown",f,a)}),i}const m5t=(s,t)=>t?s===t?!0:m5t(s,t.parentElement):!1,OUe=s=>s.pointerType==="mouse"?typeof s.button!="number"||s.button<=0:s.isPrimary!==!1,Dxs=new Set(["BUTTON","INPUT","SELECT","TEXTAREA","A"]);function Rxs(s){return Dxs.has(s.tagName)||s.isContentEditable===!0}const Oxs=new Set(["INPUT","SELECT","TEXTAREA"]);function Fxs(s){return Oxs.has(s.tagName)||s.isContentEditable===!0}const Mwe=new WeakSet;function zst(s){return t=>{t.key==="Enter"&&s(t)}}function $6e(s,t){s.dispatchEvent(new PointerEvent("pointer"+t,{isPrimary:!0,bubbles:!0}))}const zxs=(s,t)=>{const n=s.currentTarget;if(!n)return;const r=zst(()=>{if(Mwe.has(n))return;$6e(n,"down");const a=zst(()=>{$6e(n,"up")}),i=()=>$6e(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 Bst(s){return OUe(s)&&!u5t()}const $st=new WeakSet;function Bxs(s,t,n={}){const[r,a,i]=h5t(s,n),l=o=>{const c=o.currentTarget;if(!Bst(o)||$st.has(o))return;Mwe.add(c),n.stopPropagation&&$st.add(o);const d=t(c,o),u=(f,g)=>{window.removeEventListener("pointerup",h),window.removeEventListener("pointercancel",m),Mwe.has(c)&&Mwe.delete(c),Bst(f)&&typeof d=="function"&&d(f,{success:g})},h=f=>{u(f,c===window||c===document||n.useGlobalTarget||m5t(c,f.target))},m=f=>{u(f,!1)};window.addEventListener("pointerup",h,a),window.addEventListener("pointercancel",m,a)};return r.forEach(o=>{(n.useGlobalTarget?window:o).addEventListener("pointerdown",l,a),Ewe(o)&&(o.addEventListener("focus",d=>zxs(d,a)),!Rxs(o)&&!o.hasAttribute("tabindex")&&(o.tabIndex=0))}),i}function FUe(s){return xkt(s)&&"ownerSVGElement"in s}const Lwe=new WeakMap;let OC;const p5t=(s,t,n)=>(r,a)=>a&&a[0]?a[0][s+"Size"]:FUe(r)&&"getBBox"in r?r.getBBox()[t]:r[n],$xs=p5t("inline","width","offsetWidth"),Uxs=p5t("block","height","offsetHeight");function qxs({target:s,borderBoxSize:t}){var n;(n=Lwe.get(s))==null||n.forEach(r=>{r(s,{get width(){return $xs(s,t)},get height(){return Uxs(s,t)}})})}function Vxs(s){s.forEach(qxs)}function Hxs(){typeof ResizeObserver>"u"||(OC=new ResizeObserver(Vxs))}function Gxs(s,t){OC||Hxs();const n=DUe(s);return n.forEach(r=>{let a=Lwe.get(r);a||(a=new Set,Lwe.set(r,a)),a.add(t),OC==null||OC.observe(r)}),()=>{n.forEach(r=>{const a=Lwe.get(r);a==null||a.delete(t),a!=null&&a.size||OC==null||OC.unobserve(r)})}}const Pwe=new Set;let P7;function Wxs(){P7=()=>{const s={get width(){return window.innerWidth},get height(){return window.innerHeight}};Pwe.forEach(t=>t(s))},window.addEventListener("resize",P7)}function Kxs(s){return Pwe.add(s),P7||Wxs(),()=>{Pwe.delete(s),!Pwe.size&&typeof P7=="function"&&(window.removeEventListener("resize",P7),P7=void 0)}}function Ust(s,t){return typeof s=="function"?Kxs(s):Gxs(s,t)}function Yxs(s){return FUe(s)&&s.tagName==="svg"}const Zxs=[...o5t,cg,aN],Xxs=s=>Zxs.find(i5t(s)),qst=()=>({translate:0,scale:1,origin:0,originPoint:0}),I7=()=>({x:qst(),y:qst()}),Vst=()=>({min:0,max:0}),Vg=()=>({x:Vst(),y:Vst()}),Qxs=new WeakMap;function z4e(s){return s!==null&&typeof s=="object"&&typeof s.start=="function"}function gY(s){return typeof s=="string"||Array.isArray(s)}const zUe=["animate","whileInView","whileFocus","whileHover","whileTap","whileDrag","exit"],BUe=["initial",...zUe];function B4e(s){return z4e(s.animate)||BUe.some(t=>gY(s[t]))}function f5t(s){return!!(B4e(s)||s.variants)}function Jxs(s,t,n){for(const r in t){const a=t[r],i=n[r];if(F0(a))s.addValue(r,a);else if(F0(i))s.addValue(r,qB(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,qB(l!==void 0?l:a,{owner:s}))}}for(const r in n)t[r]===void 0&&s.removeValue(r);return t}const hRe={current:null},g5t={current:!1},e0s=typeof window<"u";function t0s(){if(g5t.current=!0,!!e0s)if(window.matchMedia){const s=window.matchMedia("(prefers-reduced-motion)"),t=()=>hRe.current=s.matches;s.addEventListener("change",t),t()}else hRe.current=!1}const Hst=["AnimationStart","AnimationComplete","Update","BeforeLayoutMeasure","LayoutMeasure","LayoutAnimationStart","LayoutAnimationComplete"];let tNe={};function x5t(s){tNe=s}function s0s(){return tNe}class n0s{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=TUe,this.features={},this.valueSubscriptions=new Map,this.prevMotionValues={},this.hasBeenMounted=!1,this.events={},this.propEventSubscriptions={},this.notifyUpdate=()=>this.notify("Update",this.latestValues),this.render=()=>{this.current&&(this.triggerBuild(),this.renderInstance(this.current,this.renderState,this.props.style,this.projection))},this.renderScheduledAt=0,this.scheduleRender=()=>{const f=Dv.now();this.renderScheduledAtthis.bindToMotionValue(i,a)),this.reducedMotionConfig==="never"?this.shouldReduceMotion=!1:this.reducedMotionConfig==="always"?this.shouldReduceMotion=!0:(g5t.current||t0s(),this.shouldReduceMotion=hRe.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(),hE(this.notifyUpdate),hE(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&&Qkt.has(t)&&this.current instanceof HTMLElement){const{factory:l,keyframes:o,times:c,ease:d,duration:u}=n.accelerate,h=new Zkt({element:this.current,name:t,keyframes:o,times:c,ease:d,duration:ib(u)}),m=l(h);this.valueSubscriptions.set(t,()=>{m(),h.cancel()});return}const r=hU.has(t);r&&this.onBindTransform&&this.onBindTransform();const a=n.on("change",l=>{this.latestValues[t]=l,this.props.onUpdate&&yh.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 tNe){const n=tNe[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):Vg()}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=qB(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"&&(gkt(r)||ykt(r))?r=parseFloat(r):!Xxs(r)&&aN.test(n)&&(r=c5t(t,n)),this.setBaseTarget(t,F0(r)?r.get():r)),F0(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=LUe(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&&!F0(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 bUe),this.events[t].add(n)}notify(t,...n){this.events[t]&&this.events[t].notify(...n)}scheduleRenderMicrotask(){RUe.render(this.render)}}class y5t extends n0s{constructor(){super(...arguments),this.KeyframeResolver=Mxs}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;F0(t)&&(this.childSubscription=t.on("change",n=>{this.current&&(this.current.textContent=`${n}`)}))}}class OE{constructor(t){this.isMounted=!1,this.node=t}update(){}}function v5t({top:s,left:t,right:n,bottom:r}){return{x:{min:t,max:n},y:{min:s,max:r}}}function r0s({x:s,y:t}){return{top:t.min,right:s.max,bottom:t.max,left:s.min}}function a0s(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 U6e(s){return s===void 0||s===1}function mRe({scale:s,scaleX:t,scaleY:n}){return!U6e(s)||!U6e(t)||!U6e(n)}function iI(s){return mRe(s)||b5t(s)||s.z||s.rotate||s.rotateX||s.rotateY||s.skewX||s.skewY}function b5t(s){return Gst(s.x)||Gst(s.y)}function Gst(s){return s&&s!=="0%"}function sNe(s,t,n){const r=s-n,a=t*r;return n+a}function Wst(s,t,n,r,a){return a!==void 0&&(s=sNe(s,a,r)),sNe(s,n,r)+t}function pRe(s,t=0,n=1,r,a){s.min=Wst(s.min,t,n,r,a),s.max=Wst(s.max,t,n,r,a)}function _5t(s,{x:t,y:n}){pRe(s.x,t.translate,t.scale,t.originPoint),pRe(s.y,n.translate,n.scale,n.originPoint)}const Kst=.999999999999,Yst=1.0000000000001;function i0s(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;cKst&&(t.x=1),t.yKst&&(t.y=1)}function Vk(s,t){s.min+=t,s.max+=t}function Zst(s,t,n,r,a=.5){const i=im(s.min,s.max,a);pRe(s,t,n,i,r)}function Xst(s,t){return typeof s=="string"?parseFloat(s)/100*(t.max-t.min):s}function Iwe(s,t,n){const r=n??s;Zst(s.x,Xst(t.x,r.x),t.scaleX,t.scale,t.originX),Zst(s.y,Xst(t.y,r.y),t.scaleY,t.scale,t.originY)}function w5t(s,t){return v5t(a0s(s.getBoundingClientRect(),t))}function o0s(s,t,n){const r=w5t(s,n),{scroll:a}=t;return a&&(Vk(r.x,a.offset.x),Vk(r.y,a.offset.y)),r}const l0s={x:"translateX",y:"translateY",z:"translateZ",transformPerspective:"perspective"},c0s=uU.length;function d0s(s,t,n){let r="",a=!0;for(let i=0;i{if(!t.target)return s;if(typeof s=="string")if(Qi.test(s))s=parseFloat(s);else return s;const n=Qst(s,t.target.x),r=Qst(s,t.target.y);return`${n}% ${r}%`}},u0s={correct:(s,{treeScale:t,projectionDelta:n})=>{const r=s,a=aN.parse(s);if(a.length>5)return r;const i=aN.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=im(o,c,.5);return typeof a[2+l]=="number"&&(a[2+l]/=d),typeof a[3+l]=="number"&&(a[3+l]/=d),i(a)}},fRe={borderRadius:{...EV,applyTo:["borderTopLeftRadius","borderTopRightRadius","borderBottomLeftRadius","borderBottomRightRadius"]},borderTopLeftRadius:EV,borderTopRightRadius:EV,borderBottomLeftRadius:EV,borderBottomRightRadius:EV,boxShadow:u0s};function N5t(s,{layout:t,layoutId:n}){return hU.has(s)||s.startsWith("origin")||(t||n!==void 0)&&(!!fRe[s]||s==="opacity")}function UUe(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)(F0(r[o])||a&&F0(a[o])||N5t(o,s)||((l=n==null?void 0:n.getValue(o))==null?void 0:l.liveStyle)!==void 0)&&(i[o]=r[o]);return i}function h0s(s){return window.getComputedStyle(s)}class m0s extends y5t{constructor(){super(...arguments),this.type="html",this.renderInstance=j5t}readValueFromInstance(t,n){var r;if(hU.has(n))return(r=this.projection)!=null&&r.isProjecting?tRe(n):Lgs(t,n);{const a=h0s(t),i=(Pkt(n)?a.getPropertyValue(n):a[n])||0;return typeof i=="string"?i.trim():i}}measureInstanceViewportBox(t,{transformPagePoint:n}){return w5t(t,n)}build(t,n,r){$Ue(t,n,r.transformTemplate)}scrapeMotionValuesFromProps(t,n,r){return UUe(t,n,r)}}const p0s={offset:"stroke-dashoffset",array:"stroke-dasharray"},f0s={offset:"strokeDashoffset",array:"strokeDasharray"};function g0s(s,t,n=1,r=0,a=!0){s.pathLength=1;const i=a?p0s:f0s;s[i.offset]=`${-r}`,s[i.array]=`${t} ${n}`}const x0s=["offsetDistance","offsetPath","offsetRotate","offsetAnchor"];function k5t(s,{attrX:t,attrY:n,attrScale:r,pathLength:a,pathSpacing:i=1,pathOffset:l=0,...o},c,d,u){if($Ue(s,o,d),c){s.style.viewBox&&(s.attrs.viewBox=s.style.viewBox);return}s.attrs=s.style,s.style={};const{attrs:h,style:m}=s;h.transform&&(m.transform=h.transform,delete h.transform),(m.transform||h.transformOrigin)&&(m.transformOrigin=h.transformOrigin??"50% 50%",delete h.transformOrigin),m.transform&&(m.transformBox=(u==null?void 0:u.transformBox)??"fill-box",delete h.transformBox);for(const f of x0s)h[f]!==void 0&&(m[f]=h[f],delete h[f]);t!==void 0&&(h.x=t),n!==void 0&&(h.y=n),r!==void 0&&(h.scale=r),a!==void 0&&g0s(h,a,i,l,!1)}const S5t=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"]),C5t=s=>typeof s=="string"&&s.toLowerCase()==="svg";function y0s(s,t,n,r){j5t(s,t,void 0,r);for(const a in t.attrs)s.setAttribute(S5t.has(a)?a:PUe(a),t.attrs[a])}function A5t(s,t,n){const r=UUe(s,t,n);for(const a in s)if(F0(s[a])||F0(t[a])){const i=uU.indexOf(a)!==-1?"attr"+a.charAt(0).toUpperCase()+a.substring(1):a;r[i]=s[a]}return r}class v0s extends y5t{constructor(){super(...arguments),this.type="svg",this.isSVGTag=!1,this.measureInstanceViewportBox=Vg}getBaseTargetFromProps(t,n){return t[n]}readValueFromInstance(t,n){if(hU.has(n)){const r=l5t(n);return r&&r.default||0}return n=S5t.has(n)?n:PUe(n),t.getAttribute(n)}scrapeMotionValuesFromProps(t,n,r){return A5t(t,n,r)}build(t,n,r){k5t(t,n,this.isSVGTag,r.transformTemplate,r.style)}renderInstance(t,n,r,a){y0s(t,n,r,a)}mount(t){this.isSVGTag=C5t(t.tagName),super.mount(t)}}const b0s=BUe.length;function T5t(s){if(!s)return;if(!s.isControllingVariants){const n=s.parent?T5t(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})=>bxs(s,n,r)))}function N0s(s){let t=j0s(s),n=Jst(),r=!0,a=!1;const i=d=>(u,h)=>{var f;const m=CD(s,h,d==="exit"?(f=s.presenceContext)==null?void 0:f.custom:void 0);if(m){const{transition:g,transitionEnd:y,...x}=m;u={...u,...x,...y}}return u};function l(d){t=d(s)}function o(d){const{props:u}=s,h=T5t(s.parent)||{},m=[],f=new Set;let g={},y=1/0;for(let _=0;_y&&T,z=!1;const $=Array.isArray(A)?A:[A];let V=$.reduce(i(b),{});P===!1&&(V={});const{prevResolvedValues:W={}}=k,G={...W,...V},X=me=>{L=!0,f.has(me)&&(z=!0,f.delete(me)),k.needsAnimating[me]=!0;const ue=s.getValue(me);ue&&(ue.liveStyle=!1)};for(const me in G){const ue=V[me],ce=W[me];if(g.hasOwnProperty(me))continue;let ae=!1;oRe(ue)&&oRe(ce)?ae=!E5t(ue,ce):ae=ue!==ce,ae?ue!=null?X(me):f.add(me):ue!==void 0&&f.has(me)?X(me):k.protectedKeys[me]=!0}k.prevProp=A,k.prevResolvedValues=V,k.isActive&&(g={...g,...V}),(r||a)&&s.blockInitialAnimation&&(L=!1);const te=I&&M;L&&(!te||z)&&m.push(...$.map(me=>{const ue={type:b};if(typeof me=="string"&&(r||a)&&!te&&s.manuallyAnimateOnMount&&s.parent){const{parent:ce}=s,ae=CD(ce,me);if(ce.enteringChildren&&ae){const{delayChildren:he}=ae.transition||{};ue.delay=Jkt(ce.enteringChildren,s,he)}}return{animation:me,options:ue}}))}if(f.size){const _={};if(typeof u.initial!="boolean"){const b=CD(s,Array.isArray(u.initial)?u.initial[0]:u.initial);b&&b.transition&&(_.transition=b.transition)}f.forEach(b=>{const k=s.getBaseTarget(b),A=s.getValue(b);A&&(A.liveStyle=!0),_[b]=k??null}),m.push({animation:_})}let x=!!m.length;return r&&(u.initial===!1||u.initial===u.animate)&&!s.manuallyAnimateOnMount&&(x=!1),r=!1,a=!1,x?t(m):Promise.resolve()}function c(d,u){var m;if(n[d].isActive===u)return Promise.resolve();(m=s.variantChildren)==null||m.forEach(f=>{var g;return(g=f.animationState)==null?void 0:g.setActive(d,u)}),n[d].isActive=u;const h=o(d);for(const f in n)n[f].protectedKeys={};return h}return{animateChanges:o,setActive:c,setAnimateFunction:l,getState:()=>n,reset:()=>{n=Jst(),a=!0}}}function k0s(s,t){return typeof t=="string"?t!==s:Array.isArray(t)?!E5t(t,s):!1}function O6(s=!1){return{isActive:s,protectedKeys:{},needsAnimating:{},prevResolvedValues:{}}}function Jst(){return{animate:O6(!0),whileInView:O6(),whileHover:O6(),whileTap:O6(),whileDrag:O6(),whileFocus:O6(),exit:O6()}}function gRe(s,t){s.min=t.min,s.max=t.max}function n2(s,t){gRe(s.x,t.x),gRe(s.y,t.y)}function ent(s,t){s.translate=t.translate,s.scale=t.scale,s.originPoint=t.originPoint,s.origin=t.origin}const M5t=1e-4,S0s=1-M5t,C0s=1+M5t,L5t=.01,A0s=0-L5t,T0s=0+L5t;function Rv(s){return s.max-s.min}function E0s(s,t,n){return Math.abs(s-t)<=n}function tnt(s,t,n,r=.5){s.origin=r,s.originPoint=im(t.min,t.max,s.origin),s.scale=Rv(n)/Rv(t),s.translate=im(n.min,n.max,s.origin)-s.originPoint,(s.scale>=S0s&&s.scale<=C0s||isNaN(s.scale))&&(s.scale=1),(s.translate>=A0s&&s.translate<=T0s||isNaN(s.translate))&&(s.translate=0)}function HW(s,t,n,r){tnt(s.x,t.x,n.x,r?r.originX:void 0),tnt(s.y,t.y,n.y,r?r.originY:void 0)}function snt(s,t,n,r=0){const a=r?im(n.min,n.max,r):n.min;s.min=a+t.min,s.max=s.min+Rv(t)}function M0s(s,t,n,r){snt(s.x,t.x,n.x,r==null?void 0:r.x),snt(s.y,t.y,n.y,r==null?void 0:r.y)}function nnt(s,t,n,r=0){const a=r?im(n.min,n.max,r):n.min;s.min=t.min-a,s.max=s.min+Rv(t)}function nNe(s,t,n,r){nnt(s.x,t.x,n.x,r==null?void 0:r.x),nnt(s.y,t.y,n.y,r==null?void 0:r.y)}function rnt(s,t,n,r,a){return s-=t,s=sNe(s,1/n,r),a!==void 0&&(s=sNe(s,1/a,r)),s}function L0s(s,t=0,n=1,r=.5,a,i=s,l=s){if(y5.test(t)&&(t=parseFloat(t),t=im(l.min,l.max,t/100)-l.min),typeof t!="number")return;let o=im(i.min,i.max,r);s===i&&(o-=t),s.min=rnt(s.min,t,n,o,a),s.max=rnt(s.max,t,n,o,a)}function ant(s,t,[n,r,a],i,l){L0s(s,t[n],t[r],t[a],t.scale,i,l)}const P0s=["x","scaleX","originX"],I0s=["y","scaleY","originY"];function int(s,t,n,r){ant(s.x,t,P0s,n?n.x:void 0,r?r.x:void 0),ant(s.y,t,I0s,n?n.y:void 0,r?r.y:void 0)}function ont(s){return s.translate===0&&s.scale===1}function P5t(s){return ont(s.x)&&ont(s.y)}function lnt(s,t){return s.min===t.min&&s.max===t.max}function D0s(s,t){return lnt(s.x,t.x)&&lnt(s.y,t.y)}function cnt(s,t){return Math.round(s.min)===Math.round(t.min)&&Math.round(s.max)===Math.round(t.max)}function I5t(s,t){return cnt(s.x,t.x)&&cnt(s.y,t.y)}function dnt(s){return Rv(s.x)/Rv(s.y)}function unt(s,t){return s.translate===t.translate&&s.scale===t.scale&&s.originPoint===t.originPoint}function fk(s){return[s("x"),s("y")]}function R0s(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:f,skewY:g}=n;d&&(r=`perspective(${d}px) ${r}`),u&&(r+=`rotate(${u}deg) `),h&&(r+=`rotateX(${h}deg) `),m&&(r+=`rotateY(${m}deg) `),f&&(r+=`skewX(${f}deg) `),g&&(r+=`skewY(${g}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 D5t=["borderTopLeftRadius","borderTopRightRadius","borderBottomLeftRadius","borderBottomRightRadius"],O0s=D5t.length,hnt=s=>typeof s=="string"?parseFloat(s):s,mnt=s=>typeof s=="number"||Qi.test(s);function F0s(s,t,n,r,a,i){a?(s.opacity=im(0,n.opacity??1,z0s(r)),s.opacityExit=im(t.opacity??1,0,B0s(r))):i&&(s.opacity=im(t.opacity??1,n.opacity??1,r));for(let l=0;lrt?1:n(pY(s,t,r))}function $0s(s,t,n){const r=F0(s)?s:qB(s);return r.start(MUe("",r,t,n)),r.animation}function xY(s,t,n,r={passive:!0}){return s.addEventListener(t,n,r),()=>s.removeEventListener(t,n)}const U0s=(s,t)=>s.depth-t.depth;class q0s{constructor(){this.children=[],this.isDirty=!1}add(t){vUe(this.children,t),this.isDirty=!0}remove(t){Z2e(this.children,t),this.isDirty=!0}forEach(t){this.isDirty&&this.children.sort(U0s),this.isDirty=!1,this.children.forEach(t)}}function V0s(s,t){const n=Dv.now(),r=({timestamp:a})=>{const i=a-n;i>=t&&(hE(r),s(i-t))};return yh.setup(r,!0),()=>hE(r)}function Dwe(s){return F0(s)?s.get():s}class H0s{constructor(){this.members=[]}add(t){vUe(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&&(Z2e(this.members,r),r.unmount())}t.scheduleRender()}remove(t){if(Z2e(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 Rwe={hasAnimatedSinceResize:!0,hasEverUpdated:!1},q6e=["","X","Y","Z"],G0s=1e3;let W0s=0;function V6e(s,t,n,r){const{latestValues:a}=t;a[s]&&(n[s]=a[s],t.setStaticValue(s,0),r&&(r[s]=0))}function O5t(s){if(s.hasCheckedOptimisedAppear=!0,s.root===s)return;const{visualElement:t}=s.options;if(!t)return;const n=r5t(t);if(window.MotionHasOptimisedAnimation(n,"transform")){const{layout:a,layoutId:i}=s.options;window.MotionCancelOptimisedAnimation(n,"transform",yh,!(a||i))}const{parent:r}=s;r&&!r.hasCheckedOptimisedAppear&&O5t(r)}function F5t({attachResizeListener:s,defaultParent:t,measureScroll:n,checkIsScrollRoot:r,resetTransform:a}){return class{constructor(l={},o=t==null?void 0:t()){this.id=W0s++,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(Z0s),this.nodes.forEach(sys),this.nodes.forEach(nys),this.nodes.forEach(X0s)},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;yh.read(()=>{h=window.innerWidth}),s(l,()=>{const f=window.innerWidth;f!==h&&(h=f,this.root.updateBlockedByResize=!0,u&&u(),u=V0s(m,250),Rwe.hasAnimatedSinceResize&&(Rwe.hasAnimatedSinceResize=!1,this.nodes.forEach(xnt)))})}o&&this.root.registerSharedNode(o,this),this.options.animate!==!1&&d&&(o||c)&&this.addEventListener("didUpdate",({delta:u,hasLayoutChanged:h,hasRelativeLayoutChanged:m,layout:f})=>{if(this.isTreeAnimationBlocked()){this.target=void 0,this.relativeTarget=void 0;return}const g=this.options.transition||d.getDefaultTransition()||lys,{onLayoutAnimationStart:y,onLayoutAnimationComplete:x}=d.getProps(),_=!this.targetLayout||!I5t(this.targetLayout,f),b=!h&&m;if(this.options.layoutRoot||this.resumeFrom||b||h&&(_||!this.currentAnimation)){this.resumeFrom&&(this.resumingFrom=this.resumeFrom,this.resumingFrom.resumingFrom=void 0);const k={...EUe(g,"layout"),onPlay:y,onComplete:x};(d.shouldReduceMotion||this.options.layoutRoot)&&(k.delay=0,k.type=!1),this.startAnimation(k),this.setAnimationOrigin(u,b)}else h||xnt(this),this.isLead()&&this.options.onExitComplete&&this.options.onExitComplete();this.targetLayout=f})}unmount(){this.options.layoutId&&this.willUpdate(),this.root.nodes.remove(this);const l=this.getStack();l&&l.remove(this),this.parent&&this.parent.children.delete(this),this.instance=void 0,this.eventHandlers.clear(),hE(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(rys),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&&O5t(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&&!Rv(this.snapshot.measuredBox.x)&&!Rv(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 T=A/1e3;ynt(h.x,l.x,T),ynt(h.y,l.y,T),this.setTargetDelta(h),this.relativeTarget&&this.relativeTargetOrigin&&this.layout&&this.relativeParent&&this.relativeParent.layout&&(nNe(m,this.layout.layoutBox,this.relativeParent.layout.layoutBox,this.options.layoutAnchor||void 0),iys(this.relativeTarget,this.relativeTargetOrigin,m,T),k&&D0s(this.relativeTarget,k)&&(this.isProjectionDirty=!1),k||(k=Vg()),n2(k,this.relativeTarget)),y&&(this.animationValues=u,F0s(u,d,this.latestValues,T,b,_)),this.root.scheduleUpdateProjection(),this.scheduleRender(),this.animationProgress=T},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&&(hE(this.pendingAnimation),this.pendingAnimation=void 0),this.pendingAnimation=yh.update(()=>{Rwe.hasAnimatedSinceResize=!0,this.motionValue||(this.motionValue=qB(0)),this.motionValue.jump(0,!1),this.currentAnimation=$0s(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(G0s),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&&z5t(this.options.animationType,this.layout.layoutBox,d.layoutBox)){c=this.target||Vg();const h=Rv(this.layout.layoutBox.x);c.x.min=l.target.x.min,c.x.max=c.x.min+h;const m=Rv(this.layout.layoutBox.y);c.y.min=l.target.y.min,c.y.max=c.y.min+m}n2(o,c),Iwe(o,u),HW(this.projectionDeltaWithTransform,this.layoutCorrected,o,u)}}registerSharedNode(l,o){this.sharedNodes.has(l)||this.sharedNodes.set(l,new H0s),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&&V6e("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(fnt),this.root.sharedNodes.clear()}}}function K0s(s){s.updateLayout()}function Y0s(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")fk(h=>{const m=l?t.measuredBox[h]:t.layoutBox[h],f=Rv(m);m.min=r[h].min,m.max=m.min+f});else if(i==="x"||i==="y"){const h=i==="x"?"y":"x";gRe(l?t.measuredBox[h]:t.layoutBox[h],r[h])}else z5t(i,t.layoutBox,r)&&fk(h=>{const m=l?t.measuredBox[h]:t.layoutBox[h],f=Rv(r[h]);m.max=m.min+f,s.relativeTarget&&!s.currentAnimation&&(s.isProjectionDirty=!0,s.relativeTarget[h].max=s.relativeTarget[h].min+f)});const o=I7();HW(o,r,t.layoutBox);const c=I7();l?HW(c,s.applyTransform(a,!0),t.measuredBox):HW(c,r,t.layoutBox);const d=!P5t(o);let u=!1;if(!s.resumeFrom){const h=s.getClosestProjectingParent();if(h&&!h.resumeFrom){const{snapshot:m,layout:f}=h;if(m&&f){const g=s.options.layoutAnchor||void 0,y=Vg();nNe(y,t.layoutBox,m.layoutBox,g);const x=Vg();nNe(x,r,f.layoutBox,g),I5t(y,x)||(u=!0),h.options.layoutRoot&&(s.relativeTarget=x,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 Z0s(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 X0s(s){s.isProjectionDirty=s.isSharedProjectionDirty=s.isTransformDirty=!1}function Q0s(s){s.clearSnapshot()}function fnt(s){s.clearMeasurements()}function J0s(s){s.isLayoutDirty=!0,s.updateLayout()}function gnt(s){s.isLayoutDirty=!1}function eys(s){s.isAnimationBlocked&&s.layout&&!s.isLayoutDirty&&(s.snapshot=s.layout,s.isLayoutDirty=!0)}function tys(s){const{visualElement:t}=s.options;t&&t.getProps().onBeforeLayoutMeasure&&t.notify("BeforeLayoutMeasure"),s.resetTransform()}function xnt(s){s.finishAnimation(),s.targetDelta=s.relativeTarget=s.target=void 0,s.isProjectionDirty=!0}function sys(s){s.resolveTargetDelta()}function nys(s){s.calcProjection()}function rys(s){s.resetSkewAndRotation()}function ays(s){s.removeLeadSnapshot()}function ynt(s,t,n){s.translate=im(t.translate,0,n),s.scale=im(t.scale,1,n),s.origin=t.origin,s.originPoint=t.originPoint}function vnt(s,t,n,r){s.min=im(t.min,n.min,r),s.max=im(t.max,n.max,r)}function iys(s,t,n,r){vnt(s.x,t.x,n.x,r),vnt(s.y,t.y,n.y,r)}function oys(s){return s.animationValues&&s.animationValues.opacityExit!==void 0}const lys={duration:.45,ease:[.4,0,.1,1]},bnt=s=>typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().includes(s),_nt=bnt("applewebkit/")&&!bnt("chrome/")?Math.round:fj;function wnt(s){s.min=_nt(s.min),s.max=_nt(s.max)}function cys(s){wnt(s.x),wnt(s.y)}function z5t(s,t,n){return s==="position"||s==="preserve-aspect"&&!E0s(dnt(t),dnt(n),.2)}function dys(s){var t;return s!==s.root&&((t=s.scroll)==null?void 0:t.wasRoot)}const uys=F5t({attachResizeListener:(s,t)=>xY(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}),H6e={current:void 0},B5t=F5t({measureScroll:s=>({x:s.scrollLeft,y:s.scrollTop}),defaultParent:()=>{if(!H6e.current){const s=new uys({});s.mount(window),s.setOptions({layoutScroll:!0}),H6e.current=s}return H6e.current},resetTransform:(s,t)=>{s.style.transform=t!==void 0?t:"none"},checkIsScrollRoot:s=>window.getComputedStyle(s).position==="fixed"}),qUe=N.createContext({transformPagePoint:s=>s,isStatic:!1,reducedMotion:"never"});function jnt(s,t){if(typeof s=="function")return s(t);s!=null&&(s.current=t)}function hys(...s){return t=>{let n=!1;const r=s.map(a=>{const i=jnt(a,t);return!n&&typeof i=="function"&&(n=!0),i});if(n)return()=>{for(let a=0;a{const{width:f,height:g,top:y,left:x,right:_,bottom:b}=c.current;if(t||i===!1||!o.current||!f||!g)return;const k=n==="left"?`left: ${x}`:`right: ${_}`,A=r==="bottom"?`bottom: ${b}`:`top: ${y}`;o.current.dataset.motionPopId=l;const T=document.createElement("style");d&&(T.nonce=d);const P=a??document.head;return P.appendChild(T),T.sheet&&T.sheet.insertRule(` [data-motion-pop-id="${l}"] { position: absolute !important; width: ${f}px !important; height: ${g}px !important; ${k}px !important; ${A}px !important; } `),()=>{var I;(I=o.current)==null||I.removeAttribute("data-motion-pop-id"),P.contains(T)&&P.removeChild(T)}},[t]),e.jsx(pys,{isPresent:t,childRef:o,sizeRef:c,pop:i,children:i===!1?s:N.cloneElement(s,{ref:h})})}const gys=({children:s,initial:t,isPresent:n,onExitComplete:r,custom:a,presenceAffectsLayout:i,mode:l,anchorX:o,anchorY:c,root:d})=>{const u=yUe(xys),h=N.useId();let m=!0,f=N.useMemo(()=>(m=!1,{id:h,initial:t,isPresent:n,custom:a,onExitComplete:g=>{u.set(g,!0);for(const y of u.values())if(!y)return;r&&r()},register:g=>(u.set(g,!1),()=>u.delete(g))}),[n,u,r]);return i&&m&&(f={...f}),N.useMemo(()=>{u.forEach((g,y)=>u.set(y,!1))},[n]),N.useEffect(()=>{!n&&!u.size&&r&&r()},[n]),s=e.jsx(fys,{pop:l==="popLayout",isPresent:n,anchorX:o,anchorY:c,root:d,children:s}),e.jsx(R4e.Provider,{value:f,children:s})};function xys(){return new Map}function $5t(s=!0){const t=N.useContext(R4e);if(t===null)return[!0,null];const{isPresent:n,onExitComplete:r,register:a}=t,i=N.useId();N.useEffect(()=>{if(s)return a(i)},[s]);const l=N.useCallback(()=>s&&r&&r(i),[i,r,s]);return!n&&r?[!1,l]:[!0]}const Gte=s=>s.key||"";function Nnt(s){const t=[];return N.Children.forEach(s,n=>{N.isValidElement(n)&&t.push(n)}),t}const $4e=({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]=$5t(l),m=N.useMemo(()=>Nnt(s),[s]),f=l&&!u?[]:m.map(Gte),g=N.useRef(!0),y=N.useRef(m),x=yUe(()=>new Map),_=N.useRef(new Set),[b,k]=N.useState(m),[A,T]=N.useState(m);fkt(()=>{g.current=!1,y.current=m;for(let M=0;M{const L=Gte(M),z=l&&!u?!1:m===A||f.includes(L),$=()=>{if(_.current.has(L))return;if(x.has(L))_.current.add(L),x.set(L,!0);else return;let V=!0;x.forEach(W=>{W||(V=!1)}),V&&(I==null||I(),T(y.current),l&&(h==null||h()),r&&r())};return e.jsx(gys,{isPresent:z,initial:!g.current||n?void 0:!1,custom:t,presenceAffectsLayout:a,mode:i,root:d,onExitComplete:z?void 0:$,anchorX:o,anchorY:c,children:M},L)})})},U5t=N.createContext({strict:!1}),knt={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 Snt=!1;function yys(){if(Snt)return;const s={};for(const t in knt)s[t]={isEnabled:n=>knt[t].some(r=>!!n[r])};x5t(s),Snt=!0}function q5t(){return yys(),s0s()}function vys(s){const t=q5t();for(const n in s)t[n]={...t[n],...s[n]};x5t(t)}const bys=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 rNe(s){return s.startsWith("while")||s.startsWith("drag")&&s!=="draggable"||s.startsWith("layout")||s.startsWith("onTap")||s.startsWith("onPan")||s.startsWith("onLayout")||bys.has(s)}let V5t=s=>!rNe(s);function _ys(s){typeof s=="function"&&(V5t=t=>t.startsWith("on")?!rNe(t):s(t))}try{_ys(require("@emotion/is-prop-valid").default)}catch{}function wys(s,t,n){const r={};for(const a in s)a==="values"&&typeof s.values=="object"||F0(s[a])||(V5t(a)||n===!0&&rNe(a)||!t&&!rNe(a)||s.draggable&&a.startsWith("onDrag"))&&(r[a]=s[a]);return r}const U4e=N.createContext({});function jys(s,t){if(B4e(s)){const{initial:n,animate:r}=s;return{initial:n===!1||gY(n)?n:void 0,animate:gY(r)?r:void 0}}return s.inherit!==!1?t:{}}function Nys(s){const{initial:t,animate:n}=jys(s,N.useContext(U4e));return N.useMemo(()=>({initial:t,animate:n}),[Cnt(t),Cnt(n)])}function Cnt(s){return Array.isArray(s)?s.join(" "):s}const VUe=()=>({style:{},transform:{},transformOrigin:{},vars:{}});function H5t(s,t,n){for(const r in t)!F0(t[r])&&!N5t(r,n)&&(s[r]=t[r])}function kys({transformTemplate:s},t){return N.useMemo(()=>{const n=VUe();return $Ue(n,t,s),Object.assign({},n.vars,n.style)},[t])}function Sys(s,t){const n=s.style||{},r={};return H5t(r,n,s),Object.assign(r,kys(s,t)),r}function Cys(s,t){const n={},r=Sys(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 G5t=()=>({...VUe(),attrs:{}});function Ays(s,t,n,r){const a=N.useMemo(()=>{const i=G5t();return k5t(i,t,C5t(r),s.transformTemplate,s.style),{...i.attrs,style:{...i.style}}},[t]);if(s.style){const i={};H5t(i,s.style,s),a.style={...i,...a.style}}return a}const Tys=["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 HUe(s){return typeof s!="string"||s.includes("-")?!1:!!(Tys.indexOf(s)>-1||/[A-Z]/u.test(s))}function Eys(s,t,n,{latestValues:r},a,i=!1,l){const c=(l??HUe(s)?Ays:Cys)(t,r,a,s),d=wys(t,typeof s=="string",i),u=s!==N.Fragment?{...d,...c,ref:n}:{},{children:h}=t,m=N.useMemo(()=>F0(h)?h.get():h,[h]);return N.createElement(s,{...u,children:m})}function Mys({scrapeMotionValuesFromProps:s,createRenderState:t},n,r,a){return{latestValues:Lys(n,r,a,s),renderState:t()}}function Lys(s,t,n,r){const a={},i=r(s,{});for(const m in i)a[m]=Dwe(i[m]);let{initial:l,animate:o}=s;const c=B4e(s),d=f5t(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"&&!z4e(h)){const m=Array.isArray(h)?h:[h];for(let f=0;f(t,n)=>{const r=N.useContext(U4e),a=N.useContext(R4e),i=()=>Mys(s,t,r,a);return n?i():yUe(i)},Pys=W5t({scrapeMotionValuesFromProps:UUe,createRenderState:VUe}),Iys=W5t({scrapeMotionValuesFromProps:A5t,createRenderState:G5t}),Dys=Symbol.for("motionComponentSymbol");function Rys(s,t,n){const r=N.useRef(n);N.useInsertionEffect(()=>{r.current=n});const a=N.useRef(null);return N.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 K5t=N.createContext({});function JF(s){return s&&typeof s=="object"&&Object.prototype.hasOwnProperty.call(s,"current")}function Oys(s,t,n,r,a,i){var k,A;const{visualElement:l}=N.useContext(U4e),o=N.useContext(U5t),c=N.useContext(R4e),d=N.useContext(qUe),u=d.reducedMotion,h=d.skipAnimations,m=N.useRef(null),f=N.useRef(!1);r=r||o.renderer,!m.current&&r&&(m.current=r(s,{visualState:t,parent:l,props:n,presenceContext:c,blockInitialAnimation:c?c.initial===!1:!1,reducedMotionConfig:u,skipAnimations:h,isSVG:i}),f.current&&m.current&&(m.current.manuallyAnimateOnMount=!0));const g=m.current,y=N.useContext(K5t);g&&!g.projection&&a&&(g.type==="html"||g.type==="svg")&&Fys(m.current,n,a,y);const x=N.useRef(!1);N.useInsertionEffect(()=>{g&&x.current&&g.update(n,c)});const _=n[n5t],b=N.useRef(!!_&&typeof window<"u"&&!((k=window.MotionHandoffIsComplete)!=null&&k.call(window,_))&&((A=window.MotionHasOptimisedAnimation)==null?void 0:A.call(window,_)));return fkt(()=>{f.current=!0,g&&(x.current=!0,window.MotionIsMounted=!0,g.updateFeatures(),g.scheduleRenderMicrotask(),b.current&&g.animationState&&g.animationState.animateChanges())}),N.useEffect(()=>{g&&(!b.current&&g.animationState&&g.animationState.animateChanges(),b.current&&(queueMicrotask(()=>{var T;(T=window.MotionHandoffMarkAsComplete)==null||T.call(window,_)}),b.current=!1),g.enteringChildren=void 0)}),g}function Fys(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:Y5t(s.parent)),s.projection.setOptions({layoutId:a,layout:i,alwaysMeasureLayout:!!l||o&&JF(o),visualElement:s,animationType:typeof i=="string"?i:"both",initialPromotionConfig:r,crossfade:h,layoutScroll:c,layoutRoot:d,layoutAnchor:u})}function Y5t(s){if(s)return s.options.allowProjection!==!1?s.projection:Y5t(s.parent)}function G6e(s,{forwardMotionProps:t=!1,type:n}={},r,a){r&&vys(r);const i=n?n==="svg":HUe(s),l=i?Iys:Pys;function o(d,u){let h;const m={...N.useContext(qUe),...d,layoutId:zys(d)},{isStatic:f}=m,g=Nys(d),y=l(d,f);if(!f&&typeof window<"u"){Bys();const x=$ys(m);h=x.MeasureLayout,g.visualElement=Oys(s,y,m,a,x.ProjectionNode,i)}return e.jsxs(U4e.Provider,{value:g,children:[h&&g.visualElement?e.jsx(h,{visualElement:g.visualElement,...m}):null,Eys(s,d,Rys(y,g.visualElement,u),y,f,t,i)]})}o.displayName=`motion.${typeof s=="string"?s:`create(${s.displayName??s.name??""})`}`;const c=N.forwardRef(o);return c[Dys]=s,c}function zys({layoutId:s}){const t=N.useContext(xUe).id;return t&&s!==void 0?t+"-"+s:s}function Bys(s,t){N.useContext(U5t).strict}function $ys(s){const t=q5t(),{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 Uys(s,t){if(typeof Proxy>"u")return G6e;const n=new Map,r=(i,l)=>G6e(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,G6e(l,void 0,s,t)),n.get(l))})}const qys=(s,t)=>t.isSVG??HUe(s)?new v0s(t):new m0s(t,{allowProjection:s!==N.Fragment});class Vys extends OE{constructor(t){super(t),t.animationState||(t.animationState=N0s(t))}updateAnimationControlsSubscription(){const{animate:t}=this.node.getProps();z4e(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 Hys=0;class Gys extends OE{constructor(){super(...arguments),this.id=Hys++,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=CD(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 Wys={animation:{Feature:Vys},exit:{Feature:Gys}};function zQ(s){return{point:{x:s.pageX,y:s.pageY}}}const Kys=s=>t=>OUe(t)&&s(t,zQ(t));function GW(s,t,n,r){return xY(s,t,Kys(n),r)}const Z5t=({current:s})=>s?s.ownerDocument.defaultView:null,Ant=(s,t)=>Math.abs(s-t);function Yys(s,t){const n=Ant(s.x,t.x),r=Ant(s.y,t.y);return Math.sqrt(n**2+r**2)}const Tnt=new Set(["auto","scroll"]);class X5t{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=f=>{this.handleScroll(f.target)},this.onWindowScroll=()=>{this.handleScroll(window)},this.updatePoint=()=>{if(!(this.lastMoveEvent&&this.lastMoveEventInfo))return;this.lastRawMoveEventInfo&&(this.lastMoveEventInfo=Wte(this.lastRawMoveEventInfo,this.transformPagePoint));const f=W6e(this.lastMoveEventInfo,this.history),g=this.startEvent!==null,y=Yys(f.offset,{x:0,y:0})>=this.distanceThreshold;if(!g&&!y)return;const{point:x}=f,{timestamp:_}=E0;this.history.push({...x,timestamp:_});const{onStart:b,onMove:k}=this.handlers;g||(b&&b(this.lastMoveEvent,f),this.startEvent=this.lastMoveEvent),k&&k(this.lastMoveEvent,f)},this.handlePointerMove=(f,g)=>{this.lastMoveEvent=f,this.lastRawMoveEventInfo=g,this.lastMoveEventInfo=Wte(g,this.transformPagePoint),yh.update(this.updatePoint,!0)},this.handlePointerUp=(f,g)=>{this.end();const{onEnd:y,onSessionEnd:x,resumeAnimation:_}=this.handlers;if((this.dragSnapToOrigin||!this.startEvent)&&_&&_(),!(this.lastMoveEvent&&this.lastMoveEventInfo))return;const b=W6e(f.type==="pointercancel"?this.lastMoveEventInfo:Wte(g,this.transformPagePoint),this.history);this.startEvent&&y&&y(f,b),x&&x(f,b)},!OUe(t))return;this.dragSnapToOrigin=i,this.handlers=n,this.transformPagePoint=r,this.distanceThreshold=l,this.contextWindow=a||window;const c=zQ(t),d=Wte(c,this.transformPagePoint),{point:u}=d,{timestamp:h}=E0;this.history=[{...u,timestamp:h}];const{onSessionStart:m}=n;m&&m(t,W6e(d,this.history)),this.removeListeners=RQ(GW(this.contextWindow,"pointermove",this.handlePointerMove),GW(this.contextWindow,"pointerup",this.handlePointerUp),GW(this.contextWindow,"pointercancel",this.handlePointerUp)),o&&this.startScrollTracking(o)}startScrollTracking(t){let n=t.parentElement;for(;n;){const r=getComputedStyle(n);(Tnt.has(r.overflowX)||Tnt.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),yh.update(this.updatePoint,!0))}updateHandlers(t){this.handlers=t}end(){this.removeListeners&&this.removeListeners(),this.removeScrollListeners&&this.removeScrollListeners(),this.scrollPositions.clear(),hE(this.updatePoint)}}function Wte(s,t){return t?{point:t(s.point)}:s}function Ent(s,t){return{x:s.x-t.x,y:s.y-t.y}}function W6e({point:s},t){return{point:s,delta:Ent(s,Q5t(t)),offset:Ent(s,Zys(t)),velocity:Xys(t,.1)}}function Zys(s){return s[0]}function Q5t(s){return s[s.length-1]}function Xys(s,t){if(s.length<2)return{x:0,y:0};let n=s.length-1,r=null;const a=Q5t(s);for(;n>=0&&(r=s[n],!(a.timestamp-r.timestamp>ib(t)));)n--;if(!r)return{x:0,y:0};r===s[0]&&s.length>2&&a.timestamp-r.timestamp>ib(t)*2&&(r=s[1]);const i=rj(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 Qys(s,{min:t,max:n},r){return t!==void 0&&sn&&(s=r?im(n,s,r.max):Math.min(s,n)),s}function Mnt(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 Jys(s,{top:t,left:n,bottom:r,right:a}){return{x:Mnt(s.x,n,a),y:Mnt(s.y,t,r)}}function Lnt(s,t){let n=t.min-s.min,r=t.max-s.max;return t.max-t.minr?n=pY(t.min,t.max-r,s.min):r>a&&(n=pY(s.min,s.max-a,t.min)),T5(0,1,n)}function svs(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 xRe=.35;function nvs(s=xRe){return s===!1?s=0:s===!0&&(s=xRe),{x:Pnt(s,"left","right"),y:Pnt(s,"top","bottom")}}function Pnt(s,t,n){return{min:Int(s,t),max:Int(s,n)}}function Int(s,t){return typeof s=="number"?s:s[t]||0}const rvs=new WeakMap;class avs{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=Vg(),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(zQ(h).point),this.stopAnimation()},l=(h,m)=>{const{drag:f,dragPropagation:g,onDragStart:y}=this.getProps();if(f&&!g&&(this.openDragLock&&this.openDragLock(),this.openDragLock=Lxs(f),!this.openDragLock))return;this.latestPointerEvent=h,this.latestPanInfo=m,this.isDragging=!0,this.currentDirection=null,this.resolveConstraints(),this.visualElement.projection&&(this.visualElement.projection.isAnimationBlocked=!0,this.visualElement.projection.target=void 0),fk(_=>{let b=this.getAxisMotionValue(_).get()||0;if(y5.test(b)){const{projection:k}=this.visualElement;if(k&&k.layout){const A=k.layout.layoutBox[_];A&&(b=Rv(A)*(parseFloat(b)/100))}}this.originPoint[_]=b}),y&&yh.update(()=>y(h,m),!1,!0),lRe(this.visualElement,"transform");const{animationState:x}=this.visualElement;x&&x.setActive("whileDrag",!0)},o=(h,m)=>{this.latestPointerEvent=h,this.latestPanInfo=m;const{dragPropagation:f,dragDirectionLock:g,onDirectionLock:y,onDrag:x}=this.getProps();if(!f&&!this.openDragLock)return;const{offset:_}=m;if(g&&this.currentDirection===null){this.currentDirection=ovs(_),this.currentDirection!==null&&y&&y(this.currentDirection);return}this.updateAxis("x",m.point,_),this.updateAxis("y",m.point,_),this.visualElement.render(),x&&yh.update(()=>x(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 X5t(t,{onSessionStart:i,onStart:l,onMove:o,onSessionEnd:c,resumeAnimation:d},{transformPagePoint:this.visualElement.getTransformPagePoint(),dragSnapToOrigin:u,distanceThreshold:r,contextWindow:Z5t(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&&yh.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||!Kte(t,a,this.currentDirection))return;const i=this.getAxisMotionValue(t);let l=this.originPoint[t]+r[t];this.constraints&&this.constraints[t]&&(l=Qys(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&&JF(t)?this.constraints||(this.constraints=this.resolveRefConstraints()):t&&r?this.constraints=Jys(r.layoutBox,t):this.constraints=!1,this.elastic=nvs(n),a!==this.constraints&&!JF(t)&&r&&this.constraints&&!this.hasMutatedConstraints&&fk(l=>{this.constraints!==!1&&this.getAxisMotionValue(l)&&(this.constraints[l]=svs(r.layoutBox[l],this.constraints[l]))})}resolveRefConstraints(){const{dragConstraints:t,onMeasureDragConstraints:n}=this.getProps();if(!t||!JF(t))return!1;const r=t.current;$B(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=o0s(r,a.root,this.visualElement.getTransformPagePoint());let l=evs(a.layout.layoutBox,i);if(n){const o=n(r0s(l));this.hasMutatedConstraints=!!o,o&&(l=v5t(o))}return l}startAnimation(t){const{drag:n,dragMomentum:r,dragElastic:a,dragTransition:i,dragSnapToOrigin:l,onDragTransitionEnd:o}=this.getProps(),c=this.constraints||{},d=fk(u=>{if(!Kte(u,n,this.currentDirection))return;let h=c&&c[u]||{};(l===!0||l===u)&&(h={min:0,max:0});const m=a?200:1e6,f=a?40:1e7,g={type:"inertia",velocity:r?t[u]:0,bounceStiffness:m,bounceDamping:f,timeConstant:750,restDelta:1,restSpeed:10,...i,...h};return this.startAxisValueAnimation(u,g)});return Promise.all(d).then(o)}startAxisValueAnimation(t,n){const r=this.getAxisMotionValue(t);return lRe(this.visualElement,t),r.start(MUe(t,r,0,n,this.visualElement,!1))}stopAnimation(){fk(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){fk(n=>{const{drag:r}=this.getProps();if(!Kte(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]-im(l,o,.5)+c)}})}scalePositionWithinConstraints(){if(!this.visualElement.current)return;const{drag:t,dragConstraints:n}=this.getProps(),{projection:r}=this.visualElement;if(!JF(n)||!r||!this.constraints)return;this.stopAnimation();const a={x:0,y:0};fk(l=>{const o=this.getAxisMotionValue(l);if(o&&this.constraints!==!1){const c=o.get();a[l]=tvs({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(),fk(l=>{if(!Kte(l,t,null))return;const o=this.getAxisMotionValue(l),{min:c,max:d}=this.constraints[l];o.set(im(c,d,a[l]))}),this.visualElement.render()}addListeners(){if(!this.visualElement.current)return;rvs.set(this.visualElement,this);const t=this.visualElement.current,n=GW(t,"pointerdown",d=>{const{drag:u,dragListener:h=!0}=this.getProps(),m=d.target,f=m!==t&&Fxs(m);u&&h&&!f&&this.start(d)});let r;const a=()=>{const{dragConstraints:d}=this.getProps();JF(d)&&d.current&&(this.constraints=this.resolveRefConstraints(),r||(r=ivs(t,d.current,()=>this.scalePositionWithinConstraints())))},{projection:i}=this.visualElement,l=i.addEventListener("measure",a);i&&!i.layout&&(i.root&&i.root.updateScroll(),i.updateLayout()),yh.read(a);const o=xY(window,"resize",()=>this.scalePositionWithinConstraints()),c=i.addEventListener("didUpdate",({delta:d,hasLayoutChanged:u})=>{this.isDragging&&u&&(fk(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=xRe,dragMomentum:o=!0}=t;return{...t,drag:n,dragDirectionLock:r,dragPropagation:a,dragConstraints:i,dragElastic:l,dragMomentum:o}}}function Dnt(s){let t=!0;return()=>{if(t){t=!1;return}s()}}function ivs(s,t,n){const r=Ust(s,Dnt(n)),a=Ust(t,Dnt(n));return()=>{r(),a()}}function Kte(s,t,n){return(t===!0||t===s)&&(n===null||n===s)}function ovs(s,t=10){let n=null;return Math.abs(s.y)>t?n="y":Math.abs(s.x)>t&&(n="x"),n}class lvs extends OE{constructor(t){super(t),this.removeGroupControls=fj,this.removeListeners=fj,this.controls=new avs(t)}mount(){const{dragControls:t}=this.node.getProps();t&&(this.removeGroupControls=t.subscribe(this.controls)),this.removeListeners=this.controls.addListeners()||fj}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 K6e=s=>(t,n)=>{s&&yh.update(()=>s(t,n),!1,!0)};class cvs extends OE{constructor(){super(...arguments),this.removePointerDownListener=fj}onPointerDown(t){this.session=new X5t(t,this.createPanHandlers(),{transformPagePoint:this.node.getTransformPagePoint(),contextWindow:Z5t(this.node)})}createPanHandlers(){const{onPanSessionStart:t,onPanStart:n,onPan:r,onPanEnd:a}=this.node.getProps();return{onSessionStart:K6e(t),onStart:K6e(n),onMove:K6e(r),onEnd:(i,l)=>{delete this.session,a&&yh.postRender(()=>a(i,l))}}}mount(){this.removePointerDownListener=GW(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 Y6e=!1;class dvs extends N.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),Y6e&&i.root.didUpdate(),i.addEventListener("animationComplete",()=>{this.safeToRemove()}),i.setOptions({...i.options,layoutDependency:this.props.layoutDependency,onExitComplete:()=>this.safeToRemove()})),Rwe.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}),Y6e=!0,a||t.layoutDependency!==n||n===void 0||t.isPresent!==i?l.willUpdate():this.safeToRemove(),t.isPresent!==i&&(i?l.promote():l.relegate()||yh.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(),RUe.postRender(()=>{!r.currentAnimation&&r.isLead()&&this.safeToRemove()}))}componentWillUnmount(){const{visualElement:t,layoutGroup:n,switchLayoutGroup:r}=this.props,{projection:a}=t;Y6e=!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 J5t(s){const[t,n]=$5t(),r=N.useContext(xUe);return e.jsx(dvs,{...s,layoutGroup:r,switchLayoutGroup:N.useContext(K5t),isPresent:t,safeToRemove:n})}const uvs={pan:{Feature:cvs},drag:{Feature:lvs,ProjectionNode:B5t,MeasureLayout:J5t}};function Rnt(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&&yh.postRender(()=>i(t,zQ(t)))}class hvs extends OE{mount(){const{current:t}=this.node;t&&(this.unmount=Ixs(t,(n,r)=>(Rnt(this.node,r,"Start"),a=>Rnt(this.node,a,"End"))))}unmount(){}}class mvs extends OE{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=RQ(xY(this.node.current,"focus",()=>this.onFocus()),xY(this.node.current,"blur",()=>this.onBlur()))}unmount(){}}function Ont(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&&yh.postRender(()=>i(t,zQ(t)))}class pvs extends OE{mount(){const{current:t}=this.node;if(!t)return;const{globalTapTarget:n,propagate:r}=this.node.props;this.unmount=Bxs(t,(a,i)=>(Ont(this.node,i,"Start"),(l,{success:o})=>Ont(this.node,l,o?"End":"Cancel")),{useGlobalTarget:n,stopPropagation:(r==null?void 0:r.tap)===!1})}unmount(){}}const yRe=new WeakMap,Z6e=new WeakMap,fvs=s=>{const t=yRe.get(s.target);t&&t(s)},gvs=s=>{s.forEach(fvs)};function xvs({root:s,...t}){const n=s||document;Z6e.has(n)||Z6e.set(n,{});const r=Z6e.get(n),a=JSON.stringify(t);return r[a]||(r[a]=new IntersectionObserver(gvs,{root:s,...t})),r[a]}function yvs(s,t,n){const r=xvs(t);return yRe.set(s,n),r.observe(s),()=>{yRe.delete(s),r.unobserve(s)}}const vvs={some:0,all:1};class bvs extends OE{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:vvs[a]},o=d=>{const{isIntersecting:u}=d;if(this.isInView===u||(this.isInView=u,i&&!u&&this.hasEnteredView))return;u&&(this.hasEnteredView=!0),this.node.animationState&&this.node.animationState.setActive("whileInView",u);const{onViewportEnter:h,onViewportLeave:m}=this.node.getProps(),f=u?h:m;f&&f(d)};this.stopObserver=yvs(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(_vs(t,n))&&this.startObserver()}unmount(){var t;(t=this.stopObserver)==null||t.call(this),this.hasEnteredView=!1,this.isInView=!1}}function _vs({viewport:s={}},{viewport:t={}}={}){return n=>s[n]!==t[n]}const wvs={inView:{Feature:bvs},tap:{Feature:pvs},focus:{Feature:mvs},hover:{Feature:hvs}},jvs={layout:{ProjectionNode:B5t,MeasureLayout:J5t}},Nvs={...Wys,...wvs,...uvs,...jvs},Sr=Uys(Nvs,qys),kvs={some:0,all:1};function Svs(s,t,{root:n,margin:r,amount:a="some"}={}){const i=DUe(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:kvs[a]});return i.forEach(d=>c.observe(d)),()=>c.disconnect()}function Cvs(s,{root:t,margin:n,amount:r,once:a=!1,initial:i=!1}={}){const[l,o]=N.useState(i);return N.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 Svs(s.current,c,d)},[t,s,n,a,r]),l}function Avs(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 Fnt(s){return s.visitor_intent==="buying"&&!s.has_agent}function Tvs({token:s}={}){var g;const t=uo(),n=s||t.token,{data:r,isLoading:a,isError:i}=mfs(n),l=as(),o=(g=r==null?void 0:r.open_houses)==null?void 0:g.id,{data:c}=mt({queryKey:["cohost-visitors",o],queryFn:async()=>{const{data:y,error:x}=await H.from("open_house_visitors").select("*").eq("open_house_id",o).order("created_at",{ascending:!1});if(x)throw x;return y},enabled:!!o});if(N.useEffect(()=>{if(!o)return;const y=H.channel(`cohost-visitors-${o}`).on("postgres_changes",{event:"INSERT",schema:"public",table:"open_house_visitors",filter:`open_house_id=eq.${o}`},()=>{l.invalidateQueries({queryKey:["cohost-visitors",o]})}).subscribe();return()=>{H.removeChannel(y)}},[o,l]),a)return e.jsx("div",{className:"min-h-screen bg-gradient-to-br from-slate-950 via-slate-900 to-slate-950 flex items-center justify-center",children:e.jsx("div",{className:"animate-pulse text-white/40",children:"Validating access..."})});if(i||!r)return e.jsx("div",{className:"min-h-screen bg-gradient-to-br from-slate-950 via-slate-900 to-slate-950 flex items-center justify-center p-6",children:e.jsxs("div",{className:"text-center text-white",children:[e.jsx("h1",{className:"text-xl font-bold mb-2",children:"Link Expired or Invalid"}),e.jsx("p",{className:"text-white/40 text-sm",children:"This co-host link is no longer active. Ask the host for a new one."})]})});const d=r.open_houses,u=(c==null?void 0:c.length)||0,h=(c==null?void 0:c.filter(y=>y.visitor_intent==="buying").length)||0,m=(c==null?void 0:c.filter(Fnt).length)||0,f=y=>{if(!y)return"";const[x,_]=y.split(":"),b=parseInt(x);return`${b>12?b-12:b||12}:${_} ${b>=12?"PM":"AM"}`};return e.jsxs("div",{className:"fixed inset-0 bg-gradient-to-br from-slate-950 via-slate-900 to-slate-950 flex flex-col",children:[e.jsxs("div",{className:"border-b border-white/10 px-4 sm:px-6 py-3 flex items-center justify-between bg-black/30 backdrop-blur-xl",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"w-2 h-2 rounded-full bg-emerald-400 animate-pulse"}),e.jsx("span",{className:"text-xs font-medium text-emerald-400 uppercase tracking-wider",children:"Live · Co-Host View"})]}),e.jsx("h1",{className:"text-white font-bold text-sm sm:text-base truncate",children:d.property_address})]}),e.jsxs("div",{className:"flex items-center gap-4 sm:gap-6 text-white/70",children:[e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(Yn,{className:"h-4 w-4"}),e.jsx("span",{className:"font-bold text-white",children:u})]}),e.jsxs("div",{className:"flex items-center gap-1.5 text-orange-400",children:[e.jsx(Cu,{className:"h-4 w-4"}),e.jsx("span",{className:"font-bold text-white",children:m})]}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(_a,{className:"h-4 w-4"}),e.jsx("span",{className:"font-bold text-white",children:h})]})]})]}),e.jsxs("div",{className:"px-4 sm:px-6 py-2 flex items-center gap-4 text-xs text-white/40 border-b border-white/5",children:[e.jsx("span",{children:Js(new Date(d.event_date+"T00:00:00"),"EEEE, MMMM d, yyyy")}),d.start_time&&e.jsxs("span",{children:[f(d.start_time),d.end_time?` – ${f(d.end_time)}`:""]})]}),e.jsx(lo,{className:"flex-1 p-4 sm:p-6",children:c!=null&&c.length?e.jsx("div",{className:"space-y-2 max-w-3xl mx-auto",children:e.jsx($4e,{children:c.map((y,x)=>{var k;const _=Avs(y.visitor_intent),b=Fnt(y);return e.jsxs(Sr.div,{initial:{opacity:0,x:-40,scale:.95},animate:{opacity:1,x:0,scale:1},transition:{duration:.4,delay:x*.05},className:`flex items-center gap-4 p-4 rounded-xl border ${b?"bg-orange-500/10 border-orange-500/30":"bg-white/5 border-white/10"}`,children:[e.jsx("div",{className:`w-11 h-11 rounded-full flex items-center justify-center text-lg font-bold shrink-0 ${b?"bg-gradient-to-br from-orange-500 to-amber-500 text-white":"bg-white/10 text-white/80"}`,children:(k=y.first_name[0])==null?void 0:k.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:[y.first_name," ",y.last_name||""]}),b&&e.jsx(We,{className:"bg-orange-500/20 text-orange-300 border-orange-500/40 text-[10px] px-1.5 py-0",children:"🔥 HOT"}),y.has_agent&&e.jsx(We,{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(We,{variant:"outline",className:`text-[10px] px-1.5 py-0 ${_.color}`,children:[_.emoji," ",_.label]}),e.jsx("span",{className:"text-white/30 text-xs",children:Js(new Date(y.created_at),"h:mm a")})]})]})]},y.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(Y0,{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 Evs(){const t=Id().pathname.slice(1);if(N.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(Tvs,{token: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(tkt,{slug:t})}function Mvs({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(_a,{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(ii,{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(ga,{className:"w-4 h-4"}),e.jsx("span",{className:"text-sm font-medium",children:"Call"})]}),t.email&&e.jsxs("a",{href:`mailto:${t.email}`,className:"flex-1 flex items-center justify-center gap-2 px-3 py-2.5 rounded-xl transition-colors",style:{background:"hsl(var(--portal-gold) / 0.06)",color:"var(--portal-hero-accent)",border:"1px solid hsl(var(--portal-gold) / 0.15)"},children:[e.jsx(mn,{className:"w-4 h-4"}),e.jsx("span",{className:"text-sm font-medium",children:"Email"})]}),t.phone&&e.jsxs("a",{href:`sms:${t.phone}`,className:"flex-1 flex items-center justify-center gap-2 px-3 py-2.5 rounded-xl transition-colors",style:{background:"hsl(var(--portal-gold) / 0.06)",color:"var(--portal-hero-accent)",border:"1px solid hsl(var(--portal-gold) / 0.15)"},children:[e.jsx(Ud,{className:"w-4 h-4"}),e.jsx("span",{className:"text-sm font-medium",children:"Text"})]})]})})})]})}function eSt({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=wj(a,new Date);if(x5(a)&&!O0(a))return null;const o=O0(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 tSt({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 Tc(s){const t=s.split(/[-/T]/);if(t.length>=3){const n=Number(t[0]);return n>99?new Date(n,Number(t[1])-1,Number(t[2])):new Date(Number(t[2]),Number(t[0])-1,Number(t[1]))}return new Date(`${s}T12:00:00`)}const Lvs=[{key:"contract_date",label:"Contract Accepted",icon:e3},{key:"earnest_money_due_date",label:"Earnest Money",icon:Ed},{key:"inspection_date",label:"Inspection",icon:Gr},{key:"inspection_contingency_date",label:"Inspection Deadline",icon:Wr},{key:"appraisal_date",label:"Appraisal",icon:_a},{key:"loan_approval_date",label:"Loan Approval",icon:eW},{key:"title_docs_due_date",label:"Title & Disclosures",icon:Wr},{key:"final_walkthrough_date",label:"Final Walkthrough",icon:TT},{key:"target_close_date",label:"Target Close",icon:ta}];function Pvs(s,t){const n=Js(t,"yyyyMMdd");return`https://calendar.google.com/calendar/render?${new URLSearchParams({action:"TEMPLATE",text:s,dates:`${n}/${n}`,details:"Added from your Client Portal"}).toString()}`}function Ivs(s,t){const n=Js(t,"yyyyMMdd");return`data:text/calendar;charset=utf-8,${encodeURIComponent(`BEGIN:VCALENDAR VERSION:2.0 BEGIN:VEVENT DTSTART;VALUE=DATE:${n} DTEND;VALUE=DATE:${n} SUMMARY:${s} DESCRIPTION:Added from your Client Portal END:VEVENT END:VCALENDAR`)}`}function nSt({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=Lvs.map(f=>f.key==="target_close_date"&&c?{...f,label:"Closed",date:c,done:!0}:{...f,date:o[f.key],done:d.includes(f.key)}).filter(f=>!!f.date);if(u.length===0)return null;const h=(f,g,y)=>{const x=Tc(g);if(y==="google")window.open(Pvs(f,x),"_blank");else{const _=Ivs(f,x),b=document.createElement("a");b.href=_,b.download=`${f.replace(/\s+/g,"-").toLowerCase()}.ics`,b.click()}},m=u.filter(f=>f.done).length;return e.jsxs("div",{children:[e.jsx("p",{className:"portal-eyebrow mb-2",children:"Milestones"}),e.jsxs("div",{className:"flex items-baseline justify-between gap-3 mb-5 flex-wrap",children:[e.jsx("h2",{className:"portal-serif text-2xl",style:{color:"hsl(var(--portal-ink))"},children:"Key dates"}),e.jsxs("span",{className:"text-[11px] tracking-[0.18em] uppercase",style:{color:"hsl(var(--portal-ink-dim))"},children:[m," of ",u.length," complete"]})]}),e.jsxs("div",{className:"space-y-4 relative",children:[e.jsx("div",{className:"absolute left-[10px] top-2 bottom-2 w-[1px]",style:{background:"hsl(var(--portal-gold) / 0.18)"}}),u.map(({label:f,date:g,done:y,icon:x})=>{const _=Tc(g),b=x5(_)&&!O0(_),k=O0(_),A=!b&&!k,T=y?"Completed":k?"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))":k?"hsl(var(--portal-gold) / 0.25)":"hsl(var(--portal-surface-2))",border:"1px solid hsl(var(--portal-gold) / 0.7)",boxShadow:k?"0 0 12px hsl(var(--portal-gold) / 0.5)":"none"},children:y?e.jsx(pa,{className:"w-3 h-3",style:{color:"hsl(var(--portal-surface))"}}):e.jsx(x,{className:"w-3 h-3",style:{color:"hsl(var(--portal-gold))"}})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-[10px] tracking-[0.22em] uppercase",style:{color:"hsl(var(--portal-ink-dim))"},children:f}),e.jsx("p",{className:"portal-serif mt-0.5",style:{fontSize:"1.15rem",color:y?"hsl(var(--portal-ink-muted))":"hsl(var(--portal-ink))"},children:Js(_,"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||k?"hsl(var(--portal-gold))":"hsl(var(--portal-ink-dim))",border:`1px solid hsl(var(--portal-gold) / ${y||k?.5:.18})`},children:T})]}),A&&e.jsxs("div",{className:"flex items-center gap-1 mt-1",children:[e.jsx("button",{onClick:()=>h(f,g,"google"),className:"p-1.5 rounded transition-colors",style:{color:"hsl(var(--portal-ink-dim))"},onMouseEnter:P=>{P.currentTarget.style.color="hsl(var(--portal-gold))"},onMouseLeave:P=>{P.currentTarget.style.color="hsl(var(--portal-ink-dim))"},title:"Add to Google Calendar",children:e.jsx(Pv,{className:"w-3.5 h-3.5"})}),e.jsx("button",{onClick:()=>h(f,g,"apple"),className:"text-[9px] tracking-widest px-1.5 py-1 rounded",style:{color:"hsl(var(--portal-ink-dim))"},title:"Download .ics",children:".ICS"})]})]},f)})]})]})}function rSt({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 H.storage.from("deal-files").createSignedUrl(r.storage_path,300);a!=null&&a.signedUrl&&window.open(a.signedUrl,"_blank")};return e.jsxs("div",{children:[e.jsx("p",{className:"portal-eyebrow mb-2",children:"Paperwork"}),e.jsx("h2",{className:"portal-serif text-2xl mb-5",style:{color:"hsl(var(--portal-ink))"},children:"Documents"}),e.jsx("div",{className:"space-y-2",children:s.map(r=>e.jsxs("button",{onClick:()=>n(r),className:"w-full flex items-center gap-3 p-3 rounded-xl transition-all text-left group",style:{background:"hsl(var(--portal-surface-2))",border:"1px solid hsl(var(--portal-gold) / 0.08)"},onMouseEnter:a=>{a.currentTarget.style.borderColor="hsl(var(--portal-gold) / 0.35)"},onMouseLeave:a=>{a.currentTarget.style.borderColor="hsl(var(--portal-gold) / 0.08)"},children:[e.jsx("div",{className:"w-10 h-10 rounded-lg flex items-center justify-center flex-shrink-0",style:{background:"hsl(var(--portal-gold) / 0.08)",border:"1px solid hsl(var(--portal-gold) / 0.2)"},children:e.jsx(Wr,{className:"w-4 h-4",style:{color:"hsl(var(--portal-gold))"}})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-sm portal-serif truncate",style:{color:"hsl(var(--portal-ink))",fontSize:"1rem"},children:r.file_name}),e.jsx("p",{className:"text-[10px] tracking-widest uppercase mt-0.5",style:{color:"hsl(var(--portal-ink-dim))"},children:t(r.file_size)})]}),e.jsx(oi,{className:"w-4 h-4 flex-shrink-0",style:{color:"hsl(var(--portal-gold) / 0.5)"}})]},r.id))})]})}function aSt({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(mg,{className:"w-3.5 h-3.5",style:{color:"hsl(var(--portal-gold))"}}):e.jsx(yg,{className:"w-3.5 h-3.5",style:{color:"hsl(var(--portal-gold))"}})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-baseline justify-between gap-2",children:[e.jsx("h3",{className:"portal-serif",style:{fontSize:r===0?"1.4rem":"1.15rem",color:"hsl(var(--portal-ink))"},children:n.title}),e.jsx("span",{className:"text-[10px] tracking-[0.2em] uppercase flex-shrink-0",style:{color:"hsl(var(--portal-ink-dim))"},children:Js(new Date(n.created_at),"MMM d")})]}),n.content&&e.jsx("p",{className:`text-sm mt-2 leading-relaxed ${r===0?"italic portal-serif":""}`,style:{color:"hsl(var(--portal-ink-muted))",fontSize:r===0?"1rem":"0.875rem"},children:r===0?`“${n.content}”`:n.content}),n.video_url&&e.jsx("div",{className:"mt-3 rounded-xl overflow-hidden aspect-video",style:{background:"hsl(var(--portal-bg))",border:"1px solid hsl(var(--portal-gold) / 0.15)"},children:e.jsx("iframe",{src:t(n.video_url)||n.video_url,className:"w-full h-full",allow:"accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture",allowFullScreen:!0,title:n.title})})]})]})},n.id))})]})}const _e=N.forwardRef(({className:s,...t},n)=>e.jsx("div",{ref:n,className:Ot("rounded-lg border bg-card text-card-foreground shadow-sm",s),...t}));_e.displayName="Card";const zt=N.forwardRef(({className:s,...t},n)=>e.jsx("div",{ref:n,className:Ot("flex flex-col space-y-1.5 p-6",s),...t}));zt.displayName="CardHeader";const qt=N.forwardRef(({className:s,...t},n)=>e.jsx("h3",{ref:n,className:Ot("text-2xl font-semibold leading-none tracking-tight",s),...t}));qt.displayName="CardTitle";const _r=N.forwardRef(({className:s,...t},n)=>e.jsx("p",{ref:n,className:Ot("text-sm text-muted-foreground",s),...t}));_r.displayName="CardDescription";const De=N.forwardRef(({className:s,...t},n)=>e.jsx("div",{ref:n,className:Ot("p-6 pt-0",s),...t}));De.displayName="CardContent";const WW=N.forwardRef(({className:s,...t},n)=>e.jsx("div",{ref:n,className:Ot("flex items-center p-6 pt-0",s),...t}));WW.displayName="CardFooter";const mU=[{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"}],Dvs=[{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 Rvs(s){return mt({queryKey:["vendors","brokerage",s],queryFn:async()=>{if(!s)return[];const{data:t,error:n}=await H.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 Ovs(){const s=Ya(),{brokerageId:t}=Ls();return mt({queryKey:["vendors","library",s,t],queryFn:async()=>{if(!s)return{vendors:[],selections:[]};let n=H.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}),H.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 Fvs(){const s=as();return _t({mutationFn:async t=>{if(t.id){const{id:n,created_at:r,...a}=t,{data:i,error:l}=await H.from("vendors").update(a).eq("id",n).select().single();if(l)throw l;return i}else{const{data:n,error:r}=await H.from("vendors").insert(t).select().single();if(r)throw r;return n}},onSuccess:()=>s.invalidateQueries({queryKey:["vendors"]})})}function iSt(){const s=as();return _t({mutationFn:async t=>{const{error:n}=await H.from("vendors").delete().eq("id",t);if(n)throw n},onSuccess:()=>s.invalidateQueries({queryKey:["vendors"]})})}function zvs(){const s=Ya(),t=as();return _t({mutationFn:async({vendorId:n,isVisible:r})=>{if(!s)throw new Error("No user");const{data:a}=await H.from("agent_vendor_selections").select("id").eq("agent_user_id",s).eq("vendor_id",n).maybeSingle();if(a){const{error:i}=await H.from("agent_vendor_selections").update({is_visible:r}).eq("id",a.id);if(i)throw i}else{const{error:i}=await H.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 oSt(s){return mt({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 H.from("profiles").select("brokerage_id").eq("id",t).maybeSingle(),r=n==null?void 0:n.brokerage_id,a=H.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}),H.from("agent_vendor_selections").select("vendor_id, display_order, is_visible").eq("agent_user_id",t),H.from("portal_vendor_overrides").select("vendor_id, is_visible").eq("portal_id",s.id)]);if(o)throw o;const u=new Map;(c||[]).forEach(f=>u.set(f.vendor_id,{display_order:f.display_order,is_visible:f.is_visible}));const h=new Map;return(d||[]).forEach(f=>h.set(f.vendor_id,f.is_visible)),(l||[]).filter(f=>{if(h.get(f.id)===!1)return!1;const g=u.get(f.id);return!(g&&g.is_visible===!1&&!f.is_required)}).map(f=>{var g;return{...f,display_order:((g=u.get(f.id))==null?void 0:g.display_order)??f.sort_order??0}}).sort((f,g)=>(f.display_order||0)-(g.display_order||0))},enabled:!!(s!=null&&s.id)&&!!(s!=null&&s.owner_user_id)})}async function znt(s){try{await H.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 lSt(s,t){return mt({queryKey:["vendor-clicks",s,t],queryFn:async()=>{if(!t)return{};const{data:n}=await H.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 H.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 cSt({portalId:s,ownerUserId:t,currentStage:n,brandingColor:r,layout:a="list"}){const{data:i=[],isLoading:l}=oSt({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,k)=>{switch(k){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 k=d(b,b.action_type);znt({vendorId:b.id,portalId:s,agentUserId:t,actionTaken:b.action_type}),k&&window.open(k,b.action_type==="call"||b.action_type==="email"||b.action_type==="quote"?"_self":"_blank")},h=b=>{const k=d(b,b.action_type);return[{action:"website",label:"Website",icon:e.jsx(au,{className:"w-3.5 h-3.5"})},{action:"email",label:"Email",icon:e.jsx(mn,{className:"w-3.5 h-3.5"})},{action:"call",label:"Call",icon:e.jsx(ga,{className:"w-3.5 h-3.5"})},{action:"book",label:"Book",icon:e.jsx(ta,{className:"w-3.5 h-3.5"})}].filter(T=>T.action!==b.action_type).map(T=>{const P=d(b,T.action);return!P||P===k?null:e.jsxs("button",{onClick:()=>{znt({vendorId:b.id,portalId:s,agentUserId:t,actionTaken:T.action}),window.open(P,T.action==="call"||T.action==="email"?"_self":"_blank")},className:"inline-flex items-center gap-1 text-slate-500 hover:text-slate-700 hover:underline",title:T.label,children:[T.icon,e.jsx("span",{className:"text-xs",children:T.label})]},T.action)}).filter(Boolean)},m=b=>{switch(b.action_type){case"book":return"Book Now";case"quote":return"Request Quote";case"call":return"Call";case"email":return"Email";case"website":return"Visit Site"}},f=b=>{switch(b.action_type){case"book":return e.jsx(ta,{className:"w-3.5 h-3.5"});case"call":return e.jsx(ga,{className:"w-3.5 h-3.5"});case"email":case"quote":return e.jsx(mn,{className:"w-3.5 h-3.5"});case"website":return e.jsx(au,{className:"w-3.5 h-3.5"})}},g=b=>{var k;return((k=mU.find(A=>A.value===b))==null?void 0:k.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(Cn,{className:"w-4 h-4"})}),e.jsxs("div",{children:[e.jsx("h2",{className:"font-semibold text-slate-800",children:"Trusted Partners"}),e.jsx("p",{className:"text-xs text-slate-500",children:"My personally-vetted recommendations for you"})]})]}),x=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(_e,{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:g(b.category)})]})]}),b.description&&e.jsx("p",{className:"text-xs text-slate-500 mt-3 line-clamp-2",children:b.description}),e.jsxs("div",{className:"mt-auto pt-4 flex flex-col gap-2",children:[e.jsxs(B,{size:"sm",onClick:()=>u(b),style:{backgroundColor:c},className:"text-white hover:opacity-90 w-full",children:[f(b),e.jsx("span",{className:"ml-1.5 text-xs",children:m(b)})]}),h(b).length>0&&e.jsx("div",{className:"flex flex-wrap items-center justify-center gap-3",children:h(b)})]})]},b.id))}),x]});const _=o.reduce((b,k)=>((b[k.category]=b[k.category]||[]).push(k),b),{});return e.jsxs(_e,{className:"p-5 rounded-2xl border-slate-200/80 shadow-sm",children:[y,e.jsx("div",{className:"space-y-4",children:Object.entries(_).map(([b,k])=>e.jsxs("div",{children:[e.jsx("p",{className:"text-[11px] uppercase tracking-wide text-slate-400 font-medium mb-2",children:g(b)}),e.jsx("div",{className:"space-y-2",children:k.map(A=>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:A.logo_url?e.jsx("img",{src:A.logo_url,alt:A.name,className:"w-full h-full object-cover"}):e.jsx("span",{className:"text-sm font-semibold text-slate-500",children:A.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:A.company||A.name}),A.company&&A.name&&e.jsx("p",{className:"text-xs text-slate-500 truncate",children:A.name}),A.description&&e.jsx("p",{className:"text-xs text-slate-500 truncate mt-0.5",children:A.description})]}),e.jsxs(B,{size:"sm",onClick:()=>u(A),style:{backgroundColor:c},className:"text-white hover:opacity-90 shrink-0",children:[f(A),e.jsx("span",{className:"ml-1.5 text-xs",children:m(A)})]})]},A.id))})]},b))}),x]})}function Bvs(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 $vs(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 dSt({portalId:s,portalSlug:t,ownerUserId:n,rewardText:r,ctaHeadline:a,agentName:i,clientName:l,reviewUrl:o,hubVideoUrl:c}){const[d,u]=N.useState(!1),h=N.useRef(!1),m=Bvs(t);N.useEffect(()=>{h.current||(h.current=!0,H.from("portal_referral_clicks").insert({portal_id:s,owner_user_id:n,click_type:"card_view",user_agent:navigator.userAgent.slice(0,500)}).then(()=>{}))},[s,n]);const f=async P=>{await H.from("portal_referral_clicks").insert({portal_id:s,owner_user_id:n,click_type:P,user_agent:navigator.userAgent.slice(0,500)})},g=()=>`${l?`Hey, it's ${l}!`:"Hey!"} I just had an amazing experience working with ${i||"my real estate agent"} on my home. If you or someone you know is thinking about buying or selling, here's their referral link: ${m}`,y=async()=>{await navigator.clipboard.writeText(m),u(!0),f("copy_link"),setTimeout(()=>u(!1),2e3)},x=()=>{f("share_sms");const P=encodeURIComponent(g());window.location.href=`sms:?&body=${P}`},_=()=>{f("share_email");const P=encodeURIComponent("A referral you'll thank me for"),I=encodeURIComponent(g());window.location.href=`mailto:?subject=${P}&body=${I}`},b=()=>{f("open_form"),window.open(m,"_blank")},k=a||"Know someone buying or selling?",A=c?$vs(c):null,T=A==null?void 0:A.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."})]}),A&&e.jsxs("div",{className:"bg-white rounded-2xl border border-slate-100 shadow-sm overflow-hidden",children:[e.jsx("div",{className:"px-4 pt-4 pb-2",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Cn,{className:"w-4 h-4 text-[#406E71]"}),e.jsxs("p",{className:"text-sm font-medium text-slate-700",children:["A message from ",i||"your agent"]})]})}),e.jsx("div",{className:"aspect-video bg-slate-900",children:T?e.jsx("video",{src:A,controls:!0,className:"w-full h-full",playsInline:!0}):e.jsx("iframe",{src:A,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(Io,{className:"w-3 h-3"}),"Referral Program"]}),e.jsx("h3",{className:"text-xl font-bold leading-tight mb-2 font-serif",children:k}),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(vi,{className:"w-4 h-4"})]}),e.jsxs("div",{className:"mt-4 grid grid-cols-3 gap-2",children:[e.jsxs("button",{onClick:x,className:"flex items-center justify-center gap-1.5 bg-white/10 hover:bg-white/20 backdrop-blur-sm rounded-lg py-2.5 text-xs font-medium transition-colors",children:[e.jsx(Ud,{className:"w-3.5 h-3.5"}),"Text"]}),e.jsxs("button",{onClick:_,className:"flex items-center justify-center gap-1.5 bg-white/10 hover:bg-white/20 backdrop-blur-sm rounded-lg py-2.5 text-xs font-medium transition-colors",children:[e.jsx(mn,{className:"w-3.5 h-3.5"}),"Email"]}),e.jsxs("button",{onClick: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(pa,{className:"w-3.5 h-3.5"}):e.jsx(Pa,{className:"w-3.5 h-3.5"}),d?"Copied":"Copy"]})]})]})]}),o&&e.jsx("a",{href:o,target:"_blank",rel:"noopener noreferrer",onClick:()=>f("review_click"),className:"block bg-white border border-slate-200 hover:border-amber-300 hover:bg-amber-50/30 rounded-2xl p-4 transition-colors",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"text-2xl",children:"⭐"}),e.jsxs("div",{className:"flex-1",children:[e.jsx("p",{className:"text-sm font-semibold text-slate-800",children:"Loved working together?"}),e.jsx("p",{className:"text-xs text-slate-500",children:"Leave a quick review — it means the world."})]}),e.jsx(vi,{className:"w-4 h-4 text-slate-400"})]})})]})}function Uvs(s){return s==="buy-side"?"Home Search in Progress":s==="listing"?"Your Home Is On The Market":"Active Phase"}function qvs(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 Vvs={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. 🎉"}},uSt=["Lead","Consultation","Agreement Signed","Active","Under Contract","Closing","Closed Won"];function q4e(s){return uSt.map(t=>{if(t==="Active")return{key:"Active",label:Uvs(s),description:qvs(s)};const n=Vvs[t];return{key:t,label:n.label,description:n.description}})}function aNe(s){if(!s)return 0;const t=uSt.indexOf(s);return t>=0?t:0}function Hvs({portal:s,linkedPortal:t,activePortal:n,activeTab:r,onTabChange:a,agentProfile:i,branding:l,updates:o,documents:c}){var X,te,ne;const d=(l==null?void 0:l.cover_photo_url)||null,u=(l==null?void 0:l.logo_url)||null,h=(l==null?void 0:l.tagline)||"Your Real Estate Concierge",m=n==null?void 0:n.deal_pipeline,f=m==null?void 0:m.deal_pipeline_stages,g=f==null?void 0:f.is_won_stage,y=m==null?void 0:m.deal_type,x=n==null?void 0:n.stage_mapping;let _=q4e(y);x&&x.length>0&&(_=x.map((me,ue)=>{var ce,ae;return{key:`custom-${ue}`,label:me.label||((ce=_[ue])==null?void 0:ce.label)||`Stage ${ue+1}`,description:me.description||((ae=_[ue])==null?void 0:ae.description)||"",video_url:me.video_url||void 0}}));const b=x&&x.length>0?Math.min(aNe(f==null?void 0:f.name),_.length-1):aNe(f==null?void 0:f.name),k=_[b],A=k==null?void 0:k.video_url,T=g&&n.show_post_close_tips!==!1&&n.referral_enabled!==!1,P=m!=null&&m.property_address?`${m.property_address}, ${m.city||""}, ${m.state||""}`.replace(/,\s*,/g,",").replace(/,\s*$/,""):null,I=!!t,M=(X=s==null?void 0:s.deal_pipeline)==null?void 0:X.deal_type,L=(te=t==null?void 0:t.deal_pipeline)==null?void 0:te.deal_type,z=me=>me==="listing"?"Your Sale":me==="buy-side"?"Your Purchase":"Transaction",$=_.length>1?Math.round((b+1)/_.length*100):0,{data:V=[]}=oSt({id:n==null?void 0:n.id,owner_user_id:n==null?void 0:n.owner_user_id}),W=V.some(me=>!me.stage_filter||me.stage_filter.length===0||!(f!=null&&f.name)?!0:me.stage_filter.includes(f.name)),G=()=>{var me;(me=document.getElementById("trusted-vendors"))==null||me.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(mf,{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(_a,{className:"w-3 h-3"}),y==="listing"?"Sale":y==="buy-side"?"Purchase":"Transaction",g&&e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"opacity-50 mx-1",children:"·"}),"Complete"]})]}),e.jsx("h1",{className:"portal-serif leading-[0.95] mb-4",style:{fontSize:"4.5rem",color:"var(--portal-hero-ink)",textShadow:"var(--portal-hero-text-shadow)"},children:(m==null?void 0:m.deal_name)||"Your Transaction"}),e.jsx("div",{className:"portal-hairline w-32 mb-5"}),P&&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(ii,{className:"w-4 h-4",style:{color:"var(--portal-hero-accent)"}}),e.jsx("span",{className:"text-base",children:P})]}),(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(Gvs,{pct:$}),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 ",_.length]})]})]}),e.jsx("div",{className:"absolute bottom-0 left-0 right-0 h-[1px]",style:{background:"linear-gradient(90deg, transparent, hsl(var(--portal-gold) / 0.4), transparent)"}})]}),I&&e.jsx("div",{className:"inline-flex gap-1 rounded-xl p-1 mb-8",style:{background:"hsl(var(--portal-surface))",border:"1px solid hsl(var(--portal-gold) / 0.15)"},children:["primary","linked"].map(me=>{const ue=me==="primary"?M:L,ce=r===me;return e.jsx("button",{onClick:()=>a(me),className:"portal-serif px-5 py-2 rounded-lg transition-all",style:{fontSize:"1rem",background:ce?"hsl(var(--portal-surface-3))":"transparent",color:ce?"hsl(var(--portal-gold))":"hsl(var(--portal-ink-muted))",borderBottom:ce?"1px solid hsl(var(--portal-gold))":"1px solid transparent"},children:z(ue)},me)})}),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(bC,{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:((ne=i==null?void 0:i.name)==null?void 0:ne.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(X6e,{href:`tel:${i.phone}`,icon:ga,label:"Call",sub:i.phone}),(i==null?void 0:i.phone)&&e.jsx(X6e,{href:`sms:${i.phone}`,icon:Ud,label:"Text message"}),(i==null?void 0:i.email)&&e.jsx(X6e,{href:`mailto:${i.email}`,icon:mn,label:"Email",sub:i.email})]})]}),e.jsxs(bC,{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(Q6e,{icon:ta,label:"Target close",value:Bnt(m.target_close_date)}),(m==null?void 0:m.contract_date)&&e.jsx(Q6e,{icon:Xr,label:"Under contract",value:Bnt(m.contract_date)}),e.jsx(Q6e,{icon:Xo,label:"Progress",value:`${$}%`})]})]})]})}),e.jsxs("main",{className:"col-span-6 space-y-5",children:[T&&e.jsx(dSt,{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(eSt,{targetCloseDate:m==null?void 0:m.target_close_date,actualCloseDate:m==null?void 0:m.actual_close_date,clientName:n.client_name}),k&&e.jsx(bC,{children:e.jsx(sSt,{currentStage:k,nextStepText:n.next_step_text,nextStepVideoUrl:A||n.next_step_video_url})}),e.jsx(bC,{children:e.jsx(tSt,{journeyStages:_,currentIndex:b})}),o&&o.length>0&&e.jsx(bC,{children:e.jsx(aSt,{updates:o})})]}),e.jsxs("aside",{className:"col-span-3 space-y-5",children:[e.jsx(bC,{children:e.jsx(nSt,{deal:m,portal:n})}),c&&c.length>0&&e.jsx(bC,{children:e.jsx(rSt,{documents:c})}),W&&e.jsx(bC,{children:e.jsxs("button",{onClick:G,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:me=>{me.currentTarget.style.background="hsl(var(--portal-gold) / 0.12)"},onMouseLeave:me=>{me.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(wW,{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(Xo,{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(cSt,{portalId:n.id,ownerUserId:n.owner_user_id,currentStage:f==null?void 0:f.name,brandingColor:"hsl(var(--portal-gold))",layout:"grid"})})]})]})}function bC({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 X6e({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 Q6e({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 Gvs({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 Bnt(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 Wvs({portal:s,dealData:t,agentProfile:n,customQuestions:r,deviceFingerprint:a,onComplete:i}){var x,_;const[l,o]=N.useState({first_name:((x=s.client_name)==null?void 0:x.split(" ")[0])||"",last_name:((_=s.client_name)==null?void 0:_.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]=N.useState({}),[u,h]=N.useState(!1),m=_t({mutationFn:async()=>{const{error:b}=await H.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),ie.error("Something went wrong. Please try again.")}}),f=t!=null&&t.property_address?`${t.property_address}, ${t.city||""}, ${t.state||""}`:null,g="mt-1 rounded-xl bg-white text-slate-900 placeholder:text-slate-400 border-slate-200 focus-visible:ring-slate-400",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"}),f&&e.jsxs("div",{className:"flex items-center justify-center gap-1 text-slate-500 text-sm mt-1",children:[e.jsx(ii,{className:"w-3.5 h-3.5"}),e.jsx("span",{children:f.replace(/,\s*,/g,",").replace(/,\s*$/,"")})]}),e.jsx("p",{className:"text-sm text-slate-600 mt-2",children:"Please fill in your details to access your transaction portal."})]}),e.jsxs("form",{onSubmit:b=>{b.preventDefault(),m.mutate()},className:"space-y-4",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(re,{className:"text-xs font-medium text-slate-700",children:"First Name *"}),e.jsx(we,{required:!0,value:l.first_name,onChange:b=>o(k=>({...k,first_name:b.target.value})),className:g,placeholder:"John"})]}),e.jsxs("div",{children:[e.jsx(re,{className:"text-xs font-medium text-slate-700",children:"Last Name"}),e.jsx(we,{value:l.last_name,onChange:b=>o(k=>({...k,last_name:b.target.value})),className:g,placeholder:"Doe"})]})]}),e.jsxs("div",{children:[e.jsx(re,{className:"text-xs font-medium text-slate-700",children:"Email"}),e.jsx(we,{type:"email",value:l.email,onChange:b=>o(k=>({...k,email:b.target.value})),className:g,placeholder:"john@example.com"})]}),e.jsxs("div",{children:[e.jsx(re,{className:"text-xs font-medium text-slate-700",children:"Phone"}),e.jsx(we,{type:"tel",value:l.phone,onChange:b=>o(k=>({...k,phone:b.target.value})),className:g,placeholder:"(555) 123-4567"})]}),e.jsxs("div",{children:[e.jsx(re,{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(k=>({...k,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(re,{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(k=>({...k,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(re,{className:"text-xs font-medium text-slate-700",children:[b.question_text," ",b.is_required&&"*"]}),b.field_type==="text"&&e.jsx(we,{required:b.is_required,value:c[b.id]||"",onChange:k=>d(A=>({...A,[b.id]:k.target.value})),className:g}),b.field_type==="textarea"&&e.jsx("textarea",{required:b.is_required,value:c[b.id]||"",onChange:k=>d(A=>({...A,[b.id]:k.target.value})),className:`${y} min-h-[80px]`}),b.field_type==="dropdown"&&e.jsxs("select",{required:b.is_required,value:c[b.id]||"",onChange:k=>d(A=>({...A,[b.id]:k.target.value})),className:`${y} h-10`,children:[e.jsx("option",{value:"",children:"Select..."}),(b.options||[]).map(k=>e.jsx("option",{value:k,children:k},k))]}),b.field_type==="toggle"&&e.jsx("div",{className:"mt-1.5 flex gap-2",children:["Yes","No"].map(k=>e.jsx("button",{type:"button",onClick:()=>d(A=>({...A,[b.id]:k})),className:`px-3.5 py-1.5 rounded-full text-xs font-medium border transition-colors ${c[b.id]===k?"bg-slate-800 text-white border-slate-800":"bg-white text-slate-600 border-slate-200"}`,children:k},k))})]},b.id)),e.jsxs("div",{children:[e.jsx(re,{className:"text-xs font-medium text-slate-700",children:"Notes for your agent"}),e.jsx("textarea",{value:l.notes,onChange:b=>o(k=>({...k,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(re,{className:"text-xs font-medium text-slate-700",children:"First Name"}),e.jsx(we,{value:l.spouse_first_name,onChange:b=>o(k=>({...k,spouse_first_name:b.target.value})),className:g})]}),e.jsxs("div",{children:[e.jsx(re,{className:"text-xs font-medium text-slate-700",children:"Last Name"}),e.jsx(we,{value:l.spouse_last_name,onChange:b=>o(k=>({...k,spouse_last_name:b.target.value})),className:g})]})]}),e.jsxs("div",{children:[e.jsx(re,{className:"text-xs font-medium text-slate-700",children:"Email"}),e.jsx(we,{type:"email",value:l.spouse_email,onChange:b=>o(k=>({...k,spouse_email:b.target.value})),className:g})]}),e.jsxs("div",{children:[e.jsx(re,{className:"text-xs font-medium text-slate-700",children:"Phone"}),e.jsx(we,{type:"tel",value:l.spouse_phone,onChange:b=>o(k=>({...k,spouse_phone:b.target.value})),className:g})]})]})]}),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 Kvs(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 hSt(){const s=Ya();return mt({queryKey:["agent-portal-branding",s],queryFn:async()=>{if(!s)return null;const{data:t,error:n}=await H.from("agent_portal_branding").select("*").eq("user_id",s).maybeSingle();if(n)throw n;return t},enabled:!!s})}function Yvs(s){return mt({queryKey:["agent-portal-branding-public",s],queryFn:async()=>{if(!s)return null;const{data:t,error:n}=await H.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 Zvs(){const s=Ya(),t=as();return _t({mutationFn:async n=>{if(!s)throw new Error("Not authenticated");const{data:r,error:a}=await H.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 mSt(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 H.storage.from("portal-branding").upload(a,t,{upsert:!0,cacheControl:"3600"});if(i)throw i;const{data:l}=H.storage.from("portal-branding").getPublicUrl(a);return l.publicUrl}function Xvs(s,t){return mt({queryKey:["client-portal-public",s],queryFn:async()=>{if(!s)return null;const{data:n,error:r}=await H.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 Qvs(s){return mt({queryKey:["client-portal-by-id",s],queryFn:async()=>{if(!s)return null;const{data:t,error:n}=await H.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 pSt({slug:s}){var me,ue,ce,ae,he,xe;const[t,n]=N.useState(!1),[r,a]=N.useState("primary"),[i]=N.useState(()=>{const ve=`portal_fp_${s}`;let ge=localStorage.getItem(ve);return ge||(ge=localStorage.getItem("portal_fp"),ge?localStorage.setItem(ve,ge):(ge=crypto.randomUUID(),localStorage.setItem(ve,ge),localStorage.setItem("portal_fp",ge))),ge});N.useEffect(()=>(document.body.classList.add("client-portal-page"),()=>document.body.classList.remove("client-portal-page")),[]);const{data:l,isLoading:o,error:c}=Xvs(s,!0),d=l==null?void 0:l.linked_portal_id,{data:u}=Qvs(d),h=(me=l==null?void 0:l.deal_pipeline)==null?void 0:me.owner_user_id;mt({queryKey:["portal-stages",h],queryFn:async()=>{const{data:ve,error:ge}=await H.from("deal_pipeline_stages").select("*").eq("owner_user_id",h).order("sort_order",{ascending:!0});if(ge)throw ge;return ve},enabled:!!h});const{data:m}=mt({queryKey:["portal-agent",h],queryFn:async()=>{const{data:ve,error:ge}=await H.from("profiles").select("id, name, avatar_url, phone, email").eq("id",h).single();if(ge)throw ge;return ve},enabled:!!h}),{data:f}=Yvs(h),g=r==="linked"&&u?u:l,y=g==null?void 0:g.id,x=Kvs(f,g==null?void 0:g.branding_override),_=x.portal_theme==="azure"?"azure":"noir";N.useEffect(()=>{const ve=`portal-theme-${_}`;return document.body.classList.add(ve),()=>document.body.classList.remove(ve)},[_]);const{data:b}=mt({queryKey:["portal-updates-public",y],queryFn:async()=>{const{data:ve,error:ge}=await H.from("portal_updates").select("*").eq("portal_id",y).order("created_at",{ascending:!1});if(ge)throw ge;return ve},enabled:!!y}),k=(ue=g==null?void 0:g.deal_pipeline)==null?void 0:ue.id,{data:A}=mt({queryKey:["portal-documents",k],queryFn:async()=>{const{data:ve,error:ge}=await H.from("deal_files").select("*").eq("deal_id",k).eq("visible_on_portal",!0).order("created_at",{ascending:!1});if(ge)throw ge;return ve},enabled:!!k}),T=l==null?void 0:l.id,P=T?`portal_onboarded_${T}_${i}`:null,I=P?localStorage.getItem(P)==="1":!1,{data:M,isLoading:L}=mt({queryKey:["portal-onboarding-check",T,i],queryFn:async()=>{const{data:ve,error:ge}=await H.from("portal_onboarding_submissions").select("id").eq("portal_id",T).eq("device_fingerprint",i).maybeSingle();if(ge)throw ge;return ve&&P&&localStorage.setItem(P,"1"),ve},enabled:!!T&&!!(l!=null&&l.require_onboarding)&&!I,staleTime:5*60*1e3}),z=!!(l!=null&&l.require_onboarding)&&!I&&!M&&!t,{data:$}=mt({queryKey:["portal-custom-questions-public",h],queryFn:async()=>{const{data:ve,error:ge}=await H.from("portal_custom_questions").select("*").eq("owner_user_id",h).eq("is_active",!0).order("sort_order",{ascending:!0});if(ge)throw ge;return ve},enabled:!!h&&z}),V=I||!!M||t||!(l!=null&&l.require_onboarding);if(o||l!=null&&l.require_onboarding&&!I&&L)return e.jsx("div",{className:"min-h-screen flex items-center justify-center",style:{background:"hsl(var(--portal-bg))"},children:e.jsx(us,{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(mf,{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 ve=l==null?void 0:l.deal_pipeline;return e.jsx("div",{className:"min-h-screen bg-gradient-to-b from-slate-50 to-slate-100",children:e.jsx(Wvs,{portal:l,dealData:ve,agentProfile:m,customQuestions:$||[],deviceFingerprint:i,onComplete:()=>{P&&localStorage.setItem(P,"1"),n(!0)}})})}const W=(ce=l==null?void 0:l.deal_pipeline)==null?void 0:ce.deal_type,G=(ae=u==null?void 0:u.deal_pipeline)==null?void 0:ae.deal_type,X=!!u,te=ve=>ve==="listing"?"Your Sale":ve==="buy-side"?"Your Purchase":"Transaction",ne=ve=>ve==="listing"?e.jsx(_a,{className:"w-3.5 h-3.5"}):e.jsx(nb,{className:"w-3.5 h-3.5"});return e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"hidden lg:block",children:e.jsx(Hvs,{portal:l,linkedPortal:u,activePortal:g,activeTab:r,onTabChange:a,agentProfile:m,branding:x,updates:b,documents:A})}),e.jsxs("div",{className:"lg:hidden min-h-screen pb-16",style:{background:"var(--portal-gradient-noir)"},children:[e.jsx(Mvs,{dealData:g==null?void 0:g.deal_pipeline,agentProfile:m,welcomeMessage:(g==null?void 0:g.welcome_message)||x.welcome_message,isWon:(xe=(he=g==null?void 0:g.deal_pipeline)==null?void 0:he.deal_pipeline_stages)==null?void 0:xe.is_won_stage,branding:x}),e.jsxs("div",{className:"max-w-lg mx-auto px-4 space-y-5 mt-8",children:[X&&e.jsx("div",{className:"flex gap-1 rounded-xl p-1",style:{background:"hsl(var(--portal-surface-2))",border:"1px solid hsl(var(--portal-gold) / 0.15)"},children:["primary","linked"].map(ve=>{const ge=r===ve,be=ve==="primary"?W:G;return e.jsxs("button",{onClick:()=>a(ve),className:"flex-1 flex items-center justify-center gap-1.5 rounded-lg py-2.5 text-sm font-medium transition-all portal-serif",style:{background:ge?"hsl(var(--portal-surface-3))":"transparent",color:ge?"hsl(var(--portal-gold))":"hsl(var(--portal-ink-muted))",boxShadow:ge?"0 1px 0 hsl(var(--portal-gold) / 0.3) inset":"none"},children:[ne(be),e.jsx("span",{style:{fontSize:"1rem"},children:te(be)})]},ve)})}),e.jsx(Jvs,{portal:g,updates:b,documents:A,agentProfile:m}),e.jsxs("div",{className:"text-center pt-8 pb-2 space-y-3",children:[e.jsx("div",{className:"portal-hairline w-16 mx-auto"}),e.jsxs("div",{className:"flex items-center justify-center gap-1.5",style:{color:"hsl(var(--portal-ink-dim))"},children:[e.jsx(mf,{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 Jvs({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=q4e(c);d&&d.length>0&&(u=d.map((y,x)=>{var _,b;return{key:`custom-${x}`,label:y.label||((_=u[x])==null?void 0:_.label)||`Stage ${x+1}`,description:y.description||((b=u[x])==null?void 0:b.description)||"",video_url:y.video_url||void 0}}));const h=d&&d.length>0?Math.min(aNe(l==null?void 0:l.name),u.length-1):aNe(l==null?void 0:l.name),m=u[h],f=m==null?void 0:m.video_url,g=o&&s.show_post_close_tips!==!1&&s.referral_enabled!==!1;return e.jsxs(e.Fragment,{children:[g&&e.jsx(dSt,{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(eSt,{targetCloseDate:i==null?void 0:i.target_close_date,actualCloseDate:i==null?void 0:i.actual_close_date,clientName:s.client_name}),e.jsx(tSt,{journeyStages:u,currentIndex:h}),m&&e.jsx(sSt,{currentStage:m,nextStepText:s.next_step_text,nextStepVideoUrl:f||s.next_step_video_url}),e.jsx(nSt,{deal:i,portal:s}),n&&n.length>0&&e.jsx(rSt,{documents:n}),(s==null?void 0:s.id)&&(s==null?void 0:s.owner_user_id)&&e.jsx(cSt,{portalId:s.id,ownerUserId:s.owner_user_id,currentStage:l==null?void 0:l.name}),t&&t.length>0&&e.jsx(aSt,{updates:t})]})}function fSt({slug:s}){const t=uo(),n=s||t.slug,[r,a]=N.useState(!1),[i,l]=N.useState(!1),[o,c]=N.useState(""),[d,u]=N.useState(""),[h,m]=N.useState(""),[f,g]=N.useState(""),[y,x]=N.useState(""),[_,b]=N.useState("buying"),[k,A]=N.useState("");N.useEffect(()=>(document.body.classList.add("client-portal-page"),()=>document.body.classList.remove("client-portal-page")),[]);const{data:T,isLoading:P,error:I}=mt({queryKey:["portal-referral-target",n],queryFn:async()=>{if(!n)return null;const{data:z,error:$}=await H.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($)throw $;return z},enabled:!!n}),{data:M}=mt({queryKey:["portal-referral-agent",T==null?void 0:T.owner_user_id],queryFn:async()=>{const{data:z}=await H.from("profiles").select("id, name, avatar_url").eq("id",T.owner_user_id).single();return z},enabled:!!(T!=null&&T.owner_user_id)}),L=async z=>{if(z.preventDefault(),!T||!h.trim()){ie.error("Please enter your friend's name");return}if(!f.trim()&&!y.trim()){ie.error("Please add at least an email or phone for your friend");return}a(!0);try{const{error:$}=await H.from("portal_referrals").insert({portal_id:T.id,owner_user_id:T.owner_user_id,referrer_name:o.trim()||T.client_name||null,referrer_email:d.trim()||null,friend_name:h.trim(),friend_email:f.trim()||null,friend_phone:y.trim()||null,friend_interest:_,friend_message:k.trim()||null});if($)throw $;l(!0)}catch($){ie.error($.message||"Could not submit referral")}finally{a(!1)}};return P?e.jsx("div",{className:"min-h-screen bg-gradient-to-b from-slate-50 to-white flex items-center justify-center",children:e.jsx(xn,{className:"h-96 w-full max-w-lg rounded-2xl mx-4"})}):I||!T||!T.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(pa,{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(Io,{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(Io,{className:"w-3 h-3"})," Referral"]}),e.jsx("h1",{className:"text-2xl font-bold tracking-tight mb-1 font-serif",children:T.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."]}),T.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:T.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:L,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(re,{htmlFor:"friend_name",className:"text-sm",children:["Their name ",e.jsx("span",{className:"text-red-500",children:"*"})]}),e.jsx(we,{id:"friend_name",value:h,onChange:z=>m(z.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(re,{htmlFor:"friend_email",className:"text-sm",children:"Email"}),e.jsx(we,{id:"friend_email",type:"email",value:f,onChange:z=>g(z.target.value),placeholder:"jane@email.com",className:"mt-1"})]}),e.jsxs("div",{children:[e.jsx(re,{htmlFor:"friend_phone",className:"text-sm",children:"Phone"}),e.jsx(we,{id:"friend_phone",type:"tel",value:y,onChange:z=>x(z.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(re,{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(z=>e.jsx("button",{type:"button",onClick:()=>b(z.v),className:`rounded-lg border px-3 py-2 text-sm font-medium transition-colors ${_===z.v?"bg-[#406E71] text-white border-[#406E71]":"bg-white text-slate-600 border-slate-200 hover:border-slate-300"}`,children:z.l},z.v))})]}),e.jsxs("div",{children:[e.jsx(re,{htmlFor:"friend_message",className:"text-sm",children:"A note (optional)"}),e.jsx("textarea",{id:"friend_message",value:k,onChange:z=>A(z.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(re,{htmlFor:"referrer_name",className:"text-sm",children:"Your name"}),e.jsx(we,{id:"referrer_name",value:o,onChange:z=>c(z.target.value),placeholder:T.client_name||"Your name",className:"mt-1"})]}),e.jsxs("div",{children:[e.jsx(re,{htmlFor:"referrer_email",className:"text-sm",children:"Your email"}),e.jsx(we,{id:"referrer_email",type:"email",value:d,onChange:z=>u(z.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(us,{className:"w-4 h-4 animate-spin"}):e.jsx(Io,{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 e1s(){const t=Id().pathname.slice(1).replace(/\/$/,"");if(N.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(fSt,{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(pSt,{slug:t})}function t1s(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 iNe({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=N.useMemo(()=>t1s(Array.isArray(s)?s:[]),[s]),[l,o]=N.useState(0);return N.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(_a,{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 gSt({comp:s,open:t,onClose:n}){var d;const[r,a]=N.useState(0);if(!s)return null;const i=Array.isArray(s.photos)?s.photos.filter(Boolean):[],l=s.soldPrice||s.price,o=s.sqft&&l?Math.round(l/s.sqft):null,c=u=>{if(!u)return null;const[h,m,f]=u.split(/[-/T]/);return h?`${m}/${f}/${h}`:null};return e.jsx(Bs,{open:t,onOpenChange:u=>{u||n()},children:e.jsxs(Fs,{className:"max-w-4xl max-h-[90vh] overflow-y-auto p-0",children:[e.jsxs(qs,{className:"px-6 pt-6 pb-2",children:[e.jsx($s,{className:"text-xl",children:s.address}),e.jsxs("div",{className:"text-sm text-muted-foreground flex items-center gap-1",children:[e.jsx(ii,{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(iNe,{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(iNe,{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(_a,{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(Ed,{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(We,{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(J6e,{label:"Active",date:c(s.listDate),active:!0}),e.jsx(J6e,{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(J6e,{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(Yte,{icon:e.jsx(A_,{className:"w-4 h-4"}),label:"Beds",value:s.bedrooms??"—"}),e.jsx(Yte,{icon:e.jsx(Wx,{className:"w-4 h-4"}),label:"Baths",value:s.bathrooms??"—"}),e.jsx(Yte,{icon:e.jsx(l3,{className:"w-4 h-4"}),label:"SqFt",value:((d=s.sqft)==null?void 0:d.toLocaleString())??"—"}),e.jsx(Yte,{icon:e.jsx(ta,{className:"w-4 h-4"}),label:"Year Built",value:s.yearBuilt??"—"})]}),e.jsxs("div",{className:"px-6 pt-4 grid sm:grid-cols-2 gap-x-6 gap-y-2 text-sm",children:[e.jsx(yv,{label:"MLS #",value:s.mlsNumber}),e.jsx(yv,{label:"Property Type",value:s.propertySubType||s.propertyType}),e.jsx(yv,{label:"Lot Size",value:s.lotSize}),e.jsx(yv,{label:"Garage",value:s.garageSpaces}),e.jsx(yv,{label:"Stories",value:s.stories}),e.jsx(yv,{label:"HOA",value:s.hoaFee?`$${s.hoaFee}/${(s.hoaFrequency||"mo").toLowerCase()}`:null}),e.jsx(yv,{label:"Tax (annual)",value:s.taxAmount?`$${s.taxAmount.toLocaleString()}`:null}),e.jsx(yv,{label:"Heating",value:s.heating}),e.jsx(yv,{label:"Cooling",value:s.cooling}),e.jsx(yv,{label:"Parking",value:s.parking}),e.jsx(yv,{label:"Elementary",value:s.elementarySchool}),e.jsx(yv,{label:"Middle",value:s.middleSchool}),e.jsx(yv,{label:"High",value:s.highSchool}),e.jsx(yv,{label:"Listed By",value:s.listAgentFullName}),e.jsx(yv,{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 Yte({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 yv({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 J6e({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 Zte({to:s,durationMs:t=1400,prefix:n="",suffix:r="",className:a,delayMs:i=0}){const[l,o]=N.useState(0),c=N.useRef(null);return N.useEffect(()=>{if(!Number.isFinite(s))return;let d=0;const u=0,h=f=>1-Math.pow(1-f,3),m=setTimeout(()=>{const f=g=>{d||(d=g);const y=g-d,x=Math.min(1,y/t);o(Math.round(u+(s-u)*h(x))),x<1&&(c.current=requestAnimationFrame(f))};c.current=requestAnimationFrame(f)},i);return()=>{clearTimeout(m),c.current&&cancelAnimationFrame(c.current)}},[s,t,i]),e.jsxs("span",{className:a,children:[n,l.toLocaleString(),r]})}function s1s({low:s,likely:t,high:n,defaultMortgage:r=0,defaultCommissionPct:a=6,defaultClosingPct:i=1}){const[l,o]=N.useState(t),[c,d]=N.useState(r),[u,h]=N.useState(a),[m,f]=N.useState(i),{commission:g,closing:y,net:x}=N.useMemo(()=>{const k=Math.round(l*u/100),A=Math.round(l*m/100);return{commission:k,closing:A,net:Math.max(0,l-k-A-(c||0))}},[l,u,m,c]),_=k=>`$${k.toLocaleString()}`,b=n>s?(l-s)/(n-s)*100:50;return e.jsxs(_e,{className:"overflow-hidden border-primary/20",children:[e.jsxs("div",{className:"bg-gradient-to-br from-primary/5 to-primary/10 px-6 pt-6 pb-4 border-b border-primary/10",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[e.jsx(ml,{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(De,{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:_(l)})]}),e.jsxs("div",{className:"relative",children:[e.jsx(qf,{value:[l],min:s,max:n,step:1e3,onValueChange:([k])=>o(k)}),e.jsxs("div",{className:"flex justify-between text-[10px] text-muted-foreground mt-2",children:[e.jsx("span",{children:_(s)}),e.jsxs("span",{children:["Suggested ",_(t)]}),e.jsx("span",{children:_(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(re,{className:"text-xs",children:"Mortgage payoff"}),e.jsx(we,{type:"number",inputMode:"numeric",value:c||"",placeholder:"$0",onChange:k=>d(Number(k.target.value)||0)})]}),e.jsxs("div",{children:[e.jsx(re,{className:"text-xs",children:"Commission %"}),e.jsx(we,{type:"number",step:"0.25",value:u,onChange:k=>h(Number(k.target.value)||0)})]}),e.jsxs("div",{children:[e.jsx(re,{className:"text-xs",children:"Closing costs %"}),e.jsx(we,{type:"number",step:"0.25",value:m,onChange:k=>f(Number(k.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:_(l)}),e.jsxs("span",{className:"text-muted-foreground",children:["Commission (",u,"%)"]}),e.jsxs("span",{className:"text-right tabular-nums text-rose-600",children:["−",_(g)]}),e.jsxs("span",{className:"text-muted-foreground",children:["Closing (",m,"%)"]}),e.jsxs("span",{className:"text-right tabular-nums text-rose-600",children:["−",_(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:["−",_(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(I9,{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:_(x)})]})]}),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 xSt({tokenOverride:s}={}){var Re,Be,Ne,Ge,Ce,Fe,Ae,Xe,$e,Ye,Je,Ke;const t=uo(),n=s??t.token,[r,a]=N.useState(null),[i,l]=N.useState(null),[o,c]=N.useState([]),[d,u]=N.useState(!0),[h,m]=N.useState(""),[f,g]=N.useState(""),[y,x]=N.useState(""),[_,b]=N.useState(!1),[k,A]=N.useState(!1),[T,P]=N.useState(null),[I,M]=N.useState(null),[L,z]=N.useState(!1),{toast:$}=Ci();N.useEffect(()=>{n&&(async()=>{const{data:st}=await H.from("cmas").select("*").eq("share_token",n).eq("status","shared").maybeSingle();if(!st){u(!1);return}a(st);const[{data:rt},{data:Ze}]=await Promise.all([H.from("cma_comps").select("*").eq("cma_id",st.id).order("position"),H.from("profiles").select("id,name,email,phone,avatar_url,brokerage_name,website_url,title,bio").eq("id",st.agent_id).maybeSingle()]);c((rt||[]).filter(Bt=>Bt.selected)),l(Ze);const ht=localStorage.getItem("cma_visitor_token")||crypto.randomUUID();localStorage.setItem("cma_visitor_token",ht),await H.from("cma_views").insert({cma_id:st.id,visitor_token:ht,user_agent:navigator.userAgent}),u(!1)})()},[n]);const V=async st=>{if(!r)return;const rt=localStorage.getItem("cma_visitor_token")||"";await H.from("cma_views").insert({cma_id:r.id,visitor_token:rt,reactions:{[st]:!0}}),H.functions.invoke("cma-reply-notify",{body:{shareToken:n,reaction:st,visitorToken:rt}}).catch(()=>{}),$({title:"Thanks — your agent just got notified ✨"})},W=!(r!=null&&r.contact_id),G=async()=>{if(!r||!h.trim())return;if(W&&(!f.trim()||!y.trim())){$({title:"Please add your name and email",variant:"destructive"});return}b(!0);const st=localStorage.getItem("cma_visitor_token")||"",{data:rt,error:Ze}=await H.functions.invoke("cma-reply-notify",{body:{shareToken:n,message:h,visitorToken:st,viewerName:f.trim()||void 0,viewerEmail:y.trim()||void 0}});if(b(!1),Ze||!(rt!=null&&rt.success)){$({title:"Could not send",description:(Ze==null?void 0:Ze.message)||(rt==null?void 0:rt.error),variant:"destructive"});return}m(""),A(!0),$({title:"Message sent to your agent"})},X=N.useMemo(()=>{const st=o.map(rt=>{const Ze=rt.snapshot,ht=(Ze==null?void 0:Ze.soldPrice)||(Ze==null?void 0:Ze.price);return ht&&(Ze!=null&&Ze.sqft)?ht/Ze.sqft:null}).filter(rt=>!!rt).sort((rt,Ze)=>rt-Ze);return st.length?Math.round(st[Math.floor(st.length/2)]):null},[o]);if(d)return e.jsx("div",{className:"min-h-screen flex items-center justify-center",children:e.jsx(us,{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(_a,{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 te=r.subject||{},ne=(Re=r.settings)==null?void 0:Re.personalVideo,me=(Be=te.photos)==null?void 0:Be[0],ue=r.contact_first_name?r.contact_first_name:null,ce=((i==null?void 0:i.name)||"A").split(" ").map(st=>st[0]).slice(0,2).join("").toUpperCase(),ae=i!=null&&i.phone?`tel:${String(i.phone).replace(/[^\d+]/g,"")}`:null,he=i!=null&&i.email?`mailto:${i.email}`:null,xe=i!=null&&i.phone?`sms:${String(i.phone).replace(/[^\d+]/g,"")}`:null,ve=r.price_low??null,ge=r.price_likely??null,be=r.price_high??null,Se=ve&&ge&&be,Ie=ge&&te.sqft?Math.round(ge/te.sqft):null,Me=Ie&&X?Math.round((Ie-X)/X*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:ce}),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(Ti,{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:[ae&&e.jsx(B,{variant:"outline",size:"sm",asChild:!0,children:e.jsxs("a",{href:ae,children:[e.jsx(ga,{className:"w-4 h-4 mr-1"}),"Call"]})}),he&&e.jsx(B,{variant:"outline",size:"sm",asChild:!0,children:e.jsxs("a",{href:he,children:[e.jsx(mn,{className:"w-4 h-4 mr-1"}),"Email"]})})]})]})}),e.jsxs("div",{className:"relative overflow-hidden",children:[me?e.jsxs("div",{className:"absolute inset-0",children:[e.jsx("img",{src:me,alt:te.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:`${ne!=null&&ne.url?"md:col-span-3":"md:col-span-5"} text-white animate-fade-in`,children:[e.jsxs(We,{className:"mb-4 bg-white/15 text-white border-white/20 backdrop-blur-sm hover:bg-white/20",children:[e.jsx(Cn,{className:"w-3 h-3 mr-1"}),ue?`Prepared for ${ue}`:r.buyer_mode?"Your Buyer Analysis":"Your Market Analysis"]}),e.jsx("h1",{className:"text-3xl md:text-5xl lg:text-6xl font-bold leading-[1.05] tracking-tight",children:te.address}),e.jsxs("p",{className:"text-white/70 mt-2 text-base md:text-lg flex items-center gap-2",children:[e.jsx(ii,{className:"w-4 h-4"}),te.city,", ",te.state," ",te.zip]}),Se&&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(Zte,{to:ge,prefix:"$",durationMs:1600,delayMs:250})})}),e.jsxs("div",{className:"mt-4 flex items-center gap-3 md:gap-6 text-sm text-white/80",children:[e.jsxs("div",{children:[e.jsx("span",{className:"block text-[11px] uppercase tracking-wider text-white/50",children:"Low"}),e.jsx("span",{className:"tabular-nums font-medium",children:e.jsx(Zte,{to:ve,prefix:"$",delayMs:500})})]}),e.jsx("div",{className:"h-8 w-px bg-white/20"}),e.jsxs("div",{children:[e.jsx("span",{className:"block text-[11px] uppercase tracking-wider text-white/50",children:"Likely"}),e.jsx("span",{className:"tabular-nums font-medium",children:e.jsx(Zte,{to:ge,prefix:"$",delayMs:650})})]}),e.jsx("div",{className:"h-8 w-px bg-white/20"}),e.jsxs("div",{children:[e.jsx("span",{className:"block text-[11px] uppercase tracking-wider text-white/50",children:"High"}),e.jsx("span",{className:"tabular-nums font-medium",children:e.jsx(Zte,{to:be,prefix:"$",delayMs:800})})]})]})]})]}),(ne==null?void 0:ne.url)&&e.jsx("div",{className:"md:col-span-2 animate-scale-in",children:e.jsxs("button",{onClick:()=>z(!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:[ne.thumb?e.jsx("img",{src:ne.thumb,alt:"",className:"w-full h-full object-cover"}):e.jsx("video",{src:ne.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(dd,{className:"w-7 h-7 md:w-8 md:h-8 ml-1",fill:"currentColor"})}),e.jsxs("p",{className:"mt-4 text-sm font-medium tracking-wide",children:["A message from ",((Ne=i==null?void 0:i.name)==null?void 0:Ne.split(" ")[0])||"your agent"]})]})]})})]})})]}),L&&(ne==null?void 0:ne.url)&&e.jsx("div",{className:"fixed inset-0 z-50 bg-black/90 flex items-center justify-center p-4 animate-fade-in",onClick:()=>z(!1),children:e.jsxs("div",{className:"relative w-full max-w-4xl",onClick:st=>st.stopPropagation(),children:[e.jsx("video",{src:ne.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:()=>z(!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:te.bedrooms??"—"},{label:"Baths",value:te.bathrooms??"—"},{label:"Sq Ft",value:((Ge=te.sqft)==null?void 0:Ge.toLocaleString())??"—"},{label:"Year Built",value:te.yearBuilt??"—"}].map((st,rt)=>e.jsx(_e,{className:"shadow-lg animate-fade-in",style:{animationDelay:`${rt*80}ms`},children:e.jsxs(De,{className:"p-4 md:p-6 text-center",children:[e.jsx("div",{className:"text-2xl md:text-3xl font-bold",children:st.value}),e.jsx("div",{className:"text-xs text-muted-foreground mt-1 uppercase tracking-wider",children:st.label})]})},rt))}),((Fe=(Ce=r.settings)==null?void 0:Ce.priceOverride)==null?void 0:Fe.enabled)&&((Xe=(Ae=r.settings)==null?void 0:Ae.priceOverride)==null?void 0:Xe.note)&&e.jsx(_e,{className:"border-primary/30 bg-gradient-to-br from-primary/5 to-transparent",children:e.jsxs(De,{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})]})}),Se&&e.jsx(s1s,{low:ve,likely:ge,high:be}),X&&Ie&&e.jsxs("div",{className:"grid md:grid-cols-3 gap-4",children:[e.jsx(_e,{className:"md:col-span-2",children:e.jsxs(De,{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 ",te.city,", the median sale rate is ",e.jsxs("strong",{className:"text-foreground",children:["$",X,"/sqft"]}),". Applied to your home's ",($e=te.sqft)==null?void 0:$e.toLocaleString()," sqft, the comps support a value near ",e.jsxs("strong",{className:"text-foreground",children:["$",(X*(te.sqft||0)).toLocaleString()]}),". Your agent's suggested price reflects local nuance and condition."]})]})}),e.jsx(_e,{className:"bg-gradient-to-br from-primary/10 to-primary/5 border-primary/20",children:e.jsxs(De,{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:["$",Ie,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:["$",X,"/sqft"]})]}),Me!==null&&Me!==0&&e.jsxs("p",{className:`text-sm font-medium mt-1 ${Me>0?"text-emerald-600":"text-rose-600"}`,children:[Me>0?"▲":"▼"," ",Math.abs(Me),"% ",Me>0?"above":"below"," the median"]})]})})]}),e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-baseline justify-between mb-4",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-xs uppercase tracking-widest text-primary font-semibold",children:"Homes like yours"}),e.jsx("h2",{className:"text-2xl md:text-3xl font-bold",children:"The Comparables"})]}),e.jsxs(We,{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((st,rt)=>{var Bt;const Ze=st.snapshot,ht=Ze.soldPrice||Ze.price;return e.jsxs(_e,{className:`overflow-hidden cursor-pointer transition-all duration-300 hover:shadow-xl hover:-translate-y-1 animate-fade-in ${I===rt?"ring-2 ring-primary":""}`,style:{animationDelay:`${rt*60}ms`},onClick:()=>P(rt),onMouseEnter:()=>M(rt),onMouseLeave:()=>M(null),children:[e.jsxs("div",{className:"relative",children:[e.jsx(iNe,{photos:Ze.photos,className:"w-full h-44"}),e.jsxs(We,{className:"absolute top-2 left-2 bg-black/70 text-white border-0 backdrop-blur-sm",children:["#",rt+1]}),e.jsx(We,{variant:"outline",className:"absolute top-2 right-2 bg-white/95 border-0",children:Ze.status})]}),e.jsxs(De,{className:"p-4",children:[e.jsx("div",{className:"font-semibold leading-tight truncate",children:Ze.address}),e.jsxs("div",{className:"text-xs text-muted-foreground",children:[Ze.city,", ",Ze.state]}),e.jsx("div",{className:"flex justify-between items-center mt-3 text-sm",children:e.jsxs("span",{className:"text-muted-foreground",children:[Ze.bedrooms??"?","bd · ",Ze.bathrooms??"?","ba · ",((Bt=Ze.sqft)==null?void 0:Bt.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:["$",ht==null?void 0:ht.toLocaleString()]}),Ze.sqft&&ht?e.jsxs("span",{className:"text-xs text-muted-foreground tabular-nums",children:["$",Math.round(ht/Ze.sqft),"/sqft"]}):null]})]})]},rt)})})]}),e.jsx(gSt,{comp:T!==null?(Ye=o[T])==null?void 0:Ye.snapshot:null,open:T!==null,onClose:()=>P(null)}),e.jsx(_e,{className:"border-primary/20 bg-gradient-to-br from-primary/5 via-background to-background overflow-hidden",children:e.jsxs(De,{className:"p-6 md:p-8 space-y-5",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-xs uppercase tracking-widest text-primary font-semibold mb-1",children:"Your turn"}),e.jsxs("h2",{className:"text-2xl md:text-3xl font-bold",children:["What do you think",ue?`, ${ue}`:"","?"]}),e.jsxs("p",{className:"text-sm text-muted-foreground mt-1",children:["One tap. ",((Je=i==null?void 0:i.name)==null?void 0:Je.split(" ")[0])||"Your agent"," hears you instantly."]})]}),e.jsx("div",{className:"flex flex-wrap gap-2",children:[{kind:"love",icon:co,label:"I love this price"},{kind:"fair",icon:ax,label:"Seems fair"},{kind:"lower",icon:eN,label:"I'd price lower"},{kind:"higher",icon:ml,label:"I'd price higher"},{kind:"ready_to_list",icon:Y2,label:"Ready to list"},{kind:"want_walkthrough",icon:da,label:"Want a walkthrough"},{kind:"need_time",icon:ta,label:"Need more time"},{kind:"have_questions",icon:Uk,label:"I have questions"}].map(({kind:st,icon:rt,label:Ze})=>e.jsxs(B,{variant:"outline",className:"bg-card hover:bg-primary hover:text-primary-foreground hover:scale-105 transition-all",onClick:()=>V(st),children:[e.jsx(rt,{className:"w-4 h-4 mr-2"}),Ze]},st))}),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(Ud,{className:"w-4 h-4"}),"Ask your agent a question"]}),k?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! ",((Ke=i==null?void 0:i.name)==null?void 0:Ke.split(" ")[0])||"Your agent"," was notified and will get back to you shortly."]}):e.jsxs(e.Fragment,{children:[W&&e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-2 mb-2",children:[e.jsx("input",{className:"border rounded-md p-2 text-sm bg-background",placeholder:"Your name",value:f,onChange:st=>g(st.target.value)}),e.jsx("input",{type:"email",className:"border rounded-md p-2 text-sm bg-background",placeholder:"Your email",value:y,onChange:st=>x(st.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:st=>m(st.target.value)}),e.jsx(B,{onClick:G,disabled:!h.trim()||_,className:"mt-2",children:_?"Sending…":"Send to agent"})]})]})]})}),i&&e.jsx(_e,{className:"overflow-hidden border-primary/20",children:e.jsx("div",{className:"bg-gradient-to-br from-primary/10 to-primary/5 p-6 md:p-10",children:e.jsxs("div",{className:"flex flex-col md:flex-row gap-6 items-start",children:[i.avatar_url?e.jsx("img",{src:i.avatar_url,alt:i.name,className:"w-24 h-24 md:w-32 md:h-32 rounded-2xl object-cover ring-4 ring-background shadow-lg"}):e.jsx("div",{className:"w-24 h-24 md:w-32 md:h-32 rounded-2xl bg-primary/20 flex items-center justify-center text-3xl font-bold text-primary ring-4 ring-background shadow-lg",children:ce}),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:[ae&&e.jsx(B,{asChild:!0,children:e.jsxs("a",{href:ae,children:[e.jsx(ga,{className:"w-4 h-4 mr-2"}),i.phone]})}),he&&e.jsx(B,{variant:"outline",asChild:!0,children:e.jsxs("a",{href:he,children:[e.jsx(mn,{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(au,{className:"w-4 h-4 mr-2"}),"Website"]})})]})]})]})})})]}),i&&(ae||xe||he)&&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:[ae&&e.jsx(B,{className:"flex-1",asChild:!0,children:e.jsxs("a",{href:ae,children:[e.jsx(ga,{className:"w-4 h-4 mr-1.5"}),"Call"]})}),xe&&e.jsx(B,{variant:"outline",className:"flex-1",asChild:!0,children:e.jsxs("a",{href:xe,children:[e.jsx(Ud,{className:"w-4 h-4 mr-1.5"}),"Text"]})}),he&&e.jsx(B,{variant:"outline",className:"flex-1",asChild:!0,children:e.jsxs("a",{href:he,children:[e.jsx(mn,{className:"w-4 h-4 mr-1.5"}),"Email"]})})]})]})}function n1s(){const t=Id().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(xSt,{tokenOverride:t})}const vRe="levelup_affiliate_ref",r1s=30,a1s=()=>{const[s]=$c();N.useEffect(()=>{const t=s.get("ref");if(t){const n={code:t.toUpperCase(),timestamp:Date.now()};localStorage.setItem(vRe,JSON.stringify(n)),console.log("[Affiliate] Stored referral code:",t)}},[s])},i1s=()=>{try{const s=localStorage.getItem(vRe);if(!s)return null;const t=JSON.parse(s),n=r1s*24*60*60*1e3;return Date.now()-t.timestamp>n?(localStorage.removeItem(vRe),console.log("[Affiliate] Referral code expired"),null):t.code}catch{return null}},oNe="/assets/levelup-logo-header-_ZX7DvlA.png",o1s="/assets/scale-your-team-ku4MPatU.png";function l1s({open:s,onOpenChange:t}){return e.jsx(Bs,{open:s,onOpenChange:t,children:e.jsxs(Fs,{className:"max-w-3xl max-h-[90vh] overflow-hidden",children:[e.jsx(qs,{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(Ti,{className:"h-5 w-5 text-[#4a6b6d]"})}),e.jsxs("div",{children:[e.jsx($s,{children:"Schedule a Brokerage Interest Meeting"}),e.jsx(Ar,{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 Cx={individual_agent:{name:"Individual Agent",price:"$39",period:"/month",description:"Perfect for independent agents ready to level up",features:["Full dashboard access","300+ professional templates","Academy training library","Community & networking","Live events & workshops","Social media content","Newsletter resources","Email support"],trial:"7-day free trial",popular:!1},brokerage_under_25:{name:"Brokerage",subtitle:"Under 25 Agents",price:"$299",period:"/month",description:"Empower your entire team to succeed",features:["Everything in Individual","Brokerage manager dashboard","Invite & manage up to 25 agents","Exclusive brokerage resources","Team performance analytics","Agent onboarding tools","Resource sharing","Priority support"],popular:!0},brokerage_over_25:{name:"Brokerage",subtitle:"Over 25 Agents",price:"$499",period:"/month",description:"Scale your brokerage without limits",features:["Everything in Brokerage","Unlimited agents","Advanced team analytics","Dedicated account manager","Custom onboarding sessions","White-glove support"],popular:!1}},c1s=[{icon:wp,title:"Academy Training",description:"Access a library of on-demand video training covering lead generation, marketing, technology, and more."},{icon:zc,title:"300+ Templates",description:"Professional Canva templates for social media, flyers, postcards, and marketing materials."},{icon:ta,title:"Live Events",description:"Weekly live training sessions, workshops, and Q&A events with industry experts."},{icon:Ud,title:"Agent Community",description:"Connect with fellow agents, share wins, ask questions, and network in our private community."},{icon:Wr,title:"Resource Kits",description:"Downloadable toolkits with scripts, checklists, guides, and everything you need to close more deals."},{icon:Io,title:"Social Swag",description:"Fresh social media content and designs updated regularly to help you stand out online."}],d1s=[{icon:Yn,title:"Contact Management",description:"Organize your sphere into relationship tiers—Top 25, Past Clients, Referral Partners, and more."},{icon:Cn,title:"Smart Touchpoint Plans",description:"Automated action plans that tell you exactly who to contact and how, based on relationship type."},{icon:ga,title:"One-Tap Actions",description:"Call, text, or email contacts directly with pre-written scripts tailored to each relationship."},{icon:Fm,title:"Birthday & Anniversary Alerts",description:"Never miss an important date—get reminders for birthdays and home anniversaries."},{icon:ii,title:"Pop-by Map",description:"See all your contacts on a map and plan efficient pop-by routes in your area."},{icon:fl,title:"Momentum Tracking",description:"Track your touch streaks, weekly goals, and relationship health scores."},{icon:co,title:"Relationship Health",description:"Visual dashboard showing which contacts need attention based on last touch date."},{icon:ff,title:"Daily Action Cards",description:"Wake up to a prioritized list of exactly who to reach out to today."}],u1s=[{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."}],h1s=()=>{const{user:s,loading:t}=Ls(),n=tr(),[r]=$c();N.useEffect(()=>{const I=window.location.host==="listings.relevelup.com",M=window.location.pathname==="/";if(I&&M){n("/public/listings",{replace:!0});return}},[n]);const[a,i]=N.useState(null),[l,o]=N.useState(null),[c,d]=N.useState(!1),[u,h]=N.useState(""),[m,f]=N.useState(""),[g,y]=N.useState(""),[x,_]=N.useState(!1),[b,k]=N.useState(!1),A=(I,M=!1)=>{o({tier:I,skipTrial:M}),d(!0)};a1s(),N.useEffect(()=>{const I=window.location.host==="listings.relevelup.com",M=location.pathname.startsWith("/public/");!t&&s&&!I&&!M&&n("/dashboard")},[s,t,n,location.pathname]),N.useEffect(()=>{r.get("canceled")==="true"&&ie.error("Checkout was canceled. Feel free to try again when you're ready!")},[r]);const T=async(I,M=!1)=>{if(!u){ie.error("Please enter your email address");return}if(!m.trim()){ie.error("Please enter your full name");return}_(!0),i(I+(M?"_direct":""));const L=i1s();try{const{data:z,error:$}=await H.functions.invoke("create-checkout",{body:{tier:I,email:u,name:m.trim(),couponCode:g.trim()||void 0,skipTrial:M,referralCode:L}});if($)throw $;if(z!=null&&z.url)window.open(z.url,"_blank","noopener,noreferrer"),ie.success("Checkout opened in a new tab");else throw new Error("No checkout URL returned")}catch(z){console.error("Checkout error:",z),ie.error(z.message||"Failed to start checkout. Please try again.")}finally{_(!1),i(null),d(!1),o(null)}},P=()=>{l&&T(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:oNe,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 I;return(I=document.getElementById("features"))==null?void 0:I.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 I;return(I=document.getElementById("pricing"))==null?void 0:I.scrollIntoView({behavior:"smooth"})},children:"Pricing"}),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 pt-24 pb-20 bg-gradient-to-br from-[#1e3a4c] via-[#2a4f5f] to-[#3d6b6b] overflow-hidden",children:[e.jsx("div",{className:"absolute inset-0 opacity-10",children:e.jsx("div",{className:"absolute inset-0 bg-[url('data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iNjAiIGhlaWdodD0iNjAiIHZpZXdCb3g9IjAgMCA2MCA2MCIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj48ZyBmaWxsPSJub25lIiBmaWxsLXJ1bGU9ImV2ZW5vZGQiPjxnIGZpbGw9IiNmZmZmZmYiIGZpbGwtb3BhY2l0eT0iMC40Ij48cGF0aCBkPSJNMzYgMzRoLTJ2LTRoMnY0em0wLTZ2LTRoLTJ2NGgyem0tNiA2aC0ydi00aDJ2NHptMC02di00aC0ydjRoMnoiLz48L2c+PC9nPjwvc3ZnPg==')]"})}),e.jsx("div",{className:"container mx-auto px-4 relative",children:e.jsxs("div",{className:"max-w-5xl mx-auto text-center space-y-8",children:[e.jsx("div",{className:"flex justify-center mb-8",children:e.jsx("img",{alt:"LevelUp Consulting Group",className:"h-[136px] md:h-[164px] drop-shadow-lg",src:"/lovable-uploads/3a0c7ef9-9e79-411f-a9af-6f2a99e8bd7b.webp"})}),e.jsxs("p",{className:"text-lg text-white/80 max-w-3xl mx-auto leading-relaxed font-sans font-bold md:text-4xl",children:["The tools you need to get it done.",e.jsx("br",{}),e.jsx("em",{children:"The platform you need to keep it going."})]}),e.jsxs("div",{className:"flex flex-col sm:flex-row gap-4 justify-center items-center pt-4",children:[e.jsxs(B,{size:"lg",onClick:()=>{var I;return(I=document.getElementById("free-trial"))==null?void 0:I.scrollIntoView({behavior:"smooth"})},className:"px-8 py-7 text-lg font-semibold bg-white text-[#1e3a4c] hover:bg-white/90 shadow-2xl transition-all hover:scale-105 group rounded-full",children:["Start Your Free Trial",e.jsx(vi,{className:"ml-2 w-5 h-5 group-hover:translate-x-1 transition-transform"})]}),e.jsx(B,{size:"lg",variant:"outline",onClick:()=>{var I;return(I=document.getElementById("features"))==null?void 0:I.scrollIntoView({behavior:"smooth"})},className:"px-8 py-7 text-lg font-semibold border-2 border-white text-white bg-transparent hover:bg-white hover:text-[#1e3a4c] rounded-full",children:"See What's Included"})]})]})})]}),e.jsx("section",{className:"py-20 bg-background",children:e.jsx("div",{className:"container mx-auto px-4",children:e.jsxs("div",{className:"max-w-4xl mx-auto text-center space-y-8",children:[e.jsx("h2",{className:"text-3xl md:text-5xl leading-tight font-sans font-semibold text-secondary",children:"We help brokerages and agents grow with training, tools, and built-in execution."}),e.jsxs("div",{className:"space-y-2 text-lg text-muted-foreground",children:[e.jsx("p",{children:"Agents get weekly coaching + plug-and-play marketing."}),e.jsx("p",{children:"Brokerages get higher adoption, consistency, and real engagement."})]}),e.jsx("p",{className:"text-2xl md:text-4xl text-[#4a6b6d] pt-4 font-sans font-bold",children:"LEVELUP EQUIPS BOTH TO THRIVE."}),e.jsx("p",{className:"text-lg text-muted-foreground",children:"Learn how we support agents and empower brokerages to grow—together."}),e.jsxs("div",{className:"flex flex-col sm:flex-row gap-4 justify-center pt-4",children:[e.jsxs(B,{size:"lg",variant:"outline",onClick:()=>{var I;return(I=document.getElementById("brokerage"))==null?void 0:I.scrollIntoView({behavior:"smooth"})},className:"border-[#4a6b6d] text-[#4a6b6d] hover:bg-[#4a6b6d]/5",children:[e.jsx(Ti,{className:"mr-2 h-5 w-5"}),"Brokerage Partnership"]}),e.jsxs(B,{size:"lg",onClick:()=>{var I;return(I=document.getElementById("pricing"))==null?void 0:I.scrollIntoView({behavior:"smooth"})},className:"bg-[#4a6b6d] hover:bg-[#3d5a5c]",children:[e.jsx(Ro,{className:"mr-2 h-5 w-5"}),"Individual Membership"]})]})]})})}),e.jsx("section",{id:"features",className:"py-20 bg-muted/30",children:e.jsxs("div",{className:"container mx-auto px-4",children:[e.jsxs("div",{className:"text-center max-w-3xl mx-auto mb-16",children:[e.jsx("h2",{className:"text-3xl md:text-4xl mb-6 font-sans font-bold",children:"What's inside our members only portal?"}),e.jsx("p",{className:"text-lg text-muted-foreground",children:"Everything you need to grow your business, all in one place."})]}),e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-8 max-w-6xl mx-auto",children:c1s.map((I,M)=>e.jsxs(_e,{className:"group relative overflow-hidden border hover:border-[#4a6b6d]/50 transition-all duration-300 hover:shadow-lg bg-background",children:[e.jsxs(zt,{children:[e.jsx("div",{className:"w-14 h-14 rounded-2xl bg-[#4a6b6d]/10 flex items-center justify-center mb-4",children:e.jsx(I.icon,{className:"w-7 h-7 text-[#4a6b6d]"})}),e.jsx(qt,{className:"text-xl font-sans",children:I.title})]}),e.jsx(De,{children:e.jsx("p",{className:"text-muted-foreground leading-relaxed",children:I.description})})]},M))})]})}),e.jsxs("section",{id:"agent-os",className:"py-20 bg-gradient-to-br from-[#4a6b6d] to-[#3d5a5c] relative overflow-hidden",children:[e.jsx("div",{className:"absolute inset-0 opacity-10",children:e.jsx("div",{className:"absolute inset-0 bg-[url('data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iNjAiIGhlaWdodD0iNjAiIHZpZXdCb3g9IjAgMCA2MCA2MCIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj48ZyBmaWxsPSJub25lIiBmaWxsLXJ1bGU9ImV2ZW5vZGQiPjxnIGZpbGw9IiNmZmZmZmYiIGZpbGwtb3BhY2l0eT0iMC40Ij48cGF0aCBkPSJNMzYgMzRoLTJ2LTRoMnY0em0wLTZ2LTRoLTJ2NGgyem0tNiA2aC0ydi00aDJ2NHptMC02di00aC0ydjRoMnoiLz48L2c+PC9nPjwvc3ZnPg==')]"})}),e.jsxs("div",{className:"container mx-auto px-4 relative",children:[e.jsxs("div",{className:"text-center max-w-3xl mx-auto mb-16",children:[e.jsxs("div",{className:"inline-flex items-center gap-2 px-4 py-2 rounded-full bg-white/10 text-white text-sm font-medium mb-6",children:[e.jsx(Cn,{className:"w-4 h-4"}),"Included with Membership"]}),e.jsxs("h2",{className:"text-3xl mb-6 text-white font-sans font-bold md:text-6xl",children:["Meet ",e.jsx("span",{className:"italic",children:"Agent OS"})]}),e.jsx("p",{className:"text-lg text-white/80",children:"Your relationship-first operating system. Never forget a follow-up, track every touchpoint, and turn your sphere into a referral machine."})]}),e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6 max-w-6xl mx-auto",children:d1s.map((I,M)=>e.jsxs(_e,{className:"group relative overflow-hidden border-0 bg-white/10 backdrop-blur-sm hover:bg-white/20 transition-all duration-300",children:[e.jsxs(zt,{className:"pb-3",children:[e.jsx("div",{className:"w-12 h-12 rounded-xl bg-white/20 flex items-center justify-center mb-3",children:e.jsx(I.icon,{className:"w-6 h-6 text-white"})}),e.jsx(qt,{className:"text-lg font-semibold text-white",children:I.title})]}),e.jsx(De,{children:e.jsx("p",{className:"text-white/70 text-sm leading-relaxed",children:I.description})})]},M))}),e.jsx("div",{className:"text-center mt-12",children:e.jsxs(B,{size:"lg",onClick:()=>{var I;return(I=document.getElementById("pricing"))==null?void 0:I.scrollIntoView({behavior:"smooth"})},className:"bg-white text-[#4a6b6d] hover:bg-white/90 shadow-xl transition-all hover:scale-105",children:["Get Agent OS with Your Membership",e.jsx(vi,{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(Ti,{className:"w-4 h-4"}),"For Brokerages"]}),e.jsxs("h2",{className:"text-3xl font-sans font-bold md:text-6xl",children:["Empower Your"," ",e.jsx("span",{className:"italic text-[#4a6b6d]",children:"Entire Team"})]}),e.jsx("p",{className:"text-lg text-muted-foreground",children:"Give every agent on your team access to world-class training and resources. Track performance, streamline onboarding, and watch your brokerage thrive."}),e.jsx("ul",{className:"space-y-4",children:["Dedicated brokerage manager dashboard","Invite and manage agents with one click","Exclusive brokerage-only resources","Team analytics and performance tracking","Simplified agent onboarding","Share resources across your team"].map((I,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(pa,{className:"w-4 h-4 text-[#4a6b6d]"})}),e.jsx("span",{className:"text-foreground",children:I})]},M))}),e.jsxs("div",{className:"flex flex-col sm:flex-row gap-3 mt-4",children:[e.jsxs(B,{size:"lg",onClick:()=>{var I;return(I=document.getElementById("pricing"))==null?void 0:I.scrollIntoView({behavior:"smooth"})},className:"bg-[#4a6b6d] hover:bg-[#3d5a5c]",children:["See Brokerage Plans",e.jsx(Qa,{className:"ml-2 w-5 h-5"})]}),e.jsxs(B,{size:"lg",variant:"outline",onClick:()=>k(!0),className:"border-[#4a6b6d] text-[#4a6b6d] hover:bg-[#4a6b6d]/10",children:[e.jsx(ta,{className:"mr-2 w-5 h-5"}),"Schedule Info Session"]})]})]}),e.jsx("div",{className:"relative hidden md:block",children:e.jsx("img",{src:o1s,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:u1s.map((I,M)=>e.jsx(_e,{className:"bg-muted/30 border-0",children:e.jsxs(De,{className:"pt-8",children:[e.jsx("div",{className:"flex gap-1 mb-4",children:[1,2,3,4,5].map(L=>e.jsx(Wa,{className:"w-5 h-5 fill-yellow-400 text-yellow-400"},L))}),e.jsxs("p",{className:"text-lg mb-6 italic text-muted-foreground",children:['"',I.quote,'"']}),e.jsxs("div",{children:[e.jsx("p",{className:"font-semibold",children:I.name}),e.jsx("p",{className:"text-sm text-muted-foreground",children:I.role})]})]})},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:()=>A("individual_agent"),children:["Start Free Trial",e.jsx(vi,{className:"ml-2 w-5 h-5 group-hover:translate-x-1 transition-transform"})]})})]})})]}),e.jsx("section",{id:"pricing",className:"py-20 bg-muted/30",children:e.jsxs("div",{className:"container mx-auto px-4",children:[e.jsxs("div",{className:"text-center mb-16",children:[e.jsxs("h2",{className:"text-3xl mb-6 font-sans md:text-5xl font-bold",children:["Simple, Transparent ",e.jsx("span",{className:"italic text-[#4a6b6d]",children:"Pricing"})]}),e.jsx("p",{className:"text-lg text-muted-foreground max-w-2xl mx-auto",children:"Choose the plan that fits your needs. All plans include everything you need to succeed."})]}),e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-3 gap-8 max-w-6xl mx-auto",children:[e.jsxs(_e,{className:"relative flex flex-col border hover:border-[#4a6b6d]/50 transition-all hover:shadow-xl bg-background",children:[e.jsxs(zt,{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(Ro,{className:"w-5 h-5 text-[#4a6b6d]"})}),e.jsx(qt,{className:"text-xl font-sans",children:Cx.individual_agent.name})]}),e.jsxs("div",{className:"flex items-baseline gap-1 mt-4",children:[e.jsx("span",{className:"text-5xl font-bold",children:Cx.individual_agent.price}),e.jsx("span",{className:"text-muted-foreground text-lg",children:Cx.individual_agent.period})]}),e.jsx(_r,{className:"text-base mt-2",children:Cx.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(Xr,{className:"w-4 h-4"}),Cx.individual_agent.trial]})]}),e.jsx(De,{className:"flex-1 pt-0",children:e.jsx("ul",{className:"space-y-3",children:Cx.individual_agent.features.map((I,M)=>e.jsxs("li",{className:"flex items-center gap-3",children:[e.jsx(pa,{className:"w-5 h-5 text-[#4a6b6d] flex-shrink-0"}),e.jsx("span",{children:I})]},M))})}),e.jsxs(WW,{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:()=>A("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:()=>A("individual_agent",!0),children:"Skip Trial, Subscribe Now"})]})]}),e.jsxs(_e,{className:"relative flex flex-col border-2 border-[#4a6b6d] shadow-2xl scale-105 bg-background",children:[e.jsx("div",{className:"absolute -top-4 left-1/2 -translate-x-1/2 px-6 py-2 bg-[#4a6b6d] text-white text-sm font-semibold rounded-full shadow-lg",children:"Most Popular"}),e.jsxs(zt,{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(Ti,{className:"w-5 h-5 text-[#4a6b6d]"})}),e.jsxs("div",{children:[e.jsx(qt,{className:"text-xl font-sans",children:Cx.brokerage_under_25.name}),e.jsx("span",{className:"text-sm text-muted-foreground",children:Cx.brokerage_under_25.subtitle})]})]}),e.jsxs("div",{className:"flex items-baseline gap-1 mt-4",children:[e.jsx("span",{className:"text-5xl font-bold",children:Cx.brokerage_under_25.price}),e.jsx("span",{className:"text-muted-foreground text-lg",children:Cx.brokerage_under_25.period})]}),e.jsx(_r,{className:"text-base mt-2",children:Cx.brokerage_under_25.description})]}),e.jsx(De,{className:"flex-1 pt-0",children:e.jsx("ul",{className:"space-y-3",children:Cx.brokerage_under_25.features.map((I,M)=>e.jsxs("li",{className:"flex items-center gap-3",children:[e.jsx(pa,{className:"w-5 h-5 text-[#4a6b6d] flex-shrink-0"}),e.jsx("span",{children:I})]},M))})}),e.jsx(WW,{className:"pt-4",children:e.jsx(B,{className:"w-full py-6 text-lg shadow-lg bg-[#4a6b6d] hover:bg-[#3d5a5c]",onClick:()=>A("brokerage_under_25"),children:"Get Started"})})]}),e.jsxs(_e,{className:"relative flex flex-col border hover:border-[#4a6b6d]/50 transition-all hover:shadow-xl bg-background",children:[e.jsxs(zt,{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(Ti,{className:"w-5 h-5 text-[#4a6b6d]"})}),e.jsxs("div",{children:[e.jsx(qt,{className:"text-xl font-sans",children:Cx.brokerage_over_25.name}),e.jsx("span",{className:"text-sm text-muted-foreground",children:Cx.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:Cx.brokerage_over_25.price}),e.jsx("span",{className:"text-muted-foreground text-lg",children:Cx.brokerage_over_25.period})]}),e.jsx(_r,{className:"text-base mt-2",children:Cx.brokerage_over_25.description})]}),e.jsx(De,{className:"flex-1 pt-0",children:e.jsx("ul",{className:"space-y-3",children:Cx.brokerage_over_25.features.map((I,M)=>e.jsxs("li",{className:"flex items-center gap-3",children:[e.jsx(pa,{className:"w-5 h-5 text-[#4a6b6d] flex-shrink-0"}),e.jsx("span",{children:I})]},M))})}),e.jsx(WW,{className:"pt-4",children:e.jsx(B,{className:"w-full py-6 text-lg bg-[#4a6b6d] hover:bg-[#3d5a5c]",onClick:()=>A("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(mf,{className:"w-4 h-4"}),"Our Commitment"]}),e.jsxs("h2",{className:"text-3xl md:text-4xl font-sans font-bold",children:["LevelUp Brokerage ",e.jsx("span",{className:"italic text-[#4a6b6d]",children:"Neutrality Policy"})]}),e.jsx("p",{className:"text-lg text-muted-foreground mt-4 max-w-2xl mx-auto",children:"We are committed to being a trusted, independent partner for every agent and brokerage."})]}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-6",children:[e.jsx(_e,{className:"border-[#4a6b6d]/20 bg-[#4a6b6d]/[0.03]",children:e.jsxs(De,{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(Ti,{className:"w-5 h-5 text-[#4a6b6d]"})}),e.jsx("p",{className:"text-foreground font-medium leading-relaxed",children:"LevelUp serves all brokerages."})]})}),e.jsx(_e,{className:"border-[#4a6b6d]/20 bg-[#4a6b6d]/[0.03]",children:e.jsxs(De,{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(Au,{className:"w-5 h-5 text-[#4a6b6d]"})}),e.jsx("p",{className:"text-foreground font-medium leading-relaxed",children:"LevelUp does not share member information with any brokerage."})]})}),e.jsx(_e,{className:"border-[#4a6b6d]/20 bg-[#4a6b6d]/[0.03]",children:e.jsxs(De,{className:"p-6 flex items-start gap-4",children:[e.jsx("div",{className:"w-10 h-10 rounded-lg bg-[#4a6b6d]/10 flex items-center justify-center shrink-0",children:e.jsx(tN,{className:"w-5 h-5 text-[#4a6b6d]"})}),e.jsx("p",{className:"text-foreground font-medium leading-relaxed",children:"LevelUp does not recruit brokerage partners' agents."})]})}),e.jsx(_e,{className:"border-[#4a6b6d]/20 bg-[#4a6b6d]/[0.03]",children:e.jsxs(De,{className:"p-6 flex items-start gap-4",children:[e.jsx("div",{className:"w-10 h-10 rounded-lg bg-[#4a6b6d]/10 flex items-center justify-center shrink-0",children:e.jsx(Wr,{className:"w-5 h-5 text-[#4a6b6d]"})}),e.jsx("p",{className:"text-foreground font-medium leading-relaxed",children:"LevelUp does not use LevelUp events, trainings, webinars, CRM data, or member lists for recruiting purposes."})]})})]})]})})}),e.jsxs("section",{className:"py-20 bg-gradient-to-br from-[#1e3a4c] via-[#2a4f5f] to-[#3d6b6b] relative overflow-hidden",children:[e.jsx("div",{className:"absolute inset-0 opacity-10",children:e.jsx("div",{className:"absolute inset-0 bg-[url('data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iNjAiIGhlaWdodD0iNjAiIHZpZXdCb3g9IjAgMCA2MCA2MCIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj48ZyBmaWxsPSJub25lIiBmaWxsLXJ1bGU9ImV2ZW5vZGQiPjxnIGZpbGw9IiNmZmZmZmYiIGZpbGwtb3BhY2l0eT0iMC40Ij48cGF0aCBkPSJNMzYgMzRoLTJ2LTRoMnY0em0wLTZ2LTRoLTJ2NGgyem0tNiA2aC0ydi00aDJ2NHptMC02di00aC0ydjRoMnoiLz48L2c+PC9nPjwvc3ZnPg==')]"})}),e.jsx("div",{className:"container mx-auto px-4 relative",children:e.jsxs("div",{className:"max-w-4xl mx-auto text-center space-y-8",children:[e.jsx("h2",{className:"text-3xl text-white font-sans md:text-5xl",children:"Ready to Level Up?"}),e.jsx("p",{className:"text-lg text-white/80 max-w-2xl mx-auto",children:"Join thousands of agents who are closing more deals, saving time, and growing their business with LevelUp."}),e.jsxs("div",{className:"flex flex-col sm:flex-row gap-4 justify-center",children:[e.jsxs(B,{size:"lg",onClick:()=>{var I;return(I=document.getElementById("pricing"))==null?void 0:I.scrollIntoView({behavior:"smooth"})},className:"px-10 py-7 text-lg font-semibold bg-white text-[#4a6b6d] hover:bg-white/90 shadow-2xl transition-all hover:scale-105",children:["Start Your Free Trial",e.jsx(vi,{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:oNe,alt:"LevelUp",className:"h-8"}),e.jsxs("p",{className:"text-sm",children:["© ",new Date().getFullYear()," LevelUp. All rights reserved."]}),e.jsxs("div",{className:"flex items-center gap-6",children:[e.jsx("a",{href:"/privacy-policy",className:"text-white/60 hover:text-white transition-colors text-sm",children:"Privacy Policy"}),e.jsx("a",{href:"mailto:support@relevelup.com",className:"text-white/60 hover:text-white transition-colors text-sm",children:"Contact Support"})]})]})})}),e.jsx(l1s,{open:b,onOpenChange:k}),e.jsx(Bs,{open:c,onOpenChange:d,children:e.jsxs(Fs,{className:"sm:max-w-md",children:[e.jsxs(qs,{children:[e.jsx($s,{className:"text-xl font-sans font-semibold",children:"Enter your details to get started"}),e.jsx(Ar,{children:(l==null?void 0:l.tier)==="individual_agent"&&!(l!=null&&l.skipTrial)?"Start your 7-day free trial":(l==null?void 0:l.tier)==="individual_agent"?"Subscribe to Individual Agent":(l==null?void 0:l.tier)==="brokerage_under_25"?"Subscribe to Brokerage (Under 25 Agents)":"Subscribe to Brokerage (Over 25 Agents)"})]}),e.jsxs("div",{className:"space-y-4 py-4",children:[e.jsxs("div",{children:[e.jsxs(re,{htmlFor:"dialog-name",children:["Full Name ",e.jsx("span",{className:"text-red-500",children:"*"})]}),e.jsx(we,{id:"dialog-name",type:"text",placeholder:"John Smith",value:m,onChange:I=>f(I.target.value),className:"mt-1",required:!0})]}),e.jsxs("div",{children:[e.jsxs(re,{htmlFor:"dialog-email",children:["Email Address ",e.jsx("span",{className:"text-red-500",children:"*"})]}),e.jsx(we,{id:"dialog-email",type:"email",placeholder:"you@example.com",value:u,onChange:I=>h(I.target.value),className:"mt-1",required:!0})]}),e.jsxs("div",{children:[e.jsxs(re,{htmlFor:"dialog-coupon",children:["Discount Code ",e.jsx("span",{className:"text-muted-foreground",children:"(Optional)"})]}),e.jsx(we,{id:"dialog-coupon",type:"text",placeholder:"Enter discount code",value:g,onChange:I=>y(I.target.value),className:"mt-1"})]})]}),e.jsx(B,{className:"w-full py-6 text-lg bg-[#4a6b6d] hover:bg-[#3d5a5c]",onClick:P,disabled:x,children:x?"Loading...":"Continue to Checkout"})]})})]})},$nt=()=>e.jsxs(e.Fragment,{children:[e.jsxs(ic,{children:[e.jsx("title",{children:"Privacy Policy | LevelUp"}),e.jsx("meta",{name:"description",content:"Privacy Policy for LevelUp platform"})]}),e.jsx("div",{className:"min-h-screen bg-background py-12 px-4 sm:px-6 lg:px-8",children:e.jsxs("div",{className:"max-w-3xl mx-auto",children:[e.jsx("h1",{className:"text-3xl font-bold text-foreground mb-8",children:"Privacy Policy"}),e.jsxs("div",{className:"prose prose-sm max-w-none text-muted-foreground space-y-6",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Last updated: January 17, 2026"}),e.jsxs("section",{children:[e.jsx("h2",{className:"text-xl font-semibold text-foreground mt-8 mb-4",children:"1. Introduction"}),e.jsx("p",{children:'Welcome to LevelUp ("we," "our," or "us"). We are committed to protecting your personal information and your right to privacy. This Privacy Policy explains how we collect, use, disclose, and safeguard your information when you use our platform.'})]}),e.jsxs("section",{children:[e.jsx("h2",{className:"text-xl font-semibold text-foreground mt-8 mb-4",children:"2. Information We Collect"}),e.jsx("p",{children:"We collect information that you provide directly to us, including:"}),e.jsxs("ul",{className:"list-disc pl-6 mt-2 space-y-1",children:[e.jsx("li",{children:"Name and contact information (email address, phone number)"}),e.jsx("li",{children:"Account credentials"}),e.jsx("li",{children:"Profile information"}),e.jsx("li",{children:"Transaction and billing information"}),e.jsx("li",{children:"Communications you send to us"})]})]}),e.jsxs("section",{children:[e.jsx("h2",{className:"text-xl font-semibold text-foreground mt-8 mb-4",children:"3. How We Use Your Information"}),e.jsx("p",{children:"We use the information we collect to:"}),e.jsxs("ul",{className:"list-disc pl-6 mt-2 space-y-1",children:[e.jsx("li",{children:"Provide, maintain, and improve our services"}),e.jsx("li",{children:"Process transactions and send related information"}),e.jsx("li",{children:"Send you technical notices and support messages"}),e.jsx("li",{children:"Respond to your comments and questions"}),e.jsx("li",{children:"Communicate with you about products, services, and events"})]})]}),e.jsxs("section",{children:[e.jsx("h2",{className:"text-xl font-semibold text-foreground mt-8 mb-4",children:"4. Information Sharing"}),e.jsx("p",{children:"We do not sell, trade, or otherwise transfer your personal information to third parties without your consent, except as described in this policy or as required by law."})]}),e.jsxs("section",{children:[e.jsx("h2",{className:"text-xl font-semibold text-foreground mt-8 mb-4",children:"5. Data Security"}),e.jsx("p",{children:"We implement appropriate technical and organizational measures to protect the security of your personal information. However, no method of transmission over the Internet is 100% secure."})]}),e.jsxs("section",{children:[e.jsx("h2",{className:"text-xl font-semibold text-foreground mt-8 mb-4",children:"6. Your Rights"}),e.jsx("p",{children:"You have the right to:"}),e.jsxs("ul",{className:"list-disc pl-6 mt-2 space-y-1",children:[e.jsx("li",{children:"Access your personal information"}),e.jsx("li",{children:"Correct inaccurate data"}),e.jsx("li",{children:"Request deletion of your data"}),e.jsx("li",{children:"Opt-out of marketing communications"})]})]}),e.jsxs("section",{children:[e.jsx("h2",{className:"text-xl font-semibold text-foreground mt-8 mb-4",children:"7. SMS / Text Messaging Program & Mobile Information"}),e.jsx("p",{children:"Your privacy is important to us. This section outlines how we collect, use, and protect your information when you use our services, including our SMS/text messaging program."}),e.jsxs("p",{className:"mt-3",children:[e.jsx("strong",{className:"text-foreground",children:"Information We Collect:"})," We collect personal information you provide, including your name, email address, phone number, and mobile number when you opt in to receive text messages from us."]}),e.jsxs("p",{className:"mt-3",children:[e.jsx("strong",{className:"text-foreground",children:"How We Use Your Information:"})," If you opt in, we use your mobile number to send SMS account notifications, real-time lead alerts, service updates, and customer support communications related to your LevelUp account."]}),e.jsxs("p",{className:"mt-3",children:[e.jsx("strong",{className:"text-foreground",children:"No Sharing of Mobile Information:"})," No mobile information will be shared with third parties/affiliates for marketing/promotional purposes. All the above categories exclude text messaging originator opt-in data and consent; this information will not be shared with any third parties."]}),e.jsxs("p",{className:"mt-3",children:[e.jsx("strong",{className:"text-foreground",children:"Your Rights:"})," You have the right to access, modify, or delete your personal information at any time. You may opt out of text messages at any time by replying STOP to any message. Reply HELP for help. Message and data rates may apply. Message frequency varies."]}),e.jsxs("p",{className:"mt-3",children:["For questions about this policy, contact us at"," ",e.jsx("a",{href:"mailto:support@relevelup.com",className:"text-primary hover:underline",children:"support@relevelup.com"}),"."]})]}),e.jsxs("section",{children:[e.jsx("h2",{className:"text-xl font-semibold text-foreground mt-8 mb-4",children:"8. Third-Party Services"}),e.jsx("p",{children:"Our platform may integrate with third-party services such as Facebook and Instagram for social media posting features. When you connect these accounts, you are subject to their respective privacy policies."})]}),e.jsxs("section",{children:[e.jsx("h2",{className:"text-xl font-semibold text-foreground mt-8 mb-4",children:"10. SMS Privacy Policy"}),e.jsx("p",{children:"We collect contact information you provide to us, including your name, email address, phone number, and business details, in order to provide our services, respond to inquiries, and deliver requested communications."}),e.jsx("p",{className:"mt-3",children:"If you choose to opt in to SMS communications from LevelUp, we may send you text messages including account notifications, real-time lead alerts, service updates, and customer support communications related to your LevelUp account."}),e.jsx("p",{className:"mt-3",children:"SMS consent is not shared with third parties or affiliates for marketing purposes. Mobile information will not be shared with third parties or affiliates for marketing or promotional purposes. Text messaging originator opt-in data and consent will not be shared with any third parties, except with vendors, aggregators, and providers that help us deliver these text messages."}),e.jsx("p",{className:"mt-3",children:"Message frequency may vary depending on your activity and use of our services. Message and data rates may apply."}),e.jsxs("p",{className:"mt-3",children:["You can opt out at any time by replying STOP. For help, reply HELP or contact us at"," ",e.jsx("a",{href:"mailto:hello@relevelup.com",className:"text-primary hover:underline",children:"hello@relevelup.com"}),"."]})]}),e.jsxs("section",{children:[e.jsx("h2",{className:"text-xl font-semibold text-foreground mt-8 mb-4",children:"11. Contact Us"}),e.jsxs("p",{children:["If you have questions about this Privacy Policy, please contact us at"," ",e.jsx("a",{href:"mailto:support@relevelup.com",className:"text-primary hover:underline",children:"support@relevelup.com"})]})]})]})]})})]}),Unt=()=>e.jsxs(e.Fragment,{children:[e.jsxs(ic,{children:[e.jsx("title",{children:"Terms of Service | LevelUp"}),e.jsx("meta",{name:"description",content:"Terms of Service for LevelUp platform"})]}),e.jsx("div",{className:"min-h-screen bg-background py-12 px-4 sm:px-6 lg:px-8",children:e.jsxs("div",{className:"max-w-3xl mx-auto",children:[e.jsx("h1",{className:"text-3xl font-bold text-foreground mb-8",children:"Terms of Service"}),e.jsxs("div",{className:"prose prose-sm max-w-none text-muted-foreground space-y-6",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Last updated: January 17, 2026"}),e.jsxs("section",{children:[e.jsx("h2",{className:"text-xl font-semibold text-foreground mt-8 mb-4",children:"1. Acceptance of Terms"}),e.jsx("p",{children:'By accessing or using the LevelUp platform ("Service"), you agree to be bound by these Terms of Service. If you do not agree to these terms, please do not use our Service.'})]}),e.jsxs("section",{children:[e.jsx("h2",{className:"text-xl font-semibold text-foreground mt-8 mb-4",children:"2. Description of Service"}),e.jsx("p",{children:"LevelUp provides a platform for real estate professionals to access training, resources, marketing tools, and community features. We reserve the right to modify or discontinue the Service at any time."})]}),e.jsxs("section",{children:[e.jsx("h2",{className:"text-xl font-semibold text-foreground mt-8 mb-4",children:"3. User Accounts"}),e.jsx("p",{children:"To use certain features, you must create an account. You agree to:"}),e.jsxs("ul",{className:"list-disc pl-6 mt-2 space-y-1",children:[e.jsx("li",{children:"Provide accurate and complete information"}),e.jsx("li",{children:"Maintain the security of your account credentials"}),e.jsx("li",{children:"Notify us immediately of any unauthorized access"}),e.jsx("li",{children:"Accept responsibility for all activities under your account"})]})]}),e.jsxs("section",{children:[e.jsx("h2",{className:"text-xl font-semibold text-foreground mt-8 mb-4",children:"4. Acceptable Use"}),e.jsx("p",{children:"You agree not to:"}),e.jsxs("ul",{className:"list-disc pl-6 mt-2 space-y-1",children:[e.jsx("li",{children:"Violate any applicable laws or regulations"}),e.jsx("li",{children:"Infringe on the rights of others"}),e.jsx("li",{children:"Upload malicious code or interfere with the Service"}),e.jsx("li",{children:"Attempt to gain unauthorized access to any part of the Service"}),e.jsx("li",{children:"Use the Service for any unlawful purpose"})]})]}),e.jsxs("section",{children:[e.jsx("h2",{className:"text-xl font-semibold text-foreground mt-8 mb-4",children:"5. Intellectual Property"}),e.jsx("p",{children:"The Service and its original content, features, and functionality are owned by LevelUp and are protected by international copyright, trademark, and other intellectual property laws."})]}),e.jsxs("section",{children:[e.jsx("h2",{className:"text-xl font-semibold text-foreground mt-8 mb-4",children:"6. Third-Party Integrations"}),e.jsx("p",{children:"Our Service may integrate with third-party platforms such as Facebook and Instagram. Your use of these integrations is subject to the terms and policies of those third parties. We are not responsible for the content or practices of any third-party services."})]}),e.jsxs("section",{children:[e.jsx("h2",{className:"text-xl font-semibold text-foreground mt-8 mb-4",children:"7. Payment Terms"}),e.jsx("p",{children:"Certain features may require payment. By subscribing to paid features, you agree to pay all applicable fees. All payments are non-refundable unless otherwise specified."})]}),e.jsxs("section",{children:[e.jsx("h2",{className:"text-xl font-semibold text-foreground mt-8 mb-4",children:"8. Limitation of Liability"}),e.jsx("p",{children:"To the maximum extent permitted by law, LevelUp shall not be liable for any indirect, incidental, special, consequential, or punitive damages resulting from your use of the Service."})]}),e.jsxs("section",{children:[e.jsx("h2",{className:"text-xl font-semibold text-foreground mt-8 mb-4",children:"9. Termination"}),e.jsx("p",{children:"We may terminate or suspend your account at any time, without prior notice, for conduct that we believe violates these Terms or is harmful to other users, us, or third parties."})]}),e.jsxs("section",{children:[e.jsx("h2",{className:"text-xl font-semibold text-foreground mt-8 mb-4",children:"10. Changes to Terms"}),e.jsx("p",{children:"We reserve the right to modify these Terms at any time. We will notify you of significant changes by posting a notice on our platform. Continued use of the Service constitutes acceptance of the modified terms."})]}),e.jsxs("section",{children:[e.jsx("h2",{className:"text-xl font-semibold text-foreground mt-8 mb-4",children:"11. SMS / Text Messaging Terms"}),e.jsxs("div",{className:"rounded-lg border border-primary/30 bg-primary/5 p-4 mb-4 text-sm",children:[e.jsx("strong",{children:"To opt in:"})," Submit our public SMS opt-in form at"," ",e.jsx("a",{href:"/sms-opt-in",className:"text-primary hover:underline font-medium",children:"/sms-opt-in"})," ","— consent is captured with timestamp and the exact disclosure text shown below."]}),e.jsx("p",{children:"By opting in to receive text messages from LevelUp, you agree to the following terms:"}),e.jsx("p",{className:"mt-2",children:"You consent to receive recurring SMS/MMS messages from LevelUp, including account notifications, real-time lead alerts, service updates, and customer support communications. Message frequency varies. Message and data rates may apply. Consent is not a condition of purchase."}),e.jsxs("p",{className:"mt-2",children:["You may opt out at any time by replying STOP to any message. After opting out, you will receive a confirmation message and no further messages will be sent. For assistance, reply HELP or contact us at"," ",e.jsx("a",{href:"mailto:support@relevelup.com",className:"text-primary hover:underline",children:"support@relevelup.com"}),"."]}),e.jsxs("p",{className:"mt-2",children:["No mobile information will be shared with third parties or affiliates for marketing or promotional purposes. Text messaging originator opt-in data and consent will not be shared with any third parties. See our"," ",e.jsx("a",{href:"/privacy-policy",className:"text-primary hover:underline",children:"Privacy Policy"})," ","for full details."]})]}),e.jsxs("section",{children:[e.jsx("h2",{className:"text-xl font-semibold text-foreground mt-8 mb-4",children:"12. Contact Us"}),e.jsxs("p",{children:["If you have questions about these Terms, please contact us at"," ",e.jsx("a",{href:"mailto:support@relevelup.com",className:"text-primary hover:underline",children:"support@relevelup.com"})]})]})]})]})})]}),m1s=()=>e.jsxs(e.Fragment,{children:[e.jsxs(ic,{children:[e.jsx("title",{children:"Data Deletion | LevelUp"}),e.jsx("meta",{name:"description",content:"Data deletion instructions for LevelUp platform"})]}),e.jsx("div",{className:"min-h-screen bg-background py-12 px-4 sm:px-6 lg:px-8",children:e.jsxs("div",{className:"max-w-3xl mx-auto",children:[e.jsx("h1",{className:"text-3xl font-bold text-foreground mb-8",children:"Data Deletion Instructions"}),e.jsxs("div",{className:"prose prose-sm max-w-none text-muted-foreground space-y-6",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Last updated: January 17, 2026"}),e.jsxs("section",{children:[e.jsx("h2",{className:"text-xl font-semibold text-foreground mt-8 mb-4",children:"How to Request Data Deletion"}),e.jsx("p",{children:"If you wish to have your data deleted from LevelUp, you can request deletion through one of the following methods:"})]}),e.jsxs("section",{children:[e.jsx("h2",{className:"text-xl font-semibold text-foreground mt-8 mb-4",children:"Option 1: Email Request"}),e.jsxs("p",{children:["Send an email to"," ",e.jsx("a",{href:"mailto:support@relevelup.com",className:"text-primary hover:underline",children:"support@relevelup.com"})," ",'with the subject line "Data Deletion Request" and include:']}),e.jsxs("ul",{className:"list-disc pl-6 mt-2 space-y-1",children:[e.jsx("li",{children:"Your full name"}),e.jsx("li",{children:"The email address associated with your account"}),e.jsx("li",{children:"A clear statement requesting deletion of your data"})]})]}),e.jsxs("section",{children:[e.jsx("h2",{className:"text-xl font-semibold text-foreground mt-8 mb-4",children:"Option 2: Account Settings"}),e.jsx("p",{children:"If you have an active account, you can request data deletion through your account settings:"}),e.jsxs("ol",{className:"list-decimal pl-6 mt-2 space-y-1",children:[e.jsx("li",{children:"Log in to your LevelUp account"}),e.jsx("li",{children:"Navigate to your Profile settings"}),e.jsx("li",{children:"Contact support through the Support page to request account deletion"})]})]}),e.jsxs("section",{children:[e.jsx("h2",{className:"text-xl font-semibold text-foreground mt-8 mb-4",children:"What Data Will Be Deleted"}),e.jsx("p",{children:"Upon a valid deletion request, we will delete:"}),e.jsxs("ul",{className:"list-disc pl-6 mt-2 space-y-1",children:[e.jsx("li",{children:"Your account information (name, email, profile data)"}),e.jsx("li",{children:"Any content you have created or uploaded"}),e.jsx("li",{children:"Your activity history and preferences"}),e.jsx("li",{children:"Connected social media account tokens and data"})]})]}),e.jsxs("section",{children:[e.jsx("h2",{className:"text-xl font-semibold text-foreground mt-8 mb-4",children:"Data Retention"}),e.jsx("p",{children:"Some data may be retained for legal or legitimate business purposes, such as:"}),e.jsxs("ul",{className:"list-disc pl-6 mt-2 space-y-1",children:[e.jsx("li",{children:"Transaction records required for financial reporting"}),e.jsx("li",{children:"Data necessary to comply with legal obligations"}),e.jsx("li",{children:"Anonymized or aggregated data that cannot identify you"})]})]}),e.jsxs("section",{children:[e.jsx("h2",{className:"text-xl font-semibold text-foreground mt-8 mb-4",children:"Facebook/Instagram Data"}),e.jsx("p",{children:"If you have connected your Facebook or Instagram account to LevelUp, you can also manage your data through Facebook's settings:"}),e.jsxs("ol",{className:"list-decimal pl-6 mt-2 space-y-1",children:[e.jsx("li",{children:"Go to your Facebook Settings & Privacy → Settings"}),e.jsx("li",{children:'Click on "Apps and Websites"'}),e.jsx("li",{children:'Find LevelUp and click "Remove"'}),e.jsx("li",{children:"This will revoke our access to your Facebook/Instagram data"})]})]}),e.jsxs("section",{children:[e.jsx("h2",{className:"text-xl font-semibold text-foreground mt-8 mb-4",children:"Processing Time"}),e.jsx("p",{children:"We will process your data deletion request within 30 days of receiving it. You will receive a confirmation email once your data has been deleted."})]}),e.jsxs("section",{children:[e.jsx("h2",{className:"text-xl font-semibold text-foreground mt-8 mb-4",children:"Contact Us"}),e.jsxs("p",{children:["If you have questions about data deletion, please contact us at"," ",e.jsx("a",{href:"mailto:support@relevelup.com",className:"text-primary hover:underline",children:"support@relevelup.com"})]})]})]})]})})]}),qnt="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.",p1s=H5({name:pl().trim().min(1,"Name is required").max(200),phone:pl().trim().min(10,"Enter a valid mobile number").max(30).regex(/^[+\d\s()\-.]+$/,"Enter a valid mobile number"),email:pl().trim().email("Enter a valid email").max(320).optional().or(qx(""))});function f1s(){const[s,t]=N.useState(""),[n,r]=N.useState(""),[a,i]=N.useState(""),[l,o]=N.useState(!1),[c,d]=N.useState(!1),[u,h]=N.useState(!1),m=async f=>{var x;if(f.preventDefault(),!l){ie.error("Please check the consent box to opt in.");return}const g=p1s.safeParse({name:s,phone:n,email:a});if(!g.success){ie.error(((x=g.error.issues[0])==null?void 0:x.message)??"Please check your inputs.");return}d(!0);const{error:y}=await H.from("sms_opt_in_consents").insert({name:g.data.name,phone:g.data.phone,email:g.data.email||null,consent_text:qnt,source:"web_form",user_agent:navigator.userAgent.slice(0,500)});if(d(!1),y){ie.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(ic,{children:[e.jsx("title",{children:"SMS Opt-In | LevelUp"}),e.jsx("meta",{name:"description",content:"Opt in to receive SMS account notifications and real-time lead alerts from LevelUp. Review consent terms, message frequency, and STOP/HELP instructions."}),e.jsx("link",{rel:"canonical",href:"https://dashboard.relevelup.com/sms-opt-in"})]}),e.jsxs("div",{className:"max-w-2xl mx-auto",children:[e.jsxs("header",{className:"text-center mb-8",children:[e.jsx("div",{className:"inline-flex items-center justify-center w-14 h-14 rounded-2xl bg-primary/10 text-primary mb-4",children:e.jsx(xo,{className:"w-7 h-7"})}),e.jsx("h1",{className:"text-3xl md:text-4xl font-bold tracking-tight",children:"LevelUp — SMS Opt-In"}),e.jsx("p",{className:"text-muted-foreground mt-3 max-w-xl mx-auto",children:"Sign up to receive SMS account notifications and real-time lead alerts from LevelUp. These messages help subscribed real estate agents review and respond to new consumer inquiries submitted through their websites."})]}),u?e.jsxs(_e,{className:"p-8 text-center",children:[e.jsx(Hr,{className:"w-14 h-14 text-primary mx-auto mb-4"}),e.jsx("h2",{className:"text-2xl font-semibold mb-2",children:"You're opted in!"}),e.jsxs("p",{className:"text-muted-foreground",children:["You'll now receive SMS account notifications and real-time lead alerts from LevelUp. Reply ",e.jsx("strong",{children:"STOP"})," at any time to opt out, or ",e.jsx("strong",{children:"HELP"})," for assistance."]})]}):e.jsx(_e,{className:"p-6 md:p-8",children:e.jsxs("form",{onSubmit:m,className:"space-y-5",children:[e.jsxs("div",{children:[e.jsx(re,{htmlFor:"name",children:"Full Name *"}),e.jsx(we,{id:"name",value:s,onChange:f=>t(f.target.value),required:!0,maxLength:200,autoComplete:"name",className:"mt-1.5"})]}),e.jsxs("div",{children:[e.jsx(re,{htmlFor:"phone",children:"Mobile Number *"}),e.jsx(we,{id:"phone",type:"tel",value:n,onChange:f=>r(f.target.value),required:!0,maxLength:30,placeholder:"(555) 123-4567",autoComplete:"tel",className:"mt-1.5"})]}),e.jsxs("div",{children:[e.jsx(re,{htmlFor:"email",children:"Email (optional)"}),e.jsx(we,{id:"email",type:"email",value:a,onChange:f=>i(f.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(Bi,{id:"consent",checked:l,onCheckedChange:f=>o(f===!0),className:"mt-0.5"}),e.jsx(re,{htmlFor:"consent",className:"text-sm leading-relaxed font-normal cursor-pointer",children:qnt})]})}),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(cr,{to:"/terms-of-service",className:"text-primary underline underline-offset-2",children:"SMS Terms & Conditions"})," ","and"," ",e.jsx(cr,{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.jsxs("div",{className:"flex items-center justify-center gap-2 text-xs text-muted-foreground pt-2",children:[e.jsx(Wv,{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 ySt="/assets/levelup-logo-horizontal-DEFNc0ms.png",g1s=H5({email:pl().email("Invalid email address"),password:pl().min(6,"Password must be at least 6 characters")}),x1s="https://dashboard.relevelup.com",Xte="/oauth-connect",Owe="levelupOAuthRouteHistory";function Vnt(s){return s.startsWith("/")&&!s.startsWith("//")&&!s.includes("://")}function y1s(s){const t=Date.now(),n=15e3;try{const i=[...JSON.parse(sessionStorage.getItem(Owe)??"[]").filter(o=>t-o.ato.route));return i.length>=6&&l.has("auth")&&l.has("consent")}catch{return sessionStorage.setItem(Owe,JSON.stringify([{route:s,at:t}])),!1}}function v1s(){sessionStorage.removeItem(Owe)}const b1s=()=>{const{signIn:s,user:t,loading:n}=Ls(),r=(t==null?void 0:t.id)??null,a=tr(),[i]=$c(),l=i.get("authorization_id")??"",o=i.get("next")??"",[c,d]=N.useState(!1),[u,h]=N.useState({}),[m,f]=N.useState(""),[g,y]=N.useState(!1),[x,_]=N.useState(!1),[b,k]=N.useState(null),A=N.useRef(!1);N.useEffect(()=>{if(l&&window.location.hostname==="tile-portal.lovable.app"){const I=new URL("/auth",x1s);I.searchParams.set("next",`${Xte}?authorization_id=${encodeURIComponent(l)}`),window.location.replace(I.toString());return}if(l){const I=`${Xte}?authorization_id=${encodeURIComponent(l)}`;sessionStorage.setItem("redirectAfterLogin",I);return}o&&Vnt(o)&&sessionStorage.setItem("redirectAfterLogin",o)},[l,o]),N.useEffect(()=>{if(n||!r||A.current)return;const I=l?`${Xte}?authorization_id=${encodeURIComponent(l)}`:sessionStorage.getItem("redirectAfterLogin")||"/dashboard";if(!Vnt(I)){sessionStorage.removeItem("redirectAfterLogin"),A.current=!0,a("/dashboard",{replace:!0});return}const M=I.startsWith(Xte)||I.startsWith("/oauth/consent")||I.startsWith("/.lovable/oauth/consent");if(M&&y1s("auth")){k("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}A.current=!0,M||(v1s(),sessionStorage.removeItem("redirectAfterLogin")),a(I,{replace:!0})},[l,n,a,r]);const T=async I=>{I.preventDefault(),h({}),d(!0);const M=new FormData(I.currentTarget),L=M.get("email"),z=M.get("password");try{g1s.parse({email:L,password:z}),await s(L,z)}catch($){if($ instanceof Ums){const V={};$.issues.forEach(W=>{W.path[0]&&(V[W.path[0]]=W.message)}),h(V)}}finally{d(!1)}},P=async()=>{if(!m){ie.error("Please enter your email address");return}y(!0);try{const{error:I}=await H.functions.invoke("send-password-reset",{body:{email:m,redirectTo:"https://dashboard.relevelup.com/profile?reset=true"}});if(I)throw I;ie.success("Password reset email sent! Check your inbox."),_(!1),f("")}catch(I){ie.error(I instanceof Error?I.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(cr,{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:ySt,alt:"LevelUp",className:"h-12 w-auto"})})}),e.jsxs(_e,{className:"border-0 shadow-2xl bg-white/95 backdrop-blur-sm",children:[e.jsxs(zt,{className:"space-y-1 text-center pb-4",children:[e.jsx(qt,{className:"text-3xl font-bold text-[#2a4347]",style:{fontFamily:"'Libre Baskerville', serif"},children:"Welcome Back"}),e.jsx(_r,{className:"text-gray-600",children:b||"Sign in to access your dashboard"})]}),e.jsx(De,{children:e.jsxs("form",{onSubmit:T,className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{htmlFor:"signin-email",className:"text-gray-700",children:"Email"}),e.jsx(we,{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(re,{htmlFor:"signin-password",className:"text-gray-700",children:"Password"}),e.jsx(we,{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(Bs,{open:x,onOpenChange:_,children:[e.jsx(Ao,{asChild:!0,children:e.jsx(B,{variant:"link",className:"w-full text-sm text-[#4a6b6d] hover:text-[#3d5a5c]",children:"Forgot password?"})}),e.jsxs(Fs,{className:"bg-white",children:[e.jsxs(qs,{children:[e.jsx($s,{className:"text-[#2a4347]",style:{fontFamily:"'Libre Baskerville', serif"},children:"Reset Password"}),e.jsx(Ar,{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(re,{htmlFor:"reset-email",className:"text-gray-700",children:"Email"}),e.jsx(we,{id:"reset-email",type:"email",placeholder:"your@email.com",value:m,onChange:I=>f(I.target.value),className:"border-gray-300 focus:border-[#4a6b6d] focus:ring-[#4a6b6d]"})]}),e.jsx(B,{onClick:P,className:"w-full bg-[#4a6b6d] hover:bg-[#3d5a5c] text-white",disabled:g,children:g?"Sending...":"Send Reset Link"})]})]})]})]})})]}),e.jsxs("p",{className:"text-center text-white/70 text-sm mt-6",children:["Don't have an account?"," ",e.jsx(cr,{to:"/",className:"text-white hover:underline font-medium",children:"View Plans"})]})]})})]})]})},Hnt=()=>H.auth.oauth,_1s="https://dashboard.relevelup.com",w1s="/oauth-connect",Fwe="levelupOAuthRouteHistory",j1s="https://relzejiswnotikjgvjhz.supabase.co/auth/v1",N1s="eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6InJlbHplamlzd25vdGlramd2amh6Iiwicm9sZSI6ImFub24iLCJpYXQiOjE3NjE5NTAzNDQsImV4cCI6MjA3NzUyNjM0NH0.dzIkIr_oFSbFE3oWS0ktIr83iKHHkZxt40Gc7SpC_mM";function k1s(s){return s.startsWith("/")&&!s.startsWith("//")&&!s.includes("://")}function S1s(s){const t=Date.now(),n=15e3;try{const i=[...JSON.parse(sessionStorage.getItem(Fwe)??"[]").filter(o=>t-o.ato.route));return i.length>=6&&l.has("auth")&&l.has("consent")}catch{return sessionStorage.setItem(Fwe,JSON.stringify([{route:s,at:t}])),!1}}function C1s(){sessionStorage.removeItem(Fwe)}async function Gnt(s,t,n){const r=await fetch(`${j1s}${s}`,{...n,headers:{Authorization:`Bearer ${t}`,apikey:N1s,"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 eMe(){var y;const{user:s,session:t,loading:n}=Ls(),r=(s==null?void 0:s.id)??null,a=(t==null?void 0:t.access_token)??null,[i]=$c(),l=i.get("authorization_id")??"",[o,c]=N.useState(null),[d,u]=N.useState(null),[h,m]=N.useState(!1);N.useEffect(()=>{let x=!0;return(async()=>{if(!l){u("Missing authorization_id");return}const _=`${w1s}?authorization_id=${encodeURIComponent(l)}`;if(window.location.hostname==="tile-portal.lovable.app"){window.location.href=`${_1s}${_}`;return}if(n)return;if(!r){if(S1s("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}k1s(_)&&sessionStorage.setItem("redirectAfterLogin",_),window.location.replace(`/auth?next=${encodeURIComponent(_)}`);return}if(!a)return;C1s(),sessionStorage.removeItem("redirectAfterLogin");const b=Hnt(),{data:k,error:A}=b?await b.getAuthorizationDetails(l):await Gnt(`/oauth/authorizations/${encodeURIComponent(l)}`,a);if(!x)return;if(A){u(A.message);return}const T=(k==null?void 0:k.redirect_url)??(k==null?void 0:k.redirect_to);if(T&&!(k!=null&&k.client)){window.location.href=T;return}c(k)})(),()=>{x=!1}},[a,l,n,r]);async function f(x){if(!(t!=null&&t.access_token)){u("Your sign-in session is not ready yet. Please refresh and try again.");return}m(!0);const _=Hnt(),{data:b,error:k}=_?x?await _.approveAuthorization(l,{skipBrowserRedirect:!0}):await _.denyAuthorization(l,{skipBrowserRedirect:!0}):await Gnt(`/oauth/authorizations/${encodeURIComponent(l)}/consent`,t.access_token,{method:"POST",body:JSON.stringify({action:x?"approve":"deny"})});if(k){m(!1),u(k.message);return}const A=(b==null?void 0:b.redirect_url)??(b==null?void 0:b.redirect_to);if(!A){m(!1),u("No redirect returned by the authorization server.");return}window.location.href=A}if(d)return e.jsx("div",{className:"min-h-screen flex items-center justify-center bg-background p-4",children:e.jsx(_e,{className:"w-full max-w-md",children:e.jsxs(zt,{children:[e.jsx(qt,{children:"Authorization error"}),e.jsx(_r,{children:d})]})})});if(!o)return e.jsx("div",{className:"min-h-screen flex items-center justify-center bg-background",children:e.jsx(us,{className:"h-8 w-8 animate-spin text-primary"})});const g=((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(_e,{className:"w-full max-w-md",children:[e.jsxs(zt,{children:[e.jsxs(qt,{children:["Connect ",g," to LevelUp"]}),e.jsxs(_r,{children:[g," is requesting access to use LevelUp tools on your behalf. You can revoke access at any time."]})]}),e.jsxs(De,{className:"flex gap-3 justify-end",children:[e.jsx(B,{variant:"outline",disabled:h,onClick:()=>f(!1),children:"Deny"}),e.jsx(B,{disabled:h,onClick:()=>f(!0),children:h?e.jsx(us,{className:"h-4 w-4 animate-spin"}):"Approve"})]})]})})}const vSt=s=>{const[t,n]=N.useState(null),[r,a]=N.useState(!0);return N.useEffect(()=>{if(!s){a(!1);return}(async()=>{try{const{data:o}=await H.storage.from("avatars").list(`${s}`);if(o&&o.length>0){const{data:c}=H.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 H.storage.from("avatars").list(`${s}`);if(l&&l.length>0){const{data:o}=H.storage.from("avatars").getPublicUrl(`${s}/${l[0].name}`);n(`${o.publicUrl}?t=${Date.now()}`)}}catch(l){console.error("Error refreshing avatar:",l)}}}},bSt=async s=>{const t=new Map;return await Promise.all(s.map(async n=>{try{const{data:r}=await H.storage.from("avatars").list(`${n}`);if(r&&r.length>0){const{data:a}=H.storage.from("avatars").getPublicUrl(`${n}/${r[0].name}`);t.set(n,a.publicUrl)}}catch{}})),t},A1s=s=>{const[t,n]=N.useState({isTrial:!1,isExpired:!1,expiresAt:null,daysLeft:null,loading:!0});return N.useEffect(()=>{if(!s){n(a=>({...a,loading:!1}));return}(async()=>{try{const{data:a,error:i}=await H.from("profiles").select("is_trial, trial_expires_at, subscription_status, subscription_end_date").eq("id",s).single();if(i){console.error("Error fetching trial status:",i),n(h=>({...h,loading:!1}));return}const l=(a==null?void 0:a.subscription_status)==="trialing",o=!!(a!=null&&a.is_trial),c=!!(a!=null&&a.trial_expires_at)&&new Date(a.trial_expires_at).getTime()>Date.now()&&(a==null?void 0:a.subscription_status)!=="active",d=l&&(a==null?void 0:a.subscription_end_date)||(a==null?void 0:a.trial_expires_at)||(a==null?void 0:a.subscription_end_date)||null;if((l||o||c)&&!!d&&d){const h=new Date().getTime(),m=new Date(d).getTime(),f=Math.ceil((m-h)/(1e3*60*60*24)),g=f<=0;n({isTrial:!0,isExpired:g,expiresAt:d,daysLeft:g?0:f,loading:!1})}else n({isTrial:!1,isExpired:!1,expiresAt:null,daysLeft:null,loading:!1})}catch(a){console.error("Error in useTrialStatus:",a),n(i=>({...i,loading:!1}))}})()},[s]),t},_St=()=>{const{data:s,isLoading:t}=mt({queryKey:["feature-flags"],queryFn:async()=>{const{data:r,error:a}=await H.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")}},Wnt="community_last_seen_post_at";function T1s(){const{user:s}=Ls(),t=Id(),[n,r]=N.useState(0),[a,i]=N.useState(null);N.useEffect(()=>{if(!s)return;const o=localStorage.getItem(`${Wnt}_${s.id}`);i(o)},[s]),N.useEffect(()=>{if(!s)return;const o=`community_unread_count_${s.id}`,c=2*60*1e3;(async()=>{try{const f=sessionStorage.getItem(o);if(f){const g=JSON.parse(f);if(g.ts&&Date.now()-g.ts{if(!s)return;const o=H.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 H.from("profiles").select("name").eq("id",d.user_id).single(),m=(h==null?void 0:h.name)||"Someone",f=d.content.replace(/@\[([^\]]+)\]\([^)]+\)/g,"@$1"),g=f.length>50?f.substring(0,50)+"...":f;u||ie("New Community Post",{description:`${m}: ${g}`,action:{label:"View",onClick:()=>{window.location.href="/community"}}})}).subscribe();return()=>{H.removeChannel(o)}},[s,t.pathname]);const l=N.useCallback(()=>{if(!s)return;const o=new Date().toISOString();localStorage.setItem(`${Wnt}_${s.id}`,o),i(o),r(0)},[s]);return N.useEffect(()=>{t.pathname==="/community"&&n>0&&l()},[t.pathname,n,l]),{unreadCount:n,markAsRead:l}}function E1s(){const{isAdmin:s}=Ls(),{data:t=0}=mt({queryKey:["wishlist-open-count"],queryFn:async()=>{const{count:n,error:r}=await H.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 D7="weekly_reels";function GUe(){const{user:s,loading:t,isAdmin:n}=Ls(),{data:r,isLoading:a}=mt({queryKey:["feature-entitlement",D7,s==null?void 0:s.id],enabled:!!s&&!n,staleTime:5*60*1e3,queryFn:async()=>{const{data:i,error:l}=await H.from("feature_entitlements").select("enabled, expires_at, tier").eq("user_id",s.id).eq("feature_key",D7).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}}var V4e="Collapsible",[M1s,wSt]=Um(V4e),[L1s,WUe]=M1s(V4e),jSt=N.forwardRef((s,t)=>{const{__scopeCollapsible:n,open:r,defaultOpen:a,disabled:i,onOpenChange:l,...o}=s,[c,d]=Ng({prop:r,defaultProp:a??!1,onChange:l,caller:V4e});return e.jsx(L1s,{scope:n,disabled:i,contentId:_g(),open:c,onOpenToggle:N.useCallback(()=>d(u=>!u),[d]),children:e.jsx(Da.div,{"data-state":XUe(c),"data-disabled":i?"":void 0,...o,ref:t})})});jSt.displayName=V4e;var NSt="CollapsibleTrigger",KUe=N.forwardRef((s,t)=>{const{__scopeCollapsible:n,...r}=s,a=WUe(NSt,n);return e.jsx(Da.button,{type:"button","aria-controls":a.contentId,"aria-expanded":a.open||!1,"data-state":XUe(a.open),"data-disabled":a.disabled?"":void 0,disabled:a.disabled,...r,ref:t,onClick:la(s.onClick,a.onOpenToggle)})});KUe.displayName=NSt;var YUe="CollapsibleContent",ZUe=N.forwardRef((s,t)=>{const{forceMount:n,...r}=s,a=WUe(YUe,s.__scopeCollapsible);return e.jsx(Xf,{present:n||a.open,children:({present:i})=>e.jsx(P1s,{...r,ref:t,present:i})})});ZUe.displayName=YUe;var P1s=N.forwardRef((s,t)=>{const{__scopeCollapsible:n,present:r,children:a,...i}=s,l=WUe(YUe,n),[o,c]=N.useState(r),d=N.useRef(null),u=jo(t,d),h=N.useRef(0),m=h.current,f=N.useRef(0),g=f.current,y=l.open||o,x=N.useRef(y),_=N.useRef(void 0);return N.useEffect(()=>{const b=requestAnimationFrame(()=>x.current=!1);return()=>cancelAnimationFrame(b)},[]),gf(()=>{const b=d.current;if(b){_.current=_.current||{transitionDuration:b.style.transitionDuration,animationName:b.style.animationName},b.style.transitionDuration="0s",b.style.animationName="none";const k=b.getBoundingClientRect();h.current=k.height,f.current=k.width,x.current||(b.style.transitionDuration=_.current.transitionDuration,b.style.animationName=_.current.animationName),c(r)}},[l.open,r]),e.jsx(Da.div,{"data-state":XUe(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":g?`${g}px`:void 0,...s.style},children:y&&a})});function XUe(s){return s?"open":"closed"}var kSt=jSt,I1s=KUe,D1s=ZUe;const Kv=kSt,Yv=KUe,Zv=ZUe,R1s="/assets/levelup-logo-Eif24dqY.png",O1s="/assets/levelup-logo-icon-C-7iromj.png",F1s="/assets/levelup-logo-mobile-B9skSjUG.png";var BQ=s=>s.type==="checkbox",LI=s=>s instanceof Date,Tv=s=>s==null;const SSt=s=>typeof s=="object";var Yf=s=>!Tv(s)&&!Array.isArray(s)&&SSt(s)&&!LI(s),CSt=s=>Yf(s)&&s.target?BQ(s.target)?s.target.checked:s.target.value:s,z1s=s=>s.substring(0,s.search(/\.\d+(\.|$)/))||s,ASt=(s,t)=>s.has(z1s(t)),B1s=s=>{const t=s.constructor&&s.constructor.prototype;return Yf(t)&&t.hasOwnProperty("isPrototypeOf")},QUe=typeof window<"u"&&typeof window.HTMLElement<"u"&&typeof document<"u";function zg(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(!(QUe&&(s instanceof Blob||r))&&(n||Yf(s)))if(t=n?[]:{},!n&&!B1s(s))t=s;else for(const a in s)s.hasOwnProperty(a)&&(t[a]=zg(s[a]));else return s;return t}var H4e=s=>/^\w*$/.test(s),If=s=>s===void 0,JUe=s=>Array.isArray(s)?s.filter(Boolean):[],eqe=s=>JUe(s.replace(/["|']|\]/g,"").split(/\.|\[/)),fi=(s,t,n)=>{if(!t||!Yf(s))return n;const r=(H4e(t)?[t]:eqe(t)).reduce((a,i)=>Tv(a)?a:a[i],s);return If(r)||r===s?If(s[t])?n:s[t]:r},p_=s=>typeof s=="boolean",zu=(s,t,n)=>{let r=-1;const a=H4e(t)?[t]:eqe(t),i=a.length,l=i-1;for(;++rRt.useContext(tqe),$1s=s=>{const{children:t,...n}=s;return Rt.createElement(tqe.Provider,{value:n},t)};var TSt=(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]!==F2.all&&(t._proxyFormState[l]=!r||F2.all),n&&(n[l]=!0),s[l]}});return a};const sqe=typeof window<"u"?Rt.useLayoutEffect:Rt.useEffect;function U1s(s){const t=G4e(),{control:n=t.control,disabled:r,name:a,exact:i}=s||{},[l,o]=Rt.useState(n._formState),c=Rt.useRef({isDirty:!1,isLoading:!1,dirtyFields:!1,touchedFields:!1,validatingFields:!1,isValidating:!1,isValid:!1,errors:!1});return sqe(()=>n._subscribe({name:a,formState:c.current,exact:i,callback:d=>{!r&&o({...n._formState,...d})}}),[a,r,i]),Rt.useEffect(()=>{c.current.isValid&&n._setValid(!0)},[n]),Rt.useMemo(()=>TSt(l,n,c.current,!1),[l,n])}var Jk=s=>typeof s=="string",ESt=(s,t,n,r,a)=>Jk(s)?(r&&t.watch.add(s),fi(n,s,a)):Array.isArray(s)?s.map(i=>(r&&t.watch.add(i),fi(n,i))):(r&&(t.watchAll=!0),n),bRe=s=>Tv(s)||!SSt(s);function z4(s,t,n=new WeakSet){if(bRe(s)||bRe(t))return s===t;if(LI(s)&&LI(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(LI(l)&&LI(o)||Yf(l)&&Yf(o)||Array.isArray(l)&&Array.isArray(o)?!z4(l,o,n):l!==o)return!1}}return!0}function q1s(s){const t=G4e(),{control:n=t.control,name:r,defaultValue:a,disabled:i,exact:l,compute:o}=s||{},c=Rt.useRef(a),d=Rt.useRef(o),u=Rt.useRef(void 0);d.current=o;const h=Rt.useMemo(()=>n._getWatch(r,c.current),[n,r]),[m,f]=Rt.useState(d.current?d.current(h):h);return sqe(()=>n._subscribe({name:r,formState:{values:!0},exact:l,callback:g=>{if(!i){const y=ESt(r,n._names,g.values||n._formValues,!1,c.current);if(d.current){const x=d.current(y);z4(x,u.current)||(f(x),u.current=x)}else f(y)}}}),[n,i,r,l]),Rt.useEffect(()=>n._removeUnmounted()),m}function V1s(s){const t=G4e(),{name:n,disabled:r,control:a=t.control,shouldUnregister:i,defaultValue:l}=s,o=ASt(a._names.array,n),c=Rt.useMemo(()=>fi(a._formValues,n,fi(a._defaultValues,n,l)),[a,n,l]),d=q1s({control:a,name:n,defaultValue:c,exact:!0}),u=U1s({control:a,name:n,exact:!0}),h=Rt.useRef(s),m=Rt.useRef(a.register(n,{...s.rules,value:d,...p_(s.disabled)?{disabled:s.disabled}:{}}));h.current=s;const f=Rt.useMemo(()=>Object.defineProperties({},{invalid:{enumerable:!0,get:()=>!!fi(u.errors,n)},isDirty:{enumerable:!0,get:()=>!!fi(u.dirtyFields,n)},isTouched:{enumerable:!0,get:()=>!!fi(u.touchedFields,n)},isValidating:{enumerable:!0,get:()=>!!fi(u.validatingFields,n)},error:{enumerable:!0,get:()=>fi(u.errors,n)}}),[u,n]),g=Rt.useCallback(b=>m.current.onChange({target:{value:CSt(b),name:n},type:lNe.CHANGE}),[n]),y=Rt.useCallback(()=>m.current.onBlur({target:{value:fi(a._formValues,n),name:n},type:lNe.BLUR}),[n,a._formValues]),x=Rt.useCallback(b=>{const k=fi(a._fields,n);k&&b&&(k._f.ref={focus:()=>b.focus&&b.focus(),select:()=>b.select&&b.select(),setCustomValidity:A=>b.setCustomValidity(A),reportValidity:()=>b.reportValidity()})},[a._fields,n]),_=Rt.useMemo(()=>({name:n,value:d,...p_(r)||u.disabled?{disabled:u.disabled||r}:{},onChange:g,onBlur:y,ref:x}),[n,r,u.disabled,g,y,x,d]);return Rt.useEffect(()=>{const b=a._options.shouldUnregister||i;a.register(n,{...h.current.rules,...p_(h.current.disabled)?{disabled:h.current.disabled}:{}});const k=(A,T)=>{const P=fi(a._fields,A);P&&P._f&&(P._f.mount=T)};if(k(n,!0),b){const A=zg(fi(a._options.defaultValues,n));zu(a._defaultValues,n,A),If(fi(a._formValues,n))&&zu(a._formValues,n,A)}return!o&&a.register(n),()=>{(o?b&&!a._state.action:b)?a.unregister(n):k(n,!1)}},[n,a,o,i]),Rt.useEffect(()=>{a._setDisabledField({disabled:r,name:n})},[r,n,a]),Rt.useMemo(()=>({field:_,formState:u,fieldState:f}),[_,u,f])}const H1s=s=>s.render(V1s(s));var MSt=(s,t,n,r,a)=>t?{...n[s],types:{...n[s]&&n[s].types?n[s].types:{},[r]:a||!0}}:{},KW=s=>Array.isArray(s)?s:[s],Knt=()=>{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=[]}}},z1=s=>Yf(s)&&!Object.keys(s).length,nqe=s=>s.type==="file",z2=s=>typeof s=="function",cNe=s=>{if(!QUe)return!1;const t=s?s.ownerDocument:0;return s instanceof(t&&t.defaultView?t.defaultView.HTMLElement:HTMLElement)},LSt=s=>s.type==="select-multiple",rqe=s=>s.type==="radio",G1s=s=>rqe(s)||BQ(s),tMe=s=>cNe(s)&&s.isConnected;function W1s(s,t){const n=t.slice(0,-1).length;let r=0;for(;r{for(const t in s)if(z2(s[t]))return!0;return!1};function dNe(s,t={}){const n=Array.isArray(s);if(Yf(s)||n)for(const r in s)Array.isArray(s[r])||Yf(s[r])&&!PSt(s[r])?(t[r]=Array.isArray(s[r])?[]:{},dNe(s[r],t[r])):Tv(s[r])||(t[r]=!0);return t}function ISt(s,t,n){const r=Array.isArray(s);if(Yf(s)||r)for(const a in s)Array.isArray(s[a])||Yf(s[a])&&!PSt(s[a])?If(t)||bRe(n[a])?n[a]=Array.isArray(s[a])?dNe(s[a],[]):{...dNe(s[a])}:ISt(s[a],Tv(t)?{}:t[a],n[a]):n[a]=!z4(s[a],t[a]);return n}var MV=(s,t)=>ISt(s,t,dNe(t));const Ynt={value:!1,isValid:!1},Znt={value:!0,isValid:!0};var DSt=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&&!If(s[0].attributes.value)?If(s[0].value)||s[0].value===""?Znt:{value:s[0].value,isValid:!0}:Znt:Ynt}return Ynt},RSt=(s,{valueAsNumber:t,valueAsDate:n,setValueAs:r})=>If(s)?s:t?s===""?NaN:s&&+s:n&&Jk(s)?new Date(s):r?r(s):s;const Xnt={isValid:!1,value:null};var OSt=s=>Array.isArray(s)?s.reduce((t,n)=>n&&n.checked&&!n.disabled?{isValid:!0,value:n.value}:t,Xnt):Xnt;function Qnt(s){const t=s.ref;return nqe(t)?t.files:rqe(t)?OSt(s.refs).value:LSt(t)?[...t.selectedOptions].map(({value:n})=>n):BQ(t)?DSt(s.refs).value:RSt(If(t.value)?s.ref.value:t.value,s)}var Y1s=(s,t,n,r)=>{const a={};for(const i of s){const l=fi(t,i);l&&zu(a,i,l._f)}return{criteriaMode:n,names:[...s],fields:a,shouldUseNativeValidation:r}},uNe=s=>s instanceof RegExp,LV=s=>If(s)?s:uNe(s)?s.source:Yf(s)?uNe(s.value)?s.value.source:s.value:s,Jnt=s=>({isOnSubmit:!s||s===F2.onSubmit,isOnBlur:s===F2.onBlur,isOnChange:s===F2.onChange,isOnAll:s===F2.all,isOnTouch:s===F2.onTouched});const ert="AsyncFunction";var Z1s=s=>!!s&&!!s.validate&&!!(z2(s.validate)&&s.validate.constructor.name===ert||Yf(s.validate)&&Object.values(s.validate).find(t=>t.constructor.name===ert)),X1s=s=>s.mount&&(s.required||s.min||s.max||s.maxLength||s.minLength||s.pattern||s.validate),trt=(s,t,n)=>!n&&(t.watchAll||t.watch.has(s)||[...t.watch].some(r=>s.startsWith(r)&&/^\.\w+/.test(s.slice(r.length))));const YW=(s,t,n,r)=>{for(const a of n||Object.keys(s)){const i=fi(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(YW(o,t))break}else if(Yf(o)&&YW(o,t))break}}};function srt(s,t,n){const r=fi(s,n);if(r||H4e(n))return{error:r,name:n};const a=n.split(".");for(;a.length;){const i=a.join("."),l=fi(t,i),o=fi(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 Q1s=(s,t,n,r)=>{n(s);const{name:a,...i}=s;return z1(i)||Object.keys(i).length>=Object.keys(t).length||Object.keys(i).find(l=>t[l]===(!r||F2.all))},J1s=(s,t,n)=>!s||!t||s===t||KW(s).some(r=>r&&(n?r===t:r.startsWith(t)||t.startsWith(r))),ebs=(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,tbs=(s,t)=>!JUe(fi(s,t)).length&&ig(s,t),sbs=(s,t,n)=>{const r=KW(fi(s,n));return zu(r,"root",t[n]),zu(s,n,r),s},zwe=s=>Jk(s);function nrt(s,t,n="validate"){if(zwe(s)||Array.isArray(s)&&s.every(zwe)||p_(s)&&!s)return{type:n,message:zwe(s)?s:"",ref:t}}var uF=s=>Yf(s)&&!uNe(s)?s:{value:s,message:""},rrt=async(s,t,n,r,a,i)=>{const{ref:l,refs:o,required:c,maxLength:d,minLength:u,min:h,max:m,pattern:f,validate:g,name:y,valueAsNumber:x,mount:_}=s._f,b=fi(n,y);if(!_||t.has(y))return{};const k=o?o[0]:l,A=V=>{a&&k.reportValidity&&(k.setCustomValidity(p_(V)?"":V||""),k.reportValidity())},T={},P=rqe(l),I=BQ(l),M=P||I,L=(x||nqe(l))&&If(l.value)&&If(b)||cNe(l)&&l.value===""||b===""||Array.isArray(b)&&!b.length,z=MSt.bind(null,y,r,T),$=(V,W,G,X=MS.maxLength,te=MS.minLength)=>{const ne=V?W:G;T[y]={type:V?X:te,message:ne,ref:l,...z(V?X:te,ne)}};if(i?!Array.isArray(b)||!b.length:c&&(!M&&(L||Tv(b))||p_(b)&&!b||I&&!DSt(o).isValid||P&&!OSt(o).isValid)){const{value:V,message:W}=zwe(c)?{value:!!c,message:c}:uF(c);if(V&&(T[y]={type:MS.required,message:W,ref:k,...z(MS.required,W)},!r))return A(W),T}if(!L&&(!Tv(h)||!Tv(m))){let V,W;const G=uF(m),X=uF(h);if(!Tv(b)&&!isNaN(b)){const te=l.valueAsNumber||b&&+b;Tv(G.value)||(V=te>G.value),Tv(X.value)||(W=tenew Date(new Date().toDateString()+" "+ce),me=l.type=="time",ue=l.type=="week";Jk(G.value)&&b&&(V=me?ne(b)>ne(G.value):ue?b>G.value:te>new Date(G.value)),Jk(X.value)&&b&&(W=me?ne(b)+V.value,X=!Tv(W.value)&&b.length<+W.value;if((G||X)&&($(G,V.message,W.message),!r))return A(T[y].message),T}if(f&&!L&&Jk(b)){const{value:V,message:W}=uF(f);if(uNe(V)&&!b.match(V)&&(T[y]={type:MS.pattern,message:W,ref:l,...z(MS.pattern,W)},!r))return A(W),T}if(g){if(z2(g)){const V=await g(b,n),W=nrt(V,k);if(W&&(T[y]={...W,...z(MS.validate,W.message)},!r))return A(W.message),T}else if(Yf(g)){let V={};for(const W in g){if(!z1(V)&&!r)break;const G=nrt(await g[W](b,n),k,W);G&&(V={...G,...z(W,G.message)},A(G.message),r&&(T[y]=V))}if(!z1(V)&&(T[y]={ref:k,...V},!r))return T}}return A(!0),T};const nbs={mode:F2.onSubmit,reValidateMode:F2.onChange,shouldFocusError:!0};function rbs(s={}){let t={...nbs,...s},n={submitCount:0,isDirty:!1,isReady:!1,isLoading:z2(t.defaultValues),isValidating:!1,isSubmitted:!1,isSubmitting:!1,isSubmitSuccessful:!1,isValid:!1,touchedFields:{},dirtyFields:{},validatingFields:{},errors:t.errors||{},disabled:t.disabled||!1},r={},a=Yf(t.defaultValues)||Yf(t.values)?zg(t.defaultValues||t.values)||{}:{},i=t.shouldUnregister?{}:zg(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:Knt(),state:Knt()},f=t.criteriaMode===F2.all,g=Je=>Ke=>{clearTimeout(d),d=setTimeout(Je,Ke)},y=async Je=>{if(!t.disabled&&(u.isValid||h.isValid||Je)){const Ke=t.resolver?z1((await I()).errors):await L(r,!0);Ke!==n.isValid&&m.state.next({isValid:Ke})}},x=(Je,Ke)=>{!t.disabled&&(u.isValidating||u.validatingFields||h.isValidating||h.validatingFields)&&((Je||Array.from(o.mount)).forEach(st=>{st&&(Ke?zu(n.validatingFields,st,Ke):ig(n.validatingFields,st))}),m.state.next({validatingFields:n.validatingFields,isValidating:!z1(n.validatingFields)}))},_=(Je,Ke=[],st,rt,Ze=!0,ht=!0)=>{if(rt&&st&&!t.disabled){if(l.action=!0,ht&&Array.isArray(fi(r,Je))){const Bt=st(fi(r,Je),rt.argA,rt.argB);Ze&&zu(r,Je,Bt)}if(ht&&Array.isArray(fi(n.errors,Je))){const Bt=st(fi(n.errors,Je),rt.argA,rt.argB);Ze&&zu(n.errors,Je,Bt),tbs(n.errors,Je)}if((u.touchedFields||h.touchedFields)&&ht&&Array.isArray(fi(n.touchedFields,Je))){const Bt=st(fi(n.touchedFields,Je),rt.argA,rt.argB);Ze&&zu(n.touchedFields,Je,Bt)}(u.dirtyFields||h.dirtyFields)&&(n.dirtyFields=MV(a,i)),m.state.next({name:Je,isDirty:$(Je,Ke),dirtyFields:n.dirtyFields,errors:n.errors,isValid:n.isValid})}else zu(i,Je,Ke)},b=(Je,Ke)=>{zu(n.errors,Je,Ke),m.state.next({errors:n.errors})},k=Je=>{n.errors=Je,m.state.next({errors:n.errors,isValid:!1})},A=(Je,Ke,st,rt)=>{const Ze=fi(r,Je);if(Ze){const ht=fi(i,Je,If(st)?fi(a,Je):st);If(ht)||rt&&rt.defaultChecked||Ke?zu(i,Je,Ke?ht:Qnt(Ze._f)):G(Je,ht),l.mount&&y()}},T=(Je,Ke,st,rt,Ze)=>{let ht=!1,Bt=!1;const Ct={name:Je};if(!t.disabled){if(!st||rt){(u.isDirty||h.isDirty)&&(Bt=n.isDirty,n.isDirty=Ct.isDirty=$(),ht=Bt!==Ct.isDirty);const Yt=z4(fi(a,Je),Ke);Bt=!!fi(n.dirtyFields,Je),Yt?ig(n.dirtyFields,Je):zu(n.dirtyFields,Je,!0),Ct.dirtyFields=n.dirtyFields,ht=ht||(u.dirtyFields||h.dirtyFields)&&Bt!==!Yt}if(st){const Yt=fi(n.touchedFields,Je);Yt||(zu(n.touchedFields,Je,st),Ct.touchedFields=n.touchedFields,ht=ht||(u.touchedFields||h.touchedFields)&&Yt!==st)}ht&&Ze&&m.state.next(Ct)}return ht?Ct:{}},P=(Je,Ke,st,rt)=>{const Ze=fi(n.errors,Je),ht=(u.isValid||h.isValid)&&p_(Ke)&&n.isValid!==Ke;if(t.delayError&&st?(c=g(()=>b(Je,st)),c(t.delayError)):(clearTimeout(d),c=null,st?zu(n.errors,Je,st):ig(n.errors,Je)),(st?!z4(Ze,st):Ze)||!z1(rt)||ht){const Bt={...rt,...ht&&p_(Ke)?{isValid:Ke}:{},errors:n.errors,name:Je};n={...n,...Bt},m.state.next(Bt)}},I=async Je=>{x(Je,!0);const Ke=await t.resolver(i,t.context,Y1s(Je||o.mount,r,t.criteriaMode,t.shouldUseNativeValidation));return x(Je),Ke},M=async Je=>{const{errors:Ke}=await I(Je);if(Je)for(const st of Je){const rt=fi(Ke,st);rt?zu(n.errors,st,rt):ig(n.errors,st)}else n.errors=Ke;return Ke},L=async(Je,Ke,st={valid:!0})=>{for(const rt in Je){const Ze=Je[rt];if(Ze){const{_f:ht,...Bt}=Ze;if(ht){const Ct=o.array.has(ht.name),Yt=Ze._f&&Z1s(Ze._f);Yt&&u.validatingFields&&x([rt],!0);const Kt=await rrt(Ze,o.disabled,i,f,t.shouldUseNativeValidation&&!Ke,Ct);if(Yt&&u.validatingFields&&x([rt]),Kt[ht.name]&&(st.valid=!1,Ke))break;!Ke&&(fi(Kt,ht.name)?Ct?sbs(n.errors,Kt,ht.name):zu(n.errors,ht.name,Kt[ht.name]):ig(n.errors,ht.name))}!z1(Bt)&&await L(Bt,Ke,st)}}return st.valid},z=()=>{for(const Je of o.unMount){const Ke=fi(r,Je);Ke&&(Ke._f.refs?Ke._f.refs.every(st=>!tMe(st)):!tMe(Ke._f.ref))&&Se(Je)}o.unMount=new Set},$=(Je,Ke)=>!t.disabled&&(Je&&Ke&&zu(i,Je,Ke),!z4(ce(),a)),V=(Je,Ke,st)=>ESt(Je,o,{...l.mount?i:If(Ke)?a:Jk(Je)?{[Je]:Ke}:Ke},st,Ke),W=Je=>JUe(fi(l.mount?i:a,Je,t.shouldUnregister?fi(a,Je,[]):[])),G=(Je,Ke,st={})=>{const rt=fi(r,Je);let Ze=Ke;if(rt){const ht=rt._f;ht&&(!ht.disabled&&zu(i,Je,RSt(Ke,ht)),Ze=cNe(ht.ref)&&Tv(Ke)?"":Ke,LSt(ht.ref)?[...ht.ref.options].forEach(Bt=>Bt.selected=Ze.includes(Bt.value)):ht.refs?BQ(ht.ref)?ht.refs.forEach(Bt=>{(!Bt.defaultChecked||!Bt.disabled)&&(Array.isArray(Ze)?Bt.checked=!!Ze.find(Ct=>Ct===Bt.value):Bt.checked=Ze===Bt.value||!!Ze)}):ht.refs.forEach(Bt=>Bt.checked=Bt.value===Ze):nqe(ht.ref)?ht.ref.value="":(ht.ref.value=Ze,ht.ref.type||m.state.next({name:Je,values:zg(i)})))}(st.shouldDirty||st.shouldTouch)&&T(Je,Ze,st.shouldTouch,st.shouldDirty,!0),st.shouldValidate&&ue(Je)},X=(Je,Ke,st)=>{for(const rt in Ke){if(!Ke.hasOwnProperty(rt))return;const Ze=Ke[rt],ht=Je+"."+rt,Bt=fi(r,ht);(o.array.has(Je)||Yf(Ze)||Bt&&!Bt._f)&&!LI(Ze)?X(ht,Ze,st):G(ht,Ze,st)}},te=(Je,Ke,st={})=>{const rt=fi(r,Je),Ze=o.array.has(Je),ht=zg(Ke);zu(i,Je,ht),Ze?(m.array.next({name:Je,values:zg(i)}),(u.isDirty||u.dirtyFields||h.isDirty||h.dirtyFields)&&st.shouldDirty&&m.state.next({name:Je,dirtyFields:MV(a,i),isDirty:$(Je,ht)})):rt&&!rt._f&&!Tv(ht)?X(Je,ht,st):G(Je,ht,st),trt(Je,o)&&m.state.next({...n,name:Je}),m.state.next({name:l.mount?Je:void 0,values:zg(i)})},ne=async Je=>{l.mount=!0;const Ke=Je.target;let st=Ke.name,rt=!0;const Ze=fi(r,st),ht=Yt=>{rt=Number.isNaN(Yt)||LI(Yt)&&isNaN(Yt.getTime())||z4(Yt,fi(i,st,Yt))},Bt=Jnt(t.mode),Ct=Jnt(t.reValidateMode);if(Ze){let Yt,Kt;const Xs=Ke.type?Qnt(Ze._f):CSt(Je),zs=Je.type===lNe.BLUR||Je.type===lNe.FOCUS_OUT,Vt=!X1s(Ze._f)&&!t.resolver&&!fi(n.errors,st)&&!Ze._f.deps||ebs(zs,fi(n.touchedFields,st),n.isSubmitted,Ct,Bt),At=trt(st,o,zs);zu(i,st,Xs),zs?(Ze._f.onBlur&&Ze._f.onBlur(Je),c&&c(0)):Ze._f.onChange&&Ze._f.onChange(Je);const Os=T(st,Xs,zs),Nt=!z1(Os)||At;if(!zs&&m.state.next({name:st,type:Je.type,values:zg(i)}),Vt)return(u.isValid||h.isValid)&&(t.mode==="onBlur"?zs&&y():zs||y()),Nt&&m.state.next({name:st,...At?{}:Os});if(!zs&&At&&m.state.next({...n}),t.resolver){const{errors:ms}=await I([st]);if(ht(Xs),rt){const Ys=srt(n.errors,r,st),It=srt(ms,r,Ys.name||st);Yt=It.error,st=It.name,Kt=z1(ms)}}else x([st],!0),Yt=(await rrt(Ze,o.disabled,i,f,t.shouldUseNativeValidation))[st],x([st]),ht(Xs),rt&&(Yt?Kt=!1:(u.isValid||h.isValid)&&(Kt=await L(r,!0)));rt&&(Ze._f.deps&&ue(Ze._f.deps),P(st,Kt,Yt,Os))}},me=(Je,Ke)=>{if(fi(n.errors,Ke)&&Je.focus)return Je.focus(),1},ue=async(Je,Ke={})=>{let st,rt;const Ze=KW(Je);if(t.resolver){const ht=await M(If(Je)?Je:Ze);st=z1(ht),rt=Je?!Ze.some(Bt=>fi(ht,Bt)):st}else Je?(rt=(await Promise.all(Ze.map(async ht=>{const Bt=fi(r,ht);return await L(Bt&&Bt._f?{[ht]:Bt}:Bt)}))).every(Boolean),!(!rt&&!n.isValid)&&y()):rt=st=await L(r);return m.state.next({...!Jk(Je)||(u.isValid||h.isValid)&&st!==n.isValid?{}:{name:Je},...t.resolver||!Je?{isValid:st}:{},errors:n.errors}),Ke.shouldFocus&&!rt&&YW(r,me,Je?Ze:o.mount),rt},ce=Je=>{const Ke={...l.mount?i:a};return If(Je)?Ke:Jk(Je)?fi(Ke,Je):Je.map(st=>fi(Ke,st))},ae=(Je,Ke)=>({invalid:!!fi((Ke||n).errors,Je),isDirty:!!fi((Ke||n).dirtyFields,Je),error:fi((Ke||n).errors,Je),isValidating:!!fi(n.validatingFields,Je),isTouched:!!fi((Ke||n).touchedFields,Je)}),he=Je=>{Je&&KW(Je).forEach(Ke=>ig(n.errors,Ke)),m.state.next({errors:Je?n.errors:{}})},xe=(Je,Ke,st)=>{const rt=(fi(r,Je,{_f:{}})._f||{}).ref,Ze=fi(n.errors,Je)||{},{ref:ht,message:Bt,type:Ct,...Yt}=Ze;zu(n.errors,Je,{...Yt,...Ke,ref:rt}),m.state.next({name:Je,errors:n.errors,isValid:!1}),st&&st.shouldFocus&&rt&&rt.focus&&rt.focus()},ve=(Je,Ke)=>z2(Je)?m.state.subscribe({next:st=>"values"in st&&Je(V(void 0,Ke),st)}):V(Je,Ke,!0),ge=Je=>m.state.subscribe({next:Ke=>{J1s(Je.name,Ke.name,Je.exact)&&Q1s(Ke,Je.formState||u,Xe,Je.reRenderRoot)&&Je.callback({values:{...i},...n,...Ke,defaultValues:a})}}).unsubscribe,be=Je=>(l.mount=!0,h={...h,...Je.formState},ge({...Je,formState:h})),Se=(Je,Ke={})=>{for(const st of Je?KW(Je):o.mount)o.mount.delete(st),o.array.delete(st),Ke.keepValue||(ig(r,st),ig(i,st)),!Ke.keepError&&ig(n.errors,st),!Ke.keepDirty&&ig(n.dirtyFields,st),!Ke.keepTouched&&ig(n.touchedFields,st),!Ke.keepIsValidating&&ig(n.validatingFields,st),!t.shouldUnregister&&!Ke.keepDefaultValue&&ig(a,st);m.state.next({values:zg(i)}),m.state.next({...n,...Ke.keepDirty?{isDirty:$()}:{}}),!Ke.keepIsValid&&y()},Ie=({disabled:Je,name:Ke})=>{(p_(Je)&&l.mount||Je||o.disabled.has(Ke))&&(Je?o.disabled.add(Ke):o.disabled.delete(Ke))},Me=(Je,Ke={})=>{let st=fi(r,Je);const rt=p_(Ke.disabled)||p_(t.disabled);return zu(r,Je,{...st||{},_f:{...st&&st._f?st._f:{ref:{name:Je}},name:Je,mount:!0,...Ke}}),o.mount.add(Je),st?Ie({disabled:p_(Ke.disabled)?Ke.disabled:t.disabled,name:Je}):A(Je,!0,Ke.value),{...rt?{disabled:Ke.disabled||t.disabled}:{},...t.progressive?{required:!!Ke.required,min:LV(Ke.min),max:LV(Ke.max),minLength:LV(Ke.minLength),maxLength:LV(Ke.maxLength),pattern:LV(Ke.pattern)}:{},name:Je,onChange:ne,onBlur:ne,ref:Ze=>{if(Ze){Me(Je,Ke),st=fi(r,Je);const ht=If(Ze.value)&&Ze.querySelectorAll&&Ze.querySelectorAll("input,select,textarea")[0]||Ze,Bt=G1s(ht),Ct=st._f.refs||[];if(Bt?Ct.find(Yt=>Yt===ht):ht===st._f.ref)return;zu(r,Je,{_f:{...st._f,...Bt?{refs:[...Ct.filter(tMe),ht,...Array.isArray(fi(a,Je))?[{}]:[]],ref:{type:ht.type,name:Je}}:{ref:ht}}}),A(Je,!1,void 0,ht)}else st=fi(r,Je,{}),st._f&&(st._f.mount=!1),(t.shouldUnregister||Ke.shouldUnregister)&&!(ASt(o.array,Je)&&l.action)&&o.unMount.add(Je)}}},Re=()=>t.shouldFocusError&&YW(r,me,o.mount),Be=Je=>{p_(Je)&&(m.state.next({disabled:Je}),YW(r,(Ke,st)=>{const rt=fi(r,st);rt&&(Ke.disabled=rt._f.disabled||Je,Array.isArray(rt._f.refs)&&rt._f.refs.forEach(Ze=>{Ze.disabled=rt._f.disabled||Je}))},0,!1))},Ne=(Je,Ke)=>async st=>{let rt;st&&(st.preventDefault&&st.preventDefault(),st.persist&&st.persist());let Ze=zg(i);if(m.state.next({isSubmitting:!0}),t.resolver){const{errors:ht,values:Bt}=await I();n.errors=ht,Ze=zg(Bt)}else await L(r);if(o.disabled.size)for(const ht of o.disabled)ig(Ze,ht);if(ig(n.errors,"root"),z1(n.errors)){m.state.next({errors:{}});try{await Je(Ze,st)}catch(ht){rt=ht}}else Ke&&await Ke({...n.errors},st),Re(),setTimeout(Re);if(m.state.next({isSubmitted:!0,isSubmitting:!1,isSubmitSuccessful:z1(n.errors)&&!rt,submitCount:n.submitCount+1,errors:n.errors}),rt)throw rt},Ge=(Je,Ke={})=>{fi(r,Je)&&(If(Ke.defaultValue)?te(Je,zg(fi(a,Je))):(te(Je,Ke.defaultValue),zu(a,Je,zg(Ke.defaultValue))),Ke.keepTouched||ig(n.touchedFields,Je),Ke.keepDirty||(ig(n.dirtyFields,Je),n.isDirty=Ke.defaultValue?$(Je,zg(fi(a,Je))):$()),Ke.keepError||(ig(n.errors,Je),u.isValid&&y()),m.state.next({...n}))},Ce=(Je,Ke={})=>{const st=Je?zg(Je):a,rt=zg(st),Ze=z1(Je),ht=Ze?a:rt;if(Ke.keepDefaultValues||(a=st),!Ke.keepValues){if(Ke.keepDirtyValues){const Bt=new Set([...o.mount,...Object.keys(MV(a,i))]);for(const Ct of Array.from(Bt))fi(n.dirtyFields,Ct)?zu(ht,Ct,fi(i,Ct)):te(Ct,fi(ht,Ct))}else{if(QUe&&If(Je))for(const Bt of o.mount){const Ct=fi(r,Bt);if(Ct&&Ct._f){const Yt=Array.isArray(Ct._f.refs)?Ct._f.refs[0]:Ct._f.ref;if(cNe(Yt)){const Kt=Yt.closest("form");if(Kt){Kt.reset();break}}}}if(Ke.keepFieldsRef)for(const Bt of o.mount)te(Bt,fi(ht,Bt));else r={}}i=t.shouldUnregister?Ke.keepDefaultValues?zg(a):{}:zg(ht),m.array.next({values:{...ht}}),m.state.next({values:{...ht}})}o={mount:Ke.keepDirtyValues?o.mount:new Set,unMount:new Set,array:new Set,disabled:new Set,watch:new Set,watchAll:!1,focus:""},l.mount=!u.isValid||!!Ke.keepIsValid||!!Ke.keepDirtyValues,l.watch=!!t.shouldUnregister,m.state.next({submitCount:Ke.keepSubmitCount?n.submitCount:0,isDirty:Ze?!1:Ke.keepDirty?n.isDirty:!!(Ke.keepDefaultValues&&!z4(Je,a)),isSubmitted:Ke.keepIsSubmitted?n.isSubmitted:!1,dirtyFields:Ze?{}:Ke.keepDirtyValues?Ke.keepDefaultValues&&i?MV(a,i):n.dirtyFields:Ke.keepDefaultValues&&Je?MV(a,Je):Ke.keepDirty?n.dirtyFields:{},touchedFields:Ke.keepTouched?n.touchedFields:{},errors:Ke.keepErrors?n.errors:{},isSubmitSuccessful:Ke.keepIsSubmitSuccessful?n.isSubmitSuccessful:!1,isSubmitting:!1})},Fe=(Je,Ke)=>Ce(z2(Je)?Je(i):Je,Ke),Ae=(Je,Ke={})=>{const st=fi(r,Je),rt=st&&st._f;if(rt){const Ze=rt.refs?rt.refs[0]:rt.ref;Ze.focus&&(Ze.focus(),Ke.shouldSelect&&z2(Ze.select)&&Ze.select())}},Xe=Je=>{n={...n,...Je}},Ye={control:{register:Me,unregister:Se,getFieldState:ae,handleSubmit:Ne,setError:xe,_subscribe:ge,_runSchema:I,_focusError:Re,_getWatch:V,_getDirty:$,_setValid:y,_setFieldArray:_,_setDisabledField:Ie,_setErrors:k,_getFieldArray:W,_reset:Ce,_resetDefaultValues:()=>z2(t.defaultValues)&&t.defaultValues().then(Je=>{Fe(Je,t.resetOptions),m.state.next({isLoading:!1})}),_removeUnmounted:z,_disableForm:Be,_subjects:m,_proxyFormState:u,get _fields(){return r},get _formValues(){return i},get _state(){return l},set _state(Je){l=Je},get _defaultValues(){return a},get _names(){return o},set _names(Je){o=Je},get _formState(){return n},get _options(){return t},set _options(Je){t={...t,...Je}}},subscribe:be,trigger:ue,register:Me,handleSubmit:Ne,watch:ve,setValue:te,getValues:ce,reset:Fe,resetField:Ge,clearErrors:he,unregister:Se,setError:xe,setFocus:Ae,getFieldState:ae};return{...Ye,formControl:Ye}}function W4e(s={}){const t=Rt.useRef(void 0),n=Rt.useRef(void 0),[r,a]=Rt.useState({isDirty:!1,isValidating:!1,isLoading:z2(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:z2(s.defaultValues)?void 0:s.defaultValues});if(!t.current)if(s.formControl)t.current={...s.formControl,formState:r},s.defaultValues&&!z2(s.defaultValues)&&s.formControl.reset(s.defaultValues,s.resetOptions);else{const{formControl:l,...o}=rbs(s);t.current={...o,formState:r}}const i=t.current.control;return i._options=s,sqe(()=>{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]),Rt.useEffect(()=>i._disableForm(s.disabled),[i,s.disabled]),Rt.useEffect(()=>{s.mode&&(i._options.mode=s.mode),s.reValidateMode&&(i._options.reValidateMode=s.reValidateMode)},[i,s.mode,s.reValidateMode]),Rt.useEffect(()=>{s.errors&&(i._setErrors(s.errors),i._focusError())},[i,s.errors]),Rt.useEffect(()=>{s.shouldUnregister&&i._subjects.state.next({values:i._getWatch()})},[i,s.shouldUnregister]),Rt.useEffect(()=>{if(i._proxyFormState.isDirty){const l=i._getDirty();l!==r.isDirty&&i._subjects.state.next({isDirty:l})}},[i,r.isDirty]),Rt.useEffect(()=>{s.values&&!z4(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]),Rt.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=TSt(r,i),t.current}const art=(s,t,n)=>{if(s&&"reportValidity"in s){const r=fi(n,t);s.setCustomValidity(r&&r.message||""),s.reportValidity()}},FSt=(s,t)=>{for(const n in t.fields){const r=t.fields[n];r&&r.ref&&"reportValidity"in r.ref?art(r.ref,n,s):r.refs&&r.refs.forEach(a=>art(a,n,s))}},abs=(s,t)=>{t.shouldUseNativeValidation&&FSt(s,t);const n={};for(const r in s){const a=fi(t.fields,r),i=Object.assign(s[r]||{},{ref:a&&a.ref});if(ibs(t.names||Object.keys(s),r)){const l=Object.assign({},fi(n,r));zu(l,"root",i),zu(n,r,l)}else zu(n,r,i)}return n},ibs=(s,t)=>s.some(n=>n.startsWith(t+"."));var obs=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]=MSt(l,t,n,a,d?[].concat(d,r.message):r.message)}s.shift()}return n},K4e=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&&FSt({},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:abs(obs(l.errors,!i.shouldUseNativeValidation&&i.criteriaMode==="all"),i)};throw l}))}catch(l){return Promise.reject(l)}}};const Y4e=$1s,zSt=N.createContext({}),gp=({...s})=>e.jsx(zSt.Provider,{value:{name:s.name},children:e.jsx(H1s,{...s})}),Z4e=()=>{const s=N.useContext(zSt),t=N.useContext(BSt),{getFieldState:n,formState:r}=G4e(),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}},BSt=N.createContext({}),Mm=N.forwardRef(({className:s,...t},n)=>{const r=N.useId();return e.jsx(BSt.Provider,{value:{id:r},children:e.jsx("div",{ref:n,className:Ot("space-y-2",s),...t})})});Mm.displayName="FormItem";const Lm=N.forwardRef(({className:s,...t},n)=>{const{error:r,formItemId:a}=Z4e();return e.jsx(re,{ref:n,className:Ot(r&&"text-destructive",s),htmlFor:a,...t})});Lm.displayName="FormLabel";const Pm=N.forwardRef(({...s},t)=>{const{error:n,formItemId:r,formDescriptionId:a,formMessageId:i}=Z4e();return e.jsx(JBe,{ref:t,id:r,"aria-describedby":n?`${a} ${i}`:`${a}`,"aria-invalid":!!n,...s})});Pm.displayName="FormControl";const Bwe=N.forwardRef(({className:s,...t},n)=>{const{formDescriptionId:r}=Z4e();return e.jsx("p",{ref:n,id:r,className:Ot("text-sm text-muted-foreground",s),...t})});Bwe.displayName="FormDescription";const Ov=N.forwardRef(({className:s,children:t,...n},r)=>{const{error:a,formMessageId:i}=Z4e(),l=a?String(a==null?void 0:a.message):t;return l?e.jsx("p",{ref:r,id:i,className:Ot("text-sm font-medium text-destructive",s),...n,children:l}):null});Ov.displayName="FormMessage";const lbs=H5({category:dUe(["general","technology","crm","marketing"]),subject:pl().min(5,"Subject must be at least 5 characters").max(200),description:pl().min(20,"Please provide more details (at least 20 characters)").max(2e3)}),cbs={general:"General Support",technology:"Technology Support",crm:"CRM Support",marketing:"Marketing Support"};function _Re({trigger:s}){const[t,n]=N.useState(!1),[r,a]=N.useState(!1),{user:i}=Ls(),l=W4e({resolver:K4e(lbs),defaultValues:{category:"general",subject:"",description:""}}),o=async c=>{if(!i){ie.error("You must be logged in to submit a ticket");return}a(!0);try{const{error:d}=await H.from("support_tickets").insert({user_id:i.id,category:c.category,subject:c.subject,description:c.description});if(d)throw d;try{await H.functions.invoke("support-ticket-notify",{body:{category:cbs[c.category],subject:c.subject}})}catch(u){console.log("Notification send attempted:",u)}ie.success("Support ticket submitted successfully!"),l.reset(),n(!1)}catch(d){console.error("Error submitting ticket:",d),ie.error("Failed to submit ticket. Please try again.")}finally{a(!1)}};return e.jsxs(Bs,{open:t,onOpenChange:n,children:[e.jsx(Ao,{asChild:!0,children:s||e.jsxs(B,{variant:"ghost",size:"icon",className:"relative",children:[e.jsx(aW,{className:"h-5 w-5"}),e.jsx("span",{className:"sr-only",children:"Support"})]})}),e.jsxs(Fs,{className:"sm:max-w-[500px]",children:[e.jsxs(qs,{children:[e.jsx($s,{children:"Need Help?"}),e.jsx(Ar,{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(ga,{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(Y4e,{...l,children:e.jsxs("form",{onSubmit:l.handleSubmit(o),className:"space-y-4",children:[e.jsx(gp,{control:l.control,name:"category",render:({field:c})=>e.jsxs(Mm,{children:[e.jsx(Lm,{children:"Category"}),e.jsxs(Ns,{onValueChange:c.onChange,defaultValue:c.value,children:[e.jsx(Pm,{children:e.jsx(ws,{children:e.jsx(ks,{placeholder:"Select a category"})})}),e.jsxs(js,{children:[e.jsx(nt,{value:"general",children:"General Support"}),e.jsx(nt,{value:"technology",children:"Technology Support"}),e.jsx(nt,{value:"crm",children:"CRM Support"}),e.jsx(nt,{value:"marketing",children:"Marketing Support"})]})]}),e.jsx(Ov,{})]})}),e.jsx(gp,{control:l.control,name:"subject",render:({field:c})=>e.jsxs(Mm,{children:[e.jsx(Lm,{children:"Subject"}),e.jsx(Pm,{children:e.jsx(we,{placeholder:"Brief description of your issue",...c})}),e.jsx(Ov,{})]})}),e.jsx(gp,{control:l.control,name:"description",render:({field:c})=>e.jsxs(Mm,{children:[e.jsx(Lm,{children:"Description"}),e.jsx(Pm,{children:e.jsx(Ws,{placeholder:"Please describe your issue in detail...",className:"min-h-[120px]",...c})}),e.jsx(Ov,{})]})}),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"})]})]})})]})]})}const dbs=()=>{const{user:s}=Ls(),t=tr(),[n,r]=N.useState([]),[a,i]=N.useState(0),[l,o]=N.useState(!1),[c,d]=N.useState(null),u=N.useRef(null);N.useEffect(()=>{u.current=c},[c]),N.useEffect(()=>{if(!s)return;const y=`notification_last_read_${s.id}`,x=localStorage.getItem(y);x&&!u.current&&(u.current=x,d(x));const _=`nb_cache_${s.id}`,b=60*1e3,k=async()=>{try{const M=sessionStorage.getItem(_);if(M){const L=JSON.parse(M);if(L.ts&&Date.now()-L.ts{r(P);const I=u.current?new Date(u.current):null,M=P.filter(L=>I?new Date(L.created_at)>I:!0);i(M.length)};k();const T=H.channel("push-notifications").on("postgres_changes",{event:"INSERT",schema:"public",table:"push_notifications"},P=>{const I=P.new;r(L=>{const z=[I,...L].slice(0,20);try{sessionStorage.setItem(_,JSON.stringify({ts:Date.now(),data:z}))}catch{}return z});const M=u.current?new Date(u.current):null;(!M||new Date(I.created_at)>M)&&i(L=>L+1),Notification.permission==="granted"&&new Notification(I.title,{body:I.body,icon:"/favicon.ico"})}).subscribe();return()=>{H.removeChannel(T)}},[s]);const h=y=>{const x=y.toLowerCase();return x.includes("community")||x.includes("post")?xo:x.includes("academy")||x.includes("video")?na:x.includes("template")?zc:x.includes("event")?ta:x.includes("newsletter")?E_:x.includes("brokerage")?vg:x.includes("swag")||x.includes("social")?Io:x.includes("toolbox")||x.includes("tool")?sN:x.includes("brief")?Cn:xo},m=y=>{o(!1),y.url&&y.url!=="/"&&t(y.url)},f=()=>{if(!s)return;const y=new Date().toISOString(),x=`notification_last_read_${s.id}`;localStorage.setItem(x,y),d(y),i(0)},g=y=>{o(y),y&&a>0&&f()};return e.jsxs(qd,{open:l,onOpenChange:g,children:[e.jsx(Vd,{asChild:!0,children:e.jsxs(B,{variant:"ghost",size:"icon",className:"relative",children:[e.jsx(yg,{className:"h-5 w-5"}),a>0&&e.jsx(We,{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(Ld,{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:f,children:"Mark all read"})]}),e.jsx(lo,{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 x=h(y.title);return e.jsxs(ba,{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(x,{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:nc(new Date(y.created_at),{addSuffix:!0})})]})]},y.id)})})]})]})};var irt=1,ubs=.9,hbs=.8,mbs=.17,sMe=.1,nMe=.999,pbs=.9999,fbs=.99,gbs=/[\\\/_+.#"@\[\(\{&]/,xbs=/[\\\/_+.#"@\[\(\{&]/g,ybs=/[\s-]/,$St=/[\s-]/g;function wRe(s,t,n,r,a,i,l){if(i===t.length)return a===s.length?irt:fbs;var o=`${a},${i}`;if(l[o]!==void 0)return l[o];for(var c=r.charAt(i),d=n.indexOf(c,a),u=0,h,m,f,g;d>=0;)h=wRe(s,t,n,r,d+1,i+1,l),h>u&&(d===a?h*=irt:gbs.test(s.charAt(d-1))?(h*=hbs,f=s.slice(a,d-1).match(xbs),f&&a>0&&(h*=Math.pow(nMe,f.length))):ybs.test(s.charAt(d-1))?(h*=ubs,g=s.slice(a,d-1).match($St),g&&a>0&&(h*=Math.pow(nMe,g.length))):(h*=mbs,a>0&&(h*=Math.pow(nMe,d-a))),s.charAt(d)!==t.charAt(i)&&(h*=pbs)),(hh&&(h=m*sMe)),h>u&&(u=h),d=n.indexOf(c,d+1);return l[o]=u,u}function ort(s){return s.toLowerCase().replace($St," ")}function vbs(s,t,n){return s=n&&n.length>0?`${s+" "+n.join(" ")}`:s,wRe(s,t,ort(s),ort(t),0,0,{})}var PV='[cmdk-group=""]',rMe='[cmdk-group-items=""]',bbs='[cmdk-group-heading=""]',USt='[cmdk-item=""]',lrt=`${USt}:not([aria-disabled="true"])`,jRe="cmdk-item-select",e7="data-value",_bs=(s,t,n)=>vbs(s,t,n),qSt=N.createContext(void 0),$Q=()=>N.useContext(qSt),VSt=N.createContext(void 0),aqe=()=>N.useContext(VSt),HSt=N.createContext(void 0),GSt=N.forwardRef((s,t)=>{let n=t7(()=>{var he,xe;return{search:"",value:(xe=(he=s.value)!=null?he:s.defaultValue)!=null?xe:"",selectedItemId:void 0,filtered:{count:0,items:new Map,groups:new Set}}}),r=t7(()=>new Set),a=t7(()=>new Map),i=t7(()=>new Map),l=t7(()=>new Set),o=WSt(s),{label:c,children:d,value:u,onValueChange:h,filter:m,shouldFilter:f,loop:g,disablePointerSelection:y=!1,vimBindings:x=!0,..._}=s,b=_g(),k=_g(),A=_g(),T=N.useRef(null),P=Lbs();rR(()=>{if(u!==void 0){let he=u.trim();n.current.value=he,I.emit()}},[u]),rR(()=>{P(6,W)},[]);let I=N.useMemo(()=>({subscribe:he=>(l.current.add(he),()=>l.current.delete(he)),snapshot:()=>n.current,setState:(he,xe,ve)=>{var ge,be,Se,Ie;if(!Object.is(n.current[he],xe)){if(n.current[he]=xe,he==="search")V(),z(),P(1,$);else if(he==="value"){if(document.activeElement.hasAttribute("cmdk-input")||document.activeElement.hasAttribute("cmdk-root")){let Me=document.getElementById(A);Me?Me.focus():(ge=document.getElementById(b))==null||ge.focus()}if(P(7,()=>{var Me;n.current.selectedItemId=(Me=G())==null?void 0:Me.id,I.emit()}),ve||P(5,W),((be=o.current)==null?void 0:be.value)!==void 0){let Me=xe??"";(Ie=(Se=o.current).onValueChange)==null||Ie.call(Se,Me);return}}I.emit()}},emit:()=>{l.current.forEach(he=>he())}}),[]),M=N.useMemo(()=>({value:(he,xe,ve)=>{var ge;xe!==((ge=i.current.get(he))==null?void 0:ge.value)&&(i.current.set(he,{value:xe,keywords:ve}),n.current.filtered.items.set(he,L(xe,ve)),P(2,()=>{z(),I.emit()}))},item:(he,xe)=>(r.current.add(he),xe&&(a.current.has(xe)?a.current.get(xe).add(he):a.current.set(xe,new Set([he]))),P(3,()=>{V(),z(),n.current.value||$(),I.emit()}),()=>{i.current.delete(he),r.current.delete(he),n.current.filtered.items.delete(he);let ve=G();P(4,()=>{V(),(ve==null?void 0:ve.getAttribute("id"))===he&&$(),I.emit()})}),group:he=>(a.current.has(he)||a.current.set(he,new Set),()=>{i.current.delete(he),a.current.delete(he)}),filter:()=>o.current.shouldFilter,label:c||s["aria-label"],getDisablePointerSelection:()=>o.current.disablePointerSelection,listId:b,inputId:A,labelId:k,listInnerRef:T}),[]);function L(he,xe){var ve,ge;let be=(ge=(ve=o.current)==null?void 0:ve.filter)!=null?ge:_bs;return he?be(he,n.current.search,xe):0}function z(){if(!n.current.search||o.current.shouldFilter===!1)return;let he=n.current.filtered.items,xe=[];n.current.filtered.groups.forEach(ge=>{let be=a.current.get(ge),Se=0;be.forEach(Ie=>{let Me=he.get(Ie);Se=Math.max(Me,Se)}),xe.push([ge,Se])});let ve=T.current;X().sort((ge,be)=>{var Se,Ie;let Me=ge.getAttribute("id"),Re=be.getAttribute("id");return((Se=he.get(Re))!=null?Se:0)-((Ie=he.get(Me))!=null?Ie:0)}).forEach(ge=>{let be=ge.closest(rMe);be?be.appendChild(ge.parentElement===be?ge:ge.closest(`${rMe} > *`)):ve.appendChild(ge.parentElement===ve?ge:ge.closest(`${rMe} > *`))}),xe.sort((ge,be)=>be[1]-ge[1]).forEach(ge=>{var be;let Se=(be=T.current)==null?void 0:be.querySelector(`${PV}[${e7}="${encodeURIComponent(ge[0])}"]`);Se==null||Se.parentElement.appendChild(Se)})}function $(){let he=X().find(ve=>ve.getAttribute("aria-disabled")!=="true"),xe=he==null?void 0:he.getAttribute(e7);I.setState("value",xe||void 0)}function V(){var he,xe,ve,ge;if(!n.current.search||o.current.shouldFilter===!1){n.current.filtered.count=r.current.size;return}n.current.filtered.groups=new Set;let be=0;for(let Se of r.current){let Ie=(xe=(he=i.current.get(Se))==null?void 0:he.value)!=null?xe:"",Me=(ge=(ve=i.current.get(Se))==null?void 0:ve.keywords)!=null?ge:[],Re=L(Ie,Me);n.current.filtered.items.set(Se,Re),Re>0&&be++}for(let[Se,Ie]of a.current)for(let Me of Ie)if(n.current.filtered.items.get(Me)>0){n.current.filtered.groups.add(Se);break}n.current.filtered.count=be}function W(){var he,xe,ve;let ge=G();ge&&(((he=ge.parentElement)==null?void 0:he.firstChild)===ge&&((ve=(xe=ge.closest(PV))==null?void 0:xe.querySelector(bbs))==null||ve.scrollIntoView({block:"nearest"})),ge.scrollIntoView({block:"nearest"}))}function G(){var he;return(he=T.current)==null?void 0:he.querySelector(`${USt}[aria-selected="true"]`)}function X(){var he;return Array.from(((he=T.current)==null?void 0:he.querySelectorAll(lrt))||[])}function te(he){let xe=X()[he];xe&&I.setState("value",xe.getAttribute(e7))}function ne(he){var xe;let ve=G(),ge=X(),be=ge.findIndex(Ie=>Ie===ve),Se=ge[be+he];(xe=o.current)!=null&&xe.loop&&(Se=be+he<0?ge[ge.length-1]:be+he===ge.length?ge[0]:ge[be+he]),Se&&I.setState("value",Se.getAttribute(e7))}function me(he){let xe=G(),ve=xe==null?void 0:xe.closest(PV),ge;for(;ve&&!ge;)ve=he>0?Ebs(ve,PV):Mbs(ve,PV),ge=ve==null?void 0:ve.querySelector(lrt);ge?I.setState("value",ge.getAttribute(e7)):ne(he)}let ue=()=>te(X().length-1),ce=he=>{he.preventDefault(),he.metaKey?ue():he.altKey?me(1):ne(1)},ae=he=>{he.preventDefault(),he.metaKey?te(0):he.altKey?me(-1):ne(-1)};return N.createElement(Da.div,{ref:t,tabIndex:-1,..._,"cmdk-root":"",onKeyDown:he=>{var xe;(xe=_.onKeyDown)==null||xe.call(_,he);let ve=he.nativeEvent.isComposing||he.keyCode===229;if(!(he.defaultPrevented||ve))switch(he.key){case"n":case"j":{x&&he.ctrlKey&&ce(he);break}case"ArrowDown":{ce(he);break}case"p":case"k":{x&&he.ctrlKey&&ae(he);break}case"ArrowUp":{ae(he);break}case"Home":{he.preventDefault(),te(0);break}case"End":{he.preventDefault(),ue();break}case"Enter":{he.preventDefault();let ge=G();if(ge){let be=new Event(jRe);ge.dispatchEvent(be)}}}}},N.createElement("label",{"cmdk-label":"",htmlFor:M.inputId,id:M.labelId,style:Ibs},c),X4e(s,he=>N.createElement(VSt.Provider,{value:I},N.createElement(qSt.Provider,{value:M},he))))}),wbs=N.forwardRef((s,t)=>{var n,r;let a=_g(),i=N.useRef(null),l=N.useContext(HSt),o=$Q(),c=WSt(s),d=(r=(n=c.current)==null?void 0:n.forceMount)!=null?r:l==null?void 0:l.forceMount;rR(()=>{if(!d)return o.item(a,l==null?void 0:l.id)},[d]);let u=KSt(a,i,[s.value,s.children,i],s.keywords),h=aqe(),m=mE(P=>P.value&&P.value===u.current),f=mE(P=>d||o.filter()===!1?!0:P.search?P.filtered.items.get(a)>0:!0);N.useEffect(()=>{let P=i.current;if(!(!P||s.disabled))return P.addEventListener(jRe,g),()=>P.removeEventListener(jRe,g)},[f,s.onSelect,s.disabled]);function g(){var P,I;y(),(I=(P=c.current).onSelect)==null||I.call(P,u.current)}function y(){h.setState("value",u.current,!0)}if(!f)return null;let{disabled:x,value:_,onSelect:b,forceMount:k,keywords:A,...T}=s;return N.createElement(Da.div,{ref:j3(i,t),...T,id:a,"cmdk-item":"",role:"option","aria-disabled":!!x,"aria-selected":!!m,"data-disabled":!!x,"data-selected":!!m,onPointerMove:x||o.getDisablePointerSelection()?void 0:y,onClick:x?void 0:g},s.children)}),jbs=N.forwardRef((s,t)=>{let{heading:n,children:r,forceMount:a,...i}=s,l=_g(),o=N.useRef(null),c=N.useRef(null),d=_g(),u=$Q(),h=mE(f=>a||u.filter()===!1?!0:f.search?f.filtered.groups.has(l):!0);rR(()=>u.group(l),[]),KSt(l,o,[s.value,s.heading,c]);let m=N.useMemo(()=>({id:l,forceMount:a}),[a]);return N.createElement(Da.div,{ref:j3(o,t),...i,"cmdk-group":"",role:"presentation",hidden:h?void 0:!0},n&&N.createElement("div",{ref:c,"cmdk-group-heading":"","aria-hidden":!0,id:d},n),X4e(s,f=>N.createElement("div",{"cmdk-group-items":"",role:"group","aria-labelledby":n?d:void 0},N.createElement(HSt.Provider,{value:m},f))))}),Nbs=N.forwardRef((s,t)=>{let{alwaysRender:n,...r}=s,a=N.useRef(null),i=mE(l=>!l.search);return!n&&!i?null:N.createElement(Da.div,{ref:j3(a,t),...r,"cmdk-separator":"",role:"separator"})}),kbs=N.forwardRef((s,t)=>{let{onValueChange:n,...r}=s,a=s.value!=null,i=aqe(),l=mE(d=>d.search),o=mE(d=>d.selectedItemId),c=$Q();return N.useEffect(()=>{s.value!=null&&i.setState("search",s.value)},[s.value]),N.createElement(Da.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)}})}),Sbs=N.forwardRef((s,t)=>{let{children:n,label:r="Suggestions",...a}=s,i=N.useRef(null),l=N.useRef(null),o=mE(d=>d.selectedItemId),c=$Q();return N.useEffect(()=>{if(l.current&&i.current){let d=l.current,u=i.current,h,m=new ResizeObserver(()=>{h=requestAnimationFrame(()=>{let f=d.offsetHeight;u.style.setProperty("--cmdk-list-height",f.toFixed(1)+"px")})});return m.observe(d),()=>{cancelAnimationFrame(h),m.unobserve(d)}}},[]),N.createElement(Da.div,{ref:j3(i,t),...a,"cmdk-list":"",role:"listbox",tabIndex:-1,"aria-activedescendant":o,"aria-label":r,id:c.listId},X4e(s,d=>N.createElement("div",{ref:j3(l,c.listInnerRef),"cmdk-list-sizer":""},d)))}),Cbs=N.forwardRef((s,t)=>{let{open:n,onOpenChange:r,overlayClassName:a,contentClassName:i,container:l,...o}=s;return N.createElement(m4e,{open:n,onOpenChange:r},N.createElement(p4e,{container:l},N.createElement(aU,{"cmdk-overlay":"",className:a}),N.createElement(iU,{"aria-label":s.label,"cmdk-dialog":"",className:i},N.createElement(GSt,{ref:t,...o}))))}),Abs=N.forwardRef((s,t)=>mE(n=>n.filtered.count===0)?N.createElement(Da.div,{ref:t,...s,"cmdk-empty":"",role:"presentation"}):null),Tbs=N.forwardRef((s,t)=>{let{progress:n,children:r,label:a="Loading...",...i}=s;return N.createElement(Da.div,{ref:t,...i,"cmdk-loading":"",role:"progressbar","aria-valuenow":n,"aria-valuemin":0,"aria-valuemax":100,"aria-label":a},X4e(s,l=>N.createElement("div",{"aria-hidden":!0},l)))}),yb=Object.assign(GSt,{List:Sbs,Item:wbs,Input:kbs,Group:jbs,Separator:Nbs,Dialog:Cbs,Empty:Abs,Loading:Tbs});function Ebs(s,t){let n=s.nextElementSibling;for(;n;){if(n.matches(t))return n;n=n.nextElementSibling}}function Mbs(s,t){let n=s.previousElementSibling;for(;n;){if(n.matches(t))return n;n=n.previousElementSibling}}function WSt(s){let t=N.useRef(s);return rR(()=>{t.current=s}),t}var rR=typeof window>"u"?N.useEffect:N.useLayoutEffect;function t7(s){let t=N.useRef();return t.current===void 0&&(t.current=s()),t}function mE(s){let t=aqe(),n=()=>s(t.snapshot());return N.useSyncExternalStore(t.subscribe,n,n)}function KSt(s,t,n,r=[]){let a=N.useRef(),i=$Q();return rR(()=>{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(e7,o),a.current=o}),a}var Lbs=()=>{let[s,t]=N.useState(),n=t7(()=>new Map);return rR(()=>{n.current.forEach(r=>r()),n.current=new Map},[s]),(r,a)=>{n.current.set(r,a),t({})}};function Pbs(s){let t=s.type;return typeof t=="function"?t(s.props):"render"in t?t.render(s.props):s}function X4e({asChild:s,children:t},n){return s&&N.isValidElement(t)?N.cloneElement(Pbs(t),{ref:t.ref},n(t.props.children)):n(t)}var Ibs={position:"absolute",width:"1px",height:"1px",padding:"0",margin:"-1px",overflow:"hidden",clip:"rect(0, 0, 0, 0)",whiteSpace:"nowrap",borderWidth:"0"};const db=N.forwardRef(({className:s,...t},n)=>e.jsx(yb,{ref:n,className:Ot("flex h-full w-full flex-col overflow-hidden rounded-md bg-popover text-popover-foreground",s),...t}));db.displayName=yb.displayName;const Dbs=({children:s,...t})=>e.jsx(Bs,{...t,children:e.jsx(Fs,{className:"overflow-hidden p-0 shadow-lg",children:e.jsx(db,{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})})}),ub=N.forwardRef(({className:s,...t},n)=>e.jsxs("div",{className:"flex items-center border-b px-3","cmdk-input-wrapper":"",children:[e.jsx(Gr,{className:"mr-2 h-4 w-4 shrink-0 opacity-50"}),e.jsx(yb.Input,{ref:n,className:Ot("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})]}));ub.displayName=yb.Input.displayName;const hb=N.forwardRef(({className:s,...t},n)=>e.jsx(yb.List,{ref:n,className:Ot("max-h-[300px] overflow-y-auto overflow-x-hidden",s),...t}));hb.displayName=yb.List.displayName;const mb=N.forwardRef((s,t)=>e.jsx(yb.Empty,{ref:t,className:"py-6 text-center text-sm",...s}));mb.displayName=yb.Empty.displayName;const pb=N.forwardRef(({className:s,...t},n)=>e.jsx(yb.Group,{ref:n,className:Ot("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}));pb.displayName=yb.Group.displayName;const Rbs=N.forwardRef(({className:s,...t},n)=>e.jsx(yb.Separator,{ref:n,className:Ot("-mx-1 h-px bg-border",s),...t}));Rbs.displayName=yb.Separator.displayName;const Ry=N.forwardRef(({className:s,...t},n)=>e.jsx(yb.Item,{ref:n,className:Ot("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}));Ry.displayName=yb.Item.displayName;const Obs={event:{label:"Events",icon:ld,color:"bg-blue-500/10 text-blue-600"},template:{label:"Templates",icon:zc,color:"bg-purple-500/10 text-purple-600"},academy:{label:"Academy",icon:Oh,color:"bg-amber-500/10 text-amber-600"},toolbox:{label:"Toolbox",icon:sN,color:"bg-green-500/10 text-green-600"},"social-swag":{label:"Social Swag",icon:Cn,color:"bg-fuchsia-500/10 text-fuchsia-600"}},crt=()=>{const[s,t]=N.useState(!1),[n,r]=N.useState(""),[a,i]=N.useState([]),[l,o]=N.useState(!1),c=tr();N.useEffect(()=>{const m=f=>{f.key==="k"&&(f.metaKey||f.ctrlKey)&&(f.preventDefault(),t(g=>!g))};return document.addEventListener("keydown",m),()=>document.removeEventListener("keydown",m)},[]);const d=N.useCallback(async m=>{if(!m.trim()){i([]);return}o(!0);const f=`%${m}%`;try{const[g,y,x,_,b]=await Promise.all([H.from("events").select("id, title, description, event_date").eq("is_published",!0).or(`title.ilike.${f},description.ilike.${f}`).limit(5),H.from("canva_templates").select("id, name, description, publish_date").or(`name.ilike.${f},description.ilike.${f}`).limit(5),H.from("academy_videos").select("id, title, description, publish_date").eq("is_published",!0).or(`title.ilike.${f},description.ilike.${f}`).limit(5),H.from("resource_kits").select("id, name, description, publish_date").eq("is_published",!0).or(`name.ilike.${f},description.ilike.${f}`).limit(5),H.from("social_swag").select("id, title, description, publish_date").eq("is_published",!0).or(`title.ilike.${f},description.ilike.${f}`).limit(5)]),k=[];g.data&&g.data.forEach(A=>{k.push({id:A.id,title:A.title,description:A.description,type:"event",date:A.event_date,path:`/event/${A.id}`})}),y.data&&y.data.forEach(A=>{k.push({id:A.id,title:A.name,description:A.description,type:"template",date:A.publish_date,path:`/templates/${A.id}`})}),x.data&&x.data.forEach(A=>{k.push({id:A.id,title:A.title,description:A.description,type:"academy",date:A.publish_date,path:`/academy/${A.id}`})}),_.data&&_.data.forEach(A=>{k.push({id:A.id,title:A.name,description:A.description,type:"toolbox",date:A.publish_date,path:`/toolbox/${A.id}`})}),b.data&&b.data.forEach(A=>{k.push({id:A.id,title:A.title,description:A.description,type:"social-swag",date:A.publish_date,path:`/social-swag/${A.id}`})}),i(k)}catch(g){console.error("Search error:",g)}finally{o(!1)}},[]);N.useEffect(()=>{const m=setTimeout(()=>{d(n)},300);return()=>clearTimeout(m)},[n,d]);const u=m=>{t(!1),r(""),c(m)},h=a.reduce((m,f)=>(m[f.type]||(m[f.type]=[]),m[f.type].push(f),m),{});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(Gr,{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(Dbs,{open:s,onOpenChange:t,children:[e.jsx(ub,{placeholder:"Search events, templates, academy, toolbox, social swag...",value:n,onValueChange:r}),e.jsxs(hb,{children:[l&&e.jsx("div",{className:"py-6 text-center text-sm text-muted-foreground",children:"Searching..."}),!l&&n&&a.length===0&&e.jsxs(mb,{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 across all content..."}),Object.entries(h).map(([m,f])=>{const g=Obs[m],y=g.icon;return e.jsx(pb,{heading:g.label,children:f.map(x=>e.jsxs(Ry,{value:`${x.type}-${x.id}-${x.title}`,onSelect:()=>u(x.path),className:"flex items-start gap-3 py-3 cursor-pointer",children:[e.jsx("div",{className:`p-2 rounded-md ${g.color}`,children:e.jsx(y,{className:"h-4 w-4"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("div",{className:"font-medium truncate",children:x.title}),x.description&&e.jsx("div",{className:"text-sm text-muted-foreground truncate group-data-[selected=true]:text-primary-foreground/80",children:x.description})]}),e.jsxs("div",{className:"flex flex-col items-end gap-1 shrink-0",children:[e.jsx(We,{variant:"secondary",className:"text-xs",children:g.label}),e.jsx("span",{className:"text-xs text-muted-foreground",children:nc(new Date(x.date),{addSuffix:!0})})]})]},`${x.type}-${x.id}`))},m)})]})]})]})},Fbs=({expiresAt:s,className:t,showUpgradeButton:n=!0})=>{const[r,a]=N.useState(null),i=tr();if(N.useEffect(()=>{const d=()=>{const h=new Date().getTime(),f=new Date(s).getTime()-h;if(f<=0){a({days:0,hours:0,minutes:0});return}const g=Math.floor(f/(1e3*60*60*24)),y=Math.floor(f%(1e3*60*60*24)/(1e3*60*60)),x=Math.floor(f%(1e3*60*60)/(1e3*60));a({days:g,hours:y,minutes:x})};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:Ot("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(xd,{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(Cn,{className:"h-3 w-3 mr-1"}),"Upgrade Now"]})]}):e.jsxs("div",{className:Ot("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(Xr,{className:Ot("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:Ot("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:Ot("text-sm font-bold",o?"text-destructive":c?"text-amber-600":"text-primary"),children:[r.days,"d"]}),e.jsxs("span",{className:Ot("text-sm font-bold",o?"text-destructive":c?"text-amber-600":"text-primary"),children:[r.hours,"h"]}),e.jsxs("span",{className:Ot("text-sm font-bold",o?"text-destructive":c?"text-amber-600":"text-primary"),children:[r.minutes,"m"]}),e.jsx("span",{className:Ot("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:Ot("text-xs h-7 px-3",c&&"bg-amber-500 hover:bg-amber-600 text-white"),children:[e.jsx(Cn,{className:"h-3 w-3 mr-1"}),"Upgrade"]})]})},zbs=()=>{const s=tr();return e.jsx("div",{className:"fixed inset-0 bg-background/95 backdrop-blur-sm z-50 flex items-center justify-center p-4 overflow-y-auto",children:e.jsxs(_e,{className:"w-full max-w-2xl shadow-2xl border-destructive/20 my-8",children:[e.jsxs(zt,{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(xd,{className:"h-8 w-8 text-destructive"})}),e.jsx(qt,{className:"text-2xl",children:"Your Free Trial Has Ended"}),e.jsx(_r,{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(De,{className:"space-y-6",children:[e.jsxs("div",{className:"grid sm:grid-cols-2 gap-4",children:[e.jsx(_e,{className:"border-2 border-primary/20 hover:border-primary/50 transition-colors cursor-pointer",onClick:()=>s("/subscription"),children:e.jsxs(De,{className:"p-5 text-center",children:[e.jsx("div",{className:"mx-auto mb-3 h-12 w-12 rounded-full bg-primary/10 flex items-center justify-center",children:e.jsx(Yn,{className:"h-6 w-6 text-primary"})}),e.jsx("h3",{className:"font-semibold text-lg mb-1",children:"Individual Agent"}),e.jsxs("p",{className:"text-2xl font-bold text-primary mb-2",children:["$39",e.jsx("span",{className:"text-sm font-normal text-muted-foreground",children:"/mo"})]}),e.jsx("p",{className:"text-sm text-muted-foreground mb-4",children:"Perfect for solo agents ready to level up"}),e.jsxs(B,{className:"w-full",onClick:t=>{t.stopPropagation(),s("/subscription")},children:[e.jsx(Cn,{className:"h-4 w-4 mr-2"}),"Choose Individual"]})]})}),e.jsx(_e,{className:"border-2 border-amber-500/20 hover:border-amber-500/50 transition-colors cursor-pointer",onClick:()=>s("/subscription"),children:e.jsxs(De,{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(Ti,{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(Ti,{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(ga,{className:"h-4 w-4"}),e.jsx("span",{children:"1-866-527-8668"})]}),e.jsxs("a",{href:"mailto:support@relevelup.com",className:"flex items-center justify-center gap-2 text-primary hover:underline",children:[e.jsx(mn,{className:"h-4 w-4"}),e.jsx("span",{children:"support@relevelup.com"})]})]})]})]})]})})},Bbs=({hasUnseenBrief:s,onClick:t,className:n})=>e.jsxs(wu,{children:[e.jsx(ju,{asChild:!0,children:e.jsxs(B,{variant:"ghost",size:"icon",onClick:t,className:Ot("relative transition-colors",s&&"text-primary hover:text-primary",n),children:[e.jsx(um,{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(nu,{children:e.jsx("p",{children:"The LevelUp Brief"})})]});var iqe="Radio",[$bs,YSt]=Um(iqe),[Ubs,qbs]=$bs(iqe),ZSt=N.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]=N.useState(null),f=jo(t,x=>m(x)),g=N.useRef(!1),y=h?d||!!h.closest("form"):!0;return e.jsxs(Ubs,{scope:n,checked:a,disabled:l,children:[e.jsx(Da.button,{type:"button",role:"radio","aria-checked":a,"data-state":e4t(a),"data-disabled":l?"":void 0,disabled:l,value:o,...u,ref:f,onClick:la(s.onClick,x=>{a||c==null||c(),y&&(g.current=x.isPropagationStopped(),g.current||x.stopPropagation())})}),y&&e.jsx(JSt,{control:h,bubbles:!g.current,name:r,value:o,checked:a,required:i,disabled:l,form:d,style:{transform:"translateX(-100%)"}})]})});ZSt.displayName=iqe;var XSt="RadioIndicator",QSt=N.forwardRef((s,t)=>{const{__scopeRadio:n,forceMount:r,...a}=s,i=qbs(XSt,n);return e.jsx(Xf,{present:r||i.checked,children:e.jsx(Da.span,{"data-state":e4t(i.checked),"data-disabled":i.disabled?"":void 0,...a,ref:t})})});QSt.displayName=XSt;var Vbs="RadioBubbleInput",JSt=N.forwardRef(({__scopeRadio:s,control:t,checked:n,bubbles:r=!0,...a},i)=>{const l=N.useRef(null),o=jo(l,i),c=EQ(n),d=fQ(t);return N.useEffect(()=>{const u=l.current;if(!u)return;const h=window.HTMLInputElement.prototype,f=Object.getOwnPropertyDescriptor(h,"checked").set;if(c!==n&&f){const g=new Event("click",{bubbles:r});f.call(u,n),u.dispatchEvent(g)}},[c,n,r]),e.jsx(Da.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}})});JSt.displayName=Vbs;function e4t(s){return s?"checked":"unchecked"}var Hbs=["ArrowUp","ArrowDown","ArrowLeft","ArrowRight"],Q4e="RadioGroup",[Gbs,qOn]=Um(Q4e,[ME,YSt]),t4t=ME(),s4t=YSt(),[Wbs,Kbs]=Gbs(Q4e),n4t=N.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,f=t4t(n),g=F3(d),[y,x]=Ng({prop:i,defaultProp:a??null,onChange:h,caller:Q4e});return e.jsx(Wbs,{scope:n,name:r,required:l,disabled:o,value:y,onValueChange:x,children:e.jsx(a4e,{asChild:!0,...f,orientation:c,dir:g,loop:u,children:e.jsx(Da.div,{role:"radiogroup","aria-required":l,"aria-orientation":c,"data-disabled":o?"":void 0,dir:g,...m,ref:t})})})});n4t.displayName=Q4e;var r4t="RadioGroupItem",a4t=N.forwardRef((s,t)=>{const{__scopeRadioGroup:n,disabled:r,...a}=s,i=Kbs(r4t,n),l=i.disabled||r,o=t4t(n),c=s4t(n),d=N.useRef(null),u=jo(t,d),h=i.value===a.value,m=N.useRef(!1);return N.useEffect(()=>{const f=y=>{Hbs.includes(y.key)&&(m.current=!0)},g=()=>m.current=!1;return document.addEventListener("keydown",f),document.addEventListener("keyup",g),()=>{document.removeEventListener("keydown",f),document.removeEventListener("keyup",g)}},[]),e.jsx(i4e,{asChild:!0,...o,focusable:!l,active:h,children:e.jsx(ZSt,{disabled:l,required:i.required,checked:h,...c,...a,name:i.name,ref:u,onCheck:()=>i.onValueChange(a.value),onKeyDown:la(f=>{f.key==="Enter"&&f.preventDefault()}),onFocus:la(a.onFocus,()=>{var f;m.current&&((f=d.current)==null||f.click())})})})});a4t.displayName=r4t;var Ybs="RadioGroupIndicator",i4t=N.forwardRef((s,t)=>{const{__scopeRadioGroup:n,...r}=s,a=s4t(n);return e.jsx(QSt,{...a,...r,ref:t})});i4t.displayName=Ybs;var o4t=n4t,l4t=a4t,Zbs=i4t;const K1=N.forwardRef(({className:s,...t},n)=>e.jsx(o4t,{className:Ot("grid gap-2",s),...t,ref:n}));K1.displayName=o4t.displayName;const Ju=N.forwardRef(({className:s,...t},n)=>e.jsx(l4t,{ref:n,className:Ot("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(Zbs,{className:"flex items-center justify-center",children:e.jsx(bg,{className:"h-2.5 w-2.5 fill-current text-current"})})}));Ju.displayName=l4t.displayName;const Xbs=({brief:s,open:t,onClose:n,onDismiss:r})=>{const{user:a}=Ls(),[i,l]=N.useState({}),[o,c]=N.useState({}),[d,u]=N.useState([]);N.useEffect(()=>{t&&a&&s.polls.length>0&&h()},[t,a,s.polls]);const h=async()=>{if(!a)return;const x=s.polls.map(b=>b.id),{data:_}=await H.from("levelup_brief_poll_responses").select("poll_id, option_id").eq("user_id",a.id).in("poll_id",x);if(_){const b={};_.forEach(k=>{b[k.poll_id]||(b[k.poll_id]=[]),b[k.poll_id].push(k.option_id)}),c(b)}},m=(x,_)=>{l(b=>({...b,[x]:_}))},f=(x,_,b)=>{l(k=>{const A=k[x]||[];return b?{...k,[x]:[...A,_]}:{...k,[x]:A.filter(T=>T!==_)}})},g=async x=>{if(!a)return;const _=i[x];if(!_||Array.isArray(_)&&_.length===0){ie.error("Please select an option");return}u(b=>[...b,x]);try{await H.from("levelup_brief_poll_responses").delete().eq("poll_id",x).eq("user_id",a.id);const b=Array.isArray(_)?_:[_],k=b.map(T=>({poll_id:x,option_id:T,user_id:a.id})),{error:A}=await H.from("levelup_brief_poll_responses").insert(k);if(A)throw A;c(T=>({...T,[x]:b})),ie.success("Response submitted!")}catch(b){console.error("Error submitting poll response:",b),ie.error("Failed to submit response")}finally{u(b=>b.filter(k=>k!==x))}},y=x=>(x.includes("mediadelivery.net")||x.includes("bunny"),x);return e.jsx(Bs,{open:t,onOpenChange:x=>!x&&n(),children:e.jsxs(Fs,{className:"max-w-2xl max-h-[90vh] p-0 overflow-hidden [&>button]:hidden",children:[e.jsxs("div",{className:"bg-gradient-to-r from-primary to-primary/80 p-4 pr-12 text-primary-foreground relative",children:[e.jsx("button",{onClick:n,className:"absolute top-3 right-3 p-1.5 rounded-full bg-white/30 hover:bg-white/50 transition-colors","aria-label":"Close",children:e.jsx(hr,{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(um,{className:"h-6 w-6"})}),e.jsxs("div",{children:[e.jsx(We,{variant:"secondary",className:"mb-1 bg-white/20 text-white border-0",children:"The LevelUp Brief"}),e.jsx($s,{className:"text-xl font-bold text-white",children:s.brief.title})]})]})]}),e.jsx(lo,{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(x=>e.jsxs(B,{variant:"outline",size:"sm",onClick:()=>window.open(x.url,"_blank"),className:"gap-2",children:[e.jsx(Tr,{className:"h-4 w-4"}),x.title]},x.id))})]}),s.polls.map(x=>{var k,A;const _=((k=o[x.id])==null?void 0:k.length)>0,b=d.includes(x.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:x.question}),_&&e.jsxs(We,{variant:"secondary",className:"gap-1",children:[e.jsx(Hr,{className:"h-3 w-3"}),"Responded"]})]}),x.poll_type==="single"?e.jsx(K1,{value:i[x.id]||((A=o[x.id])==null?void 0:A[0])||"",onValueChange:T=>m(x.id,T),className:"space-y-2",children:x.options.map(T=>e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(Ju,{value:T.id,id:T.id}),e.jsx(re,{htmlFor:T.id,className:"cursor-pointer",children:T.option_text})]},T.id))}):e.jsx("div",{className:"space-y-2",children:x.options.map(T=>{const I=(i[x.id]||o[x.id]||[]).includes(T.id);return e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(Bi,{id:T.id,checked:I,onCheckedChange:M=>f(x.id,T.id,M)}),e.jsx(re,{htmlFor:T.id,className:"cursor-pointer",children:T.option_text})]},T.id)})}),e.jsx(B,{size:"sm",onClick:()=>g(x.id),disabled:b,children:b?"Submitting...":_?"Update Response":"Submit"})]},x.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"})]})]})})},Qbs=()=>{const{user:s}=Ls(),[t,n]=N.useState(null),[r,a]=N.useState(!1),[i,l]=N.useState(!0),[o,c]=N.useState(!1),d=N.useCallback(async()=>{if(!s){l(!1);return}try{const{data:g,error:y}=await H.from("levelup_briefs").select("*").eq("is_published",!0).lte("publish_date",new Date().toISOString()).order("publish_date",{ascending:!1}).limit(1).single();if(y||!g){l(!1);return}const{data:x}=await H.from("levelup_brief_views").select("*").eq("brief_id",g.id).eq("user_id",s.id).maybeSingle(),[_,b]=await Promise.all([H.from("levelup_brief_links").select("*").eq("brief_id",g.id).order("sort_order"),H.from("levelup_brief_polls").select("*").eq("brief_id",g.id).order("sort_order")]),k=[];if(b.data)for(const M of b.data){const{data:L}=await H.from("levelup_brief_poll_options").select("*").eq("poll_id",M.id).order("sort_order");k.push({...M,options:L||[]})}const A={brief:g,links:_.data||[],polls:k};n(A);const T=!!x,P=(x==null?void 0:x.dismissed_at)!=null,I=localStorage.getItem(`brief-dismissed-${g.id}`)==="true";if(P||I)c(!1),a(!1);else if(!T)a(!0),c(!0);else if(g.show_frequency==="every_login")a(!0),c(!0);else if(g.show_frequency==="daily"){const M=new Date(x.viewed_at);(new Date().getTime()-M.getTime())/(1e3*60*60)>=24&&(a(!0),c(!0))}else c(!1)}catch(g){console.error("Error fetching brief:",g)}finally{l(!1)}},[s]);N.useEffect(()=>{d()},[d]);const u=async()=>{if(!(!s||!t))try{const{data:g}=await H.from("levelup_brief_views").select("id").eq("brief_id",t.brief.id).eq("user_id",s.id).maybeSingle();g?await H.from("levelup_brief_views").update({viewed_at:new Date().toISOString()}).eq("id",g.id):await H.from("levelup_brief_views").insert({brief_id:t.brief.id,user_id:s.id})}catch(g){console.error("Error marking brief as viewed:",g)}};return{currentBrief:t,shouldShowPopup:r,hasUnseenBrief:o,loading:i,openBrief:()=>{a(!0)},closeBrief:()=>{a(!1),u()},dismissBrief:async()=>{if(!(!s||!t)){a(!1),c(!1);try{const{data:g,error:y}=await H.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),g){const{error:x}=await H.from("levelup_brief_views").update({dismissed_at:new Date().toISOString()}).eq("id",g.id).eq("user_id",s.id);x&&console.error("Error updating brief dismiss:",x)}else{const{error:x}=await H.from("levelup_brief_views").insert({brief_id:t.brief.id,user_id:s.id,dismissed_at:new Date().toISOString()});x&&console.error("Error inserting brief dismiss:",x)}localStorage.setItem(`brief-dismissed-${t.brief.id}`,"true")}catch(g){console.error("Error dismissing brief:",g),t&&localStorage.setItem(`brief-dismissed-${t.brief.id}`,"true")}}},refetch:d}};function Jbs(){const[s,t]=N.useState(!1),[n,r]=N.useState(!1),[a,i]=N.useState(null);N.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=f=>{f.preventDefault(),i(f)};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(oi,{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(bW,{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(hr,{className:"h-4 w-4"})})]})]})}):null}const e_s=({children:s,onRefresh:t})=>{const[n,r]=N.useState(!1),[a,i]=N.useState(0),[l,o]=N.useState(!1),c=N.useRef(null),d=N.useRef(0),u=as(),h=80,m=120,f=N.useCallback(b=>{const k=c.current;k&&k.scrollTop<=0&&(d.current=b.touches[0].clientY,r(!0))},[]),g=N.useCallback(b=>{if(!n||l)return;const k=c.current;if(!k||k.scrollTop>0){r(!1),i(0);return}const T=b.touches[0].clientY-d.current;if(T>0){const I=Math.min(T*.5,m);i(I),I>10&&b.preventDefault()}},[n,l]),y=N.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]),x=Math.min(a/h,1),_=x*180;return e.jsxs("div",{ref:c,className:"h-full overflow-auto",onTouchStart:f,onTouchMove:g,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:x},children:e.jsx("div",{className:`p-2 rounded-full bg-primary/10 ${l?"animate-spin":""}`,style:{transform:l?void 0:`rotate(${_}deg)`,transition:l?void 0:"transform 0.1s ease-out"},children:e.jsx(oo,{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})]})},c4t=()=>{const{user:s}=Ls(),[t,n]=N.useState(!1),[r,a]=N.useState(!1),[i,l]=N.useState(0),[o,c]=N.useState(!0);N.useEffect(()=>{(async()=>{if(!s){c(!1);return}try{const{data:f}=await H.from("membership_reviews").select("id").eq("user_id",s.id).maybeSingle();if(f){a(!0),n(!1),c(!1);return}const{data:g}=await H.from("profiles").select("login_count").eq("id",s.id).single(),y=(g==null?void 0:g.login_count)||0;l(y);const x=sessionStorage.getItem("review-prompt-dismissed");n(y>=4&&!x)}catch(f){console.error("Error checking review eligibility:",f)}finally{c(!1)}})()},[s]);const d=N.useCallback(()=>{sessionStorage.setItem("review-prompt-dismissed","true"),n(!1)},[]),u=N.useCallback(async(m,f)=>{if(!s)return{success:!1,error:"Not authenticated"};try{const{error:g}=await H.from("membership_reviews").insert({user_id:s.id,rating:m,review_text:f});if(g)throw g;return a(!0),n(!1),{success:!0,pointsAwarded:25}}catch(g){return console.error("Error submitting review:",g),{success:!1,error:g.message}}},[s]),h=N.useCallback(async()=>{if(s)try{await H.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}},t_s="https://search.google.com/local/writereview?placeid=ChIJM73ERQD1QogRPxupMFObuck&source=g.page.m.ia._&laa=nmx-review-solicitation-ia2",s_s=()=>{const{shouldShowPrompt:s,isLoading:t,dismissPrompt:n,submitReview:r,markPostedToGoogle:a}=c4t(),[i,l]=N.useState(!1),[o,c]=N.useState("review"),[d,u]=N.useState(0),[h,m]=N.useState(0),[f,g]=N.useState(""),[y,x]=N.useState(!1),[_,b]=N.useState(!1);if(t||!s&&!_)return null;const k=async()=>{if(d===0){xa({title:"Please select a rating",variant:"destructive"});return}x(!0);const P=await r(d,f);x(!1),P.success?(b(!0),xa({title:"Thank you for your feedback!",description:"Your review helps us improve."}),c("google")):xa({title:"Error submitting review",description:P.error,variant:"destructive"})},A=async P=>{P&&(await navigator.clipboard.writeText(f||`${d} star rating for LevelUp!`),xa({title:"Review copied!",description:"Paste it on Google Reviews."}),await a(),window.open(t_s,"_blank")),l(!1),n()},T=()=>{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(Wa,{className:"h-3.5 w-3.5 fill-current"}),e.jsx("span",{className:"hidden sm:inline",children:"Leave a Review"})]}),e.jsx(Bs,{open:i,onOpenChange:T,children:e.jsx(Fs,{className:"sm:max-w-md",children:o==="review"?e.jsxs(e.Fragment,{children:[e.jsxs(qs,{children:[e.jsx($s,{className:"text-center",children:"How are you enjoying LevelUp?"}),e.jsx(Ar,{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(P=>e.jsx("button",{type:"button",onClick:()=>u(P),onMouseEnter:()=>m(P),onMouseLeave:()=>m(0),className:"p-1 transition-transform hover:scale-110",children:e.jsx(Wa,{className:Ot("h-8 w-8 transition-colors",(h||d)>=P?"fill-yellow-400 text-yellow-400":"text-muted-foreground")})},P))}),e.jsx(Ws,{placeholder:"Tell us about your experience (optional)",value:f,onChange:P=>g(P.target.value),rows:4,className:"resize-none"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(B,{variant:"outline",onClick:T,className:"flex-1",children:"Maybe Later"}),e.jsx(B,{onClick:k,disabled:y||d===0,className:"flex-1",children:y?"Submitting...":"Submit Review"})]})]})]}):e.jsxs(e.Fragment,{children:[e.jsxs(qs,{children:[e.jsx($s,{className:"text-center",children:"🎉 Thank you!"}),e.jsx(Ar,{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:()=>A(!1),className:"flex-1",children:"No Thanks"}),e.jsx(B,{onClick:()=>A(!0),className:"flex-1",children:"Yes, Open Google"})]})]})]})})})]})};function n_s(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 x=localStorage.getItem(y);if(!x){const{data:k,error:A}=await H.functions.invoke("get-vapid-public-key",{body:{}});if(A)throw A;if(x=(k==null?void 0:k.vapidPublicKey)??null,!x)throw new Error("Missing VAPID public key");localStorage.setItem(y,x)}u(x);const _=await navigator.serviceWorker.register("/push-sw.js",{scope:"/push-notifications/"});c(_),n(Notification.permission);const b=await _.pushManager.getSubscription();a(!!b)}catch(y){console.error("Error initializing push notifications:",y)}finally{l(!1)}})()},[h]);const m=N.useCallback(async()=>{if(!h||!o||!s)return console.error("Push notifications not supported or user not logged in"),!1;if(!d)return ie.error("Push notifications are not ready yet. Please try again in a moment."),!1;try{l(!0);const g=await o.pushManager.getSubscription();if(g){try{await g.unsubscribe()}catch(A){console.warn("Failed to unsubscribe existing push subscription:",A)}const{error:k}=await H.from("push_subscriptions").delete().eq("user_id",s.id);k&&console.warn("Failed to cleanup push_subscriptions rows:",k)}if(Notification.permission!=="granted"){const k=await Notification.requestPermission();if(n(k),k!=="granted")return k==="denied"?ie.error("Notifications blocked. Please enable them in your browser settings (click the lock icon in the address bar)."):ie.error("Notification permission was dismissed. Please try again."),!1}const y=n_s(d);let x;try{x=await o.pushManager.subscribe({userVisibleOnly:!0,applicationServerKey:y})}catch(k){console.error("PushManager.subscribe() failed:",k);const A=(k==null?void 0:k.message)||String(k);return A.includes("permission")?ie.error("Push permission denied. Check your browser notification settings."):A.includes("key")||A.includes("VAPID")?ie.error("Push configuration error. Please contact support."):A.includes("AbortError")?ie.error("Push subscription was cancelled. Please try again."):ie.error(`Failed to subscribe: ${A}`),!1}const _=x.toJSON(),{error:b}=await H.from("push_subscriptions").upsert({user_id:s.id,endpoint:_.endpoint,p256dh_key:_.keys.p256dh,auth_key:_.keys.auth},{onConflict:"user_id,endpoint"});if(b)throw console.error("Error saving subscription:",b),ie.error("Failed to save notification preferences. Please try again."),b;return a(!0),ie.success("Push notifications enabled!"),!0}catch(g){if(console.error("Error subscribing to push notifications:",g),!(g instanceof Error&&g.message.includes("toast"))){const y=g instanceof Error?g.message:"Unknown error";ie.error("Failed to enable push notifications: "+y)}return!1}finally{l(!1)}},[h,o,s,d]),f=N.useCallback(async()=>{if(!o||!s)return!1;try{l(!0);const g=await o.pushManager.getSubscription();return g&&await g.unsubscribe(),await H.from("push_subscriptions").delete().eq("user_id",s.id),a(!1),ie.success("Push notifications disabled"),!0}catch(g){console.error("Error unsubscribing:",g);const y=g instanceof Error?g.message:"Unknown error";return ie.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:f}}const aMe="push_notification_prompt_dismissed",r_s=["/dashboard","/admin"],a_s=()=>{const{user:s}=Ls(),{isSupported:t,isSubscribed:n,isLoading:r,subscribe:a}=d4t(),i=Id(),[l,o]=N.useState(!1),[c,d]=N.useState(!1),u=r_s.some(f=>i.pathname===f||i.pathname.startsWith(`${f}/`));N.useEffect(()=>{if(u){o(!1);return}if(!s||!t||n||r||localStorage.getItem(`${aMe}_${s.id}`))return;const g=setTimeout(()=>{o(!0)},2e3);return()=>clearTimeout(g)},[s,t,n,r,u]);const h=async()=>{d(!0);const f=await a();d(!1),f&&(s&&localStorage.setItem(`${aMe}_${s.id}`,"true"),o(!1))},m=()=>{s&&localStorage.setItem(`${aMe}_${s.id}`,"true"),o(!1)};return!t||n||u?null:e.jsx(Bs,{open:l,onOpenChange:f=>!f&&m(),children:e.jsxs(Fs,{className:"sm:max-w-md",children:[e.jsxs(qs,{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(yg,{className:"h-6 w-6 text-primary"})}),e.jsx($s,{className:"text-center",children:"Stay in the Loop!"}),e.jsx(Ar,{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."})]})})},drt=s=>{let t;const n=new Set,r=(d,u)=>{const h=typeof d=="function"?d(t):d;if(!Object.is(h,t)){const m=t;t=u??(typeof h!="object"||h===null)?h:Object.assign({},t,h),n.forEach(f=>f(t,m))}},a=()=>t,o={setState:r,getState:a,getInitialState:()=>c,subscribe:d=>(n.add(d),()=>n.delete(d))},c=t=s(r,a,o);return o},i_s=s=>s?drt(s):drt,o_s=s=>s;function l_s(s,t=o_s){const n=Rt.useSyncExternalStore(s.subscribe,Rt.useCallback(()=>t(s.getState()),[s,t]),Rt.useCallback(()=>t(s.getInitialState()),[s,t]));return Rt.useDebugValue(n),n}const urt=s=>{const t=i_s(s),n=r=>l_s(t,r);return Object.assign(n,t),n},c_s=s=>s?urt(s):urt;function d_s(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 NRe=s=>t=>{try{const n=s(t);return n instanceof Promise?n:{then(r){return NRe(r)(n)},catch(r){return this}}}catch(n){return{then(r){return this},catch(r){return NRe(r)(n)}}}},u_s=(s,t)=>(n,r,a)=>{let i={storage:d_s(()=>window.localStorage),partialize:x=>x,version:0,merge:(x,_)=>({..._,...x}),...t},l=!1,o=0;const c=new Set,d=new Set;let u=i.storage;if(!u)return s((...x)=>{console.warn(`[zustand persist middleware] Unable to update item '${i.name}', the given storage is currently unavailable.`),n(...x)},r,a);const h=()=>{const x=i.partialize({...r()});return u.setItem(i.name,{state:x,version:i.version})},m=a.setState;a.setState=(x,_)=>(m(x,_),h());const f=s((...x)=>(n(...x),h()),r,a);a.getInitialState=()=>f;let g;const y=()=>{var x,_;if(!u)return;const b=++o;l=!1,c.forEach(A=>{var T;return A((T=r())!=null?T:f)});const k=((_=i.onRehydrateStorage)==null?void 0:_.call(i,(x=r())!=null?x:f))||void 0;return NRe(u.getItem.bind(u))(i.name).then(A=>{if(A)if(typeof A.version=="number"&&A.version!==i.version){if(i.migrate){const T=i.migrate(A.state,A.version);return T instanceof Promise?T.then(P=>[!0,P]):[!0,T]}console.error("State loaded from storage couldn't be migrated since no migrate function was provided")}else return[!1,A.state];return[!1,void 0]}).then(A=>{var T;if(b!==o)return;const[P,I]=A;if(g=i.merge(I,(T=r())!=null?T:f),n(g,!0),P)return h()}).then(()=>{b===o&&(k==null||k(r(),void 0),g=r(),l=!0,d.forEach(A=>A(g)))}).catch(A=>{b===o&&(k==null||k(void 0,A))})};return a.persist={setOptions:x=>{i={...i,...x},x.storage&&(u=x.storage)},clearStorage:()=>{u==null||u.removeItem(i.name)},getOptions:()=>i,rehydrate:()=>y(),hasHydrated:()=>l,onHydrate:x=>(c.add(x),()=>{c.delete(x)}),onFinishHydration:x=>(d.add(x),()=>{d.delete(x)})},i.skipHydration||y(),g||f},h_s=u_s,J4e=c_s()(h_s((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 m_s(s){return s!=null&&s.length?s.find(t=>t.is_active&&t.mls_provider_id&&!t.no_mls_mode)||s[0]:null}function Qx(){const{user:s}=Ls(),{data:t,isLoading:n}=mt({queryKey:["agent-lead-site",s==null?void 0:s.id],queryFn:async()=>{const{data:r,error:a}=await H.from("lead_sites").select("id, subdomain_slug, site_title, is_active, mls_provider_id, no_mls_mode, mls_agent_id, mls_agent_key, mls_office_id").eq("agent_id",s.id).eq("is_active",!0).order("created_at",{ascending:!0}).limit(10);if(a)throw a;return m_s(r)},enabled:!!s,staleTime:5*60*1e3});return{leadSite:t??null,hasLeadSite:!!t,isLoading:n,siteUrl:t?`https://${t.subdomain_slug}.thelocalmove.com`:null}}const hrt="dashboard-sidebar-collapsed",Qs=({children:s,title:t})=>{var Ae;const{user:n,signOut:r,isAdmin:a,isBrokerageManager:i,isCoach:l,brokerageId:o}=Ls(),{isAssistant:c,actingAsAgent:d,hasPermission:u}=n4e(),{hasAccess:h}=GUe(),{isImpersonating:m}=s4e(),g=(c&&!!d?40:0)+(m?40:0),{avatarUrl:y}=vSt(n==null?void 0:n.id),{isTrial:x,isExpired:_,expiresAt:b}=A1s(n==null?void 0:n.id),{isInnerCircleEnabled:k,isMarketplaceEnabled:A}=_St(),{currentBrief:T,shouldShowPopup:P,hasUnseenBrief:I,openBrief:M,closeBrief:L,dismissBrief:z}=Qbs(),{unreadCount:$}=T1s(),{openCount:V}=E1s(),{data:W}=Cj(),G=!!W,te=J4e(Xe=>Xe.cartItems).reduce((Xe,$e)=>Xe+$e.quantity,0),{leadSite:ne,hasLeadSite:me,siteUrl:ue}=Qx(),ce=tr(),ae=Id(),[he,xe]=N.useState(null);N.useEffect(()=>{n!=null&&n.id&&H.from("profiles").select("name").eq("id",n.id).single().then(({data:Xe})=>{Xe!=null&&Xe.name&&xe(Xe.name)})},[n==null?void 0:n.id]);const ve=he||((Ae=n==null?void 0:n.user_metadata)==null?void 0:Ae.name)||(n==null?void 0:n.email)||"User",[ge,be]=N.useState(()=>typeof window<"u"?localStorage.getItem(hrt)==="true":!1);N.useEffect(()=>{localStorage.setItem(hrt,String(ge))},[ge]);const[Se,Ie]=N.useState({agentos:!0,tools:!0,marketing:!0,learning:!0,community:!0,contacts:!0,website:!0,help:!1}),Me=Xe=>{Ie($e=>({...$e,[Xe]:!$e[Xe]}))},Re=Xe=>Xe.split(" ").map($e=>$e[0]).join("").toUpperCase().slice(0,2),Be=Xe=>ae.pathname===Xe,Ne=Xe=>Xe.some($e=>ae.pathname===$e),Ge=({path:Xe,icon:$e,label:Ye,badgeCount:Je})=>{const Ke=e.jsxs(B,{variant:"ghost",size:"sm",className:Ot("text-sidebar-foreground hover:bg-sidebar-accent hover:text-sidebar-accent-foreground relative",Be(Xe)&&"bg-sidebar-accent text-sidebar-accent-foreground",ge?"w-10 h-10 p-0 justify-center":"w-full justify-start gap-2"),onClick:()=>ce(Xe),children:[e.jsxs("div",{className:"relative",children:[e.jsx($e,{className:"h-4 w-4 shrink-0"}),ge&&Je!=null&&Je>0&&e.jsx("span",{className:"absolute -top-1 -right-1 h-2 w-2 rounded-full bg-muted-foreground/40 border border-background"})]}),!ge&&Ye,!ge&&Je!=null&&Je>0&&e.jsx("span",{className:"ml-auto flex h-5 w-5 items-center justify-center rounded-full bg-muted text-muted-foreground text-xs font-medium border border-muted-foreground/20",children:Je>9?"9+":Je})]});return ge?e.jsxs(wu,{delayDuration:0,children:[e.jsx(ju,{asChild:!0,children:Ke}),e.jsxs(nu,{side:"right",className:"flex items-center gap-2",children:[Ye,Je!=null&&Je>0&&e.jsx("span",{className:"flex h-5 w-5 items-center justify-center rounded-full bg-muted text-muted-foreground text-xs font-medium border border-muted-foreground/20",children:Je>9?"9+":Je})]})]}):Ke},Ce=({id:Xe,label:$e,icon:Ye,children:Je,activePaths:Ke,showBetaBadge:st,defaultPath:rt,badgeCount:Ze})=>{if(ge){const ht=rt||Ke[0];return e.jsxs(wu,{delayDuration:0,children:[e.jsx(ju,{asChild:!0,children:e.jsx(B,{variant:"ghost",size:"sm",className:Ot("w-10 h-10 p-0 justify-center text-sidebar-foreground hover:bg-sidebar-accent hover:text-sidebar-accent-foreground relative",Ne(Ke)&&"text-primary"),onClick:()=>ce(ht),children:e.jsxs("div",{className:"relative",children:[e.jsx(Ye,{className:"h-4 w-4"}),Ze!=null&&Ze>0&&e.jsx("span",{className:"absolute -top-1 -right-1 h-2 w-2 rounded-full bg-muted-foreground/40 border border-background"})]})})}),e.jsxs(nu,{side:"right",className:"flex items-center gap-2",children:[$e,st&&e.jsx("span",{className:"text-[9px] font-bold uppercase tracking-wide px-1 py-0.5 rounded border border-amber-500 text-amber-600",children:"Beta"}),Ze!=null&&Ze>0&&e.jsx("span",{className:"flex h-5 w-5 items-center justify-center rounded-full bg-muted text-muted-foreground text-xs font-medium border border-muted-foreground/20",children:Ze>9?"9+":Ze})]})]})}return e.jsxs(Kv,{open:Se[Xe],onOpenChange:()=>Me(Xe),children:[e.jsx(Yv,{asChild:!0,children:e.jsxs(B,{variant:"ghost",size:"sm",className:Ot("w-full justify-between gap-2 text-sidebar-foreground hover:bg-sidebar-accent hover:text-sidebar-accent-foreground",Ne(Ke)&&"text-primary"),children:[e.jsxs("span",{className:"flex items-center gap-2 font-semibold text-[15px]",children:[e.jsx(Ye,{className:"h-4 w-4"}),$e,st&&e.jsx("span",{className:"text-[9px] font-bold uppercase tracking-wide px-1 py-0.5 rounded border border-amber-500 text-amber-600 dark:text-amber-400 bg-amber-500/10",children:"Beta"})]}),e.jsxs("span",{className:"flex items-center gap-1",children:[Ze!=null&&Ze>0&&e.jsx("span",{className:"flex h-5 w-5 items-center justify-center rounded-full bg-muted text-muted-foreground text-xs font-medium border border-muted-foreground/20",children:Ze>9?"9+":Ze}),e.jsx(Xo,{className:Ot("h-4 w-4 transition-transform duration-200",Se[Xe]&&"rotate-180")})]})]})}),e.jsx(Zv,{className:"pl-4 space-y-1 mt-1",children:Je})]})},Fe=({isMobile:Xe=!1})=>{const $e=Xe?!1:ge;return e.jsxs("div",{className:"flex flex-col h-full",children:[e.jsxs("div",{className:Ot("p-3 border-b border-sidebar-border",$e?"flex flex-col items-center gap-2":"flex items-center justify-between"),children:[$e?e.jsx("img",{src:O1s,alt:"LevelUp",className:"h-8 w-auto"}):e.jsx("img",{src:R1s,alt:"LevelUp",className:"h-8 w-auto"}),!Xe&&e.jsxs(wu,{delayDuration:0,children:[e.jsx(ju,{asChild:!0,children:e.jsx(B,{variant:"ghost",size:"icon",className:"h-8 w-8 shrink-0",onClick:()=>be(!$e),children:e.jsx(Fc,{className:Ot("h-4 w-4 transition-transform duration-300",$e&&"rotate-180")})})}),e.jsx(nu,{side:"right",children:$e?"Expand sidebar":"Collapse sidebar"})]})]}),e.jsx(lo,{className:"flex-1 [&_[data-radix-scroll-area-scrollbar]]:w-1.5",children:e.jsxs("nav",{className:Ot("p-3 space-y-1",$e&&"flex flex-col items-center"),children:[Xe&&x&&!_&&e.jsx("button",{type:"button",onClick:()=>ce("/subscription"),className:Ot("relative w-full overflow-hidden rounded-md p-[1.5px] mb-2","bg-[linear-gradient(120deg,#f59e0b,#ef4444,#a855f7,#f59e0b)] bg-[length:200%_200%]","animate-gradient-x shadow-lg shadow-amber-500/20"),children:e.jsxs("span",{className:"flex items-center gap-2 rounded-[5px] bg-sidebar px-3 py-2 text-sm font-semibold text-sidebar-foreground",children:[e.jsx(Cn,{className:"h-4 w-4 text-amber-500 animate-pulse"}),e.jsx("span",{className:"flex-1 text-left bg-[linear-gradient(90deg,#f59e0b,#ef4444,#a855f7)] bg-clip-text text-transparent",children:"Ready to Upgrade?"}),b&&e.jsxs("span",{className:"text-[10px] font-bold uppercase tracking-wide px-1.5 py-0.5 rounded bg-amber-500/15 text-amber-600 dark:text-amber-400 border border-amber-500/30",children:[Math.max(0,Math.ceil((new Date(b).getTime()-Date.now())/864e5)),"d left"]})]})}),e.jsx(Ge,{path:"/dashboard",icon:ET,label:"Dashboard"}),e.jsx(Ge,{path:"/apps",icon:Iw,label:"Apps & Tools"}),ge?e.jsxs(wu,{delayDuration:0,children:[e.jsx(ju,{asChild:!0,children:e.jsx(B,{variant:"ghost",size:"sm",className:Ot("w-10 h-10 p-0 justify-center relative bg-primary/10 text-primary hover:bg-primary/20 border border-primary/30",Be("/programs")&&"bg-primary/25"),onClick:()=>ce("/programs"),children:e.jsx(By,{className:"h-4 w-4 shrink-0"})})}),e.jsx(nu,{side:"right",children:"Programs"})]}):e.jsxs(B,{variant:"ghost",size:"sm",className:Ot("w-full justify-start gap-2 bg-primary/10 text-primary border border-primary/30 hover:bg-primary/20 hover:text-primary font-semibold",Be("/programs")&&"bg-primary/25"),onClick:()=>ce("/programs"),children:[e.jsx(By,{className:"h-4 w-4 shrink-0"}),"Programs"]}),ge?e.jsxs(wu,{delayDuration:0,children:[e.jsx(ju,{asChild:!0,children:e.jsxs(B,{variant:"ghost",size:"sm",className:Ot("w-10 h-10 p-0 justify-center relative text-sidebar-foreground hover:bg-sidebar-accent hover:text-sidebar-accent-foreground",Be("/levelup-u")&&"bg-sidebar-accent text-sidebar-accent-foreground"),onClick:()=>ce("/levelup-u"),children:[e.jsx(Oh,{className:"h-4 w-4 shrink-0"}),e.jsx("span",{className:"absolute -top-0.5 -right-0.5 h-2 w-2 rounded-full bg-primary animate-pulse"})]})}),e.jsxs(nu,{side:"right",className:"flex items-center gap-2",children:["LevelUp U",e.jsx("span",{className:"text-[10px] font-bold uppercase tracking-wider text-primary-foreground bg-primary rounded px-1 py-0.5",children:"New"})]})]}):e.jsxs(B,{variant:"ghost",size:"sm",className:Ot("w-full justify-start gap-2 text-sidebar-foreground hover:bg-sidebar-accent hover:text-sidebar-accent-foreground",Be("/levelup-u")&&"bg-sidebar-accent text-sidebar-accent-foreground"),onClick:()=>ce("/levelup-u"),children:[e.jsx(Oh,{className:"h-4 w-4 shrink-0"}),"LevelUp U",e.jsx("span",{className:"ml-auto text-[10px] font-bold uppercase tracking-wider text-primary-foreground bg-primary rounded px-1.5 py-0.5",children:"New"})]}),e.jsx(Ge,{path:"/events",icon:ld,label:"Events"}),e.jsxs(Ce,{id:"agentos",label:"Agent OS",icon:NT,activePaths:["/mission-control","/mission-control/contacts","/mission-control/plans","/mission-control/popbys","/mission-control/video-library","/mission-control/scorecard","/mission-control/listings","/mission-control/pipeline","/mission-control/tasks","/mission-control/smart-drips","/mission-control/relationship-scorecard","/mission-control/sphere-gaps","/mission-control/signals","/mission-control/connect-page","/mission-control/client-portals","/mission-control/vendors","/mission-control/portal-referrals","/email-campaigns/templates"],showBetaBadge:!0,defaultPath:"/mission-control",children:[u("contacts")&&e.jsx(Ge,{path:"/mission-control",icon:co,label:"Mission Control"}),u("contacts")&&!$e&&e.jsxs(Kv,{open:Se.contacts,onOpenChange:()=>Me("contacts"),children:[e.jsx(Yv,{asChild:!0,children:e.jsxs(B,{variant:"ghost",size:"sm",className:Ot("w-full justify-between gap-2 text-sidebar-foreground hover:bg-sidebar-accent hover:text-sidebar-accent-foreground",Ne(["/mission-control/contacts","/mission-control/relationship-scorecard","/mission-control/sphere-gaps","/mission-control/connect-page"])&&"text-primary"),children:[e.jsxs("span",{className:"flex items-center gap-2",children:[e.jsx(Yn,{className:"h-4 w-4"}),"Contacts"]}),e.jsx(Xo,{className:Ot("h-3.5 w-3.5 transition-transform duration-200",Se.contacts&&"rotate-180")})]})}),e.jsxs(Zv,{className:"pl-4 pr-1 space-y-0.5 mt-0.5",children:[e.jsx(Ge,{path:"/mission-control/contacts",icon:Yn,label:"All Contacts"}),e.jsx(Ge,{path:"/mission-control/relationship-scorecard",icon:gg,label:"Relationship Report"}),e.jsx(Ge,{path:"/mission-control/sphere-gaps",icon:vW,label:"Sphere Gaps"}),e.jsx(Ge,{path:"/mission-control/sent-emails",icon:Rr,label:"Sent Emails"}),e.jsx(Ge,{path:"/mission-control/connect-page",icon:cd,label:"Connect Page"})]})]}),u("contacts")&&$e&&e.jsx(Ge,{path:"/mission-control/contacts",icon:Yn,label:"Contacts"}),u("contacts")&&e.jsx(Ge,{path:"/mission-control/plans",icon:ld,label:"TouchPlans"}),u("pipeline")&&e.jsx(Ge,{path:"/mission-control/pipeline",icon:r3,label:"Deal Pipeline"}),u("pipeline")&&e.jsx(Ge,{path:"/mission-control/transactions",icon:e3,label:"Transactions"}),u("pipeline")&&e.jsx(Ge,{path:"/mission-control/tasks",icon:d4,label:"Tasks"}),u("popbys")&&e.jsx(Ge,{path:"/mission-control/popbys",icon:Io,label:"Popbys"}),u("videos")&&e.jsx(Ge,{path:"/mission-control/video-library",icon:na,label:"Video Library"}),u("scorecard")&&e.jsx(Ge,{path:"/mission-control/scorecard",icon:fl,label:"Scorecard"}),u("listings")&&e.jsx(Ge,{path:"/mission-control/listings",icon:Ti,label:"Listing Exchange"}),e.jsx(Ge,{path:"/mission-control/client-portals",icon:Cn,label:"Client Portals"}),e.jsx(Ge,{path:"/mission-control/signals",icon:_D,label:"Signals"}),!$e&&e.jsxs(B,{variant:"ghost",size:"sm",className:Ot("w-full justify-start gap-2 text-sidebar-foreground hover:bg-sidebar-accent hover:text-sidebar-accent-foreground",Be("/mission-control/smart-drips")&&"bg-sidebar-accent text-sidebar-accent-foreground"),onClick:()=>ce("/mission-control/smart-drips"),children:[e.jsx(ff,{className:"h-4 w-4"}),"Smart Drips",e.jsx("span",{className:"ml-auto text-[9px] font-bold uppercase tracking-wide px-1 py-0.5 rounded border border-amber-500 text-amber-600 dark:text-amber-400 bg-amber-500/10",children:"Beta"})]}),$e&&e.jsx(Ge,{path:"/mission-control/smart-drips",icon:ff,label:"Smart Drips"}),e.jsx(Ge,{path:"/email-campaigns/templates",icon:mn,label:"Email Templates"})]}),me&&ne&&e.jsxs(Ce,{id:"website",label:"My Website",icon:au,activePaths:[`/admin/lead-sites/${ne.id}/edit`],defaultPath:`/admin/lead-sites/${ne.id}/edit`,children:[$e?e.jsxs(wu,{delayDuration:0,children:[e.jsx(ju,{asChild:!0,children:e.jsx(B,{variant:"ghost",size:"sm",className:"w-10 h-10 p-0 justify-center text-sidebar-foreground hover:bg-sidebar-accent hover:text-sidebar-accent-foreground",onClick:()=>window.open(ue||"#","_blank"),children:e.jsx(da,{className:"h-4 w-4"})})}),e.jsx(nu,{side:"right",children:"View Site"})]}):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:()=>window.open(ue||"#","_blank"),children:[e.jsx(da,{className:"h-4 w-4"}),"View Site",e.jsx(Tr,{className:"h-3 w-3 ml-auto opacity-50"})]}),e.jsx(Ge,{path:`/my-website/${ne.id}/edit`,icon:Ja,label:"Edit Website"}),e.jsx(Ge,{path:"/my-website/mls-listings",icon:_a,label:"MLS Listings"}),e.jsx(Ge,{path:"/my-website/market-report",icon:fl,label:"Market Reports"}),(ne==null?void 0:ne.mls_provider_id)&&e.jsx(Ge,{path:"/mission-control/cma",icon:u5,label:"CMA Reports"}),e.jsx(Ge,{path:"/mission-control/website-activity",icon:gg,label:"Website Activity"}),e.jsx(Ge,{path:"/m",icon:$y,label:"Mobile Command"})]}),e.jsxs(Ce,{id:"marketing",label:"Marketing",icon:um,activePaths:["/templates","/social-swag-2","/newsletters","/website-apps","/marketing-studio","/weekly-reels"],defaultPath:"/templates",children:[e.jsx(Ge,{path:"/templates",icon:zc,label:"Templates"}),e.jsx(Ge,{path:"/marketing-studio",icon:pc,label:"Marketing Studio"}),e.jsx(Ge,{path:"/social-swag-2",icon:$y,label:"Social Swag"}),ge?e.jsxs(wu,{delayDuration:0,children:[e.jsx(ju,{asChild:!0,children:e.jsxs(B,{variant:"ghost",size:"sm",className:Ot("w-10 h-10 p-0 justify-center relative text-sidebar-foreground hover:bg-sidebar-accent hover:text-sidebar-accent-foreground",Be("/newsletters")&&"bg-sidebar-accent text-sidebar-accent-foreground"),onClick:()=>ce("/newsletters"),children:[e.jsx(E_,{className:"h-4 w-4 shrink-0"}),e.jsx("span",{className:"absolute -top-0.5 -right-0.5 h-2 w-2 rounded-full bg-primary animate-pulse"})]})}),e.jsxs(nu,{side:"right",className:"flex items-center gap-2",children:["Newsletter Pro",e.jsx("span",{className:"text-[10px] font-bold uppercase tracking-wider text-primary-foreground bg-primary rounded px-1 py-0.5",children:"New"})]})]}):e.jsxs(B,{variant:"ghost",size:"sm",className:Ot("w-full justify-start gap-2 text-sidebar-foreground hover:bg-sidebar-accent hover:text-sidebar-accent-foreground",Be("/newsletters")&&"bg-sidebar-accent text-sidebar-accent-foreground"),onClick:()=>ce("/newsletters"),children:[e.jsx(E_,{className:"h-4 w-4 shrink-0"}),"Newsletter Pro",e.jsx("span",{className:"ml-auto text-[10px] font-bold uppercase tracking-wider text-primary-foreground bg-primary rounded px-1.5 py-0.5",children:"New"})]}),e.jsx(Ge,{path:"/website-apps",icon:Cn,label:"Website Apps"}),h&&e.jsx(Ge,{path:"/weekly-reels",icon:Rh,label:"Weekly Reels"})]}),e.jsxs(Ce,{id:"learning",label:"Learning",icon:Ep,activePaths:["/academy","/toolbox","/programs"],defaultPath:"/academy",children:[e.jsx(Ge,{path:"/academy",icon:Oh,label:"Academy"}),e.jsx(Ge,{path:"/toolbox",icon:sN,label:"Toolbox"})]}),e.jsxs(Ce,{id:"community",label:"Community",icon:xo,activePaths:["/community","/wishlist"],defaultPath:"/community",badgeCount:$,children:[e.jsx(Ge,{path:"/community",icon:Yn,label:"Community",badgeCount:$}),e.jsx(Ge,{path:"/wishlist",icon:Z2,label:"Wishlist",badgeCount:V}),!$e&&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:()=>window.open("https://www.facebook.com/share/g/1CC6thti2V/","_blank"),children:[e.jsx(Tr,{className:"h-4 w-4"}),"Facebook Group"]})]}),e.jsxs(Ce,{id:"goods",label:"The Goods",icon:W1,activePaths:["/marketplace","/reward-store"],defaultPath:"/reward-store",children:[A&&!$e&&e.jsxs(B,{variant:"ghost",size:"sm",className:Ot("w-full justify-start gap-2 text-sidebar-foreground hover:bg-sidebar-accent hover:text-sidebar-accent-foreground",ae.pathname.startsWith("/marketplace")&&"bg-sidebar-accent text-sidebar-accent-foreground"),onClick:()=>ce("/marketplace"),children:[e.jsx(W1,{className:"h-4 w-4"}),"Marketplace",e.jsx("span",{className:"ml-auto text-[9px] font-bold uppercase tracking-wide px-1.5 py-0.5 rounded-full bg-primary text-primary-foreground",children:"New"})]}),A&&$e&&e.jsx(Ge,{path:"/marketplace",icon:W1,label:"Marketplace"}),e.jsx(Ge,{path:"/reward-store",icon:gl,label:"Reward Store"}),e.jsx(Ge,{path:"/refer-friends",icon:Io,label:"Refer & Earn"})]}),e.jsxs(Ce,{id:"help",label:"Help & Services",icon:Uk,activePaths:["/support","/additional-services"],defaultPath:"/support",children:[e.jsx(Ge,{path:"/support",icon:p9,label:"Support"}),e.jsx(Ge,{path:"/additional-services",icon:Cn,label:"Additional Services"})]}),l&&e.jsx("div",{className:"pt-3 border-t border-sidebar-border mt-3 space-y-1",children:e.jsx(Ge,{path:"/coaching",icon:Oh,label:"Coaching"})}),e.jsx(p_s,{}),(n==null?void 0:n.email)==="jeremy@relevelup.com"&&e.jsxs(B,{variant:"ghost",size:"sm",className:Ot("w-full justify-start gap-2 text-sidebar-foreground hover:bg-sidebar-accent hover:text-sidebar-accent-foreground",ae.pathname.startsWith("/attract")&&"bg-sidebar-accent text-sidebar-accent-foreground"),onClick:()=>ce("/attract"),children:[e.jsx(Cn,{className:"h-4 w-4 text-violet-600"}),!$e&&e.jsx("span",{children:"LevelUp Attract"}),!$e&&e.jsx("span",{className:"ml-auto text-[9px] font-semibold text-violet-600 uppercase tracking-wider",children:"Beta"})]}),a&&e.jsxs(e.Fragment,{children:[!$e&&e.jsx("div",{className:"pt-3 pb-1",children:e.jsx("p",{className:"px-2 text-xs font-semibold text-muted-foreground uppercase tracking-wider",children:"Admin"})}),$e?e.jsx("div",{className:"pt-3 border-t border-sidebar-border mt-3 space-y-1",children:e.jsx(Ge,{path:"/admin",icon:Au,label:"Admin Dashboard"})}):e.jsxs(B,{variant:"ghost",size:"sm",className:Ot("w-full justify-start gap-2 text-sidebar-foreground hover:bg-sidebar-accent hover:text-sidebar-accent-foreground",ae.pathname==="/admin"&&"bg-sidebar-accent text-sidebar-accent-foreground"),onClick:()=>ce("/admin"),children:[e.jsx(Au,{className:"h-4 w-4"}),"Admin Dashboard"]})]}),(o||i)&&!a&&e.jsxs(e.Fragment,{children:[!$e&&e.jsx("div",{className:"pt-3 pb-1",children:e.jsx("p",{className:"px-2 text-xs font-semibold text-muted-foreground uppercase tracking-wider",children:"My Brokerage"})}),$e?e.jsxs("div",{className:"border-t border-sidebar-border mt-3 pt-3 space-y-1",children:[o&&e.jsxs(e.Fragment,{children:[e.jsx(Ge,{path:"/my-brokerage",icon:Ti,label:"My Brokerage"}),e.jsx(Ge,{path:"/brokerage/help-board",icon:R2,label:"Help Board"}),e.jsx(Ge,{path:"/brokerage-content",icon:Ep,label:"Brokerage Content"})]}),G&&!i&&e.jsx(Ge,{path:"/my-team",icon:Yn,label:"My Team"}),i&&e.jsxs(e.Fragment,{children:[e.jsx(Ge,{path:"/brokerage/dashboard",icon:sc,label:"Manage Brokerages"}),e.jsx(Ge,{path:"/brokerage/teams",icon:Yn,label:"Teams"}),e.jsx(Ge,{path:"/brokerage/recruiting",icon:um,label:"Recruiting"}),e.jsx(Ge,{path:"/brokerage/vendors",icon:Y2,label:"Vendors"}),e.jsx(Ge,{path:"/brokerage-resources",icon:vg,label:"Brokerage Resources"})]})]}):e.jsxs(e.Fragment,{children:[o&&e.jsxs(e.Fragment,{children:[e.jsxs(B,{variant:"ghost",size:"sm",className:Ot("w-full justify-start gap-2 text-sidebar-foreground hover:bg-sidebar-accent hover:text-sidebar-accent-foreground",Be("/my-brokerage")&&"bg-sidebar-accent text-sidebar-accent-foreground"),onClick:()=>ce("/my-brokerage"),children:[e.jsx(Ti,{className:"h-4 w-4"}),"My Brokerage"]}),e.jsxs(B,{variant:"ghost",size:"sm",className:Ot("w-full justify-start gap-2 text-sidebar-foreground hover:bg-sidebar-accent hover:text-sidebar-accent-foreground",Be("/brokerage/help-board")&&"bg-sidebar-accent text-sidebar-accent-foreground"),onClick:()=>ce("/brokerage/help-board"),children:[e.jsx(R2,{className:"h-4 w-4"}),"Help Board"]}),e.jsxs(B,{variant:"ghost",size:"sm",className:Ot("w-full justify-start gap-2 text-sidebar-foreground hover:bg-sidebar-accent hover:text-sidebar-accent-foreground",Be("/brokerage-content")&&"bg-sidebar-accent text-sidebar-accent-foreground"),onClick:()=>ce("/brokerage-content"),children:[e.jsx(Ep,{className:"h-4 w-4"}),"Brokerage Content"]})]}),G&&!i&&e.jsxs(B,{variant:"ghost",size:"sm",className:Ot("w-full justify-start gap-2 text-sidebar-foreground hover:bg-sidebar-accent hover:text-sidebar-accent-foreground",Be("/my-team")&&"bg-sidebar-accent text-sidebar-accent-foreground"),onClick:()=>ce("/my-team"),children:[e.jsx(Yn,{className:"h-4 w-4"}),"My Team"]}),i&&e.jsxs(e.Fragment,{children:[e.jsxs(B,{variant:"ghost",size:"sm",className:Ot("w-full justify-start gap-2 text-sidebar-foreground hover:bg-sidebar-accent hover:text-sidebar-accent-foreground",Be("/brokerage/dashboard")&&"bg-sidebar-accent text-sidebar-accent-foreground"),onClick:()=>ce("/brokerage/dashboard"),children:[e.jsx(sc,{className:"h-4 w-4"}),"Manage Brokerages"]}),e.jsxs(B,{variant:"ghost",size:"sm",className:Ot("w-full justify-start gap-2 text-sidebar-foreground hover:bg-sidebar-accent hover:text-sidebar-accent-foreground",Be("/brokerage/teams")&&"bg-sidebar-accent text-sidebar-accent-foreground"),onClick:()=>ce("/brokerage/teams"),children:[e.jsx(Yn,{className:"h-4 w-4"}),"Teams",e.jsx("span",{className:"ml-auto text-[9px] font-bold uppercase tracking-wide px-1 py-0.5 rounded border border-amber-500 text-amber-600 dark:text-amber-400 bg-amber-500/10",children:"New"})]}),e.jsxs(B,{variant:"ghost",size:"sm",className:Ot("w-full justify-start gap-2 text-sidebar-foreground hover:bg-sidebar-accent hover:text-sidebar-accent-foreground",Be("/brokerage/recruiting")&&"bg-sidebar-accent text-sidebar-accent-foreground"),onClick:()=>ce("/brokerage/recruiting"),children:[e.jsx(um,{className:"h-4 w-4"}),"Recruiting"]}),e.jsxs(B,{variant:"ghost",size:"sm",className:Ot("w-full justify-start gap-2 text-sidebar-foreground hover:bg-sidebar-accent hover:text-sidebar-accent-foreground",Be("/brokerage/vendors")&&"bg-sidebar-accent text-sidebar-accent-foreground"),onClick:()=>ce("/brokerage/vendors"),children:[e.jsx(Y2,{className:"h-4 w-4"}),"Vendors"]}),e.jsxs(B,{variant:"ghost",size:"sm",className:Ot("w-full justify-start gap-2 text-sidebar-foreground hover:bg-sidebar-accent hover:text-sidebar-accent-foreground",Be("/brokerage-resources")&&"bg-sidebar-accent text-sidebar-accent-foreground"),onClick:()=>ce("/brokerage-resources"),children:[e.jsx(vg,{className:"h-4 w-4"}),"Brokerage Resources"]})]})]})]})]})}),e.jsxs("div",{className:"p-3 border-t border-sidebar-border md:hidden",children:[e.jsxs(B,{variant:"ghost",size:"sm",className:Ot("w-full justify-start gap-2 text-sidebar-foreground hover:bg-sidebar-accent hover:text-sidebar-accent-foreground",Be("/profile")&&"bg-sidebar-accent text-sidebar-accent-foreground"),onClick:()=>ce("/profile"),children:[e.jsx(Ro,{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:r,children:[e.jsx(xD,{className:"h-4 w-4"}),"Sign Out"]})]})]})};return e.jsx(fN,{children:e.jsxs("div",{className:"min-h-screen bg-background flex",children:[x&&_&&ae.pathname!=="/subscription"&&e.jsx(zbs,{}),typeof document<"u"&&Lv.createPortal(e.jsx("aside",{className:Ot("hidden md:flex flex-col bg-card border-r border-border fixed left-0 z-30 !pointer-events-auto transition-[width] duration-300",ge?"w-16":"w-56"),style:{top:`${g}px`,height:`calc(100vh - ${g}px)`},children:e.jsx(Fe,{})}),document.body),e.jsxs("div",{className:Ot("flex-1 flex flex-col overflow-hidden transition-all duration-300",ge?"md:ml-16":"md:ml-56"),style:{height:`calc(100vh - ${g}px)`,marginTop:`${g}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(l1,{children:[e.jsx(PQ,{asChild:!0,children:e.jsx(B,{variant:"ghost",size:"icon",className:"md:hidden",children:e.jsx(MT,{className:"h-5 w-5"})})}),e.jsx(Gy,{side:"left",className:"w-56 p-0 bg-card",children:e.jsx(Fe,{isMobile:!0})})]}),e.jsx("div",{className:"flex-1 md:hidden",children:e.jsx("img",{src:F1s,alt:"LevelUp",className:"h-8 w-auto"})}),e.jsx("div",{className:"hidden md:flex flex-1 justify-center",children:e.jsx(crt,{})}),e.jsxs("div",{className:"flex items-center gap-3 ml-auto",children:[x&&!_&&b&&e.jsx(Fbs,{expiresAt:b,className:"hidden lg:flex"}),e.jsx("div",{className:"md:hidden",children:e.jsx(crt,{})}),T&&e.jsx(Bbs,{hasUnseenBrief:I,onClick:M}),A&&e.jsxs(B,{variant:"ghost",size:"icon",className:"relative",onClick:()=>ce("/marketplace/cart"),children:[e.jsx(W1,{className:"h-5 w-5"}),te>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:te>99?"99+":te})]}),e.jsx(dbs,{}),e.jsx(_Re,{}),e.jsxs("span",{className:"hidden sm:block text-sm font-medium text-foreground",children:["Hello, ",ve.split(" ")[0],"!"]}),e.jsxs(qd,{children:[e.jsx(Vd,{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(Ua,{className:"h-9 w-9 cursor-pointer hover:opacity-80 transition-opacity",children:[e.jsx(Gi,{src:y||void 0}),e.jsx(qa,{className:"bg-primary text-primary-foreground font-medium text-sm",children:Re(ve)})]})})}),e.jsxs(Ld,{align:"end",className:"w-48",children:[e.jsxs(ba,{onClick:()=>ce("/profile"),className:"cursor-pointer",children:[e.jsx(Ro,{className:"h-4 w-4 mr-2"}),"Profile"]}),e.jsxs(ba,{onClick:()=>ce("/mission-control/integrations"),className:"cursor-pointer",children:[e.jsx(o3,{className:"h-4 w-4 mr-2"}),"Integrations"]}),e.jsxs(ba,{onClick:()=>ce("/mission-control/browser-extension"),className:"cursor-pointer",children:[e.jsx(o3,{className:"h-4 w-4 mr-2"}),"Browser Extension"]}),e.jsx(s1,{}),e.jsxs(ba,{onClick:r,className:"cursor-pointer text-destructive focus:text-destructive",children:[e.jsx(xD,{className:"h-4 w-4 mr-2"}),"Sign Out"]})]})]})]})]})}),e.jsx(e_s,{children:e.jsx("main",{className:"p-4 sm:p-6 lg:p-8 overflow-x-hidden",children:s})}),T&&e.jsx(Xbs,{brief:T,open:P,onClose:L,onDismiss:z}),e.jsx(Jbs,{}),e.jsx(s_s,{}),e.jsx(a_s,{})]})]})})};function p_s(){const{user:s}=Ls(),t=Id(),n=tr(),{data:r}=mt({queryKey:["my-coach-nav",s==null?void 0:s.id],enabled:!!s,queryFn:async()=>{const{data:i}=await H.from("coaching_assignments").select("id").eq("agent_id",s.id).eq("status","active").limit(1);return(i||[]).length>0}});if(!r)return null;const a=t.pathname==="/my-coach";return e.jsx("div",{className:"pt-3 border-t border-sidebar-border mt-3 space-y-1",children: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 ${a?"bg-sidebar-accent text-sidebar-accent-foreground":""}`,onClick:()=>n("/my-coach"),children:[e.jsx(Oh,{className:"h-4 w-4"}),"My Coach"]})})}const mrt="https://relzejiswnotikjgvjhz.supabase.co/functions/v1/mcp",f_s="https://tile-portal.lovable.app/mcp-oauth-bridge.html",g_s=[{label:"Open ChatGPT",description:"You need ChatGPT Plus, Pro, or Team to add custom MCP connectors."},{label:"Add a new connector",description:"Settings → Connectors → Add. Choose 'Custom / MCP Server'."},{label:"Fill in the basics",description:"Name it LevelUp and add a short description like 'Tools for the LevelUp real estate platform.'"},{label:"Paste the server URL",description:"Paste the MCP server URL below into the Server URL field. Do not paste the tile-portal bridge URL."},{label:"Confirm OAuth",description:"Authentication should be OAuth. Check the 'I understand' box, then tap Create."},{label:"Sign in to LevelUp",description:"ChatGPT will open a LevelUp consent page. Sign in with your LevelUp account and tap Approve."},{label:"Start chatting",description:"Ask ChatGPT to 'list my upcoming LevelUp trainings' or 'summarize my Inner Circle contacts'."}];function x_s(){const[s,t]=N.useState(!1),n=async()=>{try{await navigator.clipboard.writeText(mrt),t(!0),ie.success("MCP URL copied to clipboard"),setTimeout(()=>t(!1),2e3)}catch{ie.error("Could not copy URL")}};return e.jsx(Qs,{children:e.jsxs("div",{className:"space-y-6 p-4 md:p-8 max-w-3xl mx-auto",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"p-3 rounded-lg bg-primary/10",children:e.jsx(NT,{className:"h-6 w-6 text-primary"})}),e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl font-bold tracking-tight",children:"Connect ChatGPT to LevelUp"}),e.jsx("p",{className:"text-muted-foreground",children:"Let ChatGPT use LevelUp tools while you are signed in."})]})]}),e.jsxs(_e,{children:[e.jsxs(zt,{children:[e.jsx(qt,{children:"Use this exact MCP server URL"}),e.jsx(_r,{children:"Paste only this URL into ChatGPT's Server URL field."})]}),e.jsx(De,{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:mrt}),e.jsx(B,{variant:"outline",size:"icon",onClick:n,"aria-label":"Copy MCP URL",children:s?e.jsx(Po,{className:"h-4 w-4 text-green-600"}):e.jsx(Pa,{className:"h-4 w-4"})})]})})]}),e.jsx(_e,{className:"border-destructive/30 bg-destructive/5",children:e.jsx(De,{className:"pt-6",children:e.jsxs("div",{className:"flex gap-3",children:[e.jsx(xd,{className:"h-5 w-5 text-destructive shrink-0 mt-0.5"}),e.jsxs("div",{className:"space-y-2 text-sm",children:[e.jsx("p",{className:"font-semibold text-destructive",children:"Do not use the bridge URL as the Server URL."}),e.jsx("p",{className:"text-muted-foreground",children:"If ChatGPT shows “does not implement OAuth,” it means this wrong URL was pasted:"}),e.jsx("code",{className:"block rounded-md bg-background px-3 py-2 break-all text-xs",children:f_s}),e.jsx("p",{className:"text-muted-foreground",children:"Delete that plugin attempt and create a new one with the MCP server URL above."})]})]})})}),e.jsxs(_e,{children:[e.jsxs(zt,{children:[e.jsx(qt,{children:"Quick steps"}),e.jsx(_r,{children:"ChatGPT adds MCP servers as a new plugin / custom tool. Share these steps with any agent who wants to connect."})]}),e.jsx(De,{children:e.jsx("ol",{className:"space-y-4",children:g_s.map((r,a)=>e.jsxs("li",{className:"flex gap-3",children:[e.jsx("span",{className:"flex h-6 w-6 shrink-0 items-center justify-center rounded-full bg-primary/10 text-xs font-medium text-primary",children:a+1}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:r.label}),e.jsx("p",{className:"text-sm text-muted-foreground",children:r.description})]})]},a))})})]}),e.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[e.jsx(Tr,{className:"h-4 w-4"}),e.jsx("span",{children:"Only basic tools are exposed today. More LevelUp actions will be added over time."})]})]})})}const y_s=()=>{const[s]=$c(),t=s.get("tier"),n=t==null?void 0:t.includes("brokerage");return e.jsx("div",{className:"min-h-screen bg-gradient-to-br from-background via-primary/5 to-secondary/10 flex items-center justify-center p-4",children:e.jsxs(_e,{className:"max-w-lg w-full",children:[e.jsxs(zt,{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(Po,{className:"w-10 h-10 text-green-500"})}),e.jsx(qt,{className:"text-2xl",children:"Welcome to LevelUp!"}),e.jsx(_r,{className:"text-lg",children:"Your subscription has been activated successfully."})]}),e.jsxs(De,{className:"space-y-6",children:[e.jsxs("div",{className:"p-4 rounded-lg bg-primary/10 border border-primary/20 space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2 text-primary",children:[e.jsx(mn,{className:"w-5 h-5"}),e.jsx("span",{className:"font-semibold",children:"Check your email to sign in"})]}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"We've sent you an email with a secure link to access your account. Click the link in your email to get started."})]}),n?e.jsxs("div",{className:"space-y-3",children:[e.jsx("h3",{className:"font-semibold",children:"What's next?"}),e.jsxs("ul",{className:"space-y-2 text-sm text-muted-foreground",children:[e.jsxs("li",{className:"flex items-start gap-2",children:[e.jsx("span",{className:"font-bold text-primary",children:"1."}),"Click the link in your email to sign in"]}),e.jsxs("li",{className:"flex items-start gap-2",children:[e.jsx("span",{className:"font-bold text-primary",children:"2."}),"Create and name your brokerage"]}),e.jsxs("li",{className:"flex items-start gap-2",children:[e.jsx("span",{className:"font-bold text-primary",children:"3."}),"Set your password and complete your profile"]}),e.jsxs("li",{className:"flex items-start gap-2",children:[e.jsx("span",{className:"font-bold text-primary",children:"4."}),"Start inviting agents to join your team"]})]})]}):e.jsxs("div",{className:"space-y-3",children:[e.jsx("h3",{className:"font-semibold",children:"What's next?"}),e.jsxs("ul",{className:"space-y-2 text-sm text-muted-foreground",children:[e.jsxs("li",{className:"flex items-start gap-2",children:[e.jsx("span",{className:"font-bold text-primary",children:"1."}),"Click the link in your email to sign in"]}),e.jsxs("li",{className:"flex items-start gap-2",children:[e.jsx("span",{className:"font-bold text-primary",children:"2."}),"Set your password and complete your profile"]}),e.jsxs("li",{className:"flex items-start gap-2",children:[e.jsx("span",{className:"font-bold text-primary",children:"3."}),"Start exploring templates, training videos, and more!"]})]}),e.jsx("p",{className:"text-sm text-green-600 font-medium mt-4",children:"🎉 Your 7-day free trial has started!"})]}),e.jsx("div",{className:"p-3 rounded-lg bg-muted/50 text-center",children:e.jsx("p",{className:"text-sm text-muted-foreground",children:"Didn't receive the email? Check your spam folder or contact support."})})]})]})})},v_s=()=>{const{user:s}=Ls(),[t,n]=N.useState(!1),[r,a]=N.useState(null),[i,l]=N.useState(""),o=async h=>{var m;if(!(s!=null&&s.email)){ie.error("Please sign in to upgrade");return}n(!0),a(h);try{const{data:f,error:g}=await H.functions.invoke("create-checkout",{body:{tier:h,email:s.email,name:((m=s.user_metadata)==null?void 0:m.full_name)||s.email,couponCode:i.trim()||void 0,skipTrial:!0}});if(g)throw g;if(f!=null&&f.url)window.open(f.url,"_blank","noopener,noreferrer"),ie.success("Checkout opened in a new tab");else throw new Error("No checkout URL returned")}catch(f){console.error("Checkout error:",f),ie.error(f.message||"Failed to start checkout. Please try again.")}finally{n(!1),a(null)}},c=["Unlimited access to all marketing templates","Complete Academy training library","AI-powered tools and resources","Community forums and support","Exclusive member events and workshops","Deal pipeline & scorecard tracking","Listing exchange access","Social media content library"],d=["Everything in Individual plan","Up to 25 agent seats","Brokerage admin dashboard","Team performance analytics","Custom branding options","Priority support","Agent onboarding tools","Brokerage-wide announcements"],u=["Everything in Brokerage plan","Unlimited agent seats","Dedicated account manager","Advanced analytics & reporting","White-label options","API access","Custom integrations","Enterprise-level support"];return e.jsx(Qs,{children:e.jsxs("div",{className:"container max-w-6xl py-8 px-4",children:[e.jsxs("div",{className:"text-center mb-8",children:[e.jsx("h1",{className:"text-3xl font-bold mb-2",children:"Upgrade Your Membership"}),e.jsx("p",{className:"text-muted-foreground text-lg",children:"Choose the plan that's right for you and unlock the full power of LevelUp"})]}),e.jsxs("div",{className:"max-w-md mx-auto mb-8",children:[e.jsx(re,{htmlFor:"coupon",className:"text-sm font-medium",children:"Have a discount code?"}),e.jsx(we,{id:"coupon",placeholder:"Enter discount code",value:i,onChange:h=>l(h.target.value),className:"mt-1"})]}),e.jsxs("div",{className:"grid md:grid-cols-3 gap-6 mb-8",children:[e.jsxs(_e,{className:"border-2 border-primary/20 hover:border-primary/50 transition-colors relative overflow-hidden",children:[e.jsx("div",{className:"absolute top-0 right-0 bg-primary text-primary-foreground text-xs px-3 py-1 rounded-bl-lg font-medium",children:"Popular"}),e.jsxs(zt,{className:"text-center pb-2",children:[e.jsx("div",{className:"mx-auto mb-3 h-14 w-14 rounded-full bg-primary/10 flex items-center justify-center",children:e.jsx(Yn,{className:"h-7 w-7 text-primary"})}),e.jsx(qt,{className:"text-xl",children:"Individual Agent"}),e.jsx(_r,{children:"Perfect for solo agents ready to level up"})]}),e.jsxs(De,{className:"space-y-6",children:[e.jsxs("div",{className:"text-center",children:[e.jsx("span",{className:"text-4xl font-bold text-primary",children:"$39"}),e.jsx("span",{className:"text-muted-foreground",children:"/month"})]}),e.jsx("ul",{className:"space-y-2",children:c.map((h,m)=>e.jsxs("li",{className:"flex items-start gap-2 text-sm",children:[e.jsx(pa,{className:"h-4 w-4 text-primary mt-0.5 shrink-0"}),e.jsx("span",{children:h})]},m))}),e.jsxs(B,{className:"w-full",size:"lg",onClick:()=>o("individual_agent"),disabled:t,children:[t&&r==="individual_agent"?e.jsx(us,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(Cn,{className:"h-4 w-4 mr-2"}),"Get Started"]})]})]}),e.jsxs(_e,{className:"border-2 border-amber-500/20 hover:border-amber-500/50 transition-colors",children:[e.jsxs(zt,{className:"text-center pb-2",children:[e.jsx("div",{className:"mx-auto mb-3 h-14 w-14 rounded-full bg-amber-500/10 flex items-center justify-center",children:e.jsx(Ti,{className:"h-7 w-7 text-amber-600"})}),e.jsx(qt,{className:"text-xl",children:"Brokerage"}),e.jsx(_r,{children:"For teams and brokerages up to 25 agents"})]}),e.jsxs(De,{className:"space-y-6",children:[e.jsxs("div",{className:"text-center",children:[e.jsx("span",{className:"text-4xl font-bold text-amber-600",children:"$299"}),e.jsx("span",{className:"text-muted-foreground",children:"/month"})]}),e.jsx("ul",{className:"space-y-2",children:d.map((h,m)=>e.jsxs("li",{className:"flex items-start gap-2 text-sm",children:[e.jsx(pa,{className:"h-4 w-4 text-amber-600 mt-0.5 shrink-0"}),e.jsx("span",{children:h})]},m))}),e.jsxs(B,{variant:"outline",className:"w-full border-amber-500 text-amber-600 hover:bg-amber-50",size:"lg",onClick:()=>o("brokerage_under_25"),disabled:t,children:[t&&r==="brokerage_under_25"?e.jsx(us,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(Ti,{className:"h-4 w-4 mr-2"}),"Get Started"]})]})]}),e.jsxs(_e,{className:"border-2 border-purple-500/20 hover:border-purple-500/50 transition-colors",children:[e.jsxs(zt,{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(Ti,{className:"h-7 w-7 text-purple-600"})}),e.jsx(qt,{className:"text-xl",children:"Brokerage 25+"}),e.jsx(_r,{children:"For larger brokerages with 25+ agents"})]}),e.jsxs(De,{className:"space-y-6",children:[e.jsxs("div",{className:"text-center",children:[e.jsx("span",{className:"text-4xl font-bold text-purple-600",children:"$499"}),e.jsx("span",{className:"text-muted-foreground",children:"/month"})]}),e.jsx("ul",{className:"space-y-2",children:u.map((h,m)=>e.jsxs("li",{className:"flex items-start gap-2 text-sm",children:[e.jsx(pa,{className:"h-4 w-4 text-purple-600 mt-0.5 shrink-0"}),e.jsx("span",{children:h})]},m))}),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(us,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(Ti,{className:"h-4 w-4 mr-2"}),"Get Started"]})]})]})]}),e.jsx(_e,{className:"bg-muted/50",children:e.jsxs(De,{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(ga,{className:"h-4 w-4"}),e.jsx("span",{children:"1-866-527-8668"})]}),e.jsxs("a",{href:"mailto:support@relevelup.com",className:"flex items-center justify-center gap-2 text-primary hover:underline",children:[e.jsx(mn,{className:"h-4 w-4"}),e.jsx("span",{children:"support@relevelup.com"})]})]})]})})]})})},b_s=()=>{const{user:s,loading:t,isBrokerageManager:n,brokerageId:r}=Ls(),a=tr(),[i,l]=N.useState(""),[o,c]=N.useState(!1),[d,u]=N.useState(!1);N.useEffect(()=>{!t&&!s&&a("/auth")},[s,t,a]),N.useEffect(()=>{!t&&s&&r&&a("/profile?setup=true")},[s,t,r,a]);const h=async()=>{if(!i.trim()){ie.error("Please enter a brokerage name");return}const{data:m}=await H.auth.getSession(),f=m.session;if(!s||!f){ie.error("Please sign in again to create your brokerage."),a("/auth");return}c(!0);try{console.log("[SetupBrokerage] Creating brokerage…",{hasUser:!!s,hasSession:!!f,userId:s==null?void 0:s.id});const{data:g,error:y}=await H.functions.invoke("create-brokerage",{body:{name:i.trim()}});if(console.log("[SetupBrokerage] create-brokerage response",{data:g,error:y}),y)throw y;if(!(g!=null&&g.ok))throw new Error((g==null?void 0:g.error)||"Failed to create brokerage");c(!1),u(!0),ie.success("Brokerage created! Setting up your account..."),setTimeout(()=>{a("/profile?setup=true")},2e3)}catch(g){console.error("Error creating brokerage:",g),ie.error(g.message||"Failed to create brokerage"),c(!1)}};return t?e.jsx("div",{className:"flex min-h-screen items-center justify-center bg-background",children:e.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})}):d?e.jsx("div",{className:"min-h-screen bg-gradient-to-br from-background via-primary/5 to-secondary/10 flex items-center justify-center p-4",children:e.jsxs(_e,{className:"max-w-lg w-full",children:[e.jsxs(zt,{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(us,{className:"w-10 h-10 text-primary animate-spin"})}),e.jsx(qt,{className:"text-2xl",children:"Setting Up Your Brokerage"}),e.jsx(_r,{className:"text-lg",children:"We're assigning you as the brokerage manager and preparing your dashboard..."})]}),e.jsxs(De,{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-center gap-2 text-muted-foreground",children:[e.jsx(Po,{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(us,{className:"w-5 h-5 animate-spin text-primary"}),e.jsx("span",{children:"Assigning you as manager..."})]}),e.jsx("p",{className:"text-center text-sm text-muted-foreground mt-4",children:"You'll be redirected to complete your profile setup in a moment."})]})]})}):e.jsx("div",{className:"min-h-screen bg-gradient-to-br from-background via-primary/5 to-secondary/10 flex items-center justify-center p-4",children:e.jsxs(_e,{className:"max-w-lg w-full",children:[e.jsxs(zt,{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(Ti,{className:"w-10 h-10 text-primary"})}),e.jsx(qt,{className:"text-2xl",children:"Set Up Your Brokerage"}),e.jsx(_r,{className:"text-lg",children:"Create your brokerage to start managing your team"})]}),e.jsxs(De,{className:"space-y-6",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{htmlFor:"brokerage-name",children:"Brokerage Name"}),e.jsx(we,{id:"brokerage-name",placeholder:"Enter your brokerage name",value:i,onChange:m=>l(m.target.value),onKeyDown:m=>m.key==="Enter"&&h()}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"This is how your brokerage will appear to your agents"})]}),e.jsxs("div",{className:"p-4 rounded-lg bg-muted/50 space-y-3",children:[e.jsxs("h3",{className:"font-semibold flex items-center gap-2",children:[e.jsx(Yn,{className:"w-4 h-4 text-primary"}),"What you can do as a Brokerage Manager:"]}),e.jsxs("ul",{className:"space-y-2 text-sm text-muted-foreground",children:[e.jsxs("li",{className:"flex items-center gap-2",children:[e.jsx(Po,{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(Po,{className:"w-4 h-4 text-green-500"}),"Access exclusive brokerage resources"]}),e.jsxs("li",{className:"flex items-center gap-2",children:[e.jsx(Po,{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(Po,{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(vi,{className:"w-4 h-4 ml-2"})]})]})]})})},prt=()=>{const s=tr(),[t,n]=N.useState("verifying"),[r,a]=N.useState("");N.useEffect(()=>{(async()=>{try{const{data:{session:o},error:c}=await H.auth.getSession();if(c)throw c;if(o!=null&&o.user){const{data:d}=await H.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 H.functions.invoke("trial-claim-hook",{body:{userId:o.user.id}})}catch(u){console.log("Trial claim hook (non-critical):",u)}setTimeout(()=>{s("/profile?setup=true")},1500)}else setTimeout(()=>{n("already_claimed")},2e3)}catch(o){console.error("Claim error:",o),n("already_claimed")}})()},[s]);const i=()=>{window.location.href="https://dashboard.relevelup.com/auth"};return e.jsx("div",{className:"flex min-h-screen items-center justify-center bg-background p-4",children:e.jsxs(_e,{className:"w-full max-w-md",children:[e.jsxs(zt,{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(qt,{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(_r,{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(De,{children:e.jsx(B,{onClick:i,className:"w-full",children:"Go to Login"})})]})})},__s=()=>{const[s,t]=N.useState(!1),n=N.useMemo(()=>new URLSearchParams(window.location.search).get("link"),[]),r=N.useMemo(()=>{if(!n)return!1;try{const i=new URL(n);return i.hostname.endsWith(".supabase.co")&&i.pathname.startsWith("/auth/v1/verify")}catch{return!1}},[n]);N.useEffect(()=>{document.title="Reset Your Password"},[]);const a=()=>{!r||!n||(t(!0),window.location.href=n)};return e.jsxs("div",{className:"min-h-screen relative overflow-hidden",children:[e.jsx("div",{className:"absolute inset-0 bg-gradient-to-br from-[#4a6b6d] via-[#3d5a5c] to-[#2a4347]"}),e.jsx("div",{className:"relative z-10 flex flex-col min-h-screen items-center justify-center p-4",children:e.jsxs("div",{className:"w-full max-w-md",children:[e.jsx("div",{className:"flex justify-center mb-8",children:e.jsx("div",{className:"bg-white rounded-xl p-4 shadow-2xl",children:e.jsx("img",{src:ySt,alt:"LevelUp",className:"h-12 w-auto"})})}),e.jsxs(_e,{className:"border-0 shadow-2xl bg-white/95 backdrop-blur-sm",children:[e.jsxs(zt,{className:"text-center",children:[e.jsx(qt,{className:"text-2xl font-bold text-[#2a4347]",style:{fontFamily:"'Libre Baskerville', serif"},children:"Reset Your Password"}),e.jsx(_r,{className:"text-gray-600 pt-2",children:r?"Click the button below to continue resetting your password.":"This link is invalid or has expired. Please request a new password reset email."})]}),e.jsxs(De,{className:"space-y-4",children:[r?e.jsx(B,{onClick:a,disabled:s,className:"w-full bg-[#4a6b6d] hover:bg-[#3d5a5c] text-white font-semibold py-6 text-lg shadow-lg hover:shadow-xl",children:s?"Continuing…":"Continue to Reset Password"}):e.jsx(B,{onClick:()=>window.location.href="/auth",className:"w-full bg-[#4a6b6d] hover:bg-[#3d5a5c] text-white font-semibold py-6 text-lg",children:"Go to Sign In"}),e.jsx("p",{className:"text-xs text-center text-gray-500 pt-2",children:"For your security, password reset links expire and can only be used once."})]})]})]})})]})},w_s=()=>{const s=tr(),[t]=$c(),[n,r]=N.useState(t.get("code")||""),[a,i]=N.useState(""),[l,o]=N.useState(""),[c,d]=N.useState(""),[u,h]=N.useState(!1),[m,f]=N.useState(!1),[g,y]=N.useState(!1),[x,_]=N.useState(!1),[b,k]=N.useState(null),[A,T]=N.useState(null),[P,I]=N.useState(null),[M,L]=N.useState(null);N.useEffect(()=>{const W=t.get("code");W&&(r(W),z(W))},[t]);const z=async W=>{y(!0);const{data:G,error:X}=await H.from("invite_codes").select("id, code, max_uses, uses_count, expires_at, is_active, brokerage_id, trial_days").eq("code",W.toUpperCase().trim()).single();if(X||!G){ie.error("Invalid invite code"),y(!1);return}if(!G.is_active){ie.error("This invite code is no longer active"),y(!1);return}if(G.max_uses&&G.uses_count>=G.max_uses){ie.error("This invite code has reached its maximum uses"),y(!1);return}if(G.expires_at&&new Date(G.expires_at){W.preventDefault(),z(n)},V=async W=>{var G;if(W.preventDefault(),!c.trim()){ie.error("Please enter your name");return}if(l.length<6){ie.error("Password must be at least 6 characters");return}f(!0);try{const X=`${window.location.origin}/`,{data:te,error:ne}=await H.auth.signUp({email:a.trim(),password:l,options:{emailRedirectTo:X,data:{name:c.trim()}}});if(ne){ne.message.includes("already registered")?ie.error("This email is already registered. Please sign in instead."):ie.error(ne.message);return}if(te.user){await H.rpc("add_default_signup_tag",{user_id:te.user.id});const me=n.toUpperCase().trim();A?await H.functions.invoke("assign-brokerage",{body:{userId:te.user.id,brokerageId:A,inviteCode:me}}):M?await H.functions.invoke("assign-brokerage",{body:{userId:te.user.id,trialDays:M,inviteCode:me}}):await H.functions.invoke("assign-brokerage",{body:{userId:te.user.id,grandfathered:!0,inviteCode:me}}),b&&await H.from("invite_codes").update({uses_count:((G=(await H.from("invite_codes").select("uses_count").eq("id",b).single()).data)==null?void 0:G.uses_count)+1}).eq("id",b),ie.success("Account created! You can now access the dashboard."),s("/dashboard")}}catch(X){console.error("Signup error:",X),ie.error("An unexpected error occurred")}finally{f(!1)}};return e.jsx("div",{className:"min-h-screen flex items-center justify-center bg-background p-4",children:e.jsxs(_e,{className:"w-full max-w-md",children:[e.jsxs(zt,{className:"text-center",children:[e.jsx(qt,{className:"text-2xl font-bold text-primary",children:P?`Join ${P}`:"Join LevelUp"}),e.jsx(_r,{children:x?P?`Create your account to join ${P}`:"Create your account to get started":"Enter your invite code to continue"})]}),e.jsx(De,{children:x?e.jsxs("form",{onSubmit:V,className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{htmlFor:"name",children:"Full Name"}),e.jsx(we,{id:"name",type:"text",placeholder:"John Doe",value:c,onChange:W=>d(W.target.value),required:!0})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{htmlFor:"email",children:"Email"}),e.jsx(we,{id:"email",type:"email",placeholder:"you@example.com",value:a,onChange:W=>i(W.target.value),required:!0})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{htmlFor:"password",children:"Password"}),e.jsxs("div",{className:"relative",children:[e.jsx(we,{id:"password",type:u?"text":"password",placeholder:"••••••••",value:l,onChange:W=>o(W.target.value),required:!0,minLength:6}),e.jsx("button",{type:"button",className:"absolute right-3 top-1/2 -translate-y-1/2 text-muted-foreground hover:text-foreground",onClick:()=>h(!u),children:u?e.jsx(V0,{className:"h-4 w-4"}):e.jsx(da,{className:"h-4 w-4"})})]})]}),e.jsx(B,{type:"submit",className:"w-full",disabled:m,children:m?e.jsxs(e.Fragment,{children:[e.jsx(us,{className:"mr-2 h-4 w-4 animate-spin"}),"Creating Account..."]}):"Create Account"})]}):e.jsxs("form",{onSubmit:$,className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{htmlFor:"inviteCode",children:"Invite Code"}),e.jsx(we,{id:"inviteCode",type:"text",placeholder:"Enter your invite code",value:n,onChange:W=>r(W.target.value),required:!0,autoFocus:!0})]}),e.jsx(B,{type:"submit",className:"w-full",disabled:g,children:g?e.jsxs(e.Fragment,{children:[e.jsx(us,{className:"mr-2 h-4 w-4 animate-spin"}),"Verifying..."]}):"Verify Code"})]})})]})})},UQ=()=>{const{user:s,isCoach:t}=Ls();return mt({queryKey:["my-coach-profile",s==null?void 0:s.id],enabled:!!s&&t,queryFn:async()=>{const{data:n,error:r}=await H.from("coaches").select("*").eq("user_id",s.id).maybeSingle();if(r)throw r;return n}})},j_s=()=>{const{data:s}=UQ();return mt({queryKey:["coach-roster",s==null?void 0:s.id],enabled:!!s,queryFn:async()=>{const{data:t,error:n}=await H.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 H.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}))}})},N_s=()=>{const{user:s}=Ls();return mt({queryKey:["my-coaching-assignment",s==null?void 0:s.id],enabled:!!s,queryFn:async()=>{const{data:t,error:n}=await H.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 H.from("coaches").select("*").eq("id",r.coach_id).maybeSingle();let i=null;if(a!=null&&a.user_id){const{data:l}=await H.from("profiles").select("id, name, email, avatar_url").eq("id",a.user_id).maybeSingle();i=l}return{...r,coach:a,coachProfile:i}}})},k_s=s=>mt({queryKey:["coaching-assignment",s],enabled:!!s,queryFn:async()=>{const{data:t,error:n}=await H.from("coaching_assignments").select("*").eq("id",s).maybeSingle();if(n)throw n;if(!t)return null;const{data:r}=await H.from("profiles").select("id, name, email, avatar_url").eq("id",t.agent_id).maybeSingle();return{...t,agent:r}}}),u4t=s=>mt({queryKey:["coaching-sessions",s],enabled:!!s,queryFn:async()=>{const{data:t,error:n}=await H.from("coaching_sessions").select("*").eq("assignment_id",s).order("scheduled_at",{ascending:!1});if(n)throw n;return t||[]}}),h4t=s=>mt({queryKey:["coaching-action-items",s],enabled:!!s,queryFn:async()=>{const{data:t,error:n}=await H.from("coaching_action_items").select("*").eq("assignment_id",s).order("due_date",{ascending:!0,nullsFirst:!1});if(n)throw n;return t||[]}}),S_s=[{key:"onboarding",label:"Onboarding"},{key:"active",label:"Active"},{key:"thriving",label:"Thriving"},{key:"at_risk",label:"At Risk"},{key:"graduated",label:"Graduated"}];function C_s(){const s=tr(),{data:t,isLoading:n}=UQ(),{data:r=[],isLoading:a}=j_s();if(n)return e.jsx(Qs,{title:"Coaching",children:e.jsx("div",{className:"p-8",children:"Loading…"})});if(!t)return e.jsx(Qs,{title:"Coaching",children:e.jsxs("div",{className:"max-w-2xl mx-auto p-8 text-center",children:[e.jsx(Oh,{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."})]})});S_s.map(l=>({...l,items:r.filter(o=>(o.pipeline_stage||"active")===l.key)}));const i=r.filter(l=>l.status==="active").length;return e.jsx(Qs,{title:"Coaching",children:e.jsxs("div",{className:"p-4 md:p-8 max-w-7xl mx-auto space-y-8",children:[e.jsxs("div",{className:"relative overflow-hidden rounded-2xl bg-gradient-to-br from-[#2a4c64] to-[#406E71] text-white p-8",children:[e.jsx("div",{className:"absolute -right-20 -top-20 h-64 w-64 rounded-full bg-white/10 blur-3xl"}),e.jsxs("div",{className:"relative",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-2 text-white/80",children:[e.jsx(Cn,{className:"h-4 w-4"}),e.jsx("span",{className:"text-sm uppercase tracking-wider font-medium",children:"Coaching Command Center"})]}),e.jsx("h1",{className:"text-3xl md:text-4xl font-bold mb-2",children:"Welcome back, Coach"}),e.jsx("p",{className:"text-white/80 mb-6",children:"Lead your agents. Track momentum. Build champions."}),e.jsxs("div",{className:"flex flex-wrap gap-6",children:[e.jsx(iMe,{icon:Oh,label:"Active agents",value:i}),e.jsx(iMe,{icon:ld,label:"This month",value:"—"}),e.jsx(iMe,{icon:Cu,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(_e,{children:e.jsx(De,{className:"p-8 text-center",children:e.jsx("p",{className:"text-muted-foreground",children:"No agents assigned yet. An admin or you can invite agents to get started."})})}):e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 xl:grid-cols-3 gap-4",children:r.map(l=>{var o,c,d,u;return e.jsx(_e,{className:"cursor-pointer hover:shadow-lg transition-all hover:-translate-y-0.5",onClick:()=>s(`/coaching/agent/${l.id}`),children:e.jsx(De,{className:"p-5",children:e.jsxs("div",{className:"flex items-start gap-4",children:[e.jsxs(Ua,{className:"h-14 w-14",children:[e.jsx(Gi,{src:((o=l.agent)==null?void 0:o.avatar_url)||void 0}),e.jsx(qa,{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(vi,{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(We,{variant:"secondary",className:"capitalize",children:(l.pipeline_stage||"active").replace("_"," ")}),e.jsxs("span",{className:"text-xs text-muted-foreground",children:["Started ",nc(new Date(l.started_at),{addSuffix:!0})]})]})]})]})})},l.id)})})]})]})})}function iMe({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 m4t({assignmentId:s}){const{user:t}=Ls(),n=as(),[r,a]=N.useState(""),[i,l]=N.useState(!1),o=N.useRef(null),{data:c=[]}=mt({queryKey:["coaching-messages",s],enabled:!!s,queryFn:async()=>{const{data:u,error:h}=await H.from("coaching_messages").select("*").eq("assignment_id",s).order("created_at",{ascending:!0});if(h)throw h;return u||[]}});N.useEffect(()=>{if(!s)return;const u=H.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()=>{H.removeChannel(u)}},[s,n]),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 H.from("coaching_messages").insert({assignment_id:s,sender_id:t.id,body:u});l(!1),h||a("")};return e.jsxs(_e,{className:"flex flex-col h-[60vh] min-h-[400px]",children:[e.jsx("div",{ref:o,className:"flex-1 overflow-y-auto p-4 space-y-3",children:c.length===0?e.jsx("div",{className:"h-full flex items-center justify-center text-sm text-muted-foreground",children:"No messages yet. Say hi 👋"}):c.map(u=>{const h=u.sender_id===(t==null?void 0:t.id);return e.jsxs("div",{className:Ot("flex gap-2",h?"justify-end":"justify-start"),children:[!h&&e.jsx(Ua,{className:"h-8 w-8 mt-1",children:e.jsx(qa,{className:"text-xs",children:(u.sender_id||"?").charAt(0).toUpperCase()})}),e.jsxs("div",{className:Ot("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:Ot("text-[10px] mt-1",h?"text-white/70":"text-muted-foreground"),children:nc(new Date(u.created_at),{addSuffix:!0})})]})]},u.id)})}),e.jsx(De,{className:"border-t p-3",children:e.jsxs("div",{className:"flex gap-2 items-end",children:[e.jsx(Ws,{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(Rr,{className:"h-4 w-4"})})]})})]})}var oqe="Progress",lqe=100,[A_s,VOn]=Um(oqe),[T_s,E_s]=A_s(oqe),p4t=N.forwardRef((s,t)=>{const{__scopeProgress:n,value:r=null,max:a,getValueLabel:i=M_s,...l}=s;(a||a===0)&&!frt(a)&&console.error(L_s(`${a}`,"Progress"));const o=frt(a)?a:lqe;r!==null&&!grt(r,o)&&console.error(P_s(`${r}`,"Progress"));const c=grt(r,o)?r:null,d=hNe(c)?i(c,o):void 0;return e.jsx(T_s,{scope:n,value:c,max:o,children:e.jsx(Da.div,{"aria-valuemax":o,"aria-valuemin":0,"aria-valuenow":hNe(c)?c:void 0,"aria-valuetext":d,role:"progressbar","data-state":x4t(c,o),"data-value":c??void 0,"data-max":o,...l,ref:t})})});p4t.displayName=oqe;var f4t="ProgressIndicator",g4t=N.forwardRef((s,t)=>{const{__scopeProgress:n,...r}=s,a=E_s(f4t,n);return e.jsx(Da.div,{"data-state":x4t(a.value,a.max),"data-value":a.value??void 0,"data-max":a.max,...r,ref:t})});g4t.displayName=f4t;function M_s(s,t){return`${Math.round(s/t*100)}%`}function x4t(s,t){return s==null?"indeterminate":s===t?"complete":"loading"}function hNe(s){return typeof s=="number"}function frt(s){return hNe(s)&&!isNaN(s)&&s>0}function grt(s,t){return hNe(s)&&!isNaN(s)&&s<=t&&s>=0}function L_s(s,t){return`Invalid prop \`max\` of value \`${s}\` supplied to \`${t}\`. Only numbers greater than 0 are valid max values. Defaulting to \`${lqe}\`.`}function P_s(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 ${lqe} if no \`max\` prop is set) - \`null\` or \`undefined\` if the progress is indeterminate. Defaulting to \`null\`.`}var y4t=p4t,I_s=g4t;const ro=N.forwardRef(({className:s,value:t,...n},r)=>e.jsx(y4t,{ref:r,className:Ot("relative h-4 w-full overflow-hidden rounded-full bg-secondary",s),...n,children:e.jsx(I_s,{className:"h-full w-full flex-1 bg-primary transition-all",style:{transform:`translateX(-${100-(t||0)}%)`}})}));ro.displayName=y4t.displayName;function v4t({agentUserId:s}){const t=new Date().getFullYear(),n=`${t}-01-01`,r=`${t}-12-31`,{data:a=[]}=mt({queryKey:["coaching-kpi-txns",s,t],enabled:!!s,queryFn:async()=>{const{data:y,error:x}=await H.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(x)throw x;return y||[]}}),{data:i}=mt({queryKey:["coaching-kpi-goal",s,t],enabled:!!s,queryFn:async()=>{const{data:y}=await H.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,x)=>y+(Number(x.sale_price)||0),0),d=l.reduce((y,x)=>y+(Number(x.commission_amount)||0),0),u=i,h=(u==null?void 0:u.transactions_goal)||0,m=(u==null?void 0:u.volume_goal)||0,f=(u==null?void 0:u.gci_goal)||0,g=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(ml,{className:"h-5 w-5"})," ",t," KPIs"]}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-3",children:[e.jsx(oMe,{icon:ku,label:"Transactions",value:o.toString(),goal:h,current:o,suffix:h?`/ ${h}`:""}),e.jsx(oMe,{icon:ml,label:"Volume",value:g(c),goal:m,current:c,suffix:m?`of ${g(m)}`:""}),e.jsx(oMe,{icon:Ed,label:"GCI",value:g(d),goal:f,current:d,suffix:f?`of ${g(f)}`:""})]}),o===0&&e.jsx(_e,{children:e.jsxs(De,{className:"p-4 text-sm text-muted-foreground text-center",children:["No transactions logged for ",t," yet."]})})]})}function oMe({icon:s,label:t,value:n,goal:r,current:a,suffix:i}){const l=r>0?Math.min(100,a/r*100):0;return e.jsx(_e,{children:e.jsxs(De,{className:"p-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-2",children:[e.jsx(s,{className:"h-4 w-4"}),e.jsx("span",{className:"text-xs uppercase tracking-wider",children:t})]}),e.jsx("div",{className:"text-2xl font-bold",children:n}),r>0&&e.jsxs("div",{className:"mt-2 space-y-1",children:[e.jsx(ro,{value:l}),e.jsxs("div",{className:"flex justify-between text-xs text-muted-foreground",children:[e.jsx("span",{children:i}),e.jsxs("span",{children:[l.toFixed(0),"%"]})]})]})]})})}function b4t({assignmentId:s,canEdit:t}){const n=as(),[r,a]=N.useState(!1),[i,l]=N.useState(null),{data:o=[]}=mt({queryKey:["coaching-goals",s],enabled:!!s,queryFn:async()=>{const{data:d,error:u}=await H.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(iu,{className:"h-5 w-5"})," Goals"]}),t&&e.jsxs(B,{size:"sm",onClick:()=>{l(null),a(!0)},children:[e.jsx(nn,{className:"h-4 w-4 mr-1"})," New Goal"]})]}),o.length===0?e.jsx(_e,{children:e.jsx(De,{className:"p-6 text-center text-muted-foreground",children:"No goals yet."})}):o.map(d=>{const u=Number(d.target_value||0),h=Number(d.current_value||0),m=u>0?Math.min(100,h/u*100):0;return e.jsx(_e,{children:e.jsxs(De,{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(We,{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(Ja,{className:"h-4 w-4"})})]}),u>0&&e.jsxs("div",{className:"mt-3 space-y-1",children:[e.jsxs("div",{className:"flex justify-between text-xs text-muted-foreground",children:[e.jsxs("span",{children:[h.toLocaleString()," / ",u.toLocaleString()," ",d.target_metric||""]}),e.jsxs("span",{children:[m.toFixed(0),"%"]})]}),e.jsx(ro,{value:m})]}),d.due_date&&e.jsxs("p",{className:"text-xs text-muted-foreground mt-2",children:["Due ",Js(new Date(d.due_date),"PP")]})]})},d.id)}),t&&e.jsx(D_s,{open:r,onOpenChange:a,assignmentId:s,goal:i,onSaved:c})]})}function D_s({open:s,onOpenChange:t,assignmentId:n,goal:r,onSaved:a}){var A,T;const[i,l]=N.useState((r==null?void 0:r.title)||""),[o,c]=N.useState((r==null?void 0:r.description)||""),[d,u]=N.useState((r==null?void 0:r.target_metric)||""),[h,m]=N.useState(((A=r==null?void 0:r.target_value)==null?void 0:A.toString())||""),[f,g]=N.useState(((T=r==null?void 0:r.current_value)==null?void 0:T.toString())||"0"),[y,x]=N.useState((r==null?void 0:r.due_date)||""),[_,b]=N.useState(!1);N.useState(()=>{var P,I;l((r==null?void 0:r.title)||""),c((r==null?void 0:r.description)||""),u((r==null?void 0:r.target_metric)||""),m(((P=r==null?void 0:r.target_value)==null?void 0:P.toString())||""),g(((I=r==null?void 0:r.current_value)==null?void 0:I.toString())||"0"),x((r==null?void 0:r.due_date)||"")});const k=async()=>{if(!i.trim())return;b(!0);const P={assignment_id:n,title:i,description:o||null,target_metric:d||null,target_value:h?Number(h):null,current_value:f?Number(f):0,due_date:y||null},{error:I}=r!=null&&r.id?await H.from("coaching_goals").update(P).eq("id",r.id):await H.from("coaching_goals").insert(P);if(b(!1),I)return ie.error(I.message);ie.success(r!=null&&r.id?"Goal updated":"Goal created"),a==null||a(),t(!1)};return e.jsx(Bs,{open:s,onOpenChange:t,children:e.jsxs(Fs,{children:[e.jsx(qs,{children:e.jsx($s,{children:r!=null&&r.id?"Edit Goal":"New Goal"})}),e.jsxs("div",{className:"space-y-3",children:[e.jsx(we,{placeholder:"Title",value:i,onChange:P=>l(P.target.value)}),e.jsx(Ws,{placeholder:"Description (optional)",rows:2,value:o,onChange:P=>c(P.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(we,{placeholder:"transactions",value:d,onChange:P=>u(P.target.value)})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-xs text-muted-foreground",children:"Target"}),e.jsx(we,{type:"number",value:h,onChange:P=>m(P.target.value)})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-xs text-muted-foreground",children:"Current"}),e.jsx(we,{type:"number",value:f,onChange:P=>g(P.target.value)})]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-xs text-muted-foreground",children:"Due date"}),e.jsx(we,{type:"date",value:y,onChange:P=>x(P.target.value)})]})]}),e.jsxs(Cr,{children:[e.jsx(B,{variant:"outline",onClick:()=>t(!1),children:"Cancel"}),e.jsx(B,{onClick:k,disabled:_,children:r!=null&&r.id?"Save":"Create"})]})]})})}function _4t({assignmentId:s}){const t=as(),{user:n}=Ls(),r=N.useRef(null),[a,i]=N.useState(!1),{data:l=[]}=mt({queryKey:["coaching-files",s],enabled:!!s,queryFn:async()=>{const{data:h,error:m}=await H.from("coaching_shared_files").select("*").eq("assignment_id",s).order("created_at",{ascending:!1});if(m)throw m;return h||[]}}),o=()=>t.invalidateQueries({queryKey:["coaching-files",s]}),c=async h=>{var f;const m=(f=h.target.files)==null?void 0:f[0];if(!(!m||!n)){i(!0);try{const g=`${s}/${Date.now()}-${m.name}`,{error:y}=await H.storage.from("coaching-files").upload(g,m);if(y)throw y;const{error:x}=await H.from("coaching_shared_files").insert({assignment_id:s,uploaded_by:n.id,file_url:g,file_name:m.name,file_size_bytes:m.size,mime_type:m.type});if(x)throw x;ie.success("File uploaded"),o()}catch(g){ie.error(g.message||"Upload failed")}finally{i(!1),r.current&&(r.current.value="")}}},d=async h=>{const{data:m,error:f}=await H.storage.from("coaching-files").createSignedUrl(h.file_url,60);if(f||!m)return ie.error("Could not get download link");window.open(m.signedUrl,"_blank")},u=async h=>{confirm("Delete this file?")&&(await H.storage.from("coaching-files").remove([h.file_url]),await H.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(ni,{className:"h-4 w-4 mr-1"})," ",a?"Uploading…":"Upload"]}),e.jsx("input",{ref:r,type:"file",hidden:!0,onChange:c})]}),l.length===0?e.jsx(_e,{children:e.jsx(De,{className:"p-6 text-center text-muted-foreground",children:"No files yet."})}):e.jsx("div",{className:"space-y-2",children:l.map(h=>e.jsx(_e,{children:e.jsxs(De,{className:"p-3 flex items-center gap-3",children:[e.jsx("div",{className:"h-10 w-10 rounded-lg bg-muted flex items-center justify-center",children:e.jsx(Wr,{className:"h-5 w-5 text-muted-foreground"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("div",{className:"font-medium truncate",children:h.file_name}),e.jsxs("div",{className:"text-xs text-muted-foreground",children:[h.file_size_bytes?`${(h.file_size_bytes/1024).toFixed(0)} KB · `:"",Js(new Date(h.created_at),"PP")]})]}),e.jsx(B,{variant:"ghost",size:"icon",onClick:()=>d(h),children:e.jsx(oi,{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(qn,{className:"h-4 w-4"})})]})},h.id))})]})}function R_s(){var m,f,g,y;const{id:s}=uo(),t=tr(),n=as(),{data:r,isLoading:a}=k_s(s),{data:i=[]}=u4t(s),{data:l=[]}=h4t(s),[o,c]=N.useState(!1),[d,u]=N.useState(!1);if(a)return e.jsx(Qs,{title:"Coaching",children:e.jsx("div",{className:"p-8",children:"Loading…"})});if(!r)return e.jsx(Qs,{title:"Coaching",children:e.jsx("div",{className:"p-8",children:"Assignment not found."})});const h=r;return e.jsxs(Qs,{title:"Coaching",children:[e.jsxs("div",{className:"p-4 md:p-8 max-w-6xl mx-auto space-y-6",children:[e.jsxs(B,{variant:"ghost",size:"sm",onClick:()=>t("/coaching"),children:[e.jsx(ka,{className:"h-4 w-4 mr-2"})," Back to roster"]}),e.jsxs(_e,{className:"overflow-hidden",children:[e.jsx("div",{className:"h-24 bg-gradient-to-br from-[#2a4c64] to-[#406E71]"}),e.jsx(De,{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(Ua,{className:"h-24 w-24 ring-4 ring-background",children:[e.jsx(Gi,{src:((m=h.agent)==null?void 0:m.avatar_url)||void 0}),e.jsx(qa,{className:"text-2xl",children:(((f=h.agent)==null?void 0:f.name)||"?").charAt(0)})]}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("h1",{className:"text-2xl font-bold",children:((g=h.agent)==null?void 0:g.name)||"Unknown"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:(y=h.agent)==null?void 0:y.email}),e.jsxs("div",{className:"flex items-center gap-2 mt-2",children:[e.jsx(We,{variant:"secondary",className:"capitalize",children:(h.pipeline_stage||"active").replace("_"," ")}),e.jsx(We,{variant:"outline",className:"capitalize",children:h.status})]})]}),e.jsx("div",{className:"flex gap-2",children:e.jsx(O_s,{value:h.pipeline_stage||"active",onChange:async x=>{await H.from("coaching_assignments").update({pipeline_stage:x}).eq("id",h.id),n.invalidateQueries({queryKey:["coaching-assignment",h.id]}),n.invalidateQueries({queryKey:["coach-roster"]})}})})]})})]}),e.jsxs(ya,{defaultValue:"sessions",children:[e.jsxs(va,{className:"w-full flex flex-wrap justify-start h-auto",children:[e.jsxs(ls,{value:"sessions",children:[e.jsx(ta,{className:"h-4 w-4 mr-2"}),"Sessions"]}),e.jsxs(ls,{value:"actions",children:[e.jsx(zm,{className:"h-4 w-4 mr-2"}),"Actions"]}),e.jsxs(ls,{value:"goals",children:[e.jsx(iu,{className:"h-4 w-4 mr-2"}),"Goals"]}),e.jsxs(ls,{value:"kpis",children:[e.jsx(ml,{className:"h-4 w-4 mr-2"}),"KPIs"]}),e.jsxs(ls,{value:"messages",children:[e.jsx(xo,{className:"h-4 w-4 mr-2"}),"Messages"]}),e.jsxs(ls,{value:"files",children:[e.jsx(H0,{className:"h-4 w-4 mr-2"}),"Files"]}),e.jsxs(ls,{value:"notes",children:[e.jsx(Wr,{className:"h-4 w-4 mr-2"}),"Private Notes"]})]}),e.jsxs(_s,{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(nn,{className:"h-4 w-4 mr-1"})," New Session"]})]}),i.length===0?e.jsx(_e,{children:e.jsx(De,{className:"p-6 text-muted-foreground text-center",children:"No sessions yet."})}):e.jsx("div",{className:"space-y-3",children:i.map(x=>e.jsx(_e,{children:e.jsx(De,{className:"p-4",children:e.jsx("div",{className:"flex items-start justify-between gap-3",children:e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[e.jsx("span",{className:"font-medium",children:Js(new Date(x.scheduled_at),"PPp")}),e.jsx(We,{variant:"outline",className:"capitalize",children:x.status}),x.template&&e.jsx(We,{variant:"secondary",children:x.template})]}),x.summary&&e.jsx("p",{className:"text-sm text-muted-foreground whitespace-pre-wrap",children:x.summary}),x.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(Au,{className:"h-3 w-3"})," Private"]}),e.jsx("p",{className:"whitespace-pre-wrap",children:x.private_notes})]})]})})})},x.id))})]}),e.jsxs(_s,{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(nn,{className:"h-4 w-4 mr-1"})," Add"]})]}),l.length===0?e.jsx(_e,{children:e.jsx(De,{className:"p-6 text-muted-foreground text-center",children:"No action items yet."})}):e.jsx("div",{className:"space-y-2",children:l.map(x=>e.jsx(_e,{children:e.jsxs(De,{className:"p-3 flex items-center gap-3",children:[e.jsx(Bi,{checked:x.status==="done",onCheckedChange:async _=>{await H.from("coaching_action_items").update({status:_?"done":"open",completed_at:_?new Date().toISOString():null}).eq("id",x.id),n.invalidateQueries({queryKey:["coaching-action-items",h.id]})}}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("div",{className:x.status==="done"?"line-through text-muted-foreground":"font-medium",children:x.title}),x.description&&e.jsx("div",{className:"text-xs text-muted-foreground",children:x.description})]}),x.due_date&&e.jsx(We,{variant:"outline",children:Js(new Date(x.due_date),"MMM d")}),e.jsx(We,{variant:"secondary",className:"capitalize",children:x.priority})]})},x.id))})]}),e.jsx(_s,{value:"goals",children:e.jsx(b4t,{assignmentId:h.id,canEdit:!0})}),e.jsx(_s,{value:"kpis",children:h.agent_id&&e.jsx(v4t,{agentUserId:h.agent_id})}),e.jsx(_s,{value:"messages",children:e.jsx(m4t,{assignmentId:h.id})}),e.jsx(_s,{value:"files",children:e.jsx(_4t,{assignmentId:h.id})}),e.jsx(_s,{value:"notes",className:"space-y-4",children:e.jsx(_e,{children:e.jsx(De,{className:"p-6 text-muted-foreground",children:"Private notes per session live under the Sessions tab. General-relationship notes coming soon."})})})]})]}),e.jsx(F_s,{open:o,onOpenChange:c,assignmentId:h.id,onSaved:()=>n.invalidateQueries({queryKey:["coaching-sessions",h.id]})}),e.jsx(z_s,{open:d,onOpenChange:u,assignmentId:h.id,onSaved:()=>n.invalidateQueries({queryKey:["coaching-action-items",h.id]})})]})}function O_s({value:s,onChange:t}){return e.jsxs(Ns,{value:s,onValueChange:t,children:[e.jsx(ws,{className:"w-40",children:e.jsx(ks,{})}),e.jsxs(js,{children:[e.jsx(nt,{value:"onboarding",children:"Onboarding"}),e.jsx(nt,{value:"active",children:"Active"}),e.jsx(nt,{value:"thriving",children:"Thriving"}),e.jsx(nt,{value:"at_risk",children:"At Risk"}),e.jsx(nt,{value:"graduated",children:"Graduated"})]})]})}function F_s({open:s,onOpenChange:t,assignmentId:n,onSaved:r}){const[a,i]=N.useState(()=>new Date().toISOString().slice(0,16)),[l,o]=N.useState(60),[c,d]=N.useState("weekly_1on1"),[u,h]=N.useState(""),[m,f]=N.useState(""),[g,y]=N.useState(!1),[x,_]=N.useState(!0),[b,k]=N.useState(null),[A,T]=N.useState(!1),P=async()=>{T(!0);const{data:M,error:L}=await H.functions.invoke("coaching-prep-brief",{body:{assignmentId:n}});if(T(!1),L||M!=null&&M.error)return ie.error((M==null?void 0:M.error)||(L==null?void 0:L.message)||"Failed to generate brief");k(M.brief||"No brief returned.")},I=async()=>{y(!0);const{data:M,error:L}=await H.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(L)return y(!1),ie.error(L.message);if(ie.success("Session saved"),x&&u.trim()&&(M!=null&&M.id)){const{error:z}=await H.functions.invoke("coaching-send-recap",{body:{sessionId:M.id}});z?ie.error("Saved, but recap email failed: "+z.message):ie.success("Recap emailed to agent")}y(!1),r==null||r(),t(!1),h(""),f(""),k(null)};return e.jsx(Bs,{open:s,onOpenChange:t,children:e.jsxs(Fs,{className:"max-w-2xl max-h-[90vh] overflow-y-auto",children:[e.jsx(qs,{children:e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsx($s,{children:"New Session"}),e.jsxs(B,{size:"sm",variant:"outline",onClick:P,disabled:A,children:[A?e.jsx(us,{className:"h-4 w-4 mr-1 animate-spin"}):e.jsx(Cn,{className:"h-4 w-4 mr-1"}),"Pre-session brief"]})]})}),e.jsxs("div",{className:"space-y-3",children:[b&&e.jsxs("div",{className:"rounded-lg border bg-gradient-to-br from-[#406E71]/5 to-[#2a4c64]/5 p-3 text-sm whitespace-pre-wrap max-h-60 overflow-y-auto",children:[e.jsxs("div",{className:"flex items-center gap-1 text-xs font-medium text-[#406E71] mb-2",children:[e.jsx(Cn,{className:"h-3 w-3"})," AI Brief"]}),b]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx("label",{className:"text-sm font-medium",children:"When"}),e.jsx(we,{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(we,{type:"number",value:l,onChange:M=>o(Number(M.target.value))})]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-sm font-medium",children:"Template"}),e.jsxs(Ns,{value:c,onValueChange:d,children:[e.jsx(ws,{children:e.jsx(ks,{})}),e.jsxs(js,{children:[e.jsx(nt,{value:"weekly_1on1",children:"Weekly 1:1"}),e.jsx(nt,{value:"grow",children:"GROW Model"}),e.jsx(nt,{value:"goal_review",children:"Goal Review"}),e.jsx(nt,{value:"breakthrough",children:"Breakthrough Session"})]})]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-sm font-medium",children:"Summary (agent sees this)"}),e.jsx(Ws,{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(Au,{className:"h-3 w-3"})," Private notes (only you)"]}),e.jsx(Ws,{rows:3,value:m,onChange:M=>f(M.target.value),placeholder:"Your private observations…"})]}),e.jsxs("label",{className:"flex items-center gap-2 text-sm pt-1",children:[e.jsx(Bi,{checked:x,onCheckedChange:M=>_(!!M)}),e.jsx(Rr,{className:"h-3.5 w-3.5 text-muted-foreground"}),"Email recap to agent on save"]})]}),e.jsxs(Cr,{children:[e.jsx(B,{variant:"outline",onClick:()=>t(!1),children:"Cancel"}),e.jsxs(B,{onClick:I,disabled:g,children:[e.jsx(Kl,{className:"h-4 w-4 mr-1"})," Save Session"]})]})]})})}function z_s({open:s,onOpenChange:t,assignmentId:n,onSaved:r}){const[a,i]=N.useState(""),[l,o]=N.useState(""),[c,d]=N.useState(""),[u,h]=N.useState("medium"),[m,f]=N.useState(!1),g=async()=>{if(!a.trim())return;f(!0);const{error:y}=await H.from("coaching_action_items").insert({assignment_id:n,title:a,description:l||null,due_date:c||null,priority:u});if(f(!1),y)return ie.error(y.message);ie.success("Action item added"),r==null||r(),t(!1),i(""),o(""),d("")};return e.jsx(Bs,{open:s,onOpenChange:t,children:e.jsxs(Fs,{children:[e.jsx(qs,{children:e.jsx($s,{children:"New Action Item"})}),e.jsxs("div",{className:"space-y-3",children:[e.jsx(we,{placeholder:"Title",value:a,onChange:y=>i(y.target.value)}),e.jsx(Ws,{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(we,{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(Ns,{value:u,onValueChange:h,children:[e.jsx(ws,{children:e.jsx(ks,{})}),e.jsxs(js,{children:[e.jsx(nt,{value:"low",children:"Low"}),e.jsx(nt,{value:"medium",children:"Medium"}),e.jsx(nt,{value:"high",children:"High"})]})]})]})]})]}),e.jsxs(Cr,{children:[e.jsx(B,{variant:"outline",onClick:()=>t(!1),children:"Cancel"}),e.jsx(B,{onClick:g,disabled:m,children:"Add"})]})]})})}function kRe({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(Wa,{style:{width:t,height:t},className:r<=s?"fill-yellow-400 text-yellow-400":"text-muted-foreground/40"})},r))})}function B_s({coachId:s}){const[t,n]=N.useState([]),[r,a]=N.useState(!0);N.useEffect(()=>{(async()=>{const{data:l}=await H.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 H.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(kRe,{value:Math.round(i)}),e.jsxs("span",{children:[i.toFixed(1)," · ",t.length," review",t.length===1?"":"s"]})]})]}),e.jsx("div",{className:"space-y-3",children:t.map(l=>{var o,c,d;return e.jsx(_e,{children:e.jsx(De,{className:"p-4",children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsxs(Ua,{className:"h-9 w-9",children:[e.jsx(Gi,{src:((o=l.profile)==null?void 0:o.avatar_url)||void 0}),e.jsx(qa,{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(kRe,{value:l.rating,size:14})]}),l.title&&e.jsx("div",{className:"font-semibold mt-1",children:l.title}),l.body&&e.jsx("p",{className:"text-sm text-muted-foreground whitespace-pre-wrap mt-1",children:l.body})]})]})})},l.id)})})]})}function $_s({coachId:s,assignmentId:t}){const{user:n}=Ls(),[r,a]=N.useState(null),[i,l]=N.useState(0),[o,c]=N.useState(""),[d,u]=N.useState(""),[h,m]=N.useState(!1);N.useEffect(()=>{n&&(async()=>{const{data:g}=await H.from("coaching_reviews").select("*").eq("coach_id",s).eq("agent_id",n.id).maybeSingle();g&&(a(g),l(g.rating),c(g.title||""),u(g.body||""))})()},[n,s]);const f=async()=>{if(!n)return;if(!i)return ie.error("Pick a rating");m(!0);const g={coach_id:s,agent_id:n.id,assignment_id:t||null,rating:i,title:o||null,body:d||null},{error:y}=r?await H.from("coaching_reviews").update(g).eq("id",r.id):await H.from("coaching_reviews").insert(g);if(m(!1),y)return ie.error(y.message);ie.success("Thanks for your review!"),a({...g,id:r==null?void 0:r.id})};return e.jsx(_e,{children:e.jsxs(De,{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(kRe,{value:i,size:28,onChange:l}),e.jsx(we,{placeholder:"Title (optional)",value:o,onChange:g=>c(g.target.value)}),e.jsx(Ws,{rows:4,placeholder:"What was your experience like?",value:d,onChange:g=>u(g.target.value)}),e.jsx(B,{onClick:f,disabled:h,className:"bg-[#406E71] hover:bg-[#2a4c64]",children:h?"Saving…":r?"Update review":"Submit review"})]})})}function U_s(){var h,m,f,g,y,x;const{user:s}=Ls(),{data:t,isLoading:n,refetch:r}=N_s(),a=as(),i=t==null?void 0:t.id,{data:l=[]}=u4t(i),{data:o=[]}=h4t(i);if(N.useEffect(()=>{new URLSearchParams(window.location.search).get("subscribed")==="1"&&H.functions.invoke("coaching-verify-checkout").then(()=>{r(),a.invalidateQueries({queryKey:["my-coaching-assignment"]})})},[r,a]),n)return e.jsx(Qs,{title:"My Coach",children:e.jsx("div",{className:"p-8",children:"Loading…"})});if(!t)return e.jsx(Qs,{title:"My Coach",children:e.jsxs("div",{className:"max-w-2xl mx-auto p-8 text-center",children:[e.jsx(Oh,{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(_=>_.status!=="done"),u=o.length-d.length;return e.jsx(Qs,{title:"My Coach",children:e.jsxs("div",{className:"p-4 md:p-8 max-w-5xl mx-auto space-y-6",children:[e.jsx(_e,{className:"overflow-hidden",children:e.jsxs("div",{className:"relative bg-gradient-to-br from-[#2a4c64] to-[#406E71] text-white p-8",children:[e.jsx("div",{className:"absolute -right-20 -top-20 h-64 w-64 rounded-full bg-white/10 blur-3xl"}),e.jsxs("div",{className:"relative flex flex-col md:flex-row items-start md:items-center gap-6",children:[e.jsxs(Ua,{className:"h-24 w-24 ring-4 ring-white/20",children:[e.jsx(Gi,{src:((h=c.coachProfile)==null?void 0:h.avatar_url)||void 0}),e.jsx(qa,{className:"text-2xl bg-white/20 text-white",children:(((m=c.coachProfile)==null?void 0:m.name)||"C").charAt(0)})]}),e.jsxs("div",{className:"flex-1",children:[e.jsxs("div",{className:"flex items-center gap-2 text-white/80 mb-1",children:[e.jsx(Cn,{className:"h-4 w-4"}),e.jsx("span",{className:"text-sm uppercase tracking-wider",children:"Your Coach"})]}),e.jsx("h1",{className:"text-3xl font-bold",children:((f=c.coachProfile)==null?void 0:f.name)||"Your Coach"}),((g=c.coach)==null?void 0:g.headline)&&e.jsx("p",{className:"text-white/80 mt-1",children:c.coach.headline}),e.jsxs("div",{className:"flex gap-2 mt-3",children:[((y=c.coach)==null?void 0:y.is_certified)&&e.jsx(We,{className:"bg-yellow-400/20 text-yellow-100 border-yellow-300/30",children:"LevelUp Certified"}),e.jsx(We,{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(lMe,{icon:zm,label:"Open action items",value:d.length}),e.jsx(lMe,{icon:iu,label:"Completed",value:u}),e.jsx(lMe,{icon:ta,label:"Sessions",value:l.length})]}),((x=c.coach)==null?void 0:x.id)&&e.jsx($_s,{coachId:c.coach.id,assignmentId:i}),e.jsxs(ya,{defaultValue:"actions",children:[e.jsxs(va,{className:"flex flex-wrap h-auto w-full justify-start",children:[e.jsxs(ls,{value:"actions",children:[e.jsx(zm,{className:"h-4 w-4 mr-1 md:mr-2"}),e.jsx("span",{className:"hidden sm:inline",children:"Actions"})]}),e.jsxs(ls,{value:"sessions",children:[e.jsx(ta,{className:"h-4 w-4 mr-1 md:mr-2"}),e.jsx("span",{className:"hidden sm:inline",children:"Recaps"})]}),e.jsxs(ls,{value:"goals",children:[e.jsx(iu,{className:"h-4 w-4 mr-1 md:mr-2"}),e.jsx("span",{className:"hidden sm:inline",children:"Goals"})]}),e.jsxs(ls,{value:"kpis",children:[e.jsx(ml,{className:"h-4 w-4 mr-1 md:mr-2"}),e.jsx("span",{className:"hidden sm:inline",children:"KPIs"})]}),e.jsxs(ls,{value:"messages",children:[e.jsx(xo,{className:"h-4 w-4 mr-1 md:mr-2"}),e.jsx("span",{className:"hidden sm:inline",children:"Messages"})]}),e.jsxs(ls,{value:"files",children:[e.jsx(H0,{className:"h-4 w-4 mr-1 md:mr-2"}),e.jsx("span",{className:"hidden sm:inline",children:"Files"})]})]}),e.jsx(_s,{value:"actions",className:"space-y-2",children:o.length===0?e.jsx(_e,{children:e.jsx(De,{className:"p-6 text-center text-muted-foreground",children:"Your coach hasn't assigned any action items yet."})}):o.map(_=>e.jsx(_e,{children:e.jsxs(De,{className:"p-3 flex items-center gap-3",children:[e.jsx(Bi,{checked:_.status==="done",onCheckedChange:async b=>{await H.from("coaching_action_items").update({status:b?"done":"open",completed_at:b?new Date().toISOString():null}).eq("id",_.id),a.invalidateQueries({queryKey:["coaching-action-items",i]})}}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("div",{className:_.status==="done"?"line-through text-muted-foreground":"font-medium",children:_.title}),_.description&&e.jsx("div",{className:"text-xs text-muted-foreground",children:_.description})]}),_.due_date&&e.jsx(We,{variant:"outline",children:Js(new Date(_.due_date),"MMM d")}),e.jsx(We,{variant:"secondary",className:"capitalize",children:_.priority})]})},_.id))}),e.jsx(_s,{value:"sessions",className:"space-y-3",children:l.length===0?e.jsx(_e,{children:e.jsx(De,{className:"p-6 text-center text-muted-foreground",children:"No sessions logged yet."})}):l.map(_=>e.jsx(_e,{children:e.jsxs(De,{className:"p-4",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[e.jsx("span",{className:"font-medium",children:Js(new Date(_.scheduled_at),"PPp")}),e.jsx(We,{variant:"outline",className:"capitalize",children:_.status})]}),_.summary?e.jsx("p",{className:"text-sm whitespace-pre-wrap",children:_.summary}):e.jsx("p",{className:"text-sm text-muted-foreground italic",children:"Recap coming soon."})]})},_.id))}),e.jsx(_s,{value:"goals",children:e.jsx(b4t,{assignmentId:i,canEdit:!1})}),e.jsx(_s,{value:"kpis",children:s&&e.jsx(v4t,{agentUserId:s.id})}),e.jsx(_s,{value:"messages",children:e.jsx(m4t,{assignmentId:i})}),e.jsx(_s,{value:"files",children:e.jsx(_4t,{assignmentId:i})})]})]})})}function lMe({icon:s,label:t,value:n}){return e.jsx(_e,{children:e.jsxs(De,{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})]})]})})}function q_s(){const s=as(),[t,n]=N.useState(""),[r,a]=N.useState([]),[i,l]=N.useState(null),{data:o=[],isLoading:c}=mt({queryKey:["admin-coaches"],queryFn:async()=>{const{data:h,error:m}=await H.from("coaches").select("*").order("created_at",{ascending:!1});if(m)throw m;if(!(h!=null&&h.length))return[];const f=h.map(x=>x.user_id),{data:g}=await H.from("profiles").select("id, name, email, avatar_url").in("id",f),y=new Map((g||[]).map(x=>[x.id,x]));return h.map(x=>({...x,profile:y.get(x.user_id)}))}});N.useEffect(()=>{const h=t.trim();if(h.length<2){a([]);return}const m=setTimeout(async()=>{const{data:f}=await H.from("profiles").select("id, email, name, avatar_url").or(`email.ilike.%${h}%,name.ilike.%${h}%`).limit(10);a(f||[])},250);return()=>clearTimeout(m)},[t]);const d=async h=>{const{error:m}=await H.functions.invoke("manage-user-roles",{body:{userId:h.id,role:"coach",action:"add"}});if(m)return ie.error(m.message);const{error:f}=await H.from("coaches").insert({user_id:h.id});if(f&&!String(f.message).includes("duplicate"))return ie.error(f.message);ie.success(`${h.name||h.email} is now a coach`),n(""),a([]),s.invalidateQueries({queryKey:["admin-coaches"]})},u=async(h,m)=>{const{error:f}=await H.from("coaches").update({is_certified:m}).eq("id",h);if(f)return ie.error(f.message);ie.success(m?"Marked Certified":"Removed certification"),s.invalidateQueries({queryKey:["admin-coaches"]})};return e.jsxs(Qs,{title:"Coaching Admin",children:[e.jsxs("div",{className:"p-4 md:p-8 max-w-6xl mx-auto space-y-6",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(Oh,{className:"h-7 w-7 text-primary"}),e.jsx("h1",{className:"text-2xl font-bold",children:"LevelUp Coaching"})]}),e.jsx(V_s,{}),e.jsx(G_s,{}),e.jsx(_e,{children:e.jsxs(De,{className:"p-4 space-y-3",children:[e.jsx(we,{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(nn,{className:"h-4 w-4 mr-1"})," Make Coach"]})]},h.id))})]})}),e.jsxs("div",{children:[e.jsx("h2",{className:"text-lg font-semibold mb-3",children:"Coaches"}),c?e.jsx("div",{children:"Loading…"}):o.length===0?e.jsx(_e,{children:e.jsx(De,{className:"p-6 text-center text-muted-foreground",children:"No coaches yet. Search for a user above to promote them."})}):e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-3",children:o.map(h=>{var m,f,g;return e.jsx(_e,{children:e.jsxs(De,{className:"p-4 space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("div",{className:"font-medium",children:((m=h.profile)==null?void 0:m.name)||((f=h.profile)==null?void 0:f.email)||h.user_id}),e.jsx("div",{className:"text-xs text-muted-foreground",children:(g=h.profile)==null?void 0:g.email}),e.jsxs("div",{className:"flex gap-2 mt-2 flex-wrap",children:[h.is_certified&&e.jsxs(We,{className:"bg-yellow-500/15 text-yellow-700 border-yellow-300/40",children:[e.jsx(Cn,{className:"h-3 w-3 mr-1"}),"Certified"]}),h.accepting_clients&&e.jsx(We,{variant:"outline",children:"Accepting clients"})]})]}),e.jsxs(B,{size:"sm",variant:"outline",onClick:()=>l(h.id),children:[e.jsx(Yl,{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(zn,{checked:h.is_certified,onCheckedChange:y=>u(h.id,y)})]})]})},h.id)})})]})]}),e.jsx(H_s,{coachId:i,onClose:()=>l(null)})]})}function V_s(){const[s,t]=N.useState("1500"),[n,r]=N.useState(!1),[a,i]=N.useState(!1);N.useEffect(()=>{(async()=>{const{data:c}=await H.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 ie.error("Enter a value between 0 and 5000 bps (0–50%)");r(!0);const{error:d}=await H.from("settings").upsert({key:"coaching_platform_fee_bps",value:String(c)});if(r(!1),d)return ie.error(d.message);ie.success("Platform fee updated")};if(!a)return null;const o=(parseInt(s,10)/100).toFixed(2);return e.jsx(_e,{children:e.jsxs(De,{className:"p-4 space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(IT,{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(re,{children:"Fee (bps)"}),e.jsx(we,{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 H_s({coachId:s,onClose:t}){const[n,r]=N.useState(""),[a,i]=N.useState([]),[l,o]=N.useState(!1),c=as();N.useEffect(()=>{if(!s){r(""),i([]);return}},[s]),N.useEffect(()=>{const u=n.trim();if(u.length<2){i([]);return}o(!0);const h=setTimeout(async()=>{const{data:m}=await H.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 H.from("coaching_assignments").insert({coach_id:s,agent_id:u,status:"active",source:"admin",pipeline_stage:"onboarding"});if(h)return ie.error(h.message);ie.success("Agent assigned"),c.invalidateQueries({queryKey:["coach-roster"]}),t()};return e.jsx(Bs,{open:!!s,onOpenChange:u=>!u&&t(),children:e.jsxs(Fs,{children:[e.jsx(qs,{children:e.jsx($s,{children:"Assign Agent"})}),e.jsx(we,{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(Cr,{children:e.jsx(B,{variant:"outline",onClick:t,children:"Close"})})]})})}function G_s(){const s=as(),[t,n]=N.useState("pending"),[r,a]=N.useState(null),{data:i=[],isLoading:l}=mt({queryKey:["coach-applications",t],queryFn:async()=>{let u=H.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}=mt({queryKey:["coach-applications-pending-count"],queryFn:async()=>{const{count:u}=await H.from("coach_applications").select("id",{count:"exact",head:!0}).eq("status","pending");return u||0}}),c=async(u,h)=>{const{error:m}=await H.from("coach_applications").update({status:h,reviewed_at:new Date().toISOString()}).eq("id",u);if(m)return ie.error(m.message);ie.success(`Marked ${h}`),s.invalidateQueries({queryKey:["coach-applications"]}),s.invalidateQueries({queryKey:["coach-applications-pending-count"]}),a(null)},d=u=>u==="approved"?e.jsxs(We,{className:"bg-emerald-500/15 text-emerald-700 border-emerald-300/40",children:[e.jsx(pa,{className:"h-3 w-3 mr-1"}),"Approved"]}):u==="rejected"?e.jsxs(We,{className:"bg-rose-500/15 text-rose-700 border-rose-300/40",children:[e.jsx(hr,{className:"h-3 w-3 mr-1"}),"Rejected"]}):e.jsxs(We,{className:"bg-yellow-500/15 text-yellow-700 border-yellow-300/40",children:[e.jsx(Xr,{className:"h-3 w-3 mr-1"}),"Pending"]});return e.jsxs(_e,{children:[e.jsxs(De,{className:"p-4 space-y-4",children:[e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsx(n3,{className:"h-5 w-5 text-primary"}),e.jsx("h2",{className:"text-lg font-semibold",children:"Coach Applications"}),o>0&&e.jsxs(We,{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(mn,{className:"h-3 w-3"}),u.email]}),u.brokerage&&e.jsxs("span",{children:["· ",u.brokerage]}),u.years_experience&&e.jsxs("span",{children:["· ",u.years_experience," yrs"]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[d(u.status),e.jsx("span",{className:"text-xs text-muted-foreground",children:new Date(u.created_at).toLocaleDateString()})]})]})},u.id))})]}),e.jsx(Bs,{open:!!r,onOpenChange:u=>!u&&a(null),children:e.jsx(Fs,{className:"max-w-2xl max-h-[85vh] overflow-y-auto",children:r&&e.jsxs(e.Fragment,{children:[e.jsx(qs,{children:e.jsxs($s,{className:"flex items-center gap-3",children:[r.full_name,d(r.status)]})}),e.jsxs("div",{className:"space-y-4 text-sm",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsx(hF,{icon:mn,label:"Email",value:r.email,link:`mailto:${r.email}`}),r.phone&&e.jsx(hF,{icon:ga,label:"Phone",value:r.phone,link:`tel:${r.phone}`}),r.brokerage&&e.jsx(hF,{label:"Brokerage",value:r.brokerage}),r.years_experience&&e.jsx(hF,{label:"Years",value:r.years_experience}),r.website_url&&e.jsx(hF,{icon:Tr,label:"Website",value:r.website_url,link:r.website_url}),r.linkedin_url&&e.jsx(hF,{icon:Tr,label:"LinkedIn",value:r.linkedin_url,link:r.linkedin_url})]}),r.specialties&&e.jsx(cMe,{label:"Specialties",children:r.specialties}),e.jsx(cMe,{label:"Why they want to coach",children:r.why_coach}),r.results_story&&e.jsx(cMe,{label:"Results story",children:r.results_story}),e.jsxs("div",{children:[e.jsx(re,{className:"text-xs font-semibold uppercase text-muted-foreground",children:"Admin notes"}),e.jsx(Ws,{defaultValue:r.admin_notes||"",rows:3,onBlur:async u=>{const h=u.target.value;h!==(r.admin_notes||"")&&(await H.from("coach_applications").update({admin_notes:h}).eq("id",r.id),s.invalidateQueries({queryKey:["coach-applications"]}))},placeholder:"Internal notes (saved on blur)…"})]})]}),e.jsxs(Cr,{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(hr,{className:"h-4 w-4 mr-1"})," Reject"]}),r.status!=="pending"&&e.jsxs(B,{variant:"outline",onClick:()=>c(r.id,"pending"),children:[e.jsx(Xr,{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(pa,{className:"h-4 w-4 mr-1"})," Approve"]})]})]})})})]})}function hF({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 cMe({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 W_s(){const s=tr(),{data:t}=UQ(),n=as(),[r,a]=N.useState(!1),[i,l]=N.useState(!1),[o,c]=N.useState(null),{data:d,refetch:u}=mt({queryKey:["coach-stripe-status",t==null?void 0:t.id],enabled:!!t,queryFn:async()=>{const{data:x}=await H.functions.invoke("coach-stripe-status");return x}}),{data:h=[]}=mt({queryKey:["coach-packages",t==null?void 0:t.id],enabled:!!t,queryFn:async()=>{const{data:x}=await H.from("coaching_packages").select("*").eq("coach_id",t.id).order("sort_order");return x||[]}});N.useEffect(()=>{const x=new URLSearchParams(window.location.search);(x.get("onboarded")||x.get("refresh"))&&u()},[u]);const m=async()=>{var k,A;a(!0);const{data:x,error:_}=await H.functions.invoke("coach-stripe-connect");a(!1);let b=x==null?void 0:x.error;if(!b&&_)try{const T=await((A=(k=_==null?void 0:_.context)==null?void 0:k.json)==null?void 0:A.call(k));b=(T==null?void 0:T.error)||_.message}catch{b=_.message}if(b)return ie.error(b,{duration:1e4});x!=null&&x.url&&(window.location.href=x.url)},f=d||{},g=!!(t!=null&&t.use_platform_stripe),y=g||f.connected&&f.charges_enabled;return e.jsx(Qs,{title:"Coaching · Billing",children:e.jsxs("div",{className:"max-w-3xl mx-auto p-4 md:p-8 space-y-6",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(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(_e,{children:e.jsxs(De,{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(U0,{className:"h-5 w-5"})," Stripe Connect"]}),e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:g?"Your coaching sales are billed through the main LevelUp Stripe account.":"Payouts go directly to your bank. LevelUp takes a small platform fee from each charge."})]}),y?e.jsxs(We,{className:"bg-emerald-500/15 text-emerald-700 border-emerald-300/40 flex items-center gap-1",children:[e.jsx(Hr,{className:"h-3 w-3"})," ",g?"Using LevelUp billing":"Connected"]}):f.connected?e.jsxs(We,{variant:"secondary",className:"flex items-center gap-1",children:[e.jsx(Uo,{className:"h-3 w-3"})," Setup incomplete"]}):e.jsx(We,{variant:"outline",children:"Not connected"})]}),!g&&e.jsxs(B,{onClick:m,disabled:r,className:"bg-[#406E71] hover:bg-[#2a4c64]",children:[y?"Update Stripe details":f.connected?"Finish Stripe setup":"Connect Stripe",e.jsx(Tr,{className:"h-4 w-4 ml-1"})]})]})}),e.jsx(_e,{children:e.jsxs(De,{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(nn,{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(x=>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:[x.name,x.is_active&&x.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:["$",(x.price_cents/100).toFixed(0)," / ",x.billing_interval,!x.is_active&&" · Inactive"]})]}),e.jsx(B,{variant:"ghost",size:"icon",onClick:()=>{c(x),l(!0)},children:e.jsx(Ja,{className:"h-4 w-4"})}),e.jsx(B,{variant:"ghost",size:"icon",onClick:async()=>{confirm("Delete this package?")&&(await H.from("coaching_packages").delete().eq("id",x.id),n.invalidateQueries({queryKey:["coach-packages",t==null?void 0:t.id]}))},children:e.jsx(qn,{className:"h-4 w-4"})})]},x.id))})]})}),e.jsx(K_s,{open:i,onOpenChange:l,coachId:t==null?void 0:t.id,pkg:o,onSaved:()=>n.invalidateQueries({queryKey:["coach-packages",t==null?void 0:t.id]})})]})})}function K_s({open:s,onOpenChange:t,coachId:n,pkg:r,onSaved:a}){const[i,l]=N.useState(""),[o,c]=N.useState(""),[d,u]=N.useState(""),[h,m]=N.useState("month"),[f,g]=N.useState(!0),[y,x]=N.useState(!0),[_,b]=N.useState(!1);N.useEffect(()=>{s&&(l((r==null?void 0:r.name)||""),c((r==null?void 0:r.description)||""),u(r?(r.price_cents/100).toString():""),m((r==null?void 0:r.billing_interval)||"month"),g((r==null?void 0:r.is_active)??!0),x((r==null?void 0:r.accepting_clients)??!0))},[s,r]);const k=async()=>{if(!i.trim()||!d)return ie.error("Name and price required");b(!0);const A={coach_id:n,name:i,description:o||null,price_cents:Math.round(Number(d)*100),billing_interval:h,is_active:f,accepting_clients:y},{error:T}=r!=null&&r.id?await H.from("coaching_packages").update(A).eq("id",r.id):await H.from("coaching_packages").insert(A);if(b(!1),T)return ie.error(T.message);ie.success("Saved"),a==null||a(),t(!1)};return e.jsx(Bs,{open:s,onOpenChange:t,children:e.jsxs(Fs,{children:[e.jsx(qs,{children:e.jsx($s,{children:r!=null&&r.id?"Edit Package":"New Package"})}),e.jsxs("div",{className:"space-y-3",children:[e.jsx(we,{placeholder:"Name (e.g. Accelerator)",value:i,onChange:A=>l(A.target.value)}),e.jsx(Ws,{rows:3,placeholder:"What's included",value:o,onChange:A=>c(A.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(we,{type:"number",value:d,onChange:A=>u(A.target.value)})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-xs text-muted-foreground",children:"Interval"}),e.jsxs(Ns,{value:h,onValueChange:m,children:[e.jsx(ws,{children:e.jsx(ks,{})}),e.jsxs(js,{children:[e.jsx(nt,{value:"month",children:"Monthly"}),e.jsx(nt,{value:"year",children:"Yearly"}),e.jsx(nt,{value:"one_time",children:"One-time"})]})]})]})]}),e.jsxs("div",{className:"space-y-2 pt-1",children:[e.jsxs("label",{className:"flex items-center gap-2 text-sm",children:[e.jsx("input",{type:"checkbox",checked:f,onChange:A=>g(A.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:A=>x(A.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(Cr,{children:[e.jsx(B,{variant:"outline",onClick:()=>t(!1),children:"Cancel"}),e.jsx(B,{onClick:k,disabled:_,children:r!=null&&r.id?"Save":"Create"})]})]})})}function xrt({kind:s,value:t,onChange:n}){const r=N.useRef(null),[a,i]=N.useState(!1),[l,o]=N.useState(!1),[c,d]=N.useState(null),u=N.useRef(null),h=N.useRef(null),m=N.useRef(null),f=N.useRef([]),[g,y]=N.useState(!1),x=s==="photo"?"image/*":"video/*",_=s==="photo"?10*1024*1024:200*1024*1024,b=async(M,L)=>{var X;const{data:z}=await H.auth.getUser(),$=(X=z.user)==null?void 0:X.id;if(!$)return ie.error("Not signed in");if(M.size>_)return ie.error(`File too large. Max ${s==="photo"?"10MB":"200MB"}.`);i(!0);const V=`${$}/${s}-${Date.now()}.${L}`,{error:W}=await H.storage.from("coach-media").upload(V,M,{upsert:!0,contentType:M.type||(s==="photo"?"image/jpeg":"video/webm")});if(W)return i(!1),ie.error(W.message);const{data:G}=await H.storage.from("coach-media").createSignedUrl(V,60*60*24*365*10);i(!1),G!=null&&G.signedUrl&&(n(G.signedUrl),ie.success("Uploaded"),d(null))},k=async M=>{const L=M.name.split(".").pop()||(s==="photo"?"jpg":"webm");await b(M,L)},A=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 L=new MediaRecorder(M,{mimeType:"video/webm"});f.current=[],L.ondataavailable=z=>z.data.size>0&&f.current.push(z.data),L.onstop=()=>{const z=new Blob(f.current,{type:"video/webm"});d(z),M.getTracks().forEach($=>$.stop())},m.current=L,L.start(),o(!0)}catch(M){ie.error(M.message||"Could not access camera")}},T=()=>{var M;(M=m.current)==null||M.stop(),o(!1)},P=()=>{var M;(M=h.current)==null||M.getTracks().forEach(L=>L.stop()),y(!1),o(!1),d(null)},I=async()=>{c&&(await b(c,"webm"),P())};return N.useEffect(()=>()=>{var M;return(M=h.current)==null?void 0:M.getTracks().forEach(L=>L.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:x,className:"hidden",onChange:M=>{var z;const L=(z=M.target.files)==null?void 0:z[0];L&&k(L),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(us,{className:"h-4 w-4 mr-1 animate-spin"}):e.jsx(ni,{className:"h-4 w-4 mr-1"}),s==="photo"?"Upload photo":"Upload video"]}),s==="video"&&e.jsxs(B,{type:"button",variant:"outline",size:"sm",onClick:A,disabled:a||g,children:[e.jsx($0,{className:"h-4 w-4 mr-1"})," Record intro"]}),t&&e.jsxs(B,{type:"button",variant:"ghost",size:"sm",onClick:()=>n(""),children:[e.jsx(qn,{className:"h-4 w-4 mr-1"})," Remove"]})]}),g&&e.jsxs("div",{className:"rounded-lg border p-3 space-y-3 bg-background",children:[c?e.jsx("video",{src:URL.createObjectURL(c),controls:!0,className:"w-full max-h-64 rounded bg-black"}):e.jsx("video",{ref:u,muted:!0,playsInline:!0,className:"w-full max-h-64 rounded bg-black"}),e.jsxs("div",{className:"flex gap-2",children:[!c&&l&&e.jsxs(B,{type:"button",size:"sm",onClick:T,className:"bg-red-600 hover:bg-red-700",children:[e.jsx(L_,{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(na,{className:"h-4 w-4 mr-1"})," Start"]}),c&&e.jsxs(e.Fragment,{children:[e.jsxs(B,{type:"button",size:"sm",onClick:I,disabled:a,className:"bg-[#406E71] hover:bg-[#2a4c64]",children:[a?e.jsx(us,{className:"h-4 w-4 mr-1 animate-spin"}):e.jsx(ni,{className:"h-4 w-4 mr-1"}),"Use this recording"]}),e.jsx(B,{type:"button",size:"sm",variant:"outline",onClick:()=>{d(null),A()},children:"Re-record"})]}),e.jsx(B,{type:"button",size:"sm",variant:"ghost",onClick:P,children:"Cancel"})]})]})]})}function Y_s(){const s=tr(),{data:t,isLoading:n}=UQ(),r=as(),[a,i]=N.useState(""),[l,o]=N.useState(""),[c,d]=N.useState(""),[u,h]=N.useState(""),[m,f]=N.useState(""),[g,y]=N.useState(!1),[x,_]=N.useState([]),[b,k]=N.useState(""),[A,T]=N.useState(!1);N.useEffect(()=>{if(!t)return;const z=t;i(z.slug||""),o(z.headline||""),d(z.bio||""),h(z.photo_url||""),f(z.intro_video_url||""),y(!!z.accepting_clients),_(z.specialties||[])},[t]);const P=async()=>{if(!t)return;T(!0);const{error:z}=await H.from("coaches").update({slug:a.trim()||null,headline:l||null,bio:c||null,photo_url:u||null,intro_video_url:m||null,accepting_clients:g,specialties:x}).eq("id",t.id);if(T(!1),z)return ie.error(z.message);ie.success("Profile saved"),r.invalidateQueries({queryKey:["my-coach-profile"]})},I=()=>{const z=b.trim();if(z){if(x.includes(z))return k("");_([...x,z]),k("")}};if(n)return e.jsx(Qs,{title:"Coach Settings",children:e.jsx("div",{className:"p-8",children:"Loading…"})});if(!t)return e.jsx(Qs,{title:"Coach Settings",children:e.jsx("div",{className:"max-w-2xl mx-auto p-8 text-center text-muted-foreground",children:"You don't have a coach profile yet."})});const M=t,L=M.slug?`${window.location.origin}/coaches/${M.slug}`:null;return e.jsx(Qs,{title:"Coach Settings",children:e.jsxs("div",{className:"max-w-3xl mx-auto p-4 md:p-8 space-y-6",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(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:[L&&e.jsxs(B,{variant:"outline",size:"sm",onClick:()=>window.open(L,"_blank"),children:[e.jsx(Tr,{className:"h-4 w-4 mr-1"})," View public"]}),e.jsxs(B,{onClick:P,disabled:A,className:"bg-[#406E71] hover:bg-[#2a4c64]",children:[e.jsx(Kl,{className:"h-4 w-4 mr-1"})," ",A?"Saving…":"Save"]})]})]}),M.is_certified&&e.jsxs("div",{className:"rounded-lg border border-yellow-300/50 bg-yellow-50 dark:bg-yellow-950/20 px-4 py-3 text-sm",children:["✨ ",e.jsx("strong",{children:"LevelUp Certified"})," — Your profile displays a verified badge."]}),e.jsx(_e,{children:e.jsxs(De,{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(zn,{checked:g,onCheckedChange:y})]}),e.jsxs("div",{children:[e.jsx(re,{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(we,{value:a,onChange:z=>i(z.target.value.toLowerCase().replace(/[^a-z0-9-]/g,"")),placeholder:"your-name"})]})]}),e.jsxs("div",{children:[e.jsx(re,{children:"Headline"}),e.jsx(we,{value:l,onChange:z=>o(z.target.value),placeholder:"e.g. Helping new agents close their first 10 deals",maxLength:140})]}),e.jsxs("div",{children:[e.jsx(re,{children:"Bio"}),e.jsx(Ws,{rows:6,value:c,onChange:z=>d(z.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(re,{children:"Profile photo"}),e.jsx(xrt,{kind:"photo",value:u,onChange:h})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{children:"Intro video"}),e.jsx(xrt,{kind:"video",value:m,onChange:f})]})]}),e.jsxs("div",{children:[e.jsx(re,{children:"Specialties"}),e.jsx("div",{className:"flex flex-wrap gap-2 mb-2",children:x.map(z=>e.jsxs(We,{variant:"secondary",className:"gap-1",children:[z,e.jsx("button",{onClick:()=>_(x.filter($=>$!==z)),children:e.jsx(hr,{className:"h-3 w-3"})})]},z))}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(we,{value:b,onChange:z=>k(z.target.value),placeholder:"Add a specialty…",onKeyDown:z=>{z.key==="Enter"&&(z.preventDefault(),I())}}),e.jsx(B,{type:"button",variant:"outline",onClick:I,children:e.jsx(nn,{className:"h-4 w-4"})})]})]})]})}),e.jsx(_e,{children:e.jsx(De,{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(Z_s,{coachId:M.id})]})})}function Z_s({coachId:s}){const[t,n]=N.useState("");as();const{data:r=[],refetch:a}=mt({queryKey:["coach-invites",s],queryFn:async()=>{const{data:c}=await H.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 ie.error("Email required");const{error:d}=await H.from("coaching_invites").insert({coach_id:s,email:c});if(d)return ie.error(d.message);n(""),ie.success("Invite created"),a()},l=c=>{const d=`${window.location.origin}/auth?coach_invite=${c}`;navigator.clipboard.writeText(d),ie.success("Link copied")},o=async c=>{confirm("Revoke this invite?")&&(await H.from("coaching_invites").delete().eq("id",c),a())};return e.jsx(_e,{children:e.jsxs(De,{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(gc,{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(we,{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(nn,{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(Pa,{className:"h-4 w-4"})}),e.jsx(B,{variant:"ghost",size:"icon",onClick:()=>o(c.id),children:e.jsx(qn,{className:"h-4 w-4"})})]},c.id)),r.length===0&&e.jsx("div",{className:"text-sm text-muted-foreground text-center py-4",children:"No invites yet."})]})]})})}const Qte=[{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 X_s(){const s=tr(),t=as(),{data:n,isLoading:r}=UQ(),[a,i]=N.useState("pending"),[l,o]=N.useState(""),[c,d]=N.useState(null),[u,h]=N.useState(!1),[m,f]=N.useState(""),[g,y]=N.useState(!1),[x,_]=N.useState(""),{data:b=[],isLoading:k}=mt({queryKey:["coaching-waitlist",n==null?void 0:n.id],enabled:!!(n!=null&&n.id),queryFn:async()=>{const{data:z,error:$}=await H.from("coaching_waitlist").select("*").eq("coach_id",n.id).order("created_at",{ascending:!1});if($)throw $;return z||[]}}),A=N.useMemo(()=>b.filter(z=>{if(a!=="all"&&z.status!==a)return!1;if(l){const $=l.toLowerCase();return(z.name||"").toLowerCase().includes($)||(z.email||"").toLowerCase().includes($)||(z.brokerage||"").toLowerCase().includes($)}return!0}),[b,a,l]),T=N.useMemo(()=>{const z={all:b.length};for(const $ of Qte)z[$.value]=0;for(const $ of b)z[$.status]=(z[$.status]||0)+1;return z},[b]),P=async(z,$)=>{const{error:V}=await H.from("coaching_waitlist").update($).eq("id",z);if(V)return ie.error(V.message);t.invalidateQueries({queryKey:["coaching-waitlist",n==null?void 0:n.id]}),(c==null?void 0:c.id)===z&&d(W=>({...W,...$}))},I=async z=>{if(!confirm("Remove this person from the waitlist?"))return;const{error:$}=await H.from("coaching_waitlist").delete().eq("id",z);if($)return ie.error($.message);ie.success("Removed"),t.invalidateQueries({queryKey:["coaching-waitlist",n==null?void 0:n.id]}),d(null)},M=async()=>{if(!c)return;const{data:z,error:$}=await H.functions.invoke("coaching-waitlist-invite",{body:{waitlistId:c.id,message:m}});if($||z!=null&&z.error)return ie.error((z==null?void 0:z.error)||($==null?void 0:$.message)||"Could not send invite");ie.success(`Invite sent to ${c.name}`),h(!1),f(""),t.invalidateQueries({queryKey:["coaching-waitlist",n==null?void 0:n.id]})},L=async()=>{if(!n)return;const{data:z,error:$}=await H.functions.invoke("coaching-waitlist-invite",{body:{coachId:n.id,notifyAll:!0,message:x}});if($||z!=null&&z.error)return ie.error((z==null?void 0:z.error)||($==null?void 0:$.message)||"Could not notify");ie.success(`Notified ${(z==null?void 0:z.count)||0} agents`),y(!1),_(""),t.invalidateQueries({queryKey:["coaching-waitlist",n==null?void 0:n.id]})};return r?e.jsx(Qs,{title:"Waitlist",children:e.jsx("div",{className:"p-8",children:"Loading…"})}):n?e.jsxs(Qs,{title:"Coaching Waitlist",children:[e.jsxs("div",{className:"p-4 md:p-8 max-w-7xl mx-auto space-y-6",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3 flex-wrap",children:[e.jsxs("div",{children:[e.jsxs(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(lj,{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:!T.pending,title:T.pending?"":"No pending applicants",children:[e.jsx(g9,{className:"h-4 w-4 mr-2"}),"Notify all pending (",T.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 (",T.all,")"]}),Qte.map(z=>e.jsxs("button",{onClick:()=>i(z.value),className:`px-3 py-1.5 rounded-full text-sm border ${a===z.value?"bg-[#406E71] text-white border-[#406E71]":"bg-white hover:bg-muted"}`,children:[z.label," (",T[z.value]||0,")"]},z.value))]}),e.jsx(we,{placeholder:"Search by name, email, brokerage…",value:l,onChange:z=>o(z.target.value),className:"max-w-md"}),k?e.jsx("div",{className:"text-muted-foreground",children:"Loading…"}):A.length===0?e.jsx(_e,{children:e.jsx(De,{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:A.map(z=>{const $=Qte.find(V=>V.value===z.status);return e.jsx(_e,{className:"cursor-pointer hover:shadow-md transition-shadow",onClick:()=>d(z),children:e.jsxs(De,{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:z.name}),e.jsx("div",{className:"text-xs text-muted-foreground truncate",children:z.email}),z.brokerage&&e.jsx("div",{className:"text-xs text-muted-foreground truncate",children:z.brokerage})]}),e.jsx(We,{className:($==null?void 0:$.tone)||"",children:($==null?void 0:$.label)||z.status})]}),e.jsxs("div",{className:"flex items-center justify-between mt-3 text-xs text-muted-foreground",children:[e.jsxs("span",{children:["Joined ",nc(new Date(z.created_at),{addSuffix:!0})]}),z.preferred_package&&e.jsxs("span",{className:"truncate ml-2",children:["→ ",z.preferred_package]})]})]})},z.id)})})]}),e.jsx(Bs,{open:!!c,onOpenChange:z=>!z&&d(null),children:e.jsx(Fs,{className:"max-w-lg max-h-[90vh] overflow-y-auto",children:c&&e.jsxs(e.Fragment,{children:[e.jsxs(qs,{children:[e.jsx($s,{children:c.name}),e.jsxs(Ar,{children:["Joined ",nc(new Date(c.created_at),{addSuffix:!0})]})]}),e.jsxs("div",{className:"space-y-3 text-sm",children:[e.jsx(IV,{label:"Email",value:c.email}),e.jsx(IV,{label:"Phone",value:c.phone}),e.jsx(IV,{label:"Brokerage",value:c.brokerage}),e.jsx(IV,{label:"Years",value:c.years_in_business}),e.jsx(IV,{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 ",nc(new Date(c.invited_at),{addSuffix:!0})]}),e.jsxs("div",{children:[e.jsx("div",{className:"text-xs font-medium text-muted-foreground mb-1",children:"Status"}),e.jsxs(Ns,{value:c.status,onValueChange:z=>P(c.id,{status:z}),children:[e.jsx(ws,{children:e.jsx(ks,{})}),e.jsx(js,{children:Qte.map(z=>e.jsx(nt,{value:z.value,children:z.label},z.value))})]})]}),e.jsxs("div",{children:[e.jsx("div",{className:"text-xs font-medium text-muted-foreground mb-1",children:"Private notes"}),e.jsx(Ws,{rows:3,defaultValue:c.coach_notes||"",onBlur:z=>{z.target.value!==(c.coach_notes||"")&&P(c.id,{coach_notes:z.target.value})}})]})]}),e.jsxs(Cr,{className:"flex-wrap gap-2",children:[e.jsxs(B,{variant:"outline",className:"text-destructive",onClick:()=>I(c.id),children:[e.jsx(qn,{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(mn,{className:"h-4 w-4 mr-1"})," Email directly"]})}),e.jsxs(B,{className:"bg-[#406E71] hover:bg-[#2a4c64]",onClick:()=>{f(""),h(!0)},children:[e.jsx(Rr,{className:"h-4 w-4 mr-1"})," Invite to subscribe"]})]})]})})}),e.jsx(Bs,{open:u,onOpenChange:h,children:e.jsxs(Fs,{children:[e.jsxs(qs,{children:[e.jsx($s,{children:"Invite to subscribe"}),e.jsxs(Ar,{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(Ws,{rows:4,placeholder:"Hey! A spot just opened up and I'd love to work with you…",value:m,onChange:z=>f(z.target.value)})]}),e.jsxs(Cr,{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(Rr,{className:"h-4 w-4 mr-1"})," Send invite"]})]})]})}),e.jsx(Bs,{open:g,onOpenChange:y,children:e.jsxs(Fs,{children:[e.jsxs(qs,{children:[e.jsx($s,{children:"Notify all pending applicants"}),e.jsx(Ar,{children:"Send everyone with status “Pending” an email letting them know spots are opening up. They'll each be marked “Invited”."})]}),e.jsx(Ws,{rows:4,placeholder:"Good news — I just opened up new coaching spots…",value:x,onChange:z=>_(z.target.value)}),e.jsxs(Cr,{children:[e.jsx(B,{variant:"outline",onClick:()=>y(!1),children:"Cancel"}),e.jsxs(B,{className:"bg-[#406E71] hover:bg-[#2a4c64]",onClick:L,children:[e.jsx(g9,{className:"h-4 w-4 mr-1"})," Send to ",T.pending||0," agents"]})]})]})})]}):e.jsx(Qs,{title:"Waitlist",children:e.jsx("div",{className:"p-8 text-center text-muted-foreground",children:"You need a coach profile to view this page."})})}function IV({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 Q_s(){const{data:s=[],isLoading:t}=mt({queryKey:["coaches-directory"],queryFn:async()=>{const{data:n,error:r}=await H.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 H.from("profiles").select("id, name, avatar_url").in("id",a),l=new Map((i||[]).map(o=>[o.id,o]));return(n||[]).map(o=>({...o,profile:l.get(o.user_id)}))}});return e.jsxs("div",{className:"min-h-screen bg-white",children:[e.jsxs("section",{className:"relative overflow-hidden bg-gradient-to-br from-[#1c3447] via-[#2a4c64] to-[#406E71] text-white",children:[e.jsx("div",{className:"absolute -top-32 -left-24 h-96 w-96 rounded-full bg-[#5a9ea2]/20 blur-3xl"}),e.jsx("div",{className:"absolute -bottom-32 -right-24 h-96 w-96 rounded-full bg-yellow-400/10 blur-3xl"}),e.jsx("div",{className:"absolute inset-0 opacity-[0.04]",style:{backgroundImage:"radial-gradient(white 1px, transparent 1px)",backgroundSize:"22px 22px"}}),e.jsxs("div",{className:"relative max-w-6xl mx-auto px-4 py-20 md:py-28 text-center",children:[e.jsxs("div",{className:"inline-flex items-center gap-2 px-3 py-1.5 rounded-full bg-white/10 backdrop-blur-sm border border-white/15 text-xs uppercase tracking-[0.18em] font-semibold mb-6",children:[e.jsx(Cn,{className:"h-3.5 w-3.5 text-yellow-300"}),"LevelUp Certified Coaches"]}),e.jsxs("h1",{className:"text-5xl md:text-7xl font-bold tracking-tight leading-[1.05]",children:["Coaching that ",e.jsx("span",{className:"bg-gradient-to-r from-yellow-300 to-yellow-100 bg-clip-text text-transparent",children:"moves the needle."})]}),e.jsx("p",{className:"text-white/75 mt-6 max-w-2xl mx-auto text-lg leading-relaxed",children:"Hand-picked real-estate coaches ready to help you hit your next breakthrough — from lead gen to listings to luxury."}),e.jsxs("div",{className:"flex flex-wrap justify-center gap-6 mt-10 text-sm text-white/70",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Hr,{className:"h-4 w-4 text-yellow-300"})," Vetted by LevelUp"]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(gl,{className:"h-4 w-4 text-yellow-300"})," Top-producer experience"]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Wa,{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(cr,{to:`/coaches/${n.slug||n.id}`,className:"group",children:e.jsx("article",{className:"relative h-full rounded-2xl bg-[#1c3447] overflow-hidden transition-all duration-300 hover:-translate-y-1 hover:shadow-[0_24px_60px_-20px_rgba(42,76,100,0.5)]",children:e.jsxs("div",{className:"relative aspect-[3/4] w-full overflow-hidden",children:[a?e.jsx("img",{src:a,alt:r,className:"absolute inset-0 h-full w-full object-cover object-top group-hover:scale-105 transition-transform duration-700"}):e.jsx("div",{className:"absolute inset-0 flex items-center justify-center bg-gradient-to-br from-[#2a4c64] to-[#406E71] text-white text-6xl font-bold",children:r.charAt(0)}),e.jsx("div",{className:"absolute inset-0 bg-gradient-to-t from-[#0d1f2d] via-[#0d1f2d]/70 to-transparent"}),e.jsxs("div",{className:"absolute top-3 left-3 right-3 flex items-start justify-between gap-2",children:[n.is_certified?e.jsxs("div",{className:"inline-flex items-center gap-1 px-2.5 py-1 rounded-full bg-gradient-to-r from-yellow-400 to-yellow-300 text-[#2a4c64] text-[11px] font-semibold shadow-md",children:[e.jsx(Cn,{className:"h-3 w-3"})," Certified"]}):e.jsx("span",{}),e.jsxs("div",{className:`inline-flex items-center gap-1 px-2.5 py-1 rounded-full text-[11px] font-medium backdrop-blur-md ${n.accepting_clients?"bg-emerald-500/90 text-white":"bg-white/85 text-[#2a4c64]"}`,children:[e.jsx("span",{className:`h-1.5 w-1.5 rounded-full ${n.accepting_clients?"bg-white":"bg-amber-500"}`}),n.accepting_clients?"Accepting":"Waitlist"]})]}),e.jsxs("div",{className:"absolute inset-x-0 bottom-0 p-5 text-white",children:[e.jsx("h3",{className:"text-xl font-bold leading-tight drop-shadow-sm",children:r}),n.headline&&e.jsx("p",{className:"text-sm text-yellow-200/90 font-medium mt-1 line-clamp-1",children:n.headline}),n.bio&&e.jsx("p",{className:"text-[13px] text-white/80 mt-2 line-clamp-2 leading-relaxed",children:n.bio}),n.specialties&&n.specialties.length>0&&e.jsx("div",{className:"flex flex-wrap gap-1.5 mt-3",children:n.specialties.slice(0,2).map(o=>e.jsx("span",{className:"text-[10px] px-2 py-0.5 rounded-full bg-white/15 backdrop-blur-sm text-white border border-white/20",children:o},o))}),e.jsxs("div",{className:"flex items-center justify-between mt-4 pt-3 border-t border-white/15",children:[e.jsx("span",{className:"text-sm font-semibold text-white",children:"View profile"}),e.jsx("span",{className:"inline-flex items-center justify-center h-8 w-8 rounded-full bg-white/15 backdrop-blur-sm text-white group-hover:bg-yellow-300 group-hover:text-[#1c3447] transition-colors",children:e.jsx(vi,{className:"h-4 w-4"})})]})]})]})})},n.id)})}),e.jsxs("div",{className:"mt-20 rounded-3xl bg-gradient-to-br from-[#1c3447] via-[#2a4c64] to-[#406E71] text-white p-10 md:p-14 relative overflow-hidden",children:[e.jsx("div",{className:"absolute inset-0 opacity-[0.06]",style:{backgroundImage:"radial-gradient(white 1px, transparent 1px)",backgroundSize:"18px 18px"}}),e.jsx("div",{className:"absolute -top-24 -right-24 h-72 w-72 rounded-full bg-yellow-300/15 blur-3xl"}),e.jsxs("div",{className:"relative md:flex items-center gap-10",children:[e.jsxs("div",{className:"flex-1",children:[e.jsxs("div",{className:"inline-flex items-center gap-2 px-3 py-1.5 rounded-full bg-white/10 border border-white/15 text-[11px] uppercase tracking-[0.18em] font-semibold mb-5",children:[e.jsx(Cn,{className:"h-3.5 w-3.5 text-yellow-300"})," Coach Applications Open"]}),e.jsxs("h2",{className:"text-3xl md:text-4xl font-bold leading-tight",children:["Are you the kind of agent ",e.jsx("span",{className:"text-yellow-300",children:"other agents need?"})]}),e.jsx("p",{className:"text-white/80 mt-4 max-w-xl leading-relaxed",children:"LevelUp Coaches are the top 1% — top producers, proven mentors, and category leaders making a measurable difference in agents' businesses. If that's you, we want to meet you."}),e.jsxs("div",{className:"mt-6 flex flex-wrap gap-3 text-sm text-white/70",children:[e.jsxs("span",{className:"inline-flex items-center gap-1.5",children:[e.jsx(Hr,{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(Hr,{className:"h-4 w-4 text-yellow-300"})," Recurring revenue"]}),e.jsxs("span",{className:"inline-flex items-center gap-1.5",children:[e.jsx(Hr,{className:"h-4 w-4 text-yellow-300"})," Certified status"]})]})]}),e.jsxs("div",{className:"mt-8 md:mt-0",children:[e.jsxs(cr,{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(vi,{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 J_s=H5({name:pl().trim().min(1,"Name required").max(120),email:pl().trim().email("Invalid email").max(255),phone:pl().trim().max(40).optional().or(qx("")),brokerage:pl().trim().max(160).optional().or(qx("")),years_in_business:pl().max(40).optional().or(qx("")),biggest_challenge:pl().trim().max(1e3).optional().or(qx("")),preferred_package:pl().max(120).optional().or(qx("")),message:pl().trim().max(1500).optional().or(qx(""))});function ews({open:s,onOpenChange:t,coachId:n,coachName:r,packages:a=[]}){const{user:i}=Ls(),[l,o]=N.useState(!1),[c,d]=N.useState({name:"",email:(i==null?void 0:i.email)||"",phone:"",brokerage:"",years_in_business:"",biggest_challenge:"",preferred_package:"",message:""}),u=(m,f)=>d(g=>({...g,[m]:f})),h=async()=>{var g;const m=J_s.safeParse(c);if(!m.success){ie.error(((g=m.error.issues[0])==null?void 0:g.message)||"Please check your entries");return}o(!0);const{error:f}=await H.from("coaching_waitlist").insert({coach_id:n,agent_user_id:(i==null?void 0:i.id)||null,name:c.name.trim(),email:c.email.trim().toLowerCase(),phone:c.phone||null,brokerage:c.brokerage||null,years_in_business:c.years_in_business||null,biggest_challenge:c.biggest_challenge||null,preferred_package:c.preferred_package||null,message:c.message||null,status:"pending"});if(o(!1),f){ie.error(f.message||"Could not join waitlist");return}ie.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(Bs,{open:s,onOpenChange:t,children:e.jsxs(Fs,{className:"max-w-lg max-h-[90vh] overflow-y-auto",children:[e.jsxs(qs,{children:[e.jsxs($s,{children:["Join the waitlist",r?` — ${r}`:""]}),e.jsx(Ar,{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(re,{children:"Name *"}),e.jsx(we,{value:c.name,onChange:m=>u("name",m.target.value)})]}),e.jsxs("div",{children:[e.jsx(re,{children:"Email *"}),e.jsx(we,{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(re,{children:"Phone"}),e.jsx(we,{value:c.phone,onChange:m=>u("phone",m.target.value)})]}),e.jsxs("div",{children:[e.jsx(re,{children:"Brokerage"}),e.jsx(we,{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(re,{children:"Years in business"}),e.jsxs(Ns,{value:c.years_in_business,onValueChange:m=>u("years_in_business",m),children:[e.jsx(ws,{children:e.jsx(ks,{placeholder:"Select…"})}),e.jsxs(js,{children:[e.jsx(nt,{value:"< 1 year",children:"Less than 1 year"}),e.jsx(nt,{value:"1-3 years",children:"1-3 years"}),e.jsx(nt,{value:"4-7 years",children:"4-7 years"}),e.jsx(nt,{value:"8-15 years",children:"8-15 years"}),e.jsx(nt,{value:"15+ years",children:"15+ years"})]})]})]}),a.length>0&&e.jsxs("div",{children:[e.jsx(re,{children:"Preferred package"}),e.jsxs(Ns,{value:c.preferred_package,onValueChange:m=>u("preferred_package",m),children:[e.jsx(ws,{children:e.jsx(ks,{placeholder:"Any"})}),e.jsx(js,{children:a.map(m=>e.jsx(nt,{value:m.name,children:m.name},m.id))})]})]})]}),e.jsxs("div",{children:[e.jsx(re,{children:"Biggest challenge right now"}),e.jsx(Ws,{rows:2,value:c.biggest_challenge,onChange:m=>u("biggest_challenge",m.target.value)})]}),e.jsxs("div",{children:[e.jsx(re,{children:"Anything else?"}),e.jsx(Ws,{rows:2,value:c.message,onChange:m=>u("message",m.target.value)})]})]}),e.jsxs(Cr,{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 tws(){var y;const{slug:s}=uo(),t=tr(),{user:n}=Ls(),[r,a]=N.useState(null),[i,l]=N.useState(!1),{data:o,isLoading:c}=mt({queryKey:["coach-public",s],enabled:!!s,queryFn:async()=>{const x=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(s||""),_=H.from("coaches").select("*"),{data:b}=x?await _.eq("id",s).maybeSingle():await _.eq("slug",s).maybeSingle();if(!b)return null;const[{data:k},{data:A}]=await Promise.all([H.from("profiles").select("id, name, avatar_url").eq("id",b.user_id).maybeSingle(),H.from("coaching_packages").select("*").eq("coach_id",b.id).eq("is_active",!0).order("sort_order")]);return{coach:b,profile:k,packages:A||[]}}}),d=async x=>{if(!n){ie.error("Please sign in to subscribe"),t(`/auth?redirect=/coaches/${s}`);return}a(x);const{data:_,error:b}=await H.functions.invoke("create-coaching-checkout",{body:{packageId:x}});if(a(null),b||_!=null&&_.error){ie.error((_==null?void 0:_.error)||(b==null?void 0:b.message)||"Checkout failed");return}_!=null&&_.url&&(window.location.href=_.url)};if(c)return e.jsx("div",{className:"p-12 text-center",children:"Loading…"});if(!(o!=null&&o.coach))return e.jsx("div",{className:"p-12 text-center",children:"Coach not found."});const{coach:u,profile:h,packages:m}=o,f=u,g=(x,_)=>{const b=(x/100).toLocaleString("en-US",{style:"currency",currency:"USD",maximumFractionDigits:0});return _==="one_time"?b:`${b} / ${_}`};return e.jsxs("div",{className:"min-h-screen bg-background",children:[e.jsx("div",{className:"bg-gradient-to-br from-[#2a4c64] to-[#406E71] text-white",children:e.jsxs("div",{className:"max-w-5xl mx-auto px-4 py-12 md:py-20",children:[e.jsxs(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(Ua,{className:"h-28 w-28 ring-4 ring-white/20",children:[e.jsx(Gi,{src:f.photo_url||(h==null?void 0:h.avatar_url)}),e.jsx(qa,{className:"text-3xl bg-white/20",children:((h==null?void 0:h.name)||"C").charAt(0)})]}),e.jsxs("div",{className:"flex-1",children:[f.is_certified&&e.jsxs("div",{className:"inline-flex items-center gap-1 bg-yellow-400/20 border border-yellow-300/30 text-yellow-100 px-2 py-1 rounded-full text-xs mb-2",children:[e.jsx(Cn,{className:"h-3 w-3"})," LevelUp Certified"]}),e.jsx("h1",{className:"text-3xl md:text-4xl font-bold",children:(h==null?void 0:h.name)||"Coach"}),f.headline&&e.jsx("p",{className:"text-white/80 text-lg mt-2",children:f.headline}),((y=f.specialties)==null?void 0:y.length)>0&&e.jsx("div",{className:"flex flex-wrap gap-2 mt-4",children:f.specialties.map(x=>e.jsx(We,{className:"bg-white/15 text-white border-white/20",children:x},x))})]})]})]})}),e.jsxs("div",{className:"max-w-5xl mx-auto px-4 py-12 grid grid-cols-1 md:grid-cols-3 gap-8",children:[e.jsxs("div",{className:"md:col-span-2 space-y-6",children:[f.intro_video_url&&e.jsx("div",{className:"aspect-video rounded-xl overflow-hidden bg-black",children:e.jsx("video",{src:f.intro_video_url,controls:!0,className:"w-full h-full"})}),f.bio&&e.jsxs("div",{children:[e.jsx("h2",{className:"text-xl font-semibold mb-3",children:"About"}),e.jsx("p",{className:"text-muted-foreground whitespace-pre-wrap leading-relaxed",children:f.bio})]}),e.jsx(B_s,{coachId:f.id})]}),e.jsxs("div",{className:"space-y-4 md:sticky md:top-6 md:self-start",children:[e.jsx("h2",{className:"text-xl font-semibold",children:"Choose a plan"}),m.length===0?e.jsx(_e,{children:e.jsx(De,{className:"p-6 text-sm text-muted-foreground text-center",children:"No packages available yet."})}):m.map(x=>{const _=x.accepting_clients===!1;return e.jsx(_e,{className:`border-2 transition-colors ${_?"border-amber-200 bg-amber-50/30":"hover:border-[#406E71]"}`,children:e.jsxs(De,{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:x.name}),_&&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"})]}),x.description&&e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:x.description}),e.jsx("div",{className:"text-2xl font-bold mt-3",children:g(x.price_cents,x.billing_interval)}),_?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(lj,{className:"h-4 w-4 mr-1"})," Join Waitlist"]})]}):e.jsxs(B,{className:"w-full mt-4 bg-[#406E71] hover:bg-[#2a4c64]",onClick:()=>d(x.id),disabled:r===x.id,children:[r===x.id?"Loading…":"Get Started",e.jsx(pa,{className:"h-4 w-4 ml-1"})]})]})},x.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(lj,{className:"h-4 w-4 mr-1"})," Join the waitlist instead"]})]})]}),e.jsx(ews,{open:i,onOpenChange:l,coachId:f.id,coachName:h==null?void 0:h.name,packages:m.map(x=>({id:x.id,name:x.name}))})]})}const sws=H5({full_name:pl().trim().min(2,"Please enter your full name").max(100),email:pl().trim().email("Enter a valid email").max(255),phone:pl().trim().max(40).optional().or(qx("")),brokerage:pl().trim().max(150).optional().or(qx("")),years_experience:pl().trim().max(40).optional().or(qx("")),specialties:pl().trim().max(500).optional().or(qx("")),why_coach:pl().trim().min(20,"Tell us a bit more — at least 20 characters").max(2e3),results_story:pl().trim().max(2e3).optional().or(qx("")),website_url:pl().trim().max(300).optional().or(qx("")),linkedin_url:pl().trim().max(300).optional().or(qx(""))});function nws(){const s=tr(),[t,n]=N.useState(!1),[r,a]=N.useState(!1),[i,l]=N.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=sws.safeParse(i);if(!u.success){const f=(m=Object.values(u.error.flatten().fieldErrors)[0])==null?void 0:m[0];return ie.error(f||"Please check the form and try again")}n(!0);const{error:h}=await H.from("coach_applications").insert(u.data);if(n(!1),h)return ie.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(Hr,{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(cr,{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(Cn,{className:"h-3.5 w-3.5 text-yellow-300"}),"Coach Application — By Invitation & Application Only"]}),e.jsx("h1",{className:"text-4xl md:text-6xl font-bold tracking-tight leading-[1.05] max-w-3xl",children:"Join the most respected coaching program in real estate."}),e.jsx("p",{className:"text-white/80 mt-6 max-w-2xl text-lg leading-relaxed",children:"LevelUp Coaches don't just teach — they transform careers. We hand-pick top-producing agents and proven mentors who are ready to multiply their impact, build a recurring revenue stream, and help thousands of agents finally break through."}),e.jsxs("div",{className:"grid md:grid-cols-3 gap-4 mt-12",children:[e.jsxs("div",{className:"rounded-2xl bg-white/5 backdrop-blur-sm border border-white/10 p-5",children:[e.jsx(Yn,{className:"h-6 w-6 text-yellow-300 mb-3"}),e.jsx("h3",{className:"font-semibold text-lg",children:"Premium client base"}),e.jsx("p",{className:"text-sm text-white/70 mt-1",children:"Get matched with motivated, vetted agents who are serious about leveling up."})]}),e.jsxs("div",{className:"rounded-2xl bg-white/5 backdrop-blur-sm border border-white/10 p-5",children:[e.jsx(ml,{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(ku,{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(Hr,{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(gl,{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(Wa,{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(ek,{label:"Full name *",children:e.jsx(we,{value:i.full_name,onChange:d=>o("full_name",d.target.value),required:!0,maxLength:100})}),e.jsx(ek,{label:"Email *",children:e.jsx(we,{type:"email",value:i.email,onChange:d=>o("email",d.target.value),required:!0,maxLength:255})}),e.jsx(ek,{label:"Phone",children:e.jsx(we,{value:i.phone,onChange:d=>o("phone",d.target.value),maxLength:40})}),e.jsx(ek,{label:"Current brokerage",children:e.jsx(we,{value:i.brokerage,onChange:d=>o("brokerage",d.target.value),maxLength:150})}),e.jsx(ek,{label:"Years in real estate",children:e.jsx(we,{value:i.years_experience,onChange:d=>o("years_experience",d.target.value),placeholder:"e.g. 8",maxLength:40})}),e.jsx(ek,{label:"Coaching specialties",children:e.jsx(we,{value:i.specialties,onChange:d=>o("specialties",d.target.value),placeholder:"Lead gen, listings, luxury, teams…",maxLength:500})}),e.jsx(ek,{label:"Website",children:e.jsx(we,{value:i.website_url,onChange:d=>o("website_url",d.target.value),placeholder:"https://",maxLength:300})}),e.jsx(ek,{label:"LinkedIn",children:e.jsx(we,{value:i.linkedin_url,onChange:d=>o("linkedin_url",d.target.value),placeholder:"https://linkedin.com/in/",maxLength:300})})]}),e.jsx(ek,{label:"Why do you want to coach with LevelUp? *",children:e.jsx(Ws,{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(ek,{label:"Tell us about results you've created — for yourself or other agents.",children:e.jsx(Ws,{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 ek({label:s,children:t}){return e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(re,{className:"text-sm font-semibold text-[#1c3447]",children:s}),t]})}const rws="/assets/testimonial-avatar-1-BsCQFauB.jpg",aws="/assets/testimonial-avatar-2-B6VPVc2t.jpg",iws="/assets/testimonial-avatar-3-GuEFwYUE.jpg",ows="/assets/testimonial-avatar-4-98iKMtkB.jpg",lws="/assets/testimonial-avatar-5-ZsZfyxMX.jpg",cws=[rws,aws,iws,ows,lws],dws=H5({name:pl().trim().min(2,"Name must be at least 2 characters").max(100),email:pl().trim().email("Please enter a valid email address").max(255),phone:pl().trim().min(10,"Please enter a valid phone number").max(20).optional().or(qx("")),brokerage:pl().trim().max(200).optional().or(qx(""))}),uws=[{icon:wp,title:"Academy Training",description:"Access a library of on-demand video training covering lead generation, marketing, technology, and more."},{icon:zc,title:"300+ Templates",description:"Professional Canva templates for social media, flyers, postcards, and marketing materials."},{icon:ta,title:"Live Events",description:"Weekly live training sessions, workshops, and Q&A events with industry experts."},{icon:Ud,title:"Agent Community",description:"Connect with fellow agents, share wins, ask questions, and network in our private community."},{icon:Wr,title:"Resource Kits",description:"Downloadable toolkits with scripts, checklists, guides, and everything you need to close more deals."},{icon:Io,title:"Social Swag",description:"Fresh social media content and designs updated regularly to help you stand out online."}],hws=[{icon:Yn,title:"Contact Management",description:"Organize your sphere into relationship tiers—Top 25, Past Clients, Referral Partners, and more."},{icon:Cn,title:"Smart TouchPlans",description:"Automated action plans that tell you exactly who to contact and how, based on relationship type."},{icon:ga,title:"One-Tap Actions",description:"Call, text, or email contacts directly with pre-written scripts tailored to each relationship."},{icon:Fm,title:"Birthday Alerts",description:"Never miss an important date—get reminders for birthdays and home anniversaries."},{icon:ii,title:"Pop-by Map",description:"See all your contacts on a map and plan efficient pop-by routes in your area."},{icon:fl,title:"Momentum Tracking",description:"Track your touch streaks, weekly goals, and relationship health scores."},{icon:co,title:"Relationship Health",description:"Visual dashboard showing which contacts need attention based on last touch date."},{icon:ff,title:"Daily Action Cards",description:"Wake up to a prioritized list of exactly who to reach out to today."}],mws=[{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."}],pws=()=>{const s=tr(),[t,n]=N.useState(!1),[r,a]=N.useState({name:"",email:"",phone:"",brokerage:""}),[i,l]=N.useState({}),o=async c=>{var u,h;c.preventDefault(),l({});const d=dws.safeParse(r);if(!d.success){const m={};d.error.issues.forEach(f=>{f.path[0]&&(m[f.path[0]]=f.message)}),l(m);return}n(!0);try{const m=typeof window<"u"&&localStorage.getItem("levelup_referral_code")||void 0,{data:f,error:g}=await H.functions.invoke("create-trial-signup",{body:{name:r.name.trim(),email:r.email.trim().toLowerCase(),phone:((u=r.phone)==null?void 0:u.trim())||void 0,brokerage:((h=r.brokerage)==null?void 0:h.trim())||void 0,referral_code:m}});if(g){console.error("Trial signup error:",g),ie.error(g.message||"Something went wrong. Please try again.");return}if(f!=null&&f.error){ie.error(f.error);return}ie.success("🎉 Welcome aboard! Check your email to claim your account."),typeof window<"u"&&window.oaiq&&window.oaiq("measure","trial_started",{type:"plan_enrollment"}),typeof window<"u"&&window.fbq&&window.fbq("track","Lead",{content_name:"Trial Signup",value:0,currency:"USD"}),s("/trial/success")}catch(m){console.error("Trial signup error:",m),ie.error("Something went wrong. Please try again.")}finally{n(!1)}};return e.jsxs(e.Fragment,{children:[e.jsxs(ic,{children:[e.jsx("title",{children:"Start Your Free 7-Day Trial | LevelUp Dashboard"}),e.jsx("meta",{name:"description",content:"Take LevelUp for a free 7-day test drive. No credit card required. The all-in-one platform for real estate agents and brokerages."}),e.jsx("meta",{property:"og:title",content:"Start Your Free 7-Day Trial | LevelUp"}),e.jsx("meta",{property:"og:description",content:"Take LevelUp for a free 7-day test drive. No credit card required."}),e.jsx("meta",{property:"og:type",content:"website"}),e.jsx("script",{children:"!function(f,b,e,v,n,t,s){if(f.fbq)return;n=f.fbq=function(){n.callMethod?n.callMethod.apply(n,arguments):n.queue.push(arguments)};if(!f._fbq)f._fbq=n;n.push=n;n.loaded=!0;n.version='2.0';n.queue=[];t=b.createElement(e);t.async=!0;t.src=v;s=b.getElementsByTagName(e)[0];s.parentNode.insertBefore(t,s)}(window,document,'script','https://connect.facebook.net/en_US/fbevents.js'); fbq('init', '1388750291887997'); fbq('track', 'PageView');"})]}),e.jsx("noscript",{dangerouslySetInnerHTML:{__html:''}}),e.jsxs("div",{className:"min-h-screen bg-background overflow-hidden",children:[e.jsx("nav",{className:"fixed top-0 left-0 right-0 z-50 bg-[#4a6b6d] shadow-md",children:e.jsxs("div",{className:"container mx-auto px-4 py-3 flex items-center justify-between",children:[e.jsx("div",{className:"flex items-center",children:e.jsx("img",{src:oNe,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 c;return(c=document.getElementById("features"))==null?void 0:c.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 pt-24 pb-20 bg-gradient-to-br from-[#1e3a4c] via-[#2a4f5f] to-[#3d6b6b] overflow-hidden",children:[e.jsx("div",{className:"absolute inset-0 opacity-10",children:e.jsx("div",{className:"absolute inset-0 bg-[url('data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iNjAiIGhlaWdodD0iNjAiIHZpZXdCb3g9IjAgMCA2MCA2MCIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj48ZyBmaWxsPSJub25lIiBmaWxsLXJ1bGU9ImV2ZW5vZGQiPjxnIGZpbGw9IiNmZmZmZmYiIGZpbGwtb3BhY2l0eT0iMC40Ij48cGF0aCBkPSJNMzYgMzRoLTJ2LTRoMnY0em0wLTZ2LTRoLTJ2NGgyem0tNiA2aC0ydi00aDJ2NHptMC02di00aC0ydjRoMnoiLz48L2c+PC9nPjwvc3ZnPg==')]"})}),e.jsx("div",{className:"container mx-auto px-4 relative",children:e.jsxs("div",{className:"grid lg:grid-cols-2 gap-12 items-center",children:[e.jsxs("div",{className:"space-y-8 text-center lg:text-left",children:[e.jsx("div",{className:"flex justify-center lg:justify-start",children:e.jsx("img",{alt:"LevelUp Consulting Group",className:"h-24 md:h-32 drop-shadow-lg",src:"/lovable-uploads/3a0c7ef9-9e79-411f-a9af-6f2a99e8bd7b.webp"})}),e.jsxs("div",{className:"inline-flex items-center gap-2 px-4 py-2 rounded-full bg-white/10 text-white text-sm font-medium",children:[e.jsx(Cn,{className:"h-4 w-4 text-yellow-400"}),e.jsx("span",{children:"7-Day Free Trial • No Credit Card Required"})]}),e.jsxs("h1",{className:"text-3xl md:text-4xl lg:text-5xl font-bold text-white leading-tight font-sans",children:["Take LevelUp for a"," ",e.jsx("span",{className:"italic",children:"Free Test Drive"})]}),e.jsxs("p",{className:"text-lg md:text-xl text-white/80 max-w-xl mx-auto lg:mx-0 font-sans",children:["The tools you need to get it done.",e.jsx("br",{}),e.jsx("em",{children:"The platform you need to keep it going."})]}),e.jsxs("div",{className:"flex flex-col sm:flex-row gap-4 justify-center lg:justify-start",children:[e.jsxs("div",{className:"flex items-center gap-2 text-white/80",children:[e.jsx(Hr,{className:"h-5 w-5 text-green-400"}),e.jsx("span",{children:"No credit card required"})]}),e.jsxs("div",{className:"flex items-center gap-2 text-white/80",children:[e.jsx(Hr,{className:"h-5 w-5 text-green-400"}),e.jsx("span",{children:"Full access to all features"})]})]}),e.jsxs("div",{className:"flex items-center gap-4 justify-center lg:justify-start pt-4",children:[e.jsx("div",{className:"flex -space-x-3",children:cws.map((c,d)=>e.jsx("img",{src:c,alt:`Agent ${d+1}`,className:"w-10 h-10 rounded-full border-2 border-white/20 object-cover"},d))}),e.jsxs("div",{children:[e.jsx("div",{className:"flex gap-0.5",children:[1,2,3,4,5].map(c=>e.jsx(Wa,{className:"h-4 w-4 fill-yellow-400 text-yellow-400"},c))}),e.jsx("p",{className:"text-sm text-white/60",children:"Trusted by 3,000+ agents"})]})]})]}),e.jsx("div",{className:"lg:pl-8",children:e.jsx(_e,{className:"bg-white shadow-2xl border-0",children:e.jsxs(De,{className:"p-8",children:[e.jsxs("div",{className:"text-center mb-8",children:[e.jsx("div",{className:"inline-flex items-center justify-center w-16 h-16 rounded-full bg-[#4a6b6d] mb-4",children:e.jsx(By,{className:"h-8 w-8 text-white"})}),e.jsx("h2",{className:"text-2xl font-bold text-foreground font-sans",children:"Start Your Free Trial"}),e.jsx("p",{className:"text-muted-foreground mt-2",children:"Get instant access • No credit card needed"})]}),e.jsxs("form",{onSubmit:o,className:"space-y-5",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{htmlFor:"name",children:"Full Name *"}),e.jsx(we,{id:"name",type:"text",placeholder:"John Smith",value:r.name,onChange:c=>a({...r,name:c.target.value}),required:!0}),i.name&&e.jsx("p",{className:"text-sm text-destructive",children:i.name})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{htmlFor:"email",children:"Email Address *"}),e.jsx(we,{id:"email",type:"email",placeholder:"john@example.com",value:r.email,onChange:c=>a({...r,email:c.target.value}),required:!0}),i.email&&e.jsx("p",{className:"text-sm text-destructive",children:i.email})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{htmlFor:"phone",children:"Phone Number"}),e.jsx(we,{id:"phone",type:"tel",placeholder:"(555) 123-4567",value:r.phone,onChange:c=>a({...r,phone:c.target.value})}),i.phone&&e.jsx("p",{className:"text-sm text-destructive",children:i.phone})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{htmlFor:"brokerage",children:"Brokerage Name"}),e.jsx(we,{id:"brokerage",type:"text",placeholder:"Your brokerage or team name",value:r.brokerage,onChange:c=>a({...r,brokerage:c.target.value})}),i.brokerage&&e.jsx("p",{className:"text-sm text-destructive",children:i.brokerage})]}),e.jsx(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(us,{className:"mr-2 h-5 w-5 animate-spin"}),"Creating Your Account..."]}):e.jsxs(e.Fragment,{children:["Start My Free Trial",e.jsx(vi,{className:"ml-2 h-5 w-5"})]})}),e.jsxs("p",{className:"text-center text-sm text-muted-foreground",children:["By signing up, you agree to our"," ",e.jsx("a",{href:"/terms-of-service",className:"text-[#4a6b6d] hover:underline",children:"Terms"})," ","and"," ",e.jsx("a",{href:"/privacy-policy",className:"text-[#4a6b6d] hover:underline",children:"Privacy Policy"})]})]})]})})})]})})]}),e.jsx("section",{className:"py-20 bg-background",children:e.jsx("div",{className:"container mx-auto px-4",children:e.jsxs("div",{className:"max-w-4xl mx-auto text-center space-y-8",children:[e.jsx("h2",{className:"text-3xl md:text-5xl leading-tight font-sans font-semibold text-secondary",children:"We help brokerages and agents grow with training, tools, and built-in execution."}),e.jsxs("div",{className:"space-y-2 text-lg text-muted-foreground",children:[e.jsx("p",{children:"Agents get weekly coaching + plug-and-play marketing."}),e.jsx("p",{children:"Brokerages get higher adoption, consistency, and real engagement."})]}),e.jsx("p",{className:"text-2xl md:text-4xl text-[#4a6b6d] pt-4 font-sans font-bold",children:"LEVELUP EQUIPS BOTH TO THRIVE."})]})})}),e.jsx("section",{id:"features",className:"py-20 bg-muted/30",children:e.jsxs("div",{className:"container mx-auto px-4",children:[e.jsxs("div",{className:"text-center max-w-3xl mx-auto mb-16",children:[e.jsx("h2",{className:"text-3xl md:text-4xl mb-6 font-sans font-bold",children:"What's inside our members only portal?"}),e.jsx("p",{className:"text-lg text-muted-foreground",children:"Everything you need to grow your business, all in one place."})]}),e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-8 max-w-6xl mx-auto",children:uws.map((c,d)=>e.jsxs(_e,{className:"group relative overflow-hidden border hover:border-[#4a6b6d]/50 transition-all duration-300 hover:shadow-lg bg-background",children:[e.jsxs(zt,{children:[e.jsx("div",{className:"w-14 h-14 rounded-2xl bg-[#4a6b6d]/10 flex items-center justify-center mb-4",children:e.jsx(c.icon,{className:"w-7 h-7 text-[#4a6b6d]"})}),e.jsx(qt,{className:"text-xl font-sans",children:c.title})]}),e.jsx(De,{children:e.jsx("p",{className:"text-muted-foreground leading-relaxed",children:c.description})})]},d))})]})}),e.jsxs("section",{className:"py-20 bg-gradient-to-br from-[#4a6b6d] to-[#3d5a5c] relative overflow-hidden",children:[e.jsx("div",{className:"absolute inset-0 opacity-10",children:e.jsx("div",{className:"absolute inset-0 bg-[url('data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iNjAiIGhlaWdodD0iNjAiIHZpZXdCb3g9IjAgMCA2MCA2MCIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj48ZyBmaWxsPSJub25lIiBmaWxsLXJ1bGU9ImV2ZW5vZGQiPjxnIGZpbGw9IiNmZmZmZmYiIGZpbGwtb3BhY2l0eT0iMC40Ij48cGF0aCBkPSJNMzYgMzRoLTJ2LTRoMnY0em0wLTZ2LTRoLTJ2NGgyem0tNiA2aC0ydi00aDJ2NHptMC02di00aC0ydjRoMnoiLz48L2c+PC9nPjwvc3ZnPg==')]"})}),e.jsxs("div",{className:"container mx-auto px-4 relative",children:[e.jsxs("div",{className:"text-center max-w-3xl mx-auto mb-16",children:[e.jsxs("div",{className:"inline-flex items-center gap-2 px-4 py-2 rounded-full bg-white/10 text-white text-sm font-medium mb-6",children:[e.jsx(Cn,{className:"w-4 h-4"}),"Included with Your Trial"]}),e.jsxs("h2",{className:"text-3xl mb-6 text-white font-sans font-bold md:text-6xl",children:["Meet ",e.jsx("span",{className:"italic",children:"Agent OS"})]}),e.jsx("p",{className:"text-lg text-white/80",children:"Your relationship-first operating system. Never forget a follow-up, track every touchpoint, and turn your sphere into a referral machine."})]}),e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6 max-w-6xl mx-auto",children:hws.map((c,d)=>e.jsxs(_e,{className:"group relative overflow-hidden border-0 bg-white/10 backdrop-blur-sm hover:bg-white/20 transition-all duration-300",children:[e.jsxs(zt,{className:"pb-3",children:[e.jsx("div",{className:"w-12 h-12 rounded-xl bg-white/20 flex items-center justify-center mb-3",children:e.jsx(c.icon,{className:"w-6 h-6 text-white"})}),e.jsx(qt,{className:"text-lg font-semibold text-white",children:c.title})]}),e.jsx(De,{children:e.jsx("p",{className:"text-white/70 text-sm leading-relaxed",children:c.description})})]},d))})]})]}),e.jsx("section",{className:"py-20 bg-background",children:e.jsxs("div",{className:"container mx-auto px-4",children:[e.jsxs("div",{className:"text-center mb-16",children:[e.jsx("h2",{className:"text-3xl md:text-4xl font-bold mb-4 font-sans",children:"Loved by Top Producers"}),e.jsx("p",{className:"text-lg text-muted-foreground",children:"See what agents are saying about LevelUp"})]}),e.jsx("div",{className:"grid md:grid-cols-3 gap-8 max-w-5xl mx-auto",children:mws.map((c,d)=>e.jsx(_e,{className:"border hover:shadow-lg transition-shadow",children:e.jsxs(De,{className:"p-6",children:[e.jsx("div",{className:"flex gap-1 mb-4",children:[1,2,3,4,5].map(u=>e.jsx(Wa,{className:"h-4 w-4 fill-yellow-400 text-yellow-400"},u))}),e.jsxs("p",{className:"text-muted-foreground mb-4 italic",children:['"',c.quote,'"']}),e.jsxs("div",{children:[e.jsx("p",{className:"font-semibold",children:c.name}),e.jsx("p",{className:"text-sm text-muted-foreground",children:c.role})]})]})},d))})]})}),e.jsx("section",{className:"py-16 bg-muted/30",children:e.jsx("div",{className:"container mx-auto px-4",children:e.jsxs("div",{className:"flex flex-wrap justify-center gap-8 md:gap-16",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"w-12 h-12 rounded-full bg-[#4a6b6d]/10 flex items-center justify-center",children:e.jsx(mf,{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(ff,{className:"h-6 w-6 text-[#4a6b6d]"})}),e.jsxs("div",{children:[e.jsx("p",{className:"font-semibold",children:"Fast Setup"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Start in 2 minutes"})]})]}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"w-12 h-12 rounded-full bg-[#4a6b6d]/10 flex items-center justify-center",children:e.jsx(Yn,{className:"h-6 w-6 text-[#4a6b6d]"})}),e.jsxs("div",{children:[e.jsx("p",{className:"font-semibold",children:"Expert Support"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Real estate pros"})]})]})]})})}),e.jsx("section",{id:"free-trial",className:"py-20 bg-background",children:e.jsx("div",{className:"container mx-auto px-4",children:e.jsxs(_e,{className:"bg-gradient-to-br from-[#1e3a4c] via-[#2a4f5f] to-[#3d6b6b] border-0 shadow-2xl overflow-hidden relative",children:[e.jsx("div",{className:"absolute inset-0 opacity-10",children:e.jsx("div",{className:"absolute inset-0 bg-[url('data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iNjAiIGhlaWdodD0iNjAiIHZpZXdCb3g9IjAgMCA2MCA2MCIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj48ZyBmaWxsPSJub25lIiBmaWxsLXJ1bGU9ImV2ZW5vZGQiPjxnIGZpbGw9IiNmZmZmZmYiIGZpbGwtb3BhY2l0eT0iMC40Ij48cGF0aCBkPSJNMzYgMzRoLTJ2LTRoMnY0em0wLTZ2LTRoLTJ2NGgyem0tNiA2aC0ydi00aDJ2NHptMC02di00aC0ydjRoMnoiLz48L2c+PC9nPjwvc3ZnPg==')]"})}),e.jsxs(De,{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:()=>window.scrollTo({top:0,behavior:"smooth"}),size:"lg",className:"h-14 px-8 text-lg font-semibold bg-white text-[#1e3a4c] hover:bg-white/90 shadow-2xl transition-all hover:scale-105 rounded-full",children:["Start Your Free Trial Now",e.jsx(vi,{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:U2e,alt:"LevelUp",className:"h-8"}),e.jsxs("div",{className:"flex gap-6 text-sm text-white/60",children:[e.jsx("a",{href:"/privacy-policy",className:"hover:text-white transition-colors",children:"Privacy Policy"}),e.jsx("a",{href:"/terms-of-service",className:"hover:text-white transition-colors",children:"Terms of Service"})]}),e.jsx("p",{className:"text-sm text-white/40",children:"© 2025 LevelUp Consulting Group. All rights reserved."})]})})})]})]})},fws=()=>{const s=tr();return e.jsxs(e.Fragment,{children:[e.jsx(ic,{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:oNe,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(_e,{className:"max-w-lg w-full bg-white shadow-2xl border-0",children:e.jsxs(De,{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(Hr,{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(uf,{className:"h-5 w-5 text-white"})})]}),e.jsx("h1",{className:"text-3xl md:text-4xl font-bold text-foreground mb-4 font-sans",children:"You're In! 🎉"}),e.jsx("p",{className:"text-xl text-muted-foreground mb-8",children:"Your 7-day LevelUp adventure starts now!"}),e.jsxs("div",{className:"bg-[#4a6b6d]/10 rounded-xl p-6 mb-8",children:[e.jsxs("div",{className:"flex items-center justify-center gap-3 mb-4",children:[e.jsx("div",{className:"w-12 h-12 rounded-full bg-[#4a6b6d]/20 flex items-center justify-center",children:e.jsx(mn,{className:"h-6 w-6 text-[#4a6b6d]"})}),e.jsx("h2",{className:"text-lg font-semibold text-foreground",children:"Check Your Inbox"})]}),e.jsx("p",{className:"text-muted-foreground",children:"We just sent you a magic link to claim your account and set up your password. Click the link in your email to get started!"})]}),e.jsxs("div",{className:"text-left space-y-3 mb-8",children:[e.jsx("p",{className:"text-sm text-muted-foreground font-medium uppercase tracking-wide",children:"What happens next:"}),e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx("div",{className:"w-6 h-6 rounded-full bg-[#4a6b6d] flex items-center justify-center flex-shrink-0 mt-0.5",children:e.jsx("span",{className:"text-xs font-bold text-white",children:"1"})}),e.jsx("p",{className:"text-foreground",children:"Check your email for the welcome message"})]}),e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx("div",{className:"w-6 h-6 rounded-full bg-[#4a6b6d] flex items-center justify-center flex-shrink-0 mt-0.5",children:e.jsx("span",{className:"text-xs font-bold text-white",children:"2"})}),e.jsx("p",{className:"text-foreground",children:'Click "Claim Your Account" to set your password'})]}),e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx("div",{className:"w-6 h-6 rounded-full bg-[#4a6b6d] flex items-center justify-center flex-shrink-0 mt-0.5",children:e.jsx("span",{className:"text-xs font-bold text-white",children:"3"})}),e.jsx("p",{className:"text-foreground",children:"Start exploring all the features!"})]})]}),e.jsxs("p",{className:"text-sm text-muted-foreground mb-6",children:["Didn't receive the email? Check your spam folder or"," ",e.jsx("button",{onClick:()=>s("/trial"),className:"text-[#4a6b6d] hover:underline font-medium",children:"try again"})]}),e.jsxs(B,{onClick:()=>s("/auth"),className:"bg-[#4a6b6d] hover:bg-[#3d5a5c]",children:["Go to Sign In",e.jsx(vi,{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:U2e,alt:"LevelUp",className:"h-8"}),e.jsxs("p",{className:"text-sm text-white/40",children:["© ",new Date().getFullYear()," LevelUp Consulting Group. All rights reserved."]})]})})})]})]})},gws=H5({viewerName:pl().min(1,"Name is required").max(100,"Name must be less than 100 characters"),viewerEmail:pl().email("Please enter a valid email").max(255,"Email must be less than 255 characters"),viewerPhone:pl().max(20,"Phone must be less than 20 characters").optional(),message:pl().min(1,"Message is required").max(1e3,"Message must be less than 1000 characters")});function xws({shareToken:s,agentName:t,hasContact:n}){const[r,a]=N.useState(!1),[i,l]=N.useState(!1),[o,c]=N.useState(null),d=W4e({resolver:K4e(gws),defaultValues:{viewerName:"",viewerEmail:"",viewerPhone:"",message:""}}),u=async h=>{a(!0),c(null);try{const{data:m,error:f}=await H.functions.invoke("video-reply-notify",{body:{shareToken:s,viewerName:h.viewerName,viewerEmail:h.viewerEmail,viewerPhone:h.viewerPhone||void 0,message:h.message}});if(f)throw new Error(f.message);if(!(m!=null&&m.success))throw new Error((m==null?void 0:m.error)||"Failed to send reply");l(!0)}catch(m){console.error("Failed to submit reply:",m),c(m.message||"Something went wrong. Please try again.")}finally{a(!1)}};return i?e.jsx(_e,{className:"border-2 border-primary/20 bg-gradient-to-br from-primary/5 to-primary/10",children:e.jsxs(De,{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(Hr,{className:"h-8 w-8 text-primary"})}),e.jsx("h3",{className:"text-xl font-semibold mb-2",children:"Message Sent!"}),e.jsxs("p",{className:"text-muted-foreground",children:[t?`${t} will`:"They'll"," get back to you soon."]})]})}):e.jsxs(_e,{children:[e.jsxs(zt,{className:"pb-4",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[e.jsx(Ud,{className:"h-5 w-5 text-primary"}),e.jsx(qt,{className:"text-lg",children:"Reply to this video"})]}),e.jsx(_r,{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(De,{children:e.jsx(Y4e,{...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(gp,{control:d.control,name:"viewerName",render:({field:h})=>e.jsxs(Mm,{children:[e.jsx(Lm,{children:"Your Name *"}),e.jsx(Pm,{children:e.jsx(we,{placeholder:"John Smith",...h})}),e.jsx(Ov,{})]})}),e.jsx(gp,{control:d.control,name:"viewerEmail",render:({field:h})=>e.jsxs(Mm,{children:[e.jsx(Lm,{children:"Email *"}),e.jsx(Pm,{children:e.jsx(we,{type:"email",placeholder:"john@example.com",...h})}),e.jsx(Ov,{})]})})]}),!n&&e.jsx(gp,{control:d.control,name:"viewerPhone",render:({field:h})=>e.jsxs(Mm,{children:[e.jsx(Lm,{children:"Phone (optional)"}),e.jsx(Pm,{children:e.jsx(we,{type:"tel",placeholder:"(555) 123-4567",...h})}),e.jsx(Ov,{})]})}),e.jsx(gp,{control:d.control,name:"message",render:({field:h})=>e.jsxs(Mm,{children:[e.jsx(Lm,{children:"Message *"}),e.jsx(Pm,{children:e.jsx(Ws,{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(Ov,{})]})}),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(us,{className:"h-4 w-4 animate-spin"}),"Sending..."]}):e.jsxs(e.Fragment,{children:[e.jsx(Rr,{className:"h-4 w-4"}),"Send Message"]})})]})})})]})}const yws=()=>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(Wa,{className:"absolute top-[5%] left-[8%] w-6 h-6 text-blue-600/30 fill-blue-600/20"}),e.jsx(Wa,{className:"absolute top-[15%] left-[20%] w-4 h-4 text-blue-600/25 fill-blue-600/15"}),e.jsx(Wa,{className:"absolute top-[8%] left-[28%] w-5 h-5 text-blue-600/30 fill-blue-600/20"}),e.jsx(Wa,{className:"absolute top-[25%] left-[12%] w-4 h-4 text-blue-600/20 fill-blue-600/10"}),e.jsx(Wa,{className:"absolute top-[20%] right-[15%] w-5 h-5 text-red-500/25 fill-red-500/15 animate-pulse"}),e.jsx(s3,{className:"absolute bottom-[20%] right-[10%] w-12 h-12 text-blue-600/15 rotate-12"})]}),vws=()=>e.jsxs("div",{className:"absolute inset-0 overflow-hidden pointer-events-none",children:[e.jsx("div",{className:"absolute inset-0 bg-gradient-to-br from-red-500/5 via-transparent to-blue-500/5"}),e.jsxs("div",{className:"absolute top-[10%] left-[15%] w-32 h-32",children:[e.jsx("div",{className:"absolute inset-0 rounded-full border-2 border-red-400/20 animate-ping",style:{animationDuration:"3s"}}),e.jsx(Cn,{className:"absolute top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2 w-8 h-8 text-red-400/40"})]}),e.jsxs("div",{className:"absolute top-[5%] right-[20%] w-24 h-24",children:[e.jsx("div",{className:"absolute inset-0 rounded-full border-2 border-blue-400/20 animate-ping",style:{animationDuration:"4s",animationDelay:"1s"}}),e.jsx(Wa,{className:"absolute top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2 w-6 h-6 text-blue-400/40 fill-blue-400/20"})]}),e.jsxs("div",{className:"absolute top-[20%] left-[50%] w-20 h-20",children:[e.jsx("div",{className:"absolute inset-0 rounded-full border border-white/10 animate-ping",style:{animationDuration:"3.5s",animationDelay:"0.5s"}}),e.jsx(Cn,{className:"absolute top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2 w-5 h-5 text-amber-400/40"})]}),e.jsx(Wa,{className:"absolute bottom-[25%] left-[10%] w-6 h-6 text-blue-500/25 fill-blue-500/15 animate-pulse"}),e.jsx(Wa,{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(s3,{className:"absolute top-[8%] left-[5%] w-10 h-10 text-red-500/20 rotate-12"})]}),bws=()=>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(U2,{className:"w-20 h-20 text-pink-400 rotate-12"})}),e.jsx("div",{className:"absolute top-[2%] right-[8%] opacity-15",children:e.jsx(U2,{className:"w-16 h-16 text-rose-400 -rotate-12"})}),e.jsx("div",{className:"absolute bottom-[15%] left-[8%] opacity-15",children:e.jsx(U2,{className:"w-14 h-14 text-purple-400 rotate-45"})}),e.jsx("div",{className:"absolute bottom-[20%] right-[5%] opacity-20",children:e.jsx(U2,{className:"w-16 h-16 text-pink-300 -rotate-6"})}),e.jsx(co,{className:"absolute top-[15%] left-[30%] w-5 h-5 text-rose-300/40 fill-rose-300/20 animate-pulse"}),e.jsx(co,{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(co,{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"})]}),_ws=()=>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(ku,{className:"absolute top-[8%] left-[12%] w-12 h-12 text-blue-600/15"}),e.jsx(Wa,{className:"absolute top-[15%] left-[22%] w-5 h-5 text-amber-500/25 fill-amber-500/15"}),e.jsx(ku,{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(Wa,{className:"absolute bottom-[25%] left-[15%] w-6 h-6 text-blue-500/20 fill-blue-500/10 animate-pulse"}),e.jsx(Wa,{className:"absolute top-[20%] right-[22%] w-5 h-5 text-indigo-400/20 fill-indigo-400/10 animate-pulse",style:{animationDelay:"0.5s"}})]}),wws=()=>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(U2,{className:"absolute top-[20%] left-[32%] w-7 h-7 text-purple-400/30"}),e.jsx(U2,{className:"absolute top-[12%] right-[28%] w-6 h-6 text-pink-400/30"}),e.jsx(d9,{className:"absolute top-[18%] left-[52%] w-5 h-5 text-sky-400/35"})]}),jws=()=>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(hD,{className:"absolute top-[5%] left-[10%] w-16 h-16 text-orange-400/25"}),e.jsx(hD,{className:"absolute top-[10%] right-[12%] w-12 h-12 text-purple-400/20 animate-pulse"}),e.jsxs("div",{className:"absolute bottom-[18%] left-[8%]",children:[e.jsx("div",{className:"w-14 h-12 rounded-full bg-orange-500/20"}),e.jsx("div",{className:"absolute -top-2 left-1/2 -translate-x-1/2 w-2 h-4 bg-green-600/25 rounded-t-full"})]}),e.jsxs("div",{className:"absolute bottom-[22%] right-[12%]",children:[e.jsx("div",{className:"w-12 h-10 rounded-full bg-orange-400/15"}),e.jsx("div",{className:"absolute -top-1.5 left-1/2 -translate-x-1/2 w-1.5 h-3 bg-green-600/20 rounded-t-full"})]}),e.jsx("div",{className:"absolute top-[15%] left-[40%] opacity-20",children:e.jsx("svg",{viewBox:"0 0 24 12",className:"w-10 h-5 text-slate-800 fill-current",children:e.jsx("path",{d:"M12 6c-2-4-6-6-12-6 4 2 6 4 6 6s-2 4-6 6c6 0 10-2 12-6zm0 0c2-4 6-6 12-6-4 2-6 4-6 6s2 4 6 6c-6 0-10-2-12-6z"})})}),e.jsx(Cn,{className:"absolute top-[8%] left-[55%] w-6 h-6 text-purple-400/35 animate-pulse"}),e.jsx(Cn,{className:"absolute bottom-[28%] right-[25%] w-5 h-5 text-orange-400/30 animate-pulse",style:{animationDelay:"0.5s"}})]}),Nws=()=>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(zT,{className:"absolute bottom-[8%] left-[5%] w-20 h-20 text-green-600/18"}),e.jsx(zT,{className:"absolute bottom-[12%] right-[8%] w-16 h-16 text-emerald-600/15"}),e.jsx(zT,{className:"absolute bottom-[10%] left-[28%] w-12 h-12 text-green-500/12"}),e.jsx(nj,{className:"absolute top-[5%] left-[15%] w-10 h-10 text-sky-300/30 animate-pulse"}),e.jsx(nj,{className:"absolute top-[10%] right-[20%] w-8 h-8 text-blue-300/25 animate-pulse",style:{animationDelay:"0.3s"}}),e.jsx(nj,{className:"absolute top-[18%] left-[45%] w-6 h-6 text-sky-200/25 animate-pulse",style:{animationDelay:"0.6s"}}),e.jsx(nj,{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(Wa,{className:"absolute top-[3%] left-[50%] -translate-x-1/2 w-10 h-10 text-amber-400/35 fill-amber-400/25"})]}),kws=()=>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(co,{className:"absolute top-[8%] left-[55%] w-6 h-6 text-red-400/22 fill-red-400/12"}),e.jsx(co,{className:"absolute top-[20%] right-[25%] w-5 h-5 text-orange-400/22 fill-orange-400/12"})]}),Sws=()=>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(Wa,{className:"absolute top-[5%] left-[15%] w-12 h-12 text-yellow-400/35 fill-yellow-400/25 animate-pulse"}),e.jsx(Wa,{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(Wa,{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(Wa,{className:"absolute top-[12%] right-[35%] w-8 h-8 text-amber-300/28 fill-amber-300/18 animate-pulse",style:{animationDelay:"0.9s"}}),e.jsx("div",{className:"absolute top-[20%] left-[25%] w-4 h-4 rounded-full bg-pink-400/30"}),e.jsx("div",{className:"absolute top-[18%] right-[30%] w-3 h-3 rounded-full bg-sky-400/30"}),e.jsx("div",{className:"absolute top-[25%] left-[60%] w-2.5 h-2.5 rounded-full bg-emerald-400/30"}),e.jsx("div",{className:"absolute top-[22%] right-[42%] w-3 h-3 rounded-full bg-purple-400/30"}),e.jsx(Cn,{className:"absolute top-[3%] left-[50%] w-10 h-10 text-yellow-400/40"}),e.jsx(uf,{className:"absolute bottom-[18%] left-[10%] w-12 h-12 text-purple-400/18 rotate-12"}),e.jsx(uf,{className:"absolute bottom-[20%] right-[12%] w-10 h-10 text-amber-400/15 -rotate-12"})]}),Cws=()=>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(Wa,{className:"absolute top-[8%] left-[50%] -translate-x-1/2 w-14 h-14 text-yellow-400/28 fill-yellow-400/18"}),e.jsx(Cn,{className:"absolute top-[5%] left-[20%] w-7 h-7 text-blue-400/35"}),e.jsx(Cn,{className:"absolute top-[10%] right-[18%] w-6 h-6 text-sky-400/30"})]}),Aws=()=>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(V4,{className:"absolute top-[5%] left-[10%] w-16 h-16 text-green-500/25"}),e.jsx(V4,{className:"absolute top-[8%] right-[12%] w-12 h-12 text-emerald-500/20"}),e.jsx(V4,{className:"absolute bottom-[18%] left-[12%] w-14 h-14 text-green-400/22"}),e.jsx(V4,{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"})]})]})]}),Tws=()=>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(Wa,{className:"absolute top-[5%] left-[42%] w-10 h-10 text-amber-400/30 fill-amber-400/20"}),e.jsx(Wa,{className:"absolute top-[15%] right-[25%] w-7 h-7 text-yellow-400/25 fill-yellow-400/15"}),e.jsx(ku,{className:"absolute bottom-[20%] right-[12%] w-12 h-12 text-blue-500/18"}),e.jsx(ku,{className:"absolute top-[18%] left-[28%] w-8 h-8 text-indigo-400/15"}),e.jsx(s3,{className:"absolute top-[8%] left-[60%] w-10 h-10 text-indigo-400/18"})]}),Ews=()=>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(Fm,{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(uf,{className:"absolute top-[8%] left-[45%] w-10 h-10 text-purple-400/22 rotate-12"}),e.jsx(Io,{className:"absolute bottom-[18%] right-[15%] w-12 h-12 text-rose-400/18"})]}),Mws=()=>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(co,{className:"absolute top-[5%] left-[10%] w-16 h-16 text-rose-400/28 fill-rose-400/18"}),e.jsx(co,{className:"absolute top-[8%] right-[12%] w-14 h-14 text-pink-400/25 fill-pink-400/15"}),e.jsx(co,{className:"absolute bottom-[15%] left-[12%] w-12 h-12 text-red-400/22 fill-red-400/12"}),e.jsx(co,{className:"absolute bottom-[18%] right-[10%] w-13 h-13 text-rose-300/25 fill-rose-300/15"}),e.jsx(co,{className:"absolute top-[15%] left-[30%] w-6 h-6 text-pink-300/35 fill-pink-300/20 animate-pulse"}),e.jsx(co,{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(co,{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(co,{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"})]}),Lws=()=>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(J2,{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(J2,{className:"absolute top-[15%] left-[18%] w-10 h-10 text-yellow-400/30"}),e.jsx(Cn,{className:"absolute top-[10%] left-[42%] w-7 h-7 text-amber-400/35"}),e.jsx(J2,{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"})]}),Pws=()=>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(_a,{className:"absolute top-[8%] left-[10%] w-14 h-14 text-teal-500/22"}),e.jsx(_a,{className:"absolute bottom-[15%] right-[8%] w-16 h-16 text-emerald-500/18"}),e.jsx(nb,{className:"absolute top-[12%] right-[18%] w-10 h-10 text-amber-400/25"}),e.jsx(nb,{className:"absolute bottom-[22%] left-[22%] w-8 h-8 text-yellow-400/22"}),e.jsx(co,{className:"absolute top-[18%] left-[40%] w-6 h-6 text-rose-400/22 fill-rose-400/12"}),e.jsx(co,{className:"absolute top-[22%] right-[35%] w-5 h-5 text-teal-400/20 fill-teal-400/10"}),e.jsx(Cn,{className:"absolute top-[5%] left-[55%] w-8 h-8 text-teal-400/30"}),e.jsx(uf,{className:"absolute bottom-[20%] left-[48%] w-10 h-10 text-cyan-400/18 rotate-12"})]}),Iws=()=>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(uf,{className:"absolute top-[5%] left-[12%] w-14 h-14 text-emerald-400/25 rotate-12"}),e.jsx(uf,{className:"absolute top-[8%] right-[10%] w-12 h-12 text-teal-400/22 -rotate-12"}),e.jsx(nb,{className:"absolute bottom-[18%] left-[18%] w-12 h-12 text-amber-400/25"}),e.jsx(_a,{className:"absolute bottom-[15%] right-[12%] w-14 h-14 text-teal-500/18"}),e.jsx(Cn,{className:"absolute top-[15%] left-[42%] w-10 h-10 text-emerald-400/35"}),e.jsx(Cn,{className:"absolute top-[20%] right-[32%] w-7 h-7 text-cyan-400/30"}),e.jsx("div",{className:"absolute top-[25%] left-[55%] w-3 h-3 bg-amber-400/30 rounded-full"}),e.jsx("div",{className:"absolute top-[22%] right-[42%] w-2.5 h-2.5 bg-teal-400/30 rounded-full"}),e.jsx("div",{className:"absolute top-[28%] left-[35%] w-2 h-2 bg-emerald-400/30 rounded-full"})]}),Dws=()=>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(nb,{className:"absolute bottom-[12%] left-[50%] -translate-x-1/2 w-24 h-24 text-amber-400/25 rotate-45"}),e.jsx(nb,{className:"absolute top-[10%] left-[12%] w-10 h-10 text-yellow-400/30"}),e.jsx(nb,{className:"absolute top-[12%] right-[15%] w-9 h-9 text-amber-300/25"}),e.jsx(_a,{className:"absolute top-[8%] left-[42%] w-12 h-12 text-teal-500/18"}),e.jsx(uf,{className:"absolute bottom-[22%] right-[18%] w-12 h-12 text-orange-400/18 rotate-12"}),e.jsx(Cn,{className:"absolute top-[5%] right-[35%] w-8 h-8 text-yellow-400/35"}),e.jsx(Wa,{className:"absolute top-[18%] left-[28%] w-6 h-6 text-amber-400/25 fill-amber-400/15"})]}),Rws=()=>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(_a,{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(nb,{className:"absolute top-[10%] right-[12%] w-10 h-10 text-amber-400/28"}),e.jsx(co,{className:"absolute top-[8%] left-[18%] w-8 h-8 text-rose-400/25 fill-rose-400/15"}),e.jsx(Cn,{className:"absolute top-[12%] left-[45%] w-8 h-8 text-teal-400/30"}),e.jsx(h5,{className:"absolute top-[15%] right-[28%] w-10 h-10 text-emerald-400/20"})]}),yrt=()=>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"})]}),Ows=()=>e.jsxs("div",{className:"absolute inset-0 overflow-hidden pointer-events-none",children:[e.jsx(co,{className:"absolute top-6 left-[12%] w-4 h-4 text-rose-300/50 fill-rose-300/30 animate-pulse"}),e.jsx(co,{className:"absolute top-10 right-[18%] w-3 h-3 text-pink-300/50 fill-pink-300/30 animate-pulse delay-150"}),e.jsx(co,{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(co,{className:"absolute top-14 right-[35%] w-3.5 h-3.5 text-pink-300/40 fill-pink-300/20 animate-pulse delay-200"})]}),Fws=()=>e.jsxs("div",{className:"absolute inset-0 overflow-hidden pointer-events-none",children:[e.jsx(h5,{className:"absolute top-5 left-[10%] w-4 h-4 text-blue-400/50 animate-pulse"}),e.jsx(Cn,{className:"absolute top-10 right-[15%] w-3 h-3 text-amber-400/50 animate-pulse delay-100"}),e.jsx(_a,{className:"absolute top-8 left-[38%] w-3 h-3 text-teal-300/40 animate-pulse delay-200"})]}),zws=()=>e.jsxs("div",{className:"absolute inset-0 overflow-hidden pointer-events-none",children:[e.jsx(T_,{className:"absolute top-5 left-[12%] w-4 h-4 text-amber-500/50 animate-pulse"}),e.jsx(v9,{className:"absolute top-10 right-[15%] w-3 h-3 text-rose-400/50 animate-pulse delay-100"}),e.jsx(T_,{className:"absolute top-8 left-[40%] w-3 h-3 text-amber-400/40 animate-pulse delay-200"})]}),DV=()=>e.jsxs("div",{className:"absolute inset-0 overflow-hidden pointer-events-none",children:[e.jsx(Cn,{className:"absolute top-5 left-[10%] w-4 h-4 text-emerald-400/50 animate-pulse"}),e.jsx(uf,{className:"absolute top-10 right-[12%] w-5 h-5 text-amber-400/50 animate-pulse delay-150"}),e.jsx(Cn,{className:"absolute top-8 left-[45%] w-3 h-3 text-sky-400/40 animate-pulse delay-300"})]}),vrt=()=>e.jsxs("div",{className:"absolute inset-0 overflow-hidden pointer-events-none",children:[e.jsx(_a,{className:"absolute top-6 left-[12%] w-4 h-4 text-teal-400/40 animate-pulse"}),e.jsx(Cn,{className:"absolute top-10 right-[15%] w-3 h-3 text-emerald-400/50 animate-pulse delay-100"}),e.jsx(_a,{className:"absolute top-4 right-[40%] w-3 h-3 text-cyan-400/30 animate-pulse delay-200"})]}),SRe=[{id:"default",name:"Classic",description:"Clean, professional look for any occasion",icon:e.jsx(Cn,{className:"h-5 w-5"}),category:"general",headerText:()=>"Video Message",subText:"A personal video just for you",gradientClasses:"from-background to-muted/30",accentColor:"primary"},{id:"thank_you",name:"Thank You",description:"Express your gratitude",icon:e.jsx(co,{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(Ows,{})},{id:"thinking_of_you",name:"Thinking of You",description:"Let them know they're on your mind",icon:e.jsx(BG,{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(DV,{})},{id:"check_in",name:"Check-in",description:"Touch base with your contacts",icon:e.jsx(T_,{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(zws,{})},{id:"market_update",name:"Market Update",description:"Share real estate market insights",icon:e.jsx(fl,{className:"h-5 w-5"}),category:"general",headerText:s=>s?`Market Update for ${s}`:"Market Update",subText:"The latest insights from your local market",gradientClasses:"from-blue-50/70 via-indigo-50/50 to-sky-50/40 dark:from-blue-950/30 dark:via-indigo-950/20 dark:to-sky-950/20",accentColor:"blue"},{id:"referral_thank_you",name:"Referral Thank You",description:"Thank someone for a referral",icon:e.jsx(Yn,{className:"h-5 w-5"}),category:"general",headerText:s=>s?`Thank You for the Referral, ${s}!`:"Thank You for the Referral!",subText:"Your trust in me means everything",gradientClasses:"from-emerald-50/70 via-green-50/50 to-teal-50/40 dark:from-emerald-950/30 dark:via-green-950/20 dark:to-teal-950/20",accentColor:"emerald",decorativeElement:e.jsx(DV,{})},{id:"congratulations",name:"Congratulations",description:"Celebrate their achievements",icon:e.jsx(ku,{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(yrt,{})},{id:"welcome_neighborhood",name:"Welcome to the Neighborhood",description:"Greet new neighbors",icon:e.jsx(ii,{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(vrt,{})},{id:"just_because",name:"Just Because",description:"No reason needed to connect",icon:e.jsx(v9,{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(DV,{})},{id:"birthday",name:"Birthday",description:"Celebrate their special day",icon:e.jsx(Fm,{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(Ews,{})},{id:"valentines_day",name:"Valentine's Day",description:"Show appreciation on this special day",icon:e.jsx(co,{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(Mws,{})},{id:"groundhog_day",name:"Groundhog Day",description:"A fun seasonal greeting",icon:e.jsx(J2,{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(Lws,{})},{id:"new_years",name:"New Year's Day",description:"Ring in the new year",icon:e.jsx(Wa,{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(Sws,{})},{id:"easter",name:"Easter",description:"Celebrate the spring season",icon:e.jsx(d9,{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(wws,{})},{id:"mothers_day",name:"Mother's Day",description:"Celebrate the amazing moms",icon:e.jsx(U2,{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(bws,{})},{id:"fathers_day",name:"Father's Day",description:"Celebrate the amazing dads",icon:e.jsx(ku,{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(_ws,{})},{id:"memorial_day",name:"Memorial Day",description:"Honor those who served",icon:e.jsx(s3,{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(yws,{})},{id:"independence_day",name:"4th of July",description:"Celebrate Independence Day",icon:e.jsx(Cu,{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(vws,{})},{id:"labor_day",name:"Labor Day",description:"Celebrate the workers",icon:e.jsx(ku,{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(Tws,{})},{id:"halloween",name:"Halloween",description:"Spooky seasonal greetings",icon:e.jsx(hD,{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(jws,{})},{id:"thanksgiving",name:"Thanksgiving",description:"Express gratitude this season",icon:e.jsx(co,{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(kws,{})},{id:"christmas",name:"Christmas",description:"Spread holiday cheer",icon:e.jsx(zT,{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(Nws,{})},{id:"hanukkah",name:"Hanukkah",description:"Celebrate the Festival of Lights",icon:e.jsx(Cn,{className:"h-5 w-5"}),category:"holidays",headerText:s=>s?`Happy Hanukkah, ${s}!`:"Happy Hanukkah!",subText:"Wishing you eight nights of light and joy",gradientClasses:"from-blue-50/70 via-indigo-50/50 to-sky-50/40 dark:from-blue-950/30 dark:via-indigo-950/20 dark:to-sky-950/20",accentColor:"blue",decorativeElement:e.jsx(Cws,{})},{id:"st_patricks_day",name:"St. Patrick's Day",description:"Celebrate the luck of the Irish",icon:e.jsx(V4,{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(Aws,{})},{id:"home_anniversary",name:"Home Anniversary",description:"Celebrate their home ownership milestone",icon:e.jsx(_a,{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(Pws,{})},{id:"under_contract",name:"Under Contract",description:"Celebrate this exciting milestone",icon:e.jsx(uf,{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(Iws,{})},{id:"just_listed",name:"Just Listed",description:"Announce a new listing",icon:e.jsx(ta,{className:"h-5 w-5"}),category:"transactional",headerText:s=>s?`Exciting News, ${s}!`:"Just Listed!",subText:"A new property is now on the market",gradientClasses:"from-blue-50/70 via-indigo-50/50 to-violet-50/40 dark:from-blue-950/30 dark:via-indigo-950/20 dark:to-violet-950/20",accentColor:"blue",decorativeElement:e.jsx(vrt,{})},{id:"just_sold",name:"Just Sold",description:"Celebrate a successful sale",icon:e.jsx(Ed,{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(DV,{})},{id:"price_reduction",name:"Price Reduction",description:"Notify about a price change",icon:e.jsx(eN,{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(h5,{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(Fws,{})},{id:"closing_day",name:"Closing Day",description:"Celebrate their closing day",icon:e.jsx(nb,{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(Dws,{})},{id:"move_in_day",name:"Move-in Day",description:"Welcome them to their new home",icon:e.jsx(_a,{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(Rws,{})},{id:"offer_accepted",name:"Offer Accepted",description:"Celebrate their accepted offer",icon:e.jsx(ax,{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(DV,{})},{id:"pre_approval",name:"Pre-Approval Congrats",description:"Congratulate on pre-approval",icon:e.jsx(ku,{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(yrt,{})}],Bws=[{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 $ws(s){return SRe.filter(t=>t.category===s)}function q9(s){return SRe.find(t=>t.id===s)||SRe[0]}function brt(){const{shareToken:s,recipientToken:t}=uo(),[n,r]=N.useState(null),[a,i]=N.useState(null),[l,o]=N.useState(null),[c,d]=N.useState(!0),[u,h]=N.useState(null),[m,f]=N.useState(!0),g=N.useRef(null),y=N.useRef(0),x=N.useRef(0),_=(()=>{const V=new URLSearchParams(window.location.search);return t||V.get("rt")||null})(),b=N.useCallback((V,W=!1)=>{if(!_||V<=0)return;const G=Math.max(1,Math.round(V));if(G<=x.current)return;const te=`https://relzejiswnotikjgvjhz.supabase.co/functions/v1/track-video-share?t=${encodeURIComponent(_)}&e=watch&ws=${G}`;W&&navigator.sendBeacon?navigator.sendBeacon(te):fetch(te,{method:"GET",keepalive:W}).catch(()=>{}),x.current=Math.max(x.current,G)},[_]);N.useEffect(()=>{var me;if(!m||!(n!=null&&n.playback_url)||!_)return;let V=!1;const W=()=>{y.current>0&&b(y.current,!0)},G=()=>{document.visibilityState==="hidden"&&W()},X=()=>{W()},te=()=>{var ce;if(V||!g.current||!((ce=window.playerjs)!=null&&ce.Player))return;const ue=new window.playerjs.Player(g.current);ue.on("timeupdate",ae=>{const he=Math.floor(Number((ae==null?void 0:ae.seconds)??0));!Number.isFinite(he)||he<=0||(y.current=Math.max(y.current,he))}),ue.on("pause",()=>{y.current>0&&b(y.current)}),ue.on("ended",()=>{y.current>0&&b(y.current,!0)})},ne=document.querySelector('script[data-bunny-playerjs="true"]');if((me=window.playerjs)!=null&&me.Player)te();else if(ne)ne.addEventListener("load",te,{once:!0});else{const ue=document.createElement("script");ue.src="https://assets.mediadelivery.net/playerjs/playerjs-latest.min.js",ue.async=!0,ue.defer=!0,ue.dataset.bunnyPlayerjs="true",ue.onload=te,document.body.appendChild(ue)}return document.addEventListener("visibilitychange",G),window.addEventListener("beforeunload",X),()=>{V=!0,document.removeEventListener("visibilitychange",G),window.removeEventListener("beforeunload",X),W()}},[m,n==null?void 0:n.playback_url,_,b]),N.useEffect(()=>{y.current=0,x.current=0},[_,s]),N.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(te=>{document.querySelectorAll(te).forEach(ne=>{ne.style.display="none"})})};V();const W=[setTimeout(V,500),setTimeout(V,1500),setTimeout(V,3e3)],G=new MutationObserver(V);return G.observe(document.body,{childList:!0,subtree:!0}),()=>{W.forEach(clearTimeout),G.disconnect()}},[]),N.useEffect(()=>{(async()=>{if(!s){h("Invalid share link"),d(!1);return}const{data:W,error:G}=await H.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||!W){h("Video not found or has been removed"),d(!1);return}r(W);try{await H.rpc("log_video_view",{p_video_id:W.id,p_user_agent:navigator.userAgent,p_referrer:document.referrer||null})}catch(X){console.warn("Failed to log video view:",X)}if(W.owner_user_id){const{data:X}=await H.from("profiles").select("id, name, email, phone").eq("id",W.owner_user_id).single();if(X){i(X);try{const{data:te}=await H.storage.from("avatars").list(`${W.owner_user_id}`);if(te&&te.length>0){const{data:ne}=H.storage.from("avatars").getPublicUrl(`${W.owner_user_id}/${te[0].name}`);o(ne.publicUrl)}}catch{}}}d(!1)})()},[s]);const k=V=>{if(!V)return"0:00";const W=Math.floor(V/60),G=V%60;return`${W}:${G.toString().padStart(2,"0")}`},A=V=>V.includes("iframe.mediadelivery.net/play/")?V.replace("/play/","/embed/")+"?autoplay=true&responsive=true":V,T=V=>{if(!V)return"?";const W=V.split(" ");return W.length>=2?`${W[0][0]}${W[1][0]}`.toUpperCase():V.substring(0,2).toUpperCase()},P=q9((n==null?void 0:n.page_template)||"default"),I=(n==null?void 0:n.recipient_name)||null,M=P.headerText(I),z=`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(us,{className:"h-8 w-8 animate-spin text-primary"})});if(u||!n)return e.jsx("div",{className:"min-h-screen bg-background flex items-center justify-center p-4",children:e.jsx(_e,{className:"max-w-md w-full",children:e.jsxs(De,{className:"py-12 text-center",children:[e.jsx(na,{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 $=P.id!=="default";return e.jsxs(e.Fragment,{children:[e.jsxs(ic,{children:[e.jsx("title",{children:M}),e.jsx("meta",{name:"description",content:P.subText}),e.jsx("meta",{property:"og:title",content:M}),e.jsx("meta",{property:"og:description",content:P.subText}),e.jsx("meta",{property:"og:type",content:"video.other"}),e.jsx("meta",{property:"og:url",content:z}),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:P.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:Ot("min-h-screen flex items-center justify-center p-4 bg-gradient-to-b relative",P.gradientClasses),children:[$&&P.decorativeElement,e.jsxs("div",{className:"max-w-2xl w-full space-y-6 relative z-10",children:[$&&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:Ot("w-14 h-14 rounded-full flex items-center justify-center shadow-sm",P.accentColor==="primary"&&"bg-primary/10 text-primary",P.accentColor==="amber"&&"bg-amber-100 text-amber-600 dark:bg-amber-900/50 dark:text-amber-400",P.accentColor==="teal"&&"bg-teal-100 text-teal-600 dark:bg-teal-900/50 dark:text-teal-400",P.accentColor==="rose"&&"bg-rose-100 text-rose-600 dark:bg-rose-900/50 dark:text-rose-400",P.accentColor==="emerald"&&"bg-emerald-100 text-emerald-600 dark:bg-emerald-900/50 dark:text-emerald-400",P.accentColor==="yellow"&&"bg-yellow-100 text-yellow-600 dark:bg-yellow-900/50 dark:text-yellow-400",P.accentColor==="pink"&&"bg-pink-100 text-pink-600 dark:bg-pink-900/50 dark:text-pink-400",P.accentColor==="blue"&&"bg-blue-100 text-blue-600 dark:bg-blue-900/50 dark:text-blue-400",P.accentColor==="red"&&"bg-red-100 text-red-600 dark:bg-red-900/50 dark:text-red-400",P.accentColor==="orange"&&"bg-orange-100 text-orange-600 dark:bg-orange-900/50 dark:text-orange-400",P.accentColor==="green"&&"bg-green-100 text-green-600 dark:bg-green-900/50 dark:text-green-400",P.accentColor==="violet"&&"bg-violet-100 text-violet-600 dark:bg-violet-900/50 dark:text-violet-400",P.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:P.icon})})}),e.jsx("h1",{className:"text-2xl sm:text-3xl font-bold mb-2",children:M}),e.jsx("p",{className:"text-muted-foreground",children:P.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(Ua,{className:"h-14 w-14 border-2 border-primary/20",children:[e.jsx(Gi,{src:l||void 0,alt:a.name||"Agent"}),e.jsx(qa,{className:"bg-primary/10 text-primary font-semibold",children:T(a.name)})]}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:$?"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(ga,{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(mn,{className:"h-4 w-4"})})})]})]}),e.jsx(_e,{className:"overflow-hidden shadow-lg",children:m&&n.playback_url?e.jsx("div",{className:"relative w-full",style:{paddingBottom:"56.25%"},children:e.jsx("iframe",{ref:g,src:A(n.playback_url),title:n.title||"Video message",className:"absolute top-0 left-0 w-full h-full",style:{border:0},allow:"accelerometer; gyroscope; autoplay; encrypted-media; picture-in-picture",allowFullScreen:!0})}):e.jsxs("div",{className:"relative aspect-video bg-muted cursor-pointer group",onClick:()=>f(!0),children:[n.preview_url||n.thumbnail_url?e.jsx("img",{src:n.preview_url||n.thumbnail_url||"",alt:n.title?`${n.title} video preview`:"Video message preview",className:"w-full h-full object-cover",onError:V=>{var G;V.currentTarget.style.display="none";const W=(G=V.currentTarget.parentElement)==null?void 0:G.querySelector(".video-fallback");W&&(W.style.display="flex")}}):null,e.jsx("div",{className:"video-fallback w-full h-full items-center justify-center bg-gradient-to-br from-primary/20 to-primary/5",style:{display:n.preview_url||n.thumbnail_url?"none":"flex"},children:e.jsx(na,{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(dd,{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:k(n.duration_seconds)})]})}),!$&&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:()=>f(!0),className:"gap-2",children:[e.jsx(dd,{className:"h-5 w-5"}),"Watch Video"]})}),e.jsx(xws,{shareToken:s,agentName:(a==null?void 0:a.name)||null,hasContact:!!n.contact_id})]})]})]})}function Uws(){return N.useEffect(()=>(document.body.classList.add("video-landing-page"),()=>{document.body.classList.remove("video-landing-page")}),[]),e.jsx(o_t,{})}function qws(){const{token:s}=uo();return N.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(us,{className:"h-5 w-5 animate-spin"}),e.jsx("span",{children:"Loading video preview…"})]})})}const Vws={office_exclusive:"Office Exclusive",coming_soon:"Coming Soon",pre_market:"Pre-Market",active:"Active"},Hws=s=>new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:0}).format(s||0);function Gws(){var he;const[s]=$c(),t=s.get("r"),n=s.get("m"),[r,a]=N.useState(null),[i,l]=N.useState(null),[o,c]=N.useState(!0),[d,u]=N.useState(0),[h,m]=N.useState(!1),[f,g]=N.useState(""),[y,x]=N.useState(""),[_,b]=N.useState(""),[k,A]=N.useState(""),[T,P]=N.useState("tour"),[I,M]=N.useState(!1),[L,z]=N.useState(!1),$=async()=>{if(!f.trim()||!y.trim()){ie.error("Please enter your name and email");return}M(!0);try{const ve=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/private-listing-lead",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({r:t,m:n,name:f.trim(),email:y.trim(),phone:_.trim()||null,message:k.trim()||null,intent:T})}),ge=await ve.json();if(!ve.ok||!(ge!=null&&ge.success))throw new Error((ge==null?void 0:ge.error)||"Could not send");z(!0),ie.success("Sent! The agent will be in touch shortly.")}catch(xe){ie.error((xe==null?void 0:xe.message)||"Could not send")}finally{M(!1)}};if(N.useEffect(()=>{if(!t||!n){l("Invalid link"),c(!1);return}const xe=`https://relzejiswnotikjgvjhz.supabase.co/functions/v1/private-listing-view?r=${encodeURIComponent(t)}&m=${encodeURIComponent(n)}`;fetch(xe).then(ve=>ve.json()).then(ve=>{ve.error?l("This private listing link is no longer valid."):a({listing:ve.listing,agent:ve.agent})}).catch(()=>l("Unable to load listing.")).finally(()=>c(!1))},[t,n]),o)return e.jsx("div",{className:"min-h-screen flex items-center justify-center bg-slate-50",children:e.jsx("div",{className:"text-slate-500",children:"Loading…"})});if(i||!r)return e.jsxs(e.Fragment,{children:[e.jsx(ic,{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(Au,{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:W}=r,G=(he=V.photos)!=null&&he.length?V.photos:[],X=G[0],te=Vws[V.status]||V.status,ne=(W==null?void 0:W.sender_name)||(W==null?void 0:W.name)||"Your Agent",me=(W==null?void 0:W.sender_email)||null,ue=encodeURIComponent(`Interested in ${V.address}`),ce=encodeURIComponent(`Hi ${ne}, I'd love to learn more about ${V.address}, ${V.city}. Thanks!`),ae=W!=null&&W.booking_slug?`https://dashboard.relevelup.com/book/${W.booking_slug}`:null;return e.jsxs(e.Fragment,{children:[e.jsxs(ic,{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(Au,{className:"h-3.5 w-3.5"}),e.jsxs("span",{className:"font-medium tracking-wide uppercase",children:["Private listing · Shared by ",ne]})]}),e.jsxs("div",{className:"relative",children:[X?e.jsx("button",{type:"button",className:"block w-full",onClick:()=>{u(0),m(!0)},children:e.jsx("img",{src:X,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(We,{className:"bg-indigo-600 text-white border-0 text-xs px-2.5 py-1 shadow",children:te})}),G.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:[G.length," photos"]})]}),e.jsxs("div",{className:"max-w-5xl mx-auto px-4 sm:px-6 -mt-10 relative z-10",children:[e.jsx(_e,{className:"shadow-xl border-slate-200",children:e.jsxs(De,{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(ii,{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:Hws(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(A_,{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(Wx,{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(L_,{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})]}),G.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:G.slice(0,9).map((xe,ve)=>e.jsx("button",{type:"button",onClick:()=>{u(ve),m(!0)},className:"aspect-[4/3] overflow-hidden rounded-lg bg-slate-100",children:e.jsx("img",{src:xe,alt:"",className:"w-full h-full object-cover hover:scale-105 transition"})},ve))})]})]})}),e.jsxs(_e,{className:"mt-6 shadow-lg border-slate-200 overflow-hidden",children:[e.jsxs("div",{className:"bg-gradient-to-r from-indigo-600 to-indigo-500 px-6 py-4 text-white",children:[e.jsx("h2",{className:"text-lg font-semibold",children:"Request more info or a private tour"}),e.jsxs("p",{className:"text-indigo-100 text-sm",children:[ne," will get back to you personally."]})]}),e.jsx(De,{className:"p-6 sm:p-8",children:L?e.jsxs("div",{className:"flex flex-col items-center text-center py-6",children:[e.jsx(Hr,{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:[ne," 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(xe=>e.jsx("button",{type:"button",onClick:()=>P(xe.id),className:`px-3 py-2 rounded-lg border text-sm font-medium transition ${T===xe.id?"bg-indigo-600 text-white border-indigo-600":"bg-white text-slate-700 border-slate-200 hover:border-indigo-300"}`,children:xe.label},xe.id))}),e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(re,{htmlFor:"pl-name",children:"Your name *"}),e.jsx(we,{id:"pl-name",value:f,onChange:xe=>g(xe.target.value),placeholder:"Jane Doe",maxLength:120})]}),e.jsxs("div",{children:[e.jsx(re,{htmlFor:"pl-email",children:"Email *"}),e.jsx(we,{id:"pl-email",type:"email",value:y,onChange:xe=>x(xe.target.value),placeholder:"you@email.com",maxLength:255})]})]}),e.jsxs("div",{children:[e.jsx(re,{htmlFor:"pl-phone",children:"Phone (optional)"}),e.jsx(we,{id:"pl-phone",value:_,onChange:xe=>b(xe.target.value),placeholder:"(555) 555-5555",maxLength:40})]}),e.jsxs("div",{children:[e.jsx(re,{htmlFor:"pl-msg",children:"Message (optional)"}),e.jsx(Ws,{id:"pl-msg",value:k,onChange:xe=>A(xe.target.value),placeholder:`I'd love to see ${V.address}…`,rows:4,maxLength:2e3})]}),e.jsx(B,{onClick:$,disabled:I,className:"w-full bg-indigo-600 hover:bg-indigo-700 h-11 text-base",children:I?"Sending…":"Send to "+ne.split(" ")[0]}),e.jsx("p",{className:"text-xs text-slate-500 text-center",children:"By submitting, you agree to be contacted about this property."})]})})]}),e.jsx(_e,{className:"mt-6 mb-12 shadow-lg border-slate-200",children:e.jsxs(De,{className:"p-6 sm:p-8",children:[e.jsxs("div",{className:"flex flex-col sm:flex-row items-center sm:items-start gap-5",children:[W!=null&&W.avatar_url?e.jsx("img",{src:W.avatar_url,alt:ne,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:ne.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:ne}),(W==null?void 0:W.brokerage_name)&&e.jsx("p",{className:"text-slate-600 text-sm",children:W.brokerage_name}),e.jsx("p",{className:"text-slate-600 text-sm mt-2",children:"Want a private tour or more info? Reach out — I'm happy to help."})]})]}),e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-3 gap-2 mt-6",children:[me&&e.jsx(B,{asChild:!0,className:"bg-indigo-600 hover:bg-indigo-700",children:e.jsxs("a",{href:`mailto:${me}?subject=${ue}&body=${ce}`,children:[e.jsx(mn,{className:"h-4 w-4 mr-1.5"}),"Email"]})}),(W==null?void 0:W.phone)&&e.jsx(B,{asChild:!0,variant:"outline",children:e.jsxs("a",{href:`tel:${W.phone}`,children:[e.jsx(ga,{className:"h-4 w-4 mr-1.5"}),W.phone]})}),ae&&e.jsx(B,{asChild:!0,variant:"outline",children:e.jsxs("a",{href:ae,target:"_blank",rel:"noreferrer",children:[e.jsx(df,{className:"h-4 w-4 mr-1.5"}),"Book a tour"]})})]})]})})]}),h&&G.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(hr,{className:"h-6 w-6"})}),e.jsx("button",{className:"absolute left-4 text-white p-2 hover:bg-white/10 rounded-full",onClick:()=>u(xe=>(xe-1+G.length)%G.length),"aria-label":"Previous",children:e.jsx(Fc,{className:"h-8 w-8"})}),e.jsx("img",{src:G[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(xe=>(xe+1)%G.length),"aria-label":"Next",children:e.jsx(Qa,{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," / ",G.length]})]})]})]})}function Wws(){var i;const{slug:s}=uo(),{data:t,isLoading:n,error:r}=V2t(s);if(N.useEffect(()=>(document.body.classList.add("agent-card-page"),()=>{document.body.classList.remove("agent-card-page")}),[]),N.useEffect(()=>{t!=null&&t.id&&Oc(t.id,"card_view")},[t==null?void 0:t.id]),n)return e.jsx("div",{className:"min-h-screen bg-gradient-to-b from-slate-50 to-white flex items-center justify-center",children:e.jsxs("div",{className:"w-full max-w-md mx-auto p-6 space-y-6",children:[e.jsxs("div",{className:"flex flex-col items-center gap-4",children:[e.jsx(xn,{className:"h-28 w-28 rounded-full"}),e.jsx(xn,{className:"h-6 w-48"}),e.jsx(xn,{className:"h-4 w-36"})]}),e.jsx(xn,{className:"h-12 w-full"}),e.jsx(xn,{className:"h-12 w-full"})]})});if(r||!t)return e.jsx("div",{className:"min-h-screen bg-gradient-to-b from-slate-50 to-white flex items-center justify-center p-6",children:e.jsxs("div",{className:"text-center",children:[e.jsx("h1",{className:"text-2xl font-bold text-slate-800 mb-2",children:"Card Not Found"}),e.jsx("p",{className:"text-slate-500",children:"This agent card doesn't exist or isn't published yet."})]})});const a=((i=t.profile)==null?void 0:i.name)||"Agent";return e.jsxs(e.Fragment,{children:[e.jsxs(ic,{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(W$e,{card:t})]})}const Kws="https://images.unsplash.com/photo-1507525428034-b723cf961d3e?w=1600&q=80",Yws="https://images.unsplash.com/photo-1616486338812-3dadae4b4ace?w=1600&q=80",Zws="https://images.unsplash.com/photo-1500534314209-a25ddb2bd429?w=1600&q=80",Xws="https://images.unsplash.com/photo-1600585154340-be6161a56a0c?w=1600&q=80",Qws="https://images.unsplash.com/photo-1519741497674-611481863552?w=1600&q=80",Jws="https://images.unsplash.com/photo-1494526585095-c41746248156?w=1600&q=80",$we={"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:Jws},"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:Kws},"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:Yws},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:Zws},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:Xws},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:Qws}},ejs=["#111111","#2f7a7d","#c9a84c","#d84a7a","#3b6fa0","#9b72cf","#e85d3a","#4a6741"];function w4t(s){return s&&s in $we?$we[s]:$we["minimal-mono"]}function tjs(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 j4t({slugOverride:s}={}){var Ds;const{slug:t}=uo(),n=s||t,[r]=$c(),a=r.get("t"),[i,l]=N.useState(!0),[o,c]=N.useState(null),[d,u]=N.useState(null),h=N.useRef(null),m=N.useRef(null),[f,g]=N.useState(null),[y,x]=N.useState(null),[_,b]=N.useState(!1),[k,A]=N.useState(!1),[T,P]=N.useState(0),[I,M]=N.useState(!1),[L,z]=N.useState(""),[$,V]=N.useState(""),[W,G]=N.useState(""),[X,te]=N.useState(""),[ne,me]=N.useState(""),[ue,ce]=N.useState(""),[ae,he]=N.useState(""),[xe,ve]=N.useState(""),[ge,be]=N.useState(""),[Se,Ie]=N.useState(""),[Me,Re]=N.useState(""),[Be,Ne]=N.useState(""),[Ge,Ce]=N.useState(""),[Fe,Ae]=N.useState([]),[Xe,$e]=N.useState([]),[Ye,Je]=N.useState(""),[Ke,st]=N.useState(""),[rt,Ze]=N.useState(""),[ht,Bt]=N.useState([]);N.useEffect(()=>{Ct()},[n,a]);const Ct=async()=>{if(!n)return;l(!0);const{data:As,error:Hs}=await H.from("contact_intake_pages").select("*").eq("slug",n).eq("is_active",!0).maybeSingle();if(Hs||!As){M(!0),l(!1);return}u(As),m.current=As;const{data:Rs}=await H.from("profiles").select("name, avatar_url, title, phone, email, brokerage_id").eq("id",As.user_id).single();if(Rs){let en;if(Rs.brokerage_id){const{data:Dn}=await H.from("brokerages").select("name").eq("id",Rs.brokerage_id).single();en=(Dn==null?void 0:Dn.name)||void 0}let Rn=Rs.avatar_url||null;if(!Rn){const{data:Dn}=H.storage.from("avatars").getPublicUrl(`${As.user_id}/avatar.jpg`);Dn!=null&&Dn.publicUrl&&(Rn=`${Dn.publicUrl}?t=${Date.now()}`)}const Bn={...Rs,avatar_url:Rn,brokerage_name:en};c(Bn),h.current=Bn}if(a)try{console.log("[ConnectPage] Resolving token:",a,"for page:",As.id);const{data:en,error:Rn}=await H.functions.invoke("process-intake-submissions",{body:{action:"resolve_token",token:a,page_id:As.id}});if(console.log("[ConnectPage] Resolve result:",{resolved:en,resolveErr:Rn}),!Rn&&(en!=null&&en.contact_id)){x(en.contact_id);const Bn=en.contact;Bn&&(g(Bn),z(Bn.first_name||""),V(Bn.last_name||""),G(Bn.email||""),te(Bn.phone||""),me(Bn.address||""),ce(Bn.city||""),he(Bn.state||""),ve(Bn.zip||""),be(Bn.birthday||""),Ie(Bn.home_anniversary||""))}}catch(en){console.error("Failed to resolve token:",en)}l(!1)},Yt=async()=>{var As,Hs;if(!L.trim()){ie.error("Please enter your first name");return}if(!n){ie.error("Invalid page. Please refresh.");return}A(!0);try{let Rs=(As=m.current)==null?void 0:As.id,en=(Hs=m.current)==null?void 0:Hs.user_id;if(!Rs||!en){const{data:Dn}=await H.from("contact_intake_pages").select("id, user_id").eq("slug",n).eq("is_active",!0).maybeSingle();if(!Dn){ie.error("This page is no longer active. Please contact the agent directly."),A(!1);return}Rs=Dn.id,en=Dn.user_id}const Rn={intake_page_id:Rs,agent_user_id:en,existing_contact_id:y,first_name:L.trim(),last_name:$.trim()||null,email:W.trim()||null,phone:X.trim()||null,address:ne.trim()||null,city:ue.trim()||null,state:ae.trim()||null,zip:xe.trim()||null,birthday:ge||null,home_anniversary:Se||null,real_estate_interest:Me||null,message:Be.trim()||null,life_events:{spouse_name:Ge.trim()||null,kids:Fe.filter(Dn=>Dn.name.trim()),pets:Xe.filter(Dn=>Dn.name.trim()),favorite_spots:Ye.trim()||null,dream_neighborhood:Ke.trim()||null,wedding_anniversary:rt||null},referrals:ht.filter(Dn=>Dn.name.trim()&&Dn.contact.trim())},{error:Bn}=await H.from("contact_intake_submissions").insert(Rn);if(console.log("[ConnectPage] Insert result:",{error:Bn}),Bn)throw Bn;a&&await H.from("contact_intake_tokens").update({used_at:new Date().toISOString()}).eq("token",a);try{const Dn=[L.trim(),$.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:en,contactName:Dn,contactEmail:W.trim()||null,contactPhone:X.trim()||null,slug:n})})}catch(Dn){console.warn("Connect page notification failed (non-blocking):",Dn)}b(!0)}catch(Rs){console.error(Rs),ie.error("Something went wrong. Please try again.")}finally{A(!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(us,{className:"h-8 w-8 animate-spin text-slate-400"})});if(I)return e.jsx("div",{className:"min-h-screen flex items-center justify-center bg-gradient-to-br from-slate-50 via-white to-blue-50",children:e.jsxs("div",{className:"text-center space-y-3",children:[e.jsx("h1",{className:"text-2xl font-semibold text-slate-700",children:"Page Not Found"}),e.jsx("p",{className:"text-slate-500",children:"This connect page doesn't exist or is no longer active."})]})});if(_)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(ic,{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(Hr,{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(co,{className:"h-3.5 w-3.5"}),e.jsx("span",{children:"Powered by ReLevelUp"})]})]})]});const Kt=!!a&&!!f,Xs=(d==null?void 0:d.show_little_things)??!0,zs=[{title:Kt?"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:L,onChange:As=>z(As.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:$,onChange:As=>V(As.target.value),placeholder:"Smith",className:"connect-input"})]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-medium mb-1.5",style:{color:"var(--c-text-muted)"},children:"Email"}),e.jsx("input",{type:"email",value:W,onChange:As=>G(As.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:X,onChange:As=>te(As.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:ne,onChange:As=>me(As.target.value),placeholder:"123 Main St",className:"connect-input"})]}),e.jsxs("div",{className:"grid grid-cols-5 gap-3",children:[e.jsxs("div",{className:"col-span-2",children:[e.jsx("label",{className:"block text-sm font-medium mb-1.5",style:{color:"var(--c-text-muted)"},children:"City"}),e.jsx("input",{type:"text",value:ue,onChange:As=>ce(As.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:ae,onChange:As=>he(As.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:xe,onChange:As=>ve(As.target.value),placeholder:"78701",className:"connect-input"})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-medium mb-1.5",style:{color:"var(--c-text-muted)"},children:"Birthday"}),e.jsx("input",{type:"date",value:ge,onChange:As=>be(As.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:Se,onChange:As=>Ie(As.target.value),className:"connect-input"})]})]})]})},...Xs?[{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:Ge,onChange:As=>Ce(As.target.value),placeholder:"Alex",className:"connect-input"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-medium mb-1.5",style:{color:"var(--c-text-muted)"},children:"Wedding anniversary"}),e.jsx("input",{type:"date",value:rt,onChange:As=>Ze(As.target.value),className:"connect-input"})]}),e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center justify-between mb-1.5",children:[e.jsx("label",{className:"block text-sm font-medium",style:{color:"var(--c-text-muted)"},children:"Kids"}),e.jsxs("button",{type:"button",onClick:()=>Ae(As=>[...As,{name:"",age:""}]),className:"text-xs inline-flex items-center gap-1",style:{color:"var(--c-accent)"},children:[e.jsx(nn,{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((As,Hs)=>e.jsxs("div",{className:"flex gap-2 items-center",children:[e.jsx("input",{type:"text",value:As.name,onChange:Rs=>Ae(en=>en.map((Rn,Bn)=>Bn===Hs?{...Rn,name:Rs.target.value}:Rn)),placeholder:"Child's name",className:"connect-input min-w-0",style:{flex:"1 1 0%"}}),e.jsx("input",{type:"text",value:As.age,onChange:Rs=>Ae(en=>en.map((Rn,Bn)=>Bn===Hs?{...Rn,age:Rs.target.value}:Rn)),placeholder:"Age",className:"connect-input shrink-0",style:{width:"5rem"}}),e.jsx("button",{type:"button",onClick:()=>Ae(Rs=>Rs.filter((en,Rn)=>Rn!==Hs)),className:"p-2 rounded-md hover:bg-black/5 shrink-0","aria-label":"Remove",children:e.jsx(hr,{className:"h-3.5 w-3.5",style:{color:"var(--c-text-muted)"}})})]},Hs))]})]}),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:()=>$e(As=>[...As,{name:"",kind:""}]),className:"text-xs inline-flex items-center gap-1",style:{color:"var(--c-accent)"},children:[e.jsx(nn,{className:"h-3 w-3"})," Add"]})]}),e.jsxs("div",{className:"space-y-2",children:[Xe.length===0&&e.jsx("p",{className:"text-xs",style:{color:"var(--c-text-muted)"},children:"None to add? Skip this."}),Xe.map((As,Hs)=>e.jsxs("div",{className:"flex gap-2 items-center",children:[e.jsx("input",{type:"text",value:As.name,onChange:Rs=>$e(en=>en.map((Rn,Bn)=>Bn===Hs?{...Rn,name:Rs.target.value}:Rn)),placeholder:"Pet's name",className:"connect-input min-w-0",style:{flex:"1 1 0%"}}),e.jsx("input",{type:"text",value:As.kind,onChange:Rs=>$e(en=>en.map((Rn,Bn)=>Bn===Hs?{...Rn,kind:Rs.target.value}:Rn)),placeholder:"Dog, cat…",className:"connect-input shrink-0",style:{width:"7rem"}}),e.jsx("button",{type:"button",onClick:()=>$e(Rs=>Rs.filter((en,Rn)=>Rn!==Hs)),className:"p-2 rounded-md hover:bg-black/5 shrink-0","aria-label":"Remove",children:e.jsx(hr,{className:"h-3.5 w-3.5",style:{color:"var(--c-text-muted)"}})})]},Hs))]})]}),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:Ye,onChange:As=>Je(As.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:Ke,onChange:As=>st(As.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."})]}),ht.length<3&&e.jsxs("button",{type:"button",onClick:()=>Bt(As=>[...As,{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(nn,{className:"h-3 w-3"})," Add"]})]}),e.jsx("div",{className:"space-y-2",children:ht.map((As,Hs)=>e.jsxs("div",{className:"flex gap-2 items-center",children:[e.jsx("input",{type:"text",value:As.name,onChange:Rs=>Bt(en=>en.map((Rn,Bn)=>Bn===Hs?{...Rn,name:Rs.target.value}:Rn)),placeholder:"Their name",className:"connect-input min-w-0",style:{flex:"1 1 0%"}}),e.jsx("input",{type:"text",value:As.contact,onChange:Rs=>Bt(en=>en.map((Rn,Bn)=>Bn===Hs?{...Rn,contact:Rs.target.value}:Rn)),placeholder:"Phone or email",className:"connect-input min-w-0",style:{flex:"1 1 0%"}}),e.jsx("button",{type:"button",onClick:()=>Bt(Rs=>Rs.filter((en,Rn)=>Rn!==Hs)),className:"p-2 rounded-md hover:bg-black/5","aria-label":"Remove",children:e.jsx(hr,{className:"h-3.5 w-3.5",style:{color:"var(--c-text-muted)"}})})]},Hs))})]})]})}]:[],{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(As=>e.jsxs("button",{type:"button",onClick:()=>Re(Me===As.value?"":As.value),className:`p-3.5 rounded-xl border-2 text-left transition-all ${Me===As.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:As.label}),e.jsx("span",{className:"block text-xs text-slate-500 mt-0.5",children:As.desc})]},As.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:Be,onChange:As=>Ne(As.target.value),placeholder:"Feel free to drop a note...",rows:3,className:"connect-input resize-none"})]})]})}],Vt=zs.length,At=w4t(d==null?void 0:d.theme),Os=tjs(At,(d==null?void 0:d.accent_color)||null),Nt=(d==null?void 0:d.cover_image_url)||At.defaultCover,ms=(d==null?void 0:d.headline)||"Let's stay connected",Ys=(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)||""),It=["deep-luxe"].includes((d==null?void 0:d.theme)||"");return e.jsxs("div",{className:"min-h-screen connect-shell",style:Os,children:[e.jsxs(ic,{children:[e.jsxs("title",{children:["Connect with ",(o==null?void 0:o.name)||"Agent"]}),e.jsx("meta",{name:"description",content:`${ms} — ${(o==null?void 0:o.name)||"your agent"}`}),Nt&&e.jsx("meta",{property:"og:image",content:Nt}),e.jsx("meta",{property:"og:title",content:`Connect with ${(o==null?void 0:o.name)||"me"}`}),e.jsx("meta",{property:"og:description",content:ms}),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:Nt,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:At.headingFont,fontWeight:500,letterSpacing:"-0.01em"},className:"text-3xl sm:text-4xl leading-tight",children:ms}),Ys&&e.jsx(Sr.p,{initial:{opacity:0},animate:{opacity:.9},transition:{delay:.35,duration:.6},style:{color:"#fff"},className:"text-sm mt-2",children:Ys})]})]}),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:At.accent,color:At.accentText,border:"4px solid var(--c-surface)"},children:e.jsx("span",{className:"text-3xl font-bold",children:((Ds=o==null?void 0:o.name)==null?void 0:Ds.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(ga,{className:"h-4 w-4"})}),(o==null?void 0:o.email)&&e.jsx("a",{href:`mailto:${o.email}`,className:"flex items-center justify-center w-10 h-10 rounded-full transition-opacity hover:opacity-80",style:{background:"color-mix(in srgb, var(--c-accent) 12%, transparent)",color:"var(--c-accent)"},"aria-label":"Email agent",children:e.jsx(mn,{className:"h-4 w-4"})})]})]}),e.jsx(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:Vt}).map((As,Hs)=>e.jsx("div",{className:"h-1 flex-1 rounded-full transition-all duration-500",style:{background:Hs<=T?"var(--c-accent)":"color-mix(in srgb, var(--c-text) 12%, transparent)"}},Hs))}),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:It?"0 20px 40px -20px rgba(0,0,0,0.5)":"0 20px 40px -20px rgba(0,0,0,0.15)"},children:[e.jsx($4e,{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(Cn,{className:"h-4 w-4",style:{color:"var(--c-accent)"}}),e.jsx("h2",{className:"text-lg font-semibold",style:{color:"var(--c-text)"},children:zs[T].title})]}),zs[T].subtitle&&e.jsx("p",{className:"text-xs mt-1 ml-6",style:{color:"var(--c-text-muted)"},children:zs[T].subtitle})]}),zs[T].fields]},T)}),e.jsxs("div",{className:"flex justify-between mt-8",children:[T>0?e.jsx("button",{type:"button",onClick:()=>P(As=>As-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",{}),T{if(T===0&&!L.trim()){ie.error("Please enter your first name");return}P(As=>As+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:()=>Yt(),disabled:k,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:k?e.jsxs(e.Fragment,{children:[e.jsx(us,{className:"h-4 w-4 animate-spin"}),"Sending..."]}):"Submit"})]}),T>0&&TP(As=>As+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(co,{className:"h-3 w-3"}),e.jsx("span",{children:"Powered by ReLevelUp"})]})})]})]})}const pU=()=>({trackEngagement:N.useCallback(async(t,n,r,a="view")=>{try{const{data:{user:i}}=await H.auth.getUser();if(!i)return;await H.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 RV({banners:s,autoPlayInterval:t=5e3,className:n}){const[r,a]=N.useState(0),[i,l]=N.useState(!1),{trackEngagement:o}=pU(),c=N.useCallback(f=>{o("newsletter",f.id,f.title,"click_link")},[o]),d=N.useCallback(()=>{a(f=>(f+1)%s.length)},[s.length]),u=N.useCallback(()=>{a(f=>(f-1+s.length)%s.length)},[s.length]),h=N.useCallback(f=>{a(f)},[]);if(N.useEffect(()=>{if(s.length<=1||i)return;const f=setInterval(d,t);return()=>clearInterval(f)},[s.length,i,t,d]),!s||s.length===0)return null;const m=s[r];return e.jsxs("div",{className:Ot("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:Ot("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(Fc,{className:"h-6 w-6"})}),e.jsx(B,{variant:"ghost",size:"icon",className:Ot("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(Qa,{className:"h-6 w-6"})})]}),s.length>1&&e.jsx("div",{className:"absolute bottom-3 left-1/2 -translate-x-1/2 flex gap-2",children:s.map((f,g)=>e.jsx("button",{onClick:()=>h(g),className:Ot("w-2 h-2 rounded-full transition-all duration-300",g===r?"bg-white w-6":"bg-white/50 hover:bg-white/70"),"aria-label":`Go to slide ${g+1}`},g))})]}),e.jsxs("div",{className:"bg-foreground rounded-b-xl px-5 py-3 flex items-center justify-between gap-4",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("h2",{className:"text-sm md:text-base font-semibold text-background truncate",children:m.title}),m.description&&e.jsx("p",{className:"text-xs text-background/70 truncate",children:m.description})]}),m.link_url&&e.jsx("a",{href:m.link_url,target:"_blank",rel:"noopener noreferrer",className:"shrink-0",onClick:()=>c(m),children:e.jsx(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"})})]})]})}function sjs(s){return"EST"}function yY(s){const n=new Intl.DateTimeFormat("en-US",{hour:"numeric",minute:"2-digit",hour12:!0,timeZone:"America/New_York"}).format(s),r=sjs();return`${n} ${r}`}function V9(s){const t=new Date,n=new Date(s),r=E7(n,-15),a=E7(n,30);return t>a?"ended":M2(t,{start:n,end:a})?"live":M2(t,{start:r,end:n})?"starting_soon":"upcoming"}function cqe(s){const t=V9(s);return t==="starting_soon"||t==="live"}const _rt=cqe,njs=({events:s,registrations:t,onNavigateToEvents:n})=>{const[r,a]=N.useState(new Date);N.useEffect(()=>{const f=setInterval(()=>{a(new Date)},3e4);return()=>clearInterval(f)},[]);const i=s.filter(f=>cqe(f.event_date));if(i.length===0)return null;const l=i[0],o=V9(l.event_date),c=t.find(f=>f.event_id===l.id),d=(c==null?void 0:c.zoom_join_url)||l.zoom_link,u=!!c,h=o==="live",m=h?{container:"from-red-500/10 via-red-500/5 to-primary/10 border-red-500/30",pulse:"from-red-500/5",indicator:"bg-red-500",text:"text-red-500",button:"bg-red-500 hover:bg-red-600",outlineButton:"border-red-500/50 text-red-500 hover:bg-red-500/10"}:{container:"from-amber-500/10 via-amber-500/5 to-primary/10 border-amber-500/30",pulse:"from-amber-500/5",indicator:"bg-amber-500",text:"text-amber-500",button:"bg-amber-500 hover:bg-amber-600",outlineButton:"border-amber-500/50 text-amber-500 hover:bg-amber-500/10"};return e.jsxs("div",{className:`relative mb-8 overflow-hidden rounded-xl bg-gradient-to-r ${m.container} border`,children:[e.jsx("div",{className:`absolute inset-0 bg-gradient-to-r ${m.pulse} to-transparent animate-pulse`}),e.jsx("div",{className:"relative p-4 sm:p-6",children:e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center gap-4",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs("div",{className:"relative flex items-center justify-center",children:[e.jsx("span",{className:`absolute inline-flex h-full w-full animate-ping rounded-full ${m.indicator} opacity-75`}),e.jsx("span",{className:`relative flex h-3 w-3 rounded-full ${m.indicator}`})]}),e.jsx("div",{className:`flex items-center gap-2 ${m.text} font-bold text-sm uppercase tracking-wider`,children:h?e.jsxs(e.Fragment,{children:[e.jsx(Y0,{className:"h-4 w-4"}),"Live Now"]}):e.jsxs(e.Fragment,{children:[e.jsx(Xr,{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 ${yY(new Date(l.event_date))}`:`Starts at ${yY(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(Tr,{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(Yn,{className:"h-4 w-4"}),"Register & Join"]})})]})})]})};function _f(){const{user:s}=Ls(),{data:t,isLoading:n}=mt({queryKey:["gmail-integration",s==null?void 0:s.id],enabled:!!(s!=null&&s.id),queryFn:async()=>{const{data:h,error:m}=await H.from("gmail_integrations").select("*").eq("user_id",s.id).maybeSingle();if(m)throw m;return h}}),{data:r,isLoading:a}=mt({queryKey:["user-verified-ses-sender",s==null?void 0:s.id],enabled:!!s,staleTime:60*1e3,queryFn:async()=>{const{data:h}=await H.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 rjs(){const{user:s}=Ls(),{isGmailConnected:t,hasVerifiedSes:n,isLoading:r}=_f(),[a,i]=N.useState(!1),[l,o]=N.useState(!1);N.useEffect(()=>{s!=null&&s.id&&H.from("onboarding_checklist_dismissed").select("id").eq("user_id",s.id).maybeSingle().then(({data:_})=>{i(!!_),o(!0)})},[s==null?void 0:s.id]);const{data:c,isLoading:d}=mt({queryKey:["new-agent-onboarding",s==null?void 0:s.id],enabled:!!(s!=null&&s.id),staleTime:3e4,queryFn:async()=>{const[_,b,k,A,T]=await Promise.all([H.from("profiles").select("avatar_url, phone, bio, name").eq("id",s.id).maybeSingle(),H.from("innercircle_contacts").select("id",{count:"exact",head:!0}).eq("owner_user_id",s.id),H.from("event_registrations").select("id",{count:"exact",head:!0}).eq("user_id",s.id),H.from("community_posts").select("id",{count:"exact",head:!0}).eq("user_id",s.id),H.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()]),P=_.data,I=!!(P!=null&&P.avatar_url&&(P!=null&&P.phone)&&(P!=null&&P.bio)),M=b.count||0,L=(k.count||0)>0,z=A.count||0;return{profile:P,profileComplete:I,contactsCount:M,contactsComplete:M>=5,eventsRegistered:L,communityComplete:z>0,nextOnboardingEvent:T.data||null}}}),u=t||n,h=[{id:"profile",complete:!!(c!=null&&c.profileComplete)},{id:"email",complete:u},{id:"contacts",complete:!!(c!=null&&c.contactsComplete)},{id:"event",complete:!!(c!=null&&c.eventsRegistered)},{id:"community",complete:!!(c!=null&&c.communityComplete)}],m=h.filter(_=>_.complete).length,f=h.length;return{steps:h,completedCount:m,totalCount:f,allComplete:m===f,dismissed:a,dismiss:async()=>{s!=null&&s.id&&(i(!0),await H.from("onboarding_checklist_dismissed").insert({user_id:s.id}))},reopen:async()=>{s!=null&&s.id&&(i(!1),await H.from("onboarding_checklist_dismissed").delete().eq("user_id",s.id))},data:c,isGmailConnected:t,hasVerifiedSes:n,loading:d||r||!l}}const ajs={profile:{title:"Complete Your Profile",description:"Add your headshot, phone, and short bio so contacts recognize you.",icon:Ro,accent:"from-[#2a4c64] to-[#406E71]",cta:"Edit Profile"},email:{title:"Set Up Email Sending",description:"Connect Gmail (recommended) or verify a Mass Email sender to send from your address.",icon:mn,accent:"from-[#406E71] to-[#5b9ea1]",cta:"Connect Email"},contacts:{title:"Add Your First Contacts",description:"Import your database or add contacts one at a time to start building your Inner Circle.",icon:Yn,accent:"from-[#c9a84c] to-[#e8c76f]",cta:"Add Contacts"},event:{title:"Register for New Member Onboarding",description:"Join our live LevelUp onboarding session to hit the ground running.",icon:ta,accent:"from-[#8b5cf6] to-[#a78bfa]",cta:"Register"},community:{title:"Say Hi in the Community",description:"Introduce yourself and connect with other LevelUp agents.",icon:xo,accent:"from-[#ec4899] to-[#f472b6]",cta:"Visit Community"}};function ijs(){var y,x;const s=tr(),{user:t}=Ls(),{steps:n,completedCount:r,totalCount:a,allComplete:i,dismissed:l,dismiss:o,data:c,loading:d}=rjs(),[u,h]=N.useState(!0);if(d||l||i)return null;const m=(((y=c==null?void 0:c.profile)==null?void 0:y.name)||((x=t==null?void 0:t.user_metadata)==null?void 0:x.name)||"there").split(" ")[0],f=r/a*100,g=async _=>{switch(_){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:k}=await H.from("event_registrations").insert({user_id:t.id,event_id:b.id});k&&!String(k.message).toLowerCase().includes("duplicate")?(ie.error("Could not register — opening events page."),s("/events")):ie.success(`You're registered for ${b.title}!`);break}case"community":s("/community");break}};return e.jsxs(_e,{className:"mb-6 overflow-hidden border-0 shadow-lg",children:[e.jsxs("div",{className:"relative bg-gradient-to-br from-[#2a4c64] via-[#345a75] to-[#406E71] p-6 md:p-8 text-white",children:[e.jsx("button",{onClick:o,className:"absolute top-4 right-4 p-1.5 rounded-full hover:bg-white/10 transition","aria-label":"Dismiss",children:e.jsx(hr,{className:"h-4 w-4"})}),e.jsxs("div",{className:"flex items-start gap-4",children:[e.jsx("div",{className:"hidden sm:flex h-12 w-12 rounded-xl bg-white/15 backdrop-blur items-center justify-center shrink-0",children:e.jsx(Cn,{className:"h-6 w-6 text-[#f5f0e0]"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("h2",{className:"text-xl md:text-2xl font-bold",children:["Welcome to LevelUp, ",m,"! 👋"]}),e.jsx("p",{className:"text-white/80 mt-1 text-sm md:text-base",children:"Let's get you set up in under 10 minutes."}),e.jsxs("div",{className:"mt-4 max-w-md",children:[e.jsxs("div",{className:"flex items-center justify-between text-xs mb-1.5 text-white/90",children:[e.jsxs("span",{className:"font-medium",children:[r," of ",a," complete"]}),e.jsxs("span",{children:[a-r," steps left"]})]}),e.jsx(ro,{value:f,className:"h-2 bg-white/20 [&>div]:bg-[#f5f0e0]"})]}),e.jsxs("div",{className:"mt-5 flex flex-wrap items-center gap-3",children:[e.jsxs(B,{onClick:()=>h(!0),className:"bg-[#f5f0e0] text-[#2a4c64] hover:bg-white font-semibold",children:["Continue Setup ",e.jsx(vi,{className:"h-4 w-4 ml-1.5"})]}),e.jsx("button",{onClick:()=>h(_=>!_),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(zy,{className:"h-4 w-4"})]}):e.jsxs(e.Fragment,{children:["Show steps ",e.jsx(Xo,{className:"h-4 w-4"})]})})]})]})]})]}),u&&e.jsx(De,{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(_=>{const b=ajs[_.id],k=b.icon;return e.jsx("div",{className:Ot("relative rounded-xl border p-4 transition-all group",_.complete?"bg-muted/40 border-muted":"bg-card hover:shadow-md hover:border-primary/40 cursor-pointer"),onClick:()=>!_.complete&&g(_.id),children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx("div",{className:Ot("h-10 w-10 rounded-lg flex items-center justify-center shrink-0 bg-gradient-to-br text-white",_.complete?"from-emerald-500 to-emerald-600":b.accent),children:_.complete?e.jsx(Hr,{className:"h-5 w-5"}):e.jsx(k,{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:Ot("font-semibold text-sm",_.complete&&"text-muted-foreground line-through"),children:b.title})}),e.jsx("p",{className:Ot("text-xs text-muted-foreground mt-1 leading-relaxed",_.complete&&"line-through"),children:b.description}),_.id==="event"&&!_.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"]}),!_.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:A=>{A.stopPropagation(),g(_.id)},children:[b.cta," ",e.jsx(vi,{className:"h-3 w-3 ml-1"})]})]}),_.complete&&e.jsx("span",{className:"text-xs font-medium text-emerald-600 shrink-0",children:"✓ Done"})]})},_.id)})})})]})}const K_=()=>mt({queryKey:["relationship-types"],queryFn:async()=>{const{data:s,error:t}=await H.from("relationship_types").select("*").order("sort_order");if(t)throw t;return s}}),Wy=s=>{const t=Ya(),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=H.from("innercircle_contacts").select(` *, lead_source_ref:lead_sources(id, name), tags:innercircle_contact_tags( id, contact_id, relationship_type_id, relationship_type:relationship_types(*) ) `).eq("owner_user_id",t).order("created_at",{ascending:!1}).order("first_name");return await r(a)},enabled:!!t})},ojs=s=>mt({queryKey:["innercircle-contact",s],queryFn:async()=>{const{data:t,error:n}=await H.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}),N4t=()=>{const s=Ya();return mt({queryKey:["innercircle-contact-counts",s],queryFn:async()=>{const{data:t,error:n}=await H.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})},e3e=()=>{const s=as(),t=Ya();return _t({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 H.from("innercircle_contacts").insert(i).select().single();if(o)throw o;if(r&&r.length>0){const{error:c}=await H.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"]}),xa({title:"Contact created successfully"})},onError:n=>{xa({title:"Error creating contact",description:n.message,variant:"destructive"})}})},dqe=()=>{const s=as();return _t({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 H.from("innercircle_contacts").update(o).eq("id",t).select().single();if(d)throw d;if(r!==void 0&&(await H.from("innercircle_contact_tags").delete().eq("contact_id",t),r.length>0)){const{error:u}=await H.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"]}),xa({title:"Contact updated successfully"})},onError:t=>{xa({title:"Error updating contact",description:t.message,variant:"destructive"})}})},k4t=()=>{const s=as();return _t({mutationFn:async({contactId:t,spouseContactId:n})=>{if(n){const{error:r}=await H.from("innercircle_contacts").update({spouse_contact_id:n}).eq("id",t);if(r)throw r;const{error:a}=await H.from("innercircle_contacts").update({spouse_contact_id:t}).eq("id",n);if(a)throw a}else{const{data:r}=await H.from("innercircle_contacts").select("spouse_contact_id").eq("id",t).single(),a=r==null?void 0:r.spouse_contact_id,{error:i}=await H.from("innercircle_contacts").update({spouse_contact_id:null}).eq("id",t);if(i)throw i;if(a){const{error:l}=await H.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"]}),xa({title:"Spouse link updated"})},onError:t=>{xa({title:"Error linking spouse",description:t.message,variant:"destructive"})}})},uqe=()=>{const s=as();return _t({mutationFn:async t=>{const{error:n}=await H.from("innercircle_contacts").delete().eq("id",t);if(n)throw n},onSuccess:()=>{s.invalidateQueries({queryKey:["innercircle-contacts"]}),s.invalidateQueries({queryKey:["innercircle-contact-counts"]}),xa({title:"Contact deleted successfully"})},onError:t=>{xa({title:"Error deleting contact",description:t.message,variant:"destructive"})}})},fU=()=>mt({queryKey:["action-types"],queryFn:async()=>{const{data:s,error:t}=await H.from("action_types").select("*").order("sort_order");if(t)throw t;return s}}),ljs=s=>mt({queryKey:["action-scripts",s],queryFn:async()=>{let t=H.from("action_scripts").select("*, action_type:action_types(*)");const{data:n,error:r}=await t;if(r)throw r;return n}}),cjs=()=>mt({queryKey:["touchpoint-plans"],queryFn:async()=>{const{data:s,error:t}=await H.from("touchpoint_plans").select(` *, items:touchpoint_plan_items( *, action_type:action_types(*), default_script:action_scripts(*) ) `).order("name");if(t)throw t;return s}}),djs=()=>{const s=as(),t=Ya();return _t({mutationFn:async({name:n,description:r})=>{const{data:a,error:i}=await H.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"]}),xa({title:"Plan created successfully"})},onError:n=>{xa({title:"Error creating plan",description:n.message,variant:"destructive"})}})},ujs=()=>{const s=as(),t=Ya();return _t({mutationFn:async({sourcePlanId:n,newName:r})=>{const{data:a,error:i}=await H.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 H.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 H.from("touchpoint_plan_items").insert(c);if(d)throw d}return l},onSuccess:()=>{s.invalidateQueries({queryKey:["touchpoint-plans"]}),xa({title:"Plan duplicated successfully",description:"You can now edit your copy of this plan."})},onError:n=>{xa({title:"Error duplicating plan",description:n.message,variant:"destructive"})}})},hjs=()=>{const s=as();return _t({mutationFn:async({id:t,name:n,description:r})=>{const{data:a,error:i}=await H.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"]}),xa({title:"Plan updated successfully"})}})},mjs=()=>{const s=as();return _t({mutationFn:async t=>{const{error:n}=await H.from("touchpoint_plans").delete().eq("id",t);if(n)throw n},onSuccess:()=>{s.invalidateQueries({queryKey:["touchpoint-plans"]}),xa({title:"Plan deleted successfully"})}})},pjs=()=>{const s=as();return _t({mutationFn:async({planId:t,items:n})=>{if(await H.from("touchpoint_plan_items").delete().eq("plan_id",t),n.length>0){const{error:r}=await H.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"]}),xa({title:"Plan schedule updated"})}})},fjs=()=>{const s=as();return _t({mutationFn:async({actionTypeId:t,title:n,scriptBody:r,emailSubject:a,tone:i})=>{const{data:{user:l}}=await H.auth.getUser(),{data:o,error:c}=await H.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"]}),xa({title:"Script created successfully"})},onError:t=>{xa({title:"Error creating script",description:t.message,variant:"destructive"})}})},gjs=()=>{const s=Ya();return mt({queryKey:["user-plan-enrollments",s],queryFn:async()=>{const{data:t,error:n}=await H.from("user_plan_enrollments").select(` *, plan:touchpoint_plans(*), relationship_type:relationship_types(*) `);if(n)throw n;return t},enabled:!!s})},xjs=()=>{const s=as(),t=Ya();return _t({mutationFn:async({planId:n,relationshipTypeId:r,active:a})=>{const{data:i}=await H.from("user_plan_enrollments").select("id").eq("plan_id",n).eq("relationship_type_id",r).maybeSingle();if(i){const{error:l}=await H.from("user_plan_enrollments").update({active:a}).eq("id",i.id);if(l)throw l}else if(a){const{error:l}=await H.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"]}),xa({title:"Plan enrollment updated"})}})},gU=(s=7)=>{const t=Ya();return mt({queryKey:["contact-touch-logs",t,s],queryFn:async()=>{const n=new Date;n.setDate(n.getDate()-s);const{data:r,error:a}=await H.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})},S4t=()=>{const s=Ya();return mt({queryKey:["contacts-last-touch",s],queryFn:async()=>{const{data:t,error:n}=await H.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})},yjs=(s=90)=>{const{data:t}=Wy(),{data:n}=S4t();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=as(),t=Ya();return _t({mutationFn:async({contactId:n,actionTypeId:r,scriptUsedId:a,notes:i,completedAt:l})=>{const{data:o,error:c}=await H.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"]}),xa({title:"Action completed!"});try{const[l,o]=await Promise.all([H.from("innercircle_contacts").select("email").eq("id",r.contactId).single(),H.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)&&H.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&&H.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{}}})},C4t="agentos_weekly_touch_goal",wrt=20,mNe=()=>{if(typeof window>"u")return wrt;const s=localStorage.getItem(C4t);if(s){const t=parseInt(s,10);if(!isNaN(t)&&t>0)return t}return wrt},A4t=s=>{localStorage.setItem(C4t,s.toString())},hqe=()=>{const{data:s}=gU(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=mNe();return{actionsThisWeek:r,weeklyGoal:i,streak:a,progress:Math.min(r/i*100,100)}},vjs=()=>{const s=Ya();return mt({queryKey:["contact-plan-cycles",s],queryFn:async()=>{const{data:t,error:n}=await H.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})},bjs=()=>{const s=as();return Ya(),_t({mutationFn:async()=>{var c;const{data:t}=await H.from("user_plan_enrollments").select("*").eq("active",!0);if(!t||t.length===0)return;const{data:n}=await H.auth.getUser(),r=(c=n==null?void 0:n.user)==null?void 0:c.id;if(!r)return;const{data:a}=await H.from("innercircle_contacts").select(` id, tags:innercircle_contact_tags(relationship_type_id) `).eq("owner_user_id",r);if(!a)return;const{data:i}=await H.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 H.from("contact_plan_cycles").insert(o);if(d)throw d}return o.length},onSuccess:t=>{s.invalidateQueries({queryKey:["contact-plan-cycles"]}),t&&t>0&&xa({title:`${t} contact(s) enrolled in plans`})}})},T4t=()=>{const s=Ya(),{data:t}=vjs(),{data:n}=gU(30);return mt({queryKey:["today-actions",s,t==null?void 0:t.length,n==null?void 0:n.length],queryFn:async()=>{var g;if(!t||t.length===0)return[];const{data:r}=await H.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(!((g=y.plan)!=null&&g.items)||y.plan.items.length===0||!y.contact||a.has(y.contact_id))continue;const x=new Date(y.cycle_start_date),b=Math.floor((i.getTime()-x.getTime())/(30.44*24*60*60*1e3))%12+1,k=y.plan.items.find(A=>A.month_number===b);if(k&&k.action_type){const A=`${y.contact_id}-${k.action_type_id}`;if(!c.has(A)){const{data:T}=await H.from("relationship_types").select("name").eq("id",y.relationship_type_id).single();l.push({contact:y.contact,actionType:k.action_type,script:k.default_script||void 0,planName:y.plan.name,relationshipTypeName:(T==null?void 0:T.name)||"",monthNumber:b})}}}const d=5,u=i.getDate(),h=l.sort((y,x)=>y.contact.first_name.localeCompare(x.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 _js(){const s=tr(),{data:t,isLoading:n}=T4t(),{data:r}=Wy(),a=hqe(),[i,l]=N.useState(mNe()),[o,c]=N.useState(""),[d,u]=N.useState(!1);N.useEffect(()=>{l(mNe())},[]);const h=()=>{const P=parseInt(o,10);if(isNaN(P)||P<1){xa({title:"Invalid goal",description:"Please enter a number greater than 0",variant:"destructive"});return}l(P),A4t(P),u(!1),xa({title:"Goal updated",description:`Weekly touch goal set to ${P}`})},m=()=>{c(i.toString()),u(!0)},f=ey(new Date),g=Ad(f,7),y=P=>{if(!P)return null;const I=P.split(/[-/T]/);if(I.length<3)return null;const M=parseInt(I[1],10)-1,L=parseInt(I[2],10);return isNaN(M)||isNaN(L)?null:new Date(f.getFullYear(),M,L)},x=(r==null?void 0:r.map(P=>{const I=y(P.birthday),M=y(P.home_anniversary),L=[];return I&&I>=f&&I<=g&&L.push({contact:P,type:"birthday",date:I,isToday:yd(I,f)}),M&&M>=f&&M<=g&&L.push({contact:P,type:"anniversary",date:M,isToday:yd(M,f)}),L}).flat().sort((P,I)=>P.date.getTime()-I.date.getTime()).slice(0,3))||[],_=(r==null?void 0:r.filter(P=>{const I=y(P.birthday),M=y(P.home_anniversary);return I&&yd(I,f)||M&&yd(M,f)}).length)||0,b=(t==null?void 0:t.length)||0,k=_+b,A=(a==null?void 0:a.actionsThisWeek)||0,T=(a==null?void 0:a.streak)||0;return n?e.jsx(_e,{className:"bg-gradient-to-br from-primary/5 via-primary/10 to-primary/5 border-primary/20",children:e.jsx(De,{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-primary/20 rounded-lg"}),e.jsxs("div",{className:"flex-1 space-y-2",children:[e.jsx("div",{className:"h-4 bg-primary/20 rounded w-1/3"}),e.jsx("div",{className:"h-3 bg-primary/10 rounded w-1/2"})]})]})})}):e.jsxs(_e,{className:"bg-gradient-to-br from-primary/5 via-primary/10 to-primary/5 border-primary/20",children:[e.jsxs(zt,{className:"pb-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs(qt,{className:"text-lg flex items-center gap-2",children:[e.jsx(Yn,{className:"h-5 w-5 text-primary"}),"Agent OS"]}),e.jsx("div",{className:"flex items-center gap-2",children:T>0&&e.jsxs(We,{variant:"secondary",className:"gap-1 bg-orange-500/10 text-orange-600 border-orange-200",children:[e.jsx(Cu,{className:"h-3 w-3"}),T," day streak"]})})]}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:[k>0?e.jsxs(e.Fragment,{children:[e.jsxs("span",{className:"text-primary font-medium",children:[k," tasks"]})," for today"]}):"No tasks for today",A>0&&e.jsxs("span",{className:"ml-2",children:["• ",e.jsx("span",{className:"text-emerald-600 font-medium",children:A})," touches this week"]})]})]}),e.jsxs(De,{className:"space-y-4",children:[e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsxs(B,{size:"sm",variant:"outline",className:"gap-1.5",onClick:P=>{P.stopPropagation(),s("/mission-control/contacts?new=true")},children:[e.jsx(Yl,{className:"h-3.5 w-3.5"}),"Add Contact"]}),e.jsxs(B,{size:"sm",variant:"outline",className:"gap-1.5",onClick:P=>{P.stopPropagation(),s("/mission-control")},children:[e.jsx(ga,{className:"h-3.5 w-3.5"}),"Log Touch"]}),e.jsxs(B,{size:"sm",variant:"outline",className:"gap-1.5 border-emerald-200 text-emerald-700 hover:bg-emerald-50 hover:text-emerald-800",onClick:P=>{P.stopPropagation(),s("/mission-control/video/record")},children:[e.jsx(na,{className:"h-3.5 w-3.5"}),"Quick Video"]}),e.jsxs(B,{size:"sm",variant:"outline",className:"gap-1.5",onClick:P=>{P.stopPropagation(),s("/mission-control/popbys")},children:[e.jsx(ii,{className:"h-3.5 w-3.5"}),"Pop-by Map"]}),e.jsxs(B,{size:"sm",variant:"outline",className:"gap-1.5 border-purple-200 text-purple-700 hover:bg-purple-50 hover:text-purple-800",onClick:P=>{P.stopPropagation(),s("/mission-control/pipeline")},children:[e.jsx(r3,{className:"h-3.5 w-3.5"}),"Pipeline"]})]}),e.jsxs("div",{className:"pt-3 border-t border-border/50",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(iu,{className:"h-4 w-4 text-primary"}),e.jsx("span",{className:"text-sm font-medium",children:"Weekly Goal"}),e.jsxs(Bs,{open:d,onOpenChange:u,children:[e.jsx(Ao,{asChild:!0,children:e.jsx("button",{onClick:m,className:"p-0.5 rounded hover:bg-muted transition-colors","aria-label":"Edit weekly goal",children:e.jsx(sc,{className:"h-3.5 w-3.5 text-muted-foreground hover:text-primary"})})}),e.jsxs(Fs,{className:"sm:max-w-[360px]",children:[e.jsxs(qs,{children:[e.jsx($s,{children:"Set Weekly Goal"}),e.jsx(Ar,{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(re,{htmlFor:"weekly-goal",children:"Weekly touch goal"}),e.jsx(we,{id:"weekly-goal",type:"number",min:"1",value:o,onChange:P=>c(P.target.value),placeholder:"20",onKeyDown:P=>{P.key==="Enter"&&h()}})]}),e.jsx(B,{onClick:h,className:"w-full",children:"Save Goal"})]})]})]})]}),e.jsxs("span",{className:"text-sm",children:[e.jsx("span",{className:"font-medium text-primary",children:A}),e.jsxs("span",{className:"text-muted-foreground",children:[" / ",i," touches"]})]})]}),e.jsx(ro,{value:Math.min(A/i*100,100),className:"h-2 bg-muted [&>div]:bg-primary"}),A>=i&&e.jsxs("p",{className:"text-xs text-emerald-600 mt-1.5 flex items-center gap-1",children:[e.jsx("span",{children:"🎉"})," Goal achieved! Keep the momentum going."]}),A0&&e.jsxs("p",{className:"text-xs text-muted-foreground mt-1.5",children:[i-A," more to hit your weekly goal"]})]}),x.length>0&&e.jsxs("div",{className:"pt-3 border-t border-border/50",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[e.jsx(Fm,{className:"h-4 w-4 text-pink-500"}),e.jsx("span",{className:"text-sm font-medium",children:"Upcoming Milestones"})]}),e.jsx("div",{className:"space-y-2",children:x.map((P,I)=>e.jsxs("div",{className:`flex items-center justify-between p-2 rounded-lg cursor-pointer transition-colors ${P.isToday?"bg-pink-500/10 hover:bg-pink-500/15":"bg-muted/50 hover:bg-muted"}`,onClick:M=>{M.stopPropagation(),s(`/mission-control/contacts/${P.contact.id}`)},children:[e.jsxs("div",{className:"flex items-center gap-2",children:[P.type==="birthday"?e.jsx(Fm,{className:"h-3.5 w-3.5 text-pink-500"}):e.jsx(_a,{className:"h-3.5 w-3.5 text-blue-500"}),e.jsxs("span",{className:"text-sm",children:[P.contact.first_name," ",P.contact.last_name]}),P.isToday&&e.jsx(We,{variant:"secondary",className:"text-[10px] px-1.5 py-0 bg-pink-500/20 text-pink-600",children:"Today!"})]}),e.jsxs("div",{className:"flex items-center gap-2 text-xs text-muted-foreground",children:[e.jsx("span",{children:P.isToday?P.type==="birthday"?"🎂":"🏠":Js(P.date,"EEE, MMM d")}),e.jsx(Qa,{className:"h-3 w-3"})]})]},`${P.contact.id}-${P.type}-${I}`))})]}),e.jsxs(B,{variant:"ghost",size:"sm",className:"w-full gap-1 text-muted-foreground hover:text-primary",onClick:()=>s("/mission-control"),children:["Open Agent OS",e.jsx(vi,{className:"h-4 w-4"})]})]})]})}function wjs(s){return mt({queryKey:["brokerage-content-categories",s],queryFn:async()=>{if(!s)return[];const{data:t,error:n}=await H.from("brokerage_content_categories").select("*").eq("brokerage_id",s).order("sort_order");if(n)throw n;return t},enabled:!!s})}function jjs(s,t){return mt({queryKey:["brokerage-content",s,t],queryFn:async()=>{if(!s)return[];let n=H.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 Njs(s,t=4){return mt({queryKey:["brokerage-content-recent",s,t],queryFn:async()=>{if(!s)return[];const{data:n,error:r}=await H.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 kjs(s){const t=as();return _t({mutationFn:async n=>{const{data:r,error:a}=await H.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 Sjs(){const s=as();return _t({mutationFn:async t=>{const{error:n}=await H.from("brokerage_content").delete().eq("id",t);if(n)throw n},onSuccess:()=>{s.invalidateQueries({queryKey:["brokerage-content"]}),s.invalidateQueries({queryKey:["brokerage-content-recent"]})}})}function Cjs(s){const t=as();return _t({mutationFn:async n=>{const{data:r,error:a}=await H.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 Ajs(){const s=as();return _t({mutationFn:async t=>{const{error:n}=await H.from("brokerage_content_categories").delete().eq("id",t);if(n)throw n},onSuccess:()=>{s.invalidateQueries({queryKey:["brokerage-content-categories"]})}})}function Tjs(s){const t=as();return _t({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 H.from("brokerage_content_categories").upsert(n,{onConflict:"brokerage_id,name"});if(r)throw r},onSuccess:()=>{t.invalidateQueries({queryKey:["brokerage-content-categories"]})}})}const Ejs={video:dd,pdf:Wr,link:cd,event:ta,graphic:zc},Mjs={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 Ljs(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 Pjs(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 Ijs({item:s}){const t=tr(),n=Ejs[s.content_type]||cd,r=Mjs[s.content_type]||"",[a,i]=N.useState(null),l=s.thumbnail_url||(s.content_type==="graphic"&&s.file_url?s.file_url:null)||(s.content_type==="video"?Ljs(s.url):null);N.useEffect(()=>{l||!s.url||s.content_type!=="video"||!Pjs(s.url)||fetch(`https://www.youtube.com/oembed?url=${encodeURIComponent(s.url)}&format=json`).then(c=>c.ok?c.json():null).then(c=>{c!=null&&c.thumbnail_url&&i(c.thumbnail_url)}).catch(()=>{})},[s.url,s.content_type,l]);const o=l||a;return e.jsxs(_e,{className:"group cursor-pointer overflow-hidden transition-all duration-200 hover:shadow-lg hover:border-primary/30",onClick:()=>t(`/brokerage-content/${s.id}`),children:[o?e.jsx("div",{className:"aspect-video bg-muted/50 overflow-hidden",children:e.jsx("img",{src:o,alt:s.title,className:"w-full h-full object-cover group-hover:scale-105 transition-transform duration-300",referrerPolicy:"no-referrer"})}):e.jsx("div",{className:"aspect-video bg-muted/20 flex items-center justify-center",children:e.jsx(n,{className:"h-8 w-8 text-muted-foreground/30"})}),e.jsxs(De,{className:"p-3",children:[e.jsx("div",{className:"flex items-center gap-1.5 mb-1.5",children:e.jsxs(We,{variant:"secondary",className:`text-[10px] px-1.5 py-0 ${r}`,children:[e.jsx(n,{className:"h-3 w-3 mr-0.5"}),s.content_type]})}),e.jsx("h4",{className:"font-medium text-sm text-foreground truncate group-hover:text-primary transition-colors",children:s.title}),s.content_type==="event"&&s.event_date&&e.jsx("p",{className:"text-xs text-primary mt-1 font-medium",children:Js(new Date(s.event_date),"MMM d · h:mm a")})]})]})}function Djs(){const{brokerageId:s}=Ls(),t=tr(),{data:n=[],isLoading:r}=Njs(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(Ti,{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(vi,{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(Ijs,{item:a},a.id))})]})}const E4t=()=>mt({queryKey:["listing-exchange-enabled"],queryFn:async()=>{const{data:s,error:t}=await H.from("feature_flags").select("enabled").eq("key","listing_exchange_enabled").maybeSingle();if(t)throw t;return(s==null?void 0:s.enabled)??!1}}),M4t=s=>{const{user:t,brokerageId:n}=Ls();return mt({queryKey:["listings",s,n],queryFn:async()=>{let r=H.from("listings").select(` *, photos:listing_photos(*), agent:profiles!listings_agent_id_fkey(id, name, email, brokerage_id, brokerage:brokerages(name)) `).eq("is_approved",!0).eq("is_public",!0);s!=null&&s.status&&(r=r.eq("status",s.status)),s!=null&&s.propertyType&&(r=r.eq("property_type",s.propertyType)),s!=null&&s.city&&(r=r.ilike("city",`%${s.city}%`)),s!=null&&s.minPrice&&(r=r.gte("price",s.minPrice)),s!=null&&s.maxPrice&&(r=r.lte("price",s.maxPrice)),s!=null&&s.openToReferrals&&(r=r.eq("open_to_referrals",!0));const{data:a,error:i}=await r;if(i)throw i;let l=a||[];if(n){const{data:o}=await H.from("profiles").select("id").eq("brokerage_id",n);if(o&&o.length>0){const c=o.map(h=>h.id);let d=H.from("listings").select(` *, photos:listing_photos(*), agent:profiles!listings_agent_id_fkey(id, name, email, brokerage_id, brokerage:brokerages(name)) `).eq("is_approved",!0).eq("share_with_brokerage",!0).eq("is_public",!1).in("agent_id",c);s!=null&&s.status&&(d=d.eq("status",s.status)),s!=null&&s.propertyType&&(d=d.eq("property_type",s.propertyType)),s!=null&&s.city&&(d=d.ilike("city",`%${s.city}%`)),s!=null&&s.minPrice&&(d=d.gte("price",s.minPrice)),s!=null&&s.maxPrice&&(d=d.lte("price",s.maxPrice)),s!=null&&s.openToReferrals&&(d=d.eq("open_to_referrals",!0));const{data:u}=await d;if(u){const h=new Set(l.map(f=>f.id)),m=u.filter(f=>!h.has(f.id));l=[...l,...m]}}}switch(s==null?void 0:s.sortBy){case"updated":l.sort((o,c)=>new Date(c.updated_at).getTime()-new Date(o.updated_at).getTime());break;case"price_asc":l.sort((o,c)=>o.price-c.price);break;case"price_desc":l.sort((o,c)=>c.price-o.price);break;default:l.sort((o,c)=>new Date(c.created_at).getTime()-new Date(o.created_at).getTime())}return l}})},L4t=()=>{const{user:s}=Ls();return mt({queryKey:["my-listings",s==null?void 0:s.id],queryFn:async()=>{if(!s)return[];const{data:t,error:n}=await H.from("listings").select(` *, photos:listing_photos(*) `).eq("agent_id",s.id).order("created_at",{ascending:!1});if(n)throw n;return t},enabled:!!s})},mqe=s=>{const{user:t}=Ls();return mt({queryKey:["listing",s],queryFn:async()=>{const{data:n,error:r}=await H.from("listings").select(` *, photos:listing_photos(*), agent:profiles!listings_agent_id_fkey(id, name, email, brokerage_id, brokerage:brokerages(name)), video:agent_videos!listings_video_id_fkey(id, playback_url, thumbnail_url, title, duration_seconds) `).eq("id",s).single();if(r)throw r;return t&&await H.from("listing_views").insert({listing_id:s,viewer_id:t.id}),n},enabled:!!s})},Rjs=()=>{const s=as(),{user:t}=Ls();return _t({mutationFn:async n=>{if(!t)throw new Error("Not authenticated");const{data:r,error:a}=await H.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"]})}})},Ojs=()=>{const s=as();return _t({mutationFn:async({agentId:t,...n})=>{const{data:r,error:a}=await H.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"]})}})},Fjs=()=>{const s=as();return _t({mutationFn:async({id:t,...n})=>{const{data:r,error:a}=await H.from("listings").update(n).eq("id",t).select().single();if(a)throw a;return r},onSuccess:t=>{s.invalidateQueries({queryKey:["listings"]}),s.invalidateQueries({queryKey:["my-listings"]}),s.invalidateQueries({queryKey:["listing",t.id]})}})},P4t=()=>{const s=as();return _t({mutationFn:async t=>{const{error:n}=await H.from("listings").delete().eq("id",t);if(n)throw n},onSuccess:()=>{s.invalidateQueries({queryKey:["listings"]}),s.invalidateQueries({queryKey:["my-listings"]})}})},zjs=()=>{const s=as();return _t({mutationFn:async({listingId:t,photoUrl:n,isPrimary:r=!1})=>{const{data:a,error:i}=await H.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"]})}})},Bjs=()=>{const s=as();return _t({mutationFn:async({photoId:t,listingId:n})=>{const{error:r}=await H.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"]})}})},$js=()=>{const s=as();return _t({mutationFn:async({photos:t})=>{var i;const n=t.map(l=>H.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"]})}})},Ujs=()=>{const s=as();return _t({mutationFn:async({photoId:t,listingId:n})=>{const{error:r}=await H.from("listing_photos").update({is_primary:!1}).eq("listing_id",n);if(r)throw r;const{error:a}=await H.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"]})}})},qjs=()=>{const{user:s}=Ls();return mt({queryKey:["saved-listings",s==null?void 0:s.id],queryFn:async()=>{if(!s)return[];const{data:t,error:n}=await H.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})},I4t=()=>{const s=as(),{user:t}=Ls();return _t({mutationFn:async n=>{if(!t)throw new Error("Not authenticated");const{data:r}=await H.from("listing_saves").select("id").eq("listing_id",n).eq("agent_id",t.id).maybeSingle();return r?(await H.from("listing_saves").delete().eq("id",r.id),{saved:!1}):(await H.from("listing_saves").insert({listing_id:n,agent_id:t.id}),{saved:!0})},onSuccess:()=>{s.invalidateQueries({queryKey:["saved-listings"]}),s.invalidateQueries({queryKey:["listings"]})}})},D4t=s=>{const{user:t}=Ls();return mt({queryKey:["listing-saved",s,t==null?void 0:t.id],queryFn:async()=>{if(!t)return!1;const{data:n}=await H.from("listing_saves").select("id").eq("listing_id",s).eq("agent_id",t.id).maybeSingle();return!!n},enabled:!!t&&!!s})},Vjs=()=>{const s=as(),{user:t}=Ls();return _t({mutationFn:async n=>{if(!t)throw new Error("Not authenticated");const{data:r}=await H.from("listing_follows").select("id").eq("listing_id",n).eq("agent_id",t.id).maybeSingle();return r?(await H.from("listing_follows").delete().eq("id",r.id),{following:!1}):(await H.from("listing_follows").insert({listing_id:n,agent_id:t.id}),{following:!0})},onSuccess:()=>{s.invalidateQueries({queryKey:["listing-following"]})}})},Hjs=s=>{const{user:t}=Ls();return mt({queryKey:["listing-following",s,t==null?void 0:t.id],queryFn:async()=>{if(!t)return!1;const{data:n}=await H.from("listing_follows").select("id").eq("listing_id",s).eq("agent_id",t.id).maybeSingle();return!!n},enabled:!!t&&!!s})},Gjs=()=>{const{user:s}=Ls();return _t({mutationFn:async({listingId:t,shareType:n})=>{if(!s)throw new Error("Not authenticated");const{error:r}=await H.from("listing_shares").insert({listing_id:t,sharing_agent_id:s.id,share_type:n});if(r)throw r}})},Wjs=()=>{const{user:s}=Ls();return mt({queryKey:["my-referrals",s==null?void 0:s.id],queryFn:async()=>{if(!s)return{sent:[],received:[]};const[t,n]=await Promise.all([H.from("listing_referrals").select(` *, listing:listings(*,photos:listing_photos(*)) `).eq("sender_agent_id",s.id).order("created_at",{ascending:!1}),H.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})},Kjs=()=>{const s=as(),{user:t}=Ls();return _t({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 H.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"]})}})},Yjs=()=>mt({queryKey:["listing-leaderboard"],queryFn:async()=>{const{data:s}=await H.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 H.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}}}),Zjs=()=>{const{user:s,brokerageId:t}=Ls();return mt({queryKey:["brokerage-listings",t],queryFn:async()=>{if(!s||!t)return[];const{data:n}=await H.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 H.from("listings").select(` *, photos:listing_photos(*), agent:profiles!listings_agent_id_fkey(id, name, email, brokerage_id, brokerage:brokerages(name)) `).in("agent_id",r).eq("is_approved",!0).order("created_at",{ascending:!1});if(i)throw i;return a},enabled:!!s&&!!t})},R4t=({className:s,variant:t="default"})=>e.jsx(We,{variant:"outline",className:Ot("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"}),Xjs={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"},Qjs={coming_soon:"Coming Soon",office_exclusive:"Office Exclusive",pre_market:"Pre-Market",active:"Active",under_contract:"Under Contract",sold:"Sold",withdrawn:"Withdrawn"};function Jjs(s){return s>=1e6?`$${(s/1e6).toFixed(1)}M`:`$${(s/1e3).toFixed(0)}K`}function e2s(){const s=tr(),{data:t,isLoading:n}=E4t(),{data:r,isLoading:a}=M4t({status:void 0,propertyType:void 0,sortBy:"newest"}),i=(r==null?void 0:r.filter(u=>u.is_approved&&u.is_public))||[],l=i.filter(u=>u.is_featured),o=i.filter(u=>!u.is_featured),c=[...l,...o].slice(0,6),d=n||a;return!d&&!t?null:d?e.jsx(_e,{className:"bg-gradient-to-br from-emerald-500/5 via-emerald-500/10 to-emerald-500/5 border-emerald-500/20",children:e.jsx(De,{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(R4t,{})]}),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(vi,{className:"h-4 w-4"})]})]}),c.length===0?e.jsx(_e,{className:"bg-muted/30 border-dashed",children:e.jsx(De,{className:"flex items-center justify-center py-8",children:e.jsxs("div",{className:"text-center",children:[e.jsx(_a,{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,f;const h=((m=u.photos)==null?void 0:m.find(g=>g.is_primary))||((f=u.photos)==null?void 0:f[0]);return e.jsxs("div",{onClick:()=>s(`/mission-control/listings/${u.id}`),className:"group cursor-pointer bg-card rounded-xl border border-border overflow-hidden transition-all duration-200 hover:shadow-lg hover:border-primary/30",children:[e.jsxs("div",{className:"aspect-[4/3] bg-muted/50 overflow-hidden relative",children:[h!=null&&h.photo_url?e.jsx("img",{src:h.photo_url,alt:`${u.city}, ${u.state}`,className:"w-full h-full object-cover group-hover:scale-105 transition-transform duration-300"}):e.jsx("div",{className:"w-full h-full flex items-center justify-center",children:e.jsx(_a,{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(We,{className:"gap-1 bg-amber-500 text-white border-0 text-[10px] px-1.5 py-0.5",children:[e.jsx(Wa,{className:"h-2.5 w-2.5 fill-current"}),"Featured"]})}),e.jsx("div",{className:"absolute top-1.5 right-1.5",children:e.jsx(We,{className:`text-[10px] px-1.5 py-0.5 ${Xjs[u.status]}`,children:Qjs[u.status]})})]}),e.jsxs("div",{className:"p-2",children:[e.jsx("p",{className:"font-bold text-sm text-foreground",children:Jjs(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 O4t(s=10,t){return mt({queryKey:["event-leaderboard",s,t],queryFn:async()=>{const{data:n}=await H.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 H.from("profiles").select("id").eq("brokerage_id",t);a=new Set((m==null?void 0:m.map(f=>f.id))||[])}const{data:i,error:l}=await H.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 H.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 F4t(s){return mt({queryKey:["user-attendance-stats",s],queryFn:async()=>{if(!s)return null;const{data:t,error:n}=await H.from("agent_attendance_stats").select("*").eq("user_id",s).single();if(n&&n.code!=="PGRST116")throw n;return t},enabled:!!s})}function z4t(s){return mt({queryKey:["user-badges",s],queryFn:async()=>{if(!s)return[];const{data:t,error:n}=await H.from("agent_badges").select("*").eq("user_id",s).order("earned_at",{ascending:!1});if(n)throw n;return t},enabled:!!s})}function B4t(s,t){return mt({queryKey:["user-rank",s,t],queryFn:async()=>{if(!s)return null;const{data:n}=await H.from("agent_attendance_stats").select("total_points").eq("user_id",s).single();if(!n)return null;const{data:r}=await H.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 H.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 H.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 t2s(){const{user:s,brokerageId:t,isAdmin:n}=Ls();tr();const r=!!t,[a,i]=N.useState("brokerage"),l=()=>{if(n)return null;if(r)return a==="global"?null:t},{data:o,isLoading:c}=O4t(5,l()),{data:d}=F4t(s==null?void 0:s.id),{data:u}=B4t(s==null?void 0:s.id,l()),{data:h}=z4t(s==null?void 0:s.id),m=n||r,f=()=>n?"Agent Leaderboard":r?a==="global"?"All LevelUp":"My Brokerage":"My Points";if(c)return e.jsxs(_e,{children:[e.jsx(zt,{className:"pb-2",children:e.jsxs(qt,{className:"text-base flex items-center gap-2",children:[e.jsx(gl,{className:"h-4 w-4 text-yellow-500"}),f()]})}),e.jsx(De,{children:e.jsx("div",{className:"space-y-2",children:[...Array(m?5:3)].map((y,x)=>e.jsx(xn,{className:"h-10 w-full"},x))})})]});const g=y=>y===0?e.jsx(gl,{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(_e,{children:[e.jsxs(zt,{className:"pb-2",children:[e.jsxs(qt,{className:"text-base flex items-center gap-2",children:[e.jsx(gl,{className:"h-4 w-4 text-yellow-500"}),f()]}),!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(De,{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((x,_)=>{var b,k,A;return e.jsxs("div",{className:`flex items-center gap-2 p-2 rounded-lg ${x.user_id===(s==null?void 0:s.id)?"bg-primary/10 border border-primary/20":_===0?"bg-yellow-500/10":""}`,children:[e.jsx("div",{className:"w-5 text-center",children:g(_)}),e.jsx(Ua,{className:"h-6 w-6",children:e.jsx(qa,{className:"text-xs",children:((k=(b=x.profile)==null?void 0:b.name)==null?void 0:k.charAt(0))||"?"})}),e.jsx("span",{className:"flex-1 text-sm font-medium truncate",children:((A=x.profile)==null?void 0:A.name)||"Unknown"}),e.jsx("span",{className:"text-sm font-bold text-primary",children:x.total_points})]},x.user_id)}),y.length===0&&e.jsx("div",{className:"text-center text-muted-foreground py-2 text-sm",children:"No data yet"})]}),e.jsxs(cr,{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(Io,{className:"h-4 w-4"}),"Spend Points in Reward Store",e.jsx(Qa,{className:"h-4 w-4"})]})]})]})}return e.jsxs(_e,{children:[e.jsx(zt,{className:"pb-2",children:e.jsxs(qt,{className:"text-base flex items-center gap-2",children:[e.jsx(gl,{className:"h-4 w-4 text-yellow-500"}),"My Points"]})}),e.jsx(De,{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(Cu,{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(ku,{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(cr,{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(Io,{className:"h-4 w-4"}),"Spend Points in Reward Store",e.jsx(Qa,{className:"h-4 w-4"})]})]}):e.jsxs("div",{className:"text-center text-muted-foreground py-4 text-sm",children:[e.jsx(Wa,{className:"h-8 w-8 mx-auto mb-2 text-muted-foreground/50"}),e.jsx("p",{children:"Attend events to earn points!"}),e.jsxs(cr,{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(Io,{className:"h-4 w-4"}),"Visit Reward Store",e.jsx(Qa,{className:"h-4 w-4"})]})]})})]})}const $R=()=>mt({queryKey:["lead-sources"],queryFn:async()=>{const{data:s,error:t}=await H.from("lead_sources").select("*").eq("is_active",!0).order("sort_order");if(t)throw t;return s}}),pqe=()=>{const s=as(),{user:t}=Ls();return _t({mutationFn:async n=>{const{data:r}=await H.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 H.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"]}),ie.success("Lead source added")},onError:n=>{ie.error("Failed to add lead source"),console.error(n)}})},s2s=()=>{const s=as();return _t({mutationFn:async({id:t,name:n})=>{const{error:r}=await H.from("lead_sources").update({name:n}).eq("id",t);if(r)throw r},onSuccess:()=>{s.invalidateQueries({queryKey:["lead-sources"]}),ie.success("Lead source updated")},onError:t=>{ie.error(t.message||"Failed to update lead source")}})},n2s=()=>{const s=as();return _t({mutationFn:async t=>{const{error:n}=await H.from("lead_sources").update({is_active:!1}).eq("id",t);if(n)throw n},onSuccess:()=>{s.invalidateQueries({queryKey:["lead-sources"]}),ie.success("Lead source removed")},onError:t=>{ie.error(t.message||"Failed to remove lead source")}})},fqe=(s,t)=>{const{user:n,isAdmin:r}=Ls(),a=r&&t?t:n==null?void 0:n.id;return mt({queryKey:["scorecard-transactions",s,a],queryFn:async()=>{let i=H.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})},gqe=s=>{const{user:t,isAdmin:n}=Ls(),r=n&&s?s:t==null?void 0:t.id;return mt({queryKey:["scorecard-transactions-all",r],queryFn:async()=>{const{data:a,error:i}=await H.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})},t3e=()=>{const s=as(),{user:t}=Ls();return _t({mutationFn:async n=>{const{data:r,error:a}=await H.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"]}),ie.success("Transaction added")},onError:n=>{ie.error("Failed to add transaction"),console.error(n)}})},r2s=()=>{const s=as();return _t({mutationFn:async({id:t,...n})=>{const{data:r,error:a}=await H.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"]}),ie.success("Transaction updated")},onError:t=>{ie.error("Failed to update transaction"),console.error(t)}})},a2s=()=>{const s=as();return _t({mutationFn:async t=>{const{error:n}=await H.from("scorecard_transactions").delete().eq("id",t);if(n)throw n},onSuccess:()=>{s.invalidateQueries({queryKey:["scorecard-transactions"]}),s.invalidateQueries({queryKey:["scorecard-transactions-all"]}),ie.success("Transaction deleted")},onError:t=>{ie.error("Failed to delete transaction"),console.error(t)}})},$4t=(s,t)=>{const{user:n,isAdmin:r}=Ls(),a=r&&t?t:n==null?void 0:n.id;return mt({queryKey:["scorecard-goals",s,a],queryFn:async()=>{const{data:i,error:l}=await H.from("scorecard_goals").select("*").eq("owner_user_id",a).eq("year",s).maybeSingle();if(l)throw l;return i},enabled:!!a})},i2s=()=>{const s=as(),{user:t}=Ls();return _t({mutationFn:async n=>{const{data:r,error:a}=await H.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]}),ie.success("Goals saved")},onError:n=>{ie.error("Failed to save goals"),console.error(n)}})},s3e=()=>{const{user:s}=Ls();return mt({queryKey:["scorecard-settings",s==null?void 0:s.id],queryFn:async()=>{const{data:t,error:n}=await H.from("scorecard_settings").select("*").eq("user_id",s.id).maybeSingle();if(n)throw n;return t},enabled:!!(s!=null&&s.id)})},o2s=()=>{const s=as(),{user:t}=Ls();return _t({mutationFn:async n=>{const{data:r,error:a}=await H.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"]}),ie.success("Settings saved")},onError:n=>{ie.error("Failed to save settings"),console.error(n)}})},U4t=(s,t)=>{const{data:n,isLoading:r}=fqe(s,t),{data:a,isLoading:i}=gqe(t),{data:l}=s3e(),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(T=>T.transaction_type==="buyer").length,h=d.filter(T=>T.transaction_type==="seller").length,m=d.reduce((T,P)=>T+Number(P.sale_price),0),f=d.reduce((T,P)=>T+(Number(P.commission_amount)||0),0),g=d.reduce((T,P)=>{const I=Number(P.commission_amount)||0;if(!I)return T;let M=I;return P.brokerage_split_pct&&(M-=I*(P.brokerage_split_pct/100)),P.team_split_pct&&(M-=I*(P.team_split_pct/100)),P.franchise_fee_pct&&(M-=I*(P.franchise_fee_pct/100)),P.referral_fee_pct&&(M-=I*(P.referral_fee_pct/100)),P.transaction_fee&&(M-=P.transaction_fee),T+Math.max(0,M)},0),y={};d.forEach(T=>{var I;const P=((I=T.lead_source)==null?void 0:I.name)||"Unknown";y[P]=(y[P]||0)+1});const x=Object.entries(y).map(([T,P])=>({name:T,count:P})).sort((T,P)=>P.count-T.count),_=x[0]||null,b={};d.forEach(T=>{const P=Tc(T.close_date).toLocaleString("default",{month:"short"});b[P]=(b[P]||0)+1});const A=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"].map(T=>({month:T,count:b[T]||0}));return{totalTransactions:d.length,buyerCount:u,sellerCount:h,totalVolume:m,averagePrice:d.length>0?m/d.length:0,totalCommission:o?f:0,totalNetToAgent:o?g:0,topLeadSource:_,transactionsByMonth:A,leadSourceBreakdown:x}};return{yearStats:c(n),lifetimeStats:c(a),isLoading:r||i,showCommission:o}},l2s=()=>{const{isAdmin:s}=Ls();return mt({queryKey:["agents-with-transactions"],queryFn:async()=>{const{data:t,error:n}=await H.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 H.from("profiles").select("id, name, email").in("id",r);if(i)throw i;return a},enabled:s})},YC={recency:40,touchpoints:30,transactions:20,referrals:10},jrt={warm:70,cooling:40};function c2s(s){return s===null?0:s<=14?YC.recency:s<=30?YC.recency*.85:s<=60?YC.recency*.65:s<=90?YC.recency*.4:s<=180?YC.recency*.2:YC.recency*.05}function d2s(s){const t=Math.min(s/12,1);return Math.round(YC.touchpoints*t)}function u2s(s){return s?YC.transactions:0}function h2s(){return 0}function m2s(s){return s>=jrt.warm?"warm":s>=jrt.cooling?"cooling":"at-risk"}function n3e(){const{data:s,isLoading:t}=Wy(),{data:n}=S4t(),{data:r}=gU(365),{data:a}=gqe(),i=N.useMemo(()=>{if(!s)return[];const o=new Date,c=TI(o,12),d={};r==null||r.forEach(h=>{new Date(h.completed_at)>=c&&(d[h.contact_id]=(d[h.contact_id]||0)+1)});const u=new Set((a==null?void 0:a.filter(h=>h.contact_id).map(h=>h.contact_id))||[]);return s.map(h=>{const m=(n==null?void 0:n[h.id])||null,f=m?wj(o,new Date(m)):null,g=d[h.id]||0,y=u.has(h.id),x=c2s(f),_=d2s(g),b=u2s(y),k=h2s(),A=Math.round(x+_+b+k),T={score:A,status:m2s(A),breakdown:{recency:Math.round(x),touchpoints:Math.round(_),transactions:Math.round(b),referrals:Math.round(k)},lastTouchDate:m,daysSinceTouch:f,touchCountLast12Months:g,hasTransaction:y};return{...h,relationshipScore:T}})},[s,n,r,a]),l=N.useMemo(()=>{const o=i.filter(m=>m.relationshipScore.status==="warm").length,c=i.filter(m=>m.relationshipScore.status==="cooling").length,d=i.filter(m=>m.relationshipScore.status==="at-risk").length,u=i.length,h=u>0?Math.round(i.reduce((m,f)=>m+f.relationshipScore.score,0)/u):0;return{warm:o,cooling:c,atRisk:d,total:u,averageScore:h}},[i]);return{contactsWithScores:i,stats:l,isLoading:t}}function q4t(){const s=tr(),{stats:t,contactsWithScores:n,isLoading:r}=n3e();if(r)return e.jsxs(_e,{children:[e.jsx(zt,{className:"pb-2",children:e.jsx(xn,{className:"h-5 w-40"})}),e.jsxs(De,{className:"space-y-4",children:[e.jsx(xn,{className:"h-20 w-full"}),e.jsx(xn,{className:"h-16 w-full"})]})]});if(t.total===0)return e.jsxs(_e,{children:[e.jsx(zt,{className:"pb-2",children:e.jsxs(qt,{className:"text-lg flex items-center gap-2",children:[e.jsx(Yn,{className:"h-5 w-5"}),"Relationship Health"]})}),e.jsxs(De,{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(_e,{children:[e.jsxs(zt,{className:"pb-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs(qt,{className:"text-lg flex items-center gap-2",children:[e.jsx(ml,{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(De,{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:"flex items-center justify-between text-sm",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"h-2.5 w-2.5 rounded-full bg-emerald-500"}),e.jsx("span",{children:"Warm"})]}),e.jsxs("span",{className:"font-medium",children:[t.warm," (",a,"%)"]})]}),e.jsx(ro,{value:a,className:"h-2 bg-muted [&>div]:bg-emerald-500"})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:"flex items-center justify-between text-sm",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"h-2.5 w-2.5 rounded-full bg-amber-500"}),e.jsx("span",{children:"Cooling Off"})]}),e.jsxs("span",{className:"font-medium",children:[t.cooling," (",i,"%)"]})]}),e.jsx(ro,{value:i,className:"h-2 bg-muted [&>div]:bg-amber-500"})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:"flex items-center justify-between text-sm",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"h-2.5 w-2.5 rounded-full bg-red-500"}),e.jsx("span",{children:"At Risk"})]}),e.jsxs("span",{className:"font-medium",children:[t.atRisk," (",l,"%)"]})]}),e.jsx(ro,{value:l,className:"h-2 bg-muted [&>div]:bg-red-500"})]})]}),o.length>0&&e.jsxs("div",{className:"pt-3 border-t",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[e.jsx(eN,{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(Qa,{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(Qa,{className:"h-4 w-4 ml-1"})]})]})]})}const p2s=()=>{var te;const{user:s,isAdmin:t}=Ls(),n=tr(),[r,a]=N.useState([]),[i,l]=N.useState([]),[o,c]=N.useState([]),[d,u]=N.useState([]),[h,m]=N.useState([]),[f,g]=N.useState([]),[y,x]=N.useState(new Set),[_,b]=N.useState([]),[k,A]=N.useState([]),[T,P]=N.useState([]),[I,M]=N.useState(null),[L,z]=N.useState(!0);N.useEffect(()=>{$()},[s]);const $=async()=>{var ne,me,ue,ce,ae;try{const[he,xe,ve,ge,be,Se,Ie,Me,Re,Be,Ne]=await Promise.all([H.from("user_tags").select("tag").eq("user_id",s==null?void 0:s.id),H.from("app_tiles").select("*").order("name"),H.from("user_favorites").select("app_id").eq("user_id",s==null?void 0:s.id),H.from("events").select("*").order("event_date",{ascending:!0}),H.from("event_registrations").select("event_id, zoom_join_url").eq("user_id",s==null?void 0:s.id),H.from("canva_templates").select("id, name, preview_image_url, publish_date").order("publish_date",{ascending:!1}).limit(4),H.from("resource_kits").select("id, name, description, featured_image_url, publish_date").eq("is_published",!0).order("publish_date",{ascending:!1}).limit(4),H.from("academy_videos").select("id, title, description, thumbnail_url, duration, publish_date").eq("is_published",!0).order("publish_date",{ascending:!1}).limit(4),H.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),H.from("dashboard_banners").select("id, title, description, image_url, link_url, link_text, placement, section_after").eq("is_active",!0).order("sort_order"),H.from("profiles").select("name").eq("id",s==null?void 0:s.id).single()]);(ne=Ne.data)!=null&&ne.name&&M(Ne.data.name);const Ge=((me=he.data)==null?void 0:me.map(Ye=>Ye.tag))||[],Ce=new Set(((ue=ve.data)==null?void 0:ue.map(Ye=>Ye.app_id))||[]);x(Ce);const Ae=(((ce=xe.data)==null?void 0:ce.filter(Ye=>!Ye.required_tags||Ye.required_tags.length===0?!0:Ye.required_tags.some(Je=>Ge.includes(Je))))||[]).sort((Ye,Je)=>Ye.name==="LevelUp Members Portal"?-1:Je.name==="LevelUp Members Portal"?1:0);a(Ae.slice(0,6));const Xe=((ae=ge.data)==null?void 0:ae.filter(Ye=>V9(Ye.event_date)!=="ended"))||[];l(Xe.slice(0,4)),b(be.data||[]),c(Se.data||[]),u(Ie.data||[]),m(Me.data||[]),g(Re.data||[]);const $e=Be.data||[];A($e.filter(Ye=>Ye.placement==="top")),P($e.filter(Ye=>Ye.placement==="between"))}catch(he){console.error("Error loading dashboard:",he),ie.error("Failed to load dashboard data")}finally{z(!1)}},V=async ne=>{var ue;const me=window.open("about:blank","_blank");try{await H.from("activity_logs").insert({user_id:s==null?void 0:s.id,app_id:ne.app_id,app_name:ne.name,user_agent:navigator.userAgent});const{data:ce,error:ae}=await H.functions.invoke("sso-launch",{body:{app_id:ne.app_id}});if(ae)throw ae;ce!=null&&ce.redirect_url?me&&!me.closed?(me.location.href=ce.redirect_url,(ue=me.focus)==null||ue.call(me)):window.location.assign(ce.redirect_url):(me==null||me.close(),ie.error("Launch link unavailable"))}catch(ce){me==null||me.close(),console.error("Error launching app:",ce),ie.error("Failed to launch app")}},W=ne=>_==null?void 0:_.some(me=>me.event_id===ne),G=ne=>{const me=_==null?void 0:_.find(ue=>ue.event_id===ne);return me==null?void 0:me.zoom_join_url};if(L)return e.jsx(Qs,{title:"Dashboard",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 your dashboard..."})]})})});const X=ne=>T.filter(me=>me.section_after===ne);return e.jsxs(Qs,{title:"Dashboard",children:[e.jsx(njs,{events:i,registrations:_,onNavigateToEvents:()=>n("/events")}),k.length>0&&e.jsx("div",{className:"mb-8",children:e.jsx(RV,{banners:k})}),e.jsx(ijs,{}),e.jsxs("div",{className:"mb-6",children:[e.jsxs("h2",{className:"text-2xl font-bold text-foreground",children:["Welcome back, ",(I||((te=s==null?void 0:s.user_metadata)==null?void 0:te.name)||"there").split(" ")[0],"!"]}),e.jsx("p",{className:"text-muted-foreground mt-1",children:"Are you ready to LevelUp today?"})]}),e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-3 gap-4 mb-8",children:[e.jsx(_js,{}),e.jsx(q4t,{}),e.jsx(t2s,{})]}),e.jsx(Djs,{}),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:"Upcoming Events"}),e.jsxs(B,{variant:"ghost",size:"sm",onClick:()=>n("/events"),className:"gap-1 text-muted-foreground hover:text-foreground",children:["View All ",e.jsx(vi,{className:"h-4 w-4"})]})]}),i.length===0?e.jsx(_e,{className:"bg-muted/30 border-dashed",children:e.jsx(De,{className:"flex items-center justify-center py-8",children:e.jsxs("div",{className:"text-center",children:[e.jsx(ta,{className:"h-8 w-8 text-muted-foreground/50 mx-auto mb-2"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"No upcoming events"})]})})}):e.jsx("div",{className:"bg-card rounded-xl border border-border overflow-hidden divide-y divide-border max-w-full",children:i.map(ne=>{const me=W(ne.id),ue=G(ne.id)||ne.zoom_link;return e.jsxs("div",{className:`flex items-start gap-3 sm:gap-4 p-3 sm:p-4 hover:bg-muted/50 transition-colors cursor-pointer group ${_rt(ne.event_date)?"bg-red-500/5 border-l-2 border-l-red-500":""}`,onClick:()=>n("/events"),children:[_rt(ne.event_date)?e.jsxs("div",{className:"flex-shrink-0 w-12 h-12 sm:w-14 sm:h-14 rounded-lg bg-red-500/10 flex flex-col items-center justify-center relative",children:[e.jsx("span",{className:"absolute inline-flex h-3 w-3 top-1 right-1 animate-ping rounded-full bg-red-500 opacity-75"}),e.jsx(Y0,{className:"h-5 w-5 text-red-500"}),e.jsx("span",{className:"text-[10px] font-bold text-red-500 uppercase mt-0.5",children:"Live"})]}):e.jsxs("div",{className:"flex-shrink-0 w-12 h-12 sm:w-14 sm:h-14 rounded-lg bg-primary/10 flex flex-col items-center justify-center",children:[e.jsx("span",{className:"text-[10px] sm:text-xs font-medium text-primary uppercase",children:new Intl.DateTimeFormat("en-US",{month:"short",timeZone:"America/New_York"}).format(new Date(ne.event_date))}),e.jsx("span",{className:"text-lg sm:text-xl font-bold text-primary",children:new Intl.DateTimeFormat("en-US",{day:"numeric",timeZone:"America/New_York"}).format(new Date(ne.event_date))})]}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("h4",{className:"font-medium text-sm sm:text-base text-foreground group-hover:text-primary transition-colors line-clamp-2 sm:truncate",children:ne.title}),e.jsxs("p",{className:"text-xs sm:text-sm text-muted-foreground mt-0.5",children:[new Intl.DateTimeFormat("en-US",{weekday:"long",timeZone:"America/New_York"}).format(new Date(ne.event_date))," at ",yY(new Date(ne.event_date))]})]}),e.jsx("div",{className:"hidden sm:flex flex-shrink-0",children:me?e.jsxs(B,{size:"sm",variant:"default",className:"gap-1",onClick:ce=>{ce.stopPropagation(),window.open(ue,"_blank")},children:[e.jsx(Tr,{className:"h-3.5 w-3.5"}),"Join"]}):e.jsxs("div",{className:"flex items-center gap-1 text-muted-foreground group-hover:text-primary transition-colors",children:[e.jsx("span",{className:"text-sm",children:"Register"}),e.jsx(Qa,{className:"h-4 w-4"})]})})]},ne.id)})})]}),X("events").length>0&&e.jsx("div",{className:"mb-10",children:e.jsx(RV,{banners:X("events")})}),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:"Academy Videos"}),e.jsxs(B,{variant:"ghost",size:"sm",onClick:()=>n("/academy"),className:"gap-1 text-muted-foreground hover:text-foreground",children:["View All ",e.jsx(vi,{className:"h-4 w-4"})]})]}),h.length===0?e.jsx(_e,{className:"bg-muted/30 border-dashed",children:e.jsx(De,{className:"flex items-center justify-center py-8",children:e.jsxs("div",{className:"text-center",children:[e.jsx(wp,{className:"h-8 w-8 text-muted-foreground/50 mx-auto mb-2"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"No academy videos available"})]})})}):e.jsx("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4",children:h.map(ne=>e.jsxs("div",{onClick:()=>n(`/academy/${ne.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-[3/2] bg-muted/50 overflow-hidden relative",children:[ne.thumbnail_url?e.jsx("img",{src:ne.thumbnail_url,alt:ne.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",children:e.jsx(wp,{className:"h-8 w-8 text-muted-foreground/50"})}),ne.duration&&e.jsx("span",{className:"absolute bottom-2 right-2 bg-black/70 text-white text-xs px-1.5 py-0.5 rounded",children:ne.duration})]}),e.jsx("div",{className:"p-3",children:e.jsx("h4",{className:"font-medium text-sm text-foreground line-clamp-2 group-hover:text-primary transition-colors",children:ne.title})})]},ne.id))})]}),X("academy").length>0&&e.jsx("div",{className:"mb-10",children:e.jsx(RV,{banners:X("academy")})}),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:"Resource Kits"}),e.jsxs(B,{variant:"ghost",size:"sm",onClick:()=>n("/toolbox"),className:"gap-1 text-muted-foreground hover:text-foreground",children:["View All ",e.jsx(vi,{className:"h-4 w-4"})]})]}),d.length===0?e.jsx(_e,{className:"bg-muted/30 border-dashed",children:e.jsx(De,{className:"flex items-center justify-center py-8",children:e.jsxs("div",{className:"text-center",children:[e.jsx(H0,{className:"h-8 w-8 text-muted-foreground/50 mx-auto mb-2"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"No resource kits available"})]})})}):e.jsx("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4",children:d.map(ne=>e.jsxs("div",{onClick:()=>n(`/toolbox/${ne.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.jsx("div",{className:"aspect-[3/2] bg-muted/50 overflow-hidden",children:ne.featured_image_url?e.jsx("img",{src:ne.featured_image_url,alt:ne.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",children:e.jsx(H0,{className:"h-8 w-8 text-muted-foreground/50"})})}),e.jsx("div",{className:"p-3",children:e.jsx("h4",{className:"font-medium text-sm text-foreground truncate group-hover:text-primary transition-colors",children:ne.name})})]},ne.id))})]}),X("toolbox").length>0&&e.jsx("div",{className:"mb-10",children:e.jsx(RV,{banners:X("toolbox")})}),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:"New Templates"}),e.jsxs(B,{variant:"ghost",size:"sm",onClick:()=>n("/templates"),className:"gap-1 text-muted-foreground hover:text-foreground",children:["View All ",e.jsx(vi,{className:"h-4 w-4"})]})]}),o.length===0?e.jsx(_e,{className:"bg-muted/30 border-dashed",children:e.jsx(De,{className:"flex items-center justify-center py-8",children:e.jsxs("div",{className:"text-center",children:[e.jsx(t3,{className:"h-8 w-8 text-muted-foreground/50 mx-auto mb-2"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"No templates available"})]})})}):e.jsx("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4",children:o.map(ne=>e.jsxs("div",{onClick:()=>n("/templates"),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.jsx("div",{className:"aspect-[3/2] bg-muted/50 overflow-hidden",children:ne.preview_image_url?e.jsx("img",{src:ne.preview_image_url,alt:ne.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(t3,{className:"h-8 w-8 text-muted-foreground/50"})})}),e.jsx("div",{className:"p-3",children:e.jsx("h4",{className:"font-medium text-sm text-foreground truncate group-hover:text-primary transition-colors",children:ne.name})})]},ne.id))})]}),X("templates").length>0&&e.jsx("div",{className:"mb-10",children:e.jsx(RV,{banners:X("templates")})}),e.jsx("div",{className:"mb-10",children:e.jsx(e2s,{})}),e.jsxs("section",{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(vi,{className:"h-4 w-4"})]})]}),r.length===0?e.jsx(_e,{className:"bg-muted/30 border-dashed",children:e.jsx(De,{className:"flex items-center justify-center py-12",children:e.jsxs("div",{className:"text-center",children:[e.jsx(Hv,{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:r.map(ne=>{const me=y.has(ne.id);return e.jsxs("div",{onClick:()=>V(ne),className:"group flex items-start gap-4 p-5 bg-card rounded-xl border border-border cursor-pointer transition-all duration-200 hover:shadow-lg hover:border-primary/30",children:[e.jsx("div",{className:"flex-shrink-0 w-14 h-14 rounded-xl bg-primary/10 flex items-center justify-center text-3xl",children:ne.icon}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("h3",{className:"font-semibold text-foreground group-hover:text-primary transition-colors truncate",children:ne.name}),e.jsx("p",{className:"text-sm text-muted-foreground mt-1 line-clamp-2",children:ne.description})]}),me&&e.jsx(Hv,{className:"h-5 w-5 text-primary fill-current flex-shrink-0"})]},ne.id)})})]}),e.jsxs("section",{className:"mt-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:"Additional Services"}),e.jsxs(B,{variant:"ghost",size:"sm",onClick:()=>n("/additional-services"),className:"gap-1 text-muted-foreground hover:text-foreground",children:["View All ",e.jsx(vi,{className:"h-4 w-4"})]})]}),f.length===0?e.jsx(_e,{className:"bg-muted/30 border-dashed",children:e.jsx(De,{className:"flex items-center justify-center py-8",children:e.jsxs("div",{className:"text-center",children:[e.jsx(Cn,{className:"h-8 w-8 text-muted-foreground/50 mx-auto mb-2"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"No additional services available"})]})})}):e.jsx("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4",children:f.map(ne=>e.jsxs("div",{onClick:()=>window.open(ne.signup_link_url,"_blank"),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.jsx("div",{className:"aspect-[4/3] bg-muted/50 overflow-hidden",children:ne.preview_image_url?e.jsx("img",{src:ne.preview_image_url,alt:ne.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",children:e.jsx(Cn,{className:"h-8 w-8 text-muted-foreground/50"})})}),e.jsxs("div",{className:"p-3",children:[e.jsx("h4",{className:"font-medium text-sm text-foreground truncate group-hover:text-primary transition-colors",children:ne.name}),ne.description&&e.jsx("p",{className:"text-xs text-muted-foreground mt-1 line-clamp-2",children:ne.description})]})]},ne.id))})]})]})};var V4t="AlertDialog",[f2s,HOn]=Um(V4t,[djt]),z3=djt(),H4t=s=>{const{__scopeAlertDialog:t,...n}=s,r=z3(t);return e.jsx(m4e,{...r,...n,modal:!0})};H4t.displayName=V4t;var g2s="AlertDialogTrigger",G4t=N.forwardRef((s,t)=>{const{__scopeAlertDialog:n,...r}=s,a=z3(n);return e.jsx(F$e,{...a,...r,ref:t})});G4t.displayName=g2s;var x2s="AlertDialogPortal",W4t=s=>{const{__scopeAlertDialog:t,...n}=s,r=z3(t);return e.jsx(p4e,{...r,...n})};W4t.displayName=x2s;var y2s="AlertDialogOverlay",K4t=N.forwardRef((s,t)=>{const{__scopeAlertDialog:n,...r}=s,a=z3(n);return e.jsx(aU,{...a,...r,ref:t})});K4t.displayName=y2s;var H9="AlertDialogContent",[v2s,b2s]=f2s(H9),_2s=C1t("AlertDialogContent"),Y4t=N.forwardRef((s,t)=>{const{__scopeAlertDialog:n,children:r,...a}=s,i=z3(n),l=N.useRef(null),o=jo(t,l),c=N.useRef(null);return e.jsx(las,{contentName:H9,titleName:Z4t,docsSlug:"alert-dialog",children:e.jsx(v2s,{scope:n,cancelRef:c,children:e.jsxs(iU,{role:"alertdialog",...i,...a,ref:o,onOpenAutoFocus:la(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(_2s,{children:r}),e.jsx(j2s,{contentRef:l})]})})})});Y4t.displayName=H9;var Z4t="AlertDialogTitle",X4t=N.forwardRef((s,t)=>{const{__scopeAlertDialog:n,...r}=s,a=z3(n);return e.jsx(SQ,{...a,...r,ref:t})});X4t.displayName=Z4t;var Q4t="AlertDialogDescription",J4t=N.forwardRef((s,t)=>{const{__scopeAlertDialog:n,...r}=s,a=z3(n);return e.jsx(CQ,{...a,...r,ref:t})});J4t.displayName=Q4t;var w2s="AlertDialogAction",e3t=N.forwardRef((s,t)=>{const{__scopeAlertDialog:n,...r}=s,a=z3(n);return e.jsx(AQ,{...a,...r,ref:t})});e3t.displayName=w2s;var t3t="AlertDialogCancel",s3t=N.forwardRef((s,t)=>{const{__scopeAlertDialog:n,...r}=s,{cancelRef:a}=b2s(t3t,n),i=z3(n),l=jo(t,a);return e.jsx(AQ,{...i,...r,ref:l})});s3t.displayName=t3t;var j2s=({contentRef:s})=>{const t=`\`${H9}\` requires a description for the component to be accessible for screen reader users. You can add a description to the \`${H9}\` by passing a \`${Q4t}\` 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 \`${H9}\`. 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 N.useEffect(()=>{var r;document.getElementById((r=s.current)==null?void 0:r.getAttribute("aria-describedby"))||console.warn(t)},[t,s]),null},N2s=H4t,k2s=G4t,S2s=W4t,n3t=K4t,r3t=Y4t,a3t=e3t,i3t=s3t,o3t=X4t,l3t=J4t;const Fl=N2s,Gf=k2s,C2s=S2s,c3t=N.forwardRef(({className:s,...t},n)=>e.jsx(n3t,{className:Ot("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}));c3t.displayName=n3t.displayName;const kl=N.forwardRef(({className:s,...t},n)=>e.jsxs(C2s,{children:[e.jsx(c3t,{}),e.jsx(r3t,{ref:n,className:Ot("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})]}));kl.displayName=r3t.displayName;const Sl=({className:s,...t})=>e.jsx("div",{className:Ot("flex flex-col space-y-2 text-center sm:text-left",s),...t});Sl.displayName="AlertDialogHeader";const Cl=({className:s,...t})=>e.jsx("div",{className:Ot("flex flex-col-reverse sm:flex-row sm:justify-end sm:space-x-2",s),...t});Cl.displayName="AlertDialogFooter";const Al=N.forwardRef(({className:s,...t},n)=>e.jsx(o3t,{ref:n,className:Ot("text-lg font-semibold",s),...t}));Al.displayName=o3t.displayName;const Tl=N.forwardRef(({className:s,...t},n)=>e.jsx(l3t,{ref:n,className:Ot("text-sm text-muted-foreground",s),...t}));Tl.displayName=l3t.displayName;const wl=N.forwardRef(({className:s,...t},n)=>e.jsx(a3t,{ref:n,className:Ot(DB(),s),...t}));wl.displayName=a3t.displayName;const El=N.forwardRef(({className:s,...t},n)=>e.jsx(i3t,{ref:n,className:Ot(DB({variant:"outline"}),"mt-2 sm:mt-0",s),...t}));El.displayName=i3t.displayName;const A2s=[{key:"contacts",label:"Contacts",icon:ga,description:"View, add, and edit contacts"},{key:"pipeline",label:"Deal Pipeline",icon:ET,description:"View, add, and move deals"},{key:"client_portal",label:"Client Portals",icon:H0,description:"Manage client portals on deals"},{key:"videos",label:"Videos",icon:na,description:"View and upload videos"},{key:"listings",label:"Listings",icon:_a,description:"View, create, and edit listings"},{key:"scorecard",label:"Scorecard",icon:lj,description:"View and add transactions"},{key:"popbys",label:"Pop-bys",icon:ii,description:"View and log pop-bys"},{key:"digital_card",label:"Digital Card",icon:U0,description:"Create and edit digital business card"},{key:"guest_book",label:"Guest Book",icon:Ep,description:"Manage open house guest books"},{key:"presentations",label:"Presentations",icon:ab,description:"Create and manage smart presentations"}];function T2s(){var I;const{user:s}=Ls(),[t,n]=N.useState([]),[r,a]=N.useState(!0),[i,l]=N.useState(!1),[o,c]=N.useState(!1),[d,u]=N.useState(null),[h,m]=N.useState({email:"",name:"",password:""}),[f,g]=N.useState("create"),[y,x]=N.useState(!1),[_,b]=N.useState(null);N.useEffect(()=>{s&&k()},[s]);const k=async()=>{if(s){a(!0);try{const{data:M,error:L}=await H.from("agent_assistant_assignments").select("id, assistant_id, permissions, created_at").eq("agent_id",s.id);if(L)throw L;if(M&&M.length>0){const z=M.map(W=>W.assistant_id),{data:$}=await H.from("profiles").select("id, name, email").in("id",z),V=M.map(W=>{const G=$==null?void 0:$.find(X=>X.id===W.assistant_id);return{...W,permissions:W.permissions,assistant_profile:G?{name:G.name||"",email:G.email||""}:void 0}});n(V)}else n([])}catch(M){console.error("Error loading assistants:",M)}finally{a(!1)}}},A=async()=>{if(s){if(f==="link"){if(!h.email.trim()){ie.error("Please enter the assistant's email");return}x(!0);try{const{data:{session:M}}=await H.auth.getSession();if(!M)throw new Error("Not authenticated");const{data:L,error:z}=await H.from("profiles").select("id, name, email").eq("email",h.email.trim().toLowerCase()).single();if(z||!L){ie.error("No account found with that email. Try creating a new assistant instead.");return}const{data:$}=await H.from("agent_assistant_assignments").select("id").eq("agent_id",s.id).eq("assistant_id",L.id);if($&&$.length>0){ie.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:L.id,role:"assistant",action:"add",agentId:s.id})}),W=await V.json();if(!V.ok)throw new Error(W.error||"Failed to assign assistant role");const{error:G}=await H.from("agent_assistant_assignments").insert({agent_id:s.id,assistant_id:L.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(G)throw G;ie.success(`${L.name||L.email} linked as your assistant`),l(!1),m({email:"",name:"",password:""}),k()}catch(M){console.error("Error linking assistant:",M),ie.error(M.message||"Failed to link assistant")}finally{x(!1)}return}if(!h.email.trim()||!h.name.trim()||!h.password.trim()){ie.error("Please fill in all fields");return}if(h.password.length<6){ie.error("Password must be at least 6 characters");return}x(!0);try{const{data:{session:M}}=await H.auth.getSession();if(!M)throw new Error("Not authenticated");const L=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"})}),z=await L.json();if(!L.ok)throw new Error(z.error||"Failed to create assistant account");const $=z.userId||z.id;if(!$)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:$,role:"assistant",action:"add",agentId:s.id})}),W=await V.json();if(!V.ok)throw new Error(W.error||"Failed to assign assistant role");const{error:G}=await H.from("agent_assistant_assignments").insert({agent_id:s.id,assistant_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(G)throw G;ie.success(`Assistant account created for ${h.name.trim()}`),l(!1),m({email:"",name:"",password:""}),k()}catch(M){console.error("Error adding assistant:",M),ie.error(M.message||"Failed to add assistant")}finally{x(!1)}}},T=async()=>{if(!(!d||!s))try{const{data:{session:M}}=await H.auth.getSession();if(!M)throw new Error("Not authenticated");const{error:L}=await H.from("agent_assistant_assignments").delete().eq("id",d.id);if(L)throw L;const{data:z}=await H.from("agent_assistant_assignments").select("id").eq("assistant_id",d.assistant_id);(!z||z.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"})}),ie.success("Assistant removed"),c(!1),u(null),k()}catch(M){console.error("Error removing assistant:",M),ie.error(M.message||"Failed to remove assistant")}},P=async(M,L,z)=>{b(M);try{const $=t.find(G=>G.id===M);if(!$)return;const V={...$.permissions,[L]:z},{error:W}=await H.from("agent_assistant_assignments").update({permissions:V}).eq("id",M);if(W)throw W;n(G=>G.map(X=>X.id===M?{...X,permissions:V}:X))}catch($){console.error("Error updating permissions:",$),ie.error("Failed to update permissions")}finally{b(null)}};return r?e.jsxs(_e,{children:[e.jsx(zt,{children:e.jsxs(qt,{className:"flex items-center gap-2",children:[e.jsx(Yn,{className:"h-5 w-5"}),"My Assistants"]})}),e.jsx(De,{children:e.jsx("div",{className:"flex items-center justify-center py-4",children:e.jsx(us,{className:"h-6 w-6 animate-spin text-muted-foreground"})})})]}):e.jsxs(e.Fragment,{children:[e.jsxs(_e,{children:[e.jsx(zt,{children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsxs(qt,{className:"flex items-center gap-2",children:[e.jsx(Yn,{className:"h-5 w-5"}),"My Assistants"]}),e.jsx(_r,{children:"Add assistants to help manage your Agent OS"})]}),e.jsxs(B,{size:"sm",onClick:()=>{g("create"),l(!0)},children:[e.jsx(nn,{className:"h-4 w-4 mr-1"}),"Add Assistant"]})]})}),e.jsx(De,{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 L,z,$,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(Ua,{className:"h-10 w-10",children:e.jsx(qa,{children:((z=(L=M.assistant_profile)==null?void 0:L.name)==null?void 0:z.split(" ").map(W=>W[0]).join("").toUpperCase())||"A"})}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:(($=M.assistant_profile)==null?void 0:$.name)||"Unknown"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:((V=M.assistant_profile)==null?void 0:V.email)||""})]}),e.jsxs(We,{variant:"secondary",className:"ml-2",children:[e.jsx(mf,{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(qn,{className:"h-4 w-4"})})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium mb-3",children:"Permissions"}),e.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-3",children:A2s.map(W=>{const G=W.icon;return e.jsxs("div",{className:"flex items-center justify-between p-2 rounded-md border",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(G,{className:"h-4 w-4 text-muted-foreground"}),e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium",children:W.label}),e.jsx("p",{className:"text-xs text-muted-foreground",children:W.description})]})]}),e.jsx(zn,{checked:M.permissions[W.key]||!1,onCheckedChange:X=>P(M.id,W.key,X),disabled:_===M.id})]},W.key)})})]})]},M.id)})})})]}),e.jsx(Bs,{open:i,onOpenChange:l,children:e.jsxs(Fs,{children:[e.jsxs(qs,{children:[e.jsx($s,{children:"Add Assistant"}),e.jsx(Ar,{children:f==="create"?"Create a new account for your assistant.":"Link an existing assistant account by their email."})]}),e.jsxs("div",{className:"flex gap-2 mb-2",children:[e.jsxs(B,{variant:f==="create"?"default":"outline",size:"sm",onClick:()=>g("create"),children:[e.jsx(nn,{className:"h-3 w-3 mr-1"}),"Create New"]}),e.jsxs(B,{variant:f==="link"?"default":"outline",size:"sm",onClick:()=>g("link"),children:[e.jsx(gc,{className:"h-3 w-3 mr-1"}),"Link Existing"]})]}),e.jsxs("div",{className:"space-y-4 py-2",children:[f==="create"&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{htmlFor:"assistant-name",children:"Name"}),e.jsx(we,{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(re,{htmlFor:"assistant-email",children:"Email"}),e.jsx(we,{id:"assistant-email",type:"email",value:h.email,onChange:M=>m({...h,email:M.target.value}),placeholder:"assistant@email.com"})]}),f==="create"&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{htmlFor:"assistant-password",children:"Temporary Password"}),e.jsx(we,{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(Cr,{children:[e.jsx(B,{variant:"outline",onClick:()=>l(!1),children:"Cancel"}),e.jsxs(B,{onClick:A,disabled:y,children:[y&&e.jsx(us,{className:"h-4 w-4 mr-2 animate-spin"}),f==="create"?"Create Assistant":"Link Assistant"]})]})]})}),e.jsx(Fl,{open:o,onOpenChange:c,children:e.jsxs(kl,{children:[e.jsxs(Sl,{children:[e.jsx(Al,{children:"Remove Assistant?"}),e.jsxs(Tl,{children:["This will remove ",(I=d==null?void 0:d.assistant_profile)==null?void 0:I.name,"'s access to your Agent OS. Their account will remain active but they won't be able to manage your data."]})]}),e.jsxs(Cl,{children:[e.jsx(El,{children:"Cancel"}),e.jsx(wl,{onClick:T,className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:"Remove"})]})]})})]})}function A0(s){this.content=s}A0.prototype={constructor:A0,find:function(s){for(var t=0;t>1}};A0.from=function(s){if(s instanceof A0)return s;var t=[];if(s)for(var n in s)t.push(n,s[n]);return new A0(t)};function d3t(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=d3t(a.content,i.content,n+1);if(l!=null)return l}n+=a.nodeSize}}function u3t(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 bv(r,a)}cutByIndex(t,n){return t==n?bv.empty:t==0&&n==this.content.length?this:new bv(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 bv(a,i)}addToStart(t){return new bv([t].concat(this.content),this.size+t.nodeSize)}addToEnd(t){return new bv(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?Jte(n+1,i):Jte(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 bv.empty;if(!Array.isArray(n))throw new RangeError("Invalid input for Fragment.fromJSON");return new bv(n.map(t.nodeFromJSON))}static fromArray(t){if(!t.length)return bv.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}};xh.none=[];class fNe extends Error{}class li{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=m3t(this.content,t+this.openStart,n);return r&&new li(r,this.openStart,this.openEnd)}removeBetween(t,n){return new li(h3t(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 li.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 li(Ca.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 li(t,r,a)}}li.empty=new li(Ca.empty,0,0);function h3t(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(h3t(i.content,t-a-1,n-a-1)))}function m3t(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=m3t(l.content,t-i-1,n,l);return o&&s.replaceChild(a,l.copy(o))}function E2s(s,t,n){if(n.openStart>s.depth)throw new fNe("Inserted content deeper than insertion position");if(s.depth-n.openStart!=t.depth-n.openEnd)throw new fNe("Inconsistent open depths");return p3t(s,t,n,0)}function p3t(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 ZW(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&&(AD(s.nodeAfter,r),i++));for(let o=i;oa&&ARe(s,t,a+1),l=r.depth>a&&ARe(n,r,a+1),o=[];return ZW(null,s,a,o),i&&l&&t.index(a)==n.index(a)?(f3t(i,l),AD(TD(i,g3t(s,t,n,r,a+1)),o)):(i&&AD(TD(i,gNe(s,t,a+1)),o),ZW(t,n,a,o),l&&AD(TD(l,gNe(n,r,a+1)),o)),ZW(r,null,a,o),new Ca(o)}function gNe(s,t,n){let r=[];if(ZW(null,s,n,r),s.depth>n){let a=ARe(s,t,n+1);AD(TD(a,gNe(s,t,n+1)),r)}return ZW(t,null,n,r),new Ca(r)}function M2s(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(Ca.from(a));return{start:a.resolveNoCache(s.openStart+n),end:a.resolveNoCache(a.content.size-s.openEnd-n)}}class vY{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 xNe(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 vY(n,r,i)}static resolveCached(t,n){let r=Nrt.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()+")"),x3t(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=Ca.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=Ca.fromJSON(t,n.content),i=t.nodeType(n.type).create(n.attrs,a,r);return i.type.checkAttrs(i.attrs),i}};HT.prototype.text=void 0;class yNe extends HT{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):x3t(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 yNe(this.type,this.attrs,this.text,t)}withText(t){return t==this.text?this:new yNe(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 x3t(s,t){for(let n=s.length-1;n>=0;n--)t=s[n].type.name+"("+t+")";return t}class aR{constructor(t){this.validEnd=t,this.next=[],this.wrapCache=[]}static parse(t,n){let r=new D2s(t,n);if(r.next==null)return aR.empty;let a=y3t(r);r.next&&r.err("Unexpected trailing text");let i=U2s($2s(a));return q2s(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(` `)}}aR.empty=new aR(!0);class D2s{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 y3t(s){let t=[];do t.push(R2s(s));while(s.eat("|"));return t.length==1?t[0]:{type:"choice",exprs:t}}function R2s(s){let t=[];do t.push(O2s(s));while(s.next&&s.next!=")"&&s.next!="|");return t.length==1?t[0]:{type:"seq",exprs:t}}function O2s(s){let t=B2s(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=F2s(s,t);else break;return t}function krt(s){/\D/.test(s.next)&&s.err("Expected number, got '"+s.next+"'");let t=Number(s.next);return s.pos++,t}function F2s(s,t){let n=krt(s),r=n;return s.eat(",")&&(s.next!="}"?r=krt(s):r=-1),s.eat("}")||s.err("Unclosed braced range"),{type:"range",min:n,max:r,expr:t}}function z2s(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 B2s(s){if(s.eat("(")){let t=y3t(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=z2s(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 $2s(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 aR(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:_3t(this.attrs,t)}create(t=null,n,r){if(this.isText)throw new Error("NodeType.create can't construct text nodes");return new HT(this,this.computeAttrs(t),Ca.from(n),xh.setFrom(r))}createChecked(t=null,n,r){return n=Ca.from(n),this.checkContent(n),new HT(this,this.computeAttrs(t),n,xh.setFrom(r))}createAndFill(t=null,n,r){if(t=this.computeAttrs(t),n=Ca.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(Ca.empty,!0);return i?new HT(this,t,n.append(i),xh.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 N3t(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 V2s(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 H2s{constructor(t,n,r){this.hasDefault=Object.prototype.hasOwnProperty.call(r,"default"),this.default=r.default,this.validate=typeof r.validate=="string"?V2s(t,n,r.validate):r.validate}get isRequired(){return!this.hasDefault}}class r3e{constructor(t,n,r,a){this.name=t,this.rank=n,this.schema=r,this.spec=a,this.attrs=j3t(t,a.attrs),this.excluded=null;let i=b3t(this.attrs);this.instance=i?new xh(this,i):null}create(t=null){return!t&&this.instance?this.instance:new xh(this,_3t(this.attrs,t))}static compile(t,n){let r=Object.create(null),a=0;return t.forEach((i,l)=>r[i]=new r3e(i,a++,n,l)),r}removeFromSet(t){for(var n=0;n-1}}class k3t{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=A0.from(t.nodes),n.marks=A0.from(t.marks||{}),this.nodes=Crt.compile(this.spec.nodes,this),this.marks=r3e.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]=aR.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?Art(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==""?[]:Art(this,l.split(" "))}this.nodeFromJSON=a=>HT.fromJSON(this,a),this.markFromJSON=a=>xh.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 Crt){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 yNe(r,r.defaultAttrs,t,xh.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 Art(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 G2s(s){return s.tag!=null}function W2s(s){return s.style!=null}let XW=class ERe{constructor(t,n){this.schema=t,this.rules=n,this.tags=[],this.styles=[];let r=this.matchedStyles=[];n.forEach(a=>{if(G2s(a))this.tags.push(a);else if(W2s(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 Ert(this,n,!1);return r.addAll(t,xh.none,n.from,n.to),r.finish()}parseSlice(t,n={}){let r=new Ert(this,n,!0);return r.addAll(t,xh.none,n.from,n.to),li.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=Mrt(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=Mrt(l)),l.node||l.ignore||l.mark||(l.node=a)})}return n}static fromSchema(t){return t.cached.domParser||(t.cached.domParser=new ERe(t,ERe.schemaRules(t)))}};const S3t={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},K2s={head:!0,noscript:!0,object:!0,script:!0,style:!0,title:!0},C3t={ol:!0,ul:!0},bY=1,MRe=2,QW=4;function Trt(s,t,n){return t!=null?(t?bY:0)|(t==="full"?MRe:0):s&&s.whitespace=="pre"?bY|MRe:n&~QW}class ese{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=xh.none,this.match=i||(l&QW?null:t.contentMatch)}findWrapping(t){if(!this.match){if(!this.type)return[];let n=this.type.contentMatch.fillBefore(Ca.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&bY)){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=Ca.from(this.content);return!t&&this.match&&(n=n.append(this.match.fillBefore(Ca.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&&!S3t.hasOwnProperty(t.parentNode.nodeName.toLowerCase())}}class Ert{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=Trt(null,n.preserveWhitespace,0)|(r?QW:0);a?i=new ese(a.type,a.attrs,xh.none,!0,n.topMatch||a.type.contentMatch,l):r?i=new ese(null,null,xh.none,!0,null,l):i=new ese(t.schema.topNodeType,null,xh.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&MRe?"full":this.localPreserveWS||(a.options&bY)>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):Lrt(d.type,t))?(c=d.addToSet(c),!1):!0),this.nodes.push(new ese(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|=bY)}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 Y2s(s){for(let t=s.firstChild,n=null;t;t=t.nextSibling){let r=t.nodeType==1?t.nodeName.toLowerCase():null;r&&C3t.hasOwnProperty(r)&&n?(n.appendChild(t),t=n):r=="li"?n=t:r&&(n=null)}}function Z2s(s,t){return(s.matches||s.msMatchesSelector||s.webkitMatchesSelector||s.mozMatchesSelector).call(s,t)}function Mrt(s){let t={};for(let n in s)t[n]=s[n];return t}function Lrt(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&&Uwe(uMe(r),a(t,n),null,t.attrs)}static renderSpec(t,n,r=null,a){return Uwe(t,n,r,a)}static fromSchema(t){return t.cached.domSerializer||(t.cached.domSerializer=new UR(this.nodesFromSchema(t),this.marksFromSchema(t)))}static nodesFromSchema(t){let n=Prt(t.nodes);return n.text||(n.text=r=>r.text),n}static marksFromSchema(t){return Prt(t.marks)}}function Prt(s){let t={};for(let n in s){let r=s[n].spec.toDOM;r&&(t[n]=r)}return t}function uMe(s){return s.document||window.document}const Irt=new WeakMap;function X2s(s){let t=Irt.get(s);return t===void 0&&Irt.set(s,t=Q2s(s)),t}function Q2s(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:f,contentDOM:g}=Uwe(s,m,n,r);if(c.appendChild(f),g){if(o)throw new RangeError("Multiple content holes");o=g}}}return{dom:c,contentDOM:o}}const A3t=65535,T3t=Math.pow(2,16);function J2s(s,t){return s+t*T3t}function Drt(s){return s&A3t}function eNs(s){return(s-(s&A3t))/T3t}const E3t=1,M3t=2,qwe=4,L3t=8;class LRe{constructor(t,n,r){this.pos=t,this.delInfo=n,this.recover=r}get deleted(){return(this.delInfo&L3t)>0}get deletedBefore(){return(this.delInfo&(E3t|qwe))>0}get deletedAfter(){return(this.delInfo&(M3t|qwe))>0}get deletedAcross(){return(this.delInfo&qwe)>0}}class b_{constructor(t,n=!1){if(this.ranges=t,this.inverted=n,!t.length&&b_.empty)return b_.empty}recover(t){let n=0,r=Drt(t);if(!this.inverted)for(let a=0;at)break;let d=this.ranges[o+i],u=this.ranges[o+l],h=c+d;if(t<=h){let m=d?t==c?-1:t==h?1:n:n,f=c+a+(m<0?0:u);if(r)return f;let g=t==(n<0?c:h)?null:J2s(o/3,t-c),y=t==c?M3t:t==h?E3t:qwe;return(n<0?t!=c:t!=h)&&(y|=L3t),new LRe(f,y,g)}a+=u-d}return r?t+a:new LRe(t+a,0,null)}touches(t,n){let r=0,a=Drt(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 _Y;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 pg.fromReplace(t,this.from,this.to,i)}invert(){return new e5(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 aT(n.pos,r.pos,this.mark)}merge(t){return t instanceof aT&&t.mark.eq(this.mark)&&this.from<=t.to&&this.to>=t.from?new aT(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 aT(n.from,n.to,t.markFromJSON(n.mark))}}Ky.jsonID("addMark",aT);class e5 extends Ky{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 li(xqe(n.content,a=>a.mark(this.mark.removeFromSet(a.marks)),t),n.openStart,n.openEnd);return pg.fromReplace(t,this.from,this.to,r)}invert(){return new aT(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 e5(n.pos,r.pos,this.mark)}merge(t){return t instanceof e5&&t.mark.eq(this.mark)&&this.from<=t.to&&this.to>=t.from?new e5(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 e5(n.from,n.to,t.markFromJSON(n.mark))}}Ky.jsonID("removeMark",e5);class iT extends Ky{constructor(t,n){super(),this.pos=t,this.mark=n}apply(t){let n=t.nodeAt(this.pos);if(!n)return pg.fail("No node at mark step's position");let r=n.type.create(n.attrs,null,this.mark.addToSet(n.marks));return pg.fromReplace(t,this.pos,this.pos+1,new li(Ca.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 Yx(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 Yx(n.from,n.to,n.gapFrom,n.gapTo,li.fromJSON(t,n.slice),n.insert,!!n.structure)}}Ky.jsonID("replaceAround",Yx);function PRe(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 tNs(s,t,n,r){let a=[],i=[],l,o;s.doc.nodesBetween(t,n,(c,d,u)=>{if(!c.isInline)return;let h=c.marks;if(!r.isInSet(h)&&u.type.allowsMarkType(r.type)){let m=Math.max(d,t),f=Math.min(d+c.nodeSize,n),g=r.addToSet(h);for(let y=0;ys.step(c)),i.forEach(c=>s.step(c))}function sNs(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 r3e){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 e5(l.from,l.to,l.style)))}function yqe(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 nNs(s,t,n){return(t==0||s.canReplace(t,s.childCount))&&(n==s.childCount||s.canReplace(0,n))}function xU(s){let n=s.parent.content.cutByIndex(s.startIndex,s.endIndex);for(let r=s.depth,a=0,i=0;;--r){let l=s.$from.node(r),o=s.$from.index(r)+a,c=s.$to.indexAfter(r)-i;if(rn;g--)y||r.index(g)>0?(y=!0,u=Ca.from(r.node(g).copy(u)),h++):c--;let m=Ca.empty,f=0;for(let g=i,y=!1;g>n;g--)y||a.after(g+1)=0;l--){if(r.size){let o=n[l].type.contentMatch.matchFragment(r);if(!o||!o.validEnd)throw new RangeError("Wrapper type given to Transform.wrap does not form valid content of its parent wrapper")}r=Ca.from(n[l].type.create(n[l].attrs,r))}let a=t.start,i=t.end;s.step(new Yx(a,i,a,i,new li(r,0,0),n.length,!0))}function lNs(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)&&cNs(s.doc,s.mapping.slice(i).map(o),r)){let d=null;if(r.schema.linebreakReplacement){let f=r.whitespace=="pre",g=!!r.contentMatch.matchType(r.schema.linebreakReplacement);f&&!g?d=!1:!f&&g&&(d=!0)}d===!1&&I3t(s,l,o,i),yqe(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 Yx(h,m,h+1,m-1,new li(Ca.from(r.create(c,null,l.marks)),0,0),1,!0)),d===!0&&P3t(s,l,o,i),!1}})}function P3t(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 I3t(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 cNs(s,t,n){let r=s.resolve(t),a=r.index();return r.parent.canReplaceWith(a,a+1,n)}function dNs(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 Yx(t,t+i.nodeSize,t+1,t+i.nodeSize-1,new li(Ca.from(l),0,0),1,!0))}function G9(s,t,n=1,r){let a=s.resolve(t),i=a.depth-n,l=r&&r[r.length-1]||a.parent;if(i<0||a.parent.type.spec.isolating||!a.parent.canReplace(a.index(),a.parent.childCount)||!l.type.validContent(a.parent.content.cutByIndex(a.index(),a.parent.childCount)))return!1;for(let d=a.depth-1,u=n-2;d>i;d--,u--){let h=a.node(d),m=a.index(d);if(h.type.spec.isolating)return!1;let f=h.content.cutByIndex(m,h.childCount),g=r&&r[u+1];g&&(f=f.replaceChild(0,g.type.create(g.attrs)));let y=r&&r[u]||h;if(!h.canReplace(m+1,h.childCount)||!y.type.validContent(f))return!1}let o=a.indexAfter(i),c=r&&r[0];return a.node(i).canReplaceWith(o,o,c?c.type:a.node(i+1).type)}function uNs(s,t,n=1,r){let a=s.doc.resolve(t),i=Ca.empty,l=Ca.empty;for(let o=a.depth,c=a.depth-n,d=n-1;o>c;o--,d--){i=Ca.from(a.node(o).copy(i));let u=r&&r[d];l=Ca.from(u?u.type.create(u.attrs,l):a.node(o).copy(l))}s.step(new dg(t,t,new li(i.append(l),n,n),!0))}function FE(s,t){let n=s.resolve(t),r=n.index();return D3t(n.nodeBefore,n.nodeAfter)&&n.parent.canReplace(r,r+1)}function hNs(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&&D3t(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 mNs(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);I3t(s,u.node(),u.before(),o)}l.inlineContent&&yqe(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 dg(d,c.map(t+n,-1),li.empty,!0)),r===!0){let u=s.doc.resolve(d);P3t(s,u.node(),u.before(),s.steps.length)}return s}function pNs(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 i3e(s,t,n=t,r=li.empty){if(t==n&&!r.size)return null;let a=s.resolve(t),i=s.resolve(n);return O3t(a,i,r)?new dg(t,n,r):new fNs(a,i,r).fit()}function O3t(s,t,n){return!n.openStart&&!n.openEnd&&s.start()==t.start()&&s.parent.canReplace(s.index(),t.index(),n.content)}class fNs{constructor(t,n,r){this.$from=t,this.$to=n,this.unplaced=r,this.frontier=[],this.placed=Ca.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=Ca.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 li(i,l,o);return t>-1?new Yx(r.pos,t,this.$to.pos,this.$to.end(),c,n):c.size||r.pos!=this.$to.pos?new dg(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=mMe(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(Ca.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=mMe(t,n);return!a.childCount||a.firstChild.isLeaf?!1:(this.unplaced=new li(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=mMe(t,n);if(a.childCount<=1&&n>0){let i=t.size-n<=n+a.size;this.unplaced=new li(qH(t,n-1,1),n-1,i?n-1:r)}else this.unplaced=new li(qH(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=x,u.push(F3t(y.mark(m.allowedMarks(y.marks)),d==1?c:0,d==o.childCount?f:-1)))}let g=d==o.childCount;g||(f=-1),this.placed=VH(this.placed,n,Ca.from(u)),this.frontier[n].match=h,g&&f<0&&r&&r.type==this.frontier[this.depth].type&&this.frontier.length>1&&this.closeFrontierNode();for(let y=0,x=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=pMe(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=VH(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=VH(this.placed,this.depth,Ca.from(t.create(n,r))),this.frontier.push({type:t,match:t.contentMatch})}closeFrontierNode(){let n=this.frontier.pop().match.fillBefore(Ca.empty,!0);n.childCount&&(this.placed=VH(this.placed,this.frontier.length,n))}}function qH(s,t,n){return t==0?s.cutByIndex(n,s.childCount):s.replaceChild(0,s.firstChild.copy(qH(s.firstChild.content,t-1,n)))}function VH(s,t,n){return t==0?s.append(n):s.replaceChild(s.childCount-1,s.lastChild.copy(VH(s.lastChild.content,t-1,n)))}function mMe(s,t){for(let n=0;n1&&(r=r.replaceChild(0,F3t(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(Ca.empty,!0)))),s.copy(r)}function pMe(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&&!gNs(n,i.content,l)?o:null}function gNs(s,t,n){for(let r=n;r0;m--,f--){let g=a.node(m).type.spec;if(g.defining||g.definingAsContext||g.isolating)break;l.indexOf(m)>-1?o=m:a.before(m)==f&&l.splice(1,0,-m)}let c=l.indexOf(o),d=[],u=r.openStart;for(let m=r.content,f=0;;f++){let g=m.firstChild;if(d.push(g),f==r.openStart)break;m=g.content}for(let m=u-1;m>=0;m--){let f=d[m],g=xNs(f.type);if(g&&!f.sameMarkup(a.node(Math.abs(o)-1)))u=m;else if(g||!f.type.isTextblock)break}for(let m=r.openStart;m>=0;m--){let f=(m+u+1)%(r.openStart+1),g=d[f];if(g)for(let y=0;y=0&&(s.replace(t,n,r),!(s.steps.length>h));m--){let f=l[m];f<0||(t=a.before(f),n=i.after(f))}}function z3t(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(Ca.empty,!0))}return s}function vNs(s,t,n,r){if(!r.isInline&&t==n&&s.doc.resolve(t).parent.content.size){let a=pNs(s.doc,t,r.type);a!=null&&(t=n=a)}s.replaceRange(t,n,new li(Ca.from(r),0,0))}function bNs(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=B3t(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 B3t(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 W9 extends Ky{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 pg.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 pg.fromReplace(t,this.pos,this.pos+1,new li(Ca.from(a),0,n.isLeaf?0:1))}getMap(){return b_.empty}invert(t){return new W9(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 W9(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 W9(n.pos,n.attr,n.value)}}Ky.jsonID("attr",W9);class wY extends Ky{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 pg.ok(r)}getMap(){return b_.empty}invert(t){return new wY(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 wY(n.attr,n.value)}}Ky.jsonID("docAttr",wY);let VB=class extends Error{};VB=function s(t){let n=Error.call(this,t);return n.__proto__=s.prototype,n};VB.prototype=Object.create(Error.prototype);VB.prototype.constructor=VB;VB.prototype.name="TransformError";let bqe=class{constructor(t){this.doc=t,this.steps=[],this.docs=[],this.mapping=new _Y}get before(){return this.docs.length?this.docs[0]:this.doc}step(t){let n=this.maybeStep(t);if(n.failed)throw new VB(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=li.empty){let a=i3e(this.doc,t,n,r);return a&&this.step(a),this}replaceWith(t,n,r){return this.replace(t,n,new li(Ca.from(r),0,0))}delete(t,n){return this.replace(t,n,li.empty)}insert(t,n){return this.replaceWith(t,t,n)}replaceRange(t,n,r){return yNs(this,t,n,r),this}replaceRangeWith(t,n,r){return vNs(this,t,n,r),this}deleteRange(t,n){return bNs(this,t,n),this}lift(t,n){return rNs(this,t,n),this}join(t,n=1){return mNs(this,t,n),this}wrap(t,n){return oNs(this,t,n),this}setBlockType(t,n=t,r,a=null){return lNs(this,t,n,r,a),this}setNodeMarkup(t,n,r=null,a){return dNs(this,t,n,r,a),this}setNodeAttribute(t,n,r){return this.step(new W9(t,n,r)),this}setDocAttribute(t,n){return this.step(new wY(t,n)),this}addNodeMark(t,n){return this.step(new iT(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 xh)n.isInSet(r.marks)&&this.step(new iR(t,n));else{let a=r.marks,i,l=[];for(;i=n.isInSet(a);)l.push(new iR(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 uNs(this,t,n,r),this}addMark(t,n,r){return tNs(this,t,n,r),this}removeMark(t,n,r){return sNs(this,t,n,r),this}clearIncompatible(t,n,r){return yqe(this,t,n,r),this}};const fMe=Object.create(null);class nl{constructor(t,n,r){this.$anchor=t,this.$head=n,this.ranges=r||[new $3t(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?s7(t.node(0),t.node(i),t.before(i+1),t.index(i),n,r):s7(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 gj(t.node(0))}static atStart(t){return s7(t,t,0,0,1)||new gj(t)}static atEnd(t){return s7(t,t,t.content.size,t.childCount,-1)||new gj(t)}static fromJSON(t,n){if(!n||!n.type)throw new RangeError("Invalid input for Selection.fromJSON");let r=fMe[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 fMe)throw new RangeError("Duplicate use of selection JSON ID "+t);return fMe[t]=n,n.prototype.jsonID=t,n}getBookmark(){return Vo.between(this.$anchor,this.$head).getBookmark()}}nl.prototype.visible=!0;class $3t{constructor(t,n){this.$from=t,this.$to=n}}let Ort=!1;function Frt(s){!Ort&&!s.parent.inlineContent&&(Ort=!0,console.warn("TextSelection endpoint not pointing into a node with inline content ("+s.parent.type.name+")"))}class Vo extends nl{constructor(t,n=t){Frt(t),Frt(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 nl.near(r);let a=t.resolve(n.map(this.anchor));return new Vo(a.parent.inlineContent?a:r,r)}replace(t,n=li.empty){if(super.replace(t,n),n==li.empty){let r=this.$from.marksAcross(this.$to);r&&t.ensureMarks(r)}}eq(t){return t instanceof Vo&&t.anchor==this.anchor&&t.head==this.head}getBookmark(){return new o3e(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 Vo(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=nl.findFrom(n,r,!0)||nl.findFrom(n,-r,!0);if(i)n=i.$head;else return nl.near(n,r)}return t.parent.inlineContent||(a==0?t=n:(t=(nl.findFrom(t,-r,!0)||nl.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&&Do.isSelectable(o))return Do.create(s,n-(a<0?o.nodeSize:0))}else{let c=s7(s,o,n+a,a<0?o.childCount:0,a,i);if(c)return c}n+=o.nodeSize*a}return null}function zrt(s,t,n){let r=s.steps.length-1;if(r{l==null&&(l=u)}),s.setSelection(nl.near(s.doc.resolve(l),n))}const Brt=1,tse=2,$rt=4;class wNs extends bqe{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|=tse,this}ensureMarks(t){return xh.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&tse)>0}addStep(t,n){super.addStep(t,n),this.updated=this.updated&~tse,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)||xh.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(nl.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|=$rt,this}get scrolledIntoView(){return(this.updated&$rt)>0}}function Urt(s,t){return!t||!s?s:s.bind(t)}class HH{constructor(t,n,r){this.name=t,this.init=Urt(n.init,r),this.apply=Urt(n.apply,r)}}const jNs=[new HH("doc",{init(s){return s.doc||s.schema.topNodeType.createAndFill()},apply(s){return s.doc}}),new HH("selection",{init(s,t){return s.selection||nl.atStart(t.doc)},apply(s){return s.selection}}),new HH("storedMarks",{init(s){return s.storedMarks||null},apply(s,t,n,r){return r.selection.$cursor?s.storedMarks:null}}),new HH("scrollToSelection",{init(){return 0},apply(s,t){return s.scrolledIntoView?t+1:t}})];class gMe{constructor(t,n){this.schema=t,this.plugins=[],this.pluginsByKey=Object.create(null),this.fields=jNs.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 HH(r.key,r.spec.state,r))})}}class R7{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 gMe(t.schema,t.plugins),i=new R7(a);return a.fields.forEach(l=>{if(l.name=="doc")i.doc=HT.fromJSON(t.schema,n.doc);else if(l.name=="selection")i.selection=nl.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 U3t(s,t,n){for(let r in s){let a=s[r];a instanceof Function?a=a.bind(t):r=="handleDOMEvents"&&(a=U3t(a,t,{})),n[r]=a}return n}class dx{constructor(t){this.spec=t,this.props={},t.props&&U3t(t.props,this,this.props),this.key=t.key?t.key.key:q3t("plugin")}getState(t){return t[this.key]}}const xMe=Object.create(null);function q3t(s){return s in xMe?s+"$"+ ++xMe[s]:(xMe[s]=0,s+"$")}class Yy{constructor(t="key"){this.key=q3t(t)}get(t){return t.config.pluginsByKey[this.key]}getState(t){return t[this.key]}}const P0=function(s){for(var t=0;;t++)if(s=s.previousSibling,!s)return t},HB=function(s){let t=s.assignedSlot||s.parentNode;return t&&t.nodeType==11?t.host:t};let IRe=null;const t4=function(s,t,n){let r=IRe||(IRe=document.createRange());return r.setEnd(s,n??s.nodeValue.length),r.setStart(s,t||0),r},NNs=function(){IRe=null},oR=function(s,t,n,r){return n&&(qrt(s,t,n,r,-1)||qrt(s,t,n,r,1))},kNs=/^(img|br|input|textarea|hr)$/i;function qrt(s,t,n,r,a){for(var i;;){if(s==n&&t==r)return!0;if(t==(a<0?0:Kw(s))){let l=s.parentNode;if(!l||l.nodeType!=1||VQ(s)||kNs.test(s.nodeName)||s.contentEditable=="false")return!1;t=P0(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?Kw(s):0}else return!1}}function Kw(s){return s.nodeType==3?s.nodeValue.length:s.childNodes.length}function SNs(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=Kw(s)}else if(s.parentNode&&!VQ(s))t=P0(s),s=s.parentNode;else return null}}function CNs(s,t){for(;;){if(s.nodeType==3&&t2),qw=GB||(E5?/Mac/.test(E5.platform):!1),G3t=E5?/Win/.test(E5.platform):!1,G4=/Android \d/.test(zE),HQ=!!Vrt&&"webkitFontSmoothing"in Vrt.documentElement.style,MNs=HQ?+(/\bAppleWebKit\/(\d+)/.exec(navigator.userAgent)||[0,0])[1]:0;function LNs(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 LS(s,t){return typeof s=="number"?s:s[t]}function PNs(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 Hrt(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=HB(l);continue}let o=l,c=o==i.body,d=c?LNs(i):PNs(o),u=0,h=0;if(t.topd.bottom-LS(r,"bottom")&&(h=t.bottom-t.top>d.bottom-d.top?t.top+LS(a,"top")-d.top:t.bottom-d.bottom+LS(a,"bottom")),t.leftd.right-LS(r,"right")&&(u=t.right-d.right+LS(a,"right")),u||h)if(c)i.defaultView.scrollBy(u,h);else{let f=o.scrollLeft,g=o.scrollTop;h&&(o.scrollTop+=h),u&&(o.scrollLeft+=u);let y=o.scrollLeft-f,x=o.scrollTop-g;t={left:t.left-y,top:t.top-x,right:t.right-y,bottom:t.bottom-x}}let m=c?"fixed":getComputedStyle(l).position;if(/^(fixed|sticky)$/.test(m))break;l=m=="absolute"?l.offsetParent:HB(l)}}function INs(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:W3t(s.dom)}}function W3t(s){let t=[],n=s.ownerDocument;for(let r=s;r&&(t.push({dom:r,top:r.scrollTop,left:r.scrollLeft}),s!=n);r=HB(r));return t}function DNs({refDOM:s,refTop:t,stack:n}){let r=s?s.getBoundingClientRect().top:0;K3t(n,r==0?0:r-t)}function K3t(s,t){for(let n=0;n=o){l=Math.max(g.bottom,l),o=Math.min(g.top,o);let y=g.left>t.left?g.left-t.left:g.right=(g.left+g.right)/2?1:0));continue}}else g.top>t.top&&!c&&g.left<=t.left&&g.right>=t.left&&(c=u,d={left:Math.max(g.left,Math.min(g.right,t.left)),top:g.top});!n&&(t.left>=g.right&&t.top>=g.top||t.left>=g.left&&t.top>=g.bottom)&&(i=h+1)}}return!n&&c&&(n=c,a=d,r=0),n&&n.nodeType==3?ONs(n,a):!n||r&&n.nodeType==1?{node:s,offset:i}:Y3t(n,a)}function ONs(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 wqe(s,t){return s.left>=t.left-1&&s.left<=t.right+1&&s.top>=t.top-1&&s.top<=t.bottom+1}function FNs(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 BNs(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 Z3t(s,t,n){let r=s.childNodes.length;if(r&&n.topt.top&&a++}let d;HQ&&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=BNs(s,r,a,t))}o==null&&(o=zNs(s,l,t));let c=s.docView.nearestDesc(l,!0);return{pos:o,inside:c?c.posAtStart-c.border:-1}}function Grt(s){return s.top=0&&a==r.nodeValue.length?(c--,u=1):n<0?c--:d++,OV(FC(t4(r,c,d),u),u<0)}if(!s.state.doc.resolve(t-(i||0)).parent.inlineContent){if(i==null&&a&&(n<0||a==Kw(r))){let c=r.childNodes[a-1];if(c.nodeType==1)return yMe(c.getBoundingClientRect(),!1)}if(i==null&&a=0)}if(i==null&&a&&(n<0||a==Kw(r))){let c=r.childNodes[a-1],d=c.nodeType==3?t4(c,Kw(c)-(l?0:1)):c.nodeType==1&&(c.nodeName!="BR"||!c.nextSibling)?c:null;if(d)return OV(FC(d,1),!1)}if(i==null&&a=0)}function OV(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 yMe(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 Q3t(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 qNs(s,t,n){let r=t.selection,a=n=="up"?r.$from:r.$to;return Q3t(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=X3t(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=t4(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 VNs=/[\u0590-\u08ac]/;function HNs(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?!VNs.test(r.parent.textContent)||!o.modify?n=="left"||n=="backward"?i:l:Q3t(s,t,()=>{let{focusNode:c,focusOffset:d,anchorNode:u,anchorOffset:h}=s.domSelectionRange(),m=o.caretBidiLevel;o.modify("move",n,"character");let f=r.depth?s.docView.domAfterPos(r.before()):s.dom,{focusNode:g,focusOffset:y}=s.domSelectionRange(),x=g&&!f.contains(g.nodeType==1?g:g.parentNode)||c==g&&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),x}):r.pos==r.start()||r.pos==r.end()}let Wrt=null,Krt=null,Yrt=!1;function GNs(s,t,n){return Wrt==t&&Krt==n?Yrt:(Wrt=t,Krt=n,Yrt=n=="up"||n=="down"?qNs(s,t,n):HNs(s,t,n))}const yj=0,Zrt=1,PI=2,M5=3;class GQ{constructor(t,n,r,a){this.parent=t,this.children=n,this.dom=r,this.contentDOM=a,this.dirty=yj,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;nP0(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 eCt){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 J3t&&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?P0(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=P0(m.dom)+1;break}t-=m.size}a==-1&&(a=0)}if(a>-1&&(d>n||o==this.children.length-1)){n=d;for(let u=o+1;ug&&ln){let g=o;o=c,c=g}let f=document.createRange();f.setEnd(c.node,c.offset),f.setStart(o.node,o.offset),d.removeAllRanges(),d.addRange(f)}}ignoreMutation(t){return!this.contentDOM&&t.type!="selection"}get contentLost(){return this.contentDOM&&this.contentDOM!=this.dom&&!this.dom.contains(this.contentDOM)}markDirty(t,n){for(let r=0,a=0;a=r:tr){let o=r+i.border,c=l-i.border;if(t>=o&&n<=c){this.dirty=t==r||n==l?PI:Zrt,t==o&&n==c&&(i.contentLost||i.dom.parentNode!=this.contentDOM)?i.dirty=M5:i.markDirty(t-o,n-o);return}else i.dirty=i.dom==i.contentDOM&&i.dom.parentNode==this.contentDOM&&!i.children.length?PI:M5}r=l}this.dirty=PI}markParentsDirty(){let t=1;for(let n=this.parent;n;n=n.parent,t++){let r=t==1?PI:Zrt;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==yj&&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 WNs extends GQ{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 lR extends GQ{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=UR.renderSpec(document,n.type.spec.toDOM(n,r),null,n.attrs)),new lR(t,n,l.dom,l.contentDOM||l.dom,l)}parseRule(){return this.dirty&M5||this.mark.type.spec.reparseInView?null:{mark:this.mark.type.name,attrs:this.mark.attrs,contentElement:this.contentDOM}}matchesMark(t){return this.dirty!=M5&&this.mark.eq(t)}markDirty(t,n){if(super.markDirty(t,n),this.dirty!=yj){let r=this.parent;for(;!r.node;)r=r.parent;r.dirty0&&(i=zRe(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}=UR.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=nCt(u,r,n),d?c=new KNs(t,n,r,a,u,h||null,m,d,i,l+1):n.isText?new c3e(t,n,r,a,u,m,i):new WT(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=()=>Ca.empty)}return t}matchesNode(t,n,r){return this.dirty==yj&&t.eq(this.node)&&vNe(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 ZNs(this,l&&l.node,t);JNs(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?xh.none:this.node.child(u).marks,r,t,u),c.placeWidget(d,t,a)},(d,u,h,m)=>{c.syncToMarks(d.marks,r,t,m);let f;c.findNodeMatch(d,u,h,m)||o&&t.state.selection.from>a&&t.state.selection.to-1&&c.updateNodeAt(d,u,h,f,t)||c.updateNextNode(d,u,h,t,m,a)||c.addNode(d,u,h,t,a),a+=d.nodeSize}),c.syncToMarks([],r,t,0),this.node.isTextblock&&c.addTextblockHacks(),c.destroyRest(),(c.changed||this.dirty==PI)&&(l&&this.protectLocalComposition(t,l),tCt(this.contentDOM,this.children,t),GB&&eks(this.dom))}localCompositionInfo(t,n){let{from:r,to:a}=t.state.selection;if(!(t.state.selection instanceof Vo)||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=tks(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 WNs(this,i,n,a);t.input.compositionNodes.push(l),this.children=zRe(this.children,r,r+a.length,t,l)}update(t,n,r,a){return this.dirty==M5||!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=yj}updateOuterDeco(t){if(vNe(t,this.outerDeco))return;let n=this.nodeDOM.nodeType!=1,r=this.dom;this.dom=sCt(this.dom,this.nodeDOM,FRe(this.outerDeco,this.node,n),FRe(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 Xrt(s,t,n,r,a){nCt(r,t,s);let i=new WT(void 0,s,t,n,r,r,r,a,0);return i.contentDOM&&i.updateChildren(a,0),i}class c3e extends WT{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==M5||this.dirty!=yj&&!this.inParent()||!t.sameMarkup(this.node)?!1:(this.updateOuterDeco(n),(this.dirty!=yj||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=yj,!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 c3e(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=M5)}get domAtom(){return!1}isText(t){return this.node.text==t}}class eCt extends GQ{parseRule(){return{ignore:!0}}matchesHack(t){return this.dirty==yj&&this.dom.nodeName==t}get domAtom(){return!0}get ignoreForCoords(){return this.dom.nodeName=="IMG"}}class KNs extends WT{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==M5)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 tCt(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=lR.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 lR)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 QNs(s,t){return s.type.side-t.type.side}function JNs(s,t,n,r){let a=t.locals(s),i=0;if(a.length==0){for(let d=0;di;)o.push(a[l++]);let g=i+m.nodeSize;if(m.isText){let x=g;l!x.inline):o.slice();r(m,y,t.forChild(i,m),f),i=g}}function eks(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 tks(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 zRe(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 jqe(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(l3e(n)){for(c=l;a&&!a.node;)a=a.parent;let h=a.node;if(a&&h.isAtom&&Do.isSelectable(h)&&a.parent&&!(h.isInline&&ANs(n.focusNode,n.focusOffset,a.dom))){let m=a.posBefore;d=new Do(l==m?o:r.resolve(m))}}else{if(n instanceof s.dom.ownerDocument.defaultView.Selection&&n.rangeCount>1){let h=l,m=l;for(let f=0;f{(n.anchorNode!=r||n.anchorOffset!=a)&&(t.removeEventListener("selectionchange",s.input.hideSelectionGuard),setTimeout(()=>{(!rCt(s)||s.state.selection.visible)&&s.dom.classList.remove("ProseMirror-hideselection")},20))})}function nks(s){let t=s.domSelection();if(!t)return;let n=s.cursorWrapper.dom,r=n.nodeName=="IMG";r?t.collapse(n.parentNode,P0(n)+1):t.collapse(n,0),!r&&!s.state.selection.visible&&ob&><=11&&(n.disabled=!0,n.disabled=!1)}function aCt(s,t){if(t instanceof Do){let n=s.docView.descAt(t.from);n!=s.lastSelectedViewDesc&&(sat(s),n&&n.selectNode(),s.lastSelectedViewDesc=n)}else sat(s)}function sat(s){s.lastSelectedViewDesc&&(s.lastSelectedViewDesc.parent&&s.lastSelectedViewDesc.deselectNode(),s.lastSelectedViewDesc=void 0)}function Nqe(s,t,n,r){return s.someProp("createSelectionBetween",a=>a(s,t,n))||Vo.between(t,n,r)}function nat(s){return s.editable&&!s.hasFocus()?!1:iCt(s)}function iCt(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 rks(s){let t=s.docView.domFromPos(s.state.selection.anchor,0),n=s.domSelectionRange();return oR(t.node,t.offset,n.anchorNode,n.anchorOffset)}function BRe(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&&nl.findFrom(i,t)}function ZC(s,t){return s.dispatch(s.state.tr.setSelection(t).scrollIntoView()),!0}function rat(s,t,n){let r=s.state.selection;if(r instanceof Vo)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 ZC(s,new Vo(r.$anchor,l))}else if(r.empty){if(s.endOfTextblock(t>0?"forward":"backward")){let a=BRe(s.state,t);return a&&a instanceof Do?ZC(s,a):!1}else if(!(qw&&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?Do.isSelectable(i)?ZC(s,new Do(t<0?s.state.doc.resolve(a.pos-i.nodeSize):a)):HQ?ZC(s,new Vo(s.state.doc.resolve(t<0?o:o+i.nodeSize))):!1:!1}}else return!1;else{if(r instanceof Do&&r.node.isInline)return ZC(s,new Vo(t>0?r.$to:r.$from));{let a=BRe(s.state,t);return a?ZC(s,a):!1}}}function bNe(s){return s.nodeType==3?s.nodeValue.length:s.childNodes.length}function eK(s,t){let n=s.pmViewDesc;return n&&n.size==0&&(t<0||s.nextSibling||s.nodeName!="BR")}function pF(s,t){return t<0?aks(s):iks(s)}function aks(s){let t=s.domSelectionRange(),n=t.focusNode,r=t.focusOffset;if(!n)return;let a,i,l=!1;for(xj&&n.nodeType==1&&r0){if(n.nodeType!=1)break;{let o=n.childNodes[r-1];if(eK(o,-1))a=n,i=--r;else if(o.nodeType==3)n=o,r=n.nodeValue.length;else break}}else{if(oCt(n))break;{let o=n.previousSibling;for(;o&&eK(o,-1);)a=n.parentNode,i=P0(o),o=o.previousSibling;if(o)n=o,r=bNe(n);else{if(n=n.parentNode,n==s.dom)break;r=0}}}l?$Re(s,n,r):a&&$Re(s,a,i)}function iks(s){let t=s.domSelectionRange(),n=t.focusNode,r=t.focusOffset;if(!n)return;let a=bNe(n),i,l;for(;;)if(r{s.state==a&&d3(s)},50)}function aat(s,t){let n=s.state.doc.resolve(t);if(!(z0||G3t)&&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 iat(s,t,n){let r=s.state.selection;if(r instanceof Vo&&!r.empty||n.indexOf("s")>-1||qw&&n.indexOf("m")>-1)return!1;let{$from:a,$to:i}=r;if(!a.parent.inlineContent||s.endOfTextblock(t<0?"up":"down")){let l=BRe(s.state,t);if(l&&l instanceof Do)return ZC(s,l)}if(!a.parent.inlineContent){let l=t<0?a:i,o=r instanceof gj?nl.near(l,t):nl.findFrom(l,t);return o?ZC(s,o):!1}return!1}function oat(s,t){if(!(s.state.selection instanceof Vo))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 lat(s,t,n){s.domObserver.stop(),t.contentEditable=n,s.domObserver.start()}function cks(s){if(!qy||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;lat(s,r,"true"),setTimeout(()=>lat(s,r,"false"),20)}return!1}function dks(s){let t="";return s.ctrlKey&&(t+="c"),s.metaKey&&(t+="m"),s.altKey&&(t+="a"),s.shiftKey&&(t+="s"),t}function uks(s,t){let n=t.keyCode,r=dks(t);if(n==8||qw&&n==72&&r=="c")return oat(s,-1)||pF(s,-1);if(n==46&&!t.shiftKey||qw&&n==68&&r=="c")return oat(s,1)||pF(s,1);if(n==13||n==27)return!0;if(n==37||qw&&n==66&&r=="c"){let a=n==37?aat(s,s.state.selection.from)=="ltr"?-1:1:-1;return rat(s,a,r)||pF(s,a)}else if(n==39||qw&&n==70&&r=="c"){let a=n==39?aat(s,s.state.selection.from)=="ltr"?1:-1:1;return rat(s,a,r)||pF(s,a)}else{if(n==38||qw&&n==80&&r=="c")return iat(s,-1,r)||pF(s,-1);if(n==40||qw&&n==78&&r=="c")return cks(s)||iat(s,1,r)||pF(s,1);if(r==(qw?"m":"c")&&(n==66||n==73||n==89||n==90))return!0}return!1}function kqe(s,t){s.someProp("transformCopied",f=>{t=f(t,s)});let n=[],{content:r,openStart:a,openEnd:i}=t;for(;a>1&&i>1&&r.childCount==1&&r.firstChild.childCount==1;){a--,i--;let f=r.firstChild;n.push(f.type.name,f.attrs!=f.type.defaultAttrs?f.attrs:null),r=f.content}let l=s.someProp("clipboardSerializer")||UR.fromSchema(s.state.schema),o=mCt(),c=o.createElement("div");c.appendChild(l.serializeFragment(r,{document:o}));let d=c.firstChild,u,h=0;for(;d&&d.nodeType==1&&(u=hCt[d.nodeName.toLowerCase()]);){for(let f=u.length-1;f>=0;f--){let g=o.createElement(u[f]);for(;c.firstChild;)g.appendChild(c.firstChild);c.appendChild(g),h++}d=c.firstChild}d&&d.nodeType==1&&d.setAttribute("data-pm-slice",`${a} ${i}${h?` -${h}`:""} ${JSON.stringify(n)}`);let m=s.someProp("clipboardTextSerializer",f=>f(t,s))||t.content.textBetween(0,t.content.size,` `);return{dom:c,text:m,slice:t}}function lCt(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 li(Ca.from(s.state.schema.text(t.replace(/\r\n?/g,` `))),0,0),s.someProp("transformPasted",m=>{o=m(o,s,!0)}),o;let h=s.someProp("clipboardTextParser",m=>m(t,a,r,s));if(h)o=h;else{let m=a.marks(),{schema:f}=s.state,g=UR.fromSchema(f);l=document.createElement("div"),t.split(/(?:\r\n?|\n)+/).forEach(y=>{let x=l.appendChild(document.createElement("p"));y&&x.appendChild(g.serializeNode(f.text(y,m)))})}}else s.someProp("transformPastedHTML",h=>{n=h(n,s)}),l=fks(n),HQ&&gks(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")||XW.fromSchema(s.state.schema)).parseSlice(l,{preserveWhitespace:!!(c||u),context:a,ruleFromNode(m){return m.nodeName=="BR"&&!m.nextSibling&&m.parentNode&&!hks.test(m.parentNode.nodeName)?{ignore:!0}:null}})),u)o=xks(cat(o,+u[1],+u[2]),u[4]);else if(o=li.maxOpen(mks(o.content,a),!0),o.openStart||o.openEnd){let h=0,m=0;for(let f=o.content.firstChild;h{o=h(o,s,c)}),o}const hks=/^(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 mks(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&&dCt(c,i,o,l[l.length-1],0))l[l.length-1]=d;else{l.length&&(l[l.length-1]=uCt(l[l.length-1],i.length));let u=cCt(o,c);l.push(u),a=a.matchType(u.type),i=c}}),l)return Ca.from(l)}return s}function cCt(s,t,n=0){for(let r=t.length-1;r>=n;r--)s=t[r].create(null,Ca.from(s));return s}function dCt(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(Ca.empty,!0))),s.replaceChild(t<0?0:s.childCount-1,l.copy(o))}function cat(s,t,n){return tn})),bMe.createHTML(s)):s}function fks(s){let t=/^(\s*]*>)*/.exec(s);t&&(s=s.slice(t[0].length));let n=mCt().createElement("div"),r=/<([a-z][^>\s]+)/i.exec(s),a;if((a=r&&hCt[r[1].toLowerCase()])&&(s=a.map(i=>"<"+i+">").join("")+s+a.map(i=>"").reverse().join("")),n.innerHTML=pks(s),a)for(let i=0;i=0;o-=2){let c=n.nodes[r[o]];if(!c||c.hasRequiredAttrs())break;a=Ca.from(c.create(r[o+1],a)),i++,l++}return new li(a,i,l)}const n1={},r1={},yks={touchstart:!0,touchmove:!0};class vks{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 bks(s){for(let t in n1){let n=n1[t];s.dom.addEventListener(t,s.input.eventHandlers[t]=r=>{wks(s,r)&&!Sqe(s,r)&&(s.editable||!(r.type in r1))&&n(s,r)},yks[t]?{passive:!0}:void 0)}qy&&s.dom.addEventListener("input",()=>null),qRe(s)}function oT(s,t){s.input.lastSelectionOrigin=t,s.input.lastSelectionTime=Date.now()}function _ks(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 qRe(s){s.someProp("handleDOMEvents",t=>{for(let n in t)s.input.eventHandlers[n]||s.dom.addEventListener(n,s.input.eventHandlers[n]=r=>Sqe(s,r))})}function Sqe(s,t){return s.someProp("handleDOMEvents",n=>{let r=n[t.type];return r?r(s,t)||t.defaultPrevented:!1})}function wks(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 jks(s,t){!Sqe(s,t)&&n1[t.type]&&(s.editable||!(t.type in r1))&&n1[t.type](s,t)}r1.keydown=(s,t)=>{let n=t;if(s.input.shiftKey=n.keyCode==16||n.shiftKey,!fCt(s,n)&&(s.input.lastKeyCode=n.keyCode,s.input.lastKeyCodeTime=Date.now(),!(G4&&z0&&n.keyCode==13)))if(n.keyCode!=229&&s.domObserver.forceFlush(),GB&&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,bI(13,"Enter"))),s.input.lastIOSEnter=0)},200)}else s.someProp("handleKeyDown",r=>r(s,n))||uks(s,n)?n.preventDefault():oT(s,"key")};r1.keyup=(s,t)=>{t.keyCode==16&&(s.input.shiftKey=!1)};r1.keypress=(s,t)=>{let n=t;if(fCt(s,n)||!n.charCode||n.ctrlKey&&!n.altKey||qw&&n.metaKey)return;if(s.someProp("handleKeyPress",a=>a(s,n))){n.preventDefault();return}let r=s.state.selection;if(!(r instanceof Vo)||!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 d3e(s){return{left:s.clientX,top:s.clientY}}function Nks(s,t){let n=t.x-s.clientX,r=t.y-s.clientY;return n*n+r*r<100}function Cqe(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 K9(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 kks(s,t){if(t==-1)return!1;let n=s.state.doc.resolve(t),r=n.nodeAfter;return r&&r.isAtom&&Do.isSelectable(r)?(K9(s,new Do(n)),!0):!1}function Sks(s,t){if(t==-1)return!1;let n=s.state.selection,r,a;n instanceof Do&&(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(Do.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?(K9(s,Do.create(s.state.doc,a)),!0):!1}function Cks(s,t,n,r,a){return Cqe(s,"handleClickOn",t,n,r)||s.someProp("handleClick",i=>i(s,t,r))||(a?Sks(s,n):kks(s,n))}function Aks(s,t,n,r){return Cqe(s,"handleDoubleClickOn",t,n,r)||s.someProp("handleDoubleClick",a=>a(s,t,r))}function Tks(s,t,n,r){return Cqe(s,"handleTripleClickOn",t,n,r)||s.someProp("handleTripleClick",a=>a(s,t,r))||Eks(s,n,r)}function Eks(s,t,n){if(n.button!=0)return!1;let r=s.state.doc;if(t==-1)return r.inlineContent?(K9(s,Vo.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)K9(s,Vo.create(r,o+1,o+1+l.content.size));else if(Do.isSelectable(l))K9(s,Do.create(r,o));else continue;return!0}}function Aqe(s){return _Ne(s)}const pCt=qw?"metaKey":"ctrlKey";n1.mousedown=(s,t)=>{let n=t;s.input.shiftKey=n.shiftKey;let r=Aqe(s),a=Date.now(),i="singleClick";a-s.input.lastClick.time<500&&Nks(n,s.input.lastClick)&&!n[pCt]&&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(d3e(n));l&&(i=="singleClick"?(s.input.mouseDown&&s.input.mouseDown.done(),s.input.mouseDown=new Mks(s,l,n,!!r)):(i=="doubleClick"?Aks:Tks)(s,l.pos,l.inside,n)?n.preventDefault():oT(s,"pointer"))};class Mks{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[pCt],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 Do&&d.from<=l&&d.to>l)&&(this.mightDrag={node:i,pos:l,addAttr:!!(this.target&&!this.target.draggable),setUneditable:!!(this.target&&xj&&!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)),oT(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(()=>d3(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(d3e(t))),this.updateAllowDefault(t),this.allowDefault||!n?oT(this.view,"pointer"):Cks(this.view,n.pos,n.inside,t,this.selectNode)?t.preventDefault():t.button==0&&(this.flushed||qy&&this.mightDrag&&!this.mightDrag.node.isAtom||z0&&!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)?(K9(this.view,nl.near(this.view.state.doc.resolve(n.pos))),t.preventDefault()):oT(this.view,"pointer")}move(t){this.updateAllowDefault(t),oT(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)}}n1.touchstart=s=>{s.input.lastTouch=Date.now(),Aqe(s),oT(s,"pointer")};n1.touchmove=s=>{s.input.lastTouch=Date.now(),oT(s,"pointer")};n1.contextmenu=s=>Aqe(s);function fCt(s,t){return s.composing?!0:qy&&Math.abs(t.timeStamp-s.input.compositionEndedAt)<500?(s.input.compositionEndedAt=-2e8,!0):!1}const Lks=G4?5e3:-1;r1.compositionstart=r1.compositionupdate=s=>{if(!s.composing){s.domObserver.flush();let{state:t}=s,n=t.selection.$to;if(t.selection instanceof Vo&&(t.storedMarks||!n.textOffset&&n.parentOffset&&n.nodeBefore.marks.some(r=>r.type.spec.inclusive===!1)||z0&&G3t&&Pks(s)))s.markCursor=s.state.storedMarks||n.marks(),_Ne(s,!0),s.markCursor=null;else if(_Ne(s,!t.selection.empty),xj&&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}gCt(s,Lks)};function Pks(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"}r1.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++,gCt(s,20))};function gCt(s,t){clearTimeout(s.input.composingTimeout),t>-1&&(s.input.composingTimeout=setTimeout(()=>_Ne(s),t))}function xCt(s){for(s.composing&&(s.input.composing=!1,s.input.compositionEndedAt=Dks());s.input.compositionNodes.length>0;)s.input.compositionNodes.pop().markParentsDirty()}function Iks(s){let t=s.domSelectionRange();if(!t.focusNode)return null;let n=SNs(t.focusNode,t.focusOffset),r=CNs(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 Dks(){let s=document.createEvent("Event");return s.initEvent("event",!0,!0),s.timeStamp}function _Ne(s,t=!1){if(!(G4&&s.domObserver.flushingSoon>=0)){if(s.domObserver.forceFlush(),xCt(s),t||s.docView&&s.docView.dirty){let n=jqe(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 Rks(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 jY=ob&><15||GB&&MNs<604;n1.copy=r1.cut=(s,t)=>{let n=t,r=s.state.selection,a=n.type=="cut";if(r.empty)return;let i=jY?null:n.clipboardData,l=r.content(),{dom:o,text:c}=kqe(s,l);i?(n.preventDefault(),i.clearData(),i.setData("text/html",o.innerHTML),i.setData("text/plain",c)):Rks(s,o),a&&s.dispatch(s.state.tr.deleteSelection().scrollIntoView().setMeta("uiEvent","cut"))};function Oks(s){return s.openStart==0&&s.openEnd==0&&s.content.childCount==1?s.content.firstChild:null}function Fks(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?NY(s,r.value,null,a,t):NY(s,r.textContent,r.innerHTML,a,t)},50)}function NY(s,t,n,r,a){let i=lCt(s,t,n,r,s.state.selection.$from);if(s.someProp("handlePaste",c=>c(s,a,i||li.empty)))return!0;if(!i)return!1;let l=Oks(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 yCt(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," "):""}r1.paste=(s,t)=>{let n=t;if(s.composing&&!G4)return;let r=jY?null:n.clipboardData,a=s.input.shiftKey&&s.input.lastKeyCode!=45;r&&NY(s,yCt(r),r.getData("text/html"),a,n)?n.preventDefault():Fks(s,n)};class vCt{constructor(t,n,r){this.slice=t,this.move=n,this.node=r}}const zks=qw?"altKey":"ctrlKey";function bCt(s,t){let n;return s.someProp("dragCopies",r=>{n=n||r(t)}),n!=null?!n:!t[zks]}n1.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(d3e(n)),l;if(!(i&&i.pos>=a.from&&i.pos<=(a instanceof Do?a.to-1:a.to))){if(r&&r.mightDrag)l=Do.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=Do.create(s.state.doc,h.posBefore))}}let o=(l||s.state.selection).content(),{dom:c,text:d,slice:u}=kqe(s,o);(!n.dataTransfer.files.length||!z0||H3t>120)&&n.dataTransfer.clearData(),n.dataTransfer.setData(jY?"Text":"text/html",c.innerHTML),n.dataTransfer.effectAllowed="copyMove",jY||n.dataTransfer.setData("text/plain",d),s.dragging=new vCt(u,bCt(s,n),l)};n1.dragend=s=>{let t=s.dragging;window.setTimeout(()=>{s.dragging==t&&(s.dragging=null)},50)};r1.dragover=r1.dragenter=(s,t)=>t.preventDefault();r1.drop=(s,t)=>{try{Bks(s,t,s.dragging)}finally{s.dragging=null}};function Bks(s,t,n){if(!t.dataTransfer)return;let r=s.posAtCoords(d3e(t));if(!r)return;let a=s.state.doc.resolve(r.pos),i=n&&n.slice;i?s.someProp("transformPasted",f=>{i=f(i,s,!1)}):i=lCt(s,yCt(t.dataTransfer),jY?null:t.dataTransfer.getData("text/html"),!1,a);let l=!!(n&&bCt(s,t));if(s.someProp("handleDrop",f=>f(s,t,i||li.empty,l))){t.preventDefault();return}if(!i)return;t.preventDefault();let o=i?R3t(s.state.doc,a.pos,i):a.pos;o==null&&(o=a.pos);let c=s.state.tr;if(l){let{node:f}=n;f?f.replace(c):c.deleteSelection()}let d=c.mapping.map(o),u=i.openStart==0&&i.openEnd==0&&i.content.childCount==1,h=c.doc;if(u?c.replaceRangeWith(d,d,i.content.firstChild):c.replaceRange(d,d,i),c.doc.eq(h))return;let m=c.doc.resolve(d);if(u&&Do.isSelectable(i.content.firstChild)&&m.nodeAfter&&m.nodeAfter.sameMarkup(i.content.firstChild))c.setSelection(new Do(m));else{let f=c.mapping.map(o);c.mapping.maps[c.mapping.maps.length-1].forEach((g,y,x,_)=>f=_),c.setSelection(Nqe(s,m,c.doc.resolve(f)))}s.focus(),s.dispatch(c.setMeta("uiEvent","drop"))}n1.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())&&d3(s)},20))};n1.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)};n1.beforeinput=(s,t)=>{if(z0&&G4&&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,bI(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 r1)n1[s]=r1[s];function kY(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 wNe{constructor(t,n){this.toDOM=t,this.spec=n||ED,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 Fv(i-r,i-r,this)}valid(){return!0}eq(t){return this==t||t instanceof wNe&&(this.spec.key&&this.spec.key==t.spec.key||this.toDOM==t.toDOM&&kY(this.spec,t.spec))}destroy(t){this.spec.destroy&&this.spec.destroy(t)}}class KT{constructor(t,n){this.attrs=t,this.spec=n||ED}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 Fv(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==Ey||t.maps.length==0?this:this.mapInner(t,n,0,0,r||ED)}mapInner(t,n,r,a,i){let l;for(let o=0;o{let d=c+r,u;if(u=wCt(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 KT){let d=Math.max(i,c.from)-i,u=Math.min(l,c.to)-i;da.map(t,n,ED));return dA.from(r)}forChild(t,n){if(n.isLeaf)return af.empty;let r=[];for(let a=0;an instanceof af)?t:t.reduce((n,r)=>n.concat(r instanceof af?r:r.members),[]))}}forEachSet(t){for(let n=0;n{let x=y-g-(f-m);for(let _=0;_b+u-h)continue;let k=o[_]+u-h;f>=k?o[_+1]=m<=k?-2:-1:m>=u&&x&&(o[_]+=x,o[_+1]+=x)}h+=x}),u=n.maps[d].map(u,-1)}let c=!1;for(let d=0;d=r.content.size){c=!0;continue}let m=n.map(s[d+1]+i,-1),f=m-a,{index:g,offset:y}=r.content.findIndex(h),x=r.maybeChild(g);if(x&&y==h&&y+x.nodeSize==f){let _=o[d+2].mapInner(n,x,u+1,s[d]+i+1,l);_!=Ey?(o[d]=h,o[d+1]=f,o[d+2]=_):(o[d+1]=-2,c=!0)}else c=!0}if(c){let d=Uks(o,s,t,n,a,i,l),u=jNe(d,r,0,l);t=u.local;for(let h=0;hn&&l.to{let d=wCt(s,o,c+n);if(d){i=!0;let u=jNe(d,o,n+c+1,r);u!=Ey&&a.push(c,c+o.nodeSize,u)}});let l=_Ct(i?jCt(s):s,-n).sort(MD);for(let o=0;o0;)t++;s.splice(t,0,n)}function _Me(s){let t=[];return s.someProp("decorations",n=>{let r=n(s.state);r&&r!=Ey&&t.push(r)}),s.cursorWrapper&&t.push(af.create(s.state.doc,[s.cursorWrapper.deco])),dA.from(t)}const qks={childList:!0,characterData:!0,characterDataOldValue:!0,attributes:!0,attributeOldValue:!0,subtree:!0},Vks=ob&><=11;class Hks{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 Gks{constructor(t,n){this.view=t,this.handleDOMChange=n,this.queue=[],this.flushingSoon=-1,this.observer=null,this.currentSelection=new Hks,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():qy&&t.composing&&r.some(a=>a.type=="childList"&&a.target.nodeName=="TR")?(t.input.badSafariComposition=!0,this.flushSoon()):this.flush()}),Vks&&(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,qks)),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(nat(this.view)){if(this.suppressingSelectionUpdates)return d3(this.view);if(ob&><=11&&!this.view.state.selection.empty){let t=this.view.domSelectionRange();if(t.focusNode&&oR(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=HB(i))n.add(i);for(let i=t.anchorNode;i;i=HB(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)&&nat(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(xj&&c.length){let u=c.filter(h=>h.nodeName=="BR");if(u.length==2){let[h,m]=u;h.parentNode&&h.parentNode.parentNode==m.parentNode?m.remove():h.remove()}else{let{focusNode:h}=this.currentSelection;for(let m of u){let f=m.parentNode;f&&f.nodeName=="LI"&&(!h||Yks(t,h)!=f)&&m.remove()}}}let d=null;i<0&&a&&t.input.lastFocus>Date.now()-200&&Math.max(t.input.lastTouch,t.input.lastClick.time)-1||a)&&(i>-1&&(t.docView.markDirty(i,l),Wks(t)),t.input.badSafariComposition&&(t.input.badSafariComposition=!1,Zks(t,c)),this.handleDOMChange(i,l,o,c),t.docView&&t.docView.dirty?t.updateState(t.state):this.currentSelection.eq(r)||d3(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;x--){let _=r.childNodes[x-1],b=_.pmViewDesc;if(_.nodeName=="BR"&&!b){i=x;break}if(!b||b.size)break}let h=s.state.doc,m=s.someProp("domParser")||XW.fromSchema(s.state.schema),f=h.resolve(l),g=null,y=m.parse(r,{topNode:f.parent,topMatch:f.parent.contentMatchAt(f.index()),topOpen:!0,from:a,to:i,preserveWhitespace:f.parent.type.whitespace=="pre"?"full":!0,findPositions:d,ruleFromNode:Qks,context:f});if(d&&d[0].pos!=null){let x=d[0].pos,_=d[1]&&d[1].pos;_==null&&(_=x),g={anchor:x+l,head:_+l}}return{doc:y,sel:g,from:l,to:o}}function Qks(s){let t=s.pmViewDesc;if(t)return t.parseRule();if(s.nodeName=="BR"&&s.parentNode){if(qy&&/^(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||qy&&/^(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 Jks=/^(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 e5s(s,t,n,r,a){let i=s.input.compositionPendingChanges||(s.composing?s.input.compositionID:0);if(s.input.compositionPendingChanges=0,t<0){let I=s.input.lastSelectionTime>Date.now()-50?s.input.lastSelectionOrigin:null,M=jqe(s,I);if(M&&!s.state.selection.eq(M)){if(z0&&G4&&s.input.lastKeyCode===13&&Date.now()-100z(s,bI(13,"Enter"))))return;let L=s.state.tr.setSelection(M);I=="pointer"?L.setMeta("pointer",!0):I=="key"&&L.scrollIntoView(),i&&L.setMeta("composition",i),s.dispatch(L)}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=Xks(s,t,n),u=s.state.doc,h=u.slice(d.from,d.to),m,f;s.input.lastKeyCode===8&&Date.now()-100Date.now()-225||G4)&&a.some(I=>I.nodeType==1&&!Jks.test(I.nodeName))&&(!g||g.endA>=g.endB)&&s.someProp("handleKeyDown",I=>I(s,bI(13,"Enter")))){s.input.lastIOSEnter=0;return}if(!g)if(r&&c instanceof Vo&&!c.empty&&c.$head.sameParent(c.$anchor)&&!s.composing&&!(d.sel&&d.sel.anchor!=d.sel.head))g={start:c.from,endA:c.to,endB:c.to};else{if(d.sel){let I=fat(s,s.state.doc,d.sel);if(I&&!I.eq(s.state.selection)){let M=s.state.tr.setSelection(I);i&&M.setMeta("composition",i),s.dispatch(M)}}return}s.state.selection.froms.state.selection.from&&g.start<=s.state.selection.from+2&&s.state.selection.from>=d.from?g.start=s.state.selection.from:g.endA=s.state.selection.to-2&&s.state.selection.to<=d.to&&(g.endB+=s.state.selection.to-g.endA,g.endA=s.state.selection.to)),ob&><=11&&g.endB==g.start+1&&g.endA==g.start&&g.start>d.from&&d.doc.textBetween(g.start-d.from-1,g.start-d.from+1)=="  "&&(g.start--,g.endA--,g.endB--);let y=d.doc.resolveNoCache(g.start-d.from),x=d.doc.resolveNoCache(g.endB-d.from),_=u.resolve(g.start),b=y.sameParent(x)&&y.parent.inlineContent&&_.end()>=g.endA;if((GB&&s.input.lastIOSEnter>Date.now()-225&&(!b||a.some(I=>I.nodeName=="DIV"||I.nodeName=="P"))||!b&&y.posI(s,bI(13,"Enter")))){s.input.lastIOSEnter=0;return}if(s.state.selection.anchor>g.start&&s5s(u,g.start,g.endA,y,x)&&s.someProp("handleKeyDown",I=>I(s,bI(8,"Backspace")))){G4&&z0&&s.domObserver.suppressSelectionUpdates();return}z0&&g.endB==g.start&&(s.input.lastChromeDelete=Date.now()),G4&&!b&&y.start()!=x.start()&&x.parentOffset==0&&y.depth==x.depth&&d.sel&&d.sel.anchor==d.sel.head&&d.sel.head==g.endA&&(g.endB-=2,x=d.doc.resolveNoCache(g.endB-d.from),setTimeout(()=>{s.someProp("handleKeyDown",function(I){return I(s,bI(13,"Enter"))})},20));let k=g.start,A=g.endA,T=I=>{let M=I||s.state.tr.replace(k,A,d.doc.slice(g.start-d.from,g.endB-d.from));if(d.sel){let L=fat(s,M.doc,d.sel);L&&!(z0&&s.composing&&L.empty&&(g.start!=g.endB||s.input.lastChromeDeleted3(s),20));let I=T(s.state.tr.delete(k,A)),M=u.resolve(g.start).marksAcross(u.resolve(g.endA));M&&I.ensureMarks(M),s.dispatch(I)}else if(g.endA==g.endB&&(P=t5s(y.parent.content.cut(y.parentOffset,x.parentOffset),_.parent.content.cut(_.parentOffset,g.endA-_.start())))){let I=T(s.state.tr);P.type=="add"?I.addMark(k,A,P.mark):I.removeMark(k,A,P.mark),s.dispatch(I)}else if(y.parent.child(y.index()).isText&&y.index()==x.index()-(x.textOffset?0:1)){let I=y.parent.textBetween(y.parentOffset,x.parentOffset),M=()=>T(s.state.tr.insertText(I,k,A));s.someProp("handleTextInput",L=>L(s,k,A,I,M))||s.dispatch(M())}else s.dispatch(T());else s.dispatch(T())}function fat(s,t,n){return Math.max(n.anchor,n.head)>t.content.size?null:Nqe(s,t.resolve(n.anchor),t.resolve(n.head))}function t5s(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||wMe(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 n5s(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 NCt{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 vks,this.prevDirectPlugins=[],this.pluginViews=[],this.requiresGeckoHackNode=!1,this.dragging=null,this._props=n,this.state=n.state,this.directPlugins=n.plugins||[],this.directPlugins.forEach(_at),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=vat(this),yat(this),this.nodeViews=bat(this),this.docView=Xrt(this.state.doc,xat(this),_Me(this),this.dom,this),this.domObserver=new Gks(this,(r,a,i,l)=>e5s(this,r,a,i,l)),this.domObserver.start(),bks(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&&qRe(this);let n=this._props;this._props=t,t.plugins&&(t.plugins.forEach(_at),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&&(xCt(this),l=!0),this.state=t;let o=a.plugins!=t.plugins||this._props.plugins!=n.plugins;if(o||this._props.plugins!=n.plugins||this._props.nodeViews!=n.nodeViews){let f=bat(this);a5s(f,this.nodeViews)&&(this.nodeViews=f,i=!0)}(o||n.handleDOMEvents!=this._props.handleDOMEvents)&&qRe(this),this.editable=vat(this),yat(this);let c=_Me(this),d=xat(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&&INs(this);if(l){this.domObserver.stop();let f=h&&(ob||z0)&&!this.composing&&!a.selection.empty&&!t.selection.empty&&r5s(a.selection,t.selection);if(h){let g=z0?this.trackWrites=this.domSelectionRange().focusNode:null;this.composing&&(this.input.compositionNode=Iks(this)),(i||!this.docView.update(t.doc,d,c,this))&&(this.docView.updateOuterDeco(d),this.docView.destroy(),this.docView=Xrt(t.doc,d,c,this.dom,this)),g&&(!this.trackWrites||!this.dom.contains(this.trackWrites))&&(f=!0)}f||!(this.input.mouseDown&&this.domObserver.currentSelection.eq(this.domSelectionRange())&&rks(this))?d3(this,f):(aCt(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&&DNs(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 Do){let n=this.docView.domAfterPos(this.state.selection.from);n.nodeType==1&&Hrt(this,n.getBoundingClientRect(),t)}else Hrt(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 $Ns(this,t)}coordsAtPos(t,n=1){return X3t(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 GNs(this,n||this.state,t)}pasteHTML(t,n){return NY(this,"",t,!1,n||new ClipboardEvent("paste"))}pasteText(t,n){return NY(this,t,null,!0,n||new ClipboardEvent("paste"))}serializeForClipboard(t){return kqe(this,t)}destroy(){this.docView&&(_ks(this),this.destroyPluginViews(),this.mounted?(this.docView.update(this.state.doc,[],_Me(this),this),this.dom.textContent=""):this.dom.parentNode&&this.dom.parentNode.removeChild(this.dom),this.docView.destroy(),this.docView=null,NNs())}get isDestroyed(){return this.docView==null}dispatchEvent(t){return jks(this,t)}domSelectionRange(){let t=this.domSelection();return t?qy&&this.root.nodeType===11&&TNs(this.dom.ownerDocument)==this.dom&&Kks(this,t)||t:{focusNode:null,focusOffset:0,anchorNode:null,anchorOffset:0}}domSelection(){return this.root.getSelection()}}NCt.prototype.dispatch=function(s){let t=this._props.dispatchTransaction;t?t.call(this,s):this.updateState(this.state.apply(s))};function xat(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"),[Fv.node(0,s.state.doc.content.size,t)]}function yat(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:Fv.widget(s.state.selection.from,t,{raw:!0,marks:s.markCursor})}}else s.cursorWrapper=null}function vat(s){return!s.someProp("editable",t=>t(s.state)===!1)}function r5s(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 bat(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 a5s(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 _at(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 pE={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:"'"},NNe={48:")",49:"!",50:"@",51:"#",52:"$",53:"%",54:"^",55:"&",56:"*",57:"(",59:":",61:"+",173:"_",186:":",187:"+",188:"<",189:"_",190:">",191:"?",192:"~",219:"{",220:"|",221:"}",222:'"'},i5s=typeof navigator<"u"&&/Mac/.test(navigator.platform),o5s=typeof navigator<"u"&&/MSIE \d|Trident\/(?:[7-9]|\d{2,})\..*rv:(\d+)/.exec(navigator.userAgent);for(var I0=0;I0<10;I0++)pE[48+I0]=pE[96+I0]=String(I0);for(var I0=1;I0<=24;I0++)pE[I0+111]="F"+I0;for(var I0=65;I0<=90;I0++)pE[I0]=String.fromCharCode(I0+32),NNe[I0]=String.fromCharCode(I0);for(var jMe in pE)NNe.hasOwnProperty(jMe)||(NNe[jMe]=pE[jMe]);function l5s(s){var t=i5s&&s.metaKey&&s.shiftKey&&!s.ctrlKey&&!s.altKey||o5s&&s.shiftKey&&s.key&&s.key.length==1||s.key=="Unidentified",n=!t&&s.key||(s.shiftKey?NNe:pE)[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 c5s=typeof navigator<"u"&&/Mac|iP(hone|[oa]d)/.test(navigator.platform),d5s=typeof navigator<"u"&&/Win/.test(navigator.platform);function u5s(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 kCt(s,t){let{$cursor:n}=s.selection;return!n||(t?!t.endOfTextblock("backward",s):n.parentOffset>0)?null:n}const f5s=(s,t,n)=>{let r=kCt(s,n);if(!r)return!1;let a=Lqe(r);if(!a){let l=r.blockRange(),o=l&&xU(l);return o==null?!1:(t&&t(s.tr.lift(l,o).scrollIntoView()),!0)}let i=a.nodeBefore;if(TCt(s,a,t,-1))return!0;if(r.parent.content.size==0&&(WB(i,"end")||Do.isSelectable(i)))for(let l=r.depth;;l--){let o=i3e(s.doc,r.before(l),r.after(l),li.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},g5s=(s,t,n)=>{let r=kCt(s,n);if(!r)return!1;let a=Lqe(r);return a?SCt(s,a,t):!1},x5s=(s,t,n)=>{let r=CCt(s,n);if(!r)return!1;let a=Pqe(r);return a?SCt(s,a,t):!1};function SCt(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=i3e(s.doc,i,c,li.empty);if(!d||d.from!=i||d instanceof dg&&d.slice.size>=c-i)return!1;if(n){let u=s.tr.step(d);u.setSelection(Vo.create(u.doc,i)),n(u.scrollIntoView())}return!0}function WB(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 y5s=(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=Lqe(r)}let l=i&&i.nodeBefore;return!l||!Do.isSelectable(l)?!1:(t&&t(s.tr.setSelection(Do.create(s.doc,i.pos-l.nodeSize)).scrollIntoView()),!0)};function Lqe(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 CCt(s,t){let{$cursor:n}=s.selection;return!n||(t?!t.endOfTextblock("forward",s):n.parentOffset{let r=CCt(s,n);if(!r)return!1;let a=Pqe(r);if(!a)return!1;let i=a.nodeAfter;if(TCt(s,a,t,1))return!0;if(r.parent.content.size==0&&(WB(i,"start")||Do.isSelectable(i))){let l=i3e(s.doc,r.before(),r.after(),li.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 Do,a;if(r){if(n.node.isTextblock||!FE(s.doc,n.from))return!1;a=n.from}else if(a=a3e(s.doc,n.from,-1),a==null)return!1;if(t){let i=s.tr.join(a);r&&i.setSelection(Do.create(i.doc,a-s.doc.resolve(a).nodeBefore.nodeSize)),t(i.scrollIntoView())}return!0},w5s=(s,t)=>{let n=s.selection,r;if(n instanceof Do){if(n.node.isTextblock||!FE(s.doc,n.to))return!1;r=n.to}else if(r=a3e(s.doc,n.to,1),r==null)return!1;return t&&t(s.tr.join(r).scrollIntoView()),!0},j5s=(s,t)=>{let{$from:n,$to:r}=s.selection,a=n.blockRange(r),i=a&&xU(a);return i==null?!1:(t&&t(s.tr.lift(a,i).scrollIntoView()),!0)},N5s=(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 ACt(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=ACt(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(nl.near(c.doc.resolve(o),1)),t(c.scrollIntoView())}return!0},S5s=(s,t)=>{let n=s.selection,{$from:r,$to:a}=n;if(n instanceof gj||r.parent.inlineContent||a.parent.inlineContent)return!1;let i=ACt(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(G9(s.doc,i))return t&&t(s.tr.split(i).scrollIntoView()),!0}let r=n.blockRange(),a=r&&xU(r);return a==null?!1:(t&&t(s.tr.lift(r,a).scrollIntoView()),!0)},A5s=(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(Do.create(s.doc,a))),!0)};function T5s(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||FE(s.doc,t.pos))?!1:(n&&n(s.tr.join(t.pos).scrollIntoView()),!0)}function TCt(s,t,n,r){let a=t.nodeBefore,i=t.nodeAfter,l,o,c=a.type.spec.isolating||i.type.spec.isolating;if(!c&&T5s(s,t,n))return!0;let d=!c&&t.parent.canReplace(t.index(),t.index()+1);if(d&&(l=(o=a.contentMatchAt(a.childCount)).findWrapping(i.type))&&o.matchType(l[0]||i.type).validEnd){if(n){let f=t.pos+i.nodeSize,g=Ca.empty;for(let _=l.length-1;_>=0;_--)g=Ca.from(l[_].create(null,g));g=Ca.from(a.copy(g));let y=s.tr.step(new Yx(t.pos-1,f,t.pos,f,new li(g,1,0),l.length,!0)),x=y.doc.resolve(f+2*l.length);x.nodeAfter&&x.nodeAfter.type==a.type&&FE(y.doc,x.pos)&&y.join(x.pos),n(y.scrollIntoView())}return!0}let u=i.type.spec.isolating||r>0&&c?null:nl.findFrom(t,1),h=u&&u.$from.blockRange(u.$to),m=h&&xU(h);if(m!=null&&m>=t.depth)return n&&n(s.tr.lift(h,m).scrollIntoView()),!0;if(d&&WB(i,"start",!0)&&WB(a,"end")){let f=a,g=[];for(;g.push(f),!f.isTextblock;)f=f.lastChild;let y=i,x=1;for(;!y.isTextblock;y=y.firstChild)x++;if(f.canReplace(f.childCount,f.childCount,y.content)){if(n){let _=Ca.empty;for(let k=g.length-1;k>=0;k--)_=Ca.from(g[k].copy(_));let b=s.tr.step(new Yx(t.pos-g.length,t.pos+i.nodeSize,t.pos+x,t.pos+i.nodeSize-x,new li(_,g.length,0),0,!0));n(b.scrollIntoView())}return!0}}return!1}function ECt(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(Vo.create(t.doc,s<0?a.start(i):a.end(i)))),!0):!1}}const E5s=ECt(-1),M5s=ECt(1);function L5s(s,t=null){return function(n,r){let{$from:a,$to:i}=n.selection,l=a.blockRange(i),o=l&&vqe(l,s,t);return o?(r&&r(n.tr.wrap(l,o).scrollIntoView()),!0):!1}}function wat(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 xNe(c,c,t.depth),t.endIndex=0;u--)i=Ca.from(n[u].type.create(n[u].attrs,i));s.step(new Yx(t.start-(r?2:0),t.end,t.start,t.end,new li(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?O5s(t,n,s,i):F5s(t,n,i):!0:!1}}function O5s(s,t,n,r){let a=s.tr,i=r.end,l=r.$to.end(r.depth);iy;g--)f-=a.child(g).nodeSize,r.delete(f-1,f+1);let i=r.doc.resolve(n.start),l=i.nodeAfter;if(r.mapping.map(n.end)!=n.start+i.nodeAfter.nodeSize)return!1;let o=n.startIndex==0,c=n.endIndex==a.childCount,d=i.node(-1),u=i.index(-1);if(!d.canReplace(u+(o?0:1),u+1,l.content.append(c?Ca.empty:Ca.from(a))))return!1;let h=i.pos,m=h+l.nodeSize;return r.step(new Yx(h-(o?1:0),m+(c?1:0),h+1,m-1,new li((o?Ca.empty:Ca.from(a.copy(Ca.empty))).append(c?Ca.empty:Ca.from(a.copy(Ca.empty))),o?0:1,c?0:1),o?0:1)),t(r.scrollIntoView()),!0}function z5s(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=Ca.from(d?s.create():null),h=new li(Ca.from(s.create(null,Ca.from(o.type.create(null,u)))),d?3:1,0),m=i.start,f=i.end;n(t.tr.step(new Yx(m-(d?3:1),f,m,f,h,1,!0)).scrollIntoView())}return!0}}function u3e(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 h3e=class{constructor(t){this.editor=t.editor,this.rawCommands=this.editor.extensionManager.commands,this.customState=t.state}get hasCustomState(){return!!this.customState}get state(){return this.customState||this.editor.state}get commands(){const{rawCommands:t,editor:n,state:r}=this,{view:a}=n,{tr:i}=r,l=this.buildProps(i);return Object.fromEntries(Object.entries(t).map(([o,c])=>[o,(...u)=>{const h=c(...u)(l);return!i.getMeta("preventDispatch")&&!this.hasCustomState&&a.dispatch(i),h}]))}get chain(){return()=>this.createChain()}get can(){return()=>this.createCan()}createChain(t,n=!0){const{rawCommands:r,editor:a,state:i}=this,{view:l}=a,o=[],c=!!t,d=t||i.tr,u=()=>(!c&&n&&!d.getMeta("preventDispatch")&&!this.hasCustomState&&l.dispatch(d),o.every(m=>m===!0)),h={...Object.fromEntries(Object.entries(r).map(([m,f])=>[m,(...y)=>{const x=this.buildProps(d,n),_=f(...y)(x);return o.push(_),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:u3e({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}},B5s=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 eo(s,t,n){return s.config[t]===void 0&&s.parent?eo(s.parent,t,n):typeof s.config[t]=="function"?s.config[t].bind({...n,parent:s.parent?eo(s.parent,t,n):null}):s.config[t]}function m3e(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 MCt(s){const t=[],{nodeExtensions:n,markExtensions:r}=m3e(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=eo(l,"addGlobalAttributes",o);if(!c)return;c().forEach(u=>{u.types.forEach(h=>{Object.entries(u.attributes).forEach(([m,f])=>{t.push({type:h,name:m,attribute:{...i,...f}})})})})}),a.forEach(l=>{const o={name:l.name,options:l.options,storage:l.storage},c=eo(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 Xx(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 $m(...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(f=>f.trim());d.set(h,m)}),o.forEach(u=>{const[h,m]=u.split(":").map(f=>f.trim());d.set(h,m)}),r[a]=Array.from(d.entries()).map(([u,h])=>`${u}: ${h}`).join("; ")}else r[a]=i}),r},{})}function VRe(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)=>$m(n,r),{})}function LCt(s){return typeof s=="function"}function mc(s,t=void 0,...n){return LCt(s)?t?s.bind(t)(...n):s(...n):s}function $5s(s={}){return Object.keys(s).length===0&&s.constructor===Object}function U5s(s){return typeof s!="string"?s:s.match(/^[+-]?(?:\d*\.)?\d+$/)?Number(s):s==="true"?!0:s==="false"?!1:s}function jat(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):U5s(n.getAttribute(l.name));return o==null?i:{...i,[l.name]:o}},{});return{...r,...a}}}}function Nat(s){return Object.fromEntries(Object.entries(s).filter(([t,n])=>t==="attrs"&&$5s(n)?!1:n!=null))}function q5s(s,t){var n;const r=MCt(s),{nodeExtensions:a,markExtensions:i}=m3e(s),l=(n=a.find(d=>eo(d,"topNode")))===null||n===void 0?void 0:n.name,o=Object.fromEntries(a.map(d=>{const u=r.filter(_=>_.type===d.name),h={name:d.name,options:d.options,storage:d.storage,editor:t},m=s.reduce((_,b)=>{const k=eo(b,"extendNodeSchema",h);return{..._,...k?k(d):{}}},{}),f=Nat({...m,content:mc(eo(d,"content",h)),marks:mc(eo(d,"marks",h)),group:mc(eo(d,"group",h)),inline:mc(eo(d,"inline",h)),atom:mc(eo(d,"atom",h)),selectable:mc(eo(d,"selectable",h)),draggable:mc(eo(d,"draggable",h)),code:mc(eo(d,"code",h)),whitespace:mc(eo(d,"whitespace",h)),linebreakReplacement:mc(eo(d,"linebreakReplacement",h)),defining:mc(eo(d,"defining",h)),isolating:mc(eo(d,"isolating",h)),attrs:Object.fromEntries(u.map(_=>{var b;return[_.name,{default:(b=_==null?void 0:_.attribute)===null||b===void 0?void 0:b.default}]}))}),g=mc(eo(d,"parseHTML",h));g&&(f.parseDOM=g.map(_=>jat(_,u)));const y=eo(d,"renderHTML",h);y&&(f.toDOM=_=>y({node:_,HTMLAttributes:VRe(_,u)}));const x=eo(d,"renderText",h);return x&&(f.toText=x),[d.name,f]})),c=Object.fromEntries(i.map(d=>{const u=r.filter(x=>x.type===d.name),h={name:d.name,options:d.options,storage:d.storage,editor:t},m=s.reduce((x,_)=>{const b=eo(_,"extendMarkSchema",h);return{...x,...b?b(d):{}}},{}),f=Nat({...m,inclusive:mc(eo(d,"inclusive",h)),excludes:mc(eo(d,"excludes",h)),group:mc(eo(d,"group",h)),spanning:mc(eo(d,"spanning",h)),code:mc(eo(d,"code",h)),attrs:Object.fromEntries(u.map(x=>{var _;return[x.name,{default:(_=x==null?void 0:x.attribute)===null||_===void 0?void 0:_.default}]}))}),g=mc(eo(d,"parseHTML",h));g&&(f.parseDOM=g.map(x=>jat(x,u)));const y=eo(d,"renderHTML",h);return y&&(f.toDOM=x=>y({mark:x,HTMLAttributes:VRe(x,u)})),[d.name,f]}));return new k3t({topNode:l,nodes:o,marks:c})}function kMe(s,t){return t.nodes[s]||t.marks[s]||null}function kat(s,t){return Array.isArray(t)?t.some(n=>(typeof n=="string"?n:n.name)===s.name):t}function Iqe(s,t){const n=UR.fromSchema(t).serializeFragment(s),a=document.implementation.createHTMLDocument().createElement("div");return a.appendChild(n),a.innerHTML}const V5s=(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 Dqe(s){return Object.prototype.toString.call(s)==="[object RegExp]"}class p3e{constructor(t){this.find=t.find,this.handler=t.handler}}const H5s=(s,t)=>{if(Dqe(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 sse(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=V5s(d)+i;return l.forEach(m=>{if(u)return;const f=H5s(h,m.find);if(!f)return;const g=c.state.tr,y=u3e({state:c.state,transaction:g}),x={from:r-(f[0].length-i.length),to:a},{commands:_,chain:b,can:k}=new h3e({editor:n,state:y});m.handler({state:y,range:x,match:f,commands:_,chain:b,can:k})===null||!g.steps.length||(g.setMeta(o,{transform:g,from:r,to:a,text:i}),c.dispatch(g),u=!0)}),u}function G5s(s){const{editor:t,rules:n}=s,r=new dx({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=Iqe(Ca.from(u),l.schema);const{from:h}=c,m=h+u.length;sse({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 sse({editor:t,from:i,to:l,text:o,rules:n,plugin:r})},handleDOMEvents:{compositionend:a=>(setTimeout(()=>{const{$cursor:i}=a.state.selection;i&&sse({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?sse({editor:t,from:l.pos,to:l.pos,text:` `,rules:n,plugin:r}):!1}},isInputRules:!0});return r}function W5s(s){return Object.prototype.toString.call(s).slice(8,-1)}function nse(s){return W5s(s)!=="Object"?!1:s.constructor===Object&&Object.getPrototypeOf(s)===Object.prototype}function f3e(s,t){const n={...s};return nse(s)&&nse(t)&&Object.keys(t).forEach(r=>{nse(t[r])&&nse(s[r])?n[r]=f3e(s[r],t[r]):n[r]=t[r]}),n}class uN{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=mc(eo(this,"addOptions",{name:this.name}))),this.storage=mc(eo(this,"addStorage",{name:this.name,options:this.options}))||{}}static create(t={}){return new uN(t)}configure(t={}){const n=this.extend({...this.config,addOptions:()=>f3e(this.options,t)});return n.name=this.name,n.parent=this.parent,n}extend(t={}){const n=new uN(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=mc(eo(n,"addOptions",{name:n.name})),n.storage=mc(eo(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 K5s(s){return typeof s=="number"}class Y5s{constructor(t){this.find=t.find,this.handler=t.handler}}const Z5s=(s,t,n)=>{if(Dqe(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 X5s(s){const{editor:t,state:n,from:r,to:a,rule:i,pasteEvent:l,dropEvent:o}=s,{commands:c,chain:d,can:u}=new h3e({editor:t,state:n}),h=[];return n.doc.nodesBetween(r,a,(f,g)=>{if(!f.isTextblock||f.type.spec.code)return;const y=Math.max(r,g),x=Math.min(a,g+f.content.size),_=f.textBetween(y-g,x-g,void 0,"");Z5s(_,i.find,l).forEach(k=>{if(k.index===void 0)return;const A=y+k.index+1,T=A+k[0].length,P={from:n.tr.mapping.map(A),to:n.tr.mapping.map(T)},I=i.handler({state:n,range:P,match:k,commands:c,chain:d,can:u,pasteEvent:l,dropEvent:o});h.push(I)})}),h.every(f=>f!==null)}let rse=null;const Q5s=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 J5s(s){const{editor:t,rules:n}=s;let r=null,a=!1,i=!1,l=typeof ClipboardEvent<"u"?new ClipboardEvent("paste"):null,o;try{o=typeof DragEvent<"u"?new DragEvent("drop"):null}catch{o=null}const c=({state:u,from:h,to:m,rule:f,pasteEvt:g})=>{const y=u.tr,x=u3e({state:u,transaction:y});if(!(!X5s({editor:t,state:x,from:Math.max(h-1,0),to:m.b-1,rule:f,pasteEvent:g,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 dx({view(h){const m=g=>{var y;r=!((y=h.dom.parentElement)===null||y===void 0)&&y.contains(g.target)?h.dom.parentElement:null,r&&(rse=t)},f=()=>{rse&&(rse=null)};return window.addEventListener("dragstart",m),window.addEventListener("dragend",f),{destroy(){window.removeEventListener("dragstart",m),window.removeEventListener("dragend",f)}}},props:{handleDOMEvents:{drop:(h,m)=>{if(i=r===h.dom.parentElement,o=m,!i){const f=rse;f!=null&&f.isEditable&&setTimeout(()=>{const g=f.state.selection;g&&f.commands.deleteRange({from:g.from,to:g.to})},10)}return!1},paste:(h,m)=>{var f;const g=(f=m.clipboardData)===null||f===void 0?void 0:f.getData("text/html");return l=m,a=!!(g!=null&&g.includes("data-pm-slice")),!1}}},appendTransaction:(h,m,f)=>{const g=h[0],y=g.getMeta("uiEvent")==="paste"&&!a,x=g.getMeta("uiEvent")==="drop"&&!i,_=g.getMeta("applyPasteRules"),b=!!_;if(!y&&!x&&!b)return;if(b){let{text:T}=_;typeof T=="string"?T=T:T=Iqe(Ca.from(T),f.schema);const{from:P}=_,I=P+T.length,M=Q5s(T);return c({rule:u,state:f,from:P,to:{b:I},pasteEvt:M})}const k=m.doc.content.findDiffStart(f.doc.content),A=m.doc.content.findDiffEnd(f.doc.content);if(!(!K5s(k)||!A||k===A.b))return c({rule:u,state:f,from:k,to:A,pasteEvt:l})}}))}function eSs(s){const t=s.filter((n,r)=>s.indexOf(n)!==r);return Array.from(new Set(t))}class O7{constructor(t,n){this.splittableMarks=[],this.editor=n,this.extensions=O7.resolve(t),this.schema=q5s(this.extensions,n),this.setupExtensions()}static resolve(t){const n=O7.sort(O7.flatten(t)),r=eSs(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=eo(n,"addExtensions",r);return a?[n,...this.flatten(a())]:n}).flat(10)}static sort(t){return t.sort((r,a)=>{const i=eo(r,"priority")||100,l=eo(a,"priority")||100;return i>l?-1:i{const r={name:n.name,options:n.options,storage:n.storage,editor:this.editor,type:kMe(n.name,this.schema)},a=eo(n,"addCommands",r);return a?{...t,...a()}:t},{})}get plugins(){const{editor:t}=this,n=O7.sort([...this.extensions].reverse()),r=[],a=[],i=n.map(l=>{const o={name:l.name,options:l.options,storage:l.storage,editor:t,type:kMe(l.name,this.schema)},c=[],d=eo(l,"addKeyboardShortcuts",o);let u={};if(l.type==="mark"&&eo(l,"exitable",o)&&(u.ArrowRight=()=>uN.handleExit({editor:t,mark:l})),d){const y=Object.fromEntries(Object.entries(d()).map(([x,_])=>[x,()=>_({editor:t})]));u={...u,...y}}const h=m5s(u);c.push(h);const m=eo(l,"addInputRules",o);kat(l,t.options.enableInputRules)&&m&&r.push(...m());const f=eo(l,"addPasteRules",o);kat(l,t.options.enablePasteRules)&&f&&a.push(...f());const g=eo(l,"addProseMirrorPlugins",o);if(g){const y=g();c.push(...y)}return c}).flat();return[G5s({editor:t,rules:r}),...J5s({editor:t,rules:a}),...i]}get attributes(){return MCt(this.extensions)}get nodeViews(){const{editor:t}=this,{nodeExtensions:n}=m3e(this.extensions);return Object.fromEntries(n.filter(r=>!!eo(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:Xx(r.name,this.schema)},l=eo(r,"addNodeView",i);if(!l)return[];const o=(c,d,u,h,m)=>{const f=VRe(c,a);return l()({node:c,view:d,getPos:u,decorations:h,innerDecorations:m,editor:t,extension:r,HTMLAttributes:f})};return[r.name,o]}))}setupExtensions(){this.extensions.forEach(t=>{var n;this.editor.extensionStorage[t.name]=t.storage;const r={name:t.name,options:t.options,storage:t.storage,editor:this.editor,type:kMe(t.name,this.schema)};t.type==="mark"&&(!((n=mc(eo(t,"keepOnSplit",r)))!==null&&n!==void 0)||n)&&this.splittableMarks.push(t.name);const a=eo(t,"onBeforeCreate",r),i=eo(t,"onCreate",r),l=eo(t,"onUpdate",r),o=eo(t,"onSelectionUpdate",r),c=eo(t,"onTransaction",r),d=eo(t,"onFocus",r),u=eo(t,"onBlur",r),h=eo(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 sy{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=mc(eo(this,"addOptions",{name:this.name}))),this.storage=mc(eo(this,"addStorage",{name:this.name,options:this.options}))||{}}static create(t={}){return new sy(t)}configure(t={}){const n=this.extend({...this.config,addOptions:()=>f3e(this.options,t)});return n.name=this.name,n.parent=this.parent,n}extend(t={}){const n=new sy({...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=mc(eo(n,"addOptions",{name:n.name})),n.storage=mc(eo(n,"addStorage",{name:n.name,options:n.options})),n}}function PCt(s,t,n){const{from:r,to:a}=t,{blockSeparator:i=` `,textSerializers:l={}}=n||{};let o="";return s.nodesBetween(r,a,(c,d,u,h)=>{var m;c.isBlock&&d>r&&(o+=i);const f=l==null?void 0:l[c.type.name];if(f)return u&&(o+=f({node:c,pos:d,parent:u,index:h,range:t})),!1;c.isText&&(o+=(m=c==null?void 0:c.text)===null||m===void 0?void 0:m.slice(Math.max(r,d)-d,a-d))}),o}function ICt(s){return Object.fromEntries(Object.entries(s.nodes).filter(([,t])=>t.spec.toText).map(([t,n])=>[t,n.spec.toText]))}const tSs=sy.create({name:"clipboardTextSerializer",addOptions(){return{blockSeparator:void 0}},addProseMirrorPlugins(){return[new dx({key:new Yy("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=ICt(n);return PCt(r,{from:l,to:o},{...this.options.blockSeparator!==void 0?{blockSeparator:this.options.blockSeparator}:{},textSerializers:c})}}})]}}),sSs=()=>({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),nSs=(s=!1)=>({commands:t})=>t.setContent("",s),rSs=()=>({state:s,tr:t,dispatch:n})=>{const{selection:r}=t,{ranges:a}=r;return n&&a.forEach(({$from:i,$to:l})=>{s.doc.nodesBetween(i.pos,l.pos,(o,c)=>{if(o.type.isText)return;const{doc:d,mapping:u}=t,h=d.resolve(u.map(c)),m=d.resolve(u.map(c+o.nodeSize)),f=h.blockRange(m);if(!f)return;const g=xU(f);if(o.type.isTextblock){const{defaultType:y}=h.parent.contentMatchAt(h.index());t.setNodeMarkup(f.start,y)}(g||g===0)&&t.lift(f,g)})}),!0},aSs=s=>t=>s(t),iSs=()=>({state:s,dispatch:t})=>S5s(s,t),oSs=(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 Vo(r.doc.resolve(Math.max(l-1,0)))),!0},lSs=()=>({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},cSs=s=>({tr:t,state:n,dispatch:r})=>{const a=Xx(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},dSs=s=>({tr:t,dispatch:n})=>{const{from:r,to:a}=s;return n&&t.delete(r,a),!0},uSs=()=>({state:s,dispatch:t})=>p5s(s,t),hSs=()=>({commands:s})=>s.keyboardShortcut("Enter"),mSs=()=>({state:s,dispatch:t})=>k5s(s,t);function kNe(s,t,n={strict:!0}){const r=Object.keys(t);return r.length?r.every(a=>n.strict?t[a]===s[a]:Dqe(t[a])?t[a].test(s[a]):t[a]===s[a]):!0}function DCt(s,t,n={}){return s.find(r=>r.type===t&&kNe(Object.fromEntries(Object.keys(n).map(a=>[a,r.attrs[a]])),n))}function Sat(s,t,n={}){return!!DCt(s,t,n)}function Rqe(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),!DCt([...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&&Sat([...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=BE(s,r.schema),{doc:l,selection:o}=n,{$from:c,from:d,to:u}=o;if(a){const h=Rqe(c,i,t);if(h&&h.from<=d&&h.to>=u){const m=Vo.create(l,h.from,h.to);n.setSelection(m)}}return!0},fSs=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=()=>{(SNe()||Cat())&&r.dom.focus(),requestAnimationFrame(()=>{n.isDestroyed||(r.focus(),gSs()&&!SNe()&&!Cat()&&r.dom.focus({preventScroll:!0}))})};if(r.hasFocus()&&s===null||s===!1)return!0;if(i&&s===null&&!RCt(n.state.selection))return l(),!0;const o=OCt(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},ySs=(s,t)=>n=>s.every((r,a)=>t(r,{...n,index:a})),vSs=(s,t)=>({tr:n,commands:r})=>r.insertContentAt({from:n.selection.from,to:n.selection.to},s,t),FCt=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&&FCt(r)}return s};function ase(s){const t=`${s}`,n=new window.DOMParser().parseFromString(t,"text/html").body;return FCt(n)}function SY(s,t,n){if(s instanceof HT||s instanceof Ca)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 Ca.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),SY("",t,n)}if(a){if(n.errorOnInvalidContent){let l=!1,o="";const c=new k3t({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?XW.fromSchema(c).parseSlice(ase(s),n.parseOptions):XW.fromSchema(c).parse(ase(s),n.parseOptions),n.errorOnInvalidContent&&l)throw new Error("[tiptap error]: Invalid HTML content",{cause:new Error(`Invalid element found: ${o}`)})}const i=XW.fromSchema(t);return n.slice?i.parseSlice(ase(s),n.parseOptions).content:i.parse(ase(s),n.parseOptions)}return SY("",t,n)}function bSs(s,t,n){const r=s.steps.length-1;if(r{l===0&&(l=u)}),s.setSelection(nl.near(s.doc.resolve(l),n))}const _Ss=s=>!("type"in s),wSs=(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=x=>{i.emit("contentError",{editor:i,error:x,disableCollaboration:()=>{i.storage.collaboration&&(i.storage.collaboration.isDisabled=!0)}})},d={preserveWhitespace:"full",...n.parseOptions};if(!n.errorOnInvalidContent&&!i.options.enableContentCheck&&i.options.emitContentError)try{SY(t,i.schema,{parseOptions:d,errorOnInvalidContent:!0})}catch(x){c(x)}try{o=SY(t,i.schema,{parseOptions:d,errorOnInvalidContent:(l=n.errorOnInvalidContent)!==null&&l!==void 0?l:i.options.enableContentCheck})}catch(x){return c(x),!1}let{from:u,to:h}=typeof s=="number"?{from:s,to:s}:{from:s.from,to:s.to},m=!0,f=!0;if((_Ss(o)?o:[o]).forEach(x=>{x.check(),m=m?x.isText&&x.marks.length===0:!1,f=f?x.isBlock:!1}),u===h&&f){const{parent:x}=r.doc.resolve(u);x.isTextblock&&!x.type.spec.code&&!x.childCount&&(u-=1,h+=1)}let y;if(m){if(Array.isArray(t))y=t.map(x=>x.text||"").join("");else if(t instanceof Ca){let x="";t.forEach(_=>{_.text&&(x+=_.text)}),y=x}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&&bSs(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},jSs=()=>({state:s,dispatch:t})=>_5s(s,t),NSs=()=>({state:s,dispatch:t})=>w5s(s,t),kSs=()=>({state:s,dispatch:t})=>f5s(s,t),SSs=()=>({state:s,dispatch:t})=>v5s(s,t),CSs=()=>({state:s,dispatch:t,tr:n})=>{try{const r=a3e(s.doc,s.selection.$from.pos,-1);return r==null?!1:(n.join(r,2),t&&t(n),!0)}catch{return!1}},ASs=()=>({state:s,dispatch:t,tr:n})=>{try{const r=a3e(s.doc,s.selection.$from.pos,1);return r==null?!1:(n.join(r,2),t&&t(n),!0)}catch{return!1}},TSs=()=>({state:s,dispatch:t})=>g5s(s,t),ESs=()=>({state:s,dispatch:t})=>x5s(s,t);function zCt(){return typeof navigator<"u"?/Mac/.test(navigator.platform):!1}function MSs(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=MSs(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 CY(s,t,n={}){const{from:r,to:a,empty:i}=s.selection,l=t?Xx(t,s.schema):null,o=[];s.doc.nodesBetween(r,a,(h,m)=>{if(h.isText)return;const f=Math.max(r,m),g=Math.min(a,m+h.nodeSize);o.push({node:h,from:f,to:g})});const c=a-r,d=o.filter(h=>l?l.name===h.node.type.name:!0).filter(h=>kNe(h.node.attrs,n,{strict:!1}));return i?!!d.length:d.reduce((h,m)=>h+m.to-m.from,0)>=c}const PSs=(s,t={})=>({state:n,dispatch:r})=>{const a=Xx(s,n.schema);return CY(n,a,t)?j5s(n,r):!1},ISs=()=>({state:s,dispatch:t})=>C5s(s,t),DSs=s=>({state:t,dispatch:n})=>{const r=Xx(s,t.schema);return R5s(r)(t,n)},RSs=()=>({state:s,dispatch:t})=>N5s(s,t);function g3e(s,t){return t.nodes[s]?"node":t.marks[s]?"mark":null}function Aat(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 OSs=(s,t)=>({tr:n,state:r,dispatch:a})=>{let i=null,l=null;const o=g3e(typeof s=="string"?s:s.name,r.schema);return o?(o==="node"&&(i=Xx(s,r.schema)),o==="mark"&&(l=BE(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,Aat(d.attrs,t)),l&&d.marks.length&&d.marks.forEach(h=>{l===h.type&&n.addMark(u,u+d.nodeSize,l.create(Aat(h.attrs,t)))})})}),!0):!1},FSs=()=>({tr:s,dispatch:t})=>(t&&s.scrollIntoView(),!0),zSs=()=>({tr:s,dispatch:t})=>{if(t){const n=new gj(s.doc);s.setSelection(n)}return!0},BSs=()=>({state:s,dispatch:t})=>y5s(s,t),$Ss=()=>({state:s,dispatch:t})=>b5s(s,t),USs=()=>({state:s,dispatch:t})=>A5s(s,t),qSs=()=>({state:s,dispatch:t})=>M5s(s,t),VSs=()=>({state:s,dispatch:t})=>E5s(s,t);function HRe(s,t,n={},r={}){return SY(s,t,{slice:!1,parseOptions:n,errorOnInvalidContent:r.errorOnInvalidContent})}const HSs=(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=HRe(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 BCt(s,t){const n=BE(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 GSs(s,t){const n=new bqe(s);return t.forEach(r=>{r.steps.forEach(a=>{n.step(a)})}),n}function WSs(s){for(let t=0;t{n(a)&&r.push({node:a,pos:i})}),r}function $Ct(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 Oqe(s){return t=>$Ct(t.$from,s)}function YSs(s,t){const n={from:0,to:s.content.size};return PCt(s,n,t)}function ZSs(s,t){const n=Xx(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 UCt(s,t){const n=g3e(typeof t=="string"?t:t.name,s.schema);return n==="node"?ZSs(s,t):n==="mark"?BCt(s,t):{}}function XSs(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 QSs(s){const t=XSs(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 JSs(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}})})}),QSs(r)}function Fqe(s,t,n){const r=[];return s===t?n.resolve(s).marks().forEach(a=>{const i=n.resolve(s),l=Rqe(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 Vwe(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 GRe(s,t,n={}){const{empty:r,ranges:a}=s.selection,i=t?BE(t,s.schema):null;if(r)return!!(s.storedMarks||s.selection.$from.marks()).filter(h=>i?i.name===h.type.name:!0).find(h=>kNe(h.attrs,n,{strict:!1}));let l=0;const o=[];if(a.forEach(({$from:h,$to:m})=>{const f=h.pos,g=m.pos;s.doc.nodesBetween(f,g,(y,x)=>{if(!y.isText&&!y.marks.length)return;const _=Math.max(f,x),b=Math.min(g,x+y.nodeSize),k=b-_;l+=k,o.push(...y.marks.map(A=>({mark:A,from:_,to:b})))})}),l===0)return!1;const c=o.filter(h=>i?i.name===h.mark.type.name:!0).filter(h=>kNe(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 e4s(s,t,n={}){if(!t)return CY(s,null,n)||GRe(s,null,n);const r=g3e(t,s.schema);return r==="node"?CY(s,t,n):r==="mark"?GRe(s,t,n):!1}function Tat(s,t){const{nodeExtensions:n}=m3e(t),r=n.find(l=>l.name===s);if(!r)return!1;const a={name:r.name,options:r.options,storage:r.storage},i=mc(eo(r,"group",a));return typeof i!="string"?!1:i.split(" ").includes("list")}function zqe(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&&(zqe(i,{ignoreWhitespace:n,checkChildren:t})||(a=!1))}),a}return!1}function t4s(s){return s instanceof Do}function s4s(s,t,n){var r;const{selection:a}=t;let i=null;if(RCt(a)&&(i=a.$cursor),i){const o=(r=s.storedMarks)!==null&&r!==void 0?r:i.marks();return!!n.isInSet(o)||!o.some(c=>c.type.excludes(n))}const{ranges:l}=a;return l.some(({$from:o,$to:c})=>{let d=o.depth===0?s.doc.inlineContent&&s.doc.type.allowsMarkType(n):!1;return s.doc.nodesBetween(o.pos,c.pos,(u,h,m)=>{if(d)return!1;if(u.isInline){const f=!m||m.type.allowsMarkType(n),g=!!n.isInSet(u.marks)||!u.marks.some(y=>y.type.excludes(n));d=f&&g}return!d}),d})}const n4s=(s,t={})=>({tr:n,state:r,dispatch:a})=>{const{selection:i}=n,{empty:l,ranges:o}=i,c=BE(s,r.schema);if(a)if(l){const d=BCt(r,c);n.addStoredMark(c.create({...d,...t}))}else o.forEach(d=>{const u=d.$from.pos,h=d.$to.pos;r.doc.nodesBetween(u,h,(m,f)=>{const g=Math.max(f,u),y=Math.min(f+m.nodeSize,h);m.marks.find(_=>_.type===c)?m.marks.forEach(_=>{c===_.type&&n.addMark(g,y,c.create({..._.attrs,...t}))}):n.addMark(g,y,c.create(t))})});return s4s(r,n,c)},r4s=(s,t)=>({tr:n})=>(n.setMeta(s,t),!0),a4s=(s,t={})=>({state:n,dispatch:r,chain:a})=>{const i=Xx(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})=>wat(i,{...l,...t})(n)?!0:o.clearNodes()).command(({state:o})=>wat(i,{...l,...t})(o,r)).run():(console.warn('[tiptap warn]: Currently "setNode()" only supports text block nodes.'),!1)},i4s=s=>({tr:t,dispatch:n})=>{if(n){const{doc:r}=t,a=DI(s,0,r.content.size),i=Do.create(r,a);t.setSelection(i)}return!0},o4s=s=>({tr:t,dispatch:n})=>{if(n){const{doc:r}=t,{from:a,to:i}=typeof s=="number"?{from:s,to:s}:s,l=Vo.atStart(r).from,o=Vo.atEnd(r).to,c=DI(a,l,o),d=DI(i,l,o),u=Vo.create(r,c,d);t.setSelection(u)}return!0},l4s=s=>({state:t,dispatch:n})=>{const r=Xx(s,t.schema);return z5s(r)(t,n)};function Eat(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 c4s=({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=Vwe(d,o.node().type.name,o.node().attrs);if(i instanceof Do&&i.node.isBlock)return!o.parentOffset||!G9(l,o.pos)?!1:(r&&(s&&Eat(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:WSs(o.node(-1).contentMatchAt(o.indexAfter(-1)));let f=h&&m?[{type:m,attrs:u}]:void 0,g=G9(t.doc,t.mapping.map(o.pos),1,f);if(!f&&!g&&G9(t.doc,t.mapping.map(o.pos),1,m?[{type:m}]:void 0)&&(g=!0,f=m?[{type:m,attrs:u}]:void 0),r){if(g&&(i instanceof Vo&&t.deleteSelection(),t.split(t.mapping.map(o.pos),1,f),m&&!h&&!o.parentOffset&&o.parent.type!==m)){const y=t.mapping.map(o.before()),x=t.doc.resolve(y);o.node(-1).canReplaceWith(x.index(),x.index()+1,m)&&t.setNodeMarkup(t.mapping.map(o.before()),m)}s&&Eat(n,a.extensionManager.splittableMarks),t.scrollIntoView()}return g},d4s=(s,t={})=>({tr:n,state:r,dispatch:a,editor:i})=>{var l;const o=Xx(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 _=Ca.empty;const b=c.index(-1)?1:c.index(-2)?2:3;for(let M=c.depth-b;M>=c.depth-3;M-=1)_=Ca.from(c.node(M).copy(_));const k=c.indexAfter(-1){if(I>-1)return!1;M.isTextblock&&M.content.size===0&&(I=L+1)}),I>-1&&n.setSelection(Vo.near(n.doc.resolve(I))),n.scrollIntoView()}return!0}const f=d.pos===c.end()?h.contentMatchAt(0).defaultType:null,g={...Vwe(m,h.type.name,h.attrs),...t},y={...Vwe(m,c.node().type.name,c.node().attrs),...t};n.delete(c.pos,d.pos);const x=f?[{type:o,attrs:g},{type:f,attrs:y}]:[{type:o,attrs:g}];if(!G9(n.doc,c.pos,2))return!1;if(a){const{selection:_,storedMarks:b}=r,{splittableMarks:k}=i.extensionManager,A=b||_.$to.parentOffset&&_.$from.marks();if(n.split(c.pos,2,x).scrollIntoView(),!A||!a)return!0;const T=A.filter(P=>k.includes(P.type.name));n.ensureMarks(T)}return!0},SMe=(s,t)=>{const n=Oqe(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)&&FE(s.doc,n.pos)&&s.join(n.pos),!0},CMe=(s,t)=>{const n=Oqe(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)&&FE(s.doc,r)&&s.join(r),!0},u4s=(s,t,n,r={})=>({editor:a,tr:i,state:l,dispatch:o,chain:c,commands:d,can:u})=>{const{extensions:h,splittableMarks:m}=a.extensionManager,f=Xx(s,l.schema),g=Xx(t,l.schema),{selection:y,storedMarks:x}=l,{$from:_,$to:b}=y,k=_.blockRange(b),A=x||y.$to.parentOffset&&y.$from.marks();if(!k)return!1;const T=Oqe(P=>Tat(P.type.name,h))(y);if(k.depth>=1&&T&&k.depth-T.depth<=1){if(T.node.type===f)return d.liftListItem(g);if(Tat(T.node.type.name,h)&&f.validContent(T.node.content)&&o)return c().command(()=>(i.setNodeMarkup(T.pos,f),!0)).command(()=>SMe(i,f)).command(()=>CMe(i,f)).run()}return!n||!A||!o?c().command(()=>u().wrapInList(f,r)?!0:d.clearNodes()).wrapInList(f,r).command(()=>SMe(i,f)).command(()=>CMe(i,f)).run():c().command(()=>{const P=u().wrapInList(f,r),I=A.filter(M=>m.includes(M.type.name));return i.ensureMarks(I),P?!0:d.clearNodes()}).wrapInList(f,r).command(()=>SMe(i,f)).command(()=>CMe(i,f)).run()},h4s=(s,t={},n={})=>({state:r,commands:a})=>{const{extendEmptyMarkRange:i=!1}=n,l=BE(s,r.schema);return GRe(r,l,t)?a.unsetMark(l,{extendEmptyMarkRange:i}):a.setMark(l,t)},m4s=(s,t,n={})=>({state:r,commands:a})=>{const i=Xx(s,r.schema),l=Xx(t,r.schema),o=CY(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})},p4s=(s,t={})=>({state:n,commands:r})=>{const a=Xx(s,n.schema);return CY(n,a,t)?r.lift(a):r.wrapIn(a,t)},f4s=()=>({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},g4s=()=>({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},x4s=(s,t={})=>({tr:n,state:r,dispatch:a})=>{var i;const{extendEmptyMarkRange:l=!1}=t,{selection:o}=n,c=BE(s,r.schema),{$from:d,empty:u,ranges:h}=o;if(!a)return!0;if(u&&l){let{from:m,to:f}=o;const g=(i=d.marks().find(x=>x.type===c))===null||i===void 0?void 0:i.attrs,y=Rqe(d,c,g);y&&(m=y.from,f=y.to),n.removeMark(m,f,c)}else h.forEach(m=>{n.removeMark(m.$from.pos,m.$to.pos,c)});return n.removeStoredMark(c),!0},y4s=(s,t={})=>({tr:n,state:r,dispatch:a})=>{let i=null,l=null;const o=g3e(typeof s=="string"?s:s.name,r.schema);return o?(o==="node"&&(i=Xx(s,r.schema)),o==="mark"&&(l=BE(s,r.schema)),a&&n.selection.ranges.forEach(c=>{const d=c.$from.pos,u=c.$to.pos;let h,m,f,g;n.selection.empty?r.doc.nodesBetween(d,u,(y,x)=>{i&&i===y.type&&(f=Math.max(x,d),g=Math.min(x+y.nodeSize,u),h=x,m=y)}):r.doc.nodesBetween(d,u,(y,x)=>{x=d&&x<=u&&(i&&i===y.type&&n.setNodeMarkup(x,void 0,{...y.attrs,...t}),l&&y.marks.length&&y.marks.forEach(_=>{if(l===_.type){const b=Math.max(x,d),k=Math.min(x+y.nodeSize,u);n.addMark(b,k,l.create({..._.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(f,g,l.create({...y.attrs,...t}))}))}),!0):!1},v4s=(s,t={})=>({state:n,dispatch:r})=>{const a=Xx(s,n.schema);return L5s(a,t)(n,r)},b4s=(s,t={})=>({state:n,dispatch:r})=>{const a=Xx(s,n.schema);return P5s(a,t)(n,r)};var _4s=Object.freeze({__proto__:null,blur:sSs,clearContent:nSs,clearNodes:rSs,command:aSs,createParagraphNear:iSs,cut:oSs,deleteCurrentNode:lSs,deleteNode:cSs,deleteRange:dSs,deleteSelection:uSs,enter:hSs,exitCode:mSs,extendMarkRange:pSs,first:fSs,focus:xSs,forEach:ySs,insertContent:vSs,insertContentAt:wSs,joinBackward:kSs,joinDown:NSs,joinForward:SSs,joinItemBackward:CSs,joinItemForward:ASs,joinTextblockBackward:TSs,joinTextblockForward:ESs,joinUp:jSs,keyboardShortcut:LSs,lift:PSs,liftEmptyBlock:ISs,liftListItem:DSs,newlineInCode:RSs,resetAttributes:OSs,scrollIntoView:FSs,selectAll:zSs,selectNodeBackward:BSs,selectNodeForward:$Ss,selectParentNode:USs,selectTextblockEnd:qSs,selectTextblockStart:VSs,setContent:HSs,setMark:n4s,setMeta:r4s,setNode:a4s,setNodeSelection:i4s,setTextSelection:o4s,sinkListItem:l4s,splitBlock:c4s,splitListItem:d4s,toggleList:u4s,toggleMark:h4s,toggleNode:m4s,toggleWrap:p4s,undoInputRule:f4s,unsetAllMarks:g4s,unsetMark:x4s,updateAttributes:y4s,wrapIn:v4s,wrapInList:b4s});const w4s=sy.create({name:"commands",addCommands(){return{..._4s}}}),j4s=sy.create({name:"drop",addProseMirrorPlugins(){return[new dx({key:new Yy("tiptapDrop"),props:{handleDrop:(s,t,n,r)=>{this.editor.emit("drop",{editor:this.editor,event:t,slice:n,moved:r})}}})]}}),N4s=sy.create({name:"editable",addProseMirrorPlugins(){return[new dx({key:new Yy("editable"),props:{editable:()=>this.editor.options.editable}})]}}),k4s=new Yy("focusEvents"),S4s=sy.create({name:"focusEvents",addProseMirrorPlugins(){const{editor:s}=this;return[new dx({key:k4s,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}}}})]}}),C4s=sy.create({name:"keymap",addKeyboardShortcuts(){const s=()=>this.editor.commands.first(({commands:l})=>[()=>l.undoInputRule(),()=>l.command(({tr:o})=>{const{selection:c,doc:d}=o,{empty:u,$anchor:h}=c,{pos:m,parent:f}=h,g=h.parent.isTextblock&&m>0?o.doc.resolve(m-1):h,y=g.parent.type.spec.isolating,x=h.pos-h.parentOffset,_=y&&g.parent.childCount===1?x===h.pos:nl.atStart(d).from===m;return!u||!f.type.isTextblock||f.textContent.length||!_||_&&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 SNe()||zCt()?i:a},addProseMirrorPlugins(){return[new dx({key:new Yy("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=nl.atStart(t.doc).from,d=nl.atEnd(t.doc).to;if(i||!(l===c&&o===d)||!zqe(n.doc))return;const m=n.tr,f=u3e({state:n,transaction:m}),{commands:g}=new h3e({editor:this.editor,state:f});if(g.clearNodes(),!!m.steps.length)return m}})]}}),A4s=sy.create({name:"paste",addProseMirrorPlugins(){return[new dx({key:new Yy("tiptapPaste"),props:{handlePaste:(s,t,n)=>{this.editor.emit("paste",{editor:this.editor,event:t,slice:n})}}})]}}),T4s=sy.create({name:"tabindex",addProseMirrorPlugins(){return[new dx({key:new Yy("tabindex"),props:{attributes:()=>this.editor.isEditable?{tabindex:"0"}:{}}})]}});class _I{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 _I(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 _I(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 _I(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 _I(o,this.editor,a,a?n:null);a&&(c.actualDepth=this.depth+1),t.push(new _I(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 E4s=`.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 M4s(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 L4s extends B5s{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=M4s(E4s,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=LCt(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?[N4s,tSs.configure({blockSeparator:(n=(t=this.options.coreExtensionOptions)===null||t===void 0?void 0:t.clipboardTextSerializer)===null||n===void 0?void 0:n.blockSeparator}),w4s,S4s,C4s,T4s,j4s,A4s].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 O7(a,this)}createCommandManager(){this.commandManager=new h3e({editor:this})}createSchema(){this.schema=this.extensionManager.schema}createView(){var t;let n;try{n=HRe(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=HRe(this.options.content,this.schema,this.options.parseOptions,{errorOnInvalidContent:!1})}const r=OCt(n,this.options.autofocus);this.view=new NCt(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:R7.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 UCt(this.state,t)}isActive(t,n){const r=typeof t=="string"?t:null,a=typeof t=="string"?n:t;return e4s(this.state,r,a)}getJSON(){return this.state.doc.toJSON()}getHTML(){return Iqe(this.state.doc.content,this.schema)}getText(t){const{blockSeparator:n=` `,textSerializers:r={}}=t||{};return YSs(this.state.doc,{blockSeparator:n,textSerializers:{...ICt(this.schema),...r}})}get isEmpty(){return zqe(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 _I(n,this)}get $doc(){return this.$pos(0)}}function KB(s){return new p3e({find:s.find,handler:({state:t,range:n,match:r})=>{const a=mc(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(Fqe(n.from,n.to,t.doc).filter(f=>f.mark.type.excluded.find(y=>y===s.type&&y!==f.mark.type)).filter(f=>f.to>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 qCt(s){return new p3e({find:s.find,handler:({state:t,range:n,match:r})=>{const a=mc(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 WRe(s){return new p3e({find:s.find,handler:({state:t,range:n,match:r})=>{const a=t.doc.resolve(n.from),i=mc(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 AY(s){return new p3e({find:s.find,handler:({state:t,range:n,match:r,chain:a})=>{const i=mc(s.getAttributes,void 0,r)||{},l=t.tr.delete(n.from,n.to),c=l.doc.resolve(n.from).blockRange(),d=c&&vqe(c,s.type,i);if(!d)return null;if(l.wrap(c,d),s.keepMarks&&s.editor){const{selection:h,storedMarks:m}=t,{splittableMarks:f}=s.editor.extensionManager,g=m||h.$to.parentOffset&&h.$from.marks();if(g){const y=g.filter(x=>f.includes(x.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&&FE(l.doc,n.from-1)&&(!s.joinPredicate||s.joinPredicate(r,u))&&l.join(n.from-1)}})}let Zy=class KRe{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=mc(eo(this,"addOptions",{name:this.name}))),this.storage=mc(eo(this,"addStorage",{name:this.name,options:this.options}))||{}}static create(t={}){return new KRe(t)}configure(t={}){const n=this.extend({...this.config,addOptions:()=>f3e(this.options,t)});return n.name=this.name,n.parent=this.parent,n}extend(t={}){const n=new KRe(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=mc(eo(n,"addOptions",{name:n.name})),n.storage=mc(eo(n,"addStorage",{name:n.name,options:n.options})),n}};function cR(s){return new Y5s({find:s.find,handler:({state:t,range:n,match:r,pasteEvent:a})=>{const i=mc(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(Fqe(n.from,n.to,t.doc).filter(g=>g.mark.type.excluded.find(x=>x===s.type&&x!==g.mark.type)).filter(g=>g.to>h).length)return null;mn.from&&l.delete(n.from+u,h),d=n.from+u+o.length,l.addMark(n.from+u,d,s.type.create(i||{})),l.removeStoredMark(s.type)}}})}function P4s(s,t){const{selection:n}=s,{$from:r}=n;if(n instanceof Do){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 I4s(s){return s&&s.__esModule&&Object.prototype.hasOwnProperty.call(s,"default")?s.default:s}var VCt={exports:{}},AMe={};/** * @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 Mat;function D4s(){if(Mat)return AMe;Mat=1;var s=Rt;function t(h,m){return h===m&&(h!==0||1/h===1/m)||h!==h&&m!==m}var n=typeof Object.is=="function"?Object.is:t,r=s.useState,a=s.useEffect,i=s.useLayoutEffect,l=s.useDebugValue;function o(h,m){var f=m(),g=r({inst:{value:f,getSnapshot:m}}),y=g[0].inst,x=g[1];return i(function(){y.value=f,y.getSnapshot=m,c(y)&&x({inst:y})},[h,f,m]),a(function(){return c(y)&&x({inst:y}),h(function(){c(y)&&x({inst:y})})},[h]),l(f),f}function c(h){var m=h.getSnapshot;h=h.value;try{var f=m();return!n(h,f)}catch{return!0}}function d(h,m){return m()}var u=typeof window>"u"||typeof window.document>"u"||typeof window.document.createElement>"u"?d:o;return AMe.useSyncExternalStore=s.useSyncExternalStore!==void 0?s.useSyncExternalStore:u,AMe}VCt.exports=D4s();var Bqe=VCt.exports;const R4s=(...s)=>t=>{s.forEach(n=>{typeof n=="function"?n(t):n&&(n.current=t)})},O4s=({contentComponent:s})=>{const t=Bqe.useSyncExternalStore(s.subscribe,s.getSnapshot,s.getServerSnapshot);return Rt.createElement(Rt.Fragment,null,Object.values(t))};function F4s(){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]:QBe.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 z4s extends Rt.Component{constructor(t){var n;super(t),this.editorContentRef=Rt.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=F4s(),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 Rt.createElement(Rt.Fragment,null,Rt.createElement("div",{ref:R4s(n,this.editorContentRef),...r}),(t==null?void 0:t.contentComponent)&&Rt.createElement(O4s,{contentComponent:t.contentComponent}))}}const B4s=N.forwardRef((s,t)=>{const n=Rt.useMemo(()=>Math.floor(Math.random()*4294967295).toString(),[s.editor]);return Rt.createElement(z4s,{key:n,innerRef:t,...s})}),$qe=Rt.memo(B4s);var $4s=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},U4s=I4s($4s),HCt={exports:{}},TMe={};/** * @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 Lat;function q4s(){if(Lat)return TMe;Lat=1;var s=Rt,t=Bqe;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 TMe.useSyncExternalStoreWithSelector=function(d,u,h,m,f){var g=i(null);if(g.current===null){var y={hasValue:!1,value:null};g.current=y}else y=g.current;g=o(function(){function _(P){if(!b){if(b=!0,k=P,P=m(P),f!==void 0&&y.hasValue){var I=y.value;if(f(I,P))return A=I}return A=P}if(I=A,r(k,P))return I;var M=m(P);return f!==void 0&&f(I,M)?I:(k=P,A=M)}var b=!1,k,A,T=h===void 0?null:h;return[function(){return _(u())},T===null?void 0:function(){return _(T())}]},[u,h,m,f]);var x=a(d,g[0],g[1]);return l(function(){y.hasValue=!0,y.value=x},[x]),c(x),x},TMe}HCt.exports=q4s();var V4s=HCt.exports;const H4s=typeof window<"u"?N.useLayoutEffect:N.useEffect;class G4s{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 W4s(s){var t;const[n]=N.useState(()=>new G4s(s.editor)),r=V4s.useSyncExternalStoreWithSelector(n.subscribe,n.getSnapshot,n.getServerSnapshot,s.selector,(t=s.equalityFn)!==null&&t!==void 0?t:U4s);return H4s(()=>n.watch(s.editor),[s.editor,n]),N.useDebugValue(r),r}const K4s=!1,YRe=typeof window>"u",Y4s=YRe||!!(typeof window<"u"&&window.next);class Uqe{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 YRe||Y4s?null:this.createEditor();if(this.options.current.immediatelyRender&&YRe&&K4s)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 L4s(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?Uqe.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 qqe(s={},t=[]){const n=N.useRef(s);n.current=s;const[r]=N.useState(()=>new Uqe(n)),a=Bqe.useSyncExternalStore(r.subscribe,r.getEditor,r.getServerSnapshot);return N.useDebugValue(a),N.useEffect(r.onRender(t)),W4s({editor:a,selector:({transactionNumber:i})=>s.shouldRerenderOnTransaction===!1?null:s.immediatelyRender&&i===0?0:i+1}),a}const Z4s=N.createContext({editor:null});Z4s.Consumer;const X4s=N.createContext({onDragStart:void 0}),Q4s=()=>N.useContext(X4s);Rt.forwardRef((s,t)=>{const{onDragStart:n}=Q4s(),r=s.as||"div";return Rt.createElement(r,{...s,ref:t,"data-node-view-wrapper":"",onDragStart:n,style:{whiteSpace:"normal",...s.style}})});const J4s=/^\s*>\s$/,e3s=Zy.create({name:"blockquote",addOptions(){return{HTMLAttributes:{}}},content:"block+",group:"block",defining:!0,parseHTML(){return[{tag:"blockquote"}]},renderHTML({HTMLAttributes:s}){return["blockquote",$m(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[AY({find:J4s,type:this.type})]}}),t3s=/(?:^|\s)(\*\*(?!\s+\*\*)((?:[^*]+))\*\*(?!\s+\*\*))$/,s3s=/(?:^|\s)(\*\*(?!\s+\*\*)((?:[^*]+))\*\*(?!\s+\*\*))/g,n3s=/(?:^|\s)(__(?!\s+__)((?:[^_]+))__(?!\s+__))$/,r3s=/(?:^|\s)(__(?!\s+__)((?:[^_]+))__(?!\s+__))/g,a3s=uN.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",$m(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[KB({find:t3s,type:this.type}),KB({find:n3s,type:this.type})]},addPasteRules(){return[cR({find:s3s,type:this.type}),cR({find:r3s,type:this.type})]}}),i3s="listItem",Pat="textStyle",Iat=/^\s*([-+*])\s$/,o3s=Zy.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",$m(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(i3s,this.editor.getAttributes(Pat)).run():s.toggleList(this.name,this.options.itemTypeName,this.options.keepMarks)}},addKeyboardShortcuts(){return{"Mod-Shift-8":()=>this.editor.commands.toggleBulletList()}},addInputRules(){let s=AY({find:Iat,type:this.type});return(this.options.keepMarks||this.options.keepAttributes)&&(s=AY({find:Iat,type:this.type,keepMarks:this.options.keepMarks,keepAttributes:this.options.keepAttributes,getAttributes:()=>this.editor.getAttributes(Pat),editor:this.editor})),[s]}}),l3s=/(^|[^`])`([^`]+)`(?!`)/,c3s=/(^|[^`])`([^`]+)`(?!`)/g,d3s=uN.create({name:"code",addOptions(){return{HTMLAttributes:{}}},excludes:"_",code:!0,exitable:!0,parseHTML(){return[{tag:"code"}]},renderHTML({HTMLAttributes:s}){return["code",$m(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[KB({find:l3s,type:this.type})]},addPasteRules(){return[cR({find:c3s,type:this.type})]}}),u3s=/^```([a-z]+)?[\s\n]$/,h3s=/^~~~([a-z]+)?[\s\n]$/,m3s=Zy.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",$m(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(nl.near(r.resolve(o))),!0)):s.commands.exitCode()}}},addInputRules(){return[WRe({find:u3s,type:this.type,getAttributes:s=>({language:s[1]})}),WRe({find:h3s,type:this.type,getAttributes:s=>({language:s[1]})})]},addProseMirrorPlugins(){return[new dx({key:new Yy("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(Vo.near(l.doc.resolve(Math.max(0,l.selection.from-2)))),l.setMeta("paste",!0),s.dispatch(l),!0}}})]}}),p3s=Zy.create({name:"doc",topNode:!0,content:"block+"});function f3s(s={}){return new dx({view(t){return new g3s(t,s)}})}class g3s{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 f=this.editorView.nodeDOM(this.cursorPos-(h?h.nodeSize:0));if(f){let g=f.getBoundingClientRect(),y=h?g.bottom:g.top;h&&m&&(y=(y+this.editorView.nodeDOM(this.cursorPos).getBoundingClientRect().top)/2);let x=this.width/2*o;r={left:g.left,right:g.right,top:y-x,bottom:y+x}}}}if(!r){let h=this.editorView.coordsAtPos(this.cursorPos),m=this.width/2*l;r={left:h.left-m,right:h.left+m,top:h.top,bottom:h.bottom}}let c=this.editorView.dom.offsetParent;this.element||(this.element=c.appendChild(document.createElement("div")),this.class&&(this.element.className=this.class),this.element.style.cssText="position: absolute; z-index: 50; pointer-events: none;",this.color&&(this.element.style.backgroundColor=this.color)),this.element.classList.toggle("prosemirror-dropcursor-block",n),this.element.classList.toggle("prosemirror-dropcursor-inline",!n);let d,u;if(!c||c==document.body&&getComputedStyle(c).position=="static")d=-pageXOffset,u=-pageYOffset;else{let h=c.getBoundingClientRect(),m=h.width/c.offsetWidth,f=h.height/c.offsetHeight;d=h.left-c.scrollLeft*m,u=h.top-c.scrollTop*f}this.element.style.left=(r.left-d)/l+"px",this.element.style.top=(r.top-u)/o+"px",this.element.style.width=(r.right-r.left)/l+"px",this.element.style.height=(r.bottom-r.top)/o+"px"}scheduleRemoval(t){clearTimeout(this.timeout),this.timeout=setTimeout(()=>this.setCursor(null),t)}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=R3t(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 x3s=sy.create({name:"dropCursor",addOptions(){return{color:"currentColor",width:1,class:void 0}},addProseMirrorPlugins(){return[f3s(this.options)]}});class of extends nl{constructor(t){super(t,t)}map(t,n){let r=t.resolve(n.map(this.head));return of.valid(r)?new of(r):nl.near(r)}content(){return li.empty}eq(t){return t instanceof of&&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 of(t.resolve(n.pos))}getBookmark(){return new Vqe(this.anchor)}static valid(t){let n=t.parent;if(n.inlineContent||!y3s(t)||!v3s(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&&of.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(of.valid(c))return c}for(;;){let l=n>0?i.firstChild:i.lastChild;if(!l){if(i.isAtom&&!i.isText&&!Do.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(of.valid(o))return o}return null}}}of.prototype.visible=!1;of.findFrom=of.findGapCursorFrom;nl.jsonID("gapcursor",of);class Vqe{constructor(t){this.pos=t}map(t){return new Vqe(t.map(this.pos))}resolve(t){let n=t.resolve(this.pos);return of.valid(n)?new of(n):nl.near(n)}}function GCt(s){return s.isAtom||s.spec.isolating||s.spec.createGapCursor}function y3s(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||GCt(a.type))return!0;if(a.inlineContent)return!1}}return!0}function v3s(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||GCt(a.type))return!0;if(a.inlineContent)return!1}}return!0}function b3s(){return new dx({props:{decorations:N3s,createSelectionBetween(s,t,n){return t.pos==n.pos&&of.valid(n)?new of(n):null},handleClick:w3s,handleKeyDown:_3s,handleDOMEvents:{beforeinput:j3s}}})}const _3s=Mqe({ArrowLeft:ise("horiz",-1),ArrowRight:ise("horiz",1),ArrowUp:ise("vert",-1),ArrowDown:ise("vert",1)});function ise(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 Vo){if(!i.endOfTextblock(n)||o.depth==0)return!1;c=!1,o=r.doc.resolve(t>0?o.after():o.before())}let d=of.findGapCursorFrom(o,t,c);return d?(a&&a(r.tr.setSelection(new of(d))),!0):!1}}function w3s(s,t,n){if(!s||!s.editable)return!1;let r=s.state.doc.resolve(t);if(!of.valid(r))return!1;let a=s.posAtCoords({left:n.clientX,top:n.clientY});return a&&a.inside>-1&&Do.isSelectable(s.state.doc.nodeAt(a.inside))?!1:(s.dispatch(s.state.tr.setSelection(new of(r))),!0)}function j3s(s,t){if(t.inputType!="insertCompositionText"||!(s.state.selection instanceof of))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=Ca.empty;for(let l=r.length-1;l>=0;l--)a=Ca.from(r[l].createAndFill(null,a));let i=s.state.tr.replace(n.pos,n.pos,new li(a,0,0));return i.setSelection(Vo.near(i.doc.resolve(n.pos+1))),s.dispatch(i),!1}function N3s(s){if(!(s.selection instanceof of))return null;let t=document.createElement("div");return t.className="ProseMirror-gapcursor",af.create(s.doc,[Fv.widget(s.selection.head,t,{key:"gapcursor"})])}const k3s=sy.create({name:"gapCursor",addProseMirrorPlugins(){return[b3s()]},extendNodeSchema(s){var t;const n={name:s.name,options:s.options,storage:s.storage};return{allowGapCursor:(t=mc(eo(s,"allowGapCursor",n)))!==null&&t!==void 0?t:null}}}),S3s=Zy.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",$m(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()}}}),C3s=Zy.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]}`,$m(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=>WRe({find:new RegExp(`^(#{${Math.min(...this.options.levels)},${s}})\\s$`),type:this.type,getAttributes:{level:s}}))}});var CNe=200,Zx=function(){};Zx.prototype.append=function(t){return t.length?(t=Zx.from(t),!this.length&&t||t.length=n?Zx.empty:this.sliceInner(Math.max(0,t),Math.min(this.length,n))};Zx.prototype.get=function(t){if(!(t<0||t>=this.length))return this.getInner(t)};Zx.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)};Zx.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};Zx.from=function(t){return t instanceof Zx?t:t&&t.length?new WCt(t):Zx.empty};var WCt=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<=CNe)return new t(this.values.concat(a.flatten()))},t.prototype.leafPrepend=function(a){if(this.length+a.length<=CNe)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}(Zx);Zx.empty=new WCt([]);var A3s=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}(Zx);const T3s=500;class B2{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 _C(h.map));let f=h.step.map(a.slice(i)),g;f&&l.maybeStep(f).doc&&(g=l.mapping.maps[l.mapping.maps.length-1],d.push(new _C(g,void 0,void 0,d.length+u.length))),i--,g&&a.appendMap(g,i)}else l.maybeStep(h.step);if(h.selection)return o=a?h.selection.map(a.slice(i)):h.selection,c=new B2(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;uM3s&&(o=E3s(o,d),l-=d),new B2(o.append(i),l)}remapping(t,n){let r=new _Y;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 B2(this.items.append(t.map(n=>new _C(n))),this.eventCount)}rebased(t,n){if(!this.eventCount)return this;let r=[],a=Math.max(0,this.items.length-n),i=t.mapping,l=t.steps.length,o=this.eventCount;this.items.forEach(m=>{m.selection&&o--},a);let c=n;this.items.forEach(m=>{let f=i.getMirror(--c);if(f==null)return;l=Math.min(l,f);let g=i.maps[f];if(m.step){let y=t.steps[f].invert(t.docs[f]),x=m.selection&&m.selection.map(i.slice(c+1,f));x&&o++,r.push(new _C(g,y,x))}else r.push(new _C(g))},a);let d=[];for(let m=n;mT3s&&(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 _C(d.invert(),c,u),m,f=a.length-1;(m=a.length&&a[f].merge(h))?a[f]=m:a.push(h)}}else l.map&&r--},this.items.length,0),new B2(Zx.from(a.reverse()),i)}}B2.empty=new B2(Zx.empty,0);function E3s(s,t){let n;return s.forEach((r,a)=>{if(r.selection&&t--==0)return n=a,!1}),s.slice(n)}let _C=class KCt{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 KCt(n.getMap().invert(),n,this.selection)}}};class XC{constructor(t,n,r,a,i){this.done=t,this.undone=n,this.prevRanges=r,this.prevTime=a,this.prevComposition=i}}const M3s=20;function L3s(s,t,n,r){let a=n.getMeta(LD),i;if(a)return a.historyState;n.getMeta(D3s)&&(s=new XC(s.done,s.undone,null,0,-1));let l=n.getMeta("appendedTransaction");if(n.steps.length==0)return s;if(l&&l.getMeta(LD))return l.getMeta(LD).redo?new XC(s.done.addTransform(n,void 0,r,Hwe(t)),s.undone,Dat(n.mapping.maps),s.prevTime,s.prevComposition):new XC(s.done,s.undone.addTransform(n,void 0,r,Hwe(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||!P3s(n,s.prevRanges)),d=l?EMe(s.prevRanges,n.mapping):Dat(n.mapping.maps);return new XC(s.done.addTransform(n,c?t.selection.getBookmark():void 0,r,Hwe(t)),B2.empty,d,n.time,o??s.prevComposition)}else return(i=n.getMeta("rebased"))?new XC(s.done.rebased(n,i),s.undone.rebased(n,i),EMe(s.prevRanges,n.mapping),s.prevTime,s.prevComposition):new XC(s.done.addMaps(n.mapping.maps),s.undone.addMaps(n.mapping.maps),EMe(s.prevRanges,n.mapping),s.prevTime,s.prevComposition)}function P3s(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 Dat(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 EMe(s,t){if(!s)return null;let n=[];for(let r=0;r{let a=LD.getState(n);if(!a||(s?a.undone:a.done).eventCount==0)return!1;if(r){let i=I3s(a,n,s);i&&r(t?i.scrollIntoView():i)}return!0}}const ZCt=YCt(!1,!0),XCt=YCt(!0,!0),O3s=sy.create({name:"history",addOptions(){return{depth:100,newGroupDelay:500}},addCommands(){return{undo:()=>({state:s,dispatch:t})=>ZCt(s,t),redo:()=>({state:s,dispatch:t})=>XCt(s,t)}},addProseMirrorPlugins(){return[R3s(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()}}}),F3s=Zy.create({name:"horizontalRule",addOptions(){return{HTMLAttributes:{}}},group:"block",parseHTML(){return[{tag:"hr"}]},renderHTML({HTMLAttributes:s}){return["hr",$m(this.options.HTMLAttributes,s)]},addCommands(){return{setHorizontalRule:()=>({chain:s,state:t})=>{if(!P4s(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}):t4s(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(Vo.create(l.doc,d.pos+1)):d.nodeAfter.isBlock?l.setSelection(Do.create(l.doc,d.pos)):l.setSelection(Vo.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(Vo.create(l.doc,u+1)))}l.scrollIntoView()}return!0}).run()}}},addInputRules(){return[qCt({find:/^(?:---|—-|___\s|\*\*\*\s)$/,type:this.type})]}}),z3s=/(?:^|\s)(\*(?!\s+\*)((?:[^*]+))\*(?!\s+\*))$/,B3s=/(?:^|\s)(\*(?!\s+\*)((?:[^*]+))\*(?!\s+\*))/g,$3s=/(?:^|\s)(_(?!\s+_)((?:[^_]+))_(?!\s+_))$/,U3s=/(?:^|\s)(_(?!\s+_)((?:[^_]+))_(?!\s+_))/g,q3s=uN.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",$m(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[KB({find:z3s,type:this.type}),KB({find:$3s,type:this.type})]},addPasteRules(){return[cR({find:B3s,type:this.type}),cR({find:U3s,type:this.type})]}}),V3s=Zy.create({name:"listItem",addOptions(){return{HTMLAttributes:{},bulletListTypeName:"bulletList",orderedListTypeName:"orderedList"}},content:"paragraph block*",defining:!0,parseHTML(){return[{tag:"li"}]},renderHTML({HTMLAttributes:s}){return["li",$m(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)}}}),H3s="listItem",Oat="textStyle",Fat=/^(\d+)\.\s$/,G3s=Zy.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",$m(this.options.HTMLAttributes,n),0]:["ol",$m(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(H3s,this.editor.getAttributes(Oat)).run():s.toggleList(this.name,this.options.itemTypeName,this.options.keepMarks)}},addKeyboardShortcuts(){return{"Mod-Shift-7":()=>this.editor.commands.toggleOrderedList()}},addInputRules(){let s=AY({find:Fat,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=AY({find:Fat,type:this.type,keepMarks:this.options.keepMarks,keepAttributes:this.options.keepAttributes,getAttributes:t=>({start:+t[1],...this.editor.getAttributes(Oat)}),joinPredicate:(t,n)=>n.childCount+n.attrs.start===+t[1],editor:this.editor})),[s]}}),W3s=Zy.create({name:"paragraph",priority:1e3,addOptions(){return{HTMLAttributes:{}}},group:"block",content:"inline*",parseHTML(){return[{tag:"p"}]},renderHTML({HTMLAttributes:s}){return["p",$m(this.options.HTMLAttributes,s),0]},addCommands(){return{setParagraph:()=>({commands:s})=>s.setNode(this.name)}},addKeyboardShortcuts(){return{"Mod-Alt-0":()=>this.editor.commands.setParagraph()}}}),K3s=/(?:^|\s)(~~(?!\s+~~)((?:[^~]+))~~(?!\s+~~))$/,Y3s=/(?:^|\s)(~~(?!\s+~~)((?:[^~]+))~~(?!\s+~~))/g,Z3s=uN.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",$m(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[KB({find:K3s,type:this.type})]},addPasteRules(){return[cR({find:Y3s,type:this.type})]}}),X3s=Zy.create({name:"text",group:"inline"}),Hqe=sy.create({name:"starterKit",addExtensions(){const s=[];return this.options.bold!==!1&&s.push(a3s.configure(this.options.bold)),this.options.blockquote!==!1&&s.push(e3s.configure(this.options.blockquote)),this.options.bulletList!==!1&&s.push(o3s.configure(this.options.bulletList)),this.options.code!==!1&&s.push(d3s.configure(this.options.code)),this.options.codeBlock!==!1&&s.push(m3s.configure(this.options.codeBlock)),this.options.document!==!1&&s.push(p3s.configure(this.options.document)),this.options.dropcursor!==!1&&s.push(x3s.configure(this.options.dropcursor)),this.options.gapcursor!==!1&&s.push(k3s.configure(this.options.gapcursor)),this.options.hardBreak!==!1&&s.push(S3s.configure(this.options.hardBreak)),this.options.heading!==!1&&s.push(C3s.configure(this.options.heading)),this.options.history!==!1&&s.push(O3s.configure(this.options.history)),this.options.horizontalRule!==!1&&s.push(F3s.configure(this.options.horizontalRule)),this.options.italic!==!1&&s.push(q3s.configure(this.options.italic)),this.options.listItem!==!1&&s.push(V3s.configure(this.options.listItem)),this.options.orderedList!==!1&&s.push(G3s.configure(this.options.orderedList)),this.options.paragraph!==!1&&s.push(W3s.configure(this.options.paragraph)),this.options.strike!==!1&&s.push(Z3s.configure(this.options.strike)),this.options.text!==!1&&s.push(X3s.configure(this.options.text)),s}}),Q3s="aaa1rp3bb0ott3vie4c1le2ogado5udhabi7c0ademy5centure6ountant0s9o1tor4d0s1ult4e0g1ro2tna4f0l1rica5g0akhan5ency5i0g1rbus3force5tel5kdn3l0ibaba4pay4lfinanz6state5y2sace3tom5m0azon4ericanexpress7family11x2fam3ica3sterdam8nalytics7droid5quan4z2o0l2partments8p0le4q0uarelle8r0ab1mco4chi3my2pa2t0e3s0da2ia2sociates9t0hleta5torney7u0ction5di0ble3o3spost5thor3o0s4w0s2x0a2z0ure5ba0by2idu3namex4d1k2r0celona5laycard4s5efoot5gains6seball5ketball8uhaus5yern5b0c1t1va3cg1n2d1e0ats2uty4er2rlin4st0buy5t2f1g1h0arti5i0ble3d1ke2ng0o3o1z2j1lack0friday9ockbuster8g1omberg7ue3m0s1w2n0pparibas9o0ats3ehringer8fa2m1nd2o0k0ing5sch2tik2on4t1utique6x2r0adesco6idgestone9oadway5ker3ther5ussels7s1t1uild0ers6siness6y1zz3v1w1y1z0h3ca0b1fe2l0l1vinklein9m0era3p2non3petown5ital0one8r0avan4ds2e0er0s4s2sa1e1h1ino4t0ering5holic7ba1n1re3c1d1enter4o1rn3f0a1d2g1h0anel2nel4rity4se2t2eap3intai5ristmas6ome4urch5i0priani6rcle4sco3tadel4i0c2y3k1l0aims4eaning6ick2nic1que6othing5ud3ub0med6m1n1o0ach3des3ffee4llege4ogne5m0mbank4unity6pany2re3uter5sec4ndos3struction8ulting7tact3ractors9oking4l1p2rsica5untry4pon0s4rses6pa2r0edit0card4union9icket5own3s1uise0s6u0isinella9v1w1x1y0mru3ou3z2dad1nce3ta1e1ing3sun4y2clk3ds2e0al0er2s3gree4livery5l1oitte5ta3mocrat6ntal2ist5si0gn4v2hl2iamonds6et2gital5rect0ory7scount3ver5h2y2j1k1m1np2o0cs1tor4g1mains5t1wnload7rive4tv2ubai3nlop4pont4rban5vag2r2z2earth3t2c0o2deka3u0cation8e1g1mail3erck5nergy4gineer0ing9terprises10pson4quipment8r0icsson6ni3s0q1tate5t1u0rovision8s2vents5xchange6pert3osed4ress5traspace10fage2il1rwinds6th3mily4n0s2rm0ers5shion4t3edex3edback6rrari3ero6i0delity5o2lm2nal1nce1ial7re0stone6mdale6sh0ing5t0ness6j1k1lickr3ghts4r2orist4wers5y2m1o0o0d1tball6rd1ex2sale4um3undation8x2r0ee1senius7l1ogans4ntier7tr2ujitsu5n0d2rniture7tbol5yi3ga0l0lery3o1up4me0s3p1rden4y2b0iz3d0n2e0a1nt0ing5orge5f1g0ee3h1i0ft0s3ves2ing5l0ass3e1obal2o4m0ail3bh2o1x2n1odaddy5ld0point6f2o0dyear5g0le4p1t1v2p1q1r0ainger5phics5tis4een3ipe3ocery4up4s1t1u0cci3ge2ide2tars5ru3w1y2hair2mburg5ngout5us3bo2dfc0bank7ealth0care8lp1sinki6re1mes5iphop4samitsu7tachi5v2k0t2m1n1ockey4ldings5iday5medepot5goods5s0ense7nda3rse3spital5t0ing5t0els3mail5use3w2r1sbc3t1u0ghes5yatt3undai7ibm2cbc2e1u2d1e0ee3fm2kano4l1m0amat4db2mo0bilien9n0c1dustries8finiti5o2g1k1stitute6urance4e4t0ernational10uit4vestments10o1piranga7q1r0ish4s0maili5t0anbul7t0au2v3jaguar4va3cb2e0ep2tzt3welry6io2ll2m0p2nj2o0bs1urg4t1y2p0morgan6rs3uegos4niper7kaufen5ddi3e0rryhotels6properties14fh2g1h1i0a1ds2m1ndle4tchen5wi3m1n1oeln3matsu5sher5p0mg2n2r0d1ed3uokgroup8w1y0oto4z2la0caixa5mborghini8er3nd0rover6xess5salle5t0ino3robe5w0yer5b1c1ds2ease3clerc5frak4gal2o2xus4gbt3i0dl2fe0insurance9style7ghting6ke2lly3mited4o2ncoln4k2ve1ing5k1lc1p2oan0s3cker3us3l1ndon4tte1o3ve3pl0financial11r1s1t0d0a3u0ndbeck6xe1ury5v1y2ma0drid4if1son4keup4n0agement7go3p1rket0ing3s4riott5shalls7ttel5ba2c0kinsey7d1e0d0ia3et2lbourne7me1orial6n0u2rckmsd7g1h1iami3crosoft7l1ni1t2t0subishi9k1l0b1s2m0a2n1o0bi0le4da2e1i1m1nash3ey2ster5rmon3tgage6scow4to0rcycles9v0ie4p1q1r1s0d2t0n1r2u0seum3ic4v1w1x1y1z2na0b1goya4me2vy3ba2c1e0c1t0bank4flix4work5ustar5w0s2xt0direct7us4f0l2g0o2hk2i0co2ke1on3nja3ssan1y5l1o0kia3rton4w0ruz3tv4p1r0a1w2tt2u1yc2z2obi1server7ffice5kinawa6layan0group9lo3m0ega4ne1g1l0ine5oo2pen3racle3nge4g0anic5igins6saka4tsuka4t2vh3pa0ge2nasonic7ris2s1tners4s1y3y2ccw3e0t2f0izer5g1h0armacy6d1ilips5one2to0graphy6s4ysio5ics1tet2ures6d1n0g1k2oneer5zza4k1l0ace2y0station9umbing5s3m1n0c2ohl2ker3litie5rn2st3r0axi3ess3ime3o0d0uctions8f1gressive8mo2perties3y5tection8u0dential9s1t1ub2w0c2y2qa1pon3uebec3st5racing4dio4e0ad1lestate6tor2y4cipes5d0stone5umbrella9hab3ise0n3t2liance6n0t0als5pair3ort3ublican8st0aurant8view0s5xroth6ich0ardli6oh3l1o1p2o0cks3deo3gers4om3s0vp3u0gby3hr2n2w0e2yukyu6sa0arland6fe0ty4kura4le1on3msclub4ung5ndvik0coromant12ofi4p1rl2s1ve2xo3b0i1s2c0b1haeffler7midt4olarships8ol3ule3warz5ience5ot3d1e0arch3t2cure1ity6ek2lect4ner3rvices6ven3w1x0y3fr2g1h0angrila6rp3ell3ia1ksha5oes2p0ping5uji3w3i0lk2na1gles5te3j1k0i0n2y0pe4l0ing4m0art3ile4n0cf3o0ccer3ial4ftbank4ware6hu2lar2utions7ng1y2y2pa0ce3ort2t3r0l2s1t0ada2ples4r1tebank4farm7c0group6ockholm6rage3e3ream4udio2y3yle4u0cks3pplies3y2ort5rf1gery5zuki5v1watch4iss4x1y0dney4stems6z2tab1ipei4lk2obao4rget4tamotors6r2too4x0i3c0i2d0k2eam2ch0nology8l1masek5nnis4va3f1g1h0d1eater2re6iaa2ckets5enda4ps2res2ol4j0maxx4x2k0maxx5l1m0all4n1o0day3kyo3ols3p1ray3shiba5tal3urs3wn2yota3s3r0ade1ing4ining5vel0ers0insurance16ust3v2t1ube2i1nes3shu4v0s2w1z2ua1bank3s2g1k1nicom3versity8o2ol2ps2s1y1z2va0cations7na1guard7c1e0gas3ntures6risign5mögensberater2ung14sicherung10t2g1i0ajes4deo3g1king4llas4n1p1rgin4sa1ion4va1o3laanderen9n1odka3lvo3te1ing3o2yage5u2wales2mart4ter4ng0gou5tch0es6eather0channel12bcam3er2site5d0ding5ibo2r3f1hoswho6ien2ki2lliamhill9n0dows4e1ners6me2olterskluwer11odside6rk0s2ld3w2s1tc1f3xbox3erox4ihuan4n2xx2yz3yachts4hoo3maxun5ndex5e1odobashi7ga2kohama6u0tube6t1un3za0ppos4ra3ero3ip2m1one3uerich6w2",J3s="ελ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",ZRe="numeric",XRe="ascii",QRe="alpha",tK="asciinumeric",GH="alphanumeric",JRe="domain",QCt="emoji",eCs="scheme",tCs="slashscheme",LMe="whitespace";function sCs(s,t){return s in t||(t[s]=[]),t[s]}function RI(s,t,n){t[ZRe]&&(t[tK]=!0,t[GH]=!0),t[XRe]&&(t[tK]=!0,t[QRe]=!0),t[tK]&&(t[GH]=!0),t[QRe]&&(t[GH]=!0),t[GH]&&(t[JRe]=!0),t[QCt]&&(t[JRe]=!0);for(const r in t){const a=sCs(r,n);a.indexOf(s)<0&&a.push(s)}}function nCs(s,t){const n={};for(const r in t)t[r].indexOf(s)>=0&&(n[r]=!0);return n}function H1(s=null){this.j={},this.jr=[],this.jd=null,this.t=s}H1.groups={};H1.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),Yp=(s,t,n,r,a)=>s.tr(t,n,r,a),zat=(s,t,n,r,a)=>s.ts(t,n,r,a),Ma=(s,t,n,r,a)=>s.tt(t,n,r,a),KS="WORD",eOe="UWORD",JCt="ASCIINUMERICAL",eAt="ALPHANUMERICAL",TY="LOCALHOST",tOe="TLD",sOe="UTLD",Gwe="SCHEME",r7="SLASH_SCHEME",Gqe="NUM",nOe="WS",Wqe="NL",sK="OPENBRACE",nK="CLOSEBRACE",ANe="OPENBRACKET",TNe="CLOSEBRACKET",ENe="OPENPAREN",MNe="CLOSEPAREN",LNe="OPENANGLEBRACKET",PNe="CLOSEANGLEBRACKET",INe="FULLWIDTHLEFTPAREN",DNe="FULLWIDTHRIGHTPAREN",RNe="LEFTCORNERBRACKET",ONe="RIGHTCORNERBRACKET",FNe="LEFTWHITECORNERBRACKET",zNe="RIGHTWHITECORNERBRACKET",BNe="FULLWIDTHLESSTHAN",$Ne="FULLWIDTHGREATERTHAN",UNe="AMPERSAND",qNe="APOSTROPHE",VNe="ASTERISK",QC="AT",HNe="BACKSLASH",GNe="BACKTICK",WNe="CARET",uA="COLON",Kqe="COMMA",KNe="DOLLAR",gk="DOT",YNe="EQUALS",Yqe="EXCLAMATION",Pw="HYPHEN",rK="PERCENT",ZNe="PIPE",XNe="PLUS",QNe="POUND",aK="QUERY",Zqe="QUOTE",tAt="FULLWIDTHMIDDLEDOT",Xqe="SEMI",xk="SLASH",iK="TILDE",JNe="UNDERSCORE",sAt="EMOJI",eke="SYM";var nAt=Object.freeze({__proto__:null,ALPHANUMERICAL:eAt,AMPERSAND:UNe,APOSTROPHE:qNe,ASCIINUMERICAL:JCt,ASTERISK:VNe,AT:QC,BACKSLASH:HNe,BACKTICK:GNe,CARET:WNe,CLOSEANGLEBRACKET:PNe,CLOSEBRACE:nK,CLOSEBRACKET:TNe,CLOSEPAREN:MNe,COLON:uA,COMMA:Kqe,DOLLAR:KNe,DOT:gk,EMOJI:sAt,EQUALS:YNe,EXCLAMATION:Yqe,FULLWIDTHGREATERTHAN:$Ne,FULLWIDTHLEFTPAREN:INe,FULLWIDTHLESSTHAN:BNe,FULLWIDTHMIDDLEDOT:tAt,FULLWIDTHRIGHTPAREN:DNe,HYPHEN:Pw,LEFTCORNERBRACKET:RNe,LEFTWHITECORNERBRACKET:FNe,LOCALHOST:TY,NL:Wqe,NUM:Gqe,OPENANGLEBRACKET:LNe,OPENBRACE:sK,OPENBRACKET:ANe,OPENPAREN:ENe,PERCENT:rK,PIPE:ZNe,PLUS:XNe,POUND:QNe,QUERY:aK,QUOTE:Zqe,RIGHTCORNERBRACKET:ONe,RIGHTWHITECORNERBRACKET:zNe,SCHEME:Gwe,SEMI:Xqe,SLASH:xk,SLASH_SCHEME:r7,SYM:eke,TILDE:iK,TLD:tOe,UNDERSCORE:JNe,UTLD:sOe,UWORD:eOe,WORD:KS,WS:nOe});const PS=/[a-z]/,FV=new RegExp("\\p{L}","u"),PMe=new RegExp("\\p{Emoji}","u"),IS=/\d/,IMe=/\s/,Bat="\r",DMe=` `,rCs="️",aCs="‍",RMe="";let ose=null,lse=null;function iCs(s=[]){const t={};H1.groups=t;const n=new H1;ose==null&&(ose=$at(Q3s)),lse==null&&(lse=$at(J3s)),Ma(n,"'",qNe),Ma(n,"{",sK),Ma(n,"}",nK),Ma(n,"[",ANe),Ma(n,"]",TNe),Ma(n,"(",ENe),Ma(n,")",MNe),Ma(n,"<",LNe),Ma(n,">",PNe),Ma(n,"(",INe),Ma(n,")",DNe),Ma(n,"「",RNe),Ma(n,"」",ONe),Ma(n,"『",FNe),Ma(n,"』",zNe),Ma(n,"<",BNe),Ma(n,">",$Ne),Ma(n,"&",UNe),Ma(n,"*",VNe),Ma(n,"@",QC),Ma(n,"`",GNe),Ma(n,"^",WNe),Ma(n,":",uA),Ma(n,",",Kqe),Ma(n,"$",KNe),Ma(n,".",gk),Ma(n,"=",YNe),Ma(n,"!",Yqe),Ma(n,"-",Pw),Ma(n,"%",rK),Ma(n,"|",ZNe),Ma(n,"+",XNe),Ma(n,"#",QNe),Ma(n,"?",aK),Ma(n,'"',Zqe),Ma(n,"/",xk),Ma(n,";",Xqe),Ma(n,"~",iK),Ma(n,"_",JNe),Ma(n,"\\",HNe),Ma(n,"・",tAt);const r=Yp(n,IS,Gqe,{[ZRe]:!0});Yp(r,IS,r);const a=Yp(r,PS,JCt,{[tK]:!0}),i=Yp(r,FV,eAt,{[GH]:!0}),l=Yp(n,PS,KS,{[XRe]:!0});Yp(l,IS,a),Yp(l,PS,l),Yp(a,IS,a),Yp(a,PS,a);const o=Yp(n,FV,eOe,{[QRe]:!0});Yp(o,PS),Yp(o,IS,i),Yp(o,FV,o),Yp(i,IS,i),Yp(i,PS),Yp(i,FV,i);const c=Ma(n,DMe,Wqe,{[LMe]:!0}),d=Ma(n,Bat,nOe,{[LMe]:!0}),u=Yp(n,IMe,nOe,{[LMe]:!0});Ma(n,RMe,u),Ma(d,DMe,c),Ma(d,RMe,u),Yp(d,IMe,u),Ma(u,Bat),Ma(u,DMe),Yp(u,IMe,u),Ma(u,RMe,u);const h=Yp(n,PMe,sAt,{[QCt]:!0});Ma(h,"#"),Yp(h,PMe,h),Ma(h,rCs,h);const m=Ma(h,aCs);Ma(m,"#"),Yp(m,PMe,h);const f=[[PS,l],[IS,a]],g=[[PS,null],[FV,o],[IS,i]];for(let y=0;yy[0]>x[0]?1:-1);for(let y=0;y=0?b[JRe]=!0:PS.test(x)?IS.test(x)?b[tK]=!0:b[XRe]=!0:b[ZRe]=!0,zat(n,x,x,b)}return zat(n,"localhost",TY,{ascii:!0}),n.jd=new H1(eke),{start:n,tokens:Object.assign({groups:t},nAt)}}function rAt(s,t){const n=oCs(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 oCs(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 wC(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 EY={defaultProtocol:"http",events:null,format:Uat,formatHref:Uat,nl2br:!1,tagName:"a",target:null,rel:null,validate:!0,truncate:1/0,className:null,attributes:null,ignoreTags:[],render:null};function Qqe(s,t=null){let n=Object.assign({},EY);s&&(n=Object.assign(n,s instanceof Qqe?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=EY.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 x3e(s,t){class n extends aAt{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 qat=x3e("email",{isLink:!0,toHref(){return"mailto:"+this.toString()}}),Vat=x3e("text"),lCs=x3e("nl"),cse=x3e("url",{isLink:!0,toHref(s=EY.defaultProtocol){return this.hasProtocol()?this.v:`${s}://${this.v}`},hasProtocol(){const s=this.tk;return s.length>=2&&s[0].t!==TY&&s[1].t===uA}}),ww=s=>new H1(s);function cCs({groups:s}){const t=s.domain.concat([UNe,VNe,QC,HNe,GNe,WNe,KNe,YNe,Pw,Gqe,rK,ZNe,XNe,QNe,xk,eke,iK,JNe]),n=[qNe,uA,Kqe,gk,Yqe,rK,aK,Zqe,Xqe,LNe,PNe,sK,nK,TNe,ANe,ENe,MNe,INe,DNe,RNe,ONe,FNe,zNe,BNe,$Ne],r=[UNe,qNe,VNe,HNe,GNe,WNe,KNe,YNe,Pw,sK,nK,rK,ZNe,XNe,QNe,aK,xk,eke,iK,JNe],a=ww(),i=Ma(a,iK);hc(i,r,i),hc(i,s.domain,i);const l=ww(),o=ww(),c=ww();hc(a,s.domain,l),hc(a,s.scheme,o),hc(a,s.slashscheme,c),hc(l,r,i),hc(l,s.domain,l);const d=Ma(l,QC);Ma(i,QC,d),Ma(o,QC,d),Ma(c,QC,d);const u=Ma(i,gk);hc(u,r,i),hc(u,s.domain,i);const h=ww();hc(d,s.domain,h),hc(h,s.domain,h);const m=Ma(h,gk);hc(m,s.domain,h);const f=ww(qat);hc(m,s.tld,f),hc(m,s.utld,f),Ma(d,TY,f);const g=Ma(h,Pw);Ma(g,Pw,g),hc(g,s.domain,h),hc(f,s.domain,h),Ma(f,gk,m),Ma(f,Pw,g);const y=Ma(f,uA);hc(y,s.numeric,qat);const x=Ma(l,Pw),_=Ma(l,gk);Ma(x,Pw,x),hc(x,s.domain,l),hc(_,r,i),hc(_,s.domain,l);const b=ww(cse);hc(_,s.tld,b),hc(_,s.utld,b),hc(b,s.domain,l),hc(b,r,i),Ma(b,gk,_),Ma(b,Pw,x),Ma(b,QC,d);const k=Ma(b,uA),A=ww(cse);hc(k,s.numeric,A);const T=ww(cse),P=ww();hc(T,t,T),hc(T,n,P),hc(P,t,T),hc(P,n,P),Ma(b,xk,T),Ma(A,xk,T);const I=Ma(o,uA),M=Ma(c,uA),L=Ma(M,xk),z=Ma(L,xk);hc(o,s.domain,l),Ma(o,gk,_),Ma(o,Pw,x),hc(c,s.domain,l),Ma(c,gk,_),Ma(c,Pw,x),hc(I,s.domain,T),Ma(I,xk,T),Ma(I,aK,T),hc(z,s.domain,T),hc(z,t,T),Ma(z,xk,T);const $=[[sK,nK],[ANe,TNe],[ENe,MNe],[LNe,PNe],[INe,DNe],[RNe,ONe],[FNe,zNe],[BNe,$Ne]];for(let V=0;V<$.length;V++){const[W,G]=$[V],X=Ma(T,W);Ma(P,W,X),Ma(X,G,T);const te=ww(cse);hc(X,t,te);const ne=ww();hc(X,n),hc(te,t,te),hc(te,n,ne),hc(ne,t,te),hc(ne,n,ne),Ma(te,G,T),Ma(ne,G,T)}return Ma(a,TY,b),Ma(a,Wqe,lCs),{start:a,tokens:nAt}}function dCs(s,t,n){let r=n.length,a=0,i=[],l=[];for(;a=0&&m++,a++,u++;if(m<0)a-=u,a0&&(i.push(OMe(Vat,t,l)),l=[]),a-=m,u-=m;const f=h.t,g=n.slice(a-u,a);i.push(OMe(f,t,g))}}return l.length>0&&i.push(OMe(Vat,t,l)),i}function OMe(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 uCs=typeof console<"u"&&console&&console.warn||(()=>{}),hCs="until manual call of linkify.init(). Register all schemes and plugins before invoking linkify the first time.",nm={scanner:null,parser:null,tokenQueue:[],pluginQueue:[],customSchemes:[],initialized:!1};function mCs(){return H1.groups={},nm.scanner=null,nm.parser=null,nm.tokenQueue=[],nm.pluginQueue=[],nm.customSchemes=[],nm.initialized=!1,nm}function Hat(s,t=!1){if(nm.initialized&&uCs(`linkifyjs: already initialized - will not register custom scheme "${s}" ${hCs}`),!/^[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`);nm.customSchemes.push([s,t])}function pCs(){nm.scanner=iCs(nm.customSchemes);for(let s=0;s{const a=t.some(d=>d.docChanged)&&!n.doc.eq(r.doc),i=t.some(d=>d.getMeta("preventAutolink"));if(!a||i)return;const{tr:l}=r,o=GSs(n.doc,[...t]);if(JSs(o).forEach(({newRange:d})=>{const u=KSs(r.doc,d,f=>f.isTextblock);let h,m;if(u.length>1)h=u[0],m=r.doc.textBetween(h.pos,h.pos+h.node.nodeSize,void 0," ");else if(u.length){const f=r.doc.textBetween(d.from,d.to," "," ");if(!gCs.test(f))return;h=u[0],m=r.doc.textBetween(h.pos,d.to,void 0," ")}if(h&&m){const f=m.split(fCs).filter(Boolean);if(f.length<=0)return!1;const g=f[f.length-1],y=h.pos+m.lastIndexOf(g);if(!g)return!1;const x=Jqe(g).map(_=>_.toObject(s.defaultProtocol));if(!yCs(x))return!1;x.filter(_=>_.isLink).map(_=>({..._,from:y+_.start+1,to:y+_.end+1})).filter(_=>r.schema.marks.code?!r.doc.rangeHasMark(_.from,_.to,r.schema.marks.code):!0).filter(_=>s.validate(_.value)).filter(_=>s.shouldAutoLink(_.value)).forEach(_=>{Fqe(_.from,_.to,r.doc).some(b=>b.mark.type===s.type)||l.addMark(_.from,_.to,s.type.create({href:_.href}))})}}),!!l.steps.length)return l}})}function bCs(s){return new dx({key:new Yy("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=UCt(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 _Cs(s){return new dx({key:new Yy("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=iAt(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 F6(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(xCs,"").match(new RegExp(`^(?:(?:${n.join("|")}):|[^a-z]|[a-z0-9+.-]+(?:[^a-z+.-:]|$))`,"i"))}const tVe=uN.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"){Hat(s);return}Hat(s.scheme,s.optionalSlashes)})},onDestroy(){mCs()},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)=>!!F6(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=>!!F6(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=>!!F6(t,this.options.protocols),protocols:this.options.protocols,defaultProtocol:this.options.defaultProtocol})?["a",$m(this.options.HTMLAttributes,s),0]:["a",$m(this.options.HTMLAttributes,{...s,href:""}),0]},addCommands(){return{setLink:s=>({chain:t})=>{const{href:n}=s;return this.options.isAllowedUri(n,{defaultValidate:r=>!!F6(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=>!!F6(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[cR({find:s=>{const t=[];if(s){const{protocols:n,defaultProtocol:r}=this.options,a=iAt(s).filter(i=>i.isLink&&this.options.isAllowedUri(i.value,{defaultValidate:l=>!!F6(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(vCs({type:this.type,defaultProtocol:this.options.defaultProtocol,validate:r=>this.options.isAllowedUri(r,{defaultValidate:a=>!!F6(a,t),protocols:t,defaultProtocol:n}),shouldAutoLink:this.options.shouldAutoLink})),this.options.openOnClick===!0&&s.push(bCs({type:this.type})),this.options.linkOnPaste&&s.push(_Cs({editor:this.editor,defaultProtocol:this.options.defaultProtocol,type:this.type})),s}}),sVe=sy.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")}}}),wCs=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}`)})},nVe=uN.create({name:"textStyle",priority:101,addOptions(){return{HTMLAttributes:{},mergeNestedSpanStyles:!1}},parseHTML(){return[{tag:"span",getAttrs:s=>s.hasAttribute("style")?(this.options.mergeNestedSpanStyles&&wCs(s),{}):!1}]},renderHTML({HTMLAttributes:s}){return["span",$m(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}}}}),jCs=/(?:^|\s)(!\[(.+|:?)]\((\S+)(?:(?:\s+)["'](\S+)["'])?\))$/,NCs=Zy.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",$m(this.options.HTMLAttributes,s)]},addCommands(){return{setImage:s=>({commands:t})=>t.insertContent({type:this.name,attrs:s})}},addInputRules(){return[qCt({find:jCs,type:this.type,getAttributes:s=>{const[,,t,n,r]=s;return{src:n,alt:t,title:r}}})]}});let rOe,aOe;if(typeof WeakMap<"u"){let s=new WeakMap;rOe=t=>s.get(t),aOe=(t,n)=>(s.set(t,n),n)}else{const s=[];let n=0;rOe=r=>{for(let a=0;a(n==10&&(n=0),s[n++]=r,s[n++]=a)}var lf=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:_-k});break}const A=a+k*t;for(let T=0;Tr&&(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 CCs(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 TCs(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 xN(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 y3e(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=dR(t.$head)||ECs(t.$head);if(n)return n;throw new RangeError(`No cell found around position ${t.head}`)}function ECs(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 iOe(s){return s.parent.type.spec.tableRole=="row"&&!!s.nodeAfter}function MCs(s){return s.node(0).resolve(s.pos+s.nodeAfter.nodeSize)}function rVe(s,t){return s.depth==t.depth&&s.pos>=t.start(-1)&&s.pos<=t.end(-1)}function oAt(s,t,n){const r=s.node(-1),a=lf.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 uR(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 lAt(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 $3t(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(iOe(r)&&iOe(a)&&rVe(r,a)){const i=this.$anchorCell.node(-1)!=r.node(-1);return i&&this.isRowSelection()?YS.rowSelection(r,a):i&&this.isColSelection()?YS.colSelection(r,a):new YS(r,a)}return Vo.between(r,a)}content(){const t=this.$anchorCell.node(-1),n=lf.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||x>0){let _=g.attrs;if(y>0&&(_=uR(_,0,y)),x>0&&(_=uR(_,_.colspan-x,x)),f.lefta.bottom){const _={...g.attrs,rowspan:Math.min(f.bottom,a.bottom)-Math.max(f.top,a.top)};f.top0)return!1;const r=t+this.$anchorCell.nodeAfter.attrs.rowspan,a=n+this.$headCell.nodeAfter.attrs.rowspan;return Math.max(r,a)==this.$headCell.node(-1).childCount}static colSelection(t,n=t){const r=t.node(-1),a=lf.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 YS&&t.$anchorCell.pos==this.$anchorCell.pos&&t.$headCell.pos==this.$headCell.pos}static rowSelection(t,n=t){const r=t.node(-1),a=lf.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(Fv.node(r,r+n.nodeSize,{class:"selectedCell"}))}),af.create(s.doc,t)}function DCs({$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 RCs({$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 OCs(s,t,n){const r=(t||s).selection,a=(t||s).doc;let i,l;if(r instanceof Do&&(l=r.node.type.spec.tableRole)){if(l=="cell"||l=="header_cell")i=zh.create(a,r.from);else if(l=="row"){const o=a.resolve(r.from+1);i=zh.rowSelection(o,o)}else if(!n){const o=lf.get(r.node),c=r.from+1,d=c+o.map[o.width*o.height-1];i=zh.create(a,c+1,d)}}else r instanceof Vo&&DCs(r)?i=Vo.create(a,r.from):r instanceof Vo&&RCs(r)&&(i=Vo.create(a,r.$from.start(),r.$from.end()));return i&&(t||(t=s.tr)).setSelection(i),t}const FCs=new Yy("fix-tables");function dAt(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=zCs(s,a,i,n))};return t?t.doc!=s.doc&&dAt(t.doc,s.doc,0,r):s.doc.descendants(r),n}function zCs(s,t,n,r){const a=lf.get(t);if(!a.problems)return r;r||(r=s.tr);const i=[];for(let c=0;c0){let f="cell";u.firstChild&&(f=u.firstChild.type.spec.tableRole);const g=[];for(let x=0;x0?-1:0;LCs(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;VCs(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=Gat(d)?c+1:u;i.replaceWith(h+r.tableStart,u+r.tableStart,o)}i.setSelection(new zh(i.doc.resolve(c+r.tableStart))),t(i)}return!0}function Kat(s,t){const n=Vy(s.schema);return ZCs(({node:r})=>n[r.type.spec.tableRole])(s,t)}function ZCs(s){return(t,n)=>{const r=t.selection;let a,i;if(r instanceof zh){if(r.$anchorCell.pos!=r.$headCell.pos)return!1;a=r.$anchorCell.nodeAfter,i=r.$anchorCell.pos}else{var l;if(a=TCs(r.$from),!a)return!1;i=(l=dR(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=W5(t),h=t.tr;for(let f=0;f{l.attrs[s]!==t&&i.setNodeMarkup(o,null,{...l.attrs,[s]:t})}):i.setNodeMarkup(a.pos,null,{...a.nodeAfter.attrs,[s]:t}),r(i)}return!0}}function QCs(s){return function(t,n){if(!xN(t))return!1;if(n){const r=Vy(t.schema),a=W5(t),i=t.tr,l=a.map.cellsInRect(s=="column"?{left:a.left,top:0,right:a.right,bottom:a.map.height}:s=="row"?{left:0,top:a.top,right:a.map.width,bottom:a.bottom}:a),o=l.map(c=>a.table.nodeAt(c));for(let c=0;c{const f=m+i.tableStart,g=l.doc.nodeAt(f);g&&l.setNodeMarkup(f,h,g.attrs)}),r(l)}return!0}}MY("row",{useDeprecatedLogic:!0});MY("column",{useDeprecatedLogic:!0});const JCs=MY("cell",{useDeprecatedLogic:!0});function eAs(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 dse(s,t){const n=s.selection;if(!(n instanceof zh))return!1;if(t){const r=s.tr,a=Vy(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 li(a,0,0))}),r.docChanged&&t(r)}return!0}function sAs(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(Ca.empty),n[a]r&&(m=m.type.createChecked(uR(m.attrs,m.attrs.colspan,u+m.attrs.colspan-r),m.content)),d.push(m),u+=m.attrs.colspan;for(let f=1;fa&&(h=h.type.create({...h.attrs,rowspan:Math.max(1,a-h.attrs.rowspan)},h.content)),c.push(h)}i.push(Ca.from(c))}n=i,t=a}return{width:s,height:t,rows:n}}function aAs(s,t,n,r,a,i,l){const o=s.doc.type.schema,c=Vy(o);let d,u;if(a>t.width)for(let h=0,m=0;ht.height){const h=[];for(let g=0,y=(t.height-1)*t.width;g=t.width?!1:n.nodeAt(t.map[y+g]).type==c.header_cell;h.push(x?u||(u=c.header_cell.createAndFill()):d||(d=c.cell.createAndFill()))}const m=c.row.create(null,Ca.from(h)),f=[];for(let g=t.height;g{if(!a)return!1;const i=n.selection;if(i instanceof zh)return Wwe(n,r,nl.near(i.$headCell,t));if(s!="horiz"&&!i.empty)return!1;const l=pAt(a,s,t);if(l==null)return!1;if(s=="horiz")return Wwe(n,r,nl.near(n.doc.resolve(i.head+t),t));{const o=n.doc.resolve(l),c=oAt(o,s,t);let d;return c?d=nl.near(c,1):t<0?d=nl.near(n.doc.resolve(o.before(-1)),-1):d=nl.near(n.doc.resolve(o.after(-1)),1),Wwe(n,r,d)}}}function hse(s,t){return(n,r,a)=>{if(!a)return!1;const i=n.selection;let l;if(i instanceof zh)l=i;else{const c=pAt(a,s,t);if(c==null)return!1;l=new zh(n.doc.resolve(c))}const o=oAt(l.$headCell,s,t);return o?Wwe(n,r,new zh(l.$anchorCell,o)):!1}}function oAs(s,t){const n=s.state.doc,r=dR(n.resolve(t));return r?(s.dispatch(s.state.tr.setSelection(new zh(r))),!0):!1}function lAs(s,t,n){if(!xN(s.state))return!1;let r=sAs(n);const a=s.state.selection;if(a instanceof zh){r||(r={width:1,height:1,rows:[Ca.from(oOe(Vy(s.state.schema).cell,n))]});const i=a.$anchorCell.node(-1),l=a.$anchorCell.start(-1),o=lf.get(i).rectBetween(a.$anchorCell.pos-l,a.$headCell.pos-l);return r=rAs(r,o.right-o.left,o.bottom-o.top),Jat(s.state,s.dispatch,l,o,r),!0}else if(r){const i=y3e(s.state),l=i.start(-1);return Jat(s.state,s.dispatch,l,lf.get(i.node(-1)).findCell(i.pos-l),r),!0}else return!1}function cAs(s,t){var n;if(t.button!=0||t.ctrlKey||t.metaKey)return;const r=eit(s,t.target);let a;if(t.shiftKey&&s.state.selection instanceof zh)i(s.state.selection.$anchorCell,t),t.preventDefault();else if(t.shiftKey&&r&&(a=dR(s.state.selection.$anchor))!=null&&((n=FMe(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=FMe(s,d);const h=hA.getState(s.state)==null;if(!u||!rVe(c,u))if(h)u=c;else return;const m=new zh(c,u);if(h||!s.state.selection.eq(m)){const f=s.state.tr.setSelection(m);h&&f.setMeta(hA,c.pos),s.dispatch(f)}}function l(){s.root.removeEventListener("mouseup",l),s.root.removeEventListener("dragstart",l),s.root.removeEventListener("mousemove",o),hA.getState(s.state)!=null&&s.dispatch(s.state.tr.setMeta(hA,-1))}function o(c){const d=c,u=hA.getState(s.state);let h;if(u!=null)h=s.state.doc.resolve(u);else if(eit(s,d.target)!=r&&(h=FMe(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 pAt(s,t,n){if(!(s.state.selection instanceof Vo))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 eit(s,t){for(;t&&t!=s.dom;t=t.parentNode)if(t.nodeName=="TD"||t.nodeName=="TH")return t;return null}function FMe(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&&dR(s.state.doc.resolve(r))||dR(s.state.doc.resolve(a))}var dAs=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")),lOe(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,lOe(t,this.colgroup,this.table,this.defaultCellMinWidth),!0)}ignoreMutation(t){return t.type=="attributes"&&(t.target==this.table||this.colgroup.contains(t.target))}};function lOe(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 hAs(-1,!1)},apply(l,o){return o.apply(l)}},props:{attributes:l=>{const o=__.getState(l);return o&&o.activeHandle>-1?{class:"resize-cursor"}:{}},handleDOMEvents:{mousemove:(l,o)=>{mAs(l,o,s,a)},mouseleave:l=>{pAs(l)},mousedown:(l,o)=>{fAs(l,o,t,n)}},decorations:l=>{const o=__.getState(l);if(o&&o.activeHandle>-1)return bAs(l,o.activeHandle)},nodeViews:{}}});return i}var hAs=class Kwe{constructor(t,n){this.activeHandle=t,this.dragging=n}apply(t){const n=this,r=t.getMeta(__);if(r&&r.setHandle!=null)return new Kwe(r.setHandle,!1);if(r&&r.setDragging!==void 0)return new Kwe(n.activeHandle,r.setDragging);if(n.activeHandle>-1&&t.docChanged){let a=t.mapping.map(n.activeHandle,-1);return iOe(t.doc.resolve(a))||(a=-1),new Kwe(a,n.dragging)}return n}};function mAs(s,t,n,r){if(!s.editable)return;const a=__.getState(s.state);if(a&&!a.dragging){const i=xAs(t.target);let l=-1;if(i){const{left:o,right:c}=i.getBoundingClientRect();t.clientX-o<=n?l=tit(s,t,"left",n):c-t.clientX<=n&&(l=tit(s,t,"right",n))}if(l!=a.activeHandle){if(!r&&l!==-1){const o=s.state.doc.resolve(l),c=o.node(-1),d=lf.get(c),u=o.start(-1);if(d.colCount(o.pos-u)+o.nodeAfter.attrs.colspan-1==d.width-1)return}fAt(s,l)}}}function pAs(s){if(!s.editable)return;const t=__.getState(s.state);t&&t.activeHandle>-1&&!t.dragging&&fAt(s,-1)}function fAs(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=__.getState(s.state);if(!l||l.activeHandle==-1||l.dragging)return!1;const o=s.state.doc.nodeAt(l.activeHandle),c=gAs(s,l.activeHandle,o.attrs);s.dispatch(s.state.tr.setMeta(__,{setDragging:{startX:t.clientX,startWidth:c}}));function d(h){i.removeEventListener("mouseup",d),i.removeEventListener("mousemove",u);const m=__.getState(s.state);m!=null&&m.dragging&&(yAs(s,m.activeHandle,sit(m.dragging,h,n)),s.dispatch(s.state.tr.setMeta(__,{setDragging:null})))}function u(h){if(!h.which)return d(h);const m=__.getState(s.state);if(m&&m.dragging){const f=sit(m.dragging,h,n);nit(s,m.activeHandle,f,r)}}return nit(s,l.activeHandle,c,r),i.addEventListener("mouseup",d),i.addEventListener("mousemove",u),t.preventDefault(),!0}function gAs(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 kAs(s,t,n,r,a){const i=NAs(s),l=[],o=[];for(let d=0;d{const{selection:t}=s.state;if(!SAs(t))return!1;let n=0;const r=$Ct(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},CAs=Zy.create({name:"table",addOptions(){return{HTMLAttributes:{},resizable:!1,renderWrapper:!1,handleWidth:5,cellMinWidth:25,View:wAs,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}=jAs(s,this.options.cellMinWidth),i=["table",$m(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=kAs(i.schema,s,t,n);if(a){const o=r.selection.from+1;r.replaceSelectionWith(l).scrollIntoView().setSelection(Vo.near(r.doc.resolve(o)))}return!0},addColumnBefore:()=>({state:s,dispatch:t})=>BCs(s,t),addColumnAfter:()=>({state:s,dispatch:t})=>$Cs(s,t),deleteColumn:()=>({state:s,dispatch:t})=>qCs(s,t),addRowBefore:()=>({state:s,dispatch:t})=>HCs(s,t),addRowAfter:()=>({state:s,dispatch:t})=>GCs(s,t),deleteRow:()=>({state:s,dispatch:t})=>KCs(s,t),deleteTable:()=>({state:s,dispatch:t})=>tAs(s,t),mergeCells:()=>({state:s,dispatch:t})=>Wat(s,t),splitCell:()=>({state:s,dispatch:t})=>Kat(s,t),toggleHeaderColumn:()=>({state:s,dispatch:t})=>MY("column")(s,t),toggleHeaderRow:()=>({state:s,dispatch:t})=>MY("row")(s,t),toggleHeaderCell:()=>({state:s,dispatch:t})=>JCs(s,t),mergeOrSplit:()=>({state:s,dispatch:t})=>Wat(s,t)?!0:Kat(s,t),setCellAttribute:(s,t)=>({state:n,dispatch:r})=>XCs(s,t)(n,r),goToNextCell:()=>({state:s,dispatch:t})=>Zat(1)(s,t),goToPreviousCell:()=>({state:s,dispatch:t})=>Zat(-1)(s,t),fixTables:()=>({state:s,dispatch:t})=>(t&&uAt(s),!0),setCellSelection:s=>({tr:t,dispatch:n})=>{if(n){const r=zh.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:mse,"Mod-Backspace":mse,Delete:mse,"Mod-Delete":mse}},addProseMirrorPlugins(){return[...this.options.resizable&&this.editor.isEditable?[uAs({handleWidth:this.options.handleWidth,cellMinWidth:this.options.cellMinWidth,defaultCellMinWidth:this.options.cellMinWidth,View:this.options.View,lastColumnResizable:this.options.lastColumnResizable})]:[],_As({allowTableNodeSelection:this.options.allowTableNodeSelection})]},extendNodeSchema(s){const t={name:s.name,options:s.options,storage:s.storage};return{tableRole:mc(eo(s,"tableRole",t))}}}),AAs=Zy.create({name:"tableRow",addOptions(){return{HTMLAttributes:{}}},content:"(tableCell | tableHeader)*",tableRole:"row",parseHTML(){return[{tag:"tr"}]},renderHTML({HTMLAttributes:s}){return["tr",$m(this.options.HTMLAttributes,s),0]}}),TAs=Zy.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",$m(this.options.HTMLAttributes,s),0]}}),EAs=Zy.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",$m(this.options.HTMLAttributes,s),0]}});function yN({content:s,onChange:t,placeholder:n="Enter content...",minHeight:r="150px",compact:a=!1}){const[i,l]=N.useState(!1),[o,c]=N.useState(""),[d,u]=N.useState(!0),h=qqe({extensions:[Hqe,tVe.configure({openOnClick:!1,HTMLAttributes:{class:"text-primary underline"}}),sVe.configure({types:["heading","paragraph"]}),nVe,NCs.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}),CAs.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}),AAs.extend({addAttributes(){var y;return{...(y=this.parent)==null?void 0:y.call(this),style:{default:null}}}}),TAs.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}}}}),EAs.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,x)=>{var b;const _=(b=x.clipboardData)==null?void 0:b.items;if(!_)return!1;for(const k of Array.from(_))if(k.type.startsWith("image/")){x.preventDefault();const A=k.getAsFile();if(!A)continue;const T=new FileReader;return T.onload=P=>{var M;const I=(M=P.target)==null?void 0:M.result;y.dispatch(y.state.tr.replaceSelectionWith(y.state.schema.nodes.image.create({src:I})))},T.readAsDataURL(A),!0}return!1}}});N.useEffect(()=>{h&&s!==h.getHTML()&&h.commands.setContent(s)},[s,h]);const m=()=>{if(!h)return;const y=h.getAttributes("link").href||"",x=h.getAttributes("link").target;c(y),u(x==="_blank"),l(!0)},f=()=>{h&&(o===""?h.chain().focus().extendMarkRange("link").unsetLink().run():h.chain().focus().extendMarkRange("link").setLink({href:o,target:d?"_blank":null,rel:d?"noopener noreferrer nofollow":null}).run(),l(!1),c(""))},g=()=>{h&&h.chain().focus().extendMarkRange("link").unsetLink().run()};return h?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"border rounded-lg overflow-hidden",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-0.5 p-2 border-b bg-muted/30",children:[e.jsx(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(h9,{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(m9,{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(jT,{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(AT,{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(Kx,{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(dj,{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(nD,{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(sD,{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(rD,{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(gc,{className:"h-4 w-4"})}),h.isActive("link")&&e.jsx(B,{type:"button",variant:"ghost",size:"sm",onClick:g,title:"Remove Link",children:e.jsx(gc,{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(BT,{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(RT,{className:"h-4 w-4"})})]}),e.jsx($qe,{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(Bs,{open:i,onOpenChange:l,children:e.jsxs(Fs,{className:"sm:max-w-md",children:[e.jsx(qs,{children:e.jsx($s,{children:"Insert Link"})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{htmlFor:"link-url",children:"URL"}),e.jsx(we,{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(zn,{id:"link-new-tab",checked:d,onCheckedChange:u}),e.jsx(re,{htmlFor:"link-new-tab",children:"Open in new tab"})]})]}),e.jsxs(Cr,{children:[e.jsx(B,{type:"button",variant:"outline",onClick:()=>l(!1),children:"Cancel"}),e.jsx(B,{type:"button",onClick:f,children:o?"Apply Link":"Remove Link"})]})]})})]}):null}var MAs=Object.defineProperty,LAs=(s,t,n)=>t in s?MAs(s,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):s[t]=n,Em=(s,t,n)=>LAs(s,typeof t!="symbol"?t+"":t,n);const tke={x:0,y:0,width:0,height:0,unit:"px"},fF=(s,t,n)=>Math.min(Math.max(s,t),n),PAs=(...s)=>s.filter(t=>t&&typeof t=="string").join(" "),iit=(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 IAs(s,t,n,r){const a=yk(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==="%"?JC(a,n,r):a}function DAs(s,t,n){const r=yk(s,t,n);return r.x=(t-r.width)/2,r.y=(n-r.height)/2,s.unit==="%"?JC(r,t,n):r}function JC(s,t,n){return s.unit==="%"?{...tke,...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 yk(s,t,n){return s.unit?s.unit==="px"?{...tke,...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}:{...tke,...s,unit:"px"}}function oit(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),f=Math.min(c,a);t&&(t>1?(u=l?l*t:u,h=u/t,m=o*t):(h=i?i/t:h,u=h*t,f=c/t)),d.y<0&&(d.height=Math.max(d.height+d.y,h),d.y=0),d.x<0&&(d.width=Math.max(d.width+d.x,u),d.x=0);const g=r-(d.x+d.width);g<0&&(d.x=Math.min(d.x,r-u),d.width+=g);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>f&&((n==="nw"||n=="ne")&&(d.y-=f-d.height),d.height=f),t){const x=d.width/d.height;if(xt){const _=Math.max(d.height*t,u);(n==="sw"||n=="nw")&&(d.x-=_-d.width),d.width=_}}return d}function RAs(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 gF={capture:!0,passive:!1};let OAs=0;const zC=class o2 extends N.PureComponent{constructor(){super(...arguments),Em(this,"docMoveBound",!1),Em(this,"mouseDownOnCrop",!1),Em(this,"dragStarted",!1),Em(this,"evData",{startClientX:0,startClientY:0,startCropX:0,startCropY:0,clientX:0,clientY:0,isResize:!0}),Em(this,"componentRef",N.createRef()),Em(this,"mediaRef",N.createRef()),Em(this,"resizeObserver"),Em(this,"initChangeCalled",!1),Em(this,"instanceId",`rc-${OAs++}`),Em(this,"state",{cropIsActive:!1,newCropIsBeingDrawn:!1}),Em(this,"onCropPointerDown",t=>{const{crop:n,disabled:r}=this.props,a=this.getBox();if(!n)return;const i=yk(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,f=t.clientY-a.y;let g=0,y=0;l==="ne"||l=="e"?(g=m-(i.x+i.width),y=f-i.y,u=i.x,h=i.y+i.height):l==="se"||l==="s"?(g=m-(i.x+i.width),y=f-(i.y+i.height),u=i.x,h=i.y):l==="sw"||l=="w"?(g=m-i.x,y=f-(i.y+i.height),u=i.x+i.width,h=i.y):(l==="nw"||l=="n")&&(g=m-i.x,y=f-i.y,u=i.x+i.width,h=i.y+i.height),c=u+a.x+g,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})}),Em(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(yk(u,o.width,o.height),JC(u,o.width,o.height)),this.setState({cropIsActive:!0,newCropIsBeingDrawn:!0})}),Em(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(),iit(n,c)||a(yk(c,l.width,l.height),JC(c,l.width,l.height))}),Em(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)?o2.nudgeStepLarge:t.shiftKey?o2.nudgeStepMedium:o2.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=fF(d.x,0,c.width-d.width),d.y=fF(d.y,0,c.height-d.height);const h=yk(d,c.width,c.height),m=JC(d,c.width,c.height);a(h,m),i&&i(h,m)}}),Em(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 f=(navigator.platform.match("Mac")?t.metaKey:t.ctrlKey)?o2.nudgeStepLarge:t.shiftKey?o2.nudgeStepMedium:o2.nudgeStep,g=yk(a,m.width,m.height),y=RAs(g,t.key,f,n),x=oit(y,r,n,m.width,m.height,l,o,c,d);if(!iit(a,x)){const _=JC(x,m.width,m.height);u(x,_),h&&h(x,_)}}),Em(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(yk(n,l.width,l.height),JC(n,l.width,l.height)),this.setState({cropIsActive:!1,newCropIsBeingDrawn:!1}))}),Em(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(yk(n,a,i),JC(n,a,i))}}componentWillUnmount(){this.resizeObserver&&this.resizeObserver.disconnect(),this.unbindDocMove()}bindDocMove(){this.docMoveBound||(this.document.addEventListener("pointermove",this.onDocPointerMove,gF),this.document.addEventListener("pointerup",this.onDocPointerDone,gF),this.document.addEventListener("pointercancel",this.onDocPointerDone,gF),this.docMoveBound=!0)}unbindDocMove(){this.docMoveBound&&(this.document.removeEventListener("pointermove",this.onDocPointerMove,gF),this.document.removeEventListener("pointerup",this.onDocPointerDone,gF),this.document.removeEventListener("pointercancel",this.onDocPointerDone,gF),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=fF(t.startCropX+a,0,n.width-r.width),r.y=fF(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 f={unit:"px",x:0,y:0,width:0,height:0};d==="ne"?(f.x=t.startCropX,f.width=h,n?(f.height=f.width/n,f.y=t.startCropY-f.height):(f.height=Math.abs(m),f.y=t.startCropY-f.height)):d==="se"?(f.x=t.startCropX,f.y=t.startCropY,f.width=h,n?f.height=f.width/n:f.height=m):d==="sw"?(f.x=t.startCropX+h,f.y=t.startCropY,f.width=Math.abs(h),n?f.height=f.width/n:f.height=m):d==="nw"&&(f.x=t.startCropX+h,f.width=Math.abs(h),n?(f.height=f.width/n,f.y=t.startCropY-f.height):(f.height=Math.abs(m),f.y=t.startCropY+m));const g=oit(f,n,d,i.width,i.height,l,o,r,a);return n||o2.xyOrds.indexOf(u)>-1?c=g:o2.xOrds.indexOf(u)>-1?(c.x=g.x,c.width=g.width):o2.yOrds.indexOf(u)>-1&&(c.y=g.y,c.height=g.height),c.x=fF(c.x,0,i.width-c.width),c.y=fF(c.y,0,i.height-c.height),c}renderCropSelection(){const{ariaLabels:t=o2.defaultProps.ariaLabels,disabled:n,locked:r,renderSelectionAddon:a,ruleOfThirds:i,crop:l}=this.props,o=this.getCropStyle();if(l)return Rt.createElement("div",{style:o,className:"ReactCrop__crop-selection",onPointerDown:this.onCropPointerDown,"aria-label":t.cropArea,tabIndex:0,onKeyDown:this.onComponentKeyDown,role:"group"},!n&&!r&&Rt.createElement("div",{className:"ReactCrop__drag-elements",onFocus:this.onDragFocus},Rt.createElement("div",{className:"ReactCrop__drag-bar ord-n","data-ord":"n"}),Rt.createElement("div",{className:"ReactCrop__drag-bar ord-e","data-ord":"e"}),Rt.createElement("div",{className:"ReactCrop__drag-bar ord-s","data-ord":"s"}),Rt.createElement("div",{className:"ReactCrop__drag-bar ord-w","data-ord":"w"}),Rt.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"}),Rt.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"}),Rt.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"}),Rt.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"}),Rt.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"}),Rt.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"}),Rt.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"}),Rt.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&&Rt.createElement("div",{className:"ReactCrop__selection-addon",onPointerDown:c=>c.stopPropagation()},a(this.state)),i&&Rt.createElement(Rt.Fragment,null,Rt.createElement("div",{className:"ReactCrop__rule-of-thirds-hz"}),Rt.createElement("div",{className:"ReactCrop__rule-of-thirds-vt"})))}makePixelCrop(t){const n={...tke,...this.props.crop||{}};return yk(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,f=PAs("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 Rt.createElement("div",{ref:this.componentRef,className:f,style:c},Rt.createElement("div",{ref:this.mediaRef,className:"ReactCrop__child-wrapper",onPointerDown:this.onComponentPointerDown},n),i?Rt.createElement("svg",{className:"ReactCrop__crop-mask",width:"100%",height:"100%"},Rt.createElement("defs",null,Rt.createElement("mask",{id:`hole-${this.instanceId}`},Rt.createElement("rect",{width:"100%",height:"100%",fill:"white"}),r?Rt.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"}):Rt.createElement("rect",{x:`${i.x}${i.unit}`,y:`${i.y}${i.unit}`,width:`${i.width}${i.unit}`,height:`${i.height}${i.unit}`,fill:"black"}))),Rt.createElement("rect",{fill:"black",fillOpacity:.5,width:"100%",height:"100%",mask:`url(#hole-${this.instanceId})`})):void 0,m)}};Em(zC,"xOrds",["e","w"]),Em(zC,"yOrds",["n","s"]),Em(zC,"xyOrds",["nw","ne","se","sw"]),Em(zC,"nudgeStep",1),Em(zC,"nudgeStepMedium",10),Em(zC,"nudgeStepLarge",100),Em(zC,"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 FAs=zC;function zAs(s,t,n){return DAs(IAs({unit:"%",width:90},n,s,t),s,t)}const aVe=({open:s,onClose:t,imageSrc:n,onCropComplete:r,aspectRatio:a=1})=>{const i=N.useRef(null),[l,o]=N.useState(),[c,d]=N.useState(),[u,h]=N.useState(1),[m,f]=N.useState(0),g=N.useCallback(_=>{const{width:b,height:k}=_.currentTarget;o(zAs(b,k,a))},[a]),y=N.useCallback(async()=>{const _=i.current;if(!_||!c)return;const b=document.createElement("canvas"),k=b.getContext("2d");if(!k)return;const A=_.naturalWidth/_.width,T=_.naturalHeight/_.height,P=400;b.width=P,b.height=P,k.imageSmoothingQuality="high";const I=c.x*A,M=c.y*T,L=c.width*A,z=c.height*T,$=m*Math.PI/180,V=b.width/2,W=b.height/2;return k.save(),k.translate(V,W),k.rotate($),k.scale(u,u),k.translate(-V,-W),k.drawImage(_,I,M,L,z,0,0,P,P),k.restore(),new Promise((G,X)=>{b.toBlob(te=>{te?G(te):X(new Error("Canvas is empty"))},"image/jpeg",.95)})},[c,u,m]),x=async()=>{try{const _=await y();_&&(r(_),t())}catch(_){console.error("Error cropping image:",_)}};return e.jsx(Bs,{open:s,onOpenChange:t,children:e.jsxs(Fs,{className:"max-w-lg",children:[e.jsx(qs,{children:e.jsx($s,{children:"Crop Your Photo"})}),e.jsxs("div",{className:"space-y-4",children:[e.jsx("div",{className:"relative max-h-[400px] overflow-hidden rounded-lg bg-muted flex items-center justify-center",children:e.jsx(FAs,{crop:l,onChange:(_,b)=>o(b),onComplete:_=>d(_),aspect:a,circularCrop:!0,className:"max-h-[400px]",children:e.jsx("img",{ref:i,src:n,alt:"Crop preview",style:{transform:`scale(${u}) rotate(${m}deg)`,maxHeight:"400px",width:"auto"},onLoad:g})})}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(D9,{className:"h-4 w-4 text-muted-foreground"}),e.jsx(qf,{value:[u],min:.5,max:3,step:.1,onValueChange:([_])=>h(_),className:"flex-1"}),e.jsx($T,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(wD,{className:"h-4 w-4 text-muted-foreground"}),e.jsx(qf,{value:[m],min:-180,max:180,step:1,onValueChange:([_])=>f(_),className:"flex-1"}),e.jsxs("span",{className:"text-sm text-muted-foreground w-12",children:[m,"°"]})]})]})]}),e.jsxs(Cr,{children:[e.jsx(B,{variant:"outline",onClick:t,children:"Cancel"}),e.jsx(B,{onClick:x,children:"Save Photo"})]})]})})},BAs=()=>{const{user:s}=Ls(),{toast:t}=Ci(),[n,r]=N.useState(!1),[a,i]=N.useState(!1),[l,o]=N.useState(null);N.useEffect(()=>{s&&c()},[s]);const c=async()=>{r(!0);try{const{data:h}=await H.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 H.auth.getSession();if(!h)throw new Error("Not authenticated");const{data:m,error:f}=await H.functions.invoke("customer-portal",{headers:{Authorization:`Bearer ${h.access_token}`}});if(f)throw f;m!=null&&m.url&&window.open(m.url,"_blank")}catch(h){console.error("Error opening customer portal:",h),t({title:"Error",description:h.message||"Failed to open billing portal",variant:"destructive"})}finally{i(!1)}},u=()=>{if(l!=null&&l.isGrandfathered)return e.jsx(We,{className:"bg-amber-500",children:"Grandfathered"});switch(l==null?void 0:l.status){case"active":return e.jsx(We,{className:"bg-green-500",children:"Active"});case"trialing":return e.jsx(We,{className:"bg-blue-500",children:"Trial"});case"past_due":return e.jsx(We,{variant:"destructive",children:"Past Due"});case"canceled":return e.jsx(We,{variant:"secondary",children:"Canceled"});default:return e.jsx(We,{variant:"outline",children:"No Subscription"})}};return n?e.jsxs(_e,{children:[e.jsx(zt,{children:e.jsxs(qt,{className:"flex items-center gap-2",children:[e.jsx(U0,{className:"h-5 w-5"}),"Subscription"]})}),e.jsx(De,{children:e.jsx("div",{className:"flex items-center justify-center py-4",children:e.jsx(us,{className:"h-6 w-6 animate-spin text-muted-foreground"})})})]}):e.jsxs(_e,{children:[e.jsxs(zt,{children:[e.jsxs(qt,{className:"flex items-center gap-2",children:[e.jsx(U0,{className:"h-5 w-5"}),"Subscription"]}),e.jsx(_r,{children:"Manage your subscription and billing"})]}),e.jsxs(De,{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(us,{className:"mr-2 h-4 w-4 animate-spin"}):e.jsx(Tr,{className:"mr-2 h-4 w-4"}),"Manage Billing"]})]}):e.jsx("p",{className:"text-sm text-muted-foreground",children:"You don't have an active subscription."})]})]})},$As=()=>{const{user:s}=Ls(),t=tr(),{toast:n}=Ci(),[r]=$c(),a=r.get("setup")==="true",i=r.get("reset")==="true",{isSupported:l,isSubscribed:o,isLoading:c,subscribe:d,unsubscribe:u}=d4t(),[h,m]=N.useState(!1),[f,g]=N.useState(""),[y,x]=N.useState(!1),[_,b]=N.useState(!1),[k,A]=N.useState(""),[T,P]=N.useState({name:"",email:"",phone:"",title:"",bio:"",areas_served:"",years_experience:"",brokerage_name:"",instagram_url:"",facebook_url:"",linkedin_url:"",email_signature:"",use_email_signature:!1}),[I,M]=N.useState(!1),[L,z]=N.useState(!1),[$,V]=N.useState(!1),[W,G]=N.useState(!1),[X,te]=N.useState(!1),[ne,me]=N.useState({newPassword:"",confirmPassword:""});N.useEffect(()=>{s&&ue()},[s]),N.useEffect(()=>{i&&s&&setTimeout(()=>{var ve;(ve=document.getElementById("change-password-section"))==null||ve.scrollIntoView({behavior:"smooth",block:"center"})},500)},[i,s]);const ue=async()=>{var ve,ge,be,Se;if(!(s!=null&&s.id)){console.log("No user ID available yet");return}try{console.log("Loading profile for user:",s.id);const{data:Ie,error:Me}=await H.from("profiles").select("name, email, phone, digest_opt_out, event_invite_opt_out, title, bio, areas_served, years_experience, brokerage_id, brokerage_name, instagram_url, facebook_url, linkedin_url, email_signature, use_email_signature, brokerages(name)").eq("id",s.id).maybeSingle();if(Me)throw console.error("Profile query error:",Me),Me;if(Ie){console.log("Profile loaded successfully:",Ie);const Be=((ve=Ie.brokerages)==null?void 0:ve.name)||"";M(!!Ie.brokerage_id),P({name:Ie.name||"",email:Ie.email||"",phone:Ie.phone||"",title:Ie.title||"",bio:Ie.bio||"",areas_served:Ie.areas_served||"",years_experience:((ge=Ie.years_experience)==null?void 0:ge.toString())||"",brokerage_name:Ie.brokerage_id?Be:Ie.brokerage_name||"",instagram_url:Ie.instagram_url||"",facebook_url:Ie.facebook_url||"",linkedin_url:Ie.linkedin_url||"",email_signature:Ie.email_signature||"",use_email_signature:Ie.use_email_signature||!1}),z(Ie.digest_opt_out||!1),G(Ie.event_invite_opt_out||!1)}else console.warn("No profile found for user"),P({name:((be=s.user_metadata)==null?void 0:be.name)||((Se=s.email)==null?void 0:Se.split("@")[0])||"",email:s.email||"",phone:"",title:"",bio:"",areas_served:"",years_experience:"",brokerage_name:"",instagram_url:"",facebook_url:"",linkedin_url:"",email_signature:"",use_email_signature:!1});const{data:Re}=await H.storage.from("avatars").list(`${s.id}`);if(Re&&Re.length>0){const{data:Be}=H.storage.from("avatars").getPublicUrl(`${s.id}/${Re[0].name}`);g(Be.publicUrl)}}catch(Ie){console.error("Error loading profile:",Ie),n({title:"Error",description:Ie.message||"Failed to load profile",variant:"destructive"})}},ce=ve=>{var Se;const ge=(Se=ve.target.files)==null?void 0:Se[0];if(!ge)return;const be=new FileReader;be.onloadend=()=>{A(be.result),b(!0)},be.readAsDataURL(ge),ve.target.value=""},ae=async ve=>{if(s){x(!0);try{const{data:ge}=await H.storage.from("avatars").list(`${s.id}`);ge&&ge.length>0&&await H.storage.from("avatars").remove(ge.map(Be=>`${s.id}/${Be.name}`));const Se=`${s.id}/avatar.jpg`,{error:Ie}=await H.storage.from("avatars").upload(Se,ve,{upsert:!0,contentType:"image/jpeg"});if(Ie)throw Ie;const{data:Me}=H.storage.from("avatars").getPublicUrl(Se),Re=Me.publicUrl;g(`${Re}?t=${Date.now()}`),await H.from("profiles").update({avatar_url:Re}).eq("id",s.id),n({title:"Success",description:"Profile photo updated successfully"})}catch(ge){console.error("Error uploading avatar:",ge),n({title:"Error",description:ge.message||"Failed to upload photo",variant:"destructive"})}finally{x(!1)}}},he=async()=>{if(!T.name.trim()||!T.email.trim()){n({title:"Error",description:"Name and email are required",variant:"destructive"});return}m(!0);try{const{error:ve}=await H.from("profiles").update({name:T.name.trim(),email:T.email.trim(),phone:T.phone.trim()||null,title:T.title.trim()||null,bio:T.bio.trim()||null,areas_served:T.areas_served.trim()||null,years_experience:T.years_experience?parseInt(T.years_experience):null,...I?{}:{brokerage_name:T.brokerage_name.trim()||null},instagram_url:T.instagram_url.trim()||null,facebook_url:T.facebook_url.trim()||null,linkedin_url:T.linkedin_url.trim()||null,email_signature:T.email_signature||"",use_email_signature:T.use_email_signature}).eq("id",s==null?void 0:s.id);if(ve)throw ve;n({title:"Success",description:"Profile updated successfully"})}catch(ve){console.error("Error updating profile:",ve),n({title:"Error",description:ve.message||"Failed to update profile",variant:"destructive"})}finally{m(!1)}},xe=async()=>{if(!ne.newPassword){n({title:"Error",description:"Please enter a new password",variant:"destructive"});return}if(ne.newPassword.length<6){n({title:"Error",description:"Password must be at least 6 characters",variant:"destructive"});return}if(ne.newPassword!==ne.confirmPassword){n({title:"Error",description:"Passwords do not match",variant:"destructive"});return}m(!0);try{const{error:ve}=await H.auth.updateUser({password:ne.newPassword});if(ve)throw ve;n({title:"Success",description:"Password updated successfully"}),me({newPassword:"",confirmPassword:""}),a&&setTimeout(()=>t("/dashboard"),1e3)}catch(ve){console.error("Error updating password:",ve),n({title:"Error",description:ve.message||"Failed to update password",variant:"destructive"})}finally{m(!1)}};return e.jsx(Qs,{title:a?"Complete Your Profile":i?"Reset Your Password":"Profile Settings",description:a?"Welcome! Please complete your profile setup":i?"Please set a new password for your account":"Manage your account information and password",children:e.jsxs("div",{className:"mx-auto max-w-4xl",children:[!a&&!i&&e.jsx("div",{className:"mb-6",children:e.jsxs(B,{variant:"outline",onClick:()=>{var ve;(ve=document.getElementById("change-password-section"))==null||ve.scrollIntoView({behavior:"smooth",block:"center"})},className:"gap-2",children:[e.jsx(TT,{className:"h-4 w-4"}),"Change Password"]})}),e.jsxs("div",{className:"space-y-6",children:[e.jsxs(_e,{children:[e.jsxs(zt,{children:[e.jsx(qt,{children:"Profile Photo"}),e.jsx(_r,{children:"Upload a professional photo for your profile"})]}),e.jsxs(De,{className:"flex items-center gap-6",children:[e.jsxs(Ua,{className:"h-24 w-24",children:[e.jsx(Gi,{src:f}),e.jsx(qa,{className:"text-2xl",children:T.name.split(" ").map(ve=>ve[0]).join("").toUpperCase()||"U"})]}),e.jsxs("div",{className:"flex-1",children:[e.jsx("input",{type:"file",id:"avatar-upload",accept:"image/*",className:"hidden",onChange:ce,disabled:y}),e.jsxs(B,{variant:"outline",onClick:()=>{var ve;return(ve=document.getElementById("avatar-upload"))==null?void 0:ve.click()},disabled:y,children:[e.jsx(ni,{className:"mr-2 h-4 w-4"}),y?"Uploading...":"Upload Photo"]}),e.jsx("p",{className:"text-sm text-muted-foreground mt-2",children:"Upload an image and crop it to your liking."})]})]})]}),e.jsxs(_e,{children:[e.jsxs(zt,{children:[e.jsx(qt,{children:"Personal Information"}),e.jsx(_r,{children:"Update your profile details"})]}),e.jsxs(De,{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{htmlFor:"name",children:"Name"}),e.jsx(we,{id:"name",value:T.name,onChange:ve=>P({...T,name:ve.target.value}),maxLength:100})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{htmlFor:"email",children:"Email"}),e.jsx(we,{id:"email",type:"email",value:T.email,onChange:ve=>P({...T,email:ve.target.value}),maxLength:255})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{htmlFor:"phone",children:"Phone Number"}),e.jsx(we,{id:"phone",type:"tel",value:T.phone,onChange:ve=>P({...T,phone:ve.target.value}),placeholder:"e.g., +14155551234",maxLength:20}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Used for SMS lead notifications from your website — if you have a local authority site"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{htmlFor:"title",children:"Job Title"}),e.jsx(we,{id:"title",value:T.title,onChange:ve=>P({...T,title:ve.target.value}),placeholder:"e.g., Broker Associate, Team Lead",maxLength:100})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{htmlFor:"bio",children:"Bio"}),e.jsx(Ws,{id:"bio",value:T.bio,onChange:ve=>P({...T,bio:ve.target.value}),placeholder:"A short description about yourself",maxLength:500,className:"min-h-[120px] resize-y"})]}),e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{htmlFor:"areas_served",children:"Areas Served"}),e.jsx(we,{id:"areas_served",value:T.areas_served,onChange:ve=>P({...T,areas_served:ve.target.value}),placeholder:"e.g., Downtown, Suburbs"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{htmlFor:"years_experience",children:"Years Experience"}),e.jsx(we,{id:"years_experience",type:"number",min:"0",value:T.years_experience,onChange:ve=>P({...T,years_experience:ve.target.value}),placeholder:"e.g., 5"})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs(re,{htmlFor:"brokerage_name",children:["Brokerage ",I&&e.jsx("span",{className:"text-xs text-muted-foreground",children:"(managed)"})]}),e.jsx(we,{id:"brokerage_name",value:T.brokerage_name,onChange:ve=>P({...T,brokerage_name:ve.target.value}),placeholder:"e.g., Keller Williams Realty",disabled:I,maxLength:150}),e.jsx("p",{className:"text-xs text-muted-foreground",children:I?"Your brokerage is managed by your office and can't be changed here.":"Used as your brokerage name across ReelFlow, branding, and email signatures."})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{children:"Social Links"}),e.jsxs("div",{className:"grid grid-cols-1 gap-3",children:[e.jsx(we,{value:T.linkedin_url,onChange:ve=>P({...T,linkedin_url:ve.target.value}),placeholder:"LinkedIn URL"}),e.jsx(we,{value:T.instagram_url,onChange:ve=>P({...T,instagram_url:ve.target.value}),placeholder:"Instagram URL"}),e.jsx(we,{value:T.facebook_url,onChange:ve=>P({...T,facebook_url:ve.target.value}),placeholder:"Facebook URL"})]})]}),e.jsxs(B,{onClick:he,disabled:h,children:[e.jsx(Kl,{className:"mr-2 h-4 w-4"}),"Save Changes"]})]})]}),e.jsxs(_e,{children:[e.jsxs(zt,{children:[e.jsxs(qt,{className:"flex items-center gap-2",children:[e.jsx(O2,{className:"h-5 w-5"}),"Email Signature"]}),e.jsx(_r,{children:"Add a signature that will be appended to emails sent via Gmail"})]}),e.jsxs(De,{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:T.use_email_signature?"Your signature will be added to every email sent via Gmail":"Signature is currently disabled"})]}),e.jsx(zn,{checked:T.use_email_signature,onCheckedChange:ve=>P({...T,use_email_signature:ve})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{children:"Signature"}),e.jsx(yN,{content:T.email_signature,onChange:ve=>P({...T,email_signature:ve}),placeholder:"Paste your Gmail signature here or create one...",minHeight:"120px",compact:!0}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Tip: Copy your signature from Gmail Settings and paste it here — images and formatting will be preserved."})]}),e.jsxs(B,{onClick:he,disabled:h,children:[e.jsx(Kl,{className:"mr-2 h-4 w-4"}),"Save Signature"]})]})]}),e.jsxs(_e,{id:"change-password-section",children:[e.jsxs(zt,{children:[e.jsx(qt,{children:a?"Set Your Password":"Change Password"}),e.jsx(_r,{children:a?"Create a secure password for your account":"Update your password to keep your account secure"})]}),e.jsxs(De,{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{htmlFor:"newPassword",children:"New Password"}),e.jsx(we,{id:"newPassword",type:"password",value:ne.newPassword,onChange:ve=>me({...ne,newPassword:ve.target.value}),placeholder:"Min 6 characters"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{htmlFor:"confirmPassword",children:"Confirm Password"}),e.jsx(we,{id:"confirmPassword",type:"password",value:ne.confirmPassword,onChange:ve=>me({...ne,confirmPassword:ve.target.value}),placeholder:"Re-enter your new password"})]}),e.jsxs(B,{onClick:xe,disabled:h,children:[e.jsx(Kl,{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(_e,{children:[e.jsxs(zt,{children:[e.jsxs(qt,{className:"flex items-center gap-2",children:[o?e.jsx(yg,{className:"h-5 w-5"}):e.jsx(d5,{className:"h-5 w-5"}),"Push Notifications"]}),e.jsx(_r,{children:"Receive browser notifications when new content is added"})]}),e.jsx(De,{children:l?e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:o?"Notifications enabled":"Notifications disabled"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:o?"You'll receive notifications about new templates, videos, and events":"Enable to get notified about new content"})]}),e.jsx(zn,{checked:o,onCheckedChange:ve=>{ve?d():u()},disabled:c})]}):e.jsxs("div",{className:"text-sm text-muted-foreground space-y-2",children:[e.jsx("p",{children:"Push notifications are not available in this browser."}),e.jsxs("p",{className:"text-xs space-y-1",children:[e.jsx("strong",{children:"Desktop:"})," Use Chrome, Firefox, or Edge.",e.jsx("br",{}),e.jsx("strong",{children:"Android:"})," Use Chrome or Firefox.",e.jsx("br",{}),e.jsx("strong",{children:"iPhone/iPad:"})," Push notifications on iOS ",e.jsx("em",{children:"only"})," work when this site is installed as an app from ",e.jsx("strong",{children:"Safari"}),". Open this site in Safari → tap the ",e.jsx("strong",{children:"Share"})," button → ",e.jsx("strong",{children:"Add to Home Screen"}),". Other browsers (Chrome, Firefox, etc.) on iOS do not support push notifications due to Apple restrictions."]})]})})]}),e.jsxs(_e,{children:[e.jsxs(zt,{children:[e.jsxs(qt,{className:"flex items-center gap-2",children:[L?e.jsx(y9,{className:"h-5 w-5"}):e.jsx(mn,{className:"h-5 w-5"}),"Email Preferences"]}),e.jsx(_r,{children:"Manage your email subscription settings"})]}),e.jsxs(De,{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:L?"You won't receive weekly digest emails":"Receive a weekly summary of new content, events, and your progress"})]}),e.jsx(zn,{checked:!L,onCheckedChange:async ve=>{V(!0);try{const{error:ge}=await H.from("profiles").update({digest_opt_out:!ve}).eq("id",s==null?void 0:s.id);if(ge)throw ge;z(!ve),n({title:ve?"Subscribed":"Unsubscribed",description:ve?"You will now receive weekly digest emails":"You will no longer receive weekly digest emails"})}catch(ge){n({title:"Error",description:ge.message||"Failed to update preference",variant:"destructive"})}finally{V(!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:W?"You won't receive event invite emails (weekly digest is unaffected)":"Get invited to LevelUp live trainings and special events"})]}),e.jsx(zn,{checked:!W,onCheckedChange:async ve=>{te(!0);try{const{error:ge}=await H.from("profiles").update({event_invite_opt_out:!ve}).eq("id",s==null?void 0:s.id);if(ge)throw ge;G(!ve),n({title:ve?"Subscribed":"Unsubscribed",description:ve?"You will now receive event invite emails":"You will no longer receive event invite emails"})}catch(ge){n({title:"Error",description:ge.message||"Failed to update preference",variant:"destructive"})}finally{te(!1)}},disabled:X})]})]})]}),e.jsx(T2s,{}),e.jsx(BAs,{})]}),e.jsx(aVe,{open:_,onClose:()=>b(!1),imageSrc:k,onCropComplete:ae,aspectRatio:1})]})})};var UAs="AspectRatio",gAt=N.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(Da.div,{...a,ref:t,style:{...r,position:"absolute",top:0,right:0,bottom:0,left:0}})})});gAt.displayName=UAs;var qAs=gAt;const VAs=qAs;function HAs(){const{user:s}=Ls(),t=as(),[n,r]=N.useState(!1),[a,i]=N.useState(!1),{data:l,isLoading:o}=mt({queryKey:["calendar-token",s==null?void 0:s.id],queryFn:async()=>{const{data:g,error:y}=await H.from("profiles").select("calendar_token").eq("id",s==null?void 0:s.id).single();if(y)throw y;return g},enabled:!!s&&a}),c=_t({mutationFn:async()=>{const g=new Uint8Array(12);crypto.getRandomValues(g);const y=btoa(String.fromCharCode(...g)).replace(/\+/g,"x").replace(/\//g,"y").replace(/=/g,"").substring(0,16),{error:x}=await H.from("profiles").update({calendar_token:y}).eq("id",s==null?void 0:s.id);if(x)throw x;return y},onSuccess:()=>{t.invalidateQueries({queryKey:["calendar-token",s==null?void 0:s.id]}),ie.success("Calendar subscription URL generated!")},onError:g=>{ie.error("Failed to generate calendar URL: "+g.message)}}),d=l!=null&&l.calendar_token?`https://dashboard.relevelup.com/api/calendar/${l.calendar_token}.ics`:null,u=async()=>{d&&(await navigator.clipboard.writeText(d),r(!0),ie.success("Calendar URL copied to clipboard!"),setTimeout(()=>r(!1),2e3))},h=()=>{d&&(window.location.href=d.replace("https://","webcal://"))},m=()=>{if(d){const g=d.replace("https://","webcal://"),y=`https://calendar.google.com/calendar/r?cid=${encodeURIComponent(g)}`;window.open(y,"_blank")}},f=()=>{if(d){const g=`https://outlook.live.com/calendar/0/addfromweb?url=${encodeURIComponent(d)}&name=Level%20Up%20Events`;window.open(g,"_blank")}};return e.jsxs(Bs,{open:a,onOpenChange:i,children:[e.jsx(Ao,{asChild:!0,children:e.jsxs(B,{variant:"outline",className:"gap-2",children:[e.jsx(ta,{className:"h-4 w-4"}),"Subscribe to Calendar"]})}),e.jsxs(Fs,{className:"sm:max-w-md",children:[e.jsxs(qs,{children:[e.jsxs($s,{className:"flex items-center gap-2",children:[e.jsx(ta,{className:"h-5 w-5 text-primary"}),"Subscribe to Events Calendar"]}),e.jsx(Ar,{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(us,{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(we,{value:d,readOnly:!0,className:"text-xs font-mono"}),e.jsx(B,{variant:"outline",size:"icon",onClick:u,children:n?e.jsx(pa,{className:"h-4 w-4 text-green-500"}):e.jsx(Pa,{className:"h-4 w-4"})})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"text-sm font-medium",children:"Quick Add"}),e.jsxs("div",{className:"grid gap-2",children:[e.jsxs(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(Tr,{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(Tr,{className:"h-3 w-3 ml-auto opacity-50"})]}),e.jsxs(B,{variant:"outline",className:"w-full justify-start gap-2",onClick:f,children:[e.jsx("svg",{className:"h-4 w-4",viewBox:"0 0 24 24",fill:"currentColor",children:e.jsx("path",{d:"M7.88 12.04q0 .45-.11.87-.1.41-.33.74-.22.33-.58.52-.37.2-.87.2t-.85-.2q-.35-.21-.57-.55-.22-.33-.33-.75-.1-.42-.1-.86t.1-.87q.1-.43.34-.76.22-.34.59-.54.36-.2.87-.2t.86.2q.35.21.57.55.22.34.31.77.1.43.1.88zM24 12v9.38q0 .46-.33.8-.33.32-.8.32H7.13q-.46 0-.8-.33-.32-.33-.32-.8V18H1q-.41 0-.7-.3-.3-.29-.3-.7V7q0-.41.3-.7Q.58 6 1 6h6.5V2.55q0-.44.3-.75.3-.3.75-.3h12.9q.44 0 .75.3.3.3.3.75V12zm-6-8.25v3h3v-3zm0 4.5v3h3v-3zm0 4.5v1.83l3.05-1.83zm-5.25-9v3h3.75v-3zm0 4.5v3h3.75v-3zm0 4.5v2.03l2.41 1.5 1.34-.81v-2.72zM9 3.75V6h2l.13.01.12.04v-2.3zM5.98 15.98q.9 0 1.6-.3.7-.32 1.19-.86.48-.55.73-1.28.25-.74.25-1.61 0-.83-.25-1.55-.24-.71-.71-1.24t-1.15-.83q-.68-.3-1.55-.3-.92 0-1.64.3-.71.3-1.2.85-.5.54-.75 1.3-.25.74-.25 1.63 0 .85.26 1.56.26.72.74 1.23.48.52 1.17.81.69.3 1.56.3zM7.5 21h12.39L12 16.08V17q0 .41-.3.7-.29.3-.7.3H7.5zm15-.13v-7.24l-5.9 3.54Z"})}),"Add to Outlook",e.jsx(Tr,{className:"h-3 w-3 ml-auto opacity-50"})]})]})]}),e.jsx("p",{className:"text-xs text-muted-foreground text-center pt-2",children:"Events sync automatically. If your membership expires, the calendar will show as empty."})]}):e.jsxs("div",{className:"text-center space-y-4",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Generate your personal calendar subscription URL to get started."}),e.jsx(B,{onClick:()=>c.mutate(),disabled:c.isPending,className:"w-full",children:c.isPending?e.jsxs(e.Fragment,{children:[e.jsx(us,{className:"h-4 w-4 mr-2 animate-spin"}),"Generating..."]}):e.jsxs(e.Fragment,{children:[e.jsx(ta,{className:"h-4 w-4 mr-2"}),"Generate Calendar URL"]})})]})})]})]})}const GAs={first_timer:Wa,regular:i3,dedicated:ku,veteran:gl,streak_master:Cu,century:gl},WAs={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 lit(s){return s===1?e.jsx(gl,{className:"h-5 w-5 text-yellow-500"}):s===2?e.jsx(i3,{className:"h-5 w-5 text-gray-400"}):s===3?e.jsx(ku,{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 xAt({showUserStats:s=!0,compact:t=!1,brokerageId:n,title:r="Event Leaderboard"}){const{user:a}=Ls(),{data:i,isLoading:l}=O4t(t?5:10,n),{data:o}=F4t(a==null?void 0:a.id),{data:c}=B4t(a==null?void 0:a.id),{data:d}=z4t(a==null?void 0:a.id);return l?e.jsxs(_e,{children:[e.jsx(zt,{children:e.jsxs(qt,{className:"flex items-center gap-2",children:[e.jsx(gl,{className:"h-5 w-5 text-yellow-500"}),r]})}),e.jsx(De,{children:e.jsx("div",{className:"space-y-3",children:[...Array(5)].map((u,h)=>e.jsx(xn,{className:"h-12 w-full"},h))})})]}):e.jsxs(_e,{children:[e.jsx(zt,{className:"pb-3",children:e.jsxs(qt,{className:"flex items-center gap-2",children:[e.jsx(gl,{className:"h-5 w-5 text-yellow-500"}),r]})}),e.jsxs(De,{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(We,{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(Cu,{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=GAs[u.badge_type]||Wa;return e.jsxs(We,{variant:"outline",className:`text-xs ${WAs[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(We,{variant:"outline",className:"text-xs",children:["+",d.length-4," more"]})]})]}),e.jsxs(ya,{defaultValue:"points",className:"w-full",children:[e.jsxs(va,{className:"w-full mb-3",children:[e.jsx(ls,{value:"points",className:"flex-1",children:"By Points"}),e.jsx(ls,{value:"events",className:"flex-1",children:"By Events"})]}),e.jsx(_s,{value:"points",className:"mt-0",children:e.jsxs("div",{className:"space-y-2",children:[i==null?void 0:i.map((u,h)=>{var m,f,g;return e.jsxs("div",{className:`flex items-center gap-3 p-2 rounded-lg ${u.user_id===(a==null?void 0:a.id)?"bg-primary/5 border border-primary/10":""} ${h===0?"bg-yellow-500/5":""}`,children:[e.jsx("div",{className:"w-6 flex justify-center",children:lit(h+1)}),e.jsx(Ua,{className:"h-8 w-8",children:e.jsx(qa,{className:"text-xs",children:((f=(m=u.profile)==null?void 0:m.name)==null?void 0:f.charAt(0))||"?"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"font-medium text-sm truncate",children:[((g=u.profile)==null?void 0:g.name)||"Unknown",u.user_id===(a==null?void 0:a.id)&&e.jsx("span",{className:"text-xs text-muted-foreground ml-1",children:"(You)"})]}),e.jsxs("div",{className:"text-xs text-muted-foreground",children:[u.total_events_attended," events"]})]}),e.jsxs("div",{className:"text-right",children:[e.jsx("div",{className:"font-bold text-primary",children:u.total_points}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"pts"})]})]},u.user_id)}),(!i||i.length===0)&&e.jsx("div",{className:"text-center text-muted-foreground py-4 text-sm",children:"No attendance data yet. Attend an event to get on the leaderboard!"})]})}),e.jsx(_s,{value:"events",className:"mt-0",children:e.jsx("div",{className:"space-y-2",children:[...i||[]].sort((u,h)=>h.total_events_attended-u.total_events_attended).map((u,h)=>{var m,f,g;return e.jsxs("div",{className:`flex items-center gap-3 p-2 rounded-lg ${u.user_id===(a==null?void 0:a.id)?"bg-primary/5 border border-primary/10":""} ${h===0?"bg-yellow-500/5":""}`,children:[e.jsx("div",{className:"w-6 flex justify-center",children:lit(h+1)}),e.jsx(Ua,{className:"h-8 w-8",children:e.jsx(qa,{className:"text-xs",children:((f=(m=u.profile)==null?void 0:m.name)==null?void 0:f.charAt(0))||"?"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"font-medium text-sm truncate",children:[((g=u.profile)==null?void 0:g.name)||"Unknown",u.user_id===(a==null?void 0:a.id)&&e.jsx("span",{className:"text-xs text-muted-foreground ml-1",children:"(You)"})]}),e.jsxs("div",{className:"text-xs text-muted-foreground",children:[u.total_points," points"]})]}),e.jsxs("div",{className:"text-right",children:[e.jsx("div",{className:"font-bold",children:u.total_events_attended}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"events"})]})]},u.user_id)})})})]})]})]})}function KAs(){const s=tr(),{user:t,isAdmin:n}=Ls(),r=as(),{data:a,isLoading:i}=mt({queryKey:["public-events"],queryFn:async()=>{const{data:y,error:x}=await H.from("events").select("*").order("event_date",{ascending:!0});if(x)throw x;return y}}),{data:l}=mt({queryKey:["my-registrations"],queryFn:async()=>{if(!t)return[];const{data:y,error:x}=await H.from("event_registrations").select("event_id, zoom_join_url").eq("user_id",t.id);if(x)throw x;return y},enabled:!!t}),{data:o}=mt({queryKey:["event-registration-counts"],queryFn:async()=>{let y=[],x=0;const _=1e3;for(;;){const{data:k,error:A}=await H.from("event_registrations").select("event_id").range(x,x+_-1);if(A)throw A;if(!k||k.length===0||(y=y.concat(k),k.length<_))break;x+=_}const b={};return y.forEach(k=>{b[k.event_id]=(b[k.event_id]||0)+1}),b}}),c=_t({mutationFn:async y=>{await H.auth.refreshSession();const{data:x,error:_}=await H.functions.invoke("zoom-register",{body:{event_id:y}});if(_)throw _;if(x!=null&&x.error)throw new Error(x.error);return x},onSuccess:y=>{r.invalidateQueries({queryKey:["my-registrations"]}),r.invalidateQueries({queryKey:["event-registration-counts"]}),y!=null&&y.join_url?ie.success("Successfully registered! You'll receive a Zoom confirmation email."):ie.success("Successfully registered for the event!")},onError:y=>{ie.error("Failed to register: "+y.message)}}),d=_t({mutationFn:async y=>{const{data:x,error:_}=await H.functions.invoke("zoom-unregister",{body:{event_id:y}});if(_)throw _;if(x!=null&&x.error)throw new Error(x.error);return x},onSuccess:()=>{r.invalidateQueries({queryKey:["my-registrations"]}),r.invalidateQueries({queryKey:["event-registration-counts"]}),ie.success("Registration cancelled and removed from Zoom")},onError:y=>{ie.error("Failed to cancel: "+y.message)}}),u=y=>l==null?void 0:l.some(x=>x.event_id===y),h=y=>{const x=l==null?void 0:l.find(_=>_.event_id===y);return x==null?void 0:x.zoom_join_url},m=y=>y.capacity?((o==null?void 0:o[y.id])||0)>=y.capacity:!1,f=(a==null?void 0:a.filter(y=>V9(y.event_date)!=="ended"))||[],g=(a==null?void 0:a.filter(y=>V9(y.event_date)==="ended"))||[];return e.jsx(Qs,{title:"Events",children:e.jsxs("div",{className:"max-w-6xl mx-auto",children:[e.jsxs("div",{className:"flex items-center justify-between mb-6",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"text-2xl font-bold text-foreground",children:"Events"}),e.jsx("p",{className:"text-muted-foreground",children:"Browse and register for upcoming events"})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(HAs,{}),n&&e.jsx(B,{variant:"outline",onClick:()=>s("/admin/events"),children:"Manage Events"})]})]}),e.jsxs("div",{className:`grid grid-cols-1 ${n?"lg:grid-cols-3":""} gap-6`,children:[e.jsxs("div",{className:n?"lg:col-span-2":"",children:[i?e.jsx("div",{className:"text-center py-12 text-muted-foreground",children:"Loading events..."}):f.length===0?e.jsx(_e,{className:"text-center py-12",children:e.jsx(De,{children: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:f.map(y=>{const x=V9(y.event_date),_=cqe(y.event_date),b=x==="live",k=x==="starting_soon";return e.jsxs(_e,{className:`flex flex-col overflow-hidden cursor-pointer hover:shadow-lg transition-all ${b?"border-red-500 ring-2 ring-red-500/20":k?"border-amber-500 ring-2 ring-amber-500/20":"hover:border-primary/50"}`,onClick:()=>s(`/events/${y.id}`),children:[_&&e.jsxs("div",{className:`${b?"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"})]}),b?e.jsxs(e.Fragment,{children:[e.jsx(Y0,{className:"h-3.5 w-3.5"}),"LIVE NOW"]}):e.jsxs(e.Fragment,{children:[e.jsx(Xr,{className:"h-3.5 w-3.5"}),"STARTING SOON"]})]}),y.image_url&&e.jsxs(VAs,{ratio:16/9,className:"overflow-hidden relative bg-neutral-900",children:[e.jsx("img",{src:y.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:y.image_url,alt:y.title,className:"relative w-full h-full object-contain group-hover:scale-[1.03] transition-transform"})]}),e.jsxs(zt,{children:[e.jsx(qt,{className:"line-clamp-2",children:y.title}),y.description&&e.jsx(_r,{className:"line-clamp-2",children:y.description.replace(/<[^>]*>/g,"")})]}),e.jsxs(De,{className:"flex-1 space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[e.jsx(ta,{className:"h-4 w-4"}),new Intl.DateTimeFormat("en-US",{weekday:"long",year:"numeric",month:"long",day:"numeric",timeZone:"America/New_York"}).format(new Date(y.event_date))]}),e.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[e.jsx(Xr,{className:"h-4 w-4"}),yY(new Date(y.event_date))]}),e.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[e.jsx(Yn,{className:"h-4 w-4"}),(o==null?void 0:o[y.id])||0," registered",y.capacity&&` / ${y.capacity} spots`]})]}),e.jsx(WW,{className:"flex gap-2",onClick:A=>A.stopPropagation(),children:u(y.id)?e.jsxs(e.Fragment,{children:[e.jsxs(B,{variant:"outline",className:"flex-1",onClick:()=>d.mutate(y.id),disabled:d.isPending,children:[e.jsx(hr,{className:"h-4 w-4 mr-2"}),"Cancel"]}),e.jsxs(B,{className:"flex-1",onClick:()=>window.open(h(y.id)||y.zoom_link,"_blank"),children:[e.jsx(Tr,{className:"h-4 w-4 mr-2"}),"Join Zoom"]})]}):e.jsx(B,{className:"w-full",onClick:()=>c.mutate(y.id),disabled:c.isPending||m(y),children:m(y)?"Event Full":e.jsxs(e.Fragment,{children:[e.jsx(pa,{className:"h-4 w-4 mr-2"}),"Register"]})})})]},y.id)})}),g.length>0&&e.jsxs("div",{className:"mt-12",children:[e.jsx("h3",{className:"text-xl font-semibold mb-4 text-muted-foreground",children:"Past Events"}),e.jsx("div",{className:"grid gap-4 md:grid-cols-2",children:g.map(y=>e.jsx(_e,{className:"opacity-60 cursor-pointer hover:opacity-80 transition-opacity",onClick:()=>s(`/events/${y.id}`),children:e.jsxs(zt,{children:[e.jsx(qt,{className:"text-base line-clamp-1",children:y.title}),e.jsx(_r,{children:new Intl.DateTimeFormat("en-US",{year:"numeric",month:"long",day:"numeric",timeZone:"America/New_York"}).format(new Date(y.event_date))})]})},y.id))})]})]}),n&&e.jsx("div",{className:"lg:col-span-1",children:e.jsx(xAt,{showUserStats:!0})})]})]})})}const zMe=[{value:"all",label:"All Roles",icon:Yn},{value:"newest",label:"Newest Members",icon:Xr},{value:"brokerage_manager",label:"Brokerage Managers",icon:EW},{value:"admin",label:"Admins",icon:mf}];function YAs({open:s,onOpenChange:t,resourceType:n,resourceId:r,resourceTitle:a}){var Re,Be;const{user:i,isAdmin:l,isBrokerageManager:o}=Ls(),[c,d]=N.useState([]),[u,h]=N.useState([]),[m,f]=N.useState([]),[g,y]=N.useState([]),[x,_]=N.useState(""),[b,k]=N.useState(""),[A,T]=N.useState(""),[P,I]=N.useState(!1),[M,L]=N.useState(!1),[z,$]=N.useState("agents"),[V,W]=N.useState("all"),[G,X]=N.useState({}),te=l||o;N.useEffect(()=>{s&&i&&(l?ne():me())},[s,i,l]),N.useEffect(()=>{s||(f([]),y([]),_(""),k(""),T(""),$("agents"),W("all"))},[s]);const ne=async()=>{if(i){I(!0);try{const{data:Ne,error:Ge}=await H.from("brokerages").select("id, name").order("name");if(Ge)throw Ge;const Ce=1e3,Fe={};let Ae=0,Xe=!0;for(;Xe;){const{data:Je,error:Ke}=await H.from("profiles").select("brokerage_id").range(Ae*Ce,(Ae+1)*Ce-1);if(Ke)throw Ke;Je==null||Je.forEach(st=>{st.brokerage_id&&(Fe[st.brokerage_id]=(Fe[st.brokerage_id]||0)+1)}),Xe=(Je==null?void 0:Je.length)===Ce,Ae++}h((Ne==null?void 0:Ne.map(Je=>({...Je,agent_count:Fe[Je.id]||0})))||[]);const $e=[];for(Ae=0,Xe=!0;Xe;){const{data:Je,error:Ke}=await H.from("profiles").select("id, name, email, brokerage_id, created_at, brokerages(name)").neq("id",i.id).order("name").range(Ae*Ce,(Ae+1)*Ce-1);if(Ke)throw Ke;Je&&$e.push(...Je),Xe=(Je==null?void 0:Je.length)===Ce,Ae++}const Ye={};for(Ae=0,Xe=!0;Xe;){const{data:Je,error:Ke}=await H.from("user_roles").select("user_id, role").range(Ae*Ce,(Ae+1)*Ce-1);if(Ke)throw Ke;Je==null||Je.forEach(st=>{Ye[st.user_id]||(Ye[st.user_id]=[]),Ye[st.user_id].push(st.role)}),Xe=(Je==null?void 0:Je.length)===Ce,Ae++}X(Ye),d($e.map(Je=>{var Ke;return{id:Je.id,name:Je.name,email:Je.email,brokerage_name:((Ke=Je.brokerages)==null?void 0:Ke.name)||"No Brokerage",roles:Ye[Je.id]||[],created_at:Je.created_at}}))}catch(Ne){console.error("Error loading data:",Ne),ie.error("Failed to load agents and brokerages")}finally{I(!1)}}},me=async()=>{if(i){I(!0);try{const{data:Ne}=await H.from("profiles").select("brokerage_id").eq("id",i.id).single();if(!(Ne!=null&&Ne.brokerage_id)){ie.error("You must be part of a brokerage to share resources"),t(!1);return}const{data:Ge,error:Ce}=await H.from("profiles").select("id, name, email").eq("brokerage_id",Ne.brokerage_id).neq("id",i.id).order("name");if(Ce)throw Ce;d(Ge||[])}catch(Ne){console.error("Error loading agents:",Ne),ie.error("Failed to load agents")}finally{I(!1)}}},ue=c.filter(Ne=>{var Ce;const Ge=Ne.name.toLowerCase().includes(x.toLowerCase())||Ne.email.toLowerCase().includes(x.toLowerCase())||((Ce=Ne.brokerage_name)==null?void 0:Ce.toLowerCase().includes(x.toLowerCase()));if(l&&V!=="all"&&V!=="newest"){const Fe=G[Ne.id]||[];return Ge&&Fe.includes(V)}return Ge}).sort((Ne,Ge)=>V==="newest"?(Ge.created_at||"").localeCompare(Ne.created_at||""):0),ce=u.filter(Ne=>Ne.name.toLowerCase().includes(b.toLowerCase())),ae=()=>{m.length===ue.length?f([]):f(ue.map(Ne=>Ne.id))},he=()=>{g.length===ce.length?y([]):y(ce.map(Ne=>Ne.id))},xe=Ne=>{if(!te){f([Ne]);return}f(Ge=>Ge.includes(Ne)?Ge.filter(Ce=>Ce!==Ne):[...Ge,Ne])},ve=Ne=>{y(Ge=>Ge.includes(Ne)?Ge.filter(Ce=>Ce!==Ne):[...Ge,Ne])},ge=async()=>{if(!(m.length>0||g.length>0)){ie.error("Please select at least one agent or brokerage to share with");return}L(!0);try{const{data:Ge,error:Ce}=await H.functions.invoke("send-share-notification",{body:{recipientIds:m,brokerageIds:g,resourceType:n,resourceId:r,resourceTitle:a,message:A.trim()||void 0}});if(Ce)throw Ce;const Fe=(Ge==null?void 0:Ge.sharesCreated)||m.length;ie.success(`Shared with ${Fe} agent${Fe!==1?"s":""}`),t(!1)}catch(Ge){console.error("Error sharing resource:",Ge),ie.error("Failed to share resource")}finally{L(!1)}},be=Ne=>Ne.split(" ").map(Ge=>Ge[0]).join("").toUpperCase().slice(0,2),Se=Ne=>{const Ge=G[Ne]||[];return Ge.includes("admin")?e.jsx(We,{variant:"secondary",className:"text-[10px] px-1.5 py-0",children:"Admin"}):Ge.includes("brokerage_manager")?e.jsx(We,{variant:"outline",className:"text-[10px] px-1.5 py-0",children:"Manager"}):null},Ie=m.length+g.length,Me=V!=="all"&&V!=="newest"?ue.length:null;return e.jsx(Bs,{open:s,onOpenChange:t,children:e.jsxs(Fs,{className:"sm:max-w-lg max-h-[90vh] overflow-hidden flex flex-col",children:[e.jsxs(qs,{className:"flex-shrink-0",children:[e.jsxs($s,{className:"flex items-center gap-2",children:[e.jsx(Rr,{className:"h-5 w-5 text-primary"}),"Share Resource"]}),e.jsxs(Ar,{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(ya,{value:z,onValueChange:$,className:"flex-1 flex flex-col overflow-hidden",children:[e.jsxs(va,{className:"grid w-full grid-cols-2 flex-shrink-0",children:[e.jsxs(ls,{value:"agents",className:"flex items-center gap-2",children:[e.jsx(Yn,{className:"h-4 w-4"}),e.jsx("span",{children:"Agents"}),m.length>0&&e.jsx(We,{variant:"default",className:"h-5 min-w-5 px-1.5 text-xs",children:m.length})]}),e.jsxs(ls,{value:"brokerages",className:"flex items-center gap-2",children:[e.jsx(Ti,{className:"h-4 w-4"}),e.jsx("span",{children:"Brokerages"}),g.length>0&&e.jsx(We,{variant:"default",className:"h-5 min-w-5 px-1.5 text-xs",children:g.length})]})]}),e.jsxs(_s,{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(Gr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(we,{placeholder:"Search by name, email, or brokerage...",value:x,onChange:Ne=>_(Ne.target.value),className:"pl-9"})]}),e.jsxs(Ns,{value:V,onValueChange:W,children:[e.jsxs(ws,{className:"w-[180px]",children:[e.jsx(cj,{className:"h-4 w-4 mr-2 text-muted-foreground"}),e.jsx(ks,{placeholder:"Filter by role"})]}),e.jsx(js,{children:zMe.map(Ne=>e.jsx(nt,{value:Ne.value,children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ne.icon,{className:"h-4 w-4"}),e.jsx("span",{children:Ne.label})]})},Ne.value))})]})]}),e.jsxs("div",{className:"flex items-center justify-between px-1 flex-shrink-0",children:[e.jsxs(B,{variant:"ghost",size:"sm",onClick:ae,className:"text-xs h-8",disabled:ue.length===0,children:[e.jsx(Yn,{className:"h-3.5 w-3.5 mr-1.5"}),m.length===ue.length&&ue.length>0?"Deselect All":"Select All"]}),e.jsxs("div",{className:"flex items-center gap-2 text-xs text-muted-foreground",children:[Me!==null&&e.jsxs("span",{className:"text-primary font-medium",children:[Me," ",(Re=zMe.find(Ne=>Ne.value===V))==null?void 0:Re.label]}),e.jsxs("span",{className:"font-medium",children:[m.length," selected"]})]})]}),e.jsx(lo,{className:"h-[300px] border rounded-lg",children:P?e.jsx("div",{className:"flex items-center justify-center h-[200px]",children:e.jsx(us,{className:"h-6 w-6 animate-spin text-muted-foreground"})}):ue.length===0?e.jsxs("div",{className:"flex flex-col items-center justify-center h-[200px] text-muted-foreground",children:[e.jsx(Yn,{className:"h-8 w-8 mb-2 opacity-50"}),e.jsx("p",{className:"text-sm",children:V!=="all"?`No ${(Be=zMe.find(Ne=>Ne.value===V))==null?void 0:Be.label.toLowerCase()} found`:"No agents found"})]}):e.jsx("div",{className:"p-2 space-y-1",children:ue.map(Ne=>e.jsxs("div",{className:`flex items-center gap-3 p-2.5 rounded-lg cursor-pointer hover:bg-accent/50 transition-colors ${m.includes(Ne.id)?"bg-accent":""}`,onClick:()=>xe(Ne.id),children:[e.jsx(Bi,{checked:m.includes(Ne.id),onCheckedChange:()=>xe(Ne.id),className:"flex-shrink-0"}),e.jsx(Ua,{className:"h-9 w-9 flex-shrink-0",children:e.jsx(qa,{className:"text-xs bg-primary/10 text-primary",children:be(Ne.name)})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("p",{className:"text-sm font-medium truncate",children:Ne.name}),Se(Ne.id)]}),e.jsxs("p",{className:"text-xs text-muted-foreground truncate",children:[Ne.email,Ne.brokerage_name&&e.jsxs("span",{className:"ml-1 opacity-75",children:["• ",Ne.brokerage_name]})]})]})]},Ne.id))})})]}),e.jsxs(_s,{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(Gr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(we,{placeholder:"Search brokerages...",value:b,onChange:Ne=>k(Ne.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:he,className:"text-xs h-8",disabled:ce.length===0,children:[e.jsx(Ti,{className:"h-3.5 w-3.5 mr-1.5"}),g.length===ce.length&&ce.length>0?"Deselect All":"Select All"]}),e.jsxs("span",{className:"text-xs text-muted-foreground font-medium",children:[g.length," selected"]})]}),e.jsx("p",{className:"text-xs text-muted-foreground px-1 flex-shrink-0",children:"Selecting a brokerage will send to all agents in that brokerage."}),e.jsx(lo,{className:"h-[250px] border rounded-lg",children:P?e.jsx("div",{className:"flex items-center justify-center h-[180px]",children:e.jsx(us,{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-[180px] text-muted-foreground",children:[e.jsx(Ti,{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:ce.map(Ne=>e.jsxs("div",{className:`flex items-center gap-3 p-2.5 rounded-lg cursor-pointer hover:bg-accent/50 transition-colors ${g.includes(Ne.id)?"bg-accent":""}`,onClick:()=>ve(Ne.id),children:[e.jsx(Bi,{checked:g.includes(Ne.id),onCheckedChange:()=>ve(Ne.id),className:"flex-shrink-0"}),e.jsx("div",{className:"h-9 w-9 rounded-lg bg-primary/10 flex items-center justify-center flex-shrink-0",children:e.jsx(Ti,{className:"h-4 w-4 text-primary"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-sm font-medium truncate",children:Ne.name}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[Ne.agent_count," agent",Ne.agent_count!==1?"s":""]})]})]},Ne.id))})})]})]}):e.jsxs("div",{className:"flex-1 flex flex-col space-y-3 overflow-hidden",children:[e.jsxs("div",{className:"relative flex-shrink-0",children:[e.jsx(Gr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(we,{placeholder:"Search agents...",value:x,onChange:Ne=>_(Ne.target.value),className:"pl-9"})]}),te&&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:ue.length===0,children:[e.jsx(Yn,{className:"h-3.5 w-3.5 mr-1.5"}),m.length===ue.length&&ue.length>0?"Deselect All":"Select All"]}),e.jsxs("span",{className:"text-xs text-muted-foreground font-medium",children:[m.length," selected"]})]}),e.jsx(lo,{className:"h-[300px] border rounded-lg",children:P?e.jsx("div",{className:"flex items-center justify-center h-[200px]",children:e.jsx(us,{className:"h-6 w-6 animate-spin text-muted-foreground"})}):ue.length===0?e.jsxs("div",{className:"flex flex-col items-center justify-center h-[200px] text-muted-foreground",children:[e.jsx(Yn,{className:"h-8 w-8 mb-2 opacity-50"}),e.jsx("p",{className:"text-sm",children:"No agents found"})]}):e.jsx("div",{className:"p-2 space-y-1",children:ue.map(Ne=>e.jsxs("div",{className:`flex items-center gap-3 p-2.5 rounded-lg cursor-pointer hover:bg-accent/50 transition-colors ${m.includes(Ne.id)?"bg-accent":""}`,onClick:()=>xe(Ne.id),children:[e.jsx(Bi,{checked:m.includes(Ne.id),onCheckedChange:()=>xe(Ne.id),className:"flex-shrink-0"}),e.jsx(Ua,{className:"h-9 w-9 flex-shrink-0",children:e.jsx(qa,{className:"text-xs bg-primary/10 text-primary",children:be(Ne.name)})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-sm font-medium truncate",children:Ne.name}),e.jsx("p",{className:"text-xs text-muted-foreground truncate",children:Ne.email})]})]},Ne.id))})})]}),e.jsxs("div",{className:"space-y-2 flex-shrink-0",children:[e.jsx(re,{htmlFor:"message",className:"text-sm font-medium",children:"Add a message (optional)"}),e.jsx(Ws,{id:"message",placeholder:"I thought you might find this useful...",value:A,onChange:Ne=>T(Ne.target.value),rows:2,className:"resize-none"})]}),e.jsxs("div",{className:"flex justify-end gap-2 pt-2 flex-shrink-0",children:[e.jsx(B,{variant:"outline",onClick:()=>t(!1),children:"Cancel"}),e.jsx(B,{onClick:ge,disabled:Ie===0||M,children:M?e.jsxs(e.Fragment,{children:[e.jsx(us,{className:"h-4 w-4 mr-2 animate-spin"}),"Sharing..."]}):e.jsxs(e.Fragment,{children:[e.jsx(Rr,{className:"h-4 w-4 mr-2"}),"Share"]})})]})]})]})})}function yU({resourceType:s,resourceId:t,resourceTitle:n,variant:r="outline",size:a="sm",className:i=""}){const[l,o]=N.useState(!1),{user:c}=Ls();return c?e.jsxs(e.Fragment,{children:[e.jsxs(B,{variant:r,size:a,onClick:()=>o(!0),className:i,children:[e.jsx(Md,{className:"h-4 w-4 mr-2"}),"Share"]}),e.jsx(YAs,{open:l,onOpenChange:o,resourceType:s,resourceId:t,resourceTitle:n})]}):null}function ZAs(){const{eventId:s}=uo(),t=tr(),{user:n}=Ls(),[r,a]=N.useState(null),[i,l]=N.useState(null),[o,c]=N.useState(0),[d,u]=N.useState(!0),[h,m]=N.useState(!1);N.useEffect(()=>{s&&f()},[s,n]);const f=async()=>{try{const{data:k,error:A}=await H.from("events").select("*").eq("id",s).single();if(A)throw A;a(k);const{count:T}=await H.from("event_registrations").select("*",{count:"exact",head:!0}).eq("event_id",s);if(c(T||0),n){const{data:P}=await H.from("event_registrations").select("id, zoom_join_url").eq("event_id",s).eq("user_id",n.id).maybeSingle();l(P)}}catch(k){console.error("Error loading event:",k),ie.error("Failed to load event"),t("/events")}finally{u(!1)}},g=async()=>{if(!(!n||!r)){m(!0);try{const{error:k}=await H.auth.refreshSession();if(k){console.error("Session refresh failed:",k),ie.error("Your session has expired. Please log in again.");return}if(i){const{error:A}=await H.functions.invoke("zoom-unregister",{body:{event_id:r.id}});if(A)throw A;ie.success("Successfully cancelled registration"),l(null),c(T=>T-1)}else{const{data:A,error:T}=await H.functions.invoke("zoom-register",{body:{event_id:r.id}});if(T)throw T;ie.success("Successfully registered for event!"),l({id:A.registration_id,zoom_join_url:A.zoom_join_url}),c(P=>P+1)}}catch(k){console.error("Registration error:",k),ie.error(i?"Failed to cancel registration":"Failed to register for event")}finally{m(!1)}}},y=k=>{var A,T,P;if(k.includes("iframe.mediadelivery.net")||k.includes("video.bunnycdn.com")){const I=k.match(/embed\/(\d+)\/([a-f0-9-]+)/);if(I)return`https://iframe.mediadelivery.net/embed/${I[1]}/${I[2]}?autoplay=false&preload=true`}if(k.includes("youtube.com")||k.includes("youtu.be")){const I=k.includes("youtu.be")?(A=k.split("youtu.be/")[1])==null?void 0:A.split("?")[0]:(T=k.split("v=")[1])==null?void 0:T.split("&")[0];if(I)return`https://www.youtube.com/embed/${I}`}if(k.includes("vimeo.com")){const I=(P=k.split("vimeo.com/")[1])==null?void 0:P.split("?")[0];if(I)return`https://player.vimeo.com/video/${I}`}return k};if(d)return e.jsx(Qs,{title:"Event",children:e.jsx("div",{className:"flex items-center justify-center py-16",children:e.jsxs("div",{className:"text-center",children:[e.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent mx-auto mb-4"}),e.jsx("p",{className:"text-muted-foreground",children:"Loading event..."})]})})});if(!r)return e.jsx(Qs,{title:"Event Not Found",children:e.jsxs("div",{className:"text-center py-16",children:[e.jsx("p",{className:"text-muted-foreground",children:"Event not found"}),e.jsx(B,{onClick:()=>t("/events"),className:"mt-4",children:"Back to Events"})]})});const x=x5(new Date(r.event_date)),_=r.capacity&&o>=r.capacity,b=(i==null?void 0:i.zoom_join_url)||r.zoom_link;return e.jsx(Qs,{title:r.title,children:e.jsxs("div",{className:"max-w-4xl mx-auto",children:[e.jsxs(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"}),x&&e.jsx("div",{className:"absolute inset-0 bg-black/50 flex items-center justify-center",children:e.jsx(We,{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(yU,{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(wp,{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(_e,{children:e.jsxs(De,{className:"p-6 space-y-4",children:[e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx(ta,{className:"h-5 w-5 text-primary mt-0.5"}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:new Intl.DateTimeFormat("en-US",{weekday:"long",year:"numeric",month:"long",day:"numeric",timeZone:"America/New_York"}).format(new Date(r.event_date))}),e.jsx("p",{className:"text-sm text-muted-foreground",children:yY(new Date(r.event_date))})]})]}),r.capacity&&e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx(Yn,{className:"h-5 w-5 text-primary mt-0.5"}),e.jsxs("div",{children:[e.jsxs("p",{className:"font-medium",children:[o," / ",r.capacity]}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Registered"})]})]}),i&&e.jsxs("div",{className:"flex items-center gap-2 p-3 bg-green-500/10 rounded-lg",children:[e.jsx(Po,{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:[!x&&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(Tr,{className:"h-4 w-4"}),"Join Event"]}),e.jsxs(B,{variant:"outline",className:"w-full",onClick:g,disabled:h,children:[h?e.jsx(us,{className:"h-4 w-4 animate-spin mr-2"}):null,"Cancel Registration"]})]}):e.jsx(B,{className:"w-full gap-2",onClick:g,disabled:h||(_??!1),children:h?e.jsx(us,{className:"h-4 w-4 animate-spin"}):_?"Event Full":"Register Now"})}),x&&i&&e.jsxs(B,{variant:"outline",className:"w-full gap-2",onClick:()=>window.open(r.zoom_link,"_blank"),children:[e.jsx(Tr,{className:"h-4 w-4"}),"View Recording"]})]})]})})})]})]})})}const XAs=[{id:"quickvid",name:"QuickVid",description:"Record, manage, and share personalized video messages",icon:e.jsx(na,{className:"h-6 w-6"}),path:"/mission-control/video/record",category:"Marketing",color:"bg-rose-500/15 text-rose-600"},{id:"smart-card",name:"Smart Card",description:"Your digital business card — share your info with a single link",icon:e.jsx(U0,{className:"h-6 w-6"}),path:"/mission-control/my-card",category:"Marketing",color:"bg-sky-500/15 text-sky-600"},{id:"smart-presentations",name:"Smart Presentations",description:"Create beautiful listing and buyer presentations",icon:e.jsx(ab,{className:"h-6 w-6"}),path:"/mission-control/presentations",category:"Marketing",color:"bg-amber-500/15 text-amber-600"},{id:"landing-pages",name:"Landing Pages",description:"Build custom landing pages to capture leads",icon:e.jsx(Wr,{className:"h-6 w-6"}),path:"/mission-control/landing-pages",category:"Marketing",color:"bg-emerald-500/15 text-emerald-600"},{id:"guest-book",name:"Guest Book",description:"Digital open house sign-in to capture visitor info",icon:e.jsx(Ep,{className:"h-6 w-6"}),path:"/mission-control/guest-book",category:"Open House",color:"bg-orange-500/15 text-orange-600"},{id:"card-studio",name:"Card Studio",description:"Send beautiful animated digital cards for birthdays, anniversaries & milestones",icon:e.jsx(Cn,{className:"h-6 w-6"}),path:"/mission-control/card-studio",category:"Marketing",color:"bg-pink-500/15 text-pink-600"},{id:"direct-mail",name:"Direct Mail",description:"Send professional postcards to your contacts via direct mail",icon:e.jsx(mn,{className:"h-6 w-6"}),path:"/mission-control/direct-mail",category:"Marketing",adminOnly:!0,beta:!0,color:"bg-indigo-500/15 text-indigo-600"},{id:"reelflow",name:"ReelFlow",description:"Turn property photos into cinematic video clips and reels — powered by AI",icon:e.jsx(Rh,{className:"h-6 w-6"}),path:"/admin/beta/homereel",category:"Marketing",beta:!0,isNew:!0,color:"bg-violet-500/15 text-violet-600"},{id:"mass-emails",name:"Mass Emails",description:"Create and send bulk email campaigns to your contacts",icon:e.jsx(Rr,{className:"h-6 w-6"}),path:"/admin/email-campaigns",category:"Marketing",beta:!0,color:"bg-teal-500/15 text-teal-600"},{id:"listing-studio",name:"Listing Studio",description:"Generate MLS descriptions, luxury copy, open house blurbs and more — powered by AI",icon:e.jsx(O2,{className:"h-6 w-6"}),path:"/mission-control/listing-studio",category:"Marketing",isNew:!0,color:"bg-fuchsia-500/15 text-fuchsia-600"},{id:"website-apps",name:"Website Apps",description:"Drop-in conversion widgets for your website — Video Greeter & more",icon:e.jsx(w9,{className:"h-6 w-6"}),path:"/website-apps",category:"Website",isNew:!0,color:"bg-cyan-500/15 text-cyan-600"},{id:"newsletter-pro",name:"Newsletter Pro",description:"Design and send beautiful branded newsletters to your database",icon:e.jsx(E_,{className:"h-6 w-6"}),path:"/newsletters",category:"Marketing",color:"bg-yellow-500/15 text-yellow-600"},{id:"weekly-reels",name:"Weekly Reels",description:"5 personalized Instagram Reel scripts delivered to your inbox every Monday morning",icon:e.jsx(Rh,{className:"h-6 w-6"}),path:"/weekly-reels",category:"Marketing",isNew:!0,requiresWeeklyReels:!0,color:"bg-orange-500/15 text-orange-600"},{id:"cma",name:"CMA Reports",description:"Build interactive CMAs with live comps, share with clients, and auto-create deals",icon:e.jsx(fl,{className:"h-6 w-6"}),path:"/mission-control/cma",category:"Website",isNew:!0,requiresLeadSiteMLS:!0,color:"bg-blue-500/15 text-blue-600"},{id:"listing-presentation-studio",name:"Listing Presentation Studio",description:"Build a branded 12-page seller listing presentation PDF in minutes",icon:e.jsx(ab,{className:"h-6 w-6"}),path:"/apps/listing-presentation-studio",category:"Listing Marketing",isNew:!0,color:"bg-emerald-500/15 text-emerald-600"}],QAs=()=>{const{user:s,isAdmin:t}=Ls(),n=tr(),[r,a]=N.useState([]),[i,l]=N.useState(!0),[o,c]=N.useState(""),[d,u]=N.useState("all"),[h,m]=N.useState(new Set),[f,g]=N.useState(new Set),[y,x]=N.useState(!1),{hasAccess:_}=GUe();N.useEffect(()=>{b()},[s]);const b=async()=>{try{const{data:V}=await H.from("user_tags").select("tag").eq("user_id",s==null?void 0:s.id),W=(V==null?void 0:V.map(ve=>ve.tag))||[],{data:G,error:X}=await H.from("app_tiles").select("*").order("name");if(X)throw X;const[{data:te},{data:ne},{data:me}]=await Promise.all([H.from("user_favorites").select("app_id").eq("user_id",s==null?void 0:s.id),H.from("user_tool_favorites").select("tool_id").eq("user_id",s==null?void 0:s.id),H.from("lead_sites").select("id, mls_provider_id, no_mls_mode, is_active").eq("agent_id",s==null?void 0:s.id)]),ue=(me||[]).some(ve=>ve.is_active&&ve.mls_provider_id&&!ve.no_mls_mode);x(ue);const ce=new Set((te==null?void 0:te.map(ve=>ve.app_id))||[]);m(ce);const ae=new Set((ne||[]).map(ve=>ve.tool_id));g(ae);const xe=((G==null?void 0:G.filter(ve=>ve.app_id==="newsletter_studio"?!1:!ve.required_tags||ve.required_tags.length===0?!0:ve.required_tags.some(ge=>W.includes(ge))))||[]).sort((ve,ge)=>ve.name==="LevelUp Members Portal"?-1:ge.name==="LevelUp Members Portal"?1:0);a(xe)}catch(V){console.error("Error loading apps:",V),ie.error("Failed to load apps")}finally{l(!1)}},k=async V=>{var G;try{const X=new URL(V.target_url);if(new Set([window.location.hostname,"dashboard.relevelup.com"]).has(X.hostname)){await H.from("activity_logs").insert({user_id:s==null?void 0:s.id,app_id:V.app_id,app_name:V.name,user_agent:navigator.userAgent}),n(X.pathname+X.search+X.hash);return}}catch{}const W=window.open("about:blank","_blank");try{const{data:X,error:te}=await H.auth.getSession();if(te||!X.session){W==null||W.close(),ie.error("Session expired. Please refresh the page and try again.");return}const ne=X.session.access_token;await H.from("activity_logs").insert({user_id:s==null?void 0:s.id,app_id:V.app_id,app_name:V.name,user_agent:navigator.userAgent});const{data:me,error:ue}=await H.functions.invoke("sso-launch",{body:{app_id:V.app_id},headers:{Authorization:`Bearer ${ne}`}});if(ue)throw ue;me!=null&&me.redirect_url?W&&!W.closed?(W.location.href=me.redirect_url,(G=W.focus)==null||G.call(W)):window.location.assign(me.redirect_url):(W==null||W.close(),ie.error("Launch link unavailable"))}catch(X){W==null||W.close(),console.error("Error launching app:",X),ie.error("Failed to launch app. Please try again.")}},A=async(V,W)=>{V.stopPropagation();const G=h.has(W);try{if(G){const{error:X}=await H.from("user_favorites").delete().eq("user_id",s==null?void 0:s.id).eq("app_id",W);if(X)throw X;m(te=>{const ne=new Set(te);return ne.delete(W),ne}),ie.success("Removed from favorites")}else{const{error:X}=await H.from("user_favorites").insert({user_id:s==null?void 0:s.id,app_id:W});if(X)throw X;m(te=>new Set(te).add(W)),ie.success("Added to favorites")}}catch(X){console.error("Error toggling favorite:",X),ie.error("Failed to update favorites")}},T=async(V,W)=>{V.stopPropagation();const G=f.has(W);try{if(G){const{error:X}=await H.from("user_tool_favorites").delete().eq("user_id",s==null?void 0:s.id).eq("tool_id",W);if(X)throw X;g(te=>{const ne=new Set(te);return ne.delete(W),ne}),ie.success("Removed from favorites")}else{const{error:X}=await H.from("user_tool_favorites").insert({user_id:s==null?void 0:s.id,tool_id:W});if(X)throw X;g(te=>new Set(te).add(W)),ie.success("Added to favorites")}}catch(X){console.error("Error toggling tool favorite:",X),ie.error("Failed to update favorites")}},P=r.filter(V=>{var G;const W=V.name.toLowerCase().includes(o.toLowerCase())||((G=V.description)==null?void 0:G.toLowerCase().includes(o.toLowerCase()));return d==="favorites"?W&&h.has(V.id):W}),I=XAs.filter(V=>{if(V.adminOnly&&!t||V.requiresLeadSiteMLS&&!y&&!t||V.requiresWeeklyReels&&!_)return!1;const W=V.name.toLowerCase().includes(o.toLowerCase())||V.description.toLowerCase().includes(o.toLowerCase());return d==="favorites"?W&&f.has(V.id):W}),M=I.reduce((V,W)=>(V[W.category]||(V[W.category]=[]),V[W.category].push(W),V),{}),L=[{id:"all",label:"All"},{id:"tools",label:"Built-in Tools"},{id:"apps",label:"Connected Apps"},{id:"favorites",label:"Favorites"}];if(i)return e.jsx(Qs,{title:"Apps & Tools",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 apps & tools..."})]})})});const z=d==="all"||d==="tools"||d==="favorites",$=d==="all"||d==="apps"||d==="favorites";return e.jsxs(Qs,{title:"Apps & Tools",children:[e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center justify-between gap-4 mb-6",children:[e.jsx("h2",{className:"text-2xl font-bold text-foreground",children:"Apps & Tools"}),e.jsxs("div",{className:"relative max-w-sm w-full",children:[e.jsx(Gr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(we,{placeholder:"Search apps & tools...",className:"pl-10 bg-muted/50 border-0 focus-visible:ring-1",value:o,onChange:V=>c(V.target.value)})]})]}),e.jsx("div",{className:"flex gap-6 border-b border-border mb-8",children:L.map(V=>e.jsxs("button",{onClick:()=>u(V.id),className:Ot("pb-3 text-sm font-medium transition-colors relative",d===V.id?"text-primary":"text-muted-foreground hover:text-foreground"),children:[V.label,d===V.id&&e.jsx("span",{className:"absolute bottom-0 left-0 right-0 h-0.5 bg-primary"})]},V.id))}),z&&Object.keys(M).length>0&&e.jsxs("div",{className:"mb-10",children:[d==="all"&&e.jsxs("div",{className:"flex items-center gap-2 mb-5",children:[e.jsx(sN,{className:"h-5 w-5 text-primary"}),e.jsx("h3",{className:"text-lg font-semibold text-foreground",children:"Built-in Tools"})]}),Object.entries(M).map(([V,W])=>e.jsxs("div",{className:"mb-6",children:[e.jsx("div",{className:"flex items-center gap-2 mb-3",children:e.jsx("span",{className:"text-xs font-semibold uppercase tracking-wider text-muted-foreground bg-muted px-2.5 py-1 rounded-full",children:V})}),e.jsx("div",{className:"grid gap-4 md:grid-cols-2 xl:grid-cols-3",children:W.map(G=>{const X=f.has(G.id);return e.jsxs("div",{onClick:()=>n(G.path),className:Ot("group flex items-start gap-4 p-5 bg-card rounded-xl border transition-all duration-200 hover:shadow-lg cursor-pointer relative overflow-hidden",G.isNew?"border-primary/40 ring-1 ring-primary/20 hover:border-primary/60":"border-border hover:border-primary/30"),children:[G.isNew&&e.jsx("div",{className:"absolute top-0 right-0 bg-gradient-to-r from-violet-500 to-indigo-500 text-white text-[10px] font-bold uppercase px-3 py-0.5 rounded-bl-lg tracking-wider shadow-sm",children:"✨ New"}),e.jsx("div",{className:Ot("flex-shrink-0 w-14 h-14 rounded-xl flex items-center justify-center transition-transform group-hover:scale-105",G.color||"bg-primary/10 text-primary"),children:G.icon}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("h3",{className:"font-semibold text-foreground group-hover:text-primary transition-colors truncate flex items-center gap-2",children:[G.name,G.beta&&e.jsx("span",{className:"text-[10px] font-semibold bg-amber-100 text-amber-700 px-1.5 py-0.5 rounded-full border border-amber-200",children:"Beta"})]}),e.jsx("p",{className:"text-sm text-muted-foreground mt-1 line-clamp-2",children:G.description})]}),e.jsx("button",{className:Ot("flex-shrink-0 p-1 transition-colors",X?"text-primary":"text-muted-foreground/50 hover:text-primary"),onClick:te=>T(te,G.id),children:e.jsx(Hv,{className:Ot("h-5 w-5",X&&"fill-current")})})]},G.id)})})]},V))]}),$&&e.jsxs("div",{children:[d==="all"&&P.length>0&&e.jsxs("div",{className:"flex items-center gap-2 mb-5",children:[e.jsx(Tr,{className:"h-5 w-5 text-primary"}),e.jsx("h3",{className:"text-lg font-semibold text-foreground",children:"Connected Apps"})]}),P.length===0&&d!=="all"&&!(d==="favorites"&&I.length>0)?e.jsx("div",{className:"flex flex-col items-center justify-center py-16 bg-card rounded-xl border border-border",children:d==="favorites"?e.jsxs(e.Fragment,{children:[e.jsx(Hv,{className:"h-12 w-12 text-muted-foreground mb-4"}),e.jsx("p",{className:"text-lg font-medium mb-2 text-foreground",children:"No favorites yet"}),e.jsx("p",{className:"text-sm text-muted-foreground text-center max-w-md",children:"Click the bookmark icon on any app or tool to add it to your favorites"})]}):e.jsxs(e.Fragment,{children:[e.jsx(Au,{className:"h-12 w-12 text-muted-foreground mb-4"}),e.jsx("p",{className:"text-lg font-medium mb-2 text-foreground",children:"No apps available"}),e.jsx("p",{className:"text-sm text-muted-foreground text-center max-w-md",children:t?"Get started by adding apps in the admin panel":"Contact your administrator to get access to apps"}),t&&e.jsx(B,{className:"mt-4",onClick:()=>n("/admin/apps"),children:"Add Apps"})]})}):e.jsx("div",{className:"grid gap-4 md:grid-cols-2 xl:grid-cols-3",children:P.map(V=>{const W=h.has(V.id),G=V.name.toLowerCase().includes("agent review")||V.app_id==="agent_review";return e.jsxs("div",{className:"group flex flex-col p-5 bg-card rounded-xl border border-border transition-all duration-200 hover:shadow-lg hover:border-primary/30",children:[e.jsxs("div",{className:"flex items-start gap-4 cursor-pointer",onClick:()=>k(V),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:V.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:V.name}),e.jsx("p",{className:"text-sm text-muted-foreground mt-1 line-clamp-2",children:V.description})]}),e.jsx("button",{className:Ot("flex-shrink-0 p-1 transition-colors",W?"text-primary":"text-muted-foreground/50 hover:text-primary"),onClick:X=>A(X,V.id),children:e.jsx(Hv,{className:Ot("h-5 w-5",W&&"fill-current")})})]}),G&&e.jsx("a",{href:"https://forms.gle/vXnrzgSnPbw7CKPV6",target:"_blank",rel:"noopener noreferrer",onClick:X=>X.stopPropagation(),className:"mt-3 text-sm text-primary hover:underline flex items-center gap-1",children:"Create your account with this link →"})]},V.id)})})]}),z&&$&&P.length===0&&I.length===0&&o&&e.jsxs("div",{className:"flex flex-col items-center justify-center py-16 bg-card rounded-xl border border-border",children:[e.jsx(Gr,{className:"h-12 w-12 text-muted-foreground mb-4"}),e.jsx("p",{className:"text-lg font-medium mb-2 text-foreground",children:"No results found"}),e.jsx("p",{className:"text-sm text-muted-foreground text-center max-w-md",children:"Try a different search term"})]})]})},JAs=()=>{var k;const s=tr(),{isAdmin:t}=Ls(),[n,r]=N.useState(""),[a,i]=N.useState("all"),[l,o]=N.useState("all"),[c,d]=N.useState("grid"),{data:u=[]}=mt({queryKey:["template-categories"],queryFn:async()=>{const{data:A,error:T}=await H.from("template_categories").select("*").order("name");if(T)throw T;return A}}),{data:h=[]}=mt({queryKey:["template-types"],queryFn:async()=>{const{data:A,error:T}=await H.from("template_types").select("*").order("name");if(T)throw T;return A}}),{data:m=[],isLoading:f}=mt({queryKey:["canva-templates",t],queryFn:async()=>{const{data:A,error:T}=await H.from("canva_templates").select(` *, category:template_categories(id, name), type:template_types(id, name) `).order("publish_date",{ascending:!1});if(T)throw T;const{data:P,error:I}=await H.from("template_links").select("*").order("sort_order");if(I)throw I;const M=async X=>{let ne=0;const me=[];for(;;){const{data:ue,error:ce}=await X().range(ne,ne+1e3-1);if(ce)throw ce;if(!ue||ue.length===0||(me.push(...ue),ue.length<1e3))break;ne+=1e3}return me},L=await M(()=>H.from("template_likes").select("template_id")),z=await M(()=>H.from("template_comments").select("template_id")),$=new Map;L.forEach(X=>{$.set(X.template_id,($.get(X.template_id)||0)+1)});const V=new Map;z.forEach(X=>{V.set(X.template_id,(V.get(X.template_id)||0)+1)});const W=new Map;return t&&(await M(()=>H.from("content_engagement_logs").select("resource_id").eq("resource_type","template").eq("action_type","view"))).forEach(te=>{W.set(te.resource_id,(W.get(te.resource_id)||0)+1)}),(A||[]).map(X=>({...X,links:(P||[]).filter(te=>te.template_id===X.id)||[],likesCount:$.get(X.id)||0,commentsCount:V.get(X.id)||0,viewsCount:W.get(X.id)||0}))}}),g=m.filter(A=>{var M;const T=A.name.toLowerCase().includes(n.toLowerCase())||((M=A.description)==null?void 0:M.toLowerCase().includes(n.toLowerCase())),P=a==="all"||A.category_id===a,I=l==="all"||A.type_id===l;return T&&P&&I}),y=()=>{r(""),i("all"),o("all")},x=n||a!=="all"||l!=="all",_=(k=[...m].sort((A,T)=>new Date(T.publish_date||T.created_at).getTime()-new Date(A.publish_date||A.created_at).getTime())[0])==null?void 0:k.id,b=A=>{s(`/templates/${A}`)};return e.jsx(Qs,{title:"Canva Templates",children:e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{children:[e.jsx("h1",{className:"font-bold text-foreground text-5xl",children:"Canva Templates"}),e.jsx("p",{className:"text-muted-foreground mt-1",children:"Browse and use our collection of professionally designed templates"})]}),!f&&m.filter(A=>A.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(Wa,{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(A=>A.is_featured).slice(0,4).map(A=>e.jsxs(_e,{className:"group overflow-hidden hover:shadow-lg transition-all duration-200 cursor-pointer relative",onClick:()=>b(A.id),children:[e.jsxs("div",{className:"aspect-[3/2] relative overflow-hidden bg-muted",children:[A.id===_&&e.jsx(We,{className:"absolute top-2 left-2 z-10 font-bold border-0 hover:opacity-90",style:{backgroundColor:"#e8c369",color:"#3d2f0a"},children:"NEW!"}),A.preview_image_url?e.jsx("img",{src:A.preview_image_url,alt:A.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(De,{className:"p-3",children:[e.jsx("h3",{className:"font-semibold text-foreground line-clamp-1 text-sm",children:A.name}),A.description&&e.jsx("p",{className:"text-xs text-muted-foreground line-clamp-2 mt-1",children:eY(A.description)})]})]},A.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(Gr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(we,{placeholder:"Search templates...",value:n,onChange:A=>r(A.target.value),className:"pl-9"})]}),e.jsxs(Ns,{value:a,onValueChange:i,children:[e.jsx(ws,{className:"w-full sm:w-48",children:e.jsx(ks,{placeholder:"All Categories"})}),e.jsxs(js,{children:[e.jsx(nt,{value:"all",children:"All Categories"}),u.map(A=>e.jsx(nt,{value:A.id,children:A.name},A.id))]})]}),e.jsxs(Ns,{value:l,onValueChange:o,children:[e.jsx(ws,{className:"w-full sm:w-48",children:e.jsx(ks,{placeholder:"All Types"})}),e.jsxs(js,{children:[e.jsx(nt,{value:"all",children:"All Types"}),h.map(A=>e.jsx(nt,{value:A.id,children:A.name},A.id))]})]}),e.jsxs("div",{className:"flex gap-2",children:[x&&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(G0,{className:"h-4 w-4"})}),e.jsx(B,{variant:c==="list"?"secondary":"outline",size:"icon",onClick:()=>d("list"),className:"rounded-full",children:e.jsx(Kx,{className:"h-4 w-4"})})]})]})]}),e.jsxs("div",{className:"text-sm text-muted-foreground",children:[g.length," template",g.length!==1?"s":""," found"]}),f&&e.jsx("div",{className:c==="grid"?"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-6":"space-y-4",children:[...Array(8)].map((A,T)=>e.jsx(_e,{children:e.jsxs(De,{className:"p-4",children:[e.jsx(xn,{className:"aspect-[4/3] w-full rounded-lg mb-4"}),e.jsx(xn,{className:"h-5 w-3/4 mb-2"}),e.jsx(xn,{className:"h-4 w-full mb-4"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(xn,{className:"h-5 w-16"}),e.jsx(xn,{className:"h-5 w-20"})]})]})},T))}),!f&&g.length===0&&e.jsxs("div",{className:"text-center py-12",children:[e.jsx("div",{className:"text-muted-foreground mb-4",children:x?"No templates match your filters":"No templates available yet"}),x&&e.jsx(B,{variant:"outline",onClick:y,children:"Clear Filters"})]}),!f&&g.length>0&&e.jsx("div",{className:c==="grid"?"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-6":"space-y-4",children:g.map(A=>e.jsxs(_e,{className:`group overflow-hidden hover:shadow-lg transition-all duration-200 cursor-pointer ${c==="list"?"flex flex-row":""}`,onClick:()=>b(A.id),children:[e.jsxs("div",{className:`relative overflow-hidden bg-muted ${c==="list"?"w-48 shrink-0":"aspect-[3/2]"}`,children:[A.id===_&&e.jsx(We,{className:"absolute top-2 left-2 z-10 font-bold border-0 hover:opacity-90",style:{backgroundColor:"#e8c369",color:"#3d2f0a"},children:"NEW!"}),A.preview_image_url?e.jsx("img",{src:A.preview_image_url,alt:A.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"}),A.links.length>1&&e.jsx("div",{className:"absolute top-2 right-2",children:e.jsxs(We,{variant:"secondary",className:"gap-1 bg-background/90 backdrop-blur-sm !text-secondary",children:[e.jsx(gc,{className:"h-3 w-3"}),A.links.length]})})]}),e.jsxs(De,{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:A.name}),A.description&&e.jsx("p",{className:"text-sm text-muted-foreground line-clamp-2 mb-3 flex-1",children:eY(A.description)}),e.jsxs("div",{className:"flex flex-wrap gap-2 mb-3",children:[A.category&&e.jsx(We,{variant:"secondary",className:"text-xs",children:A.category.name}),A.type&&e.jsx(We,{variant:"outline",className:"text-xs",children:A.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(ax,{className:"h-3.5 w-3.5"}),A.likesCount]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Ud,{className:"h-3.5 w-3.5"}),A.commentsCount]}),t&&e.jsxs("span",{className:"flex items-center gap-1",title:"Total views (admin only)",children:[e.jsx(da,{className:"h-3.5 w-3.5"}),A.viewsCount]})]}),e.jsxs(B,{size:"sm",className:"w-full gap-2",onClick:T=>{T.stopPropagation(),b(A.id)},children:[e.jsx(Tr,{className:"h-4 w-4"}),"View Template"]})]})]},A.id))})]})})};var eTs="Separator",cit="horizontal",tTs=["horizontal","vertical"],yAt=N.forwardRef((s,t)=>{const{decorative:n,orientation:r=cit,...a}=s,i=sTs(r)?r:cit,o=n?{role:"none"}:{"aria-orientation":i==="vertical"?i:void 0,role:"separator"};return e.jsx(Da.div,{"data-orientation":i,...o,...a,ref:t})});yAt.displayName=eTs;function sTs(s){return tTs.includes(s)}var vAt=yAt;const Wl=N.forwardRef(({className:s,orientation:t="horizontal",decorative:n=!0,...r},a)=>e.jsx(vAt,{ref:a,decorative:n,orientation:t,className:Ot("shrink-0 bg-border",t==="horizontal"?"h-[1px] w-full":"h-full w-[1px]",s),...r}));Wl.displayName=vAt.displayName;const nTs=()=>{const{templateId:s}=uo(),t=tr(),{user:n,isAdmin:r}=Ls(),{toast:a}=Ci(),i=as(),{trackEngagement:l}=pU(),[o,c]=N.useState(""),{data:d,isLoading:u}=mt({queryKey:["template-detail",s],queryFn:async()=>{const{data:A,error:T}=await H.from("canva_templates").select(` *, category:template_categories(id, name), type:template_types(id, name) `).eq("id",s).single();if(T)throw T;const{data:P}=await H.from("template_links").select("*").eq("template_id",s).order("sort_order"),{data:I}=await H.from("template_guides").select("*").eq("template_id",s).order("sort_order");return{...A,links:P||[],guides:I||[]}},enabled:!!s}),{data:h=[]}=mt({queryKey:["template-linked-toolkits",s],queryFn:async()=>{const{data:A,error:T}=await H.from("resource_kit_templates").select("kit_id, resource_kits:kit_id(id, name, featured_image_url)").eq("template_id",s);if(T)throw T;return(A||[]).map(P=>P.resource_kits).filter(Boolean)},enabled:!!s});N.useEffect(()=>{d&&l("template",d.id,d.name,"view")},[d==null?void 0:d.id]);const{data:m=[]}=mt({queryKey:["template-likes",s],queryFn:async()=>{const{data:A,error:T}=await H.from("template_likes").select("*").eq("template_id",s);if(T)throw T;return A},enabled:!!s}),{data:f=[]}=mt({queryKey:["template-comments",s],queryFn:async()=>{const{data:A,error:T}=await H.from("template_comments").select("*").eq("template_id",s).order("created_at",{ascending:!1});if(T)throw T;const P=[...new Set(A.map(L=>L.user_id))],{data:I}=await H.from("profiles").select("id, name").in("id",P),M=new Map((I==null?void 0:I.map(L=>[L.id,L.name]))||[]);return A.map(L=>({...L,user_name:M.get(L.user_id)||"Unknown User"}))},enabled:!!s}),g=_t({mutationFn:async A=>{const{error:T}=await H.from("template_comments").insert({template_id:s,user_id:n.id,content:A});if(T)throw T},onSuccess:()=>{i.invalidateQueries({queryKey:["template-comments",s]}),c(""),a({title:"Comment added!"})},onError:A=>{a({title:"Error adding comment",description:A.message,variant:"destructive"})}}),y=_t({mutationFn:async A=>{const{error:T}=await H.from("template_comments").delete().eq("id",A);if(T)throw T},onSuccess:()=>{i.invalidateQueries({queryKey:["template-comments",s]}),a({title:"Comment deleted"})}}),x=_t({mutationFn:async()=>{const A=m.find(T=>T.user_id===(n==null?void 0:n.id));if(A){const{error:T}=await H.from("template_likes").delete().eq("id",A.id);if(T)throw T}else{const{error:T}=await H.from("template_likes").insert({template_id:s,user_id:n.id});if(T)throw T}},onSuccess:()=>{i.invalidateQueries({queryKey:["template-likes",s]})}}),_=m.some(A=>A.user_id===(n==null?void 0:n.id)),b=A=>A.split(" ").map(T=>T[0]).join("").toUpperCase().slice(0,2),k=A=>{A.preventDefault(),!(!o.trim()||!n)&&g.mutate(o.trim())};return u?e.jsx(Qs,{title:"Templates",children:e.jsx("div",{className:"flex justify-center py-12",children:e.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})})}):d?e.jsx(Qs,{title:d.name,children:e.jsxs("div",{className:"space-y-6 max-w-5xl mx-auto",children:[e.jsx(B,{variant:"ghost",size:"sm",asChild:!0,className:"gap-2",children:e.jsxs(cr,{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(We,{variant:"secondary",children:d.category.name}),d.type&&e.jsx(We,{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(cr,{to:`/admin/templates?edit=${d.id}`,children:[e.jsx(Ja,{className:"h-4 w-4"}),e.jsx("span",{children:"Edit"})]})}),e.jsx(yU,{resourceType:"template",resourceId:d.id,resourceTitle:d.name,size:"default",className:"rounded-full"}),e.jsxs(B,{variant:_?"default":"outline",className:"gap-2 rounded-full",onClick:()=>x.mutate(),disabled:!n||x.isPending,children:[e.jsx(ax,{className:`h-4 w-4 ${_?"fill-current":""}`}),m.length," ",m.length===1?"Like":"Likes"]})]})]}),d.description&&e.jsx("div",{className:"text-muted-foreground prose prose-sm max-w-none dark:prose-invert [&>p]:mb-4 [&>p:last-child]:mb-0 whitespace-pre-line",dangerouslySetInnerHTML:{__html:d.description}})]}),e.jsx(_e,{children:e.jsxs(De,{className:"pt-6",children:[e.jsxs("h3",{className:"font-semibold flex items-center gap-2 mb-4",children:[e.jsx(gc,{className:"h-4 w-4"}),d.links.length===1?"Template Link":"Template Links"]}),e.jsx("div",{className:"grid gap-2",children:d.links.map(A=>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(A.canva_share_link,"_blank")},children:[e.jsx("span",{className:"font-medium",children:A.title}),e.jsx(Tr,{className:"h-4 w-4 text-muted-foreground"})]},A.id))})]})}),d.video_url&&e.jsx(_e,{children:e.jsx(De,{className:"pt-6",children:e.jsx("div",{className:"aspect-video w-full rounded-lg overflow-hidden",children:e.jsx("iframe",{src:d.video_url,className:"w-full h-full",allow:"accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture",allowFullScreen:!0})})})}),d.guides&&d.guides.length>0&&e.jsx(_e,{children:e.jsxs(De,{className:"pt-6",children:[e.jsxs("h3",{className:"font-semibold flex items-center gap-2 mb-4",children:[e.jsx(Wr,{className:"h-4 w-4"}),"Guide Files"]}),e.jsx("div",{className:"grid gap-2",children:d.guides.map(A=>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(A.file_url,"_blank")},children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Wr,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{className:"font-medium",children:A.name}),A.file_size&&e.jsxs("span",{className:"text-xs text-muted-foreground",children:["(",(A.file_size/1024).toFixed(0)," KB)"]})]}),e.jsx(oi,{className:"h-4 w-4 text-muted-foreground"})]},A.id))})]})}),h.length>0&&e.jsx(_e,{children:e.jsxs(De,{className:"pt-6",children:[e.jsxs("h3",{className:"font-semibold flex items-center gap-2 mb-4",children:[e.jsx(Ku,{className:"h-4 w-4"}),"Related Toolkits"]}),e.jsx("div",{className:"grid gap-2",children:h.map(A=>e.jsxs(B,{variant:"outline",className:"w-full justify-start gap-3 h-auto py-3",onClick:()=>t(`/toolbox/${A.id}`),children:[A.featured_image_url?e.jsx("img",{src:A.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(Ku,{className:"h-4 w-4 text-muted-foreground"})}),e.jsx("span",{className:"font-medium",children:A.name})]},A.id))})]})}),e.jsx(Wl,{}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("h3",{className:"font-semibold flex items-center gap-2 text-lg",children:[e.jsx(Ud,{className:"h-5 w-5"}),"Comments (",f.length,")"]}),n?e.jsxs("form",{onSubmit:k,className:"flex gap-2",children:[e.jsx(Ws,{placeholder:"Add a comment...",value:o,onChange:A=>c(A.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()||g.isPending,children:e.jsx(Rr,{className:"h-4 w-4"})})]}):e.jsx("p",{className:"text-sm text-muted-foreground",children:"Log in to add a comment"}),e.jsx("div",{className:"space-y-4",children:f.length===0?e.jsx(_e,{children:e.jsx(De,{className:"py-8 text-center",children:e.jsx("p",{className:"text-muted-foreground",children:"No comments yet. Be the first to share your thoughts!"})})}):f.map(A=>e.jsx(_e,{children:e.jsx(De,{className:"pt-4 pb-4",children:e.jsxs("div",{className:"flex gap-3",children:[e.jsx(Ua,{className:"h-10 w-10 flex-shrink-0",children:e.jsx(qa,{className:"text-sm",children:b(A.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:A.user_name}),e.jsx("span",{className:"text-sm text-muted-foreground",children:nc(new Date(A.created_at),{addSuffix:!0})}),A.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(A.id),children:e.jsx(qn,{className:"h-3 w-3 text-muted-foreground"})})]}),e.jsx("p",{className:"text-sm whitespace-pre-wrap",children:A.content})]})]})})},A.id))})]})]})}):e.jsx(Qs,{title:"Templates",children:e.jsxs("div",{className:"flex flex-col items-center justify-center py-12 text-center",children:[e.jsx(gc,{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(cr,{to:"/templates",children:"Back to Templates"})})]})})},rTs=["reserved","scheduled_for_charge","paid","payment_failed","completed"],LY=s=>!!s&&(s.access_override||rTs.includes(s.status)),_p=(s,t="usd")=>new Intl.NumberFormat("en-US",{style:"currency",currency:t.toUpperCase(),maximumFractionDigits:s%100===0?0:2}).format(s/100),PY=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`},dOe=(s,t="usd",n)=>`One-time payment: ${_p(s,t)} for the ${PY(n)}`,iVe=[{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}],IY=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:[]}},aTs=(s,t)=>!s.hidden.includes(t),dit=(s,t)=>s.required.includes(t)&&!s.hidden.includes(t),vd=(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,v3e=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&&rmt({queryKey:["programs"],queryFn:async()=>{const{data:s,error:t}=await H.from("programs").select("*").eq("status","published").order("is_featured",{ascending:!1}).order("sort_order",{ascending:!0});if(t)throw t;return s||[]}}),oVe=s=>mt({queryKey:["program",s],enabled:!!s,queryFn:async()=>{const{data:t,error:n}=await H.from("programs").select("*").eq("slug",s).maybeSingle();if(n)throw n;return t||null}}),bAt=s=>mt({queryKey:["program-seats",s],enabled:!!s,refetchInterval:6e4,queryFn:async()=>{const{data:t,error:n}=await H.rpc("program_seats_remaining",{_program_id:s});if(n)throw n;return t??0}}),_At=()=>{const{user:s}=Ls();return mt({queryKey:["program-enrollments",s==null?void 0:s.id],enabled:!!(s!=null&&s.id),queryFn:async()=>{const{data:t,error:n}=await H.from("program_enrollments").select("*").eq("user_id",s.id);if(n)throw n;return t||[]}})},lVe=s=>{const{data:t=[],...n}=_At();return{...n,data:s&&t.find(r=>r.program_id===s)||null}},oTs=()=>{const{user:s}=Ls(),t=as();return _t({mutationFn:async n=>{const{data:r,error:a}=await H.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=>ie.error(n.message||"Could not save your answers")})},wAt=s=>{const{user:t}=Ls();return mt({queryKey:["program-intake",s,t==null?void 0:t.id],enabled:!!s&&!!(t!=null&&t.id),queryFn:async()=>{const{data:n,error:r}=await H.from("program_intake_responses").select("*").eq("program_id",s).eq("user_id",t.id).maybeSingle();if(r)throw r;return n}})},lTs=()=>{const s=as();return _t({mutationFn:async t=>{const{data:n,error:r}=await H.rpc("program_claim_seat",{_program_id:t});if(r)throw r;return n},onSuccess:()=>{s.invalidateQueries({queryKey:["program-enrollments"]}),s.invalidateQueries({queryKey:["program-seats"]})}})},cTs=(s,t)=>{const{user:n}=Ls(),r=t||(n==null?void 0:n.id);return mt({queryKey:["program-workspace",s,r],enabled:!!s&&!!r,queryFn:async()=>{const a=r,[i,l,o,c,d,u,h,m,f,g,y]=await Promise.all([H.from("program_weeks").select("*").eq("program_id",s).order("week_number"),H.from("program_lessons").select("*").eq("program_id",s).order("sort_order"),H.from("program_resources").select("*").eq("program_id",s).order("sort_order"),H.from("program_events").select("*").eq("program_id",s).order("starts_at"),H.from("program_announcements").select("*").eq("program_id",s).order("published_at",{ascending:!1}),H.from("program_lesson_completions").select("*").eq("program_id",s).eq("user_id",a),H.from("program_weekly_progress").select("*").eq("program_id",s).eq("user_id",a).order("week_number"),H.from("program_video_logs").select("*").eq("program_id",s).eq("user_id",a).order("posted_at",{ascending:!1}),H.from("program_badge_awards").select("*").eq("program_id",s).eq("user_id",a),H.from("program_profile_analyses").select("*").eq("program_id",s).eq("user_id",a).maybeSingle(),H.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:f.data||[],analysis:g.data||null}}})},dTs=s=>{const{user:t}=Ls(),n=as();return _t({mutationFn:async({lessonId:r,done:a})=>{if(a){const{error:i}=await H.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 H.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=>ie.error(r.message||"Could not update progress")})},uTs=s=>{const{user:t}=Ls(),n=as();return _t({mutationFn:async r=>{const{error:a}=await H.from("program_video_logs").insert({...r,program_id:s,user_id:t.id});if(a)throw a},onSuccess:()=>{ie.success("Video logged — nice work"),n.invalidateQueries({queryKey:["program-workspace"]})},onError:r=>ie.error(r.message||"Could not log the video")})},hTs=s=>{const{user:t}=Ls(),n=as();return _t({mutationFn:async r=>{const{error:a}=await H.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:()=>{ie.success("Weekly check-in saved"),n.invalidateQueries({queryKey:["program-workspace"]})},onError:r=>ie.error(r.message||"Could not save your check-in")})},mTs=s=>{const{user:t}=Ls(),n=as();return _t({mutationFn:async({eventId:r,optIn:a})=>{const{error:i}=await H.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=>ie.error(r.message||"Could not update your RSVP")})},pTs=s=>mt({queryKey:["program-discount-codes",s],enabled:!!s,queryFn:async()=>{const{data:t,error:n}=await H.from("program_discount_codes").select("*").eq("program_id",s).order("created_at",{ascending:!1});if(n)throw n;return t||[]}}),fTs=s=>{const t=as();return _t({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 H.from("program_discount_codes").update(r).eq("id",n.id);if(a)throw a}else{const{error:a}=await H.from("program_discount_codes").insert(r);if(a)throw a}},onSuccess:()=>{ie.success("Discount code saved"),t.invalidateQueries({queryKey:["program-discount-codes"]})},onError:n=>{var r;return ie.error((r=n.message)!=null&&r.includes("duplicate")?"That code already exists for this program":n.message||"Could not save the code")}})},gTs=()=>{const s=as();return _t({mutationFn:async t=>{const{error:n}=await H.from("program_discount_codes").delete().eq("id",t);if(n)throw n},onSuccess:()=>{ie.success("Discount code deleted"),s.invalidateQueries({queryKey:["program-discount-codes"]})},onError:t=>ie.error(t.message||"Could not delete the code")})},xTs=()=>_t({mutationFn:async({enrollmentId:s,code:t})=>{const{data:n,error:r}=await H.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}}),yTs=()=>_t({mutationFn:async s=>{const{error:t}=await H.rpc("program_clear_discount",{_enrollment_id:s});if(t)throw t}}),vTs=s=>mt({queryKey:["admin-program-events",s],enabled:!!s,queryFn:async()=>{const{data:t,error:n}=await H.from("program_events").select("*").eq("program_id",s).order("starts_at",{ascending:!0});if(n)throw n;return t||[]}}),bTs=s=>{const t=as();return _t({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 H.from("program_events").update(r).eq("id",n.id);if(a)throw a}else{const{error:a}=await H.from("program_events").insert(r);if(a)throw a}},onSuccess:()=>{ie.success("Session saved"),t.invalidateQueries({queryKey:["admin-program-events"]}),t.invalidateQueries({queryKey:["program-workspace"]})},onError:n=>ie.error(n.message||"Could not save the session")})},_Ts=()=>{const s=as();return _t({mutationFn:async t=>{const{error:n}=await H.from("program_events").delete().eq("id",t);if(n)throw n},onSuccess:()=>{ie.success("Session removed"),s.invalidateQueries({queryKey:["admin-program-events"]}),s.invalidateQueries({queryKey:["program-workspace"]})},onError:t=>ie.error(t.message||"Could not remove the session")})},wTs=s=>mt({queryKey:["admin-program-lessons",s],enabled:!!s,queryFn:async()=>{const[t,n]=await Promise.all([H.from("program_lessons").select("*").eq("program_id",s).order("sort_order"),H.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||[]}}}),jTs=s=>{const t=as();return _t({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 H.from("program_lessons").update(r).eq("id",n.id);if(a)throw a}else{const{error:a}=await H.from("program_lessons").insert(r);if(a)throw a}},onSuccess:()=>{ie.success("Video saved"),t.invalidateQueries({queryKey:["admin-program-lessons"]}),t.invalidateQueries({queryKey:["program-workspace"]})},onError:n=>ie.error(n.message||"Could not save the video")})},NTs=()=>{const s=as();return _t({mutationFn:async t=>{const{error:n}=await H.from("program_lessons").delete().eq("id",t);if(n)throw n},onSuccess:()=>{ie.success("Video removed"),s.invalidateQueries({queryKey:["admin-program-lessons"]}),s.invalidateQueries({queryKey:["program-workspace"]})},onError:t=>ie.error(t.message||"Could not remove the video")})},jAt=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},NAt=[{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"}],vU="event-images",b3e=s=>{if(s.file_path){const{data:t}=H.storage.from(vU).getPublicUrl(s.file_path);return t.publicUrl}return s.url||null},oK=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 H.storage.from(vU).download(s.file_path);if(r||!n){const c=b3e(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)},kTs=s=>mt({queryKey:["admin-program-resources",s],enabled:!!s,queryFn:async()=>{const{data:t,error:n}=await H.from("program_resources").select("*").eq("program_id",s).order("sort_order");if(n)throw n;return t||[]}}),STs=s=>{const t=as();return _t({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 H.from("program_resources").update(r).eq("id",n.id);if(a)throw a}else{const{error:a}=await H.from("program_resources").insert(r);if(a)throw a}},onSuccess:()=>{ie.success("Resource saved"),t.invalidateQueries({queryKey:["admin-program-resources"]}),t.invalidateQueries({queryKey:["program-workspace"]})},onError:n=>ie.error(n.message||"Could not save the resource")})},CTs=()=>{const s=as();return _t({mutationFn:async t=>{t.file_path&&await H.storage.from(vU).remove([t.file_path]);const{error:n}=await H.from("program_resources").delete().eq("id",t.id);if(n)throw n},onSuccess:()=>{ie.success("Resource removed"),s.invalidateQueries({queryKey:["admin-program-resources"]}),s.invalidateQueries({queryKey:["program-workspace"]})},onError:t=>ie.error(t.message||"Could not remove the resource")})},ATs=(s,t)=>mt({queryKey:["admin-program-member-resources",s,t],enabled:!!s&&!!t,queryFn:async()=>{const{data:n,error:r}=await H.from("program_member_resources").select("*").eq("program_id",s).eq("user_id",t).order("sort_order");if(r)throw r;return n||[]}}),TTs=(s,t)=>{const n=as(),{user:r}=Ls();return _t({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 H.from("program_member_resources").update(i).eq("id",a.id);if(l)throw l}else{const{error:l}=await H.from("program_member_resources").insert(i);if(l)throw l}},onSuccess:()=>{ie.success("Personal resource saved"),n.invalidateQueries({queryKey:["admin-program-member-resources"]}),n.invalidateQueries({queryKey:["program-workspace"]})},onError:a=>ie.error(a.message||"Could not save the resource")})},ETs=()=>{const s=as();return _t({mutationFn:async t=>{t.file_path&&await H.storage.from(vU).remove([t.file_path]);const{error:n}=await H.from("program_member_resources").delete().eq("id",t.id);if(n)throw n},onSuccess:()=>{ie.success("Personal resource removed"),s.invalidateQueries({queryKey:["admin-program-member-resources"]}),s.invalidateQueries({queryKey:["program-workspace"]})},onError:t=>ie.error(t.message||"Could not remove the resource")})},MTs=s=>{const{user:t}=Ls();return mt({queryKey:["program-interest",s,t==null?void 0:t.id],enabled:!!s&&!!(t!=null&&t.id),queryFn:async()=>{const{data:n,error:r}=await H.from("program_interest").select("*").eq("program_id",s).eq("user_id",t.id).maybeSingle();if(r)throw r;return n||null}})},LTs=s=>{const t=as(),{user:n}=Ls();return _t({mutationFn:async r=>{if(!(n!=null&&n.id)||!s)throw new Error("You need to be signed in.");if(r){const{error:a}=await H.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 H.from("program_interest").delete().eq("program_id",s).eq("user_id",n.id);if(a)throw a}return r},onSuccess:r=>{ie.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=>ie.error(r.message||"Could not update your notify preference")})},PTs=s=>mt({queryKey:["admin-program-interest",s],enabled:!!s,queryFn:async()=>{const{data:t,error:n}=await H.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 H.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}})}}),uit=({program:s,enrolled:t})=>{const{notOpenYet:n,closed:r,opensLabel:a}=v3e(s);return e.jsxs(_e,{className:"group overflow-hidden border-border/60 transition-all hover:border-primary/40 hover:shadow-lg",children:[e.jsxs("div",{className:"relative aspect-[16/9] overflow-hidden bg-muted",children:[s.cover_image_url?e.jsx("img",{src:s.cover_image_url,alt:`${s.name} program cover`,loading:"lazy",className:"h-full w-full object-cover transition-transform duration-500 group-hover:scale-105"}):e.jsx("div",{className:"flex h-full w-full items-center justify-center bg-gradient-to-br from-primary/15 via-background to-accent/20",children:e.jsx(Cn,{className:"h-10 w-10 text-primary/60"})}),e.jsxs("div",{className:"absolute left-3 top-3 flex gap-2",children:[s.is_featured&&e.jsx(We,{className:"shadow-sm",children:"Featured"}),t&&e.jsxs(We,{variant:"secondary",className:"shadow-sm",children:[e.jsx(Hr,{className:"mr-1 h-3 w-3"})," Enrolled"]})]})]}),e.jsxs(De,{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(Xr,{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(ld,{className:"h-3.5 w-3.5"}),"Starts ",vd(s.kickoff_at)]}),e.jsxs("span",{className:"inline-flex items-center gap-1.5",children:[e.jsx(Yn,{className:"h-3.5 w-3.5"}),s.capacity," seats"]})]}),e.jsxs("div",{className:"flex items-center justify-between border-t border-border/60 pt-4",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-lg font-semibold",children:s.payment_mode==="free"?"Included":_p(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 ",PY(s.duration_weeks)," — no subscription",s.charge_at?` · charged ${vd(s.charge_at)}`:""]}):null]}),e.jsx(B,{asChild:!0,size:"sm",children:e.jsxs(cr,{to:t?`/programs/${s.slug}/workspace`:`/programs/${s.slug}`,children:[t?"Open program":n?"Preview details":"View details",e.jsx(vi,{className:"ml-1.5 h-4 w-4"})]})})]})]})]})},ITs=()=>{const{data:s=[],isLoading:t}=iTs(),{data:n=[]}=_At(),r=new Set(n.filter(l=>LY(l)).map(l=>l.program_id)),a=s.filter(l=>r.has(l.id)),i=s.filter(l=>!r.has(l.id));return e.jsx(Qs,{children:e.jsxs("div",{className:"mx-auto w-full max-w-6xl space-y-10 p-4 md:p-8",children:[e.jsxs("header",{className:"space-y-3",children:[e.jsx("p",{className:"text-xs font-semibold uppercase tracking-[0.2em] text-primary",children:"LevelUp Programs"}),e.jsx("h1",{className:"text-3xl font-bold tracking-tight md:text-4xl",children:"Go deeper than the membership"}),e.jsx("p",{className:"max-w-2xl text-muted-foreground",children:"Time-bound coaching programs, masterminds and challenges built to move one specific part of your business forward — with a real cohort, a real roadmap and real accountability."})]}),t?e.jsx("div",{className:"grid gap-6 md:grid-cols-2 lg:grid-cols-3",children:[0,1,2].map(l=>e.jsx(xn,{className:"h-80 rounded-xl"},l))}):e.jsxs(e.Fragment,{children:[a.length>0&&e.jsxs("section",{className:"space-y-4",children:[e.jsx("h2",{className:"text-sm font-semibold uppercase tracking-wider text-muted-foreground",children:"Your programs"}),e.jsx("div",{className:"grid gap-6 md:grid-cols-2 lg:grid-cols-3",children:a.map(l=>e.jsx(uit,{program:l,enrolled:!0},l.id))})]}),e.jsxs("section",{className:"space-y-4",children:[a.length>0&&e.jsx("h2",{className:"text-sm font-semibold uppercase tracking-wider text-muted-foreground",children:"Open for enrollment"}),i.length===0&&a.length===0?e.jsx(_e,{className:"border-dashed",children:e.jsxs(De,{className:"flex flex-col items-center gap-3 p-12 text-center",children:[e.jsx(Cn,{className:"h-8 w-8 text-muted-foreground"}),e.jsx("p",{className:"font-medium",children:"No programs are open right now"}),e.jsx("p",{className:"max-w-md text-sm text-muted-foreground",children:"New cohorts are announced inside the Hub. Check back soon — seats are limited when they open."})]})}):e.jsx("div",{className:"grid gap-6 md:grid-cols-2 lg:grid-cols-3",children:i.map(l=>e.jsx(uit,{program:l,enrolled:!1},l.id))})]})]})]})})},DTs=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},RTs=({url:s,headline:t,posterUrl:n})=>{const[r,a]=N.useState(!1),i=(s||"").trim();if(!i)return null;const l=DTs(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(wp,{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 vN="Accordion",OTs=["Home","End","ArrowDown","ArrowUp","ArrowLeft","ArrowRight"],[cVe,FTs,zTs]=K$(vN),[_3e,XOn]=Um(vN,[zTs,wSt]),dVe=wSt(),kAt=Rt.forwardRef((s,t)=>{const{type:n,...r}=s,a=r,i=r;return e.jsx(cVe.Provider,{scope:s.__scopeAccordion,children:n==="multiple"?e.jsx(qTs,{...i,ref:t}):e.jsx(UTs,{...a,ref:t})})});kAt.displayName=vN;var[SAt,BTs]=_3e(vN),[CAt,$Ts]=_3e(vN,{collapsible:!1}),UTs=Rt.forwardRef((s,t)=>{const{value:n,defaultValue:r,onValueChange:a=()=>{},collapsible:i=!1,...l}=s,[o,c]=Ng({prop:n,defaultProp:r??"",onChange:a,caller:vN});return e.jsx(SAt,{scope:s.__scopeAccordion,value:Rt.useMemo(()=>o?[o]:[],[o]),onItemOpen:c,onItemClose:Rt.useCallback(()=>i&&c(""),[i,c]),children:e.jsx(CAt,{scope:s.__scopeAccordion,collapsible:i,children:e.jsx(AAt,{...l,ref:t})})})}),qTs=Rt.forwardRef((s,t)=>{const{value:n,defaultValue:r,onValueChange:a=()=>{},...i}=s,[l,o]=Ng({prop:n,defaultProp:r??[],onChange:a,caller:vN}),c=Rt.useCallback(u=>o((h=[])=>[...h,u]),[o]),d=Rt.useCallback(u=>o((h=[])=>h.filter(m=>m!==u)),[o]);return e.jsx(SAt,{scope:s.__scopeAccordion,value:l,onItemOpen:c,onItemClose:d,children:e.jsx(CAt,{scope:s.__scopeAccordion,collapsible:!0,children:e.jsx(AAt,{...i,ref:t})})})}),[VTs,w3e]=_3e(vN),AAt=Rt.forwardRef((s,t)=>{const{__scopeAccordion:n,disabled:r,dir:a,orientation:i="vertical",...l}=s,o=Rt.useRef(null),c=jo(o,t),d=FTs(n),h=F3(a)==="ltr",m=la(s.onKeyDown,f=>{var M;if(!OTs.includes(f.key))return;const g=f.target,y=d().filter(L=>{var z;return!((z=L.ref.current)!=null&&z.disabled)}),x=y.findIndex(L=>L.ref.current===g),_=y.length;if(x===-1)return;f.preventDefault();let b=x;const k=0,A=_-1,T=()=>{b=x+1,b>A&&(b=k)},P=()=>{b=x-1,b{const{__scopeAccordion:n,value:r,...a}=s,i=w3e(ske,n),l=BTs(ske,n),o=dVe(n),c=_g(),d=r&&l.value.includes(r)||!1,u=i.disabled||s.disabled;return e.jsx(HTs,{scope:n,open:d,disabled:u,triggerId:c,children:e.jsx(kSt,{"data-orientation":i.orientation,"data-state":DAt(d),...o,...a,ref:t,disabled:u,open:d,onOpenChange:h=>{h?l.onItemOpen(r):l.onItemClose(r)}})})});TAt.displayName=ske;var EAt="AccordionHeader",MAt=Rt.forwardRef((s,t)=>{const{__scopeAccordion:n,...r}=s,a=w3e(vN,n),i=uVe(EAt,n);return e.jsx(Da.h3,{"data-orientation":a.orientation,"data-state":DAt(i.open),"data-disabled":i.disabled?"":void 0,...r,ref:t})});MAt.displayName=EAt;var uOe="AccordionTrigger",LAt=Rt.forwardRef((s,t)=>{const{__scopeAccordion:n,...r}=s,a=w3e(vN,n),i=uVe(uOe,n),l=$Ts(uOe,n),o=dVe(n);return e.jsx(cVe.ItemSlot,{scope:n,children:e.jsx(I1s,{"aria-disabled":i.open&&!l.collapsible||void 0,"data-orientation":a.orientation,id:i.triggerId,...o,...r,ref:t})})});LAt.displayName=uOe;var PAt="AccordionContent",IAt=Rt.forwardRef((s,t)=>{const{__scopeAccordion:n,...r}=s,a=w3e(vN,n),i=uVe(PAt,n),l=dVe(n);return e.jsx(D1s,{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}})});IAt.displayName=PAt;function DAt(s){return s?"open":"closed"}var GTs=kAt,WTs=TAt,KTs=MAt,RAt=LAt,OAt=IAt;const qR=GTs,$E=N.forwardRef(({className:s,...t},n)=>e.jsx(WTs,{ref:n,className:Ot("border-b",s),...t}));$E.displayName="AccordionItem";const UE=N.forwardRef(({className:s,children:t,...n},r)=>e.jsx(KTs,{className:"flex",children:e.jsxs(RAt,{ref:r,className:Ot("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(Xo,{className:"h-4 w-4 shrink-0 transition-transform duration-200"})]})}));UE.displayName=RAt.displayName;const qE=N.forwardRef(({className:s,children:t,...n},r)=>e.jsx(OAt,{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:Ot("pb-4 pt-0",s),children:t})}));qE.displayName=OAt.displayName;const YTs=({programId:s,opensLabel:t})=>{const{data:n,isLoading:r}=MTs(s),a=LTs(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(wT,{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(us,{className:"mr-2 h-4 w-4 animate-spin"}):i?e.jsx(pa,{className:"mr-2 h-4 w-4"}):e.jsx(wT,{className:"mr-2 h-4 w-4"}),i?"You're on the list":"Notify me"]})]})},ZTs=()=>{const{slug:s}=uo(),{data:t,isLoading:n}=oVe(s),{data:r}=bAt(t==null?void 0:t.id),{data:a}=lVe(t==null?void 0:t.id),i=LY(a),l=(t==null?void 0:t.sales_copy)||{},o=l.outcomes||[],c=l.included||[],d=l.for_who||[],u=l.not_for||[],h=l.faqs||[],m=l.phases||[];if(n)return e.jsx(Qs,{children:e.jsxs("div",{className:"mx-auto max-w-5xl space-y-6 p-8",children:[e.jsx(xn,{className:"h-64 w-full rounded-xl"}),e.jsx(xn,{className:"h-40 w-full rounded-xl"})]})});if(!t)return e.jsx(Qs,{children:e.jsxs("div",{className:"mx-auto max-w-2xl p-12 text-center",children:[e.jsx("h1",{className:"text-2xl font-bold",children:"Program not found"}),e.jsx("p",{className:"mt-2 text-muted-foreground",children:"This program may have been closed or unpublished."}),e.jsx(B,{asChild:!0,className:"mt-6",children:e.jsx(cr,{to:"/programs",children:"Back to Programs"})})]})});const f=typeof r=="number"&&r<=0&&!i,{notOpenYet:g,closed:y,opensLabel:x}=v3e(t),_=!i&&(f||y||g),b=i?"Open your program":g?`Enrollment opens ${vd(t.enrollment_open_at)}`:f?"Cohort is full":y?"Enrollment closed":t.payment_mode==="delayed"?"Reserve my seat":"Enroll now",k=i?`/programs/${t.slug}/workspace`:`/programs/${t.slug}/enroll`;return e.jsxs(Qs,{children:[e.jsxs(ic,{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(RTs,{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(We,{variant:"secondary",children:[t.duration_weeks,"-week program"]}),typeof r=="number"&&!i&&e.jsx(We,{variant:r<=10?"destructive":"outline",children:r>0?`${r} of ${t.capacity} seats left`:"Full"}),i&&e.jsxs(We,{children:[e.jsx(Hr,{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":_p(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 ",PY(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:vd(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(U0,{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:[dOe(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:vd(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:!_,size:"lg",disabled:_,children:_?e.jsx("span",{children:b}):e.jsxs(cr,{to:k,children:[b,e.jsx(vi,{className:"ml-2 h-4 w-4"})]})}),e.jsx(B,{asChild:!0,variant:"ghost",size:"lg",children:e.jsx(cr,{to:"/programs",children:"All programs"})})]}),g&&!i&&e.jsxs(e.Fragment,{children:[e.jsxs("p",{className:"inline-flex items-center gap-1.5 text-xs text-muted-foreground",children:[e.jsx(ld,{className:"h-3.5 w-3.5"}),"Enrollment opens ",x]}),e.jsx(YTs,{programId:t.id,opensLabel:x})]})]})]}),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((A,T)=>e.jsxs("div",{className:"flex items-start gap-3 rounded-lg border border-border/60 p-4",children:[e.jsx(Hr,{className:"mt-0.5 h-4 w-4 shrink-0 text-primary"}),e.jsx("p",{className:"text-sm",children:A})]},T))})]}),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((A,T)=>e.jsx(_e,{className:"border-border/60",children:e.jsxs(De,{className:"space-y-2 p-5",children:[e.jsxs("p",{className:"text-xs font-semibold uppercase tracking-wider text-primary",children:["Phase ",T+1]}),e.jsx("h3",{className:"font-semibold",children:A.title}),e.jsx("p",{className:"text-sm text-muted-foreground",children:A.detail})]})},T))})]}),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((A,T)=>e.jsxs("li",{className:"flex items-start gap-2.5 text-sm",children:[e.jsx(Cn,{className:"mt-0.5 h-4 w-4 shrink-0 text-primary"}),A]},T))})]}),(d.length>0||u.length>0)&&e.jsxs("section",{className:"grid gap-6 md:grid-cols-2",children:[d.length>0&&e.jsx(_e,{className:"border-border/60",children:e.jsxs(De,{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((A,T)=>e.jsxs("li",{className:"flex gap-2",children:[e.jsx(Hr,{className:"mt-0.5 h-4 w-4 shrink-0 text-primary"}),A]},T))})]})}),u.length>0&&e.jsx(_e,{className:"border-border/60",children:e.jsxs(De,{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((A,T)=>e.jsxs("li",{className:"flex gap-2",children:[e.jsx(Xr,{className:"mt-0.5 h-4 w-4 shrink-0"}),A]},T))})]})})]}),h.length>0&&e.jsxs("section",{className:"space-y-4",children:[e.jsx("h2",{className:"text-xl font-semibold",children:"Questions"}),e.jsx(qR,{type:"single",collapsible:!0,className:"rounded-xl border border-border/60 px-4",children:h.map((A,T)=>e.jsxs($E,{value:`faq-${T}`,children:[e.jsx(UE,{className:"text-left text-sm font-medium",children:A.q}),e.jsx(qE,{className:"text-sm text-muted-foreground",children:A.a})]},T))})]}),e.jsxs("section",{className:"rounded-2xl border border-border/60 bg-muted/40 p-6 text-center md:p-10",children:[e.jsx(na,{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:!_,size:"lg",disabled:_,children:_?e.jsx("span",{children:b}):e.jsxs(cr,{to:k,children:[b,e.jsx(vi,{className:"ml-2 h-4 w-4"})]})}),typeof r=="number"&&r>0&&!i&&e.jsxs("span",{className:"inline-flex items-center gap-1.5 text-sm text-muted-foreground",children:[e.jsx(Yn,{className:"h-4 w-4"}),r," seats remaining"]})]}),!i&&(g?e.jsxs("p",{className:"mt-3 inline-flex items-center gap-1.5 text-xs text-muted-foreground",children:[e.jsx(ld,{className:"h-3.5 w-3.5"}),"Enrollment opens ",x]}):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(ld,{className:"h-3.5 w-3.5"}),"Enrollment closes ",vd(t.enrollment_close_at)]}):null)]})]})]})},pse=["Your business","Your content","Your goals","Reserve your seat"],XTs=()=>{const{slug:s}=uo(),t=tr(),[n,r]=$c(),{user:a}=Ls(),{data:i,isLoading:l}=oVe(s),{data:o}=bAt(i==null?void 0:i.id),{data:c,refetch:d}=lVe(i==null?void 0:i.id),{data:u}=wAt(i==null?void 0:i.id),h=oTs(),m=lTs(),f=xTs(),g=yTs(),[y,x]=N.useState(0),[_,b]=N.useState(!1),[k,A]=N.useState(!1),[T,P]=N.useState(!1),[I,M]=N.useState(!1),[L,z]=N.useState(""),[$,V]=N.useState(null),W=N.useRef({}),[G,X]=N.useState({}),te=N.useRef(!1),ne=($e,Ye)=>{W.current={...W.current,[$e]:Ye},X(W.current)};N.useEffect(()=>{te.current||(u?(W.current={...u},X(W.current),te.current=!0):a&&(W.current={email:a.email,...W.current},X(W.current)))},[u,a]),N.useEffect(()=>{const $e=c;!i||!($e!=null&&$e.discount_code)||$||V({code:$e.discount_code,discount_cents:$e.discount_cents||0,amount_cents:$e.amount_cents??i.price_cents,original_cents:i.price_cents})},[c,i,$]);const me=$?$.amount_cents:(i==null?void 0:i.price_cents)??0,ue=N.useMemo(()=>IY(i),[i]),ce=$e=>aTs(ue,$e),ae=$e=>dit(ue,$e)?e.jsx("span",{className:"text-destructive",children:" *"}):null,he=($e,Ye)=>{const Je={...W.current.extra||{},[$e]:Ye};ne("extra",Je)},xe=$e=>ue.custom.filter((Ye,Je)=>Je%3===$e),ve=$e=>{const Ye=xe($e);if(!Ye.length)return null;const Je=G.extra||{};return e.jsx("div",{className:"space-y-4",children:Ye.map(Ke=>e.jsxs("div",{className:"space-y-2",children:[Ke.type==="checkbox"?e.jsxs("div",{className:"flex items-start gap-3 rounded-lg border border-border/60 p-4",children:[e.jsx(Bi,{id:Ke.id,checked:!!Je[Ke.id],onCheckedChange:st=>he(Ke.id,!!st)}),e.jsxs(re,{htmlFor:Ke.id,className:"text-sm font-normal leading-relaxed",children:[Ke.label,Ke.required&&e.jsx("span",{className:"text-destructive",children:" *"})]})]}):e.jsxs(e.Fragment,{children:[e.jsxs(re,{htmlFor:Ke.id,children:[Ke.label,Ke.required&&e.jsx("span",{className:"text-destructive",children:" *"})]}),Ke.type==="long_text"?e.jsx(Ws,{id:Ke.id,rows:3,value:Je[Ke.id]||"",onChange:st=>he(Ke.id,st.target.value)}):Ke.type==="select"?e.jsxs(Ns,{value:Je[Ke.id]||"",onValueChange:st=>he(Ke.id,st),children:[e.jsx(ws,{children:e.jsx(ks,{placeholder:"Select"})}),e.jsx(js,{children:(Ke.options||[]).map(st=>e.jsx(nt,{value:st,children:st},st))})]}):e.jsx(we,{id:Ke.id,value:Je[Ke.id]||"",onChange:st=>he(Ke.id,st.target.value)})]}),Ke.help&&e.jsx("p",{className:"text-xs text-muted-foreground",children:Ke.help})]},Ke.id))})},ge=$e=>{const Ye=W.current,Je=Ze=>Ze==null||Ze===""||Ze===!1,Ke=iVe.find(Ze=>Ze.step===$e&&dit(ue,Ze.key)&&Je(Ze.key==="timezone"?Ye.timezone||(i==null?void 0:i.timezone):Ye[Ze.key]));if(Ke)return Ke.label;const st=Ye.extra||{},rt=xe($e).find(Ze=>Ze.required&&Je(st[Ze.id]));return rt?rt.label:null},be=()=>{if(y<=2){const $e=ge(y);if($e)return ie.error(`Please answer: ${$e}`)}x($e=>$e+1)},Se=async()=>{if(!(!i||!L.trim()))try{let $e=c==null?void 0:c.id;(!$e||(c==null?void 0:c.status)==="canceled")&&($e=await m.mutateAsync(i.id));const Ye=await f.mutateAsync({enrollmentId:$e,code:L});V(Ye),z(""),await d(),ie.success(`Code applied — you save ${_p(Ye.discount_cents,i.currency)}`)}catch($e){ie.error($e.message||"That code could not be applied")}},Ie=async()=>{if(!(c!=null&&c.id))return V(null);try{await g.mutateAsync(c.id),V(null),await d()}catch($e){ie.error($e.message||"Could not remove the code")}},Me=n.get("setup"),Re=n.get("session_id"),Be=N.useRef(!1);N.useEffect(()=>{Me!=="success"||!Re||!(c!=null&&c.id)||Be.current||(Be.current=!0,A(!0),(async()=>{const{data:$e,error:Ye}=await H.functions.invoke("program-enroll",{body:{action:"verify",enrollment_id:c.id,session_id:Re}});if(A(!1),Ye||$e!=null&&$e.error||($e==null?void 0:$e.success)===!1){ie.error(($e==null?void 0:$e.error)||(Ye==null?void 0:Ye.message)||"We could not confirm your card");return}await d(),n.delete("setup"),n.delete("session_id"),r(n,{replace:!0}),ie.success("Your seat is confirmed")})())},[Me,Re,c==null?void 0:c.id]),N.useEffect(()=>{Me==="cancelled"&&ie.info("Checkout cancelled — your seat is held for a short while.")},[Me]);const Ne=N.useMemo(()=>c&&["reserved","scheduled_for_charge","paid","completed"].includes(c.status),[c]),Ge=async()=>{if(i){if(!T||i.payment_mode!=="free"&&!I){ie.error("Please confirm the checkboxes to continue");return}b(!0);try{let $e=c==null?void 0:c.id;(!$e||(c==null?void 0:c.status)==="canceled")&&($e=await m.mutateAsync(i.id)),await h.mutateAsync({...W.current,id:void 0,program_id:i.id,enrollment_id:$e,created_at:void 0,updated_at:void 0,user_id:void 0});const{data:Ye,error:Je}=await H.functions.invoke("program-enroll",{body:{action:"setup",enrollment_id:$e}});if(Je||Ye!=null&&Ye.error)throw new Error((Ye==null?void 0:Ye.error)||(Je==null?void 0:Je.message));if(Ye!=null&&Ye.free){await d(),ie.success("You're in"),t(`/programs/${i.slug}/workspace`);return}Ye!=null&&Ye.url&&(window.location.href=Ye.url)}catch($e){ie.error($e.message||"Could not start enrollment")}finally{b(!1)}}};if(l)return e.jsx(Qs,{children:e.jsxs("div",{className:"mx-auto max-w-2xl space-y-4 p-8",children:[e.jsx(xn,{className:"h-10 w-1/2"}),e.jsx(xn,{className:"h-64 w-full rounded-xl"})]})});if(!i)return e.jsx(Qs,{children:e.jsxs("div",{className:"mx-auto max-w-xl p-12 text-center",children:[e.jsx("h1",{className:"text-2xl font-bold",children:"Program not found"}),e.jsx(B,{asChild:!0,className:"mt-6",children:e.jsx(cr,{to:"/programs",children:"Back to Programs"})})]})});if(LY(c)&&Ne&&Me!=="success")return e.jsx(Qs,{children:e.jsxs("div",{className:"mx-auto max-w-xl space-y-4 p-12 text-center",children:[e.jsx(Hr,{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 ${vd(c==null?void 0:c.charge_scheduled_at)||"the program start date"}.`}),e.jsx(B,{asChild:!0,size:"lg",children:e.jsx(cr,{to:`/programs/${i.slug}/workspace`,children:"Open your program workspace"})})]})});const Ce=typeof o=="number"&&o<=0,{notOpenYet:Fe,closed:Ae,opensLabel:Xe}=v3e(i);return Fe||Ae?e.jsx(Qs,{children:e.jsxs("div",{className:"mx-auto w-full max-w-xl space-y-4 p-8 text-center",children:[e.jsx("h1",{className:"text-2xl font-bold",children:Fe?"Enrollment is not open yet":"Enrollment is closed"}),e.jsx("p",{className:"text-muted-foreground",children:Fe?`Enrollment for ${i.name} opens ${Xe}. 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(cr,{to:`/programs/${i.slug}`,children:"Back to program details"})})]})}):e.jsx(Qs,{children:e.jsxs("div",{className:"mx-auto w-full max-w-3xl space-y-6 p-4 md:p-8",children:[e.jsx(B,{asChild:!0,variant:"ghost",size:"sm",className:"-ml-2",children:e.jsxs(cr,{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?`${dOe(i.price_cents,i.currency,i.duration_weeks)}. Your card is saved today and charged once on ${vd(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:pse[y]}),e.jsxs("span",{children:["Step ",y+1," of ",pse.length]})]}),e.jsx(ro,{value:(y+1)/pse.length*100})]}),k&&e.jsx(_e,{className:"border-primary/40 bg-primary/5",children:e.jsxs(De,{className:"flex items-center gap-3 p-4 text-sm",children:[e.jsx(us,{className:"h-4 w-4 animate-spin text-primary"}),"Confirming your card with Stripe…"]})}),e.jsx(_e,{children:e.jsxs(De,{className:"space-y-5 p-6",children:[y===0&&ue.intro&&e.jsx("p",{className:"rounded-lg border border-border/60 bg-muted/30 p-4 text-sm text-muted-foreground",children:ue.intro}),y===0&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"grid gap-4 sm:grid-cols-2",children:[ce("full_name")&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs(re,{htmlFor:"full_name",children:["Full name",ae("full_name")]}),e.jsx(we,{id:"full_name",value:G.full_name||"",onChange:$e=>ne("full_name",$e.target.value)})]}),ce("phone")&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs(re,{htmlFor:"phone",children:["Mobile number",ae("phone")]}),e.jsx(we,{id:"phone",value:G.phone||"",onChange:$e=>ne("phone",$e.target.value)})]}),ce("instagram_handle")&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs(re,{htmlFor:"instagram_handle",children:["Instagram handle",ae("instagram_handle")]}),e.jsx(we,{id:"instagram_handle",placeholder:"@yourhandle",value:G.instagram_handle||"",onChange:$e=>ne("instagram_handle",$e.target.value)})]}),ce("city")&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs(re,{htmlFor:"city",children:["Primary city / market",ae("city")]}),e.jsx(we,{id:"city",value:G.city||"",onChange:$e=>ne("city",$e.target.value)})]})]}),ce("service_areas")&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs(re,{htmlFor:"service_areas",children:["Neighborhoods or areas you serve",ae("service_areas")]}),e.jsx(Ws,{id:"service_areas",rows:2,value:G.service_areas||"",onChange:$e=>ne("service_areas",$e.target.value)})]}),e.jsxs("div",{className:"grid gap-4 sm:grid-cols-2",children:[ce("years_experience")&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs(re,{children:["Years in real estate",ae("years_experience")]}),e.jsxs(Ns,{value:G.years_experience||"",onValueChange:$e=>ne("years_experience",$e),children:[e.jsx(ws,{children:e.jsx(ks,{placeholder:"Select"})}),e.jsx(js,{children:["Less than 1","1-3","4-7","8-15","15+"].map($e=>e.jsx(nt,{value:$e,children:$e},$e))})]})]}),ce("specialty")&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs(re,{htmlFor:"specialty",children:["Specialty or niche",ae("specialty")]}),e.jsx(we,{id:"specialty",value:G.specialty||"",onChange:$e=>ne("specialty",$e.target.value)})]})]}),ve(0)]}),y===1&&e.jsxs(e.Fragment,{children:[ce("target_audience")&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs(re,{htmlFor:"target_audience",children:["Who are you trying to reach?",ae("target_audience")]}),e.jsx(Ws,{id:"target_audience",rows:2,placeholder:"First-time buyers, move-up sellers, investors…",value:G.target_audience||"",onChange:$e=>ne("target_audience",$e.target.value)})]}),e.jsxs("div",{className:"grid gap-4 sm:grid-cols-2",children:[ce("video_comfort")&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs(re,{children:["How comfortable are you on camera?",ae("video_comfort")]}),e.jsxs(Ns,{value:G.video_comfort||"",onValueChange:$e=>ne("video_comfort",$e),children:[e.jsx(ws,{children:e.jsx(ks,{placeholder:"Select"})}),e.jsx(js,{children:["Terrified","Nervous but willing","Getting comfortable","Very comfortable"].map($e=>e.jsx(nt,{value:$e,children:$e},$e))})]})]}),ce("posting_frequency")&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs(re,{children:["How often do you post today?",ae("posting_frequency")]}),e.jsxs(Ns,{value:G.posting_frequency||"",onValueChange:$e=>ne("posting_frequency",$e),children:[e.jsx(ws,{children:e.jsx(ks,{placeholder:"Select"})}),e.jsx(js,{children:["Never","Rarely","Weekly","A few times a week","Daily"].map($e=>e.jsx(nt,{value:$e,children:$e},$e))})]})]})]}),ce("content_style")&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs(re,{htmlFor:"content_style",children:["What content style feels like you?",ae("content_style")]}),e.jsx(Ws,{id:"content_style",rows:2,placeholder:"Educational, funny, behind-the-scenes, luxury-polished…",value:G.content_style||"",onChange:$e=>ne("content_style",$e.target.value)})]}),ce("personal_interests")&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs(re,{htmlFor:"personal_interests",children:["Interests or hobbies we can weave in",ae("personal_interests")]}),e.jsx(Ws,{id:"personal_interests",rows:2,value:G.personal_interests||"",onChange:$e=>ne("personal_interests",$e.target.value)})]}),ve(1)]}),y===2&&e.jsxs(e.Fragment,{children:[ce("primary_goal")&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs(re,{htmlFor:"primary_goal",children:["Your #1 goal for this program",ae("primary_goal")]}),e.jsx(Ws,{id:"primary_goal",rows:3,value:G.primary_goal||"",onChange:$e=>ne("primary_goal",$e.target.value)})]}),ce("topics_to_avoid")&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs(re,{htmlFor:"topics_to_avoid",children:["Anything you don't want to talk about",ae("topics_to_avoid")]}),e.jsx(Ws,{id:"topics_to_avoid",rows:2,value:G.topics_to_avoid||"",onChange:$e=>ne("topics_to_avoid",$e.target.value)})]}),ce("timezone")&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs(re,{children:["Your time zone",ae("timezone")]}),e.jsxs(Ns,{value:G.timezone||i.timezone,onValueChange:$e=>ne("timezone",$e),children:[e.jsx(ws,{children:e.jsx(ks,{placeholder:"Select"})}),e.jsx(js,{children:["America/New_York","America/Chicago","America/Denver","America/Phoenix","America/Los_Angeles","Pacific/Honolulu"].map($e=>e.jsx(nt,{value:$e,children:$e.replace("America/","").replace("_"," ")},$e))})]})]}),ve(2),ce("consent_public_profile")&&e.jsxs("div",{className:"flex items-start gap-3 rounded-lg border border-border/60 p-4",children:[e.jsx(Bi,{id:"consent_public_profile",checked:!!G.consent_public_profile,onCheckedChange:$e=>ne("consent_public_profile",!!$e)}),e.jsx(re,{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":$?e.jsxs("span",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-sm font-normal text-muted-foreground line-through",children:_p($.original_cents,i.currency)}),_p(me,i.currency)]}):_p(i.price_cents,i.currency)})]}),i.payment_mode!=="free"&&e.jsx("p",{className:"mt-1 text-xs text-muted-foreground",children:dOe(me,i.currency,i.duration_weeks)}),i.payment_mode!=="free"&&e.jsx("div",{className:"mt-3 border-t border-border/60 pt-3",children:$?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(pf,{className:"h-3.5 w-3.5 text-primary"}),"Code ",e.jsx("span",{className:"font-mono font-semibold",children:$.code})," applied — you save ",_p($.discount_cents,i.currency)]}),e.jsxs(B,{variant:"ghost",size:"sm",onClick:Ie,disabled:g.isPending,children:[e.jsx(hr,{className:"mr-1 h-3.5 w-3.5"})," Remove"]})]}):e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{htmlFor:"discount_code",className:"text-xs text-muted-foreground",children:"Have a discount code?"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(we,{id:"discount_code",placeholder:"Enter code",className:"font-mono uppercase",value:L,onChange:$e=>z($e.target.value.toUpperCase()),onKeyDown:$e=>{$e.key==="Enter"&&($e.preventDefault(),Se())}}),e.jsx(B,{variant:"outline",onClick:Se,disabled:!L.trim()||f.isPending||m.isPending,children:f.isPending||m.isPending?e.jsx(us,{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(U0,{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:vd(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(Bi,{id:"terms",checked:T,onCheckedChange:$e=>P(!!$e)}),e.jsx(re,{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(Bi,{id:"charge",checked:I,onCheckedChange:$e=>M(!!$e)}),e.jsx(re,{htmlFor:"charge",className:"text-sm font-normal leading-relaxed",children:i.payment_mode==="delayed"?`I authorize LevelUp to charge my saved card one time — ${_p(me,i.currency)} for the ${PY(i.duration_weeks)} — on ${vd(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 — ${_p(me,i.currency)} for the ${PY(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(Wv,{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:()=>x($e=>Math.max(0,$e-1)),disabled:y===0||_,children:[e.jsx(ka,{className:"mr-1.5 h-4 w-4"})," Back"]}),yString(s).padStart(2,"0"),$Me=s=>s.toISOString().replace(/[-:]/g,"").split(".")[0]+"Z",QTs=({program:s,intakeComplete:t})=>{const n=s!=null&&s.kickoff_at?new Date(s.kickoff_at).getTime():null,[r,a]=N.useState(()=>Date.now());N.useEffect(()=>{const d=setInterval(()=>a(Date.now()),1e3);return()=>clearInterval(d)},[]);const i=N.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:${$Me(new Date)}`,`DTSTART:${$Me(d)}`,`DTEND:${$Me(u)}`,`SUMMARY:${s.name} — Kickoff Call`,`DESCRIPTION:The official kickoff for ${s.name}. Bring a phone and a story.`,"END:VEVENT","END:VCALENDAR"].join(`\r `),m=URL.createObjectURL(new Blob([h],{type:"text/calendar"})),f=document.createElement("a");f.href=m,f.download="program-kickoff.ics",f.click(),URL.revokeObjectURL(m)},c=[{label:"Days",value:i.days},{label:"Hours",value:BMe(i.hours)},{label:"Minutes",value:BMe(i.minutes)},{label:"Seconds",value:BMe(i.seconds)}];return e.jsxs(_e,{className:"relative overflow-hidden border-primary/25",children:[e.jsx("div",{className:"absolute inset-0 bg-gradient-to-br from-primary/15 via-background to-secondary/10"}),s.hero_image_url&&e.jsx("img",{src:s.hero_image_url,alt:"",className:"pointer-events-none absolute inset-0 h-full w-full object-cover opacity-10"}),e.jsxs(De,{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(We,{className:"gap-1.5",children:[e.jsx(Cn,{className:"h-3.5 w-3.5"})," Your seat is confirmed"]}),e.jsxs(We,{variant:"outline",className:"gap-1.5",children:[e.jsx(Xr,{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(Pv,{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(Hr,{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))})]})]})},UMe=s=>s.toISOString().replace(/[-:]/g,"").split(".")[0]+"Z",JTs=(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:${UMe(new Date)}`,`DTSTART:${UMe(n)}`,`DTEND:${UMe(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)},eEs={pdf:Wr,document:m5,checklist:zm,template_link:a3,video:Rh,external:cd},tEs=()=>{var xe;const{slug:s}=uo(),[t]=$c(),{isAdmin:n}=Ls(),r=n?t.get("as"):null,a=t.get("name")||"this member",i=n&&(t.get("preview")==="1"||!!r),{data:l,isLoading:o}=oVe(s),{data:c}=lVe(l==null?void 0:l.id),{data:d,isLoading:u}=cTs(l==null?void 0:l.id,r),h=dTs(l==null?void 0:l.id),m=uTs(l==null?void 0:l.id),f=hTs(l==null?void 0:l.id),g=mTs(l==null?void 0:l.id),{data:y}=wAt(l==null?void 0:l.id),x=!!(l!=null&&l.kickoff_at)&&new Date(l.kickoff_at).getTime()>Date.now(),[_,b]=N.useState(!1),[k,A]=N.useState({title:"",instagram_url:""}),[T,P]=N.useState({}),[I,M]=N.useState(null),L=N.useMemo(()=>{if(!(l!=null&&l.kickoff_at))return 1;const ve=Math.floor((Date.now()-new Date(l.kickoff_at).getTime())/864e5);return Math.min(Math.max(Math.floor(ve/7)+1,1),l.duration_weeks)},[l]),z=new Set(((d==null?void 0:d.completions)||[]).map(ve=>ve.lesson_id)),$=(d==null?void 0:d.lessons)||[],V=$.length?Math.round(z.size/$.length*100):0,W=((d==null?void 0:d.videoLogs)||[]).filter(ve=>ve.week_number===L).length,G=((d==null?void 0:d.videoLogs)||[]).length,X=(l==null?void 0:l.weekly_video_goal)||3,te=N.useMemo(()=>{const ve=new Map;((d==null?void 0:d.videoLogs)||[]).forEach(be=>ve.set(be.week_number,(ve.get(be.week_number)||0)+1));let ge=0;for(let be=L;be>=1;be--)if((ve.get(be)||0)>=X)ge++;else if(be!==L)break;return ge},[d==null?void 0:d.videoLogs,L,X]);if(o||u)return e.jsx(Qs,{children:e.jsxs("div",{className:"mx-auto max-w-6xl space-y-6 p-8",children:[e.jsx(xn,{className:"h-28 w-full rounded-xl"}),e.jsx(xn,{className:"h-64 w-full rounded-xl"})]})});if(!l)return e.jsx(Qs,{children:e.jsxs("div",{className:"mx-auto max-w-xl p-12 text-center",children:[e.jsx("h1",{className:"text-2xl font-bold",children:"Program not found"}),e.jsx(B,{asChild:!0,className:"mt-6",children:e.jsx(cr,{to:"/programs",children:"Back to Programs"})})]})});if(!LY(c)&&!i)return e.jsx(Qs,{children:e.jsxs("div",{className:"mx-auto max-w-xl space-y-4 p-12 text-center",children:[e.jsx("h1",{className:"text-2xl font-bold",children:"You're not enrolled yet"}),e.jsxs("p",{className:"text-muted-foreground",children:["Reserve your seat in ",l.name," to unlock the roadmap, lessons and mastermind sessions."]}),e.jsx(B,{asChild:!0,size:"lg",children:e.jsx(cr,{to:`/programs/${l.slug}`,children:"View the program"})})]})});const ne=((d==null?void 0:d.events)||[]).filter(ve=>new Date(ve.starts_at)>=new Date),me=((d==null?void 0:d.events)||[]).filter(ve=>new Date(ve.starts_at)ve.is_pinned),ae=[...(d==null?void 0:d.myResources)||[],...(d==null?void 0:d.resources)||[]].reduce((ve,ge)=>{const be=ge.user_id?`Just for you · ${ge.category}`:ge.category;return(ve[be]||(ve[be]=[])).push(ge),ve},{}),he=((d==null?void 0:d.progress)||[]).find(ve=>ve.week_number===L)||{};return e.jsx(Qs,{children:e.jsx("div",{className:"program-theme-neon relative min-h-screen",children:e.jsxs("div",{className:"relative mx-auto w-full max-w-6xl space-y-8 p-4 md:p-8",children:[i&&(r||!LY(c))&&e.jsx(_e,{className:"border-primary/40 bg-primary/5",children:e.jsxs(De,{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(cr,{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(We,{variant:"secondary",children:["Week ",L," of ",l.duration_weeks]}),(c==null?void 0:c.status)==="scheduled_for_charge"&&c.charge_scheduled_at&&e.jsxs(We,{variant:"outline",children:["Billing ",vd(c.charge_scheduled_at)]}),(c==null?void 0:c.status)==="payment_failed"&&e.jsx(We,{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})]}),x&&e.jsx(QTs,{program:l,intakeComplete:!!y}),e.jsxs("div",{className:"grid gap-4 sm:grid-cols-2 lg:grid-cols-4",children:[e.jsx(_e,{className:"neon-topline",children:e.jsxs(De,{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(iu,{className:"h-3.5 w-3.5 text-primary"})," This week"]}),e.jsxs("p",{className:"neon-stat text-3xl font-black",children:[W,e.jsxs("span",{className:"text-base font-normal text-muted-foreground",children:[" / ",X]})]}),e.jsx(ro,{value:Math.min(W/X*100,100),className:"h-1.5"})]})}),e.jsx(_e,{className:"neon-topline",children:e.jsxs(De,{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(Rh,{className:"h-3.5 w-3.5 text-primary"})," Videos posted"]}),e.jsx("p",{className:"neon-stat text-3xl font-black",children:G}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"since kickoff"})]})}),e.jsx(_e,{className:"neon-topline",children:e.jsxs(De,{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(Cu,{className:"h-3.5 w-3.5 text-primary"})," Streak"]}),e.jsxs("p",{className:"neon-stat text-3xl font-black",children:[te," wk"]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"hitting your goal"})]})}),e.jsx(_e,{className:"neon-topline",children:e.jsxs(De,{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(ml,{className:"h-3.5 w-3.5 text-primary"})," Curriculum"]}),e.jsxs("p",{className:"neon-stat text-3xl font-black",children:[V,"%"]}),e.jsx(ro,{value:V,className:"h-1.5"})]})})]}),e.jsxs("div",{className:"flex flex-wrap gap-3",children:[e.jsxs(Bs,{open:_,onOpenChange:b,children:[e.jsx(Ao,{asChild:!0,children:e.jsxs(B,{children:[e.jsx(nn,{className:"mr-1.5 h-4 w-4"})," Log a video"]})}),e.jsxs(Fs,{children:[e.jsx(qs,{children:e.jsx($s,{children:"Log a posted video"})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{htmlFor:"v-title",children:"What was it about?"}),e.jsx(we,{id:"v-title",value:k.title,onChange:ve=>A(ge=>({...ge,title:ve.target.value}))})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{htmlFor:"v-url",children:"Instagram link (optional)"}),e.jsx(we,{id:"v-url",placeholder:"https://instagram.com/reel/…",value:k.instagram_url,onChange:ve=>A(ge=>({...ge,instagram_url:ve.target.value}))})]})]}),e.jsx(Cr,{children:e.jsx(B,{onClick:async()=>{await m.mutateAsync({week_number:L,...k}),A({title:"",instagram_url:""}),b(!1)},children:"Log video"})})]})]}),((xe=ne[0])==null?void 0:xe.meeting_link)&&e.jsx(B,{variant:"outline",asChild:!0,children:e.jsxs("a",{href:ne[0].meeting_link,target:"_blank",rel:"noreferrer",children:[e.jsx(wp,{className:"mr-1.5 h-4 w-4"})," Join next session"]})})]}),ue.length>0&&e.jsx(_e,{className:"border-primary/30 bg-primary/5",children:e.jsx(De,{className:"space-y-3 p-5",children:ue.map(ve=>e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx(um,{className:"mt-0.5 h-4 w-4 shrink-0 text-primary"}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:ve.title}),ve.body&&e.jsx("p",{className:"text-sm text-muted-foreground",children:ve.body})]})]},ve.id))})}),e.jsxs(ya,{defaultValue:"roadmap",children:[e.jsxs(va,{className:"flex w-full flex-wrap justify-start",children:[e.jsx(ls,{value:"roadmap",children:"Roadmap"}),e.jsx(ls,{value:"lessons",children:"Lessons"}),e.jsx(ls,{value:"checkin",children:"Weekly check-in"}),e.jsx(ls,{value:"events",children:"Sessions"}),e.jsx(ls,{value:"resources",children:"Resources"}),e.jsx(ls,{value:"profile",children:"Profile review"})]}),e.jsxs(_s,{value:"roadmap",className:"mt-6 space-y-4",children:[((d==null?void 0:d.weeks)||[]).length===0&&e.jsx("p",{className:"text-sm text-muted-foreground",children:"The roadmap will appear here before kickoff."}),((d==null?void 0:d.weeks)||[]).map(ve=>{const ge=ve.release_at&&new Date(ve.release_at)>new Date;return e.jsx(_e,{className:ge?"opacity-60":ve.week_number===L?"border-primary/50":"",children:e.jsxs(De,{className:"space-y-2 p-5",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsxs(We,{variant:"outline",children:["Week ",ve.week_number]}),e.jsx("span",{className:"text-xs uppercase tracking-wide text-muted-foreground",children:ve.phase}),ve.week_number===L&&e.jsx(We,{children:"Current"}),ge&&e.jsxs("span",{className:"inline-flex items-center gap-1 text-xs text-muted-foreground",children:[e.jsx(Xr,{className:"h-3 w-3"})," Unlocks ",vd(ve.release_at)]})]}),e.jsx("h3",{className:"font-semibold",children:ve.title}),ve.learning_goal&&e.jsx("p",{className:"text-sm text-muted-foreground",children:ve.learning_goal}),!ge&&Array.isArray(ve.tasks)&&ve.tasks.length>0&&e.jsx("ul",{className:"mt-2 space-y-1.5",children:ve.tasks.map((be,Se)=>e.jsxs("li",{className:"flex items-start gap-2 text-sm",children:[e.jsx(Hr,{className:"mt-0.5 h-3.5 w-3.5 shrink-0 text-primary"}),typeof be=="string"?be:be.label]},Se))})]})},ve.id)})]}),e.jsxs(_s,{value:"lessons",className:"mt-6 space-y-3",children:[$.length===0&&e.jsx("p",{className:"text-sm text-muted-foreground",children:"Lessons unlock as the program progresses."}),$.map(ve=>{const ge=jAt(ve.video_url),be=I===ve.id;return e.jsx(_e,{children:e.jsxs(De,{className:"space-y-4 p-5",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-4",children:[e.jsx(Bi,{checked:z.has(ve.id),onCheckedChange:Se=>h.mutate({lessonId:ve.id,done:!!Se}),"aria-label":`Mark ${ve.title} complete`}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("p",{className:"font-medium",children:ve.title}),ve.summary&&e.jsx("p",{className:"text-sm text-muted-foreground",children:ve.summary}),ve.action_assignment&&e.jsxs("p",{className:"mt-1 text-xs text-primary",children:["Action: ",ve.action_assignment]})]}),ve.duration_minutes&&e.jsxs("span",{className:"inline-flex items-center gap-1 text-xs text-muted-foreground",children:[e.jsx(Xr,{className:"h-3 w-3"})," ",ve.duration_minutes," min"]}),e.jsxs("div",{className:"flex gap-2",children:[ve.video_url&&ge&&e.jsxs(B,{size:"sm",variant:"outline",onClick:()=>M(be?null:ve.id),children:[e.jsx(wp,{className:"mr-1.5 h-3.5 w-3.5"})," ",be?"Close":"Watch"]}),ve.video_url&&!ge&&e.jsx(B,{size:"sm",variant:"outline",asChild:!0,children:e.jsxs("a",{href:ve.video_url,target:"_blank",rel:"noreferrer",children:[e.jsx(wp,{className:"mr-1.5 h-3.5 w-3.5"})," Watch"]})}),ve.worksheet_url&&e.jsx(B,{size:"sm",variant:"ghost",asChild:!0,children:e.jsxs("a",{href:ve.worksheet_url,target:"_blank",rel:"noreferrer",children:[e.jsx(oi,{className:"mr-1.5 h-3.5 w-3.5"})," Worksheet"]})})]})]}),be&&ge&&e.jsx("div",{className:"overflow-hidden rounded-lg border border-border/60",children:e.jsx("iframe",{src:ge,title:ve.title,className:"aspect-video w-full",allow:"accelerometer; autoplay; clipboard-write; encrypted-media; picture-in-picture",allowFullScreen:!0})})]})},ve.id)})]}),e.jsx(_s,{value:"checkin",className:"mt-6",children:e.jsx(_e,{children:e.jsxs(De,{className:"space-y-5 p-6",children:[e.jsxs("div",{children:[e.jsxs("h3",{className:"font-semibold",children:["Week ",L," check-in"]}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Two minutes of honesty here is what makes the next week better."})]}),e.jsx("div",{className:"grid gap-4 sm:grid-cols-3",children:[["videos_planned","Videos planned"],["videos_recorded","Videos recorded"],["videos_posted","Videos posted"]].map(([ve,ge])=>e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{htmlFor:ve,children:ge}),e.jsx(we,{id:ve,type:"number",min:0,defaultValue:he[ve]??"",onChange:be=>P(Se=>({...Se,[ve]:Number(be.target.value)}))})]},ve))}),[["biggest_win","Biggest win"],["biggest_challenge","Biggest challenge"],["what_to_improve","What you’ll change next week"]].map(([ve,ge])=>e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{htmlFor:ve,children:ge}),e.jsx(Ws,{id:ve,rows:2,defaultValue:he[ve]??"",onChange:be=>P(Se=>({...Se,[ve]:be.target.value}))})]},ve)),e.jsx(B,{onClick:()=>f.mutate({week_number:L,goal_videos:X,...T}),children:"Save check-in"})]})})}),e.jsxs(_s,{value:"events",className:"mt-6 space-y-4",children:[ne.length===0&&me.length===0&&e.jsx("p",{className:"text-sm text-muted-foreground",children:"Sessions will be scheduled before kickoff."}),ne.map(ve=>e.jsx(_e,{className:"border-primary/30",children:e.jsxs(De,{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(We,{variant:"secondary",className:"capitalize",children:String(ve.event_kind).replace("_"," ")}),e.jsxs("span",{className:"inline-flex items-center gap-1 text-xs text-muted-foreground",children:[e.jsx(ld,{className:"h-3 w-3"})," ",vd(ve.starts_at,!0)]})]}),e.jsx("p",{className:"mt-1.5 font-medium",children:ve.title}),ve.speaker&&e.jsxs("p",{className:"text-sm text-muted-foreground",children:["with ",ve.speaker]}),ve.description&&e.jsx("p",{className:"mt-1 text-sm text-muted-foreground",children:ve.description})]}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsx(B,{size:"sm",variant:"outline",onClick:()=>g.mutate({eventId:ve.id,optIn:!0}),children:"Remind me"}),e.jsxs(B,{size:"sm",variant:"ghost",onClick:()=>JTs(ve,l.name),children:[e.jsx(ld,{className:"mr-1.5 h-3.5 w-3.5"})," Add to calendar"]}),ve.meeting_link&&e.jsx(B,{size:"sm",asChild:!0,children:e.jsxs("a",{href:ve.meeting_link,target:"_blank",rel:"noreferrer",children:["Join ",e.jsx(Tr,{className:"ml-1.5 h-3.5 w-3.5"})]})})]})]})},ve.id)),me.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"}),me.map(ve=>e.jsx(_e,{children:e.jsxs(De,{className:"flex flex-wrap items-center gap-4 p-5",children:[e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("p",{className:"font-medium",children:ve.title}),e.jsx("p",{className:"text-xs text-muted-foreground",children:vd(ve.starts_at,!0)})]}),ve.replay_url?e.jsx(B,{size:"sm",variant:"outline",asChild:!0,children:e.jsxs("a",{href:ve.replay_url,target:"_blank",rel:"noreferrer",children:[e.jsx(wp,{className:"mr-1.5 h-3.5 w-3.5"})," Watch replay"]})}):e.jsx("span",{className:"text-xs text-muted-foreground",children:"Replay coming soon"})]})},ve.id))]})]}),e.jsxs(_s,{value:"resources",className:"mt-6 space-y-8",children:[Object.keys(ae).length===0&&e.jsx(_e,{className:"border-dashed",children:e.jsxs(De,{className:"flex flex-col items-center gap-2 p-12 text-center",children:[e.jsx(Wr,{className:"h-8 w-8 text-muted-foreground"}),e.jsx("p",{className:"font-medium",children:"Your resource library is being built"}),e.jsx("p",{className:"max-w-md text-sm text-muted-foreground",children:"Worksheets, scripts and swipe files will appear here as the program unlocks."})]})}),Object.entries(ae).map(([ve,ge])=>e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("h3",{className:"text-sm font-semibold uppercase tracking-[0.18em] text-muted-foreground",children:ve}),e.jsx("span",{className:"h-px flex-1 bg-border"}),e.jsxs("span",{className:"text-xs text-muted-foreground",children:[ge.length," item",ge.length===1?"":"s"]})]}),e.jsx("div",{className:"grid gap-4 md:grid-cols-2 xl:grid-cols-3",children:ge.map(be=>{const Se=b3e(be),Ie=eEs[be.resource_kind]||Wr;return e.jsxs("div",{role:"button",tabIndex:0,onClick:()=>Se&&oK(be),onKeyDown:Me=>{Se&&(Me.key==="Enter"||Me.key===" ")&&(Me.preventDefault(),oK(be))},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(Ie,{className:"h-5 w-5"})}),e.jsx(We,{variant:"secondary",className:"capitalize",children:String(be.resource_kind).replace("_"," ")})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx("p",{className:"font-semibold leading-snug",children:be.title}),be.description&&e.jsx("p",{className:"line-clamp-3 text-sm text-muted-foreground",children:be.description})]}),e.jsxs("div",{className:"mt-auto flex items-center gap-4",children:[e.jsxs("span",{className:"inline-flex items-center gap-1.5 text-sm font-medium text-primary",children:[e.jsx(Tr,{className:"h-3.5 w-3.5"})," Open"]}),be.file_path&&e.jsxs("button",{type:"button",onClick:Me=>{Me.stopPropagation(),oK(be,"download")},className:"inline-flex items-center gap-1.5 text-sm font-medium text-muted-foreground hover:text-primary",children:[e.jsx(oi,{className:"h-3.5 w-3.5"})," Download"]})]})]},be.id)})})]},ve))]}),e.jsx(_s,{value:"profile",className:"mt-6",children:e.jsx(_e,{children:e.jsxs(De,{className:"space-y-4 p-6",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(dm,{className:"h-5 w-5 text-primary"}),e.jsx("h3",{className:"font-semibold",children:"Your profile review"})]}),!(d!=null&&d.analysis)||d.analysis.status==="not_submitted"?e.jsx("p",{className:"text-sm text-muted-foreground",children:"Your Instagram review hasn't been submitted yet. Your coach will request screenshots during onboarding week."}):d.analysis.status==="in_review"?e.jsx("p",{className:"text-sm text-muted-foreground",children:"Your profile is in review — you'll get a notification when the report is ready."}):e.jsxs("div",{className:"space-y-4",children:[d.analysis.scores&&Object.keys(d.analysis.scores).length>0&&e.jsx("div",{className:"grid gap-3 sm:grid-cols-2",children:Object.entries(d.analysis.scores).map(([ve,ge])=>e.jsxs("div",{className:"space-y-1 rounded-lg border border-border/60 p-3",children:[e.jsxs("div",{className:"flex justify-between text-sm",children:[e.jsx("span",{className:"capitalize",children:ve.replace(/_/g," ")}),e.jsxs("span",{className:"font-semibold",children:[ge,"/10"]})]}),e.jsx(ro,{value:Number(ge)*10,className:"h-1.5"})]},ve))}),Array.isArray(d.analysis.top_priorities)&&d.analysis.top_priorities.length>0&&e.jsxs("div",{className:"space-y-2",children:[e.jsx("p",{className:"text-sm font-semibold",children:"Top priorities"}),e.jsx("ul",{className:"space-y-1.5",children:d.analysis.top_priorities.map((ve,ge)=>e.jsxs("li",{className:"flex items-start gap-2 text-sm",children:[e.jsx(ku,{className:"mt-0.5 h-3.5 w-3.5 shrink-0 text-primary"}),typeof ve=="string"?ve:ve.label]},ge))})]}),d.analysis.member_notes&&e.jsx("div",{className:"rounded-lg border border-border/60 bg-muted/30 p-4 text-sm leading-relaxed whitespace-pre-line",children:d.analysis.member_notes}),d.analysis.report_url&&e.jsx(B,{variant:"outline",asChild:!0,children:e.jsxs("a",{href:d.analysis.report_url,target:"_blank",rel:"noreferrer",children:[e.jsx(oi,{className:"mr-1.5 h-4 w-4"})," Download full report"]})})]})]})})})]})]})})})},Oa=N.forwardRef(({className:s,...t},n)=>e.jsx("div",{className:"relative w-full overflow-auto",children:e.jsx("table",{ref:n,className:Ot("w-full caption-bottom text-sm",s),...t})}));Oa.displayName="Table";const Fa=N.forwardRef(({className:s,...t},n)=>e.jsx("thead",{ref:n,className:Ot("[&_tr]:border-b",s),...t}));Fa.displayName="TableHeader";const za=N.forwardRef(({className:s,...t},n)=>e.jsx("tbody",{ref:n,className:Ot("[&_tr:last-child]:border-0",s),...t}));za.displayName="TableBody";const sEs=N.forwardRef(({className:s,...t},n)=>e.jsx("tfoot",{ref:n,className:Ot("border-t bg-muted/50 font-medium [&>tr]:last:border-b-0",s),...t}));sEs.displayName="TableFooter";const un=N.forwardRef(({className:s,...t},n)=>e.jsx("tr",{ref:n,className:Ot("border-b transition-colors data-[state=selected]:bg-muted hover:bg-muted/50",s),...t}));un.displayName="TableRow";const Mt=N.forwardRef(({className:s,...t},n)=>e.jsx("th",{ref:n,className:Ot("h-12 px-4 text-left align-middle font-medium text-muted-foreground [&:has([role=checkbox])]:pr-0",s),...t}));Mt.displayName="TableHead";const gt=N.forwardRef(({className:s,...t},n)=>e.jsx("td",{ref:n,className:Ot("p-4 align-middle [&:has([role=checkbox])]:pr-0",s),...t}));gt.displayName="TableCell";const nEs=N.forwardRef(({className:s,...t},n)=>e.jsx("caption",{ref:n,className:Ot("mt-4 text-sm text-muted-foreground",s),...t}));nEs.displayName="TableCaption";const fse=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())}`},gse=s=>s?new Date(s).toISOString():null,qMe=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:fse(s.enrollment_open_at),enrollment_close_at:fse(s.enrollment_close_at),kickoff_at:fse(s.kickoff_at),charge_at:fse(s.charge_at),status:s.status||"draft",is_public:!!s.is_public,is_featured:!!s.is_featured,sort_order:s.sort_order??0}),rEs=({program:s,onSaved:t})=>{const[n,r]=N.useState(()=>qMe(s)),[a,i]=N.useState(!1),[l,o]=N.useState(!1),[c,d]=N.useState(null),u=N.useRef(null),h=N.useRef(null);N.useEffect(()=>{r(qMe(s)),i(!1)},[s.id,s.updated_at]);const m=(x,_)=>{r(b=>({...b,[x]:_})),i(!0)},f=async(x,_)=>{if(!x.type.startsWith("image/")){ie.error("Please choose an image file");return}if(x.size>8*1024*1024){ie.error("Image must be under 8MB");return}d(_);try{const b=x.name.split(".").pop()||"jpg",k=`programs/${s.id}/${_}-${Date.now()}.${b}`,{error:A}=await H.storage.from("event-images").upload(k,x,{cacheControl:"31536000",upsert:!0});if(A)throw A;const{data:T}=H.storage.from("event-images").getPublicUrl(k);m(_==="cover"?"cover_image_url":"hero_image_url",T.publicUrl),ie.success(`${_==="cover"?"Cover":"Hero"} image uploaded — remember to save`)}catch(b){ie.error(b.message||"Upload failed")}finally{d(null)}},g=async()=>{if(!n.name.trim())return ie.error("Program name is required");if(!n.slug.trim())return ie.error("Slug is required");o(!0);try{const x={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:gse(n.enrollment_open_at),enrollment_close_at:gse(n.enrollment_close_at),kickoff_at:gse(n.kickoff_at),charge_at:gse(n.charge_at),status:n.status,is_public:n.is_public,is_featured:n.is_featured,sort_order:Math.round(n.sort_order)},{error:_}=await H.from("programs").update(x).eq("id",s.id);if(_)throw _;ie.success("Program saved"),i(!1),t()}catch(x){ie.error(x.message||"Could not save the program")}finally{o(!1)}},y=({kind:x,label:_,hint:b})=>{const k=x==="cover"?n.cover_image_url:n.hero_image_url,A=x==="cover"?u:h;return e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{children:_}),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:k?e.jsxs(e.Fragment,{children:[e.jsx("img",{src:k,alt:`${_} preview`,className:"h-full w-full object-cover"}),e.jsx("button",{type:"button",onClick:()=>m(x==="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 ${_}`,children:e.jsx(hr,{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(Gv,{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:A,type:"file",accept:"image/*",className:"hidden",onChange:T=>{var I;const P=(I=T.target.files)==null?void 0:I[0];P&&f(P,x),T.target.value=""}}),e.jsxs(B,{type:"button",variant:"outline",size:"sm",onClick:()=>{var T;return(T=A.current)==null?void 0:T.click()},disabled:c===x,children:[c===x?e.jsx(us,{className:"mr-1.5 h-4 w-4 animate-spin"}):e.jsx(ni,{className:"mr-1.5 h-4 w-4"}),"Upload image"]}),e.jsx(we,{placeholder:"…or paste an image URL",value:k,onChange:T=>m(x==="cover"?"cover_image_url":"hero_image_url",T.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(qMe(s)),i(!1)},children:"Discard"}),e.jsxs(B,{onClick:g,disabled:l||!a,children:[l?e.jsx(us,{className:"mr-1.5 h-4 w-4 animate-spin"}):e.jsx(Kl,{className:"mr-1.5 h-4 w-4"}),"Save changes"]})]})]}),e.jsx(_e,{children:e.jsxs(De,{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(re,{children:"Program name"}),e.jsx(we,{value:n.name,onChange:x=>m("name",x.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{children:"Slug (public URL)"}),e.jsx(we,{value:n.slug,onChange:x=>m("slug",x.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(re,{children:"Subtitle"}),e.jsx(we,{value:n.subtitle,onChange:x=>m("subtitle",x.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{children:"Tagline"}),e.jsx(we,{value:n.tagline,onChange:x=>m("tagline",x.target.value)})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{children:"Short description (cards & previews)"}),e.jsx(Ws,{rows:2,value:n.short_description,onChange:x=>m("short_description",x.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{children:"Full program description (sales page)"}),e.jsx(Ws,{rows:8,value:n.description,onChange:x=>m("description",x.target.value)})]})]})}),e.jsx(_e,{children:e.jsxs(De,{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(re,{children:"Promo video URL (optional)"}),e.jsx(we,{placeholder:"https://youtu.be/… , Vimeo, or a direct .mp4 link",value:n.promo_video_url,onChange:x=>m("promo_video_url",x.target.value)}),e.jsx(we,{placeholder:"Video headline (e.g. Watch: what 90 days inside Reel Estate looks like)",value:n.promo_video_headline,onChange:x=>m("promo_video_headline",x.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(re,{children:"Accent color"}),e.jsx(we,{placeholder:"#406E71",value:n.accent_color,onChange:x=>m("accent_color",x.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{children:"Sort order"}),e.jsx(we,{type:"number",value:n.sort_order,onChange:x=>m("sort_order",Number(x.target.value))})]})]})]})}),e.jsx(_e,{children:e.jsxs(De,{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(re,{children:"One-time price (USD)"}),e.jsx(we,{type:"number",min:0,step:"1",value:n.price_cents/100,onChange:x=>m("price_cents",Math.round(Number(x.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(re,{children:"Seats (capacity)"}),e.jsx(we,{type:"number",min:0,value:n.capacity,onChange:x=>m("capacity",Number(x.target.value))})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{children:"Billing mode"}),e.jsxs(Ns,{value:n.payment_mode,onValueChange:x=>m("payment_mode",x),children:[e.jsx(ws,{children:e.jsx(ks,{})}),e.jsxs(js,{children:[e.jsx(nt,{value:"delayed",children:"Save card, charge once later"}),e.jsx(nt,{value:"immediate",children:"Charge once at checkout"}),e.jsx(nt,{value:"free",children:"Free / included"})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{children:"Charge date (one-time)"}),e.jsx(we,{type:"datetime-local",value:n.charge_at,onChange:x=>m("charge_at",x.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{children:"Payment grace days"}),e.jsx(we,{type:"number",min:0,value:n.payment_grace_days,onChange:x=>m("payment_grace_days",Number(x.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(re,{children:"Currency"}),e.jsx(we,{value:n.currency,onChange:x=>m("currency",x.target.value)})]})]})]})}),e.jsx(_e,{children:e.jsxs(De,{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(re,{children:"Enrollment opens"}),e.jsx(we,{type:"datetime-local",value:n.enrollment_open_at,onChange:x=>m("enrollment_open_at",x.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{children:"Enrollment closes"}),e.jsx(we,{type:"datetime-local",value:n.enrollment_close_at,onChange:x=>m("enrollment_close_at",x.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{children:"Kickoff"}),e.jsx(we,{type:"datetime-local",value:n.kickoff_at,onChange:x=>m("kickoff_at",x.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{children:"Length (weeks)"}),e.jsx(we,{type:"number",min:1,value:n.duration_weeks,onChange:x=>m("duration_weeks",Number(x.target.value))})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{children:"Videos per week goal"}),e.jsx(we,{type:"number",min:0,value:n.weekly_video_goal,onChange:x=>m("weekly_video_goal",Number(x.target.value))})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{children:"Timezone"}),e.jsx(we,{value:n.timezone,onChange:x=>m("timezone",x.target.value)})]})]})]})}),e.jsx(_e,{children:e.jsxs(De,{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(re,{children:"Status"}),e.jsxs(Ns,{value:n.status,onValueChange:x=>m("status",x),children:[e.jsx(ws,{className:"sm:max-w-xs",children:e.jsx(ks,{})}),e.jsxs(js,{children:[e.jsx(nt,{value:"draft",children:"Draft (hidden)"}),e.jsx(nt,{value:"published",children:"Published (members can enroll)"}),e.jsx(nt,{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(zn,{checked:n.is_featured,onCheckedChange:x=>m("is_featured",x)})]}),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(zn,{checked:n.is_public,onCheckedChange:x=>m("is_public",x)})]})]})}),e.jsx("div",{className:"flex justify-end pb-4",children:e.jsxs(B,{onClick:g,disabled:l||!a,size:"lg",children:[l?e.jsx(us,{className:"mr-1.5 h-4 w-4 animate-spin"}):e.jsx(Kl,{className:"mr-1.5 h-4 w-4"}),"Save changes"]})})]})},hit={title:"",description:"",category:"Personal",resource_kind:"pdf",url:"",file_path:"",status:"published",sort_order:0},aEs=({programId:s,userId:t,memberName:n})=>{const{data:r=[],isLoading:a}=ATs(s,t),i=TTs(s,t),l=ETs(),[o,c]=N.useState(!1),[d,u]=N.useState({...hit}),[h,m]=N.useState(!1),f=N.useRef(null),g=()=>{u({...hit,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)},x=async b=>{if(!(!b||!s||!t)){if(b.size>50*1024*1024)return ie.error("File must be under 50MB");m(!0);try{const k=b.name.split(".").pop()||"pdf",A=`programs/${s}/members/${t}/${Date.now()}-${Math.random().toString(36).slice(2,8)}.${k}`,{error:T}=await H.storage.from(vU).upload(A,b,{contentType:b.type||"application/pdf",upsert:!1});if(T)throw T;u(P=>({...P,file_path:A,url:"",title:P.title||b.name.replace(/\.[^.]+$/,""),resource_kind:b.type==="application/pdf"?"pdf":P.resource_kind})),ie.success("File uploaded")}catch(k){ie.error(k.message||"Upload failed")}finally{m(!1),f.current&&(f.current.value="")}}},_=async()=>{if(!d.title.trim())return ie.error("Give the resource a title");if(!d.file_path&&!d.url.trim())return ie.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(Au,{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:g,disabled:!t,children:[e.jsx(nn,{className:"mr-1.5 h-4 w-4"})," Add for this member"]})]}),a?e.jsx("p",{className:"text-sm text-muted-foreground",children:"Loading…"}):r.length===0?e.jsx(_e,{className:"border-dashed",children:e.jsx(De,{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(_e,{className:"border-border/60",children:e.jsxs(De,{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(We,{variant:"secondary",children:b.category}),e.jsx(We,{variant:"outline",className:"capitalize",children:b.resource_kind.replace("_"," ")}),b.status!=="published"&&e.jsx(We,{variant:"outline",className:"capitalize",children:b.status})]}),b.description&&e.jsx("p",{className:"max-w-xl text-sm text-muted-foreground",children:b.description}),b3e(b)&&e.jsxs("button",{type:"button",onClick:()=>oK(b),className:"inline-flex items-center gap-1 text-xs text-primary hover:underline",children:[e.jsx(Tr,{className:"h-3 w-3"})," Open"]})]}),e.jsxs("div",{className:"flex gap-1",children:[e.jsx(B,{variant:"ghost",size:"icon",onClick:()=>y(b),children:e.jsx(Ja,{className:"h-4 w-4"})}),e.jsx(B,{variant:"ghost",size:"icon",onClick:()=>{confirm(`Remove "${b.title}"?`)&&l.mutate(b)},children:e.jsx(qn,{className:"h-4 w-4 text-destructive"})})]})]})},b.id))}),e.jsx(Bs,{open:o,onOpenChange:c,children:e.jsxs(Fs,{className:"max-w-lg",children:[e.jsx(qs,{children:e.jsx($s,{children:d.id?"Edit personal resource":"New personal resource"})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(re,{children:"Title"}),e.jsx(we,{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(re,{children:"Description"}),e.jsx(Ws,{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(re,{children:"Category"}),e.jsx(we,{value:d.category,onChange:b=>u({...d,category:b.target.value}),placeholder:"Personal"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(re,{children:"Type"}),e.jsxs(Ns,{value:d.resource_kind,onValueChange:b=>u({...d,resource_kind:b}),children:[e.jsx(ws,{children:e.jsx(ks,{})}),e.jsx(js,{children:NAt.map(b=>e.jsx(nt,{value:b.value,children:b.label},b.value))})]})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(re,{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=f.current)==null?void 0:b.click()},children:[h?e.jsx(us,{className:"mr-1.5 h-4 w-4 animate-spin"}):e.jsx(ni,{className:"mr-1.5 h-4 w-4"}),d.file_path?"Replace file":"Upload file"]}),d.file_path&&e.jsx("span",{className:"truncate text-xs text-muted-foreground",children:d.file_path.split("/").pop()})]}),e.jsx("input",{ref:f,type:"file",hidden:!0,onChange:b=>{var k;return x((k=b.target.files)==null?void 0:k[0])}})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(re,{children:"…or link"}),e.jsx(we,{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(re,{children:"Status"}),e.jsxs(Ns,{value:d.status,onValueChange:b=>u({...d,status:b}),children:[e.jsx(ws,{children:e.jsx(ks,{})}),e.jsxs(js,{children:[e.jsx(nt,{value:"published",children:"Published"}),e.jsx(nt,{value:"draft",children:"Draft"}),e.jsx(nt,{value:"archived",children:"Archived"})]})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(re,{children:"Sort order"}),e.jsx(we,{type:"number",value:d.sort_order,onChange:b=>u({...d,sort_order:b.target.value})})]})]})]}),e.jsxs(Cr,{children:[e.jsx(B,{variant:"ghost",onClick:()=>c(!1),children:"Cancel"}),e.jsxs(B,{onClick:_,disabled:i.isPending||h,children:[i.isPending&&e.jsx(us,{className:"mr-1.5 h-4 w-4 animate-spin"})," Save"]})]})]})})]})},iEs=({program:s,enrollment:t,open:n,onOpenChange:r,onUpdated:a})=>{var X,te,ne,me,ue,ce,ae,he,xe,ve;const i=t==null?void 0:t.user_id,[l,o]=N.useState((t==null?void 0:t.admin_notes)||""),[c,d]=N.useState(!1),[u,h]=N.useState(""),[m,f]=N.useState(!1),[g,y]=N.useState(!1),x=N.useRef(null),{data:_,isLoading:b,refetch:k}=mt({queryKey:["admin-program-agent",s.id,i],enabled:n&&!!i,queryFn:async()=>{const[ge,be,Se,Ie,Me,Re,Be,Ne]=await Promise.all([H.from("program_weekly_progress").select("*").eq("program_id",s.id).eq("user_id",i).order("week_number"),H.from("program_video_logs").select("*").eq("program_id",s.id).eq("user_id",i).order("posted_at",{ascending:!1}),H.from("program_lesson_completions").select("*").eq("program_id",s.id).eq("user_id",i),H.from("program_badge_awards").select("*").eq("program_id",s.id).eq("user_id",i),H.from("program_intake_responses").select("*").eq("program_id",s.id).eq("user_id",i).maybeSingle(),H.from("program_event_attendance").select("*").eq("program_id",s.id).eq("user_id",i),H.from("program_lessons").select("id").eq("program_id",s.id),H.from("program_profile_analyses").select("*").eq("program_id",s.id).eq("user_id",i).maybeSingle()]);return{weekly:ge.data||[],videos:be.data||[],completions:Se.data||[],badges:Ie.data||[],intake:Me.data,attendance:Re.data||[],lessonCount:(Be.data||[]).length,analysis:Ne.data}}});N.useEffect(()=>{var ge;h(((ge=_==null?void 0:_.analysis)==null?void 0:ge.member_notes)||"")},[(X=_==null?void 0:_.analysis)==null?void 0:X.id]);const A=N.useMemo(()=>{var Se;const ge=IY(s),be=((Se=_==null?void 0:_.intake)==null?void 0:Se.extra)||{};return ge.custom.map(Ie=>({label:Ie.label,value:typeof be[Ie.id]=="boolean"?be[Ie.id]?"Yes":"No":be[Ie.id]||""})).filter(Ie=>!!Ie.value)},[s,_==null?void 0:_.intake]),T=async ge=>i?H.from("program_profile_analyses").upsert({program_id:s.id,user_id:i,enrollment_id:(t==null?void 0:t.id)||null,...ge},{onConflict:"program_id,user_id"}):{error:{message:"Missing agent"}},P=async ge=>{if(ge.type!=="application/pdf")return ie.error("Please choose a PDF file");if(ge.size>25*1024*1024)return ie.error("PDF must be under 25MB");y(!0);try{const be=`programs/${s.id}/reviews/${i}-${Date.now()}.pdf`,{error:Se}=await H.storage.from("event-images").upload(be,ge,{contentType:"application/pdf",upsert:!0});if(Se)throw Se;const{data:Ie}=H.storage.from("event-images").getPublicUrl(be),{error:Me}=await T({report_url:Ie.publicUrl,status:"ready",reviewed_at:new Date().toISOString()});if(Me)throw Me;ie.success("Profile review uploaded"),await k()}catch(be){ie.error(be.message||"Upload failed")}finally{y(!1)}},I=async()=>{const{error:ge}=await T({report_url:null,status:"in_review"});if(ge)return ie.error(ge.message);ie.success("Review removed"),await k()},M=async()=>{f(!0);const{error:ge}=await T({member_notes:u});if(f(!1),ge)return ie.error(ge.message);ie.success("Review notes saved"),await k()},L=async()=>{if(!t)return;d(!0);const{error:ge}=await H.from("program_enrollments").update({admin_notes:l}).eq("id",t.id);if(d(!1),ge)return ie.error(ge.message);ie.success("Notes saved"),a()},z=((_==null?void 0:_.videos)||[]).filter(ge=>ge.posted).length,$=(s.weekly_video_goal||0)*(s.duration_weeks||0),V=_!=null&&_.lessonCount?Math.round(((_==null?void 0:_.completions.length)||0)/_.lessonCount*100):0,W=$?Math.min(100,Math.round(z/$*100)):0,G=((_==null?void 0:_.attendance)||[]).filter(ge=>ge.attended).length;return e.jsx(l1,{open:n,onOpenChange:r,children:e.jsxs(Gy,{className:"w-full overflow-y-auto sm:max-w-2xl",children:[e.jsxs(gb,{className:"mb-4",children:[e.jsxs(xb,{children:[((te=t==null?void 0:t.profile)==null?void 0:te.name)||"Agent"," · ",s.name]}),e.jsx("p",{className:"text-sm text-muted-foreground",children:(ne=t==null?void 0:t.profile)==null?void 0:ne.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(((me=t==null?void 0:t.profile)==null?void 0:me.name)||((ue=t==null?void 0:t.profile)==null?void 0:ue.email)||"this member")}`,target:"_blank",rel:"noreferrer",children:[e.jsx(Tr,{className:"mr-2 h-4 w-4"}),"Open their dashboard"]})})]}),t?b?e.jsx(xn,{className:"h-64 w-full rounded-xl"}):e.jsxs("div",{className:"space-y-4 pb-8",children:[e.jsxs("div",{className:"grid gap-3 sm:grid-cols-2",children:[e.jsx(_e,{children:e.jsxs(De,{className:"p-4",children:[e.jsx("p",{className:"text-xs uppercase tracking-wide text-muted-foreground",children:"Status"}),e.jsx(We,{className:"mt-1 capitalize",children:String(t.status).replace(/_/g," ")}),e.jsxs("p",{className:"mt-2 text-xs text-muted-foreground",children:[_p(t.amount_cents,t.currency)," ·"," ",t.charged_at?`Charged ${vd(t.charged_at)}`:`Charge ${vd(t.charge_scheduled_at)||"not set"}`]})]})}),e.jsx(_e,{children:e.jsxs(De,{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:vd(t.last_activity_at,!0)||"No activity yet"}),e.jsxs("p",{className:"mt-2 text-xs text-muted-foreground",children:["Enrolled ",vd(t.created_at)]})]})})]}),e.jsx(_e,{children:e.jsxs(De,{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:[z," / ",$||"—"]})]}),e.jsx(ro,{value:W})]}),e.jsxs("div",{children:[e.jsxs("div",{className:"mb-1 flex items-center justify-between text-sm",children:[e.jsx("span",{className:"font-medium",children:"Curriculum completed"}),e.jsxs("span",{className:"text-muted-foreground",children:[(_==null?void 0:_.completions.length)||0," / ",(_==null?void 0:_.lessonCount)||0]})]}),e.jsx(ro,{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: "}),G]}),e.jsxs("span",{children:[e.jsx("span",{className:"text-muted-foreground",children:"Badges: "}),(_==null?void 0:_.badges.length)||0]}),e.jsxs("span",{children:[e.jsx("span",{className:"text-muted-foreground",children:"Weeks reported: "}),(_==null?void 0:_.weekly.length)||0]})]})]})}),e.jsx(_e,{children:e.jsxs(De,{className:"p-5",children:[e.jsx("p",{className:"mb-3 text-sm font-semibold",children:"Weekly progress"}),((_==null?void 0:_.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:_.weekly.map(ge=>e.jsxs("div",{className:"rounded-lg border border-border/60 p-3 text-sm",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("span",{className:"font-medium",children:["Week ",ge.week_number]}),e.jsxs("span",{className:"text-xs text-muted-foreground",children:[ge.videos_posted,"/",ge.goal_videos||s.weekly_video_goal," posted ·"," ",ge.stories_posted," stories"]})]}),ge.biggest_win&&e.jsxs("p",{className:"mt-1 text-muted-foreground",children:["Win: ",ge.biggest_win]}),ge.biggest_challenge&&e.jsxs("p",{className:"text-muted-foreground",children:["Challenge: ",ge.biggest_challenge]})]},ge.id))})]})}),e.jsx(_e,{children:e.jsxs(De,{className:"p-5",children:[e.jsx("p",{className:"mb-3 text-sm font-semibold",children:"Video log"}),((_==null?void 0:_.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:_.videos.slice(0,25).map(ge=>e.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[e.jsx(na,{className:"h-3.5 w-3.5 shrink-0 text-muted-foreground"}),e.jsx("span",{className:"truncate",children:ge.title||"Untitled video"}),e.jsxs("span",{className:"ml-auto shrink-0 text-xs text-muted-foreground",children:["Wk ",ge.week_number," · ",vd(ge.posted_at)]}),ge.instagram_url&&e.jsx("a",{href:ge.instagram_url,target:"_blank",rel:"noreferrer",className:"shrink-0 text-muted-foreground hover:text-foreground","aria-label":"Open post",children:e.jsx(Tr,{className:"h-3.5 w-3.5"})})]},ge.id))})]})}),(_==null?void 0:_.intake)&&e.jsx(_e,{children:e.jsxs(De,{className:"space-y-1 p-5 text-sm",children:[e.jsx("p",{className:"mb-2 text-sm font-semibold",children:"Intake answers"}),[["Full name",_.intake.full_name],["Email",_.intake.email],["Phone",_.intake.phone],["Instagram",_.intake.instagram_handle],["City / market",_.intake.city],["Areas served",_.intake.service_areas],["Years in real estate",_.intake.years_experience],["Specialty",_.intake.specialty],["Target audience",_.intake.target_audience],["On camera",_.intake.video_comfort],["Posts today",_.intake.posting_frequency],["Content style",_.intake.content_style],["Interests",_.intake.personal_interests],["#1 goal",_.intake.primary_goal],["Topics to avoid",_.intake.topics_to_avoid],["Time zone",_.intake.timezone]].filter(([,ge])=>!!ge).map(([ge,be])=>e.jsxs("p",{children:[e.jsxs("span",{className:"text-muted-foreground",children:[ge,": "]}),be]},ge)),A.map(({label:ge,value:be})=>e.jsxs("p",{children:[e.jsxs("span",{className:"text-muted-foreground",children:[ge,": "]}),be]},ge)),e.jsxs("p",{className:"pt-1 text-xs text-muted-foreground",children:["Content-sharing consent: ",_.intake.consent_public_profile?"Yes":"No"]})]})}),e.jsx(_e,{children:e.jsx(De,{className:"p-5",children:e.jsx(aEs,{programId:s.id,userId:i,memberName:(ce=t==null?void 0:t.profile)==null?void 0:ce.name})})}),e.jsx(_e,{children:e.jsxs(De,{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."})]}),((ae=_==null?void 0:_.analysis)==null?void 0:ae.status)&&e.jsx(We,{variant:"secondary",className:"capitalize",children:String(_.analysis.status).replace(/_/g," ")})]}),(he=_==null?void 0:_.analysis)!=null&&he.report_url?e.jsxs("div",{className:"flex flex-wrap items-center gap-2 rounded-lg border border-border/60 p-3 text-sm",children:[e.jsx(Wr,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{className:"truncate",children:"Review uploaded"}),e.jsxs("a",{href:_.analysis.report_url,target:"_blank",rel:"noreferrer",className:"ml-auto inline-flex items-center gap-1 text-primary hover:underline",children:["View ",e.jsx(Tr,{className:"h-3.5 w-3.5"})]})]}):e.jsx("p",{className:"text-sm text-muted-foreground",children:"No review uploaded yet."}),e.jsx("input",{ref:x,type:"file",accept:"application/pdf",className:"hidden",onChange:ge=>{var Se;const be=(Se=ge.target.files)==null?void 0:Se[0];be&&P(be),ge.target.value=""}}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsxs(B,{size:"sm",variant:"outline",onClick:()=>{var ge;return(ge=x.current)==null?void 0:ge.click()},disabled:g,children:[e.jsx(ni,{className:"mr-1.5 h-3.5 w-3.5"}),g?"Uploading…":(xe=_==null?void 0:_.analysis)!=null&&xe.report_url?"Replace PDF":"Upload PDF"]}),((ve=_==null?void 0:_.analysis)==null?void 0:ve.report_url)&&e.jsx(B,{size:"sm",variant:"ghost",onClick:I,children:"Remove"})]}),e.jsxs("div",{className:"space-y-2 pt-1",children:[e.jsx(re,{children:"Review summary shown to the agent (optional)"}),e.jsx(Ws,{rows:3,value:u,onChange:ge=>h(ge.target.value),placeholder:"Top 3 priorities, quick wins, what to fix first…"}),e.jsx("div",{className:"flex justify-end",children:e.jsx(B,{size:"sm",variant:"outline",onClick:M,disabled:m,children:"Save review notes"})})]})]})}),e.jsx(_e,{children:e.jsxs(De,{className:"space-y-3 p-5",children:[e.jsx(re,{children:"Coach notes (internal)"}),e.jsx(Ws,{rows:4,value:l,onChange:ge=>o(ge.target.value)}),e.jsx("div",{className:"flex justify-end",children:e.jsx(B,{size:"sm",onClick:L,disabled:c,children:"Save notes"})})]})})]}):null]})})},mit={code:"",label:"",kind:"percent",percent_off:"20",amount_off:"",max_redemptions:"",starts_at:"",expires_at:"",is_active:!0},pit=s=>{if(!s)return"";const t=new Date(s),n=t.getTimezoneOffset();return new Date(t.getTime()-n*6e4).toISOString().slice(0,16)},oEs=({program:s})=>{const{data:t=[],isLoading:n}=pTs(s.id),r=fTs(s.id),a=gTs(),[i,l]=N.useState(!1),[o,c]=N.useState({...mit}),d=()=>{c({...mit}),l(!0)},u=g=>{c({id:g.id,code:g.code,label:g.label||"",kind:g.percent_off!=null?"percent":"amount",percent_off:g.percent_off!=null?String(g.percent_off):"",amount_off:g.amount_off_cents!=null?String(g.amount_off_cents/100):"",max_redemptions:g.max_redemptions!=null?String(g.max_redemptions):"",starts_at:pit(g.starts_at),expires_at:pit(g.expires_at),is_active:g.is_active}),l(!0)},h=N.useMemo(()=>{const g=o.kind==="percent"?Math.floor(s.price_cents*Number(o.percent_off||0)/100):Math.round(Number(o.amount_off||0)*100),y=Math.min(Math.max(g,0),s.price_cents);return{discount:y,final:s.price_cents-y}},[o,s.price_cents]),m=async()=>{if(!o.code.trim())return ie.error("Give the code a name, e.g. FOUNDER50");await r.mutateAsync({id:o.id,code:o.code,label:o.label||null,percent_off:o.kind==="percent"?Number(o.percent_off)||0:null,amount_off_cents:o.kind==="amount"?Math.round(Number(o.amount_off||0)*100):null,max_redemptions:o.max_redemptions?Number(o.max_redemptions):null,starts_at:o.starts_at?new Date(o.starts_at).toISOString():null,expires_at:o.expires_at?new Date(o.expires_at).toISOString():null,is_active:o.is_active}),l(!1)},f=g=>{const y=g.percent_off!=null?Math.floor(s.price_cents*Number(g.percent_off)/100):g.amount_off_cents||0,x=Math.max(s.price_cents-Math.min(y,s.price_cents),0);return{off:g.percent_off!=null?`${Number(g.percent_off)}% off`:`${_p(g.amount_off_cents||0,s.currency)} off`,final:_p(x,s.currency)}};return e.jsxs("div",{className:"space-y-4",children:[e.jsx(_e,{children:e.jsxs(De,{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 ",_p(s.price_cents,s.currency)," charge."]})]}),e.jsxs(Bs,{open:i,onOpenChange:l,children:[e.jsx(Ao,{asChild:!0,children:e.jsxs(B,{onClick:d,children:[e.jsx(nn,{className:"mr-1.5 h-4 w-4"})," New code"]})}),e.jsxs(Fs,{className:"max-h-[85vh] overflow-y-auto",children:[e.jsx(qs,{children:e.jsx($s,{children:o.id?"Edit discount code":"Create a discount code"})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"grid gap-4 sm:grid-cols-2",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{children:"Code"}),e.jsx(we,{placeholder:"FOUNDER50",value:o.code,onChange:g=>c({...o,code:g.target.value.toUpperCase()})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{children:"Internal label (optional)"}),e.jsx(we,{placeholder:"Founding cohort",value:o.label,onChange:g=>c({...o,label:g.target.value})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{children:"Discount type"}),e.jsxs(Ns,{value:o.kind,onValueChange:g=>c({...o,kind:g}),children:[e.jsx(ws,{children:e.jsx(ks,{})}),e.jsxs(js,{children:[e.jsx(nt,{value:"percent",children:"Percent off"}),e.jsx(nt,{value:"amount",children:"Dollar amount off"})]})]})]}),o.kind==="percent"?e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{children:"Percent off"}),e.jsx(we,{type:"number",min:1,max:100,value:o.percent_off,onChange:g=>c({...o,percent_off:g.target.value})})]}):e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{children:"Amount off (USD)"}),e.jsx(we,{type:"number",min:0,value:o.amount_off,onChange:g=>c({...o,amount_off:g.target.value})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{children:"Max redemptions (blank = unlimited)"}),e.jsx(we,{type:"number",min:1,value:o.max_redemptions,onChange:g=>c({...o,max_redemptions:g.target.value})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{children:"Active from (optional)"}),e.jsx(we,{type:"datetime-local",value:o.starts_at,onChange:g=>c({...o,starts_at:g.target.value})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{children:"Expires (optional)"}),e.jsx(we,{type:"datetime-local",value:o.expires_at,onChange:g=>c({...o,expires_at:g.target.value})})]})]}),e.jsxs("div",{className:"flex items-center justify-between rounded-lg border border-border/60 p-4",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium",children:"Code is active"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Turn off to stop new redemptions instantly."})]}),e.jsx(zn,{checked:o.is_active,onCheckedChange:g=>c({...o,is_active:g})})]}),e.jsxs("div",{className:"rounded-lg border border-primary/30 bg-primary/5 p-4 text-sm",children:[e.jsx("p",{className:"font-medium",children:"Enrollee sees"}),e.jsxs("p",{className:"mt-1 text-muted-foreground",children:[_p(s.price_cents,s.currency)," →"," ",e.jsx("span",{className:"font-semibold text-foreground",children:_p(h.final,s.currency)})," ","(",_p(h.discount,s.currency)," off) — charged one time."]})]})]}),e.jsx(Cr,{children:e.jsxs(B,{onClick:m,disabled:r.isPending,children:[r.isPending&&e.jsx(us,{className:"mr-1.5 h-4 w-4 animate-spin"}),o.id?"Save changes":"Create code"]})})]})]})]})}),n?e.jsx(xn,{className:"h-40 w-full rounded-xl"}):t.length===0?e.jsx(_e,{className:"border-dashed",children:e.jsxs(De,{className:"flex flex-col items-center gap-3 p-12 text-center",children:[e.jsx(pf,{className:"h-8 w-8 text-muted-foreground"}),e.jsx("p",{className:"font-medium",children:"No discount codes yet"}),e.jsx("p",{className:"max-w-md text-sm text-muted-foreground",children:"Create a code for early birds, brokerage partners or a founding cohort. Codes are entered by the enrollee at checkout and change the one-time price."})]})}):e.jsx(_e,{children:e.jsx(De,{className:"overflow-x-auto p-0",children:e.jsxs(Oa,{children:[e.jsx(Fa,{children:e.jsxs(un,{children:[e.jsx(Mt,{children:"Code"}),e.jsx(Mt,{children:"Discount"}),e.jsx(Mt,{children:"Price after"}),e.jsx(Mt,{children:"Used"}),e.jsx(Mt,{children:"Window"}),e.jsx(Mt,{children:"Status"}),e.jsx(Mt,{className:"text-right",children:"Actions"})]})}),e.jsx(za,{children:t.map(g=>{const y=f(g);return e.jsxs(un,{children:[e.jsxs(gt,{children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"font-mono font-semibold",children:g.code}),e.jsx(B,{variant:"ghost",size:"icon",className:"h-6 w-6",onClick:()=>{navigator.clipboard.writeText(g.code),ie.success("Code copied")},children:e.jsx(Pa,{className:"h-3.5 w-3.5"})})]}),g.label&&e.jsx("p",{className:"text-xs text-muted-foreground",children:g.label})]}),e.jsx(gt,{className:"whitespace-nowrap",children:e.jsxs("span",{className:"inline-flex items-center gap-1.5",children:[e.jsx(IT,{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:[g.times_redeemed,g.max_redemptions?` / ${g.max_redemptions}`:""]}),e.jsxs(gt,{className:"text-xs text-muted-foreground",children:[g.starts_at?`From ${vd(g.starts_at)}`:"Anytime",g.expires_at?` · until ${vd(g.expires_at)}`:""]}),e.jsx(gt,{children:e.jsx(We,{variant:g.is_active?"default":"secondary",children:g.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(g),children:"Edit"}),e.jsx(B,{variant:"ghost",size:"icon",onClick:()=>{confirm(`Delete ${g.code}?`)&&a.mutate(g.id)},children:e.jsx(qn,{className:"h-4 w-4 text-destructive"})})]})})]},g.id)})})]})})})]})},tk=({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(Hr,{className:"mt-0.5 h-4 w-4 shrink-0 text-primary"}):e.jsx(xd,{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})]})]}),lEs=({program:s})=>{var c,d;const{data:t,isLoading:n}=mt({queryKey:["admin-program-content-counts",s.id],queryFn:async()=>{const[u,h,m,f,g]=await Promise.all([H.from("program_weeks").select("id, week_number, title").eq("program_id",s.id),H.from("program_lessons").select("id, title").eq("program_id",s.id),H.from("program_resources").select("id, title").eq("program_id",s.id),H.from("program_events").select("id, title, starts_at").eq("program_id",s.id),H.from("program_announcements").select("id, title").eq("program_id",s.id)]);return{weeks:u.data||[],lessons:h.data||[],resources:m.data||[],events:f.data||[],announcements:g.data||[]}}}),{notOpenYet:r,closed:a,opensLabel:i}=v3e(s),l=`/programs/${s.slug}`,o=[{icon:Cn,title:"1 · Sales page",body:`${s.name} — hero image, ${s.subtitle?"subtitle":"no subtitle"}, description, price, dates, seats left and FAQ.`,href:l,cta:"Preview sales page"},{icon:gW,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:U0,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 ${_p(s.price_cents,s.currency)} charge runs on ${vd(s.charge_at||s.kickoff_at)||"the charge date (not set)"}.`:`Stripe charges ${_p(s.price_cents,s.currency)} once at checkout.`},{icon:mn,title:"4 · Emails",body:"Confirmation right after enrollment, then payment receipt (or a payment-failed action email) when the one-time charge runs."},{icon:w9,title:"5 · Program workspace",body:`Their home base: progress dashboard, ${s.duration_weeks}-week roadmap, lessons, resources, events, weekly check-ins and video logging (${s.weekly_video_goal}/week goal).`,href:`${l}/workspace?preview=1`,cta:"Preview workspace as an enrollee"}];return e.jsxs("div",{className:"space-y-6",children:[e.jsx(_e,{children:e.jsxs(De,{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(Tr,{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(Tr,{className:"ml-1.5 h-3.5 w-3.5"})]})})]})]})}),(s.status!=="published"||r||a)&&e.jsx(_e,{className:"border-amber-500/40 bg-amber-500/5",children:e.jsxs(De,{className:"flex items-start gap-3 p-5 text-sm",children:[e.jsx(xd,{className:"mt-0.5 h-4 w-4 shrink-0 text-amber-500"}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:"Members can't enroll right now"}),e.jsx("p",{className:"text-muted-foreground",children:s.status!=="published"?`This program is ${s.status} — it isn't listed on the member Programs page yet.`:r?`Enrollment opens ${i}. CTAs are disabled until then.`:"Enrollment has closed for this cohort."})]})]})}),e.jsxs("div",{className:"grid gap-4 lg:grid-cols-2",children:[e.jsx(_e,{children:e.jsxs(De,{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(Tr,{className:"ml-1 h-3 w-3"})]})})]})]},u.title))})]})}),e.jsx(_e,{children:e.jsxs(De,{className:"p-5",children:[e.jsx("p",{className:"text-xs font-semibold uppercase tracking-wider text-muted-foreground",children:"Premium-experience checklist"}),n?e.jsx(xn,{className:"mt-4 h-64 w-full rounded-lg"}):e.jsxs("div",{className:"mt-2",children:[e.jsx(tk,{ok:!!s.cover_image_url,label:"Cover image",detail:s.cover_image_url?"Set":"Missing — cards look empty on the Programs page"}),e.jsx(tk,{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(tk,{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(tk,{ok:s.payment_mode==="free"||s.price_cents>0,label:"One-time price",detail:s.payment_mode==="free"?"Free / included":_p(s.price_cents,s.currency)}),e.jsx(tk,{ok:!!s.kickoff_at&&(s.payment_mode==="free"||!!s.charge_at),label:"Kickoff and charge dates",detail:`Kickoff ${vd(s.kickoff_at)||"not set"} · charge ${vd(s.charge_at)||"not set"}`}),e.jsx(tk,{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(tk,{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(tk,{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(tk,{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 ${vd(t.events[0].starts_at)}`:""}`}),e.jsx(tk,{ok:((t==null?void 0:t.announcements.length)||0)>0,label:"Welcome announcement",detail:`${(t==null?void 0:t.announcements.length)||0} announcements — a day-one welcome post makes the workspace feel alive`})]})]})})]}),t&&e.jsx(_e,{children:e.jsx(De,{className:"grid gap-4 p-5 sm:grid-cols-2 lg:grid-cols-5",children:[{icon:ld,label:"Weeks",value:t.weeks.length},{icon:Wr,label:"Lessons",value:t.lessons.length},{icon:Wr,label:"Resources",value:t.resources.length},{icon:ld,label:"Events",value:t.events.length},{icon:um,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(We,{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."})]})},cEs=["Step 1 · Your business","Step 2 · Your content","Step 3 · Your goals"],dEs={short_text:"Short answer",long_text:"Paragraph",select:"Dropdown",checkbox:"Yes / no checkbox"},uEs=({program:s,onSaved:t})=>{const[n,r]=N.useState(()=>IY(s)),[a,i]=N.useState(!1),[l,o]=N.useState(!1);N.useEffect(()=>{r(IY(s)),i(!1)},[s.id,s.updated_at]);const c=x=>{r(_=>({..._,...x})),i(!0)},d=(x,_)=>{const b=_?n.hidden.filter(A=>A!==x):[...new Set([...n.hidden,x])],k=_?n.required:n.required.filter(A=>A!==x);c({hidden:b,required:k})},u=(x,_)=>{c({required:_?[...new Set([...n.required,x])]:n.required.filter(b=>b!==x)})},h=()=>{const x={id:`q_${Date.now().toString(36)}`,label:"",type:"short_text",required:!1,options:[]};c({custom:[...n.custom,x]})},m=(x,_)=>c({custom:n.custom.map(b=>b.id===x?{...b,..._}:b)}),f=x=>c({custom:n.custom.filter(_=>_.id!==x)}),g=(x,_)=>{const b=[...n.custom],k=x+_;k<0||k>=b.length||([b[x],b[k]]=[b[k],b[x]],c({custom:b}))},y=async()=>{if(n.custom.find(k=>!k.label.trim()))return ie.error("Every custom question needs a label");o(!0);const _={...s.sales_copy||{},intake:n},{error:b}=await H.from("programs").update({sales_copy:_}).eq("id",s.id);if(o(!1),b)return ie.error(b.message);i(!1),ie.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(Tr,{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(Kl,{className:"mr-1.5 h-3.5 w-3.5"}),l?"Saving…":"Save intake form"]})]})]}),e.jsxs(_e,{children:[e.jsx(zt,{className:"pb-3",children:e.jsx(qt,{className:"text-sm",children:"Intro message"})}),e.jsx(De,{children:e.jsx(Ws,{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:x=>c({intro:x.target.value})})})]}),[0,1,2].map(x=>e.jsxs(_e,{children:[e.jsx(zt,{className:"pb-3",children:e.jsx(qt,{className:"text-sm",children:cEs[x]})}),e.jsxs(De,{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"})]}),iVe.filter(_=>_.step===x).map(_=>{const b=!n.hidden.includes(_.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:_.label}),e.jsx("div",{className:"flex w-16 justify-center",children:e.jsx(zn,{checked:b,onCheckedChange:k=>d(_.key,k),"aria-label":`Show ${_.label}`})}),e.jsx("div",{className:"flex w-16 justify-center",children:e.jsx(zn,{checked:n.required.includes(_.key),disabled:!b,onCheckedChange:k=>u(_.key,k),"aria-label":`Require ${_.label}`})})]},_.key)})]})]},x)),e.jsxs(_e,{children:[e.jsxs(zt,{className:"flex-row items-center justify-between space-y-0 pb-3",children:[e.jsxs(qt,{className:"text-sm",children:["Custom questions"," ",e.jsx(We,{variant:"secondary",className:"ml-1",children:n.custom.length})]}),e.jsxs(B,{size:"sm",variant:"outline",onClick:h,children:[e.jsx(nn,{className:"mr-1.5 h-3.5 w-3.5"})," Add question"]})]}),e.jsxs(De,{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((x,_)=>e.jsxs("div",{className:"space-y-3 rounded-lg border border-border/60 p-4",children:[e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsx("div",{className:"flex flex-col pt-1.5",children:e.jsx("button",{type:"button",className:"text-muted-foreground hover:text-foreground",onClick:()=>g(_,-1),"aria-label":"Move up",children:e.jsx(Mp,{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(re,{className:"text-xs",children:"Question"}),e.jsx(we,{value:x.label,placeholder:"What is your biggest content roadblock?",onChange:b=>m(x.id,{label:b.target.value})})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(re,{className:"text-xs",children:"Answer type"}),e.jsxs(Ns,{value:x.type,onValueChange:b=>m(x.id,{type:b}),children:[e.jsx(ws,{children:e.jsx(ks,{})}),e.jsx(js,{children:Object.entries(dEs).map(([b,k])=>e.jsx(nt,{value:b,children:k},b))})]})]})]}),e.jsx(B,{size:"icon",variant:"ghost",onClick:()=>f(x.id),"aria-label":"Delete question",children:e.jsx(qn,{className:"h-4 w-4 text-destructive"})})]}),x.type==="select"&&e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(re,{className:"text-xs",children:"Options (one per line)"}),e.jsx(Ws,{rows:3,value:(x.options||[]).join(` `),onChange:b=>m(x.id,{options:b.target.value.split(` `).map(k=>k.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(re,{className:"text-xs",children:"Helper text (optional)"}),e.jsx(we,{value:x.help||"",onChange:b=>m(x.id,{help:b.target.value})})]}),e.jsxs("div",{className:"flex items-center gap-2 pt-6",children:[e.jsx(zn,{checked:!!x.required,onCheckedChange:b=>m(x.id,{required:b}),"aria-label":"Required"}),e.jsx("span",{className:"text-sm",children:"Required"})]})]})]},x.id))]})]})]})},hEs=[vg,Wr,iu],mEs=["Business profile","Content style","Goals & consent"],pEs=({fieldKey:s})=>s.includes("phone")?e.jsx(ga,{className:"h-3.5 w-3.5"}):s.includes("email")?e.jsx(mn,{className:"h-3.5 w-3.5"}):s.includes("instagram")?e.jsx(dm,{className:"h-3.5 w-3.5"}):s.includes("city")||s.includes("area")?e.jsx(ii,{className:"h-3.5 w-3.5"}):s.includes("timezone")?e.jsx(Xr,{className:"h-3.5 w-3.5"}):s.includes("consent")?s.includes("true")?e.jsx(Hr,{className:"h-3.5 w-3.5"}):e.jsx(Nu,{className:"h-3.5 w-3.5"}):e.jsx(Ro,{className:"h-3.5 w-3.5"}),fit=(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(Hr,{className:"h-3.5 w-3.5"})," Yes"]}):e.jsxs("span",{className:"inline-flex items-center gap-1 text-muted-foreground",children:[e.jsx(Nu,{className:"h-3.5 w-3.5"})," No"]}):String(s),fEs=({program:s})=>{const[t,n]=N.useState(""),[r,a]=N.useState(new Set),{data:i=[],isLoading:l}=mt({queryKey:["admin-program-intakes",s.id],queryFn:async()=>{const{data:h,error:m}=await H.from("program_intake_responses").select("*").eq("program_id",s.id).order("created_at",{ascending:!1});if(m)throw m;return h||[]}}),o=IY(s),c=iVe.filter(h=>!o.hidden.includes(h.key)),d=i.filter(h=>{const m=t.toLowerCase();return m?String(h.full_name||"").toLowerCase().includes(m)||String(h.email||"").toLowerCase().includes(m)||String(h.city||"").toLowerCase().includes(m)||Object.values(h).some(f=>String(f).toLowerCase().includes(m)):!0}),u=h=>{const m=new Set(r);m.has(h)?m.delete(h):m.add(h),a(m)};return l?e.jsx(xn,{className:"h-96 w-full rounded-xl"}):i.length===0?e.jsx(_e,{className:"border-dashed",children:e.jsxs(De,{className:"p-12 text-center text-sm text-muted-foreground",children:[e.jsx(Wr,{className:"mx-auto mb-3 h-6 w-6"}),e.jsx("p",{children:"No intake responses yet."}),e.jsx("p",{className:"mt-1 text-xs",children:"Responses appear here once members complete the enrollment intake form."})]})}):e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-semibold",children:"Intake responses"}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[d.length," of ",i.length," response",i.length===1?"":"s"," · every field from the enrollment intake form"]})]}),e.jsxs("div",{className:"relative w-full sm:w-64",children:[e.jsx(Gr,{className:"absolute left-2.5 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground"}),e.jsx(we,{placeholder:"Search responses…",value:t,onChange:h=>n(h.target.value),className:"pl-9"})]})]}),d.length===0&&e.jsx("p",{className:"text-sm text-muted-foreground",children:"No responses match your search."}),e.jsx("div",{className:"space-y-3",children:d.map(h=>{const m=r.has(h.id),f=vd(h.created_at,!0);return e.jsx(_e,{className:"overflow-hidden",children:e.jsxs(Kv,{open:m,onOpenChange:()=>u(h.id),children:[e.jsx(Yv,{asChild:!0,children:e.jsxs(zt,{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(Ro,{className:"h-4 w-4 text-primary"})}),e.jsxs("div",{children:[e.jsxs(qt,{className:"text-sm font-semibold",children:[h.full_name||"Unnamed member",h.city&&e.jsxs("span",{className:"ml-2 font-normal text-muted-foreground",children:["· ",h.city]})]}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[h.email,h.email&&h.phone&&" · ",h.phone]})]})]}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs("div",{className:"hidden text-right sm:block",children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"Submitted"}),e.jsx("p",{className:"text-xs font-medium",children:f})]}),e.jsx(B,{variant:"ghost",size:"icon",className:"h-8 w-8 shrink-0",children:e.jsx(Xo,{className:`h-4 w-4 transition-transform ${m?"rotate-180":""}`})})]})]})}),e.jsx(Zv,{children:e.jsxs(De,{className:"space-y-5 p-5",children:[[0,1,2].map(g=>{const y=c.filter(_=>_.step===g),x=hEs[g];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(x,{className:"h-3.5 w-3.5 text-primary"})}),e.jsx("p",{className:"text-xs font-semibold uppercase tracking-wide text-muted-foreground",children:mEs[g]})]}),e.jsx("div",{className:"grid gap-3 sm:grid-cols-2 lg:grid-cols-3",children:y.map(_=>{const b=h[_.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(pEs,{fieldKey:_.key}),_.label]}),e.jsx("p",{className:"text-sm font-medium",children:fit(b,_.key)})]},_.key)})})]},g)}),o.custom&&o.custom.length>0&&e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-2 border-b border-border/40 pb-2",children:[e.jsx("div",{className:"flex h-6 w-6 items-center justify-center rounded-md bg-primary/10",children:e.jsx(Wr,{className:"h-3.5 w-3.5 text-primary"})}),e.jsx("p",{className:"text-xs font-semibold uppercase tracking-wide text-muted-foreground",children:"Custom questions"})]}),e.jsx("div",{className:"grid gap-3 sm:grid-cols-2",children:o.custom.map(g=>{var x;const y=(x=h.extra)==null?void 0:x[g.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:g.label}),e.jsx("p",{className:"text-sm font-medium",children:fit(y,g.id)})]},g.id)})})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2 pt-2 text-xs text-muted-foreground",children:[e.jsx(ta,{className:"h-3.5 w-3.5"}),"Submitted ",f,h.timezone&&e.jsxs("span",{className:"ml-2",children:["· Timezone: ",h.timezone]})]})]})})]})},h.id)})})]})},gEs=[{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"}],xEs=s=>{if(!s)return"";const t=new Date(s),n=t.getTimezoneOffset();return new Date(t.getTime()-n*6e4).toISOString().slice(0,16)},git={title:"",description:"",event_kind:"mastermind",starts_at:"",duration_minutes:60,speaker:"",meeting_link:"",replay_url:"",is_published:!0},yEs=({programId:s})=>{const{data:t=[],isLoading:n}=vTs(s),r=bTs(s),a=_Ts(),[i,l]=N.useState(!1),[o,c]=N.useState({...git}),d=()=>{c({...git}),l(!0)},u=x=>{c({id:x.id,title:x.title,description:x.description||"",event_kind:x.event_kind,starts_at:xEs(x.starts_at),duration_minutes:x.duration_minutes,speaker:x.speaker||"",meeting_link:x.meeting_link||"",replay_url:x.replay_url||"",is_published:x.is_published}),l(!0)},h=async()=>{if(!o.title.trim())return ie.error("Give the session a title");if(!o.starts_at)return ie.error("Pick a date and time");await r.mutateAsync({...o,starts_at:new Date(o.starts_at).toISOString(),duration_minutes:Number(o.duration_minutes)||60}),l(!1)},m=Date.now(),f=t.filter(x=>new Date(x.starts_at).getTime()>=m),g=t.filter(x=>new Date(x.starts_at).getTime()e.jsx(_e,{className:"border-border/60",children:e.jsxs(De,{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:x.title}),e.jsx(We,{variant:"secondary",className:"capitalize",children:x.event_kind.replace("_"," ")}),!x.is_published&&e.jsx(We,{variant:"outline",children:"Hidden"})]}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:[vd(x.starts_at,!0)," · ",x.duration_minutes," min",x.speaker?` · ${x.speaker}`:""]}),x.description&&e.jsx("p",{className:"max-w-2xl text-sm text-muted-foreground",children:x.description}),e.jsxs("div",{className:"flex flex-wrap gap-3 pt-1 text-xs",children:[x.meeting_link?e.jsxs(e.Fragment,{children:[e.jsxs("a",{className:"inline-flex items-center gap-1 text-primary hover:underline",href:x.meeting_link,target:"_blank",rel:"noreferrer",children:[e.jsx(Tr,{className:"h-3 w-3"})," Join link"]}),e.jsxs("button",{className:"inline-flex items-center gap-1 text-muted-foreground hover:text-foreground",onClick:()=>{navigator.clipboard.writeText(x.meeting_link),ie.success("Join link copied")},children:[e.jsx(Pa,{className:"h-3 w-3"})," Copy"]})]}):e.jsx("span",{className:"text-muted-foreground",children:"No meeting link yet"}),x.replay_url&&e.jsxs("a",{className:"inline-flex items-center gap-1 text-primary hover:underline",href:x.replay_url,target:"_blank",rel:"noreferrer",children:[e.jsx(na,{className:"h-3 w-3"})," Replay"]})]})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(B,{variant:"outline",size:"sm",onClick:()=>u(x),children:e.jsx(Ja,{className:"h-3.5 w-3.5"})}),e.jsx(B,{variant:"outline",size:"sm",onClick:()=>{confirm(`Remove "${x.title}"?`)&&a.mutate(x.id)},children:e.jsx(qn,{className:"h-3.5 w-3.5"})})]})]})});return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex flex-wrap items-end justify-between gap-4",children:[e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:"Live sessions"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Add your Zoom (or Meet / Teams) sessions here. Enrolled members see them in the Sessions tab with the join button, RSVP reminders and an add-to-calendar link."})]}),e.jsxs(B,{onClick:d,children:[e.jsx(nn,{className:"mr-1.5 h-4 w-4"})," Add session"]})]}),n?e.jsx("p",{className:"text-sm text-muted-foreground",children:"Loading sessions…"}):t.length===0?e.jsx(_e,{className:"border-dashed",children:e.jsxs(De,{className:"flex flex-col items-center gap-3 p-12 text-center",children:[e.jsx(df,{className:"h-8 w-8 text-muted-foreground"}),e.jsx("p",{className:"font-medium",children:"No live sessions scheduled"}),e.jsx("p",{className:"max-w-md text-sm text-muted-foreground",children:"Paste your recurring Zoom link once for each call — kickoff, weekly masterminds, workshops and office hours."})]})}):e.jsxs(e.Fragment,{children:[e.jsxs("section",{className:"space-y-3",children:[e.jsxs("h3",{className:"text-xs font-semibold uppercase tracking-wider text-muted-foreground",children:["Upcoming (",f.length,")"]}),f.length===0?e.jsx("p",{className:"text-sm text-muted-foreground",children:"Nothing upcoming."}):f.map(x=>e.jsx(y,{e:x},x.id))]}),g.length>0&&e.jsxs("section",{className:"space-y-3",children:[e.jsxs("h3",{className:"text-xs font-semibold uppercase tracking-wider text-muted-foreground",children:["Past (",g.length,") — add replay links so members can catch up"]}),g.map(x=>e.jsx(y,{e:x},x.id))]})]}),e.jsx(Bs,{open:i,onOpenChange:l,children:e.jsxs(Fs,{className:"max-h-[85vh] max-w-2xl overflow-y-auto",children:[e.jsx(qs,{children:e.jsx($s,{children:o.id?"Edit session":"Add a live session"})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{children:"Title"}),e.jsx(we,{placeholder:"Week 1 Mastermind — Content that converts",value:o.title,onChange:x=>c({...o,title:x.target.value})})]}),e.jsxs("div",{className:"grid gap-4 sm:grid-cols-2",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{children:"Type"}),e.jsxs(Ns,{value:o.event_kind,onValueChange:x=>c({...o,event_kind:x}),children:[e.jsx(ws,{children:e.jsx(ks,{})}),e.jsx(js,{children:gEs.map(x=>e.jsx(nt,{value:x.value,children:x.label},x.value))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{children:"Host / speaker"}),e.jsx(we,{value:o.speaker,onChange:x=>c({...o,speaker:x.target.value})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{children:"Starts (your local time)"}),e.jsx(we,{type:"datetime-local",value:o.starts_at,onChange:x=>c({...o,starts_at:x.target.value})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{children:"Length (minutes)"}),e.jsx(we,{type:"number",value:o.duration_minutes,onChange:x=>c({...o,duration_minutes:x.target.value})})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{children:"Zoom / meeting link"}),e.jsx(we,{placeholder:"https://us02web.zoom.us/j/1234567890?pwd=…",value:o.meeting_link,onChange:x=>c({...o,meeting_link:x.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(re,{children:"Replay link (after the call)"}),e.jsx(we,{placeholder:"YouTube, Vimeo, Loom or Zoom cloud recording URL",value:o.replay_url,onChange:x=>c({...o,replay_url:x.target.value})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{children:"What we'll cover"}),e.jsx(Ws,{rows:3,value:o.description,onChange:x=>c({...o,description:x.target.value})})]}),e.jsxs("div",{className:"flex items-center justify-between rounded-lg border border-border/60 p-4",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium",children:"Visible to members"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Turn off to draft a session privately."})]}),e.jsx(zn,{checked:o.is_published,onCheckedChange:x=>c({...o,is_published:x})})]})]}),e.jsx(Cr,{children:e.jsxs(B,{onClick:h,disabled:r.isPending,children:[r.isPending&&e.jsx(us,{className:"mr-1.5 h-4 w-4 animate-spin"}),o.id?"Save session":"Add session"]})})]})})]})},xit={title:"",summary:"",week_id:"none",duration_minutes:"",video_url:"",worksheet_url:"",action_assignment:"",status:"published",sort_order:0},vEs=({programId:s})=>{const{data:t,isLoading:n}=wTs(s),r=(t==null?void 0:t.lessons)||[],a=(t==null?void 0:t.weeks)||[],i=jTs(s),l=NTs(),[o,c]=N.useState(!1),[d,u]=N.useState({...xit}),h=()=>{u({...xit,sort_order:r.length}),c(!0)},m=x=>{u({id:x.id,title:x.title,summary:x.summary||"",week_id:x.week_id||"none",duration_minutes:x.duration_minutes??"",video_url:x.video_url||"",worksheet_url:x.worksheet_url||"",action_assignment:x.action_assignment||"",status:x.status,sort_order:x.sort_order}),c(!0)},f=async()=>{if(!d.title.trim())return ie.error("Give the video a title");await i.mutateAsync({...d,week_id:d.week_id==="none"?null:d.week_id,duration_minutes:d.duration_minutes===""?null:Number(d.duration_minutes),sort_order:Number(d.sort_order)||0}),c(!1)},g=x=>{const _=a.find(b=>b.id===x);return _?`Week ${_.week_number}`:"Unassigned"},y=jAt(d.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:h,children:[e.jsx(nn,{className:"mr-1.5 h-4 w-4"})," Add video"]})]}),n?e.jsx("p",{className:"text-sm text-muted-foreground",children:"Loading library…"}):r.length===0?e.jsx(_e,{className:"border-dashed",children:e.jsxs(De,{className:"flex flex-col items-center gap-3 p-12 text-center",children:[e.jsx(Rh,{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(x=>e.jsx(_e,{className:"border-border/60",children:e.jsxs(De,{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:x.title}),e.jsx(We,{variant:"secondary",children:g(x.week_id)}),x.status!=="published"&&e.jsx(We,{variant:"outline",className:"capitalize",children:x.status}),x.duration_minutes?e.jsxs("span",{className:"text-xs text-muted-foreground",children:[x.duration_minutes," min"]}):null]}),x.summary&&e.jsx("p",{className:"max-w-2xl text-sm text-muted-foreground",children:x.summary}),e.jsxs("div",{className:"flex flex-wrap gap-3 pt-1 text-xs",children:[x.video_url?e.jsxs("a",{className:"inline-flex items-center gap-1 text-primary hover:underline",href:x.video_url,target:"_blank",rel:"noreferrer",children:[e.jsx(Tr,{className:"h-3 w-3"})," Video"]}):e.jsx("span",{className:"text-muted-foreground",children:"No video link"}),x.worksheet_url&&e.jsxs("a",{className:"inline-flex items-center gap-1 text-primary hover:underline",href:x.worksheet_url,target:"_blank",rel:"noreferrer",children:[e.jsx(Tr,{className:"h-3 w-3"})," Worksheet"]})]})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(B,{variant:"outline",size:"sm",onClick:()=>m(x),children:e.jsx(Ja,{className:"h-3.5 w-3.5"})}),e.jsx(B,{variant:"outline",size:"sm",onClick:()=>{confirm(`Remove "${x.title}"?`)&&l.mutate(x.id)},children:e.jsx(qn,{className:"h-3.5 w-3.5"})})]})]})},x.id))}),e.jsx(Bs,{open:o,onOpenChange:c,children:e.jsxs(Fs,{className:"max-h-[85vh] max-w-2xl overflow-y-auto",children:[e.jsx(qs,{children:e.jsx($s,{children:d.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(re,{children:"Title"}),e.jsx(we,{placeholder:"How to script a 30-second listing reel",value:d.title,onChange:x=>u({...d,title:x.target.value})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{children:"Video link"}),e.jsx(we,{placeholder:"https://youtu.be/… , Vimeo or Loom URL",value:d.video_url,onChange:x=>u({...d,video_url:x.target.value})}),d.video_url&&!y&&e.jsx("p",{className:"text-xs text-muted-foreground",children:`We can't embed this link — members will get an "Open video" button instead.`})]}),y&&e.jsx("div",{className:"overflow-hidden rounded-lg border border-border/60",children:e.jsx("iframe",{src:y,title:"Video preview",className:"aspect-video w-full",allow:"accelerometer; autoplay; clipboard-write; encrypted-media; picture-in-picture",allowFullScreen:!0})}),e.jsxs("div",{className:"grid gap-4 sm:grid-cols-2",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{children:"Week"}),e.jsxs(Ns,{value:d.week_id,onValueChange:x=>u({...d,week_id:x}),children:[e.jsx(ws,{children:e.jsx(ks,{})}),e.jsxs(js,{children:[e.jsx(nt,{value:"none",children:"Unassigned (library)"}),a.map(x=>e.jsxs(nt,{value:x.id,children:["Week ",x.week_number," — ",x.title]},x.id))]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{children:"Length (minutes)"}),e.jsx(we,{type:"number",value:d.duration_minutes,onChange:x=>u({...d,duration_minutes:x.target.value})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{children:"Status"}),e.jsxs(Ns,{value:d.status,onValueChange:x=>u({...d,status:x}),children:[e.jsx(ws,{children:e.jsx(ks,{})}),e.jsxs(js,{children:[e.jsx(nt,{value:"published",children:"Published (visible)"}),e.jsx(nt,{value:"draft",children:"Draft (hidden)"}),e.jsx(nt,{value:"archived",children:"Archived"})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{children:"Order"}),e.jsx(we,{type:"number",value:d.sort_order,onChange:x=>u({...d,sort_order:x.target.value})})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{children:"Summary"}),e.jsx(Ws,{rows:3,value:d.summary,onChange:x=>u({...d,summary:x.target.value})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{children:"Worksheet / download link"}),e.jsx(we,{value:d.worksheet_url,onChange:x=>u({...d,worksheet_url:x.target.value})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{children:"Action assignment"}),e.jsx(Ws,{rows:2,placeholder:"Post one reel using this hook before your next mastermind.",value:d.action_assignment,onChange:x=>u({...d,action_assignment:x.target.value})})]})]}),e.jsx(Cr,{children:e.jsxs(B,{onClick:f,disabled:i.isPending,children:[i.isPending&&e.jsx(us,{className:"mr-1.5 h-4 w-4 animate-spin"}),d.id?"Save video":"Add video"]})})]})})]})},yit={title:"",description:"",category:"Resources",resource_kind:"pdf",url:"",file_path:"",status:"published",sort_order:0},bEs=({programId:s})=>{const{data:t=[],isLoading:n}=kTs(s),r=STs(s),a=CTs(),[i,l]=N.useState(!1),[o,c]=N.useState({...yit}),[d,u]=N.useState(!1),h=N.useRef(null),m=Array.from(new Set(t.map(_=>_.category))).filter(Boolean),f=()=>{c({...yit,sort_order:t.length}),l(!0)},g=_=>{c({id:_.id,title:_.title,description:_.description||"",category:_.category||"Resources",resource_kind:_.resource_kind,url:_.url||"",file_path:_.file_path||"",status:_.status,sort_order:_.sort_order}),l(!0)},y=async _=>{if(!(!_||!s)){if(_.size>50*1024*1024)return ie.error("File must be under 50MB");u(!0);try{const b=_.name.split(".").pop()||"pdf",k=`programs/${s}/resources/${Date.now()}-${Math.random().toString(36).slice(2,8)}.${b}`,{error:A}=await H.storage.from(vU).upload(k,_,{contentType:_.type||"application/pdf",upsert:!1});if(A)throw A;c(T=>({...T,file_path:k,url:"",title:T.title||_.name.replace(/\.[^.]+$/,""),resource_kind:_.type==="application/pdf"?"pdf":T.resource_kind})),ie.success("File uploaded")}catch(b){ie.error(b.message||"Upload failed")}finally{u(!1),h.current&&(h.current.value="")}}},x=async()=>{if(!o.title.trim())return ie.error("Give the resource a title");if(!o.file_path&&!o.url.trim())return ie.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:f,children:[e.jsx(nn,{className:"mr-1.5 h-4 w-4"})," Add resource"]})]}),n?e.jsx("p",{className:"text-sm text-muted-foreground",children:"Loading resources…"}):t.length===0?e.jsx(_e,{className:"border-dashed",children:e.jsxs(De,{className:"flex flex-col items-center gap-3 p-12 text-center",children:[e.jsx(Wr,{className:"h-8 w-8 text-muted-foreground"}),e.jsx("p",{className:"font-medium",children:"No resources yet"}),e.jsx("p",{className:"max-w-md text-sm text-muted-foreground",children:"Add the swipe files, scripts and worksheets that make this program feel premium."})]})}):e.jsx("div",{className:"space-y-3",children:t.map(_=>{const b=b3e(_);return e.jsx(_e,{className:"border-border/60",children:e.jsxs(De,{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:_.title}),e.jsx(We,{variant:"secondary",children:_.category}),e.jsx(We,{variant:"outline",className:"capitalize",children:_.resource_kind.replace("_"," ")}),_.status!=="published"&&e.jsx(We,{variant:"outline",className:"capitalize",children:_.status})]}),_.description&&e.jsx("p",{className:"max-w-2xl text-sm text-muted-foreground",children:_.description}),b&&e.jsxs("button",{type:"button",onClick:()=>oK(_),className:"inline-flex items-center gap-1 text-xs text-primary hover:underline",children:[e.jsx(Tr,{className:"h-3 w-3"})," Open"]})]}),e.jsxs("div",{className:"flex gap-1",children:[e.jsx(B,{variant:"ghost",size:"icon",onClick:()=>g(_),children:e.jsx(Ja,{className:"h-4 w-4"})}),e.jsx(B,{variant:"ghost",size:"icon",onClick:()=>{confirm(`Remove "${_.title}"?`)&&a.mutate(_)},children:e.jsx(qn,{className:"h-4 w-4 text-destructive"})})]})]})},_.id)})}),e.jsx(Bs,{open:i,onOpenChange:l,children:e.jsxs(Fs,{className:"max-w-lg",children:[e.jsx(qs,{children:e.jsx($s,{children:o.id?"Edit resource":"Add resource"})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(re,{children:"Title"}),e.jsx(we,{value:o.title,onChange:_=>c({...o,title:_.target.value}),placeholder:"90-Day Content Calendar"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(re,{children:"Description"}),e.jsx(Ws,{rows:2,value:o.description,onChange:_=>c({...o,description:_.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(re,{children:"Category"}),e.jsx(we,{value:o.category,onChange:_=>c({...o,category:_.target.value}),placeholder:"Getting started",list:"program-resource-categories"}),e.jsx("datalist",{id:"program-resource-categories",children:m.map(_=>e.jsx("option",{value:_},_))})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(re,{children:"Type"}),e.jsxs(Ns,{value:o.resource_kind,onValueChange:_=>c({...o,resource_kind:_}),children:[e.jsx(ws,{children:e.jsx(ks,{})}),e.jsx(js,{children:NAt.map(_=>e.jsx(nt,{value:_.value,children:_.label},_.value))})]})]})]}),e.jsxs("div",{className:"space-y-2 rounded-lg border p-3",children:[e.jsx(re,{children:"File"}),e.jsx("input",{ref:h,type:"file",className:"hidden",accept:".pdf,.doc,.docx,.xls,.xlsx,.ppt,.pptx,.csv,.zip,image/*",onChange:_=>{var b;return y((b=_.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 _;return(_=h.current)==null?void 0:_.click()},disabled:d,children:[d?e.jsx(us,{className:"mr-1.5 h-4 w-4 animate-spin"}):e.jsx(ni,{className:"mr-1.5 h-4 w-4"}),"Upload PDF or document"]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Or paste an external link instead (Canva, Google Doc, Notion…)."}),e.jsx(we,{value:o.url,onChange:_=>c({...o,url:_.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(re,{children:"Status"}),e.jsxs(Ns,{value:o.status,onValueChange:_=>c({...o,status:_}),children:[e.jsx(ws,{children:e.jsx(ks,{})}),e.jsxs(js,{children:[e.jsx(nt,{value:"published",children:"Published (visible)"}),e.jsx(nt,{value:"draft",children:"Draft (hidden)"}),e.jsx(nt,{value:"archived",children:"Archived"})]})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(re,{children:"Sort order"}),e.jsx(we,{type:"number",value:o.sort_order,onChange:_=>c({...o,sort_order:_.target.value})})]})]})]}),e.jsxs(Cr,{children:[e.jsx(B,{variant:"outline",onClick:()=>l(!1),children:"Cancel"}),e.jsxs(B,{onClick:x,disabled:r.isPending||d,children:[r.isPending&&e.jsx(us,{className:"mr-1.5 h-4 w-4 animate-spin"})," Save resource"]})]})]})})]})},_Es=({programId:s})=>{const{data:t=[],isLoading:n}=PTs(s),r=N.useMemo(()=>{const l=Date.now()-6048e5;return t.filter(o=>new Date(o.created_at).getTime()>=l).length},[t]),a=t.map(l=>l.email).filter(Boolean).join(", "),i=()=>{const l=`Name,Email,Phone,Brokerage,Joined `,o=t.map(u=>[u.full_name,u.email,u.phone,u.brokerage,u.created_at].map(h=>`"${(h??"").toString().replace(/"/g,'""')}"`).join(",")).join(` `),c=URL.createObjectURL(new Blob([l+o],{type:"text/csv"})),d=document.createElement("a");d.href=c,d.download="program-interest.csv",d.click(),URL.revokeObjectURL(c)};return n?e.jsx(xn,{className:"h-64 w-full rounded-xl"}):e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"grid gap-4 sm:grid-cols-3",children:[e.jsx(_e,{children:e.jsxs(De,{className:"flex items-center gap-3 p-4",children:[e.jsx(wT,{className:"h-5 w-5 text-primary"}),e.jsxs("div",{children:[e.jsx("p",{className:"text-2xl font-bold",children:t.length}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"On the notify list"})]})]})}),e.jsx(_e,{children:e.jsxs(De,{className:"flex items-center gap-3 p-4",children:[e.jsx(Yn,{className:"h-5 w-5 text-primary"}),e.jsxs("div",{children:[e.jsx("p",{className:"text-2xl font-bold",children:r}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Signed up in last 7 days"})]})]})}),e.jsx(_e,{children:e.jsx(De,{className:"flex items-center gap-3 p-4",children:e.jsxs(We,{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),ie.success("Emails copied")},children:[e.jsx(Pa,{className:"mr-2 h-4 w-4"})," Copy emails"]}),e.jsxs(B,{variant:"outline",size:"sm",disabled:!t.length,onClick:i,children:[e.jsx(oi,{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(Oa,{children:[e.jsx(Fa,{children:e.jsxs(un,{children:[e.jsx(Mt,{children:"Member"}),e.jsx(Mt,{children:"Email"}),e.jsx(Mt,{children:"Phone"}),e.jsx(Mt,{children:"Brokerage"}),e.jsx(Mt,{children:"Joined"})]})}),e.jsx(za,{children:t.map(l=>e.jsxs(un,{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:vd(l.created_at)})]},l.id))})]})})]})},vit={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:""},wEs=()=>{const s=as(),[t,n]=N.useState(null),[r,a]=N.useState(!1),[i,l]=N.useState({...vit}),[o,c]=N.useState(!1),[d,u]=N.useState(!1),[h,m]=N.useState(null),{data:f=[],isLoading:g}=mt({queryKey:["admin-programs"],queryFn:async()=>{const{data:M,error:L}=await H.from("programs").select("*").order("created_at",{ascending:!1});if(L)throw L;return M||[]}}),y=f.find(M=>M.id===t)||f[0]||null,{data:x=[]}=mt({queryKey:["admin-program-enrollments",y==null?void 0:y.id],enabled:!!(y!=null&&y.id),queryFn:async()=>{const{data:M,error:L}=await H.from("program_enrollments").select("*").eq("program_id",y.id).order("created_at",{ascending:!1});if(L)throw L;const z=(M||[]).map(W=>W.user_id),{data:$}=z.length?await H.from("profiles").select("id, name, email").in("id",z):{data:[]},V=new Map(($||[]).map(W=>[W.id,W]));return(M||[]).map(W=>({...W,profile:V.get(W.user_id)}))}}),{data:_=[]}=mt({queryKey:["admin-program-intakes",y==null?void 0:y.id],enabled:!!(y!=null&&y.id),queryFn:async()=>{const{data:M,error:L}=await H.from("program_intake_responses").select("*").eq("program_id",y.id);if(L)throw L;return M||[]}}),{data:b=[]}=mt({queryKey:["admin-program-audit",y==null?void 0:y.id],enabled:!!(y!=null&&y.id),queryFn:async()=>{const{data:M,error:L}=await H.from("program_audit_logs").select("*").eq("program_id",y.id).order("created_at",{ascending:!1}).limit(100);if(L)throw L;return M||[]}}),k=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:L}=await H.from("programs").insert(M);if(L)throw L;ie.success("Program created"),a(!1),l({...vit}),s.invalidateQueries({queryKey:["admin-programs"]})}catch(M){ie.error(M.message||"Could not create the program")}finally{c(!1)}},A=async M=>{if(!y)return;const{error:L}=await H.from("programs").update(M).eq("id",y.id);if(L)return ie.error(L.message);s.invalidateQueries({queryKey:["admin-programs"]})},T=async(M,L)=>{const{error:z}=await H.from("program_enrollments").update(L).eq("id",M);if(z)return ie.error(z.message);ie.success("Enrollment updated"),s.invalidateQueries({queryKey:["admin-program-enrollments"]})},P=async M=>{u(!0);const{data:L,error:z}=await H.functions.invoke("program-charge-due",{body:M?{enrollment_id:M}:{}});if(u(!1),z||L!=null&&L.error)return ie.error((L==null?void 0:L.error)||(z==null?void 0:z.message));ie.success(`Processed ${(L==null?void 0:L.processed)??0} charge(s)`),s.invalidateQueries({queryKey:["admin-program-enrollments"]})},I=M=>M==="paid"||M==="completed"?"default":M==="payment_failed"?"destructive":"secondary";return e.jsx(Qs,{children:e.jsxs("div",{className:"mx-auto w-full max-w-7xl space-y-6 p-4 md:p-8",children:[e.jsxs("header",{className:"flex flex-wrap items-end justify-between gap-4",children:[e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl font-bold tracking-tight",children:"Programs"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Manage cohorts, enrollments, delayed billing and program content."})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(B,{variant:"outline",onClick:()=>P(),disabled:d,children:[d?e.jsx(us,{className:"mr-1.5 h-4 w-4 animate-spin"}):e.jsx(U0,{className:"mr-1.5 h-4 w-4"}),"Run due charges"]}),e.jsxs(Bs,{open:r,onOpenChange:a,children:[e.jsx(Ao,{asChild:!0,children:e.jsxs(B,{children:[e.jsx(nn,{className:"mr-1.5 h-4 w-4"})," New program"]})}),e.jsxs(Fs,{className:"max-h-[85vh] overflow-y-auto",children:[e.jsx(qs,{children:e.jsx($s,{children:"Create a program"})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{children:"Name"}),e.jsx(we,{value:i.name,onChange:M=>l({...i,name:M.target.value})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{children:"Slug (URL)"}),e.jsx(we,{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(re,{children:"Subtitle"}),e.jsx(we,{value:i.subtitle,onChange:M=>l({...i,subtitle:M.target.value})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{children:"Description"}),e.jsx(Ws,{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(re,{children:"One-time price (USD)"}),e.jsx(we,{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(re,{children:"Seats"}),e.jsx(we,{type:"number",value:i.capacity,onChange:M=>l({...i,capacity:Number(M.target.value)})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{children:"Weeks"}),e.jsx(we,{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(re,{children:"Videos per week"}),e.jsx(we,{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(re,{children:"Billing"}),e.jsxs(Ns,{value:i.payment_mode,onValueChange:M=>l({...i,payment_mode:M}),children:[e.jsx(ws,{children:e.jsx(ks,{})}),e.jsxs(js,{children:[e.jsx(nt,{value:"delayed",children:"Save card, charge later"}),e.jsx(nt,{value:"immediate",children:"Charge at checkout"}),e.jsx(nt,{value:"free",children:"Free / included"})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{children:"Kickoff"}),e.jsx(we,{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(re,{children:"Charge date"}),e.jsx(we,{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(re,{children:"Enrollment closes"}),e.jsx(we,{type:"datetime-local",value:i.enrollment_close_at,onChange:M=>l({...i,enrollment_close_at:M.target.value})})]})]})]}),e.jsx(Cr,{children:e.jsxs(B,{onClick:k,disabled:o||!i.name,children:[o&&e.jsx(us,{className:"mr-1.5 h-4 w-4 animate-spin"})," Create"]})})]})]})]})]}),g?e.jsx(xn,{className:"h-40 w-full rounded-xl"}):f.length===0?e.jsx(_e,{className:"border-dashed",children:e.jsx(De,{className:"p-12 text-center text-sm text-muted-foreground",children:"No programs yet. Create your first cohort to get started."})}):e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"flex flex-wrap gap-2",children:f.map(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(We,{variant:"secondary",className:"ml-2 capitalize",children:M.status})]},M.id))}),y&&e.jsxs(ya,{defaultValue:"overview",children:[e.jsxs(va,{className:"flex w-full flex-wrap justify-start",children:[e.jsx(ls,{value:"overview",children:"Overview"}),e.jsx(ls,{value:"details",children:"Details & pricing"}),e.jsx(ls,{value:"sessions",children:"Live sessions"}),e.jsx(ls,{value:"videos",children:"On-demand videos"}),e.jsx(ls,{value:"resources",children:"Resources"}),e.jsx(ls,{value:"intake-form",children:"Intake form"}),e.jsx(ls,{value:"discounts",children:"Discount codes"}),e.jsx(ls,{value:"experience",children:"Enrollee experience"}),e.jsx(ls,{value:"interest",children:"Interest list"}),e.jsxs(ls,{value:"enrollments",children:["Enrollments (",x.length,")"]}),e.jsxs(ls,{value:"intake",children:["Intake (",_.length,")"]}),e.jsx(ls,{value:"audit",children:"Audit"})]}),e.jsxs(_s,{value:"overview",className:"mt-6 space-y-4",children:[e.jsxs("div",{className:"grid gap-4 sm:grid-cols-2 lg:grid-cols-4",children:[e.jsx(_e,{children:e.jsxs(De,{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:[x.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(_e,{children:e.jsxs(De,{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:x.filter(M=>M.status==="paid").length})]})}),e.jsx(_e,{children:e.jsxs(De,{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:x.filter(M=>M.status==="payment_failed").length})]})}),e.jsx(_e,{children:e.jsxs(De,{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:_p(x.filter(M=>["scheduled_for_charge","paid","completed"].includes(M.status)).reduce((M,L)=>M+(L.amount_cents||0),0),y.currency)})]})})]}),e.jsx(_e,{children:e.jsxs(De,{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(zn,{checked:y.status==="published",onCheckedChange:M=>A({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(zn,{checked:y.is_featured,onCheckedChange:M=>A({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:_p(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:vd(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:vd(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(_s,{value:"details",className:"mt-6",children:e.jsx(rEs,{program:y,onSaved:()=>s.invalidateQueries({queryKey:["admin-programs"]})})}),e.jsx(_s,{value:"sessions",className:"mt-6",children:e.jsx(yEs,{programId:y.id})}),e.jsx(_s,{value:"videos",className:"mt-6",children:e.jsx(vEs,{programId:y.id})}),e.jsx(_s,{value:"resources",className:"mt-6",children:e.jsx(bEs,{programId:y.id})}),e.jsx(_s,{value:"discounts",className:"mt-6",children:e.jsx(oEs,{program:y})}),e.jsx(_s,{value:"intake-form",className:"mt-6",children:e.jsx(uEs,{program:y,onSaved:()=>s.invalidateQueries({queryKey:["admin-programs"]})})}),e.jsx(_s,{value:"experience",className:"mt-6",children:e.jsx(lEs,{program:y})}),e.jsx(_s,{value:"interest",className:"mt-6",children:e.jsx(_Es,{programId:y.id})}),e.jsx(_s,{value:"enrollments",className:"mt-6",children:e.jsx(_e,{children:e.jsx(De,{className:"overflow-x-auto p-0",children:e.jsxs(Oa,{children:[e.jsx(Fa,{children:e.jsxs(un,{children:[e.jsx(Mt,{children:"Member"}),e.jsx(Mt,{children:"Status"}),e.jsx(Mt,{children:"Charge date"}),e.jsx(Mt,{children:"Amount"}),e.jsx(Mt,{children:"Access"}),e.jsx(Mt,{className:"text-right",children:"Actions"})]})}),e.jsxs(za,{children:[x.length===0&&e.jsx(un,{children:e.jsxs(gt,{colSpan:6,className:"py-10 text-center text-sm text-muted-foreground",children:[e.jsx(Yn,{className:"mx-auto mb-2 h-5 w-5"}),"No enrollments yet"]})}),x.map(M=>{var L,z;return e.jsxs(un,{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:((L=M.profile)==null?void 0:L.name)||"Unknown"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:(z=M.profile)==null?void 0:z.email})]})}),e.jsxs(gt,{children:[e.jsx(We,{variant:I(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:vd(M.charge_scheduled_at)||"—"}),e.jsx(gt,{className:"text-sm",children:_p(M.amount_cents,M.currency)}),e.jsx(gt,{children:e.jsx(zn,{checked:M.access_override,onCheckedChange:$=>T(M.id,{access_override:$})})}),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:()=>P(M.id),disabled:d,children:[e.jsx(oo,{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:()=>T(M.id,{status:"canceled",canceled_at:new Date().toISOString()}),children:"Cancel"})]})]},M.id)})]})]})})})}),e.jsx(_s,{value:"intake",className:"mt-6",children:e.jsx(fEs,{program:y})}),e.jsx(_s,{value:"audit",className:"mt-6",children:e.jsx(_e,{children:e.jsxs(De,{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(We,{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:vd(M.created_at,!0)})]},M.id))]})})})]}),y&&e.jsx(iEs,{program:y,enrollment:h,open:!!h,onOpenChange:M=>!M&&m(null),onUpdated:()=>s.invalidateQueries({queryKey:["admin-program-enrollments"]})})]})]})})},jEs=()=>{const{user:s}=Ls(),[t,n]=N.useState(""),[r,a]=N.useState("all"),{data:i=[]}=mt({queryKey:["academy-categories"],queryFn:async()=>{const{data:m,error:f}=await H.from("academy_categories").select("*").order("sort_order",{ascending:!0});if(f)throw f;return m}}),{data:l=[],isLoading:o}=mt({queryKey:["academy-videos"],queryFn:async()=>{const{data:m,error:f}=await H.from("academy_videos").select(` *, category:academy_categories(id, name) `).eq("is_published",!0).order("publish_date",{ascending:!1});if(f)throw f;const{data:g,error:y}=await H.from("academy_resources").select("*").order("sort_order");if(y)throw y;return m.map(_=>({..._,resources:(g==null?void 0:g.filter(b=>b.video_id===_.id))||[]}))}}),{data:c=[]}=mt({queryKey:["academy-video-likes"],queryFn:async()=>{const{data:m,error:f}=await H.from("academy_video_likes").select("video_id, user_id");if(f)throw f;return m}}),d=l.filter(m=>{var y;const f=t===""||m.title.toLowerCase().includes(t.toLowerCase())||((y=m.description)==null?void 0:y.toLowerCase().includes(t.toLowerCase())),g=r==="all"||m.category_id===r;return f&&g}),u=m=>c.filter(f=>f.video_id===m).length,h=m=>c.some(f=>f.video_id===m&&f.user_id===(s==null?void 0:s.id));return e.jsx(Qs,{title:"Academy",children:e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{children:[e.jsx("h1",{className:"text-5xl font-bold text-foreground",children:"Academy"}),e.jsx("p",{className:"text-muted-foreground mt-1",children:"On-demand training videos and resources"})]}),e.jsx("div",{className:"flex flex-col sm:flex-row gap-4",children:e.jsxs("div",{className:"relative flex-1",children:[e.jsx(Gr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(we,{placeholder:"Search videos...",value:t,onChange:m=>n(m.target.value),className:"pl-10"})]})}),e.jsx(ya,{value:r,onValueChange:a,children:e.jsxs(va,{className:"w-full justify-start flex-wrap h-auto gap-2 bg-transparent p-0",children:[e.jsx(ls,{value:"all",className:"data-[state=active]:bg-primary data-[state=active]:text-primary-foreground",children:"All Videos"}),i.map(m=>e.jsx(ls,{value:m.id,className:"data-[state=active]:bg-primary data-[state=active]:text-primary-foreground",children:m.name},m.id))]})}),o?e.jsx("div",{className:"flex justify-center py-12",children:e.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})}):d.length===0?e.jsx(_e,{children:e.jsxs(De,{className:"flex flex-col items-center justify-center py-12 text-center",children:[e.jsx(na,{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(cr,{to:`/academy/${m.id}`,children:e.jsxs(_e,{className:"overflow-hidden cursor-pointer hover:shadow-lg transition-shadow group h-full",children:[e.jsxs("div",{className:"relative aspect-video bg-muted",children:[m.thumbnail_url?e.jsx("img",{src:m.thumbnail_url,alt:m.title,className:"w-full h-full object-cover"}):e.jsx("div",{className:"w-full h-full flex items-center justify-center",children:e.jsx(na,{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(dd,{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(Xr,{className:"h-3 w-3"}),m.duration]})]}),e.jsxs(zt,{className:"pb-2",children:[e.jsx("div",{className:"flex items-start justify-between gap-2",children:e.jsx(qt,{className:"text-lg line-clamp-2",children:m.title})}),m.category&&e.jsx(We,{variant:"secondary",className:"w-fit",children:m.category.name})]}),e.jsxs(De,{className:"pt-0",children:[m.description&&e.jsx(_r,{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(ax,{className:`h-4 w-4 ${h(m.id)?"fill-primary text-primary":""}`}),u(m.id)]}),m.resources&&m.resources.length>0&&e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Wr,{className:"h-4 w-4"}),m.resources.length]})]})]})]})},m.id))})]})})};function FAt({resourceType:s,resourceId:t}){const{data:n=[]}=mt({queryKey:["linked-templates",s,t],queryFn:async()=>{if(s==="academy_video"){const{data:r,error:a}=await H.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 H.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(zc,{className:"h-4 w-4"}),"Related Templates"]}),e.jsx("div",{className:"flex flex-wrap gap-2",children:n.map(r=>e.jsx(cr,{to:`/templates/${r.id}`,children:e.jsxs(We,{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(zc,{className:"h-3 w-3"}),r.name]})},r.id))})]})}const NEs=(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},kEs=()=>{const{videoId:s}=uo();tr();const{user:t,isAdmin:n}=Ls(),{toast:r}=Ci(),a=as(),{trackEngagement:i}=pU(),[l,o]=N.useState(""),{data:c,isLoading:d}=mt({queryKey:["academy-video",s],queryFn:async()=>{const{data:k,error:A}=await H.from("academy_videos").select(` *, category:academy_categories(id, name) `).eq("id",s).eq("is_published",!0).single();if(A)throw A;const{data:T}=await H.from("academy_resources").select("*").eq("video_id",s).order("sort_order");return{...k,resources:T||[]}},enabled:!!s});N.useEffect(()=>{c&&i("academy_video",c.id,c.title,"view")},[c==null?void 0:c.id]);const{data:u=[]}=mt({queryKey:["academy-video-likes",s],queryFn:async()=>{const{data:k,error:A}=await H.from("academy_video_likes").select("*").eq("video_id",s);if(A)throw A;return k},enabled:!!s}),{data:h=[]}=mt({queryKey:["academy-video-comments",s],queryFn:async()=>{const{data:k,error:A}=await H.from("academy_video_comments").select("*").eq("video_id",s).order("created_at",{ascending:!1});if(A)throw A;const T=[...new Set(k.map(M=>M.user_id))],{data:P}=await H.from("profiles").select("id, name").in("id",T),I=new Map((P==null?void 0:P.map(M=>[M.id,M.name]))||[]);return k.map(M=>({...M,user_name:I.get(M.user_id)||"Unknown User"}))},enabled:!!s}),m=_t({mutationFn:async k=>{const{error:A}=await H.from("academy_video_comments").insert({video_id:s,user_id:t.id,content:k});if(A)throw A},onSuccess:()=>{a.invalidateQueries({queryKey:["academy-video-comments",s]}),o(""),r({title:"Comment added!"})},onError:k=>{r({title:"Error adding comment",description:k.message,variant:"destructive"})}}),f=_t({mutationFn:async k=>{const{error:A}=await H.from("academy_video_comments").delete().eq("id",k);if(A)throw A},onSuccess:()=>{a.invalidateQueries({queryKey:["academy-video-comments",s]}),r({title:"Comment deleted"})}}),g=_t({mutationFn:async()=>{const k=u.find(A=>A.user_id===(t==null?void 0:t.id));if(k){const{error:A}=await H.from("academy_video_likes").delete().eq("id",k.id);if(A)throw A}else{const{error:A}=await H.from("academy_video_likes").insert({video_id:s,user_id:t.id});if(A)throw A}},onSuccess:()=>{a.invalidateQueries({queryKey:["academy-video-likes",s]})}}),y=u.some(k=>k.user_id===(t==null?void 0:t.id)),x=k=>{switch(k==null?void 0:k.toLowerCase()){case"pdf":return"📄";case"pptx":case"ppt":return"📊";case"xlsx":case"xls":return"📈";case"docx":case"doc":return"📝";case"zip":return"📦";default:return"📁"}},_=k=>k.split(" ").map(A=>A[0]).join("").toUpperCase().slice(0,2),b=k=>{k.preventDefault(),!(!l.trim()||!t)&&m.mutate(l.trim())};return d?e.jsx(Qs,{title:"Academy",children:e.jsx("div",{className:"flex justify-center py-12",children:e.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})})}):c?e.jsx(Qs,{title:c.title,children:e.jsxs("div",{className:"space-y-6 max-w-5xl mx-auto",children:[e.jsx(B,{variant:"ghost",size:"sm",asChild:!0,className:"gap-2",children:e.jsxs(cr,{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:NEs(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(na,{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(Tr,{className:"h-4 w-4"}),"Open Video"]})})]})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-start sm:justify-between gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("h1",{className:"text-2xl font-bold text-foreground",children:c.title}),c.category&&e.jsx(We,{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(cr,{to:`/admin/academy?edit=${c.id}`,children:[e.jsx(Ja,{className:"h-4 w-4"}),e.jsx("span",{children:"Edit"})]})}),e.jsx(yU,{resourceType:"academy_video",resourceId:c.id,resourceTitle:c.title}),e.jsxs(B,{variant:y?"default":"outline",className:"gap-2 w-fit",onClick:()=>g.mutate(),disabled:!t||g.isPending,children:[e.jsx(ax,{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(_e,{children:e.jsxs(De,{className:"pt-6",children:[e.jsxs("h3",{className:"font-semibold flex items-center gap-2 mb-4",children:[e.jsx(Wr,{className:"h-4 w-4"}),"Resources"]}),e.jsx("div",{className:"grid gap-2",children:c.resources.map(k=>e.jsxs("a",{href:k.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:x(k.file_type)}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"font-medium truncate",children:k.title}),e.jsx("p",{className:"text-xs text-muted-foreground uppercase",children:k.file_type})]}),e.jsx(oi,{className:"h-4 w-4 text-muted-foreground"})]},k.id))})]})}),e.jsx(FAt,{resourceType:"academy_video",resourceId:c.id}),e.jsx(Wl,{}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("h3",{className:"font-semibold flex items-center gap-2 text-lg",children:[e.jsx(Ud,{className:"h-5 w-5"}),"Comments (",h.length,")"]}),t?e.jsxs("form",{onSubmit:b,className:"flex gap-2",children:[e.jsx(Ws,{placeholder:"Add a comment...",value:l,onChange:k=>o(k.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(Rr,{className:"h-4 w-4"})})]}):e.jsx("p",{className:"text-sm text-muted-foreground",children:"Log in to add a comment"}),e.jsx("div",{className:"space-y-4",children:h.length===0?e.jsx(_e,{children:e.jsx(De,{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(k=>e.jsx(_e,{children:e.jsx(De,{className:"pt-4 pb-4",children:e.jsxs("div",{className:"flex gap-3",children:[e.jsx(Ua,{className:"h-10 w-10 flex-shrink-0",children:e.jsx(qa,{className:"text-sm",children:_(k.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:k.user_name}),e.jsx("span",{className:"text-sm text-muted-foreground",children:nc(new Date(k.created_at),{addSuffix:!0})}),k.user_id===(t==null?void 0:t.id)&&e.jsx(B,{variant:"ghost",size:"icon",className:"h-6 w-6 ml-auto",onClick:()=>f.mutate(k.id),children:e.jsx(qn,{className:"h-3 w-3 text-muted-foreground"})})]}),e.jsx("p",{className:"text-sm whitespace-pre-wrap",children:k.content})]})]})})},k.id))})]})]})}):e.jsx(Qs,{title:"Academy",children:e.jsxs("div",{className:"flex flex-col items-center justify-center py-12 text-center",children:[e.jsx(na,{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(cr,{to:"/academy",children:"Back to Academy"})})]})})},xF="https://dashboard.relevelup.com",SEs=(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},CEs=[{icon:wp,title:"100+ Training Videos",desc:"On-demand LevelUp Academy content covering lead gen, listings, buyer conversion, marketing, and more."},{icon:ff,title:"Marketing Studio & Tools",desc:"AI-powered marketing tools, listing videos, landing pages, and social content — done for you."},{icon:Yn,title:"Coaching & Community",desc:"Live coaching sessions, private community, and a network of top-performing agents."},{icon:gl,title:"Business Scorecard",desc:"Track your deals, GCI, and pipeline in one dashboard built for real estate."}];function AEs(){var i;const{slug:s}=uo(),{data:t,isLoading:n,error:r}=mt({queryKey:["public-academy-video",s],queryFn:async()=>{if(!s)return null;const{data:l,error:o}=await H.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});N.useEffect(()=>{if(t&&s){H.rpc("increment_academy_public_view",{_slug:s}),document.title=`${t.title} | LevelUp Academy`;const l=(t.description||"").replace(/<[^>]+>/g,"").slice(0,155),o=document.querySelector('meta[name="description"]');if(o&&o.setAttribute("content",l||"Free training preview from LevelUp Academy."),t.thumbnail_url){let c=document.querySelector('meta[property="og:image"]');c||(c=document.createElement("meta"),c.setAttribute("property","og:image"),document.head.appendChild(c)),c.setAttribute("content",t.thumbnail_url)}}},[t,s]);const a=N.useMemo(()=>t?SEs(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:xF,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(Cn,{className:"w-5 h-5 text-white"})}),e.jsxs("div",{children:[e.jsx("div",{className:"font-bold text-lg tracking-tight",children:"LevelUp"}),e.jsx("div",{className:"text-[10px] uppercase tracking-widest text-[#5a9ea1] -mt-1",children:"Academy"})]})]}),e.jsx("a",{href:xF,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(We,{className:"bg-[#406E71]/20 text-[#7ec0c3] border-[#406E71]/40 hover:bg-[#406E71]/30",children:[e.jsx(wp,{className:"w-3 h-3 mr-1.5"}),"Free Training Preview"]}),((i=t.category)==null?void 0:i.name)&&e.jsx("div",{className:"text-xs uppercase tracking-[0.2em] text-[#5a9ea1]",children:t.category.name}),e.jsx("h1",{className:"text-3xl md:text-5xl lg:text-6xl font-bold tracking-tight leading-[1.1] max-w-4xl mx-auto",children:t.title}),t.duration&&e.jsx("div",{className:"text-[#8ba1b3] text-sm",children:t.duration})]}),e.jsxs("div",{className:"relative rounded-2xl overflow-hidden shadow-2xl ring-1 ring-white/10 bg-black",children:[e.jsx("div",{className:"absolute -inset-px rounded-2xl bg-gradient-to-r from-[#406E71]/50 via-transparent to-[#2a4c64]/50 blur-xl -z-10"}),e.jsx("div",{className:"aspect-video",children:e.jsx("iframe",{src:a,title:t.title,className:"w-full h-full",allow:"accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture",allowFullScreen:!0})})]}),t.description&&e.jsx("div",{className:"mt-10 max-w-3xl mx-auto text-[#c5d3de] text-lg leading-relaxed prose prose-invert prose-headings:text-white prose-a:text-[#7ec0c3]",dangerouslySetInnerHTML:{__html:t.description}})]}),e.jsx("section",{className:"relative z-10 max-w-4xl mx-auto px-6 pb-16",children:e.jsxs("div",{className:"relative rounded-3xl overflow-hidden p-10 md:p-14 text-center bg-gradient-to-br from-[#2a4c64] via-[#1d3a4f] to-[#0d1b26] ring-1 ring-white/10",children:[e.jsx("div",{className:"absolute top-0 right-0 w-64 h-64 bg-[#406E71]/30 rounded-full blur-3xl"}),e.jsxs("div",{className:"relative",children:[e.jsx(By,{className:"w-10 h-10 mx-auto mb-4 text-[#7ec0c3]"}),e.jsxs("h2",{className:"text-3xl md:text-4xl font-bold mb-3",children:["This is just ",e.jsx("span",{className:"text-[#7ec0c3]",children:"one"})," of hundreds."]}),e.jsx("p",{className:"text-[#c5d3de] text-lg mb-8 max-w-2xl mx-auto",children:"LevelUp members get unlimited access to the full Academy, AI marketing tools, coaching, and everything you need to grow your real estate business."}),e.jsxs("div",{className:"flex flex-col sm:flex-row items-center justify-center gap-3",children:[e.jsx("a",{href:xF,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(vi,{className:"w-4 h-4 ml-2"})]})}),e.jsx("a",{href:xF,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:CEs.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(Hr,{className:"w-4 h-4 text-[#7ec0c3]"})," Trusted by top producers"]}),e.jsxs("span",{className:"flex items-center gap-2",children:[e.jsx(Hr,{className:"w-4 h-4 text-[#7ec0c3]"})," New training weekly"]}),e.jsxs("span",{className:"flex items-center gap-2",children:[e.jsx(Hr,{className:"w-4 h-4 text-[#7ec0c3]"})," Cancel anytime"]})]}),e.jsx("div",{className:"text-center",children:e.jsx("a",{href:xF,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(vi,{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:xF,className:"hover:text-[#7ec0c3]",children:"dashboard.relevelup.com"})]})]})}function TEs(){const s=tr(),[t,n]=N.useState(""),{data:r,isLoading:a}=mt({queryKey:["resource-kits-published"],queryFn:async()=>{const{data:f,error:g}=await H.from("resource_kits").select("*").eq("is_published",!0).order("publish_date",{ascending:!1});if(g)throw g;return f}}),{data:i}=mt({queryKey:["resource-kit-files-all"],queryFn:async()=>{const{data:f,error:g}=await H.from("resource_kit_files").select("*").order("sort_order",{ascending:!0});if(g)throw g;return f}}),{data:l}=mt({queryKey:["resource-kit-likes-all"],queryFn:async()=>{const{data:f,error:g}=await H.from("resource_kit_likes").select("kit_id");if(g)throw g;return f}}),{data:o}=mt({queryKey:["resource-kit-comments-all"],queryFn:async()=>{const{data:f,error:g}=await H.from("resource_kit_comments").select("kit_id");if(g)throw g;return f}}),c=r==null?void 0:r.filter(f=>{var g;return f.name.toLowerCase().includes(t.toLowerCase())||((g=f.description)==null?void 0:g.toLowerCase().includes(t.toLowerCase()))}),d=f=>(i==null?void 0:i.filter(g=>g.kit_id===f))||[],u=f=>(l==null?void 0:l.filter(g=>g.kit_id===f).length)||0,h=f=>(o==null?void 0:o.filter(g=>g.kit_id===f).length)||0,m=f=>{s(`/toolbox/${f}`)};return e.jsx(Qs,{title:"Toolbox",description:"Download resource kits and tools to help grow your business",children:e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{children:[e.jsx("h1",{className:"text-5xl font-bold text-foreground",children:"Toolbox"}),e.jsx("p",{className:"text-muted-foreground mt-1",children:"Download resource kits and tools to help grow your business"})]}),e.jsxs("div",{className:"relative max-w-md",children:[e.jsx(Gr,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(we,{placeholder:"Search resource kits...",value:t,onChange:f=>n(f.target.value),className:"pl-10"})]}),!a&&e.jsxs("p",{className:"text-sm text-muted-foreground",children:[(c==null?void 0:c.length)||0," resource kit",(c==null?void 0:c.length)!==1?"s":""," available"]}),a?e.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-6",children:[...Array(8)].map((f,g)=>e.jsx(_e,{children:e.jsxs(De,{className:"p-4",children:[e.jsx(xn,{className:"aspect-[4/3] w-full rounded-lg mb-4"}),e.jsx(xn,{className:"h-5 w-3/4 mb-2"}),e.jsx(xn,{className:"h-4 w-full mb-4"}),e.jsx(xn,{className:"h-4 w-2/3"})]})},g))}):(c==null?void 0:c.length)===0?e.jsxs(_e,{className:"p-12 text-center",children:[e.jsx(Ku,{className:"h-12 w-12 mx-auto text-muted-foreground mb-4"}),e.jsx("h3",{className:"text-lg font-medium mb-2",children:"No resource kits found"}),e.jsx("p",{className:"text-muted-foreground",children:t?"Try adjusting your search terms":"Check back later for new resources"})]}):e.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-6",children:c==null?void 0:c.map(f=>{const g=d(f.id).length,y=u(f.id),x=h(f.id);return e.jsxs(_e,{className:"group overflow-hidden cursor-pointer hover:shadow-lg transition-all duration-200",onClick:()=>m(f.id),children:[e.jsx("div",{className:"relative overflow-hidden bg-muted aspect-[3/2]",children:f.featured_image_url?e.jsx("img",{src:f.featured_image_url,alt:f.name,className:"w-full h-full object-contain group-hover:scale-105 transition-transform duration-300"}):e.jsx("div",{className:"w-full h-full flex items-center justify-center",children:e.jsx(Ku,{className:"h-16 w-16 text-muted-foreground"})})}),e.jsxs(De,{className:"p-4",children:[e.jsx("h3",{className:"font-semibold text-foreground line-clamp-1 mb-1",children:f.name}),f.description&&e.jsx("p",{className:"text-sm text-muted-foreground line-clamp-2 mb-3",children:eY(f.description)}),e.jsxs("div",{className:"flex items-center justify-between text-sm text-muted-foreground",children:[e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Wr,{className:"h-4 w-4"}),g," file",g!==1?"s":""]}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(ax,{className:"h-3.5 w-3.5"}),y]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Ud,{className:"h-3.5 w-3.5"}),x]})]})]})]})]},f.id)})})]})})}const EEs=()=>{const{kitId:s}=uo(),{user:t,isAdmin:n}=Ls(),{toast:r}=Ci(),a=as(),{trackEngagement:i}=pU(),[l,o]=N.useState(""),{data:c,isLoading:d}=mt({queryKey:["resource-kit-detail",s],queryFn:async()=>{const{data:k,error:A}=await H.from("resource_kits").select("*").eq("id",s).eq("is_published",!0).single();if(A)throw A;const{data:T}=await H.from("resource_kit_files").select("*").eq("kit_id",s).order("sort_order"),{data:P}=await H.from("resource_kit_links").select("*").eq("kit_id",s).order("sort_order");return{...k,files:T||[],links:P||[]}},enabled:!!s});N.useEffect(()=>{c&&i("toolbox",c.id,c.name,"view")},[c==null?void 0:c.id]);const{data:u=[]}=mt({queryKey:["resource-kit-likes",s],queryFn:async()=>{const{data:k,error:A}=await H.from("resource_kit_likes").select("*").eq("kit_id",s);if(A)throw A;return k},enabled:!!s}),{data:h=[]}=mt({queryKey:["resource-kit-comments",s],queryFn:async()=>{const{data:k,error:A}=await H.from("resource_kit_comments").select("*").eq("kit_id",s).order("created_at",{ascending:!1});if(A)throw A;const T=[...new Set(k.map(M=>M.user_id))],{data:P}=await H.from("profiles").select("id, name").in("id",T),I=new Map((P==null?void 0:P.map(M=>[M.id,M.name]))||[]);return k.map(M=>({...M,user_name:I.get(M.user_id)||"Unknown User"}))},enabled:!!s}),m=_t({mutationFn:async k=>{const{error:A}=await H.from("resource_kit_comments").insert({kit_id:s,user_id:t.id,content:k});if(A)throw A},onSuccess:()=>{a.invalidateQueries({queryKey:["resource-kit-comments",s]}),o(""),r({title:"Comment added!"})},onError:k=>{r({title:"Error adding comment",description:k.message,variant:"destructive"})}}),f=_t({mutationFn:async k=>{const{error:A}=await H.from("resource_kit_comments").delete().eq("id",k);if(A)throw A},onSuccess:()=>{a.invalidateQueries({queryKey:["resource-kit-comments",s]}),r({title:"Comment deleted"})}}),g=_t({mutationFn:async()=>{const k=u.find(A=>A.user_id===(t==null?void 0:t.id));if(k){const{error:A}=await H.from("resource_kit_likes").delete().eq("id",k.id);if(A)throw A}else{const{error:A}=await H.from("resource_kit_likes").insert({kit_id:s,user_id:t.id});if(A)throw A}},onSuccess:()=>{a.invalidateQueries({queryKey:["resource-kit-likes",s]})}}),y=u.some(k=>k.user_id===(t==null?void 0:t.id)),x=k=>k.split(" ").map(A=>A[0]).join("").toUpperCase().slice(0,2),_=k=>k?k<1024?k+" B":k<1024*1024?(k/1024).toFixed(1)+" KB":(k/(1024*1024)).toFixed(1)+" MB":"",b=k=>{k.preventDefault(),!(!l.trim()||!t)&&m.mutate(l.trim())};return d?e.jsx(Qs,{title:"Toolbox",children:e.jsx("div",{className:"flex justify-center py-12",children:e.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})})}):c?e.jsx(Qs,{title:c.name,children:e.jsxs("div",{className:"space-y-6 max-w-5xl mx-auto",children:[e.jsx(B,{variant:"ghost",size:"sm",asChild:!0,className:"gap-2",children:e.jsxs(cr,{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(cr,{to:`/admin/toolbox?edit=${c.id}`,children:[e.jsx(Ja,{className:"h-4 w-4"}),e.jsx("span",{children:"Edit"})]})}),e.jsx(yU,{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:()=>g.mutate(),disabled:!t||g.isPending,children:[e.jsx(ax,{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(_e,{children:e.jsxs(De,{className:"pt-6",children:[e.jsxs("h3",{className:"font-semibold flex items-center gap-2 mb-4",children:[e.jsx(Wr,{className:"h-4 w-4"}),"Included Resources (",c.files.length,")"]}),e.jsx("div",{className:"grid gap-2",children:c.files.map(k=>e.jsxs("a",{href:k.file_url,target:"_blank",rel:"noopener noreferrer",onClick:()=>i("toolbox",c.id,c.name,"click_pdf"),className:"flex items-center justify-between p-3 rounded-lg border hover:bg-muted transition-colors group",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"p-2 rounded-md bg-primary/10",children:e.jsx(Wr,{className:"h-4 w-4 text-primary"})}),e.jsxs("div",{children:[e.jsx("div",{className:"font-medium text-sm",children:k.name}),k.file_size&&e.jsx("div",{className:"text-xs text-muted-foreground",children:_(k.file_size)})]})]}),e.jsx(oi,{className:"h-4 w-4 text-muted-foreground group-hover:text-primary transition-colors"})]},k.id))})]})}),c.links&&c.links.length>0&&e.jsx(_e,{children:e.jsxs(De,{className:"pt-6",children:[e.jsxs("h3",{className:"font-semibold flex items-center gap-2 mb-4",children:[e.jsx(Tr,{className:"h-4 w-4"}),"Canva Templates (",c.links.length,")"]}),e.jsx("div",{className:"grid gap-2",children:c.links.map(k=>e.jsxs("a",{href:k.canva_share_link,target:"_blank",rel:"noopener noreferrer",onClick:()=>i("toolbox",c.id,c.name,"click_canva"),className:"flex items-center justify-between p-3 rounded-lg border hover:bg-muted transition-colors group",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"p-2 rounded-md bg-purple-500/10",children:e.jsx(Tr,{className:"h-4 w-4 text-purple-600"})}),e.jsx("div",{className:"font-medium text-sm",children:k.title})]}),e.jsx("span",{className:"text-xs text-muted-foreground group-hover:text-primary transition-colors",children:"Open in Canva"})]},k.id))})]})}),e.jsx(FAt,{resourceType:"resource_kit",resourceId:c.id}),e.jsx(Wl,{}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("h3",{className:"font-semibold flex items-center gap-2 text-lg",children:[e.jsx(Ud,{className:"h-5 w-5"}),"Comments (",h.length,")"]}),t?e.jsxs("form",{onSubmit:b,className:"flex gap-2",children:[e.jsx(Ws,{placeholder:"Add a comment...",value:l,onChange:k=>o(k.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(Rr,{className:"h-4 w-4"})})]}):e.jsx("p",{className:"text-sm text-muted-foreground",children:"Log in to add a comment"}),e.jsx("div",{className:"space-y-4",children:h.length===0?e.jsx(_e,{children:e.jsx(De,{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(k=>e.jsx(_e,{children:e.jsx(De,{className:"pt-4 pb-4",children:e.jsxs("div",{className:"flex gap-3",children:[e.jsx(Ua,{className:"h-10 w-10 flex-shrink-0",children:e.jsx(qa,{className:"text-sm",children:x(k.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:k.user_name}),e.jsx("span",{className:"text-sm text-muted-foreground",children:nc(new Date(k.created_at),{addSuffix:!0})}),k.user_id===(t==null?void 0:t.id)&&e.jsx(B,{variant:"ghost",size:"icon",className:"h-6 w-6 ml-auto",onClick:()=>f.mutate(k.id),children:e.jsx(qn,{className:"h-3 w-3 text-muted-foreground"})})]}),e.jsx("p",{className:"text-sm whitespace-pre-wrap",children:k.content})]})]})})},k.id))})]})]})}):e.jsx(Qs,{title:"Toolbox",children:e.jsxs("div",{className:"flex flex-col items-center justify-center py-12 text-center",children:[e.jsx(Ku,{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(cr,{to:"/toolbox",children:"Back to Toolbox"})})]})})},MEs=()=>{const s=tr(),[t,n]=N.useState(""),[r,a]=N.useState("grid"),{data:i=[],isLoading:l}=mt({queryKey:["social-swag"],queryFn:async()=>{const{data:d,error:u}=await H.from("social_swag").select("*").eq("is_published",!0).order("publish_date",{ascending:!1});if(u)throw u;const{data:h,error:m}=await H.from("social_swag_links").select("*").order("sort_order");if(m)throw m;const{data:f}=await H.from("social_swag_likes").select("swag_id"),{data:g}=await H.from("social_swag_comments").select("swag_id"),y=new Map;f==null||f.forEach(b=>{y.set(b.swag_id,(y.get(b.swag_id)||0)+1)});const x=new Map;return g==null||g.forEach(b=>{x.set(b.swag_id,(x.get(b.swag_id)||0)+1)}),(d||[]).map(b=>({...b,links:(h||[]).filter(k=>k.swag_id===b.id)||[],likesCount:y.get(b.id)||0,commentsCount:x.get(b.id)||0}))}}),o=i.filter(d=>{var h;return d.title.toLowerCase().includes(t.toLowerCase())||((h=d.description)==null?void 0:h.toLowerCase().includes(t.toLowerCase()))}),c=d=>{s(`/social-swag/${d}`)};return e.jsx(Qs,{title:"Social Swag",children:e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl font-bold text-foreground",children:"Social Swag"}),e.jsx("p",{className:"text-muted-foreground mt-1",children:"Browse our collection of social media content and graphics"})]}),e.jsxs("div",{className:"flex flex-col sm:flex-row gap-4",children:[e.jsxs("div",{className:"relative flex-1 max-w-sm",children:[e.jsx(Gr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(we,{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(G0,{className:"h-4 w-4"})}),e.jsx(B,{variant:r==="list"?"secondary":"outline",size:"icon",onClick:()=>a("list"),className:"rounded-full",children:e.jsx(Kx,{className:"h-4 w-4"})})]})]})]}),e.jsxs("div",{className:"text-sm text-muted-foreground",children:[o.length," item",o.length!==1?"s":""," found"]}),l&&e.jsx("div",{className:r==="grid"?"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-6":"space-y-4",children:[...Array(8)].map((d,u)=>e.jsx(_e,{children:e.jsxs(De,{className:"p-4",children:[e.jsx(xn,{className:"aspect-[4/3] w-full rounded-lg mb-4"}),e.jsx(xn,{className:"h-5 w-3/4 mb-2"}),e.jsx(xn,{className:"h-4 w-full mb-4"})]})},u))}),!l&&o.length===0&&e.jsxs("div",{className:"text-center py-12",children:[e.jsx("div",{className:"text-muted-foreground mb-4",children:t?"No items match your search":"No social swag available yet"}),t&&e.jsx(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(_e,{className:`group overflow-hidden hover:shadow-lg transition-all duration-200 cursor-pointer ${r==="list"?"flex flex-row":""}`,onClick:()=>c(d.id),children:[e.jsxs("div",{className:`relative overflow-hidden bg-muted ${r==="list"?"w-48 shrink-0":"aspect-[3/2]"}`,children:[d.preview_image_url?e.jsx("img",{src:d.preview_image_url,alt:d.title,className:"w-full h-full object-cover group-hover:scale-105 transition-transform duration-300"}):e.jsx("div",{className:"w-full h-full flex items-center justify-center text-muted-foreground",children:"No Preview"}),d.links.length>1&&e.jsx("div",{className:"absolute top-2 right-2",children:e.jsxs(We,{variant:"secondary",className:"gap-1 bg-background/90 backdrop-blur-sm",children:[e.jsx(gc,{className:"h-3 w-3"}),d.links.length]})})]}),e.jsxs(De,{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(ax,{className:"h-3.5 w-3.5"}),d.likesCount]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Ud,{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(Tr,{className:"h-4 w-4"}),"View Details"]})]})]},d.id))})]})})};var al=function(){return al=Object.assign||function(t){for(var n,r=1,a=arguments.length;r1&&(c||!d),h=t>1&&(d||!c),m=function(){r&&i(r)},f=function(){a&&i(a)};return e.jsx(d6s,{displayMonth:s.displayMonth,hideNext:u,hidePrevious:h,nextMonth:a,previousMonth:r,onPreviousClick:m,onNextClick:f})}function u6s(s){var t,n=$h(),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:$At,d;return a?d=e.jsx(c,{id:s.id,displayMonth:s.displayMonth}):l==="dropdown"?d=e.jsx(bit,{displayMonth:s.displayMonth,id:s.id}):l==="dropdown-buttons"?d=e.jsxs(e.Fragment,{children:[e.jsx(bit,{displayMonth:s.displayMonth,displayIndex:s.displayIndex,id:s.id}),e.jsx(_it,{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(_it,{displayMonth:s.displayMonth,id:s.id})]}),e.jsx("div",{className:r.caption,style:i.caption,children:d})}function h6s(s){var t=$h(),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 m6s(s,t,n){for(var r=n?S3(new Date):lx(new Date,{locale:s,weekStartsOn:t}),a=[],i=0;i<7;i++){var l=Ad(r,i);a.push(l)}return a}function p6s(){var s=$h(),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=m6s(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 f6s(){var s,t=$h(),n=t.classNames,r=t.styles,a=t.components,i=(s=a==null?void 0:a.HeadRow)!==null&&s!==void 0?s:p6s;return e.jsx("thead",{style:r.head,className:n.head,children:e.jsx(i,{})})}function g6s(s){var t=$h(),n=t.locale,r=t.formatters.formatDay;return e.jsx(e.Fragment,{children:r(s.date,{locale:n})})}var hVe=N.createContext(void 0);function x6s(s){if(!WQ(s.initialProps)){var t={selected:void 0,modifiers:{disabled:[]}};return e.jsx(hVe.Provider,{value:t,children:s.children})}return e.jsx(y6s,{initialProps:s.initialProps,children:s.children})}function y6s(s){var t=s.initialProps,n=s.children,r=t.selected,a=t.min,i=t.max,l=function(d,u,h){var m,f;(m=t.onDayClick)===null||m===void 0||m.call(t,d,u,h);var g=!!(u.selected&&a&&(r==null?void 0:r.length)===a);if(!g){var y=!!(!u.selected&&i&&(r==null?void 0:r.length)===i);if(!y){var x=r?zAt([],r):[];if(u.selected){var _=x.findIndex(function(b){return yd(d,b)});x.splice(_,1)}else x.push(d);(f=t.onSelect)===null||f===void 0||f.call(t,x,d,u,h)}}},o={disabled:[]};r&&o.disabled.push(function(d){var u=i&&r.length>i-1,h=r.some(function(m){return yd(m,d)});return!!(u&&!h)});var c={selected:r,onDayClick:l,modifiers:o};return e.jsx(hVe.Provider,{value:c,children:n})}function mVe(){var s=N.useContext(hVe);if(!s)throw new Error("useSelectMultiple must be used within a SelectMultipleProvider");return s}function v6s(s,t){var n=t||{},r=n.from,a=n.to;return r&&a?yd(a,s)&&yd(r,s)?void 0:yd(a,s)?{from:a,to:void 0}:yd(r,s)?void 0:pj(r,s)?{from:s,to:a}:{from:r,to:s}:a?pj(s,a)?{from:a,to:s}:{from:s,to:a}:r?rN(s,r)?{from:s,to:r}:{from:r,to:s}:{from:s,to:void 0}}var pVe=N.createContext(void 0);function b6s(s){if(!KQ(s.initialProps)){var t={selected:void 0,modifiers:{range_start:[],range_end:[],range_middle:[],disabled:[]}};return e.jsx(pVe.Provider,{value:t,children:s.children})}return e.jsx(_6s,{initialProps:s.initialProps,children:s.children})}function _6s(s){var t=s.initialProps,n=s.children,r=t.selected,a=r||{},i=a.from,l=a.to,o=t.min,c=t.max,d=function(f,g,y){var x,_;(x=t.onDayClick)===null||x===void 0||x.call(t,f,g,y);var b=v6s(f,r);(_=t.onSelect)===null||_===void 0||_.call(t,b,f,g,y)},u={range_start:[],range_end:[],range_middle:[],disabled:[]};if(i?(u.range_start=[i],l?(u.range_end=[l],yd(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:zW(i,o-1),before:Ad(i,o-1)}),i&&l&&u.disabled.push({after:i,before:Ad(i,o-1)}),!i&&l&&u.disabled.push({after:zW(l,o-1),before:Ad(l,o-1)})),c){if(i&&!l&&(u.disabled.push({before:Ad(i,-c+1)}),u.disabled.push({after:Ad(i,c-1)})),i&&l){var h=Iv(l,i)+1,m=c-h;u.disabled.push({before:zW(i,m)}),u.disabled.push({after:Ad(l,m)})}!i&&l&&(u.disabled.push({before:Ad(l,-c+1)}),u.disabled.push({after:Ad(l,c-1)}))}return e.jsx(pVe.Provider,{value:{selected:r,onDayClick:d,modifiers:u},children:n})}function fVe(){var s=N.useContext(pVe);if(!s)throw new Error("useSelectRange must be used within a SelectRangeProvider");return s}function Ywe(s){return Array.isArray(s)?zAt([],s):s!==void 0?[s]:[]}function w6s(s){var t={};return Object.entries(s).forEach(function(n){var r=n[0],a=n[1];t[r]=Ywe(a)}),t}var hN;(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"})(hN||(hN={}));var j6s=hN.Selected,DS=hN.Disabled,N6s=hN.Hidden,k6s=hN.Today,VMe=hN.RangeEnd,HMe=hN.RangeMiddle,GMe=hN.RangeStart,S6s=hN.Outside;function C6s(s,t,n){var r,a=(r={},r[j6s]=Ywe(s.selected),r[DS]=Ywe(s.disabled),r[N6s]=Ywe(s.hidden),r[k6s]=[s.today],r[VMe]=[],r[HMe]=[],r[GMe]=[],r[S6s]=[],r);return s.fromDate&&a[DS].push({before:s.fromDate}),s.toDate&&a[DS].push({after:s.toDate}),WQ(s)?a[DS]=a[DS].concat(t.modifiers[DS]):KQ(s)&&(a[DS]=a[DS].concat(n.modifiers[DS]),a[GMe]=n.modifiers[GMe],a[HMe]=n.modifiers[HMe],a[VMe]=n.modifiers[VMe]),a}var VAt=N.createContext(void 0);function A6s(s){var t=$h(),n=mVe(),r=fVe(),a=C6s(t,n,r),i=w6s(t.modifiers),l=al(al({},a),i);return e.jsx(VAt.Provider,{value:l,children:s.children})}function HAt(){var s=N.useContext(VAt);if(!s)throw new Error("useModifiers must be used within a ModifiersProvider");return s}function T6s(s){return!!(s&&typeof s=="object"&&"before"in s&&"after"in s)}function E6s(s){return!!(s&&typeof s=="object"&&"from"in s)}function M6s(s){return!!(s&&typeof s=="object"&&"after"in s)}function L6s(s){return!!(s&&typeof s=="object"&&"before"in s)}function P6s(s){return!!(s&&typeof s=="object"&&"dayOfWeek"in s)}function I6s(s,t){var n,r=t.from,a=t.to;if(r&&a){var i=Iv(a,r)<0;i&&(n=[a,r],r=n[0],a=n[1]);var l=Iv(s,r)>=0&&Iv(a,s)>=0;return l}return a?yd(a,s):r?yd(r,s):!1}function D6s(s){return Y$e(s)}function R6s(s){return Array.isArray(s)&&s.every(Y$e)}function O6s(s,t){return t.some(function(n){if(typeof n=="boolean")return n;if(D6s(n))return yd(s,n);if(R6s(n))return n.includes(s);if(E6s(n))return I6s(s,n);if(P6s(n))return n.dayOfWeek.includes(s.getDay());if(T6s(n)){var r=Iv(n.before,s),a=Iv(n.after,s),i=r>0,l=a<0,o=pj(n.before,n.after);return o?l&&i:i||l}return M6s(n)?Iv(s,n.after)>0:L6s(n)?Iv(n.before,s)>0:typeof n=="function"?n(s):!1})}function gVe(s,t,n){var r=Object.keys(t).reduce(function(i,l){var o=t[l];return O6s(s,o)&&i.push(l),i},[]),a={};return r.forEach(function(i){return a[i]=!0}),n&&!MQ(s,n)&&(a.outside=!0),a}function F6s(s,t){for(var n=am(s[0]),r=m_(s[s.length-1]),a,i,l=n;l<=r;){var o=gVe(l,t),c=!o.disabled&&!o.hidden;if(!c){l=Ad(l,1);continue}if(o.selected)return l;o.today&&!i&&(i=l),a||(a=l),l=Ad(l,1)}return i||a}var z6s=365;function GAt(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:Ad,week:H4,month:J0,year:Hos,startOfWeek:function(x){return a.ISOWeek?S3(x):lx(x,{locale:h,weekStartsOn:c})},endOfWeek:function(x){return a.ISOWeek?oNt(x):FB(x,{locale:h,weekStartsOn:c})}},f=m[n](s,r==="after"?1:-1);r==="before"&&d?f=Gos([d,f]):r==="after"&&u&&(f=Wos([u,f]));var g=!0;if(i){var y=gVe(f,i);g=!y.disabled&&!y.hidden}return g?f:o.count>z6s?o.lastFocused:GAt(f,{moveBy:n,direction:r,context:a,modifiers:i,retry:al(al({},o),{count:o.count+1})})}var WAt=N.createContext(void 0);function B6s(s){var t=YQ(),n=HAt(),r=N.useState(),a=r[0],i=r[1],l=N.useState(),o=l[0],c=l[1],d=F6s(t.displayMonths,n),u=a??(o&&t.isDateDisplayed(o))?o:d,h=function(){c(a),i(void 0)},m=function(x){i(x)},f=$h(),g=function(x,_){if(a){var b=GAt(a,{moveBy:x,direction:_,context:f,modifiers:n});yd(a,b)||(t.goToDate(b,a),m(b))}},y={focusedDay:a,focusTarget:u,blur:h,focus:m,focusDayAfter:function(){return g("day","after")},focusDayBefore:function(){return g("day","before")},focusWeekAfter:function(){return g("week","after")},focusWeekBefore:function(){return g("week","before")},focusMonthBefore:function(){return g("month","before")},focusMonthAfter:function(){return g("month","after")},focusYearBefore:function(){return g("year","before")},focusYearAfter:function(){return g("year","after")},focusStartOfWeek:function(){return g("startOfWeek","before")},focusEndOfWeek:function(){return g("endOfWeek","after")}};return e.jsx(WAt.Provider,{value:y,children:s.children})}function xVe(){var s=N.useContext(WAt);if(!s)throw new Error("useFocusContext must be used within a FocusProvider");return s}function $6s(s,t){var n=HAt(),r=gVe(s,n,t);return r}var yVe=N.createContext(void 0);function U6s(s){if(!j3e(s.initialProps)){var t={selected:void 0};return e.jsx(yVe.Provider,{value:t,children:s.children})}return e.jsx(q6s,{initialProps:s.initialProps,children:s.children})}function q6s(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(yVe.Provider,{value:a,children:n})}function KAt(){var s=N.useContext(yVe);if(!s)throw new Error("useSelectSingle must be used within a SelectSingleProvider");return s}function V6s(s,t){var n=$h(),r=KAt(),a=mVe(),i=fVe(),l=xVe(),o=l.focusDayAfter,c=l.focusDayBefore,d=l.focusWeekAfter,u=l.focusWeekBefore,h=l.blur,m=l.focus,f=l.focusMonthBefore,g=l.focusMonthAfter,y=l.focusYearBefore,x=l.focusYearAfter,_=l.focusStartOfWeek,b=l.focusEndOfWeek,k=function(ne){var me,ue,ce,ae;j3e(n)?(me=r.onDayClick)===null||me===void 0||me.call(r,s,t,ne):WQ(n)?(ue=a.onDayClick)===null||ue===void 0||ue.call(a,s,t,ne):KQ(n)?(ce=i.onDayClick)===null||ce===void 0||ce.call(i,s,t,ne):(ae=n.onDayClick)===null||ae===void 0||ae.call(n,s,t,ne)},A=function(ne){var me;m(s),(me=n.onDayFocus)===null||me===void 0||me.call(n,s,t,ne)},T=function(ne){var me;h(),(me=n.onDayBlur)===null||me===void 0||me.call(n,s,t,ne)},P=function(ne){var me;(me=n.onDayMouseEnter)===null||me===void 0||me.call(n,s,t,ne)},I=function(ne){var me;(me=n.onDayMouseLeave)===null||me===void 0||me.call(n,s,t,ne)},M=function(ne){var me;(me=n.onDayPointerEnter)===null||me===void 0||me.call(n,s,t,ne)},L=function(ne){var me;(me=n.onDayPointerLeave)===null||me===void 0||me.call(n,s,t,ne)},z=function(ne){var me;(me=n.onDayTouchCancel)===null||me===void 0||me.call(n,s,t,ne)},$=function(ne){var me;(me=n.onDayTouchEnd)===null||me===void 0||me.call(n,s,t,ne)},V=function(ne){var me;(me=n.onDayTouchMove)===null||me===void 0||me.call(n,s,t,ne)},W=function(ne){var me;(me=n.onDayTouchStart)===null||me===void 0||me.call(n,s,t,ne)},G=function(ne){var me;(me=n.onDayKeyUp)===null||me===void 0||me.call(n,s,t,ne)},X=function(ne){var me;switch(ne.key){case"ArrowLeft":ne.preventDefault(),ne.stopPropagation(),n.dir==="rtl"?o():c();break;case"ArrowRight":ne.preventDefault(),ne.stopPropagation(),n.dir==="rtl"?c():o();break;case"ArrowDown":ne.preventDefault(),ne.stopPropagation(),d();break;case"ArrowUp":ne.preventDefault(),ne.stopPropagation(),u();break;case"PageUp":ne.preventDefault(),ne.stopPropagation(),ne.shiftKey?y():f();break;case"PageDown":ne.preventDefault(),ne.stopPropagation(),ne.shiftKey?x():g();break;case"Home":ne.preventDefault(),ne.stopPropagation(),_();break;case"End":ne.preventDefault(),ne.stopPropagation(),b();break}(me=n.onDayKeyDown)===null||me===void 0||me.call(n,s,t,ne)},te={onClick:k,onFocus:A,onBlur:T,onKeyDown:X,onKeyUp:G,onMouseEnter:P,onMouseLeave:I,onPointerEnter:M,onPointerLeave:L,onTouchCancel:z,onTouchEnd:$,onTouchMove:V,onTouchStart:W};return te}function H6s(){var s=$h(),t=KAt(),n=mVe(),r=fVe(),a=j3e(s)?t.selected:WQ(s)?n.selected:KQ(s)?r.selected:void 0;return a}function G6s(s){return Object.values(hN).includes(s)}function W6s(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(G6s(r)){var i=s.classNames["day_".concat(r)];i&&n.push(i)}}),n}function K6s(s,t){var n=al({},s.styles.day);return Object.keys(t).forEach(function(r){var a;n=al(al({},n),(a=s.modifiersStyles)===null||a===void 0?void 0:a[r])}),n}function Y6s(s,t,n){var r,a,i,l=$h(),o=xVe(),c=$6s(s,t),d=V6s(s,c),u=H6s(),h=!!(l.onDayClick||l.mode!=="default");N.useEffect(function(){var P;c.outside||o.focusedDay&&h&&yd(o.focusedDay,s)&&((P=n.current)===null||P===void 0||P.focus())},[o.focusedDay,s,n,h,c.outside]);var m=W6s(l,c).join(" "),f=K6s(l,c),g=!!(c.outside&&!l.showOutsideDays||c.hidden),y=(i=(a=l.components)===null||a===void 0?void 0:a.DayContent)!==null&&i!==void 0?i:g6s,x=e.jsx(y,{date:s,displayMonth:t,activeModifiers:c}),_={style:f,className:m,children:x,role:"gridcell"},b=o.focusTarget&&yd(o.focusTarget,s)&&!c.outside,k=o.focusedDay&&yd(o.focusedDay,s),A=al(al(al({},_),(r={disabled:c.disabled,role:"gridcell"},r["aria-selected"]=c.selected,r.tabIndex=k||b?0:-1,r)),d),T={isButton:h,isHidden:g,activeModifiers:c,selectedDays:u,buttonProps:A,divProps:_};return T}function Z6s(s){var t=N.useRef(null),n=Y6s(s.date,s.displayMonth,t);return n.isHidden?e.jsx("div",{role:"gridcell"}):n.isButton?e.jsx(nke,al({name:"day",ref:t},n.buttonProps)):e.jsx("div",al({},n.divProps))}function X6s(s){var t=s.number,n=s.dates,r=$h(),a=r.onWeekNumberClick,i=r.styles,l=r.classNames,o=r.locale,c=r.labels.labelWeekNumber,d=r.formatters.formatWeekNumber,u=d(Number(t),{locale:o});if(!a)return e.jsx("span",{className:l.weeknumber,style:i.weeknumber,children:u});var h=c(Number(t),{locale:o}),m=function(f){a(t,n,f)};return e.jsx(nke,{name:"week-number","aria-label":h,className:l.weeknumber,style:i.weeknumber,onClick:m,children:u})}function Q6s(s){var t,n,r=$h(),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:Z6s,d=(n=o==null?void 0:o.WeekNumber)!==null&&n!==void 0?n:X6s,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})},Zls(h))})]})}function wit(s,t,n){for(var r=n!=null&&n.ISOWeek?oNt(t):FB(t,n),a=n!=null&&n.ISOWeek?S3(s):lx(s,n),i=Iv(r,a),l=[],o=0;o<=i;o++)l.push(Ad(a,o));var c=l.reduce(function(d,u){var h=n!=null&&n.ISOWeek?Z$e(u):Q$e(u,n),m=d.find(function(f){return f.weekNumber===h});return m?(m.dates.push(u),d):(d.push({weekNumber:h,dates:[u]}),d)},[]);return c}function J6s(s,t){var n=wit(am(s),m_(s),t);if(t!=null&&t.useFixedWeeks){var r=Qls(s,t);if(r<6){var a=n[n.length-1],i=a.dates[a.dates.length-1],l=H4(i,6-r),o=wit(H4(i,1),l,t);n.push.apply(n,o)}}return n}function eMs(s){var t,n,r,a=$h(),i=a.locale,l=a.classNames,o=a.styles,c=a.hideHead,d=a.fixedWeeks,u=a.components,h=a.weekStartsOn,m=a.firstWeekContainsDate,f=a.ISOWeek,g=J6s(s.displayMonth,{useFixedWeeks:!!d,ISOWeek:f,locale:i,weekStartsOn:h,firstWeekContainsDate:m}),y=(t=u==null?void 0:u.Head)!==null&&t!==void 0?t:f6s,x=(n=u==null?void 0:u.Row)!==null&&n!==void 0?n:Q6s,_=(r=u==null?void 0:u.Footer)!==null&&r!==void 0?r:h6s;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:g.map(function(b){return e.jsx(x,{displayMonth:s.displayMonth,dates:b.dates,weekNumber:b.weekNumber},b.weekNumber)})}),e.jsx(_,{displayMonth:s.displayMonth})]})}function tMs(){return!!(typeof window<"u"&&window.document&&window.document.createElement)}var sMs=tMs()?N.useLayoutEffect:N.useEffect,WMe=!1,nMs=0;function jit(){return"react-day-picker-".concat(++nMs)}function rMs(s){var t,n=s??(WMe?jit():null),r=N.useState(n),a=r[0],i=r[1];return sMs(function(){a===null&&i(jit())},[]),N.useEffect(function(){WMe===!1&&(WMe=!0)},[]),(t=s??a)!==null&&t!==void 0?t:void 0}function aMs(s){var t,n,r=$h(),a=r.dir,i=r.classNames,l=r.styles,o=r.components,c=YQ().displayMonths,d=rMs(r.id?"".concat(r.id,"-").concat(s.displayIndex):void 0),u=r.id?"".concat(r.id,"-grid-").concat(s.displayIndex):void 0,h=[i.month],m=l.month,f=s.displayIndex===0,g=s.displayIndex===c.length-1,y=!f&&!g;a==="rtl"&&(t=[f,g],g=t[0],f=t[1]),f&&(h.push(i.caption_start),m=al(al({},m),l.caption_start)),g&&(h.push(i.caption_end),m=al(al({},m),l.caption_end)),y&&(h.push(i.caption_between),m=al(al({},m),l.caption_between));var x=(n=o==null?void 0:o.Caption)!==null&&n!==void 0?n:u6s;return e.jsxs("div",{className:h.join(" "),style:m,children:[e.jsx(x,{id:d,displayMonth:s.displayMonth,displayIndex:s.displayIndex}),e.jsx(eMs,{id:u,"aria-labelledby":d,displayMonth:s.displayMonth})]},s.displayIndex)}function iMs(s){var t=$h(),n=t.classNames,r=t.styles;return e.jsx("div",{className:n.months,style:r.months,children:s.children})}function oMs(s){var t,n,r=s.initialProps,a=$h(),i=xVe(),l=YQ(),o=N.useState(!1),c=o[0],d=o[1];N.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=al(al({},a.styles.root),a.style),m=Object.keys(r).filter(function(g){return g.startsWith("data-")}).reduce(function(g,y){var x;return al(al({},g),(x={},x[y]=r[y],x))},{}),f=(n=(t=r.components)===null||t===void 0?void 0:t.Months)!==null&&n!==void 0?n:iMs;return e.jsx("div",al({className:u.join(" "),style:h,dir:a.dir,id:a.id,nonce:r.nonce,title:r.title,lang:r.lang},m,{children:e.jsx(f,{children:l.displayMonths.map(function(g,y){return e.jsx(aMs,{displayIndex:y,displayMonth:g},y)})})}))}function lMs(s){var t=s.children,n=LEs(s,["children"]);return e.jsx(XEs,{initialProps:n,children:e.jsx(o6s,{children:e.jsx(U6s,{initialProps:n,children:e.jsx(x6s,{initialProps:n,children:e.jsx(b6s,{initialProps:n,children:e.jsx(A6s,{children:e.jsx(B6s,{children:t})})})})})})})}function cMs(s){return e.jsx(lMs,al({},s,{children:e.jsx(oMs,{initialProps:s})}))}function Xv({className:s,classNames:t,showOutsideDays:n=!0,...r}){return e.jsx(cMs,{showOutsideDays:n,className:Ot("p-3",s),classNames:{months:"flex flex-col sm:flex-row space-y-4 sm:space-x-4 sm:space-y-0",month:"space-y-4",caption:"flex justify-center pt-1 relative items-center",caption_label:"text-sm font-medium",nav:"space-x-1 flex items-center",nav_button:Ot(DB({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:Ot(DB({variant:"ghost"}),"h-9 w-9 p-0 font-normal aria-selected:opacity-100"),day_range_end:"day-range-end",day_selected:"bg-primary text-primary-foreground hover:bg-primary hover:text-primary-foreground focus:bg-primary focus:text-primary-foreground",day_today:"bg-accent text-accent-foreground",day_outside:"day-outside text-muted-foreground opacity-50 aria-selected:bg-accent/50 aria-selected:text-muted-foreground aria-selected:opacity-30",day_disabled:"text-muted-foreground opacity-50",day_range_middle:"aria-selected:bg-accent aria-selected:text-accent-foreground",day_hidden:"invisible",...t},components:{IconLeft:({...a})=>e.jsx(Fc,{className:"h-4 w-4"}),IconRight:({...a})=>e.jsx(Qa,{className:"h-4 w-4"})},...r})}Xv.displayName="Calendar";var N3e="Popover",[YAt,QOn]=Um(N3e,[q5]),ZQ=q5(),[dMs,VE]=YAt(N3e),ZAt=s=>{const{__scopePopover:t,children:n,open:r,defaultOpen:a,onOpenChange:i,modal:l=!1}=s,o=ZQ(t),c=N.useRef(null),[d,u]=N.useState(!1),[h,m]=Ng({prop:r,defaultProp:a??!1,onChange:i,caller:N3e});return e.jsx(gQ,{...o,children:e.jsx(dMs,{scope:t,contentId:_g(),triggerRef:c,open:h,onOpenChange:m,onOpenToggle:N.useCallback(()=>m(f=>!f),[m]),hasCustomAnchor:d,onCustomAnchorAdd:N.useCallback(()=>u(!0),[]),onCustomAnchorRemove:N.useCallback(()=>u(!1),[]),modal:l,children:n})})};ZAt.displayName=N3e;var XAt="PopoverAnchor",uMs=N.forwardRef((s,t)=>{const{__scopePopover:n,...r}=s,a=VE(XAt,n),i=ZQ(n),{onCustomAnchorAdd:l,onCustomAnchorRemove:o}=a;return N.useEffect(()=>(l(),()=>o()),[l,o]),e.jsx(J$,{...i,...r,ref:t})});uMs.displayName=XAt;var QAt="PopoverTrigger",JAt=N.forwardRef((s,t)=>{const{__scopePopover:n,...r}=s,a=VE(QAt,n),i=ZQ(n),l=jo(t,a.triggerRef),o=e.jsx(Da.button,{type:"button","aria-haspopup":"dialog","aria-expanded":a.open,"aria-controls":a.contentId,"data-state":rTt(a.open),...r,ref:l,onClick:la(s.onClick,a.onOpenToggle)});return a.hasCustomAnchor?o:e.jsx(J$,{asChild:!0,...i,children:o})});JAt.displayName=QAt;var vVe="PopoverPortal",[hMs,mMs]=YAt(vVe,{forceMount:void 0}),eTt=s=>{const{__scopePopover:t,forceMount:n,children:r,container:a}=s,i=VE(vVe,t);return e.jsx(hMs,{scope:t,forceMount:n,children:e.jsx(Xf,{present:n||i.open,children:e.jsx(Y$,{asChild:!0,container:a,children:r})})})};eTt.displayName=vVe;var YB="PopoverContent",tTt=N.forwardRef((s,t)=>{const n=mMs(YB,s.__scopePopover),{forceMount:r=n.forceMount,...a}=s,i=VE(YB,s.__scopePopover);return e.jsx(Xf,{present:r||i.open,children:i.modal?e.jsx(fMs,{...a,ref:t}):e.jsx(gMs,{...a,ref:t})})});tTt.displayName=YB;var pMs=rE("PopoverContent.RemoveScroll"),fMs=N.forwardRef((s,t)=>{const n=VE(YB,s.__scopePopover),r=N.useRef(null),a=jo(t,r),i=N.useRef(!1);return N.useEffect(()=>{const l=r.current;if(l)return o4e(l)},[]),e.jsx(jQ,{as:pMs,allowPinchZoom:!0,children:e.jsx(sTt,{...s,ref:a,trapFocus:n.open,disableOutsidePointerEvents:!0,onCloseAutoFocus:la(s.onCloseAutoFocus,l=>{var o;l.preventDefault(),i.current||(o=n.triggerRef.current)==null||o.focus()}),onPointerDownOutside:la(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:la(s.onFocusOutside,l=>l.preventDefault(),{checkForDefaultPrevented:!1})})})}),gMs=N.forwardRef((s,t)=>{const n=VE(YB,s.__scopePopover),r=N.useRef(!1),a=N.useRef(!1);return e.jsx(sTt,{...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()}})}),sTt=N.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=VE(YB,n),f=ZQ(n);return r4e(),e.jsx(_Q,{asChild:!0,loop:!0,trapped:r,onMountAutoFocus:a,onUnmountAutoFocus:i,children:e.jsx(TE,{asChild:!0,disableOutsidePointerEvents:l,onInteractOutside:u,onEscapeKeyDown:o,onPointerDownOutside:c,onFocusOutside:d,onDismiss:()=>m.onOpenChange(!1),children:e.jsx(xQ,{"data-state":rTt(m.open),role:"dialog",id:m.contentId,...f,...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)"}})})})}),nTt="PopoverClose",xMs=N.forwardRef((s,t)=>{const{__scopePopover:n,...r}=s,a=VE(nTt,n);return e.jsx(Da.button,{type:"button",...r,ref:t,onClick:la(s.onClick,()=>a.onOpenChange(!1))})});xMs.displayName=nTt;var yMs="PopoverArrow",vMs=N.forwardRef((s,t)=>{const{__scopePopover:n,...r}=s,a=ZQ(n);return e.jsx(yQ,{...a,...r,ref:t})});vMs.displayName=yMs;function rTt(s){return s?"open":"closed"}var bMs=ZAt,_Ms=JAt,wMs=eTt,aTt=tTt;const rc=bMs,ac=_Ms,Zl=N.forwardRef(({className:s,align:t="center",sideOffset:n=4,...r},a)=>e.jsx(wMs,{children:e.jsx(aTt,{ref:a,align:t,sideOffset:n,className:Ot("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})}));Zl.displayName=aTt.displayName;const jMs=RR("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"}}),bVe=N.forwardRef(({className:s,variant:t,...n},r)=>e.jsx("div",{ref:r,role:"alert",className:Ot(jMs({variant:t}),s),...n}));bVe.displayName="Alert";const NMs=N.forwardRef(({className:s,...t},n)=>e.jsx("h5",{ref:n,className:Ot("mb-1 font-medium leading-none tracking-tight",s),...t}));NMs.displayName="AlertTitle";const _Ve=N.forwardRef(({className:s,...t},n)=>e.jsx("div",{ref:n,className:Ot("text-sm [&_p]:leading-relaxed",s),...t}));_Ve.displayName="AlertDescription";function kMs({open:s,onOpenChange:t,imageUrl:n,imageId:r,defaultCaption:a="",swagItemId:i,reelId:l}){const o=as(),{user:c}=Ls(),d=(c==null?void 0:c.id)??null,[u,h]=N.useState(a),[m,f]=N.useState([]),[g,y]=N.useState(null),[x,_]=N.useState("now"),[b,k]=N.useState($tt(Wtt(new Date),1)),[A,T]=N.useState("12"),[P,I]=N.useState("00"),[M,L]=N.useState("PM");N.useEffect(()=>{if(s){h(a),_("now"),f([]);const ge=$tt(Wtt(new Date),1);k(ge);const be=ge.getHours();T(String(be>12?be-12:be===0?12:be)),I("00"),L(be>=12?"PM":"AM")}},[s,a]);const z=()=>{if(!b)return null;let ge=parseInt(A);const be=parseInt(P);return M==="PM"&&ge!==12&&(ge+=12),M==="AM"&&ge===12&&(ge=0),$W(BW(b,ge),be)},{data:$,isLoading:V}=mt({queryKey:["social-accounts-for-post",d],queryFn:async()=>{const{data:{user:ge}}=await H.auth.getUser();if(!ge)return[];const{data:be,error:Se}=await H.from("social_accounts").select("*").eq("user_id",ge.id).eq("is_active",!0).order("platform",{ascending:!0});if(Se)throw Se;return console.log("Fetched social accounts for posting:",be),be},enabled:s,staleTime:0}),W=_t({mutationFn:async({accountId:ge,platform:be})=>{y(ge);const{data:Se,error:Ie}=await H.functions.invoke("social-post",{body:{platform:be,accountId:ge,imageUrl:n,caption:u}});if(Ie)throw Ie;if(Se!=null&&Se.error)throw new Error(Se.error);return Se},onSuccess:ge=>{const be=ge.platform==="facebook"?"Facebook":ge.platform==="instagram"?"Instagram":ge.platform==="linkedin"?"LinkedIn":"Google Business";ie.success(`Posted to ${be}!`)},onError:ge=>{ie.error(`Failed to post: ${ge.message}`)},onSettled:()=>{y(null)}}),G=_t({mutationFn:async({accountId:ge,platform:be,scheduledFor:Se})=>{const{data:{user:Ie}}=await H.auth.getUser();if(!Ie)throw new Error("Not authenticated");const{error:Me}=await H.from("scheduled_posts").insert({user_id:Ie.id,social_account_id:ge,platform:be,image_url:n,caption:u,swag_item_id:i||null,reel_id:l||null,scheduled_for:Se.toISOString(),status:"scheduled"});if(Me)throw Me;return{platform:be}},onSuccess:ge=>{const be=ge.platform==="facebook"?"Facebook":ge.platform==="instagram"?"Instagram":"LinkedIn";ie.success(`Post scheduled for ${be}!`)},onError:ge=>{ie.error(`Failed to schedule: ${ge.message}`)}}),X=async()=>{if(m.length===0){ie.error("Please select at least one account");return}if(x==="schedule"){const ge=z();if(!ge||ge<=new Date){ie.error("Please select a future date and time");return}for(const be of m){const Se=$==null?void 0:$.find(Ie=>Ie.id===be);Se&&await G.mutateAsync({accountId:be,platform:Se.platform,scheduledFor:ge})}o.invalidateQueries({queryKey:["scheduled-posts",d]}),ie.success(`${m.length} post(s) scheduled for ${Js(ge,"PPp")}`)}else for(const ge of m){const be=$==null?void 0:$.find(Se=>Se.id===ge);be&&await W.mutateAsync({accountId:ge,platform:be.platform})}o.invalidateQueries({queryKey:["scheduled-posts",d]}),h(""),f([]),t(!1)},te=ge=>{f(be=>be.includes(ge)?be.filter(Se=>Se!==ge):[...be,ge])},ne=($==null?void 0:$.filter(ge=>ge.platform==="facebook"))||[],me=($==null?void 0:$.filter(ge=>ge.platform==="instagram"))||[],ue=($==null?void 0:$.filter(ge=>ge.platform==="linkedin"))||[],ce=($==null?void 0:$.filter(ge=>ge.platform==="google_business"))||[],ae=(($==null?void 0:$.length)||0)>0,he=W.isPending||G.isPending,xe=Array.from({length:12},(ge,be)=>String(be+1)),ve=["00","15","30","45"];return e.jsx(Bs,{open:s,onOpenChange:t,children:e.jsxs(Fs,{className:"sm:max-w-lg max-h-[90vh] overflow-y-auto",children:[e.jsxs(qs,{children:[e.jsx($s,{children:"Create Social Post"}),e.jsx(Ar,{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(re,{htmlFor:"caption",children:"Caption"}),e.jsx(Ws,{id:"caption",placeholder:"Write a caption for your post...",value:u,onChange:ge=>h(ge.target.value),rows:3}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[u.length,"/2200 characters"]})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsx(re,{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:()=>_("now"),className:Ot("flex-1 px-4 py-2 rounded-md text-sm font-medium transition-all",x==="now"?"bg-background text-foreground shadow-sm":"text-muted-foreground hover:text-foreground"),children:"Post Now"}),e.jsx("button",{type:"button",onClick:()=>_("schedule"),className:Ot("flex-1 px-4 py-2 rounded-md text-sm font-medium transition-all",x==="schedule"?"bg-background text-foreground shadow-sm":"text-muted-foreground hover:text-foreground"),children:"Schedule"})]})]}),x==="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(Xr,{className:"h-4 w-4"}),"Schedule for"]}),e.jsxs("div",{className:"flex flex-col sm:flex-row gap-3",children:[e.jsxs(rc,{children:[e.jsx(ac,{asChild:!0,children:e.jsxs(B,{variant:"outline",className:Ot("justify-start text-left font-normal flex-1",!b&&"text-muted-foreground"),children:[e.jsx(ta,{className:"mr-2 h-4 w-4"}),b?Js(b,"PPP"):e.jsx("span",{children:"Pick a date"})]})}),e.jsx(Zl,{className:"w-auto p-0",align:"start",children:e.jsx(Xv,{mode:"single",selected:b,onSelect:k,disabled:ge=>gee.jsx(nt,{value:ge,children:ge},ge))})]}),e.jsx("span",{className:"text-muted-foreground",children:":"}),e.jsxs(Ns,{value:P,onValueChange:I,children:[e.jsx(ws,{className:"w-[70px]",children:e.jsx(ks,{})}),e.jsx(js,{children:ve.map(ge=>e.jsx(nt,{value:ge,children:ge},ge))})]}),e.jsxs(Ns,{value:M,onValueChange:ge=>L(ge),children:[e.jsx(ws,{className:"w-[70px]",children:e.jsx(ks,{})}),e.jsxs(js,{children:[e.jsx(nt,{value:"AM",children:"AM"}),e.jsx(nt,{value:"PM",children:"PM"})]})]})]})]}),b&&e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Post will be published on ",Js(z()||new Date,"PPP 'at' p")]})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsx(re,{children:"Post to"}),V&&e.jsx("div",{className:"flex items-center justify-center py-4",children:e.jsx(us,{className:"h-6 w-6 animate-spin"})}),!V&&!ae&&e.jsxs(bVe,{children:[e.jsx(Uo,{className:"h-4 w-4"}),e.jsxs(_Ve,{className:"flex flex-col gap-2",children:[e.jsx("span",{children:"No social accounts connected yet."}),e.jsxs(cr,{to:"/social-connections",className:"inline-flex items-center gap-1.5 text-primary hover:underline font-medium",children:[e.jsx(sc,{className:"h-3.5 w-3.5"}),"Connect your Facebook, Instagram & LinkedIn"]})]})]}),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(Kf,{className:"h-4 w-4 text-blue-600"})," Facebook"]}),ne.map(ge=>e.jsxs("label",{className:"flex items-center gap-3 rounded-lg border p-3 cursor-pointer hover:bg-muted/50 transition-colors",children:[e.jsx(Bi,{checked:m.includes(ge.id),onCheckedChange:()=>te(ge.id),disabled:g===ge.id}),e.jsxs(Ua,{className:"h-8 w-8",children:[e.jsx(Gi,{src:ge.profile_picture_url||""}),e.jsx(qa,{children:e.jsx(Kf,{className:"h-4 w-4"})})]}),e.jsx("span",{className:"flex-1 text-sm font-medium",children:ge.page_name||ge.platform_username}),g===ge.id&&e.jsx(us,{className:"h-4 w-4 animate-spin"})]},ge.id))]}),me.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(dm,{className:"h-4 w-4 text-pink-600"})," Instagram"]}),me.map(ge=>e.jsxs("label",{className:"flex items-center gap-3 rounded-lg border p-3 cursor-pointer hover:bg-muted/50 transition-colors",children:[e.jsx(Bi,{checked:m.includes(ge.id),onCheckedChange:()=>te(ge.id),disabled:g===ge.id}),e.jsxs(Ua,{className:"h-8 w-8",children:[e.jsx(Gi,{src:ge.profile_picture_url||""}),e.jsx(qa,{children:e.jsx(dm,{className:"h-4 w-4"})})]}),e.jsxs("span",{className:"flex-1 text-sm font-medium",children:["@",ge.platform_username]}),g===ge.id&&e.jsx(us,{className:"h-4 w-4 animate-spin"})]},ge.id))]}),ue.length>0&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs("p",{className:"text-sm font-medium text-muted-foreground flex items-center gap-2",children:[e.jsx(W0,{className:"h-4 w-4 text-blue-700"})," LinkedIn"]}),ue.map(ge=>e.jsxs("label",{className:"flex items-center gap-3 rounded-lg border p-3 cursor-pointer hover:bg-muted/50 transition-colors",children:[e.jsx(Bi,{checked:m.includes(ge.id),onCheckedChange:()=>te(ge.id),disabled:g===ge.id}),e.jsxs(Ua,{className:"h-8 w-8",children:[e.jsx(Gi,{src:ge.profile_picture_url||""}),e.jsx(qa,{children:e.jsx(W0,{className:"h-4 w-4"})})]}),e.jsx("span",{className:"flex-1 text-sm font-medium",children:ge.platform_username}),g===ge.id&&e.jsx(us,{className:"h-4 w-4 animate-spin"})]},ge.id))]}),ce.length>0&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs("p",{className:"text-sm font-medium text-muted-foreground flex items-center gap-2",children:[e.jsx(ii,{className:"h-4 w-4 text-red-600"})," Google Business"]}),ce.map(ge=>e.jsxs("label",{className:"flex items-center gap-3 rounded-lg border p-3 cursor-pointer hover:bg-muted/50 transition-colors",children:[e.jsx(Bi,{checked:m.includes(ge.id),onCheckedChange:()=>te(ge.id),disabled:g===ge.id}),e.jsxs(Ua,{className:"h-8 w-8",children:[e.jsx(Gi,{src:ge.profile_picture_url||""}),e.jsx(qa,{children:e.jsx(ii,{className:"h-4 w-4"})})]}),e.jsx("span",{className:"flex-1 text-sm font-medium",children:ge.page_name||ge.platform_username}),g===ge.id&&e.jsx(us,{className:"h-4 w-4 animate-spin"})]},ge.id))]})]})]}),e.jsxs(Cr,{children:[e.jsx(B,{variant:"outline",onClick:()=>t(!1),children:"Cancel"}),e.jsxs(B,{onClick:X,disabled:m.length===0||he,className:"gap-2",children:[he?e.jsx(us,{className:"h-4 w-4 animate-spin"}):x==="schedule"?e.jsx(ta,{className:"h-4 w-4"}):e.jsx(Rr,{className:"h-4 w-4"}),x==="schedule"?`Schedule ${m.length} post${m.length!==1?"s":""}`:`Post to ${m.length} account${m.length!==1?"s":""}`]})]})]})})}function SMs(){const{user:s}=Ls(),t=(s==null?void 0:s.id)??null,n=as(),[r,a]=N.useState(void 0),[i,l]=N.useState("all"),[o,c]=N.useState(null),[d,u]=N.useState(""),[h,m]=N.useState(void 0),[f,g]=N.useState("12"),[y,x]=N.useState("00"),[_,b]=N.useState("PM"),{data:k=[],isLoading:A}=mt({queryKey:["scheduled-posts",t],enabled:!!t,queryFn:async()=>{const{data:ce,error:ae}=await H.from("scheduled_posts").select(` *, social_accounts ( page_name, platform_username, profile_picture_url ) `).eq("user_id",t).order("scheduled_for",{ascending:!1});if(ae)throw ae;return ce}}),T=k.filter(ce=>{if(i!=="all"&&ce.status!==i)return!1;if(r&&ce.scheduled_for){const ae=new Date(ce.scheduled_for);if(!yd(ae,r))return!1}return!0}),P=k.filter(ce=>ce.scheduled_for).map(ce=>ey(new Date(ce.scheduled_for))),I=_t({mutationFn:async ce=>{const{error:ae}=await H.from("scheduled_posts").update({caption:ce.caption,scheduled_for:ce.scheduled_for}).eq("id",ce.id);if(ae)throw ae},onSuccess:()=>{ie.success("Post updated!"),n.invalidateQueries({queryKey:["scheduled-posts",t]}),c(null)},onError:ce=>{ie.error(`Failed to update: ${ce.message}`)}}),M=_t({mutationFn:async ce=>{const{error:ae}=await H.from("scheduled_posts").update({status:"cancelled"}).eq("id",ce);if(ae)throw ae},onSuccess:()=>{ie.success("Post cancelled"),n.invalidateQueries({queryKey:["scheduled-posts",t]})},onError:ce=>{ie.error(`Failed to cancel: ${ce.message}`)}}),L=_t({mutationFn:async ce=>{const{error:ae}=await H.from("scheduled_posts").delete().eq("id",ce);if(ae)throw ae},onSuccess:()=>{ie.success("Post deleted"),n.invalidateQueries({queryKey:["scheduled-posts",t]})},onError:ce=>{ie.error(`Failed to delete: ${ce.message}`)}}),z=_t({mutationFn:async ce=>{const{data:ae,error:he}=await H.functions.invoke("social-post",{body:{platform:ce.platform,accountId:ce.social_account_id,imageUrl:ce.image_url,caption:ce.caption}});if(he)throw he;if(ae!=null&&ae.error)throw new Error(ae.error);return await H.from("scheduled_posts").update({status:"posted",posted_at:new Date().toISOString(),post_id:ae.postId}).eq("id",ce.id),ae},onSuccess:ce=>{const ae=ce.platform==="facebook"?"Facebook":ce.platform==="instagram"?"Instagram":"LinkedIn";ie.success(`Posted to ${ae}!`),n.invalidateQueries({queryKey:["scheduled-posts",t]})},onError:ce=>{ie.error(`Failed to post: ${ce.message}`)}}),$=ce=>{if(c(ce),u(ce.caption||""),ce.scheduled_for){const ae=new Date(ce.scheduled_for);m(ae);const he=ae.getHours();g(String(he>12?he-12:he===0?12:he)),x(String(ae.getMinutes()).padStart(2,"0")),b(he>=12?"PM":"AM")}},V=()=>{if(!o||!h)return;let ce=parseInt(f);const ae=parseInt(y);_==="PM"&&ce!==12&&(ce+=12),_==="AM"&&ce===12&&(ce=0);const he=$W(BW(h,ce),ae);I.mutate({id:o.id,caption:d,scheduled_for:he.toISOString()})},W=ce=>{switch(ce){case"facebook":return e.jsx(Kf,{className:"h-4 w-4 text-blue-600"});case"instagram":return e.jsx(dm,{className:"h-4 w-4 text-pink-600"});case"linkedin":return e.jsx(W0,{className:"h-4 w-4 text-blue-700"});default:return null}},G=ce=>{switch(ce){case"scheduled":return e.jsxs(We,{variant:"secondary",className:"gap-1",children:[e.jsx(Xr,{className:"h-3 w-3"}),"Scheduled"]});case"posted":return e.jsxs(We,{variant:"default",className:"gap-1 bg-green-600",children:[e.jsx(Po,{className:"h-3 w-3"}),"Posted"]});case"failed":return e.jsxs(We,{variant:"destructive",className:"gap-1",children:[e.jsx(Nu,{className:"h-3 w-3"}),"Failed"]});case"cancelled":return e.jsxs(We,{variant:"outline",className:"gap-1 text-muted-foreground",children:[e.jsx(Uo,{className:"h-3 w-3"}),"Cancelled"]});default:return e.jsx(We,{variant:"outline",children:ce})}},X=Array.from({length:12},(ce,ae)=>String(ae+1)),te=["00","15","30","45"],ne=k.filter(ce=>ce.status==="scheduled").length,me=k.filter(ce=>ce.status==="posted").length,ue=k.filter(ce=>ce.status==="scheduled"&&ce.scheduled_for&&Jls(new Date(ce.scheduled_for))).length;return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4",children:[e.jsxs(_e,{className:"p-4",children:[e.jsx("div",{className:"text-2xl font-bold",children:ne}),e.jsx("div",{className:"text-sm text-muted-foreground",children:"Scheduled"})]}),e.jsxs(_e,{className:"p-4",children:[e.jsx("div",{className:"text-2xl font-bold",children:ue}),e.jsx("div",{className:"text-sm text-muted-foreground",children:"Upcoming"})]}),e.jsxs(_e,{className:"p-4",children:[e.jsx("div",{className:"text-2xl font-bold",children:me}),e.jsx("div",{className:"text-sm text-muted-foreground",children:"Posted"})]}),e.jsxs(_e,{className:"p-4",children:[e.jsx("div",{className:"text-2xl font-bold",children:k.length}),e.jsx("div",{className:"text-sm text-muted-foreground",children:"Total"})]})]}),e.jsxs("div",{className:"flex flex-col lg:flex-row gap-6",children:[e.jsxs(_e,{className:"p-4",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-4",children:[e.jsx(ld,{className:"h-5 w-5"}),e.jsx("h3",{className:"font-semibold",children:"Calendar"})]}),e.jsx(Xv,{mode:"single",selected:r,onSelect:a,className:Ot("pointer-events-auto"),modifiers:{hasPost:P},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(cj,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("div",{className:"flex flex-wrap gap-1",children:["all","scheduled","posted","failed","cancelled"].map(ce=>e.jsx(B,{variant:i===ce?"default":"outline",size:"sm",onClick:()=>l(ce),className:"capitalize",children:ce},ce))})]}),A&&e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsx(us,{className:"h-8 w-8 animate-spin text-muted-foreground"})}),!A&&T.length===0&&e.jsxs(_e,{className:"p-8 text-center",children:[e.jsx(ta,{className:"h-12 w-12 mx-auto text-muted-foreground/50 mb-4"}),e.jsx("h3",{className:"font-medium mb-2",children:"No posts found"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:r?`No posts scheduled for ${Js(r,"PPP")}`:"Schedule a post from Social Swag to get started!"})]}),e.jsx("div",{className:"space-y-4",children:T.map(ce=>{var ae,he;return e.jsx(_e,{className:"overflow-hidden",children:e.jsxs("div",{className:"flex flex-col sm:flex-row",children:[e.jsx("div",{className:"sm:w-32 h-32 sm:h-auto bg-muted flex-shrink-0",children:e.jsx("img",{src:ce.image_url,alt:"Post preview",className:"w-full h-full object-cover"})}),e.jsxs(De,{className:"flex-1 p-4",children:[e.jsxs("div",{className:"flex flex-wrap items-start justify-between gap-2 mb-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[W(ce.platform),e.jsx("span",{className:"font-medium",children:((ae=ce.social_accounts)==null?void 0:ae.page_name)||((he=ce.social_accounts)==null?void 0:he.platform_username)||"Unknown"}),G(ce.status)]}),e.jsxs("div",{className:"flex items-center gap-1",children:[ce.status==="scheduled"&&e.jsxs(fN,{children:[e.jsxs(wu,{children:[e.jsx(ju,{asChild:!0,children:e.jsx(B,{variant:"ghost",size:"icon",onClick:()=>$(ce),children:e.jsx(Ja,{className:"h-4 w-4"})})}),e.jsx(nu,{children:"Edit post"})]}),e.jsxs(wu,{children:[e.jsx(ju,{asChild:!0,children:e.jsx(B,{variant:"ghost",size:"icon",onClick:()=>z.mutate(ce),disabled:z.isPending,children:z.isPending?e.jsx(us,{className:"h-4 w-4 animate-spin"}):e.jsx(Rr,{className:"h-4 w-4"})})}),e.jsx(nu,{children:"Post now"})]}),e.jsxs(Fl,{children:[e.jsx(Gf,{asChild:!0,children:e.jsx(B,{variant:"ghost",size:"icon",className:"text-destructive",children:e.jsx(qn,{className:"h-4 w-4"})})}),e.jsxs(kl,{children:[e.jsxs(Sl,{children:[e.jsx(Al,{children:"Cancel this scheduled post?"}),e.jsx(Tl,{children:"This will cancel the post. You can delete it entirely or keep it in your history."})]}),e.jsxs(Cl,{children:[e.jsx(El,{children:"Keep"}),e.jsx(wl,{onClick:()=>M.mutate(ce.id),className:"bg-amber-600 hover:bg-amber-700",children:"Cancel Post"}),e.jsx(wl,{onClick:()=>L.mutate(ce.id),className:"bg-destructive hover:bg-destructive/90",children:"Delete"})]})]})]})]}),(ce.status==="posted"||ce.status==="cancelled"||ce.status==="failed")&&e.jsxs(Fl,{children:[e.jsx(Gf,{asChild:!0,children:e.jsx(B,{variant:"ghost",size:"icon",className:"text-destructive",children:e.jsx(qn,{className:"h-4 w-4"})})}),e.jsxs(kl,{children:[e.jsxs(Sl,{children:[e.jsx(Al,{children:"Delete this post?"}),e.jsx(Tl,{children:"This will permanently remove this post from your history."})]}),e.jsxs(Cl,{children:[e.jsx(El,{children:"Cancel"}),e.jsx(wl,{onClick:()=>L.mutate(ce.id),className:"bg-destructive hover:bg-destructive/90",children:"Delete"})]})]})]})]})]}),ce.caption&&e.jsx("p",{className:"text-sm text-muted-foreground line-clamp-2 mb-2",children:ce.caption}),e.jsxs("div",{className:"text-xs text-muted-foreground flex items-center gap-1",children:[e.jsx(Xr,{className:"h-3 w-3"}),ce.status==="posted"&&ce.posted_at?`Posted ${Js(new Date(ce.posted_at),"PPp")}`:ce.scheduled_for?`Scheduled for ${Js(new Date(ce.scheduled_for),"PPp")}`:"Not scheduled"]}),ce.status==="failed"&&ce.error_message&&e.jsxs("p",{className:"text-xs text-destructive mt-2",children:["Error: ",ce.error_message]})]})]})},ce.id)})})]})]}),e.jsx(Bs,{open:!!o,onOpenChange:ce=>!ce&&c(null),children:e.jsxs(Fs,{className:"max-w-lg",children:[e.jsxs(qs,{children:[e.jsx($s,{children:"Edit Scheduled Post"}),e.jsx(Ar,{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(re,{children:"Caption"}),e.jsx(Ws,{value:d,onChange:ce=>u(ce.target.value),rows:3})]}),e.jsxs("div",{className:"space-y-3 p-4 border rounded-lg",children:[e.jsx(re,{children:"Schedule for"}),e.jsxs("div",{className:"flex flex-col sm:flex-row gap-3",children:[e.jsxs(rc,{children:[e.jsx(ac,{asChild:!0,children:e.jsxs(B,{variant:"outline",className:Ot("justify-start text-left font-normal flex-1",!h&&"text-muted-foreground"),children:[e.jsx(ta,{className:"mr-2 h-4 w-4"}),h?Js(h,"PPP"):"Pick a date"]})}),e.jsx(Zl,{className:"w-auto p-0",align:"start",children:e.jsx(Xv,{mode:"single",selected:h,onSelect:m,disabled:ce=>cee.jsx(nt,{value:ce,children:ce},ce))})]}),e.jsx("span",{className:"text-muted-foreground",children:":"}),e.jsxs(Ns,{value:y,onValueChange:x,children:[e.jsx(ws,{className:"w-[70px]",children:e.jsx(ks,{})}),e.jsx(js,{children:te.map(ce=>e.jsx(nt,{value:ce,children:ce},ce))})]}),e.jsxs(Ns,{value:_,onValueChange:ce=>b(ce),children:[e.jsx(ws,{className:"w-[70px]",children:e.jsx(ks,{})}),e.jsxs(js,{children:[e.jsx(nt,{value:"AM",children:"AM"}),e.jsx(nt,{value:"PM",children:"PM"})]})]})]})]})]})]}),e.jsxs(Cr,{children:[e.jsx(B,{variant:"outline",onClick:()=>c(null),children:"Cancel"}),e.jsxs(B,{onClick:V,disabled:I.isPending,children:[I.isPending?e.jsx(us,{className:"h-4 w-4 animate-spin mr-2"}):null,"Save Changes"]})]})]})})]})}function xse(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 iTt={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 xse=="function"&&xse;if(!u&&h)return h(d,!0);if(o)return o(d,!0);var m=new Error("Cannot find module '"+d+"'");throw m.code="MODULE_NOT_FOUND",m}var f=a[d]={exports:{}};r[d][0].call(f.exports,function(g){var y=r[d][1][g];return l(y||g)},f,f.exports,n,r,a,i)}return a[d].exports}for(var o=typeof xse=="function"&&xse,c=0;c>2,f=(3&d)<<4|u>>4,g=1>6:64,y=2>4,u=(15&m)<<4|(f=o.indexOf(c.charAt(y++)))>>2,h=(3&f)<<6|(g=o.indexOf(c.charAt(y++))),b[x++]=d,f!==64&&(b[x++]=u),g!==64&&(b[x++]=h);return b}},{"./support":30,"./utils":32}],2:[function(n,r,a){var i=n("./external"),l=n("./stream/DataWorker"),o=n("./stream/Crc32Probe"),c=n("./stream/DataLengthProbe");function d(u,h,m,f,g){this.compressedSize=u,this.uncompressedSize=h,this.crc32=m,this.compression=f,this.compressedContent=g}d.prototype={getContentWorker:function(){var u=new l(i.Promise.resolve(this.compressedContent)).pipe(this.compression.uncompressWorker()).pipe(new c("data_length")),h=this;return u.on("end",function(){if(this.streamInfo.data_length!==h.uncompressedSize)throw new Error("Bug : uncompressed data size mismatch")}),u},getCompressedWorker:function(){return new l(i.Promise.resolve(this.compressedContent)).withStreamInfo("compressedSize",this.compressedSize).withStreamInfo("uncompressedSize",this.uncompressedSize).withStreamInfo("crc32",this.crc32).withStreamInfo("compression",this.compression)}},d.createWorkerFrom=function(u,h,m){return u.pipe(new o).pipe(new c("uncompressedSize")).pipe(h.compressWorker(m)).pipe(new c("compressedSize")).withStreamInfo("compression",h)},r.exports=d},{"./external":6,"./stream/Crc32Probe":25,"./stream/DataLengthProbe":26,"./stream/DataWorker":27}],3:[function(n,r,a){var i=n("./stream/GenericWorker");a.STORE={magic:"\0\0",compressWorker:function(){return new i("STORE compression")},uncompressWorker:function(){return new i("STORE decompression")}},a.DEFLATE=n("./flate")},{"./flate":7,"./stream/GenericWorker":28}],4:[function(n,r,a){var i=n("./utils"),l=function(){for(var o,c=[],d=0;d<256;d++){o=d;for(var u=0;u<8;u++)o=1&o?3988292384^o>>>1:o>>>1;c[d]=o}return c}();r.exports=function(o,c){return o!==void 0&&o.length?i.getTypeOf(o)!=="string"?function(d,u,h,m){var f=l,g=m+h;d^=-1;for(var y=m;y>>8^f[255&(d^u[y])];return-1^d}(0|c,o,o.length,0):function(d,u,h,m){var f=l,g=m+h;d^=-1;for(var y=m;y>>8^f[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(f,g){var y,x="";for(y=0;y>>=8;return x}function l(f,g,y,x,_,b){var k,A,T=f.file,P=f.compression,I=b!==d.utf8encode,M=o.transformTo("string",b(T.name)),L=o.transformTo("string",d.utf8encode(T.name)),z=T.comment,$=o.transformTo("string",b(z)),V=o.transformTo("string",d.utf8encode(z)),W=L.length!==T.name.length,G=V.length!==z.length,X="",te="",ne="",me=T.dir,ue=T.date,ce={crc32:0,compressedSize:0,uncompressedSize:0};g&&!y||(ce.crc32=f.crc32,ce.compressedSize=f.compressedSize,ce.uncompressedSize=f.uncompressedSize);var ae=0;g&&(ae|=8),I||!W&&!G||(ae|=2048);var he=0,xe=0;me&&(he|=16),_==="UNIX"?(xe=798,he|=function(ge,be){var Se=ge;return ge||(Se=be?16893:33204),(65535&Se)<<16}(T.unixPermissions,me)):(xe=20,he|=function(ge){return 63&(ge||0)}(T.dosPermissions)),k=ue.getUTCHours(),k<<=6,k|=ue.getUTCMinutes(),k<<=5,k|=ue.getUTCSeconds()/2,A=ue.getUTCFullYear()-1980,A<<=4,A|=ue.getUTCMonth()+1,A<<=5,A|=ue.getUTCDate(),W&&(te=i(1,1)+i(u(M),4)+L,X+="up"+i(te.length,2)+te),G&&(ne=i(1,1)+i(u($),4)+V,X+="uc"+i(ne.length,2)+ne);var ve="";return ve+=` \0`,ve+=i(ae,2),ve+=P.magic,ve+=i(k,2),ve+=i(A,2),ve+=i(ce.crc32,4),ve+=i(ce.compressedSize,4),ve+=i(ce.uncompressedSize,4),ve+=i(M.length,2),ve+=i(X.length,2),{fileRecord:h.LOCAL_FILE_HEADER+ve+M+X,dirRecord:h.CENTRAL_FILE_HEADER+i(xe,2)+ve+i($.length,2)+"\0\0\0\0"+i(he,4)+i(x,4)+M+X+$}}var o=n("../utils"),c=n("../stream/GenericWorker"),d=n("../utf8"),u=n("../crc32"),h=n("../signature");function m(f,g,y,x){c.call(this,"ZipFileWorker"),this.bytesWritten=0,this.zipComment=g,this.zipPlatform=y,this.encodeFileName=x,this.streamFiles=f,this.accumulate=!1,this.contentBuffer=[],this.dirRecords=[],this.currentSourceOffset=0,this.entriesCount=0,this.currentFile=null,this._sources=[]}o.inherits(m,c),m.prototype.push=function(f){var g=f.meta.percent||0,y=this.entriesCount,x=this._sources.length;this.accumulate?this.contentBuffer.push(f):(this.bytesWritten+=f.data.length,c.prototype.push.call(this,{data:f.data,meta:{currentFile:this.currentFile,percent:y?(g+100*(y-x-1))/y:100}}))},m.prototype.openedSource=function(f){this.currentSourceOffset=this.bytesWritten,this.currentFile=f.file.name;var g=this.streamFiles&&!f.file.dir;if(g){var y=l(f,g,!1,this.currentSourceOffset,this.zipPlatform,this.encodeFileName);this.push({data:y.fileRecord,meta:{percent:0}})}else this.accumulate=!0},m.prototype.closedSource=function(f){this.accumulate=!1;var g=this.streamFiles&&!f.file.dir,y=l(f,g,!0,this.currentSourceOffset,this.zipPlatform,this.encodeFileName);if(this.dirRecords.push(y.dirRecord),g)this.push({data:function(x){return h.DATA_DESCRIPTOR+i(x.crc32,4)+i(x.compressedSize,4)+i(x.uncompressedSize,4)}(f),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 f=this.bytesWritten,g=0;g=this.index;c--)d=(d<<8)+this.byteAt(c);return this.index+=o,d},readString:function(o){return i.transformTo("string",this.readData(o))},readData:function(){},lastIndexOfSignature:function(){},readAndCheckSignature:function(){},readDate:function(){var o=this.readInt(4);return new Date(Date.UTC(1980+(o>>25&127),(o>>21&15)-1,o>>16&31,o>>11&31,o>>5&63,(31&o)<<1))}},r.exports=l},{"../utils":32}],19:[function(n,r,a){var i=n("./Uint8ArrayReader");function l(o){i.call(this,o)}n("../utils").inherits(l,i),l.prototype.readData=function(o){this.checkOffset(o);var c=this.data.slice(this.zero+this.index,this.zero+this.index+o);return this.index+=o,c},r.exports=l},{"../utils":32,"./Uint8ArrayReader":21}],20:[function(n,r,a){var i=n("./DataReader");function l(o){i.call(this,o)}n("../utils").inherits(l,i),l.prototype.byteAt=function(o){return this.data.charCodeAt(this.zero+o)},l.prototype.lastIndexOfSignature=function(o){return this.data.lastIndexOf(o)-this.zero},l.prototype.readAndCheckSignature=function(o){return o===this.readData(4)},l.prototype.readData=function(o){this.checkOffset(o);var c=this.data.slice(this.zero+this.index,this.zero+this.index+o);return this.index+=o,c},r.exports=l},{"../utils":32,"./DataReader":18}],21:[function(n,r,a){var i=n("./ArrayReader");function l(o){i.call(this,o)}n("../utils").inherits(l,i),l.prototype.readData=function(o){if(this.checkOffset(o),o===0)return new Uint8Array(0);var c=this.data.subarray(this.zero+this.index,this.zero+this.index+o);return this.index+=o,c},r.exports=l},{"../utils":32,"./ArrayReader":17}],22:[function(n,r,a){var i=n("../utils"),l=n("../support"),o=n("./ArrayReader"),c=n("./StringReader"),d=n("./NodeBufferReader"),u=n("./Uint8ArrayReader");r.exports=function(h){var m=i.getTypeOf(h);return i.checkSupport(m),m!=="string"||l.uint8array?m==="nodebuffer"?new d(h):l.uint8array?new u(i.transformTo("uint8array",h)):new o(i.transformTo("array",h)):new c(h)}},{"../support":30,"../utils":32,"./ArrayReader":17,"./NodeBufferReader":19,"./StringReader":20,"./Uint8ArrayReader":21}],23:[function(n,r,a){a.LOCAL_FILE_HEADER="PK",a.CENTRAL_FILE_HEADER="PK",a.CENTRAL_DIRECTORY_END="PK",a.ZIP64_CENTRAL_DIRECTORY_LOCATOR="PK\x07",a.ZIP64_CENTRAL_DIRECTORY_END="PK",a.DATA_DESCRIPTOR="PK\x07\b"},{}],24:[function(n,r,a){var i=n("./GenericWorker"),l=n("../utils");function o(c){i.call(this,"ConvertWorker to "+c),this.destType=c}l.inherits(o,i),o.prototype.processChunk=function(c){this.push({data:l.transformTo(this.destType,c.data),meta:c.meta})},r.exports=o},{"../utils":32,"./GenericWorker":28}],25:[function(n,r,a){var i=n("./GenericWorker"),l=n("../crc32");function o(){i.call(this,"Crc32Probe"),this.withStreamInfo("crc32",0)}n("../utils").inherits(o,i),o.prototype.processChunk=function(c){this.streamInfo.crc32=l(c.data,this.streamInfo.crc32||0),this.push(c)},r.exports=o},{"../crc32":4,"../utils":32,"./GenericWorker":28}],26:[function(n,r,a){var i=n("../utils"),l=n("./GenericWorker");function o(c){l.call(this,"DataLengthProbe for "+c),this.propName=c,this.withStreamInfo(c,0)}i.inherits(o,l),o.prototype.processChunk=function(c){if(c){var d=this.streamInfo[this.propName]||0;this.streamInfo[this.propName]=d+c.data.length}l.prototype.processChunk.call(this,c)},r.exports=o},{"../utils":32,"./GenericWorker":28}],27:[function(n,r,a){var i=n("../utils"),l=n("./GenericWorker");function o(c){l.call(this,"DataWorker");var d=this;this.dataIsReady=!1,this.index=0,this.max=0,this.data=null,this.type="",this._tickScheduled=!1,c.then(function(u){d.dataIsReady=!0,d.data=u,d.max=u&&u.length||0,d.type=i.getTypeOf(u),d.isPaused||d._tickAndRepeat()},function(u){d.error(u)})}i.inherits(o,l),o.prototype.cleanUp=function(){l.prototype.cleanUp.call(this),this.data=null},o.prototype.resume=function(){return!!l.prototype.resume.call(this)&&(!this._tickScheduled&&this.dataIsReady&&(this._tickScheduled=!0,i.delay(this._tickAndRepeat,[],this)),!0)},o.prototype._tickAndRepeat=function(){this._tickScheduled=!1,this.isPaused||this.isFinished||(this._tick(),this.isFinished||(i.delay(this._tickAndRepeat,[],this),this._tickScheduled=!0))},o.prototype._tick=function(){if(this.isPaused||this.isFinished)return!1;var c=null,d=Math.min(this.max,this.index+16384);if(this.index>=this.max)return this.end();switch(this.type){case"string":c=this.data.substring(this.index,d);break;case"uint8array":c=this.data.subarray(this.index,d);break;case"array":case"nodebuffer":c=this.data.slice(this.index,d)}return this.index=d,this.push({data:c,meta:{percent:this.max?this.index/this.max*100:0}})},r.exports=o},{"../utils":32,"./GenericWorker":28}],28:[function(n,r,a){function i(l){this.name=l||"default",this.streamInfo={},this.generatedError=null,this.extraStreamInfo={},this.isPaused=!0,this.isFinished=!1,this.isLocked=!1,this._listeners={data:[],end:[],error:[]},this.previous=null}i.prototype={push:function(l){this.emit("data",l)},end:function(){if(this.isFinished)return!1;this.flush();try{this.emit("end"),this.cleanUp(),this.isFinished=!0}catch(l){this.emit("error",l)}return!0},error:function(l){return!this.isFinished&&(this.isPaused?this.generatedError=l:(this.isFinished=!0,this.emit("error",l),this.previous&&this.previous.error(l),this.cleanUp()),!0)},on:function(l,o){return this._listeners[l].push(o),this},cleanUp:function(){this.streamInfo=this.generatedError=this.extraStreamInfo=null,this._listeners=[]},emit:function(l,o){if(this._listeners[l])for(var c=0;c "+l:l}},r.exports=i},{}],29:[function(n,r,a){var i=n("../utils"),l=n("./ConvertWorker"),o=n("./GenericWorker"),c=n("../base64"),d=n("../support"),u=n("../external"),h=null;if(d.nodestream)try{h=n("../nodejs/NodejsStreamOutputAdapter")}catch{}function m(g,y){return new u.Promise(function(x,_){var b=[],k=g._internalType,A=g._outputType,T=g._mimeType;g.on("data",function(P,I){b.push(P),y&&y(I)}).on("error",function(P){b=[],_(P)}).on("end",function(){try{var P=function(I,M,L){switch(I){case"blob":return i.newBlob(i.transformTo("arraybuffer",M),L);case"base64":return c.encode(M);default:return i.transformTo(I,M)}}(A,function(I,M){var L,z=0,$=null,V=0;for(L=0;L"u")a.blob=!1;else{var i=new ArrayBuffer(0);try{a.blob=new Blob([i],{type:"application/zip"}).size===0}catch{try{var l=new(self.BlobBuilder||self.WebKitBlobBuilder||self.MozBlobBuilder||self.MSBlobBuilder);l.append(i),a.blob=l.getBlob("application/zip").size===0}catch{a.blob=!1}}}try{a.nodestream=!!n("readable-stream").Readable}catch{a.nodestream=!1}},{"readable-stream":16}],31:[function(n,r,a){for(var i=n("./utils"),l=n("./support"),o=n("./nodejsUtils"),c=n("./stream/GenericWorker"),d=new Array(256),u=0;u<256;u++)d[u]=252<=u?6:248<=u?5:240<=u?4:224<=u?3:192<=u?2:1;d[254]=d[254]=1;function h(){c.call(this,"utf-8 decode"),this.leftOver=null}function m(){c.call(this,"utf-8 encode")}a.utf8encode=function(f){return l.nodebuffer?o.newBufferFrom(f,"utf-8"):function(g){var y,x,_,b,k,A=g.length,T=0;for(b=0;b>>6:(x<65536?y[k++]=224|x>>>12:(y[k++]=240|x>>>18,y[k++]=128|x>>>12&63),y[k++]=128|x>>>6&63),y[k++]=128|63&x);return y}(f)},a.utf8decode=function(f){return l.nodebuffer?i.transformTo("nodebuffer",f).toString("utf-8"):function(g){var y,x,_,b,k=g.length,A=new Array(2*k);for(y=x=0;y>10&1023,A[x++]=56320|1023&_)}return A.length!==x&&(A.subarray?A=A.subarray(0,x):A.length=x),i.applyFromCharCode(A)}(f=i.transformTo(l.uint8array?"uint8array":"array",f))},i.inherits(h,c),h.prototype.processChunk=function(f){var g=i.transformTo(l.uint8array?"uint8array":"array",f.data);if(this.leftOver&&this.leftOver.length){if(l.uint8array){var y=g;(g=new Uint8Array(y.length+this.leftOver.length)).set(this.leftOver,0),g.set(y,this.leftOver.length)}else g=this.leftOver.concat(g);this.leftOver=null}var x=function(b,k){var A;for((k=k||b.length)>b.length&&(k=b.length),A=k-1;0<=A&&(192&b[A])==128;)A--;return A<0||A===0?k:A+d[b[A]]>k?A:k}(g),_=g;x!==g.length&&(l.uint8array?(_=g.subarray(0,x),this.leftOver=g.subarray(x,g.length)):(_=g.slice(0,x),this.leftOver=g.slice(x,g.length))),this.push({data:a.utf8decode(_),meta:f.meta})},h.prototype.flush=function(){this.leftOver&&this.leftOver.length&&(this.push({data:a.utf8decode(this.leftOver),meta:{}}),this.leftOver=null)},a.Utf8DecodeWorker=h,i.inherits(m,c),m.prototype.processChunk=function(f){this.push({data:a.utf8encode(f.data),meta:f.meta})},a.Utf8EncodeWorker=m},{"./nodejsUtils":14,"./stream/GenericWorker":28,"./support":30,"./utils":32}],32:[function(n,r,a){var i=n("./support"),l=n("./base64"),o=n("./nodejsUtils"),c=n("./external");function d(y){return y}function u(y,x){for(var _=0;_>8;this.dir=!!(16&this.externalFileAttributes),f==0&&(this.dosPermissions=63&this.externalFileAttributes),f==3&&(this.unixPermissions=this.externalFileAttributes>>16&65535),this.dir||this.fileNameStr.slice(-1)!=="/"||(this.dir=!0)},parseZIP64ExtraField:function(){if(this.extraFields[1]){var f=i(this.extraFields[1].value);this.uncompressedSize===l.MAX_VALUE_32BITS&&(this.uncompressedSize=f.readInt(8)),this.compressedSize===l.MAX_VALUE_32BITS&&(this.compressedSize=f.readInt(8)),this.localHeaderOffset===l.MAX_VALUE_32BITS&&(this.localHeaderOffset=f.readInt(8)),this.diskNumberStart===l.MAX_VALUE_32BITS&&(this.diskNumberStart=f.readInt(4))}},readExtraFields:function(f){var g,y,x,_=f.index+this.extraFieldsLength;for(this.extraFields||(this.extraFields={});f.index+4<_;)g=f.readInt(2),y=f.readInt(2),x=f.readData(y),this.extraFields[g]={id:g,length:y,value:x};f.setIndex(_)},handleUTF8:function(){var f=h.uint8array?"uint8array":"array";if(this.useUTF8())this.fileNameStr=d.utf8decode(this.fileName),this.fileCommentStr=d.utf8decode(this.fileComment);else{var g=this.findExtraFieldUnicodePath();if(g!==null)this.fileNameStr=g;else{var y=l.transformTo(f,this.fileName);this.fileNameStr=this.loadOptions.decodeFileName(y)}var x=this.findExtraFieldUnicodeComment();if(x!==null)this.fileCommentStr=x;else{var _=l.transformTo(f,this.fileComment);this.fileCommentStr=this.loadOptions.decodeFileName(_)}}},findExtraFieldUnicodePath:function(){var f=this.extraFields[28789];if(f){var g=i(f.value);return g.readInt(1)!==1||c(this.fileName)!==g.readInt(4)?null:d.utf8decode(g.readData(f.length-5))}return null},findExtraFieldUnicodeComment:function(){var f=this.extraFields[25461];if(f){var g=i(f.value);return g.readInt(1)!==1||c(this.fileComment)!==g.readInt(4)?null:d.utf8decode(g.readData(f.length-5))}return null}},r.exports=m},{"./compressedObject":2,"./compressions":3,"./crc32":4,"./reader/readerFor":22,"./support":30,"./utf8":31,"./utils":32}],35:[function(n,r,a){function i(g,y,x){this.name=g,this.dir=x.dir,this.date=x.date,this.comment=x.comment,this.unixPermissions=x.unixPermissions,this.dosPermissions=x.dosPermissions,this._data=y,this._dataBinary=x.binary,this.options={compression:x.compression,compressionOptions:x.compressionOptions}}var l=n("./stream/StreamHelper"),o=n("./stream/DataWorker"),c=n("./utf8"),d=n("./compressedObject"),u=n("./stream/GenericWorker");i.prototype={internalStream:function(g){var y=null,x="string";try{if(!g)throw new Error("No output type specified.");var _=(x=g.toLowerCase())==="string"||x==="text";x!=="binarystring"&&x!=="text"||(x="string"),y=this._decompressWorker();var b=!this._dataBinary;b&&!_&&(y=y.pipe(new c.Utf8EncodeWorker)),!b&&_&&(y=y.pipe(new c.Utf8DecodeWorker))}catch(k){(y=new u("error")).error(k)}return new l(y,x,"")},async:function(g,y){return this.internalStream(g).accumulate(y)},nodeStream:function(g,y){return this.internalStream(g||"nodebuffer").toNodejsStream(y)},_compressWorker:function(g,y){if(this._data instanceof d&&this._data.compression.magic===g.magic)return this._data.getCompressedWorker();var x=this._decompressWorker();return this._dataBinary||(x=x.pipe(new c.Utf8EncodeWorker)),d.createWorkerFrom(x,g,y)},_decompressWorker:function(){return this._data instanceof d?this._data.getContentWorker():this._data instanceof u?this._data:new o(this._data)}};for(var h=["asText","asBinary","asNodeBuffer","asUint8Array","asArrayBuffer"],m=function(){throw new Error("This method has been removed in JSZip 3.0, please check the upgrade guide.")},f=0;f>>6:(f<65536?m[x++]=224|f>>>12:(m[x++]=240|f>>>18,m[x++]=128|f>>>12&63),m[x++]=128|f>>>6&63),m[x++]=128|63&f);return m},a.buf2binstring=function(h){return u(h,h.length)},a.binstring2buf=function(h){for(var m=new i.Buf8(h.length),f=0,g=m.length;f>10&1023,b[g++]=56320|1023&y)}return u(b,g)},a.utf8border=function(h,m){var f;for((m=m||h.length)>h.length&&(m=h.length),f=m-1;0<=f&&(192&h[f])==128;)f--;return f<0||f===0?m:f+c[h[f]]>m?f:m}},{"./common":41}],43:[function(n,r,a){r.exports=function(i,l,o,c){for(var d=65535&i|0,u=i>>>16&65535|0,h=0;o!==0;){for(o-=h=2e3>>1:l>>>1;o[c]=l}return o}();r.exports=function(l,o,c,d){var u=i,h=d+c;l^=-1;for(var m=d;m>>8^u[255&(l^o[m])];return-1^l}},{}],46:[function(n,r,a){var i,l=n("../utils/common"),o=n("./trees"),c=n("./adler32"),d=n("./crc32"),u=n("./messages"),h=0,m=4,f=0,g=-2,y=-1,x=4,_=2,b=8,k=9,A=286,T=30,P=19,I=2*A+1,M=15,L=3,z=258,$=z+L+1,V=42,W=113,G=1,X=2,te=3,ne=4;function me(Ce,Fe){return Ce.msg=u[Fe],Fe}function ue(Ce){return(Ce<<1)-(4Ce.avail_out&&(Ae=Ce.avail_out),Ae!==0&&(l.arraySet(Ce.output,Fe.pending_buf,Fe.pending_out,Ae,Ce.next_out),Ce.next_out+=Ae,Fe.pending_out+=Ae,Ce.total_out+=Ae,Ce.avail_out-=Ae,Fe.pending-=Ae,Fe.pending===0&&(Fe.pending_out=0))}function he(Ce,Fe){o._tr_flush_block(Ce,0<=Ce.block_start?Ce.block_start:-1,Ce.strstart-Ce.block_start,Fe),Ce.block_start=Ce.strstart,ae(Ce.strm)}function xe(Ce,Fe){Ce.pending_buf[Ce.pending++]=Fe}function ve(Ce,Fe){Ce.pending_buf[Ce.pending++]=Fe>>>8&255,Ce.pending_buf[Ce.pending++]=255&Fe}function ge(Ce,Fe){var Ae,Xe,$e=Ce.max_chain_length,Ye=Ce.strstart,Je=Ce.prev_length,Ke=Ce.nice_match,st=Ce.strstart>Ce.w_size-$?Ce.strstart-(Ce.w_size-$):0,rt=Ce.window,Ze=Ce.w_mask,ht=Ce.prev,Bt=Ce.strstart+z,Ct=rt[Ye+Je-1],Yt=rt[Ye+Je];Ce.prev_length>=Ce.good_match&&($e>>=2),Ke>Ce.lookahead&&(Ke=Ce.lookahead);do if(rt[(Ae=Fe)+Je]===Yt&&rt[Ae+Je-1]===Ct&&rt[Ae]===rt[Ye]&&rt[++Ae]===rt[Ye+1]){Ye+=2,Ae++;do;while(rt[++Ye]===rt[++Ae]&&rt[++Ye]===rt[++Ae]&&rt[++Ye]===rt[++Ae]&&rt[++Ye]===rt[++Ae]&&rt[++Ye]===rt[++Ae]&&rt[++Ye]===rt[++Ae]&&rt[++Ye]===rt[++Ae]&&rt[++Ye]===rt[++Ae]&&Yest&&--$e!=0);return Je<=Ce.lookahead?Je:Ce.lookahead}function be(Ce){var Fe,Ae,Xe,$e,Ye,Je,Ke,st,rt,Ze,ht=Ce.w_size;do{if($e=Ce.window_size-Ce.lookahead-Ce.strstart,Ce.strstart>=ht+(ht-$)){for(l.arraySet(Ce.window,Ce.window,ht,ht,0),Ce.match_start-=ht,Ce.strstart-=ht,Ce.block_start-=ht,Fe=Ae=Ce.hash_size;Xe=Ce.head[--Fe],Ce.head[Fe]=ht<=Xe?Xe-ht:0,--Ae;);for(Fe=Ae=ht;Xe=Ce.prev[--Fe],Ce.prev[Fe]=ht<=Xe?Xe-ht:0,--Ae;);$e+=ht}if(Ce.strm.avail_in===0)break;if(Je=Ce.strm,Ke=Ce.window,st=Ce.strstart+Ce.lookahead,rt=$e,Ze=void 0,Ze=Je.avail_in,rt=L)for(Ye=Ce.strstart-Ce.insert,Ce.ins_h=Ce.window[Ye],Ce.ins_h=(Ce.ins_h<=L&&(Ce.ins_h=(Ce.ins_h<=L)if(Xe=o._tr_tally(Ce,Ce.strstart-Ce.match_start,Ce.match_length-L),Ce.lookahead-=Ce.match_length,Ce.match_length<=Ce.max_lazy_match&&Ce.lookahead>=L){for(Ce.match_length--;Ce.strstart++,Ce.ins_h=(Ce.ins_h<=L&&(Ce.ins_h=(Ce.ins_h<=L&&Ce.match_length<=Ce.prev_length){for($e=Ce.strstart+Ce.lookahead-L,Xe=o._tr_tally(Ce,Ce.strstart-1-Ce.prev_match,Ce.prev_length-L),Ce.lookahead-=Ce.prev_length-1,Ce.prev_length-=2;++Ce.strstart<=$e&&(Ce.ins_h=(Ce.ins_h<Ce.pending_buf_size-5&&(Ae=Ce.pending_buf_size-5);;){if(Ce.lookahead<=1){if(be(Ce),Ce.lookahead===0&&Fe===h)return G;if(Ce.lookahead===0)break}Ce.strstart+=Ce.lookahead,Ce.lookahead=0;var Xe=Ce.block_start+Ae;if((Ce.strstart===0||Ce.strstart>=Xe)&&(Ce.lookahead=Ce.strstart-Xe,Ce.strstart=Xe,he(Ce,!1),Ce.strm.avail_out===0)||Ce.strstart-Ce.block_start>=Ce.w_size-$&&(he(Ce,!1),Ce.strm.avail_out===0))return G}return Ce.insert=0,Fe===m?(he(Ce,!0),Ce.strm.avail_out===0?te:ne):(Ce.strstart>Ce.block_start&&(he(Ce,!1),Ce.strm.avail_out),G)}),new Me(4,4,8,4,Se),new Me(4,5,16,8,Se),new Me(4,6,32,32,Se),new Me(4,4,16,16,Ie),new Me(8,16,32,32,Ie),new Me(8,16,128,128,Ie),new Me(8,32,128,256,Ie),new Me(32,128,258,1024,Ie),new Me(32,258,258,4096,Ie)],a.deflateInit=function(Ce,Fe){return Ge(Ce,Fe,b,15,8,0)},a.deflateInit2=Ge,a.deflateReset=Ne,a.deflateResetKeep=Be,a.deflateSetHeader=function(Ce,Fe){return Ce&&Ce.state?Ce.state.wrap!==2?g:(Ce.state.gzhead=Fe,f):g},a.deflate=function(Ce,Fe){var Ae,Xe,$e,Ye;if(!Ce||!Ce.state||5>8&255),xe(Xe,Xe.gzhead.time>>16&255),xe(Xe,Xe.gzhead.time>>24&255),xe(Xe,Xe.level===9?2:2<=Xe.strategy||Xe.level<2?4:0),xe(Xe,255&Xe.gzhead.os),Xe.gzhead.extra&&Xe.gzhead.extra.length&&(xe(Xe,255&Xe.gzhead.extra.length),xe(Xe,Xe.gzhead.extra.length>>8&255)),Xe.gzhead.hcrc&&(Ce.adler=d(Ce.adler,Xe.pending_buf,Xe.pending,0)),Xe.gzindex=0,Xe.status=69):(xe(Xe,0),xe(Xe,0),xe(Xe,0),xe(Xe,0),xe(Xe,0),xe(Xe,Xe.level===9?2:2<=Xe.strategy||Xe.level<2?4:0),xe(Xe,3),Xe.status=W);else{var Je=b+(Xe.w_bits-8<<4)<<8;Je|=(2<=Xe.strategy||Xe.level<2?0:Xe.level<6?1:Xe.level===6?2:3)<<6,Xe.strstart!==0&&(Je|=32),Je+=31-Je%31,Xe.status=W,ve(Xe,Je),Xe.strstart!==0&&(ve(Xe,Ce.adler>>>16),ve(Xe,65535&Ce.adler)),Ce.adler=1}if(Xe.status===69)if(Xe.gzhead.extra){for($e=Xe.pending;Xe.gzindex<(65535&Xe.gzhead.extra.length)&&(Xe.pending!==Xe.pending_buf_size||(Xe.gzhead.hcrc&&Xe.pending>$e&&(Ce.adler=d(Ce.adler,Xe.pending_buf,Xe.pending-$e,$e)),ae(Ce),$e=Xe.pending,Xe.pending!==Xe.pending_buf_size));)xe(Xe,255&Xe.gzhead.extra[Xe.gzindex]),Xe.gzindex++;Xe.gzhead.hcrc&&Xe.pending>$e&&(Ce.adler=d(Ce.adler,Xe.pending_buf,Xe.pending-$e,$e)),Xe.gzindex===Xe.gzhead.extra.length&&(Xe.gzindex=0,Xe.status=73)}else Xe.status=73;if(Xe.status===73)if(Xe.gzhead.name){$e=Xe.pending;do{if(Xe.pending===Xe.pending_buf_size&&(Xe.gzhead.hcrc&&Xe.pending>$e&&(Ce.adler=d(Ce.adler,Xe.pending_buf,Xe.pending-$e,$e)),ae(Ce),$e=Xe.pending,Xe.pending===Xe.pending_buf_size)){Ye=1;break}Ye=Xe.gzindex$e&&(Ce.adler=d(Ce.adler,Xe.pending_buf,Xe.pending-$e,$e)),Ye===0&&(Xe.gzindex=0,Xe.status=91)}else Xe.status=91;if(Xe.status===91)if(Xe.gzhead.comment){$e=Xe.pending;do{if(Xe.pending===Xe.pending_buf_size&&(Xe.gzhead.hcrc&&Xe.pending>$e&&(Ce.adler=d(Ce.adler,Xe.pending_buf,Xe.pending-$e,$e)),ae(Ce),$e=Xe.pending,Xe.pending===Xe.pending_buf_size)){Ye=1;break}Ye=Xe.gzindex$e&&(Ce.adler=d(Ce.adler,Xe.pending_buf,Xe.pending-$e,$e)),Ye===0&&(Xe.status=103)}else Xe.status=103;if(Xe.status===103&&(Xe.gzhead.hcrc?(Xe.pending+2>Xe.pending_buf_size&&ae(Ce),Xe.pending+2<=Xe.pending_buf_size&&(xe(Xe,255&Ce.adler),xe(Xe,Ce.adler>>8&255),Ce.adler=0,Xe.status=W)):Xe.status=W),Xe.pending!==0){if(ae(Ce),Ce.avail_out===0)return Xe.last_flush=-1,f}else if(Ce.avail_in===0&&ue(Fe)<=ue(Ae)&&Fe!==m)return me(Ce,-5);if(Xe.status===666&&Ce.avail_in!==0)return me(Ce,-5);if(Ce.avail_in!==0||Xe.lookahead!==0||Fe!==h&&Xe.status!==666){var Ke=Xe.strategy===2?function(st,rt){for(var Ze;;){if(st.lookahead===0&&(be(st),st.lookahead===0)){if(rt===h)return G;break}if(st.match_length=0,Ze=o._tr_tally(st,0,st.window[st.strstart]),st.lookahead--,st.strstart++,Ze&&(he(st,!1),st.strm.avail_out===0))return G}return st.insert=0,rt===m?(he(st,!0),st.strm.avail_out===0?te:ne):st.last_lit&&(he(st,!1),st.strm.avail_out===0)?G:X}(Xe,Fe):Xe.strategy===3?function(st,rt){for(var Ze,ht,Bt,Ct,Yt=st.window;;){if(st.lookahead<=z){if(be(st),st.lookahead<=z&&rt===h)return G;if(st.lookahead===0)break}if(st.match_length=0,st.lookahead>=L&&0st.lookahead&&(st.match_length=st.lookahead)}if(st.match_length>=L?(Ze=o._tr_tally(st,1,st.match_length-L),st.lookahead-=st.match_length,st.strstart+=st.match_length,st.match_length=0):(Ze=o._tr_tally(st,0,st.window[st.strstart]),st.lookahead--,st.strstart++),Ze&&(he(st,!1),st.strm.avail_out===0))return G}return st.insert=0,rt===m?(he(st,!0),st.strm.avail_out===0?te:ne):st.last_lit&&(he(st,!1),st.strm.avail_out===0)?G:X}(Xe,Fe):i[Xe.level].func(Xe,Fe);if(Ke!==te&&Ke!==ne||(Xe.status=666),Ke===G||Ke===te)return Ce.avail_out===0&&(Xe.last_flush=-1),f;if(Ke===X&&(Fe===1?o._tr_align(Xe):Fe!==5&&(o._tr_stored_block(Xe,0,0,!1),Fe===3&&(ce(Xe.head),Xe.lookahead===0&&(Xe.strstart=0,Xe.block_start=0,Xe.insert=0))),ae(Ce),Ce.avail_out===0))return Xe.last_flush=-1,f}return Fe!==m?f:Xe.wrap<=0?1:(Xe.wrap===2?(xe(Xe,255&Ce.adler),xe(Xe,Ce.adler>>8&255),xe(Xe,Ce.adler>>16&255),xe(Xe,Ce.adler>>24&255),xe(Xe,255&Ce.total_in),xe(Xe,Ce.total_in>>8&255),xe(Xe,Ce.total_in>>16&255),xe(Xe,Ce.total_in>>24&255)):(ve(Xe,Ce.adler>>>16),ve(Xe,65535&Ce.adler)),ae(Ce),0=Ae.w_size&&(Ye===0&&(ce(Ae.head),Ae.strstart=0,Ae.block_start=0,Ae.insert=0),rt=new l.Buf8(Ae.w_size),l.arraySet(rt,Fe,Ze-Ae.w_size,Ae.w_size,0),Fe=rt,Ze=Ae.w_size),Je=Ce.avail_in,Ke=Ce.next_in,st=Ce.input,Ce.avail_in=Ze,Ce.next_in=0,Ce.input=Fe,be(Ae);Ae.lookahead>=L;){for(Xe=Ae.strstart,$e=Ae.lookahead-(L-1);Ae.ins_h=(Ae.ins_h<>>=L=M>>>24,k-=L,(L=M>>>16&255)===0)X[u++]=65535&M;else{if(!(16&L)){if(!(64&L)){M=A[(65535&M)+(b&(1<>>=L,k-=L),k<15&&(b+=G[c++]<>>=L=M>>>24,k-=L,!(16&(L=M>>>16&255))){if(!(64&L)){M=T[(65535&M)+(b&(1<>>=L,k-=L,(L=u-h)<$){if(y<(L=$-L)&&o.sane){i.msg="invalid distance too far back",o.mode=30;break e}if(W=_,(V=0)===x){if(V+=g-L,L>3,b&=(1<<(k-=z<<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 k(V){var W;return V&&V.state?(W=V.state,V.total_in=V.total_out=W.total=0,V.msg="",W.wrap&&(V.adler=1&W.wrap),W.mode=g,W.last=0,W.havedict=0,W.dmax=32768,W.head=null,W.hold=0,W.bits=0,W.lencode=W.lendyn=new i.Buf32(y),W.distcode=W.distdyn=new i.Buf32(x),W.sane=1,W.back=-1,m):f}function A(V){var W;return V&&V.state?((W=V.state).wsize=0,W.whave=0,W.wnext=0,k(V)):f}function T(V,W){var G,X;return V&&V.state?(X=V.state,W<0?(G=0,W=-W):(G=1+(W>>4),W<48&&(W&=15)),W&&(W<8||15=ne.wsize?(i.arraySet(ne.window,W,G-ne.wsize,ne.wsize,0),ne.wnext=0,ne.whave=ne.wsize):(X<(te=ne.wsize-ne.wnext)&&(te=X),i.arraySet(ne.window,W,G-X,te,ne.wnext),(X-=te)?(i.arraySet(ne.window,W,G-X,X,0),ne.wnext=X,ne.whave=ne.wsize):(ne.wnext+=te,ne.wnext===ne.wsize&&(ne.wnext=0),ne.whave>>8&255,G.check=o(G.check,Ye,2,0),he=ae=0,G.mode=2;break}if(G.flags=0,G.head&&(G.head.done=!1),!(1&G.wrap)||(((255&ae)<<8)+(ae>>8))%31){V.msg="incorrect header check",G.mode=30;break}if((15&ae)!=8){V.msg="unknown compression method",G.mode=30;break}if(he-=4,Ce=8+(15&(ae>>>=4)),G.wbits===0)G.wbits=Ce;else if(Ce>G.wbits){V.msg="invalid window size",G.mode=30;break}G.dmax=1<>8&1),512&G.flags&&(Ye[0]=255&ae,Ye[1]=ae>>>8&255,G.check=o(G.check,Ye,2,0)),he=ae=0,G.mode=3;case 3:for(;he<32;){if(ue===0)break e;ue--,ae+=X[ne++]<>>8&255,Ye[2]=ae>>>16&255,Ye[3]=ae>>>24&255,G.check=o(G.check,Ye,4,0)),he=ae=0,G.mode=4;case 4:for(;he<16;){if(ue===0)break e;ue--,ae+=X[ne++]<>8),512&G.flags&&(Ye[0]=255&ae,Ye[1]=ae>>>8&255,G.check=o(G.check,Ye,2,0)),he=ae=0,G.mode=5;case 5:if(1024&G.flags){for(;he<16;){if(ue===0)break e;ue--,ae+=X[ne++]<>>8&255,G.check=o(G.check,Ye,2,0)),he=ae=0}else G.head&&(G.head.extra=null);G.mode=6;case 6:if(1024&G.flags&&(ue<(ge=G.length)&&(ge=ue),ge&&(G.head&&(Ce=G.head.extra_len-G.length,G.head.extra||(G.head.extra=new Array(G.head.extra_len)),i.arraySet(G.head.extra,X,ne,ge,Ce)),512&G.flags&&(G.check=o(G.check,X,ge,ne)),ue-=ge,ne+=ge,G.length-=ge),G.length))break e;G.length=0,G.mode=7;case 7:if(2048&G.flags){if(ue===0)break e;for(ge=0;Ce=X[ne+ge++],G.head&&Ce&&G.length<65536&&(G.head.name+=String.fromCharCode(Ce)),Ce&&ge>9&1,G.head.done=!0),V.adler=G.check=0,G.mode=12;break;case 10:for(;he<32;){if(ue===0)break e;ue--,ae+=X[ne++]<>>=7&he,he-=7&he,G.mode=27;break}for(;he<3;){if(ue===0)break e;ue--,ae+=X[ne++]<>>=1)){case 0:G.mode=14;break;case 1:if(z(G),G.mode=20,W!==6)break;ae>>>=2,he-=2;break e;case 2:G.mode=17;break;case 3:V.msg="invalid block type",G.mode=30}ae>>>=2,he-=2;break;case 14:for(ae>>>=7&he,he-=7&he;he<32;){if(ue===0)break e;ue--,ae+=X[ne++]<>>16^65535)){V.msg="invalid stored block lengths",G.mode=30;break}if(G.length=65535&ae,he=ae=0,G.mode=15,W===6)break e;case 15:G.mode=16;case 16:if(ge=G.length){if(ue>>=5,he-=5,G.ndist=1+(31&ae),ae>>>=5,he-=5,G.ncode=4+(15&ae),ae>>>=4,he-=4,286>>=3,he-=3}for(;G.have<19;)G.lens[Je[G.have++]]=0;if(G.lencode=G.lendyn,G.lenbits=7,Ae={bits:G.lenbits},Fe=d(0,G.lens,0,19,G.lencode,0,G.work,Ae),G.lenbits=Ae.bits,Fe){V.msg="invalid code lengths set",G.mode=30;break}G.have=0,G.mode=19;case 19:for(;G.have>>16&255,Re=65535&$e,!((Ie=$e>>>24)<=he);){if(ue===0)break e;ue--,ae+=X[ne++]<>>=Ie,he-=Ie,G.lens[G.have++]=Re;else{if(Re===16){for(Xe=Ie+2;he>>=Ie,he-=Ie,G.have===0){V.msg="invalid bit length repeat",G.mode=30;break}Ce=G.lens[G.have-1],ge=3+(3&ae),ae>>>=2,he-=2}else if(Re===17){for(Xe=Ie+3;he>>=Ie)),ae>>>=3,he-=3}else{for(Xe=Ie+7;he>>=Ie)),ae>>>=7,he-=7}if(G.have+ge>G.nlen+G.ndist){V.msg="invalid bit length repeat",G.mode=30;break}for(;ge--;)G.lens[G.have++]=Ce}}if(G.mode===30)break;if(G.lens[256]===0){V.msg="invalid code -- missing end-of-block",G.mode=30;break}if(G.lenbits=9,Ae={bits:G.lenbits},Fe=d(u,G.lens,0,G.nlen,G.lencode,0,G.work,Ae),G.lenbits=Ae.bits,Fe){V.msg="invalid literal/lengths set",G.mode=30;break}if(G.distbits=6,G.distcode=G.distdyn,Ae={bits:G.distbits},Fe=d(h,G.lens,G.nlen,G.ndist,G.distcode,0,G.work,Ae),G.distbits=Ae.bits,Fe){V.msg="invalid distances set",G.mode=30;break}if(G.mode=20,W===6)break e;case 20:G.mode=21;case 21:if(6<=ue&&258<=ce){V.next_out=me,V.avail_out=ce,V.next_in=ne,V.avail_in=ue,G.hold=ae,G.bits=he,c(V,ve),me=V.next_out,te=V.output,ce=V.avail_out,ne=V.next_in,X=V.input,ue=V.avail_in,ae=G.hold,he=G.bits,G.mode===12&&(G.back=-1);break}for(G.back=0;Me=($e=G.lencode[ae&(1<>>16&255,Re=65535&$e,!((Ie=$e>>>24)<=he);){if(ue===0)break e;ue--,ae+=X[ne++]<>Be)])>>>16&255,Re=65535&$e,!(Be+(Ie=$e>>>24)<=he);){if(ue===0)break e;ue--,ae+=X[ne++]<>>=Be,he-=Be,G.back+=Be}if(ae>>>=Ie,he-=Ie,G.back+=Ie,G.length=Re,Me===0){G.mode=26;break}if(32&Me){G.back=-1,G.mode=12;break}if(64&Me){V.msg="invalid literal/length code",G.mode=30;break}G.extra=15&Me,G.mode=22;case 22:if(G.extra){for(Xe=G.extra;he>>=G.extra,he-=G.extra,G.back+=G.extra}G.was=G.length,G.mode=23;case 23:for(;Me=($e=G.distcode[ae&(1<>>16&255,Re=65535&$e,!((Ie=$e>>>24)<=he);){if(ue===0)break e;ue--,ae+=X[ne++]<>Be)])>>>16&255,Re=65535&$e,!(Be+(Ie=$e>>>24)<=he);){if(ue===0)break e;ue--,ae+=X[ne++]<>>=Be,he-=Be,G.back+=Be}if(ae>>>=Ie,he-=Ie,G.back+=Ie,64&Me){V.msg="invalid distance code",G.mode=30;break}G.offset=Re,G.extra=15&Me,G.mode=24;case 24:if(G.extra){for(Xe=G.extra;he>>=G.extra,he-=G.extra,G.back+=G.extra}if(G.offset>G.dmax){V.msg="invalid distance too far back",G.mode=30;break}G.mode=25;case 25:if(ce===0)break e;if(ge=ve-ce,G.offset>ge){if((ge=G.offset-ge)>G.whave&&G.sane){V.msg="invalid distance too far back",G.mode=30;break}be=ge>G.wnext?(ge-=G.wnext,G.wsize-ge):G.wnext-ge,ge>G.length&&(ge=G.length),Se=G.window}else Se=te,be=me-G.offset,ge=G.length;for(ceI?(L=be[Se+x[W]],he[xe+x[W]]):(L=96,0),b=1<>me)+(k-=b)]=M<<24|L<<16|z|0,k!==0;);for(b=1<>=1;if(b!==0?(ae&=b-1,ae+=b):ae=0,W++,--ve[V]==0){if(V===X)break;V=h[m+x[W]]}if(te>>7)]}function xe($e,Ye){$e.pending_buf[$e.pending++]=255&Ye,$e.pending_buf[$e.pending++]=Ye>>>8&255}function ve($e,Ye,Je){$e.bi_valid>_-Je?($e.bi_buf|=Ye<<$e.bi_valid&65535,xe($e,$e.bi_buf),$e.bi_buf=Ye>>_-$e.bi_valid,$e.bi_valid+=Je-_):($e.bi_buf|=Ye<<$e.bi_valid&65535,$e.bi_valid+=Je)}function ge($e,Ye,Je){ve($e,Je[2*Ye],Je[2*Ye+1])}function be($e,Ye){for(var Je=0;Je|=1&$e,$e>>>=1,Je<<=1,0<--Ye;);return Je>>>1}function Se($e,Ye,Je){var Ke,st,rt=new Array(x+1),Ze=0;for(Ke=1;Ke<=x;Ke++)rt[Ke]=Ze=Ze+Je[Ke-1]<<1;for(st=0;st<=Ye;st++){var ht=$e[2*st+1];ht!==0&&($e[2*st]=be(rt[ht]++,ht))}}function Ie($e){var Ye;for(Ye=0;Ye>1;1<=Je;Je--)Be($e,rt,Je);for(st=Bt;Je=$e.heap[1],$e.heap[1]=$e.heap[$e.heap_len--],Be($e,rt,1),Ke=$e.heap[1],$e.heap[--$e.heap_max]=Je,$e.heap[--$e.heap_max]=Ke,rt[2*st]=rt[2*Je]+rt[2*Ke],$e.depth[st]=($e.depth[Je]>=$e.depth[Ke]?$e.depth[Je]:$e.depth[Ke])+1,rt[2*Je+1]=rt[2*Ke+1]=st,$e.heap[1]=st++,Be($e,rt,1),2<=$e.heap_len;);$e.heap[--$e.heap_max]=$e.heap[1],function(Yt,Kt){var Xs,zs,Vt,At,Os,Nt,ms=Kt.dyn_tree,Ys=Kt.max_code,It=Kt.stat_desc.static_tree,Ds=Kt.stat_desc.has_stree,As=Kt.stat_desc.extra_bits,Hs=Kt.stat_desc.extra_base,Rs=Kt.stat_desc.max_length,en=0;for(At=0;At<=x;At++)Yt.bl_count[At]=0;for(ms[2*Yt.heap[Yt.heap_max]+1]=0,Xs=Yt.heap_max+1;Xs>=7;st>>=1)if(1&Ct&&ht.dyn_ltree[2*Bt]!==0)return l;if(ht.dyn_ltree[18]!==0||ht.dyn_ltree[20]!==0||ht.dyn_ltree[26]!==0)return o;for(Bt=32;Bt>>3,(rt=$e.static_len+3+7>>>3)<=st&&(st=rt)):st=rt=Je+5,Je+4<=st&&Ye!==-1?Xe($e,Ye,Je,Ke):$e.strategy===4||rt===st?(ve($e,2+(Ke?1:0),3),Ne($e,$,V)):(ve($e,4+(Ke?1:0),3),function(ht,Bt,Ct,Yt){var Kt;for(ve(ht,Bt-257,5),ve(ht,Ct-1,5),ve(ht,Yt-4,4),Kt=0;Kt>>8&255,$e.pending_buf[$e.d_buf+2*$e.last_lit+1]=255&Ye,$e.pending_buf[$e.l_buf+$e.last_lit]=255&Je,$e.last_lit++,Ye===0?$e.dyn_ltree[2*Je]++:($e.matches++,Ye--,$e.dyn_ltree[2*(G[Je]+h+1)]++,$e.dyn_dtree[2*he(Ye)]++),$e.last_lit===$e.lit_bufsize-1},a._tr_align=function($e){ve($e,2,3),ge($e,k,$),function(Ye){Ye.bi_valid===16?(xe(Ye,Ye.bi_buf),Ye.bi_buf=0,Ye.bi_valid=0):8<=Ye.bi_valid&&(Ye.pending_buf[Ye.pending++]=255&Ye.bi_buf,Ye.bi_buf>>=8,Ye.bi_valid-=8)}($e)}},{"../utils/common":41}],53:[function(n,r,a){r.exports=function(){this.input=null,this.next_in=0,this.avail_in=0,this.total_in=0,this.output=null,this.next_out=0,this.avail_out=0,this.total_out=0,this.msg="",this.state=null,this.data_type=2,this.adler=0}},{}],54:[function(n,r,a){(function(i){(function(l,o){if(!l.setImmediate){var c,d,u,h,m=1,f={},g=!1,y=l.document,x=Object.getPrototypeOf&&Object.getPrototypeOf(l);x=x&&x.setTimeout?x:l,c={}.toString.call(l.process)==="[object process]"?function(A){process.nextTick(function(){b(A)})}:function(){if(l.postMessage&&!l.importScripts){var A=!0,T=l.onmessage;return l.onmessage=function(){A=!1},l.postMessage("","*"),l.onmessage=T,A}}()?(h="setImmediate$"+Math.random()+"$",l.addEventListener?l.addEventListener("message",k,!1):l.attachEvent("onmessage",k),function(A){l.postMessage(h+A,"*")}):l.MessageChannel?((u=new MessageChannel).port1.onmessage=function(A){b(A.data)},function(A){u.port2.postMessage(A)}):y&&"onreadystatechange"in y.createElement("script")?(d=y.documentElement,function(A){var T=y.createElement("script");T.onreadystatechange=function(){b(A),T.onreadystatechange=null,d.removeChild(T),T=null},d.appendChild(T)}):function(A){setTimeout(b,0,A)},x.setImmediate=function(A){typeof A!="function"&&(A=new Function(""+A));for(var T=new Array(arguments.length-1),P=0;P"u"?i===void 0?this:i:self)}).call(this,typeof Uf<"u"?Uf:typeof self<"u"?self:typeof window<"u"?window:{})},{}]},{},[10])(10)})})(iTt);var CMs=iTt.exports;const oTt=Xc(CMs);function KMe(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 AMs=()=>{Ls();const[s,t]=N.useState(null),[n,r]=N.useState(null),[a,i]=N.useState("all"),[l,o]=N.useState(new Set),[c,d]=N.useState(!1),[u,h]=N.useState(!1),[m,f]=N.useState("images"),[g,y]=N.useState(null),{data:x=[],isLoading:_}=mt({queryKey:["social-swag-2"],queryFn:async()=>{const{data:me,error:ue}=await H.from("social_swag_2").select("*").order("month",{ascending:!1}).order("sort_order");if(ue)throw ue;return me}}),{data:b=[]}=mt({queryKey:["social-swag-2-months"],queryFn:async()=>{const{data:me,error:ue}=await H.from("social_swag_2_months").select("*").order("month",{ascending:!1});if(ue)throw ue;return me}}),{data:k=[]}=mt({queryKey:["social-swag-2-reels"],queryFn:async()=>{const{data:me,error:ue}=await H.from("social_swag_2_reels").select("*").order("month",{ascending:!1});if(ue)throw ue;return me}}),{data:A=[]}=mt({queryKey:["my-social-accounts-count"],queryFn:async()=>{const{data:me,error:ue}=await H.from("social_accounts").select("id, platform").eq("is_active",!0);if(ue)throw ue;return me||[]}}),T=A.length>0,P=N.useMemo(()=>a==="all"?null:k.find(me=>me.month===a)||null,[a,k]),I=N.useMemo(()=>[...new Set(x.map(ue=>ue.month))].sort((ue,ce)=>ce.localeCompare(ue)),[x]);N.useEffect(()=>{I.length>0&&a==="all"&&i(I[0])},[I,a]);const M=me=>{try{const ue=tUe(me,"yyyy-MM",new Date);return Js(ue,"MMMM yyyy")}catch{return me}},L=N.useMemo(()=>a==="all"?x:x.filter(me=>me.month===a),[a,x]),z=N.useMemo(()=>{var me;return a==="all"?null:((me=b.find(ue=>ue.month===a))==null?void 0:me.canva_link)||null},[a,b]),$=async me=>{try{await navigator.clipboard.writeText(me),ie.success("Caption copied to clipboard!")}catch{ie.error("Failed to copy caption")}},V=async(me,ue)=>{try{const ae=await(await fetch(me)).blob(),he=/iPhone|iPad|iPod|Android/i.test(navigator.userAgent),xe=navigator.canShare&&navigator.canShare({files:[new File([ae],"test.jpg",{type:"image/jpeg"})]});if(he&&xe){const ve=new File([ae],`social-swag-${ue}.jpg`,{type:"image/jpeg"});await navigator.share({files:[ve],title:"Social Swag Image"}),ie.success("Image ready to save!")}else{const ve=window.URL.createObjectURL(ae),ge=document.createElement("a");ge.href=ve,ge.download=`social-swag-${ue}.jpg`,document.body.appendChild(ge),ge.click(),document.body.removeChild(ge),window.URL.revokeObjectURL(ve),ie.success("Image downloaded!")}}catch(ce){ce.name!=="AbortError"&&ie.error("Failed to download image")}},W=me=>{o(ue=>{const ce=new Set(ue);return ce.has(me)?ce.delete(me):ce.add(me),ce})},G=()=>{o(new Set(L.map(me=>me.id)))},X=()=>{o(new Set),d(!1)},te=async()=>{const me=L.filter(ue=>l.has(ue.id));if(me.length===0){ie.error("No images selected");return}h(!0),ie.info(`Preparing ${me.length} images for download...`);try{const ue=new oTt,ce=[...me].sort((ge,be)=>ge.sort_order-be.sort_order);for(let ge=0;ge{c?W(me.id):t(me)};return e.jsx(Qs,{title:"Social Swag 2.0",children:e.jsxs("div",{className:"space-y-8",children:[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(We,{variant:"secondary",className:"bg-white/20 text-white border-0 backdrop-blur-sm",children:[e.jsx(Cn,{className:"h-3 w-3 mr-1"}),"New content monthly"]}),e.jsxs(We,{variant:"secondary",className:"bg-white/20 text-white border-0 backdrop-blur-sm",children:[e.jsx(pc,{className:"h-3 w-3 mr-1"}),x.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(ya,{defaultValue:"gallery",className:"space-y-6",children:[e.jsxs(va,{className:"grid w-full max-w-md grid-cols-2",children:[e.jsxs(ls,{value:"gallery",className:"gap-2",children:[e.jsx(pc,{className:"h-4 w-4"}),"Gallery"]}),e.jsxs(ls,{value:"scheduled",className:"gap-2",children:[e.jsx(ld,{className:"h-4 w-4"}),"Scheduled"]})]}),e.jsxs(_s,{value:"gallery",className:"space-y-6",children:[T?e.jsx(_e,{className:"border rounded-xl",children:e.jsx(De,{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(cr,{to:"/mission-control/integrations",children:"Manage Accounts"})})]})})}):e.jsx(_e,{className:"border-2 border-dashed border-primary/30 bg-gradient-to-r from-pink-500/5 via-purple-500/5 to-blue-500/5 rounded-xl",children:e.jsx(De,{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(Kf,{className:"h-5 w-5 text-blue-600"})}),e.jsx("div",{className:"p-2 rounded-full bg-pink-500/10",children:e.jsx(dm,{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(cr,{to:"/social-connections",children:[e.jsx(cd,{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(me=>e.jsx("button",{onClick:()=>i(me),className:Ot("px-4 py-2 rounded-full text-sm font-medium transition-all",a===me?"bg-primary text-primary-foreground shadow-sm":"bg-muted text-muted-foreground hover:text-foreground"),children:M(me)},me))}),a!=="all"&&(z?e.jsxs("a",{href:z,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 ",M(a)," 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 ",M(a)," 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:()=>{f("images"),X()},className:Ot("flex items-center gap-2 px-4 py-2 rounded-full text-sm font-medium transition-all",m==="images"?"bg-background text-foreground shadow-sm":"text-muted-foreground hover:text-foreground"),children:[e.jsx(pc,{className:"h-4 w-4"}),"Images"]}),e.jsxs("button",{onClick:()=>{f("reels"),X()},className:Ot("flex items-center gap-2 px-4 py-2 rounded-full text-sm font-medium transition-all",m==="reels"?"bg-background text-foreground shadow-sm":"text-muted-foreground hover:text-foreground"),children:[e.jsx(Rh,{className:"h-4 w-4"}),"Reels"]})]}),m==="images"&&e.jsx("div",{className:"flex flex-wrap items-center gap-3",children:c?e.jsxs(e.Fragment,{children:[e.jsxs(B,{variant:"outline",size:"sm",onClick:G,className:"gap-2",children:["Select All (",L.length,")"]}),e.jsxs(B,{variant:"outline",size:"sm",onClick:X,className:"gap-2",children:[e.jsx(hr,{className:"h-4 w-4"}),"Cancel"]}),l.size>0&&e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs(B,{size:"sm",onClick:te,disabled:u,className:"gap-2",children:[e.jsx(oi,{className:"h-4 w-4"}),u?"Downloading...":`Download ${l.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:()=>d(!0),className:"gap-2",children:[e.jsx(pa,{className:"h-4 w-4"}),"Select Images"]})})]}),_&&e.jsx("div",{className:"text-center py-12 text-muted-foreground",children:"Loading..."}),!_&&m==="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:L.map(me=>{const ue=l.has(me.id);return e.jsx(_e,{className:Ot("group cursor-pointer overflow-hidden border-0 shadow-md hover:shadow-xl transition-all duration-300 rounded-2xl",c&&ue&&"ring-2 ring-primary ring-offset-2"),onClick:()=>ne(me),children:e.jsxs("div",{className:"relative aspect-[4/5] overflow-hidden",children:[e.jsx("img",{src:KMe(me.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"}),me.post_date&&!c&&e.jsx("div",{className:"absolute top-0 left-0 w-24 h-24 overflow-hidden pointer-events-none",children:e.jsx("div",{className:"absolute flex items-center justify-center text-white font-bold text-[10px] tracking-wider uppercase",style:{top:"20px",left:"-34px",width:"136px",transform:"rotate(-45deg)",backgroundColor:"#2d5052",padding:"5px 0",boxShadow:"0 2px 4px rgba(0,0,0,0.25)"},children:Js(new Date(me.post_date+"T00:00:00"),"MMM d")})}),c&&e.jsx("div",{className:Ot("absolute top-2 right-2 w-6 h-6 rounded-full border-2 flex items-center justify-center transition-all",ue?"bg-primary border-primary text-primary-foreground":"bg-white/80 border-muted-foreground/50"),children:ue&&e.jsx(pa,{className:"h-4 w-4"})}),!c&&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"})})]})},me.id)})}),L.length===0&&e.jsxs("div",{className:"text-center py-12",children:[e.jsx(pc,{className:"h-12 w-12 text-muted-foreground/50 mx-auto mb-4"}),e.jsx("p",{className:"text-muted-foreground",children:"No images available for this month yet."})]})]}),!_&&m==="reels"&&e.jsx(e.Fragment,{children:P?e.jsx("div",{className:"grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-5 xl:grid-cols-6 gap-4",children:e.jsx(_e,{className:"group overflow-hidden rounded-2xl cursor-pointer transition-all duration-300 hover:shadow-xl hover:scale-[1.02]",onClick:()=>r(P),children:e.jsxs("div",{className:"relative aspect-[9/16] overflow-hidden",children:[e.jsx("img",{src:KMe(P.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(We,{variant:"secondary",className:"bg-black/50 text-white border-0 backdrop-blur-sm text-xs",children:[e.jsx(Rh,{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(Rh,{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(Bs,{open:!!s,onOpenChange:()=>t(null),children:e.jsx(Fs,{className:"max-w-4xl max-h-[90vh] overflow-hidden p-0",children:e.jsx("div",{className:"max-h-[90vh] overflow-y-auto touch-pan-y",style:{WebkitOverflowScrolling:"touch"},children:s&&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:KMe(s.image_url,900,85),alt:"Social swag",className:"w-full h-full object-cover",decoding:"async"})})}),e.jsxs("div",{className:"md:w-1/2 p-6 flex flex-col",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-3 text-sm text-muted-foreground mb-4",children:[e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx(ta,{className:"h-4 w-4"}),Js(new Date(s.created_at),"MMMM d, yyyy")]}),s.post_date&&e.jsxs("span",{className:"inline-flex items-center gap-1.5 font-medium rounded-full px-3 py-1 text-xs text-white",style:{background:"#406E71"},children:[e.jsx(ta,{className:"h-3.5 w-3.5"}),"Post on ",Js(new Date(s.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:s.caption})})]}),e.jsxs("div",{className:"flex flex-col gap-3 mt-6",children:[e.jsxs(B,{onClick:()=>{y({imageUrl:s.image_url,imageId:s.id,caption:s.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(Rr,{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:()=>$(s.caption),className:"flex-1 gap-2",children:[e.jsx(Pa,{className:"h-4 w-4"}),"Copy Caption"]}),e.jsxs(B,{variant:"outline",onClick:()=>V(s.image_url,s.id),className:"flex-1 gap-2",children:[e.jsx(oi,{className:"h-4 w-4"}),"Download"]})]})]})]})]})})})}),e.jsx(Bs,{open:!!n,onOpenChange:()=>r(null),children:e.jsx(Fs,{className:"max-w-4xl max-h-[90vh] overflow-hidden p-0",children:e.jsx("div",{className:"max-h-[90vh] overflow-y-auto touch-pan-y",style:{WebkitOverflowScrolling:"touch"},children:n&&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:n.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(Rh,{className:"h-4 w-4"}),"Monthly Reel"]}),n.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:n.caption})})]}),e.jsxs("div",{className:"flex flex-col sm:flex-row gap-3 mt-6",children:[n.caption&&e.jsxs(B,{onClick:()=>$(n.caption||""),className:"flex-1 gap-2",children:[e.jsx(Pa,{className:"h-4 w-4"}),"Copy Caption"]}),n.canva_link&&e.jsxs(B,{variant:"outline",onClick:()=>window.open(n.canva_link,"_blank"),className:"flex-1 gap-2",children:[e.jsx(Tr,{className:"h-4 w-4"}),"Open in Canva"]})]})]})]})})})}),e.jsx(kMs,{open:!!g,onOpenChange:me=>!me&&y(null),imageUrl:(g==null?void 0:g.imageUrl)||"",imageId:(g==null?void 0:g.imageId)||"",defaultCaption:(g==null?void 0:g.caption)||"",swagItemId:g==null?void 0:g.imageId})]}),e.jsx(_s,{value:"scheduled",children:e.jsx(SMs,{})})]})]})})},TMs=[{id:"branding-bar",title:"Branding Bar Studio",description:"Drop in any image — get a branded version with your headshot, logo, and contact info.",icon:pc,to:"/marketing-studio/branding-bar",color:"from-violet-500 to-fuchsia-500"},{id:"listing-templates",title:"Listing Templates",description:"Just Listed, Just Sold, Open House, Price Drop — pulled from your MLS in one click.",icon:_a,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:Ro,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:fl,comingSoon:!0,color:"from-orange-500 to-red-500"},{id:"milestones",title:"Client Milestones",description:"Closing day, home anniversaries, birthdays, referral thank-yous.",icon:Fm,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:nj,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:f5,comingSoon:!0,color:"from-amber-500 to-yellow-500"}];function EMs(){return e.jsx(Qs,{title:"Marketing Studio",children:e.jsxs("div",{className:"container max-w-6xl py-8 space-y-6",children:[e.jsxs(ic,{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(We,{variant:"secondary",className:"mb-2 gap-1",children:[e.jsx(Cn,{className:"h-3 w-3"})," New"]}),e.jsx("h1",{className:"text-3xl md:text-4xl font-bold tracking-tight",children:"Marketing Studio"}),e.jsx("p",{className:"text-muted-foreground max-w-2xl mt-1",children:"Your one-stop creative hub. Drop in any photo or video, and walk away with a fully branded export — no design skills, no AI credits."})]}),e.jsx(B,{variant:"outline",asChild:!0,children:e.jsxs(cr,{to:"/marketing-studio/brand-kit",children:[e.jsx(zc,{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:TMs.map(s=>{const t=s.icon,n=e.jsxs(_e,{className:`group relative overflow-hidden transition-all h-full ${s.comingSoon?"opacity-70":"hover:shadow-xl hover:-translate-y-0.5 cursor-pointer"}`,children:[e.jsx("div",{className:`absolute inset-x-0 top-0 h-1 bg-gradient-to-r ${s.color}`}),e.jsxs(De,{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(We,{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(cr,{to:s.to,className:"block",children:n},s.id):e.jsx("div",{children:n},s.id)})})]})})}function XQ(){const s=Ya();return mt({queryKey:["marketing-brand-presets",s],queryFn:async()=>{if(!s)return[];const{data:t,error:n}=await H.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 MMs(){const{data:s,...t}=XQ();return{data:(s==null?void 0:s.find(n=>n.is_default))??(s==null?void 0:s[0])??null,...t}}function LMs(){const s=Ya(),t=as();return _t({mutationFn:async n=>{if(!s)throw new Error("Not signed in");if(n.is_default&&await H.from("marketing_brand_presets").update({is_default:!1}).eq("user_id",s),n.id){const{id:r,...a}=n,{data:i,error:l}=await H.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 H.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 PMs(){const s=Ya(),t=as();return _t({mutationFn:async n=>{const{error:r}=await H.from("marketing_brand_presets").delete().eq("id",n);if(r)throw r},onSuccess:()=>t.invalidateQueries({queryKey:["marketing-brand-presets",s]})})}async function IMs(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 H.storage.from("marketing-studio-uploads").upload(a,t,{upsert:!0,cacheControl:"3600"});if(i)throw i;const{data:l}=await H.storage.from("marketing-studio-uploads").createSignedUrl(a,60*60*24*365*5);return(l==null?void 0:l.signedUrl)??""}function DMs({preset:s,onSaved:t,onCancel:n}){var y;const r=Ya(),a=LMs(),i=PMs(),l=N.useRef(null),o=N.useRef(null),[c,d]=N.useState(null),[u,h]=N.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"});N.useEffect(()=>{s||(async()=>{if(!r)return;const{supabase:x}=await Fi(async()=>{const{supabase:b}=await Promise.resolve().then(()=>mss);return{supabase:b}},void 0),{data:_}=await x.from("profiles").select("name, email, phone, avatar_url, website_url, title, brokerage_id").eq("id",r).maybeSingle();_&&h(b=>({...b,display_name:b.display_name||(_.name??""),email:b.email||(_.email??""),phone:b.phone||(_.phone??""),headshot_url:b.headshot_url||(_.avatar_url??""),website_url:b.website_url||(_.website_url??""),tagline:b.tagline||(_.title??"")}))})()},[r]);const m=async(x,_)=>{if(r){d(x);try{const b=await IMs(r,_,x);h(k=>({...k,[x==="headshot"?"headshot_url":"brokerage_logo_url"]:b}))}catch(b){ie.error(b.message||"Upload failed")}finally{d(null)}}},f=async()=>{try{const x=await a.mutateAsync({id:s==null?void 0:s.id,...u});ie.success("Brand preset saved"),t==null||t(x)}catch(x){ie.error(x.message||"Save failed")}},g=async()=>{s!=null&&s.id&&confirm("Delete this brand preset?")&&(await i.mutateAsync(s.id),ie.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(re,{children:"Preset name"}),e.jsx(we,{value:u.name,onChange:x=>h({...u,name:x.target.value}),placeholder:"Personal, Team, Luxury..."})]}),e.jsxs("div",{className:"flex items-end gap-3 pb-1",children:[e.jsx(zn,{checked:u.is_default,onCheckedChange:x=>h({...u,is_default:x})}),e.jsx(re,{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(re,{children:"Display name"}),e.jsx(we,{value:u.display_name,onChange:x=>h({...u,display_name:x.target.value})})]}),e.jsxs("div",{children:[e.jsx(re,{children:"Phone"}),e.jsx(we,{value:u.phone,onChange:x=>h({...u,phone:x.target.value})})]}),e.jsxs("div",{children:[e.jsx(re,{children:"Email"}),e.jsx(we,{value:u.email,onChange:x=>h({...u,email:x.target.value})})]}),e.jsxs("div",{children:[e.jsx(re,{children:"License #"}),e.jsx(we,{value:u.license_number,onChange:x=>h({...u,license_number:x.target.value})})]}),e.jsxs("div",{className:"md:col-span-2",children:[e.jsx(re,{children:"Tagline"}),e.jsx(we,{value:u.tagline,onChange:x=>h({...u,tagline:x.target.value}),placeholder:"Helping families find home"})]}),e.jsxs("div",{className:"md:col-span-2",children:[e.jsx(re,{children:"Website"}),e.jsx(we,{value:u.website_url,onChange:x=>h({...u,website_url:x.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(re,{children:"Headshot"}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs(Ua,{className:"h-16 w-16",children:[e.jsx(Gi,{src:u.headshot_url||void 0}),e.jsx(qa,{children:((y=u.display_name)==null?void 0:y[0])??"A"})]}),e.jsxs(B,{type:"button",variant:"outline",size:"sm",onClick:()=>{var x;return(x=l.current)==null?void 0:x.click()},disabled:c==="headshot",children:[c==="headshot"?e.jsx(us,{className:"h-4 w-4 animate-spin"}):e.jsx(ni,{className:"h-4 w-4 mr-1"}),"Upload"]}),e.jsx("input",{ref:l,type:"file",accept:"image/*",hidden:!0,onChange:x=>{var _;return((_=x.target.files)==null?void 0:_[0])&&m("headshot",x.target.files[0])}})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{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 x;return(x=o.current)==null?void 0:x.click()},disabled:c==="logo",children:[c==="logo"?e.jsx(us,{className:"h-4 w-4 animate-spin"}):e.jsx(ni,{className:"h-4 w-4 mr-1"}),"Upload"]}),e.jsx("input",{ref:o,type:"file",accept:"image/*",hidden:!0,onChange:x=>{var _;return((_=x.target.files)==null?void 0:_[0])&&m("logo",x.target.files[0])}})]})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx(re,{children:"Brand color"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("input",{type:"color",value:u.brand_color,onChange:x=>h({...u,brand_color:x.target.value}),className:"h-10 w-14 rounded cursor-pointer border"}),e.jsx(we,{value:u.brand_color,onChange:x=>h({...u,brand_color:x.target.value})})]})]}),e.jsxs("div",{children:[e.jsx(re,{children:"Accent color"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("input",{type:"color",value:u.accent_color,onChange:x=>h({...u,accent_color:x.target.value}),className:"h-10 w-14 rounded cursor-pointer border"}),e.jsx(we,{value:u.accent_color,onChange:x=>h({...u,accent_color:x.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:g,className:"text-destructive",children:[e.jsx(qn,{className:"h-4 w-4 mr-1"})," Delete"]})}),e.jsxs("div",{className:"flex gap-2",children:[n&&e.jsx(B,{variant:"outline",onClick:n,children:"Cancel"}),e.jsxs(B,{onClick:f,disabled:a.isPending,children:[a.isPending&&e.jsx(us,{className:"h-4 w-4 mr-1 animate-spin"}),"Save preset"]})]})]})]})}function RMs(){const{data:s,isLoading:t}=XQ(),[n,r]=N.useState(null);return e.jsx(Qs,{title:"Brand Kit",children:e.jsxs("div",{className:"container max-w-5xl py-6 md:py-8 space-y-6 px-4",children:[e.jsx(ic,{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(cr,{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(nn,{className:"h-4 w-4 mr-1"})," New preset"]})]}),t&&e.jsx("div",{className:"text-sm text-muted-foreground",children:"Loading..."}),!t&&s&&s.length===0&&e.jsx(_e,{className:"border-dashed",children:e.jsxs(De,{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(nn,{className:"h-4 w-4 mr-1"})," Create preset"]})]})}),e.jsx("div",{className:"grid gap-4 md:grid-cols-2",children:s==null?void 0:s.map(a=>e.jsxs(_e,{className:"overflow-hidden",children:[e.jsx("div",{className:"h-3",style:{background:`linear-gradient(90deg, ${a.brand_color}, ${a.accent_color})`}}),e.jsxs(zt,{className:"pb-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs(qt,{className:"text-lg flex items-center gap-2",children:[a.name,a.is_default&&e.jsxs(We,{variant:"secondary",className:"gap-1",children:[e.jsx(Wa,{className:"h-3 w-3"})," Default"]})]}),e.jsx(B,{size:"sm",variant:"ghost",onClick:()=>r(a),children:e.jsx(Ja,{className:"h-4 w-4"})})]}),e.jsx(_r,{children:a.display_name})]}),e.jsxs(De,{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(Bs,{open:n!==null,onOpenChange:a=>!a&&r(null),children:e.jsxs(Fs,{className:"max-w-2xl max-h-[90vh] overflow-y-auto w-[calc(100vw-2rem)] sm:w-full",children:[e.jsx(qs,{children:e.jsx($s,{children:n==="new"?"New brand preset":"Edit brand preset"})}),e.jsx(DMs,{preset:n==="new"?null:n,onSaved:()=>r(null),onCancel:()=>r(null)})]})})]})})}const hOe=[{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"}],OMs=s=>hOe.find(t=>t.id===s)??hOe[0];function FMs(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 zMs({value:s,onChange:t,mediaType:n}){const r=hOe.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:Ot("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(BMs,{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 BMs({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 $Ms=Math.PI/180;function UMs(){return typeof window<"u"&&({}.toString.call(window)==="[object Window]"||{}.toString.call(window)==="[object global]")}const OI=typeof global<"u"?global:typeof window<"u"?window:typeof WorkerGlobalScope<"u"?self:{},Xa={_global:OI,version:"10.2.5",isBrowser:UMs(),isUnminified:/param/.test((function(s){}).toString()),dblClickWindow:400,getAngle(s){return Xa.angleDeg?s*$Ms: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 Xa.DD.isDragging},isTransforming(){var s,t;return(t=(s=Xa.Transformer)===null||s===void 0?void 0:s.isTransforming())!==null&&t!==void 0?t:!1},isDragReady(){return!!Xa.DD.node},releaseCanvasOnDestroy:!0,document:OI.document,_injectGlobal(s){typeof OI.Konva<"u"&&console.error("Several Konva instances detected. It is not recommended to use multiple Konva instances in the same environment."),OI.Konva=s}},Rp=s=>{Xa[s.prototype.getClassName()]=s};Xa._injectGlobal(Xa);const qMs=`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"; `,Nit=()=>{if(typeof document>"u")throw new Error(qMs)};class w_{constructor(t=[1,0,0,1,0,0]){this.dirty=!1,this.m=t&&t.slice()||[1,0,0,1,0,0]}reset(){this.m[0]=1,this.m[1]=0,this.m[2]=0,this.m[3]=1,this.m[4]=0,this.m[5]=0}copy(){return new w_(this.m)}copyInto(t){t.m[0]=this.m[0],t.m[1]=this.m[1],t.m[2]=this.m[2],t.m[3]=this.m[3],t.m[4]=this.m[4],t.m[5]=this.m[5]}point(t){const n=this.m;return{x:n[0]*t.x+n[2]*t.y+n[4],y:n[1]*t.x+n[3]*t.y+n[5]}}translate(t,n){return this.m[4]+=this.m[0]*t+this.m[2]*n,this.m[5]+=this.m[1]*t+this.m[3]*n,this}scale(t,n){return this.m[0]*=t,this.m[1]*=t,this.m[2]*=n,this.m[3]*=n,this}rotate(t){const n=Math.cos(t),r=Math.sin(t),a=this.m[0]*n+this.m[2]*r,i=this.m[1]*n+this.m[3]*r,l=this.m[0]*-r+this.m[2]*n,o=this.m[1]*-r+this.m[3]*n;return this.m[0]=a,this.m[1]=i,this.m[2]=l,this.m[3]=o,this}getTranslation(){return{x:this.m[4],y:this.m[5]}}skew(t,n){const r=this.m[0]+this.m[2]*n,a=this.m[1]+this.m[3]*n,i=this.m[2]+this.m[0]*t,l=this.m[3]+this.m[1]*t;return this.m[0]=r,this.m[1]=a,this.m[2]=i,this.m[3]=l,this}multiply(t){const n=this.m[0]*t.m[0]+this.m[2]*t.m[1],r=this.m[1]*t.m[0]+this.m[3]*t.m[1],a=this.m[0]*t.m[2]+this.m[2]*t.m[3],i=this.m[1]*t.m[2]+this.m[3]*t.m[3],l=this.m[0]*t.m[4]+this.m[2]*t.m[5]+this.m[4],o=this.m[1]*t.m[4]+this.m[3]*t.m[5]+this.m[5];return this.m[0]=n,this.m[1]=r,this.m[2]=a,this.m[3]=i,this.m[4]=l,this.m[5]=o,this}invert(){const t=1/(this.m[0]*this.m[3]-this.m[1]*this.m[2]),n=this.m[3]*t,r=-this.m[1]*t,a=-this.m[2]*t,i=this.m[0]*t,l=t*(this.m[2]*this.m[5]-this.m[3]*this.m[4]),o=t*(this.m[1]*this.m[4]-this.m[0]*this.m[5]);return this.m[0]=n,this.m[1]=r,this.m[2]=a,this.m[3]=i,this.m[4]=l,this.m[5]=o,this}getMatrix(){return this.m}decompose(){const t=this.m[0],n=this.m[1],r=this.m[2],a=this.m[3],i=this.m[4],l=this.m[5],o=t*a-n*r,c={x:i,y:l,rotation:0,scaleX:0,scaleY:0,skewX:0,skewY:0};if(t!=0||n!=0){const d=Math.sqrt(t*t+n*n);c.rotation=n>0?Math.acos(t/d):-Math.acos(t/d),c.scaleX=d,c.scaleY=o/d,c.skewX=(t*r+n*a)/o,c.skewY=0}else if(r!=0||a!=0){const d=Math.sqrt(r*r+a*a);c.rotation=Math.PI/2-(a>0?Math.acos(-r/d):-Math.acos(r/d)),c.scaleX=o/d,c.scaleY=d,c.skewX=0,c.skewY=(t*r+n*a)/o}return c.rotation=Hn._getRotation(c.rotation),c}}const VMs="[object Array]",HMs="[object Number]",GMs="[object String]",WMs="[object Boolean]",KMs=Math.PI/180,YMs=180/Math.PI,zV="#",ZMs="",XMs="0",QMs="Konva warning: ",kit="Konva error: ",JMs="rgb(",YMe={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]},eLs=/rgb\((\d{1,3}),(\d{1,3}),(\d{1,3})\)/;let yse=[],BV=null;const tLs=typeof requestAnimationFrame<"u"&&requestAnimationFrame||function(s){setTimeout(s,16)},Hn={_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)===VMs},_isNumber(s){return Object.prototype.toString.call(s)===HMs&&!isNaN(s)&&isFinite(s)},_isString(s){return Object.prototype.toString.call(s)===GMs},_isBoolean(s){return Object.prototype.toString.call(s)===WMs},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){yse.push(s),yse.length===1&&tLs(function(){const t=yse;yse=[],t.forEach(function(n){n()})})},createCanvasElement(){Nit();const s=document.createElement("canvas");try{s.style=s.style||{}}catch{}return s},createImageElement(){return Nit(),document.createElement("img")},_isInDocument(s){for(;s=s.parentNode;)if(s==document)return!0;return!1},_urlToImage(s,t){const n=Hn.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(zV,ZMs);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=XMs+s;return zV+s},isCanvasFarblingActive(){if(BV!==null)return BV;if(typeof document>"u")return BV=!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 BV=r,this.releaseCanvas(s),BV},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),zV+this._rgbToHex(s,t,n)},getSnappedHexColor(s){const t=this._hexToRgb(s);return zV+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 YMe?(t=YMe[s],{r:t[0],g:t[1],b:t[2]}):s[0]===zV?this._hexToRgb(s.substring(1)):s.substr(0,4)===JMs?(t=eLs.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",Hn._namedColorToRBA(s)||Hn._hex3ColorToRGBA(s)||Hn._hex4ColorToRGBA(s)||Hn._hex6ColorToRGBA(s)||Hn._hex8ColorToRGBA(s)||Hn._rgbColorToRGBA(s)||Hn._rgbaColorToRGBA(s)||Hn._hslColorToRGBA(s)},_namedColorToRBA(s){const t=YMe[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=Hn.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=Hn._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+=nLs+d.join(Sit)+rLs)):(i+=o.property,t||(i+=cLs+o.val)),i+=oLs;return i}clearTrace(){this.traceArr=[]}_trace(t){let n=this.traceArr,r;n.push(t),r=n.length,r>=uLs&&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=Cit.length,r=this.setAttr,a,i;const l=function(o){let c=t[o],d;t[o]=function(){return i=sLs(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 Cd._dragElements.forEach(t=>{s=t.node}),s},_dragElements:new Map,_drag(s){const t=[];Cd._dragElements.forEach((n,r)=>{const{node:a}=n,i=a.getStage();i.setPointersPositions(s),n.pointerId===void 0&&(n.pointerId=Hn._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=[];Cd._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")&&(Cd.justDragged=!0,Xa._mouseListenClick=!1,Xa._touchListenClick=!1,Xa._pointerListenClick=!1,n.dragStatus="stopped");const l=n.node.getLayer()||n.node instanceof Xa.Stage&&n.node;l&&t.indexOf(l)===-1&&t.push(l)}),t.forEach(n=>{n.draw()})},_endDragAfter(s){Cd._dragElements.forEach((t,n)=>{t.dragStatus==="stopped"&&t.node.fire("dragend",{type:"dragend",target:t.node,evt:s},!0),t.dragStatus!=="dragging"&&Cd._dragElements.delete(n)})}};Xa.isBrowser&&(window.addEventListener("mouseup",Cd._endDragBefore,!0),window.addEventListener("touchend",Cd._endDragBefore,!0),window.addEventListener("touchcancel",Cd._endDragBefore,!0),window.addEventListener("mousemove",Cd._drag),window.addEventListener("touchmove",Cd._drag),window.addEventListener("mouseup",Cd._endDragAfter,!1),window.addEventListener("touchend",Cd._endDragAfter,!1),window.addEventListener("touchcancel",Cd._endDragAfter,!1));function HE(s){return Hn._isString(s)?'"'+s+'"':Object.prototype.toString.call(s)==="[object Number]"||Hn._isBoolean(s)?s:Object.prototype.toString.call(s)}function lTt(s){return s>255?255:s<0?0:Math.round(s)}function Va(){if(Xa.isUnminified)return function(s,t){return Hn._isNumber(s)||Hn.warn(HE(s)+' is a not valid value for "'+t+'" attribute. The value should be a number.'),s}}function S3e(s){if(Xa.isUnminified)return function(t,n){let r=Hn._isNumber(t),a=Hn._isArray(t)&&t.length==s;return!r&&!a&&Hn.warn(HE(t)+' is a not valid value for "'+n+'" attribute. The value should be a number or Array('+s+")"),t}}function NVe(){if(Xa.isUnminified)return function(s,t){return Hn._isNumber(s)||s==="auto"||Hn.warn(HE(s)+' is a not valid value for "'+t+'" attribute. The value should be a number or "auto".'),s}}function VR(){if(Xa.isUnminified)return function(s,t){return Hn._isString(s)||Hn.warn(HE(s)+' is a not valid value for "'+t+'" attribute. The value should be a string.'),s}}function cTt(){if(Xa.isUnminified)return function(s,t){const n=Hn._isString(s),r=Object.prototype.toString.call(s)==="[object CanvasGradient]"||s&&s.addColorStop;return n||r||Hn.warn(HE(s)+' is a not valid value for "'+t+'" attribute. The value should be a string or a native gradient.'),s}}function fLs(){if(Xa.isUnminified)return function(s,t){const n=Int8Array?Object.getPrototypeOf(Int8Array):null;return n&&s instanceof n||(Hn._isArray(s)?s.forEach(function(r){Hn._isNumber(r)||Hn.warn('"'+t+'" attribute has non numeric element '+r+". Make sure that all elements are numbers.")}):Hn.warn(HE(s)+' is a not valid value for "'+t+'" attribute. The value should be a array of numbers.')),s}}function bN(){if(Xa.isUnminified)return function(s,t){return s===!0||s===!1||Hn.warn(HE(s)+' is a not valid value for "'+t+'" attribute. The value should be a boolean.'),s}}function gLs(s){if(Xa.isUnminified)return function(t,n){return t==null||Hn.isObject(t)||Hn.warn(HE(t)+' is a not valid value for "'+n+'" attribute. The value should be an object with properties '+s),t}}const $V="get",UV="set",on={addGetterSetter(s,t,n,r,a){on.addGetter(s,t,n),on.addSetter(s,t,r,a),on.addOverloadedGetterSetter(s,t)},addGetter(s,t,n){const r=$V+Hn._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=UV+Hn._capitalize(t);s.prototype[a]||on.overWriteSetter(s,t,n,r)},overWriteSetter(s,t,n,r){const a=UV+Hn._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=Hn._capitalize,o=$V+l(t),c=UV+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},on.addOverloadedGetterSetter(s,t)},addOverloadedGetterSetter(s,t){const n=Hn._capitalize(t),r=UV+n,a=$V+n;s.prototype[t]=function(){return arguments.length?(this[r](arguments[0]),this):this[a]()}},addDeprecatedGetterSetter(s,t,n,r){Hn.error("Adding deprecated "+t);const a=$V+Hn._capitalize(t),i=t+" property is deprecated and will be removed soon. Look at Konva change log for more information.";s.prototype[a]=function(){Hn.error(i);const l=this.attrs[t];return l===void 0?n:l},on.addSetter(s,t,r,function(){Hn.error(i)}),on.addOverloadedGetterSetter(s,t)},backCompat(s,t){Hn.each(t,function(n,r){const a=s.prototype[r],i=$V+Hn._capitalize(n),l=UV+Hn._capitalize(n);function o(){a.apply(this,arguments),Hn.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 xLs(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=Xa.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=Xa.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=Xa.Filters;c&&c.Contrast&&c.Contrast.call(this,l)}}case"grayscale":return function(i){const l=Xa.Filters;l&&l.Grayscale&&l.Grayscale.call(this,i)};case"sepia":return function(i){const l=Xa.Filters;l&&l.Sepia&&l.Sepia.call(this,i)};case"invert":return function(i){const l=Xa.Filters;l&&l.Invert&&l.Invert.call(this,i)};default:Hn.warn(`CSS filter "${r}" is not supported in fallback mode. Consider using function filters for better compatibility.`);break}}return()=>{}}const Zwe="absoluteOpacity",Tit="allEventListeners",ZS="absoluteTransform",Eit="absoluteScale",z6="canvas",yLs="Change",vLs="children",bLs="konva",mOe="listening",_Ls="mouseenter",wLs="mouseleave",jLs="pointerenter",NLs="pointerleave",kLs="touchenter",SLs="touchleave",Mit="set",Lit="Shape",Xwe=" ",Pit="stage",BC="transform",CLs="Stage",pOe="visible",ALs=["xChange.konva","yChange.konva","scaleXChange.konva","scaleYChange.konva","skewXChange.konva","skewYChange.konva","rotationChange.konva","offsetXChange.konva","offsetYChange.konva","transformsEnabledChange.konva"].join(Xwe);let TLs=1,si=class WH{constructor(t){this._id=TLs++,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===BC||t===ZS)&&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===BC||t===ZS)&&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(Xwe);this.on(a,()=>{this._clearCache(t)}),this._attachedDepsListeners.set(t,!0)}return this._getCache(t,r)}_getCanvasCache(){return this._cache.get(z6)}_clearSelfAndDescendantCache(t){this._clearCache(t),t===ZS&&this.fire("absoluteTransformChange")}clearCache(){if(this._cache.has(z6)){const{scene:t,filter:n,hit:r}=this._cache.get(z6);Hn.releaseCanvas(t._canvas,n._canvas,r._canvas),this._cache.delete(z6)}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){Hn.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,f=Math.abs(Math.round(r.y)-c)>.5?1:0;a+=d*2+m,i+=d*2+f,o-=d,c-=d;const g=new mA({pixelRatio:l,width:a,height:i}),y=new mA({pixelRatio:l,width:0,height:0,willReadFrequently:!0}),x=new jVe({pixelRatio:h,width:a,height:i}),_=g.getContext(),b=x.getContext(),k=new mA({width:g.width/g.pixelRatio+Math.abs(o),height:g.height/g.pixelRatio+Math.abs(c),pixelRatio:g.pixelRatio}),A=k.getContext();return x.isCache=!0,g.isCache=!0,this._cache.delete(z6),this._filterUpToDate=!1,n.imageSmoothingEnabled===!1&&(g.getContext()._context.imageSmoothingEnabled=!1,y.getContext()._context.imageSmoothingEnabled=!1),_.save(),b.save(),A.save(),_.translate(-o,-c),b.translate(-o,-c),A.translate(-o,-c),k.x=o,k.y=c,this._isUnderCache=!0,this._clearSelfAndDescendantCache(Zwe),this._clearSelfAndDescendantCache(Eit),this.drawScene(g,this,k),this.drawHit(x,this),this._isUnderCache=!1,_.restore(),b.restore(),u&&(_.save(),_.beginPath(),_.rect(0,0,a,i),_.closePath(),_.setAttr("strokeStyle","red"),_.setAttr("lineWidth",5),_.stroke(),_.restore()),Hn.releaseCanvas(k._canvas),this._cache.set(z6,{scene:g,filter:y,hit:x,x:o,y:c}),this._requestDraw(),this}isCached(){return this._cache.has(z6)}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)&&Cd._dragElements.delete(n)}),this._remove(),this}_clearCaches(){this._clearSelfAndDescendantCache(ZS),this._clearSelfAndDescendantCache(Zwe),this._clearSelfAndDescendantCache(Eit),this._clearSelfAndDescendantCache(Pit),this._clearSelfAndDescendantCache(pOe),this._clearSelfAndDescendantCache(mOe)}_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"+Hn._capitalize(t);return Hn._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!==vLs&&(r=Mit+Hn._capitalize(n),Hn._isFunction(this[r])?this[r](t[n]):this._setAttr(n,t[n]))}),this}isListening(){return this._getCache(mOe,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(pOe,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;Cd._dragElements.forEach(l=>{l.dragStatus==="dragging"&&(l.node.nodeType==="Stage"||l.node.getLayer()===r)&&(a=!0)});const i=!n&&!Xa.hitOnDragEnabled&&(a||Xa.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!==CLs&&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(BC),this._clearSelfAndDescendantCache(ZS)),this._needClearTransformCache=!1}setPosition(t){return this._batchTransformChanges(()=>{this.x(t.x),this.y(t.y)}),this}getPosition(){return{x:this.x(),y:this.y()}}getRelativePointerPosition(){const t=this.getStage();if(!t)return null;const n=t.getPointerPosition();if(!n)return null;const r=this.getAbsoluteTransform().copy();return r.invert(),r.point(n)}getAbsolutePosition(t){let n=!1,r=this.parent;for(;r;){if(r.isCached()){n=!0;break}r=r.parent}n&&!t&&(t=!0);const a=this.getAbsoluteTransform(t).getMatrix(),i=new w_,l=this.offset();return i.m=a.slice(),i.translate(l.x,l.y),i.getTranslation()}setAbsolutePosition(t){const{x:n,y:r,...a}=this._clearTransform();this.attrs.x=n,this.attrs.y=r,this._clearCache(BC);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(BC),this._clearSelfAndDescendantCache(ZS),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 Hn.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 Hn.warn("Node has no parent. zIndex parameter is ignored."),this;(t<0||t>=this.parent.children.length)&&Hn.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(Zwe,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=Hn.isObject(r)&&!Hn._isPlainObject(r)&&!Hn._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 Hn._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,Hn._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():Xa.dragDistance}_off(t,n,r){let a=this.eventListeners[t],i,l,o;for(i=0;i=0)||this.isDragging())return;let a=!1;Cd._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=Cd._dragElements.get(this._id),r=n&&n.dragStatus==="dragging",a=n&&n.dragStatus==="ready";r?this.stopDrag():a&&Cd._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 Hn.haveIntersection(r,this.getClientRect())}static create(t,n){return Hn._isString(t)&&(t=JSON.parse(t)),this._createNode(t,n)}static _createNode(t,n){let r=WH.prototype.getClassName.call(t),a=t.children,i,l,o;n&&(t.attrs.container=n),Xa[r]||(Hn.warn('Can not find a node with class name "'+r+'". Fallback to "Shape".'),r="Shape");const c=Xa[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=si.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=si.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 f=this.getAbsoluteTransform(r);let g=f.getMatrix();l.transform(g[0],g[1],g[2],g[3],g[4],g[5]),l.beginPath();let y;if(d)y=d.call(this,l,this);else{const x=this.clipX(),_=this.clipY();l.rect(x||0,_||0,o,c)}l.clip.apply(l,y),g=f.copy().invert().getMatrix(),l.transform(g[0],g[1],g[2],g[3],g[4],g[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(f){f[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(f){if(!f.visible())return;const g=f.getClientRect({relativeTo:u,skipShadow:t.skipShadow,skipStroke:t.skipStroke});g.width===0&&g.height===0||(i===void 0?(i=g.x,l=g.y,o=g.x+g.width,c=g.y+g.height):(i=Math.min(i,g.x),l=Math.min(l,g.y),o=Math.max(o,g.x+g.width),c=Math.max(c,g.y+g.height)))});const h=this.find("Shape");let m=!1;for(let f=0;fs.indexOf("pointer")>=0?"pointer":s.indexOf("touch")>=0?"touch":"mouse",yF=s=>{const t=QH(s);if(t==="pointer")return Xa.pointerEventsEnabled&&XMe.pointer;if(t==="touch")return XMe.touch;if(t==="mouse")return XMe.mouse};function Dit(s={}){return(s.clipFunc||s.clipWidth||s.clipHeight)&&Hn.warn("Stage does not support clipping. Please use clip for Layers or Groups."),s}const RLs="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);",cK=[];let C3e=class extends I_{constructor(t){super(Dit(t)),this._pointerPositions=[],this._changedPointerPositions=[],this._buildDOM(),this._bindContentEvents(),cK.push(this),this.on("widthChange.konva heightChange.konva",this._resizeDOM),this.on("visibleChange.konva",this._checkVisibility),this.on("clipWidthChange.konva clipHeightChange.konva clipFuncChange.konva",()=>{Dit(this.attrs)}),this._checkVisibility()}_validateAdd(t){const n=t.getType()==="Layer",r=t.getType()==="FastLayer";n||r||Hn.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===MLs){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&&cK.splice(n,1),Hn.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}:(Hn.warn(RLs),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 mA({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+Iit,this.content.style.height=n+Iit),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;aILs&&Hn.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(),Xa.isBrowser&&this.content.appendChild(t.canvas._canvas),this}getParent(){return null}getLayer(){return null}hasPointerCapture(t){return uTt(t,this)}setPointerCapture(t){hTt(t,this)}releaseCapture(t){lK(t)}getLayers(){return this.children}_bindContentEvents(){Xa.isBrowser&&DLs.forEach(([t,n])=>{this.content.addEventListener(t,r=>{this[n](r)},{passive:!1})})}_pointerenter(t){this.setPointersPositions(t);const n=yF(t.type);n&&this._fire(n.pointerenter,{evt:t,target:this,currentTarget:this})}_pointerover(t){this.setPointersPositions(t);const n=yF(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=yF(t.type),r=QH(t.type);if(!n)return;this.setPointersPositions(t);const a=this._getTargetShape(r),i=!(Xa.isDragging()||Xa.isTransforming())||Xa.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=yF(t.type),r=QH(t.type);if(!n)return;this.setPointersPositions(t);let a=!1;this._changedPointerPositions.forEach(i=>{const l=this.getIntersection(i);if(Cd.justDragged=!1,Xa["_"+r+"ListenClick"]=!0,!l||!l.isListening()){this[r+"ClickStartShape"]=void 0;return}Xa.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=yF(t.type),r=QH(t.type);if(!n)return;const a=t.type.indexOf("touch")>=0||t.pointerType==="touch";if(Xa.isDragging()&&Cd.node.preventDefault()&&t.cancelable&&a&&t.preventDefault(),this.setPointersPositions(t),!(!(Xa.isDragging()||Xa.isTransforming())||Xa.hitOnDragEnabled))return;const l={};let o=!1;const c=this._getTargetShape(r);this._changedPointerPositions.forEach(d=>{const u=ZMe(d.id)||this.getIntersection(d),h=d.id,m={evt:t,pointerId:h},f=c!==u;if(f&&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,f&&(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=yF(t.type),r=QH(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=ZMe(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;Xa["_"+r+"InDblClickWindow"]?(m=!0,clearTimeout(this[r+"DblTimeout"])):Cd.justDragged||(Xa["_"+r+"InDblClickWindow"]=!0,clearTimeout(this[r+"DblTimeout"])),this[r+"DblTimeout"]=setTimeout(function(){Xa["_"+r+"InDblClickWindow"]=!1},Xa.dblClickWindow),d&&d.isListening()?(o=!0,this[r+"ClickEndShape"]=d,d._fireAndBubble(n.pointerup,{...h}),Xa["_"+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),Xa["_"+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}),Xa["_"+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(fOe,{evt:t}):this._fire(fOe,{evt:t,target:this,currentTarget:this})}_wheel(t){this.setPointersPositions(t);const n=this.getIntersection(this.getPointerPosition());n&&n.isListening()?n._fireAndBubble(gOe,{evt:t}):this._fire(gOe,{evt:t,target:this,currentTarget:this})}_pointercancel(t){this.setPointersPositions(t);const n=ZMe(t.pointerId)||this.getIntersection(this.getPointerPosition());n&&n._fireAndBubble(F7,kVe(t)),lK(t.pointerId)}_lostpointercapture(t){lK(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:Hn._getFirstPointerId(t)}],this._changedPointerPositions=[{x:r,y:a,id:Hn._getFirstPointerId(t)}])}_setPointerPosition(t){Hn.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 mA({width:this.width(),height:this.height()}),this.bufferHitCanvas=new jVe({pixelRatio:1,width:this.width(),height:this.height()}),!Xa.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 Hn.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}};C3e.prototype.nodeType=ELs;Rp(C3e);on.addGetterSetter(C3e,"container");Xa.isBrowser&&document.addEventListener("visibilitychange",()=>{cK.forEach(s=>{s.batchDraw()})});const jTt="hasShadow",NTt="shadowRGBA",kTt="patternImage",STt="linearGradient",CTt="radialGradient";let Nse;function QMe(){return Nse||(Nse=Hn.createCanvasElement().getContext("2d"),Nse)}const dK={};function OLs(s){const t=this.attrs.fillRule;t?s.fill(t):s.fill()}function FLs(s){s.stroke()}function zLs(s){const t=this.attrs.fillRule;t?s.fill(t):s.fill()}function BLs(s){s.stroke()}function $Ls(){this._clearCache(jTt)}function ULs(){this._clearCache(NTt)}function qLs(){this._clearCache(kTt)}function VLs(){this._clearCache(STt)}function HLs(){this._clearCache(CTt)}let Ia=class extends si{constructor(t){super(t);let n,r=0;for(;n=Hn.getHitColor(),!(n&&!(n in dK));)if(r++,r>=1e4){Hn.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=Hn.getRandomColor();break}this.colorKey=n,dK[n]=this}getContext(){return Hn.warn("shape.getContext() method is deprecated. Please do not use it."),this.getLayer().getContext()}getCanvas(){return Hn.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(jTt,this._hasShadow)}_hasShadow(){return this.shadowEnabled()&&this.shadowOpacity()!==0&&!!(this.shadowColor()||this.shadowBlur()||this.shadowOffsetX()||this.shadowOffsetY())}_getFillPattern(){return this._getCache(kTt,this.__getFillPattern)}__getFillPattern(){if(this.fillPatternImage()){const n=QMe().createPattern(this.fillPatternImage(),this.fillPatternRepeat()||"repeat");if(n&&n.setTransform){const r=new w_;r.translate(this.fillPatternX(),this.fillPatternY()),r.rotate(Xa.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(STt,this.__getLinearGradient)}__getLinearGradient(){const t=this.fillLinearGradientColorStops();if(t){const n=QMe(),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 si.prototype.destroy.call(this),delete dK[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){Hn.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,f=h?this.shadowOffsetY():0,g=d+Math.abs(m),y=u+Math.abs(f),x=h&&this.shadowBlur()||0,_=g+x*2,b=y+x*2,k={width:_,height:b,x:-(c/2+x)+Math.min(m,0)+l.x,y:-(c/2+x)+Math.min(f,0)+l.y};return a?k:this._transformedRect(k,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 f=this.getAbsoluteTransform(n).getMatrix();return l.transform(f[0],f[1],f[2],f[3],f[4],f[5]),this._drawCachedSceneCanvas(l),l.restore(),this}if(!c)return this;if(l.save(),this._useBufferCanvas()&&!h){u=this.getStage();const f=r||u.bufferCanvas,g=f.getContext();r?(g.save(),g.setTransform(1,0,0,1,0,0),g.clearRect(0,0,f.width,f.height),g.restore()):g.clear(),g.save(),g._applyLineJoin(this),g._applyMiterLimit(this);const y=this.getAbsoluteTransform(n).getMatrix();g.transform(y[0],y[1],y[2],y[3],y[4],y[5]),c.call(this,g,this),g.restore();const x=f.pixelRatio;d&&l._applyShadow(this),m||(l._applyOpacity(this),l._applyGlobalCompositeOperation(this)),l.drawImage(f._canvas,f.x||0,f.y||0,f.width/x,f.height/x)}else{if(l._applyLineJoin(this),l._applyMiterLimit(this),!m){const f=this.getAbsoluteTransform(n).getMatrix();l.transform(f[0],f[1],f[2],f[3],f[4],f[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||Hn.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=Hn._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){Hn.error("Unable to draw hit graph from cached scene canvas. "+c.message)}return this}hasPointerCapture(t){return uTt(t,this)}setPointerCapture(t){hTt(t,this)}releaseCapture(t){lK(t)}};Ia.prototype._fillFunc=OLs;Ia.prototype._strokeFunc=FLs;Ia.prototype._fillFuncHit=zLs;Ia.prototype._strokeFuncHit=BLs;Ia.prototype._centroid=!1;Ia.prototype.nodeType="Shape";Rp(Ia);Ia.prototype.eventListeners={};Ia.prototype.on("shadowColorChange.konva shadowBlurChange.konva shadowOffsetChange.konva shadowOpacityChange.konva shadowEnabledChange.konva",$Ls);Ia.prototype.on("shadowColorChange.konva shadowOpacityChange.konva shadowEnabledChange.konva",ULs);Ia.prototype.on("fillPriorityChange.konva fillPatternImageChange.konva fillPatternRepeatChange.konva fillPatternScaleXChange.konva fillPatternScaleYChange.konva fillPatternOffsetXChange.konva fillPatternOffsetYChange.konva fillPatternXChange.konva fillPatternYChange.konva fillPatternRotationChange.konva",qLs);Ia.prototype.on("fillPriorityChange.konva fillLinearGradientColorStopsChange.konva fillLinearGradientStartPointXChange.konva fillLinearGradientStartPointYChange.konva fillLinearGradientEndPointXChange.konva fillLinearGradientEndPointYChange.konva",VLs);Ia.prototype.on("fillPriorityChange.konva fillRadialGradientColorStopsChange.konva fillRadialGradientStartPointXChange.konva fillRadialGradientStartPointYChange.konva fillRadialGradientEndPointXChange.konva fillRadialGradientEndPointYChange.konva fillRadialGradientStartRadiusChange.konva fillRadialGradientEndRadiusChange.konva",HLs);on.addGetterSetter(Ia,"stroke",void 0,cTt());on.addGetterSetter(Ia,"strokeWidth",2,Va());on.addGetterSetter(Ia,"fillAfterStrokeEnabled",!1);on.addGetterSetter(Ia,"hitStrokeWidth","auto",NVe());on.addGetterSetter(Ia,"strokeHitEnabled",!0,bN());on.addGetterSetter(Ia,"perfectDrawEnabled",!0,bN());on.addGetterSetter(Ia,"shadowForStrokeEnabled",!0,bN());on.addGetterSetter(Ia,"lineJoin");on.addGetterSetter(Ia,"lineCap");on.addGetterSetter(Ia,"miterLimit");on.addGetterSetter(Ia,"sceneFunc");on.addGetterSetter(Ia,"hitFunc");on.addGetterSetter(Ia,"dash");on.addGetterSetter(Ia,"dashOffset",0,Va());on.addGetterSetter(Ia,"shadowColor",void 0,VR());on.addGetterSetter(Ia,"shadowBlur",0,Va());on.addGetterSetter(Ia,"shadowOpacity",1,Va());on.addComponentsGetterSetter(Ia,"shadowOffset",["x","y"]);on.addGetterSetter(Ia,"shadowOffsetX",0,Va());on.addGetterSetter(Ia,"shadowOffsetY",0,Va());on.addGetterSetter(Ia,"fillPatternImage");on.addGetterSetter(Ia,"fill",void 0,cTt());on.addGetterSetter(Ia,"fillPatternX",0,Va());on.addGetterSetter(Ia,"fillPatternY",0,Va());on.addGetterSetter(Ia,"fillLinearGradientColorStops");on.addGetterSetter(Ia,"strokeLinearGradientColorStops");on.addGetterSetter(Ia,"fillRadialGradientStartRadius",0);on.addGetterSetter(Ia,"fillRadialGradientEndRadius",0);on.addGetterSetter(Ia,"fillRadialGradientColorStops");on.addGetterSetter(Ia,"fillPatternRepeat","repeat");on.addGetterSetter(Ia,"fillEnabled",!0);on.addGetterSetter(Ia,"strokeEnabled",!0);on.addGetterSetter(Ia,"shadowEnabled",!0);on.addGetterSetter(Ia,"dashEnabled",!0);on.addGetterSetter(Ia,"strokeScaleEnabled",!0);on.addGetterSetter(Ia,"fillPriority","color");on.addComponentsGetterSetter(Ia,"fillPatternOffset",["x","y"]);on.addGetterSetter(Ia,"fillPatternOffsetX",0,Va());on.addGetterSetter(Ia,"fillPatternOffsetY",0,Va());on.addComponentsGetterSetter(Ia,"fillPatternScale",["x","y"]);on.addGetterSetter(Ia,"fillPatternScaleX",1,Va());on.addGetterSetter(Ia,"fillPatternScaleY",1,Va());on.addComponentsGetterSetter(Ia,"fillLinearGradientStartPoint",["x","y"]);on.addComponentsGetterSetter(Ia,"strokeLinearGradientStartPoint",["x","y"]);on.addGetterSetter(Ia,"fillLinearGradientStartPointX",0);on.addGetterSetter(Ia,"strokeLinearGradientStartPointX",0);on.addGetterSetter(Ia,"fillLinearGradientStartPointY",0);on.addGetterSetter(Ia,"strokeLinearGradientStartPointY",0);on.addComponentsGetterSetter(Ia,"fillLinearGradientEndPoint",["x","y"]);on.addComponentsGetterSetter(Ia,"strokeLinearGradientEndPoint",["x","y"]);on.addGetterSetter(Ia,"fillLinearGradientEndPointX",0);on.addGetterSetter(Ia,"strokeLinearGradientEndPointX",0);on.addGetterSetter(Ia,"fillLinearGradientEndPointY",0);on.addGetterSetter(Ia,"strokeLinearGradientEndPointY",0);on.addComponentsGetterSetter(Ia,"fillRadialGradientStartPoint",["x","y"]);on.addGetterSetter(Ia,"fillRadialGradientStartPointX",0);on.addGetterSetter(Ia,"fillRadialGradientStartPointY",0);on.addComponentsGetterSetter(Ia,"fillRadialGradientEndPoint",["x","y"]);on.addGetterSetter(Ia,"fillRadialGradientEndPointX",0);on.addGetterSetter(Ia,"fillRadialGradientEndPointY",0);on.addGetterSetter(Ia,"fillPatternRotation",0);on.addGetterSetter(Ia,"fillRule",void 0,VR());on.backCompat(Ia,{dashArray:"dash",getDashArray:"getDash",setDashArray:"getDash",drawFunc:"sceneFunc",getDrawFunc:"getSceneFunc",setDrawFunc:"setSceneFunc",drawHitFunc:"hitFunc",getDrawHitFunc:"getHitFunc",setDrawHitFunc:"setHitFunc"});const GLs="beforeDraw",WLs="draw",ATt=[{x:0,y:0},{x:-1,y:-1},{x:1,y:-1},{x:1,y:1},{x:-1,y:1}],KLs=ATt.length;let HR=class extends I_{constructor(t){super(t),this.canvas=new mA,this.hitCanvas=new jVe({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(GLs,{node:this}),this.clearBeforeDraw()&&i.getContext().clear(),I_.prototype.drawScene.call(this,i,n,r),this._fire(WLs,{node:this}),this}drawHit(t,n){const r=this.getLayer(),a=t||r&&r.hitCanvas;return r&&r.clearBeforeDraw()&&r.getHitCanvas().getContext().clear(),I_.prototype.drawHit.call(this,a,n),this}enableHitGraph(){return this.hitGraphEnabled(!0),this}disableHitGraph(){return this.hitGraphEnabled(!1),this}setHitGraphEnabled(t){Hn.warn("hitGraphEnabled method is deprecated. Please use layer.listening() instead."),this.listening(t)}getHitGraphEnabled(t){return Hn.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 Hn.releaseCanvas(this.getNativeCanvasElement(),this.getHitCanvas()._canvas),super.destroy()}};HR.prototype.nodeType="Layer";Rp(HR);on.addGetterSetter(HR,"imageSmoothingEnabled",!0);on.addGetterSetter(HR,"clearBeforeDraw",!0);on.addGetterSetter(HR,"hitGraphEnabled",!0,bN());class SVe extends HR{constructor(t){super(t),this.listening(!1),Hn.warn('Konva.Fast layer is deprecated. Please use "new Konva.Layer({ listening: false })" instead.')}}SVe.prototype.nodeType="FastLayer";Rp(SVe);let ZB=class extends I_{_validateAdd(t){const n=t.getType();n!=="Group"&&n!=="Shape"&&Hn.throw("You may only add groups and shapes to groups.")}};ZB.prototype.nodeType="Group";Rp(ZB);const JMe=function(){return OI.performance&&OI.performance.now?function(){return OI.performance.now()}:function(){return new Date().getTime()}}();class Yw{constructor(t,n){this.id=Yw.animIdCounter++,this.frame={time:0,timeDiff:0,lastTime:JMe(),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=Rit,this._startTime=this.getTimer()-this._time,this.onEnterFrame(),this.fire("onPlay")}reverse(){this.state=Oit,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===Rit?this.setTime(t):this.state===Oit&&this.setTime(this.duration-t)}pause(){this.state=ZLs,this.fire("onPause")}getTimer(){return new Date().getTime()}}class Mh{constructor(t){const n=this,r=t.node,a=r._id,i=t.easing||uK.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=XLs++;const d=r.getLayer()||(r instanceof Xa.Stage?r.getLayers():null);d||Hn.error("Tween constructor have `node` that is not in a layer. Please add node into layer first."),this.anim=new Yw(function(){n.tween.onEnterFrame()},d),this.tween=new QLs(c,function(u){n._tweenFunc(u)},i,0,1,o*1e3,l),this._addListeners(),Mh.attrs[a]||(Mh.attrs[a]={}),Mh.attrs[a][this._id]||(Mh.attrs[a][this._id]={}),Mh.tweens[a]||(Mh.tweens[a]={});for(c in t)YLs[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=Mh.tweens[a][t];u&&delete Mh.attrs[a][u][t];let h=r.getAttr(t);if(Hn._isArray(n))if(i=[],l=Math.max(n.length,h.length),t==="points"&&n.length!==h.length&&(n.length>h.length?(c=h,h=Hn._prepareArrayForTween(h,n,r.closed())):(o=n,n=Hn._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=Mh.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=Mh.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=Mh.tweens[t];this.pause(),this.anim&&this.anim.stop();for(const a in r)delete Mh.tweens[t][a];delete Mh.attrs[t][n],Mh.tweens[t]&&(Object.keys(Mh.tweens[t]).length===0&&delete Mh.tweens[t],Object.keys(Mh.attrs[t]).length===0&&delete Mh.attrs[t])}}Mh.attrs={};Mh.tweens={};si.prototype.to=function(s){const t=s.onFinish;s.node=this,s.onFinish=function(){this.destroy(),t&&t()},new Mh(s).play()};const uK={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}}}B3.prototype._centroid=!0;B3.prototype.className="Arc";B3.prototype._attrsAffectingSize=["innerRadius","outerRadius","angle","clockwise"];Rp(B3);on.addGetterSetter(B3,"innerRadius",0,Va());on.addGetterSetter(B3,"outerRadius",0,Va());on.addGetterSetter(B3,"angle",0,Va());on.addGetterSetter(B3,"clockwise",!1,bN());function xOe(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),f=n+u*(a-s),g=r+u*(i-t);return[h,m,f,g]}function zit(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 $3=class extends Ia{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*ePs[20][o]+l,r+=tPs[20][o]*nPs(s,t,a);return l*r},$it=(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,f=h-u*u,g=m*m+f>0?Math.sqrt(m*m+f):0,y=u*u+f>0?Math.sqrt(u*u+f):0,x=u+Math.sqrt(u*u+f)!==0?f*Math.log(Math.abs((m+g)/(u+y))):0;return Math.sqrt(o)/2*(m*g-u*y+x)};function nPs(s,t,n){const r=yOe(1,n,s),a=yOe(1,n,t),i=r*r+a*a;return Math.sqrt(i)}const yOe=(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+=sPs[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 Zw=class L1 extends Ia{constructor(t){super(t),this.dataArray=[],this.pathLength=0,this._readDataAttribute(),this.on("dataChange.konva",function(){this._readDataAttribute()})}_readDataAttribute(){this.dataArray=L1.parsePathData(this.data()),this.pathLength=L1.getPathLength(this.dataArray)}_sceneFunc(t){const n=this.dataArray;t.beginPath();let r=!1;for(let a=0;au?d:u,x=d>u?1:d/u,_=d>u?u/d:1;t.translate(o,c),t.rotate(f),t.scale(x,_),t.arc(0,0,y,h,h+m,1-g),t.scale(1/x,1/_),t.rotate(-f),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;f-=m){const g=L1.getPointOnEllipticalArc(c.points[0],c.points[1],c.points[2],c.points[3],f,0);t.push(g.x,g.y)}else for(let f=d+m;fn[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 L1.getPointOnLine(t,l.start.x,l.start.y,o[0],o[1]);case"C":return L1.getPointOnCubicBezier(Uit(t,L1.getPathLength(n),y=>Bit([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 L1.getPointOnQuadraticBezier(Uit(t,L1.getPathLength(n),y=>$it([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],f=o[6];let g=o[4];return g+=m*t/l.pathLength,L1.getPointOnEllipticalArc(c,d,u,h,g,f)}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)){g.push(parseInt(b[0],10)),g.push(parseInt(b[1],10)),g.push(parseFloat(b.slice(2))),y+=3,y>=7&&(y-=7);continue}if(b==="11"||b==="10"||b==="01"){g.push(parseInt(b[0],10)),g.push(parseInt(b[1],10)),y+=2,y>=7&&(y-=7);continue}if(b==="0"||b==="1"){g.push(parseInt(b,10)),y+=1,y>=7&&(y-=7);continue}}else if(y===4){if(/^[01]\d+(?:\.\d+)?$/.test(b)){g.push(parseInt(b[0],10)),g.push(parseFloat(b.slice(1))),y+=2,y>=7&&(y-=7);continue}if(b==="0"||b==="1"){g.push(parseInt(b,10)),y+=1,y>=7&&(y-=7);continue}}const k=parseFloat(b);isNaN(k)?g.push(0):g.push(k),y+=1,y>=7&&(y-=7)}else{const k=parseFloat(b);isNaN(k)?g.push(0):g.push(k)}}for(;g.length>0&&!isNaN(g[0]);){let x="",_=[];const b=o,k=c;let A,T,P,I,M,L,z,$,V,W;switch(f){case"l":o+=g.shift(),c+=g.shift(),x="L",_.push(o,c);break;case"L":o=g.shift(),c=g.shift(),_.push(o,c);break;case"m":const G=g.shift(),X=g.shift();if(o+=G,c+=X,x="M",i.length>2&&i[i.length-1].command==="z"){for(let te=i.length-2;te>=0;te--)if(i[te].command==="M"){o=i[te].points[0]+G,c=i[te].points[1]+X;break}}_.push(o,c),f="l";break;case"M":o=g.shift(),c=g.shift(),x="M",_.push(o,c),f="L";break;case"h":o+=g.shift(),x="L",_.push(o,c);break;case"H":o=g.shift(),x="L",_.push(o,c);break;case"v":c+=g.shift(),x="L",_.push(o,c);break;case"V":c=g.shift(),x="L",_.push(o,c);break;case"C":_.push(g.shift(),g.shift(),g.shift(),g.shift()),o=g.shift(),c=g.shift(),_.push(o,c);break;case"c":_.push(o+g.shift(),c+g.shift(),o+g.shift(),c+g.shift()),o+=g.shift(),c+=g.shift(),x="C",_.push(o,c);break;case"S":T=o,P=c,A=i[i.length-1],A.command==="C"&&(T=o+(o-A.points[2]),P=c+(c-A.points[3])),_.push(T,P,g.shift(),g.shift()),o=g.shift(),c=g.shift(),x="C",_.push(o,c);break;case"s":T=o,P=c,A=i[i.length-1],A.command==="C"&&(T=o+(o-A.points[2]),P=c+(c-A.points[3])),_.push(T,P,o+g.shift(),c+g.shift()),o+=g.shift(),c+=g.shift(),x="C",_.push(o,c);break;case"Q":_.push(g.shift(),g.shift()),o=g.shift(),c=g.shift(),_.push(o,c);break;case"q":_.push(o+g.shift(),c+g.shift()),o+=g.shift(),c+=g.shift(),x="Q",_.push(o,c);break;case"T":T=o,P=c,A=i[i.length-1],A.command==="Q"&&(T=o+(o-A.points[0]),P=c+(c-A.points[1])),o=g.shift(),c=g.shift(),x="Q",_.push(T,P,o,c);break;case"t":T=o,P=c,A=i[i.length-1],A.command==="Q"&&(T=o+(o-A.points[0]),P=c+(c-A.points[1])),o+=g.shift(),c+=g.shift(),x="Q",_.push(T,P,o,c);break;case"A":I=g.shift(),M=g.shift(),L=g.shift(),z=g.shift(),$=g.shift(),V=o,W=c,o=g.shift(),c=g.shift(),x="A",_=this.convertEndpointToCenterParameterization(V,W,o,c,z,$,I,M,L);break;case"a":I=g.shift(),M=g.shift(),L=g.shift(),z=g.shift(),$=g.shift(),V=o,W=c,o+=g.shift(),c+=g.shift(),x="A",_=this.convertEndpointToCenterParameterization(V,W,o,c,z,$,I,M,L);break}i.push({command:x||f,points:_,start:{x:b,y:k},pathLength:this.calcLength(b,k,x||f,_)})}(f==="z"||f==="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=L1;switch(r){case"L":return d.getLineLength(t,n,a[0],a[1]);case"C":return Bit([t,a[0],a[2],a[4]],[n,a[1],a[3],a[5]],1);case"Q":return $it([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 f=Math.PI/180;if(Math.abs(u-m)m;c-=f)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+f;c1&&(o*=Math.sqrt(f),c*=Math.sqrt(f));let g=Math.sqrt((o*o*(c*c)-o*o*(m*m)-c*c*(h*h))/(o*o*(m*m)+c*c*(h*h)));i===l&&(g*=-1),isNaN(g)&&(g=0);const y=g*o*m/c,x=g*-c*h/o,_=(t+r)/2+Math.cos(u)*y-Math.sin(u)*x,b=(n+a)/2+Math.sin(u)*y+Math.cos(u)*x,k=function(z){return Math.sqrt(z[0]*z[0]+z[1]*z[1])},A=function(z,$){return(z[0]*$[0]+z[1]*$[1])/(k(z)*k($))},T=function(z,$){return(z[0]*$[1]=1&&(L=0),l===0&&L>0&&(L=L-2*Math.PI),l===1&&L<0&&(L=L+2*Math.PI),[_,b,o,c,P,L,u,l]}};Zw.prototype.className="Path";Zw.prototype._attrsAffectingSize=["data"];Rp(Zw);on.addGetterSetter(Zw,"data");class GR extends $3{_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]],f=Zw.calcLength(a[a.length-4],a[a.length-3],"C",m),g=Zw.getPointOnQuadraticBezier(Math.min(1,1-l/f),m[0],m[1],m[2],m[3],m[4],m[5]);c=r[o-2]-g.x,d=r[o-1]-g.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}}}GR.prototype.className="Arrow";Rp(GR);on.addGetterSetter(GR,"pointerLength",10,Va());on.addGetterSetter(GR,"pointerWidth",10,Va());on.addGetterSetter(GR,"pointerAtBeginning",!1);on.addGetterSetter(GR,"pointerAtEnding",!0);class bU extends Ia{_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)}}bU.prototype._centroid=!0;bU.prototype.className="Circle";bU.prototype._attrsAffectingSize=["radius"];Rp(bU);on.addGetterSetter(bU,"radius",0,Va());class GE extends Ia{_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)}}GE.prototype.className="Ellipse";GE.prototype._centroid=!0;GE.prototype._attrsAffectingSize=["radiusX","radiusY"];Rp(GE);on.addComponentsGetterSetter(GE,"radius",["x","y"]);on.addGetterSetter(GE,"radiusX",0,Va());on.addGetterSetter(GE,"radiusY",0,Va());let _N=class TTt extends Ia{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?Hn.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?Hn.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=Hn.createImageElement();a.onload=function(){const i=new TTt({image:a});n(i)},a.onerror=r,a.crossOrigin="Anonymous",a.src=t}};_N.prototype.className="Image";_N.prototype._attrsAffectingSize=["image"];Rp(_N);on.addGetterSetter(_N,"cornerRadius",0,S3e(4));on.addGetterSetter(_N,"image");on.addComponentsGetterSetter(_N,"crop",["x","y","width","height"]);on.addGetterSetter(_N,"cropX",0,Va());on.addGetterSetter(_N,"cropY",0,Va());on.addGetterSetter(_N,"cropWidth",0,Va());on.addGetterSetter(_N,"cropHeight",0,Va());const ETt=["fontFamily","fontSize","fontStyle","padding","lineHeight","text","width","height","pointerDirection","pointerWidth","pointerHeight"],rPs="Change.konva",aPs="none",vOe="up",bOe="right",_Oe="down",wOe="left",iPs=ETt.length;let CVe=class extends ZB{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)}}WE.prototype.className="RegularPolygon";WE.prototype._centroid=!0;WE.prototype._attrsAffectingSize=["radius"];Rp(WE);on.addGetterSetter(WE,"radius",0,Va());on.addGetterSetter(WE,"sides",0,Va());on.addGetterSetter(WE,"cornerRadius",0,S3e(4));const qit=Math.PI*2;let KR=class extends Ia{_sceneFunc(t){t.beginPath(),t.arc(0,0,this.innerRadius(),0,qit,!1),t.moveTo(this.outerRadius(),0),t.arc(0,0,this.outerRadius(),qit,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)}};KR.prototype.className="Ring";KR.prototype._centroid=!0;KR.prototype._attrsAffectingSize=["innerRadius","outerRadius"];Rp(KR);on.addGetterSetter(KR,"innerRadius",0,Va());on.addGetterSetter(KR,"outerRadius",0,Va());class K5 extends Ia{constructor(t){super(t),this._updated=!0,this.anim=new Yw(()=>{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],f=r*2;t.drawImage(h,o,c,d,u,m[f+0],m[f+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 vF="auto",oPs="center",MTt="inherit",qV="justify",lPs="Change.konva",LTt="2d",Vit="-",PTt="left",cPs="text",dPs="Text",uPs="top",hPs="bottom",Hit="middle",ITt="normal",mPs="px ",kse=" ",pPs="right",Git="rtl",fPs="word",gPs="char",Wit="none",eLe="…",DTt=["direction","fontFamily","fontSize","fontStyle","fontVariant","padding","align","verticalAlign","lineHeight","text","width","height","wrap","ellipsis","letterSpacing"],xPs=DTt.length;let VV=null;function yPs(){if(VV!==null)return VV;VV=!1;try{const s=document.createElement("canvas");s.width=10,s.height=10;const t=s.getContext(LTt);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){VV=!0;break}}}catch{}return VV}function vPs(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 Sse;function tLe(){return Sse||(Sse=Hn.createCanvasElement().getContext(LTt),Sse)}function bPs(s){s.fillText(this._partialText,this._partialTextX,this._partialTextY)}function _Ps(s){s.setAttr("miterLimit",2),s.strokeText(this._partialText,this._partialTextX,this._partialTextY)}function wPs(s){return s=s||{},!s.fillLinearGradientColorStops&&!s.fillRadialGradientColorStops&&!s.fillPatternImage&&(s.fill=s.fill||"black"),s}let Bh=class extends Ia{constructor(t){super(wPs(t)),this._partialTextX=0,this._partialTextY=0;for(let n=0;nhe+$C(xe.text).length,0),ae=ne+ce;y({char:me,index:ae,x:M,y:P+L,lineIndex:T,column:ne,isLastInLine:W,width:this.measureSize(me).width,context:t})}t.fillStrokeShape(this),y&&t.restore(),M+=this.measureSize(me).width+g}}else g!==0&&t.setAttr("letterSpacing",`${g}px`),this._partialTextX=M,this._partialTextY=P+L,this._partialText=$,t.fillStrokeShape(this);if(A){t.save(),t.beginPath();const X=Xa.legacyTextRendering?0:-Math.round(o/4),te=G;t.moveTo(te,P+L+X);const ne=m===qV&&!W?f-l*2:V;t.lineTo(te+Math.round(ne),P+L+X),t.lineWidth=o/15;const me=this._getLinearGradient();t.strokeStyle=me||x,t.stroke(),t.restore()}t.restore(),i>1&&(P+=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=Hn._isString(t)?t:t==null?"":t+"";return this._setAttr(cPs,n),this}getWidth(){return this.attrs.width===vF||this.attrs.width===void 0?this.getTextWidth()+this.padding()*2:this.attrs.width}getHeight(){return this.attrs.height===vF||this.attrs.height===void 0?this.fontSize()*this.textArr.length*this.lineHeight()+this.padding()*2:this.attrs.height}getTextWidth(){return this.textWidth}getTextHeight(){return Hn.warn("text.getTextHeight() method is deprecated. Use text.height() - for full height and text.fontSize() - for one line height."),this.textHeight}measureSize(t){var n,r,a,i,l,o,c,d,u,h,m;let f=tLe(),g=this.fontSize(),y;f.save(),f.font=this._getContextFont(),y=f.measureText(t),f.restore();const x=g/100;return{actualBoundingBoxAscent:(n=y.actualBoundingBoxAscent)!==null&&n!==void 0?n:71.58203125*x,actualBoundingBoxDescent:(r=y.actualBoundingBoxDescent)!==null&&r!==void 0?r:0,actualBoundingBoxLeft:(a=y.actualBoundingBoxLeft)!==null&&a!==void 0?a:-7.421875*x,actualBoundingBoxRight:(i=y.actualBoundingBoxRight)!==null&&i!==void 0?i:75.732421875*x,alphabeticBaseline:(l=y.alphabeticBaseline)!==null&&l!==void 0?l:0,emHeightAscent:(o=y.emHeightAscent)!==null&&o!==void 0?o:100*x,emHeightDescent:(c=y.emHeightDescent)!==null&&c!==void 0?c:-20*x,fontBoundingBoxAscent:(d=y.fontBoundingBoxAscent)!==null&&d!==void 0?d:91*x,fontBoundingBoxDescent:(u=y.fontBoundingBoxDescent)!==null&&u!==void 0?u:21*x,hangingBaseline:(h=y.hangingBaseline)!==null&&h!==void 0?h:72.80000305175781*x,ideographicBaseline:(m=y.ideographicBaseline)!==null&&m!==void 0?m:-21*x,width:y.width,height:g}}_getContextFont(){return this.fontStyle()+kse+this.fontVariant()+kse+(this.fontSize()+mPs)+vPs(this.fontFamily())}_addTextLine(t){this.align()===qV&&(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 tLe().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!==vF&&i!==void 0,c=l!==vF&&l!==void 0,d=this.padding(),u=i-d*2,h=l-d*2,m=0,f=this.wrap(),g=f!==Wit,y=f!==gPs&&g,x=this.ellipsis();this.textArr=[],tLe().font=this._getContextFont();const _=x?this._getTextWidth(eLe):0;for(let b=0,k=t.length;bu)for(;A.length>0;){let P=0,I=$C(A).length,M="",L=0;for(;P>>1,$=$C(A),V=$.slice(0,z+1).join(""),W=this._getTextWidth(V);(x&&c&&m+a>h?W+_:W)<=u?(P=z+1,M=V,L=W):I=z}if(M){if(y){const V=$C(A),W=$C(M),G=V[W.length],X=G===kse||G===Vit;let te;if(X&&L<=u)te=W.length;else{const ne=W.lastIndexOf(kse),me=W.lastIndexOf(Vit);te=Math.max(ne,me)+1}te>0&&(P=te,M=V.slice(0,P).join(""),L=this._getTextWidth(M))}if(M=M.trimRight(),this._addTextLine(M),r=Math.max(r,L),m+=a,this._shouldHandleEllipsis(m)){this._tryToAddEllipsisToLastLine();break}if(A=$C(A).slice(P).join("").trimLeft(),A.length>0&&(T=this._getTextWidth(A),T<=u)){this._addTextLine(A),m+=a,r=Math.max(r,T);break}}else break}else this._addTextLine(A),m+=a,r=Math.max(r,T),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!==vF&&a!==void 0,l=this.padding(),o=a-l*2;return!(this.wrap()!==Wit)||i&&t+r>o}_tryToAddEllipsisToLastLine(){const t=this.attrs.width,n=t!==vF&&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+eLe)n?null:Zw.getPointAtLengthOfDataArray(t,this.dataArray)}_readDataAttribute(){this.dataArray=Zw.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&&_-this.pathLength<=d?this.pathLength:_);if(!b)return;const k=Zw.getLineLength(g.x,g.y,b.x,b.y);let A=0;if(c)try{A=c(n[f-1].char,y)*this.fontSize()}catch{A=0}g.x+=A,b.x+=A,this.textWidth+=A;const T=Zw.getPointOnLine(A+k/2,g.x,g.y,b.x,b.y),P=Math.atan2(b.y-g.y,b.x-g.x);this.glyphInfo.push({transposeX:T.x,transposeY:T.y,text:t[f],rotation:P,p0:g,p1:b,width:k}),m+=x}}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+`.${zTt}`).join(" "),Kit="nodesRect",kPs=["widthChange","heightChange","scaleXChange","scaleYChange","skewXChange","skewYChange","rotationChange","offsetXChange","offsetYChange","transformsEnabledChange","strokeWidthChange","draggableChange"],SPs={"top-left":-45,"top-center":0,"top-right":45,"middle-right":-90,"middle-left":90,"bottom-left":-135,"bottom-center":180,"bottom-right":135},CPs="ontouchstart"in Xa._global;function APs(s,t,n){if(s==="rotater")return n;t+=Hn.degToRad(SPs[s]||0);const r=(Hn.radToDeg(t)%360+360)%360;return Hn._inRange(r,315+22.5,360)||Hn._inRange(r,0,22.5)?"ns-resize":Hn._inRange(r,45-22.5,45+22.5)?"nesw-resize":Hn._inRange(r,90-22.5,90+22.5)?"ew-resize":Hn._inRange(r,135-22.5,135+22.5)?"nwse-resize":Hn._inRange(r,180-22.5,180+22.5)?"ns-resize":Hn._inRange(r,225-22.5,225+22.5)?"nesw-resize":Hn._inRange(r,270-22.5,270+22.5)?"ew-resize":Hn._inRange(r,315-22.5,315+22.5)?"nwse-resize":(Hn.error("Transformer has unknown angle for cursor detection: "+r),"pointer")}const rke=["top-left","top-center","top-right","middle-right","middle-left","bottom-left","bottom-center","bottom-right"],Yit=1e8;function TPs(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 BTt(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 EPs(s,t){const n=TPs(s);return BTt(s,t,n)}function MPs(s,t,n){let r=t;for(let a=0;aa.isAncestorOf(this)?(Hn.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(kPs.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(Kit),this._clearCache("transform"),this._clearSelfAndDescendantCache("absoluteTransform")}_getNodeRect(){return this._getCache(Kit,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=(Xa.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 BTt(u,-Xa.getAngle(n),{x:0,y:0})}__getNodeRect(){if(!this.getNode())return{x:-Yit,y:-Yit,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(f){const g=m.point(f);n.push(g)})});const r=new w_;r.rotate(-Xa.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:Xa.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(),rke.forEach(t=>{this._createAnchor(t)}),this._createAnchor("rotater"),this._elementsCreated=!0}_createAnchor(t){const n=new QQ({stroke:"rgb(0, 161, 255)",fill:"white",strokeWidth:1,name:t+" _anchor",dragDistance:0,draggable:!0,hitStrokeWidth:CPs?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=Xa.getAngle(this.rotation()),i=this.rotateAnchorCursor(),l=APs(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 Ia({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=Hn.degToRad(c),h=Math.sin(u),m=-Math.cos(u),f=l/2,g=o/2;let y=1/0;m<0?y=Math.min(y,-g/m):m>0&&(y=Math.min(y,(o-g)/m)),h<0?y=Math.min(y,-f/h):h>0&&(y=Math.min(y,(l-f)/h));const x=f+h*y,_=g+m*y,b=Hn._sign(o),k=x+h*d*b,A=_+m*d*b;n.moveTo(x,_),n.lineTo(k,A)}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},jOe++,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 k=Xa.getAngle(this.rotateAnchorAngle());let A=Math.atan2(-r,n)+Math.PI/2-k;b.height<0&&(A-=Math.PI);const P=Xa.getAngle(this.rotation())+A,I=Xa.getAngle(this.rotationSnapTolerance()),L=MPs(this.rotationSnaps(),P,I)-b.rotation,z=EPs(b,L);this._fitNodesInto(z,t);return}const h=this.shiftBehavior();let m;h==="inverted"?m=this.keepRatio()&&!t.shiftKey:h==="none"?m=this.keepRatio():m=this.keepRatio()||t.shiftKey;let f=this.centeredScaling()||t.altKey;if(this._movingAnchorName==="top-left"){if(m){const b=f?{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 k=this.findOne(".top-left").x()>b.x?-1:1,A=this.findOne(".top-left").y()>b.y?-1:1;n=a*this.cos*k,r=a*this.sin*A,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=f?{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 k=this.findOne(".top-right").x()b.y?-1:1;n=a*this.cos*k,r=a*this.sin*A,this.findOne(".top-right").x(b.x+n),this.findOne(".top-right").y(b.y-r)}var g=i.position();this.findOne(".top-left").y(g.y),this.findOne(".bottom-right").x(g.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=f?{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 k=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(Hn._inRange(t.width,-this.padding()*2-a,a)){this.update();return}if(Hn._inRange(t.height,-this.padding()*2-a,a)){this.update();return}const i=new w_;if(i.rotate(Xa.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:Hn.warn("boundBoxFunc returned falsy. You should return new bound rect from it!")}const l=1e7,o=new w_;o.translate(r.x,r.y),o.rotate(r.rotation),o.scale(r.width/l,r.height/l);const c=new w_,d=t.width/l,u=t.height/l;this.flipEnabled()===!1?(c.translate(t.x,t.y),c.rotate(t.rotation),c.translate(t.width<0?t.width:0,t.height<0?t.height:0),c.scale(Math.abs(d),Math.abs(u))):(c.translate(t.x,t.y),c.rotate(t.rotation),c.scale(d,u));const h=c.multiply(o.invert());this._nodes.forEach(m=>{var f;if(!m.getStage())return;const g=m.getParent().getAbsoluteTransform(),y=m.getTransform().copy();y.translate(m.offsetX(),m.offsetY());const x=new w_;x.multiply(g.copy().invert()).multiply(h).multiply(g).multiply(y);const _=x.decompose();m.setAttrs(_),(f=m.getLayer())===null||f===void 0||f.batchDraw()}),this.rotation(Hn._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(Hn._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(P=>{P.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=Hn.degToRad(u),f=Math.sin(m),g=-Math.cos(m),y=r/2,x=a/2;let _=1/0;g<0?_=Math.min(_,-x/g):g>0&&(_=Math.min(_,(a-x)/g)),f<0?_=Math.min(_,-y/f):f>0&&(_=Math.min(_,(r-y)/f));const b=y+f*_,k=x+g*_,A=Hn._sign(a);this._batchChangeChild(".rotater",{x:b+f*h*A,y:k+g*h*A-o*g,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(P=>P.draggable()),x:0,y:0});const T=this.anchorStyleFunc();T&&d.forEach(P=>{T(P)}),(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=""),ZB.prototype.destroy.call(this),this.detach(),this._removeEvents(),this}add(...t){return this._elementsCreated?(Hn.error("You cannot add external nodes to the Transformer. Use tr.nodes([node]) instead."),this):super.add(...t)}toObject(){return si.prototype.toObject.call(this)}clone(t){return si.prototype.clone.call(this,t)}getClientRect(){return this.nodes().length>0?super.getClientRect():{x:0,y:0,width:0,height:0}}};Qc.isTransforming=()=>jOe>0;function LPs(s){return s instanceof Array||Hn.warn("enabledAnchors value should be an array"),s instanceof Array&&s.forEach(function(t){rke.indexOf(t)===-1&&Hn.warn("Unknown anchor name: "+t+". Available names are: "+rke.join(", "))}),s||[]}Qc.prototype.className="Transformer";Rp(Qc);on.addGetterSetter(Qc,"enabledAnchors",rke,LPs);on.addGetterSetter(Qc,"flipEnabled",!0,bN());on.addGetterSetter(Qc,"resizeEnabled",!0);on.addGetterSetter(Qc,"anchorSize",10,Va());on.addGetterSetter(Qc,"rotateEnabled",!0);on.addGetterSetter(Qc,"rotateLineVisible",!0);on.addGetterSetter(Qc,"rotationSnaps",[]);on.addGetterSetter(Qc,"rotateAnchorOffset",50,Va());on.addGetterSetter(Qc,"rotateAnchorAngle",0,Va());on.addGetterSetter(Qc,"rotateAnchorCursor","crosshair");on.addGetterSetter(Qc,"rotationSnapTolerance",5,Va());on.addGetterSetter(Qc,"borderEnabled",!0);on.addGetterSetter(Qc,"anchorStroke","rgb(0, 161, 255)");on.addGetterSetter(Qc,"anchorStrokeWidth",1,Va());on.addGetterSetter(Qc,"anchorFill","white");on.addGetterSetter(Qc,"anchorCornerRadius",0,Va());on.addGetterSetter(Qc,"borderStroke","rgb(0, 161, 255)");on.addGetterSetter(Qc,"borderStrokeWidth",1,Va());on.addGetterSetter(Qc,"borderDash");on.addGetterSetter(Qc,"keepRatio",!0);on.addGetterSetter(Qc,"shiftBehavior","default");on.addGetterSetter(Qc,"centeredScaling",!1);on.addGetterSetter(Qc,"ignoreStroke",!1);on.addGetterSetter(Qc,"padding",0,Va());on.addGetterSetter(Qc,"nodes");on.addGetterSetter(Qc,"node");on.addGetterSetter(Qc,"boundBoxFunc");on.addGetterSetter(Qc,"anchorDragBoundFunc");on.addGetterSetter(Qc,"anchorStyleFunc");on.addGetterSetter(Qc,"shouldOverdrawWholeArea",!1);on.addGetterSetter(Qc,"useSingleNodeRotation",!0);on.backCompat(Qc,{lineEnabled:"borderEnabled",rotateHandlerOffset:"rotateAnchorOffset",enabledHandlers:"enabledAnchors"});class U3 extends Ia{_sceneFunc(t){t.beginPath(),t.arc(0,0,this.radius(),0,Xa.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)}}U3.prototype.className="Wedge";U3.prototype._centroid=!0;U3.prototype._attrsAffectingSize=["radius"];Rp(U3);on.addGetterSetter(U3,"radius",0,Va());on.addGetterSetter(U3,"angle",0,Va());on.addGetterSetter(U3,"clockwise",!1);on.backCompat(U3,{angleDeg:"angle",getAngleDeg:"getAngle",setAngleDeg:"setAngle"});function Zit(){this.r=0,this.g=0,this.b=0,this.a=0,this.next=null}const PPs=[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],IPs=[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 DPs(s,t){const n=s.data,r=s.width,a=s.height;let i,l,o,c,d,u,h,m,f,g,y,x,_,b,k,A,T,P,I,M;const L=t+t+1,z=r-1,$=a-1,V=t+1,W=V*(V+1)/2,G=new Zit,X=PPs[t],te=IPs[t];let ne=null,me=G,ue=null,ce=null;for(let ae=1;ae>te,I!==0?(I=255/I,n[l]=(c*X>>te)*I,n[l+1]=(d*X>>te)*I,n[l+2]=(u*X>>te)*I):n[l]=n[l+1]=n[l+2]=0,c-=m,d-=f,u-=g,h-=y,m-=ue.r,f-=ue.g,g-=ue.b,y-=ue.a,i=o+((i=he+t+1)>te,I>0?(I=255/I,n[i]=(c*X>>te)*I,n[i+1]=(d*X>>te)*I,n[i+2]=(u*X>>te)*I):n[i]=n[i+1]=n[i+2]=0,c-=m,d-=f,u-=g,h-=y,m-=ue.r,f-=ue.g,g-=ue.b,y-=ue.a,i=ae+((i=xe+V)<$?i:$)*r<<2,c+=x+=ue.r=n[i],d+=_+=ue.g=n[i+1],u+=b+=ue.b=n[i+2],h+=k+=ue.a=n[i+3],ue=ue.next,m+=A=ce.r,f+=T=ce.g,g+=P=ce.b,y+=I=ce.a,x-=A,_-=T,b-=P,k-=I,ce=ce.next,l+=r}}const RPs=function(t){const n=Math.round(this.blurRadius());n>0&&DPs(t,n)};on.addGetterSetter(si,"blurRadius",0,Va(),on.afterSetFilter);const OPs=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};on.addGetterSetter(si,"contrast",0,Va(),on.afterSetFilter);const BPs=function(s){var t,n,r,a,i,l,o,c,d;const u=s.data,h=s.width,m=s.height,f=Math.min(1,Math.max(0,(n=(t=this.embossStrength)===null||t===void 0?void 0:t.call(this))!==null&&n!==void 0?n:.5)),g=Math.min(1,Math.max(0,(a=(r=this.embossWhiteLevel)===null||r===void 0?void 0:r.call(this))!==null&&a!==void 0?a:.5)),x=(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,_=!!((d=(c=this.embossBlend)===null||c===void 0?void 0:c.call(this))!==null&&d!==void 0&&d),b=f*10,k=g*255,A=x*Math.PI/180,T=Math.cos(A),P=Math.sin(A),I=128/1020*b,M=new Uint8ClampedArray(u),L=new Float32Array(h*m);for(let G=0,X=0;XG<0?0:G>255?255:G;for(let G=1;Ga&&(a=i),c=t[k+1],co&&(o=c),h=t[k+2],hu&&(u=h);a===r&&(a=255,r=0),o===l&&(o=255,l=0),u===d&&(u=255,d=0);let f,g,y,x,_,b;if(m>0)f=a+m*(255-a),g=r-m*(r-0),y=o+m*(255-o),x=l-m*(l-0),_=u+m*(255-u),b=d-m*(d-0);else{const k=(a+r)*.5;f=a+m*(a-k),g=r+m*(r-k);const A=(o+l)*.5;y=o+m*(o-A),x=l+m*(l-A);const T=(u+d)*.5;_=u+m*(u-T),b=d+m*(d-T)}for(let k=0;kd?m:d;const f=l,g=i,y=360/g*Math.PI/180;for(let x=0;xd?m:d;const f=l,g=i,y=0;let x,_;for(u=0;ut&&(A=k,T=0,P=-1),a=0;a=0&&f=0&&g=0&&f=0&&g=255*4?255:0}return l}function eIs(s,t,n){const r=[.1111111111111111,.1111111111111111,.1111111111111111,.1111111111111111,.1111111111111111,.1111111111111111,.1111111111111111,.1111111111111111,.1111111111111111],a=Math.round(Math.sqrt(r.length)),i=Math.floor(a/2),l=[];for(let o=0;o=0&&f=0&&g=n))for(let k=y;k=r)continue;const A=(n*k+b)*4;d+=l[A+0],u+=l[A+1],h+=l[A+2],m+=l[A+3],_+=1}d=d/_,u=u/_,h=h/_,m=m/_;for(let b=f;b=n))for(let k=y;k=r)continue;const A=(n*k+b)*4;l[A+0]=d,l[A+1]=u,l[A+2]=h,l[A+3]=m}}};on.addGetterSetter(si,"pixelSize",8,Va(),on.afterSetFilter);const rIs=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)});on.addGetterSetter(si,"green",0,function(s){return this._filterUpToDate=!1,s>255?255:s<0?0:Math.round(s)});on.addGetterSetter(si,"blue",0,lTt,on.afterSetFilter);const iIs=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)});on.addGetterSetter(si,"green",0,function(s){return this._filterUpToDate=!1,s>255?255:s<0?0:Math.round(s)});on.addGetterSetter(si,"blue",0,lTt,on.afterSetFilter);on.addGetterSetter(si,"alpha",1,function(s){return this._filterUpToDate=!1,s>1?1:s<0?0:s});const oIs=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},cIs=function(s){const t=this.threshold()*255,n=s.data,r=n.length;for(let a=0;aFn||lt[Ps]!==St[Fn]){var kr=` `+lt[Ps].replace(" at new "," at ");return Q.displayName&&kr.includes("")&&(kr=kr.replace("",Q.displayName)),kr}while(1<=Ps&&0<=Fn);break}}}finally{qr=!1,Error.prepareStackTrace=Le}return(Q=Q?Q.displayName||Q.name:"")?Er(Q):""}var Gn=Object.prototype.hasOwnProperty,Jr=[],Or=-1;function ja(Q){return{current:Q}}function ea(Q){0>Or||(Q.current=Jr[Or],Jr[Or]=null,Or--)}function dr(Q,ee){Or++,Jr[Or]=Q.current,Q.current=ee}var Wi={},ho=ja(Wi),oa=ja(!1),Ha=Wi;function $i(Q,ee){var Le=Q.type.contextTypes;if(!Le)return Wi;var tt=Q.stateNode;if(tt&&tt.__reactInternalMemoizedUnmaskedChildContext===ee)return tt.__reactInternalMemoizedMaskedChildContext;var lt={},St;for(St in Le)lt[St]=ee[St];return tt&&(Q=Q.stateNode,Q.__reactInternalMemoizedUnmaskedChildContext=ee,Q.__reactInternalMemoizedMaskedChildContext=lt),lt}function Ta(Q){return Q=Q.childContextTypes,Q!=null}function Wn(){ea(oa),ea(ho)}function Ra(Q,ee,Le){if(ho.current!==Wi)throw Error(l(168));dr(ho,ee),dr(oa,Le)}function mo(Q,ee,Le){var tt=Q.stateNode;if(ee=ee.childContextTypes,typeof tt.getChildContext!="function")return Le;tt=tt.getChildContext();for(var lt in tt)if(!(lt in ee))throw Error(l(108,M(Q)||"Unknown",lt));return i({},Le,tt)}function Ho(Q){return Q=(Q=Q.stateNode)&&Q.__reactInternalMemoizedMergedChildContext||Wi,Ha=ho.current,dr(ho,Q),dr(oa,oa.current),!0}function No(Q,ee,Le){var tt=Q.stateNode;if(!tt)throw Error(l(169));Le?(Q=mo(Q,ee,Ha),tt.__reactInternalMemoizedMergedChildContext=Q,ea(oa),ea(ho),dr(ho,Q)):ea(oa),dr(oa,Le)}var Go=Math.clz32?Math.clz32:Vm,Dd=Math.log,Tu=Math.LN2;function Vm(Q){return Q>>>=0,Q===0?32:31-(Dd(Q)/Tu|0)|0}var Uc=64,Eu=4194304;function Ec(Q){switch(Q&-Q){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 Q&4194240;case 4194304:case 8388608:case 16777216:case 33554432:case 67108864:return Q&130023424;case 134217728:return 134217728;case 268435456:return 268435456;case 536870912:return 536870912;case 1073741824:return 1073741824;default:return Q}}function Gd(Q,ee){var Le=Q.pendingLanes;if(Le===0)return 0;var tt=0,lt=Q.suspendedLanes,St=Q.pingedLanes,Ps=Le&268435455;if(Ps!==0){var Fn=Ps&~lt;Fn!==0?tt=Ec(Fn):(St&=Ps,St!==0&&(tt=Ec(St)))}else Ps=Le&~lt,Ps!==0?tt=Ec(Ps):St!==0&&(tt=Ec(St));if(tt===0)return 0;if(ee!==0&&ee!==tt&&!(ee<)&&(lt=tt&-tt,St=ee&-ee,lt>=St||lt===16&&(St&4194240)!==0))return ee;if(tt&4&&(tt|=Le&16),ee=Q.entangledLanes,ee!==0)for(Q=Q.entanglements,ee&=tt;0Le;Le++)ee.push(Q);return ee}function jf(Q,ee,Le){Q.pendingLanes|=ee,ee!==536870912&&(Q.suspendedLanes=0,Q.pingedLanes=0),Q=Q.eventTimes,ee=31-Go(ee),Q[ee]=Le}function cu(Q,ee){var Le=Q.pendingLanes&~ee;Q.pendingLanes=ee,Q.suspendedLanes=0,Q.pingedLanes=0,Q.expiredLanes&=ee,Q.mutableReadLanes&=ee,Q.entangledLanes&=ee,ee=Q.entanglements;var tt=Q.eventTimes;for(Q=Q.expirationTimes;0>=Ps,lt-=Ps,Rd=1<<32-Go(ee)+lt|Le<rl?(_m=Yi,Yi=null):_m=Yi.sibling;var Sc=di(br,Yi,Pn[rl],yi);if(Sc===null){Yi===null&&(Yi=_m);break}Q&&Yi&&Sc.alternate===null&&ee(br,Yi),yn=St(Sc,yn,rl),Fo===null?Mi=Sc:Fo.sibling=Sc,Fo=Sc,Yi=_m}if(rl===Pn.length)return Le(br,Yi),tn&&Hh(br,rl),Mi;if(Yi===null){for(;rlrl?(_m=Yi,Yi=null):_m=Yi.sibling;var j1=di(br,Yi,Sc.value,yi);if(j1===null){Yi===null&&(Yi=_m);break}Q&&Yi&&j1.alternate===null&&ee(br,Yi),yn=St(j1,yn,rl),Fo===null?Mi=j1:Fo.sibling=j1,Fo=j1,Yi=_m}if(Sc.done)return Le(br,Yi),tn&&Hh(br,rl),Mi;if(Yi===null){for(;!Sc.done;rl++,Sc=Pn.next())Sc=ol(br,Sc.value,yi),Sc!==null&&(yn=St(Sc,yn,rl),Fo===null?Mi=Sc:Fo.sibling=Sc,Fo=Sc);return tn&&Hh(br,rl),Mi}for(Yi=tt(br,Yi);!Sc.done;rl++,Sc=Pn.next())Sc=Du(Yi,br,rl,Sc.value,yi),Sc!==null&&(Q&&Sc.alternate!==null&&Yi.delete(Sc.key===null?rl:Sc.key),yn=St(Sc,yn,rl),Fo===null?Mi=Sc:Fo.sibling=Sc,Fo=Sc);return Q&&Yi.forEach(function(u6){return ee(br,u6)}),tn&&Hh(br,rl),Mi}function x0(br,yn,Pn,yi){if(typeof Pn=="object"&&Pn!==null&&Pn.type===u&&Pn.key===null&&(Pn=Pn.props.children),typeof Pn=="object"&&Pn!==null){switch(Pn.$$typeof){case c:e:{for(var Mi=Pn.key,Fo=yn;Fo!==null;){if(Fo.key===Mi){if(Mi=Pn.type,Mi===u){if(Fo.tag===7){Le(br,Fo.sibling),yn=lt(Fo,Pn.props.children),yn.return=br,br=yn;break e}}else if(Fo.elementType===Mi||typeof Mi=="object"&&Mi!==null&&Mi.$$typeof===k&&fx(Mi)===Fo.type){Le(br,Fo.sibling),yn=lt(Fo,Pn.props),yn.ref=Gh(br,Fo,Pn),yn.return=br,br=yn;break e}Le(br,Fo);break}else ee(br,Fo);Fo=Fo.sibling}Pn.type===u?(yn=Is(Pn.props.children,br.mode,yi,Pn.key),yn.return=br,br=yn):(yi=dc(Pn.type,Pn.key,Pn.props,null,br.mode,yi),yi.ref=Gh(br,yn,Pn),yi.return=br,br=yi)}return Ps(br);case d:e:{for(Fo=Pn.key;yn!==null;){if(yn.key===Fo)if(yn.tag===4&&yn.stateNode.containerInfo===Pn.containerInfo&&yn.stateNode.implementation===Pn.implementation){Le(br,yn.sibling),yn=lt(yn,Pn.children||[]),yn.return=br,br=yn;break e}else{Le(br,yn);break}else ee(br,yn);yn=yn.sibling}yn=gS(Pn,br.mode,yi),yn.return=br,br=yn}return Ps(br);case k:return Fo=Pn._init,x0(br,yn,Fo(Pn._payload),yi)}if(X(Pn))return ll(br,yn,Pn,yi);if(P(Pn))return Tf(br,yn,Pn,yi);px(br,Pn)}return typeof Pn=="string"&&Pn!==""||typeof Pn=="number"?(Pn=""+Pn,yn!==null&&yn.tag===6?(Le(br,yn.sibling),yn=lt(yn,Pn),yn.return=br,br=yn):(Le(br,yn),yn=UN(Pn,br.mode,yi),yn.return=br,br=yn),Ps(br)):Le(br,yn)}return x0}var $l=du(!0),c1=du(!1),Tg=ja(null),r0=null,Od=null,ep=null;function a0(){ep=Od=r0=null}function oy(Q,ee,Le){Re?(dr(Tg,ee._currentValue),ee._currentValue=Le):(dr(Tg,ee._currentValue2),ee._currentValue2=Le)}function ed(Q){var ee=Tg.current;ea(Tg),Re?Q._currentValue=ee:Q._currentValue2=ee}function ud(Q,ee,Le){for(;Q!==null;){var tt=Q.alternate;if((Q.childLanes&ee)!==ee?(Q.childLanes|=ee,tt!==null&&(tt.childLanes|=ee)):tt!==null&&(tt.childLanes&ee)!==ee&&(tt.childLanes|=ee),Q===Le)break;Q=Q.return}}function Mu(Q,ee){r0=Q,ep=Od=null,Q=Q.dependencies,Q!==null&&Q.firstContext!==null&&(Q.lanes&ee&&(Up=!0),Q.firstContext=null)}function pm(Q){var ee=Re?Q._currentValue:Q._currentValue2;if(ep!==Q)if(Q={context:Q,memoizedValue:ee,next:null},Od===null){if(r0===null)throw Error(l(308));Od=Q,r0.dependencies={lanes:0,firstContext:Q}}else Od=Od.next=Q;return ee}var Nf=null;function il(Q){Nf===null?Nf=[Q]:Nf.push(Q)}function wa(Q,ee,Le,tt){var lt=ee.interleaved;return lt===null?(Le.next=Le,il(ee)):(Le.next=lt.next,lt.next=Le),ee.interleaved=Le,Ir(Q,tt)}function Ir(Q,ee){Q.lanes|=ee;var Le=Q.alternate;for(Le!==null&&(Le.lanes|=ee),Le=Q,Q=Q.return;Q!==null;)Q.childLanes|=ee,Le=Q.alternate,Le!==null&&(Le.childLanes|=ee),Le=Q,Q=Q.return;return Le.tag===3?Le.stateNode:null}var Pl=!1;function Na(Q){Q.updateQueue={baseState:Q.memoizedState,firstBaseUpdate:null,lastBaseUpdate:null,shared:{pending:null,interleaved:null,lanes:0},effects:null}}function fm(Q,ee){Q=Q.updateQueue,ee.updateQueue===Q&&(ee.updateQueue={baseState:Q.baseState,firstBaseUpdate:Q.firstBaseUpdate,lastBaseUpdate:Q.lastBaseUpdate,shared:Q.shared,effects:Q.effects})}function td(Q,ee){return{eventTime:Q,lane:ee,tag:0,payload:null,callback:null,next:null}}function ra(Q,ee,Le){var tt=Q.updateQueue;if(tt===null)return null;if(tt=tt.shared,fo&2){var lt=tt.pending;return lt===null?ee.next=ee:(ee.next=lt.next,lt.next=ee),tt.pending=ee,Ir(Q,Le)}return lt=tt.interleaved,lt===null?(ee.next=ee,il(tt)):(ee.next=lt.next,lt.next=ee),tt.interleaved=ee,Ir(Q,Le)}function Eg(Q,ee,Le){if(ee=ee.updateQueue,ee!==null&&(ee=ee.shared,(Le&4194240)!==0)){var tt=ee.lanes;tt&=Q.pendingLanes,Le|=tt,ee.lanes=Le,Sg(Q,Le)}}function gx(Q,ee){var Le=Q.updateQueue,tt=Q.alternate;if(tt!==null&&(tt=tt.updateQueue,Le===tt)){var lt=null,St=null;if(Le=Le.firstBaseUpdate,Le!==null){do{var Ps={eventTime:Le.eventTime,lane:Le.lane,tag:Le.tag,payload:Le.payload,callback:Le.callback,next:null};St===null?lt=St=Ps:St=St.next=Ps,Le=Le.next}while(Le!==null);St===null?lt=St=ee:St=St.next=ee}else lt=St=ee;Le={baseState:tt.baseState,firstBaseUpdate:lt,lastBaseUpdate:St,shared:tt.shared,effects:tt.effects},Q.updateQueue=Le;return}Q=Le.lastBaseUpdate,Q===null?Le.firstBaseUpdate=ee:Q.next=ee,Le.lastBaseUpdate=ee}function Jf(Q,ee,Le,tt){var lt=Q.updateQueue;Pl=!1;var St=lt.firstBaseUpdate,Ps=lt.lastBaseUpdate,Fn=lt.shared.pending;if(Fn!==null){lt.shared.pending=null;var kr=Fn,Sa=kr.next;kr.next=null,Ps===null?St=Sa:Ps.next=Sa,Ps=kr;var Ai=Q.alternate;Ai!==null&&(Ai=Ai.updateQueue,Fn=Ai.lastBaseUpdate,Fn!==Ps&&(Fn===null?Ai.firstBaseUpdate=Sa:Fn.next=Sa,Ai.lastBaseUpdate=kr))}if(St!==null){var ol=lt.baseState;Ps=0,Ai=Sa=kr=null,Fn=St;do{var di=Fn.lane,Du=Fn.eventTime;if((tt&di)===di){Ai!==null&&(Ai=Ai.next={eventTime:Du,lane:0,tag:Fn.tag,payload:Fn.payload,callback:Fn.callback,next:null});e:{var ll=Q,Tf=Fn;switch(di=ee,Du=Le,Tf.tag){case 1:if(ll=Tf.payload,typeof ll=="function"){ol=ll.call(Du,ol,di);break e}ol=ll;break e;case 3:ll.flags=ll.flags&-65537|128;case 0:if(ll=Tf.payload,di=typeof ll=="function"?ll.call(Du,ol,di):ll,di==null)break e;ol=i({},ol,di);break e;case 2:Pl=!0}}Fn.callback!==null&&Fn.lane!==0&&(Q.flags|=64,di=lt.effects,di===null?lt.effects=[Fn]:di.push(Fn))}else Du={eventTime:Du,lane:di,tag:Fn.tag,payload:Fn.payload,callback:Fn.callback,next:null},Ai===null?(Sa=Ai=Du,kr=ol):Ai=Ai.next=Du,Ps|=di;if(Fn=Fn.next,Fn===null){if(Fn=lt.shared.pending,Fn===null)break;di=Fn,Fn=di.next,di.next=null,lt.lastBaseUpdate=di,lt.shared.pending=null}}while(!0);if(Ai===null&&(kr=ol),lt.baseState=kr,lt.firstBaseUpdate=Sa,lt.lastBaseUpdate=Ai,ee=lt.shared.interleaved,ee!==null){lt=ee;do Ps|=lt.lane,lt=lt.next;while(lt!==ee)}else St===null&&(lt.shared.lanes=0);rv|=Ps,Q.lanes=Ps,Q.memoizedState=ol}}function i0(Q,ee,Le){if(Q=ee.effects,ee.effects=null,Q!==null)for(ee=0;eeLe?Le:4,Q(!0);var tt=d1.transition;d1.transition={};try{Q(!1),ee()}finally{Eo=Le,d1.transition=tt}}function TN(){return mu().memoizedState}function iS(Q,ee,Le){var tt=p0(Q);if(Le={lane:tt,action:Le,hasEagerState:!1,eagerState:null,next:null},oS(Q))W3(ee,Le);else if(Le=wa(Q,ee,Le,tt),Le!==null){var lt=fu();Af(Le,Q,tt,lt),vc(Le,ee,tt)}}function a6(Q,ee,Le){var tt=p0(Q),lt={lane:tt,action:Le,hasEagerState:!1,eagerState:null,next:null};if(oS(Q))W3(ee,lt);else{var St=Q.alternate;if(Q.lanes===0&&(St===null||St.lanes===0)&&(St=ee.lastRenderedReducer,St!==null))try{var Ps=ee.lastRenderedState,Fn=St(Ps,Le);if(lt.hasEagerState=!0,lt.eagerState=Fn,qh(Fn,Ps)){var kr=ee.interleaved;kr===null?(lt.next=lt,il(ee)):(lt.next=kr.next,kr.next=lt),ee.interleaved=lt;return}}catch{}finally{}Le=wa(Q,ee,lt,tt),Le!==null&&(lt=fu(),Af(Le,Q,tt,lt),vc(Le,ee,tt))}}function oS(Q){var ee=Q.alternate;return Q===Il||ee!==null&&ee===Il}function W3(Q,ee){Vc=Fd=!0;var Le=Q.pending;Le===null?ee.next=ee:(ee.next=Le.next,Le.next=ee),Q.pending=ee}function vc(Q,ee,Le){if(Le&4194240){var tt=ee.lanes;tt&=Q.pendingLanes,Le|=tt,ee.lanes=Le,Sg(Q,Le)}}var Mb={readContext:pm,useCallback:lh,useContext:lh,useEffect:lh,useImperativeHandle:lh,useInsertionEffect:lh,useLayoutEffect:lh,useMemo:lh,useReducer:lh,useRef:lh,useState:lh,useDebugValue:lh,useDeferredValue:lh,useTransition:lh,useMutableSource:lh,useSyncExternalStore:lh,useId:lh,unstable_isNewReconciler:!1},lS={readContext:pm,useCallback:function(Q,ee){return Pg().memoizedState=[Q,ee===void 0?null:ee],Q},useContext:pm,useEffect:sv,useImperativeHandle:function(Q,ee,Le){return Le=Le!=null?Le.concat([Q]):null,m1(4194308,4,Eb.bind(null,ee,Q),Le)},useLayoutEffect:function(Q,ee){return m1(4194308,4,Q,ee)},useInsertionEffect:function(Q,ee){return m1(4,2,Q,ee)},useMemo:function(Q,ee){var Le=Pg();return ee=ee===void 0?null:ee,Q=Q(),Le.memoizedState=[Q,ee],Q},useReducer:function(Q,ee,Le){var tt=Pg();return ee=Le!==void 0?Le(ee):ee,tt.memoizedState=tt.baseState=ee,Q={pending:null,interleaved:null,lanes:0,dispatch:null,lastRenderedReducer:Q,lastRenderedState:ee},tt.queue=Q,Q=Q.dispatch=iS.bind(null,Il,Q),[tt.memoizedState,Q]},useRef:function(Q){var ee=Pg();return Q={current:Q},ee.memoizedState=Q},useState:np,useDebugValue:Fj,useDeferredValue:function(Q){return Pg().memoizedState=Q},useTransition:function(){var Q=np(!1),ee=Q[0];return Q=no.bind(null,Q[1]),Pg().memoizedState=Q,[ee,Q]},useMutableSource:function(){},useSyncExternalStore:function(Q,ee,Le){var tt=Il,lt=Pg();if(tn){if(Le===void 0)throw Error(l(407));Le=Le()}else{if(Le=ee(),kc===null)throw Error(l(349));hu&30||Rj(tt,ee,Le)}lt.memoizedState=Le;var St={value:Le,getSnapshot:ee};return lt.queue=St,sv(h1.bind(null,tt,St,Q),[Q]),tt.flags|=2048,ch(9,u1.bind(null,tt,St,Le,ee),void 0,null),Le},useId:function(){var Q=Pg(),ee=kc.identifierPrefix;if(tn){var Le=Jm,tt=Rd;Le=(tt&~(1<<32-Go(tt)-1)).toString(32)+Le,ee=":"+ee+"R"+Le,Le=Lg++,0bx&&(ee.flags|=128,tt=!0,bn(lt,!1),ee.lanes=4194304)}else{if(!tt)if(Q=Mg(St),Q!==null){if(ee.flags|=128,tt=!0,Q=Q.updateQueue,Q!==null&&(ee.updateQueue=Q,ee.flags|=4),bn(lt,!0),lt.tail===null&<.tailMode==="hidden"&&!St.alternate&&!tn)return $n(ee),null}else 2*Bl()-lt.renderingStartTime>bx&&Le!==1073741824&&(ee.flags|=128,tt=!0,bn(lt,!1),ee.lanes=4194304);lt.isBackwards?(St.sibling=ee.child,ee.child=St):(Q=lt.last,Q!==null?Q.sibling=St:ee.child=St,lt.last=St)}return lt.tail!==null?(ee=lt.tail,lt.rendering=ee,lt.tail=ee.sibling,lt.renderingStartTime=Bl(),ee.sibling=null,Q=yc.current,dr(yc,tt?Q&1|2:Q&1),ee):($n(ee),null);case 22:case 23:return lv(),Le=ee.memoizedState!==null,Q!==null&&Q.memoizedState!==null!==Le&&(ee.flags|=8192),Le&&ee.mode&1?Kh&1073741824&&($n(ee),Be&&ee.subtreeFlags&6&&(ee.flags|=8192)):$n(ee),null;case 24:return null;case 25:return null}throw Error(l(156,ee.tag))}function En(Q,ee){switch(xt(ee),ee.tag){case 1:return Ta(ee.type)&&Wn(),Q=ee.flags,Q&65536?(ee.flags=Q&-65537|128,ee):null;case 3:return sp(),ea(oa),ea(ho),oh(),Q=ee.flags,Q&65536&&!(Q&128)?(ee.flags=Q&-65537|128,ee):null;case 5:return tv(ee),null;case 13:if(ea(yc),Q=ee.memoizedState,Q!==null&&Q.dehydrated!==null){if(ee.alternate===null)throw Error(l(340));Za()}return Q=ee.flags,Q&65536?(ee.flags=Q&-65537|128,ee):null;case 19:return ea(yc),null;case 4:return sp(),null;case 10:return ed(ee.type._context),null;case 22:case 23:return lv(),null;case 24:return null;default:return null}}var Kn=!1,wr=!1,ur=typeof WeakSet=="function"?WeakSet:Set,Ln=null;function Pr(Q,ee){var Le=Q.ref;if(Le!==null)if(typeof Le=="function")try{Le(null)}catch(tt){xi(Q,ee,tt)}else Le.current=null}function ha(Q,ee,Le){try{Le()}catch(tt){xi(Q,ee,tt)}}var aa=!1;function Ei(Q,ee){for(ue(Q.containerInfo),Ln=ee;Ln!==null;)if(Q=Ln,ee=Q.child,(Q.subtreeFlags&1028)!==0&&ee!==null)ee.return=Q,Ln=ee;else for(;Ln!==null;){Q=Ln;try{var Le=Q.alternate;if(Q.flags&1024)switch(Q.tag){case 0:case 11:case 15:break;case 1:if(Le!==null){var tt=Le.memoizedProps,lt=Le.memoizedState,St=Q.stateNode,Ps=St.getSnapshotBeforeUpdate(Q.elementType===Q.type?tt:yx(Q.type,tt),lt);St.__reactInternalSnapshotBeforeUpdate=Ps}break;case 3:Be&&Rs(Q.stateNode.containerInfo);break;case 5:case 6:case 4:case 17:break;default:throw Error(l(163))}}catch(Fn){xi(Q,Q.return,Fn)}if(ee=Q.sibling,ee!==null){ee.return=Q.return,Ln=ee;break}Ln=Q.return}return Le=aa,aa=!1,Le}function hi(Q,ee,Le){var tt=ee.updateQueue;if(tt=tt!==null?tt.lastEffect:null,tt!==null){var lt=tt=tt.next;do{if((lt.tag&Q)===Q){var St=lt.destroy;lt.destroy=void 0,St!==void 0&&ha(ee,Le,St)}lt=lt.next}while(lt!==tt)}}function Ko(Q,ee){if(ee=ee.updateQueue,ee=ee!==null?ee.lastEffect:null,ee!==null){var Le=ee=ee.next;do{if((Le.tag&Q)===Q){var tt=Le.create;Le.destroy=tt()}Le=Le.next}while(Le!==ee)}}function wi(Q){var ee=Q.ref;if(ee!==null){var Le=Q.stateNode;switch(Q.tag){case 5:Q=te(Le);break;default:Q=Le}typeof ee=="function"?ee(Q):ee.current=Q}}function xl(Q){var ee=Q.alternate;ee!==null&&(Q.alternate=null,xl(ee)),Q.child=null,Q.deletions=null,Q.sibling=null,Q.tag===5&&(ee=Q.stateNode,ee!==null&&Xe(ee)),Q.stateNode=null,Q.return=null,Q.dependencies=null,Q.memoizedProps=null,Q.memoizedState=null,Q.pendingProps=null,Q.stateNode=null,Q.updateQueue=null}function _d(Q){return Q.tag===5||Q.tag===3||Q.tag===4}function Yo(Q){e:for(;;){for(;Q.sibling===null;){if(Q.return===null||_d(Q.return))return null;Q=Q.return}for(Q.sibling.return=Q.return,Q=Q.sibling;Q.tag!==5&&Q.tag!==6&&Q.tag!==18;){if(Q.flags&2||Q.child===null||Q.tag===4)continue e;Q.child.return=Q,Q=Q.child}if(!(Q.flags&2))return Q.stateNode}}function Si(Q,ee,Le){var tt=Q.tag;if(tt===5||tt===6)Q=Q.stateNode,ee?Os(Le,Q,ee):Kt(Le,Q);else if(tt!==4&&(Q=Q.child,Q!==null))for(Si(Q,ee,Le),Q=Q.sibling;Q!==null;)Si(Q,ee,Le),Q=Q.sibling}function Ga(Q,ee,Le){var tt=Q.tag;if(tt===5||tt===6)Q=Q.stateNode,ee?At(Le,Q,ee):Yt(Le,Q);else if(tt!==4&&(Q=Q.child,Q!==null))for(Ga(Q,ee,Le),Q=Q.sibling;Q!==null;)Ga(Q,ee,Le),Q=Q.sibling}var Qo=null,so=!1;function zo(Q,ee,Le){for(Le=Le.child;Le!==null;)hd(Q,ee,Le),Le=Le.sibling}function hd(Q,ee,Le){if(_i&&typeof _i.onCommitFiberUnmount=="function")try{_i.onCommitFiberUnmount(Km,Le)}catch{}switch(Le.tag){case 5:wr||Pr(Le,ee);case 6:if(Be){var tt=Qo,lt=so;Qo=null,zo(Q,ee,Le),Qo=tt,so=lt,Qo!==null&&(so?ms(Qo,Le.stateNode):Nt(Qo,Le.stateNode))}else zo(Q,ee,Le);break;case 18:Be&&Qo!==null&&(so?kn(Qo,Le.stateNode):Zs(Qo,Le.stateNode));break;case 4:Be?(tt=Qo,lt=so,Qo=Le.stateNode.containerInfo,so=!0,zo(Q,ee,Le),Qo=tt,so=lt):(Ne&&(tt=Le.stateNode.containerInfo,lt=Rn(tt),Jn(tt,lt)),zo(Q,ee,Le));break;case 0:case 11:case 14:case 15:if(!wr&&(tt=Le.updateQueue,tt!==null&&(tt=tt.lastEffect,tt!==null))){lt=tt=tt.next;do{var St=lt,Ps=St.destroy;St=St.tag,Ps!==void 0&&(St&2||St&4)&&ha(Le,ee,Ps),lt=lt.next}while(lt!==tt)}zo(Q,ee,Le);break;case 1:if(!wr&&(Pr(Le,ee),tt=Le.stateNode,typeof tt.componentWillUnmount=="function"))try{tt.props=Le.memoizedProps,tt.state=Le.memoizedState,tt.componentWillUnmount()}catch(Fn){xi(Le,ee,Fn)}zo(Q,ee,Le);break;case 21:zo(Q,ee,Le);break;case 22:Le.mode&1?(wr=(tt=wr)||Le.memoizedState!==null,zo(Q,ee,Le),wr=tt):zo(Q,ee,Le);break;default:zo(Q,ee,Le)}}function jh(Q){var ee=Q.updateQueue;if(ee!==null){Q.updateQueue=null;var Le=Q.stateNode;Le===null&&(Le=Q.stateNode=new ur),ee.forEach(function(tt){var lt=$N.bind(null,Q,tt);Le.has(tt)||(Le.add(tt),tt.then(lt,lt))})}}function md(Q,ee){var Le=ee.deletions;if(Le!==null)for(var tt=0;tt";case Lu:return":has("+(wd(Q)||"")+")";case gm:return'[role="'+Q.value+'"]';case Zu:return'"'+Q.value+'"';case Pc:return'[data-testname="'+Q.value+'"]';default:throw Error(l(365))}}function Vp(Q,ee){var Le=[];Q=[Q,0];for(var tt=0;ttlt&&(lt=Ps),tt&=~St}if(tt=lt,tt=Bl()-tt,tt=(120>tt?120:480>tt?480:1080>tt?1080:1920>tt?1920:3e3>tt?3e3:4320>tt?4320:1960*ym(tt/1960))-tt,10Q?16:Q,sg===null)var tt=!1;else{if(Q=sg,sg=null,Rb=0,fo&6)throw Error(l(331));var lt=fo;for(fo|=4,Ln=Q.current;Ln!==null;){var St=Ln,Ps=St.child;if(Ln.flags&16){var Fn=St.deletions;if(Fn!==null){for(var kr=0;krBl()-uw?_x(Q,0):av|=Le),Wp(Q,ee)}function pS(Q,ee){ee===0&&(Q.mode&1?(ee=Eu,Eu<<=1,!(Eu&130023424)&&(Eu=4194304)):ee=1);var Le=fu();Q=Ir(Q,ee),Q!==null&&(jf(Q,ee,Le),Wp(Q,Le))}function Y3(Q){var ee=Q.memoizedState,Le=0;ee!==null&&(Le=ee.retryLane),pS(Q,Le)}function $N(Q,ee){var Le=0;switch(Q.tag){case 13:var tt=Q.stateNode,lt=Q.memoizedState;lt!==null&&(Le=lt.retryLane);break;case 19:tt=Q.stateNode;break;default:throw Error(l(314))}tt!==null&&tt.delete(ee),pS(Q,Le)}var Z3;Z3=function(Q,ee,Le){if(Q!==null)if(Q.memoizedProps!==ee.pendingProps||oa.current)Up=!0;else{if(!(Q.lanes&Le)&&!(ee.flags&128))return Up=!1,ut(Q,ee,Le);Up=!!(Q.flags&131072)}else Up=!1,tn&&ee.flags&1048576&&Wt(ee,Jy,ee.index);switch(ee.lanes=0,ee.tag){case 2:var tt=ee.type;ke(Q,ee),Q=ee.pendingProps;var lt=$i(ee,ho.current);Mu(ee,Le),lt=J_(null,ee,tt,Q,lt,Le);var St=Cb();return ee.flags|=1,typeof lt=="object"&<!==null&&typeof lt.render=="function"&<.$$typeof===void 0?(ee.tag=1,ee.memoizedState=null,ee.updateQueue=null,Ta(tt)?(St=!0,Ho(ee)):St=!1,ee.memoizedState=lt.state!==null&<.state!==void 0?lt.state:null,Na(ee),lt.updater=Lb,ee.stateNode=lt,lt._reactInternals=ee,Cf(ee,tt,Q,Le),ee=ow(null,ee,tt,!0,St,Le)):(ee.tag=0,tn&&St&&ze(ee),rp(null,ee,lt,Le),ee=ee.child),ee;case 16:tt=ee.elementType;e:{switch(ke(Q,ee),Q=ee.pendingProps,lt=tt._init,tt=lt(tt._payload),ee.type=tt,lt=ee.tag=Qn(tt),Q=yx(tt,Q),lt){case 0:ee=PN(null,ee,tt,Q,Le);break e;case 1:ee=IN(null,ee,tt,Q,Le);break e;case 11:ee=dS(null,ee,tt,Q,Le);break e;case 14:ee=cy(null,ee,tt,yx(tt.type,Q),Le);break e}throw Error(l(306,tt,""))}return ee;case 0:return tt=ee.type,lt=ee.pendingProps,lt=ee.elementType===tt?lt:yx(tt,lt),PN(Q,ee,tt,lt,Le);case 1:return tt=ee.type,lt=ee.pendingProps,lt=ee.elementType===tt?lt:yx(tt,lt),IN(Q,ee,tt,lt,Le);case 3:e:{if(lw(ee),Q===null)throw Error(l(387));tt=ee.pendingProps,St=ee.memoizedState,lt=St.element,fm(Q,ee),Jf(ee,tt,null,Le);var Ps=ee.memoizedState;if(tt=Ps.element,Ge&&St.isDehydrated)if(St={element:tt,isDehydrated:!1,cache:Ps.cache,pendingSuspenseBoundaries:Ps.pendingSuspenseBoundaries,transitions:Ps.transitions},ee.updateQueue.baseState=St,ee.memoizedState=St,ee.flags&256){lt=Wd(Error(l(423)),ee),ee=Pb(Q,ee,tt,Le,lt);break e}else if(tt!==lt){lt=Wd(Error(l(424)),ee),ee=Pb(Q,ee,tt,Le,lt);break e}else for(Ge&&(cs=Ve(ee.stateNode.containerInfo),ss=ee,tn=!0,Xn=null,Mn=!1),Le=c1(ee,null,tt,Le),ee.child=Le;Le;)Le.flags=Le.flags&-3|4096,Le=Le.sibling;else{if(Za(),tt===lt){ee=Oe(Q,ee,Le);break e}rp(Q,ee,tt,Le)}ee=ee.child}return ee;case 5:return ev(ee),Q===null&&Ui(ee),tt=ee.type,lt=ee.pendingProps,St=Q!==null?Q.memoizedProps:null,Ps=lt.children,ge(tt,lt)?Ps=null:St!==null&&ge(tt,St)&&(ee.flags|=32),LN(Q,ee),rp(Q,ee,Ps,Le),ee.child;case 6:return Q===null&&Ui(ee),null;case 13:return K3(Q,ee,Le);case 4:return qc(ee,ee.stateNode.containerInfo),tt=ee.pendingProps,Q===null?ee.child=$l(ee,null,tt,Le):rp(Q,ee,tt,Le),ee.child;case 11:return tt=ee.type,lt=ee.pendingProps,lt=ee.elementType===tt?lt:yx(tt,lt),dS(Q,ee,tt,lt,Le);case 7:return rp(Q,ee,ee.pendingProps,Le),ee.child;case 8:return rp(Q,ee,ee.pendingProps.children,Le),ee.child;case 12:return rp(Q,ee,ee.pendingProps.children,Le),ee.child;case 10:e:{if(tt=ee.type._context,lt=ee.pendingProps,St=ee.memoizedProps,Ps=lt.value,oy(ee,tt,Ps),St!==null)if(qh(St.value,Ps)){if(St.children===lt.children&&!oa.current){ee=Oe(Q,ee,Le);break e}}else for(St=ee.child,St!==null&&(St.return=ee);St!==null;){var Fn=St.dependencies;if(Fn!==null){Ps=St.child;for(var kr=Fn.firstContext;kr!==null;){if(kr.context===tt){if(St.tag===1){kr=td(-1,Le&-Le),kr.tag=2;var Sa=St.updateQueue;if(Sa!==null){Sa=Sa.shared;var Ai=Sa.pending;Ai===null?kr.next=kr:(kr.next=Ai.next,Ai.next=kr),Sa.pending=kr}}St.lanes|=Le,kr=St.alternate,kr!==null&&(kr.lanes|=Le),ud(St.return,Le,ee),Fn.lanes|=Le;break}kr=kr.next}}else if(St.tag===10)Ps=St.type===ee.type?null:St.child;else if(St.tag===18){if(Ps=St.return,Ps===null)throw Error(l(341));Ps.lanes|=Le,Fn=Ps.alternate,Fn!==null&&(Fn.lanes|=Le),ud(Ps,Le,ee),Ps=St.sibling}else Ps=St.child;if(Ps!==null)Ps.return=St;else for(Ps=St;Ps!==null;){if(Ps===ee){Ps=null;break}if(St=Ps.sibling,St!==null){St.return=Ps.return,Ps=St;break}Ps=Ps.return}St=Ps}rp(Q,ee,lt.children,Le),ee=ee.child}return ee;case 9:return lt=ee.type,tt=ee.pendingProps.children,Mu(ee,Le),lt=pm(lt),tt=tt(lt),ee.flags|=1,rp(Q,ee,tt,Le),ee.child;case 14:return tt=ee.type,lt=yx(tt,ee.pendingProps),lt=yx(tt.type,lt),cy(Q,ee,tt,lt,Le);case 15:return aw(Q,ee,ee.type,ee.pendingProps,Le);case 17:return tt=ee.type,lt=ee.pendingProps,lt=ee.elementType===tt?lt:yx(tt,lt),ke(Q,ee),ee.tag=1,Ta(tt)?(Q=!0,Ho(ee)):Q=!1,Mu(ee,Le),g1(ee,tt,lt),Cf(ee,tt,lt,Le),ow(null,ee,tt,!0,Q,Le);case 19:return Db(Q,ee,Le);case 22:return iw(Q,ee,Le)}throw Error(l(156,ee.tag))};function X3(Q,ee){return Gm(Q,ee)}function Vj(Q,ee,Le,tt){this.tag=Q,this.key=Le,this.sibling=this.child=this.return=this.stateNode=this.type=this.elementType=null,this.index=0,this.ref=null,this.pendingProps=ee,this.dependencies=this.memoizedState=this.updateQueue=this.memoizedProps=null,this.mode=tt,this.subtreeFlags=this.flags=0,this.deletions=null,this.childLanes=this.lanes=0,this.alternate=null}function bm(Q,ee,Le,tt){return new Vj(Q,ee,Le,tt)}function er(Q){return Q=Q.prototype,!(!Q||!Q.isReactComponent)}function Qn(Q){if(typeof Q=="function")return er(Q)?1:0;if(Q!=null){if(Q=Q.$$typeof,Q===y)return 11;if(Q===b)return 14}return 2}function g0(Q,ee){var Le=Q.alternate;return Le===null?(Le=bm(Q.tag,ee,Q.key,Q.mode),Le.elementType=Q.elementType,Le.type=Q.type,Le.stateNode=Q.stateNode,Le.alternate=Q,Q.alternate=Le):(Le.pendingProps=ee,Le.type=Q.type,Le.flags=0,Le.subtreeFlags=0,Le.deletions=null),Le.flags=Q.flags&14680064,Le.childLanes=Q.childLanes,Le.lanes=Q.lanes,Le.child=Q.child,Le.memoizedProps=Q.memoizedProps,Le.memoizedState=Q.memoizedState,Le.updateQueue=Q.updateQueue,ee=Q.dependencies,Le.dependencies=ee===null?null:{lanes:ee.lanes,firstContext:ee.firstContext},Le.sibling=Q.sibling,Le.index=Q.index,Le.ref=Q.ref,Le}function dc(Q,ee,Le,tt,lt,St){var Ps=2;if(tt=Q,typeof Q=="function")er(Q)&&(Ps=1);else if(typeof Q=="string")Ps=5;else e:switch(Q){case u:return Is(Le.children,lt,St,ee);case h:Ps=8,lt|=8;break;case m:return Q=bm(12,Le,ee,lt|2),Q.elementType=m,Q.lanes=St,Q;case x:return Q=bm(13,Le,ee,lt),Q.elementType=x,Q.lanes=St,Q;case _:return Q=bm(19,Le,ee,lt),Q.elementType=_,Q.lanes=St,Q;case A:return fS(Le,lt,St,ee);default:if(typeof Q=="object"&&Q!==null)switch(Q.$$typeof){case f:Ps=10;break e;case g:Ps=9;break e;case y:Ps=11;break e;case b:Ps=14;break e;case k:Ps=16,tt=null;break e}throw Error(l(130,Q==null?Q:typeof Q,""))}return ee=bm(Ps,Le,ee,lt),ee.elementType=Q,ee.type=tt,ee.lanes=St,ee}function Is(Q,ee,Le,tt){return Q=bm(7,Q,tt,ee),Q.lanes=Le,Q}function fS(Q,ee,Le,tt){return Q=bm(22,Q,tt,ee),Q.elementType=A,Q.lanes=Le,Q.stateNode={isHidden:!1},Q}function UN(Q,ee,Le){return Q=bm(6,Q,null,ee),Q.lanes=Le,Q}function gS(Q,ee,Le){return ee=bm(4,Q.children!==null?Q.children:[],Q.key,ee),ee.lanes=Le,ee.stateNode={containerInfo:Q.containerInfo,pendingChildren:null,implementation:Q.implementation},ee}function Q3(Q,ee,Le,tt,lt){this.tag=ee,this.containerInfo=Q,this.finishedWork=this.pingCache=this.current=this.pendingChildren=null,this.timeoutHandle=Me,this.callbackNode=this.pendingContext=this.context=null,this.callbackPriority=0,this.eventTimes=wf(0),this.expirationTimes=wf(-1),this.entangledLanes=this.finishedLanes=this.mutableReadLanes=this.expiredLanes=this.pingedLanes=this.suspendedLanes=this.pendingLanes=0,this.entanglements=wf(0),this.identifierPrefix=tt,this.onRecoverableError=lt,Ge&&(this.mutableSourceEagerHydrationData=null)}function l6(Q,ee,Le,tt,lt,St,Ps,Fn,kr){return Q=new Q3(Q,ee,Le,Fn,kr),ee===1?(ee=1,St===!0&&(ee|=8)):ee=0,St=bm(3,null,null,ee),Q.current=St,St.stateNode=Q,St.memoizedState={element:tt,isDehydrated:Le,cache:null,transitions:null,pendingSuspenseBoundaries:null},Na(St),Q}function c6(Q){if(!Q)return Wi;Q=Q._reactInternals;e:{if(L(Q)!==Q||Q.tag!==1)throw Error(l(170));var ee=Q;do{switch(ee.tag){case 3:ee=ee.stateNode.context;break e;case 1:if(Ta(ee.type)){ee=ee.stateNode.__reactInternalMemoizedMergedChildContext;break e}}ee=ee.return}while(ee!==null);throw Error(l(171))}if(Q.tag===1){var Le=Q.type;if(Ta(Le))return mo(Q,Le,ee)}return ee}function Hj(Q){var ee=Q._reactInternals;if(ee===void 0)throw typeof Q.render=="function"?Error(l(188)):(Q=Object.keys(Q).join(","),Error(l(268,Q)));return Q=V(ee),Q===null?null:Q.stateNode}function d6(Q,ee){if(Q=Q.memoizedState,Q!==null&&Q.dehydrated!==null){var Le=Q.retryLane;Q.retryLane=Le!==0&&Le=Sa&&St>=ol&<<=Ai&&Ps<=di){Q.splice(ee,1);break}else if(tt!==Sa||Le.width!==kr.width||diPs){if(!(St!==ol||Le.height!==kr.height||Ailt)){Sa>tt&&(kr.width+=Sa-tt,kr.x=tt),AiSt&&(kr.height+=ol-St,kr.y=St),diLe&&(Le=Ps)),Ps ")+` No matching component was found for: `)+Q.join(" > ")}return null},n.getPublicRootInstance=function(Q){if(Q=Q.current,!Q.child)return null;switch(Q.child.tag){case 5:return te(Q.child.stateNode);default:return Q.child.stateNode}},n.injectIntoDevTools=function(Q){if(Q={bundleType:Q.bundleType,version:Q.version,rendererPackageName:Q.rendererPackageName,rendererConfig:Q.rendererConfig,overrideHookState:null,overrideHookStateDeletePath:null,overrideHookStateRenamePath:null,overrideProps:null,overridePropsDeletePath:null,overridePropsRenamePath:null,setErrorHandler:null,setSuspenseHandler:null,scheduleUpdate:null,currentDispatcherRef:o.ReactCurrentDispatcher,findHostInstanceByFiber:yO,findFiberByHostInstance:Q.findFiberByHostInstance||eC,findHostInstancesForRefresh:null,scheduleRefresh:null,scheduleRoot:null,setRefreshHandler:null,getCurrentFiber:null,reconcilerVersion:"18.3.1"},typeof __REACT_DEVTOOLS_GLOBAL_HOOK__>"u")Q=!1;else{var ee=__REACT_DEVTOOLS_GLOBAL_HOOK__;if(ee.isDisabled||!ee.supportsFiber)Q=!0;else{try{Km=ee.inject(Q),_i=ee}catch{}Q=!!ee.checkDCE}}return Q},n.isAlreadyRendering=function(){return!1},n.observeVisibleRects=function(Q,ee,Le,tt){if(!Je)throw Error(l(363));Q=Hp(Q,ee);var lt=Ct(Q,Le,tt).disconnect;return{disconnect:function(){lt()}}},n.registerMutableSourceForHydration=function(Q,ee){var Le=ee._getVersion;Le=Le(ee._source),Q.mutableSourceEagerHydrationData==null?Q.mutableSourceEagerHydrationData=[ee,Le]:Q.mutableSourceEagerHydrationData.push(ee,Le)},n.runWithPriority=function(Q,ee){var Le=Eo;try{return Eo=Q,ee()}finally{Eo=Le}},n.shouldError=function(){return null},n.shouldSuspend=function(){return!1},n.updateContainer=function(Q,ee,Le,tt){var lt=ee.current,St=fu(),Ps=p0(lt);return Le=c6(Le),ee.context===null?ee.context=Le:ee.pendingContext=Le,ee=td(St,Ps),ee.payload={element:Q},tt=tt===void 0?null:tt,tt!==null&&(ee.callback=tt),Q=ra(lt,ee,Ps),Q!==null&&(Af(Q,lt,Ps,St),Eg(Q,lt,Ps)),Ps},n};$Tt.exports=dIs;var uIs=$Tt.exports;const hIs=Xc(uIs);var UTt={exports:{}},YR={};/** * @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. */YR.ConcurrentRoot=1;YR.ContinuousEventPriority=4;YR.DefaultEventPriority=16;YR.DiscreteEventPriority=1;YR.IdleEventPriority=536870912;YR.LegacyRoot=0;UTt.exports=YR;var qTt=UTt.exports;const Xit={children:!0,ref:!0,key:!0,style:!0,forwardedRef:!0,unstable_applyCache:!0,unstable_applyDrawHitFromCache:!0};let Qit=!1,Jit=!1;const AVe=".react-konva-event",mIs=`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 `,pIs=`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 `,fIs={};function A3e(s,t,n=fIs){if(!Qit&&"zIndex"in t&&(console.warn(pIs),Qit=!0),!Jit&&t.draggable){var r=t.x!==void 0||t.y!==void 0,a=t.onDragEnd||t.onDragMove;r&&!a&&(console.warn(mIs),Jit=!0)}for(var i in n)if(!Xit[i]){var l=i.slice(0,2)==="on",o=n[i]!==t[i];if(l&&o){var c=i.substr(2).toLowerCase();c.substr(0,7)==="content"&&(c="content"+c.substr(7,1).toUpperCase()+c.substr(8)),s.off(c,n[i])}var d=!t.hasOwnProperty(i);d&&s.setAttr(i,void 0)}var u=t._useStrictMode,h={},m=!1;const f={};for(var i in t)if(!Xit[i]){var l=i.slice(0,2)==="on",g=n[i]!==t[i];if(l&&g){var c=i.substr(2).toLowerCase();c.substr(0,7)==="content"&&(c="content"+c.substr(7,1).toUpperCase()+c.substr(8)),t[i]&&(f[c]=t[i])}!l&&(t[i]!==n[i]||u&&t[i]!==s.getAttr(i))&&(m=!0,h[i]=t[i])}m&&(s.setAttrs(h),YE(s));for(var c in f)s.on(c+AVe,f[c])}function YE(s){if(!Xa.autoDrawEnabled){var t=s.getLayer()||s.getStage();t&&t.batchDraw()}}const VTt={},gIs={};hR.Node.prototype._applyProps=A3e;function xIs(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),YE(s)}function yIs(s,t,n){let r=hR[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=hR.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 A3e(c,i),c}function vIs(s,t,n){console.error(`Text components are not supported for now in ReactKonva. Your text is: "${s}"`)}function bIs(s,t,n){return!1}function _Is(s){return s}function wIs(){return null}function jIs(){return null}function NIs(s,t,n,r){return gIs}function kIs(){}function SIs(s){}function CIs(s,t){return!1}function AIs(){return VTt}function TIs(){return VTt}const EIs=setTimeout,MIs=clearTimeout,LIs=-1;function PIs(s,t){return!1}const IIs=!1,DIs=!0,RIs=!0;function OIs(s,t){t.parent===s?t.moveToTop():s.add(t),YE(s)}function FIs(s,t){t.parent===s?t.moveToTop():s.add(t),YE(s)}function HTt(s,t,n){t._remove(),s.add(t),t.setZIndex(n.getZIndex()),YE(s)}function zIs(s,t,n){HTt(s,t,n)}function BIs(s,t){t.destroy(),t.off(AVe),YE(s)}function $Is(s,t){t.destroy(),t.off(AVe),YE(s)}function UIs(s,t,n){console.error(`Text components are not yet supported in ReactKonva. You text is: "${n}"`)}function qIs(s,t,n){}function VIs(s,t,n,r,a){A3e(s,a,r)}function HIs(s){s.hide(),YE(s)}function GIs(s){}function WIs(s,t){(t.visible==null||t.visible)&&s.show()}function KIs(s,t){}function YIs(s){}function ZIs(){}const XIs=()=>qTt.DefaultEventPriority,QIs=Object.freeze(Object.defineProperty({__proto__:null,appendChild:OIs,appendChildToContainer:FIs,appendInitialChild:xIs,cancelTimeout:MIs,clearContainer:YIs,commitMount:qIs,commitTextUpdate:UIs,commitUpdate:VIs,createInstance:yIs,createTextInstance:vIs,detachDeletedInstance:ZIs,finalizeInitialChildren:bIs,getChildHostContext:TIs,getCurrentEventPriority:XIs,getPublicInstance:_Is,getRootHostContext:AIs,hideInstance:HIs,hideTextInstance:GIs,idlePriority:SG.unstable_IdlePriority,insertBefore:HTt,insertInContainerBefore:zIs,isPrimaryRenderer:IIs,noTimeout:LIs,now:SG.unstable_now,prepareForCommit:wIs,preparePortalMount:jIs,prepareUpdate:NIs,removeChild:BIs,removeChildFromContainer:$Is,resetAfterCommit:kIs,resetTextContent:SIs,run:SG.unstable_runWithPriority,scheduleTimeout:EIs,shouldDeprioritizeSubtree:CIs,shouldSetTextContent:PIs,supportsMutation:RIs,unhideInstance:WIs,unhideTextInstance:KIs,warnsIfNotActing:DIs},Symbol.toStringTag,{value:"Module"}));var JIs=Object.defineProperty,e8s=Object.defineProperties,t8s=Object.getOwnPropertyDescriptors,eot=Object.getOwnPropertySymbols,s8s=Object.prototype.hasOwnProperty,n8s=Object.prototype.propertyIsEnumerable,tot=(s,t,n)=>t in s?JIs(s,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):s[t]=n,sot=(s,t)=>{for(var n in t||(t={}))s8s.call(t,n)&&tot(s,n,t[n]);if(eot)for(var n of eot(t))n8s.call(t,n)&&tot(s,n,t[n]);return s},r8s=(s,t)=>e8s(s,t8s(t)),not,rot;typeof window<"u"&&((not=window.document)!=null&¬.createElement||((rot=window.navigator)==null?void 0:rot.product)==="ReactNative")?N.useLayoutEffect:N.useEffect;function GTt(s,t,n){if(!s)return;if(n(s)===!0)return s;let r=s.child;for(;r;){const a=GTt(r,t,n);if(a)return a;r=r.sibling}}function WTt(s){try{return Object.defineProperties(s,{_currentRenderer:{get(){return null},set(){}},_currentRenderer2:{get(){return null},set(){}}})}catch{return s}}const aot=console.error;console.error=function(){const s=[...arguments].join("");if(s!=null&&s.startsWith("Warning:")&&s.includes("useContext")){console.error=aot;return}return aot.apply(this,arguments)};const TVe=WTt(N.createContext(null));class KTt extends N.Component{render(){return N.createElement(TVe.Provider,{value:this._reactInternals},this.props.children)}}function a8s(){const s=N.useContext(TVe);if(s===null)throw new Error("its-fine: useFiber must be called within a !");const t=N.useId();return N.useMemo(()=>{for(const r of[s,s==null?void 0:s.alternate]){if(!r)continue;const a=GTt(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 i8s(){const s=a8s(),[t]=N.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!==TVe&&!t.has(a)&&t.set(a,N.useContext(WTt(a)))}n=n.return}return t}function o8s(){const s=i8s();return N.useMemo(()=>Array.from(s.keys()).reduce((t,n)=>r=>N.createElement(t,null,N.createElement(n.Provider,r8s(sot({},r),{value:s.get(n)}))),t=>N.createElement(KTt,sot({},t))),[s])}function l8s(s){const t=Rt.useRef({});return Rt.useLayoutEffect(()=>{t.current=s}),Rt.useLayoutEffect(()=>()=>{t.current={}},[]),t.current}const c8s=s=>{const t=Rt.useRef(null),n=Rt.useRef(null),r=Rt.useRef(null),a=l8s(s),i=o8s(),l=o=>{const{forwardedRef:c}=s;c&&(typeof c=="function"?c(o):c.current=o)};return Rt.useLayoutEffect(()=>(n.current=new hR.Stage({width:s.width,height:s.height,container:t.current}),l(n.current),r.current=JH.createContainer(n.current,qTt.LegacyRoot,!1,null),JH.updateContainer(Rt.createElement(i,{},s.children),r.current),()=>{hR.isBrowser&&(l(null),JH.updateContainer(null,r.current,null),n.current.destroy())}),[]),Rt.useLayoutEffect(()=>{l(n.current),A3e(n.current,s,a),JH.updateContainer(Rt.createElement(i,{},s.children),r.current,null)}),Rt.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})},d8s="Layer",lT="Group",uk="Rect",z7="Image",bF="Text",dFn="Transformer",JH=hIs(QIs);JH.injectIntoDevTools({findHostInstanceByFiber:()=>null,bundleType:0,version:Rt.version,rendererPackageName:"react-konva"});const u8s=Rt.forwardRef((s,t)=>Rt.createElement(KTt,{},Rt.createElement(c8s,{...s,forwardedRef:t})));function h8s({imageUrl:s,preset:t,barStyleId:n,overrides:r,maxDisplayWidth:a=720,stageRef:i}){const l=N.useRef(null),[o,c]=N.useState(null),[d,u]=N.useState(null),[h,m]=N.useState(null),f=(t==null?void 0:t.headshot_url)??"",g=(t==null?void 0:t.brokerage_logo_url)??"";N.useEffect(()=>{if(!s){c(null);return}const W=new window.Image;W.crossOrigin="anonymous",W.onload=()=>c(W),W.onerror=()=>c(null),W.src=s},[s]),N.useEffect(()=>{if(!f){u(null);return}const W=new window.Image;W.crossOrigin="anonymous",W.onload=()=>u(W),W.onerror=()=>u(null),W.src=f},[f]),N.useEffect(()=>{if(!g){m(null);return}const W=new window.Image;W.crossOrigin="anonymous",W.onload=()=>m(W),W.onerror=()=>m(null),W.src=g},[g]);const y=OMs(n),x=(o==null?void 0:o.naturalWidth)??1080,_=(o==null?void 0:o.naturalHeight)??1080,b=N.useMemo(()=>Math.min(1,a/x),[x,a]),k=x*b,A=_*b,T=(r==null?void 0:r.brand_color)??(t==null?void 0:t.brand_color)??"#0f172a",P=(r==null?void 0:r.accent_color)??(t==null?void 0:t.accent_color)??"#3b82f6",I=(r==null?void 0:r.display_name)??(t==null?void 0:t.display_name)??"",M=(r==null?void 0:r.phone)??(t==null?void 0:t.phone)??"",L=(r==null?void 0:r.email)??(t==null?void 0:t.email)??"",z=(r==null?void 0:r.tagline)??(t==null?void 0:t.tagline)??"",$=new Set((r==null?void 0:r.hidden_fields)??(t==null?void 0:t.hidden_fields)??[]),V=W=>y.fields.includes(W)&&!$.has(W);return e.jsx("div",{className:"border rounded-lg overflow-hidden bg-muted/40 inline-block",children:e.jsx(u8s,{ref:W=>{l.current=W,i&&(i.current=W)},width:k,height:A,scaleX:b,scaleY:b,children:e.jsxs(d8s,{children:[o&&e.jsx(z7,{image:o,width:x,height:_,listening:!1}),!o&&e.jsx(uk,{x:0,y:0,width:x,height:_,fill:"#e2e8f0"}),e.jsx(m8s,{style:y,canvasW:x,canvasH:_,brandColor:T,accentColor:P,name:I,phone:M,email:L,tagline:z,headshot:d,logo:h,hidden:$,has:V})]})})})}function m8s({style:s,canvasW:t,canvasH:n,brandColor:r,accentColor:a,name:i,phone:l,email:o,tagline:c,headshot:d,logo:u,has:h}){const m=n*s.heightRatio,f=m*.18,g=s.textColor==="light"?"#ffffff":s.textColor==="dark"?"#0f172a":s.background==="dark"||s.background==="gradient"?"#ffffff":FMs(r),y=g==="#ffffff"?"rgba(255,255,255,0.78)":"rgba(15,23,42,0.7)";if(s.position==="bottom"||s.position==="top"){const x=s.position==="bottom"?n-m:0;return e.jsxs(lT,{children:[e.jsx(uk,{x:0,y:x,width:t,height:m,fill:r}),e.jsx(uk,{x:0,y:s.position==="bottom"?x:m-4,width:t,height:4,fill:a}),e.jsx(Ase,{x:f,y:x+f,width:t-f*2,height:m-f*2,textColor:g,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 x=t*.42,_=m,b=t-x-n*.025,k=n-_-n*.025;return e.jsxs(lT,{children:[e.jsx(uk,{x:b,y:k,width:x,height:_,fill:r,cornerRadius:_*.12,opacity:.92}),e.jsx(uk,{x:b,y:k+_-4,width:x,height:4,fill:a,cornerRadius:2}),e.jsx(Ase,{x:b+f,y:k+f,width:x-f*2,height:_-f*2,textColor:g,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 x=Math.max(t*.22,Math.min(t*.3,260)),_=x*.12;return e.jsxs(lT,{children:[e.jsx(uk,{x:t-x,y:0,width:x,height:n,fill:r}),e.jsx(uk,{x:t-x,y:0,width:4,height:n,fill:a}),e.jsx(Ase,{x:t-x+_,y:n*.08,width:x-_*2,height:n*.84,textColor:g,subTextColor:y,name:i,phone:l,email:o,tagline:c,headshot:d,logo:u,has:h,circular:s.circularHeadshot,vertical:!0,railWidth:x})]})}return s.position==="letterbox"?e.jsxs(lT,{children:[e.jsx(uk,{x:0,y:0,width:t,height:m,fill:"#0a0a0a"}),e.jsx(uk,{x:0,y:n-m,width:t,height:m,fill:"#0a0a0a"}),e.jsx(uk,{x:0,y:n-m,width:t,height:3,fill:a}),e.jsx(Ase,{x:f,y:n-m+f,width:t-f*2,height:m-f*2,textColor:"#ffffff",subTextColor:"rgba(255,255,255,0.75)",name:i,phone:l,email:o,tagline:c,headshot:d,logo:u,has:h,circular:s.circularHeadshot}),u&&h("logo")&&e.jsx(z7,{image:u,x:t-f-m*.7,y:f,height:m-f*2,width:m*.7})]}):null}function Ase({x:s,y:t,width:n,height:r,textColor:a,subTextColor:i,name:l,phone:o,email:c,tagline:d,headshot:u,logo:h,has:m,circular:f,vertical:g,railWidth:y}){if(g){const W=y??n,G=Math.min(n,W*.7),X=Math.max(14,W*.13),te=Math.max(11,W*.085),ne=W*.08,me=W*.35;let ue=t;const ce=ue;ue+=G+ne;const ae=ue,he=l.length>12?2:1;ue+=X*1.15*he+ne*.5;const xe=ue;m("phone")&&o&&(ue+=te*1.3+ne*.4);const ve=ue;m("email")&&c&&(ue+=te*1.3+ne*.4);const ge=ue+ne*.5;return e.jsxs(lT,{children:[m("headshot")&&u&&e.jsx(lT,{clipFunc:f?be=>{be.beginPath(),be.arc(s+n/2,ce+G/2,G/2,0,Math.PI*2),be.closePath()}:void 0,children:e.jsx(z7,{image:u,x:s+(n-G)/2,y:ce,width:G,height:G})}),m("name")&&l&&e.jsx(bF,{text:l,x:s,y:ae,width:n,align:"center",fontSize:X,fontStyle:"bold",fill:a}),m("phone")&&o&&e.jsx(bF,{text:o,x:s,y:xe,width:n,align:"center",fontSize:te,fill:i}),m("email")&&c&&e.jsx(bF,{text:c,x:s,y:ve,width:n,align:"center",fontSize:te,fill:i,ellipsis:!0,wrap:"none"}),m("logo")&&h&&e.jsx(z7,{image:h,x:s,y:ge,width:n,height:me})]})}const x=r*.95,_=u&&m("headshot")?s+x+r*.18:s,b=n-(_-s)-(h&&m("logo")?r*1.6:0),k=Math.max(20,r*.34),A=Math.max(13,r*.22),T=r*.06,P=m("tagline")&&d?1:0,I=m("phone")&&o?1:0,M=m("email")&&c?1:0,L=1+P+(I||M?1:0),z=L*k+(L-1)*T;let V=t+(r-z)/2;return e.jsxs(lT,{children:[m("headshot")&&u&&e.jsx(lT,{clipFunc:f?W=>{W.beginPath(),W.arc(s+x/2,t+x/2,x/2,0,Math.PI*2),W.closePath()}:void 0,children:e.jsx(z7,{image:u,x:s,y:t+(r-x)/2,width:x,height:x})}),m("name")&&l&&e.jsx(bF,{text:l,x:_,y:V,width:b,fontSize:k,fontStyle:"bold",fill:a,ellipsis:!0,wrap:"none"}),(V+=k+T,null),m("tagline")&&d&&e.jsxs(e.Fragment,{children:[e.jsx(bF,{text:d,x:_,y:V,width:b,fontSize:A*1.1,fontStyle:"italic",fill:i,ellipsis:!0,wrap:"none"}),(V+=A*1.1+T,null)]}),I||M?e.jsx(bF,{text:[o,c].filter(Boolean).join(" • "),x:_,y:V,width:b,fontSize:A,fill:i,ellipsis:!0,wrap:"none"}):null,m("logo")&&h&&e.jsx(z7,{image:h,x:s+n-r*1.4,y:t+(r-r*.8)/2,width:r*1.4,height:r*.8})]})}function p8s(){const{data:s}=XQ(),t=(s==null?void 0:s.find(V=>V.is_default))??(s==null?void 0:s[0])??null,[n,r]=N.useState(void 0),a=(s==null?void 0:s.find(V=>V.id===n))??t,[i,l]=N.useState([]),[o,c]=N.useState(0),[d,u]=N.useState("minimal-stripe"),[h,m]=N.useState({}),[f,g]=N.useState(!1),y=N.useRef(null),[x,_]=N.useState(780),b=N.useRef(null),k=V=>{if(b.current&&(b.current.disconnect(),b.current=null),!V)return;const W=()=>{const X=V.clientWidth;X>0&&_(Math.min(780,X-16))};W();const G=new ResizeObserver(W);G.observe(V),b.current=G};N.useEffect(()=>()=>{var V;(V=b.current)==null||V.disconnect()},[]);const A=N.useRef(null),T=V=>{if(!V)return;const W=[];Array.from(V).forEach(G=>{G.type.startsWith("image/")&&W.push({id:crypto.randomUUID(),url:URL.createObjectURL(G),file:G,name:G.name})}),l(G=>[...G,...W])},P=V=>{l(W=>{const G=W.find(X=>X.id===V);return G&&URL.revokeObjectURL(G.url),W.filter(X=>X.id!==V)}),c(0)},I=typeof navigator<"u"&&/iPad|iPhone|iPod/.test(navigator.userAgent),M=V=>{var me;const[W,G]=V.split(","),X=((me=W.match(/:(.*?);/))==null?void 0:me[1])??"image/jpeg",te=atob(G),ne=new Uint8Array(te.length);for(let ue=0;ue{var V;if(A.current){g(!0);try{const W=A.current,G=W.toDataURL({pixelRatio:1/(W.scaleX()||1),mimeType:"image/jpeg",quality:.95}),te=`${((V=i[o])==null?void 0:V.name.replace(/\.[^.]+$/,""))||"branded"}-branded.jpg`,ne=M(G),me=URL.createObjectURL(ne);if(I)window.open(me,"_blank")||(window.location.href=me),ie.success('Long-press the image and tap "Save to Photos"');else{const ue=document.createElement("a");ue.href=me,ue.download=te,document.body.appendChild(ue),ue.click(),ue.remove(),ie.success("Image exported")}setTimeout(()=>URL.revokeObjectURL(me),6e4)}catch(W){ie.error(W.message||"Export failed")}finally{g(!1)}}},z=async()=>{if(i.length){g(!0);try{const V=new oTt,W=i.length,G=o;for(let ne=0;nesetTimeout(he,600)),!A.current)continue;const me=A.current,ce=me.toDataURL({pixelRatio:1/(me.scaleX()||1),mimeType:"image/jpeg",quality:.95}).split(",")[1],ae=i[ne].name.replace(/\.[^.]+$/,"")||`image-${ne+1}`;V.file(`${ae}-branded.jpg`,ce,{base64:!0})}c(G);const X=await V.generateAsync({type:"blob"}),te=document.createElement("a");te.href=URL.createObjectURL(X),te.download=`branded-images-${Date.now()}.zip`,te.click(),URL.revokeObjectURL(te.href),ie.success(`${W} images exported`)}catch(V){ie.error(V.message||"Batch export failed")}finally{g(!1)}}},$=i[o];return e.jsx(Qs,{title:"Branding Bar Studio",children:e.jsxs("div",{className:"container max-w-7xl py-4 md:py-6 space-y-4 px-3 md:px-6",children:[e.jsx(ic,{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(cr,{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(cr,{to:"/marketing-studio/brand-kit",children:[e.jsx(zc,{className:"h-4 w-4 mr-1"})," Brand Kit"]})})]}),!a&&e.jsx(_e,{className:"border-dashed border-amber-500/50 bg-amber-500/5",children:e.jsxs(De,{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(cr,{to:"/marketing-studio/brand-kit",children:"Set up brand"})})]})}),e.jsxs("div",{className:"grid gap-6 lg:grid-cols-[1fr_360px]",children:[e.jsxs("div",{className:"space-y-4 min-w-0",children:[e.jsx(_e,{className:"overflow-hidden",children:e.jsxs(De,{className:"p-4",children:[$?e.jsx("div",{ref:k,className:"flex justify-center bg-muted/30 rounded p-2 overflow-hidden",children:e.jsx(h8s,{imageUrl:$.url,preset:a,barStyleId:d,overrides:h,maxDisplayWidth:x,stageRef:A})}):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(),T(V.dataTransfer.files)},children:[e.jsx(pc,{className:"h-12 w-12 mx-auto text-muted-foreground/60"}),e.jsxs("div",{children:[e.jsx("h3",{className:"font-medium",children:"Drop images here or click to browse"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Add up to 50 photos at once. We'll batch-brand them all."})]}),e.jsxs(B,{type:"button",children:[e.jsx(ni,{className:"h-4 w-4 mr-1"})," Choose images"]})]}),e.jsx("input",{ref:y,type:"file",accept:"image/*",multiple:!0,hidden:!0,onChange:V=>T(V.target.files)})]})}),i.length>0&&e.jsx(_e,{className:"overflow-hidden",children:e.jsx(De,{className:"p-3",children:e.jsxs("div",{className:"flex gap-2 overflow-x-auto py-1",children:[i.map((V,W)=>e.jsxs("div",{className:"relative group flex-shrink-0",children:[e.jsx("button",{onClick:()=>c(W),className:`block h-16 w-16 rounded overflow-hidden border-2 transition-all ${W===o?"border-primary":"border-transparent hover:border-muted-foreground/30"}`,children:e.jsx("img",{src:V.url,alt:"",className:"h-full w-full object-cover"})}),e.jsx("button",{onClick:()=>P(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(hr,{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(nn,{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:L,disabled:f||!$,children:[f?e.jsx(us,{className:"h-4 w-4 mr-1 animate-spin"}):e.jsx(oi,{className:"h-4 w-4 mr-1"}),"Download this image"]}),i.length>1&&e.jsxs(B,{onClick:z,disabled:f,children:[f?e.jsx(us,{className:"h-4 w-4 mr-1 animate-spin"}):e.jsx(oi,{className:"h-4 w-4 mr-1"}),"Download all (",i.length,") as ZIP"]})]})]}),e.jsxs("div",{className:"space-y-4 min-w-0",children:[e.jsxs(_e,{className:"overflow-hidden",children:[e.jsx(zt,{className:"pb-2",children:e.jsx(qt,{className:"text-base",children:"Brand preset"})}),e.jsx(De,{children:e.jsxs(Ns,{value:(a==null?void 0:a.id)??"",onValueChange:r,children:[e.jsx(ws,{children:e.jsx(ks,{placeholder:"Choose preset"})}),e.jsx(js,{children:s==null?void 0:s.map(V=>e.jsxs(nt,{value:V.id,children:[V.name," ",V.is_default?"(default)":""]},V.id))})]})})]}),e.jsxs(_e,{className:"overflow-hidden",children:[e.jsx(zt,{className:"pb-2",children:e.jsx(qt,{className:"text-base",children:"Bar style"})}),e.jsx(De,{children:e.jsx(zMs,{value:d,onChange:u,mediaType:"image"})})]}),e.jsxs(_e,{className:"overflow-hidden",children:[e.jsx(zt,{className:"pb-2",children:e.jsx(qt,{className:"text-base",children:"Tweak this design"})}),e.jsx(De,{children:e.jsxs(ya,{defaultValue:"text",children:[e.jsxs(va,{className:"grid grid-cols-2 w-full",children:[e.jsx(ls,{value:"text",children:"Text"}),e.jsx(ls,{value:"colors",children:"Colors"})]}),e.jsxs(_s,{value:"text",className:"space-y-3 pt-3",children:[e.jsxs("div",{children:[e.jsx(re,{children:"Display name"}),e.jsx(we,{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(re,{children:"Phone"}),e.jsx(we,{value:h.phone??(a==null?void 0:a.phone)??"",onChange:V=>m({...h,phone:V.target.value})})]}),e.jsxs("div",{children:[e.jsx(re,{children:"Email"}),e.jsx(we,{value:h.email??(a==null?void 0:a.email)??"",onChange:V=>m({...h,email:V.target.value})})]}),e.jsxs("div",{children:[e.jsx(re,{children:"Tagline"}),e.jsx(we,{value:h.tagline??(a==null?void 0:a.tagline)??"",onChange:V=>m({...h,tagline:V.target.value})})]})]}),e.jsxs(_s,{value:"colors",className:"space-y-3 pt-3",children:[e.jsxs("div",{children:[e.jsx(re,{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(we,{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(re,{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(we,{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 f8s(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 g8s=(()=>{let s=0;const t=()=>`0000${(Math.random()*36**4<<0).toString(36)}`.slice(-4);return()=>(s+=1,`u${t()}${s}`)})();function YT(s){const t=[];for(let n=0,r=s.length;n$b||s.height>$b)&&(s.width>$b&&s.height>$b?s.width>s.height?(s.height*=$b/s.width,s.width=$b):(s.width*=$b/s.height,s.height=$b):s.width>$b?(s.height*=$b/s.width,s.width=$b):(s.width*=$b/s.height,s.height=$b))}function ike(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 _8s(s){return Promise.resolve().then(()=>new XMLSerializer().serializeToString(s)).then(encodeURIComponent).then(t=>`data:image/svg+xml;charset=utf-8,${t}`)}async function w8s(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),_8s(a)}const lb=(s,t)=>{if(s instanceof t)return!0;const n=Object.getPrototypeOf(s);return n===null?!1:n.constructor.name===t.name||lb(n,t)};function j8s(s){const t=s.getPropertyValue("content");return`${s.cssText} content: '${t.replace(/'|"/g,"")}';`}function N8s(s,t){return YTt(t).map(n=>{const r=s.getPropertyValue(n),a=s.getPropertyPriority(n);return`${n}: ${r}${a?" !important":""};`}).join(" ")}function k8s(s,t,n,r){const a=`.${s}:${t}`,i=n.cssText?j8s(n):N8s(n,r);return document.createTextNode(`${a}{${i}}`)}function iot(s,t,n,r){const a=window.getComputedStyle(s,n),i=a.getPropertyValue("content");if(i===""||i==="none")return;const l=g8s();try{t.className=`${t.className} ${l}`}catch{return}const o=document.createElement("style");o.appendChild(k8s(l,n,a,r)),t.appendChild(o)}function S8s(s,t,n){iot(s,t,":before",n),iot(s,t,":after",n)}const oot="application/font-woff",lot="image/jpeg",C8s={woff:oot,woff2:oot,ttf:"application/font-truetype",eot:"application/vnd.ms-fontobject",png:"image/png",jpg:lot,jpeg:lot,gif:"image/gif",tiff:"image/tiff",svg:"image/svg+xml",webp:"image/webp"};function A8s(s){const t=/\.([^./]*?)$/g.exec(s);return t?t[1]:""}function EVe(s){const t=A8s(s).toLowerCase();return C8s[t]||""}function T8s(s){return s.split(/,/)[1]}function NOe(s){return s.search(/^(data:)/)!==-1}function E8s(s,t){return`data:${t};base64,${s}`}async function XTt(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 nLe={};function M8s(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 MVe(s,t,n){const r=M8s(s,t,n.includeQueryParams);if(nLe[r]!=null)return nLe[r];n.cacheBust&&(s+=(/\?/.test(s)?"&":"?")+new Date().getTime());let a;try{const i=await XTt(s,n.fetchRequestInit,({res:l,result:o})=>(t||(t=l.headers.get("Content-Type")||""),T8s(o)));a=E8s(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 nLe[r]=a,a}async function L8s(s){const t=s.toDataURL();return t==="data:,"?s.cloneNode(!1):ike(t)}async function P8s(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 ike(o)}const n=s.poster,r=EVe(n),a=await MVe(n,r,t);return ike(a)}async function I8s(s,t){var n;try{if(!((n=s==null?void 0:s.contentDocument)===null||n===void 0)&&n.body)return await T3e(s.contentDocument.body,t,!0)}catch{}return s.cloneNode(!1)}async function D8s(s,t){return lb(s,HTMLCanvasElement)?L8s(s):lb(s,HTMLVideoElement)?P8s(s,t):lb(s,HTMLIFrameElement)?I8s(s,t):s.cloneNode(QTt(s))}const R8s=s=>s.tagName!=null&&s.tagName.toUpperCase()==="SLOT",QTt=s=>s.tagName!=null&&s.tagName.toUpperCase()==="SVG";async function O8s(s,t,n){var r,a;if(QTt(t))return t;let i=[];return R8s(s)&&s.assignedNodes?i=YT(s.assignedNodes()):lb(s,HTMLIFrameElement)&&(!((r=s.contentDocument)===null||r===void 0)&&r.body)?i=YT(s.contentDocument.body.childNodes):i=YT(((a=s.shadowRoot)!==null&&a!==void 0?a:s).childNodes),i.length===0||lb(s,HTMLVideoElement)||await i.reduce((l,o)=>l.then(()=>T3e(o,n)).then(c=>{c&&t.appendChild(c)}),Promise.resolve()),t}function F8s(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):YTt(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`),lb(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 z8s(s,t){lb(s,HTMLTextAreaElement)&&(t.innerHTML=s.value),lb(s,HTMLInputElement)&&t.setAttribute("value",s.value)}function B8s(s,t){if(lb(s,HTMLSelectElement)){const n=t,r=Array.from(n.children).find(a=>s.value===a.getAttribute("value"));r&&r.setAttribute("selected","")}}function $8s(s,t,n){return lb(t,Element)&&(F8s(s,t,n),S8s(s,t,n),z8s(s,t),B8s(s,t)),t}async function U8s(s,t){const n=s.querySelectorAll?s.querySelectorAll("use"):[];if(n.length===0)return s;const r={};for(let i=0;iD8s(r,t)).then(r=>O8s(s,r,t)).then(r=>$8s(s,r,t)).then(r=>U8s(r,t))}const JTt=/url\((['"]?)([^'"]+?)\1\)/g,q8s=/url\([^)]+\)\s*format\((["']?)([^"']+)\1\)/g,V8s=/src:\s*(?:url\([^)]+\)\s*format\([^)]+\)[,;]\s*)+/g;function H8s(s){const t=s.replace(/([.*+?^${}()|\[\]\/\\])/g,"\\$1");return new RegExp(`(url\\(['"]?)(${t})(['"]?\\))`,"g")}function G8s(s){const t=[];return s.replace(JTt,(n,r,a)=>(t.push(a),n)),t.filter(n=>!NOe(n))}async function W8s(s,t,n,r,a){try{const i=n?f8s(t,n):t,l=EVe(t);let o;return a||(o=await MVe(i,l,r)),s.replace(H8s(t),`$1${o}$3`)}catch{}return s}function K8s(s,{preferredFontFormat:t}){return t?s.replace(V8s,n=>{for(;;){const[r,,a]=q8s.exec(n)||[];if(!a)return"";if(a===t)return`src: ${r};`}}):s}function eEt(s){return s.search(JTt)!==-1}async function tEt(s,t,n){if(!eEt(s))return s;const r=K8s(s,n);return G8s(r).reduce((i,l)=>i.then(o=>W8s(o,l,t,n)),Promise.resolve(r))}async function wF(s,t,n){var r;const a=(r=t.style)===null||r===void 0?void 0:r.getPropertyValue(s);if(a){const i=await tEt(a,null,n);return t.style.setProperty(s,i,t.style.getPropertyPriority(s)),!0}return!1}async function Y8s(s,t){await wF("background",s,t)||await wF("background-image",s,t),await wF("mask",s,t)||await wF("-webkit-mask",s,t)||await wF("mask-image",s,t)||await wF("-webkit-mask-image",s,t)}async function Z8s(s,t){const n=lb(s,HTMLImageElement);if(!(n&&!NOe(s.src))&&!(lb(s,SVGImageElement)&&!NOe(s.href.baseVal)))return;const r=n?s.src:s.href.baseVal,a=await MVe(r,EVe(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 X8s(s,t){const r=YT(s.childNodes).map(a=>sEt(a,t));await Promise.all(r).then(()=>s)}async function sEt(s,t){lb(s,Element)&&(await Y8s(s,t),await Z8s(s,t),await X8s(s,t))}function Q8s(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 cot={};async function dot(s){let t=cot[s];if(t!=null)return t;const r=await(await fetch(s)).text();return t={url:s,cssText:r},cot[s]=t,t}async function uot(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),XTt(o,t.fetchRequestInit,({result:c})=>(n=n.replace(l,`url(${c})`),[l,c]))});return Promise.all(i).then(()=>n)}function hot(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 J8s(s,t){const n=[],r=[];return s.forEach(a=>{if("cssRules"in a)try{YT(a.cssRules||[]).forEach((i,l)=>{if(i.type===CSSRule.IMPORT_RULE){let o=l+1;const c=i.href,d=dot(c).then(u=>uot(u,t)).then(u=>hot(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(dot(a.href).then(o=>uot(o,t)).then(o=>hot(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{YT(a.cssRules||[]).forEach(i=>{n.push(i)})}catch(i){console.error(`Error while reading CSS rules from ${a.href}`,i)}}),n))}function eDs(s){return s.filter(t=>t.type===CSSRule.FONT_FACE_RULE).filter(t=>eEt(t.style.getPropertyValue("src")))}async function tDs(s,t){if(s.ownerDocument==null)throw new Error("Provided element is not within a Document");const n=YT(s.ownerDocument.styleSheets),r=await J8s(n,t);return eDs(r)}function nEt(s){return s.trim().replace(/["']/g,"")}function sDs(s){const t=new Set;function n(r){(r.style.fontFamily||getComputedStyle(r).fontFamily).split(",").forEach(i=>{t.add(nEt(i))}),Array.from(r.children).forEach(i=>{i instanceof HTMLElement&&n(i)})}return n(s),t}async function nDs(s,t){const n=await tDs(s,t),r=sDs(s);return(await Promise.all(n.filter(i=>r.has(nEt(i.style.fontFamily))).map(i=>{const l=i.parentStyleSheet?i.parentStyleSheet.href:null;return tEt(i.cssText,l,t)}))).join(` `)}async function rDs(s,t){const n=t.fontEmbedCSS!=null?t.fontEmbedCSS:t.skipFonts?null:await nDs(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 aDs(s,t={}){const{width:n,height:r}=ZTt(s,t),a=await T3e(s,t,!0);return await rDs(a,t),await sEt(a,t),Q8s(a,t),await w8s(a,n,r)}async function iDs(s,t={}){const{width:n,height:r}=ZTt(s,t),a=await aDs(s,t),i=await ike(a),l=document.createElement("canvas"),o=l.getContext("2d"),c=t.pixelRatio||v8s(),d=t.canvasWidth||n,u=t.canvasHeight||r;return l.width=d*c,l.height=u*c,t.skipAutoScale||b8s(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 LVe(s,t={}){return(await iDs(s,t)).toDataURL()}const XB=s=>new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:0}).format(s),E3e={"just-listed":"JUST LISTED","just-sold":"JUST SOLD","open-house":"OPEN HOUSE","price-drop":"PRICE DROP"},cT={"instagram-square":{width:1080,height:1080},"instagram-story":{width:1080,height:1920},"facebook-post":{width:1200,height:630}},oDs=({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})]})]}),PVe=Rt.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=E3e[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:XB(s.price)}),t==="just-sold"&&s.soldPrice&&e.jsxs("div",{style:{fontSize:l.w*.028,color:"#C9A84C",marginBottom:l.w*.01},children:["Sold for ",XB(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(oDs,{branding:r,dim:l})]})]})]})});PVe.displayName="LuxuryDarkTemplate";const lDs=({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})]})]}),IVe=Rt.forwardRef(({listing:s,postType:t,format:n,branding:r,selectedPhotoIndex:a},i)=>{var f;const l=n==="instagram-story"?{w:1080,h:1920}:n==="facebook-post"?{w:1200,h:630}:{w:1080,h:1080},o=400/l.w,c=(f=s.photos)==null?void 0:f[a],d=E3e[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:XB(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(lDs,{branding:r,dim:l,accentColor:m})]})]})});IVe.displayName="ModernCleanTemplate";const cDs=({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})]})]}),DVe=Rt.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=E3e[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:XB(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(cDs,{branding:r,dim:l})]})]})]})});DVe.displayName="BoldColorfulTemplate";const dDs=({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})]})]}),RVe=Rt.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=E3e[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:XB(s.price)}),t==="just-sold"&&s.soldPrice&&e.jsxs("div",{style:{fontSize:l.w*.02,color:"#8B7355",marginBottom:l.w*.01},children:["Sold: ",XB(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(dDs,{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"}})]})]})})});RVe.displayName="EditorialTemplate";const uDs=[{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:"📉"}],mot=[{value:"instagram-square",label:"IG Post",dimensions:"1080×1080",icon:e.jsx(dm,{className:"h-4 w-4"})},{value:"instagram-story",label:"IG Story",dimensions:"1080×1920",icon:e.jsx(dm,{className:"h-4 w-4"})},{value:"facebook-post",label:"Facebook",dimensions:"1200×630",icon:e.jsx(Kf,{className:"h-4 w-4"})}],hDs=[{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:"📰"}],pot={"luxury-dark":PVe,"modern-clean":IVe,"bold-colorful":DVe,editorial:RVe},rLe=s=>new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:0}).format(s);function mDs(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;oIe.is_default))??(s==null?void 0:s[0])??null,[n,r]=N.useState(void 0),a=(s==null?void 0:s.find(Ie=>Ie.id===n))??t,i=Ya(),[l,o]=N.useState("mine"),[c,d]=N.useState(""),[u,h]=N.useState("address"),[m,f]=N.useState(!1),[g,y]=N.useState([]),[x,_]=N.useState(null),[b,k]=N.useState(0),[A,T]=N.useState("just-listed"),[P,I]=N.useState(["instagram-square"]),[M,L]=N.useState("luxury-dark"),[z,$]=N.useState(!0),[V,W]=N.useState(!1),[G,X]=N.useState([]),[te,ne]=N.useState("search"),me=N.useRef({}),{data:ue=[],isLoading:ce}=mt({queryKey:["marketing-studio-my-listings",i],enabled:!!i,queryFn:async()=>{const{data:Ie,error:Me}=await H.from("listings").select("id, property_address, city, state, price, status, bedrooms, bathrooms, square_footage, year_built, property_type, description, created_at, listing_photos(photo_url, sort_order, is_primary)").eq("agent_id",i).order("created_at",{ascending:!1}).limit(60);if(Me)throw Me;return(Ie||[]).map(Re=>{const Be=(Re.listing_photos||[]).slice().sort((Ge,Ce)=>(Ce.is_primary?1:0)-(Ge.is_primary?1:0)||(Ge.sort_order??0)-(Ce.sort_order??0)).map(Ge=>Ge.photo_url).filter(Boolean),Ne=String(Re.status||"");return{mlsNumber:Re.id,address:Re.property_address||"",city:Re.city||"",state:Re.state||"",zip:"",price:Number(Re.price||0),status:Ne,bedrooms:Number(Re.bedrooms||0),bathrooms:Number(Re.bathrooms||0),sqft:Number(Re.square_footage||0),lotSize:"",yearBuilt:Re.year_built??null,propertyType:Re.property_type||"",description:Re.description||"",photos:Be,listDate:Re.created_at,soldDate:Ne.toLowerCase().includes("sold")?Re.created_at:null,soldPrice:null,agent:{name:"",office:""}}})}}),ae=N.useMemo(()=>!z||!a?{enabled:!1}:{enabled:!0,agentName:a.display_name||"",brokerage:a.tagline||"",agentPhotoUrl:a.headshot_url||void 0},[z,a]),he=async()=>{if(c.trim()){f(!0),y([]);try{const{data:Ie,error:Me}=await H.functions.invoke("repliers-mls-search",{body:{searchType:u,query:c.trim()}});if(Me)throw Me;if(Ie!=null&&Ie.error)throw new Error(Ie.error);y((Ie==null?void 0:Ie.listings)||[]),((Ie==null?void 0:Ie.listings)||[]).length===0&&ie.info("No listings found. Try a different search.")}catch(Ie){ie.error(Ie.message||"Search failed")}finally{f(!1)}}},xe=Ie=>{var Me;_(Ie),k(0),ne("customize"),Ie.soldDate||(Me=Ie.status)!=null&&Me.toLowerCase().includes("sold")?T("just-sold"):T("just-listed")},ve=Ie=>I(Me=>Me.includes(Ie)?Me.filter(Re=>Re!==Ie):[...Me,Ie]),ge=x?{listing:x,postType:A,format:"instagram-square",branding:ae,selectedPhotoIndex:b}:null,be=N.useCallback(async()=>{if(!(!x||P.length===0)){W(!0),X([]),ne("generate");try{await new Promise(Me=>setTimeout(Me,600));const Ie=[];for(const Me of P){const Re=`${M}-${Me}`,Be=me.current[Re];if(!Be)continue;const Ne=cT[Me],Ge=await LVe(Be,{width:Ne.width,height:Ne.height,pixelRatio:1,cacheBust:!0,style:{transform:"none",transformOrigin:"top left"}});Ie.push({format:Me,url:Ge})}X(Ie),ie.success(`Generated ${Ie.length} design${Ie.length>1?"s":""}!`)}catch(Ie){ie.error(Ie.message||"Generation failed")}finally{W(!1)}}},[x,P,M]),Se=(Ie,Me)=>{const Re=`${((x==null?void 0:x.address)||"listing").replace(/\s+/g,"-")}-${A}-${Me}.png`;try{const Be=mDs(Ie),Ne=URL.createObjectURL(Be);if(pDs)window.open(Ne,"_blank"),ie.message("Long-press the image to save to Photos");else{const Ge=document.createElement("a");Ge.href=Ne,Ge.download=Re,document.body.appendChild(Ge),Ge.click(),document.body.removeChild(Ge)}setTimeout(()=>URL.revokeObjectURL(Ne),6e4)}catch{const Be=document.createElement("a");Be.href=Ie,Be.download=Re,Be.click()}};return N.useEffect(()=>{!n&&t&&r(t.id)},[t,n]),e.jsx(Qs,{title:"Listing Templates",children:e.jsxs("div",{className:"container max-w-6xl py-4 md:py-8 px-3 md:px-6 space-y-5",children:[e.jsxs(ic,{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(cr,{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(We,{variant:"secondary",className:"mb-2 gap-1",children:[e.jsx(Cn,{className:"h-3 w-3"})," Listing Templates"]}),e.jsx("h1",{className:"text-2xl md:text-3xl font-bold tracking-tight",children:"Just Listed. Just Stunning."}),e.jsx("p",{className:"text-sm md:text-base text-muted-foreground max-w-2xl mt-1",children:"Search any MLS listing and get pixel-perfect, on-brand graphics for Instagram, Stories and Facebook in one click."})]}),s&&s.length>0&&e.jsxs("div",{className:"min-w-0 sm:min-w-[220px]",children:[e.jsx(re,{className:"text-xs text-muted-foreground",children:"Brand preset"}),e.jsxs(Ns,{value:n,onValueChange:r,children:[e.jsx(ws,{children:e.jsx(ks,{placeholder:"Default"})}),e.jsx(js,{children:s.map(Ie=>e.jsxs(nt,{value:Ie.id,children:[Ie.name,Ie.is_default?" (default)":""]},Ie.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:()=>ne("search"),className:`flex items-center gap-1.5 px-3 py-1.5 rounded-full whitespace-nowrap ${te==="search"?"bg-primary text-primary-foreground":"bg-muted text-muted-foreground"}`,children:[e.jsx(Gr,{className:"h-3.5 w-3.5"})," 1. Find listing"]}),e.jsx(Qa,{className:"h-4 w-4 text-muted-foreground shrink-0"}),e.jsxs("button",{onClick:()=>x&&ne("customize"),disabled:!x,className:`flex items-center gap-1.5 px-3 py-1.5 rounded-full whitespace-nowrap ${te==="customize"?"bg-primary text-primary-foreground":x?"bg-muted text-muted-foreground":"bg-muted text-muted-foreground/50"}`,children:[e.jsx(Cn,{className:"h-3.5 w-3.5"})," 2. Customize"]}),e.jsx(Qa,{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 ${te==="generate"?"bg-primary text-primary-foreground":"bg-muted text-muted-foreground/50"}`,children:[e.jsx(oi,{className:"h-3.5 w-3.5"})," 3. Download"]})]}),te==="search"&&e.jsxs("div",{className:"space-y-4",children:[e.jsx(ya,{value:l,onValueChange:Ie=>o(Ie),children:e.jsxs(va,{className:"grid grid-cols-2 w-full sm:w-auto",children:[e.jsxs(ls,{value:"mine",children:[e.jsx(_a,{className:"h-4 w-4 mr-1.5"})," My Listings"]}),e.jsxs(ls,{value:"mls",children:[e.jsx(Gr,{className:"h-4 w-4 mr-1.5"})," MLS Search"]})]})}),l==="mine"&&e.jsx("div",{className:"space-y-3",children:ce?e.jsx(_e,{children:e.jsx(De,{className:"py-12 flex items-center justify-center",children:e.jsx(us,{className:"h-6 w-6 animate-spin text-muted-foreground"})})}):ue.length===0?e.jsx(_e,{children:e.jsxs(De,{className:"py-10 text-center space-y-2",children:[e.jsx(_a,{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(cr,{to:"/mission-control/listings",children:"Go to Listings"})})]})}):e.jsxs(e.Fragment,{children:[e.jsxs("h3",{className:"text-sm font-medium text-muted-foreground",children:[ue.length," listing",ue.length!==1?"s":""," from your Listing Exchange"]}),e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-3",children:ue.map((Ie,Me)=>{var Re;return e.jsx(_e,{className:"cursor-pointer hover:border-primary/50 hover:shadow-md transition-all group overflow-hidden",onClick:()=>xe(Ie),children:e.jsx(De,{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:(Re=Ie.photos)!=null&&Re[0]?e.jsx("img",{src:Ie.photos[0],alt:Ie.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(_a,{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:Ie.price>0?rLe(Ie.price):"—"}),e.jsx("p",{className:"text-sm text-muted-foreground truncate",children:Ie.address}),e.jsxs("p",{className:"text-xs text-muted-foreground truncate",children:[Ie.city,Ie.state?`, ${Ie.state}`:""]}),e.jsxs("div",{className:"flex items-center gap-3 mt-1.5 text-xs text-muted-foreground",children:[Ie.bedrooms>0&&e.jsxs("span",{className:"flex items-center gap-0.5",children:[e.jsx(J4,{className:"h-3 w-3"})," ",Ie.bedrooms]}),Ie.bathrooms>0&&e.jsxs("span",{className:"flex items-center gap-0.5",children:[e.jsx(Wx,{className:"h-3 w-3"})," ",Ie.bathrooms]}),Ie.sqft>0&&e.jsxs("span",{className:"flex items-center gap-0.5",children:[e.jsx(vD,{className:"h-3 w-3"})," ",Ie.sqft.toLocaleString()]})]}),Ie.status&&e.jsx("div",{className:"flex items-center gap-2 mt-1 flex-wrap",children:e.jsx(We,{variant:"outline",className:"text-[10px]",children:Ie.status})})]})]})})},Ie.mlsNumber||Me)})})]})}),l==="mls"&&e.jsxs(e.Fragment,{children:[e.jsxs(_e,{className:"overflow-hidden",children:[e.jsxs(zt,{children:[e.jsxs(qt,{className:"flex items-center gap-2 text-base md:text-lg",children:[e.jsx(Gr,{className:"h-5 w-5 text-primary"})," Search MLS"]}),e.jsxs(_r,{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(De,{className:"space-y-3",children:[e.jsx(ya,{value:u,onValueChange:Ie=>h(Ie),children:e.jsxs(va,{children:[e.jsxs(ls,{value:"address",children:[e.jsx(ii,{className:"h-4 w-4 mr-1.5"})," Address"]}),e.jsxs(ls,{value:"mls",children:[e.jsx(pf,{className:"h-4 w-4 mr-1.5"})," MLS #"]})]})}),e.jsxs("div",{className:"flex flex-col sm:flex-row gap-2",children:[e.jsx(we,{value:c,onChange:Ie=>d(Ie.target.value),placeholder:u==="mls"?"Enter MLS number...":"Enter property address...",className:"flex-1",onKeyDown:Ie=>Ie.key==="Enter"&&he()}),e.jsxs(B,{onClick:he,disabled:m||!c.trim(),className:"sm:w-auto w-full",children:[m?e.jsx(us,{className:"h-4 w-4 animate-spin mr-1.5"}):e.jsx(Gr,{className:"h-4 w-4 mr-1.5"})," Search"]})]})]})]}),g.length>0&&e.jsxs("div",{className:"space-y-3",children:[e.jsxs("h3",{className:"text-sm font-medium text-muted-foreground",children:[g.length," listing",g.length!==1?"s":""," found"]}),e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-3",children:g.map((Ie,Me)=>{var Re;return e.jsx(_e,{className:"cursor-pointer hover:border-primary/50 hover:shadow-md transition-all group overflow-hidden",onClick:()=>xe(Ie),children:e.jsx(De,{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:(Re=Ie.photos)!=null&&Re[0]?e.jsx("img",{src:Ie.photos[0],alt:Ie.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(_a,{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:rLe(Ie.price)}),e.jsx("p",{className:"text-sm text-muted-foreground truncate",children:Ie.address}),e.jsxs("p",{className:"text-xs text-muted-foreground truncate",children:[Ie.city,", ",Ie.state," ",Ie.zip]}),e.jsxs("div",{className:"flex items-center gap-3 mt-1.5 text-xs text-muted-foreground",children:[Ie.bedrooms>0&&e.jsxs("span",{className:"flex items-center gap-0.5",children:[e.jsx(J4,{className:"h-3 w-3"})," ",Ie.bedrooms]}),Ie.bathrooms>0&&e.jsxs("span",{className:"flex items-center gap-0.5",children:[e.jsx(Wx,{className:"h-3 w-3"})," ",Ie.bathrooms]}),Ie.sqft>0&&e.jsxs("span",{className:"flex items-center gap-0.5",children:[e.jsx(vD,{className:"h-3 w-3"})," ",Ie.sqft.toLocaleString()]})]}),e.jsxs("div",{className:"flex items-center gap-2 mt-1 flex-wrap",children:[Ie.mlsNumber&&e.jsx(We,{variant:"outline",className:"text-[10px]",children:Ie.mlsNumber}),Ie.status&&e.jsx(We,{variant:"outline",className:"text-[10px]",children:Ie.status})]})]})]})})},Ie.mlsNumber||Me)})})]})]})]}),te==="customize"&&x&&ge&&e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-3 gap-4 md:gap-6",children:[e.jsxs(_e,{className:"lg:col-span-1 overflow-hidden min-w-0",children:[e.jsx(zt,{className:"pb-3",children:e.jsx(qt,{className:"text-base",children:"Selected listing"})}),e.jsxs(De,{className:"space-y-3",children:[x.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:x.photos[b],alt:"",className:"w-full h-full object-cover"})}),x.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:()=>k(Ie=>Math.max(0,Ie-1)),disabled:b===0,children:e.jsx(Fc,{className:"h-4 w-4"})}),e.jsxs("span",{className:"text-xs text-muted-foreground",children:[b+1," of ",x.photos.length]}),e.jsx(B,{variant:"outline",size:"icon",className:"h-7 w-7",onClick:()=>k(Ie=>Math.min(x.photos.length-1,Ie+1)),disabled:b===x.photos.length-1,children:e.jsx(Qa,{className:"h-4 w-4"})})]})]}),e.jsxs("div",{children:[e.jsx("p",{className:"font-bold text-lg",children:rLe(x.price)}),e.jsx("p",{className:"text-sm text-muted-foreground",children:x.address}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[x.city,", ",x.state," ",x.zip]})]}),e.jsxs("div",{className:"grid grid-cols-3 gap-2 text-center",children:[x.bedrooms>0&&e.jsxs("div",{className:"bg-muted/50 rounded-lg p-2",children:[e.jsx("p",{className:"text-sm font-semibold",children:x.bedrooms}),e.jsx("p",{className:"text-[10px] text-muted-foreground",children:"Beds"})]}),x.bathrooms>0&&e.jsxs("div",{className:"bg-muted/50 rounded-lg p-2",children:[e.jsx("p",{className:"text-sm font-semibold",children:x.bathrooms}),e.jsx("p",{className:"text-[10px] text-muted-foreground",children:"Baths"})]}),x.sqft>0&&e.jsxs("div",{className:"bg-muted/50 rounded-lg p-2",children:[e.jsx("p",{className:"text-sm font-semibold",children:x.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:()=>{ne("search"),_(null)},children:[e.jsx(hf,{className:"h-3.5 w-3.5 mr-1.5"})," Choose different listing"]})]})]}),e.jsxs(_e,{className:"lg:col-span-2 overflow-hidden min-w-0",children:[e.jsxs(zt,{children:[e.jsxs(qt,{className:"flex items-center gap-2 text-base",children:[e.jsx(Cn,{className:"h-5 w-5 text-primary"})," Customize"]}),e.jsx(_r,{children:"Pick a template, post type, and output format."})]}),e.jsxs(De,{className:"space-y-5",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsxs(re,{className:"text-sm font-medium flex items-center gap-2",children:[e.jsx(zc,{className:"h-4 w-4"})," Template style"]}),e.jsx("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-2",children:hDs.map(Ie=>e.jsxs("button",{onClick:()=>L(Ie.value),className:`flex flex-col items-center gap-1 px-2 py-3 rounded-lg border-2 transition-all text-center ${M===Ie.value?"border-primary bg-primary/5":"border-border hover:border-primary/30"}`,children:[e.jsx("span",{className:"text-2xl",children:Ie.preview}),e.jsx("span",{className:"text-sm font-medium",children:Ie.label}),e.jsx("span",{className:"text-[10px] text-muted-foreground leading-tight",children:Ie.description})]},Ie.value))})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{className:"text-sm font-medium",children:"Post type"}),e.jsx("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-2",children:uDs.map(Ie=>e.jsxs("button",{onClick:()=>T(Ie.value),className:`flex items-center justify-center gap-2 px-3 py-2.5 rounded-lg border-2 transition-all text-sm font-medium ${A===Ie.value?"border-primary bg-primary/5":"border-border hover:border-primary/30"}`,children:[e.jsx("span",{className:"text-lg",children:Ie.icon})," ",e.jsx("span",{className:"truncate",children:Ie.label})]},Ie.value))})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{className:"text-sm font-medium",children:"Output formats"}),e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-2",children:mot.map(Ie=>e.jsxs("button",{onClick:()=>ve(Ie.value),className:`flex items-center gap-2 px-3 py-2.5 rounded-lg border-2 transition-all text-sm ${P.includes(Ie.value)?"border-primary bg-primary/5":"border-border hover:border-primary/30"}`,children:[Ie.icon,e.jsxs("div",{className:"text-left min-w-0",children:[e.jsx("p",{className:"font-medium truncate",children:Ie.label}),e.jsx("p",{className:"text-[10px] text-muted-foreground",children:Ie.dimensions})]})]},Ie.value))})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs(re,{className:"text-sm font-medium flex items-center gap-2",children:[e.jsx(Ro,{className:"h-4 w-4"})," Show my branding"]}),e.jsx(zn,{checked:z,onCheckedChange:$})]}),z&&!a&&e.jsxs("p",{className:"text-xs text-muted-foreground",children:["No brand preset yet. ",e.jsx(cr,{to:"/marketing-studio/brand-kit",className:"underline",children:"Create one"})," to add your headshot and name."]}),z&&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(re,{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*(cT[P[0]||"instagram-square"].height/cT[P[0]||"instagram-square"].width)},children:(()=>{const Ie=pot[M],Me=P[0]||"instagram-square";return e.jsx(Ie,{...ge,format:Me})})()})})]}),e.jsx(B,{onClick:be,disabled:P.length===0||V,size:"lg",className:"w-full gap-2",children:V?e.jsxs(e.Fragment,{children:[e.jsx(us,{className:"h-5 w-5 animate-spin"})," Generating..."]}):e.jsxs(e.Fragment,{children:[e.jsx(Cn,{className:"h-5 w-5"})," Generate ",P.length," design",P.length>1?"s":""]})})]})]})]}),te==="generate"&&e.jsxs("div",{className:"space-y-4",children:[V&&e.jsx(_e,{children:e.jsxs(De,{className:"flex flex-col items-center justify-center py-16",children:[e.jsx(us,{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."})]})}),G.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:()=>ne("customize"),children:[e.jsx(hf,{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:G.map((Ie,Me)=>{const Re=mot.find(Be=>Be.value===Ie.format);return e.jsxs(_e,{className:"overflow-hidden",children:[e.jsx("div",{className:"bg-muted/30 p-1",children:e.jsx("img",{src:Ie.url,alt:"",className:"w-full rounded"})}),e.jsxs(De,{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:[Re==null?void 0:Re.icon,e.jsx("span",{className:"text-sm font-medium",children:Re==null?void 0:Re.label})]}),e.jsx(We,{variant:"outline",className:"text-[10px]",children:Re==null?void 0:Re.dimensions})]}),e.jsxs(B,{size:"sm",className:"w-full gap-1.5",onClick:()=>Se(Ie.url,Ie.format),children:[e.jsx(oi,{className:"h-3.5 w-3.5"})," Download"]})]})]},Me)})})]})]}),te==="generate"&&x&&ge&&e.jsx("div",{style:{position:"fixed",left:"-99999px",top:0,pointerEvents:"none"},"aria-hidden":!0,children:P.map(Ie=>{const Me=pot[M],Re=cT[Ie];return e.jsx("div",{style:{width:Re.width,height:Re.height},children:e.jsx(Me,{ref:Be=>{me.current[`${M}-${Ie}`]=Be},...ge,format:Ie})},`${M}-${Ie}`)})})]})})}var rEt="Toggle",OVe=N.forwardRef((s,t)=>{const{pressed:n,defaultPressed:r,onPressedChange:a,...i}=s,[l,o]=Ng({prop:n,onChange:a,defaultProp:r??!1,caller:rEt});return e.jsx(Da.button,{type:"button","aria-pressed":l,"data-state":l?"on":"off","data-disabled":s.disabled?"":void 0,...i,ref:t,onClick:la(s.onClick,()=>{s.disabled||o(!l)})})});OVe.displayName=rEt;var aEt=OVe,ZE="ToggleGroup",[iEt,uFn]=Um(ZE,[ME]),oEt=ME(),FVe=Rt.forwardRef((s,t)=>{const{type:n,...r}=s;if(n==="single"){const a=r;return e.jsx(gDs,{...a,ref:t})}if(n==="multiple"){const a=r;return e.jsx(xDs,{...a,ref:t})}throw new Error(`Missing prop \`type\` expected on \`${ZE}\``)});FVe.displayName=ZE;var[lEt,cEt]=iEt(ZE),gDs=Rt.forwardRef((s,t)=>{const{value:n,defaultValue:r,onValueChange:a=()=>{},...i}=s,[l,o]=Ng({prop:n,defaultProp:r??"",onChange:a,caller:ZE});return e.jsx(lEt,{scope:s.__scopeToggleGroup,type:"single",value:Rt.useMemo(()=>l?[l]:[],[l]),onItemActivate:o,onItemDeactivate:Rt.useCallback(()=>o(""),[o]),children:e.jsx(dEt,{...i,ref:t})})}),xDs=Rt.forwardRef((s,t)=>{const{value:n,defaultValue:r,onValueChange:a=()=>{},...i}=s,[l,o]=Ng({prop:n,defaultProp:r??[],onChange:a,caller:ZE}),c=Rt.useCallback(u=>o((h=[])=>[...h,u]),[o]),d=Rt.useCallback(u=>o((h=[])=>h.filter(m=>m!==u)),[o]);return e.jsx(lEt,{scope:s.__scopeToggleGroup,type:"multiple",value:l,onItemActivate:c,onItemDeactivate:d,children:e.jsx(dEt,{...i,ref:t})})});FVe.displayName=ZE;var[yDs,vDs]=iEt(ZE),dEt=Rt.forwardRef((s,t)=>{const{__scopeToggleGroup:n,disabled:r=!1,rovingFocus:a=!0,orientation:i,dir:l,loop:o=!0,...c}=s,d=oEt(n),u=F3(l),h={role:"group",dir:u,...c};return e.jsx(yDs,{scope:n,rovingFocus:a,disabled:r,children:a?e.jsx(a4e,{asChild:!0,...d,orientation:i,dir:u,loop:o,children:e.jsx(Da.div,{...h,ref:t})}):e.jsx(Da.div,{...h,ref:t})})}),oke="ToggleGroupItem",uEt=Rt.forwardRef((s,t)=>{const n=cEt(oke,s.__scopeToggleGroup),r=vDs(oke,s.__scopeToggleGroup),a=oEt(s.__scopeToggleGroup),i=n.value.includes(s.value),l=r.disabled||s.disabled,o={...s,pressed:i,disabled:l},c=Rt.useRef(null);return r.rovingFocus?e.jsx(i4e,{asChild:!0,...a,focusable:!l,active:i,ref:c,children:e.jsx(fot,{...o,ref:t})}):e.jsx(fot,{...o,ref:t})});uEt.displayName=oke;var fot=Rt.forwardRef((s,t)=>{const{__scopeToggleGroup:n,value:r,...a}=s,i=cEt(oke,n),l={role:"radio","aria-checked":s.pressed,"aria-pressed":void 0},o=i.type==="single"?l:void 0;return e.jsx(OVe,{...o,...a,ref:t,onPressedChange:c=>{c?i.onItemActivate(r):i.onItemDeactivate(r)}})}),hEt=FVe,mEt=uEt;const pEt=RR("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"}}),bDs=N.forwardRef(({className:s,variant:t,size:n,...r},a)=>e.jsx(aEt,{ref:a,className:Ot(pEt({variant:t,size:n,className:s})),...r}));bDs.displayName=aEt.displayName;const fEt=N.createContext({size:"default",variant:"default"}),Y9=N.forwardRef(({className:s,variant:t,size:n,children:r,...a},i)=>e.jsx(hEt,{ref:i,className:Ot("flex items-center justify-center gap-1",s),...a,children:e.jsx(fEt.Provider,{value:{variant:t,size:n},children:r})}));Y9.displayName=hEt.displayName;const PD=N.forwardRef(({className:s,children:t,variant:n,size:r,...a},i)=>{const l=N.useContext(fEt);return e.jsx(mEt,{ref:i,className:Ot(pEt({variant:l.variant||n,size:l.size||r}),s),...a,children:t})});PD.displayName=mEt.displayName;const _Ds=[{id:"meet",label:"Meet Your Agent",icon:Ro,description:"Polished intro card with your headshot, story, and contact."},{id:"testimonial",label:"Testimonial",icon:Q2,description:"Turn a Zillow / Google review into a branded graphic."},{id:"milestone",label:"Milestone",icon:gl,description:"Celebrate homes sold, awards, anniversaries, achievements."},{id:"tip",label:"Pro Tip",icon:Z2,description:"Drop a value-bomb tip — buyer/seller advice, market insight."},{id:"quote",label:"Quote / Mantra",icon:um,description:"Personal philosophy, mantra, or rallying call."}],aLe={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"}},wDs=[{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."}],got={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 jDs(){const{data:s}=MMs(),{data:t}=XQ(),[n,r]=N.useState(void 0),a=N.useMemo(()=>(t==null?void 0:t.find(g=>g.id===n))??s??null,[t,n,s]),[i,l]=N.useState({template:"meet",style:"editorial",aspect:"portrait",rating:5,...got.meet}),o=g=>l(y=>({...y,...g})),c=g=>l(y=>({...y,template:g,...got[g]})),d=N.useRef(null),[u,h]=N.useState(!1),m=async()=>{if(!d.current)return;h(!0);const g=d.current,y=g.style.transform;try{g.style.transform="none",await new Promise(b=>requestAnimationFrame(()=>b(null)));const x=await LVe(g,{cacheBust:!0,pixelRatio:2,width:g.offsetWidth,height:g.offsetHeight,backgroundColor:"#ffffff"}),_=document.createElement("a");_.href=x,_.download=`personal-branding-${i.template}-${Date.now()}.png`,document.body.appendChild(_),_.click(),_.remove(),ie.success("Downloaded to your device")}catch(x){ie.error((x==null?void 0:x.message)||"Export failed")}finally{g.style.transform=y,h(!1)}},f=aLe[i.aspect];return e.jsx(Qs,{title:"Personal Branding",children:e.jsxs("div",{className:"container max-w-7xl py-6 md:py-8 space-y-6 px-4",children:[e.jsxs(ic,{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(cr,{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(We,{variant:"secondary",className:"gap-1",children:[e.jsx(Cn,{className:"h-3 w-3"})," New"]})}),e.jsx("h1",{className:"text-2xl md:text-3xl font-bold tracking-tight mt-1",children:"Personal Branding"}),e.jsx("p",{className:"text-sm md:text-base text-muted-foreground max-w-2xl",children:"Five editorial-grade templates, four distinct aesthetics. Pick one, drop in your story, export in seconds."})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(B,{variant:"outline",asChild:!0,children:e.jsxs(cr,{to:"/marketing-studio/brand-kit",children:[e.jsx(zc,{className:"h-4 w-4 mr-1"})," Brand Kit"]})}),e.jsxs(B,{onClick:m,disabled:u,children:[e.jsx(oi,{className:"h-4 w-4 mr-1"})," ",u?"Exporting…":"Download"]})]})]}),e.jsxs("div",{className:"grid lg:grid-cols-[380px_1fr] gap-6",children:[e.jsxs("div",{className:"space-y-5",children:[e.jsx(_e,{children:e.jsxs(De,{className:"p-4 space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{className:"text-xs uppercase tracking-wider text-muted-foreground",children:"Template"}),e.jsx("div",{className:"grid grid-cols-2 gap-2",children:_Ds.map(g=>{const y=g.icon,x=i.template===g.id;return e.jsxs("button",{onClick:()=>c(g.id),className:`text-left rounded-lg border p-3 transition-all ${x?"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:g.label})]},g.id)})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{className:"text-xs uppercase tracking-wider text-muted-foreground",children:"Style"}),e.jsx(Y9,{type:"single",value:i.style,onValueChange:g=>g&&o({style:g}),className:"grid grid-cols-2 gap-1",children:wDs.map(g=>e.jsx(PD,{value:g.id,className:"text-xs h-9",children:g.label},g.id))})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{className:"text-xs uppercase tracking-wider text-muted-foreground",children:"Format"}),e.jsx(Y9,{type:"single",value:i.aspect,onValueChange:g=>g&&o({aspect:g}),className:"grid grid-cols-3 gap-1",children:Object.keys(aLe).map(g=>e.jsx(PD,{value:g,className:"text-xs h-9",children:aLe[g].label},g))})]}),t&&t.length>0&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{className:"text-xs uppercase tracking-wider text-muted-foreground",children:"Brand preset"}),e.jsxs(Ns,{value:n??(s==null?void 0:s.id)??"",onValueChange:r,children:[e.jsx(ws,{children:e.jsx(ks,{placeholder:"Choose preset"})}),e.jsx(js,{children:t.map(g=>e.jsx(nt,{value:g.id,children:g.name},g.id))})]})]})]})}),e.jsx(_e,{children:e.jsxs(De,{className:"p-4 space-y-3",children:[e.jsx(re,{className:"text-xs uppercase tracking-wider text-muted-foreground",children:"Content"}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(re,{htmlFor:"headline",className:"text-xs",children:"Headline"}),e.jsx(Ws,{id:"headline",value:i.headline,onChange:g=>o({headline:g.target.value}),rows:2})]}),i.template!=="quote"&&e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(re,{htmlFor:"subline",className:"text-xs",children:"Subline"}),e.jsx(we,{id:"subline",value:i.subline,onChange:g=>o({subline:g.target.value})})]}),i.template!=="quote"&&e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(re,{htmlFor:"body",className:"text-xs",children:"Body"}),e.jsx(Ws,{id:"body",value:i.body,onChange:g=>o({body:g.target.value}),rows:4})]}),(i.template==="testimonial"||i.template==="quote")&&e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(re,{htmlFor:"attribution",className:"text-xs",children:"Attribution"}),e.jsx(we,{id:"attribution",value:i.attribution,onChange:g=>o({attribution:g.target.value}),placeholder:"— Client name / Source"})]}),i.template==="testimonial"&&e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(re,{className:"text-xs",children:"Rating"}),e.jsx(Y9,{type:"single",value:String(i.rating),onValueChange:g=>g&&o({rating:Number(g)}),className:"grid grid-cols-5 gap-1",children:[1,2,3,4,5].map(g=>e.jsxs(PD,{value:String(g),className:"text-xs h-9",children:[g,"★"]},g))})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(re,{htmlFor:"badge",className:"text-xs",children:"Eyebrow tag"}),e.jsx(we,{id:"badge",value:i.badgeText,onChange:g=>o({badgeText:g.target.value})})]})]})})]}),e.jsx(NDs,{aspect:f,canvasRef:d,children:e.jsx(kDs,{form:i,preset:a,width:f.w,height:f.h})})]})]})})}function NDs({aspect:s,canvasRef:t,children:n}){const r=N.useRef(null),[a,i]=N.useState(.5);return N.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 kDs({form:s,preset:t,width:n,height:r}){const a=(t==null?void 0:t.brand_color)||"#0F172A",i=(t==null?void 0:t.accent_color)||"#D4AF37",l=t==null?void 0:t.headshot_url,o=t==null?void 0:t.brokerage_logo_url,c=(t==null?void 0:t.display_name)||"Your Name",d=(t==null?void 0:t.phone)||"",u=(t==null?void 0:t.email)||"",h=(t==null?void 0:t.tagline)||"",m=(t==null?void 0:t.website_url)||"",f={form:s,brandColor:a,accentColor:i,headshot:l,logo:o,name:c,phone:d,email:u,tagline:h,website:m,width:n,height:r};return s.style==="editorial"?e.jsx(SDs,{...f}):s.style==="bold"?e.jsx(CDs,{...f}):s.style==="luxury"?e.jsx(TDs,{...f}):e.jsx(ADs,{...f})}function gEt({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 M3e({rating:s,color:t}){return e.jsx("div",{style:{display:"flex",gap:4},children:Array.from({length:5}).map((n,r)=>e.jsx(Wa,{size:28,fill:r1.5;return e.jsxs("div",{style:{width:h,height:m,background:"#FAF7F2",position:"relative",fontFamily:"Georgia, serif",color:"#1a1a1a",overflow:"hidden"},children:[e.jsxs("div",{style:{position:"absolute",top:64,left:64,right:64,display:"flex",justifyContent:"space-between",alignItems:"center"},children:[e.jsx("div",{style:{fontFamily:"Inter, sans-serif",fontSize:14,letterSpacing:"0.3em",color:n},children:t.badgeText}),e.jsxs("div",{style:{fontFamily:"Inter, sans-serif",fontSize:12,letterSpacing:"0.2em",color:"#888"},children:["EST. ",new Date().getFullYear()]})]}),e.jsx("div",{style:{position:"absolute",top:100,left:64,right:64,height:1,background:"#1a1a1a",opacity:.15}}),a&&(t.template==="meet"||t.template==="milestone")&&e.jsx("div",{style:{position:"absolute",top:140,left:64,width:h-128,height:f?700:480,overflow:"hidden",borderRadius:4},children:e.jsx("img",{src:a,crossOrigin:"anonymous",style:{width:"100%",height:"100%",objectFit:"cover",objectPosition:"center top",filter:"grayscale(0.15)"}})}),e.jsxs("div",{style:{position:"absolute",left:64,right:64,bottom:220,textAlign:t.template==="quote"?"center":"left"},children:[t.template==="testimonial"&&e.jsx("div",{style:{fontSize:120,lineHeight:.7,color:r,fontFamily:"Georgia, serif"},children:'"'}),e.jsx("h1",{style:{fontSize:t.template==="quote"?76:92,lineHeight:1.05,fontWeight:400,margin:0,letterSpacing:"-0.02em",whiteSpace:"pre-wrap"},children:t.headline}),t.subline&&e.jsx("div",{style:{fontFamily:"Inter, sans-serif",fontSize:22,marginTop:16,color:"#555",fontStyle:"italic"},children:t.subline}),t.body&&e.jsx("p",{style:{fontFamily:"Inter, sans-serif",fontSize:22,lineHeight:1.5,color:"#333",marginTop:28,maxWidth:820},children:t.body}),t.template==="testimonial"&&e.jsxs("div",{style:{marginTop:24,display:"flex",alignItems:"center",gap:16},children:[e.jsx(M3e,{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(gEt,{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 CDs(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%, ${EDs(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(M3e,{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(gEt,{name:l,phone:o,email:c,website:d,color:"#fff"})]})]})}function ADs(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(M3e,{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 TDs(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(M3e,{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 EDs(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 MDs=()=>{const{swagId:s}=uo(),{user:t}=Ls(),{toast:n}=Ci(),r=as(),{trackEngagement:a}=pU(),[i,l]=N.useState(""),{data:o,isLoading:c}=mt({queryKey:["social-swag-detail",s],queryFn:async()=>{const{data:_,error:b}=await H.from("social_swag").select("*").eq("id",s).single();if(b)throw b;const{data:k}=await H.from("social_swag_links").select("*").eq("swag_id",s).order("sort_order");return{..._,links:k||[]}},enabled:!!s});N.useEffect(()=>{o&&a("social_swag",o.id,o.title,"view")},[o==null?void 0:o.id]);const{data:d=[]}=mt({queryKey:["social-swag-likes",s],queryFn:async()=>{const{data:_,error:b}=await H.from("social_swag_likes").select("*").eq("swag_id",s);if(b)throw b;return _},enabled:!!s}),{data:u=[]}=mt({queryKey:["social-swag-comments",s],queryFn:async()=>{const{data:_,error:b}=await H.from("social_swag_comments").select("*").eq("swag_id",s).order("created_at",{ascending:!1});if(b)throw b;const k=[...new Set(_.map(P=>P.user_id))],{data:A}=await H.from("profiles").select("id, name").in("id",k),T=new Map((A==null?void 0:A.map(P=>[P.id,P.name]))||[]);return _.map(P=>({...P,user_name:T.get(P.user_id)||"Unknown User"}))},enabled:!!s}),h=_t({mutationFn:async _=>{const{error:b}=await H.from("social_swag_comments").insert({swag_id:s,user_id:t.id,content:_});if(b)throw b},onSuccess:()=>{r.invalidateQueries({queryKey:["social-swag-comments",s]}),l(""),n({title:"Comment added!"})},onError:_=>{n({title:"Error adding comment",description:_.message,variant:"destructive"})}}),m=_t({mutationFn:async _=>{const{error:b}=await H.from("social_swag_comments").delete().eq("id",_);if(b)throw b},onSuccess:()=>{r.invalidateQueries({queryKey:["social-swag-comments",s]}),n({title:"Comment deleted"})}}),f=_t({mutationFn:async()=>{const _=d.find(b=>b.user_id===(t==null?void 0:t.id));if(_){const{error:b}=await H.from("social_swag_likes").delete().eq("id",_.id);if(b)throw b}else{const{error:b}=await H.from("social_swag_likes").insert({swag_id:s,user_id:t.id});if(b)throw b}},onSuccess:()=>{r.invalidateQueries({queryKey:["social-swag-likes",s]})}}),g=d.some(_=>_.user_id===(t==null?void 0:t.id)),y=_=>_.split(" ").map(b=>b[0]).join("").toUpperCase().slice(0,2),x=_=>{_.preventDefault(),!(!i.trim()||!t)&&h.mutate(i.trim())};return c?e.jsx(Qs,{title:"Social Swag",children:e.jsx("div",{className:"flex justify-center py-12",children:e.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})})}):o?e.jsx(Qs,{title:o.title,children:e.jsxs("div",{className:"space-y-6 max-w-5xl mx-auto",children:[e.jsx(B,{variant:"ghost",size:"sm",asChild:!0,className:"gap-2",children:e.jsxs(cr,{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(yU,{resourceType:"social_swag",resourceId:o.id,resourceTitle:o.title}),e.jsxs(B,{variant:g?"default":"outline",className:"gap-2 w-fit",onClick:()=>f.mutate(),disabled:!t||f.isPending,children:[e.jsx(ax,{className:`h-4 w-4 ${g?"fill-current":""}`}),d.length," ",d.length===1?"Like":"Likes"]})]})]}),o.description&&e.jsx("div",{className:"text-muted-foreground prose prose-sm max-w-none dark:prose-invert",dangerouslySetInnerHTML:{__html:o.description}})]}),o.links.length>0&&e.jsx(_e,{children:e.jsxs(De,{className:"pt-6",children:[e.jsxs("h3",{className:"font-semibold flex items-center gap-2 mb-4",children:[e.jsx(gc,{className:"h-4 w-4"}),o.links.length===1?"Canva Link":"Canva Links"]}),e.jsx("div",{className:"grid gap-2",children:o.links.map(_=>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(_.canva_share_link,"_blank")},children:[e.jsx("span",{className:"font-medium",children:_.title}),e.jsx(Tr,{className:"h-4 w-4 text-muted-foreground"})]},_.id))})]})}),e.jsx(Wl,{}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("h3",{className:"font-semibold flex items-center gap-2 text-lg",children:[e.jsx(Ud,{className:"h-5 w-5"}),"Comments (",u.length,")"]}),t?e.jsxs("form",{onSubmit:x,className:"flex gap-2",children:[e.jsx(Ws,{placeholder:"Add a comment...",value:i,onChange:_=>l(_.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(Rr,{className:"h-4 w-4"})})]}):e.jsx("p",{className:"text-sm text-muted-foreground",children:"Log in to add a comment"}),e.jsx("div",{className:"space-y-4",children:u.length===0?e.jsx(_e,{children:e.jsx(De,{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(_=>e.jsx(_e,{children:e.jsx(De,{className:"pt-4 pb-4",children:e.jsxs("div",{className:"flex gap-3",children:[e.jsx(Ua,{className:"h-10 w-10 flex-shrink-0",children:e.jsx(qa,{className:"text-sm",children:y(_.user_name||"U")})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[e.jsx("span",{className:"font-medium",children:_.user_name}),e.jsx("span",{className:"text-sm text-muted-foreground",children:nc(new Date(_.created_at),{addSuffix:!0})}),_.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(_.id),children:e.jsx(qn,{className:"h-3 w-3 text-muted-foreground"})})]}),e.jsx("p",{className:"text-sm whitespace-pre-wrap",children:_.content})]})]})})},_.id))})]})]})}):e.jsx(Qs,{title:"Social Swag",children:e.jsxs("div",{className:"flex flex-col items-center justify-center py-12 text-center",children:[e.jsx(gc,{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(cr,{to:"/social-swag",children:"Back to Social Swag"})})]})})},LDs=({categories:s,privateGroups:t,selectedFilter:n,onFilterChange:r,onlineUsers:a})=>{const[i,l]=N.useState(!0),[o,c]=N.useState(!0),[d,u]=N.useState(!0),h=m=>m.split(" ").map(f=>f[0]).join("").toUpperCase().slice(0,2);return e.jsx("aside",{className:"w-64 shrink-0 hidden lg:block relative z-0",children:e.jsx("div",{className:"sticky top-4 space-y-4 max-h-[calc(100vh-8rem)] overflow-y-auto overscroll-contain",children:e.jsxs("div",{className:"space-y-2 pr-4",children:[e.jsxs(B,{variant:n==="all"?"secondary":"ghost",className:"w-full justify-start",onClick:()=>r("all"),children:[e.jsx(CT,{className:"h-4 w-4 mr-2"}),"All Posts"]}),e.jsxs(Kv,{open:i,onOpenChange:l,children:[e.jsx(Yv,{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(Xo,{className:"h-4 w-4"}):e.jsx(Qa,{className:"h-4 w-4"})]})}),e.jsx(Zv,{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(Kv,{open:o,onOpenChange:c,children:[e.jsx(Yv,{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(Au,{className:"h-3 w-3"}),"Your Groups"]}),o?e.jsx(Xo,{className:"h-4 w-4"}):e.jsx(Qa,{className:"h-4 w-4"})]})}),e.jsx(Zv,{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(Kv,{open:d,onOpenChange:u,children:[e.jsx(Yv,{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(Yn,{className:"h-3 w-3"}),"Online Now",a.length>0&&e.jsx("span",{className:"ml-1 bg-green-500 text-white text-xs rounded-full px-1.5 py-0.5 min-w-[20px] text-center",children:a.length})]}),d?e.jsx(Xo,{className:"h-4 w-4"}):e.jsx(Qa,{className:"h-4 w-4"})]})}),e.jsx(Zv,{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(Ua,{className:"h-7 w-7",children:[e.jsx(Gi,{src:m.avatarUrl}),e.jsx(qa,{className:"text-xs",children:h(m.name)})]}),e.jsx(bg,{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))})]})]})})})},PDs=({categories:s,privateGroups:t,selectedFilter:n,onFilterChange:r,onlineUsers:a})=>{const[i,l]=N.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(qd,{children:[e.jsx(Vd,{asChild:!0,children:e.jsxs(B,{variant:"outline",className:"flex-1 justify-between",children:[e.jsx("span",{className:"truncate",children:c()}),e.jsx(Xo,{className:"h-4 w-4 ml-2 shrink-0"})]})}),e.jsxs(Ld,{className:"w-56 bg-background border",children:[e.jsxs(ba,{onClick:()=>r("all"),children:[e.jsx(CT,{className:"h-4 w-4 mr-2"}),"All Posts"]}),e.jsx(s1,{}),e.jsx(cE,{className:"text-xs text-muted-foreground",children:"Categories"}),s.map(d=>e.jsxs(ba,{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(s1,{}),e.jsxs(cE,{className:"text-xs text-muted-foreground flex items-center gap-1",children:[e.jsx(Au,{className:"h-3 w-3"}),"Your Groups"]}),t.map(d=>e.jsxs(ba,{onClick:()=>r(`group:${d.id}`),children:[e.jsx("span",{className:"mr-2",children:d.icon||"🔒"}),d.name]},d.id))]})]})]}),e.jsxs(l1,{open:i,onOpenChange:l,children:[e.jsx(PQ,{asChild:!0,children:e.jsxs(B,{variant:"outline",size:"icon",className:"relative",children:[e.jsx(Yn,{className:"h-4 w-4"}),a.length>0&&e.jsx("span",{className:"absolute -top-1 -right-1 bg-green-500 text-white text-xs rounded-full h-4 w-4 flex items-center justify-center",children:a.length})]})}),e.jsxs(Gy,{children:[e.jsx(gb,{children:e.jsxs(xb,{className:"flex items-center gap-2",children:[e.jsx(Yn,{className:"h-5 w-5"}),"Online Now (",a.length,")"]})}),e.jsx(lo,{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(Ua,{className:"h-10 w-10",children:[e.jsx(Gi,{src:d.avatarUrl}),e.jsx(qa,{children:o(d.name)})]}),e.jsx(bg,{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 iLe,L3e="HoverCard",[xEt,hFn]=Um(L3e,[q5]),P3e=q5(),[IDs,zVe]=xEt(L3e),yEt=s=>{const{__scopeHoverCard:t,children:n,open:r,defaultOpen:a,onOpenChange:i,openDelay:l=700,closeDelay:o=300}=s,c=P3e(t),d=N.useRef(0),u=N.useRef(0),h=N.useRef(!1),m=N.useRef(!1),[f,g]=Ng({prop:r,defaultProp:a??!1,onChange:i,caller:L3e}),y=N.useCallback(()=>{clearTimeout(u.current),d.current=window.setTimeout(()=>g(!0),l)},[l,g]),x=N.useCallback(()=>{clearTimeout(d.current),!h.current&&!m.current&&(u.current=window.setTimeout(()=>g(!1),o))},[o,g]),_=N.useCallback(()=>g(!1),[g]);return N.useEffect(()=>()=>{clearTimeout(d.current),clearTimeout(u.current)},[]),e.jsx(IDs,{scope:t,open:f,onOpenChange:g,onOpen:y,onClose:x,onDismiss:_,hasSelectionRef:h,isPointerDownOnContentRef:m,children:e.jsx(gQ,{...c,children:n})})};yEt.displayName=L3e;var vEt="HoverCardTrigger",bEt=N.forwardRef((s,t)=>{const{__scopeHoverCard:n,...r}=s,a=zVe(vEt,n),i=P3e(n);return e.jsx(J$,{asChild:!0,...i,children:e.jsx(Da.a,{"data-state":a.open?"open":"closed",...r,ref:t,onPointerEnter:la(s.onPointerEnter,cke(a.onOpen)),onPointerLeave:la(s.onPointerLeave,cke(a.onClose)),onFocus:la(s.onFocus,a.onOpen),onBlur:la(s.onBlur,a.onClose),onTouchStart:la(s.onTouchStart,l=>l.preventDefault())})})});bEt.displayName=vEt;var DDs="HoverCardPortal",[mFn,RDs]=xEt(DDs,{forceMount:void 0}),lke="HoverCardContent",_Et=N.forwardRef((s,t)=>{const n=RDs(lke,s.__scopeHoverCard),{forceMount:r=n.forceMount,...a}=s,i=zVe(lke,s.__scopeHoverCard);return e.jsx(Xf,{present:r||i.open,children:e.jsx(ODs,{"data-state":i.open?"open":"closed",...a,onPointerEnter:la(s.onPointerEnter,cke(i.onOpen)),onPointerLeave:la(s.onPointerLeave,cke(i.onClose)),ref:t})})});_Et.displayName=lke;var ODs=N.forwardRef((s,t)=>{const{__scopeHoverCard:n,onEscapeKeyDown:r,onPointerDownOutside:a,onFocusOutside:i,onInteractOutside:l,...o}=s,c=zVe(lke,n),d=P3e(n),u=N.useRef(null),h=jo(t,u),[m,f]=N.useState(!1);return N.useEffect(()=>{if(m){const g=document.body;return iLe=g.style.userSelect||g.style.webkitUserSelect,g.style.userSelect="none",g.style.webkitUserSelect="none",()=>{g.style.userSelect=iLe,g.style.webkitUserSelect=iLe}}},[m]),N.useEffect(()=>{if(u.current){const g=()=>{f(!1),c.isPointerDownOnContentRef.current=!1,setTimeout(()=>{var x;((x=document.getSelection())==null?void 0:x.toString())!==""&&(c.hasSelectionRef.current=!0)})};return document.addEventListener("pointerup",g),()=>{document.removeEventListener("pointerup",g),c.hasSelectionRef.current=!1,c.isPointerDownOnContentRef.current=!1}}},[c.isPointerDownOnContentRef,c.hasSelectionRef]),N.useEffect(()=>{u.current&&BDs(u.current).forEach(y=>y.setAttribute("tabindex","-1"))}),e.jsx(TE,{asChild:!0,disableOutsidePointerEvents:!1,onInteractOutside:l,onEscapeKeyDown:r,onPointerDownOutside:a,onFocusOutside:la(i,g=>{g.preventDefault()}),onDismiss:c.onDismiss,children:e.jsx(xQ,{...d,...o,onPointerDown:la(o.onPointerDown,g=>{g.currentTarget.contains(g.target)&&f(!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)"}})})}),FDs="HoverCardArrow",zDs=N.forwardRef((s,t)=>{const{__scopeHoverCard:n,...r}=s,a=P3e(n);return e.jsx(yQ,{...a,...r,ref:t})});zDs.displayName=FDs;function cke(s){return t=>t.pointerType==="touch"?void 0:s()}function BDs(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 $Ds=yEt,UDs=bEt,wEt=_Et;const qDs=$Ds,VDs=UDs,jEt=N.forwardRef(({className:s,align:t="center",sideOffset:n=4,...r},a)=>e.jsx(wEt,{ref:a,align:t,sideOffset:n,className:Ot("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}));jEt.displayName=wEt.displayName;const HDs=[{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"}],GDs=s=>s.split(" ").map(t=>t[0]).join("").toUpperCase().slice(0,2),NEt=({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(qDs,{openDelay:200,closeDelay:100,children:[e.jsx(VDs,{asChild:!0,children:e.jsx("div",{className:"cursor-pointer",children:t})}),e.jsx(jEt,{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=HDs.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(Ua,{className:"h-6 w-6",children:[e.jsx(Gi,{src:l.user_avatar||void 0}),e.jsx(qa,{className:"text-[10px]",children:GDs(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 WDs({images:s,initialIndex:t=0,open:n,onOpenChange:r}){const[a,i]=N.useState(t),[l,o]=N.useState(!1);N.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]);N.useEffect(()=>(window.addEventListener("keydown",u),()=>window.removeEventListener("keydown",u)),[u]);const h=s[a];return e.jsx(Bs,{open:n,onOpenChange:r,children:e.jsxs(Fs,{className:"max-w-[95vw] max-h-[95vh] w-auto h-auto p-0 border-none bg-black/95 overflow-hidden",children:[e.jsx(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(hr,{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(Fc,{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(Qa,{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(D9,{className:"h-5 w-5"}):e.jsx($T,{className:"h-5 w-5"})}),e.jsx("div",{className:Ot("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:Ot("object-contain transition-transform duration-200",l?"max-w-none max-h-none scale-150":"max-w-full max-h-[85vh]")})}),s.length>1&&e.jsx("div",{className:"absolute bottom-12 left-1/2 -translate-x-1/2 z-50 flex gap-2 bg-black/50 p-2 rounded-lg max-w-[90vw] overflow-x-auto",children:s.map((m,f)=>e.jsx("button",{onClick:()=>{i(f),o(!1)},className:Ot("w-12 h-12 rounded overflow-hidden flex-shrink-0 border-2 transition-all",a===f?"border-white":"border-transparent opacity-60 hover:opacity-100"),children:m.type==="video"?e.jsx("video",{src:m.url,className:"w-full h-full object-cover"}):e.jsx("img",{src:m.url,alt:"",className:"w-full h-full object-cover"})},f))})]})})}const Tse=[{type:"like",emoji:"👍",label:"Like"},{type:"love",emoji:"❤️",label:"Love"}],KDs=({commentId:s,reactions:t,currentUserId:n})=>{var d,u;const r=as(),[a,i]=N.useState(!1),l=t.find(h=>h.user_id===n),o=_t({mutationFn:async h=>{l?l.reaction_type===h?await H.from("community_comment_reactions").delete().eq("id",l.id):await H.from("community_comment_reactions").update({reaction_type:h}).eq("id",l.id):await H.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(NEt,{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=Tse.find(f=>f.type===h))==null?void 0:m.emoji},h)})}),e.jsx("span",{children:t.length})]})}),n&&e.jsxs(rc,{open:a,onOpenChange:i,children:[e.jsx(ac,{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=Tse.find(h=>h.type===l.reaction_type))==null?void 0:d.emoji," ",(u=Tse.find(h=>h.type===l.reaction_type))==null?void 0:u.label]}):e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(co,{className:"h-3 w-3"}),"Like"]})})}),e.jsx(Zl,{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:Tse.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 BVe({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(cr,{to:u?`/templates/${d}`:`/profile?user=${d}`,className:Ot("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(N.Fragment,{children:o},c))})}function dke({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=N.useRef(null),h=N.useRef(null),[m,f]=N.useState(!1),[g,y]=N.useState("user"),[x,_]=N.useState(""),[b,k]=N.useState(null),[A,T]=N.useState(0),[P,I]=N.useState({top:0,left:0,width:0}),M=N.useRef(new Map),L=N.useRef(new Map),z=he=>{if(c==="plain"){const be=[];return M.current.forEach((Ie,Me)=>{he.includes(`@${Me}`)&&be.push(Ie)}),[...new Set(be)]}const xe=/@\[([^\]]+)\]\(([^)]+)\)/g,ve=[];let ge;for(;(ge=xe.exec(he))!==null;)ve.push(ge[2]);return[...new Set(ve)]},$=he=>{if(c==="plain"){const be=[];return L.current.forEach((Ie,Me)=>{he.includes(`#${Me}`)&&be.push(Ie)}),[...new Set(be)]}const xe=/#\[([^\]]+)\]\(([^)]+)\)/g,ve=[];let ge;for(;(ge=xe.exec(he))!==null;)ve.push(ge[2]);return[...new Set(ve)]};N.useEffect(()=>{if(i){const he=z(s);i(he)}if(l){const he=$(s);l(he)}},[s,i,l,c]);const{data:V=[],isLoading:W}=mt({queryKey:["mention-users",x],queryFn:async()=>{const he=H.from("profiles").select("id, name").limit(8),xe=x.length>=1?he.ilike("name",`%${x}%`):he.order("name"),{data:ve,error:ge}=await xe;if(ge)throw ge;const be=ve.map(Ie=>Ie.id),Se=await bSt(be);return ve.map(Ie=>({id:Ie.id,name:Ie.name||"Unknown",avatar_url:Se.get(Ie.id)}))},enabled:m&&g==="user",staleTime:3e4}),{data:G=[],isLoading:X}=mt({queryKey:["mention-templates",x],queryFn:async()=>{let he=H.from("canva_templates").select("id, name, preview_image_url").lte("publish_date",new Date().toISOString()).order("publish_date",{ascending:!1}).limit(8);x.length>=1&&(he=he.ilike("name",`%${x}%`));const{data:xe,error:ve}=await he;if(ve)throw ve;return xe||[]},enabled:m&&g==="template"&&d,staleTime:3e4}),te=g==="user"?W:X,ne=g==="user"?V:G,me=he=>he.split(" ").map(xe=>xe[0]).join("").toUpperCase().slice(0,2),ue=he=>{const xe=he.target.value,ve=he.target.selectionStart;t(xe);const ge=xe.substring(0,ve),be=ge.lastIndexOf("@"),Se=d?ge.lastIndexOf("#"):-1;let Ie=-1,Me="user";if(be>Se?(Ie=be,Me="user"):Se>be&&d&&(Ie=Se,Me="template"),Ie!==-1){const Re=ge.substring(Ie+1),Be=Re.includes(" "),Ne=Re.includes(` `);if(!Be&&!Ne&&Re.length<=30){k(Ie),_(Re),y(Me),f(!0),T(0);return}}f(!1),k(null)},ce=he=>{if(b===null)return;const xe=s.substring(0,b),ve=s.substring(b+x.length+1),ge=g==="user"?"@":"#",be=c==="plain"?`${ge}${he.name} `:`${ge}[${he.name}](${he.id}) `;c==="plain"&&(g==="user"?M.current.set(he.name,he.id):L.current.set(he.name,he.id));const Se=xe+be+ve;t(Se),f(!1),k(null),_(""),setTimeout(()=>{if(u.current){const Ie=xe.length+be.length;u.current.focus(),u.current.setSelectionRange(Ie,Ie)}},0)},ae=he=>{if(!(!m||ne.length===0))switch(he.key){case"ArrowDown":he.preventDefault(),T(xe=>(xe+1)%ne.length);break;case"ArrowUp":he.preventDefault(),T(xe=>(xe-1+ne.length)%ne.length);break;case"Enter":ne[A]&&(he.preventDefault(),ce(ne[A]));break;case"Escape":he.preventDefault(),f(!1);break;case"Tab":ne[A]&&(he.preventDefault(),ce(ne[A]));break}};return N.useEffect(()=>{const he=xe=>{h.current&&!h.current.contains(xe.target)&&u.current&&!u.current.contains(xe.target)&&f(!1)};return document.addEventListener("mousedown",he),()=>document.removeEventListener("mousedown",he)},[]),N.useEffect(()=>{if(!m)return;const he=()=>{const xe=u.current;if(!xe)return;const ve=xe.getBoundingClientRect();I({top:ve.bottom+4,left:ve.left,width:ve.width})};return he(),window.addEventListener("resize",he),window.addEventListener("scroll",he,!0),()=>{window.removeEventListener("resize",he),window.removeEventListener("scroll",he,!0)}},[m,s]),e.jsxs("div",{className:"relative flex-1",children:[e.jsx(Ws,{ref:u,value:s,onChange:ue,onKeyDown:he=>{ae(he),he.defaultPrevented||o==null||o(he)},placeholder:n,className:Ot("resize-none",r),style:{minHeight:a}}),m&&Lv.createPortal(e.jsxs("div",{ref:h,className:"fixed z-[1000] max-h-[220px] overflow-hidden rounded-lg border bg-popover shadow-lg",style:{top:P.top,left:P.left,width:P.width,maxWidth:"320px"},children:[e.jsx("div",{className:"px-3 py-1.5 text-xs font-medium text-muted-foreground border-b bg-muted/30",children:g==="user"?"👤 Mention a person":"📋 Link a template"}),te?e.jsx("div",{className:"px-3 py-2 text-sm text-muted-foreground",children:"Searching..."}):ne.length===0?e.jsx("div",{className:"px-3 py-2 text-sm text-muted-foreground",children:x.length<1?`Type to search ${g==="user"?"people":"templates"}...`:`No ${g==="user"?"users":"templates"} found`}):e.jsx("ul",{className:"py-1 max-h-[180px] overflow-y-auto",children:ne.map((he,xe)=>e.jsx("li",{className:Ot("flex items-center gap-2 px-3 py-2 cursor-pointer transition-colors",xe===A?"bg-accent":"hover:bg-accent/50"),onClick:()=>ce(he),onMouseEnter:()=>T(xe),children:g==="user"?e.jsxs(e.Fragment,{children:[e.jsxs(Ua,{className:"h-6 w-6",children:[e.jsx(Gi,{src:he.avatar_url}),e.jsx(qa,{className:"text-xs",children:me(he.name)})]}),e.jsx("span",{className:"text-sm font-medium truncate",children:he.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:he.preview_image_url?e.jsx("img",{src:he.preview_image_url,alt:"",className:"w-full h-full object-cover"}):e.jsx(zc,{className:"h-4 w-4 text-muted-foreground"})}),e.jsx("span",{className:"text-sm font-medium truncate",children:he.name})]})},he.id))})]}),document.body)]})}function YDs(s){const t=/#\[([^\]]+)\]\(([^)]+)\)/g,n=[];let r;for(;(r=t.exec(s))!==null;)n.push(r[2]);return[...new Set(n)]}const xot=s=>s.split(" ").map(t=>t[0]).join("").toUpperCase().slice(0,2);function kEt({comment:s,postId:t,currentUserId:n,currentUserAvatar:r,currentUserEmail:a,canModerate:i,depth:l=0}){const o=as(),[c,d]=N.useState(!1),[u,h]=N.useState(""),[m,f]=N.useState([]),g=_t({mutationFn:async({content:b,parentCommentId:k})=>{const{data:A,error:T}=await H.from("community_comments").insert({post_id:t,user_id:n,content:b,parent_comment_id:k}).select("id").single();if(T)throw T;const P=m;if(P.length>0&&A){const I=P.filter(M=>M!==n).map(M=>({comment_id:A.id,mentioned_user_id:M,mentioned_by_user_id:n}));I.length>0&&await H.from("community_comment_mentions").insert(I)}},onSuccess:()=>{o.invalidateQueries({queryKey:["community-posts"]}),h(""),f([]),d(!1)}}),y=_t({mutationFn:async b=>{const{error:k}=await H.from("community_comments").delete().eq("id",b);if(k)throw k},onSuccess:()=>o.invalidateQueries({queryKey:["community-posts"]})}),x=()=>{u.trim()&&g.mutate({content:u,parentCommentId:s.id})};return e.jsxs("div",{className:l>0?"ml-8 border-l-2 border-muted pl-3":"",children:[e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(Ua,{className:"h-8 w-8 shrink-0",children:[e.jsx(Gi,{src:s.user_avatar||void 0}),e.jsx(qa,{className:"text-xs",children:xot(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(BVe,{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:nc(new Date(s.created_at),{addSuffix:!0})}),e.jsx(KDs,{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(fW,{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(Ua,{className:"h-6 w-6 shrink-0 mt-1",children:[e.jsx(Gi,{src:r||void 0}),e.jsx(qa,{className:"text-xs",children:xot((a==null?void 0:a.split("@")[0])||"U")})]}),e.jsxs("div",{className:"flex-1 flex gap-2 items-start",children:[e.jsx(dke,{placeholder:`Reply to ${s.user_name}...`,value:u,onChange:h,onMentionsChange:f,mentionFormat:"plain",className:"text-sm min-h-0 py-1.5",minHeight:"32px"}),e.jsx(B,{size:"sm",variant:"ghost",onClick:x,disabled:!u.trim()||g.isPending,className:"h-8 px-2 mt-0.5",children:e.jsx(Rr,{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(kEt,{comment:b,postId:t,currentUserId:n,currentUserAvatar:r,currentUserEmail:a,canModerate:i,depth:l+1},b.id))})]})}const Ese=[{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"}],ZDs=()=>{const{user:s,isBrokerageManager:t,managedBrokerages:n,isAdmin:r}=Ls(),{avatarUrl:a}=vSt(s==null?void 0:s.id),{onlineUsers:i}=U_t(),{toast:l}=Ci(),o=as(),c=N.useRef(null),[d,u]=N.useState("all"),[h,m]=N.useState(""),[f,g]=N.useState(""),[y,x]=N.useState(""),[_,b]=N.useState([]),[k,A]=N.useState([]),[T,P]=N.useState(""),[I,M]=N.useState(!1),[L,z]=N.useState(null),[$,V]=N.useState(""),[W,G]=N.useState(new Set),[X,te]=N.useState({}),[ne,me]=N.useState({}),[ue,ce]=N.useState([]),[ae,he]=N.useState([]),[xe,ve]=N.useState({open:!1,images:[],index:0});N.useEffect(()=>{if(d.startsWith("group:")){const Ct=d.replace("group:","");x(Ct),g("")}else d!=="all"?(g(d),x("")):(g(""),x(""))},[d]);const{data:ge=[]}=mt({queryKey:["community-categories"],queryFn:async()=>{const{data:Ct,error:Yt}=await H.from("community_categories").select("*").order("sort_order");if(Yt)throw Yt;return Ct}}),{data:be=[]}=mt({queryKey:["community-private-groups"],queryFn:async()=>{const{data:Ct,error:Yt}=await H.from("community_private_groups").select("id, name, description, icon, brokerage_id, sort_order").order("sort_order");if(Yt)throw Yt;return Ct}}),Se=20,{data:Ie,isLoading:Me,hasNextPage:Re,fetchNextPage:Be,isFetchingNextPage:Ne}=_Qt({queryKey:["community-posts",d],initialPageParam:0,queryFn:async({pageParam:Ct})=>{var it;const Yt=Ct*Se,Kt=Yt+Se;let Xs=H.from("community_posts").select("*").order("is_pinned",{ascending:!1}).order("pinned_at",{ascending:!1,nullsFirst:!1}).order("created_at",{ascending:!1}).range(Yt,Kt);if(d.startsWith("group:")){const ft=d.replace("group:","");Xs=Xs.eq("private_group_id",ft)}else d==="all"||(Xs=Xs.eq("category_id",d).is("private_group_id",null));const{data:zs,error:Vt}=await Xs;if(Vt)throw Vt;const At=((zs==null?void 0:zs.length)||0)>Se,Os=(zs||[]).slice(0,Se);if(Os.length===0)return{posts:[],hasMore:!1,nextPage:Ct+1};const Nt=Os.map(ft=>ft.id),ms=[...new Set(Os.filter(ft=>ft.category_id).map(ft=>ft.category_id))].filter(Boolean),[Ys,It,Ds,As,Hs]=await Promise.all([ms.length?H.from("community_categories").select("*").in("id",ms):Promise.resolve({data:[]}),H.from("community_post_media").select("*").in("post_id",Nt).order("sort_order"),H.from("community_reactions").select("*").in("post_id",Nt),H.from("community_comments").select("*").in("post_id",Nt).order("created_at",{ascending:!0}),H.from("community_post_resources").select("*").in("post_id",Nt)]),Rs=Ys==null?void 0:Ys.data,en=It==null?void 0:It.data,Rn=Ds==null?void 0:Ds.data,Bn=As==null?void 0:As.data,Dn=Hs==null?void 0:Hs.data,Jn=(Bn||[]).map(ft=>ft.id),[ua,Mr]=await Promise.all([Jn.length?H.from("community_comment_reactions").select("*").in("comment_id",Jn):Promise.resolve({data:[]}),(()=>{const ft=(Dn||[]).filter(kt=>kt.resource_type==="template").map(kt=>kt.resource_id);return ft.length===0?Promise.resolve({data:[]}):H.from("canva_templates").select("id, name, preview_image_url").in("id",ft)})()]),sn=(ua==null?void 0:ua.data)||[],ki=(Mr==null?void 0:Mr.data)||[],ia=new Map(ki.map(ft=>[ft.id,{name:ft.name,preview_image_url:ft.preview_image_url}])),vr=Array.from(new Set([...Os.map(ft=>ft.user_id),...(Rn||[]).map(ft=>ft.user_id),...(Bn||[]).map(ft=>ft.user_id),...sn.map(ft=>ft.user_id)])),[Nr,rn]=await Promise.all([vr.length?H.from("profiles").select("id, name").in("id",vr):Promise.resolve({data:[]}),bSt(vr)]),Zn=new Map(((it=Nr==null?void 0:Nr.data)==null?void 0:it.map(ft=>[ft.id,ft.name]))||[]),sa=new Map((Rs||[]).map(ft=>[ft.id,ft])),xs=ft=>{const kt=new Map,Ut=[];return ft.forEach(es=>{kt.set(es.id,{...es,user_name:Zn.get(es.user_id)||"Unknown User",user_avatar:rn.get(es.user_id),reactions:sn.filter(Ms=>Ms.comment_id===es.id).map(Ms=>({...Ms,user_name:Zn.get(Ms.user_id)||"Unknown User",user_avatar:rn.get(Ms.user_id)})),replies:[]})}),ft.forEach(es=>{const Ms=kt.get(es.id);if(es.parent_comment_id&&kt.has(es.parent_comment_id)){const bs=kt.get(es.parent_comment_id);bs.replies=bs.replies||[],bs.replies.push(Ms)}else Ut.push(Ms)}),Ut};return{posts:Os.map(ft=>{const kt=(Dn||[]).filter(Ut=>Ut.post_id===ft.id).map(Ut=>{let es="",Ms=null;if(Ut.resource_type==="template"){const bs=ia.get(Ut.resource_id);es=(bs==null?void 0:bs.name)||"Unknown Template",Ms=(bs==null?void 0:bs.preview_image_url)||null}return{id:Ut.id,resource_type:Ut.resource_type,resource_id:Ut.resource_id,resource_name:es,resource_preview_url:Ms}});return{...ft,user_name:Zn.get(ft.user_id)||"Unknown User",user_avatar:rn.get(ft.user_id),category:ft.category_id?sa.get(ft.category_id):null,media:(en||[]).filter(Ut=>Ut.post_id===ft.id),reactions:((Rn||[]).filter(Ut=>Ut.post_id===ft.id)||[]).map(Ut=>({...Ut,user_name:Zn.get(Ut.user_id)||"Unknown User",user_avatar:rn.get(Ut.user_id)})),comments:xs((Bn||[]).filter(Ut=>Ut.post_id===ft.id)),resources:kt}}),hasMore:At,nextPage:Ct+1}},getNextPageParam:Ct=>Ct.hasMore?Ct.nextPage:void 0}),Ge=N.useMemo(()=>(Ie==null?void 0:Ie.pages.flatMap(Ct=>Ct.posts))??[],[Ie]),Ce=_t({mutationFn:async()=>{M(!0);const{data:Ct,error:Yt}=await H.from("community_posts").insert({user_id:s.id,category_id:y?null:f||null,private_group_id:y||null,content:h,link_url:T||null}).select().single();if(Yt)throw Yt;for(let Xs=0;Xs<_.length;Xs++){const zs=_[Xs],Vt=zs.name.split(".").pop(),At=`${s.id}/${Ct.id}/${Date.now()}-${Xs}.${Vt}`,{error:Os}=await H.storage.from("community-media").upload(At,zs);if(Os)throw Os;const{data:{publicUrl:Nt}}=H.storage.from("community-media").getPublicUrl(At);await H.from("community_post_media").insert({post_id:Ct.id,media_url:Nt,media_type:zs.type.startsWith("video/")?"video":"image",sort_order:Xs})}if(ue.length>0){const Xs=ue.filter(zs=>zs!==s.id).map(zs=>({post_id:Ct.id,mentioned_user_id:zs,mentioned_by_user_id:s.id}));Xs.length>0&&await H.from("community_post_mentions").insert(Xs)}const Kt=YDs(h);if(Kt.length>0){const Xs=Kt.map(zs=>({post_id:Ct.id,resource_type:"template",resource_id:zs}));await H.from("community_post_resources").insert(Xs)}return Ct},onSuccess:async Ct=>{var Yt;o.invalidateQueries({queryKey:["community-posts"]}),m(""),ce([]),he([]),g(""),x(""),b([]),A([]),P(""),l({title:"Post created!"});try{const Kt=((Yt=s==null?void 0:s.user_metadata)==null?void 0:Yt.name)||"Someone",Xs=h.replace(/@\[([^\]]+)\]\([^)]+\)/g,"@$1"),zs=Xs.length>50?Xs.substring(0,50)+"...":Xs;await H.functions.invoke("send-push-notification",{body:{title:"New Community Post",body:`${Kt}: ${zs}`,url:"/community"}})}catch(Kt){console.error("Failed to send push notification:",Kt)}},onError:Ct=>{l({title:"Error creating post",description:Ct.message,variant:"destructive"})},onSettled:()=>M(!1)}),Fe=_t({mutationFn:async({postId:Ct,content:Yt})=>{const{error:Kt}=await H.from("community_posts").update({content:Yt}).eq("id",Ct);if(Kt)throw Kt},onSuccess:()=>{o.invalidateQueries({queryKey:["community-posts"]}),z(null),V(""),l({title:"Post updated!"})}}),Ae=_t({mutationFn:async Ct=>{const{error:Yt}=await H.from("community_posts").delete().eq("id",Ct);if(Yt)throw Yt},onSuccess:()=>{o.invalidateQueries({queryKey:["community-posts"]}),l({title:"Post deleted"})}}),Xe=_t({mutationFn:async({postId:Ct,isPinned:Yt})=>{const{error:Kt}=await H.from("community_posts").update({is_pinned:!Yt,pinned_at:Yt?null:new Date().toISOString(),pinned_by:Yt?null:s==null?void 0:s.id}).eq("id",Ct);if(Kt)throw Kt},onSuccess:(Ct,{isPinned:Yt})=>{o.invalidateQueries({queryKey:["community-posts"]}),l({title:Yt?"Post unpinned":"Post pinned to top"})}}),$e=_t({mutationFn:async({postId:Ct,reactionType:Yt})=>{var Xs;const Kt=(Xs=Ge.find(zs=>zs.id===Ct))==null?void 0:Xs.reactions.find(zs=>zs.user_id===(s==null?void 0:s.id));Kt?Kt.reaction_type===Yt?await H.from("community_reactions").delete().eq("id",Kt.id):await H.from("community_reactions").update({reaction_type:Yt}).eq("id",Kt.id):await H.from("community_reactions").insert({post_id:Ct,user_id:s.id,reaction_type:Yt})},onSuccess:()=>o.invalidateQueries({queryKey:["community-posts"]})}),Ye=_t({mutationFn:async({postId:Ct,content:Yt})=>{const{data:Kt,error:Xs}=await H.from("community_comments").insert({post_id:Ct,user_id:s.id,content:Yt}).select("id").single();if(Xs)throw Xs;const zs=ne[Ct]||[];if(zs.length>0&&Kt){const Vt=zs.filter(At=>At!==s.id).map(At=>({comment_id:Kt.id,mentioned_user_id:At,mentioned_by_user_id:s.id}));Vt.length>0&&await H.from("community_comment_mentions").insert(Vt)}},onSuccess:(Ct,{postId:Yt})=>{o.invalidateQueries({queryKey:["community-posts"]}),te(Kt=>({...Kt,[Yt]:""})),me(Kt=>({...Kt,[Yt]:[]}))}});_t({mutationFn:async Ct=>{const{error:Yt}=await H.from("community_comments").delete().eq("id",Ct);if(Yt)throw Yt},onSuccess:()=>o.invalidateQueries({queryKey:["community-posts"]})});const Je=Ct=>{const Yt=Array.from(Ct.target.files||[]);if(Yt.length+_.length>10){l({title:"Maximum 10 files allowed",variant:"destructive"});return}b(Kt=>[...Kt,...Yt]),Yt.forEach(Kt=>{const Xs=new FileReader;Xs.onloadend=()=>{A(zs=>[...zs,Xs.result])},Xs.readAsDataURL(Kt)})},Ke=Ct=>{b(Yt=>Yt.filter((Kt,Xs)=>Xs!==Ct)),A(Yt=>Yt.filter((Kt,Xs)=>Xs!==Ct))},st=Ct=>Ct.split(" ").map(Yt=>Yt[0]).join("").toUpperCase().slice(0,2),rt=Ct=>{const Yt={};return Ct.forEach(Kt=>{Yt[Kt.reaction_type]=(Yt[Kt.reaction_type]||0)+1}),Yt},Ze=Ct=>{var Yt;return(Yt=Ct.find(Kt=>Kt.user_id===(s==null?void 0:s.id)))==null?void 0:Yt.reaction_type},ht=Ct=>Ct.reduce((Yt,Kt)=>Yt+1+(Kt.replies?ht(Kt.replies):0),0),Bt=Ct=>{if(r)return!0;if(!t||!Ct.private_group_id)return!1;const Yt=be.find(Kt=>Kt.id===Ct.private_group_id);return Yt!=null&&Yt.brokerage_id?n.some(Kt=>Kt.id===Yt.brokerage_id):!1};return e.jsx(Qs,{title:"Community",children:e.jsxs("div",{className:"flex gap-6 w-full isolate z-0",children:[e.jsx(LDs,{categories:ge,privateGroups:be,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(PDs,{categories:ge,privateGroups:be,selectedFilter:d,onFilterChange:u,onlineUsers:i}),e.jsx(_e,{children:e.jsx(De,{className:"pt-6",children:e.jsxs("div",{className:"flex gap-3",children:[e.jsxs(Ua,{className:"h-10 w-10",children:[e.jsx(Gi,{src:a||void 0}),e.jsx(qa,{children:s!=null&&s.email?st(s.email.split("@")[0]):"U"})]}),e.jsxs("div",{className:"flex-1 space-y-3",children:[e.jsx(dke,{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:ce,onTemplatesChange:he,mentionFormat:"encoded",minHeight:"80px",enableTemplateMentions:r}),k.length>0&&e.jsx("div",{className:"grid grid-cols-3 gap-2",children:k.map((Ct,Yt)=>{var Kt;return e.jsxs("div",{className:"relative aspect-square rounded-lg overflow-hidden bg-muted",children:[(Kt=_[Yt])!=null&&Kt.type.startsWith("video/")?e.jsx("video",{src:Ct,className:"w-full h-full object-cover"}):e.jsx("img",{src:Ct,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:()=>Ke(Yt),children:e.jsx(hr,{className:"h-3 w-3"})})]},Yt)})}),T&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(gc,{className:"h-4 w-4 text-muted-foreground"}),e.jsx(we,{value:T,onChange:Ct=>P(Ct.target.value),placeholder:"https://...",className:"flex-1"}),e.jsx(B,{variant:"ghost",size:"icon",onClick:()=>P(""),children:e.jsx(hr,{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:Je,accept:"image/*,video/*",multiple:!0,className:"hidden"}),e.jsxs(B,{variant:"ghost",size:"sm",onClick:()=>{var Ct;return(Ct=c.current)==null?void 0:Ct.click()},children:[e.jsx(pc,{className:"h-4 w-4 mr-1"}),"Photo"]}),e.jsxs(B,{variant:"ghost",size:"sm",onClick:()=>{var Ct;return(Ct=c.current)==null?void 0:Ct.click()},children:[e.jsx(na,{className:"h-4 w-4 mr-1"}),"Video"]}),e.jsxs(B,{variant:"ghost",size:"sm",onClick:()=>P("https://"),children:[e.jsx(gc,{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:[be.length>0?e.jsxs(Ns,{value:y||f||"none",onValueChange:Ct=>{Ct==="none"?(g(""),x("")):Ct.startsWith("group:")?(x(Ct.replace("group:","")),g("")):(g(Ct),x(""))},children:[e.jsx(ws,{className:"w-[130px] sm:w-[160px] h-8 text-xs sm:text-sm",children:e.jsx(ks,{placeholder:"Select..."})}),e.jsxs(js,{children:[e.jsx(nt,{value:"none",children:"No category"}),ge.map(Ct=>e.jsxs(nt,{value:Ct.id,children:[Ct.icon," ",Ct.name]},Ct.id)),be.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"}),be.map(Ct=>e.jsxs(nt,{value:`group:${Ct.id}`,children:[Ct.icon||"🔒"," ",Ct.name]},Ct.id))]})]})]}):e.jsxs(Ns,{value:f,onValueChange:g,children:[e.jsx(ws,{className:"w-[110px] sm:w-[140px] h-8 text-xs sm:text-sm",children:e.jsx(ks,{placeholder:"Category"})}),e.jsx(js,{children:ge.map(Ct=>e.jsxs(nt,{value:Ct.id,children:[Ct.icon," ",Ct.name]},Ct.id))})]}),e.jsxs(B,{size:"sm",onClick:()=>Ce.mutate(),disabled:!h.trim()||I,children:[e.jsx(Rr,{className:"h-4 w-4 mr-1"}),"Post"]})]})]})]})]})})}),Me?e.jsx("div",{className:"space-y-4",children:[...Array(3)].map((Ct,Yt)=>e.jsx(_e,{children:e.jsx(De,{className:"pt-6",children:e.jsxs("div",{className:"flex gap-3",children:[e.jsx(xn,{className:"h-10 w-10 rounded-full"}),e.jsxs("div",{className:"flex-1 space-y-2",children:[e.jsx(xn,{className:"h-4 w-32"}),e.jsx(xn,{className:"h-4 w-full"}),e.jsx(xn,{className:"h-4 w-3/4"})]})]})})},Yt))}):Ge.length===0?e.jsx(_e,{children:e.jsxs(De,{className:"py-12 text-center",children:[e.jsx(Ud,{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:[Ge.map(Ct=>{var Yt,Kt,Xs,zs;return e.jsx(_e,{children:e.jsxs(De,{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(Ua,{className:"h-10 w-10",children:[e.jsx(Gi,{src:Ct.user_avatar||void 0}),e.jsx(qa,{children:st(Ct.user_name||"U")})]}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"font-semibold break-words",children:Ct.user_name}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2 text-sm text-muted-foreground",children:[e.jsx("span",{children:nc(new Date(Ct.created_at),{addSuffix:!0})}),Ct.category&&e.jsxs(e.Fragment,{children:[e.jsx("span",{children:"•"}),e.jsxs(We,{variant:"secondary",className:"text-xs",children:[Ct.category.icon," ",Ct.category.name]})]})]})]})]}),(Ct.user_id===(s==null?void 0:s.id)||Bt(Ct))&&e.jsxs(qd,{children:[e.jsx(Vd,{asChild:!0,children:e.jsx(B,{variant:"ghost",size:"icon",className:"h-8 w-8",children:e.jsx(Iy,{className:"h-4 w-4"})})}),e.jsxs(Ld,{align:"end",children:[Bt(Ct)&&Ct.private_group_id&&e.jsx(ba,{onClick:()=>Xe.mutate({postId:Ct.id,isPinned:Ct.is_pinned}),children:Ct.is_pinned?e.jsxs(e.Fragment,{children:[e.jsx(uW,{className:"h-4 w-4 mr-2"}),"Unpin Post"]}):e.jsxs(e.Fragment,{children:[e.jsx(DT,{className:"h-4 w-4 mr-2"}),"Pin to Top"]})}),Ct.user_id===(s==null?void 0:s.id)&&e.jsxs(ba,{onClick:()=>{z(Ct),V(Ct.content)},children:[e.jsx(Ja,{className:"h-4 w-4 mr-2"}),"Edit"]}),e.jsxs(ba,{className:"text-destructive",onClick:()=>Ae.mutate(Ct.id),children:[e.jsx(qn,{className:"h-4 w-4 mr-2"}),Ct.user_id!==(s==null?void 0:s.id)?"Remove (Moderate)":"Delete"]})]})]})]}),Ct.is_pinned&&e.jsxs("div",{className:"flex items-center gap-2 mb-2 text-sm text-primary",children:[e.jsx(DT,{className:"h-4 w-4"}),e.jsx("span",{className:"font-medium",children:"Pinned"})]}),e.jsx("div",{className:"mb-3",children:e.jsx(BVe,{content:Ct.content})}),Ct.media.length>0&&e.jsx("div",{className:`grid gap-2 mb-3 ${Ct.media.length===1?"grid-cols-1":Ct.media.length===2?"grid-cols-2":Ct.media.length===3?"grid-cols-3":"grid-cols-2"}`,children:Ct.media.slice(0,4).map((Vt,At)=>{const Os=At===3&&Ct.media.length>4,Nt=Ct.media.length-4;return e.jsxs("div",{className:`relative rounded-lg overflow-hidden bg-muted cursor-pointer group ${Ct.media.length===1?"max-h-[500px]":Ct.media.length===2?"aspect-[4/3]":"aspect-square"}`,onClick:()=>ve({open:!0,images:Ct.media.map(ms=>({url:ms.media_url,type:ms.media_type==="video"?"video":"image"})),index:At}),children:[Vt.media_type==="video"?e.jsx("video",{src:Vt.media_url,className:"w-full h-full object-cover transition-transform group-hover:scale-105"}):e.jsx("img",{src:Vt.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"})})})}),Os&&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:["+",Nt]})})]},Vt.id)})}),Ct.link_url&&e.jsxs("a",{href:Ct.link_url,target:"_blank",rel:"noopener noreferrer",className:"block rounded-lg border hover:bg-muted transition-colors mb-3 overflow-hidden",children:[Ct.link_image&&e.jsx("div",{className:"aspect-video bg-muted",children:e.jsx("img",{src:Ct.link_image,alt:Ct.link_title||"Link preview",className:"w-full h-full object-cover",onError:Vt=>{Vt.currentTarget.style.display="none"}})}),e.jsx("div",{className:"p-3",children:Ct.link_title?e.jsxs(e.Fragment,{children:[e.jsx("p",{className:"font-medium text-foreground line-clamp-2",children:Ct.link_title}),Ct.link_description&&e.jsx("p",{className:"text-sm text-muted-foreground line-clamp-2 mt-1",children:Ct.link_description}),e.jsx("p",{className:"text-xs text-muted-foreground mt-2 truncate",children:new URL(Ct.link_url).hostname})]}):e.jsxs("div",{className:"flex items-center gap-2 text-sm text-primary",children:[e.jsx(gc,{className:"h-4 w-4 flex-shrink-0"}),e.jsx("span",{className:"truncate",children:Ct.link_url})]})})]}),Ct.reactions.length>0&&e.jsx(NEt,{reactions:Ct.reactions,children:e.jsxs("div",{className:"flex items-center gap-2 mb-3 text-sm text-muted-foreground hover:text-foreground transition-colors cursor-pointer",children:[e.jsx("div",{className:"flex -space-x-1",children:Object.entries(rt(Ct.reactions)).slice(0,3).map(([Vt])=>{var At;return e.jsx("span",{className:"text-base",children:(At=Ese.find(Os=>Os.type===Vt))==null?void 0:At.emoji},Vt)})}),e.jsx("span",{children:Ct.reactions.length})]})}),e.jsxs("div",{className:"flex items-center gap-1 border-t border-b py-1 my-2",children:[e.jsxs(rc,{children:[e.jsx(ac,{asChild:!0,children:e.jsxs(B,{variant:"ghost",size:"sm",className:"flex-1",children:[Ze(Ct.reactions)?e.jsx("span",{className:"mr-1",children:(Yt=Ese.find(Vt=>Vt.type===Ze(Ct.reactions)))==null?void 0:Yt.emoji}):e.jsx(ax,{className:"h-4 w-4 mr-1"}),Ze(Ct.reactions)?(Kt=Ese.find(Vt=>Vt.type===Ze(Ct.reactions)))==null?void 0:Kt.label:"Like"]})}),e.jsx(Zl,{className:"w-auto p-2",side:"top",children:e.jsx("div",{className:"flex gap-1",children:Ese.map(Vt=>e.jsx("button",{onClick:()=>$e.mutate({postId:Ct.id,reactionType:Vt.type}),className:"text-2xl hover:scale-125 transition-transform p-1",title:Vt.label,children:Vt.emoji},Vt.type))})})]}),e.jsxs(B,{variant:"ghost",size:"sm",className:"flex-1",onClick:()=>G(Vt=>{const At=new Set(Vt);return At.has(Ct.id)?At.delete(Ct.id):At.add(Ct.id),At}),children:[e.jsx(Ud,{className:"h-4 w-4 mr-1"}),(()=>{const Vt=ht(Ct.comments);return Vt>0?`Comment (${Vt})`:"Comment"})()]})]}),W.has(Ct.id)&&e.jsxs("div",{className:"space-y-3 mt-3",children:[Ct.comments.map(Vt=>e.jsx(kEt,{comment:Vt,postId:Ct.id,currentUserId:s==null?void 0:s.id,currentUserAvatar:a,currentUserEmail:s==null?void 0:s.email,canModerate:Bt(Ct)},Vt.id)),s&&e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(Ua,{className:"h-8 w-8",children:[e.jsx(Gi,{src:a||void 0}),e.jsx(qa,{className:"text-xs",children:st(((Xs=s.email)==null?void 0:Xs.split("@")[0])||"U")})]}),e.jsxs("div",{className:"flex-1 flex gap-2",children:[e.jsx(dke,{placeholder:"Write a comment... (use @ to mention)",value:X[Ct.id]||"",onChange:Vt=>te(At=>({...At,[Ct.id]:Vt})),onMentionsChange:Vt=>me(At=>({...At,[Ct.id]:Vt})),mentionFormat:"plain",onKeyDown:Vt=>{var At;Vt.defaultPrevented||Vt.key==="Enter"&&!Vt.shiftKey&&((At=X[Ct.id])!=null&&At.trim())&&(Vt.preventDefault(),Ye.mutate({postId:Ct.id,content:X[Ct.id]}))},className:"text-sm min-h-0 py-1.5",minHeight:"32px"}),e.jsx(B,{size:"sm",variant:"ghost",onClick:()=>{var Vt;(Vt=X[Ct.id])!=null&&Vt.trim()&&Ye.mutate({postId:Ct.id,content:X[Ct.id]})},disabled:!((zs=X[Ct.id])!=null&&zs.trim()),className:"h-8 px-2 mt-0.5",children:e.jsx(Rr,{className:"h-4 w-4"})})]})]})]})]})},Ct.id)}),Re&&e.jsx("div",{className:"flex justify-center pt-2",children:e.jsx(B,{variant:"outline",onClick:()=>Be(),disabled:Ne,children:Ne?"Loading…":"Load more posts"})})]}),e.jsx(Bs,{open:!!L,onOpenChange:()=>z(null),children:e.jsxs(Fs,{children:[e.jsx(qs,{children:e.jsx($s,{children:"Edit Post"})}),e.jsx(Ws,{value:$,onChange:Ct=>V(Ct.target.value),className:"min-h-[120px]"}),e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx(B,{variant:"outline",onClick:()=>z(null),children:"Cancel"}),e.jsx(B,{onClick:()=>{L&&Fe.mutate({postId:L.id,content:$})},disabled:!$.trim(),children:"Save Changes"})]})]})}),e.jsx(WDs,{images:xe.images,initialIndex:xe.index,open:xe.open,onOpenChange:Ct=>ve(Yt=>({...Yt,open:Ct}))})]})]})})},XDs=50*1024*1024;function SEt({value:s,onChange:t,disabled:n}){const{user:r}=Ls(),a=N.useRef(null),[i,l]=N.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/")){ie.error(`${h.name}: only images and videos allowed`);continue}if(h.size>XDs){ie.error(`${h.name}: must be under 50MB`);continue}const m=h.name.split(".").pop()||"bin",f=`${r.id}/${Date.now()}-${Math.random().toString(36).slice(2,8)}.${m}`,{error:g}=await H.storage.from("support-attachments").upload(f,h,{contentType:h.type,upsert:!1});if(g){ie.error(`${h.name}: ${g.message}`);continue}u.push({path:f,type:h.type,name:h.name,size:h.size})}u.length&&t([...s,...u])}finally{l(!1),a.current&&(a.current.value="")}},c=async d=>{const u=s[d];t(s.filter((h,m)=>m!==d)),await H.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(KG,{className:"h-3.5 w-3.5 text-muted-foreground"}):e.jsx(t3,{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(hr,{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(us,{className:"h-3.5 w-3.5 animate-spin"}):e.jsx(LT,{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 CEt({attachments:s}){const[t,n]=N.useState({}),[r,a]=N.useState(!0);return N.useEffect(()=>{if(!(s!=null&&s.length)){a(!1);return}let i=!1;return(async()=>{const l=s.map(d=>d.path),{data:o}=await H.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(us,{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 jF={open:{label:"Open",icon:Xr,color:"bg-yellow-500"},in_progress:{label:"In Progress",icon:Ud,color:"bg-blue-500"},resolved:{label:"Resolved",icon:Po,color:"bg-green-500"},closed:{label:"Closed",icon:Nu,color:"bg-muted-foreground"}},yot={general:"General Support",technology:"Technology Support",crm:"CRM Support",marketing:"Marketing Support"};function QDs(){const{user:s}=Ls(),t=as(),[n,r]=N.useState(null),[a,i]=N.useState(""),[l,o]=N.useState([]),{data:c=[],isLoading:d}=mt({queryKey:["support-tickets"],queryFn:async()=>{const{data:f,error:g}=await H.from("support_tickets").select("*").eq("user_id",s==null?void 0:s.id).order("created_at",{ascending:!1});if(g)throw g;return f},enabled:!!s}),{data:u=[]}=mt({queryKey:["ticket-replies",n==null?void 0:n.id],queryFn:async()=>{if(!n)return[];const{data:f,error:g}=await H.from("support_ticket_replies").select("*, profiles(name)").eq("ticket_id",n.id).order("created_at",{ascending:!0});if(g)throw g;return f},enabled:!!n}),h=_t({mutationFn:async({content:f,attachments:g})=>{if(!n||!s)throw new Error("Missing data");const{error:y}=await H.from("support_ticket_replies").insert({ticket_id:n.id,user_id:s.id,content:f,is_admin_reply:!1,attachments:g});if(y)throw y},onSuccess:()=>{t.invalidateQueries({queryKey:["ticket-replies",n==null?void 0:n.id]}),i(""),o([]),ie.success("Reply sent!")},onError:()=>{ie.error("Failed to send reply")}}),m=()=>{!a.trim()&&l.length===0||h.mutate({content:a,attachments:l})};if(n){const f=jF[n.status].icon;return e.jsx(Qs,{children:e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsx(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(We,{variant:"secondary",children:yot[n.category]}),e.jsxs(We,{className:jF[n.status].color,children:[e.jsx(f,{className:"h-3 w-3 mr-1"}),jF[n.status].label]})]})]})]}),e.jsxs(_e,{children:[e.jsx(zt,{children:e.jsxs(_r,{children:["Created on ",Js(new Date(n.created_at),"MMM d, yyyy 'at' h:mm a")]})}),e.jsx(De,{children:e.jsx("p",{className:"text-muted-foreground whitespace-pre-wrap",children:n.description})})]}),e.jsxs(_e,{children:[e.jsx(zt,{children:e.jsx(qt,{className:"text-lg",children:"Conversation"})}),e.jsxs(De,{children:[e.jsx(lo,{className:"h-[300px] pr-4",children:u.length===0?e.jsx("p",{className:"text-muted-foreground text-center py-8",children:"No replies yet"}):e.jsx("div",{className:"space-y-4",children:u.map(g=>{var y;return e.jsxs("div",{className:`p-4 rounded-lg ${g.is_admin_reply?"bg-primary/10 ml-4":"bg-muted mr-4"}`,children:[e.jsxs("div",{className:"flex justify-between items-start mb-2",children:[e.jsx("span",{className:"font-medium text-sm",children:g.is_admin_reply?"Support Team":((y=g.profiles)==null?void 0:y.name)||"You"}),e.jsx("span",{className:"text-xs text-muted-foreground",children:Js(new Date(g.created_at),"MMM d, h:mm a")})]}),e.jsx("p",{className:"text-sm whitespace-pre-wrap",children:g.content}),g.attachments&&g.attachments.length>0&&e.jsx(CEt,{attachments:g.attachments})]},g.id)})})}),n.status!=="closed"&&e.jsxs(e.Fragment,{children:[e.jsx(Wl,{className:"my-4"}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex gap-2",children:[e.jsx(Ws,{placeholder:"Type your reply...",value:a,onChange:g=>i(g.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(Rr,{className:"h-4 w-4"})})]}),e.jsx(SEt,{value:l,onChange:o,disabled:h.isPending})]})]})]})]})]})})}return e.jsx(Qs,{children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(_e,{className:"bg-gradient-to-br from-primary/10 via-primary/5 to-background border-primary/20",children:e.jsx(De,{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(Uk,{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(_Re,{trigger:e.jsxs(B,{size:"lg",className:"gap-2",children:[e.jsx(nn,{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(ga,{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(_Re,{trigger:e.jsxs(B,{variant:"outline",size:"sm",className:"gap-2",children:[e.jsx(nn,{className:"h-4 w-4"}),"New Ticket"]})})]}),d?e.jsx("div",{className:"text-center py-12 text-muted-foreground",children:"Loading tickets..."}):c.length===0?e.jsx(_e,{className:"border-dashed",children:e.jsxs(De,{className:"text-center py-12",children:[e.jsx(Ud,{className:"h-12 w-12 mx-auto text-muted-foreground mb-4"}),e.jsx("h3",{className:"text-lg font-medium mb-2",children:"No tickets yet"}),e.jsx("p",{className:"text-muted-foreground",children:"You haven't submitted any support tickets. Use the button above to get started!"})]})}):e.jsx("div",{className:"space-y-3",children:c.map(f=>{const g=jF[f.status].icon;return e.jsx(_e,{className:"cursor-pointer hover:bg-muted/50 transition-colors",onClick:()=>r(f),children:e.jsx(De,{className:"p-4",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("h3",{className:"font-medium truncate",children:f.subject}),e.jsxs("div",{className:"flex items-center gap-2 mt-1",children:[e.jsx(We,{variant:"outline",className:"text-xs",children:yot[f.category]}),e.jsx("span",{className:"text-xs text-muted-foreground",children:Js(new Date(f.created_at),"MMM d, yyyy")})]})]}),e.jsxs(We,{className:jF[f.status].color,children:[e.jsx(g,{className:"h-3 w-3 mr-1"}),jF[f.status].label]})]})})},f.id)})})]})})}function JDs({open:s,onOpenChange:t}){return e.jsx(Bs,{open:s,onOpenChange:t,children:e.jsxs(Fs,{className:"max-w-3xl max-h-[90vh] overflow-hidden",children:[e.jsx(qs,{children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"p-2 bg-primary/10 rounded-lg",children:e.jsx(ta,{className:"h-5 w-5 text-primary"})}),e.jsxs("div",{children:[e.jsx($s,{children:"Schedule Agent Onboarding"}),e.jsx(Ar,{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 eRs({open:s,onOpenChange:t}){const{brokerageId:n}=Ls(),[r,a]=N.useState(""),[i,l]=N.useState([]),[o,c]=N.useState(!1),{data:d,isLoading:u}=mt({queryKey:["brokerage-agents-for-onboarding",n],queryFn:async()=>{if(!n)return[];const{data:y,error:x}=await H.from("profiles").select("id, name, email").eq("brokerage_id",n).order("name",{ascending:!0});if(x)throw x;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(x=>x.includes(y)?x.filter(_=>_!==y):[...x,y])},f=async()=>{if(i.length===0){ie.error("Please select at least one agent");return}c(!0);try{const{data:y,error:x}=await H.functions.invoke("send-onboarding-link",{body:{agentIds:i}});if(x)throw x;ie.success(`Onboarding link sent to ${i.length} agent${i.length>1?"s":""}`),l([]),t(!1)}catch(y){console.error("Error sending onboarding link:",y),ie.error(y.message||"Failed to send onboarding link")}finally{c(!1)}},g=y=>{y||(l([]),a("")),t(y)};return e.jsx(Bs,{open:s,onOpenChange:g,children:e.jsxs(Fs,{className:"max-w-md",children:[e.jsx(qs,{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(Rr,{className:"h-5 w-5 text-primary"})}),e.jsxs("div",{children:[e.jsx($s,{children:"Send Onboarding Link"}),e.jsx(Ar,{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(Gr,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(we,{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(us,{className:"h-6 w-6 animate-spin text-muted-foreground"})}):(h==null?void 0:h.length)===0?e.jsxs("div",{className:"text-center py-8 text-muted-foreground",children:[e.jsx(Yn,{className:"h-8 w-8 mx-auto mb-2 opacity-50"}),e.jsx("p",{children:"No agents found"})]}):e.jsx(lo,{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(Bi,{checked:i.includes(y.id),onCheckedChange:()=>m(y.id)}),e.jsx(Ua,{className:"h-8 w-8",children:e.jsx(qa,{className:"text-xs",children:y.name.split(" ").map(x=>x[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(Cr,{children:[e.jsx(B,{variant:"outline",onClick:()=>g(!1),children:"Cancel"}),e.jsx(B,{onClick:f,disabled:i.length===0||o,children:o?e.jsxs(e.Fragment,{children:[e.jsx(us,{className:"h-4 w-4 mr-2 animate-spin"}),"Sending..."]}):e.jsxs(e.Fragment,{children:[e.jsx(Rr,{className:"h-4 w-4 mr-2"}),"Send Link"]})})]})]})})}function tRs(){const[s,t]=N.useState(!1),[n,r]=N.useState(!1);return e.jsxs(e.Fragment,{children:[e.jsxs(_e,{className:"mb-8",children:[e.jsx(zt,{children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"p-2 bg-primary/10 rounded-lg",children:e.jsx(Yn,{className:"h-6 w-6 text-primary"})}),e.jsxs("div",{children:[e.jsx(qt,{children:"Agent Onboarding"}),e.jsx(_r,{children:"Schedule onboarding sessions for yourself or your agents"})]})]})}),e.jsx(De,{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(ta,{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(Rr,{className:"h-4 w-4"}),"Send New Agent Onboarding Link"]})]})})]}),e.jsx(JDs,{open:s,onOpenChange:t}),e.jsx(eRs,{open:n,onOpenChange:r})]})}function sRs({open:s,onOpenChange:t}){return e.jsx(Bs,{open:s,onOpenChange:t,children:e.jsxs(Fs,{className:"max-w-3xl max-h-[90vh] overflow-hidden",children:[e.jsx(qs,{children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"p-2 bg-primary/10 rounded-lg",children:e.jsx(By,{className:"h-5 w-5 text-primary"})}),e.jsxs("div",{children:[e.jsx($s,{children:"Schedule Launch Meeting"}),e.jsx(Ar,{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 nRs(){const[s,t]=N.useState(!1);return e.jsxs(e.Fragment,{children:[e.jsxs(_e,{className:"mb-8",children:[e.jsx(zt,{children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"p-2 bg-primary/10 rounded-lg",children:e.jsx(By,{className:"h-6 w-6 text-primary"})}),e.jsxs("div",{children:[e.jsx(qt,{children:"Launch or ReLaunch Meeting"}),e.jsx(_r,{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(De,{children:e.jsxs(B,{onClick:()=>t(!0),className:"flex items-center gap-2",children:[e.jsx(By,{className:"h-4 w-4"}),"Schedule Launch Meeting"]})})]}),e.jsx(sRs,{open:s,onOpenChange:t})]})}function rRs(){const s=tr(),[t,n]=N.useState(""),[r,a]=N.useState(null),{data:i,isLoading:l}=mt({queryKey:["brokerage-resources-published"],queryFn:async()=>{const{data:y,error:x}=await H.from("brokerage_resources").select("*").eq("is_published",!0).order("publish_date",{ascending:!1});if(x)throw x;return y}}),{data:o}=mt({queryKey:["brokerage-resource-categories"],queryFn:async()=>{const{data:y,error:x}=await H.from("brokerage_resource_categories").select("*").order("sort_order",{ascending:!0});if(x)throw x;return y}}),{data:c}=mt({queryKey:["brokerage-resource-pdfs-all"],queryFn:async()=>{const{data:y,error:x}=await H.from("brokerage_resource_pdfs").select("resource_id");if(x)throw x;return y}}),{data:d}=mt({queryKey:["brokerage-resource-videos-all"],queryFn:async()=>{const{data:y,error:x}=await H.from("brokerage_resource_videos").select("resource_id");if(x)throw x;return y}}),{data:u}=mt({queryKey:["brokerage-resource-links-all"],queryFn:async()=>{const{data:y,error:x}=await H.from("brokerage_resource_links").select("resource_id");if(x)throw x;return y}}),h=i==null?void 0:i.filter(y=>{var b;const x=y.title.toLowerCase().includes(t.toLowerCase())||((b=y.description)==null?void 0:b.toLowerCase().includes(t.toLowerCase())),_=!r||y.category_id===r;return x&&_}),m=o==null?void 0:o.filter(y=>i==null?void 0:i.some(x=>x.category_id===y.id)),f=y=>{const x=(c==null?void 0:c.filter(k=>k.resource_id===y).length)||0,_=(d==null?void 0:d.filter(k=>k.resource_id===y).length)||0,b=(u==null?void 0:u.filter(k=>k.resource_id===y).length)||0;return{pdfCount:x,videoCount:_,linkCount:b}},g=y=>{s(`/brokerage-resources/${y}`)};return e.jsx(Qs,{title:"Brokerage Resources",description:"Access exclusive resources for brokerage managers",children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(tRs,{}),e.jsx(nRs,{}),e.jsxs("div",{className:"relative max-w-md",children:[e.jsx(Gr,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(we,{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(We,{variant:r===null?"default":"outline",className:"cursor-pointer",onClick:()=>a(null),children:"All"}),m.map(y=>e.jsx(We,{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,x)=>e.jsxs(_e,{children:[e.jsx(xn,{className:"h-40 w-full"}),e.jsx(zt,{children:e.jsx(xn,{className:"h-5 w-3/4"})}),e.jsxs(De,{children:[e.jsx(xn,{className:"h-4 w-full mb-2"}),e.jsx(xn,{className:"h-4 w-2/3"})]})]},x))}):(h==null?void 0:h.length)===0?e.jsxs(_e,{className:"p-12 text-center",children:[e.jsx(vg,{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:x,videoCount:_,linkCount:b}=f(y.id),k=o==null?void 0:o.find(A=>A.id===y.category_id);return e.jsxs(_e,{className:"overflow-hidden cursor-pointer hover:shadow-lg transition-shadow",onClick:()=>g(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(vg,{className:"h-16 w-16 text-muted-foreground"})}),e.jsx(zt,{className:"pb-2",children:e.jsxs("div",{className:"flex items-start justify-between gap-2",children:[e.jsx(qt,{className:"text-lg line-clamp-1",children:y.title}),k&&e.jsx(We,{variant:"secondary",className:"shrink-0 text-xs",children:k.name})]})}),e.jsxs(De,{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:[x>0&&e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Wr,{className:"h-4 w-4"}),x]}),_>0&&e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(na,{className:"h-4 w-4"}),_]}),b>0&&e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(gc,{className:"h-4 w-4"}),b]})]})]})]},y.id)})})]})})}const aRs=()=>{const{resourceId:s}=uo(),{data:t,isLoading:n}=mt({queryKey:["brokerage-resource-detail",s],queryFn:async()=>{const{data:a,error:i}=await H.from("brokerage_resources").select("*").eq("id",s).eq("is_published",!0).single();if(i)throw i;const{data:l}=await H.from("brokerage_resource_pdfs").select("*").eq("resource_id",s).order("sort_order"),{data:o}=await H.from("brokerage_resource_videos").select("*").eq("resource_id",s).order("sort_order"),{data:c}=await H.from("brokerage_resource_links").select("*").eq("resource_id",s).order("sort_order");return{...a,pdfs:l||[],videos:o||[],links:c||[]}},enabled:!!s}),r=a=>a?a<1024?a+" B":a<1024*1024?(a/1024).toFixed(1)+" KB":(a/(1024*1024)).toFixed(1)+" MB":"";return n?e.jsx(Qs,{title:"Brokerage Resources",children:e.jsx("div",{className:"flex justify-center py-12",children:e.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})})}):t?e.jsx(Qs,{title:t.title,children:e.jsxs("div",{className:"space-y-6 max-w-5xl mx-auto",children:[e.jsx(B,{variant:"ghost",size:"sm",asChild:!0,className:"gap-2",children:e.jsxs(cr,{to:"/brokerage-resources",children:[e.jsx(ka,{className:"h-4 w-4"}),"Back to Resources"]})}),t.preview_image_url&&e.jsx("div",{className:"relative w-full rounded-lg overflow-hidden bg-muted",children:e.jsx("img",{src:t.preview_image_url,alt:t.title,className:"w-full max-h-[400px] object-cover"})}),e.jsxs("div",{className:"space-y-4",children:[e.jsx("h1",{className:"text-2xl font-bold text-foreground",children:t.title}),t.description&&e.jsx("div",{className:"text-muted-foreground prose prose-sm max-w-none dark:prose-invert",dangerouslySetInnerHTML:{__html:t.description}})]}),t.videos&&t.videos.length>0&&e.jsx(_e,{children:e.jsxs(De,{className:"pt-6",children:[e.jsxs("h3",{className:"font-semibold flex items-center gap-2 mb-4",children:[e.jsx(na,{className:"h-4 w-4"}),"Videos (",t.videos.length,")"]}),e.jsx("div",{className:"space-y-4",children:t.videos.map(a=>e.jsxs("div",{className:"space-y-2",children:[e.jsx("h4",{className:"font-medium",children:a.title}),e.jsx("div",{className:"relative w-full",style:{paddingTop:"56.25%"},children:e.jsx("iframe",{src:a.video_url,className:"absolute top-0 left-0 w-full h-full rounded-lg border",allow:"accelerometer; gyroscope; autoplay; encrypted-media; picture-in-picture",allowFullScreen:!0})})]},a.id))})]})}),t.pdfs&&t.pdfs.length>0&&e.jsx(_e,{children:e.jsxs(De,{className:"pt-6",children:[e.jsxs("h3",{className:"font-semibold flex items-center gap-2 mb-4",children:[e.jsx(Wr,{className:"h-4 w-4"}),"Documents (",t.pdfs.length,")"]}),e.jsx("div",{className:"grid gap-2",children:t.pdfs.map(a=>e.jsxs("a",{href:a.file_url,target:"_blank",rel:"noopener noreferrer",className:"flex items-center justify-between p-3 rounded-lg border hover:bg-muted transition-colors group",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"p-2 rounded-md bg-primary/10",children:e.jsx(Wr,{className:"h-4 w-4 text-primary"})}),e.jsxs("div",{children:[e.jsx("div",{className:"font-medium text-sm",children:a.name}),a.file_size&&e.jsx("div",{className:"text-xs text-muted-foreground",children:r(a.file_size)})]})]}),e.jsx(oi,{className:"h-4 w-4 text-muted-foreground group-hover:text-primary transition-colors"})]},a.id))})]})}),t.links&&t.links.length>0&&e.jsx(_e,{children:e.jsxs(De,{className:"pt-6",children:[e.jsxs("h3",{className:"font-semibold flex items-center gap-2 mb-4",children:[e.jsx(Tr,{className:"h-4 w-4"}),"Canva Templates (",t.links.length,")"]}),e.jsx("div",{className:"grid gap-2",children:t.links.map(a=>e.jsxs("a",{href:a.canva_share_link,target:"_blank",rel:"noopener noreferrer",className:"flex items-center justify-between p-3 rounded-lg border hover:bg-muted transition-colors group",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"p-2 rounded-md bg-primary/10",children:e.jsx(Tr,{className:"h-4 w-4 text-primary"})}),e.jsx("div",{className:"font-medium text-sm",children:a.title})]}),e.jsx(Tr,{className:"h-4 w-4 text-muted-foreground group-hover:text-primary transition-colors"})]},a.id))})]})})]})}):e.jsx(Qs,{title:"Brokerage Resources",children:e.jsxs("div",{className:"flex flex-col items-center justify-center py-12 text-center",children:[e.jsx(vg,{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(cr,{to:"/brokerage-resources",children:"Back to Resources"})})]})})};function iRs(){const{onlineUsers:s,totalOnline:t}=U_t();return e.jsxs(_e,{children:[e.jsx(zt,{className:"pb-3",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs(qt,{className:"text-base flex items-center gap-2",children:[e.jsx(Yn,{className:"h-4 w-4"}),"Online Now"]}),e.jsxs(We,{variant:"secondary",className:"bg-green-100 text-green-700",children:[e.jsx(bg,{className:"h-2 w-2 fill-green-500 text-green-500 mr-1"}),t," online"]})]})}),e.jsx(De,{children:s.length===0?e.jsx("p",{className:"text-sm text-muted-foreground text-center py-4",children:"No other users online right now"}):e.jsx(lo,{className:"h-[300px] pr-4",children:e.jsx("div",{className:"space-y-3",children:s.map(n=>{var r;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(Ua,{className:"h-9 w-9",children:[e.jsx(Gi,{src:n.avatarUrl,alt:n.name}),e.jsx(qa,{className:"text-xs",children:(r=n.name)==null?void 0:r.split(" ").map(a=>a[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.jsx("p",{className:"text-sm font-medium truncate",children:n.name}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Online ",nc(new Date(n.onlineSince),{addSuffix:!1})]})]})]},n.id)})})})})]})}const vot={users:{label:"Users & Access",sections:[{title:"Members",description:"Manage users, roles, and brokerage assignments",icon:Yn,path:"/admin/members",color:"bg-blue-500/10 text-blue-600"},{title:"Invite Codes",description:"Create and manage signup invite codes",icon:CW,path:"/admin/invite-codes",color:"bg-amber-500/10 text-amber-600"},{title:"Subscriptions",description:"Track and manage user subscriptions",icon:U0,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:VG,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:pf,path:"/admin/discounts",color:"bg-red-500/10 text-red-600"},{title:"Referral Program",description:"Track brokerage referrals and discounts",icon:Md,path:"/admin/referrals",color:"bg-teal-500/10 text-teal-600"},{title:"Teams",description:"Manage agent teams across all brokerages",icon:Yn,path:"/admin/members?tab=teams",color:"bg-violet-500/10 text-violet-600"},{title:"Prospector",description:"Send free trial invites and track conversions",icon:iu,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:Yl,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:gl,path:"/admin/coaching",color:"bg-gradient-to-br from-teal-500/20 to-cyan-500/10 text-teal-600"}]},content:{label:"Content",sections:[{title:"Manage Templates",description:"Upload and organize Canva templates",icon:zc,path:"/admin/templates",color:"bg-pink-500/10 text-pink-600"},{title:"Manage Programs",description:"Cohorts, enrollments and delayed billing",icon:Oh,path:"/admin/programs",color:"bg-emerald-500/10 text-emerald-600"},{title:"Manage Academy",description:"Upload videos and training content",icon:Oh,path:"/admin/academy",color:"bg-indigo-500/10 text-indigo-600"},{title:"Manage Toolbox",description:"Create and manage resource kits",icon:sN,path:"/admin/toolbox",color:"bg-orange-500/10 text-orange-600"},{title:"Social Swag",description:"Manage social media content and links",icon:Cn,path:"/admin/social-swag",color:"bg-fuchsia-500/10 text-fuchsia-600"},{title:"Social Swag 2.0",description:"New monthly social media images",icon:Cn,path:"/admin/social-swag-2",color:"bg-cyan-500/10 text-cyan-600"},{title:"Newsletters",description:"Manage monthly newsletter templates",icon:E_,path:"/admin/newsletters",color:"bg-violet-500/10 text-violet-600"},{title:"Newsletter Graphics",description:"Upload branded graphics agents drop into newsletters & emails",icon:E_,path:"/admin/newsletter-graphics",color:"bg-fuchsia-500/10 text-fuchsia-600"},{title:"Manage Events",description:"Create and publish events with Zoom integration",icon:ld,path:"/admin/events",color:"bg-green-500/10 text-green-600"},{title:"LevelUp Live",description:"Public streaming pages, invite links, and live leads",icon:Y0,path:"/admin/live",color:"bg-red-500/10 text-red-600"},{title:"Additional Services",description:"Manage additional service offerings",icon:vg,path:"/admin/additional-services",color:"bg-lime-500/10 text-lime-600"},{title:"Brokerage Resources",description:"Manage resources for brokerage managers",icon:vg,path:"/admin/brokerage-resources",color:"bg-slate-500/10 text-slate-600"},{title:"Agent Email Templates",description:"Manage curated email templates for agents",icon:mn,path:"/admin/agent-email-templates",color:"bg-rose-500/10 text-rose-600"},{title:"Mass Email Templates",description:"Create and manage shared campaign templates",icon:um,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:ET,path:"/admin/dashboard-management",color:"bg-teal-500/10 text-teal-600"},{title:"Manage Apps",description:"Configure app tiles and access requirements",icon:Iw,path:"/admin/apps",color:"bg-purple-500/10 text-purple-600"},{title:"Email Templates",description:"Customize system email templates",icon:mn,path:"/admin/email-templates",color:"bg-sky-500/10 text-sky-600"},{title:"The LevelUp Brief",description:"Create popup briefs with videos, links, and polls",icon:um,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:e3,path:"/admin/onboarding-checklist",color:"bg-emerald-500/10 text-emerald-600"},{title:"Marketplace",description:"Manage store categories, products, and orders",icon:g5,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:Io,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:gl,path:"/admin/agent-points",color:"bg-amber-500/10 text-amber-600"},{title:"Integrations",description:"Connect Canva, Facebook & Instagram for platform-level features",icon:cd,path:"/admin/integrations",color:"bg-blue-500/10 text-blue-600"},{title:"Agent Cards",description:"Manage digital business cards for agents",icon:Yn,path:"/admin/agent-cards",color:"bg-gradient-to-br from-violet-500/20 to-purple-500/10 text-violet-600"},{title:"Notification Settings",description:"Test and manage push notifications",icon:um,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:xo,path:"/admin/community",color:"bg-cyan-500/10 text-cyan-600"},{title:"Support Tickets",description:"View and respond to agent support requests",icon:p9,path:"/admin/support-tickets",color:"bg-rose-500/10 text-rose-600"},{title:"Wishlist",description:"Review and manage community feature requests",icon:Z2,path:"/admin/wishlist",color:"bg-yellow-500/10 text-yellow-600"},{title:"Membership Reviews",description:"View member feedback and ratings",icon:Wa,path:"/admin/membership-reviews",color:"bg-amber-500/10 text-amber-600"},{title:"Weekly Digest",description:"Configure automated weekly email digests",icon:mn,path:"/admin/weekly-digest",color:"bg-indigo-500/10 text-indigo-600"}]},insights:{label:"Insights",sections:[{title:"Analytics",description:"View activity logs and platform statistics",icon:fl,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:Ep,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:ab,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:Oh,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:co,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:_a,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:Yl,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:Yl,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:ab,path:"/admin/presentation-analytics",color:"bg-gradient-to-br from-violet-500/20 to-indigo-500/10 text-violet-600"},{title:"Listing Presentation Studio",description:"Track every listing presentation agents build, generate, and send",icon:Wr,path:"/admin/listing-presentation-studio",color:"bg-gradient-to-br from-slate-500/20 to-zinc-500/10 text-slate-600"},{title:"Weekly Reels",description:"Manage Weekly Reels access, generation runs, and email delivery",icon:Rh,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:Ep,path:"/admin/guest-book-analytics",color:"bg-gradient-to-br from-emerald-500/20 to-teal-500/10 text-emerald-600"}]},beta:{label:"🧪 Beta Lab",sections:[{title:"Social Post Generator",description:"Auto-generate branded social media posts from MLS listing data",icon:pc,path:"/admin/beta/social-post-generator",color:"bg-gradient-to-br from-fuchsia-500/20 to-pink-500/10 text-fuchsia-600"},{title:"Postcard Direct Mail",description:"Upload monthly postcard designs and manage agent direct mail via Postalytics",icon:mn,path:"/admin/beta/postcard-manager",color:"bg-gradient-to-br from-orange-500/20 to-amber-500/10 text-orange-600"},{title:"ReelFlow",description:"Turn property photos into cinematic video reels for social media",icon:ST,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:au,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:HG,path:"/admin/mls-feeds",color:"bg-gradient-to-br from-emerald-500/20 to-green-500/10 text-emerald-600"},{title:"Lead Analytics",description:"Cross-site lead capture stats, conversions, and top-performing sites",icon:ml,path:"/admin/lead-site-analytics",color:"bg-gradient-to-br from-amber-500/20 to-orange-500/10 text-amber-600"},{title:"Website Interests",description:"Track interest form submissions from TheLocalMove.com",icon:Wr,path:"/admin/website-interests",color:"bg-gradient-to-br from-rose-500/20 to-pink-500/10 text-rose-600"},{title:"Website Order Tracker",description:"Full setup requests with all build details from /get-started",icon:Wr,path:"/admin/website-orders",color:"bg-gradient-to-br from-emerald-500/20 to-teal-500/10 text-emerald-600"},{title:"MLS Fee Tracker",description:"Track MLS providers, setup fees, and monthly costs",icon:Ed,path:"/admin/mls-fee-tracker",color:"bg-gradient-to-br from-teal-500/20 to-cyan-500/10 text-teal-600"}]}};function bot(){const s=tr();return console.log("[AdminDashboard] render"),e.jsx(Qs,{title:"Admin Dashboard",children:e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex flex-col lg:flex-row gap-6",children:[e.jsxs("div",{className:"flex-1",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.jsx("div",{className:"w-full lg:w-80",children:e.jsx(iRs,{})})]}),e.jsxs(ya,{defaultValue:"users",className:"w-full",children:[e.jsx(va,{className:"w-full justify-start flex-wrap h-auto gap-1 bg-muted/50 p-1 overflow-x-auto",children:Object.entries(vot).map(([t,n])=>e.jsx(ls,{value:t,className:"data-[state=active]:bg-background",children:n.label},t))}),Object.entries(vot).map(([t,n])=>e.jsx(_s,{value:t,className:"mt-6",children:e.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-4",children:n.sections.map(r=>e.jsxs(_e,{className:"cursor-pointer hover:shadow-md transition-all hover:border-primary/50 group",onClick:()=>s(r.path),children:[e.jsxs(zt,{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(qt,{className:"text-base",children:r.title})]}),e.jsx(De,{className:"pt-0",children:e.jsx(_r,{className:"text-sm",children:r.description})})]},r.path))})},t))]})]})})}const oRs=()=>{const{isAdmin:s}=Ls(),t=tr(),[n,r]=N.useState([]),[a,i]=N.useState(!0),[l,o]=N.useState(!1),[c,d]=N.useState(null);N.useEffect(()=>{if(!s){t("/dashboard");return}u()},[s]);const u=async()=>{try{const{data:y,error:x}=await H.from("app_tiles").select("*").order("name");if(x)throw x;r(y||[])}catch(y){console.error("Error loading apps:",y),ie.error("Failed to load apps")}finally{i(!1)}},h=async y=>{y.preventDefault();const x=new FormData(y.currentTarget),_={name:x.get("name"),description:x.get("description"),icon:x.get("icon"),app_id:x.get("app_id"),target_url:x.get("target_url"),required_tags:x.get("required_tags").split(",").map(b=>b.trim()).filter(Boolean)};try{if(c){const{error:b}=await H.from("app_tiles").update(_).eq("id",c.id);if(b)throw b;ie.success("App updated successfully")}else{const{error:b}=await H.from("app_tiles").insert([_]);if(b)throw b;ie.success("App created successfully")}o(!1),d(null),u()}catch(b){console.error("Error saving app:",b),ie.error("Failed to save app")}},m=async y=>{if(confirm("Are you sure you want to delete this app?"))try{const{error:x}=await H.from("app_tiles").delete().eq("id",y);if(x)throw x;ie.success("App deleted successfully"),u()}catch(x){console.error("Error deleting app:",x),ie.error("Failed to delete app")}},f=y=>{d(y),o(!0)},g=()=>{d(null),o(!0)};return a?e.jsx("div",{className:"flex items-center justify-center min-h-screen",children:"Loading..."}):e.jsxs("div",{className:"min-h-screen bg-background",children:[e.jsx("header",{className:"border-b bg-card",children:e.jsx("div",{className:"container mx-auto px-4 py-4",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsxs(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(Bs,{open:l,onOpenChange:o,children:[e.jsx(Ao,{asChild:!0,children:e.jsxs(B,{onClick:g,children:[e.jsx(nn,{className:"mr-2 h-4 w-4"}),"Add App"]})}),e.jsxs(Fs,{className:"max-w-2xl",children:[e.jsxs(qs,{children:[e.jsx($s,{children:c?"Edit App":"Create New App"}),e.jsx(Ar,{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(re,{htmlFor:"name",children:"App Name"}),e.jsx(we,{id:"name",name:"name",defaultValue:c==null?void 0:c.name,required:!0})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{htmlFor:"app_id",children:"App ID"}),e.jsx(we,{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(re,{htmlFor:"description",children:"Description"}),e.jsx(Ws,{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(re,{htmlFor:"icon",children:"Icon (emoji)"}),e.jsx(we,{id:"icon",name:"icon",defaultValue:c==null?void 0:c.icon,placeholder:"🚀",required:!0})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{htmlFor:"target_url",children:"Target URL"}),e.jsx(we,{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(re,{htmlFor:"required_tags",children:"Required Tags (comma-separated)"}),e.jsx(we,{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(_e,{children:[e.jsxs(zt,{children:[e.jsx(qt,{children:"Application Tiles"}),e.jsx(_r,{children:"Manage the apps that appear on the member dashboard"})]}),e.jsx(De,{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:g,children:[e.jsx(nn,{className:"mr-2 h-4 w-4"}),"Create First App"]})]}):e.jsxs(Oa,{children:[e.jsx(Fa,{children:e.jsxs(un,{children:[e.jsx(Mt,{children:"Icon"}),e.jsx(Mt,{children:"Name"}),e.jsx(Mt,{children:"App ID"}),e.jsx(Mt,{children:"Target URL"}),e.jsx(Mt,{children:"Tags"}),e.jsx(Mt,{className:"text-right",children:"Actions"})]})}),e.jsx(za,{children:n.map(y=>e.jsxs(un,{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(x=>e.jsx("span",{className:"text-xs bg-secondary text-secondary-foreground px-2 py-1 rounded",children:x},x))})}),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:()=>f(y),children:e.jsx(Ja,{className:"h-4 w-4"})}),e.jsx(B,{size:"sm",variant:"ghost",onClick:()=>m(y.id),children:e.jsx(qn,{className:"h-4 w-4"})})]})})]},y.id))})]})})]})})]})};function Uh({title:s,description:t,children:n}){return e.jsxs("div",{className:"space-y-4",children:[e.jsx(cr,{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 _ot=({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(We,{variant:"destructive",className:Ot("gap-1",t),children:[e.jsx(xd,{className:"h-3 w-3"}),"Trial Expired"]}):a<=1?e.jsxs(We,{variant:"destructive",className:Ot("gap-1",t),children:[e.jsx(Xr,{className:"h-3 w-3"}),"Trial: <1 day left"]}):a<=3?e.jsxs(We,{className:Ot("gap-1 bg-amber-500 hover:bg-amber-600",t),children:[e.jsx(Xr,{className:"h-3 w-3"}),"Trial: ",a," days left"]}):e.jsxs(We,{variant:"secondary",className:Ot("gap-1",t),children:[e.jsx(Xr,{className:"h-3 w-3"}),"Trial: ",a," days left"]})},AEt=({open:s,onOpenChange:t,brokerages:n,fixedBrokerageId:r,onSuccess:a})=>{const{toast:i}=Ci(),l=N.useRef(null),[o,c]=N.useState([]),[d,u]=N.useState(""),[h,m]=N.useState(!1),[f,g]=N.useState("upload"),[y,x]=N.useState(null),_=()=>{c([]),u(""),g("upload"),x(null),l.current&&(l.current.value="")},b=()=>{_(),t(!1)},k=M=>{const L=M.split(` `).map(G=>G.trim()).filter(G=>G);if(L.length===0)return[];const z=L[0].toLowerCase(),V=z.includes("first")||z.includes("last")||z.includes("email")||z.includes("name")||z.includes("phone")||z.includes("sms")||z.includes("consent")?L.slice(1):L,W=[];for(const G of V){const te=(G.includes(" ")?G.split(" "):G.split(",")).map(ne=>ne.trim().replace(/^["']|["']$/g,""));if(te.length>=2){let ne="",me="",ue="",ce="",ae;if(te.length===2){const ve=te[0].split(" ");ne=ve[0]||"",me=ve.slice(1).join(" ")||"",ue=te[1]}else if(te.length===3)ne=te[0],me=te[1],ue=te[2];else if(te.length===4)ne=te[0],me=te[1],ue=te[2],ce=te[3];else if(te.length>=5){ne=te[0],me=te[1],ue=te[2],ce=te[3];const ve=te[4].toLowerCase();ae=ve==="true"||ve==="yes"||ve==="1"||ve==="y"}const xe=/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(ue);W.push({firstName:ne.trim(),lastName:me.trim(),email:ue.trim().toLowerCase(),phone:ce.trim()||void 0,smsConsent:ae,isValid:xe&&ne.trim().length>0,error:xe?ne.trim()?void 0:"Missing name":"Invalid email"})}}return W},A=M=>{var $;const L=($=M.target.files)==null?void 0:$[0];if(!L)return;const z=new FileReader;z.onload=V=>{var X;const W=(X=V.target)==null?void 0:X.result,G=k(W);if(G.length===0){i({title:"No data found",description:"The CSV file appears to be empty or in an unsupported format.",variant:"destructive"});return}c(G),g("preview")},z.readAsText(L)},T=async()=>{const M=o.filter(z=>z.isValid);if(M.length===0){i({title:"No valid users",description:"There are no valid users to import.",variant:"destructive"});return}const L=r||d||null;m(!0);try{const{data:{session:z}}=await H.auth.getSession(),$=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/bulk-create-users",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${z==null?void 0:z.access_token}`},body:JSON.stringify({users:M.map(W=>({firstName:W.firstName,lastName:W.lastName,email:W.email,phone:W.phone,smsConsent:W.smsConsent})),brokerageId:L})}),V=await $.json();if(!$.ok)throw new Error(V.error||"Failed to import users");x(V),g("result"),V.created>0&&a(),i({title:"Import Complete",description:`${V.created} user(s) created successfully.${V.failed>0?` ${V.failed} failed.`:""}`})}catch(z){console.error("Import error:",z),i({title:"Import Failed",description:z.message||"Failed to import users",variant:"destructive"})}finally{m(!1)}},P=o.filter(M=>M.isValid).length,I=o.filter(M=>!M.isValid).length;return e.jsx(Bs,{open:s,onOpenChange:b,children:e.jsxs(Fs,{className:"max-w-2xl max-h-[85vh] overflow-hidden flex flex-col",children:[e.jsxs(qs,{children:[e.jsxs($s,{className:"flex items-center gap-2",children:[e.jsx(m5,{className:"h-5 w-5"}),"Import Agents from CSV"]}),e.jsx(Ar,{children:"Upload a CSV file with agent information. Each row should contain First Name, Last Name, and Email."})]}),f==="upload"&&e.jsxs("div",{className:"space-y-4 py-4",children:[e.jsxs("div",{className:"border-2 border-dashed rounded-lg p-8 text-center",children:[e.jsx("input",{type:"file",accept:".csv,.txt",ref:l,onChange:A,className:"hidden"}),e.jsx(ni,{className:"h-10 w-10 mx-auto text-muted-foreground mb-4"}),e.jsx("p",{className:"text-sm text-muted-foreground mb-4",children:"Click to upload or drag and drop a CSV file"}),e.jsx(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."})]})]}),f==="preview"&&e.jsxs("div",{className:"flex-1 overflow-hidden flex flex-col space-y-4",children:[!r&&n&&n.length>0&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{children:"Assign to Brokerage (optional)"}),e.jsxs(Ns,{value:d||"none",onValueChange:M=>u(M==="none"?"":M),children:[e.jsx(ws,{children:e.jsx(ks,{placeholder:"Select a brokerage..."})}),e.jsxs(js,{children:[e.jsx(nt,{value:"none",children:"No brokerage"}),n.map(M=>e.jsx(nt,{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(Hr,{className:"h-4 w-4 text-green-500"}),e.jsxs("span",{children:[P," valid"]})]}),I>0&&e.jsxs("div",{className:"flex items-center gap-2 text-destructive",children:[e.jsx(Uo,{className:"h-4 w-4"}),e.jsxs("span",{children:[I," invalid"]})]})]}),e.jsxs("div",{className:"flex-1 overflow-auto border rounded-lg",children:[e.jsxs(Oa,{children:[e.jsx(Fa,{children:e.jsxs(un,{className:"bg-muted/30",children:[e.jsx(Mt,{children:"First Name"}),e.jsx(Mt,{children:"Last Name"}),e.jsx(Mt,{children:"Email"}),e.jsx(Mt,{children:"Phone"}),e.jsx(Mt,{children:"SMS"}),e.jsx(Mt,{children:"Status"})]})}),e.jsx(za,{children:o.slice(0,100).map((M,L)=>e.jsxs(un,{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(We,{variant:"default",className:"bg-green-500/10 text-green-600",children:"Valid"}):e.jsx(We,{variant:"destructive",children:M.error||"Invalid"})})]},L))})]}),o.length>100&&e.jsxs("p",{className:"text-sm text-muted-foreground text-center py-2",children:["Showing first 100 of ",o.length," users"]})]})]}),f==="result"&&y&&e.jsxs("div",{className:"space-y-4 py-4",children:[e.jsxs("div",{className:"text-center",children:[e.jsx(Hr,{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,L)=>e.jsxs("li",{children:["• ",M]},L)),y.errors.length>10&&e.jsxs("li",{children:["...and ",y.errors.length-10," more"]})]})]})]}),e.jsxs(Cr,{children:[f==="upload"&&e.jsx(B,{variant:"outline",onClick:b,children:"Cancel"}),f==="preview"&&e.jsxs(e.Fragment,{children:[e.jsx(B,{variant:"outline",onClick:_,children:"Back"}),e.jsx(B,{onClick:T,disabled:h||P===0,children:h?e.jsxs(e.Fragment,{children:[e.jsx(us,{className:"mr-2 h-4 w-4 animate-spin"}),"Importing..."]}):`Import ${P} Agent${P!==1?"s":""}`})]}),f==="result"&&e.jsx(B,{onClick:b,children:"Done"})]})]})})};function Hu({sortKey:s,currentSortKey:t,currentDirection:n,onSort:r,children:a,className:i,...l}){const o=t===s;return e.jsx(Mt,{className:Ot("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(Om,{className:"h-3.5 w-3.5 shrink-0"}):e.jsx(Wf,{className:"h-3.5 w-3.5 shrink-0"}):e.jsx(mg,{className:"h-3.5 w-3.5 shrink-0 opacity-40"})]})})}function JQ(s=null,t=null){const[n,r]=N.useState(s),[a,i]=N.useState(t),l=N.useCallback(c=>{n===c?a==="asc"?i("desc"):a==="desc"?(r(null),i(null)):i("asc"):(r(c),i("asc"))},[n,a]),o=N.useCallback((c,d)=>{if(!n||!a||!d[n])return c;const u=d[n];return[...c].sort((h,m)=>{const f=u(h),g=u(m);if(f==null&&g==null)return 0;if(f==null)return 1;if(g==null)return-1;let y;return typeof f=="string"&&typeof g=="string"?y=f.localeCompare(g,void 0,{sensitivity:"base"}):y=f-g,a==="asc"?y:-y})},[n,a]);return{sortKey:n,sortDirection:a,handleSort:l,sortData:o}}const lRs=[{type:"custom",title:"Great job!",message:"Keep up the amazing work!",icon:Wa},{type:"custom",title:"You're on fire!",message:"Your dedication is inspiring!",icon:gl},{type:"custom",title:"Congratulations!",message:"You earned this celebration!",icon:uf}];function TEt({open:s,onOpenChange:t,userId:n,userName:r}){const[a,i]=N.useState("custom"),[l,o]=N.useState(""),[c,d]=N.useState(""),u=tas(),h=f=>{i(f.type),o(f.title),d(f.message)},m=async f=>{if(f.preventDefault(),!l.trim()){xa({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}),xa({title:"Celebration sent! 🎉",description:`${r} will see confetti on their next visit!`}),t(!1),o(""),d(""),i("custom")}catch{xa({title:"Error",description:"Failed to send celebration",variant:"destructive"})}};return e.jsx(Bs,{open:s,onOpenChange:t,children:e.jsxs(Fs,{className:"sm:max-w-md",children:[e.jsxs(qs,{children:[e.jsxs($s,{className:"flex items-center gap-2",children:[e.jsx(uf,{className:"h-5 w-5 text-primary"}),"Send Celebration to ",r]}),e.jsx(Ar,{children:"They'll see confetti and this message next time they log in!"})]}),e.jsxs("div",{className:"mb-4",children:[e.jsx(re,{className:"text-sm text-muted-foreground mb-2 block",children:"Quick presets:"}),e.jsx("div",{className:"flex gap-2 flex-wrap",children:lRs.map((f,g)=>e.jsxs(B,{variant:"outline",size:"sm",onClick:()=>h(f),className:"text-xs",children:[e.jsx(f.icon,{className:"h-3 w-3 mr-1"}),f.title]},g))})]}),e.jsxs("form",{onSubmit:m,className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(re,{htmlFor:"type",children:"Celebration Type"}),e.jsxs(Ns,{value:a,onValueChange:f=>i(f),children:[e.jsx(ws,{children:e.jsx(ks,{})}),e.jsxs(js,{children:[e.jsx(nt,{value:"custom",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Wa,{className:"h-4 w-4"})," Custom"]})}),e.jsx(nt,{value:"points_earned",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(gl,{className:"h-4 w-4"})," Points Earned"]})}),e.jsx(nt,{value:"listing_created",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(_a,{className:"h-4 w-4"})," Listing Created"]})}),e.jsx(nt,{value:"deal_closed",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ed,{className:"h-4 w-4"})," Deal Closed"]})})]})]})]}),e.jsxs("div",{children:[e.jsx(re,{htmlFor:"title",children:"Title *"}),e.jsx(we,{id:"title",value:l,onChange:f=>o(f.target.value),placeholder:"e.g., Congratulations!",maxLength:100})]}),e.jsxs("div",{children:[e.jsx(re,{htmlFor:"message",children:"Message (optional)"}),e.jsx(Ws,{id:"message",value:c,onChange:f=>d(f.target.value),placeholder:"Add a personal message...",rows:3,maxLength:500})]}),e.jsxs("div",{className:"flex gap-2 justify-end",children:[e.jsx(B,{type:"button",variant:"outline",onClick:()=>t(!1),children:"Cancel"}),e.jsxs(B,{type:"submit",disabled:u.isPending,children:[e.jsx(uf,{className:"h-4 w-4 mr-2"}),u.isPending?"Sending...":"Send Celebration"]})]})]})]})})}const oLe={points_earned:{label:"Points Earned",icon:gl,color:"bg-yellow-500"},listing_created:{label:"Listing Created",icon:_a,color:"bg-blue-500"},deal_closed:{label:"Deal Closed",icon:Ed,color:"bg-green-500"},custom:{label:"Custom",icon:Cn,color:"bg-purple-500"}};function cRs(){const[s,t]=N.useState(""),[n,r]=N.useState("all"),[a,i]=N.useState("all"),{data:l=[],isLoading:o}=mt({queryKey:["admin-celebrations"],queryFn:async()=>{const{data:u,error:h}=await H.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:f}=await H.from("profiles").select("id, name, email").in("id",m),g=new Map((f==null?void 0:f.map(y=>[y.id,y]))||[]);return u.map(y=>{var x,_,b;return{...y,user_name:((x=g.get(y.user_id))==null?void 0:x.name)||"Unknown",user_email:((_=g.get(y.user_id))==null?void 0:_.email)||"",creator_name:y.created_by?((b=g.get(y.created_by))==null?void 0:b.name)||"System":"Auto-triggered"}})}}),c=l.filter(u=>{var g,y;const h=((g=u.user_name)==null?void 0:g.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,f=a==="all"||a==="seen"&&u.seen_at||a==="unseen"&&!u.seen_at;return h&&m&&f}),d={total:l.length,seen:l.filter(u=>u.seen_at).length,unseen:l.filter(u=>!u.seen_at).length,byType:Object.keys(oLe).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(us,{className:"h-8 w-8 animate-spin text-muted-foreground"})}):e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"grid gap-4 md:grid-cols-4",children:[e.jsxs(_e,{children:[e.jsx(zt,{className:"pb-2",children:e.jsx(qt,{className:"text-sm font-medium",children:"Total Celebrations"})}),e.jsx(De,{children:e.jsx("div",{className:"text-2xl font-bold",children:d.total})})]}),e.jsxs(_e,{children:[e.jsx(zt,{className:"pb-2",children:e.jsx(qt,{className:"text-sm font-medium text-green-600",children:"Seen"})}),e.jsx(De,{children:e.jsx("div",{className:"text-2xl font-bold text-green-600",children:d.seen})})]}),e.jsxs(_e,{children:[e.jsx(zt,{className:"pb-2",children:e.jsx(qt,{className:"text-sm font-medium text-orange-600",children:"Pending"})}),e.jsx(De,{children:e.jsx("div",{className:"text-2xl font-bold text-orange-600",children:d.unseen})})]}),e.jsxs(_e,{children:[e.jsx(zt,{className:"pb-2",children:e.jsx(qt,{className:"text-sm font-medium text-purple-600",children:"Custom Sent"})}),e.jsx(De,{children:e.jsx("div",{className:"text-2xl font-bold text-purple-600",children:d.byType.custom||0})})]})]}),e.jsxs(_e,{children:[e.jsxs(zt,{children:[e.jsxs(qt,{className:"flex items-center gap-2",children:[e.jsx(uf,{className:"h-5 w-5"}),"Celebration History"]}),e.jsx(_r,{children:"View all celebrations awarded to agents"})]}),e.jsxs(De,{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(Gr,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(we,{placeholder:"Search by agent name, email, or title...",value:s,onChange:u=>t(u.target.value),className:"pl-9"})]}),e.jsxs(Ns,{value:n,onValueChange:r,children:[e.jsx(ws,{className:"w-[180px]",children:e.jsx(ks,{placeholder:"Filter by type"})}),e.jsxs(js,{children:[e.jsx(nt,{value:"all",children:"All Types"}),Object.entries(oLe).map(([u,h])=>e.jsx(nt,{value:u,children:h.label},u))]})]}),e.jsxs(Ns,{value:a,onValueChange:i,children:[e.jsx(ws,{className:"w-[140px]",children:e.jsx(ks,{placeholder:"Status"})}),e.jsxs(js,{children:[e.jsx(nt,{value:"all",children:"All Status"}),e.jsx(nt,{value:"seen",children:"Seen"}),e.jsx(nt,{value:"unseen",children:"Pending"})]})]})]}),e.jsx("div",{className:"rounded-md border",children:e.jsxs(Oa,{children:[e.jsx(Fa,{children:e.jsxs(un,{children:[e.jsx(Mt,{children:"Type"}),e.jsx(Mt,{children:"Agent"}),e.jsx(Mt,{children:"Title"}),e.jsx(Mt,{children:"Points"}),e.jsx(Mt,{children:"Created By"}),e.jsx(Mt,{children:"Created"}),e.jsx(Mt,{children:"Status"})]})}),e.jsx(za,{children:c.length===0?e.jsx(un,{children:e.jsx(gt,{colSpan:7,className:"text-center py-8 text-muted-foreground",children:"No celebrations found"})}):c.map(u=>{const h=oLe[u.celebration_type],m=h.icon;return e.jsxs(un,{children:[e.jsx(gt,{children:e.jsxs(We,{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(We,{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:Js(new Date(u.created_at),"MMM d, yyyy h:mm a")})}),e.jsx(gt,{children:u.seen_at?e.jsx(We,{variant:"outline",className:"bg-green-50 text-green-700 border-green-200",children:"Seen"}):e.jsx(We,{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 dRs=()=>{const{user:s}=Ls(),{toast:t}=Ci(),[n,r]=N.useState([]),[a,i]=N.useState(!0),[l,o]=N.useState(!1),[c,d]=N.useState("all"),[u,h]=N.useState("all"),[m,f]=N.useState("new"),[g,y]=N.useState(new Set),x=N.useCallback(async()=>{try{i(!0);const{data:W,error:G}=await H.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(G)throw G;const{data:X,error:te}=await H.from("trial_email_exports").select("user_id");if(te)throw te;const ne=new Set((X||[]).map(ue=>ue.user_id)),me=(W||[]).map(ue=>({...ue,converted_from_trial_at:ue.converted_from_trial_at??null,already_exported:ne.has(ue.id)}));me.sort((ue,ce)=>new Date(ce.created_at).getTime()-new Date(ue.created_at).getTime()),r(me)}catch(W){console.error("Error loading trial users:",W),t({title:"Error",description:"Failed to load trial users",variant:"destructive"})}finally{i(!1)}},[t]);N.useEffect(()=>{x()},[x]);const _=W=>W.trial_started_at?"ghl":"stripe",b=W=>W.trial_expires_at?W.trial_expires_at:W.subscription_end_date?W.subscription_end_date:null,k=W=>W.converted_from_trial_at!==null,A=W=>{if(k(W))return!1;const G=b(W);return G?new Date(G).getTime()<=Date.now():!1},T=n.filter(W=>!(c!=="all"&&_(W)!==c||u==="active"&&(A(W)||k(W))||u==="expired"&&!A(W)||u==="converted"&&!k(W)||m==="new"&&W.already_exported||m==="exported"&&!W.already_exported)),P=()=>{g.size===T.length?y(new Set):y(new Set(T.map(W=>W.id)))},I=W=>{const G=new Set(g);G.has(W)?G.delete(W):G.add(W),y(G)},M=async()=>{if(g.size===0){t({title:"No users selected",description:"Select users to export",variant:"destructive"});return}o(!0);try{const W=n.filter(ae=>g.has(ae.id)),G="First Name,Last Name,Email,Phone,Trial Type,Status,Signup Date,Expiry Date",X=W.map(ae=>{const he=(ae.name||"").split(" "),xe=he[0]||"",ve=he.slice(1).join(" ")||"",ge=_(ae)==="stripe"?"Credit Card Trial":"Free Trial (No CC)",be=k(ae)?"Converted":A(ae)?"Expired":"Active",Se=ae.created_at?new Date(ae.created_at).toLocaleDateString():"",Ie=b(ae)?new Date(b(ae)).toLocaleDateString():"";return`"${xe}","${ve}","${ae.email}","${ae.phone||""}","${ge}","${be}","${Se}","${Ie}"`}),te=[G,...X].join(` `),ne=new Blob([te],{type:"text/csv"}),me=URL.createObjectURL(ne),ue=document.createElement("a");ue.href=me,ue.download=`trial-users-${new Date().toISOString().split("T")[0]}.csv`,ue.click(),URL.revokeObjectURL(me);const ce=W.filter(ae=>!ae.already_exported).map(ae=>({user_id:ae.id,exported_by:s.id}));if(ce.length>0){const{error:ae}=await H.from("trial_email_exports").upsert(ce,{onConflict:"user_id"});ae&&console.error("Error marking exports:",ae)}t({title:"Export complete",description:`Downloaded ${W.length} trial user(s). ${ce.length} newly marked as exported.`}),y(new Set),x()}catch(W){console.error("Export error:",W),t({title:"Error",description:"Failed to export",variant:"destructive"})}finally{o(!1)}},L=n.filter(W=>!W.already_exported).length,z=n.filter(W=>W.already_exported).length,$=n.filter(W=>k(W)).length,V=n.filter(W=>!A(W)&&!k(W)).length;return a?e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsx(us,{className:"h-6 w-6 animate-spin text-muted-foreground"})}):e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"grid grid-cols-2 sm:grid-cols-5 gap-4",children:[e.jsx(_e,{children:e.jsxs(zt,{className:"pb-2",children:[e.jsx(_r,{children:"Total"}),e.jsx(qt,{className:"text-2xl",children:n.length})]})}),e.jsx(_e,{children:e.jsxs(zt,{className:"pb-2",children:[e.jsx(_r,{children:"New (Not Exported)"}),e.jsx(qt,{className:"text-2xl text-green-600",children:L})]})}),e.jsx(_e,{children:e.jsxs(zt,{className:"pb-2",children:[e.jsx(_r,{children:"Active Trials"}),e.jsx(qt,{className:"text-2xl",children:V})]})}),e.jsx(_e,{children:e.jsxs(zt,{className:"pb-2",children:[e.jsx(_r,{children:"Converted 🎉"}),e.jsx(qt,{className:"text-2xl text-primary",children:$})]})}),e.jsx(_e,{children:e.jsxs(zt,{className:"pb-2",children:[e.jsx(_r,{children:"Already Exported"}),e.jsx(qt,{className:"text-2xl text-muted-foreground",children:z})]})})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-3",children:[e.jsxs(Ns,{value:m,onValueChange:W=>f(W),children:[e.jsx(ws,{className:"w-[160px]",children:e.jsx(ks,{})}),e.jsxs(js,{children:[e.jsx(nt,{value:"all",children:"All Users"}),e.jsx(nt,{value:"new",children:"New Only"}),e.jsx(nt,{value:"exported",children:"Already Exported"})]})]}),e.jsxs(Ns,{value:c,onValueChange:W=>d(W),children:[e.jsx(ws,{className:"w-[180px]",children:e.jsx(ks,{})}),e.jsxs(js,{children:[e.jsx(nt,{value:"all",children:"All Trial Types"}),e.jsx(nt,{value:"stripe",children:"Credit Card Trial"}),e.jsx(nt,{value:"ghl",children:"Free Trial (No CC)"})]})]}),e.jsxs(Ns,{value:u,onValueChange:W=>h(W),children:[e.jsx(ws,{className:"w-[160px]",children:e.jsx(ks,{})}),e.jsxs(js,{children:[e.jsx(nt,{value:"all",children:"All Statuses"}),e.jsx(nt,{value:"active",children:"Active Trial"}),e.jsx(nt,{value:"expired",children:"Expired"}),e.jsx(nt,{value:"converted",children:"Converted ✓"})]})]}),e.jsx("div",{className:"ml-auto",children:e.jsxs(B,{onClick:M,disabled:l||g.size===0,children:[l?e.jsx(us,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(oi,{className:"h-4 w-4 mr-2"}),"Export Selected (",g.size,")"]})})]}),e.jsx("div",{className:"border rounded-lg",children:e.jsxs(Oa,{children:[e.jsx(Fa,{children:e.jsxs(un,{className:"bg-muted/30 hover:bg-muted/30",children:[e.jsx(Mt,{className:"w-[40px]",children:e.jsx(Bi,{checked:T.length>0&&g.size===T.length,onCheckedChange:P})}),e.jsx(Mt,{children:"Name"}),e.jsx(Mt,{children:"Email"}),e.jsx(Mt,{children:"Trial Type"}),e.jsx(Mt,{children:"Status"}),e.jsx(Mt,{children:"Signup Date"}),e.jsx(Mt,{children:"Last Login"}),e.jsx(Mt,{children:"Expires / Renews"}),e.jsx(Mt,{children:"Exported"})]})}),e.jsx(za,{children:T.length===0?e.jsx(un,{children:e.jsx(gt,{colSpan:9,className:"text-center py-8 text-muted-foreground",children:"No trial users match the current filters"})}):T.map(W=>{const G=_(W),X=k(W),te=A(W),ne=b(W);return e.jsxs(un,{className:`hover:bg-muted/30 ${X?"bg-primary/5":""}`,children:[e.jsx(gt,{children:e.jsx(Bi,{checked:g.has(W.id),onCheckedChange:()=>I(W.id)})}),e.jsx(gt,{className:"font-medium",children:e.jsxs("div",{className:"flex items-center gap-2",children:[W.name,X&&e.jsx(ml,{className:"h-3.5 w-3.5 text-primary"})]})}),e.jsx(gt,{className:"text-muted-foreground",children:W.email}),e.jsx(gt,{children:G==="stripe"?e.jsxs(We,{variant:"outline",className:"gap-1",children:[e.jsx(U0,{className:"h-3 w-3"}),"Credit Card"]}):e.jsxs(We,{variant:"secondary",className:"gap-1",children:[e.jsx(mn,{className:"h-3 w-3"}),"Free (No CC)"]})}),e.jsx(gt,{children:X?e.jsxs(We,{className:"bg-primary/10 text-primary hover:bg-primary/20 gap-1",children:[e.jsx(ml,{className:"h-3 w-3"}),"Converted"]}):te?e.jsx(We,{variant:"destructive",children:"Expired"}):e.jsx(We,{className:"bg-green-500/10 text-green-600 hover:bg-green-500/20",children:"Active Trial"})}),e.jsx(gt,{className:"text-sm",children:W.created_at?new Date(W.created_at).toLocaleDateString():"—"}),e.jsx(gt,{className:"text-sm",children:W.last_login?e.jsxs("div",{className:"flex flex-col",children:[e.jsx("span",{children:new Date(W.last_login).toLocaleDateString()}),e.jsx("span",{className:"text-xs text-muted-foreground",children:new Date(W.last_login).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})})]}):e.jsx("span",{className:"text-muted-foreground",children:"Never"})}),e.jsx(gt,{className:"text-sm",children:X&&ne?e.jsxs("span",{className:"text-muted-foreground",children:["Renews ",new Date(ne).toLocaleDateString()]}):ne?new Date(ne).toLocaleDateString():"—"}),e.jsx(gt,{children:W.already_exported?e.jsx(Hr,{className:"h-4 w-4 text-muted-foreground"}):e.jsx(We,{variant:"outline",className:"text-green-600 border-green-300",children:"New"})})]},W.id)})})]})}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:["Showing ",T.length," of ",n.length," trial users · ",$," converted to paid"]})]})},uRs=s=>s==null?'""':`"${String(s).replace(/"/g,'""')}"`,hRs=()=>{const[s,t]=N.useState([]),[n,r]=N.useState(!0);N.useEffect(()=>{(async()=>{const{data:l,error:o}=await H.from("user_deletion_log").select("*").order("created_at",{ascending:!1});!o&&l&&t(l),r(!1)})()},[]);const a=()=>{if(s.length===0){ie.info("No deletion records to export");return}const i=["Date","Deleted User","Deleted Email","Brokerage","Type","Deleted By"],l=s.map(h=>[Js(new Date(h.created_at),"MMM d, yyyy h:mm a"),h.deleted_user_name||"—",h.deleted_user_email||"—",h.brokerage_name||"—",h.deletion_type==="deleted"?"Account Deleted":"Removed",h.deleted_by_name||h.deleted_by_email||"—"]),o=[i.join(","),...l.map(h=>h.map(uRs).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),ie.success(`Exported ${s.length} deletion record(s)`)};return n?e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsx(us,{className:"h-6 w-6 animate-spin text-muted-foreground"})}):s.length===0?e.jsx(_e,{children:e.jsxs(De,{className:"py-12 text-center text-muted-foreground",children:[e.jsx(qn,{className:"h-10 w-10 mx-auto mb-3 opacity-40"}),e.jsx("p",{children:"No deletion records yet"})]})}):e.jsxs(_e,{children:[e.jsxs(zt,{className:"flex flex-row items-center justify-between",children:[e.jsx(qt,{className:"text-lg",children:"User Deletion History"}),e.jsxs(B,{variant:"outline",size:"sm",onClick:a,children:[e.jsx(oi,{className:"h-4 w-4 mr-2"}),"Export CSV"]})]}),e.jsx(De,{children:e.jsxs(Oa,{children:[e.jsx(Fa,{children:e.jsxs(un,{children:[e.jsx(Mt,{children:"Date"}),e.jsx(Mt,{children:"User"}),e.jsx(Mt,{children:"Email"}),e.jsx(Mt,{children:"Brokerage"}),e.jsx(Mt,{children:"Type"}),e.jsx(Mt,{children:"Deleted By"})]})}),e.jsx(za,{children:s.map(i=>e.jsxs(un,{children:[e.jsx(gt,{className:"whitespace-nowrap text-sm",children:Js(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(We,{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))})]})})]})},ZR=s=>{const{user:t}=Ls(),n=as(),r=mt({queryKey:["teams",s],queryFn:async()=>{let h=H.from("teams").select("*").order("created_at",{ascending:!1});s&&(h=h.eq("brokerage_id",s));const{data:m,error:f}=await h;if(f)throw f;return m||[]},enabled:!!t}),a=h=>mt({queryKey:["team-members",h],queryFn:async()=>{const{data:m,error:f}=await H.from("team_members").select("*").eq("team_id",h).order("role",{ascending:!0});if(f)throw f;const g=(m||[]).map(_=>_.user_id),{data:y}=await H.from("profiles").select("id, name, email, avatar_url").in("id",g),x=new Map((y||[]).map(_=>[_.id,_]));return(m||[]).map(_=>({..._,profile:x.get(_.user_id)||null}))},enabled:!!h}),i=_t({mutationFn:async h=>{const m={name:h.name,created_by:t.id,description:h.description,contact_visibility:h.contact_visibility,lead_pond_enabled:h.lead_pond_enabled,shared_assets_enabled:h.shared_assets_enabled};h.brokerage_id&&(m.brokerage_id=h.brokerage_id);const{data:f,error:g}=await H.from("teams").insert(m).select().single();if(g)throw g;return f},onSuccess:()=>{n.invalidateQueries({queryKey:["teams"]}),ie.success("Team created!")},onError:h=>{ie.error("Failed to create team: "+h.message)}}),l=_t({mutationFn:async({id:h,...m})=>{const{data:f,error:g}=await H.from("teams").update(m).eq("id",h).select().single();if(g)throw g;return f},onSuccess:()=>{n.invalidateQueries({queryKey:["teams"]}),ie.success("Team updated")},onError:h=>{ie.error("Failed to update team: "+h.message)}}),o=_t({mutationFn:async h=>{const{error:m}=await H.from("teams").delete().eq("id",h);if(m)throw m},onSuccess:()=>{n.invalidateQueries({queryKey:["teams"]}),ie.success("Team deleted")},onError:h=>{ie.error("Failed to delete team: "+h.message)}}),c=_t({mutationFn:async h=>{const{data:m,error:f}=await H.from("team_members").insert({team_id:h.team_id,user_id:h.user_id,role:h.role||"team_member"}).select().single();if(f)throw f.message.includes("duplicate")||f.message.includes("unique")?new Error("This agent is already on a team. They must be removed from their current team first."):f;return m},onSuccess:(h,m)=>{n.invalidateQueries({queryKey:["team-members",m.team_id]}),ie.success("Member added to team")},onError:h=>{ie.error(h.message)}}),d=_t({mutationFn:async h=>{const{error:m}=await H.from("team_members").delete().eq("id",h.member_id);if(m)throw m},onSuccess:(h,m)=>{n.invalidateQueries({queryKey:["team-members",m.team_id]}),ie.success("Member removed from team")},onError:h=>{ie.error("Failed to remove member: "+h.message)}}),u=_t({mutationFn:async h=>{const{error:m}=await H.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]}),ie.success("Member role updated")},onError:h=>{ie.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}},mRs=()=>{const{user:s}=Ls();return mt({queryKey:["team-contacts",s==null?void 0:s.id],queryFn:async()=>{const{data:t,error:n}=await H.rpc("get_team_contacts",{_user_id:s.id});if(n)throw n;return t||[]},enabled:!!s})},EEt=s=>{const{user:t}=Ls(),n=as(),r=mt({queryKey:["lead-pond",s],queryFn:async()=>{const{data:o,error:c}=await H.from("team_lead_pond").select("*").eq("team_id",s).order("created_at",{ascending:!1});if(c)throw c;if(!o||o.length===0)return[];const d=o.map(_=>_.contact_id),u=[...new Set(o.map(_=>_.added_by))],h=o.filter(_=>_.claimed_by).map(_=>_.claimed_by),m=[...new Set([...u,...h])],[f,g]=await Promise.all([H.from("innercircle_contacts").select("id, first_name, last_name, email, phone").in("id",d),H.from("profiles").select("id, name, avatar_url").in("id",m)]),y=new Map((f.data||[]).map(_=>[_.id,_])),x=new Map((g.data||[]).map(_=>[_.id,_]));return o.map(_=>({..._,status:_.claimed_by?"claimed":"available",contact:y.get(_.contact_id)||null,contributor:x.get(_.added_by)||null,claimer:_.claimed_by&&x.get(_.claimed_by)||null}))},enabled:!!s&&!!t}),a=_t({mutationFn:async o=>{const{data:c,error:d}=await H.rpc("add_to_lead_pond",{_contact_id:o.contact_id,_team_id:o.team_id,_notes:o.notes||null});if(d)throw d;return c},onSuccess:()=>{n.invalidateQueries({queryKey:["lead-pond"]}),ie.success("Contact added to Lead Pond")},onError:o=>{ie.error(o.message)}}),i=_t({mutationFn:async o=>{const{error:c}=await H.rpc("claim_lead_pond_contact",{_lead_pond_id:o});if(c)throw c},onSuccess:()=>{n.invalidateQueries({queryKey:["lead-pond"]}),ie.success("Lead claimed!")},onError:o=>{ie.error(o.message)}}),l=_t({mutationFn:async o=>{const{error:c}=await H.rpc("return_lead_pond_contact",{_lead_pond_id:o});if(c)throw c},onSuccess:()=>{n.invalidateQueries({queryKey:["lead-pond"]}),ie.success("Lead returned to pond")},onError:o=>{ie.error(o.message)}});return{leadPondItems:r.data||[],isLoading:r.isLoading,addToLeadPond:a,claimLead:i,returnLead:l}},pRs=()=>{const s=as();return _t({mutationFn:async t=>{const{data:n,error:r}=await H.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"]}),ie.success("Contact transferred successfully")},onError:t=>{ie.error(t.message||"Failed to transfer contact")}})};function MEt({open:s,onOpenChange:t,contactIds:n,contactNames:r=[],onComplete:a}){var T;const{user:i}=Ls(),{data:l}=Cj(),{useTeamMembers:o}=ZR(),{data:c=[]}=o((l==null?void 0:l.teamId)||""),d=pRs(),[u,h]=N.useState(null),[m,f]=N.useState(""),[g,y]=N.useState(!1),x=c.filter(P=>P.user_id!==(i==null?void 0:i.id)),_=async()=>{if(u){y(!0);try{for(const P of n)await d.mutateAsync({contactId:P,toUserId:u,notes:m||void 0});t(!1),h(null),f(""),a==null||a()}catch{}finally{y(!1)}}},b=x.find(P=>P.user_id===u),k=n.length>1,A=r.length>0?k?`${r.length} contacts`:r[0]:k?`${n.length} contacts`:"this contact";return e.jsx(Bs,{open:s,onOpenChange:t,children:e.jsxs(Fs,{className:"sm:max-w-md",children:[e.jsxs(qs,{children:[e.jsxs($s,{className:"flex items-center gap-2",children:[e.jsx(c5,{className:"h-5 w-5"}),"Transfer ",A]}),e.jsxs(Ar,{children:["Select a team member to transfer ",k?"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(re,{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:x.length===0?e.jsx("p",{className:"text-sm text-muted-foreground py-4 text-center",children:"No other team members available"}):x.map(P=>{var I,M,L;return e.jsxs("button",{onClick:()=>h(P.user_id),className:`w-full flex items-center gap-3 p-3 rounded-lg text-left transition-colors ${u===P.user_id?"bg-primary/10 border border-primary/30":"hover:bg-accent border border-transparent"}`,children:[e.jsxs(Ua,{className:"h-8 w-8",children:[e.jsx(Gi,{src:((I=P.profile)==null?void 0:I.avatar_url)||""}),e.jsx(qa,{className:"text-xs",children:(((M=P.profile)==null?void 0:M.name)||"?").charAt(0).toUpperCase()})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium",children:((L=P.profile)==null?void 0:L.name)||"Unknown"}),e.jsx("p",{className:"text-xs text-muted-foreground capitalize",children:P.role.replace("_"," ")})]})]},P.user_id)})})]}),e.jsxs("div",{children:[e.jsx(re,{htmlFor:"transfer-notes",className:"text-sm font-medium",children:"Notes (optional)"}),e.jsx(Ws,{id:"transfer-notes",value:m,onChange:P=>f(P.target.value),placeholder:"Reason for transfer...",className:"mt-1",rows:2})]})]}),e.jsxs(Cr,{children:[e.jsx(B,{variant:"outline",onClick:()=>t(!1),children:"Cancel"}),e.jsxs(B,{onClick:_,disabled:!u||g,children:[g?e.jsx(us,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(c5,{className:"h-4 w-4 mr-2"}),"Transfer",b?` to ${(T=b.profile)==null?void 0:T.name}`:""]})]})]})})}const $Ve=()=>{const s=tr(),{data:t,isLoading:n}=mRs(),{data:r}=Cj(),[a,i]=N.useState(""),[l,o]=N.useState("all"),[c,d]=N.useState(null),[u,h]=N.useState(""),m=(r==null?void 0:r.role)==="team_leader",f=N.useMemo(()=>{if(!t)return[];const y=new Map;return t.forEach(x=>{y.has(x.owner_user_id)||y.set(x.owner_user_id,{id:x.owner_user_id,name:x.owner_name||"Unknown",avatar:x.owner_avatar_url})}),Array.from(y.values())},[t]),g=N.useMemo(()=>{if(!t)return[];let y=t;if(l!=="all"&&(y=y.filter(x=>x.owner_user_id===l)),a.trim()){const x=a.toLowerCase();y=y.filter(_=>{var b,k,A;return(_.first_name+" "+(_.last_name||"")).toLowerCase().includes(x)||((b=_.email)==null?void 0:b.toLowerCase().includes(x))||((k=_.phone)==null?void 0:k.includes(x))||((A=_.owner_name)==null?void 0:A.toLowerCase().includes(x))})}return y},[t,a,l]);return n?e.jsxs("div",{className:"space-y-4",children:[e.jsx(xn,{className:"h-10 w-full"}),e.jsx(xn,{className:"h-64 w-full"})]}):!t||t.length===0?e.jsx(_e,{children:e.jsxs(De,{className:"flex flex-col items-center justify-center py-12 text-center",children:[e.jsx(Yn,{className:"h-12 w-12 text-muted-foreground mb-4"}),e.jsx("h3",{className:"text-lg font-semibold mb-2",children:"No Team Contacts"}),e.jsx("p",{className:"text-muted-foreground text-sm",children:"Team contact sharing is not enabled, or you're not on a team. Ask your manager about contact visibility settings."})]})}):e.jsxs("div",{className:"space-y-4",children:[e.jsx(_e,{children:e.jsx(De,{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(Gr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(we,{placeholder:"Search by name, email, phone, or agent...",value:a,onChange:y=>i(y.target.value),className:"pl-9"})]}),e.jsxs(Ns,{value:l,onValueChange:o,children:[e.jsx(ws,{className:"w-[200px]",children:e.jsx(ks,{placeholder:"Filter by agent"})}),e.jsxs(js,{children:[e.jsx(nt,{value:"all",children:"All Team Members"}),f.map(y=>e.jsx(nt,{value:y.id,children:y.name},y.id))]})]})]})})}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:[g.length," contact",g.length!==1?"s":""," from ",f.length," teammate",f.length!==1?"s":""]}),e.jsx(_e,{children:e.jsx(De,{className:"p-0 overflow-x-auto",children:e.jsxs(Oa,{className:"min-w-[800px]",children:[e.jsx(Fa,{children:e.jsxs(un,{children:[e.jsx(Mt,{children:"Name"}),e.jsx(Mt,{children:"Agent"}),e.jsx(Mt,{children:"Contact Info"}),e.jsx(Mt,{children:"Address"}),e.jsx(Mt,{children:"Lead Source"}),e.jsx(Mt,{children:"Date Added"}),m&&e.jsx(Mt,{className:"w-[80px]",children:"Actions"})]})}),e.jsx(za,{children:g.length===0?e.jsx(un,{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"})}):g.map(y=>e.jsxs(un,{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(Ua,{className:"h-6 w-6",children:[e.jsx(Gi,{src:y.owner_avatar_url||""}),e.jsx(qa,{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(mn,{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(ga,{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(ii,{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(We,{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:Js(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:x=>{x.stopPropagation(),d(y.id),h(`${y.first_name} ${y.last_name||""}`.trim())},title:"Transfer to team member",children:e.jsx(c5,{className:"h-4 w-4"})})})]},y.id))})]})})}),e.jsx(MEt,{open:!!c,onOpenChange:y=>{y||d(null)},contactIds:c?[c]:[],contactNames:u?[u]:[],onComplete:()=>d(null)})]})},UVe=({teamId:s})=>{const{user:t}=Ls(),{leadPondItems:n,isLoading:r,claimLead:a,returnLead:i}=EEt(s);if(console.log("[LeadPondView] render — teamId:",s,"itemCount:",n.length,"loading:",r),r)return e.jsx("div",{className:"space-y-3",children:[1,2,3].map(c=>e.jsx(xn,{className:"h-20 w-full"},c))});if(n.length===0)return e.jsx(_e,{children:e.jsxs(De,{className:"flex flex-col items-center justify-center py-12 text-center",children:[e.jsx(K2,{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."})]})});const l=n.filter(c=>c.status==="available"),o=n.filter(c=>c.status==="claimed");return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{children:[e.jsxs("h3",{className:"text-sm font-semibold text-muted-foreground mb-3",children:["Available (",l.length,")"]}),l.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:l.map(c=>{var d,u,h,m,f,g,y;return e.jsx(_e,{children:e.jsxs(De,{className:"flex items-center justify-between p-4",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsxs("p",{className:"font-medium text-sm",children:[(d=c.contact)==null?void 0:d.first_name," ",((u=c.contact)==null?void 0:u.last_name)||""]}),e.jsxs("div",{className:"flex flex-wrap gap-x-4 gap-y-1 mt-1",children:[((h=c.contact)==null?void 0:h.email)&&e.jsxs("span",{className:"text-xs text-muted-foreground flex items-center gap-1",children:[e.jsx(mn,{className:"h-3 w-3"})," ",c.contact.email]}),((m=c.contact)==null?void 0:m.phone)&&e.jsxs("span",{className:"text-xs text-muted-foreground flex items-center gap-1",children:[e.jsx(ga,{className:"h-3 w-3"})," ",c.contact.phone]})]}),e.jsxs("div",{className:"flex items-center gap-2 mt-1",children:[e.jsxs(Ua,{className:"h-4 w-4",children:[e.jsx(Gi,{src:((f=c.contributor)==null?void 0:f.avatar_url)||""}),e.jsx(qa,{className:"text-[8px]",children:(((g=c.contributor)==null?void 0:g.name)||"?").charAt(0)})]}),e.jsxs("span",{className:"text-xs text-muted-foreground",children:["from ",((y=c.contributor)==null?void 0:y.name)||"Unknown"]})]})]}),e.jsxs(B,{size:"sm",onClick:()=>a.mutate(c.id),disabled:a.isPending,children:[e.jsx(XG,{className:"mr-1 h-3 w-3"}),"Claim"]})]})},c.id)})})]}),o.length>0&&e.jsxs("div",{children:[e.jsxs("h3",{className:"text-sm font-semibold text-muted-foreground mb-3",children:["Claimed (",o.length,")"]}),e.jsx("div",{className:"space-y-2",children:o.map(c=>{var d,u,h;return e.jsx(_e,{className:"opacity-75",children:e.jsxs(De,{className:"flex items-center justify-between p-4",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsxs("p",{className:"font-medium text-sm",children:[(d=c.contact)==null?void 0:d.first_name," ",((u=c.contact)==null?void 0:u.last_name)||""]}),e.jsx("div",{className:"flex items-center gap-2 mt-1",children:e.jsxs(We,{variant:"secondary",className:"text-xs",children:["Claimed by ",((h=c.claimer)==null?void 0:h.name)||"Unknown"]})})]}),c.claimed_by===(t==null?void 0:t.id)&&e.jsxs(B,{size:"sm",variant:"outline",onClick:()=>i.mutate(c.id),disabled:i.isPending,children:[e.jsx(hf,{className:"mr-1 h-3 w-3"}),"Return"]})]})},c.id)})})]})]})},LEt=({teamId:s})=>{const{useTeamMembers:t}=ZR(),{data:n=[]}=t(s),r=n.map(f=>f.user_id),a=new Map(n.map(f=>[f.user_id,f.profile])),{data:i=[],isLoading:l}=mt({queryKey:["team-shared-presentations",s,r],queryFn:async()=>{if(r.length===0)return[];const{data:f,error:g}=await H.from("smart_presentations").select("id, owner_user_id, title, client_name, status, view_count, cta_clicked_count, share_token, created_at, published_at").in("owner_user_id",r).neq("status","archived").order("created_at",{ascending:!1});if(g)throw g;return f||[]},enabled:r.length>0}),{data:o=[],isLoading:c}=mt({queryKey:["team-shared-open-houses",s,r],queryFn:async()=>{if(r.length===0)return[];const{data:f,error:g}=await H.from("open_houses").select("id, agent_id, property_address, city, state, event_date, is_active, visitor_count, slug, created_at").in("agent_id",r).order("event_date",{ascending:!1});if(g)throw g;return f||[]},enabled:r.length>0}),{data:d=[],isLoading:u}=mt({queryKey:["team-shared-videos",s,r],queryFn:async()=>{if(r.length===0)return[];const{data:f,error:g}=await H.from("agent_videos").select("id, owner_user_id, title, recipient_name, status, view_count, touch_type, share_token, created_at").in("owner_user_id",r).eq("is_deleted",!1).order("created_at",{ascending:!1}).limit(50);if(g)throw g;return f||[]},enabled:r.length>0});if(l||c||u)return e.jsx("div",{className:"space-y-3",children:[1,2,3].map(f=>e.jsx(xn,{className:"h-20 w-full"},f))});const m=f=>{const g=a.get(f);return{name:(g==null?void 0:g.name)||"Unknown",avatar:(g==null?void 0:g.avatar_url)||"",initials:((g==null?void 0:g.name)||"?").charAt(0).toUpperCase()}};return e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"grid gap-3 grid-cols-3",children:[e.jsx(_e,{children:e.jsxs(De,{className:"flex items-center gap-3 p-4",children:[e.jsx(ab,{className:"h-5 w-5 text-primary"}),e.jsxs("div",{children:[e.jsx("p",{className:"text-2xl font-bold",children:i.length}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Presentations"})]})]})}),e.jsx(_e,{children:e.jsxs(De,{className:"flex items-center gap-3 p-4",children:[e.jsx(_a,{className:"h-5 w-5 text-primary"}),e.jsxs("div",{children:[e.jsx("p",{className:"text-2xl font-bold",children:o.length}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Guest Books"})]})]})}),e.jsx(_e,{children:e.jsxs(De,{className:"flex items-center gap-3 p-4",children:[e.jsx(na,{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(ya,{defaultValue:"presentations",className:"space-y-4",children:[e.jsxs(va,{children:[e.jsxs(ls,{value:"presentations",children:["Presentations (",i.length,")"]}),e.jsxs(ls,{value:"guest-books",children:["Guest Books (",o.length,")"]}),e.jsxs(ls,{value:"videos",children:["Videos (",d.length,")"]})]}),e.jsx(_s,{value:"presentations",className:"space-y-2",children:i.length===0?e.jsx(lLe,{icon:e.jsx(ab,{className:"h-10 w-10"}),label:"No presentations yet"}):i.map(f=>{const g=m(f.owner_user_id);return e.jsx(_e,{children:e.jsxs(De,{className:"flex items-center justify-between p-4",children:[e.jsxs("div",{className:"flex items-center gap-3 min-w-0",children:[e.jsxs(Ua,{className:"h-8 w-8 shrink-0",children:[e.jsx(Gi,{src:g.avatar}),e.jsx(qa,{className:"text-xs",children:g.initials})]}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"font-medium truncate",children:f.title||"Untitled"}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[g.name," · ",Js(new Date(f.created_at),"MMM d, yyyy")]})]})]}),e.jsxs("div",{className:"flex items-center gap-3 shrink-0",children:[e.jsx(We,{variant:f.status==="published"?"default":"secondary",className:"text-xs capitalize",children:f.status}),e.jsxs("div",{className:"flex items-center gap-1 text-xs text-muted-foreground",children:[e.jsx(da,{className:"h-3 w-3"}),f.view_count||0]})]})]})},f.id)})}),e.jsx(_s,{value:"guest-books",className:"space-y-2",children:o.length===0?e.jsx(lLe,{icon:e.jsx(_a,{className:"h-10 w-10"}),label:"No guest books yet"}):o.map(f=>{const g=m(f.agent_id);return e.jsx(_e,{children:e.jsxs(De,{className:"flex items-center justify-between p-4",children:[e.jsxs("div",{className:"flex items-center gap-3 min-w-0",children:[e.jsxs(Ua,{className:"h-8 w-8 shrink-0",children:[e.jsx(Gi,{src:g.avatar}),e.jsx(qa,{className:"text-xs",children:g.initials})]}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"font-medium truncate",children:f.property_address}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[g.name," · ",Js(new Date(f.event_date),"MMM d, yyyy")]})]})]}),e.jsxs("div",{className:"flex items-center gap-3 shrink-0",children:[f.is_active?e.jsx(We,{className:"text-xs",children:"Active"}):e.jsx(We,{variant:"secondary",className:"text-xs",children:"Inactive"}),e.jsxs("div",{className:"flex items-center gap-1 text-xs text-muted-foreground",children:[e.jsx(Yn,{className:"h-3 w-3"}),f.visitor_count||0]})]})]})},f.id)})}),e.jsx(_s,{value:"videos",className:"space-y-2",children:d.length===0?e.jsx(lLe,{icon:e.jsx(na,{className:"h-10 w-10"}),label:"No videos yet"}):d.map(f=>{const g=m(f.owner_user_id);return e.jsx(_e,{children:e.jsxs(De,{className:"flex items-center justify-between p-4",children:[e.jsxs("div",{className:"flex items-center gap-3 min-w-0",children:[e.jsxs(Ua,{className:"h-8 w-8 shrink-0",children:[e.jsx(Gi,{src:g.avatar}),e.jsx(qa,{className:"text-xs",children:g.initials})]}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"font-medium truncate",children:f.title||f.recipient_name||"Untitled Video"}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[g.name," · ",Js(new Date(f.created_at),"MMM d, yyyy")]})]})]}),e.jsxs("div",{className:"flex items-center gap-3 shrink-0",children:[e.jsx(We,{variant:"secondary",className:"text-xs capitalize",children:f.touch_type}),e.jsxs("div",{className:"flex items-center gap-1 text-xs text-muted-foreground",children:[e.jsx(da,{className:"h-3 w-3"}),f.view_count||0]})]})]})},f.id)})})]})]})},lLe=({icon:s,label:t})=>e.jsx(_e,{children:e.jsxs(De,{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})]})}),PEt=({team:s,brokerageAgents:t,onBack:n,onUpdate:r,onAddMember:a,onRemoveMember:i,onUpdateRole:l,onDeleteTeam:o,isUpdating:c,isAddingMember:d})=>{var I,M;const{useTeamMembers:u}=ZR(),{data:h=[],isLoading:m}=u(s.id),[f,g]=N.useState(!1),[y,x]=N.useState(""),[_,b]=N.useState("team_member"),{data:k}=mt({queryKey:["agents-on-other-teams",s.id],queryFn:async()=>{const{data:L}=await H.from("team_members").select("user_id, team_id, teams:team_id(name)").neq("team_id",s.id),z=new Map;return(L||[]).forEach($=>{var V;z.set($.user_id,((V=$.teams)==null?void 0:V.name)||"another team")}),z}}),A=new Set(h.map(L=>L.user_id)),T=t.filter(L=>!A.has(L.id)),P=async()=>{y&&(await a(y,_),x(""),b("team_member"),g(!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(ya,{defaultValue:"members",className:"space-y-4",children:[e.jsxs(va,{children:[e.jsx(ls,{value:"members",children:"Members"}),e.jsxs(ls,{value:"contacts",children:[e.jsx(dD,{className:"mr-1 h-3.5 w-3.5"}),"Team Contacts"]}),s.lead_pond_enabled&&e.jsxs(ls,{value:"lead-pond",children:[e.jsx(K2,{className:"mr-1 h-3.5 w-3.5"}),"Lead Pond"]}),s.shared_assets_enabled&&e.jsxs(ls,{value:"shared-assets",children:[e.jsx(H0,{className:"mr-1 h-3.5 w-3.5"}),"Shared Assets"]}),e.jsx(ls,{value:"settings",children:"Settings"})]}),e.jsxs(_s,{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(Bs,{open:f,onOpenChange:g,children:[e.jsx(Ao,{asChild:!0,children:e.jsxs(B,{size:"sm",children:[e.jsx(Yl,{className:"mr-2 h-4 w-4"}),"Add Member"]})}),e.jsxs(Fs,{children:[e.jsxs(qs,{children:[e.jsx($s,{children:"Add Team Member"}),e.jsxs(Ar,{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(re,{children:"Agent"}),e.jsxs(rc,{children:[e.jsx(ac,{asChild:!0,children:e.jsxs(B,{variant:"outline",role:"combobox",className:"w-full justify-between font-normal",children:[y&&(((I=T.find(L=>L.id===y))==null?void 0:I.name)||((M=T.find(L=>L.id===y))==null?void 0:M.email))||"Select an agent",e.jsx(sb,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]})}),e.jsx(Zl,{className:"w-[--radix-popover-trigger-width] p-0",align:"start",children:e.jsxs(db,{children:[e.jsx(ub,{placeholder:"Search agents..."}),e.jsxs(hb,{children:[e.jsx(mb,{children:"No agents found."}),e.jsx(pb,{children:T.map(L=>{const z=k==null?void 0:k.get(L.id);return e.jsxs(Ry,{value:L.name||L.email||L.id,disabled:!!z,onSelect:()=>x(L.id),children:[e.jsx(pa,{className:Ot("mr-2 h-4 w-4",y===L.id?"opacity-100":"opacity-0")}),L.name||L.email,z&&e.jsxs("span",{className:"text-xs text-muted-foreground ml-1",children:["(on ",z,")"]})]},L.id)})})]})]})})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{children:"Role"}),e.jsxs(Ns,{value:_,onValueChange:b,children:[e.jsx(ws,{children:e.jsx(ks,{})}),e.jsxs(js,{children:[e.jsx(nt,{value:"team_leader",children:"Team Leader"}),e.jsx(nt,{value:"team_member",children:"Team Member"})]})]})]})]}),e.jsxs(Cr,{children:[e.jsx(B,{variant:"outline",onClick:()=>g(!1),children:"Cancel"}),e.jsx(B,{onClick:P,disabled:!y||d,children:d?"Adding...":"Add to Team"})]})]})]})]}),m?e.jsx("div",{className:"space-y-3",children:[1,2,3].map(L=>e.jsx(xn,{className:"h-16 w-full"},L))}):h.length===0?e.jsx(_e,{children:e.jsxs(De,{className:"flex flex-col items-center justify-center py-8 text-center",children:[e.jsx(Yn,{className:"h-10 w-10 text-muted-foreground mb-3"}),e.jsx("p",{className:"text-muted-foreground",children:"No members yet. Add agents to this team."})]})}):e.jsx("div",{className:"space-y-2",children:h.map(L=>{var z,$,V,W,G;return e.jsx(_e,{children:e.jsxs(De,{className:"flex items-center justify-between p-4",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs(Ua,{className:"h-10 w-10",children:[e.jsx(Gi,{src:((z=L.profile)==null?void 0:z.avatar_url)||""}),e.jsx(qa,{children:((($=L.profile)==null?void 0:$.name)||"?").charAt(0).toUpperCase()})]}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:((V=L.profile)==null?void 0:V.name)||"Unknown"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:(W=L.profile)==null?void 0:W.email})]}),L.role==="team_leader"?e.jsxs(We,{className:"bg-[hsl(var(--chart-4)/0.1)] text-[hsl(var(--chart-4))] border-[hsl(var(--chart-4))]",children:[e.jsx(q0,{className:"mr-1 h-3 w-3"})," Leader"]}):e.jsx(We,{variant:"secondary",children:"Member"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(Ns,{value:L.role,onValueChange:X=>l(L.id,X),children:[e.jsx(ws,{className:"w-[140px]",children:e.jsx(ks,{})}),e.jsxs(js,{children:[e.jsx(nt,{value:"team_leader",children:"Team Leader"}),e.jsx(nt,{value:"team_member",children:"Team Member"})]})]}),e.jsxs(Fl,{children:[e.jsx(Gf,{asChild:!0,children:e.jsx(B,{variant:"ghost",size:"icon",className:"text-muted-foreground hover:text-destructive",children:e.jsx(MW,{className:"h-4 w-4"})})}),e.jsxs(kl,{children:[e.jsxs(Sl,{children:[e.jsx(Al,{children:"Remove Member?"}),e.jsxs(Tl,{children:["Remove ",((G=L.profile)==null?void 0:G.name)||"this member"," from ",s.name,"?"]})]}),e.jsxs(Cl,{children:[e.jsx(El,{children:"Cancel"}),e.jsx(wl,{onClick:()=>i(L.id),className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:"Remove"})]})]})]})]})]})},L.id)})})]}),e.jsx(_s,{value:"contacts",className:"space-y-4",children:e.jsx($Ve,{})}),s.lead_pond_enabled&&e.jsx(_s,{value:"lead-pond",className:"space-y-4",children:e.jsx(UVe,{teamId:s.id})}),s.shared_assets_enabled&&e.jsx(_s,{value:"shared-assets",className:"space-y-4",children:e.jsx(LEt,{teamId:s.id})}),e.jsxs(_s,{value:"settings",className:"space-y-4",children:[e.jsxs(_e,{children:[e.jsxs(zt,{children:[e.jsx(qt,{className:"text-lg",children:"Team Settings"}),e.jsx(_r,{children:"Configure how this team operates."})]}),e.jsxs(De,{className:"space-y-6",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{children:"Team Name"}),e.jsx(we,{defaultValue:s.name,onBlur:L=>{L.target.value!==s.name&&r({name:L.target.value})}})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{children:"Description"}),e.jsx(Ws,{defaultValue:s.description||"",onBlur:L=>{L.target.value!==(s.description||"")&&r({description:L.target.value||null})},rows:3})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{children:"Contact Visibility"}),e.jsxs(Ns,{defaultValue:s.contact_visibility,onValueChange:L=>r({contact_visibility:L}),children:[e.jsx(ws,{children:e.jsx(ks,{})}),e.jsxs(js,{children:[e.jsx(nt,{value:"private",children:"Private — Members keep their contacts private"}),e.jsx(nt,{value:"leader_only",children:"Leader Only — Only team leaders can see member contacts"}),e.jsx(nt,{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(re,{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(zn,{checked:s.lead_pond_enabled,onCheckedChange:L=>r({lead_pond_enabled:L})})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(re,{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(zn,{checked:s.shared_assets_enabled,onCheckedChange:L=>r({shared_assets_enabled:L})})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(re,{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(zn,{checked:s.shared_videos_enabled??!1,onCheckedChange:L=>r({shared_videos_enabled:L})})]})]})]}),e.jsxs(Fl,{children:[e.jsx(Gf,{asChild:!0,children:e.jsxs(B,{variant:"destructive",size:"sm",children:[e.jsx(qn,{className:"mr-2 h-4 w-4"}),"Delete Team"]})}),e.jsxs(kl,{children:[e.jsxs(Sl,{children:[e.jsx(Al,{children:"Delete Team?"}),e.jsxs(Tl,{children:['This will permanently delete "',s.name,'" and remove all team members. This cannot be undone.']})]}),e.jsxs(Cl,{children:[e.jsx(El,{children:"Cancel"}),e.jsx(wl,{onClick:()=>{o(),n()},className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:"Delete Team"})]})]})]})]})]})]})},IEt=({open:s,onOpenChange:t,onCreateTeam:n,isCreating:r,brokerageAgents:a,isAdmin:i,allBrokerages:l,activeBrokerageId:o})=>{const[c,d]=N.useState(1),[u,h]=N.useState(""),[m,f]=N.useState(""),[g,y]=N.useState(""),[x,_]=N.useState(""),[b,k]=N.useState([]),A=()=>{d(1),h(""),f(""),y(""),_(""),k([])},T=L=>{L||A(),t(L)},P=async()=>{const L=g&&g!=="none"?g:o||null;await n({name:u.trim(),description:m.trim()||void 0,brokerage_id:L,leaderId:x||void 0,memberIds:b.length>0?b:void 0}),A()},I=L=>{L!==x&&k(z=>z.includes(L)?z.filter($=>$!==L):[...z,L])},M=a.filter(L=>L.id!==x);return e.jsx(Bs,{open:s,onOpenChange:T,children:e.jsxs(Fs,{className:"sm:max-w-lg max-h-[90vh] flex flex-col",children:[e.jsxs(qs,{children:[e.jsx($s,{children:c===1?"Create New Team":"Assign Team Members"}),e.jsx(Ar,{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:Ot("h-1.5 flex-1 rounded-full transition-colors","bg-primary")}),e.jsx("div",{className:Ot("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(re,{htmlFor:"team-name",children:"Team Name *"}),e.jsx(we,{id:"team-name",value:u,onChange:L=>h(L.target.value),placeholder:"e.g., Downtown Squad",autoFocus:!0})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{htmlFor:"team-desc",children:"Description"}),e.jsx(Ws,{id:"team-desc",value:m,onChange:L=>f(L.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(re,{children:"Brokerage"}),e.jsxs(Ns,{value:g,onValueChange:y,children:[e.jsx(ws,{children:e.jsx(ks,{placeholder:"No brokerage (independent team)"})}),e.jsxs(js,{children:[e.jsx(nt,{value:"none",children:"No brokerage (independent)"}),l.map(L=>e.jsx(nt,{value:L.id,children:L.name},L.id))]})]})]})]}):e.jsxs("div",{className:"space-y-4 py-2",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsxs(re,{className:"flex items-center gap-1.5",children:[e.jsx(q0,{className:"h-3.5 w-3.5 text-[hsl(var(--chart-4))]"}),"Team Leader"]}),e.jsxs(Ns,{value:x,onValueChange:L=>{_(L),k(z=>z.filter($=>$!==L))},children:[e.jsx(ws,{children:e.jsx(ks,{placeholder:"Select a team leader (optional)"})}),e.jsxs(js,{children:[e.jsx(nt,{value:"none",children:"No leader for now"}),a.map(L=>e.jsx(nt,{value:L.id,children:L.name||L.email||"Unknown"},L.id))]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs(re,{className:"flex items-center gap-1.5",children:[e.jsx(Yl,{className:"h-3.5 w-3.5"}),"Initial Members",b.length>0&&e.jsxs(We,{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(Yn,{className:"h-8 w-8 mx-auto mb-2 opacity-50"}),"No agents available"]}):M.map(L=>{const z=b.includes(L.id);return e.jsxs("button",{type:"button",className:Ot("w-full flex items-center gap-3 p-3 text-left transition-colors hover:bg-accent/50",z&&"bg-primary/5"),onClick:()=>I(L.id),children:[e.jsxs(Ua,{className:"h-8 w-8",children:[e.jsx(Gi,{src:L.avatar_url||""}),e.jsx(qa,{className:"text-xs",children:(L.name||"?").charAt(0).toUpperCase()})]}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-sm font-medium truncate",children:L.name||"Unknown"}),e.jsx("p",{className:"text-xs text-muted-foreground truncate",children:L.email})]}),e.jsx("div",{className:Ot("h-5 w-5 rounded-full border-2 flex items-center justify-center transition-colors shrink-0",z?"bg-primary border-primary text-primary-foreground":"border-muted-foreground/30"),children:z&&e.jsx(pa,{className:"h-3 w-3"})})]},L.id)})})]})]})}),e.jsx(Cr,{className:"gap-2 sm:gap-0",children:c===1?e.jsxs(e.Fragment,{children:[e.jsx(B,{variant:"outline",onClick:()=>T(!1),children:"Cancel"}),e.jsxs(B,{onClick:()=>d(2),disabled:!u.trim(),children:["Next",e.jsx(vi,{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:P,disabled:r,children:r?"Creating…":"Create Team"})]})})]})})},fRs=()=>{const{teams:s,isLoading:t,createTeam:n,updateTeam:r,deleteTeam:a,addMember:i,removeMember:l,updateMemberRole:o}=ZR(),[c,d]=N.useState(!1),[u,h]=N.useState(null),[m,f]=N.useState(""),{data:g}=mt({queryKey:["all-brokerages-for-teams"],queryFn:async()=>{const{data:T,error:P}=await H.from("brokerages").select("id, name").order("name");if(P)throw P;return T||[]}}),{data:y}=mt({queryKey:["admin-team-member-info",s.map(T=>T.id).join(",")],queryFn:async()=>{var L;if(s.length===0)return{};const{data:T}=await H.from("team_members").select("team_id, user_id, role").in("team_id",s.map(z=>z.id));if(!T)return{};const P=T.filter(z=>z.role==="team_leader").map(z=>z.user_id);let I={};if(P.length>0){const{data:z}=await H.from("profiles").select("id, name").in("id",P);z&&(I=Object.fromEntries(z.map($=>[$.id,{name:$.name}])))}const M={};for(const z of s){const $=T.filter(W=>W.team_id===z.id),V=$.find(W=>W.role==="team_leader");M[z.id]={count:$.length,leaderName:V&&((L=I[V.user_id])==null?void 0:L.name)||null}}return M},enabled:s.length>0}),x=(u==null?void 0:u.brokerage_id)||null,{data:_}=mt({queryKey:["brokerage-agents-for-teams",x],queryFn:async()=>{let T=H.from("profiles").select("id, name, email, avatar_url").order("name");x&&(T=T.eq("brokerage_id",x));const{data:P,error:I}=await T;if(I)throw I;return P||[]},enabled:!!u}),b=Object.fromEntries((g||[]).map(T=>[T.id,T.name])),k=async T=>{const P=await n.mutateAsync({name:T.name,brokerage_id:T.brokerage_id||null,description:T.description});if(T.leaderId&&T.leaderId!=="none"&&await i.mutateAsync({team_id:P.id,user_id:T.leaderId,role:"team_leader"}),T.memberIds)for(const I of T.memberIds)await i.mutateAsync({team_id:P.id,user_id:I,role:"team_member"});d(!1)};if(u)return e.jsx(PEt,{team:u,brokerageAgents:_||[],onBack:()=>h(null),onUpdate:T=>r.mutateAsync({id:u.id,...T}).then(P=>h(P)),onAddMember:(T,P)=>i.mutateAsync({team_id:u.id,user_id:T,role:P}),onRemoveMember:T=>l.mutateAsync({team_id:u.id,member_id:T}),onUpdateRole:(T,P)=>o.mutateAsync({team_id:u.id,member_id:T,role:P}),onDeleteTeam:()=>{a.mutate(u.id),h(null)},isUpdating:r.isPending,isAddingMember:i.isPending});const A=s.filter(T=>T.name.toLowerCase().includes(m.toLowerCase())||(T.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(Gr,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(we,{placeholder:"Search teams...",value:m,onChange:T=>f(T.target.value),className:"pl-10"})]}),e.jsxs("span",{className:"text-sm text-muted-foreground whitespace-nowrap",children:[A.length," of ",s.length," teams"]})]}),e.jsxs(B,{size:"sm",onClick:()=>d(!0),children:[e.jsx(nn,{className:"mr-2 h-4 w-4"}),"Create Team"]})]}),e.jsx(IEt,{open:c,onOpenChange:d,onCreateTeam:k,isCreating:n.isPending,brokerageAgents:[],isAdmin:!0,allBrokerages:g,activeBrokerageId:null}),e.jsx("div",{className:"border rounded-lg bg-card overflow-hidden",children:e.jsxs(Oa,{children:[e.jsx(Fa,{children:e.jsxs(un,{className:"bg-muted/30 hover:bg-muted/30",children:[e.jsx(Mt,{className:"font-semibold",children:"Team Name"}),e.jsx(Mt,{className:"font-semibold",children:"Brokerage"}),e.jsx(Mt,{className:"font-semibold",children:"Leader"}),e.jsx(Mt,{className:"font-semibold",children:"Members"}),e.jsx(Mt,{className:"font-semibold",children:"Visibility"}),e.jsx(Mt,{className:"w-[100px]"})]})}),e.jsx(za,{children:t?e.jsx(e.Fragment,{children:[1,2,3].map(T=>e.jsxs(un,{children:[e.jsx(gt,{children:e.jsx(xn,{className:"h-4 w-32"})}),e.jsx(gt,{children:e.jsx(xn,{className:"h-4 w-24"})}),e.jsx(gt,{children:e.jsx(xn,{className:"h-4 w-28"})}),e.jsx(gt,{children:e.jsx(xn,{className:"h-4 w-12"})}),e.jsx(gt,{children:e.jsx(xn,{className:"h-4 w-20"})}),e.jsx(gt,{children:e.jsx(xn,{className:"h-4 w-16"})})]},T))}):A.length===0?e.jsx(un,{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."})}):A.map(T=>{const P=y==null?void 0:y[T.id];return e.jsxs(un,{className:"hover:bg-muted/30",children:[e.jsxs(gt,{children:[e.jsx("button",{onClick:()=>h(T),className:"text-primary hover:underline font-medium",children:T.name}),T.description&&e.jsx("p",{className:"text-xs text-muted-foreground mt-0.5 line-clamp-1",children:T.description})]}),e.jsx(gt,{children:T.brokerage_id?e.jsx("span",{className:"text-sm",children:b[T.brokerage_id]||"—"}):e.jsx("span",{className:"text-sm text-muted-foreground",children:"Independent"})}),e.jsx(gt,{children:P!=null&&P.leaderName?e.jsxs("span",{className:"text-sm flex items-center gap-1",children:[e.jsx(q0,{className:"h-3 w-3 text-[hsl(var(--chart-4))]"}),P.leaderName]}):e.jsx("span",{className:"text-sm text-muted-foreground",children:"No leader"})}),e.jsx(gt,{children:e.jsxs(We,{variant:"secondary",className:"text-xs",children:[e.jsx(Yn,{className:"h-3 w-3 mr-1"}),(P==null?void 0:P.count)??0]})}),e.jsx(gt,{children:e.jsxs("span",{className:"text-xs text-muted-foreground capitalize flex items-center gap-1",children:[e.jsx(mf,{className:"h-3 w-3"}),T.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(T),title:"Edit team",children:e.jsx(Ja,{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:()=>{confirm(`Delete team "${T.name}"? This cannot be undone.`)&&a.mutate(T.id)},title:"Delete team",children:e.jsx(qn,{className:"h-3.5 w-3.5"})})]})})]},T.id)})})]})})]})};function wot(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 gRs({open:s,onOpenChange:t,recipients:n}){const{toast:r}=Ci(),[a,i]=N.useState([]),[l,o]=N.useState(!1),[c,d]=N.useState(""),[u,h]=N.useState(""),[m,f]=N.useState(""),[g,y]=N.useState(!1),[x,_]=N.useState(!1),b=N.useMemo(()=>a.find(P=>P.id===c)||null,[a,c]);N.useEffect(()=>{s&&(o(!0),(async()=>{const P=new Date().toISOString(),{data:I,error:M}=await H.from("events").select("id,title,description,event_date,zoom_link,image_url,is_published").gte("event_date",P).order("event_date",{ascending:!0}).limit(50);M?r({title:"Could not load events",description:M.message,variant:"destructive"}):i(I||[]),o(!1)})())},[s,r]);const k=N.useMemo(()=>n.filter(P=>P.email&&/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(P.email)),[n]),A=()=>{if(!b){r({title:"Pick an event first",variant:"destructive"});return}if(k.length===0){r({title:"No valid recipient emails",variant:"destructive"});return}_(!0)},T=async()=>{if(b){_(!1),y(!0);try{const{data:{session:P}}=await H.auth.getSession(),I=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/admin-send-event-invite",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${P==null?void 0:P.access_token}`},body:JSON.stringify({event_id:b.id,recipients:k.map($=>({email:$.email,name:$.name,user_id:$.id})),custom_subject:u.trim()||void 0,custom_intro:m.trim()||void 0})}),M=await I.json().catch(()=>({}));if(!I.ok)throw new Error((M==null?void 0:M.error)||"Failed to send event invite");const L=(M==null?void 0:M.sent)??0,z=(M==null?void 0:M.failed)??0;r({title:"Invites sent",description:`Sent: ${L}${z?` · Failed: ${z}`:""}`}),t(!1),f(""),h(""),d("")}catch(P){const I=P instanceof Error?P.message:"Send failed";r({title:"Send failed",description:I,variant:"destructive"})}finally{y(!1)}}};return e.jsxs(e.Fragment,{children:[e.jsx(Bs,{open:s,onOpenChange:t,children:e.jsxs(Fs,{className:"max-w-2xl max-h-[90vh] overflow-y-auto",children:[e.jsxs(qs,{children:[e.jsxs($s,{className:"flex items-center gap-2",children:[e.jsx(mn,{className:"h-5 w-5 text-primary"}),"Send Event Invite"]}),e.jsxs(Ar,{children:["Send a beautiful event invitation to ",k.length," selected member",k.length===1?"":"s",".",n.length!==k.length&&e.jsxs("span",{className:"block text-amber-600 mt-1",children:[n.length-k.length," skipped (missing or invalid email)"]})]})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(re,{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(us,{className:"h-4 w-4 animate-spin"})," Loading upcoming events..."]}):a.length===0?e.jsx("p",{className:"text-sm text-muted-foreground py-2",children:"No upcoming events found. Create an event first."}):e.jsxs(Ns,{value:c,onValueChange:d,children:[e.jsx(ws,{id:"event-select",children:e.jsx(ks,{placeholder:"Pick an upcoming event..."})}),e.jsx(js,{children:a.map(P=>e.jsx(nt,{value:P.id,children:e.jsxs("div",{className:"flex flex-col text-left",children:[e.jsx("span",{className:"font-medium",children:P.title}),e.jsxs("span",{className:"text-xs text-muted-foreground",children:[wot(P.event_date),!P.is_published&&" · (Draft)"]})]})},P.id))})]})]}),b&&e.jsxs("div",{className:"rounded-lg border bg-muted/30 p-3 space-y-1",children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm font-medium",children:[e.jsx(ta,{className:"h-4 w-4 text-primary"}),b.title]}),e.jsx("div",{className:"text-xs text-muted-foreground",children:wot(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(re,{htmlFor:"subject",children:"Subject line (optional)"}),e.jsx(we,{id:"subject",placeholder:b?`You're invited: ${b.title}`:"You're invited to...",value:u,onChange:P=>h(P.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(re,{htmlFor:"intro",children:"Personal message (optional)"}),e.jsx(Ws,{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:P=>f(P.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 (",k.length,")"]}),e.jsxs("div",{className:"flex flex-wrap gap-1 max-h-24 overflow-y-auto",children:[k.slice(0,30).map(P=>e.jsx(We,{variant:"secondary",className:"text-xs font-normal",children:P.name||P.email},P.id)),k.length>30&&e.jsxs(We,{variant:"outline",className:"text-xs",children:["+",k.length-30," more"]})]})]})]}),e.jsxs(Cr,{children:[e.jsx(B,{variant:"outline",onClick:()=>t(!1),disabled:g,children:"Cancel"}),e.jsx(B,{onClick:A,disabled:g||!c||k.length===0,children:g?e.jsxs(e.Fragment,{children:[e.jsx(us,{className:"h-4 w-4 mr-2 animate-spin"})," Sending..."]}):e.jsxs(e.Fragment,{children:[e.jsx(Rr,{className:"h-4 w-4 mr-2"})," Send to ",k.length]})})]})]})}),e.jsx(Fl,{open:x,onOpenChange:_,children:e.jsxs(kl,{children:[e.jsxs(Sl,{children:[e.jsx(Al,{children:"Send event invite?"}),e.jsx(Tl,{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:[k.length," member",k.length===1?"":"s"]}),"?"]}):null})]}),e.jsxs(Cl,{children:[e.jsx(El,{children:"Cancel"}),e.jsxs(wl,{onClick:T,children:[e.jsx(Rr,{className:"h-4 w-4 mr-2"})," Send"]})]})]})})]})}const xRs=()=>{const s=tr(),{user:t,isAdmin:n}=Ls(),{startImpersonation:r,isLoading:a}=s4e(),{toast:i}=Ci(),[l,o]=N.useState([]),[c,d]=N.useState([]),[u,h]=N.useState([]),[m,f]=N.useState({}),[g,y]=N.useState(!0);N.useState({});const[x,_]=N.useState(!1),[b,k]=N.useState({email:"",name:"",password:"",brokerage_id:"",role:"user",phone:"",trial_days:""}),[A,T]=N.useState(!1),[P,I]=N.useState(""),[M,L]=N.useState(1),[z,$]=N.useState(50),[V,W]=N.useState("all"),[G,X]=N.useState("all"),[te,ne]=N.useState("all"),[me,ue]=N.useState("all"),[ce,ae]=N.useState("all"),[he,xe]=N.useState(!1),[ve,ge]=N.useState(!1),[be,Se]=N.useState(!1),[Ie,Me]=N.useState(null),[Re,Be]=N.useState(null),[Ne,Ge]=N.useState(!1),[Ce,Fe]=N.useState({name:"",email:"",brokerage_id:"",phone:""}),[Ae,Xe]=N.useState(null),[$e,Ye]=N.useState(!1),[Je,Ke]=N.useState(""),[st,rt]=N.useState(!1),[Ze,ht]=N.useState(!1),[Bt,Ct]=N.useState(null),[Yt,Kt]=N.useState(""),[Xs,zs]=N.useState(!1),[Vt,At]=N.useState(!1),[Os,Nt]=N.useState(null),[ms,Ys]=N.useState(!1),[It,Ds]=N.useState(!1),[As,Hs]=N.useState(null),[Rs,en]=N.useState(""),[Rn,Bn]=N.useState(!1),[Dn,Jn]=N.useState({email:"",name:"",password:"",phone:""}),[ua,Mr]=N.useState(!1),[sn,ki]=N.useState(!1),[ia,vr]=N.useState(""),[Nr,rn]=N.useState(!1),[Zn,sa]=N.useState(!1),[xs,Ve]=N.useState(""),[it,ft]=N.useState(new Set),[kt,Ut]=N.useState(!1),[es,Ms]=N.useState(!1),[bs,Zs]=N.useState(null),[kn,gn]=N.useState(!1),[xr,Kr]=N.useState(null),[ca,Er]=N.useState([]),[qr,Xt]=N.useState([]),[Gn,Jr]=N.useState(!1),[Or,ja]=N.useState({});N.useEffect(()=>{!t||!n||(dr(),Wi())},[t,n]);const ea=async()=>{try{const{data:Wt,error:ze}=await H.from("brokerage_manager_assignments").select("user_id, brokerage_id");if(ze)throw ze;const xt={};for(const ss of Wt??[])xt[ss.brokerage_id]||(xt[ss.brokerage_id]=[]),xt[ss.brokerage_id].push(ss.user_id);f(xt)}catch(Wt){console.error("Error loading brokerage manager assignments:",Wt)}},dr=async()=>{try{y(!0);const{data:Wt,error:ze}=await H.functions.invoke("get-user-details");if(ze)throw ze;const xt=Wt.users||[];o(xt),h(Wt.brokerages||[]),await ea();const ss=xt.filter(cs=>cs.roles.includes("assistant"));if(ss.length>0){const cs=ss.map(Mn=>Mn.id),{data:tn}=await H.from("agent_assistant_assignments").select("agent_id, assistant_id").in("assistant_id",cs);if(tn&&tn.length>0){const Mn=[...new Set(tn.map(Ba=>Ba.agent_id))],{data:Xn}=await H.from("profiles").select("id, name, email").in("id",Mn),mr={};for(const Ba of tn){const Ki=Xn==null?void 0:Xn.find(Ui=>Ui.id===Ba.agent_id);Ki&&(mr[Ba.assistant_id]={agent_name:Ki.name||"",agent_email:Ki.email||""})}ja(mr)}}}catch(Wt){console.error("Error loading members:",Wt),i({title:"Error",description:"Failed to load members",variant:"destructive"})}finally{y(!1)}},Wi=async()=>{try{const{data:Wt,error:ze}=await H.from("app_tiles").select("id, name, icon, app_id, required_tags").order("name");if(ze)throw ze;d(Wt||[])}catch(Wt){console.error("Error loading apps:",Wt),i({title:"Error",description:"Failed to load apps",variant:"destructive"})}},ho=async Wt=>{if(!Ce.name.trim()||!Ce.email.trim()){i({title:"Error",description:"Name and email are required",variant:"destructive"});return}if(!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(Ce.email)){i({title:"Error",description:"Please enter a valid email address",variant:"destructive"});return}try{const{error:xt}=await H.from("profiles").update({name:Ce.name.trim(),email:Ce.email.trim(),brokerage_id:Ce.brokerage_id||null,phone:Ce.phone.trim()||null}).eq("id",Wt);if(xt)throw xt;i({title:"Success",description:"Member details updated successfully"}),Me(null),dr()}catch(xt){console.error("Error updating member:",xt),i({title:"Error",description:xt.message||"Failed to update member",variant:"destructive"})}},oa=async Wt=>{try{const{data:{session:ze}}=await H.auth.getSession(),xt=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/resend-welcome-email",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${ze==null?void 0:ze.access_token}`},body:JSON.stringify({userId:Wt})}),ss=await xt.json();if(!xt.ok)throw new Error(ss.error||"Failed to resend welcome email");i({title:"Success",description:"Welcome email sent successfully"})}catch(ze){console.error("Error resending welcome email:",ze),i({title:"Error",description:ze.message||"Failed to resend welcome email",variant:"destructive"})}},Ha=async(Wt,ze)=>{try{const{error:xt}=await H.functions.invoke("send-password-reset",{body:{email:Wt,redirectTo:window.location.origin}});if(xt)throw xt;i({title:"Password Reset Sent",description:`Password reset email sent to ${ze}`})}catch(xt){console.error("Error sending password reset:",xt),i({title:"Error",description:xt.message||"Failed to send password reset email",variant:"destructive"})}},$i=async(Wt,ze)=>{if(confirm(`Are you sure you want to delete ${ze}? This action cannot be undone.`))try{const{data:{session:xt}}=await H.auth.getSession(),ss=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/delete-user",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${xt==null?void 0:xt.access_token}`},body:JSON.stringify({userId:Wt})}),cs=await ss.json();if(!ss.ok)throw new Error(cs.error||"Failed to delete user");i({title:"Success",description:"User deleted successfully"}),dr()}catch(xt){console.error("Error deleting user:",xt),i({title:"Error",description:xt.message||"Failed to delete user",variant:"destructive"})}},Ta=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}_(!0);try{const{data:{session:Wt}}=await H.auth.getSession(),ze=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/create-user",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${Wt==null?void 0:Wt.access_token}`},body:JSON.stringify(b)}),xt=await ze.json();if(!ze.ok)throw new Error(xt.error||"Failed to create user");if(b.role&&b.role!=="user"&&xt.userId){const ss=b.role==="brokerage_manager"?b.brokerage_id:void 0;await Wn(xt.userId,b.role,"add",ss)}i({title:"Success",description:`User ${b.email} created successfully`}),k({email:"",name:"",password:"",brokerage_id:"",role:"user",phone:"",trial_days:""}),T(!1),dr()}catch(Wt){console.error("Error creating user:",Wt),i({title:"Error",description:Wt.message||"Failed to create user",variant:"destructive"})}finally{_(!1)}},Wn=async(Wt,ze,xt,ss)=>{try{const{data:{session:cs}}=await H.auth.getSession(),tn={userId:Wt,role:ze,action:xt};if(ze==="brokerage_manager"){if(!ss){i({title:"Error",description:"Please choose a brokerage for this manager assignment",variant:"destructive"});return}tn.brokerageId=ss}const Mn=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/manage-user-roles",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${cs==null?void 0:cs.access_token}`},body:JSON.stringify(tn)}),Xn=await Mn.json();if(!Mn.ok)throw new Error(Xn.error||"Failed to manage user role");i({title:"Success",description:`Role ${xt==="add"?"added":"removed"} successfully`}),dr()}catch(cs){console.error("Error managing user role:",cs),i({title:"Error",description:cs.message||"Failed to manage user role",variant:"destructive"})}},Ra=(Wt,ze)=>ze.length===0?!0:ze.some(xt=>Wt.includes(xt)),mo=async(Wt,ze,xt)=>{const ss=`${Wt}-${ze.id}`;Xe(ss);try{if(xt){const cs=l.find(Mn=>Mn.id===Wt),tn=ze.required_tags.filter(Mn=>cs==null?void 0:cs.tags.includes(Mn));for(const Mn of tn){const{error:Xn}=await H.from("user_tags").delete().eq("user_id",Wt).eq("tag",Mn);if(Xn)throw Xn}i({title:"Access Removed",description:`Removed access to ${ze.name}`})}else if(ze.required_tags.length>0){const{error:cs}=await H.from("user_tags").insert({user_id:Wt,tag:ze.required_tags[0]});if(cs)throw cs;i({title:"Access Granted",description:`Granted access to ${ze.name}`})}await dr()}catch(cs){console.error("Error toggling access:",cs),i({title:"Error",description:cs.message||"Failed to update access",variant:"destructive"})}finally{Xe(null)}},Ho=async()=>{const Wt=Je.trim();if(!Wt){i({title:"Error",description:"Brokerage name is required",variant:"destructive"});return}if(Wt.length>100){i({title:"Error",description:"Brokerage name must be less than 100 characters",variant:"destructive"});return}if(u.find(xt=>xt.name.toLowerCase()===Wt.toLowerCase())){i({title:"Error",description:"A brokerage with this name already exists",variant:"destructive"});return}rt(!0);try{const{error:xt}=await H.from("brokerages").insert({name:Wt});if(xt)throw xt;i({title:"Success",description:`Brokerage "${Wt}" created successfully`}),Ke(""),Ye(!1),dr()}catch(xt){console.error("Error creating brokerage:",xt),i({title:"Error",description:xt.message||"Failed to create brokerage",variant:"destructive"})}finally{rt(!1)}},No=Wt=>{Ct(Wt),Kt(Wt.name),ht(!0)},Go=()=>{Ct(null),Kt(""),ht(!1)},Dd=async()=>{if(!Bt)return;const Wt=Yt.trim();if(!Wt){i({title:"Error",description:"Brokerage name is required",variant:"destructive"});return}if(Wt.length>100){i({title:"Error",description:"Brokerage name must be less than 100 characters",variant:"destructive"});return}zs(!0);try{const{error:ze}=await H.from("brokerages").update({name:Wt}).eq("id",Bt.id);if(ze)throw ze;i({title:"Success",description:"Brokerage updated successfully"}),Go(),dr()}catch(ze){console.error("Error updating brokerage:",ze),i({title:"Error",description:ze.message||"Failed to update brokerage",variant:"destructive"})}finally{zs(!1)}},Tu=async(Wt,ze)=>{var xt;if(!ze||typeof ze!="string"){i({title:"Error",description:"Please select a brokerage first",variant:"destructive"});return}try{const ss={userId:Wt,role:"brokerage_manager",action:"add",brokerageId:ze};console.debug("[assignManagerToBrokerage] payload",ss);const{data:{session:cs}}=await H.auth.getSession(),tn=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/manage-user-roles",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${cs==null?void 0:cs.access_token}`},body:JSON.stringify(ss)}),Mn=await tn.json();if(!tn.ok&&!((xt=Mn.error)!=null&&xt.includes("duplicate")))throw new Error(Mn.error||"Failed to add role");i({title:"Success",description:"Manager assigned to brokerage"}),await dr()}catch(ss){console.error("Error assigning manager:",ss),i({title:"Error",description:ss.message||"Failed to assign manager",variant:"destructive"})}},Vm=Wt=>{Nt(Wt),At(!0)},Uc=async()=>{if(Os){Ys(!0);try{const Wt=l.filter(ss=>ss.brokerage_id===Os.id),{data:{session:ze}}=await H.auth.getSession();for(const ss of Wt){const cs=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/delete-user",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${ze==null?void 0:ze.access_token}`},body:JSON.stringify({userId:ss.id})});if(!cs.ok){const tn=await cs.json();console.error(`Failed to delete user ${ss.email}:`,tn.error)}}const{error:xt}=await H.from("brokerages").delete().eq("id",Os.id);if(xt)throw xt;i({title:"Success",description:`Brokerage "${Os.name}" and ${Wt.length} member(s) deleted`}),At(!1),Nt(null),dr()}catch(Wt){console.error("Error deleting brokerage:",Wt),i({title:"Error",description:Wt.message||"Failed to delete brokerage",variant:"destructive"})}finally{Ys(!1)}}},Eu=Wt=>{Hs(Wt),en(""),Ds(!0)},Ec=()=>{Hs(null),en(""),Ds(!1)},Gd=async Wt=>{try{const{error:ze}=await H.from("profiles").update({brokerage_id:null}).eq("id",Wt);if(ze)throw ze;i({title:"Success",description:"User removed from brokerage"}),dr()}catch(ze){console.error("Error removing user from brokerage:",ze),i({title:"Error",description:ze.message||"Failed to remove user",variant:"destructive"})}},s0=async(Wt,ze)=>{try{const{error:xt}=await H.from("profiles").update({brokerage_id:ze}).eq("id",Wt);if(xt)throw xt;i({title:"Success",description:"User added to brokerage"}),dr()}catch(xt){console.error("Error adding user to brokerage:",xt),i({title:"Error",description:xt.message||"Failed to add user",variant:"destructive"})}},Nb=async()=>{if(!As||!Dn.email||!Dn.name||!Dn.password){i({title:"Error",description:"Please fill in all fields",variant:"destructive"});return}Mr(!0);try{const{data:{session:Wt}}=await H.auth.getSession(),ze=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/create-user",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${Wt==null?void 0:Wt.access_token}`},body:JSON.stringify({...Dn,brokerage_id:As.id,role:"user"})}),xt=await ze.json();if(!ze.ok)throw new Error(xt.error||"Failed to create agent");i({title:"Success",description:`Agent ${Dn.email} created successfully`}),Jn({email:"",name:"",password:"",phone:""}),Bn(!1),dr()}catch(Wt){console.error("Error creating agent:",Wt),i({title:"Error",description:Wt.message||"Failed to create agent",variant:"destructive"})}finally{Mr(!1)}},Hm=Wt=>l.filter(ze=>ze.brokerage_id===Wt),ay=Wt=>{const ze=Hm(Wt);if(!Rs)return ze;const xt=Rs.toLowerCase();return ze.filter(ss=>ss.name.toLowerCase().includes(xt)||ss.email.toLowerCase().includes(xt))},wf=Wt=>l.filter(ze=>ze.brokerage_id!==Wt),jf=l.filter(Wt=>{var xt;if(P){const ss=P.toLowerCase();if(!(Wt.name.toLowerCase().includes(ss)||Wt.email.toLowerCase().includes(ss)||((xt=Wt.brokerage_name)==null?void 0:xt.toLowerCase().includes(ss))))return!1}if(V==="claimed"&&!Wt.claimed||V==="unclaimed"&&Wt.claimed||G!=="all"&&!Wt.roles.includes(G))return!1;const ze=Wt.is_trial||Wt.subscription_status==="trialing";if(te==="trial"&&!ze||te==="non-trial"&&ze||me==="none"&&Wt.brokerage_id||me!=="all"&&me!=="none"&&Wt.brokerage_id!==me)return!1;if(ce!=="all"){if(!Wt.created_at)return!1;const ss=parseInt(ce,10),cs=Date.now()-ss*24*60*60*1e3;if(new Date(Wt.created_at).getTime(){var ze;return((ze=Wt.name)==null?void 0:ze.toLowerCase())||""},brokerage:Wt=>{var ze;return((ze=Wt.brokerage_name)==null?void 0:ze.toLowerCase())||""},status:Wt=>Wt.claimed?"active":"pending",role:Wt=>Wt.roles[0]||"",last_login:Wt=>Wt.last_sign_in_at?new Date(Wt.last_sign_in_at).getTime():null,created_at:Wt=>Wt.created_at?new Date(Wt.created_at).getTime():null}),hm=Gm.length,Cg=z===0,wh=Cg?1:Math.ceil(hm/z),Bl=Cg?0:(M-1)*z,Wm=Cg?hm:Bl+z,bd=Gm.slice(Bl,Wm),n0=Wt=>{I(Wt),L(1)},kb=Wt=>{$(Wt),L(1)},Km=(Wt,ze)=>{Wt(ze),L(1)},_i=async(Wt,ze)=>{ge(!0);try{const xt=l.find(Mn=>Mn.id===Wt);if(!xt)return;const ss=xt.trial_expires_at?new Date(xt.trial_expires_at):new Date,cs=new Date(ss.getTime()+ze*24*60*60*1e3),{error:tn}=await H.from("profiles").update({trial_expires_at:cs.toISOString()}).eq("id",Wt);if(tn)throw tn;i({title:"Trial Extended",description:`Trial extended by ${ze} days`}),dr()}catch(xt){console.error("Error extending trial:",xt),i({title:"Error",description:xt.message||"Failed to extend trial",variant:"destructive"})}finally{ge(!1)}},Ym=async Wt=>{Se(!0);try{const{error:ze}=await H.from("profiles").update({is_trial:!1,trial_expires_at:null,trial_started_at:null,trial_claimed_at:null}).eq("id",Wt);if(ze)throw ze;i({title:"Account Converted",description:"User has been converted to a full account"}),dr(),Qf()}catch(ze){console.error("Error converting trial:",ze),i({title:"Error",description:ze.message||"Failed to convert account",variant:"destructive"})}finally{Se(!1)}},[iy,qh]=N.useState(!1),Fp=async(Wt,ze)=>{if(confirm(`Revert this user to a ${ze}-day free trial? This will clear their paid/grandfathered status. Any active Stripe subscription will need to be cancelled separately.`)){qh(!0);try{const xt=new Date,ss=new Date(xt.getTime()+ze*24*60*60*1e3),{error:cs}=await H.from("profiles").update({is_trial:!0,trial_started_at:xt.toISOString(),trial_expires_at:ss.toISOString(),trial_claimed_at:xt.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",Wt);if(cs)throw cs;i({title:"Reverted to Trial",description:`User is now on a ${ze}-day free trial.`}),dr()}catch(xt){console.error("Error reverting to trial:",xt),i({title:"Error",description:xt.message||"Failed to revert to trial",variant:"destructive"})}finally{qh(!1)}}},Zm=async Wt=>{Jr(!0);try{const{data:ze}=await H.from("agent_assistant_assignments").select("id, assistant_id, permissions").eq("agent_id",Wt);if(ze&&ze.length>0){const ss=ze.map(tn=>tn.assistant_id),{data:cs}=await H.from("profiles").select("id, name, email").in("id",ss);Er(ze.map(tn=>{const Mn=cs==null?void 0:cs.find(Xn=>Xn.id===tn.assistant_id);return{id:tn.id,assistant_id:tn.assistant_id,assistant_name:(Mn==null?void 0:Mn.name)||"Unknown",assistant_email:(Mn==null?void 0:Mn.email)||"",permissions:tn.permissions||{}}}))}else Er([]);const{data:xt}=await H.from("agent_assistant_assignments").select("id, agent_id, permissions").eq("assistant_id",Wt);if(xt&&xt.length>0){const ss=xt.map(tn=>tn.agent_id),{data:cs}=await H.from("profiles").select("id, name, email").in("id",ss);Xt(xt.map(tn=>{const Mn=cs==null?void 0:cs.find(Xn=>Xn.id===tn.agent_id);return{id:tn.id,agent_id:tn.agent_id,agent_name:(Mn==null?void 0:Mn.name)||"Unknown",agent_email:(Mn==null?void 0:Mn.email)||"",permissions:tn.permissions||{}}}))}else Xt([])}catch(ze){console.error("Error loading assistant data:",ze)}finally{Jr(!1)}},mm=Wt=>{Be(Wt),Fe({name:Wt.name,email:Wt.email,brokerage_id:Wt.brokerage_id||"",phone:Wt.phone||""}),Ge(!0),Zm(Wt.id)},Qf=()=>{Be(null),Ge(!1),Fe({name:"",email:"",brokerage_id:"",phone:""})},mx=async()=>{Re&&(await ho(Re.id),Qf())},Xm=Wt=>{ft(ze=>{const xt=new Set(ze);return xt.has(Wt)?xt.delete(Wt):xt.add(Wt),xt})},Vh=()=>{if(it.size===bd.length&&bd.every(Wt=>it.has(Wt.id))){const Wt=new Set(it);bd.forEach(ze=>Wt.delete(ze.id)),ft(Wt)}else{const Wt=new Set(it);bd.forEach(ze=>Wt.add(ze.id)),ft(Wt)}},zp=()=>{ft(new Set)},Ag=async()=>{if(it.size===0)return;Ut(!0);let Wt=0,ze=0;try{const{data:{session:xt}}=await H.auth.getSession();for(const ss of it)try{(await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/resend-welcome-email",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${xt==null?void 0:xt.access_token}`},body:JSON.stringify({userId:ss})})).ok?Wt++:ze++}catch{ze++}i({title:"Bulk Email Complete",description:`Sent ${Wt} emails${ze>0?`, ${ze} failed`:""}`}),zp()}catch(xt){i({title:"Error",description:xt.message||"Failed to send emails",variant:"destructive"})}finally{Ut(!1)}},Jy=async()=>{if(it.size===0)return;Ut(!0);let Wt=0,ze=0;try{const{data:{session:xt}}=await H.auth.getSession();for(const ss of it)try{(await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/send-password-reset",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${xt==null?void 0:xt.access_token}`},body:JSON.stringify({userId:ss})})).ok?Wt++:ze++}catch{ze++}i({title:"Bulk Password Reset Complete",description:`Sent ${Wt} reset emails${ze>0?`, ${ze} failed`:""}`}),zp()}catch(xt){i({title:"Error",description:xt.message||"Failed to send password reset emails",variant:"destructive"})}finally{Ut(!1)}},Jc=async()=>{if(it.size===0)return;const Wt=l.filter(cs=>it.has(cs.id)).map(cs=>cs.name).slice(0,5).join(", "),ze=it.size>5?` and ${it.size-5} more`:"";if(!confirm(`Are you sure you want to delete ${it.size} users (${Wt}${ze})? This action cannot be undone.`))return;Ut(!0);let xt=0,ss=0;try{const{data:{session:cs}}=await H.auth.getSession();for(const tn of it)try{(await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/delete-user",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${cs==null?void 0:cs.access_token}`},body:JSON.stringify({userId:tn})})).ok?xt++:ss++}catch{ss++}i({title:"Bulk Delete Complete",description:`Deleted ${xt} users${ss>0?`, ${ss} failed`:""}`}),zp(),dr()}catch(cs){i({title:"Error",description:cs.message||"Failed to delete users",variant:"destructive"})}finally{Ut(!1)}},Nc=async()=>{Ms(!0);try{const{data:{session:Wt}}=await H.auth.getSession(),ze=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/ghl-phone-sync",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${Wt==null?void 0:Wt.access_token}`}});if(!ze.ok){const ss=await ze.json();throw new Error(ss.error||"Failed to sync phones")}const xt=await ze.json();i({title:"Phone Sync Complete",description:`Pulled ${xt.summary.pulledFromGHL} from GHL, pushed ${xt.summary.pushedToGHL} to GHL, ${xt.summary.alreadySynced} already synced`}),dr()}catch(Wt){i({title:"Error",description:Wt.message||"Failed to sync phones with GHL",variant:"destructive"})}finally{Ms(!1)}},Qm=async(Wt,ze)=>{Zs(Wt);try{const{data:{session:xt}}=await H.auth.getSession(),{data:ss}=await H.from("profiles").select("phone").eq("id",Wt).single(),cs=(ss==null?void 0:ss.phone)||"",tn=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/ghl-tag-sync",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${xt==null?void 0:xt.access_token}`},body:JSON.stringify({email:ze,action:"update",phone:cs||void 0})});if(!tn.ok){const Xn=await tn.json();throw new Error(Xn.error||"Failed to sync with GHL")}const Mn=await fetch(`https://services.leadconnectorhq.com/contacts/lookup?locationId=&email=${encodeURIComponent(ze)}`,{method:"GET",headers:{"Content-Type":"application/json"}});i({title:"Phone Synced",description:cs?`Phone ${cs} synced to GHL`:"Sync attempted - run bulk sync to pull phone from GHL"}),dr()}catch(xt){i({title:"Error",description:xt.message||"Failed to sync phone",variant:"destructive"})}finally{Zs(null)}},Rd=async Wt=>{await r(Wt)},Jm=()=>{if(it.size===0){i({title:"No members selected",description:"Please select members to export",variant:"destructive"});return}const Wt=l.filter(Xn=>it.has(Xn.id)),ze=["Name","Email","Phone","Brokerage","Roles","Status","Created At"],xt=Wt.map(Xn=>[Xn.name,Xn.email,Xn.phone||"",Xn.brokerage_name||"",Xn.roles.join("; "),Xn.claimed?"Claimed":"Unclaimed",new Date(Xn.created_at).toLocaleDateString()]),ss=[ze.join(","),...xt.map(Xn=>Xn.map(mr=>`"${(mr||"").replace(/"/g,'""')}"`).join(","))].join(` `),cs=new Blob([ss],{type:"text/csv"}),tn=URL.createObjectURL(cs),Mn=document.createElement("a");Mn.href=tn,Mn.download=`members-export-${new Date().toISOString().split("T")[0]}.csv`,Mn.click(),URL.revokeObjectURL(tn),i({title:"Export complete",description:`Exported ${Wt.length} member(s)`})},Hh=()=>{if(jf.length===0){i({title:"No members to export",description:"Adjust filters to include at least one member",variant:"destructive"});return}const Wt=["Name","Email","Phone","Brokerage","Roles","Status","Created At"],ze=jf.map(Xn=>[Xn.name,Xn.email,Xn.phone||"",Xn.brokerage_name||"",Xn.roles.join("; "),Xn.claimed?"Claimed":"Unclaimed",Xn.created_at?new Date(Xn.created_at).toLocaleDateString():""]),xt=[Wt.join(","),...ze.map(Xn=>Xn.map(mr=>`"${(mr||"").replace(/"/g,'""')}"`).join(","))].join(` `),ss=new Blob([xt],{type:"text/csv"}),cs=URL.createObjectURL(ss),tn=document.createElement("a"),Mn=ce!=="all"?`-last-${ce}days`:"";tn.href=cs,tn.download=`members-export${Mn}-${new Date().toISOString().split("T")[0]}.csv`,tn.click(),URL.revokeObjectURL(cs),i({title:"Export complete",description:`Exported ${jf.length} member(s)`})};return g?e.jsx(Qs,{title:"Members",children:e.jsx("div",{className:"flex items-center justify-center py-20",children:e.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})})}):e.jsxs(Qs,{title:"Members",children:[e.jsxs("div",{className:"space-y-6",children:[e.jsx(Uh,{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(xd,{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:Nc,disabled:es,children:[es?e.jsx(us,{className:"mr-2 h-4 w-4 animate-spin"}):e.jsx(ga,{className:"mr-2 h-4 w-4"}),e.jsx("span",{className:"hidden sm:inline",children:es?"Syncing...":"Sync Phones with GHL"}),e.jsx("span",{className:"sm:hidden",children:es?"Syncing...":"Sync GHL"})]}),e.jsxs(B,{size:"sm",variant:"outline",onClick:()=>ki(!0),children:[e.jsx(m5,{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(Bs,{open:A,onOpenChange:T,children:[e.jsx(Ao,{asChild:!0,children:e.jsxs(B,{size:"sm",children:[e.jsx(Yl,{className:"mr-2 h-4 w-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Add Member"}),e.jsx("span",{className:"sm:hidden",children:"Add"})]})}),e.jsxs(Fs,{children:[e.jsxs(qs,{children:[e.jsx($s,{children:"Create New User"}),e.jsx(Ar,{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(re,{htmlFor:"name",children:"Name"}),e.jsx(we,{id:"name",placeholder:"John Doe",value:b.name,onChange:Wt=>k({...b,name:Wt.target.value})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{htmlFor:"email",children:"Email"}),e.jsx(we,{id:"email",type:"email",placeholder:"john@example.com",value:b.email,onChange:Wt=>k({...b,email:Wt.target.value})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{htmlFor:"password",children:"Password"}),e.jsx(we,{id:"password",type:"password",placeholder:"Min 6 characters",value:b.password,onChange:Wt=>k({...b,password:Wt.target.value})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{htmlFor:"phone",children:"Phone (optional)"}),e.jsx(we,{id:"phone",type:"tel",placeholder:"555-123-4567",value:b.phone,onChange:Wt=>k({...b,phone:Wt.target.value})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs(re,{htmlFor:"brokerage",children:["Brokerage",b.role==="brokerage_manager"?" (required)":""]}),e.jsxs(Ns,{value:b.brokerage_id||"none",onValueChange:Wt=>k({...b,brokerage_id:Wt==="none"?"":Wt}),children:[e.jsx(ws,{id:"brokerage",children:e.jsx(ks,{placeholder:b.role==="brokerage_manager"?"Select brokerage":"Select brokerage (optional)"})}),e.jsxs(js,{children:[e.jsx(nt,{value:"none",children:"None"}),u.map(Wt=>e.jsx(nt,{value:Wt.id,children:Wt.name},Wt.id))]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{htmlFor:"role",children:"Role"}),e.jsxs(Ns,{value:b.role,onValueChange:Wt=>k({...b,role:Wt}),children:[e.jsx(ws,{id:"role",children:e.jsx(ks,{placeholder:"Select role"})}),e.jsxs(js,{children:[e.jsx(nt,{value:"user",children:"User"}),e.jsx(nt,{value:"moderator",children:"Moderator"}),e.jsx(nt,{value:"brokerage_manager",children:"Brokerage Manager"}),e.jsx(nt,{value:"admin",children:"Admin"})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{htmlFor:"trial_days",children:"Trial Period (optional)"}),e.jsxs(Ns,{value:b.trial_days||"none",onValueChange:Wt=>k({...b,trial_days:Wt==="none"?"":Wt}),children:[e.jsx(ws,{id:"trial_days",children:e.jsx(ks,{placeholder:"No trial (full access)"})}),e.jsxs(js,{children:[e.jsx(nt,{value:"none",children:"No trial (full access)"}),e.jsx(nt,{value:"7",children:"7-day trial"}),e.jsx(nt,{value:"30",children:"30-day trial"}),e.jsx(nt,{value:"60",children:"60-day trial"}),e.jsx(nt,{value:"90",children:"90-day trial"}),e.jsx(nt,{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(Cr,{children:[e.jsx(B,{variant:"outline",onClick:()=>T(!1),children:"Cancel"}),e.jsx(B,{onClick:Ta,disabled:x,children:x?"Creating...":"Create User"})]})]})]})]})]}),e.jsxs(ya,{defaultValue:new URLSearchParams(window.location.search).get("tab")||"members",className:"space-y-6",children:[e.jsxs(va,{children:[e.jsx(ls,{value:"members",children:"Members"}),e.jsx(ls,{value:"brokerages",children:"Brokerages"}),e.jsx(ls,{value:"teams",children:"Teams"}),e.jsx(ls,{value:"trials",children:"Trial Users"}),e.jsx(ls,{value:"access",children:"Access Matrix"}),e.jsx(ls,{value:"celebrations",children:"Celebrations"}),e.jsx(ls,{value:"deletions",children:"Deletion Log"})]}),e.jsxs(_s,{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(Gr,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(we,{placeholder:"Search members...",value:P,onChange:Wt=>n0(Wt.target.value),className:"pl-10 h-9"})]}),e.jsxs(Ns,{value:V,onValueChange:Wt=>Km(W,Wt),children:[e.jsx(ws,{className:"w-[130px] h-9",children:e.jsx(ks,{})}),e.jsxs(js,{children:[e.jsx(nt,{value:"all",children:"All Status"}),e.jsx(nt,{value:"claimed",children:"Active"}),e.jsx(nt,{value:"unclaimed",children:"Pending"})]})]}),e.jsxs(Ns,{value:G,onValueChange:Wt=>Km(X,Wt),children:[e.jsx(ws,{className:"w-[130px] h-9",children:e.jsx(ks,{})}),e.jsxs(js,{children:[e.jsx(nt,{value:"all",children:"All Roles"}),e.jsx(nt,{value:"admin",children:"Admin"}),e.jsx(nt,{value:"brokerage_manager",children:"Manager"}),e.jsx(nt,{value:"assistant",children:"Assistant"}),e.jsx(nt,{value:"user",children:"User"})]})]}),e.jsxs(Ns,{value:te,onValueChange:Wt=>Km(ne,Wt),children:[e.jsx(ws,{className:"w-[130px] h-9",children:e.jsx(ks,{})}),e.jsxs(js,{children:[e.jsx(nt,{value:"all",children:"All Users"}),e.jsx(nt,{value:"trial",children:"Trial Only"}),e.jsx(nt,{value:"non-trial",children:"Full Only"})]})]}),e.jsxs(Ns,{value:me,onValueChange:Wt=>Km(ue,Wt),children:[e.jsx(ws,{className:"w-[150px] h-9",children:e.jsx(ks,{})}),e.jsxs(js,{children:[e.jsx(nt,{value:"all",children:"All Brokerages"}),e.jsx(nt,{value:"none",children:"No Brokerage"}),u.map(Wt=>e.jsx(nt,{value:Wt.id,children:Wt.name},Wt.id))]})]}),e.jsxs(Ns,{value:ce,onValueChange:Wt=>Km(ae,Wt),children:[e.jsx(ws,{className:"w-[150px] h-9",children:e.jsx(ks,{})}),e.jsxs(js,{children:[e.jsx(nt,{value:"all",children:"Any Join Date"}),e.jsx(nt,{value:"30",children:"Joined Last 30 Days"}),e.jsx(nt,{value:"60",children:"Joined Last 60 Days"}),e.jsx(nt,{value:"90",children:"Joined Last 90 Days"})]})]}),e.jsxs(B,{size:"sm",variant:"outline",className:"h-9",onClick:Hh,title:"Export currently filtered members to CSV",children:[e.jsx(oi,{className:"h-4 w-4 mr-1"}),"Export Filtered"]}),(P||V!=="all"||G!=="all"||te!=="all"||me!=="all"||ce!=="all")&&e.jsxs(B,{variant:"ghost",size:"sm",className:"h-9",onClick:()=>{I(""),W("all"),X("all"),ne("all"),ue("all"),ae("all"),L(1)},children:[e.jsx(hr,{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:Cg?`Showing all ${hm} members`:`Showing ${Bl+1}-${Math.min(Wm,hm)} of ${hm} members`}),e.jsxs(Ns,{value:z.toString(),onValueChange:Wt=>kb(Number(Wt)),children:[e.jsx(ws,{className:"h-9 w-[110px]",children:e.jsx(ks,{})}),e.jsxs(js,{children:[e.jsx(nt,{value:"50",children:"50 / page"}),e.jsx(nt,{value:"100",children:"100 / page"}),e.jsx(nt,{value:"250",children:"250 / page"}),e.jsx(nt,{value:"0",children:"All"})]})]})]})]}),it.size>0&&e.jsxs("div",{className:"flex flex-col gap-2 p-3 bg-primary/10 border border-primary/20 rounded-lg",children:[bd.length>0&&bd.every(Wt=>it.has(Wt.id))&&Gm.length>it.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 ",it.size," on this page are selected."]}),e.jsxs(B,{size:"sm",variant:"link",className:"h-auto p-0 text-primary",onClick:()=>ft(new Set(Gm.map(Wt=>Wt.id))),children:["Select all ",Gm.length," filtered members"]})]}),Gm.length>0&&it.size===Gm.length&&e.jsxs("div",{className:"px-1 text-sm text-muted-foreground",children:["All ",Gm.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(d4,{className:"h-4 w-4 text-primary"}),e.jsxs("span",{className:"text-sm font-medium",children:[it.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:Ag,disabled:kt,children:[kt?e.jsx(us,{className:"h-4 w-4 animate-spin mr-1"}):e.jsx(mn,{className:"h-4 w-4 mr-1"}),e.jsx("span",{className:"hidden sm:inline",children:"Resend Invite"}),e.jsx("span",{className:"sm:hidden",children:"Invite"})]}),e.jsxs(B,{size:"sm",variant:"outline",onClick:Jy,disabled:kt,children:[kt?e.jsx(us,{className:"h-4 w-4 animate-spin mr-1"}):e.jsx(nb,{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:()=>xe(!0),disabled:kt,className:"bg-primary/5 border-primary/30 text-primary hover:bg-primary/10",children:[e.jsx(W2,{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:Jm,children:[e.jsx(oi,{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:Jc,disabled:kt,children:[kt?e.jsx(us,{className:"h-4 w-4 animate-spin mr-1"}):e.jsx(qn,{className:"h-4 w-4 mr-1"}),e.jsx("span",{className:"hidden sm:inline",children:"Delete"}),e.jsx("span",{className:"sm:hidden",children:"Del"})]}),e.jsx(B,{size:"sm",variant:"ghost",onClick:zp,disabled:kt,children:e.jsx(hr,{className:"h-4 w-4"})})]})]})]}),e.jsx("div",{className:"border rounded-lg bg-card overflow-hidden",children:e.jsxs(Oa,{children:[e.jsx(Fa,{children:e.jsxs(un,{className:"bg-muted/30 hover:bg-muted/30",children:[e.jsx(Mt,{className:"w-[50px]",children:e.jsx(Bi,{checked:bd.length>0&&bd.every(Wt=>it.has(Wt.id)),onCheckedChange:Vh,"aria-label":"Select all on page"})}),e.jsx(Hu,{sortKey:"name",currentSortKey:cu,currentDirection:Sg,onSort:Eo,children:"Name"}),e.jsx(Hu,{sortKey:"brokerage",currentSortKey:cu,currentDirection:Sg,onSort:Eo,children:"Brokerage"}),e.jsx(Hu,{sortKey:"status",currentSortKey:cu,currentDirection:Sg,onSort:Eo,children:"Status"}),e.jsx(Hu,{sortKey:"role",currentSortKey:cu,currentDirection:Sg,onSort:Eo,children:"Role"}),e.jsx(Hu,{sortKey:"last_login",currentSortKey:cu,currentDirection:Sg,onSort:Eo,children:"Last Login"}),e.jsx(Hu,{sortKey:"created_at",currentSortKey:cu,currentDirection:Sg,onSort:Eo,children:"Member Since"}),e.jsx(Mt,{className:"w-[100px]"})]})}),e.jsx(za,{children:bd.length===0?e.jsx(un,{children:e.jsx(gt,{colSpan:8,className:"text-center py-12 text-muted-foreground",children:"No members found"})}):bd.map(Wt=>e.jsxs(un,{className:`hover:bg-muted/30 ${it.has(Wt.id)?"bg-primary/5":""}`,children:[e.jsx(gt,{children:e.jsx(Bi,{checked:it.has(Wt.id),onCheckedChange:()=>Xm(Wt.id),"aria-label":`Select ${Wt.name}`})}),e.jsx(gt,{children:e.jsxs("div",{children:[e.jsx("button",{onClick:()=>mm(Wt),className:"text-primary hover:underline font-medium text-left",children:Wt.name}),e.jsx("div",{className:"text-xs text-muted-foreground",children:Wt.email})]})}),e.jsx(gt,{className:"text-muted-foreground",children:Wt.brokerage_name||"—"}),e.jsx(gt,{children:e.jsx("div",{className:"flex flex-col",children:(()=>{const ze=Wt.trial_expires_at||Wt.subscription_end_date;if((Wt.is_trial||Wt.subscription_status==="trialing")&&ze){const ss=Math.ceil((new Date(ze).getTime()-Date.now())/864e5),cs=ss<=0,tn=ss<=3;return e.jsx(We,{variant:"outline",className:Ot("w-fit",cs?"border-destructive text-destructive":tn?"border-amber-500 text-amber-600":"border-violet-300 text-violet-700 bg-violet-50"),children:cs?"Trial Expired":`Trial · ${ss}d left`})}return e.jsx(We,{variant:Wt.claimed?"default":"secondary",className:Wt.claimed?"bg-primary text-primary-foreground w-fit":"w-fit",children:Wt.claimed?"Active":"Pending"})})()})}),e.jsx(gt,{children:e.jsxs("div",{className:"flex flex-col",children:[Wt.roles.length>0?e.jsx("span",{className:"text-sm capitalize",children:Wt.roles[0]}):e.jsx("span",{className:"text-muted-foreground",children:"—"}),Wt.roles.includes("assistant")&&Or[Wt.id]&&e.jsxs("span",{className:"text-xs text-muted-foreground",children:["→ ",Or[Wt.id].agent_name||Or[Wt.id].agent_email]})]})}),e.jsx(gt,{className:"text-muted-foreground",children:Wt.last_sign_in_at?new Date(Wt.last_sign_in_at).toLocaleDateString():"—"}),e.jsx(gt,{className:"text-muted-foreground",children:Wt.created_at?new Date(Wt.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:()=>{Kr(Wt),gn(!0)},title:"Send celebration",children:e.jsx(uf,{className:"h-4 w-4"})}),e.jsx(B,{size:"icon",variant:"ghost",className:"h-8 w-8",onClick:()=>mm(Wt),title:"Edit member",children:e.jsx(Ja,{className:"h-4 w-4"})}),e.jsx(B,{size:"icon",variant:"ghost",className:"h-8 w-8",onClick:()=>Qm(Wt.id,Wt.email),disabled:bs===Wt.id,title:"Sync phone with GHL",children:bs===Wt.id?e.jsx(us,{className:"h-4 w-4 animate-spin"}):e.jsx(ga,{className:"h-4 w-4"})}),e.jsx(B,{size:"icon",variant:"ghost",className:"h-8 w-8",onClick:()=>oa(Wt.id),title:"Resend welcome email",children:e.jsx(mn,{className:"h-4 w-4"})}),e.jsx(B,{size:"icon",variant:"ghost",className:"h-8 w-8",onClick:()=>Ha(Wt.email,Wt.name),title:"Send password reset",children:e.jsx(TT,{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:()=>Rd(Wt.id),disabled:a||Wt.id===(t==null?void 0:t.id),title:Wt.id===(t==null?void 0:t.id)?"Cannot impersonate yourself":`Login as ${Wt.name}`,children:a?e.jsx(us,{className:"h-4 w-4 animate-spin"}):e.jsx(gD,{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:()=>$i(Wt.id,Wt.name),title:"Delete user",children:e.jsx(qn,{className:"h-4 w-4"})})]})})]},Wt.id))})]})}),wh>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 ",wh]}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(B,{variant:"outline",size:"sm",onClick:()=>L(1),disabled:M===1,children:"First"}),e.jsx(B,{variant:"outline",size:"icon",className:"h-8 w-8",onClick:()=>L(Wt=>Math.max(1,Wt-1)),disabled:M===1,children:e.jsx(Fc,{className:"h-4 w-4"})}),e.jsx("div",{className:"flex items-center gap-1",children:Array.from({length:Math.min(5,wh)},(Wt,ze)=>{let xt;return wh<=5||M<=3?xt=ze+1:M>=wh-2?xt=wh-4+ze:xt=M-2+ze,e.jsx(B,{variant:M===xt?"default":"outline",size:"sm",className:"h-8 w-8 p-0",onClick:()=>L(xt),children:xt},xt)})}),e.jsx(B,{variant:"outline",size:"icon",className:"h-8 w-8",onClick:()=>L(Wt=>Math.min(wh,Wt+1)),disabled:M===wh,children:e.jsx(Qa,{className:"h-4 w-4"})}),e.jsx(B,{variant:"outline",size:"sm",onClick:()=>L(wh),disabled:M===wh,children:"Last"})]})]})]}),e.jsx(Bs,{open:Ne,onOpenChange:Ge,children:e.jsxs(Fs,{className:"max-w-2xl max-h-[90vh] overflow-y-auto",children:[e.jsxs(qs,{children:[e.jsx($s,{children:"Edit Member"}),e.jsx(Ar,{children:"Update member details, roles, and app access"})]}),Re&&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(re,{htmlFor:"edit-name",children:"Name"}),e.jsx(we,{id:"edit-name",value:Ce.name,onChange:Wt=>Fe({...Ce,name:Wt.target.value}),maxLength:100})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{htmlFor:"edit-email",children:"Email"}),e.jsx(we,{id:"edit-email",type:"email",value:Ce.email,onChange:Wt=>Fe({...Ce,email:Wt.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(re,{htmlFor:"edit-phone",children:"Phone"}),e.jsx(we,{id:"edit-phone",type:"tel",value:Ce.phone,onChange:Wt=>Fe({...Ce,phone:Wt.target.value}),placeholder:"555-123-4567"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{htmlFor:"edit-brokerage",children:"Brokerage"}),e.jsxs(Ns,{value:Ce.brokerage_id||"none",onValueChange:Wt=>Fe({...Ce,brokerage_id:Wt==="none"?"":Wt}),children:[e.jsx(ws,{id:"edit-brokerage",children:e.jsx(ks,{placeholder:"Select brokerage"})}),e.jsxs(js,{children:[e.jsx(nt,{value:"none",children:"None"}),u.map(Wt=>e.jsx(nt,{value:Wt.id,children:Wt.name},Wt.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:[Re.roles.map(Wt=>e.jsxs(We,{variant:"default",className:"gap-1",children:[e.jsx(mf,{className:"h-3 w-3"}),Wt,Wt==="brokerage_manager"?e.jsx("span",{className:"text-xs text-muted-foreground ml-1",children:"(manage in Brokerages tab)"}):e.jsx("button",{onClick:()=>Wn(Re.id,Wt,"remove"),className:"ml-1 rounded-full hover:bg-destructive/20",title:"Remove role",children:e.jsx(hr,{className:"h-3 w-3"})})]},Wt)),Re.roles.length===0&&e.jsx("span",{className:"text-sm text-muted-foreground",children:"No roles assigned"})]}),e.jsxs(Ns,{onValueChange:Wt=>Wn(Re.id,Wt,"add"),children:[e.jsx(ws,{className:"w-[200px]",children:e.jsx(ks,{placeholder:"Add role..."})}),e.jsxs(js,{children:[!Re.roles.includes("admin")&&e.jsx(nt,{value:"admin",children:"Admin"}),!Re.roles.includes("user")&&e.jsx(nt,{value:"user",children:"User"})]})]}),!Re.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"})]}),(ca.length>0||qr.length>0||Re.roles.includes("assistant"))&&e.jsxs("div",{className:"space-y-3",children:[e.jsxs("h3",{className:"text-sm font-semibold flex items-center gap-2",children:[e.jsx(Yn,{className:"h-4 w-4"}),"Assistant Relationships"]}),Gn?e.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[e.jsx(us,{className:"h-4 w-4 animate-spin"}),"Loading..."]}):e.jsxs("div",{className:"space-y-3",children:[ca.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:"}),ca.map(Wt=>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:Wt.assistant_name}),e.jsx(We,{variant:"outline",className:"text-xs",children:"Assistant"})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:Wt.assistant_email}),e.jsx("div",{className:"flex flex-wrap gap-1 mt-1",children:Object.entries(Wt.permissions).filter(([,ze])=>ze).map(([ze])=>e.jsx(We,{variant:"secondary",className:"text-[10px] capitalize",children:ze},ze))})]},Wt.id))]}),qr.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:"}),qr.map(Wt=>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:Wt.agent_name}),e.jsx(We,{variant:"outline",className:"text-xs",children:"Agent"})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:Wt.agent_email}),e.jsx("div",{className:"flex flex-wrap gap-1 mt-1",children:Object.entries(Wt.permissions).filter(([,ze])=>ze).map(([ze])=>e.jsx(We,{variant:"secondary",className:"text-[10px] capitalize",children:ze},ze))})]},Wt.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(Wt=>{const ze=Ra(Re.tags,Wt.required_tags),xt=`${Re.id}-${Wt.id}`,ss=Ae===xt,cs=Wt.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:Wt.icon}),e.jsxs("div",{children:[e.jsx("div",{className:"font-medium text-sm",children:Wt.name}),cs&&e.jsx("span",{className:"text-xs text-muted-foreground",children:"Available to all members"})]})]}),e.jsx("div",{className:"flex items-center gap-2",children:ss?e.jsx(us,{className:"h-4 w-4 animate-spin text-muted-foreground"}):cs?e.jsx(We,{variant:"secondary",className:"text-xs",children:"Always On"}):e.jsx(zn,{checked:ze,onCheckedChange:()=>mo(Re.id,Wt,ze)})})]},Wt.id)})})]}),(Re.is_trial||Re.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(Xr,{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:[Re.trial_expires_at&&e.jsx(_ot,{expiresAt:Re.trial_expires_at}),!Re.trial_expires_at&&Re.subscription_status==="trialing"&&Re.subscription_end_date&&e.jsx(_ot,{expiresAt:Re.subscription_end_date})]}),(Re.trial_expires_at||Re.subscription_end_date)&&e.jsxs("span",{className:"text-sm text-muted-foreground",children:["Expires: ",new Date(Re.trial_expires_at||Re.subscription_end_date).toLocaleDateString()]})]}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsxs(B,{size:"sm",variant:"outline",onClick:()=>_i(Re.id,7),disabled:ve,children:[e.jsx(Pv,{className:"h-4 w-4 mr-1"}),"+7 Days"]}),e.jsxs(B,{size:"sm",variant:"outline",onClick:()=>_i(Re.id,14),disabled:ve,children:[e.jsx(Pv,{className:"h-4 w-4 mr-1"}),"+14 Days"]}),e.jsxs(B,{size:"sm",variant:"outline",onClick:()=>_i(Re.id,30),disabled:ve,children:[e.jsx(Pv,{className:"h-4 w-4 mr-1"}),"+30 Days"]}),e.jsxs(B,{size:"sm",variant:"default",onClick:()=>Ym(Re.id),disabled:be,className:"bg-green-600 hover:bg-green-700",children:[e.jsx(tN,{className:"h-4 w-4 mr-1"}),"Convert to Full Account"]})]}),Re.trial_started_at&&e.jsxs("div",{className:"mt-3 text-xs text-muted-foreground",children:["Trial started: ",new Date(Re.trial_started_at).toLocaleDateString(),Re.trial_claimed_at&&e.jsxs("span",{children:[" • Claimed: ",new Date(Re.trial_claimed_at).toLocaleDateString()]})]})]})]}),!(Re.is_trial||Re.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(Xr,{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(Wt=>e.jsxs(B,{size:"sm",variant:"outline",onClick:()=>Fp(Re.id,Wt),disabled:iy,children:[e.jsx(Pv,{className:"h-4 w-4 mr-1"}),Wt,"-day trial"]},Wt))})]})]}),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:[Re.email_confirmed_at&&e.jsxs("div",{children:["Claimed: ",new Date(Re.email_confirmed_at).toLocaleString()]}),Re.last_sign_in_at&&e.jsxs("div",{children:["Last login: ",new Date(Re.last_sign_in_at).toLocaleString()]}),e.jsxs("div",{children:["Created: ",new Date(Re.created_at).toLocaleString()]})]})]})]}),e.jsxs(Cr,{children:[e.jsx(B,{variant:"outline",onClick:Qf,children:"Cancel"}),e.jsx(B,{onClick:mx,children:"Save Changes"})]})]})}),e.jsxs(_s,{value:"access",children:[c.length===0?e.jsx(_e,{children:e.jsxs(De,{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(_e,{children:[e.jsxs(zt,{className:"flex flex-col sm:flex-row sm:items-center justify-between gap-4 space-y-0",children:[e.jsxs("div",{children:[e.jsx(qt,{children:"Member Access Matrix"}),e.jsx(_r,{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(Gr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(we,{placeholder:"Search agents by name or email...",value:P,onChange:Wt=>{I(Wt.target.value),L(1)},className:"pl-9"})]})]}),e.jsxs(De,{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(Wt=>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:Wt.icon}),e.jsx("span",{className:"text-sm",children:Wt.name})]})},Wt.id))]})}),e.jsxs("tbody",{children:[bd.map(Wt=>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:Wt.name}),e.jsx("div",{className:"text-sm text-muted-foreground",children:Wt.email})]})}),c.map(ze=>{const xt=Ra(Wt.tags,ze.required_tags),ss=`${Wt.id}-${ze.id}`,cs=Ae===ss;return e.jsx("td",{className:"p-4 text-center",children:e.jsx("div",{className:"flex items-center justify-center",children:cs?e.jsx(us,{className:"h-5 w-5 animate-spin text-muted-foreground"}):e.jsx(zn,{checked:xt,onCheckedChange:()=>mo(Wt.id,ze,xt),disabled:ze.required_tags.length===0})})},ze.id)})]},Wt.id)),bd.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"})})]})]})}),wh>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 ",Bl+1,"-",Math.min(Wm,hm)," of ",hm," • Page ",M," of ",wh]}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(B,{variant:"outline",size:"icon",className:"h-8 w-8",onClick:()=>L(Wt=>Math.max(1,Wt-1)),disabled:M===1,children:e.jsx(Fc,{className:"h-4 w-4"})}),e.jsx(B,{variant:"outline",size:"icon",className:"h-8 w-8",onClick:()=>L(Wt=>Math.min(wh,Wt+1)),disabled:M===wh,children:e.jsx(Qa,{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(_s,{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(Gr,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(we,{placeholder:"Search brokerages...",value:ia,onChange:Wt=>vr(Wt.target.value),className:"pl-10"})]}),e.jsxs("span",{className:"text-sm text-muted-foreground whitespace-nowrap",children:[u.filter(Wt=>Wt.name.toLowerCase().includes(ia.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 Wt=[];for(const Mn of u){const Xn=m[Mn.id]??[];for(const mr of Xn){const Ba=l.find(Ki=>Ki.id===mr);if(Ba){const Ki=(Ba.name||"").trim().split(/\s+/),Ui=Ki[0]||"",tl=Ki.slice(1).join(" ")||"";Wt.push({firstName:Ui,lastName:tl,email:Ba.email,brokerageName:Mn.name})}}}if(Wt.length===0){i({title:"No managers found to export"});return}const xt=[["First Name","Last Name","Email","Brokerage Name"].join(","),...Wt.map(Mn=>[Mn.firstName,Mn.lastName,Mn.email,Mn.brokerageName].map(Xn=>`"${(Xn||"").replace(/"/g,'""')}"`).join(","))].join(` `),ss=new Blob([xt],{type:"text/csv"}),cs=URL.createObjectURL(ss),tn=document.createElement("a");tn.href=cs,tn.download=`brokerage-managers-${new Date().toISOString().slice(0,10)}.csv`,tn.click(),URL.revokeObjectURL(cs),i({title:`Exported ${Wt.length} managers`})},children:[e.jsx(oi,{className:"mr-2 h-4 w-4"}),"Export Managers"]}),e.jsxs(Bs,{open:$e,onOpenChange:Ye,children:[e.jsx(Ao,{asChild:!0,children:e.jsxs(B,{size:"sm",children:[e.jsx(Ti,{className:"mr-2 h-4 w-4"}),"Add Brokerage"]})}),e.jsxs(Fs,{children:[e.jsxs(qs,{children:[e.jsx($s,{children:"Create New Brokerage"}),e.jsx(Ar,{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(re,{htmlFor:"brokerage-name",children:"Brokerage Name"}),e.jsx(we,{id:"brokerage-name",placeholder:"Enter brokerage name",value:Je,onChange:Wt=>Ke(Wt.target.value),maxLength:100})]})}),e.jsxs(Cr,{children:[e.jsx(B,{variant:"outline",onClick:()=>Ye(!1),children:"Cancel"}),e.jsx(B,{onClick:Ho,disabled:st,children:st?"Creating...":"Create Brokerage"})]})]})]})]})]}),e.jsx("div",{className:"border rounded-lg bg-card overflow-hidden",children:e.jsxs(Oa,{children:[e.jsx(Fa,{children:e.jsxs(un,{className:"bg-muted/30 hover:bg-muted/30",children:[e.jsx(Mt,{className:"font-semibold",children:"Brokerage Name"}),e.jsx(Mt,{className:"font-semibold",children:"Manager(s)"}),e.jsx(Mt,{className:"font-semibold",children:"Agents"}),e.jsx(Mt,{className:"w-[150px]"})]})}),e.jsx(za,{children:(()=>{const Wt=u.filter(ze=>ze.name.toLowerCase().includes(ia.toLowerCase()));return Wt.length===0?e.jsx(un,{children:e.jsx(gt,{colSpan:4,className:"text-center py-12 text-muted-foreground",children:ia?"No brokerages match your search":"No brokerages found"})}):Wt.map(ze=>{const xt=l.filter(Mn=>Mn.brokerage_id===ze.id),cs=(m[ze.id]??[]).map(Mn=>l.find(Xn=>Xn.id===Mn)).filter(Boolean),tn=xt.length;return e.jsxs(un,{className:"hover:bg-muted/30",children:[e.jsx(gt,{children:e.jsx("button",{onClick:()=>No(ze),className:"text-primary hover:underline font-medium",children:ze.name})}),e.jsx(gt,{children:cs.length>0?e.jsx("div",{className:"flex flex-wrap gap-1",children:cs.map(Mn=>e.jsx(We,{variant:"secondary",className:"text-xs",children:Mn.name},Mn.id))}):e.jsx("span",{className:"text-muted-foreground text-sm",children:"No manager"})}),e.jsxs(gt,{children:[tn," member",tn!==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:()=>Eu(ze),children:[e.jsx(Yn,{className:"h-4 w-4 mr-1"}),"Manage"]}),e.jsx(B,{size:"icon",variant:"ghost",className:"h-8 w-8",onClick:()=>No(ze),title:"Edit brokerage",children:e.jsx(Ja,{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:()=>Vm(ze),title:"Delete brokerage",children:e.jsx(qn,{className:"h-4 w-4"})})]})})]},ze.id)})})()})]})}),e.jsx(Bs,{open:Ze,onOpenChange:ht,children:e.jsxs(Fs,{className:"max-w-lg",children:[e.jsxs(qs,{children:[e.jsx($s,{children:"Edit Brokerage"}),e.jsx(Ar,{children:"Update brokerage details and manage managers"})]}),Bt&&e.jsxs("div",{className:"space-y-6 py-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{htmlFor:"edit-brokerage-name",children:"Brokerage Name"}),e.jsx(we,{id:"edit-brokerage-name",value:Yt,onChange:Wt=>Kt(Wt.target.value),maxLength:100})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsx(re,{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 ze=(m[Bt.id]??[]).map(xt=>l.find(ss=>ss.id===xt)).filter(Boolean);return ze.length===0?e.jsx("span",{className:"text-sm text-muted-foreground",children:"No managers assigned"}):ze.map(xt=>e.jsxs(We,{variant:"default",className:"gap-1",children:[e.jsx(mf,{className:"h-3 w-3"}),xt.name,e.jsx("button",{onClick:()=>Wn(xt.id,"brokerage_manager","remove",Bt.id),className:"ml-1 rounded-full hover:bg-destructive/20",title:"Remove manager from this brokerage",children:e.jsx(hr,{className:"h-3 w-3"})})]},xt.id))})()}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{className:"text-sm text-muted-foreground",children:"Assign manager from existing members:"}),e.jsxs(rc,{open:Nr,onOpenChange:rn,children:[e.jsx(ac,{asChild:!0,children:e.jsxs(B,{variant:"outline",role:"combobox","aria-expanded":Nr,className:"w-full justify-between",children:["Search for a member...",e.jsx(Gr,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]})}),e.jsx(Zl,{className:"w-full p-0",align:"start",children:e.jsxs(db,{children:[e.jsx(ub,{placeholder:"Search by name or email..."}),e.jsxs(hb,{className:"max-h-[200px]",children:[e.jsx(mb,{children:"No members found."}),e.jsx(pb,{children:(()=>{const Wt=new Set(m[Bt.id]??[]);return l.filter(ze=>!Wt.has(ze.id)&&(n||ze.brokerage_id===Bt.id)).map(ze=>e.jsxs(Ry,{value:`${ze.name} ${ze.email}`,onSelect:()=>{Tu(ze.id,Bt.id),rn(!1)},children:[ze.name," (",ze.email,")"]},ze.id))})()})]})]})})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{children:"Members in this Brokerage"}),e.jsx("div",{className:"max-h-32 overflow-y-auto border rounded p-2",children:l.filter(Wt=>Wt.brokerage_id===Bt.id).length===0?e.jsx("span",{className:"text-sm text-muted-foreground",children:"No members"}):l.filter(Wt=>Wt.brokerage_id===Bt.id).map(Wt=>e.jsxs("div",{className:"text-sm py-1 flex items-center justify-between",children:[e.jsx("span",{children:Wt.name}),Wt.roles.includes("brokerage_manager")&&e.jsx(We,{variant:"outline",className:"text-xs",children:"Manager"})]},Wt.id))})]})]}),e.jsxs(Cr,{children:[e.jsx(B,{variant:"outline",onClick:Go,children:"Cancel"}),e.jsx(B,{onClick:Dd,disabled:Xs,children:Xs?"Saving...":"Save Changes"})]})]})}),e.jsx(Bs,{open:Vt,onOpenChange:At,children:e.jsxs(Fs,{children:[e.jsxs(qs,{children:[e.jsx($s,{className:"text-destructive",children:"Delete Brokerage"}),e.jsxs(Ar,{children:['Are you sure you want to delete "',Os==null?void 0:Os.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 "',Os==null?void 0:Os.name,'"']}),e.jsxs("li",{children:["All ",l.filter(Wt=>Wt.brokerage_id===(Os==null?void 0:Os.id)).length," member(s) assigned to this brokerage"]}),e.jsx("li",{children:"All their data, roles, and access"})]})]})}),e.jsxs(Cr,{children:[e.jsx(B,{variant:"outline",onClick:()=>At(!1),children:"Cancel"}),e.jsx(B,{variant:"destructive",onClick:Uc,disabled:ms,children:ms?"Deleting...":"Yes, Delete Brokerage"})]})]})}),e.jsx(Bs,{open:It,onOpenChange:Ds,children:e.jsxs(Fs,{className:"max-w-4xl max-h-[85vh] overflow-hidden flex flex-col",children:[e.jsxs(qs,{children:[e.jsxs($s,{className:"flex items-center gap-2",children:[e.jsx(Ti,{className:"h-5 w-5"}),"Manage ",As==null?void 0:As.name]}),e.jsx(Ar,{children:"Add, remove, or manage users in this brokerage"})]}),As&&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(Gr,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(we,{placeholder:"Search members...",value:Rs,onChange:Wt=>en(Wt.target.value),className:"pl-10 h-9"})]}),e.jsxs(Bs,{open:Rn,onOpenChange:Bn,children:[e.jsx(Ao,{asChild:!0,children:e.jsxs(B,{size:"sm",children:[e.jsx(Yl,{className:"h-4 w-4 mr-1"}),"Add New Agent"]})}),e.jsxs(Fs,{children:[e.jsxs(qs,{children:[e.jsx($s,{children:"Add New Agent"}),e.jsxs(Ar,{children:["Create a new agent for ",As.name]})]}),e.jsxs("div",{className:"space-y-4 py-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{htmlFor:"agent-name",children:"Name"}),e.jsx(we,{id:"agent-name",placeholder:"John Doe",value:Dn.name,onChange:Wt=>Jn({...Dn,name:Wt.target.value})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{htmlFor:"agent-email",children:"Email"}),e.jsx(we,{id:"agent-email",type:"email",placeholder:"john@example.com",value:Dn.email,onChange:Wt=>Jn({...Dn,email:Wt.target.value})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{htmlFor:"agent-password",children:"Password"}),e.jsx(we,{id:"agent-password",type:"password",placeholder:"Min 6 characters",value:Dn.password,onChange:Wt=>Jn({...Dn,password:Wt.target.value})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{htmlFor:"agent-phone",children:"Phone (optional)"}),e.jsx(we,{id:"agent-phone",type:"tel",placeholder:"555-123-4567",value:Dn.phone,onChange:Wt=>Jn({...Dn,phone:Wt.target.value})})]})]}),e.jsxs(Cr,{children:[e.jsx(B,{variant:"outline",onClick:()=>Bn(!1),children:"Cancel"}),e.jsx(B,{onClick:Nb,disabled:ua,children:ua?"Creating...":"Create Agent"})]})]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(re,{className:"text-sm text-muted-foreground whitespace-nowrap",children:"Add existing user:"}),e.jsxs(rc,{open:Zn,onOpenChange:sa,children:[e.jsx(ac,{asChild:!0,children:e.jsxs(B,{variant:"outline",role:"combobox","aria-expanded":Zn,className:"w-[300px] justify-between",children:["Select a user to add...",e.jsx(Gr,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]})}),e.jsx(Zl,{className:"w-[300px] p-0",align:"start",children:e.jsxs(db,{children:[e.jsx(ub,{placeholder:"Search users...",value:xs,onValueChange:Ve}),e.jsxs(hb,{children:[e.jsx(mb,{children:"No users found."}),e.jsx(pb,{children:wf(As.id).filter(Wt=>xs===""||Wt.name.toLowerCase().includes(xs.toLowerCase())||Wt.email.toLowerCase().includes(xs.toLowerCase())).map(Wt=>e.jsxs(Ry,{value:`${Wt.name} ${Wt.email}`,onSelect:()=>{s0(Wt.id,As.id),sa(!1),Ve("")},children:[Wt.name," (",Wt.email,")"]},Wt.id))})]})]})})]})]}),e.jsx("div",{className:"flex-1 overflow-auto border rounded-lg",children:e.jsxs(Oa,{children:[e.jsx(Fa,{children:e.jsxs(un,{className:"bg-muted/30 hover:bg-muted/30",children:[e.jsx(Mt,{className:"font-semibold",children:"Name"}),e.jsx(Mt,{className:"font-semibold",children:"Email"}),e.jsx(Mt,{className:"font-semibold",children:"Status"}),e.jsx(Mt,{className:"font-semibold",children:"Role"}),e.jsx(Mt,{className:"w-[120px]"})]})}),e.jsx(za,{children:ay(As.id).length===0?e.jsx(un,{children:e.jsx(gt,{colSpan:5,className:"text-center py-8 text-muted-foreground",children:Rs?"No matching members found":"No members in this brokerage"})}):ay(As.id).map(Wt=>e.jsxs(un,{className:"hover:bg-muted/30",children:[e.jsx(gt,{className:"font-medium",children:Wt.name}),e.jsx(gt,{className:"text-muted-foreground",children:Wt.email}),e.jsx(gt,{children:Wt.claimed?e.jsx(We,{variant:"default",className:"bg-green-500/10 text-green-600 hover:bg-green-500/20",children:"Active"}):e.jsx(We,{variant:"secondary",children:"Pending"})}),e.jsx(gt,{children:Wt.roles.includes("brokerage_manager")?e.jsxs(We,{variant:"outline",className:"gap-1",children:[e.jsx(mf,{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:[!Wt.claimed&&e.jsx(B,{size:"icon",variant:"ghost",className:"h-8 w-8",onClick:()=>oa(Wt.id),title:"Resend welcome email",children:e.jsx(mn,{className:"h-4 w-4"})}),e.jsx(B,{size:"icon",variant:"ghost",className:"h-8 w-8",onClick:()=>Gd(Wt.id),title:"Remove from brokerage",children:e.jsx(hr,{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:()=>Rd(Wt.id),disabled:a||Wt.id===(t==null?void 0:t.id),title:Wt.id===(t==null?void 0:t.id)?"Cannot impersonate yourself":`Login as ${Wt.name}`,children:a?e.jsx(us,{className:"h-4 w-4 animate-spin"}):e.jsx(gD,{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:()=>$i(Wt.id,Wt.name),title:"Delete user",children:e.jsx(qn,{className:"h-4 w-4"})})]})})]},Wt.id))})]})}),e.jsxs("div",{className:"text-sm text-muted-foreground",children:[Hm(As.id).length," total member",Hm(As.id).length!==1?"s":""," •",Hm(As.id).filter(Wt=>Wt.roles.includes("brokerage_manager")).length," manager",Hm(As.id).filter(Wt=>Wt.roles.includes("brokerage_manager")).length!==1?"s":""]})]}),e.jsx(Cr,{children:e.jsx(B,{variant:"outline",onClick:Ec,children:"Close"})})]})})]}),e.jsx(_s,{value:"teams",children:e.jsx(fRs,{})}),e.jsx(_s,{value:"trials",children:e.jsx(dRs,{})}),e.jsx(_s,{value:"celebrations",children:e.jsx(cRs,{})}),e.jsx(_s,{value:"deletions",children:e.jsx(hRs,{})})]})]}),e.jsx(AEt,{open:sn,onOpenChange:ki,brokerages:u,onSuccess:dr}),xr&&e.jsx(TEt,{open:kn,onOpenChange:Wt=>{gn(Wt),Wt||Kr(null)},userId:xr.id,userName:xr.name}),e.jsx(gRs,{open:he,onOpenChange:xe,recipients:l.filter(Wt=>it.has(Wt.id)).map(Wt=>({id:Wt.id,name:Wt.name,email:Wt.email}))})]})};function yRs(){const{toast:s}=Ci(),t=as(),[n,r]=N.useState(""),[a,i]=N.useState(new Set),[l,o]=N.useState({}),[c,d]=N.useState({}),[u,h]=N.useState(""),[m,f]=N.useState(!1),{data:g=[],isLoading:y}=mt({queryKey:["unassigned-members"],queryFn:async()=>{const{data:M,error:L}=await H.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(L)throw L;return M||[]}}),{data:x=[]}=mt({queryKey:["brokerages-all"],queryFn:async()=>{const{data:M,error:L}=await H.from("brokerages").select("id, name").order("name");if(L)throw L;return M||[]}}),_=N.useMemo(()=>{const M=n.toLowerCase().trim();return M?g.filter(L=>(L.name||"").toLowerCase().includes(M)||(L.email||"").toLowerCase().includes(M)||(L.phone||"").toLowerCase().includes(M)):g},[g,n]),b=N.useMemo(()=>{var L;const M=new Map;for(const z of g){const $=(L=(z.email||"").split("@")[1])==null?void 0:L.toLowerCase();$&&(["gmail.com","yahoo.com","hotmail.com","outlook.com","icloud.com","aol.com","me.com","comcast.net"].includes($)||M.set($,(M.get($)||0)+1))}return Array.from(M.entries()).sort((z,$)=>$[1]-z[1]).slice(0,10)},[g]),k=M=>{i(L=>{const z=new Set(L);return z.has(M)?z.delete(M):z.add(M),z})},A=()=>{a.size===_.length?i(new Set):i(new Set(_.map(M=>M.id)))},T=async(M,L)=>{if(L){d(z=>({...z,[M]:!0}));try{const{data:z,error:$}=await H.functions.invoke("assign-brokerage",{body:{userId:M,brokerageId:L}});if($)throw $;if(z!=null&&z.error)throw new Error(z.error);s({title:"Assigned",description:"Member added to brokerage."}),t.invalidateQueries({queryKey:["unassigned-members"]}),i(V=>{const W=new Set(V);return W.delete(M),W})}catch(z){s({title:"Failed",description:z.message,variant:"destructive"})}finally{d(z=>({...z,[M]:!1}))}}},P=async()=>{if(!u||a.size===0)return;f(!0);let M=0,L=0;for(const z of a)try{const{data:$,error:V}=await H.functions.invoke("assign-brokerage",{body:{userId:z,brokerageId:u}});if(V||$!=null&&$.error)throw new Error((V==null?void 0:V.message)||$.error);M++}catch{L++}f(!1),s({title:`Assigned ${M}${L?`, ${L} failed`:""}`,description:"Bulk assignment complete.",variant:L?"destructive":"default"}),i(new Set),h(""),t.invalidateQueries({queryKey:["unassigned-members"]})},I=(M,L)=>{const z={...l};for(const $ of g)($.email||"").toLowerCase().endsWith(`@${M}`)&&(z[$.id]=L);o(z),s({title:"Suggestions applied",description:`Pre-filled brokerage for @${M}`})};return e.jsx(Qs,{children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(Uh,{title:"Unassigned Members",description:"Members with no brokerage and no active subscription — likely missed brokerage invites."}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-4",children:[e.jsxs(_e,{children:[e.jsx(zt,{className:"pb-2",children:e.jsxs(qt,{className:"text-sm font-medium text-muted-foreground flex items-center gap-2",children:[e.jsx(Yn,{className:"h-4 w-4"})," Orphan members"]})}),e.jsx(De,{children:e.jsx("div",{className:"text-3xl font-bold",children:g.length})})]}),e.jsxs(_e,{children:[e.jsx(zt,{className:"pb-2",children:e.jsxs(qt,{className:"text-sm font-medium text-muted-foreground flex items-center gap-2",children:[e.jsx(Ti,{className:"h-4 w-4"})," Selected"]})}),e.jsx(De,{children:e.jsx("div",{className:"text-3xl font-bold",children:a.size})})]}),e.jsxs(_e,{children:[e.jsx(zt,{className:"pb-2",children:e.jsxs(qt,{className:"text-sm font-medium text-muted-foreground flex items-center gap-2",children:[e.jsx(Cn,{className:"h-4 w-4"})," Top email domains"]})}),e.jsx(De,{children:e.jsx("div",{className:"text-3xl font-bold",children:b.length})})]})]}),b.length>0&&e.jsxs(_e,{children:[e.jsx(zt,{children:e.jsx(qt,{className:"text-base",children:"Domain suggestions"})}),e.jsx(De,{children:e.jsx("div",{className:"flex flex-wrap gap-2",children:b.map(([M,L])=>{const z=x.find($=>$.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(We,{variant:"secondary",children:L}),e.jsxs(Ns,{onValueChange:$=>I(M,$),defaultValue:z==null?void 0:z.id,children:[e.jsx(ws,{className:"h-8 w-[220px]",children:e.jsx(ks,{placeholder:"Apply brokerage…"})}),e.jsx(js,{children:x.map($=>e.jsx(nt,{value:$.id,children:$.name},$.id))})]})]},M)})})})]}),e.jsxs(_e,{children:[e.jsxs(zt,{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(Gr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(we,{value:n,onChange:M=>r(M.target.value),placeholder:"Search name, email, phone…",className:"pl-9"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(Ns,{value:u,onValueChange:h,children:[e.jsx(ws,{className:"w-[240px]",children:e.jsx(ks,{placeholder:"Bulk assign to brokerage…"})}),e.jsx(js,{children:x.map(M=>e.jsx(nt,{value:M.id,children:M.name},M.id))})]}),e.jsxs(B,{onClick:P,disabled:!u||a.size===0||m,children:[m&&e.jsx(us,{className:"h-4 w-4 mr-2 animate-spin"}),"Assign ",a.size||""]})]})]}),e.jsx(De,{children:y?e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsx(us,{className:"h-6 w-6 animate-spin text-muted-foreground"})}):_.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(Oa,{children:[e.jsx(Fa,{children:e.jsxs(un,{children:[e.jsx(Mt,{className:"w-10",children:e.jsx(Bi,{checked:a.size===_.length&&_.length>0,onCheckedChange:A})}),e.jsx(Mt,{children:"Name"}),e.jsx(Mt,{children:"Email"}),e.jsx(Mt,{children:"Signed up"}),e.jsx(Mt,{children:"Status"}),e.jsx(Mt,{children:"Assign to brokerage"}),e.jsx(Mt,{className:"w-24"})]})}),e.jsx(za,{children:_.map(M=>{const L=l[M.id]||"";return e.jsxs(un,{children:[e.jsx(gt,{children:e.jsx(Bi,{checked:a.has(M.id),onCheckedChange:()=>k(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:nc(new Date(M.created_at),{addSuffix:!0})}),e.jsx(gt,{children:e.jsx(We,{variant:"outline",children:M.subscription_status||"none"})}),e.jsx(gt,{children:e.jsxs(Ns,{value:L,onValueChange:z=>o($=>({...$,[M.id]:z})),children:[e.jsx(ws,{className:"h-9 w-[240px]",children:e.jsx(ks,{placeholder:"Pick brokerage…"})}),e.jsx(js,{children:x.map(z=>e.jsx(nt,{value:z.id,children:z.name},z.id))})]})}),e.jsx(gt,{children:e.jsx(B,{size:"sm",disabled:!L||c[M.id],onClick:()=>T(M.id,L),children:c[M.id]?e.jsx(us,{className:"h-4 w-4 animate-spin"}):"Assign"})})]},M.id)})})]})})})]})]})})}const vRs=()=>{const[s,t]=N.useState([]),[n,r]=N.useState(!0),[a,i]=N.useState(!1),[l,o]=N.useState(""),[c,d]=N.useState(""),[u,h]=N.useState(""),[m,f]=N.useState("");N.useEffect(()=>{g()},[]);const g=async()=>{const{data:T,error:P}=await H.from("invite_codes").select("*").order("created_at",{ascending:!1});P?(ie.error("Failed to load invite codes"),console.error(P)):t(T||[]),r(!1)},y=async T=>{if(T.preventDefault(),!l.trim()){ie.error("Please enter a code");return}i(!0);const{error:P}=await H.from("invite_codes").insert({code:l.trim().toUpperCase(),description:c.trim()||null,max_uses:u?parseInt(u):null,trial_days:m?parseInt(m):null});P?P.code==="23505"?ie.error("This code already exists"):(ie.error("Failed to create invite code"),console.error(P)):(ie.success("Invite code created"),o(""),d(""),h(""),f(""),g()),i(!1)},x=async(T,P)=>{const{error:I}=await H.from("invite_codes").update({is_active:!P}).eq("id",T);I?ie.error("Failed to update code"):t(s.map(M=>M.id===T?{...M,is_active:!P}:M))},_=async T=>{const{error:P}=await H.from("invite_codes").delete().eq("id",T);P?ie.error("Failed to delete code"):(ie.success("Code deleted"),t(s.filter(I=>I.id!==T)))},b="https://dashboard.relevelup.com",k=T=>{const P=`${b}/join?code=${T}`;navigator.clipboard.writeText(P),ie.success("Link copied to clipboard")},A=`${b}/join`;return e.jsx(Qs,{title:"Invite Codes",children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(Uh,{title:"Invite Codes",description:"Manage signup invite codes"}),e.jsxs(_e,{children:[e.jsxs(zt,{children:[e.jsx(qt,{children:"Create New Code"}),e.jsxs(_r,{children:["Share link: ",e.jsx("code",{className:"bg-muted px-2 py-1 rounded text-sm",children:A})]})]}),e.jsx(De,{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(re,{htmlFor:"code",children:"Code"}),e.jsx(we,{id:"code",placeholder:"WELCOME2024",value:l,onChange:T=>o(T.target.value),className:"w-40"})]}),e.jsxs("div",{className:"space-y-2 flex-1 min-w-[200px]",children:[e.jsx(re,{htmlFor:"description",children:"Description (optional)"}),e.jsx(we,{id:"description",placeholder:"For marketing campaign",value:c,onChange:T=>d(T.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{htmlFor:"maxUses",children:"Max Uses"}),e.jsx(we,{id:"maxUses",type:"number",placeholder:"Unlimited",value:u,onChange:T=>h(T.target.value),className:"w-28"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{htmlFor:"trialDays",children:"Trial Days"}),e.jsx(we,{id:"trialDays",type:"number",placeholder:"None",value:m,onChange:T=>f(T.target.value),className:"w-28"})]}),e.jsxs(B,{type:"submit",disabled:a,children:[a?e.jsx(us,{className:"h-4 w-4 animate-spin"}):e.jsx(nn,{className:"h-4 w-4 mr-2"}),"Create"]})]})})]}),e.jsxs(_e,{children:[e.jsx(zt,{children:e.jsx(qt,{children:"Active Codes"})}),e.jsx(De,{children:n?e.jsx("div",{className:"flex justify-center py-8",children:e.jsx(us,{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(Oa,{children:[e.jsx(Fa,{children:e.jsxs(un,{children:[e.jsx(Mt,{children:"Code"}),e.jsx(Mt,{children:"Description"}),e.jsx(Mt,{children:"Uses"}),e.jsx(Mt,{children:"Trial"}),e.jsx(Mt,{children:"Created"}),e.jsx(Mt,{children:"Active"}),e.jsx(Mt,{className:"w-24",children:"Actions"})]})}),e.jsx(za,{children:s.map(T=>e.jsxs(un,{children:[e.jsx(gt,{className:"font-mono font-medium",children:T.code}),e.jsx(gt,{className:"text-muted-foreground",children:T.description||"—"}),e.jsxs(gt,{children:[T.uses_count,T.max_uses&&` / ${T.max_uses}`]}),e.jsx(gt,{children:T.trial_days?e.jsxs("span",{className:"text-amber-600 dark:text-amber-400 font-medium",children:[T.trial_days," days"]}):e.jsx("span",{className:"text-muted-foreground",children:"—"})}),e.jsx(gt,{className:"text-muted-foreground",children:Js(new Date(T.created_at),"MMM d, yyyy")}),e.jsx(gt,{children:e.jsx(zn,{checked:T.is_active,onCheckedChange:()=>x(T.id,T.is_active)})}),e.jsx(gt,{children:e.jsxs("div",{className:"flex gap-1",children:[e.jsx(B,{variant:"ghost",size:"icon",onClick:()=>k(T.code),title:"Copy invite link",children:e.jsx(Pa,{className:"h-4 w-4"})}),e.jsx(B,{variant:"ghost",size:"icon",onClick:()=>_(T.id),className:"text-destructive hover:text-destructive",title:"Delete code",children:e.jsx(qn,{className:"h-4 w-4"})})]})})]},T.id))})]})})]})]})})},W4=H;function pFn(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 bRs(s){return s.toLowerCase().replace(/[^a-z0-9\s-]/g,"").trim().replace(/\s+/g,"-").slice(0,70)}const _Rs="https://dashboard.relevelup.com";function fFn(s,t){const r=`${typeof window<"u"&&window.location.hostname==="localhost"?window.location.origin:_Rs}/live/${s}`;return t?`${r}?i=${t}`:r}function gFn(){const s=as(),t=mt({queryKey:["live-events"],queryFn:async()=>{const{data:i,error:l}=await W4.from("live_events").select("*").order("starts_at",{ascending:!1});if(l)throw l;return i||[]}}),n=_t({mutationFn:async i=>{var d;const{data:l}=await H.auth.getUser(),{data:o,error:c}=await W4.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"]}),ie.success("Live event created")},onError:i=>ie.error((i==null?void 0:i.message)||"Could not create event")}),r=_t({mutationFn:async({id:i,...l})=>{const{error:o}=await W4.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]}),ie.success("Saved")},onError:i=>ie.error((i==null?void 0:i.message)||"Could not save")}),a=_t({mutationFn:async i=>{const{error:l}=await W4.from("live_events").delete().eq("id",i);if(l)throw l},onSuccess:()=>{s.invalidateQueries({queryKey:["live-events"]}),ie.success("Event deleted")},onError:i=>ie.error((i==null?void 0:i.message)||"Could not delete")});return{list:t,create:n,update:r,remove:a}}function xFn(s){return mt({queryKey:["live-event",s],enabled:!!s,queryFn:async()=>{const{data:t,error:n}=await W4.from("live_events").select("*").eq("id",s).maybeSingle();if(n)throw n;return t}})}function yFn(s){return mt({queryKey:["live-registrations",s],enabled:!!s,refetchInterval:2e4,queryFn:async()=>{const{data:t,error:n}=await W4.from("live_registrations").select("*").eq("event_id",s).order("created_at",{ascending:!1});if(n)throw n;return t||[]}})}function vFn(s){const t=as(),n=mt({queryKey:["live-invites",s],enabled:!!s,queryFn:async()=>{const{data:i,error:l}=await W4.from("live_invites").select("*").eq("event_id",s).order("created_at",{ascending:!1});if(l)throw l;return i||[]}}),r=_t({mutationFn:async i=>{const{data:l}=await H.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 W4.from("live_invites").insert(o).select();if(d)throw d;return c||[]},onSuccess:i=>{t.invalidateQueries({queryKey:["live-invites",s]}),ie.success(`${i.length} invite link${i.length===1?"":"s"} created`)},onError:i=>ie.error((i==null?void 0:i.message)||"Could not create invites")}),a=_t({mutationFn:async i=>{const{error:l}=await W4.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 eJ=async s=>{try{const{data:t,error:n}=await H.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}},_U=async s=>{try{const{data:t,error:n}=await H.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}}},wRs=async(s,t)=>await eJ("new_templates")?_U({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}),jRs=async(s,t)=>_U({title:"New Academy Video",body:`New video added: ${s}`,url:`/academy/${t}`}),NRs=async(s,t)=>await eJ("new_events")?_U({title:"New Event",body:`New event: ${s}`,url:`/events/${t}`}):(console.log("New event notifications are disabled"),{success:!1,skipped:!0}),kRs=async(s,t)=>await eJ("new_toolbox")?_U({title:"New Resource Kit",body:`New resource kit available: ${s}`,url:`/toolbox/${t}`}):(console.log("New toolbox notifications are disabled"),{success:!1,skipped:!0}),kOe=async(s,t)=>await eJ("new_social_swag")?_U({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}),SRs=async(s,t)=>await eJ("new_newsletters")?_U({title:"New Newsletter",body:`New newsletter available: ${s}`,url:`/newsletters/${t}`}):(console.log("New newsletter notifications are disabled"),{success:!1,skipped:!0}),cLe=400;function CRs(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 ARs(){const s=[];let t=0;const n=1e3;for(;;){const{data:r,error:a}=await H.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 te=!1;return(async()=>{h(!0);try{const[ne,me,ue]=await Promise.all([ARs(),jot("event_registrations",n.id),jot("event_attendees",n.id)]);if(te)return;f(ne),y(me),_(ue)}catch(ne){te||r({title:"Could not load audience",description:ne instanceof Error?ne.message:"Unknown error",variant:"destructive"})}finally{te||h(!1)}})(),()=>{te=!0}},[s,n,r]),N.useEffect(()=>{s||(T(null),d(""),o(""),i("not_registered"))},[s]);const z=N.useMemo(()=>a==="all"?m:a==="not_registered"?m.filter(te=>!g.has(te.id)):m.filter(te=>g.has(te.id)&&!x.has(te.id)),[a,m,g,x]),$={all:m.length,not_registered:m.filter(te=>!g.has(te.id)).length,registered_never_attended:m.filter(te=>g.has(te.id)&&!x.has(te.id)).length},V=async te=>{const{data:{session:ne}}=await H.auth.getSession(),me=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:te.map(ce=>({email:ce.email,name:ce.name,user_id:ce.id})),custom_subject:l.trim()||void 0,custom_intro:c.trim()||void 0})}),ue=await me.json().catch(()=>({}));if(!me.ok)throw new Error((ue==null?void 0:ue.error)||`HTTP ${me.status}`);return{sent:(ue==null?void 0:ue.sent)??0,failed:(ue==null?void 0:ue.failed)??0}},W=async()=>{var te;if(n){L(!0);try{const{data:{session:ne}}=await H.auth.getSession(),me=ne==null?void 0:ne.user;if(!(me!=null&&me.email))throw new Error("No signed-in email found");const ue=await V([{id:me.id,name:((te=me.user_metadata)==null?void 0:te.name)||"",email:me.email}]);r({title:"Test sent",description:`Sent to ${me.email} · Sent: ${ue.sent} · Failed: ${ue.failed}`})}catch(ne){r({title:"Test failed",description:ne instanceof Error?ne.message:"Unknown error",variant:"destructive"})}finally{L(!1)}}},G=async()=>{if(!(!n||z.length===0)){I(!1),k(!0),T({done:0,total:z.length,sent:0,failed:0});try{let te=0,ne=0;for(let me=0;me!b&&t(te),children:e.jsxs(Fs,{className:"max-w-2xl max-h-[92vh] overflow-y-auto",children:[e.jsxs(qs,{children:[e.jsxs($s,{className:"flex items-center gap-2",children:[e.jsx(Cn,{className:"h-5 w-5 text-primary"}),"Invite Members to Event"]}),e.jsx(Ar,{children:n?e.jsxs("span",{className:"flex items-center gap-2 text-sm",children:[e.jsx(df,{className:"h-4 w-4"}),e.jsx("span",{className:"font-medium text-foreground",children:n.title}),e.jsx("span",{children:"·"}),e.jsx("span",{children:CRs(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(re,{className:"flex items-center gap-2",children:[e.jsx(Yn,{className:"h-4 w-4"})," Audience"]}),u?e.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground py-2",children:[e.jsx(us,{className:"h-4 w-4 animate-spin"})," Loading members..."]}):e.jsxs(K1,{value:a,onValueChange:te=>i(te),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(Ju,{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:$.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(Ju,{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:$.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(Ju,{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:$.registered_never_attended.toLocaleString()})]})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(re,{htmlFor:"ev-inv-subject",children:"Subject line (optional)"}),e.jsx(we,{id:"ev-inv-subject",placeholder:n?`You're invited: ${n.title}`:"You're invited to...",value:l,onChange:te=>o(te.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(re,{htmlFor:"ev-inv-intro",children:"Personal message (optional)"}),e.jsx(Ws,{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:te=>d(te.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."})]}),A&&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 ",A.done.toLocaleString()," / ",A.total.toLocaleString()]}),e.jsxs("span",{className:"font-medium",children:["✓ ",A.sent.toLocaleString(),A.failed>0&&e.jsxs("span",{className:"text-destructive",children:[" · ✗ ",A.failed.toLocaleString()]})]})]}),e.jsx(ro,{value:X})]})]}),e.jsxs(Cr,{className:"gap-2 sm:gap-2",children:[e.jsx(B,{variant:"outline",onClick:W,disabled:b||M||u,children:M?e.jsxs(e.Fragment,{children:[e.jsx(us,{className:"h-4 w-4 mr-2 animate-spin"})," Sending test..."]}):e.jsxs(e.Fragment,{children:[e.jsx(mn,{className:"h-4 w-4 mr-2"})," Send test to me"]})}),e.jsx(B,{variant:"ghost",onClick:()=>t(!1),disabled:b,children:"Cancel"}),e.jsx(B,{onClick:()=>I(!0),disabled:b||u||z.length===0,children:b?e.jsxs(e.Fragment,{children:[e.jsx(us,{className:"h-4 w-4 mr-2 animate-spin"})," Sending..."]}):e.jsxs(e.Fragment,{children:[e.jsx(Rr,{className:"h-4 w-4 mr-2"})," Send to ",z.length.toLocaleString()]})})]})]})}),e.jsx(Fl,{open:P,onOpenChange:I,children:e.jsxs(kl,{children:[e.jsxs(Sl,{children:[e.jsx(Al,{children:"Send event invite?"}),e.jsxs(Tl,{children:["This will send a branded invite to"," ",e.jsxs("span",{className:"font-semibold text-foreground",children:[z.length.toLocaleString()," member",z.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(Cl,{children:[e.jsx(El,{children:"Cancel"}),e.jsxs(wl,{onClick:G,children:[e.jsx(Rr,{className:"h-4 w-4 mr-2"})," Send now"]})]})]})})]})}const Mse={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 ERs(){const s=tr(),t=as(),[n,r]=N.useState(!1),[a,i]=N.useState(null),[l,o]=N.useState(Mse),[c,d]=N.useState(null),[u,h]=N.useState(null),[m,f]=N.useState(!1),g=N.useRef(null),[y,x]=N.useState(!1),[_,b]=N.useState(null),[k,A]=N.useState(!1),[T,P]=N.useState(null),[I,M]=N.useState(null),[L,z]=N.useState(!0),[$,V]=N.useState(""),[W,G]=N.useState(!1),[X,te]=N.useState(null),{data:ne,isLoading:me}=mt({queryKey:["admin-events"],queryFn:async()=>{const{data:Ze,error:ht}=await H.from("events").select("*").order("event_date",{ascending:!0});if(ht)throw ht;return Ze}}),{data:ue}=mt({queryKey:["event-registrations-count"],queryFn:async()=>{let Ze=[],ht=0;const Bt=1e3;for(;;){const{data:Yt,error:Kt}=await H.from("event_registrations").select("event_id").range(ht,ht+Bt-1);if(Kt)throw Kt;if(!Yt||Yt.length===0||(Ze=Ze.concat(Yt),Yt.length{Ct[Yt.event_id]=(Ct[Yt.event_id]||0)+1}),Ct}}),{data:ce,isLoading:ae}=mt({queryKey:["event-registrations-details",_==null?void 0:_.id],queryFn:async()=>{if(!_)return[];const{data:Ze,error:ht}=await H.from("event_registrations").select("id, user_id, registered_at, zoom_join_url, zoom_name, zoom_email").eq("event_id",_.id).order("registered_at",{ascending:!1});if(ht)throw ht;if(!Ze||Ze.length===0)return[];const Bt=Ze.map(Kt=>Kt.user_id).filter(Boolean);let Ct=[];if(Bt.length>0){const{data:Kt,error:Xs}=await H.from("profiles").select("id, name, email").in("id",Bt);if(Xs)throw Xs;Ct=Kt||[]}const Yt=new Map((Ct==null?void 0:Ct.map(Kt=>[Kt.id,Kt]))||[]);return Ze.map(Kt=>({...Kt,profiles:Kt.user_id&&Yt.get(Kt.user_id)||null}))},enabled:!!_}),{data:he,isLoading:xe}=mt({queryKey:["event-attendees-details",_==null?void 0:_.id],queryFn:async()=>{if(!_)return[];const{data:Ze,error:ht}=await H.from("event_attendees").select("id, user_id, zoom_email, zoom_name, join_time, leave_time, duration_minutes, manually_added, created_at").eq("event_id",_.id).order("created_at",{ascending:!1});if(ht)throw ht;if(!Ze||Ze.length===0)return[];const Bt=Ze.map(zs=>zs.user_id).filter(Boolean);let Ct=[];if(Bt.length>0){const{data:zs,error:Vt}=await H.from("profiles").select("id, name, email").in("id",Bt);if(Vt)throw Vt;Ct=zs||[]}const{data:Yt}=await H.from("agent_points").select("user_id").eq("event_id",_.id),Kt=new Set((Yt==null?void 0:Yt.map(zs=>zs.user_id))||[]),Xs=new Map((Ct==null?void 0:Ct.map(zs=>[zs.id,zs]))||[]);return Ze.map(zs=>({...zs,profiles:zs.user_id&&Xs.get(zs.user_id)||null,points_awarded:zs.user_id?Kt.has(zs.user_id):!1}))},enabled:!!_}),ve=Ze=>{b(Ze),x(!0)},ge=_t({mutationFn:async Ze=>{const{data:{session:ht}}=await H.auth.getSession();if(!ht)throw new Error("Not authenticated");const Bt=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/zoom-sync-registrations",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${ht.access_token}`},body:JSON.stringify({event_id:Ze})}),Ct=await Bt.json();if(!Bt.ok){const Yt=new Error(Ct.error||"Failed to sync");throw Yt.scopeError=!!Ct.scope_error,Yt.details=Ct.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,Yt}return Ct},onSuccess:Ze=>{if(t.invalidateQueries({queryKey:["event-registrations-details",_==null?void 0:_.id]}),t.invalidateQueries({queryKey:["event-registrations-count"]}),Ze!=null&&Ze.scope_error||(Ze==null?void 0:Ze.success)===!1){ie.error("Zoom needs one more authorization step",{description:Ze!=null&&Ze.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.":(Ze==null?void 0:Ze.message)||"Zoom registration sync could not complete.",duration:2e4});return}ie.success(Ze.message)},onError:Ze=>{ie.error("Failed to sync Zoom registrations",{description:Ze.scopeError&&Ze.details||Ze.message,duration:Ze.scopeError?2e4:5e3})}}),be=_t({mutationFn:async Ze=>{const{data:{session:ht}}=await H.auth.getSession();if(!ht)throw new Error("Not authenticated");const Bt=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/zoom-sync-attendees",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${ht.access_token}`},body:JSON.stringify({event_id:Ze})}),Ct=await Bt.json();if(!Bt.ok)throw new Error(Ct.error||"Failed to sync attendees");return Ct},onSuccess:Ze=>{if(t.invalidateQueries({queryKey:["event-attendees-details",_==null?void 0:_.id]}),t.invalidateQueries({queryKey:["event-leaderboard"]}),t.invalidateQueries({queryKey:["admin-agent-points"]}),Ze!=null&&Ze.scope_error||(Ze==null?void 0:Ze.success)===!1){ie.error((Ze==null?void 0:Ze.message)||"Zoom sync failed",{description:Ze!=null&&Ze.scope_error?"Zoom must be re-authorized after adding the missing report scope.":void 0,duration:15e3});return}Ze!=null&&Ze.message?ie.success(Ze.message):ie.success(`Synced ${Ze.synced||0} attendees. ${Ze.points_awarded||0} points awarded!`)},onError:Ze=>{ie.error("Failed to sync attendees: "+Ze.message)}}),Se=_t({mutationFn:async()=>{const{data:Ze,error:ht}=await H.functions.invoke("zoom-retry-registrations",{body:{}});if(ht)throw ht;return Ze},onSuccess:Ze=>{t.invalidateQueries({queryKey:["event-registrations-details",_==null?void 0:_.id]}),t.invalidateQueries({queryKey:["event-registrations-count"]}),ie.success(`Retry complete: ${(Ze==null?void 0:Ze.successCount)??0} fixed, ${(Ze==null?void 0:Ze.failCount)??0} still failing, ${(Ze==null?void 0:Ze.rateLimitedCount)??0} rate-limited`)},onError:Ze=>{ie.error("Retry failed: "+Ze.message)}}),Ie=_t({mutationFn:async({eventId:Ze,testMode:ht})=>{const{data:{session:Bt}}=await H.auth.getSession();if(!Bt)throw new Error("Not authenticated");const Ct=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/send-event-reminder",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${Bt.access_token}`},body:JSON.stringify({event_id:Ze,test_mode:ht})}),Yt=await Ct.json();if(!Ct.ok)throw new Error(Yt.error||"Failed to send reminders");return Yt},onSuccess:Ze=>{Ze.test?ie.success(Ze.message||"Test email sent!"):ie.success(Ze.message||`Reminder emails sent to ${Ze.sent} registrants!`)},onError:Ze=>{ie.error("Failed to send reminders: "+Ze.message)}}),{data:Me}=mt({queryKey:["all-profiles-for-linking"],queryFn:async()=>{let Ze=[],ht=0;const Bt=1e3;for(;;){const{data:Ct,error:Yt}=await H.from("profiles").select("id, name, email").order("name",{ascending:!0}).range(ht,ht+Bt-1);if(Yt)throw Yt;if(!Ct||Ct.length===0||(Ze=[...Ze,...Ct],Ct.length{const{error:Yt}=await H.from("event_attendees").update({user_id:ht}).eq("id",Ze);if(Yt)throw Yt;if(Ct&&Bt){const{error:Xs}=await H.from("zoom_email_aliases").upsert({user_id:ht,zoom_email:Bt.toLowerCase()},{onConflict:"zoom_email"});Xs&&console.error("Failed to save alias:",Xs)}const Kt=_==null?void 0:_.id;if(Kt){const{data:Xs}=await H.from("user_roles").select("id").eq("user_id",ht).eq("role","admin").single();if(!Xs){const{data:zs}=await H.from("agent_points").select("id").eq("user_id",ht).eq("event_id",Kt).single();zs||(await H.rpc("award_attendance_points",{p_user_id:ht,p_event_id:Kt,p_points:10,p_reason:"Event Attendance (Manual Link)"}),await H.rpc("check_and_award_badges",{p_user_id:ht}))}}return{userId:ht,zoomEmail:Bt,shouldSaveAlias:Ct}},onSuccess:Ze=>{t.invalidateQueries({queryKey:["event-attendees-details",_==null?void 0:_.id]}),t.invalidateQueries({queryKey:["event-leaderboard"]}),t.invalidateQueries({queryKey:["admin-agent-points"]});let ht="Attendee linked and points awarded!";Ze.shouldSaveAlias&&Ze.zoomEmail&&(ht+=` Email "${Ze.zoomEmail}" will be auto-matched in the future.`),ie.success(ht),A(!1),P(null),M(null),V("")},onError:Ze=>{ie.error("Failed to link attendee: "+Ze.message)}}),Be=Ze=>{P(Ze),M(null),z(!0),V(""),A(!0)},Ne=()=>{!T||!I||Re.mutate({attendeeId:T.id,userId:I,zoomEmail:T.zoom_email,shouldSaveAlias:L})},Ge=(Me==null?void 0:Me.filter(Ze=>{var Bt,Ct;if(!$)return!0;const ht=$.toLowerCase();return((Bt=Ze.name)==null?void 0:Bt.toLowerCase().includes(ht))||((Ct=Ze.email)==null?void 0:Ct.toLowerCase().includes(ht))}))||[],Ce=async Ze=>{const ht=Ze.name.split(".").pop(),Ct=`${`${crypto.randomUUID()}.${ht}`}`,{error:Yt}=await H.storage.from("event-images").upload(Ct,Ze);if(Yt)throw Yt;const{data:{publicUrl:Kt}}=H.storage.from("event-images").getPublicUrl(Ct);return Kt},Fe=Ze=>{var Bt;const ht=(Bt=Ze.target.files)==null?void 0:Bt[0];if(ht){if(ht.size>5*1024*1024){ie.error("Image must be less than 5MB");return}d(ht),h(URL.createObjectURL(ht))}},Ae=()=>{d(null),h(null),o({...l,image_url:""}),g.current&&(g.current.value="")},Xe=_t({mutationFn:async Ze=>{f(!0);let ht=Ze.image_url;c&&(ht=await Ce(c)||"");const Bt=new Date(Ze.event_date),[Ct,Yt]=Ze.event_time.split(":");Bt.setHours(parseInt(Ct),parseInt(Yt));const Kt=[new Date(Bt)];if(Ze.is_recurring&&Ze.recurrence_end_date){let At=new Date(Bt);for(;Ze.recurrence_pattern==="weekly"?At=H4(At,1):Ze.recurrence_pattern==="biweekly"?At=H4(At,2):At=J0(At,1),!(At>Ze.recurrence_end_date);)Kt.push(new Date(At))}const Xs=Kt.map(At=>({title:Ze.title,description:Ze.description||null,image_url:ht||null,video_url:Ze.video_url||null,event_date:At.toISOString(),zoom_link:Ze.zoom_link,zoom_meeting_id:Ze.zoom_meeting_id||null,capacity:Ze.capacity?parseInt(Ze.capacity):null,is_published:Ze.is_published})),{data:zs,error:Vt}=await H.from("events").insert(Xs).select();if(Vt)throw Vt;return zs&&zs.length>0&&NRs(Ze.title,zs[0].id),Kt.length},onSuccess:Ze=>{t.invalidateQueries({queryKey:["admin-events"]}),ie.success(Ze>1?`${Ze} recurring events created successfully`:"Event created successfully"),r(!1),o(Mse),d(null),h(null),f(!1)},onError:Ze=>{ie.error("Failed to create event: "+Ze.message),f(!1)}}),$e=_t({mutationFn:async({id:Ze,data:ht})=>{f(!0);let Bt=ht.image_url;c&&(Bt=await Ce(c)||"");const Ct=new Date(ht.event_date),[Yt,Kt]=ht.event_time.split(":");Ct.setHours(parseInt(Yt),parseInt(Kt));const{error:Xs}=await H.from("events").update({title:ht.title,description:ht.description||null,image_url:Bt||null,video_url:ht.video_url||null,event_date:Ct.toISOString(),zoom_link:ht.zoom_link,zoom_meeting_id:ht.zoom_meeting_id||null,capacity:ht.capacity?parseInt(ht.capacity):null,is_published:ht.is_published}).eq("id",Ze);if(Xs)throw Xs},onSuccess:()=>{t.invalidateQueries({queryKey:["admin-events"]}),ie.success("Event updated successfully"),r(!1),i(null),o(Mse),d(null),h(null),f(!1)},onError:Ze=>{ie.error("Failed to update event: "+Ze.message),f(!1)}}),Ye=_t({mutationFn:async Ze=>{const{error:ht}=await H.from("events").delete().eq("id",Ze);if(ht)throw ht},onSuccess:()=>{t.invalidateQueries({queryKey:["admin-events"]}),ie.success("Event deleted successfully")},onError:Ze=>{ie.error("Failed to delete event: "+Ze.message)}}),Je=_t({mutationFn:async Ze=>{var At;const{data:ht}=await H.auth.getUser(),Bt=new Date(Ze.event_date),Ct=new Date(Bt.getTime()+60*60*1e3),Yt=bRs(Ze.title),Kt=Math.random().toString(36).slice(2,7),Xs=`${Yt}-${Kt}`,{data:zs,error:Vt}=await H.from("live_events").insert({slug:Xs,title:Ze.title,description:Ze.description||null,hero_image_url:Ze.image_url||null,starts_at:Ze.event_date,ends_at:Ct.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:Ze.zoom_meeting_id||null,cta_label:"Join the training",cta_url:Ze.zoom_link||"https://dashboard.relevelup.com/trial",created_by:(At=ht.user)==null?void 0:At.id,agenda:[],offer_bullets:[]}).select().single();if(Vt)throw Vt;return zs},onSuccess:Ze=>{t.invalidateQueries({queryKey:["live-events"]}),ie.success("Cloned to LevelUp Live — configure stream next"),s(`/admin/live/${Ze.id}`)},onError:Ze=>{ie.error("Failed to clone to LevelUp Live: "+Ze.message)}}),Ke=Ze=>{var Bt;const ht=new Date(Ze.event_date);i(Ze),o({title:Ze.title,description:Ze.description||"",image_url:Ze.image_url||"",video_url:Ze.video_url||"",event_date:ht,event_time:Js(ht,"HH:mm"),zoom_link:Ze.zoom_link,zoom_meeting_id:Ze.zoom_meeting_id||"",capacity:((Bt=Ze.capacity)==null?void 0:Bt.toString())||"",is_published:Ze.is_published,is_recurring:!1,recurrence_pattern:"weekly",recurrence_end_date:void 0}),h(Ze.image_url||null),d(null),r(!0)},st=Ze=>{if(Ze.preventDefault(),!l.event_date){ie.error("Please select a date");return}if(l.is_recurring&&!l.recurrence_end_date){ie.error("Please select an end date for recurring events");return}a?$e.mutate({id:a.id,data:l}):Xe.mutate(l)},rt=()=>{r(!1),i(null),o(Mse),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(Uh,{title:"Event Management",description:"Create and manage upcoming events"}),e.jsxs(_e,{className:"mb-6",children:[e.jsxs(zt,{className:"flex flex-row items-center justify-between",children:[e.jsx(qt,{children:"All Events"}),e.jsxs(Bs,{open:n,onOpenChange:Ze=>!Ze&&rt(),children:[e.jsx(Ao,{asChild:!0,children:e.jsxs(B,{onClick:()=>r(!0),children:[e.jsx(nn,{className:"h-4 w-4 mr-2"}),"Add Event"]})}),e.jsxs(Fs,{className:"max-w-lg max-h-[90vh] overflow-y-auto",children:[e.jsx(qs,{children:e.jsx($s,{children:a?"Edit Event":"Create New Event"})}),e.jsxs("form",{onSubmit:st,className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{htmlFor:"title",children:"Title *"}),e.jsx(we,{id:"title",value:l.title,onChange:Ze=>o({...l,title:Ze.target.value}),placeholder:"Event title",required:!0})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{children:"Description"}),e.jsx(yN,{content:l.description,onChange:Ze=>o({...l,description:Ze}),placeholder:"Event description",minHeight:"120px"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{children:"Event Image"}),e.jsx("input",{type:"file",ref:g,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:Ae,children:e.jsx(hr,{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 Ze;return(Ze=g.current)==null?void 0:Ze.click()},children:[e.jsx(ni,{className:"h-6 w-6"}),e.jsx("span",{className:"text-sm",children:"Click to upload image"})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{children:"Date *"}),e.jsxs(rc,{children:[e.jsx(ac,{asChild:!0,children:e.jsxs(B,{variant:"outline",className:Ot("w-full justify-start text-left font-normal",!l.event_date&&"text-muted-foreground"),children:[e.jsx(ta,{className:"mr-2 h-4 w-4"}),l.event_date?Js(l.event_date,"PPP"):"Pick a date"]})}),e.jsx(Zl,{className:"w-auto p-0",align:"start",children:e.jsx(Xv,{mode:"single",selected:l.event_date,onSelect:Ze=>o({...l,event_date:Ze}),initialFocus:!0,className:"p-3 pointer-events-auto"})})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{htmlFor:"time",children:"Time *"}),e.jsx(we,{id:"time",type:"time",value:l.event_time,onChange:Ze=>o({...l,event_time:Ze.target.value}),required:!0})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{htmlFor:"zoom_link",children:"Zoom Link *"}),e.jsx(we,{id:"zoom_link",value:l.zoom_link,onChange:Ze=>o({...l,zoom_link:Ze.target.value}),placeholder:"https://zoom.us/j/...",required:!0})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{htmlFor:"zoom_meeting_id",children:"Zoom Meeting ID (for API registration)"}),e.jsx(we,{id:"zoom_meeting_id",value:l.zoom_meeting_id,onChange:Ze=>o({...l,zoom_meeting_id:Ze.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(re,{htmlFor:"video_url",children:"Promo Video URL (optional)"}),e.jsx(we,{id:"video_url",value:l.video_url,onChange:Ze=>o({...l,video_url:Ze.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(re,{htmlFor:"capacity",children:"Capacity (optional)"}),e.jsx(we,{id:"capacity",type:"number",value:l.capacity,onChange:Ze=>o({...l,capacity:Ze.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(S9,{className:"h-4 w-4 text-muted-foreground"}),e.jsx(re,{htmlFor:"is_recurring",children:"Recurring Event"})]}),e.jsx(zn,{id:"is_recurring",checked:l.is_recurring,onCheckedChange:Ze=>o({...l,is_recurring:Ze})})]}),l.is_recurring&&e.jsxs("div",{className:"space-y-3 pt-1",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{children:"Frequency"}),e.jsxs(Ns,{value:l.recurrence_pattern,onValueChange:Ze=>o({...l,recurrence_pattern:Ze}),children:[e.jsx(ws,{children:e.jsx(ks,{})}),e.jsxs(js,{children:[e.jsx(nt,{value:"weekly",children:"Weekly"}),e.jsx(nt,{value:"biweekly",children:"Every 2 Weeks"}),e.jsx(nt,{value:"monthly",children:"Monthly"})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{children:"Repeat Until"}),e.jsxs(rc,{children:[e.jsx(ac,{asChild:!0,children:e.jsxs(B,{variant:"outline",className:Ot("w-full justify-start text-left font-normal",!l.recurrence_end_date&&"text-muted-foreground"),children:[e.jsx(ta,{className:"mr-2 h-4 w-4"}),l.recurrence_end_date?Js(l.recurrence_end_date,"PPP"):"Pick end date"]})}),e.jsx(Zl,{className:"w-auto p-0",align:"start",children:e.jsx(Xv,{mode:"single",selected:l.recurrence_end_date,onSelect:Ze=>o({...l,recurrence_end_date:Ze}),disabled:Ze=>Ze<(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 Ze=1,ht=new Date(l.event_date);for(;ht=l.recurrence_pattern==="weekly"?H4(ht,1):l.recurrence_pattern==="biweekly"?H4(ht,2):J0(ht,1),!(ht>l.recurrence_end_date);)Ze++;return Ze})()," events with the same Zoom link"]})]})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(re,{htmlFor:"is_published",children:"Published"}),e.jsx(zn,{id:"is_published",checked:l.is_published,onCheckedChange:Ze=>o({...l,is_published:Ze})})]}),e.jsxs("div",{className:"flex gap-2 pt-4",children:[e.jsx(B,{type:"button",variant:"outline",onClick:rt,className:"flex-1",children:"Cancel"}),e.jsx(B,{type:"submit",className:"flex-1",disabled:Xe.isPending||$e.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(De,{children:me?e.jsx("div",{className:"text-center py-8 text-muted-foreground",children:"Loading events..."}):(ne==null?void 0:ne.length)===0?e.jsx("div",{className:"text-center py-8 text-muted-foreground",children:"No events yet. Create your first event!"}):(()=>{const Ze=new Date,ht=[...ne||[]],Bt=ht.filter(zs=>new Date(zs.event_date)>=Ze).sort((zs,Vt)=>new Date(zs.event_date).getTime()-new Date(Vt.event_date).getTime()),Ct=ht.filter(zs=>new Date(zs.event_date)new Date(Vt.event_date).getTime()-new Date(zs.event_date).getTime()),Yt=Bt[0],Kt=zs=>e.jsxs(un,{children:[e.jsx(gt,{className:"font-medium",children:zs.title}),e.jsx(gt,{className:"whitespace-nowrap",children:Js(new Date(zs.event_date),"PPP p")}),e.jsx(gt,{children:e.jsxs(B,{variant:"ghost",size:"sm",className:"gap-1",onClick:()=>ve(zs),children:[e.jsx(Yn,{className:"h-4 w-4"}),(ue==null?void 0:ue[zs.id])||0,zs.capacity&&` / ${zs.capacity}`]})}),e.jsx(gt,{children:e.jsx("span",{className:Ot("px-2 py-1 rounded-full text-xs font-medium",zs.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:zs.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:()=>{te(zs),G(!0)},title:"Send invite email to members",children:[e.jsx(Rr,{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:()=>Je.mutate(zs),disabled:Je.isPending,title:"Clone to LevelUp Live",children:[e.jsx(Y0,{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(zs.zoom_link,"_blank"),title:"Open Zoom Link",children:e.jsx(Tr,{className:"h-4 w-4"})}),e.jsx(B,{variant:"ghost",size:"icon",onClick:()=>Ke(zs),children:e.jsx(Ja,{className:"h-4 w-4"})}),e.jsx(B,{variant:"ghost",size:"icon",onClick:()=>{confirm("Are you sure you want to delete this event?")&&Ye.mutate(zs.id)},children:e.jsx(qn,{className:"h-4 w-4 text-destructive"})})]})})]},zs.id),Xs=(zs,Vt)=>zs.length===0?e.jsx("div",{className:"text-center py-8 text-muted-foreground",children:Vt}):e.jsxs(Oa,{children:[e.jsx(Fa,{children:e.jsxs(un,{children:[e.jsx(Mt,{children:"Title"}),e.jsx(Mt,{children:"Date & Time"}),e.jsx(Mt,{children:"Registrations"}),e.jsx(Mt,{children:"Status"}),e.jsx(Mt,{className:"text-right",children:"Actions"})]})}),e.jsx(za,{children:zs.map(Kt)})]});return e.jsxs("div",{className:"space-y-6",children:[Yt&&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(Xr,{className:"h-3.5 w-3.5"}),"Next Upcoming Event"]}),e.jsx("h3",{className:"text-xl font-bold truncate",children:Yt.title}),e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:Js(new Date(Yt.event_date),"EEEE, PPP 'at' p")}),e.jsxs("p",{className:"text-xs text-muted-foreground mt-1",children:[(ue==null?void 0:ue[Yt.id])||0," registered",Yt.capacity?` of ${Yt.capacity}`:""]})]}),e.jsxs("div",{className:"flex gap-2 flex-wrap",children:[e.jsxs(B,{size:"sm",className:"gap-1.5",onClick:()=>{te(Yt),G(!0)},children:[e.jsx(Rr,{className:"h-4 w-4"}),"Invite Members"]}),e.jsxs(B,{size:"sm",variant:"outline",className:"gap-1.5",onClick:()=>ve(Yt),children:[e.jsx(Yn,{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:()=>Je.mutate(Yt),disabled:Je.isPending,children:[e.jsx(Y0,{className:"h-4 w-4"}),"LevelUp Live"]}),e.jsxs(B,{size:"sm",variant:"outline",className:"gap-1.5",onClick:()=>window.open(Yt.zoom_link,"_blank"),children:[e.jsx(Tr,{className:"h-4 w-4"}),"Zoom"]})]})]})}),e.jsxs(ya,{defaultValue:"upcoming",className:"w-full",children:[e.jsxs(va,{children:[e.jsxs(ls,{value:"upcoming",className:"gap-2",children:[e.jsx(Xr,{className:"h-4 w-4"}),"Upcoming",e.jsx("span",{className:"ml-1 rounded-full bg-muted px-2 py-0.5 text-xs",children:Bt.length})]}),e.jsxs(ls,{value:"past",className:"gap-2",children:[e.jsx(Hr,{className:"h-4 w-4"}),"Past",e.jsx("span",{className:"ml-1 rounded-full bg-muted px-2 py-0.5 text-xs",children:Ct.length})]})]}),e.jsx(_s,{value:"upcoming",className:"mt-4",children:Xs(Bt,"No upcoming events scheduled.")}),e.jsx(_s,{value:"past",className:"mt-4",children:Xs(Ct,"No past events.")})]})]})})()})]}),e.jsx(TRs,{open:W,onOpenChange:G,event:X}),e.jsx(Bs,{open:y,onOpenChange:x,children:e.jsxs(Fs,{className:"max-w-3xl max-h-[80vh] overflow-y-auto",children:[e.jsxs(qs,{children:[e.jsxs($s,{className:"flex items-center gap-2",children:[e.jsx(Yn,{className:"h-5 w-5"}),_==null?void 0:_.title]}),e.jsx(Ar,{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:()=>Ie.mutate({eventId:_.id,testMode:!0}),disabled:Ie.isPending,children:[e.jsx(mn,{className:Ot("h-4 w-4 mr-2",Ie.isPending&&"animate-spin")}),"Send Test to Me"]}),e.jsxs(B,{variant:"outline",size:"sm",onClick:()=>Ie.mutate({eventId:_.id}),disabled:Ie.isPending||!(ce!=null&&ce.length),children:[e.jsx(mn,{className:Ot("h-4 w-4 mr-2",Ie.isPending&&"animate-spin")}),Ie.isPending?"Sending...":"Send Reminder to All"]}),(_==null?void 0:_.zoom_meeting_id)&&e.jsxs(e.Fragment,{children:[e.jsxs(B,{variant:"outline",size:"sm",onClick:()=>ge.mutate(_.id),disabled:ge.isPending,children:[e.jsx(oo,{className:Ot("h-4 w-4 mr-2",ge.isPending&&"animate-spin")}),ge.isPending?"Syncing...":"Sync Registrations"]}),e.jsxs(B,{variant:"outline",size:"sm",onClick:()=>Se.mutate(),disabled:Se.isPending,children:[e.jsx(oo,{className:Ot("h-4 w-4 mr-2",Se.isPending&&"animate-spin")}),Se.isPending?"Retrying...":"Retry Failed Registrations"]}),e.jsxs(B,{variant:"default",size:"sm",onClick:()=>be.mutate(_.id),disabled:be.isPending,children:[e.jsx(gl,{className:Ot("h-4 w-4 mr-2",be.isPending&&"animate-spin")}),be.isPending?"Syncing...":"Sync Attendees & Award Points"]})]})]}),e.jsxs(ya,{defaultValue:"registrations",className:"w-full",children:[e.jsxs(va,{className:"grid w-full grid-cols-2",children:[e.jsxs(ls,{value:"registrations",className:"gap-2",children:[e.jsx(Yn,{className:"h-4 w-4"}),"Registrations (",(ce==null?void 0:ce.length)||0,")"]}),e.jsxs(ls,{value:"attendees",className:"gap-2",children:[e.jsx(Hr,{className:"h-4 w-4"}),"Attendees (",(he==null?void 0:he.length)||0,")"]})]}),e.jsx(_s,{value:"registrations",className:"mt-4",children:ae?e.jsx("div",{className:"text-center py-8 text-muted-foreground",children:"Loading registrations..."}):(ce==null?void 0:ce.length)===0?e.jsxs("div",{className:"text-center py-8 text-muted-foreground",children:[e.jsx("p",{children:"No registrations yet for this event."}),(_==null?void 0:_.zoom_meeting_id)&&e.jsx("p",{className:"text-xs mt-2",children:'Click "Sync Registrations" to import from Zoom.'})]}):e.jsxs(Oa,{children:[e.jsx(Fa,{children:e.jsxs(un,{children:[e.jsx(Mt,{children:"Name"}),e.jsx(Mt,{children:"Email"}),e.jsx(Mt,{children:"Registered"}),e.jsx(Mt,{children:"Status"})]})}),e.jsx(za,{children:ce==null?void 0:ce.map(Ze=>{var Yt,Kt;const ht=((Yt=Ze.profiles)==null?void 0:Yt.name)||Ze.zoom_name||"Unknown",Bt=((Kt=Ze.profiles)==null?void 0:Kt.email)||Ze.zoom_email||null,Ct=!Ze.user_id;return e.jsxs(un,{children:[e.jsx(gt,{className:"font-medium",children:e.jsxs("div",{className:"flex items-center gap-2",children:[ht,Ct&&e.jsx("span",{className:"text-xs px-1.5 py-0.5 rounded bg-muted text-muted-foreground",children:"External"})]})}),e.jsx(gt,{children:Bt?e.jsxs("a",{href:`mailto:${Bt}`,className:"flex items-center gap-1 text-primary hover:underline",children:[e.jsx(mn,{className:"h-3 w-3"}),Bt]}):e.jsx("span",{className:"text-muted-foreground",children:"No email"})}),e.jsx(gt,{className:"text-muted-foreground text-sm",children:Js(new Date(Ze.registered_at),"MMM d, yyyy h:mm a")}),e.jsx(gt,{children:Ze.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"})})]},Ze.id)})})]})}),e.jsx(_s,{value:"attendees",className:"mt-4",children:xe?e.jsx("div",{className:"text-center py-8 text-muted-foreground",children:"Loading attendees..."}):(he==null?void 0:he.length)===0?e.jsxs("div",{className:"text-center py-8 text-muted-foreground",children:[e.jsx("p",{children:"No attendees recorded yet."}),(_==null?void 0:_.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:[(he==null?void 0:he.filter(Ze=>!Ze.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(Uo,{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 (",he==null?void 0:he.filter(Ze=>!Ze.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:he==null?void 0:he.filter(Ze=>!Ze.user_id).map(Ze=>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:Ze.zoom_name||"Unknown"}),e.jsx("span",{className:"text-xs text-muted-foreground",children:Ze.zoom_email||"No email"})]}),e.jsxs(B,{variant:"outline",size:"sm",onClick:()=>Be(Ze),className:"gap-1",children:[e.jsx(cd,{className:"h-3 w-3"}),"Link to Profile"]})]},Ze.id))})]}),e.jsxs(Oa,{children:[e.jsx(Fa,{children:e.jsxs(un,{children:[e.jsx(Mt,{children:"Name"}),e.jsx(Mt,{children:"Email"}),e.jsx(Mt,{children:"Duration"}),e.jsx(Mt,{children:"Points"})]})}),e.jsx(za,{children:he==null?void 0:he.filter(Ze=>Ze.user_id).map(Ze=>{var Ct,Yt;const ht=((Ct=Ze.profiles)==null?void 0:Ct.name)||Ze.zoom_name||"Unknown",Bt=((Yt=Ze.profiles)==null?void 0:Yt.email)||Ze.zoom_email||null;return e.jsxs(un,{children:[e.jsx(gt,{className:"font-medium",children:e.jsxs("div",{className:"flex items-center gap-2",children:[ht,Ze.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:Bt?e.jsxs("a",{href:`mailto:${Bt}`,className:"flex items-center gap-1 text-primary hover:underline",children:[e.jsx(mn,{className:"h-3 w-3"}),Bt]}):e.jsx("span",{className:"text-muted-foreground",children:"No email"})}),e.jsx(gt,{children:Ze.duration_minutes?e.jsxs("span",{className:"flex items-center gap-1 text-muted-foreground text-sm",children:[e.jsx(Xr,{className:"h-3 w-3"}),Ze.duration_minutes," min"]}):e.jsx("span",{className:"text-muted-foreground text-sm",children:"—"})}),e.jsx(gt,{children:Ze.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(gl,{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"})})]},Ze.id)})})]})]})})]})]})}),e.jsx(Bs,{open:k,onOpenChange:A,children:e.jsxs(Fs,{className:"max-w-md",children:[e.jsxs(qs,{children:[e.jsxs($s,{className:"flex items-center gap-2",children:[e.jsx(cd,{className:"h-5 w-5"}),"Link Attendee to Profile"]}),e.jsx(Ar,{children:"Link this Zoom attendee to an existing member profile to award them points."})]}),T&&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:T.zoom_name||"Unknown"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:T.zoom_email||"No email"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{children:"Search for a profile"}),e.jsxs("div",{className:"relative",children:[e.jsx(Gr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(we,{placeholder:"Search by name or email...",value:$,onChange:Ze=>V(Ze.target.value),className:"pl-9"})]})]}),e.jsx("div",{className:"max-h-48 overflow-y-auto border rounded-md",children:Ge.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:Ge.slice(0,20).map(Ze=>e.jsxs("button",{type:"button",onClick:()=>M(Ze.id),className:Ot("w-full p-3 text-left hover:bg-muted/50 transition-colors",I===Ze.id&&"bg-primary/10 border-l-2 border-primary"),children:[e.jsx("p",{className:"text-sm font-medium",children:Ze.name||"Unnamed"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:Ze.email})]},Ze.id))})}),T.zoom_email&&e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(Bi,{id:"save-alias",checked:L,onCheckedChange:Ze=>z(Ze)}),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:()=>A(!1),children:"Cancel"}),e.jsx(B,{onClick:Ne,disabled:!I||Re.isPending,children:Re.isPending?"Linking...":"Link & Award Points"})]})]})]})})]})})}const MRs={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 LRs(){const[s,t]=N.useState([]),[n,r]=N.useState(!0),[a,i]=N.useState("issues");async function l(){r(!0);let o=H.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 N.useEffect(()=>{l()},[a]),e.jsx(Qs,{title:"MCP Audit Log",children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(Uh,{title:"MCP Audit Log",description:"Recent LevelUp MCP tool calls — ChatGPT / Claude / Codex activity, denials, and rate limits."}),e.jsxs(_e,{children:[e.jsxs(zt,{className:"flex flex-row items-center justify-between",children:[e.jsxs(qt,{className:"flex items-center gap-2",children:[e.jsx(A9,{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(oo,{className:`h-4 w-4 ${n?"animate-spin":""}`})})]})]}),e.jsx(De,{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(We,{className:MRs[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 PRs({selectedKitIds:s,onChange:t}){const[n,r]=N.useState(""),[a,i]=N.useState(!1),{data:l=[]}=mt({queryKey:["all-resource-kits-picker"],queryFn:async()=>{const{data:h,error:m}=await H.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(re,{className:"flex items-center gap-2",children:[e.jsx(Ku,{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(We,{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(hr,{className:"h-3 w-3"})})]},h.id))}),e.jsxs(rc,{open:a,onOpenChange:i,children:[e.jsx(ac,{asChild:!0,children:e.jsxs(B,{type:"button",variant:"outline",size:"sm",className:"gap-1",children:[e.jsx(Ku,{className:"h-3.5 w-3.5"}),"Add Toolkit"]})}),e.jsxs(Zl,{className:"w-80 p-2",align:"start",children:[e.jsxs("div",{className:"relative mb-2",children:[e.jsx(Gr,{className:"absolute left-2 top-2.5 h-3.5 w-3.5 text-muted-foreground"}),e.jsx(we,{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(Ku,{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 IRs=()=>{const{user:s}=Ls(),{toast:t}=Ci(),n=as(),[r,a]=$c(),[i,l]=N.useState(!1),[o,c]=N.useState(null),[d,u]=N.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]=N.useState(null),[f,g]=N.useState(0),[y,x]=N.useState(!1),[_,b]=N.useState(null),[k,A]=N.useState(""),[T,P]=N.useState([]),[I,M]=N.useState(""),[L,z]=N.useState(""),[$,V]=N.useState(!1),[W,G]=N.useState(!1),{data:X=[]}=mt({queryKey:["template-categories"],queryFn:async()=>{const{data:Ae,error:Xe}=await H.from("template_categories").select("*").order("name");if(Xe)throw Xe;return Ae}}),{data:te=[]}=mt({queryKey:["template-types"],queryFn:async()=>{const{data:Ae,error:Xe}=await H.from("template_types").select("*").order("name");if(Xe)throw Xe;return Ae}}),{data:ne=[],isLoading:me}=mt({queryKey:["canva-templates-admin"],queryFn:async()=>{const{data:Ae,error:Xe}=await H.from("canva_templates").select(` *, category:template_categories(id, name), type:template_types(id, name) `).order("publish_date",{ascending:!1});if(Xe)throw Xe;const{data:$e,error:Ye}=await H.from("template_links").select("*").order("sort_order");if(Ye)throw Ye;const{data:Je,error:Ke}=await H.from("template_guides").select("*").order("sort_order");if(Ke)throw Ke;return Ae.map(rt=>({...rt,links:($e==null?void 0:$e.filter(Ze=>Ze.template_id===rt.id))||[],guides:(Je==null?void 0:Je.filter(Ze=>Ze.template_id===rt.id))||[]}))}});N.useEffect(()=>{const Ae=r.get("edit");if(Ae&&ne.length>0){const Xe=ne.find($e=>$e.id===Ae);Xe&&(ge(Xe),a({},{replace:!0}))}},[ne,r]);const ue=_t({mutationFn:async Ae=>{const{data:Xe,error:$e}=await H.from("template_categories").insert({name:Ae}).select().single();if($e)throw $e;return Xe},onSuccess:Ae=>{n.invalidateQueries({queryKey:["template-categories"]}),u({...d,category_id:Ae.id}),M(""),V(!1),t({title:"Category added"})},onError:Ae=>{t({title:"Error adding category",description:Ae.message,variant:"destructive"})}}),ce=_t({mutationFn:async Ae=>{const{data:Xe,error:$e}=await H.from("template_types").insert({name:Ae}).select().single();if($e)throw $e;return Xe},onSuccess:Ae=>{n.invalidateQueries({queryKey:["template-types"]}),u({...d,type_id:Ae.id}),z(""),G(!1),t({title:"Type added"})},onError:Ae=>{t({title:"Error adding type",description:Ae.message,variant:"destructive"})}}),ae=_t({mutationFn:async Ae=>{var Ke;let Xe=Ae.existingImageUrl;if(Ae.image){const st=Ae.image.name.split(".").pop(),rt=`${Date.now()}-${Math.random().toString(36).substring(7)}.${st}`,{error:Ze}=await H.storage.from("template-previews").upload(rt,Ae.image);if(Ze)throw Ze;const{data:ht}=H.storage.from("template-previews").getPublicUrl(rt);Xe=ht.publicUrl}const $e={name:Ae.template.name,description:Ae.template.description||null,category_id:Ae.template.category_id||null,type_id:Ae.template.type_id||null,preview_image_url:Xe,video_url:Ae.videoUrl||null,publish_date:Ae.template.publish_date?new Date(Ae.template.publish_date).toISOString():new Date().toISOString(),created_by:s==null?void 0:s.id};let Ye=Ae.templateId;if(Ye){const{error:st}=await H.from("canva_templates").update($e).eq("id",Ye);if(st)throw st;const{error:rt}=await H.from("template_links").delete().eq("template_id",Ye);if(rt)throw rt;const Ze=((Ke=Ae.existingGuides)==null?void 0:Ke.map(Ct=>Ct.id).filter(Boolean))||[],ht=Ae.template.guides.map(Ct=>Ct.id).filter(Boolean),Bt=Ze.filter(Ct=>!ht.includes(Ct));Bt.length>0&&await H.from("template_guides").delete().in("id",Bt)}else{const{data:st,error:rt}=await H.from("canva_templates").insert($e).select().single();if(rt)throw rt;Ye=st.id,wRs(Ae.template.name,st.id)}const Je=Ae.template.links.filter(st=>st.title.trim()&&st.canva_share_link.trim());if(Je.length>0){const st=Je.map((Ze,ht)=>({template_id:Ye,title:Ze.title.trim(),canva_share_link:Ze.canva_share_link.trim(),sort_order:ht})),{error:rt}=await H.from("template_links").insert(st);if(rt)throw rt}for(let st=0;st0)){const{error:st}=await H.from("resource_kit_templates").insert(Ae.linkedKitIds.map(rt=>({template_id:Ye,kit_id:rt})));if(st)throw st}},onSuccess:()=>{n.invalidateQueries({queryKey:["canva-templates-admin"]}),n.invalidateQueries({queryKey:["canva-templates"]}),ve(),l(!1),t({title:o?"Template updated":"Template created"})},onError:Ae=>{t({title:"Error saving template",description:Ae.message,variant:"destructive"})}}),he=_t({mutationFn:async Ae=>{const{error:Xe}=await H.from("canva_templates").delete().eq("id",Ae);if(Xe)throw Xe},onSuccess:()=>{n.invalidateQueries({queryKey:["canva-templates-admin"]}),n.invalidateQueries({queryKey:["canva-templates"]}),t({title:"Template deleted"})},onError:Ae=>{t({title:"Error deleting template",description:Ae.message,variant:"destructive"})}}),xe=_t({mutationFn:async({id:Ae,is_featured:Xe})=>{const{error:$e}=await H.from("canva_templates").update({is_featured:Xe}).eq("id",Ae);if($e)throw $e},onSuccess:()=>{n.invalidateQueries({queryKey:["canva-templates-admin"]}),n.invalidateQueries({queryKey:["canva-templates"]})},onError:Ae=>{t({title:"Error updating featured",description:Ae.message,variant:"destructive"})}}),ve=()=>{u({name:"",description:"",category_id:"",type_id:"",publish_date:new Date().toISOString().split("T")[0],links:[{title:"",canva_share_link:"",sort_order:0}],guides:[],video_url:""}),b(null),A(""),c(null),V(!1),G(!1),M(""),z(""),m(null),g(0),x(!1),P([])},ge=async Ae=>{var $e;c(Ae),u({name:Ae.name,description:Ae.description||"",category_id:Ae.category_id||"",type_id:Ae.type_id||"",publish_date:Ae.publish_date?new Date(Ae.publish_date).toISOString().split("T")[0]:new Date().toISOString().split("T")[0],links:Ae.links&&Ae.links.length>0?Ae.links.map(Ye=>({id:Ye.id,title:Ye.title,canva_share_link:Ye.canva_share_link,sort_order:Ye.sort_order})):[{title:"",canva_share_link:"",sort_order:0}],guides:(($e=Ae.guides)==null?void 0:$e.map(Ye=>({id:Ye.id,name:Ye.name,file_url:Ye.file_url,file_type:Ye.file_type,file_size:Ye.file_size,sort_order:Ye.sort_order})))||[],video_url:Ae.video_url||""}),A(Ae.preview_image_url||""),m(null);const{data:Xe}=await H.from("resource_kit_templates").select("kit_id").eq("template_id",Ae.id);P((Xe||[]).map(Ye=>Ye.kit_id)),l(!0)},be=Ae=>{var $e;const Xe=($e=Ae.target.files)==null?void 0:$e[0];Xe&&(b(Xe),A(URL.createObjectURL(Xe)))},Se=()=>{u({...d,links:[...d.links,{title:"",canva_share_link:"",sort_order:d.links.length}]})},Ie=Ae=>{if(d.links.length<=1)return;const Xe=d.links.filter(($e,Ye)=>Ye!==Ae);u({...d,links:Xe})},Me=(Ae,Xe,$e)=>{const Ye=[...d.links];Ye[Ae]={...Ye[Ae],[Xe]:$e},u({...d,links:Ye})},Re=Ae=>{const Xe=Ae.target.files;if(!Xe)return;const $e=Array.from(Xe).map((Ye,Je)=>({name:Ye.name.replace(/\.[^/.]+$/,""),file_url:"",file_type:Ye.type,file_size:Ye.size,sort_order:d.guides.length+Je,file:Ye}));u({...d,guides:[...d.guides,...$e]}),Ae.target.value=""},Be=Ae=>{const Xe=d.guides.filter(($e,Ye)=>Ye!==Ae);u({...d,guides:Xe})},Ne=(Ae,Xe)=>{const $e=[...d.guides];$e[Ae]={...$e[Ae],name:Xe},u({...d,guides:$e})},Ge=async()=>{if(!h)return null;x(!0),g(0);try{const{data:Ae,error:Xe}=await H.functions.invoke("bunny-upload",{body:{action:"create",title:d.name||h.name}});if(Xe)throw new Error(Xe.message);const{videoId:$e,libraryId:Ye}=Ae,{data:Je,error:Ke}=await H.functions.invoke("bunny-upload",{body:{action:"upload-url",videoId:$e}});if(Ke)throw new Error(Ke.message);const st=new XMLHttpRequest;return await new Promise((Ze,ht)=>{st.upload.addEventListener("progress",Bt=>{if(Bt.lengthComputable){const Ct=Math.round(Bt.loaded/Bt.total*100);g(Ct)}}),st.addEventListener("load",()=>{st.status>=200&&st.status<300?Ze():ht(new Error(`Upload failed with status ${st.status}`))}),st.addEventListener("error",()=>ht(new Error("Upload failed"))),st.open("PUT",Je.uploadUrl),st.setRequestHeader("AccessKey",Je.apiKey),st.send(h)}),`https://player.mediadelivery.net/embed/${Ye}/${$e}`}catch(Ae){return console.error("Bunny upload error:",Ae),t({title:"Video upload failed",description:Ae instanceof Error?Ae.message:"Unknown error",variant:"destructive"}),null}finally{x(!1)}},Ce=Ae=>{var $e;const Xe=($e=Ae.target.files)==null?void 0:$e[0];Xe&&m(Xe),Ae.target.value=""},Fe=async Ae=>{if(Ae.preventDefault(),!d.name.trim()){t({title:"Please enter a template name",variant:"destructive"});return}if(d.links.filter(Ye=>Ye.title.trim()&&Ye.canva_share_link.trim()).length===0){t({title:"Please add at least one Canva link",variant:"destructive"});return}let $e=d.video_url;if(h){const Ye=await Ge();if(!Ye)return;$e=Ye}ae.mutate({template:d,image:_,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:$e,linkedKitIds:T})};return e.jsx(Qs,{title:"Manage Templates",children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(Uh,{title:"Manage Templates",description:"Create and manage Canva templates"}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"grid grid-cols-3 gap-4",children:[e.jsxs(_e,{children:[e.jsx(zt,{className:"pb-2",children:e.jsx(qt,{className:"text-sm font-medium text-muted-foreground",children:"Total Templates"})}),e.jsx(De,{children:e.jsx("div",{className:"text-2xl font-bold",children:ne.length})})]}),e.jsxs(_e,{children:[e.jsx(zt,{className:"pb-2",children:e.jsx(qt,{className:"text-sm font-medium text-muted-foreground",children:"Categories"})}),e.jsx(De,{children:e.jsx("div",{className:"text-2xl font-bold",children:X.length})})]}),e.jsxs(_e,{children:[e.jsx(zt,{className:"pb-2",children:e.jsx(qt,{className:"text-sm font-medium text-muted-foreground",children:"Template Types"})}),e.jsx(De,{children:e.jsx("div",{className:"text-2xl font-bold",children:te.length})})]})]}),e.jsxs(Bs,{open:i,onOpenChange:Ae=>{l(Ae),Ae||ve()},children:[e.jsx(Ao,{asChild:!0,children:e.jsxs(B,{className:"gap-2",children:[e.jsx(nn,{className:"h-4 w-4"}),"Add Template"]})}),e.jsxs(Fs,{className:"max-w-2xl max-h-[90vh] overflow-y-auto",children:[e.jsx(qs,{children:e.jsx($s,{children:o?"Edit Template":"Add New Template"})}),e.jsxs("form",{onSubmit:Fe,className:"space-y-6 pt-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{htmlFor:"name",children:"Name *"}),e.jsx(we,{id:"name",value:d.name,onChange:Ae=>u({...d,name:Ae.target.value}),placeholder:"Template name",required:!0})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{children:"Description"}),e.jsx(yN,{content:d.description,onChange:Ae=>u({...d,description:Ae}),placeholder:"Brief description of the template",minHeight:"120px"})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(re,{children:"Canva Links *"}),e.jsxs(B,{type:"button",variant:"outline",size:"sm",onClick:Se,className:"gap-1",children:[e.jsx(nn,{className:"h-3 w-3"}),"Add Link"]})]}),e.jsx("div",{className:"space-y-3",children:d.links.map((Ae,Xe)=>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(we,{value:Ae.title,onChange:$e=>Me(Xe,"title",$e.target.value),placeholder:"Link title (e.g., Instagram Post, Story)"}),e.jsx(we,{value:Ae.canva_share_link,onChange:$e=>Me(Xe,"canva_share_link",$e.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:()=>Ie(Xe),children:e.jsx(hr,{className:"h-4 w-4"})})]},Xe))})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{children:"Category"}),$?e.jsxs("div",{className:"flex gap-2",children:[e.jsx(we,{value:I,onChange:Ae=>M(Ae.target.value),placeholder:"New category name",className:"flex-1"}),e.jsx(B,{type:"button",size:"sm",onClick:()=>I.trim()&&ue.mutate(I.trim()),disabled:ue.isPending,children:"Add"}),e.jsx(B,{type:"button",size:"sm",variant:"ghost",onClick:()=>{V(!1),M("")},children:e.jsx(hr,{className:"h-4 w-4"})})]}):e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(Ns,{value:d.category_id,onValueChange:Ae=>u({...d,category_id:Ae}),children:[e.jsx(ws,{className:"flex-1",children:e.jsx(ks,{placeholder:"Select category"})}),e.jsx(js,{children:X.map(Ae=>e.jsx(nt,{value:Ae.id,children:Ae.name},Ae.id))})]}),e.jsx(B,{type:"button",variant:"outline",size:"icon",onClick:()=>V(!0),children:e.jsx(nn,{className:"h-4 w-4"})})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{children:"Template Type"}),W?e.jsxs("div",{className:"flex gap-2",children:[e.jsx(we,{value:L,onChange:Ae=>z(Ae.target.value),placeholder:"New type name",className:"flex-1"}),e.jsx(B,{type:"button",size:"sm",onClick:()=>L.trim()&&ce.mutate(L.trim()),disabled:ce.isPending,children:"Add"}),e.jsx(B,{type:"button",size:"sm",variant:"ghost",onClick:()=>{G(!1),z("")},children:e.jsx(hr,{className:"h-4 w-4"})})]}):e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(Ns,{value:d.type_id,onValueChange:Ae=>u({...d,type_id:Ae}),children:[e.jsx(ws,{className:"flex-1",children:e.jsx(ks,{placeholder:"Select type"})}),e.jsx(js,{children:te.map(Ae=>e.jsx(nt,{value:Ae.id,children:Ae.name},Ae.id))})]}),e.jsx(B,{type:"button",variant:"outline",size:"icon",onClick:()=>G(!0),children:e.jsx(nn,{className:"h-4 w-4"})})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{htmlFor:"publish_date",children:"Publish Date"}),e.jsx(we,{id:"publish_date",type:"date",value:d.publish_date,onChange:Ae=>u({...d,publish_date:Ae.target.value})}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Templates are sorted by publish date (newest first) on the member page"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{children:"Preview Image"}),e.jsxs("div",{className:"flex items-start gap-4",children:[k?e.jsxs("div",{className:"relative w-32 h-24 rounded-lg overflow-hidden border bg-muted",children:[e.jsx("img",{src:k,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),A("")},children:e.jsx(hr,{className:"h-3 w-3"})})]}):e.jsx("div",{className:"w-32 h-24 rounded-lg border-2 border-dashed border-muted-foreground/25 flex items-center justify-center",children:e.jsx(pc,{className:"h-8 w-8 text-muted-foreground/50"})}),e.jsxs("div",{className:"flex-1",children:[e.jsx(we,{type:"file",accept:"image/*",onChange:be,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(re,{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(na,{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(us,{className:"h-4 w-4 animate-spin"}),e.jsxs("span",{className:"text-sm",children:["Uploading video... ",f,"%"]})]}),e.jsx(ro,{value:f,className:"h-2"})]}):h?e.jsxs("div",{className:"flex items-center gap-2 p-3 border rounded-lg bg-muted/30",children:[e.jsx(na,{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(hr,{className:"h-4 w-4"})})]}):e.jsxs("div",{className:"space-y-2",children:[e.jsxs("label",{className:"cursor-pointer",children:[e.jsx(we,{type:"file",accept:"video/*",onChange:Ce,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(na,{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(re,{children:"Guide Files (PDFs)"}),e.jsxs("label",{className:"cursor-pointer",children:[e.jsx(we,{type:"file",accept:".pdf,.doc,.docx",multiple:!0,onChange:Re,className:"hidden"}),e.jsx(B,{type:"button",variant:"outline",size:"sm",className:"gap-1",asChild:!0,children:e.jsxs("span",{children:[e.jsx(ni,{className:"h-3 w-3"}),"Add Files"]})})]})]}),d.guides.length>0?e.jsx("div",{className:"space-y-2",children:d.guides.map((Ae,Xe)=>e.jsxs("div",{className:"flex gap-2 items-center p-3 border rounded-lg bg-muted/30",children:[e.jsx(Wr,{className:"h-5 w-5 text-muted-foreground shrink-0"}),e.jsx(we,{value:Ae.name,onChange:$e=>Ne(Xe,$e.target.value),placeholder:"Guide name",className:"flex-1"}),Ae.file_size&&e.jsxs("span",{className:"text-xs text-muted-foreground shrink-0",children:[(Ae.file_size/1024).toFixed(0)," KB"]}),e.jsx(B,{type:"button",variant:"ghost",size:"icon",className:"shrink-0 text-muted-foreground hover:text-destructive h-8 w-8",onClick:()=>Be(Xe),children:e.jsx(hr,{className:"h-4 w-4"})})]},Ae.id||Xe))}):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(PRs,{selectedKitIds:T,onChange:P}),e.jsxs("div",{className:"flex justify-end gap-2 pt-4",children:[e.jsx(B,{type:"button",variant:"outline",onClick:()=>{l(!1),ve()},children:"Cancel"}),e.jsx(B,{type:"submit",disabled:ae.isPending,children:ae.isPending?"Saving...":o?"Update":"Create"})]})]})]})]})]}),e.jsx(_e,{children:e.jsx(De,{className:"p-0",children:me?e.jsx("div",{className:"text-center py-8 text-muted-foreground",children:"Loading..."}):ne.length===0?e.jsx("div",{className:"text-center py-8 text-muted-foreground",children:"No templates yet. Add your first template!"}):e.jsxs(Oa,{children:[e.jsx(Fa,{children:e.jsxs(un,{children:[e.jsx(Mt,{children:"Preview"}),e.jsx(Mt,{children:"Name"}),e.jsx(Mt,{children:"Links"}),e.jsx(Mt,{children:"Category"}),e.jsx(Mt,{children:"Type"}),e.jsx(Mt,{children:"Publish Date"}),e.jsx(Mt,{className:"w-[72px] text-center",children:"Featured"}),e.jsx(Mt,{className:"text-right",children:"Actions"})]})}),e.jsx(za,{children:ne.map(Ae=>{var Xe,$e,Ye,Je,Ke;return e.jsxs(un,{children:[e.jsx(gt,{children:e.jsx("div",{className:"w-16 h-12 rounded overflow-hidden bg-muted",children:Ae.preview_image_url?e.jsx("img",{src:Ae.preview_image_url,alt:Ae.name,className:"w-full h-full object-cover"}):e.jsx("div",{className:"w-full h-full flex items-center justify-center",children:e.jsx(pc,{className:"h-4 w-4 text-muted-foreground"})})})}),e.jsx(gt,{className:"font-medium",children:Ae.name}),e.jsx(gt,{children:e.jsxs("div",{className:"flex flex-col gap-1",children:[e.jsxs(We,{variant:"secondary",children:[((Xe=Ae.links)==null?void 0:Xe.length)||0," link",((($e=Ae.links)==null?void 0:$e.length)||0)!==1?"s":""]}),(((Ye=Ae.guides)==null?void 0:Ye.length)||0)>0&&e.jsxs(We,{variant:"outline",className:"gap-1",children:[e.jsx(Wr,{className:"h-3 w-3"}),(Je=Ae.guides)==null?void 0:Je.length," guide",(((Ke=Ae.guides)==null?void 0:Ke.length)||0)!==1?"s":""]})]})}),e.jsx(gt,{children:Ae.category?e.jsx(We,{variant:"secondary",children:Ae.category.name}):e.jsx("span",{className:"text-muted-foreground",children:"-"})}),e.jsx(gt,{children:Ae.type?e.jsx(We,{variant:"outline",children:Ae.type.name}):e.jsx("span",{className:"text-muted-foreground",children:"-"})}),e.jsx(gt,{className:"text-muted-foreground",children:new Date(Ae.publish_date).toLocaleDateString()}),e.jsx(gt,{className:"text-center",children:e.jsx(B,{type:"button",size:"icon",variant:"ghost",className:"mx-auto",title:Ae.is_featured?"Remove from featured templates":"Add to featured templates",onClick:()=>xe.mutate({id:Ae.id,is_featured:!Ae.is_featured}),children:e.jsx(Wa,{className:`h-4 w-4 ${Ae.is_featured?"fill-yellow-400 text-yellow-400":"text-muted-foreground"}`})})}),e.jsx(gt,{className:"text-right",children:e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx(B,{size:"icon",variant:"ghost",onClick:()=>ge(Ae),children:e.jsx(Ja,{className:"h-4 w-4"})}),e.jsx(B,{size:"icon",variant:"ghost",className:"text-destructive hover:text-destructive",onClick:()=>{confirm("Delete this template?")&&he.mutate(Ae.id)},children:e.jsx(qn,{className:"h-4 w-4"})})]})})]},Ae.id)})})]})})})]})})};function DEt({selectedTemplateIds:s,onChange:t}){const[n,r]=N.useState(""),[a,i]=N.useState(!1),{data:l=[]}=mt({queryKey:["all-canva-templates-picker"],queryFn:async()=>{const{data:h,error:m}=await H.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(re,{className:"flex items-center gap-2",children:[e.jsx(a3,{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(We,{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(hr,{className:"h-3 w-3"})})]},h.id))}),e.jsxs(rc,{open:a,onOpenChange:i,children:[e.jsx(ac,{asChild:!0,children:e.jsxs(B,{type:"button",variant:"outline",size:"sm",className:"gap-1",children:[e.jsx(a3,{className:"h-3.5 w-3.5"}),"Add Template"]})}),e.jsxs(Zl,{className:"w-80 p-2",align:"start",children:[e.jsxs("div",{className:"relative mb-2",children:[e.jsx(Gr,{className:"absolute left-2 top-2.5 h-3.5 w-3.5 text-muted-foreground"}),e.jsx(we,{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(a3,{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 DRs=[{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"}],RRs=()=>{const{user:s}=Ls(),[t,n]=$c(),{toast:r}=Ci(),a=as(),[i,l]=N.useState(!1),[o,c]=N.useState(null),[d,u]=N.useState({title:"",description:"",video_url:"",video_type:"youtube",duration:"",category_id:"",publish_date:new Date().toISOString().split("T")[0],is_published:!1}),[h,m]=N.useState(null),[f,g]=N.useState(""),[y,x]=N.useState([]),[_,b]=N.useState([]),[k,A]=N.useState([]),[T,P]=N.useState([]),[I,M]=N.useState(""),[L,z]=N.useState(!1),[$,V]=N.useState(null),[W,G]=N.useState(0),[X,te]=N.useState(!1),[ne,me]=N.useState(null),{data:ue=[]}=mt({queryKey:["academy-categories"],queryFn:async()=>{const{data:Ae,error:Xe}=await H.from("academy_categories").select("*").order("sort_order",{ascending:!0});if(Xe)throw Xe;return Ae}}),{data:ce=[],isLoading:ae}=mt({queryKey:["academy-videos-admin"],queryFn:async()=>{const{data:Ae,error:Xe}=await H.from("academy_videos").select(` *, category:academy_categories(id, name) `).order("publish_date",{ascending:!1});if(Xe)throw Xe;const{data:$e,error:Ye}=await H.from("academy_resources").select("*").order("sort_order");if(Ye)throw Ye;return Ae.map(Ke=>({...Ke,resources:($e==null?void 0:$e.filter(st=>st.video_id===Ke.id))||[]}))}});N.useEffect(()=>{const Ae=t.get("edit");if(Ae&&ce.length>0){const Xe=ce.find($e=>$e.id===Ae);Xe&&(Me(Xe),n({},{replace:!0}))}},[ce,t]);const he=_t({mutationFn:async Ae=>{const{data:Xe,error:$e}=await H.from("academy_categories").insert({name:Ae,sort_order:ue.length}).select().single();if($e)throw $e;return Xe},onSuccess:Ae=>{a.invalidateQueries({queryKey:["academy-categories"]}),u({...d,category_id:Ae.id}),M(""),z(!1),r({title:"Category added"})},onError:Ae=>{r({title:"Error adding category",description:Ae.message,variant:"destructive"})}}),xe=_t({mutationFn:async Ae=>{let Xe=Ae.existingThumbnailUrl;if(Ae.thumbnail){const Je=Ae.thumbnail.name.split(".").pop(),Ke=`thumbnails/${Date.now()}-${Math.random().toString(36).substring(7)}.${Je}`,{error:st}=await H.storage.from("academy-resources").upload(Ke,Ae.thumbnail);if(st)throw st;const{data:rt}=H.storage.from("academy-resources").getPublicUrl(Ke);Xe=rt.publicUrl}const $e={title:Ae.video.title,description:Ae.video.description||null,video_url:Ae.video.video_url,video_type:Ae.video.video_type,duration:Ae.video.duration||null,thumbnail_url:Xe,category_id:Ae.video.category_id||null,publish_date:Ae.video.publish_date?new Date(Ae.video.publish_date).toISOString():new Date().toISOString(),is_published:Ae.video.is_published,created_by:s==null?void 0:s.id};let Ye=Ae.videoId;if(Ye){const{error:Je}=await H.from("academy_videos").update($e).eq("id",Ye);if(Je)throw Je}else{const{data:Je,error:Ke}=await H.from("academy_videos").insert($e).select().single();if(Ke)throw Ke;Ye=Je.id,jRs(Ae.video.title,Je.id)}if(Ae.resourcesToDelete.length>0){const{error:Je}=await H.from("academy_resources").delete().in("id",Ae.resourcesToDelete);if(Je)throw Je}for(let Je=0;Je0){const{error:Je}=await H.from("academy_video_templates").insert(T.map(Ke=>({video_id:Ye,template_id:Ke})));if(Je)throw Je}},onSuccess:()=>{a.invalidateQueries({queryKey:["academy-videos-admin"]}),a.invalidateQueries({queryKey:["academy-videos"]}),Ie(),l(!1),r({title:o?"Video updated":"Video created"})},onError:Ae=>{r({title:"Error saving video",description:Ae.message,variant:"destructive"})}}),ve=_t({mutationFn:async Ae=>{const{error:Xe}=await H.from("academy_videos").delete().eq("id",Ae);if(Xe)throw Xe},onSuccess:()=>{a.invalidateQueries({queryKey:["academy-videos-admin"]}),a.invalidateQueries({queryKey:["academy-videos"]}),r({title:"Video deleted"})},onError:Ae=>{r({title:"Error deleting video",description:Ae.message,variant:"destructive"})}}),ge=_t({mutationFn:async({id:Ae,is_published:Xe})=>{const{error:$e}=await H.from("academy_videos").update({is_published:Xe}).eq("id",Ae);if($e)throw $e},onSuccess:()=>{a.invalidateQueries({queryKey:["academy-videos-admin"]}),a.invalidateQueries({queryKey:["academy-videos"]})},onError:Ae=>{r({title:"Error updating video",description:Ae.message,variant:"destructive"})}}),be=async Ae=>{try{let Xe=Ae.public_slug||null,$e=!!Ae.is_public;if(!Xe||!$e){const Je=(Ae.title||"video").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,60)||"video";if(!Xe){let st=Je;const{data:rt}=await H.from("academy_videos").select("id").eq("public_slug",st).maybeSingle();rt&&rt.id!==Ae.id&&(st=`${Je}-${Ae.id.slice(0,6)}`),Xe=st}const{error:Ke}=await H.from("academy_videos").update({public_slug:Xe,is_public:!0}).eq("id",Ae.id);if(Ke)throw Ke;a.invalidateQueries({queryKey:["academy-videos-admin"]})}const Ye=`${window.location.origin}/watch/${Xe}`;await navigator.clipboard.writeText(Ye),r({title:"Public link copied",description:Ye})}catch(Xe){r({title:"Could not copy link",description:Xe.message,variant:"destructive"})}},Se=async Ae=>{if(!confirm("Disable the public teaser link for this video?"))return;const{error:Xe}=await H.from("academy_videos").update({is_public:!1}).eq("id",Ae.id);if(Xe){r({title:"Error",description:Xe.message,variant:"destructive"});return}a.invalidateQueries({queryKey:["academy-videos-admin"]}),r({title:"Public link disabled"})},Ie=()=>{u({title:"",description:"",video_url:"",video_type:"bunny_stream",duration:"",category_id:"",publish_date:new Date().toISOString().split("T")[0],is_published:!1}),m(null),g(""),x([]),b([]),A([]),c(null),P([]),M(""),V(null),G(0),te(!1),me(null)},Me=async Ae=>{c(Ae),u({title:Ae.title,description:Ae.description||"",video_url:Ae.video_url,video_type:Ae.video_type,duration:Ae.duration||"",category_id:Ae.category_id||"",publish_date:Ae.publish_date?new Date(Ae.publish_date).toISOString().split("T")[0]:new Date().toISOString().split("T")[0],is_published:Ae.is_published}),g(Ae.thumbnail_url||""),b(Ae.resources||[]),x([]),A([]);const{data:Xe}=await H.from("academy_video_templates").select("template_id").eq("video_id",Ae.id);P((Xe||[]).map($e=>$e.template_id)),l(!0)},Re=Ae=>{var $e;const Xe=($e=Ae.target.files)==null?void 0:$e[0];Xe&&(m(Xe),g(URL.createObjectURL(Xe)))},Be=Ae=>{const Xe=Ae.target.files;if(Xe){const $e=Array.from(Xe).map(Ye=>({file:Ye,title:Ye.name.replace(/\.[^/.]+$/,"")}));x([...y,...$e])}Ae.target.value=""},Ne=Ae=>{x(y.filter((Xe,$e)=>$e!==Ae))},Ge=Ae=>{A([...k,Ae]),b(_.filter(Xe=>Xe.id!==Ae))},Ce=async()=>{if(!$)return null;te(!0),G(0);try{const{data:Ae,error:Xe}=await H.functions.invoke("bunny-upload",{body:{action:"create",title:d.title||$.name}});if(Xe)throw new Error(Xe.message);const{videoId:$e,libraryId:Ye}=Ae;me($e);const{data:Je,error:Ke}=await H.functions.invoke("bunny-upload",{body:{action:"upload-url",videoId:$e}});if(Ke)throw new Error(Ke.message);const st=new XMLHttpRequest;return await new Promise((Ze,ht)=>{st.upload.addEventListener("progress",Bt=>{if(Bt.lengthComputable){const Ct=Math.round(Bt.loaded/Bt.total*100);G(Ct)}}),st.addEventListener("load",()=>{st.status>=200&&st.status<300?Ze():ht(new Error(`Upload failed with status ${st.status}`))}),st.addEventListener("error",()=>ht(new Error("Upload failed"))),st.open("PUT",Je.uploadUrl),st.setRequestHeader("AccessKey",Je.apiKey),st.send($)}),`https://player.mediadelivery.net/embed/${Ye}/${$e}`}catch(Ae){return console.error("Bunny upload error:",Ae),r({title:"Video upload failed",description:Ae instanceof Error?Ae.message:"Unknown error",variant:"destructive"}),null}finally{te(!1)}},Fe=async Ae=>{if(Ae.preventDefault(),!d.title.trim()){r({title:"Please enter a video title",variant:"destructive"});return}let Xe=d.video_url;if(d.video_type==="bunny_stream"&&$&&!o){const $e=await Ce();if(!$e)return;Xe=$e}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"&&!$&&!d.video_url&&!o){r({title:"Please select a video file to upload",variant:"destructive"});return}xe.mutate({video:{...d,video_url:Xe},thumbnail:h,existingThumbnailUrl:(o==null?void 0:o.thumbnail_url)||null,videoId:o==null?void 0:o.id,newResources:y,resourcesToDelete:k})};return e.jsx(Qs,{title:"Manage Academy",children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(Uh,{title:"Manage Academy",description:"Create and manage training videos and resources"}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4",children:[e.jsxs(_e,{children:[e.jsx(zt,{className:"pb-2",children:e.jsx(qt,{className:"text-sm font-medium text-muted-foreground",children:"Total Videos"})}),e.jsx(De,{children:e.jsx("div",{className:"text-2xl font-bold",children:ce.length})})]}),e.jsxs(_e,{children:[e.jsx(zt,{className:"pb-2",children:e.jsx(qt,{className:"text-sm font-medium text-muted-foreground",children:"Published"})}),e.jsx(De,{children:e.jsx("div",{className:"text-2xl font-bold",children:ce.filter(Ae=>Ae.is_published).length})})]}),e.jsxs(_e,{children:[e.jsx(zt,{className:"pb-2",children:e.jsx(qt,{className:"text-sm font-medium text-muted-foreground",children:"Public Teasers"})}),e.jsx(De,{children:e.jsx("div",{className:"text-2xl font-bold",children:ce.filter(Ae=>Ae.is_public).length})})]}),e.jsxs(_e,{children:[e.jsx(zt,{className:"pb-2",children:e.jsx(qt,{className:"text-sm font-medium text-muted-foreground",children:"Total Public Views"})}),e.jsx(De,{children:e.jsx("div",{className:"text-2xl font-bold",children:ce.reduce((Ae,Xe)=>Ae+(Xe.public_view_count||0),0).toLocaleString()})})]})]}),e.jsxs(Bs,{open:i,onOpenChange:Ae=>{l(Ae),Ae||Ie()},children:[e.jsx(Ao,{asChild:!0,children:e.jsxs(B,{className:"gap-2",children:[e.jsx(nn,{className:"h-4 w-4"}),"Add Video"]})}),e.jsxs(Fs,{className:"max-w-2xl max-h-[90vh] overflow-y-auto",children:[e.jsx(qs,{children:e.jsx($s,{children:o?"Edit Video":"Add New Video"})}),e.jsxs("form",{onSubmit:Fe,className:"space-y-6 pt-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{htmlFor:"title",children:"Title *"}),e.jsx(we,{id:"title",value:d.title,onChange:Ae=>u({...d,title:Ae.target.value}),placeholder:"Video title",required:!0})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{children:"Description"}),e.jsx(yN,{content:d.description,onChange:Ae=>u({...d,description:Ae}),placeholder:"Brief description of the video",minHeight:"120px"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{children:"Video Type"}),e.jsxs(Ns,{value:d.video_type,onValueChange:Ae=>{u({...d,video_type:Ae,video_url:""}),V(null)},disabled:X,children:[e.jsx(ws,{children:e.jsx(ks,{})}),e.jsx(js,{children:DRs.map(Ae=>e.jsx(nt,{value:Ae.value,children:Ae.label},Ae.value))})]})]}),d.video_type==="bunny_stream"?e.jsxs("div",{className:"space-y-3",children:[e.jsxs(re,{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(we,{type:"file",accept:"video/*",onChange:Ae=>{var $e;const Xe=($e=Ae.target.files)==null?void 0:$e[0];Xe&&V(Xe)},disabled:X}),$&&e.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[e.jsx(na,{className:"h-4 w-4"}),$.name," (",($.size/(1024*1024)).toFixed(1)," MB)"]}),X&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(us,{className:"h-4 w-4 animate-spin"}),e.jsx("span",{className:"text-sm",children:"Uploading to Bunny.net..."})]}),e.jsx(ro,{value:W,className:"h-2"}),e.jsxs("p",{className:"text-xs text-muted-foreground text-right",children:[W,"%"]})]})]})]}):e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{htmlFor:"video_url",children:"Video URL *"}),e.jsx(we,{id:"video_url",value:d.video_url,onChange:Ae=>u({...d,video_url:Ae.target.value}),placeholder:"https://...",required:!0})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{htmlFor:"duration",children:"Duration"}),e.jsx(we,{id:"duration",value:d.duration,onChange:Ae=>u({...d,duration:Ae.target.value}),placeholder:"e.g., 45:30"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{htmlFor:"publish_date",children:"Publish Date"}),e.jsx(we,{id:"publish_date",type:"date",value:d.publish_date,onChange:Ae=>u({...d,publish_date:Ae.target.value})})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{children:"Category"}),L?e.jsxs("div",{className:"flex gap-2",children:[e.jsx(we,{value:I,onChange:Ae=>M(Ae.target.value),placeholder:"New category name",className:"flex-1"}),e.jsx(B,{type:"button",size:"sm",onClick:()=>I.trim()&&he.mutate(I.trim()),disabled:he.isPending,children:"Add"}),e.jsx(B,{type:"button",size:"sm",variant:"ghost",onClick:()=>{z(!1),M("")},children:e.jsx(hr,{className:"h-4 w-4"})})]}):e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(Ns,{value:d.category_id,onValueChange:Ae=>u({...d,category_id:Ae}),children:[e.jsx(ws,{className:"flex-1",children:e.jsx(ks,{placeholder:"Select category"})}),e.jsx(js,{children:ue.map(Ae=>e.jsx(nt,{value:Ae.id,children:Ae.name},Ae.id))})]}),e.jsx(B,{type:"button",variant:"outline",size:"sm",onClick:()=>z(!0),children:e.jsx(nn,{className:"h-4 w-4"})})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{children:"Thumbnail Image"}),e.jsxs("div",{className:"flex items-start gap-4",children:[f&&e.jsx("img",{src:f,alt:"Thumbnail preview",className:"w-32 h-20 object-cover rounded-md border"}),e.jsxs("div",{className:"flex-1",children:[e.jsx(we,{type:"file",accept:"image/*",onChange:Re,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(re,{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(ni,{className:"h-3 w-3"}),"Add Files",e.jsx("input",{type:"file",multiple:!0,accept:".pdf,.pptx,.ppt,.xlsx,.xls,.docx,.doc,.zip",onChange:Be,className:"hidden"})]})})]}),(_.length>0||y.length>0)&&e.jsxs("div",{className:"space-y-2 mt-2",children:[_.map(Ae=>e.jsxs("div",{className:"flex items-center gap-2 p-2 border rounded-md bg-muted/30",children:[e.jsx(Wr,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{className:"flex-1 text-sm truncate",children:Ae.title}),e.jsx(We,{variant:"outline",className:"text-xs",children:Ae.file_type}),e.jsx(B,{type:"button",variant:"ghost",size:"sm",onClick:()=>Ge(Ae.id),className:"text-destructive hover:text-destructive",children:e.jsx(hr,{className:"h-4 w-4"})})]},Ae.id)),y.map((Ae,Xe)=>e.jsxs("div",{className:"flex items-center gap-2 p-2 border rounded-md bg-muted/30",children:[e.jsx(Wr,{className:"h-4 w-4 text-muted-foreground"}),e.jsx(we,{value:Ae.title,onChange:$e=>{const Ye=[...y];Ye[Xe].title=$e.target.value,x(Ye)},className:"flex-1 h-8",placeholder:"Resource title"}),e.jsx(We,{variant:"secondary",className:"text-xs",children:"New"}),e.jsx(B,{type:"button",variant:"ghost",size:"sm",onClick:()=>Ne(Xe),className:"text-destructive hover:text-destructive",children:e.jsx(hr,{className:"h-4 w-4"})})]},Xe))]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Supported: PDF, PowerPoint, Excel, Word, ZIP"})]}),e.jsx(DEt,{selectedTemplateIds:T,onChange:P}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(zn,{id:"is_published",checked:d.is_published,onCheckedChange:Ae=>u({...d,is_published:Ae})}),e.jsx(re,{htmlFor:"is_published",children:"Published"})]}),e.jsxs(Cr,{children:[e.jsx(B,{type:"button",variant:"outline",onClick:()=>l(!1),disabled:X,children:"Cancel"}),e.jsx(B,{type:"submit",disabled:xe.isPending||X,children:X?e.jsxs(e.Fragment,{children:[e.jsx(us,{className:"h-4 w-4 mr-2 animate-spin"}),"Uploading..."]}):xe.isPending?"Saving...":o?"Update Video":"Add Video"})]})]})]})]})]}),e.jsx(_e,{children:e.jsx(De,{className:"p-0",children:ae?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"})}):ce.length===0?e.jsxs("div",{className:"text-center py-8 text-muted-foreground",children:[e.jsx(na,{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(Oa,{children:[e.jsx(Fa,{children:e.jsxs(un,{children:[e.jsx(Mt,{children:"Title"}),e.jsx(Mt,{children:"Category"}),e.jsx(Mt,{children:"Duration"}),e.jsx(Mt,{children:"Resources"}),e.jsx(Mt,{children:"Publish Date"}),e.jsx(Mt,{children:"Status"}),e.jsx(Mt,{children:"Public Views"}),e.jsx(Mt,{className:"w-[120px]",children:"Actions"})]})}),e.jsx(za,{children:ce.map(Ae=>e.jsxs(un,{children:[e.jsx(gt,{children:e.jsxs("div",{className:"flex items-center gap-3",children:[Ae.thumbnail_url?e.jsx("img",{src:Ae.thumbnail_url,alt:"",className:"w-16 h-10 object-cover rounded"}):e.jsx("div",{className:"w-16 h-10 bg-muted rounded flex items-center justify-center",children:e.jsx(na,{className:"h-4 w-4 text-muted-foreground"})}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:Ae.title}),e.jsx("p",{className:"text-xs text-muted-foreground capitalize",children:Ae.video_type.replace("_"," ")})]})]})}),e.jsx(gt,{children:Ae.category?e.jsx(We,{variant:"outline",children:Ae.category.name}):e.jsx("span",{className:"text-muted-foreground text-sm",children:"-"})}),e.jsx(gt,{children:Ae.duration||"-"}),e.jsx(gt,{children:Ae.resources&&Ae.resources.length>0?e.jsxs(We,{variant:"secondary",children:[Ae.resources.length," file(s)"]}):e.jsx("span",{className:"text-muted-foreground text-sm",children:"-"})}),e.jsx(gt,{children:new Date(Ae.publish_date).toLocaleDateString()}),e.jsx(gt,{children:e.jsx(zn,{checked:Ae.is_published,onCheckedChange:Xe=>ge.mutate({id:Ae.id,is_published:Xe})})}),e.jsx(gt,{children:Ae.is_public?e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(da,{className:"h-3.5 w-3.5 text-muted-foreground"}),e.jsx("span",{className:"text-sm font-medium",children:(Ae.public_view_count||0).toLocaleString()})]}):e.jsx("span",{className:"text-muted-foreground text-sm",children:"-"})}),e.jsx(gt,{children:e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(B,{variant:"ghost",size:"sm",title:Ae.is_public?"Copy public teaser link":"Make public & copy teaser link",onClick:()=>be(Ae),children:Ae.is_public?e.jsx(Pa,{className:"h-4 w-4 text-primary"}):e.jsx(Md,{className:"h-4 w-4"})}),Ae.is_public&&e.jsx(B,{variant:"ghost",size:"sm",title:"Disable public link",onClick:()=>Se(Ae),children:e.jsx(au,{className:"h-4 w-4 text-emerald-500"})}),e.jsx(B,{variant:"ghost",size:"sm",onClick:()=>Me(Ae),children:e.jsx(Ja,{className:"h-4 w-4"})}),e.jsx(B,{variant:"ghost",size:"sm",onClick:()=>ve.mutate(Ae.id),className:"text-destructive hover:text-destructive",children:e.jsx(qn,{className:"h-4 w-4"})})]})})]},Ae.id))})]})})})]})})};function ORs(){var xe,ve,ge;const s=as(),[t,n]=$c(),[r,a]=N.useState(!1),[i,l]=N.useState(null),[o,c]=N.useState({name:"",description:"",publish_date:new Date().toISOString().split("T")[0],is_published:!1}),[d,u]=N.useState(null),[h,m]=N.useState(""),[f,g]=N.useState([]),[y,x]=N.useState([]),[_,b]=N.useState([]),[k,A]=N.useState(null),{data:T,isLoading:P}=mt({queryKey:["resource-kits"],queryFn:async()=>{const{data:be,error:Se}=await H.from("resource_kits").select("*").order("publish_date",{ascending:!1});if(Se)throw Se;return be}}),{data:I}=mt({queryKey:["resource-kit-files"],queryFn:async()=>{const{data:be,error:Se}=await H.from("resource_kit_files").select("*").order("sort_order",{ascending:!0});if(Se)throw Se;return be}}),{data:M}=mt({queryKey:["resource-kit-links"],queryFn:async()=>{const{data:be,error:Se}=await H.from("resource_kit_links").select("*").order("sort_order",{ascending:!0});if(Se)throw Se;return be}});N.useEffect(()=>{const be=t.get("edit");if(be&&T&&T.length>0&&I&&M){const Se=T.find(Ie=>Ie.id===be);Se&&(z(Se),n({},{replace:!0}))}},[T,I,M,t]);const L=()=>{c({name:"",description:"",publish_date:new Date().toISOString().split("T")[0],is_published:!1}),u(null),m(""),g([]),x([]),b([]),l(null)},z=async be=>{l(be),c({name:be.name,description:be.description||"",publish_date:be.publish_date.split("T")[0],is_published:be.is_published}),m(be.featured_image_url||"");const Se=(I==null?void 0:I.filter(Re=>Re.kit_id===be.id))||[];g(Se.map(Re=>({id:Re.id,name:Re.name,file_url:Re.file_url,file_type:Re.file_type,file_size:Re.file_size,sort_order:Re.sort_order})));const Ie=(M==null?void 0:M.filter(Re=>Re.kit_id===be.id))||[];x(Ie.map(Re=>({id:Re.id,title:Re.title,canva_share_link:Re.canva_share_link,sort_order:Re.sort_order})));const{data:Me}=await H.from("resource_kit_templates").select("template_id").eq("kit_id",be.id);b((Me||[]).map(Re=>Re.template_id)),a(!0)},$=be=>{var Ie;const Se=(Ie=be.target.files)==null?void 0:Ie[0];Se&&(u(Se),m(URL.createObjectURL(Se)))},V=()=>{g([...f,{name:"",file_url:"",sort_order:f.length}])},W=be=>{g(f.filter((Se,Ie)=>Ie!==be))},G=(be,Se,Ie)=>{const Me=[...f];Me[be]={...Me[be],[Se]:Ie},g(Me)},X=()=>{x([...y,{title:"",canva_share_link:"",sort_order:y.length}])},te=be=>{x(y.filter((Se,Ie)=>Ie!==be))},ne=(be,Se,Ie)=>{const Me=[...y];Me[be]={...Me[be],[Se]:Ie},x(Me)},me=(be,Se)=>{var Me;const Ie=(Me=Se.target.files)==null?void 0:Me[0];if(Ie){const Re=[...f],Be=Ie.name.replace(/\.[^/.]+$/,"");Re[be]={...Re[be],file:Ie,file_type:Ie.type,file_size:Ie.size,name:Re[be].name||Be},g(Re)}},ue=_t({mutationFn:async()=>{let be=(i==null?void 0:i.featured_image_url)||null;if(d){const Be=d.name.split(".").pop(),Ne=`${Date.now()}.${Be}`,{error:Ge}=await H.storage.from("resource-kits").upload(`featured/${Ne}`,d);if(Ge)throw Ge;const{data:Ce}=H.storage.from("resource-kits").getPublicUrl(`featured/${Ne}`);be=Ce.publicUrl}const Se={name:o.name,description:o.description||null,featured_image_url:be,publish_date:o.publish_date,is_published:o.is_published};let Ie;const Me=!i,Re=(i==null?void 0:i.is_published)||!1;if(i){const{error:Be}=await H.from("resource_kits").update(Se).eq("id",i.id);if(Be)throw Be;Ie=i.id;const Ne=(I==null?void 0:I.filter($e=>$e.kit_id===i.id).map($e=>$e.id))||[],Ge=f.filter($e=>$e.id).map($e=>$e.id),Ce=Ne.filter($e=>!Ge.includes($e));Ce.length>0&&await H.from("resource_kit_files").delete().in("id",Ce);const Fe=(M==null?void 0:M.filter($e=>$e.kit_id===i.id).map($e=>$e.id))||[],Ae=y.filter($e=>$e.id).map($e=>$e.id),Xe=Fe.filter($e=>!Ae.includes($e));Xe.length>0&&await H.from("resource_kit_links").delete().in("id",Xe)}else{const{data:Be,error:Ne}=await H.from("resource_kits").insert(Se).select().single();if(Ne)throw Ne;Ie=Be.id}for(let Be=0;Be0){const{error:Be}=await H.from("resource_kit_templates").insert(_.map(Ne=>({kit_id:Ie,template_id:Ne})));if(Be)throw Be}return{kitId:Ie,kitName:o.name,isNewKit:Me,wasPublished:Re,isPublished:o.is_published}},onSuccess:be=>{s.invalidateQueries({queryKey:["resource-kits"]}),s.invalidateQueries({queryKey:["resource-kit-files"]}),s.invalidateQueries({queryKey:["resource-kit-links"]}),ie.success(i?"Resource kit updated":"Resource kit created"),be.isPublished&&(be.isNewKit||!be.wasPublished)&&kRs(be.kitName,be.kitId),a(!1),L()},onError:be=>{ie.error("Failed to save resource kit: "+be.message)}}),ce=_t({mutationFn:async be=>{const{error:Se}=await H.from("resource_kits").delete().eq("id",be);if(Se)throw Se},onSuccess:()=>{s.invalidateQueries({queryKey:["resource-kits"]}),s.invalidateQueries({queryKey:["resource-kit-files"]}),ie.success("Resource kit deleted")},onError:be=>{ie.error("Failed to delete: "+be.message)}}),ae=be=>{if(be.preventDefault(),!o.name){ie.error("Please enter a name");return}ue.mutate()},he=be=>(I==null?void 0:I.filter(Se=>Se.kit_id===be).length)||0;return e.jsx(Qs,{title:"Toolbox Management",description:"Create and manage resource kits for agents",children:e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex justify-between items-center",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs(_e,{children:[e.jsx(zt,{className:"pb-2",children:e.jsx(qt,{className:"text-sm font-medium text-muted-foreground",children:"Total Kits"})}),e.jsx(De,{children:e.jsx("div",{className:"text-2xl font-bold",children:(T==null?void 0:T.length)||0})})]}),e.jsxs(_e,{children:[e.jsx(zt,{className:"pb-2",children:e.jsx(qt,{className:"text-sm font-medium text-muted-foreground",children:"Published"})}),e.jsx(De,{children:e.jsx("div",{className:"text-2xl font-bold",children:(T==null?void 0:T.filter(be=>be.is_published).length)||0})})]})]}),e.jsxs(B,{onClick:()=>{L(),a(!0)},children:[e.jsx(nn,{className:"h-4 w-4 mr-2"}),"Add Resource Kit"]})]}),e.jsx(_e,{children:e.jsx(De,{className:"p-0",children:e.jsxs(Oa,{children:[e.jsx(Fa,{children:e.jsxs(un,{children:[e.jsx(Mt,{children:"Name"}),e.jsx(Mt,{children:"Files"}),e.jsx(Mt,{children:"Publish Date"}),e.jsx(Mt,{children:"Status"}),e.jsx(Mt,{className:"text-right",children:"Actions"})]})}),e.jsx(za,{children:P?e.jsx(un,{children:e.jsx(gt,{colSpan:5,className:"text-center py-8",children:"Loading..."})}):(T==null?void 0:T.length)===0?e.jsx(un,{children:e.jsx(gt,{colSpan:5,className:"text-center py-8 text-muted-foreground",children:"No resource kits yet. Create your first one!"})}):T==null?void 0:T.map(be=>e.jsxs(un,{children:[e.jsx(gt,{children:e.jsxs("div",{className:"flex items-center gap-3",children:[be.featured_image_url?e.jsx("img",{src:be.featured_image_url,alt:be.name,className:"w-10 h-10 rounded object-cover"}):e.jsx("div",{className:"w-10 h-10 rounded bg-muted flex items-center justify-center",children:e.jsx(Ku,{className:"h-5 w-5 text-muted-foreground"})}),e.jsxs("div",{children:[e.jsx("div",{className:"font-medium",children:be.name}),be.description&&e.jsx("div",{className:"text-sm text-muted-foreground line-clamp-1",children:be.description})]})]})}),e.jsx(gt,{children:e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(Wr,{className:"h-4 w-4 text-muted-foreground"}),he(be.id)]})}),e.jsx(gt,{children:Js(new Date(be.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 ${be.is_published?"bg-green-100 text-green-800":"bg-yellow-100 text-yellow-800"}`,children:be.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 Se=(I==null?void 0:I.filter(Me=>Me.kit_id===be.id))||[],Ie=(M==null?void 0:M.filter(Me=>Me.kit_id===be.id))||[];A({...be,files:Se,links:Ie})},children:e.jsx(da,{className:"h-4 w-4"})}),e.jsx(B,{variant:"ghost",size:"icon",onClick:()=>z(be),children:e.jsx(Ja,{className:"h-4 w-4"})}),e.jsx(B,{variant:"ghost",size:"icon",onClick:()=>{confirm("Delete this resource kit?")&&ce.mutate(be.id)},children:e.jsx(qn,{className:"h-4 w-4 text-destructive"})})]})})]},be.id))})]})})}),e.jsx(Bs,{open:r,onOpenChange:a,children:e.jsxs(Fs,{className:"max-w-2xl max-h-[90vh] overflow-y-auto",children:[e.jsx(qs,{children:e.jsx($s,{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(re,{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(Ku,{className:"h-8 w-8 text-muted-foreground"})}),e.jsx(we,{type:"file",accept:"image/*",onChange:$})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{htmlFor:"name",children:"Name *"}),e.jsx(we,{id:"name",value:o.name,onChange:be=>c({...o,name:be.target.value}),placeholder:"Resource Kit Name"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{children:"Description"}),e.jsx(yN,{content:o.description,onChange:be=>c({...o,description:be}),placeholder:"Brief description of this resource kit",minHeight:"120px"})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{htmlFor:"publish_date",children:"Publish Date"}),e.jsx(we,{id:"publish_date",type:"date",value:o.publish_date,onChange:be=>c({...o,publish_date:be.target.value})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{children:"Published"}),e.jsxs("div",{className:"flex items-center space-x-2 pt-2",children:[e.jsx(zn,{checked:o.is_published,onCheckedChange:be=>c({...o,is_published:be})}),e.jsx("span",{className:"text-sm text-muted-foreground",children:o.is_published?"Visible to agents":"Hidden from agents"})]})]})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex justify-between items-center",children:[e.jsx(re,{children:"Resource Files"}),e.jsxs(B,{type:"button",variant:"outline",size:"sm",onClick:V,children:[e.jsx(nn,{className:"h-4 w-4 mr-1"}),"Add File"]})]}),f.length===0?e.jsx("div",{className:"text-sm text-muted-foreground py-4 text-center border rounded-md border-dashed",children:'No files added yet. Click "Add File" to include resources.'}):e.jsx("div",{className:"space-y-3",children:f.map((be,Se)=>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 ",Se+1]}),e.jsx(B,{type:"button",variant:"ghost",size:"icon",className:"h-6 w-6",onClick:()=>W(Se),children:e.jsx(hr,{className:"h-4 w-4"})})]}),e.jsx(we,{placeholder:"File name (e.g., Getting Started Guide)",value:be.name,onChange:Ie=>G(Se,"name",Ie.target.value)}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(we,{type:"file",onChange:Ie=>me(Se,Ie),className:"flex-1"}),be.file_url&&!be.file&&e.jsx("a",{href:be.file_url,target:"_blank",rel:"noopener noreferrer",className:"text-sm text-primary hover:underline whitespace-nowrap",children:"Current file"}),be.file&&e.jsx("span",{className:"text-sm text-green-600 whitespace-nowrap",children:"New file selected"})]})]},Se))})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex justify-between items-center",children:[e.jsx(re,{children:"Canva Links"}),e.jsxs(B,{type:"button",variant:"outline",size:"sm",onClick:X,children:[e.jsx(nn,{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((be,Se)=>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 ",Se+1]}),e.jsx(B,{type:"button",variant:"ghost",size:"icon",className:"h-6 w-6",onClick:()=>te(Se),children:e.jsx(hr,{className:"h-4 w-4"})})]}),e.jsx(we,{placeholder:"Link title (e.g., Social Media Post Template)",value:be.title,onChange:Ie=>ne(Se,"title",Ie.target.value)}),e.jsx(we,{placeholder:"Canva share link (e.g., https://www.canva.com/design/...)",value:be.canva_share_link,onChange:Ie=>ne(Se,"canva_share_link",Ie.target.value)})]},Se))})]}),e.jsx(DEt,{selectedTemplateIds:_,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:ue.isPending,children:ue.isPending?"Saving...":i?"Update":"Create"})]})]})]})}),e.jsx(Bs,{open:!!k,onOpenChange:()=>A(null),children:e.jsxs(Fs,{className:"max-w-lg",children:[e.jsx(qs,{children:e.jsx($s,{children:k==null?void 0:k.name})}),e.jsxs("div",{className:"space-y-4",children:[(k==null?void 0:k.featured_image_url)&&e.jsx("img",{src:k.featured_image_url,alt:k.name,className:"w-full h-48 object-cover rounded-lg"}),(k==null?void 0:k.description)&&e.jsx("p",{className:"text-muted-foreground",children:k.description}),e.jsxs("div",{children:[e.jsxs("h4",{className:"font-medium mb-2",children:["Resource Files (",((xe=k==null?void 0:k.files)==null?void 0:xe.length)||0,")"]}),((ve=k==null?void 0:k.files)==null?void 0:ve.length)===0?e.jsx("p",{className:"text-sm text-muted-foreground",children:"No files in this kit"}):e.jsx("div",{className:"space-y-2",children:(ge=k==null?void 0:k.files)==null?void 0:ge.map(be=>e.jsxs("a",{href:be.file_url,target:"_blank",rel:"noopener noreferrer",className:"flex items-center gap-2 p-2 rounded-md hover:bg-muted transition-colors",children:[e.jsx(Wr,{className:"h-4 w-4 text-primary"}),e.jsx("span",{className:"text-sm",children:be.name})]},be.id))})]}),(k==null?void 0:k.links)&&k.links.length>0&&e.jsxs("div",{children:[e.jsxs("h4",{className:"font-medium mb-2",children:["Canva Links (",k.links.length,")"]}),e.jsx("div",{className:"space-y-2",children:k.links.map(be=>e.jsxs("a",{href:be.canva_share_link,target:"_blank",rel:"noopener noreferrer",className:"flex items-center gap-2 p-2 rounded-md hover:bg-muted transition-colors",children:[e.jsx(gc,{className:"h-4 w-4 text-primary"}),e.jsx("span",{className:"text-sm",children:be.title})]},be.id))})]})]})]})})]})})}const FRs=()=>{const{user:s}=Ls(),{toast:t}=Ci(),n=as(),[r,a]=N.useState(!1),[i,l]=N.useState(null),[o,c]=N.useState({title:"",description:"",publish_date:new Date().toISOString().split("T")[0],is_published:!1,links:[{title:"",canva_share_link:"",sort_order:0}]}),[d,u]=N.useState(null),[h,m]=N.useState(""),{data:f=[],isLoading:g}=mt({queryKey:["social-swag-admin"],queryFn:async()=>{const{data:M,error:L}=await H.from("social_swag").select("*").order("publish_date",{ascending:!1});if(L)throw L;const{data:z,error:$}=await H.from("social_swag_links").select("*").order("sort_order");if($)throw $;return M.map(W=>({...W,links:(z==null?void 0:z.filter(G=>G.swag_id===W.id))||[]}))}}),y=_t({mutationFn:async M=>{let L=M.existingImageUrl;if(M.image){const X=M.image.name.split(".").pop(),te=`${Date.now()}-${Math.random().toString(36).substring(7)}.${X}`,{error:ne}=await H.storage.from("template-previews").upload(te,M.image);if(ne)throw ne;const{data:me}=H.storage.from("template-previews").getPublicUrl(te);L=me.publicUrl}const z={title:M.item.title,description:M.item.description||null,preview_image_url:L,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 $=M.itemId;const V=!$,W=(i==null?void 0:i.is_published)||!1;if($){const{error:X}=await H.from("social_swag").update(z).eq("id",$);if(X)throw X;await H.from("social_swag_links").delete().eq("swag_id",$)}else{const{data:X,error:te}=await H.from("social_swag").insert(z).select().single();if(te)throw te;$=X.id}const G=M.item.links.filter(X=>X.title.trim()&&X.canva_share_link.trim());if(G.length>0){const X=G.map((ne,me)=>({swag_id:$,title:ne.title.trim(),canva_share_link:ne.canva_share_link.trim(),sort_order:me})),{error:te}=await H.from("social_swag_links").insert(X);if(te)throw te}return{itemId:$,itemTitle:M.item.title,isNewItem:V,wasPublished:W,isPublished:M.item.is_published}},onSuccess:M=>{n.invalidateQueries({queryKey:["social-swag-admin"]}),n.invalidateQueries({queryKey:["social-swag"]}),t({title:i?"Item updated":"Item created"}),M.isPublished&&(M.isNewItem||!M.wasPublished)&&kOe(M.itemTitle,M.itemId),a(!1),_()},onError:M=>{t({title:"Error saving item",description:M.message,variant:"destructive"})}}),x=_t({mutationFn:async M=>{const{error:L}=await H.from("social_swag").delete().eq("id",M);if(L)throw L},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"})}}),_=()=>{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(L=>({id:L.id,title:L.title,canva_share_link:L.canva_share_link,sort_order:L.sort_order})):[{title:"",canva_share_link:"",sort_order:0}]}),m(M.preview_image_url||""),a(!0)},k=M=>{var z;const L=(z=M.target.files)==null?void 0:z[0];L&&(u(L),m(URL.createObjectURL(L)))},A=()=>{c({...o,links:[...o.links,{title:"",canva_share_link:"",sort_order:o.links.length}]})},T=M=>{if(o.links.length<=1)return;const L=o.links.filter((z,$)=>$!==M);c({...o,links:L})},P=(M,L,z)=>{const $=[...o.links];$[M]={...$[M],[L]:z},c({...o,links:$})},I=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(Qs,{title:"Manage Social Swag",children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(Uh,{title:"Manage Social Swag",description:"Create and manage social media content"}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs(_e,{children:[e.jsx(zt,{className:"pb-2",children:e.jsx(qt,{className:"text-sm font-medium text-muted-foreground",children:"Total Items"})}),e.jsx(De,{children:e.jsx("div",{className:"text-2xl font-bold",children:f.length})})]}),e.jsxs(_e,{children:[e.jsx(zt,{className:"pb-2",children:e.jsx(qt,{className:"text-sm font-medium text-muted-foreground",children:"Published"})}),e.jsx(De,{children:e.jsx("div",{className:"text-2xl font-bold",children:f.filter(M=>M.is_published).length})})]})]}),e.jsxs(Bs,{open:r,onOpenChange:M=>{a(M),M||_()},children:[e.jsx(Ao,{asChild:!0,children:e.jsxs(B,{className:"gap-2",children:[e.jsx(nn,{className:"h-4 w-4"}),"Add Item"]})}),e.jsxs(Fs,{className:"max-w-2xl max-h-[90vh] overflow-y-auto",children:[e.jsx(qs,{children:e.jsx($s,{children:i?"Edit Item":"Add New Item"})}),e.jsxs("form",{onSubmit:I,className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{htmlFor:"title",children:"Title *"}),e.jsx(we,{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(re,{children:"Description"}),e.jsx(yN,{content:o.description,onChange:M=>c({...o,description:M}),placeholder:"Enter description",minHeight:"120px"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{htmlFor:"publish_date",children:"Publish Date"}),e.jsx(we,{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(zn,{id:"is_published",checked:o.is_published,onCheckedChange:M=>c({...o,is_published:M})}),e.jsx(re,{htmlFor:"is_published",children:"Published"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{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(hr,{className:"h-3 w-3"})})]}):e.jsxs("div",{className:"border-2 border-dashed rounded-lg p-4 text-center",children:[e.jsx(pc,{className:"h-8 w-8 mx-auto text-muted-foreground mb-2"}),e.jsx(we,{type:"file",accept:"image/*",onChange:k,className:"cursor-pointer"})]})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(re,{children:"Canva Links"}),e.jsxs(B,{type:"button",variant:"outline",size:"sm",onClick:A,children:[e.jsx(nn,{className:"h-3 w-3 mr-1"}),"Add Link"]})]}),o.links.map((M,L)=>e.jsx(_e,{children:e.jsxs(De,{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 ",L+1]}),o.links.length>1&&e.jsx(B,{type:"button",variant:"ghost",size:"icon",className:"h-6 w-6 ml-auto",onClick:()=>T(L),children:e.jsx(hr,{className:"h-3 w-3"})})]}),e.jsx(we,{placeholder:"Link title (e.g., Instagram Post)",value:M.title,onChange:z=>P(L,"title",z.target.value)}),e.jsx(we,{placeholder:"Canva share link",value:M.canva_share_link,onChange:z=>P(L,"canva_share_link",z.target.value)})]})},L))]}),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(_e,{children:e.jsx(De,{className:"p-0",children:g?e.jsx("div",{className:"flex justify-center py-8",children:e.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})}):f.length===0?e.jsx("div",{className:"text-center py-8 text-muted-foreground",children:'No items yet. Click "Add Item" to create your first one.'}):e.jsxs(Oa,{children:[e.jsx(Fa,{children:e.jsxs(un,{children:[e.jsx(Mt,{className:"w-16",children:"Preview"}),e.jsx(Mt,{children:"Title"}),e.jsx(Mt,{children:"Links"}),e.jsx(Mt,{children:"Publish Date"}),e.jsx(Mt,{children:"Status"}),e.jsx(Mt,{className:"text-right",children:"Actions"})]})}),e.jsx(za,{children:f.map(M=>{var L;return e.jsxs(un,{children:[e.jsx(gt,{children:M.preview_image_url?e.jsx("img",{src:M.preview_image_url,alt:"",className:"w-12 h-12 object-cover rounded"}):e.jsx("div",{className:"w-12 h-12 bg-muted rounded flex items-center justify-center",children:e.jsx(pc,{className:"h-4 w-4 text-muted-foreground"})})}),e.jsx(gt,{className:"font-medium",children:M.title}),e.jsxs(gt,{children:[((L=M.links)==null?void 0:L.length)||0," links"]}),e.jsx(gt,{children:new Date(M.publish_date).toLocaleDateString()}),e.jsx(gt,{children:e.jsx(We,{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(da,{className:"h-4 w-4"})}),e.jsx(B,{variant:"ghost",size:"icon",onClick:()=>b(M),children:e.jsx(Ja,{className:"h-4 w-4"})}),e.jsx(B,{variant:"ghost",size:"icon",onClick:()=>{confirm("Are you sure you want to delete this item?")&&x.mutate(M.id)},children:e.jsx(qn,{className:"h-4 w-4"})})]})})]},M.id)})})]})})})]})})};function zRs(){for(var s=arguments.length,t=new Array(s),n=0;nr=>{t.forEach(a=>a(r))},t)}const I3e=typeof window<"u"&&typeof window.document<"u"&&typeof window.document.createElement<"u";function wU(s){const t=Object.prototype.toString.call(s);return t==="[object Window]"||t==="[object global]"}function qVe(s){return"nodeType"in s}function vb(s){var t,n;return s?wU(s)?s:qVe(s)&&(t=(n=s.ownerDocument)==null?void 0:n.defaultView)!=null?t:window:window}function VVe(s){const{Document:t}=vb(s);return s instanceof t}function tJ(s){return wU(s)?!1:s instanceof vb(s).HTMLElement}function REt(s){return s instanceof vb(s).SVGElement}function jU(s){return s?wU(s)?s.document:qVe(s)?VVe(s)?s:tJ(s)||REt(s)?s.ownerDocument:document:document:document}const L5=I3e?N.useLayoutEffect:N.useEffect;function HVe(s){const t=N.useRef(s);return L5(()=>{t.current=s}),N.useCallback(function(){for(var n=arguments.length,r=new Array(n),a=0;a{s.current=setInterval(r,a)},[]),n=N.useCallback(()=>{s.current!==null&&(clearInterval(s.current),s.current=null)},[]);return[t,n]}function RY(s,t){t===void 0&&(t=[s]);const n=N.useRef(s);return L5(()=>{n.current!==s&&(n.current=s)},t),n}function sJ(s,t){const n=N.useRef();return N.useMemo(()=>{const r=s(n.current);return n.current=r,r},[...t])}function uke(s){const t=HVe(s),n=N.useRef(null),r=N.useCallback(a=>{a!==n.current&&(t==null||t(a,n.current)),n.current=a},[]);return[n,r]}function SOe(s){const t=N.useRef();return N.useEffect(()=>{t.current=s},[s]),t.current}let dLe={};function nJ(s,t){return N.useMemo(()=>{if(t)return t;const n=dLe[s]==null?0:dLe[s]+1;return dLe[s]=n,s+"-"+n},[s,t])}function OEt(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 Z9=OEt(1),OY=OEt(-1);function $Rs(s){return"clientX"in s&&"clientY"in s}function GVe(s){if(!s)return!1;const{KeyboardEvent:t}=vb(s.target);return t&&s instanceof t}function URs(s){if(!s)return!1;const{TouchEvent:t}=vb(s.target);return t&&s instanceof t}function COe(s){if(URs(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 $Rs(s)?{x:s.clientX,y:s.clientY}:null}const fE=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[fE.Translate.toString(s),fE.Scale.toString(s)].join(" ")}},Transition:{toString(s){let{property:t,duration:n,easing:r}=s;return t+" "+n+"ms "+r}}}),Not="a,frame,iframe,input:not([type=hidden]):not(:disabled),select:not(:disabled),textarea:not(:disabled),button:not(:disabled),*[tabindex]";function qRs(s){return s.matches(Not)?s:s.querySelector(Not)}const VRs={display:"none"};function HRs(s){let{id:t,value:n}=s;return Rt.createElement("div",{id:t,style:VRs},n)}function GRs(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 Rt.createElement("div",{id:t,style:a,role:"status","aria-live":r,"aria-atomic":!0},n)}function WRs(){const[s,t]=N.useState("");return{announce:N.useCallback(r=>{r!=null&&t(r)},[]),announcement:s}}const FEt=N.createContext(null);function KRs(s){const t=N.useContext(FEt);N.useEffect(()=>{if(!t)throw new Error("useDndMonitor must be used within a children of ");return t(s)},[s,t])}function YRs(){const[s]=N.useState(()=>new Set),t=N.useCallback(r=>(s.add(r),()=>s.delete(r)),[s]);return[N.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 ZRs={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. `},XRs={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 QRs(s){let{announcements:t=XRs,container:n,hiddenTextDescribedById:r,screenReaderInstructions:a=ZRs}=s;const{announce:i,announcement:l}=WRs(),o=nJ("DndLiveRegion"),[c,d]=N.useState(!1);if(N.useEffect(()=>{d(!0)},[]),KRs(N.useMemo(()=>({onDragStart(h){let{active:m}=h;i(t.onDragStart({active:m}))},onDragMove(h){let{active:m,over:f}=h;t.onDragMove&&i(t.onDragMove({active:m,over:f}))},onDragOver(h){let{active:m,over:f}=h;i(t.onDragOver({active:m,over:f}))},onDragEnd(h){let{active:m,over:f}=h;i(t.onDragEnd({active:m,over:f}))},onDragCancel(h){let{active:m,over:f}=h;i(t.onDragCancel({active:m,over:f}))}}),[i,t])),!c)return null;const u=Rt.createElement(Rt.Fragment,null,Rt.createElement(HRs,{id:r,value:a.draggable}),Rt.createElement(GRs,{id:o,announcement:l}));return n?Lv.createPortal(u,n):u}var Kg;(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"})(Kg||(Kg={}));function hke(){}function QB(s,t){return N.useMemo(()=>({sensor:s,options:t??{}}),[s,t])}function D3e(){for(var s=arguments.length,t=new Array(s),n=0;n[...t].filter(r=>r!=null),[...t])}const mN=Object.freeze({x:0,y:0});function zEt(s,t){return Math.sqrt(Math.pow(s.x-t.x,2)+Math.pow(s.y-t.y,2))}function BEt(s,t){let{data:{value:n}}=s,{data:{value:r}}=t;return n-r}function JRs(s,t){let{data:{value:n}}=s,{data:{value:r}}=t;return r-n}function kot(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 $Et(s,t){if(!s||s.length===0)return null;const[n]=s;return n[t]}function Sot(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 R3e=s=>{let{collisionRect:t,droppableRects:n,droppableContainers:r}=s;const a=Sot(t,t.left,t.top),i=[];for(const l of r){const{id:o}=l,c=n.get(o);if(c){const d=zEt(Sot(c),a);i.push({id:o,data:{droppableContainer:l,value:d}})}}return i.sort(BEt)},eOs=s=>{let{collisionRect:t,droppableRects:n,droppableContainers:r}=s;const a=kot(t),i=[];for(const l of r){const{id:o}=l,c=n.get(o);if(c){const d=kot(c),u=a.reduce((m,f,g)=>m+zEt(d[g],f),0),h=Number((u/4).toFixed(4));i.push({id:o,data:{droppableContainer:l,value:h}})}}return i.sort(BEt)};function tOs(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=tOs(o,t);c>0&&a.push({id:l,data:{droppableContainer:i,value:c}})}}return a.sort(JRs)};function nOs(s,t,n){return{...s,scaleX:t&&n?t.width/n.width:1,scaleY:t&&n?t.height/n.height:1}}function UEt(s,t){return s&&t?{x:s.left-t.left,y:s.top-t.top}:mN}function rOs(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 aOs=rOs(1);function iOs(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 oOs(s,t,n){const r=iOs(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 lOs={ignoreTransform:!1};function NU(s,t){t===void 0&&(t=lOs);let n=s.getBoundingClientRect();if(t.ignoreTransform){const{transform:d,transformOrigin:u}=vb(s).getComputedStyle(s);d&&(n=oOs(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 Cot(s){return NU(s,{ignoreTransform:!0})}function cOs(s){const t=s.innerWidth,n=s.innerHeight;return{top:0,left:0,right:t,bottom:n,width:t,height:n}}function dOs(s,t){return t===void 0&&(t=vb(s).getComputedStyle(s)),t.position==="fixed"}function uOs(s,t){t===void 0&&(t=vb(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 O3e(s,t){const n=[];function r(a){if(t!=null&&n.length>=t||!a)return n;if(VVe(a)&&a.scrollingElement!=null&&!n.includes(a.scrollingElement))return n.push(a.scrollingElement),n;if(!tJ(a)||REt(a)||n.includes(a))return n;const i=vb(s).getComputedStyle(a);return a!==s&&uOs(a,i)&&n.push(a),dOs(a,i)?n:r(a.parentNode)}return s?r(s):n}function qEt(s){const[t]=O3e(s,1);return t??null}function uLe(s){return!I3e||!s?null:wU(s)?s:qVe(s)?VVe(s)||s===jU(s).scrollingElement?window:tJ(s)?s:null:null}function VEt(s){return wU(s)?s.scrollX:s.scrollLeft}function HEt(s){return wU(s)?s.scrollY:s.scrollTop}function AOe(s){return{x:VEt(s),y:HEt(s)}}var Bx;(function(s){s[s.Forward=1]="Forward",s[s.Backward=-1]="Backward"})(Bx||(Bx={}));function GEt(s){return!I3e||!s?!1:s===document.scrollingElement}function WEt(s){const t={x:0,y:0},n=GEt(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 hOs={x:.2,y:.2};function mOs(s,t,n,r,a){let{top:i,left:l,right:o,bottom:c}=n;r===void 0&&(r=10),a===void 0&&(a=hOs);const{isTop:d,isBottom:u,isLeft:h,isRight:m}=WEt(s),f={x:0,y:0},g={x:0,y:0},y={height:t.height*a.y,width:t.width*a.x};return!d&&i<=t.top+y.height?(f.y=Bx.Backward,g.y=r*Math.abs((t.top+y.height-i)/y.height)):!u&&c>=t.bottom-y.height&&(f.y=Bx.Forward,g.y=r*Math.abs((t.bottom-y.height-c)/y.height)),!m&&o>=t.right-y.width?(f.x=Bx.Forward,g.x=r*Math.abs((t.right-y.width-o)/y.width)):!h&&l<=t.left+y.width&&(f.x=Bx.Backward,g.x=r*Math.abs((t.left+y.width-l)/y.width)),{direction:f,speed:g}}function pOs(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 KEt(s){return s.reduce((t,n)=>Z9(t,AOe(n)),mN)}function fOs(s){return s.reduce((t,n)=>t+VEt(n),0)}function gOs(s){return s.reduce((t,n)=>t+HEt(n),0)}function xOs(s,t){if(t===void 0&&(t=NU),!s)return;const{top:n,left:r,bottom:a,right:i}=t(s);qEt(s)&&(a<=0||i<=0||n>=window.innerHeight||r>=window.innerWidth)&&s.scrollIntoView({block:"center",inline:"center"})}const yOs=[["x",["left","right"],fOs],["y",["top","bottom"],gOs]];class WVe{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=O3e(n),a=KEt(r);this.rect={...t},this.width=t.width,this.height=t.height;for(const[i,l,o]of yOs)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 hK{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 vOs(s){const{EventTarget:t}=vb(s);return s instanceof t?s:jU(s)}function hLe(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 Vw;(function(s){s.Click="click",s.DragStart="dragstart",s.Keydown="keydown",s.ContextMenu="contextmenu",s.Resize="resize",s.SelectionChange="selectionchange",s.VisibilityChange="visibilitychange"})(Vw||(Vw={}));function Aot(s){s.preventDefault()}function bOs(s){s.stopPropagation()}var ad;(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"})(ad||(ad={}));const YEt={start:[ad.Space,ad.Enter],cancel:[ad.Esc],end:[ad.Space,ad.Enter,ad.Tab]},_Os=(s,t)=>{let{currentCoordinates:n}=t;switch(s.code){case ad.Right:return{...n,x:n.x+25};case ad.Left:return{...n,x:n.x-25};case ad.Down:return{...n,y:n.y+25};case ad.Up:return{...n,y:n.y-25}}};class F3e{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 hK(jU(n)),this.windowListeners=new hK(vb(n)),this.handleKeyDown=this.handleKeyDown.bind(this),this.handleCancel=this.handleCancel.bind(this),this.attach()}attach(){this.handleStart(),this.windowListeners.add(Vw.Resize,this.handleCancel),this.windowListeners.add(Vw.VisibilityChange,this.handleCancel),setTimeout(()=>this.listeners.add(Vw.Keydown,this.handleKeyDown))}handleStart(){const{activeNode:t,onStart:n}=this.props,r=t.node.current;r&&xOs(r),n(mN)}handleKeyDown(t){if(GVe(t)){const{active:n,context:r,options:a}=this.props,{keyboardCodes:i=YEt,coordinateGetter:l=_Os,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}:mN;this.referenceCoordinates||(this.referenceCoordinates=u);const h=l(t,{active:n,context:r.current,currentCoordinates:u});if(h){const m=OY(h,u),f={x:0,y:0},{scrollableAncestors:g}=r.current;for(const y of g){const x=t.code,{isTop:_,isRight:b,isLeft:k,isBottom:A,maxScroll:T,minScroll:P}=WEt(y),I=pOs(y),M={x:Math.min(x===ad.Right?I.right-I.width/2:I.right,Math.max(x===ad.Right?I.left:I.left+I.width/2,h.x)),y:Math.min(x===ad.Down?I.bottom-I.height/2:I.bottom,Math.max(x===ad.Down?I.top:I.top+I.height/2,h.y))},L=x===ad.Right&&!b||x===ad.Left&&!k,z=x===ad.Down&&!A||x===ad.Up&&!_;if(L&&M.x!==h.x){const $=y.scrollLeft+m.x,V=x===ad.Right&&$<=T.x||x===ad.Left&&$>=P.x;if(V&&!m.y){y.scrollTo({left:$,behavior:o});return}V?f.x=y.scrollLeft-$:f.x=x===ad.Right?y.scrollLeft-T.x:y.scrollLeft-P.x,f.x&&y.scrollBy({left:-f.x,behavior:o});break}else if(z&&M.y!==h.y){const $=y.scrollTop+m.y,V=x===ad.Down&&$<=T.y||x===ad.Up&&$>=P.y;if(V&&!m.x){y.scrollTo({top:$,behavior:o});return}V?f.y=y.scrollTop-$:f.y=x===ad.Down?y.scrollTop-T.y:y.scrollTop-P.y,f.y&&y.scrollBy({top:-f.y,behavior:o});break}}this.handleMove(t,Z9(OY(h,this.referenceCoordinates),f))}}}handleMove(t,n){const{onMove:r}=this.props;t.preventDefault(),r(n)}handleEnd(t){const{onEnd:n}=this.props;t.preventDefault(),this.detach(),n()}handleCancel(t){const{onCancel:n}=this.props;t.preventDefault(),this.detach(),n()}detach(){this.listeners.removeAll(),this.windowListeners.removeAll()}}F3e.activators=[{eventName:"onKeyDown",handler:(s,t,n)=>{let{keyboardCodes:r=YEt,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 Tot(s){return!!(s&&"distance"in s)}function Eot(s){return!!(s&&"delay"in s)}class KVe{constructor(t,n,r){var a;r===void 0&&(r=vOs(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=jU(l),this.documentListeners=new hK(this.document),this.listeners=new hK(r),this.windowListeners=new hK(vb(l)),this.initialCoordinates=(a=COe(i))!=null?a:mN,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(Vw.Resize,this.handleCancel),this.windowListeners.add(Vw.DragStart,Aot),this.windowListeners.add(Vw.VisibilityChange,this.handleCancel),this.windowListeners.add(Vw.ContextMenu,Aot),this.documentListeners.add(Vw.Keydown,this.handleKeydown),n){if(r!=null&&r({event:this.props.event,activeNode:this.props.activeNode,options:this.props.options}))return this.handleStart();if(Eot(n)){this.timeoutId=setTimeout(this.handleStart,n.delay),this.handlePending(n);return}if(Tot(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(Vw.Click,bOs,{capture:!0}),this.removeTextSelection(),this.documentListeners.add(Vw.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=COe(t))!=null?n:mN,d=OY(a,c);if(!r&&o){if(Tot(o)){if(o.tolerance!=null&&hLe(d,o.tolerance))return this.handleCancel();if(hLe(d,o.distance))return this.handleStart()}if(Eot(o)&&hLe(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===ad.Esc&&this.handleCancel()}removeTextSelection(){var t;(t=this.document.getSelection())==null||t.removeAllRanges()}}const wOs={cancel:{name:"pointercancel"},move:{name:"pointermove"},end:{name:"pointerup"}};class kU extends KVe{constructor(t){const{event:n}=t,r=jU(n.target);super(t,wOs,r)}}kU.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 jOs={move:{name:"mousemove"},end:{name:"mouseup"}};var TOe;(function(s){s[s.RightClick=2]="RightClick"})(TOe||(TOe={}));class NOs extends KVe{constructor(t){super(t,jOs,jU(t.event.target))}}NOs.activators=[{eventName:"onMouseDown",handler:(s,t)=>{let{nativeEvent:n}=s,{onActivation:r}=t;return n.button===TOe.RightClick?!1:(r==null||r({event:n}),!0)}}];const mLe={cancel:{name:"touchcancel"},move:{name:"touchmove"},end:{name:"touchend"}};class kOs extends KVe{constructor(t){super(t,mLe)}static setup(){return window.addEventListener(mLe.move.name,t,{capture:!1,passive:!1}),function(){window.removeEventListener(mLe.move.name,t)};function t(){}}}kOs.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 mK;(function(s){s[s.Pointer=0]="Pointer",s[s.DraggableRect=1]="DraggableRect"})(mK||(mK={}));var mke;(function(s){s[s.TreeOrder=0]="TreeOrder",s[s.ReversedTreeOrder=1]="ReversedTreeOrder"})(mke||(mke={}));function SOs(s){let{acceleration:t,activator:n=mK.Pointer,canScroll:r,draggingRect:a,enabled:i,interval:l=5,order:o=mke.TreeOrder,pointerCoordinates:c,scrollableAncestors:d,scrollableAncestorRects:u,delta:h,threshold:m}=s;const f=AOs({delta:h,disabled:!i}),[g,y]=BRs(),x=N.useRef({x:0,y:0}),_=N.useRef({x:0,y:0}),b=N.useMemo(()=>{switch(n){case mK.Pointer:return c?{top:c.y,bottom:c.y,left:c.x,right:c.x}:null;case mK.DraggableRect:return a}},[n,a,c]),k=N.useRef(null),A=N.useCallback(()=>{const P=k.current;if(!P)return;const I=x.current.x*_.current.x,M=x.current.y*_.current.y;P.scrollBy(I,M)},[]),T=N.useMemo(()=>o===mke.TreeOrder?[...d].reverse():d,[o,d]);N.useEffect(()=>{if(!i||!d.length||!b){y();return}for(const P of T){if((r==null?void 0:r(P))===!1)continue;const I=d.indexOf(P),M=u[I];if(!M)continue;const{direction:L,speed:z}=mOs(P,M,b,t,m);for(const $ of["x","y"])f[$][L[$]]||(z[$]=0,L[$]=0);if(z.x>0||z.y>0){y(),k.current=P,g(A,l),x.current=z,_.current=L;return}}x.current={x:0,y:0},_.current={x:0,y:0},y()},[t,A,r,y,i,l,JSON.stringify(b),JSON.stringify(f),g,d,T,u,JSON.stringify(m)])}const COs={x:{[Bx.Backward]:!1,[Bx.Forward]:!1},y:{[Bx.Backward]:!1,[Bx.Forward]:!1}};function AOs(s){let{delta:t,disabled:n}=s;const r=SOe(t);return sJ(a=>{if(n||!r||!a)return COs;const i={x:Math.sign(t.x-r.x),y:Math.sign(t.y-r.y)};return{x:{[Bx.Backward]:a.x[Bx.Backward]||i.x===-1,[Bx.Forward]:a.x[Bx.Forward]||i.x===1},y:{[Bx.Backward]:a.y[Bx.Backward]||i.y===-1,[Bx.Forward]:a.y[Bx.Forward]||i.y===1}}},[n,t,r])}function TOs(s,t){const n=t!=null?s.get(t):void 0,r=n?n.node.current:null;return sJ(a=>{var i;return t==null?null:(i=r??a)!=null?i:null},[r,t])}function EOs(s,t){return N.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 FY;(function(s){s[s.Always=0]="Always",s[s.BeforeDragging=1]="BeforeDragging",s[s.WhileDragging=2]="WhileDragging"})(FY||(FY={}));var EOe;(function(s){s.Optimized="optimized"})(EOe||(EOe={}));const Mot=new Map;function MOs(s,t){let{dragging:n,dependencies:r,config:a}=t;const[i,l]=N.useState(null),{frequency:o,measure:c,strategy:d}=a,u=N.useRef(s),h=x(),m=RY(h),f=N.useCallback(function(_){_===void 0&&(_=[]),!m.current&&l(b=>b===null?_:b.concat(_.filter(k=>!b.includes(k))))},[m]),g=N.useRef(null),y=sJ(_=>{if(h&&!n)return Mot;if(!_||_===Mot||u.current!==s||i!=null){const b=new Map;for(let k of s){if(!k)continue;if(i&&i.length>0&&!i.includes(k.id)&&k.rect.current){b.set(k.id,k.rect.current);continue}const A=k.node.current,T=A?new WVe(c(A),A):null;k.rect.current=T,T&&b.set(k.id,T)}return b}return _},[s,i,n,h,c]);return N.useEffect(()=>{u.current=s},[s]),N.useEffect(()=>{h||f()},[n,h]),N.useEffect(()=>{i&&i.length>0&&l(null)},[JSON.stringify(i)]),N.useEffect(()=>{h||typeof o!="number"||g.current!==null||(g.current=setTimeout(()=>{f(),g.current=null},o))},[o,h,f,...r]),{droppableRects:y,measureDroppableContainers:f,measuringScheduled:i!=null};function x(){switch(d){case FY.Always:return!1;case FY.BeforeDragging:return n;default:return!n}}}function ZEt(s,t){return sJ(n=>s?n||(typeof t=="function"?t(s):s):null,[t,s])}function LOs(s,t){return ZEt(s,t)}function POs(s){let{callback:t,disabled:n}=s;const r=HVe(t),a=N.useMemo(()=>{if(n||typeof window>"u"||typeof window.MutationObserver>"u")return;const{MutationObserver:i}=window;return new i(r)},[r,n]);return N.useEffect(()=>()=>a==null?void 0:a.disconnect(),[a]),a}function z3e(s){let{callback:t,disabled:n}=s;const r=HVe(t),a=N.useMemo(()=>{if(n||typeof window>"u"||typeof window.ResizeObserver>"u")return;const{ResizeObserver:i}=window;return new i(r)},[n]);return N.useEffect(()=>()=>a==null?void 0:a.disconnect(),[a]),a}function IOs(s){return new WVe(NU(s),s)}function Lot(s,t,n){t===void 0&&(t=IOs);const[r,a]=N.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=POs({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=z3e({callback:i});return L5(()=>{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 DOs(s){const t=ZEt(s);return UEt(s,t)}const Pot=[];function ROs(s){const t=N.useRef(s),n=sJ(r=>s?r&&r!==Pot&&s&&t.current&&s.parentNode===t.current.parentNode?r:O3e(s):Pot,[s]);return N.useEffect(()=>{t.current=s},[s]),n}function OOs(s){const[t,n]=N.useState(null),r=N.useRef(s),a=N.useCallback(i=>{const l=uLe(i.target);l&&n(o=>o?(o.set(l,AOe(l)),new Map(o)):null)},[]);return N.useEffect(()=>{const i=r.current;if(s!==i){l(i);const o=s.map(c=>{const d=uLe(c);return d?(d.addEventListener("scroll",a,{passive:!0}),[d,AOe(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=uLe(c);d==null||d.removeEventListener("scroll",a)})}},[a,s]),N.useMemo(()=>s.length?t?Array.from(t.values()).reduce((i,l)=>Z9(i,l),mN):KEt(s):mN,[s,t])}function Iot(s,t){t===void 0&&(t=[]);const n=N.useRef(null);return N.useEffect(()=>{n.current=null},t),N.useEffect(()=>{const r=s!==mN;r&&!n.current&&(n.current=s),!r&&n.current&&(n.current=null)},[s]),n.current?OY(s,n.current):mN}function FOs(s){N.useEffect(()=>{if(!I3e)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 zOs(s,t){return N.useMemo(()=>s.reduce((n,r)=>{let{eventName:a,handler:i}=r;return n[a]=l=>{i(l,t)},n},{}),[s,t])}function XEt(s){return N.useMemo(()=>s?cOs(s):null,[s])}const Dot=[];function BOs(s,t){t===void 0&&(t=NU);const[n]=s,r=XEt(n?vb(n):null),[a,i]=N.useState(Dot);function l(){i(()=>s.length?s.map(c=>GEt(c)?r:new WVe(t(c),c)):Dot)}const o=z3e({callback:l});return L5(()=>{o==null||o.disconnect(),l(),s.forEach(c=>o==null?void 0:o.observe(c))},[s]),a}function $Os(s){if(!s)return null;if(s.children.length>1)return s;const t=s.children[0];return tJ(t)?t:s}function UOs(s){let{measure:t}=s;const[n,r]=N.useState(null),a=N.useCallback(d=>{for(const{target:u}of d)if(tJ(u)){r(h=>{const m=t(u);return h?{...h,width:m.width,height:m.height}:m});break}},[t]),i=z3e({callback:a}),l=N.useCallback(d=>{const u=$Os(d);i==null||i.disconnect(),u&&(i==null||i.observe(u)),r(u?t(u):null)},[t,i]),[o,c]=uke(l);return N.useMemo(()=>({nodeRef:o,rect:n,setRef:c}),[n,o,c])}const qOs=[{sensor:kU,options:{}},{sensor:F3e,options:{}}],VOs={current:{}},Qwe={draggable:{measure:Cot},droppable:{measure:Cot,strategy:FY.WhileDragging,frequency:EOe.Optimized},dragOverlay:{measure:NU}};class pK 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 HOs={activatorEvent:null,active:null,activeNode:null,activeNodeRect:null,collisions:null,containerNodeRect:null,draggableNodes:new Map,droppableRects:new Map,droppableContainers:new pK,over:null,dragOverlay:{nodeRef:{current:null},rect:null,setRef:hke},scrollableAncestors:[],scrollableAncestorRects:[],measuringConfiguration:Qwe,measureDroppableContainers:hke,windowRect:null,measuringScheduled:!1},GOs={activatorEvent:null,activators:[],active:null,activeNodeRect:null,ariaDescribedById:{draggable:""},dispatch:hke,draggableNodes:new Map,over:null,measureDroppableContainers:hke},B3e=N.createContext(GOs),QEt=N.createContext(HOs);function WOs(){return{draggable:{active:null,initialCoordinates:{x:0,y:0},nodes:new Map,translate:{x:0,y:0}},droppable:{containers:new pK}}}function KOs(s,t){switch(t.type){case Kg.DragStart:return{...s,draggable:{...s.draggable,initialCoordinates:t.initialCoordinates,active:t.active}};case Kg.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 Kg.DragEnd:case Kg.DragCancel:return{...s,draggable:{...s.draggable,active:null,initialCoordinates:{x:0,y:0},translate:{x:0,y:0}}};case Kg.RegisterDroppable:{const{element:n}=t,{id:r}=n,a=new pK(s.droppable.containers);return a.set(r,n),{...s,droppable:{...s.droppable,containers:a}}}case Kg.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 pK(s.droppable.containers);return l.set(n,{...i,disabled:a}),{...s,droppable:{...s.droppable,containers:l}}}case Kg.UnregisterDroppable:{const{id:n,key:r}=t,a=s.droppable.containers.get(n);if(!a||r!==a.key)return s;const i=new pK(s.droppable.containers);return i.delete(n),{...s,droppable:{...s.droppable,containers:i}}}default:return s}}function YOs(s){let{disabled:t}=s;const{active:n,activatorEvent:r,draggableNodes:a}=N.useContext(B3e),i=SOe(r),l=SOe(n==null?void 0:n.id);return N.useEffect(()=>{if(!t&&!r&&i&&l!=null){if(!GVe(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=qRs(u);if(h){h.focus();break}}})}},[r,t,a,l,i]),null}function ZOs(s,t){let{transform:n,...r}=t;return s!=null&&s.length?s.reduce((a,i)=>i({transform:a,...r}),n):n}function XOs(s){return N.useMemo(()=>({draggable:{...Qwe.draggable,...s==null?void 0:s.draggable},droppable:{...Qwe.droppable,...s==null?void 0:s.droppable},dragOverlay:{...Qwe.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 QOs(s){let{activeNode:t,measure:n,initialRect:r,config:a=!0}=s;const i=N.useRef(!1),{x:l,y:o}=typeof a=="boolean"?{x:a,y:a}:a;L5(()=>{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=UEt(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=qEt(d);m&&m.scrollBy({top:h.y,left:h.x})}},[t,l,o,r,n])}const JEt=N.createContext({...mN,scaleX:1,scaleY:1});var eA;(function(s){s[s.Uninitialized=0]="Uninitialized",s[s.Initializing=1]="Initializing",s[s.Initialized=2]="Initialized"})(eA||(eA={}));const $3e=N.memo(function(t){var n,r,a,i;let{id:l,accessibility:o,autoScroll:c=!0,children:d,sensors:u=qOs,collisionDetection:h=sOs,measuring:m,modifiers:f,...g}=t;const y=N.useReducer(KOs,void 0,WOs),[x,_]=y,[b,k]=YRs(),[A,T]=N.useState(eA.Uninitialized),P=A===eA.Initialized,{draggable:{active:I,nodes:M,translate:L},droppable:{containers:z}}=x,$=I!=null?M.get(I):null,V=N.useRef({initial:null,translated:null}),W=N.useMemo(()=>{var Rs;return I!=null?{id:I,data:(Rs=$==null?void 0:$.data)!=null?Rs:VOs,rect:V}:null},[I,$]),G=N.useRef(null),[X,te]=N.useState(null),[ne,me]=N.useState(null),ue=RY(g,Object.values(g)),ce=nJ("DndDescribedBy",l),ae=N.useMemo(()=>z.getEnabled(),[z]),he=XOs(m),{droppableRects:xe,measureDroppableContainers:ve,measuringScheduled:ge}=MOs(ae,{dragging:P,dependencies:[L.x,L.y],config:he.droppable}),be=TOs(M,I),Se=N.useMemo(()=>ne?COe(ne):null,[ne]),Ie=Hs(),Me=LOs(be,he.draggable.measure);QOs({activeNode:I!=null?M.get(I):null,config:Ie.layoutShiftCompensation,initialRect:Me,measure:he.draggable.measure});const Re=Lot(be,he.draggable.measure,Me),Be=Lot(be?be.parentElement:null),Ne=N.useRef({activatorEvent:null,active:null,activeNode:be,collisionRect:null,collisions:null,droppableRects:xe,draggableNodes:M,draggingNode:null,draggingNodeRect:null,droppableContainers:z,over:null,scrollableAncestors:[],scrollAdjustedTranslate:null}),Ge=z.getNodeFor((n=Ne.current.over)==null?void 0:n.id),Ce=UOs({measure:he.dragOverlay.measure}),Fe=(r=Ce.nodeRef.current)!=null?r:be,Ae=P?(a=Ce.rect)!=null?a:Re:null,Xe=!!(Ce.nodeRef.current&&Ce.rect),$e=DOs(Xe?null:Re),Ye=XEt(Fe?vb(Fe):null),Je=ROs(P?Ge??be:null),Ke=BOs(Je),st=ZOs(f,{transform:{x:L.x-$e.x,y:L.y-$e.y,scaleX:1,scaleY:1},activatorEvent:ne,active:W,activeNodeRect:Re,containerNodeRect:Be,draggingNodeRect:Ae,over:Ne.current.over,overlayNodeRect:Ce.rect,scrollableAncestors:Je,scrollableAncestorRects:Ke,windowRect:Ye}),rt=Se?Z9(Se,L):null,Ze=OOs(Je),ht=Iot(Ze),Bt=Iot(Ze,[Re]),Ct=Z9(st,ht),Yt=Ae?aOs(Ae,st):null,Kt=W&&Yt?h({active:W,collisionRect:Yt,droppableRects:xe,droppableContainers:ae,pointerCoordinates:rt}):null,Xs=$Et(Kt,"id"),[zs,Vt]=N.useState(null),At=Xe?st:Z9(st,Bt),Os=nOs(At,(i=zs==null?void 0:zs.rect)!=null?i:null,Re),Nt=N.useRef(null),ms=N.useCallback((Rs,en)=>{let{sensor:Rn,options:Bn}=en;if(G.current==null)return;const Dn=M.get(G.current);if(!Dn)return;const Jn=Rs.nativeEvent,ua=new Rn({active:G.current,activeNode:Dn,event:Jn,options:Bn,context:Ne,onAbort(sn){if(!M.get(sn))return;const{onDragAbort:ia}=ue.current,vr={id:sn};ia==null||ia(vr),b({type:"onDragAbort",event:vr})},onPending(sn,ki,ia,vr){if(!M.get(sn))return;const{onDragPending:rn}=ue.current,Zn={id:sn,constraint:ki,initialCoordinates:ia,offset:vr};rn==null||rn(Zn),b({type:"onDragPending",event:Zn})},onStart(sn){const ki=G.current;if(ki==null)return;const ia=M.get(ki);if(!ia)return;const{onDragStart:vr}=ue.current,Nr={activatorEvent:Jn,active:{id:ki,data:ia.data,rect:V}};Lv.unstable_batchedUpdates(()=>{vr==null||vr(Nr),T(eA.Initializing),_({type:Kg.DragStart,initialCoordinates:sn,active:ki}),b({type:"onDragStart",event:Nr}),te(Nt.current),me(Jn)})},onMove(sn){_({type:Kg.DragMove,coordinates:sn})},onEnd:Mr(Kg.DragEnd),onCancel:Mr(Kg.DragCancel)});Nt.current=ua;function Mr(sn){return async function(){const{active:ia,collisions:vr,over:Nr,scrollAdjustedTranslate:rn}=Ne.current;let Zn=null;if(ia&&rn){const{cancelDrop:sa}=ue.current;Zn={activatorEvent:Jn,active:ia,collisions:vr,delta:rn,over:Nr},sn===Kg.DragEnd&&typeof sa=="function"&&await Promise.resolve(sa(Zn))&&(sn=Kg.DragCancel)}G.current=null,Lv.unstable_batchedUpdates(()=>{_({type:sn}),T(eA.Uninitialized),Vt(null),te(null),me(null),Nt.current=null;const sa=sn===Kg.DragEnd?"onDragEnd":"onDragCancel";if(Zn){const xs=ue.current[sa];xs==null||xs(Zn),b({type:sa,event:Zn})}})}}},[M]),Ys=N.useCallback((Rs,en)=>(Rn,Bn)=>{const Dn=Rn.nativeEvent,Jn=M.get(Bn);if(G.current!==null||!Jn||Dn.dndKit||Dn.defaultPrevented)return;const ua={active:Jn};Rs(Rn,en.options,ua)===!0&&(Dn.dndKit={capturedBy:en.sensor},G.current=Bn,ms(Rn,en))},[M,ms]),It=EOs(u,Ys);FOs(u),L5(()=>{Re&&A===eA.Initializing&&T(eA.Initialized)},[Re,A]),N.useEffect(()=>{const{onDragMove:Rs}=ue.current,{active:en,activatorEvent:Rn,collisions:Bn,over:Dn}=Ne.current;if(!en||!Rn)return;const Jn={active:en,activatorEvent:Rn,collisions:Bn,delta:{x:Ct.x,y:Ct.y},over:Dn};Lv.unstable_batchedUpdates(()=>{Rs==null||Rs(Jn),b({type:"onDragMove",event:Jn})})},[Ct.x,Ct.y]),N.useEffect(()=>{const{active:Rs,activatorEvent:en,collisions:Rn,droppableContainers:Bn,scrollAdjustedTranslate:Dn}=Ne.current;if(!Rs||G.current==null||!en||!Dn)return;const{onDragOver:Jn}=ue.current,ua=Bn.get(Xs),Mr=ua&&ua.rect.current?{id:ua.id,rect:ua.rect.current,data:ua.data,disabled:ua.disabled}:null,sn={active:Rs,activatorEvent:en,collisions:Rn,delta:{x:Dn.x,y:Dn.y},over:Mr};Lv.unstable_batchedUpdates(()=>{Vt(Mr),Jn==null||Jn(sn),b({type:"onDragOver",event:sn})})},[Xs]),L5(()=>{Ne.current={activatorEvent:ne,active:W,activeNode:be,collisionRect:Yt,collisions:Kt,droppableRects:xe,draggableNodes:M,draggingNode:Fe,draggingNodeRect:Ae,droppableContainers:z,over:zs,scrollableAncestors:Je,scrollAdjustedTranslate:Ct},V.current={initial:Ae,translated:Yt}},[W,be,Kt,Yt,M,Fe,Ae,xe,z,zs,Je,Ct]),SOs({...Ie,delta:L,draggingRect:Yt,pointerCoordinates:rt,scrollableAncestors:Je,scrollableAncestorRects:Ke});const Ds=N.useMemo(()=>({active:W,activeNode:be,activeNodeRect:Re,activatorEvent:ne,collisions:Kt,containerNodeRect:Be,dragOverlay:Ce,draggableNodes:M,droppableContainers:z,droppableRects:xe,over:zs,measureDroppableContainers:ve,scrollableAncestors:Je,scrollableAncestorRects:Ke,measuringConfiguration:he,measuringScheduled:ge,windowRect:Ye}),[W,be,Re,ne,Kt,Be,Ce,M,z,xe,zs,ve,Je,Ke,he,ge,Ye]),As=N.useMemo(()=>({activatorEvent:ne,activators:It,active:W,activeNodeRect:Re,ariaDescribedById:{draggable:ce},dispatch:_,draggableNodes:M,over:zs,measureDroppableContainers:ve}),[ne,It,W,Re,_,ce,M,zs,ve]);return Rt.createElement(FEt.Provider,{value:k},Rt.createElement(B3e.Provider,{value:As},Rt.createElement(QEt.Provider,{value:Ds},Rt.createElement(JEt.Provider,{value:Os},d)),Rt.createElement(YOs,{disabled:(o==null?void 0:o.restoreFocus)===!1})),Rt.createElement(QRs,{...o,hiddenTextDescribedById:ce}));function Hs(){const Rs=(X==null?void 0:X.autoScrollEnabled)===!1,en=typeof c=="object"?c.enabled===!1:c===!1,Rn=P&&!Rs&&!en;return typeof c=="object"?{...c,enabled:Rn}:{enabled:Rn}}}),JOs=N.createContext(null),Rot="button",eFs="Draggable";function tFs(s){let{id:t,data:n,disabled:r=!1,attributes:a}=s;const i=nJ(eFs),{activators:l,activatorEvent:o,active:c,activeNodeRect:d,ariaDescribedById:u,draggableNodes:h,over:m}=N.useContext(B3e),{role:f=Rot,roleDescription:g="draggable",tabIndex:y=0}=a??{},x=(c==null?void 0:c.id)===t,_=N.useContext(x?JEt:JOs),[b,k]=uke(),[A,T]=uke(),P=zOs(l,t),I=RY(n);L5(()=>(h.set(t,{id:t,key:i,node:b,activatorNode:A,data:I}),()=>{const L=h.get(t);L&&L.key===i&&h.delete(t)}),[h,t]);const M=N.useMemo(()=>({role:f,tabIndex:y,"aria-disabled":r,"aria-pressed":x&&f===Rot?!0:void 0,"aria-roledescription":g,"aria-describedby":u.draggable}),[r,f,y,x,g,u.draggable]);return{active:c,activatorEvent:o,activeNodeRect:d,attributes:M,isDragging:x,listeners:r?void 0:P,node:b,over:m,setNodeRef:k,setActivatorNodeRef:T,transform:_}}function sFs(){return N.useContext(QEt)}const nFs="Droppable",rFs={timeout:25};function aFs(s){let{data:t,disabled:n=!1,id:r,resizeObserverConfig:a}=s;const i=nJ(nFs),{active:l,dispatch:o,over:c,measureDroppableContainers:d}=N.useContext(B3e),u=N.useRef({disabled:n}),h=N.useRef(!1),m=N.useRef(null),f=N.useRef(null),{disabled:g,updateMeasurementsFor:y,timeout:x}={...rFs,...a},_=RY(y??r),b=N.useCallback(()=>{if(!h.current){h.current=!0;return}f.current!=null&&clearTimeout(f.current),f.current=setTimeout(()=>{d(Array.isArray(_.current)?_.current:[_.current]),f.current=null},x)},[x]),k=z3e({callback:b,disabled:g||!l}),A=N.useCallback((M,L)=>{k&&(L&&(k.unobserve(L),h.current=!1),M&&k.observe(M))},[k]),[T,P]=uke(A),I=RY(t);return N.useEffect(()=>{!k||!T.current||(k.disconnect(),h.current=!1,k.observe(T.current))},[T,k]),N.useEffect(()=>(o({type:Kg.RegisterDroppable,element:{id:r,key:i,disabled:n,node:T,rect:m,data:I}}),()=>o({type:Kg.UnregisterDroppable,key:i,id:r})),[r]),N.useEffect(()=>{n!==u.current.disabled&&(o({type:Kg.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:T,over:c,setNodeRef:P}}function U3e(s,t,n){const r=s.slice();return r.splice(n<0?r.length+n:n,0,r.splice(t,1)[0]),r}function iFs(s,t){return s.reduce((n,r,a)=>{const i=t.get(r);return i&&(n[a]=i),n},Array(s.length))}function Lse(s){return s!==null&&s>=0}function oFs(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=cFs(n,l,a);if(l===a){const d=n[i];return d?{x:aa&&l<=i?{x:-o.width-c,y:0,...Pse}:l=i?{x:o.width+c,y:0,...Pse}:{x:0,y:0,...Pse}};function cFs(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=U3e(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}},Ise={scaleX:1,scaleY:1},dFs=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,...Ise}:a=l?{x:0,y:o.height+c,...Ise}:{x:0,y:0,...Ise}};function uFs(s,t,n){const r=s[t],a=s[t-1],i=s[t+1];return r?nr.map(P=>typeof P=="object"&&"id"in P?P.id:P),[r]),g=l!=null,y=l?f.indexOf(l.id):-1,x=d?f.indexOf(d.id):-1,_=N.useRef(f),b=!oFs(f,_.current),k=x!==-1&&y===-1||b,A=lFs(i);L5(()=>{b&&g&&u(f)},[b,f,g,u]),N.useEffect(()=>{_.current=f},[f]);const T=N.useMemo(()=>({activeIndex:y,containerId:h,disabled:A,disableTransforms:k,items:f,overIndex:x,useDragOverlay:m,sortedRects:iFs(f,c),strategy:a}),[y,h,A.draggable,A.droppable,k,f,x,c,m,a]);return Rt.createElement(t6t.Provider,{value:T},t)}const hFs=s=>{let{id:t,items:n,activeIndex:r,overIndex:a}=s;return U3e(n,r,a).indexOf(t)},mFs=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},pFs={duration:200,easing:"ease"},s6t="transform",fFs=fE.Transition.toString({property:s6t,duration:0,easing:"linear"}),gFs={roleDescription:"sortable"};function xFs(s){let{disabled:t,index:n,node:r,rect:a}=s;const[i,l]=N.useState(null),o=N.useRef(n);return L5(()=>{if(!t&&n!==o.current&&r.current){const c=a.current;if(c){const d=NU(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]),N.useEffect(()=>{i&&l(null)},[i]),i}function V3e(s){let{animateLayoutChanges:t=mFs,attributes:n,disabled:r,data:a,getNewIndex:i=hFs,id:l,strategy:o,resizeObserverConfig:c,transition:d=pFs}=s;const{items:u,containerId:h,activeIndex:m,disabled:f,disableTransforms:g,sortedRects:y,overIndex:x,useDragOverlay:_,strategy:b}=N.useContext(t6t),k=yFs(r,f),A=u.indexOf(l),T=N.useMemo(()=>({sortable:{containerId:h,index:A,items:u},...a}),[h,a,A,u]),P=N.useMemo(()=>u.slice(u.indexOf(l)),[u,l]),{rect:I,node:M,isOver:L,setNodeRef:z}=aFs({id:l,data:T,disabled:k.droppable,resizeObserverConfig:{updateMeasurementsFor:P,...c}}),{active:$,activatorEvent:V,activeNodeRect:W,attributes:G,setNodeRef:X,listeners:te,isDragging:ne,over:me,setActivatorNodeRef:ue,transform:ce}=tFs({id:l,data:T,attributes:{...gFs,...n},disabled:k.draggable}),ae=zRs(z,X),he=!!$,xe=he&&!g&&Lse(m)&&Lse(x),ve=!_&&ne,ge=ve&&xe?ce:null,Se=xe?ge??(o??b)({rects:y,activeNodeRect:W,activeIndex:m,overIndex:x,index:A}):null,Ie=Lse(m)&&Lse(x)?i({id:l,items:u,activeIndex:m,overIndex:x}):A,Me=$==null?void 0:$.id,Re=N.useRef({activeId:Me,items:u,newIndex:Ie,containerId:h}),Be=u!==Re.current.items,Ne=t({active:$,containerId:h,isDragging:ne,isSorting:he,id:l,index:A,items:u,newIndex:Re.current.newIndex,previousItems:Re.current.items,previousContainerId:Re.current.containerId,transition:d,wasDragging:Re.current.activeId!=null}),Ge=xFs({disabled:!Ne,index:A,node:M,rect:I});return N.useEffect(()=>{he&&Re.current.newIndex!==Ie&&(Re.current.newIndex=Ie),h!==Re.current.containerId&&(Re.current.containerId=h),u!==Re.current.items&&(Re.current.items=u)},[he,Ie,h,u]),N.useEffect(()=>{if(Me===Re.current.activeId)return;if(Me!=null&&Re.current.activeId==null){Re.current.activeId=Me;return}const Fe=setTimeout(()=>{Re.current.activeId=Me},50);return()=>clearTimeout(Fe)},[Me]),{active:$,activeIndex:m,attributes:G,data:T,rect:I,index:A,newIndex:Ie,items:u,isOver:L,isSorting:he,isDragging:ne,listeners:te,node:M,overIndex:x,over:me,setNodeRef:ae,setActivatorNodeRef:ue,setDroppableNodeRef:z,setDraggableNodeRef:X,transform:Ge??Se,transition:Ce()};function Ce(){if(Ge||Be&&Re.current.newIndex===A)return fFs;if(!(ve&&!GVe(V)||!d)&&(he||Ne))return fE.Transition.toString({...d,property:s6t})}}function yFs(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 pke(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 vFs=[ad.Down,ad.Right,ad.Up,ad.Left],n6t=(s,t)=>{let{context:{active:n,collisionRect:r,droppableRects:a,droppableContainers:i,over:l,scrollableAncestors:o}}=t;if(vFs.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 ad.Down:r.topm.top&&c.push(h);break;case ad.Left:r.left>m.left&&c.push(h);break;case ad.Right:r.left1&&(u=d[1].id),u!=null){const h=i.get(n.id),m=i.get(u),f=m?a.get(m.id):null,g=m==null?void 0:m.node.current;if(g&&f&&h&&m){const x=O3e(g).some((P,I)=>o[I]!==P),_=r6t(h,m),b=bFs(h,m),k=x||!_?{x:0,y:0}:{x:b?r.width-f.width:0,y:b?r.height-f.height:0},A={x:f.left,y:f.top};return k.x&&k.y?A:OY(A,k)}}}};function r6t(s,t){return!pke(s)||!pke(t)?!1:s.data.current.sortable.containerId===t.data.current.sortable.containerId}function bFs(s,t){return!pke(s)||!pke(t)||!r6t(s,t)?!1:s.data.current.sortable.indext(s),children:e.jsx(Ja,{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(qn,{className:"h-3.5 w-3.5"})})]}),s.post_date&&e.jsx("div",{className:"absolute bottom-2 left-2",children:e.jsxs(We,{className:"bg-primary/90 text-primary-foreground text-[10px] gap-1 backdrop-blur-sm px-1.5 py-0.5",children:[e.jsx(ta,{className:"h-2.5 w-2.5"}),Js(new Date(s.post_date+"T00:00:00"),"MMM d")]})})]}),e.jsxs(De,{className:"p-3 space-y-2",children:[e.jsx("p",{className:"text-xs text-muted-foreground line-clamp-3",children:s.caption}),e.jsxs(rc,{children:[e.jsx(ac,{asChild:!0,children:e.jsxs(B,{variant:"outline",size:"sm",className:Ot("w-full h-7 text-[11px] gap-1 justify-start font-normal",!s.post_date&&"text-muted-foreground"),children:[e.jsx(ta,{className:"h-3 w-3"}),s.post_date?Js(new Date(s.post_date+"T00:00:00"),"MMM d, yyyy"):"Set post date"]})}),e.jsxs(Zl,{className:"w-auto p-0",align:"start",children:[e.jsx(Xv,{mode:"single",selected:s.post_date?new Date(s.post_date+"T00:00:00"):void 0,onSelect:h=>r(s.id,h?Js(h,"yyyy-MM-dd"):null),className:"p-3 pointer-events-auto"}),s.post_date&&e.jsx("div",{className:"p-2 border-t",children:e.jsx(B,{variant:"ghost",size:"sm",className:"w-full text-xs text-muted-foreground",onClick:()=>r(s.id,null),children:"Clear date"})})]})]})]})]})})}const wFs=()=>{const s=as(),[t,n]=N.useState("all"),[r,a]=N.useState(!1),[i,l]=N.useState(Js(new Date,"yyyy-MM")),[o,c]=N.useState([]),[d,u]=N.useState(!1),[h,m]=N.useState(null),[f,g]=N.useState(null),[y,x]=N.useState(""),[_,b]=N.useState(null),[k,A]=N.useState(!1),[T,P]=N.useState(!1),[I,M]=N.useState(Js(new Date,"yyyy-MM")),[L,z]=N.useState(null),[$,V]=N.useState(""),[W,G]=N.useState(""),[X,te]=N.useState(""),[ne,me]=N.useState(!1),ue=D3e(QB(kU,{activationConstraint:{distance:5}}),QB(F3e,{coordinateGetter:n6t})),{data:ce=[],isLoading:ae}=mt({queryKey:["admin-social-swag-2"],queryFn:async()=>{const{data:rt,error:Ze}=await H.from("social_swag_2").select("*").order("month",{ascending:!1}).order("sort_order");if(Ze)throw Ze;return rt}}),{data:he=[]}=mt({queryKey:["admin-social-swag-2-months"],queryFn:async()=>{const{data:rt,error:Ze}=await H.from("social_swag_2_months").select("*").order("month",{ascending:!1});if(Ze)throw Ze;return rt}}),{data:xe=[]}=mt({queryKey:["admin-social-swag-2-reels"],queryFn:async()=>{const{data:rt,error:Ze}=await H.from("social_swag_2_reels").select("*").order("month",{ascending:!1});if(Ze)throw Ze;return rt}}),ve=[...new Set(ce.map(rt=>rt.month))].sort((rt,Ze)=>Ze.localeCompare(rt)),ge=t==="all"?ce:ce.filter(rt=>rt.month===t),be=rt=>{const Ze=tUe(rt,"yyyy-MM",new Date);return Js(Ze,"MMMM yyyy")},Se=rt=>{g(rt),x(rt.caption),b(rt.post_date)},Ie=async()=>{if(f){A(!0);try{const{error:rt}=await H.from("social_swag_2").update({caption:y,post_date:_}).eq("id",f.id);if(rt)throw rt;ie.success("Image updated"),g(null),s.invalidateQueries({queryKey:["admin-social-swag-2"]}),s.invalidateQueries({queryKey:["social-swag-2"]})}catch{ie.error("Failed to update image")}finally{A(!1)}}},Me=async rt=>{const{active:Ze,over:ht}=rt;if(!ht||Ze.id===ht.id)return;const Bt=ge,Ct=Bt.findIndex(Xs=>Xs.id===Ze.id),Yt=Bt.findIndex(Xs=>Xs.id===ht.id);if(Ct===-1||Yt===-1)return;const Kt=U3e(Bt,Ct,Yt);s.setQueryData(["admin-social-swag-2"],Xs=>{if(!Xs)return Xs;const zs={};return Kt.forEach((Vt,At)=>{zs[Vt.id]=At}),Xs.map(Vt=>zs[Vt.id]!==void 0?{...Vt,sort_order:zs[Vt.id]}:Vt).sort((Vt,At)=>Vt.month!==At.month?At.month.localeCompare(Vt.month):Vt.sort_order-At.sort_order)});try{await Promise.all(Kt.map((Xs,zs)=>H.from("social_swag_2").update({sort_order:zs}).eq("id",Xs.id)))}catch{ie.error("Failed to save order"),s.invalidateQueries({queryKey:["admin-social-swag-2"]})}},Re=rt=>{const ht=Array.from(rt.target.files||[]).sort((Bt,Ct)=>Bt.name.localeCompare(Ct.name,void 0,{numeric:!0,sensitivity:"base"})).slice(0,16-o.length).map(Bt=>({file:Bt,preview:URL.createObjectURL(Bt),caption:""}));c(Bt=>[...Bt,...ht].slice(0,16))},Be=rt=>{c(Ze=>{const ht=[...Ze];return URL.revokeObjectURL(ht[rt].preview),ht.splice(rt,1),ht})},Ne=(rt,Ze)=>{c(ht=>{const Bt=[...ht];return Bt[rt]={...Bt[rt],caption:Ze},Bt})},Ge=async()=>{var Ze;if(o.length===0){ie.error("Please add at least one image");return}if(o.filter(ht=>!ht.caption.trim()).length>0){ie.error("Please add captions to all images");return}u(!0);try{const{data:ht}=await H.from("social_swag_2").select("sort_order").eq("month",i).order("sort_order",{ascending:!1}).limit(1),Bt=(((Ze=ht==null?void 0:ht[0])==null?void 0:Ze.sort_order)??-1)+1;for(let Ct=0;Ct{const Ze=rt.image_url.split("/social-swag-2/");Ze[1]&&await H.storage.from("social-swag-2").remove([Ze[1]]);const{error:ht}=await H.from("social_swag_2").delete().eq("id",rt.id);if(ht)throw ht},onSuccess:()=>{ie.success("Image deleted"),s.invalidateQueries({queryKey:["admin-social-swag-2"]})},onError:()=>ie.error("Failed to delete image")}),Fe=_t({mutationFn:async({id:rt,postDate:Ze})=>{const{error:ht}=await H.from("social_swag_2").update({post_date:Ze}).eq("id",rt);if(ht)throw ht},onSuccess:()=>{ie.success("Post date updated"),s.invalidateQueries({queryKey:["admin-social-swag-2"]}),s.invalidateQueries({queryKey:["social-swag-2"]})},onError:()=>ie.error("Failed to update post date")}),Ae=_t({mutationFn:async({month:rt,link:Ze})=>{const{error:ht}=await H.from("social_swag_2_months").upsert({month:rt,canva_link:Ze||null},{onConflict:"month"});if(ht)throw ht},onSuccess:()=>{ie.success("Canva link updated"),m(null),s.invalidateQueries({queryKey:["admin-social-swag-2-months"]})},onError:()=>ie.error("Failed to update Canva link")}),Xe=rt=>{var Ze;return((Ze=he.find(ht=>ht.month===rt))==null?void 0:Ze.canva_link)||""},$e=rt=>xe.find(Ze=>Ze.month===rt)||null,Ye=rt=>{var ht;const Ze=(ht=rt.target.files)==null?void 0:ht[0];Ze&&(z(Ze),V(URL.createObjectURL(Ze)))},Je=()=>{$&&URL.revokeObjectURL($),z(null),V(""),G(""),te("")},Ke=async()=>{if(!L){ie.error("Please select an image");return}me(!0);try{const rt=L.name.split(".").pop(),Ze=`reels/${I}-${Date.now()}.${rt}`,{error:ht}=await H.storage.from("social-swag-2").upload(Ze,L);if(ht)throw ht;const{data:{publicUrl:Bt}}=H.storage.from("social-swag-2").getPublicUrl(Ze),{error:Ct}=await H.from("social_swag_2_reels").upsert({month:I,image_url:Bt,canva_link:X||null,caption:W||null},{onConflict:"month"});if(Ct)throw Ct;ie.success("Reel uploaded successfully!"),kOe(`${be(I)} Reel`,"social-swag-2"),Je(),P(!1),s.invalidateQueries({queryKey:["admin-social-swag-2-reels"]})}catch(rt){console.error("Reel upload error:",rt),ie.error("Failed to upload reel")}finally{me(!1)}},st=_t({mutationFn:async rt=>{const Ze=rt.image_url.split("/social-swag-2/");Ze[1]&&await H.storage.from("social-swag-2").remove([Ze[1]]);const{error:ht}=await H.from("social_swag_2_reels").delete().eq("id",rt.id);if(ht)throw ht},onSuccess:()=>{ie.success("Reel deleted"),s.invalidateQueries({queryKey:["admin-social-swag-2-reels"]})},onError:()=>ie.error("Failed to delete reel")});return e.jsxs(Qs,{title:"Admin - Social Swag 2.0",children:[e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4",children:[e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl font-bold",children:"Social Swag 2.0"}),e.jsx("p",{className:"text-muted-foreground",children:"Manage monthly social media images and captions"})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(Bs,{open:r,onOpenChange:a,children:[e.jsx(Ao,{asChild:!0,children:e.jsxs(B,{className:"gap-2",children:[e.jsx(nn,{className:"h-4 w-4"}),"Upload Images"]})}),e.jsxs(Fs,{className:"max-w-4xl max-h-[90vh] overflow-y-auto",children:[e.jsx(qs,{children:e.jsx($s,{children:"Upload Social Swag Images"})}),e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{children:"Month"}),e.jsx(we,{type:"month",value:i,onChange:rt=>l(rt.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs(re,{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:Re,className:"hidden",id:"swag-upload",disabled:o.length>=16}),e.jsxs("label",{htmlFor:"swag-upload",className:"cursor-pointer",children:[e.jsx(ni,{className:"h-8 w-8 mx-auto text-muted-foreground mb-2"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Click to select images (max 16)"})]})]})]}),o.length>0&&e.jsx("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4",children:o.map((rt,Ze)=>e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"relative aspect-[4/5] rounded-lg overflow-hidden bg-muted",children:[e.jsx("img",{src:rt.preview,alt:`Upload ${Ze+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:()=>Be(Ze),children:e.jsx(hr,{className:"h-3 w-3"})})]}),e.jsx(Ws,{placeholder:"Caption...",value:rt.caption,onChange:ht=>Ne(Ze,ht.target.value),className:"text-xs h-20"})]},Ze))}),e.jsx(B,{onClick:Ge,disabled:d||o.length===0,className:"w-full gap-2",children:d?e.jsxs(e.Fragment,{children:[e.jsx(us,{className:"h-4 w-4 animate-spin"}),"Uploading..."]}):e.jsxs(e.Fragment,{children:[e.jsx(ni,{className:"h-4 w-4"}),"Upload ",o.length," Images"]})})]})]})]}),e.jsxs(Bs,{open:T,onOpenChange:rt=>{P(rt),rt||Je()},children:[e.jsx(Ao,{asChild:!0,children:e.jsxs(B,{variant:"outline",className:"gap-2",children:[e.jsx(Rh,{className:"h-4 w-4"}),"Upload Reel"]})}),e.jsxs(Fs,{className:"max-w-lg max-h-[85vh] overflow-y-auto",children:[e.jsx(qs,{children:e.jsx($s,{children:"Upload Monthly Reel"})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{children:"Month"}),e.jsx(we,{type:"month",value:I,onChange:rt=>M(rt.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{children:"Reel Preview Image"}),$?e.jsxs("div",{className:"relative aspect-[9/16] max-w-[120px] mx-auto rounded-lg overflow-hidden bg-muted",children:[e.jsx("img",{src:$,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($),z(null),V("")},children:e.jsx(hr,{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:Ye,className:"hidden",id:"reel-upload"}),e.jsxs("label",{htmlFor:"reel-upload",className:"cursor-pointer",children:[e.jsx(Rh,{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(re,{children:"Canva Download Link"}),e.jsx(we,{value:X,onChange:rt=>te(rt.target.value),placeholder:"https://www.canva.com/..."})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{children:"Caption"}),e.jsx(Ws,{value:W,onChange:rt=>G(rt.target.value),placeholder:"Enter caption for this reel...",className:"h-24"})]}),e.jsx(B,{onClick:Ke,disabled:ne||!L,className:"w-full gap-2",children:ne?e.jsxs(e.Fragment,{children:[e.jsx(us,{className:"h-4 w-4 animate-spin"}),"Uploading..."]}):e.jsxs(e.Fragment,{children:[e.jsx(ni,{className:"h-4 w-4"}),"Upload Reel"]})})]})]})]})]})]}),e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4",children:[e.jsx(_e,{children:e.jsxs(De,{className:"p-4",children:[e.jsx("div",{className:"text-2xl font-bold",children:ce.length}),e.jsx("div",{className:"text-sm text-muted-foreground",children:"Total Images"})]})}),e.jsx(_e,{children:e.jsxs(De,{className:"p-4",children:[e.jsx("div",{className:"text-2xl font-bold",children:ve.length}),e.jsx("div",{className:"text-sm text-muted-foreground",children:"Months"})]})})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsx(ya,{value:t,onValueChange:n,children:e.jsxs(va,{children:[e.jsx(ls,{value:"all",children:"All"}),ve.map(rt=>e.jsx(ls,{value:rt,children:be(rt)},rt))]})}),t!=="all"&&e.jsx(_e,{children:e.jsx(De,{className:"p-4",children:e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsx(gc,{className:"h-4 w-4 text-muted-foreground"}),e.jsxs("div",{className:"flex-1",children:[e.jsxs(re,{className:"text-sm text-muted-foreground",children:["Canva Edit Link for ",be(t)]}),(h==null?void 0:h.month)===t?e.jsxs("div",{className:"flex gap-2 mt-1",children:[e.jsx(we,{value:h.link,onChange:rt=>m({...h,link:rt.target.value}),placeholder:"https://www.canva.com/..."}),e.jsx(B,{size:"sm",onClick:()=>Ae.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:Xe(t)||"No link set"}),e.jsx(B,{size:"sm",variant:"outline",onClick:()=>m({month:t,link:Xe(t)}),children:"Edit"})]})]})]})})}),t!=="all"&&e.jsx(_e,{children:e.jsx(De,{className:"p-4",children:e.jsxs("div",{className:"flex items-start gap-4",children:[e.jsx(Rh,{className:"h-4 w-4 text-muted-foreground mt-1"}),e.jsxs("div",{className:"flex-1",children:[e.jsxs(re,{className:"text-sm text-muted-foreground",children:["Reel for ",be(t)]}),(()=>{const rt=$e(t);return rt?e.jsxs("div",{className:"flex items-center gap-4 mt-2",children:[e.jsx("img",{src:rt.image_url,alt:"Reel preview",className:"w-16 h-28 object-cover rounded"}),e.jsxs("div",{className:"flex-1 text-sm",children:[e.jsx("p",{className:"line-clamp-2",children:rt.caption||"No caption"}),rt.canva_link&&e.jsx("a",{href:rt.canva_link,target:"_blank",rel:"noopener noreferrer",className:"text-primary hover:underline text-xs",children:"View Canva Link"})]}),e.jsx(B,{variant:"destructive",size:"sm",onClick:()=>st.mutate(rt),children:e.jsx(qn,{className:"h-4 w-4"})})]}):e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:"No reel uploaded for this month"})})()]})]})})})]}),ae?e.jsx("div",{className:"text-center py-12 text-muted-foreground",children:"Loading..."}):ge.length===0?e.jsxs("div",{className:"text-center py-12",children:[e.jsx(pc,{className:"h-12 w-12 mx-auto text-muted-foreground/50 mb-4"}),e.jsx("p",{className:"text-muted-foreground",children:"No images yet. Upload some!"})]}):e.jsx($3e,{sensors:ue,collisionDetection:R3e,onDragEnd:Me,children:e.jsx(q3e,{items:ge.map(rt=>rt.id),strategy:rJ,children:e.jsx("div",{className:"grid grid-cols-2 md:grid-cols-4 lg:grid-cols-6 gap-4",children:ge.map(rt=>e.jsx(_Fs,{item:rt,onEdit:Se,onDelete:Ze=>Ce.mutate(Ze),onDateChange:(Ze,ht)=>Fe.mutate({id:Ze,postDate:ht})},rt.id))})})})]}),e.jsx(Bs,{open:!!f,onOpenChange:rt=>{rt||g(null)},children:e.jsxs(Fs,{className:"max-w-md",children:[e.jsx(qs,{children:e.jsx($s,{children:"Edit Image"})}),f&&e.jsxs("div",{className:"space-y-4",children:[e.jsx("div",{className:"aspect-[4/5] max-h-48 w-full rounded-lg overflow-hidden bg-muted",children:e.jsx("img",{src:f.image_url,alt:"Preview",className:"w-full h-full object-cover"})}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{children:"Caption"}),e.jsx(Ws,{value:y,onChange:rt=>x(rt.target.value),placeholder:"Enter caption...",className:"h-28"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{children:"Post Date"}),e.jsxs("div",{className:"flex gap-2 items-center",children:[e.jsxs(rc,{children:[e.jsx(ac,{asChild:!0,children:e.jsxs(B,{variant:"outline",className:Ot("flex-1 justify-start gap-2 font-normal",!_&&"text-muted-foreground"),children:[e.jsx(ta,{className:"h-4 w-4"}),_?Js(new Date(_+"T00:00:00"),"MMM d, yyyy"):"Pick a date"]})}),e.jsx(Zl,{className:"w-auto p-0",align:"start",children:e.jsx(Xv,{mode:"single",selected:_?new Date(_+"T00:00:00"):void 0,onSelect:rt=>b(rt?Js(rt,"yyyy-MM-dd"):null),className:"p-3 pointer-events-auto"})})]}),_&&e.jsx(B,{variant:"ghost",size:"icon",onClick:()=>b(null),children:e.jsx(hr,{className:"h-4 w-4"})})]})]})]}),e.jsxs(Cr,{children:[e.jsx(B,{variant:"outline",onClick:()=>g(null),children:"Cancel"}),e.jsx(B,{onClick:Ie,disabled:k,className:"gap-2",children:k?e.jsxs(e.Fragment,{children:[e.jsx(us,{className:"h-4 w-4 animate-spin"}),"Saving..."]}):"Save Changes"})]})]})})]})},jFs=()=>{const{toast:s}=Ci(),t=as(),[n,r]=N.useState("categories"),[a,i]=N.useState(!1),[l,o]=N.useState(null),[c,d]=N.useState({name:"",description:"",icon:""}),[u,h]=N.useState(!1),[m,f]=N.useState(null),[g,y]=N.useState({name:"",description:"",icon:""}),[x,_]=N.useState(!1),[b,k]=N.useState(null),[A,T]=N.useState(""),{data:P=[],isLoading:I}=mt({queryKey:["admin-community-categories"],queryFn:async()=>{const{data:Me,error:Re}=await H.from("community_categories").select("*").order("sort_order");if(Re)throw Re;return Me}}),{data:M=[],isLoading:L}=mt({queryKey:["admin-private-groups"],queryFn:async()=>{const{data:Me,error:Re}=await H.from("community_private_groups").select("*").order("sort_order");if(Re)throw Re;return Me}}),{data:z=[]}=mt({queryKey:["admin-group-members",b==null?void 0:b.id],queryFn:async()=>{if(!b)return[];const{data:Me,error:Re}=await H.from("community_private_group_members").select("*").eq("group_id",b.id);if(Re)throw Re;return Me},enabled:!!b}),{data:$=[]}=mt({queryKey:["admin-all-profiles"],queryFn:async()=>{let Re=[],Be=0,Ne=!0;for(;Ne;){const{data:Ge,error:Ce}=await H.from("profiles").select("id, name, email, brokerage_id").order("name").range(Be,Be+1e3-1);if(Ce)throw Ce;Ge&&Ge.length>0?(Re=[...Re,...Ge],Be+=1e3,Ne=Ge.length===1e3):Ne=!1}return Re}}),{data:V=[]}=mt({queryKey:["admin-all-brokerages"],queryFn:async()=>{const{data:Me,error:Re}=await H.from("brokerages").select("*").order("name");if(Re)throw Re;return Me}}),W=_t({mutationFn:async Me=>{if(Me.id){const{error:Re}=await H.from("community_categories").update({name:Me.name,description:Me.description||null,icon:Me.icon||null}).eq("id",Me.id);if(Re)throw Re}else{const Re=Math.max(...P.map(Ne=>Ne.sort_order),0),{error:Be}=await H.from("community_categories").insert({name:Me.name,description:Me.description||null,icon:Me.icon||null,sort_order:Re+1});if(Be)throw Be}},onSuccess:()=>{t.invalidateQueries({queryKey:["admin-community-categories"]}),i(!1),o(null),d({name:"",description:"",icon:""}),s({title:l?"Category updated!":"Category created!"})},onError:Me=>{s({title:"Error",description:Me.message,variant:"destructive"})}}),G=_t({mutationFn:async Me=>{const{error:Re}=await H.from("community_categories").delete().eq("id",Me);if(Re)throw Re},onSuccess:()=>{t.invalidateQueries({queryKey:["admin-community-categories"]}),s({title:"Category deleted"})}}),X=_t({mutationFn:async({id:Me,direction:Re})=>{const Be=P.findIndex(Ne=>Ne.id===Me);if(Re==="up"&&Be>0){const Ne=P[Be-1],Ge=P[Be];await H.from("community_categories").update({sort_order:Ge.sort_order}).eq("id",Ne.id),await H.from("community_categories").update({sort_order:Ne.sort_order}).eq("id",Ge.id)}else if(Re==="down"&&Bet.invalidateQueries({queryKey:["admin-community-categories"]})}),te=_t({mutationFn:async Me=>{if(Me.id){const{error:Re}=await H.from("community_private_groups").update({name:Me.name,description:Me.description||null,icon:Me.icon||null}).eq("id",Me.id);if(Re)throw Re}else{const Re=Math.max(...M.map(Ne=>Ne.sort_order),0),{error:Be}=await H.from("community_private_groups").insert({name:Me.name,description:Me.description||null,icon:Me.icon||null,sort_order:Re+1});if(Be)throw Be}},onSuccess:()=>{t.invalidateQueries({queryKey:["admin-private-groups"]}),h(!1),f(null),y({name:"",description:"",icon:""}),s({title:m?"Private group updated!":"Private group created!"})},onError:Me=>{s({title:"Error",description:Me.message,variant:"destructive"})}}),ne=_t({mutationFn:async Me=>{const{error:Re}=await H.from("community_private_groups").delete().eq("id",Me);if(Re)throw Re},onSuccess:()=>{t.invalidateQueries({queryKey:["admin-private-groups"]}),s({title:"Private group deleted"})}}),me=_t({mutationFn:async({id:Me,direction:Re})=>{const Be=M.findIndex(Ne=>Ne.id===Me);if(Re==="up"&&Be>0){const Ne=M[Be-1],Ge=M[Be];await H.from("community_private_groups").update({sort_order:Ge.sort_order}).eq("id",Ne.id),await H.from("community_private_groups").update({sort_order:Ne.sort_order}).eq("id",Ge.id)}else if(Re==="down"&&Bet.invalidateQueries({queryKey:["admin-private-groups"]})}),ue=_t({mutationFn:async({groupId:Me,userId:Re,isMember:Be})=>{if(Be){const{error:Ne}=await H.from("community_private_group_members").delete().eq("group_id",Me).eq("user_id",Re);if(Ne)throw Ne}else{const{error:Ne}=await H.from("community_private_group_members").insert({group_id:Me,user_id:Re});if(Ne)throw Ne}},onSuccess:()=>{t.invalidateQueries({queryKey:["admin-group-members",b==null?void 0:b.id]})}}),ce=_t({mutationFn:async({groupId:Me,brokerageId:Re,isMember:Be})=>{if(Be){const{error:Ne}=await H.from("community_private_group_members").delete().eq("group_id",Me).eq("brokerage_id",Re);if(Ne)throw Ne}else{const{error:Ne}=await H.from("community_private_group_members").insert({group_id:Me,brokerage_id:Re});if(Ne)throw Ne}},onSuccess:()=>{t.invalidateQueries({queryKey:["admin-group-members",b==null?void 0:b.id]})}}),ae=Me=>{o(Me),d({name:Me.name,description:Me.description||"",icon:Me.icon||""}),i(!0)},he=()=>{o(null),d({name:"",description:"",icon:""}),i(!0)},xe=Me=>{f(Me),y({name:Me.name,description:Me.description||"",icon:Me.icon||""}),h(!0)},ve=()=>{f(null),y({name:"",description:"",icon:""}),h(!0)},ge=Me=>{k(Me),T(""),_(!0)},be=Me=>z.some(Re=>Re.user_id===Me),Se=Me=>z.some(Re=>Re.brokerage_id===Me),Ie=$.filter(Me=>Me.name.toLowerCase().includes(A.toLowerCase())||Me.email.toLowerCase().includes(A.toLowerCase()));return e.jsx(Qs,{title:"Community Management",children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(Uh,{title:"Community Management",description:"Manage categories and private groups for community discussions"}),e.jsxs(ya,{value:n,onValueChange:r,children:[e.jsxs(va,{children:[e.jsx(ls,{value:"categories",children:"Public Categories"}),e.jsxs(ls,{value:"private-groups",children:[e.jsx(Au,{className:"h-4 w-4 mr-1"}),"Private Groups"]})]}),e.jsxs(_s,{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:he,children:[e.jsx(nn,{className:"h-4 w-4 mr-2"}),"Add Category"]})]}),e.jsx(_e,{children:e.jsx(De,{className:"pt-6",children:e.jsxs(Oa,{children:[e.jsx(Fa,{children:e.jsxs(un,{children:[e.jsx(Mt,{className:"w-[50px]",children:"Order"}),e.jsx(Mt,{className:"w-[80px]",children:"Icon"}),e.jsx(Mt,{children:"Name"}),e.jsx(Mt,{children:"Description"}),e.jsx(Mt,{className:"w-[100px]",children:"Actions"})]})}),e.jsx(za,{children:I?e.jsx(un,{children:e.jsx(gt,{colSpan:5,className:"text-center py-8",children:"Loading..."})}):P.length===0?e.jsx(un,{children:e.jsx(gt,{colSpan:5,className:"text-center py-8 text-muted-foreground",children:"No categories yet. Create your first one!"})}):P.map((Me,Re)=>e.jsxs(un,{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:Re===0,onClick:()=>X.mutate({id:Me.id,direction:"up"}),children:"↑"}),e.jsx(B,{variant:"ghost",size:"icon",className:"h-6 w-6",disabled:Re===P.length-1,onClick:()=>X.mutate({id:Me.id,direction:"down"}),children:"↓"})]})}),e.jsx(gt,{className:"text-2xl",children:Me.icon||"📁"}),e.jsx(gt,{className:"font-medium",children:Me.name}),e.jsx(gt,{className:"text-muted-foreground",children:Me.description||"—"}),e.jsx(gt,{children:e.jsxs("div",{className:"flex gap-1",children:[e.jsx(B,{variant:"ghost",size:"icon",onClick:()=>ae(Me),children:e.jsx(Ja,{className:"h-4 w-4"})}),e.jsx(B,{variant:"ghost",size:"icon",className:"text-destructive",onClick:()=>{confirm("Delete this category? Posts will be uncategorized.")&&G.mutate(Me.id)},children:e.jsx(qn,{className:"h-4 w-4"})})]})})]},Me.id))})]})})})]}),e.jsxs(_s,{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(Ti,{className:"h-3 w-3"}),"Brokerage groups are created automatically and sync with brokerage names"]})]}),e.jsxs(B,{onClick:ve,children:[e.jsx(nn,{className:"h-4 w-4 mr-2"}),"Add Private Group"]})]}),e.jsx(_e,{children:e.jsx(De,{className:"pt-6",children:e.jsxs(Oa,{children:[e.jsx(Fa,{children:e.jsxs(un,{children:[e.jsx(Mt,{className:"w-[50px]",children:"Order"}),e.jsx(Mt,{className:"w-[80px]",children:"Icon"}),e.jsx(Mt,{children:"Name"}),e.jsx(Mt,{children:"Description"}),e.jsx(Mt,{className:"w-[120px]",children:"Members"}),e.jsx(Mt,{className:"w-[140px]",children:"Actions"})]})}),e.jsx(za,{children:L?e.jsx(un,{children:e.jsx(gt,{colSpan:6,className:"text-center py-8",children:"Loading..."})}):M.length===0?e.jsx(un,{children:e.jsx(gt,{colSpan:6,className:"text-center py-8 text-muted-foreground",children:"No private groups yet. Create your first one!"})}):M.map((Me,Re)=>e.jsxs(un,{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:Re===0,onClick:()=>me.mutate({id:Me.id,direction:"up"}),children:"↑"}),e.jsx(B,{variant:"ghost",size:"icon",className:"h-6 w-6",disabled:Re===M.length-1,onClick:()=>me.mutate({id:Me.id,direction:"down"}),children:"↓"})]})}),e.jsx(gt,{className:"text-2xl",children:Me.icon||"🔒"}),e.jsx(gt,{className:"font-medium",children:e.jsxs("div",{className:"flex items-center gap-2",children:[Me.name,Me.brokerage_id?e.jsxs(We,{variant:"outline",className:"text-xs bg-blue-50 text-blue-700 border-blue-200",children:[e.jsx(Ti,{className:"h-3 w-3 mr-1"}),"Auto-managed"]}):e.jsxs(We,{variant:"secondary",className:"text-xs",children:[e.jsx(Au,{className:"h-3 w-3 mr-1"}),"Private"]})]})}),e.jsx(gt,{className:"text-muted-foreground",children:Me.description||"—"}),e.jsx(gt,{children:e.jsxs(B,{variant:"outline",size:"sm",onClick:()=>ge(Me),children:[e.jsx(Yn,{className:"h-4 w-4 mr-1"}),"Manage"]})}),e.jsx(gt,{children:e.jsxs("div",{className:"flex gap-1",children:[!Me.brokerage_id&&e.jsx(B,{variant:"ghost",size:"icon",onClick:()=>xe(Me),children:e.jsx(Ja,{className:"h-4 w-4"})}),!Me.brokerage_id&&e.jsx(B,{variant:"ghost",size:"icon",className:"text-destructive",onClick:()=>{confirm("Delete this private group? All posts in this group will be deleted.")&&ne.mutate(Me.id)},children:e.jsx(qn,{className:"h-4 w-4"})}),Me.brokerage_id&&e.jsx("span",{className:"text-xs text-muted-foreground italic",children:"Managed via brokerage"})]})})]},Me.id))})]})})})]})]}),e.jsx(Bs,{open:a,onOpenChange:i,children:e.jsxs(Fs,{children:[e.jsx(qs,{children:e.jsx($s,{children:l?"Edit Category":"Create Category"})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx("label",{className:"text-sm font-medium",children:"Icon (emoji)"}),e.jsx(we,{value:c.icon,onChange:Me=>d(Re=>({...Re,icon:Me.target.value})),placeholder:"💬",className:"mt-1"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-sm font-medium",children:"Name *"}),e.jsx(we,{value:c.name,onChange:Me=>d(Re=>({...Re,name:Me.target.value})),placeholder:"Category name",className:"mt-1"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-sm font-medium",children:"Description"}),e.jsx(Ws,{value:c.description,onChange:Me=>d(Re=>({...Re,description:Me.target.value})),placeholder:"Brief description of this category",className:"mt-1"})]}),e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx(B,{variant:"outline",onClick:()=>i(!1),children:"Cancel"}),e.jsx(B,{onClick:()=>W.mutate({...c,id:l==null?void 0:l.id}),disabled:!c.name.trim(),children:l?"Save Changes":"Create Category"})]})]})]})}),e.jsx(Bs,{open:u,onOpenChange:h,children:e.jsxs(Fs,{children:[e.jsx(qs,{children:e.jsx($s,{children:m?"Edit Private Group":"Create Private Group"})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx("label",{className:"text-sm font-medium",children:"Icon (emoji)"}),e.jsx(we,{value:g.icon,onChange:Me=>y(Re=>({...Re,icon:Me.target.value})),placeholder:"🔒",className:"mt-1"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-sm font-medium",children:"Name *"}),e.jsx(we,{value:g.name,onChange:Me=>y(Re=>({...Re,name:Me.target.value})),placeholder:"e.g., Pioneers",className:"mt-1"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-sm font-medium",children:"Description"}),e.jsx(Ws,{value:g.description,onChange:Me=>y(Re=>({...Re,description:Me.target.value})),placeholder:"Brief description of this private group",className:"mt-1"})]}),e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx(B,{variant:"outline",onClick:()=>h(!1),children:"Cancel"}),e.jsx(B,{onClick:()=>te.mutate({...g,id:m==null?void 0:m.id}),disabled:!g.name.trim(),children:m?"Save Changes":"Create Private Group"})]})]})]})}),e.jsx(Bs,{open:x,onOpenChange:_,children:e.jsxs(Fs,{className:"max-w-2xl",children:[e.jsx(qs,{children:e.jsxs($s,{children:["Manage Members: ",b==null?void 0:b.name]})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs(ya,{defaultValue:"brokerages",children:[e.jsxs(va,{className:"w-full",children:[e.jsx(ls,{value:"brokerages",className:"flex-1",children:"By Brokerage"}),e.jsx(ls,{value:"users",className:"flex-1",children:"Individual Users"})]}),e.jsxs(_s,{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(lo,{className:"h-[300px] border rounded-md p-4",children:e.jsxs("div",{className:"space-y-2",children:[V.map(Me=>e.jsxs("div",{className:"flex items-center justify-between p-2 hover:bg-muted rounded-md",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(Bi,{checked:Se(Me.id),onCheckedChange:()=>{b&&ce.mutate({groupId:b.id,brokerageId:Me.id,isMember:Se(Me.id)})}}),e.jsx("span",{className:"font-medium",children:Me.name})]}),e.jsxs(We,{variant:"secondary",children:[$.filter(Re=>Re.brokerage_id===Me.id).length," agents"]})]},Me.id)),V.length===0&&e.jsx("p",{className:"text-center text-muted-foreground py-4",children:"No brokerages found"})]})})]}),e.jsxs(_s,{value:"users",className:"space-y-4",children:[e.jsxs("div",{className:"relative",children:[e.jsx(Gr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(we,{placeholder:"Search users...",value:A,onChange:Me=>T(Me.target.value),className:"pl-9"})]}),e.jsx(lo,{className:"h-[300px] border rounded-md p-4",children:e.jsxs("div",{className:"space-y-2",children:[Ie.map(Me=>e.jsx("div",{className:"flex items-center justify-between p-2 hover:bg-muted rounded-md",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(Bi,{checked:be(Me.id),onCheckedChange:()=>{b&&ue.mutate({groupId:b.id,userId:Me.id,isMember:be(Me.id)})}}),e.jsxs("div",{children:[e.jsx("div",{className:"font-medium",children:Me.name}),e.jsx("div",{className:"text-sm text-muted-foreground",children:Me.email})]})]})},Me.id)),Ie.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:()=>_(!1),children:"Done"})})]})]})})]})})},Oot=s=>{switch(s){case"academy_video":return e.jsx(dd,{className:"h-3 w-3"});case"template":return e.jsx(Wr,{className:"h-3 w-3"});case"toolbox":return e.jsx(Ku,{className:"h-3 w-3"});case"newsletter":return e.jsx(E_,{className:"h-3 w-3"});case"social_swag":return e.jsx(Cn,{className:"h-3 w-3"});default:return e.jsx(Tr,{className:"h-3 w-3"})}},NFs=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}},kFs=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}},SFs=()=>{const{toast:s}=Ci(),[t,n]=N.useState([]),[r,a]=N.useState([]),[i,l]=N.useState([]),[o,c]=N.useState(!0),[d,u]=N.useState(""),[h,m]=N.useState(null),[f,g]=N.useState([]),[y,x]=N.useState([]);N.useEffect(()=>{_()},[]);const _=async()=>{try{c(!0);const{data:z,error:$}=await H.from("activity_logs").select(` id, user_id, app_name, launched_at, profiles ( name, email, brokerages ( name ) ) `).order("launched_at",{ascending:!1}).limit(5e3);if($)throw $;const{data:V,error:W}=await H.from("content_engagement_logs").select(` id, user_id, resource_type, resource_id, resource_title, action_type, created_at `).order("created_at",{ascending:!1}).limit(5e3);if(W)throw W;const G=[...new Set((V==null?void 0:V.map(ae=>ae.user_id))||[])],{data:X}=await H.from("profiles").select(` id, name, email, brokerages ( name ) `).in("id",G),te=new Map((X==null?void 0:X.map(ae=>[ae.id,ae]))||[]),ne=(z==null?void 0:z.map(ae=>{var he,xe,ve,ge;return{id:ae.id,user_id:ae.user_id,app_name:ae.app_name,launched_at:ae.launched_at,user_name:((he=ae.profiles)==null?void 0:he.name)||"Unknown",user_email:((xe=ae.profiles)==null?void 0:xe.email)||"Unknown",brokerage_name:((ge=(ve=ae.profiles)==null?void 0:ve.brokerages)==null?void 0:ge.name)||null}}))||[],me=(V==null?void 0:V.map(ae=>{var xe;const he=te.get(ae.user_id);return{id:ae.id,user_id:ae.user_id,resource_type:ae.resource_type,resource_id:ae.resource_id,resource_title:ae.resource_title,action_type:ae.action_type,created_at:ae.created_at,user_name:(he==null?void 0:he.name)||"Unknown",user_email:(he==null?void 0:he.email)||"Unknown",brokerage_name:((xe=he==null?void 0:he.brokerages)==null?void 0:xe.name)||null}}))||[];n(ne),a(me);const ue=new Map;ne.forEach(ae=>{if(!ue.has(ae.user_id))ue.set(ae.user_id,{user_id:ae.user_id,user_name:ae.user_name,user_email:ae.user_email,brokerage_name:ae.brokerage_name,last_activity_type:"app",last_activity_name:ae.app_name,last_activity_at:ae.launched_at,total_app_launches:1,total_content_views:0});else{const he=ue.get(ae.user_id);he.total_app_launches++,new Date(ae.launched_at)>new Date(he.last_activity_at)&&(he.last_activity_type="app",he.last_activity_name=ae.app_name,he.last_activity_at=ae.launched_at)}}),me.forEach(ae=>{if(!ue.has(ae.user_id))ue.set(ae.user_id,{user_id:ae.user_id,user_name:ae.user_name,user_email:ae.user_email,brokerage_name:ae.brokerage_name,last_activity_type:ae.resource_type,last_activity_name:ae.resource_title,last_activity_at:ae.created_at,total_app_launches:0,total_content_views:1});else{const he=ue.get(ae.user_id);he.total_content_views++,new Date(ae.created_at)>new Date(he.last_activity_at)&&(he.last_activity_type=ae.resource_type,he.last_activity_name=ae.resource_title,he.last_activity_at=ae.created_at)}});const ce=Array.from(ue.values()).sort((ae,he)=>new Date(he.last_activity_at).getTime()-new Date(ae.last_activity_at).getTime());l(ce)}catch(z){console.error("Error loading activity:",z),s({title:"Error",description:"Failed to load activity logs",variant:"destructive"})}finally{c(!1)}},b=z=>{m({id:z.user_id,name:z.user_name,email:z.user_email});const $=t.filter(W=>W.user_id===z.user_id),V=r.filter(W=>W.user_id===z.user_id);g($),x(V)},k=()=>{m(null),g([]),x([])},{sortKey:A,sortDirection:T,handleSort:P,sortData:I}=JQ("last_activity_at","desc"),M=i.filter(z=>{var V;if(!d)return!0;const $=d.toLowerCase();return z.user_name.toLowerCase().includes($)||z.user_email.toLowerCase().includes($)||((V=z.brokerage_name)==null?void 0:V.toLowerCase().includes($))}),L=I(M,{user:z=>{var $;return(($=z.user_name)==null?void 0:$.toLowerCase())||""},brokerage:z=>{var $;return(($=z.brokerage_name)==null?void 0:$.toLowerCase())||""},last_activity_at:z=>new Date(z.last_activity_at).getTime(),apps:z=>z.total_app_launches,content:z=>z.total_content_views});return o?e.jsx(_e,{children:e.jsx(De,{className:"flex items-center justify-center py-8",children:e.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})})}):e.jsxs(e.Fragment,{children:[e.jsxs(_e,{children:[e.jsxs(zt,{children:[e.jsx(qt,{children:"User Activity"}),e.jsx(_r,{children:"App launches and content engagement - click to see full history"})]}),e.jsxs(De,{children:[e.jsx("div",{className:"mb-4",children:e.jsxs("div",{className:"relative",children:[e.jsx(Gr,{className:"absolute left-3 top-3 h-4 w-4 text-muted-foreground"}),e.jsx(we,{placeholder:"Search by name, email, or brokerage...",value:d,onChange:z=>u(z.target.value),className:"pl-9"})]})}),e.jsx("div",{className:"rounded-md border",children:e.jsxs(Oa,{children:[e.jsx(Fa,{children:e.jsxs(un,{children:[e.jsx(Hu,{sortKey:"user",currentSortKey:A,currentDirection:T,onSort:P,children:"User"}),e.jsx(Hu,{sortKey:"brokerage",currentSortKey:A,currentDirection:T,onSort:P,children:"Brokerage"}),e.jsx(Mt,{children:"Last Activity"}),e.jsx(Hu,{sortKey:"last_activity_at",currentSortKey:A,currentDirection:T,onSort:P,children:"Last Active"}),e.jsx(Hu,{sortKey:"apps",currentSortKey:A,currentDirection:T,onSort:P,className:"text-right",children:"Apps"}),e.jsx(Hu,{sortKey:"content",currentSortKey:A,currentDirection:T,onSort:P,className:"text-right",children:"Content"})]})}),e.jsx(za,{children:L.length===0?e.jsx(un,{children:e.jsx(gt,{colSpan:6,className:"text-center text-muted-foreground",children:"No activity found"})}):L.map(z=>e.jsxs(un,{className:"cursor-pointer hover:bg-muted/50 transition-colors",onClick:()=>b(z),children:[e.jsx(gt,{children:e.jsxs("div",{children:[e.jsx("div",{className:"font-medium",children:z.user_name}),e.jsx("div",{className:"text-sm text-muted-foreground",children:z.user_email})]})}),e.jsx(gt,{children:z.brokerage_name?e.jsx(We,{variant:"outline",children:z.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:z.last_activity_type==="app"?e.jsxs(We,{variant:"secondary",children:[e.jsx(Tr,{className:"h-3 w-3 mr-1"}),z.last_activity_name]}):e.jsxs(We,{variant:"outline",className:"flex items-center gap-1",children:[Oot(z.last_activity_type),e.jsx("span",{className:"max-w-32 truncate",children:z.last_activity_name})]})})}),e.jsx(gt,{className:"text-sm text-muted-foreground",children:nc(new Date(z.last_activity_at),{addSuffix:!0})}),e.jsx(gt,{className:"text-right",children:e.jsx(We,{variant:"outline",children:z.total_app_launches})}),e.jsx(gt,{className:"text-right",children:e.jsx(We,{variant:"outline",children:z.total_content_views})})]},z.user_id))})]})})]})]}),e.jsx(Bs,{open:!!h,onOpenChange:z=>!z&&k(),children:e.jsxs(Fs,{className:"max-w-3xl max-h-[80vh] overflow-hidden flex flex-col",children:[e.jsxs(qs,{children:[e.jsxs($s,{children:[h==null?void 0:h.name,"'s Activity"]}),e.jsx(Ar,{children:h==null?void 0:h.email})]}),e.jsxs(ya,{defaultValue:"content",className:"flex-1 overflow-hidden flex flex-col",children:[e.jsxs(va,{className:"grid w-full grid-cols-2",children:[e.jsxs(ls,{value:"content",children:["Content (",y.length,")"]}),e.jsxs(ls,{value:"apps",children:["App Launches (",f.length,")"]})]}),e.jsx(_s,{value:"content",className:"flex-1 overflow-auto mt-4",children:e.jsx("div",{className:"rounded-md border",children:e.jsxs(Oa,{children:[e.jsx(Fa,{children:e.jsxs(un,{children:[e.jsx(Mt,{children:"Type"}),e.jsx(Mt,{children:"Resource"}),e.jsx(Mt,{children:"Action"}),e.jsx(Mt,{children:"Time"})]})}),e.jsx(za,{children:y.length===0?e.jsx(un,{children:e.jsx(gt,{colSpan:4,className:"text-center text-muted-foreground",children:"No content engagement"})}):y.map(z=>e.jsxs(un,{children:[e.jsx(gt,{children:e.jsxs(We,{variant:"outline",className:"flex items-center gap-1 w-fit",children:[Oot(z.resource_type),NFs(z.resource_type)]})}),e.jsx(gt,{className:"max-w-48",children:e.jsx("span",{className:"truncate block",children:z.resource_title})}),e.jsx(gt,{children:e.jsx(We,{variant:"secondary",children:kFs(z.action_type)})}),e.jsx(gt,{className:"text-sm text-muted-foreground",children:nc(new Date(z.created_at),{addSuffix:!0})})]},z.id))})]})})}),e.jsx(_s,{value:"apps",className:"flex-1 overflow-auto mt-4",children:e.jsx("div",{className:"rounded-md border",children:e.jsxs(Oa,{children:[e.jsx(Fa,{children:e.jsxs(un,{children:[e.jsx(Mt,{children:"App"}),e.jsx(Mt,{children:"Time"})]})}),e.jsx(za,{children:f.length===0?e.jsx(un,{children:e.jsx(gt,{colSpan:2,className:"text-center text-muted-foreground",children:"No app launches"})}):f.map(z=>e.jsxs(un,{children:[e.jsx(gt,{children:e.jsx(We,{variant:"secondary",children:z.app_name})}),e.jsx(gt,{className:"text-sm text-muted-foreground",children:nc(new Date(z.launched_at),{addSuffix:!0})})]},z.id))})]})})})]})]})})]})},CFs=()=>{const{toast:s}=Ci(),[t,n]=N.useState({totalUsers:0,activeUsers:0,pendingUsers:0,totalBrokerages:0,totalLaunches:0,launchesThisWeek:0,launchesThisMonth:0,uniqueActiveThisWeek:0}),[r,a]=N.useState(!0);N.useEffect(()=>{i()},[]);const i=async()=>{try{a(!0);const{count:l}=await H.from("profiles").select("*",{count:"exact",head:!0}),{count:o}=await H.from("profiles").select("*",{count:"exact",head:!0}).not("last_login","is",null),c=(l||0)-(o||0),{count:d}=await H.from("brokerages").select("*",{count:"exact",head:!0}),{count:u}=await H.from("activity_logs").select("*",{count:"exact",head:!0}),h=new Date;h.setDate(h.getDate()-7);const{count:m}=await H.from("activity_logs").select("*",{count:"exact",head:!0}).gte("launched_at",h.toISOString()),f=new Date;f.setMonth(f.getMonth()-1);const{count:g}=await H.from("activity_logs").select("*",{count:"exact",head:!0}).gte("launched_at",f.toISOString()),{data:y}=await H.from("activity_logs").select("user_id").gte("launched_at",h.toISOString()),x=new Set(y==null?void 0:y.map(_=>_.user_id)).size;n({totalUsers:l||0,activeUsers:o||0,pendingUsers:c,totalBrokerages:d||0,totalLaunches:u||0,launchesThisWeek:m||0,launchesThisMonth:g||0,uniqueActiveThisWeek:x})}catch(l){console.error("Error loading analytics:",l),s({title:"Error",description:"Failed to load analytics",variant:"destructive"})}finally{a(!1)}};return r?e.jsx(_e,{children:e.jsx(De,{className:"flex items-center justify-center py-8",children:e.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})})}):e.jsxs("div",{className:"grid gap-4 md:grid-cols-2 lg:grid-cols-4",children:[e.jsxs(_e,{children:[e.jsxs(zt,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(qt,{className:"text-sm font-medium",children:"Total Users"}),e.jsx(Yn,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(De,{children:[e.jsx("div",{className:"text-2xl font-bold",children:t.totalUsers}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[t.activeUsers," active, ",t.pendingUsers," pending"]})]})]}),e.jsxs(_e,{children:[e.jsxs(zt,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(qt,{className:"text-sm font-medium",children:"Active Users"}),e.jsx(Po,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(De,{children:[e.jsx("div",{className:"text-2xl font-bold",children:t.activeUsers}),e.jsx("p",{className:"text-xs text-muted-foreground",children:t.totalUsers>0?`${Math.round(t.activeUsers/t.totalUsers*100)}% of total`:"0% of total"})]})]}),e.jsxs(_e,{children:[e.jsxs(zt,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(qt,{className:"text-sm font-medium",children:"Pending Invites"}),e.jsx(Xr,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(De,{children:[e.jsx("div",{className:"text-2xl font-bold",children:t.pendingUsers}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Awaiting setup"})]})]}),e.jsxs(_e,{children:[e.jsxs(zt,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(qt,{className:"text-sm font-medium",children:"Brokerages"}),e.jsx(Ti,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(De,{children:[e.jsx("div",{className:"text-2xl font-bold",children:t.totalBrokerages}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Total brokerages"})]})]}),e.jsxs(_e,{children:[e.jsxs(zt,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(qt,{className:"text-sm font-medium",children:"Total App Launches"}),e.jsx(gg,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(De,{children:[e.jsx("div",{className:"text-2xl font-bold",children:t.totalLaunches}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"All time"})]})]}),e.jsxs(_e,{children:[e.jsxs(zt,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(qt,{className:"text-sm font-medium",children:"Launches This Week"}),e.jsx(gg,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(De,{children:[e.jsx("div",{className:"text-2xl font-bold",children:t.launchesThisWeek}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Last 7 days"})]})]}),e.jsxs(_e,{children:[e.jsxs(zt,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(qt,{className:"text-sm font-medium",children:"Launches This Month"}),e.jsx(gg,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(De,{children:[e.jsx("div",{className:"text-2xl font-bold",children:t.launchesThisMonth}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Last 30 days"})]})]}),e.jsxs(_e,{children:[e.jsxs(zt,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(qt,{className:"text-sm font-medium",children:"Active This Week"}),e.jsx(ml,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(De,{children:[e.jsx("div",{className:"text-2xl font-bold",children:t.uniqueActiveThisWeek}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Unique users"})]})]})]})},Fot={event:"Event",template:"Template",academy_video:"Academy Video",resource_kit:"Resource Kit",newsletter:"Newsletter",social_swag:"Social Swag"},zot={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 a6t({brokerageOnly:s=!1,brokerageId:t}){const[n,r]=N.useState([]),[a,i]=N.useState(!0),[l,o]=N.useState(""),[c,d]=N.useState("all");N.useEffect(()=>{u()},[t]);const u=async()=>{i(!0);try{let P=[];if(s&&t){const{data:G}=await H.from("profiles").select("id").eq("brokerage_id",t);if(P=(G==null?void 0:G.map(X=>X.id))||[],P.length===0){r([]),i(!1);return}}let I=H.from("resource_shares").select("*").order("created_at",{ascending:!1});s&&P.length>0&&(I=I.or(`sender_id.in.(${P.join(",")}),recipient_id.in.(${P.join(",")})`));const{data:M,error:L}=await I;if(L)throw L;const z=new Set;M==null||M.forEach(G=>{z.add(G.sender_id),z.add(G.recipient_id)});const{data:$}=await H.from("profiles").select("id, name, email").in("id",Array.from(z)),V=new Map(($==null?void 0:$.map(G=>[G.id,G]))||[]),W=(M==null?void 0:M.map(G=>({...G,sender:V.get(G.sender_id),recipient:V.get(G.recipient_id)})))||[];r(W)}catch(P){console.error("Error loading shares:",P)}finally{i(!1)}},{sortKey:h,sortDirection:m,handleSort:f,sortData:g}=JQ("created_at","desc"),y=n.filter(P=>{var L,z;const I=l===""||P.resource_title.toLowerCase().includes(l.toLowerCase())||((L=P.sender)==null?void 0:L.name.toLowerCase().includes(l.toLowerCase()))||((z=P.recipient)==null?void 0:z.name.toLowerCase().includes(l.toLowerCase())),M=c==="all"||P.resource_type===c;return I&&M}),x=g(y,{resource:P=>{var I;return((I=P.resource_title)==null?void 0:I.toLowerCase())||""},type:P=>P.resource_type,sender:P=>{var I,M;return((M=(I=P.sender)==null?void 0:I.name)==null?void 0:M.toLowerCase())||""},recipient:P=>{var I,M;return((M=(I=P.recipient)==null?void 0:I.name)==null?void 0:M.toLowerCase())||""},status:P=>P.is_read?1:0,created_at:P=>new Date(P.created_at).getTime()}),_=n.length,b=new Set(n.map(P=>P.sender_id)).size,k=new Set(n.map(P=>P.recipient_id)).size,A=n.length>0?Math.round(n.filter(P=>P.is_read).length/n.length*100):0,T=n.reduce((P,I)=>(P[I.resource_type]=(P[I.resource_type]||0)+1,P),{});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((P,I)=>e.jsxs(_e,{children:[e.jsx(zt,{className:"pb-2",children:e.jsx(xn,{className:"h-4 w-20"})}),e.jsx(De,{children:e.jsx(xn,{className:"h-8 w-16"})})]},I))}),e.jsx(_e,{children:e.jsx(De,{className:"p-6",children:e.jsx(xn,{className:"h-[300px]"})})})]}):e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"grid gap-4 md:grid-cols-4",children:[e.jsxs(_e,{children:[e.jsxs(zt,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(qt,{className:"text-sm font-medium",children:"Total Shares"}),e.jsx(Md,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsx(De,{children:e.jsx("div",{className:"text-2xl font-bold",children:_})})]}),e.jsxs(_e,{children:[e.jsxs(zt,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(qt,{className:"text-sm font-medium",children:"Active Sharers"}),e.jsx(Yn,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsx(De,{children:e.jsx("div",{className:"text-2xl font-bold",children:b})})]}),e.jsxs(_e,{children:[e.jsxs(zt,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(qt,{className:"text-sm font-medium",children:"Recipients Reached"}),e.jsx(ml,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsx(De,{children:e.jsx("div",{className:"text-2xl font-bold",children:k})})]}),e.jsxs(_e,{children:[e.jsxs(zt,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(qt,{className:"text-sm font-medium",children:"Read Rate"}),e.jsx(Wr,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsx(De,{children:e.jsxs("div",{className:"text-2xl font-bold",children:[A,"%"]})})]})]}),e.jsxs(_e,{children:[e.jsx(zt,{children:e.jsx(qt,{className:"text-sm font-medium",children:"Shares by Resource Type"})}),e.jsx(De,{children:e.jsxs("div",{className:"flex flex-wrap gap-2",children:[Object.entries(T).map(([P,I])=>e.jsxs(We,{variant:"secondary",className:zot[P],children:[Fot[P],": ",I]},P)),Object.keys(T).length===0&&e.jsx("span",{className:"text-muted-foreground text-sm",children:"No shares yet"})]})})]}),e.jsxs(_e,{children:[e.jsxs(zt,{children:[e.jsx(qt,{children:"Share History"}),e.jsxs(_r,{children:["All resource shares ",s?"in your brokerage":"across the platform"]})]}),e.jsxs(De,{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(Gr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(we,{placeholder:"Search by resource, sender, or recipient...",value:l,onChange:P=>o(P.target.value),className:"pl-9"})]}),e.jsxs(Ns,{value:c,onValueChange:d,children:[e.jsx(ws,{className:"w-[180px]",children:e.jsx(ks,{placeholder:"Resource type"})}),e.jsxs(js,{children:[e.jsx(nt,{value:"all",children:"All Types"}),e.jsx(nt,{value:"event",children:"Events"}),e.jsx(nt,{value:"template",children:"Templates"}),e.jsx(nt,{value:"academy_video",children:"Academy Videos"}),e.jsx(nt,{value:"resource_kit",children:"Resource Kits"}),e.jsx(nt,{value:"newsletter",children:"Newsletters"}),e.jsx(nt,{value:"social_swag",children:"Social Swag"})]})]})]}),e.jsx(lo,{className:"h-[400px]",children:e.jsxs(Oa,{children:[e.jsx(Fa,{children:e.jsxs(un,{children:[e.jsx(Hu,{sortKey:"resource",currentSortKey:h,currentDirection:m,onSort:f,children:"Resource"}),e.jsx(Hu,{sortKey:"type",currentSortKey:h,currentDirection:m,onSort:f,children:"Type"}),e.jsx(Hu,{sortKey:"sender",currentSortKey:h,currentDirection:m,onSort:f,children:"Sender"}),e.jsx(Hu,{sortKey:"recipient",currentSortKey:h,currentDirection:m,onSort:f,children:"Recipient"}),e.jsx(Hu,{sortKey:"status",currentSortKey:h,currentDirection:m,onSort:f,children:"Status"}),e.jsx(Hu,{sortKey:"created_at",currentSortKey:h,currentDirection:m,onSort:f,children:"Date"})]})}),e.jsx(za,{children:x.length===0?e.jsx(un,{children:e.jsx(gt,{colSpan:6,className:"text-center text-muted-foreground py-8",children:"No shares found"})}):x.map(P=>{var I,M;return e.jsxs(un,{children:[e.jsx(gt,{className:"font-medium max-w-[200px] truncate",children:P.resource_title}),e.jsx(gt,{children:e.jsx(We,{variant:"secondary",className:zot[P.resource_type],children:Fot[P.resource_type]})}),e.jsx(gt,{children:((I=P.sender)==null?void 0:I.name)||"Unknown"}),e.jsx(gt,{children:((M=P.recipient)==null?void 0:M.name)||"Unknown"}),e.jsx(gt,{children:e.jsx(We,{variant:P.is_read?"default":"outline",children:P.is_read?"Read":"Unread"})}),e.jsx(gt,{className:"text-muted-foreground",children:Js(new Date(P.created_at),"MMM d, yyyy")})]},P.id)})})]})})]})]})]})}const pLe={academy_video:{label:"Academy Videos",icon:na,color:"bg-purple-100 text-purple-800",actionLabel:"Watched",actionIcon:da},template:{label:"Templates",icon:c4,color:"bg-blue-100 text-blue-800",actionLabel:"Accessed",actionIcon:Qg},toolbox:{label:"Toolkit",icon:sN,color:"bg-amber-100 text-amber-800",actionLabel:"Downloaded",actionIcon:oi},newsletter:{label:"Newsletters",icon:mn,color:"bg-emerald-100 text-emerald-800",actionLabel:"Clicked",actionIcon:Qg},social_swag:{label:"Social Swag",icon:zc,color:"bg-pink-100 text-pink-800",actionLabel:"Accessed",actionIcon:Qg},event:{label:"Events",icon:ta,color:"bg-cyan-100 text-cyan-800",actionLabel:"Registered",actionIcon:Qg}};function Bot(s){return s.resource_type==="toolbox"?s.total_downloads:s.total_clicks}function AFs(s,t){return s==="toolbox"?t.downloads:t.clicks}function TFs(){var P;const[s,t]=N.useState([]),[n,r]=N.useState(!0),[a,i]=N.useState(null),l=N.useRef(null),{sortKey:o,sortDirection:c,handleSort:d,sortData:u}=JQ("total_views","desc");N.useEffect(()=>{h()},[]);const h=async()=>{try{const{data:I,error:M}=await H.rpc("get_admin_content_engagement");if(M)throw M;t(I||[])}catch(I){console.error("Error loading content engagement:",I)}finally{r(!1)}},m=I=>{i(M=>{const L=M===I?null:I;return requestAnimationFrame(()=>{var z;(z=l.current)==null||z.scrollIntoView({behavior:"smooth",block:"start"})}),L})};if(n)return e.jsxs("div",{className:"space-y-4",children:[e.jsx("div",{className:"grid gap-3 grid-cols-2 md:grid-cols-4",children:[...Array(4)].map((I,M)=>e.jsxs(_e,{children:[e.jsx(zt,{className:"pb-2",children:e.jsx(xn,{className:"h-4 w-20"})}),e.jsx(De,{children:e.jsx(xn,{className:"h-8 w-16"})})]},M))}),e.jsx(_e,{children:e.jsx(De,{className:"py-8",children:e.jsx(xn,{className:"h-64 w-full"})})})]});const f=s.reduce((I,M)=>I+M.total_views,0),g=s.reduce((I,M)=>I+M.total_clicks,0),y=s.reduce((I,M)=>I+M.total_downloads,0),x=s.length,_=s.reduce((I,M)=>(I[M.resource_type]||(I[M.resource_type]={views:0,clicks:0,downloads:0,assets:0,uniqueUsers:0}),I[M.resource_type].views+=M.total_views,I[M.resource_type].clicks+=M.total_clicks,I[M.resource_type].downloads+=M.total_downloads,I[M.resource_type].assets+=1,I[M.resource_type].uniqueUsers+=M.unique_users,I),{}),b=a?s.filter(I=>I.resource_type===a):s,k=u(b,{asset:I=>{var M;return((M=I.resource_title)==null?void 0:M.toLowerCase())||""},type:I=>I.resource_type,views:I=>I.total_views,actions:I=>Bot(I),unique_users:I=>I.unique_users,last_activity:I=>I.last_engaged_at?new Date(I.last_engaged_at).getTime():0}),A=a?pLe[a]||{label:a,icon:da,color:"bg-muted text-muted-foreground",actionLabel:"Actions",actionIcon:Qg}:null,T=A==null?void 0:A.icon;return e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"grid gap-3 grid-cols-2 md:grid-cols-5",children:[e.jsxs(_e,{children:[e.jsxs(zt,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(qt,{className:"text-sm font-medium",children:"Total Views"}),e.jsx(da,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(De,{children:[e.jsx("div",{className:"text-2xl font-bold",children:f.toLocaleString()}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Across all content"})]})]}),e.jsxs(_e,{children:[e.jsxs(zt,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(qt,{className:"text-sm font-medium",children:"Total Clicks"}),e.jsx(Qg,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(De,{children:[e.jsx("div",{className:"text-2xl font-bold",children:g.toLocaleString()}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Link & Canva clicks"})]})]}),e.jsxs(_e,{children:[e.jsxs(zt,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(qt,{className:"text-sm font-medium",children:"Downloads"}),e.jsx(oi,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(De,{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(_e,{children:[e.jsxs(zt,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(qt,{className:"text-sm font-medium",children:"Assets Tracked"}),e.jsx(ml,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(De,{children:[e.jsx("div",{className:"text-2xl font-bold",children:x}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Unique content items"})]})]}),e.jsxs(_e,{children:[e.jsxs(zt,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(qt,{className:"text-sm font-medium",children:"Click Rate"}),e.jsx(Qg,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(De,{children:[e.jsxs("div",{className:"text-2xl font-bold",children:[f>0?Math.round((g+y)/f*100):0,"%"]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Of views → actions"})]})]})]}),e.jsxs(_e,{children:[e.jsxs(zt,{children:[e.jsx(qt,{className:"text-sm font-medium",children:"Engagement by Content Type"}),e.jsx(_r,{children:"Click a category to see individual asset performance"})]}),e.jsx(De,{children:e.jsx("div",{className:"grid gap-3 grid-cols-2 md:grid-cols-3",children:Object.entries(_).map(([I,M])=>{const L=pLe[I]||{label:I,icon:da,color:"bg-muted text-muted-foreground",actionLabel:"Actions",actionIcon:Qg},z=L.icon,$=a===I;return e.jsxs("button",{type:"button",onClick:()=>m(I),className:`flex items-center gap-3 p-3 rounded-lg border text-left transition-colors cursor-pointer ${$?"ring-2 ring-primary border-primary bg-primary/5":"hover:bg-muted/50"}`,children:[e.jsx("div",{className:`p-2 rounded-md ${L.color}`,children:e.jsx(z,{className:"h-4 w-4"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-sm font-medium",children:L.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(da,{className:"h-3 w-3"})," ",M.views]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(L.actionIcon,{className:"h-3 w-3"})," ",AFs(I,M)]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Yn,{className:"h-3 w-3"})," ",M.uniqueUsers]})]})]}),e.jsxs(We,{variant:"secondary",className:"text-[10px]",children:[M.assets," items"]})]},I)})})})]}),e.jsx("div",{ref:l,children:e.jsxs(_e,{children:[e.jsx(zt,{children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(qt,{className:"text-sm font-medium flex items-center gap-2",children:A&&T?e.jsxs(e.Fragment,{children:[e.jsx(T,{className:"h-4 w-4"}),A.label," — Top Performers"]}):"Top Content by Engagement"}),e.jsx(_r,{children:a?`${b.length} ${((P=A==null?void 0:A.label)==null?void 0:P.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(De,{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(lo,{className:"h-[400px]",children:e.jsxs(Oa,{children:[e.jsx(Fa,{children:e.jsxs(un,{children:[e.jsx(Mt,{className:"w-[40px]",children:"#"}),e.jsx(Hu,{sortKey:"asset",currentSortKey:o,currentDirection:c,onSort:d,children:"Asset"}),!a&&e.jsx(Hu,{sortKey:"type",currentSortKey:o,currentDirection:c,onSort:d,children:"Type"}),e.jsx(Hu,{sortKey:"views",currentSortKey:o,currentDirection:c,onSort:d,className:"text-right",children:"Views"}),e.jsx(Hu,{sortKey:"actions",currentSortKey:o,currentDirection:c,onSort:d,className:"text-right",children:A?A.actionLabel:"Actions"}),e.jsx(Hu,{sortKey:"unique_users",currentSortKey:o,currentDirection:c,onSort:d,className:"text-right",children:"Unique Users"}),e.jsx(Hu,{sortKey:"last_activity",currentSortKey:o,currentDirection:c,onSort:d,children:"Last Activity"})]})}),e.jsx(za,{children:k.map((I,M)=>{const L=pLe[I.resource_type]||{label:I.resource_type,color:"bg-muted text-muted-foreground",actionLabel:"Actions",actionIcon:Qg};return e.jsxs(un,{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:I.resource_title})}),!a&&e.jsx(gt,{children:e.jsx(We,{className:`text-[10px] ${L.color}`,children:L.label})}),e.jsx(gt,{className:"text-right font-medium",children:I.total_views}),e.jsx(gt,{className:"text-right font-medium",children:Bot(I)}),e.jsx(gt,{className:"text-right",children:I.unique_users}),e.jsx(gt,{className:"text-xs text-muted-foreground",children:I.last_engaged_at?nc(new Date(I.last_engaged_at),{addSuffix:!0}):"—"})]},`${I.resource_type}-${I.resource_id}`)})})]})})})]})})]})}var EFs=Array.isArray,bb=EFs,MFs=typeof Uf=="object"&&Uf&&Uf.Object===Object&&Uf,i6t=MFs,LFs=i6t,PFs=typeof self=="object"&&self&&self.Object===Object&&self,IFs=LFs||PFs||Function("return this")(),Y5=IFs,DFs=Y5,RFs=DFs.Symbol,aJ=RFs,$ot=aJ,o6t=Object.prototype,OFs=o6t.hasOwnProperty,FFs=o6t.toString,GV=$ot?$ot.toStringTag:void 0;function zFs(s){var t=OFs.call(s,GV),n=s[GV];try{s[GV]=void 0;var r=!0}catch{}var a=FFs.call(s);return r&&(t?s[GV]=n:delete s[GV]),a}var BFs=zFs,$Fs=Object.prototype,UFs=$Fs.toString;function qFs(s){return UFs.call(s)}var VFs=qFs,Uot=aJ,HFs=BFs,GFs=VFs,WFs="[object Null]",KFs="[object Undefined]",qot=Uot?Uot.toStringTag:void 0;function YFs(s){return s==null?s===void 0?KFs:WFs:qot&&qot in Object(s)?HFs(s):GFs(s)}var q3=YFs;function ZFs(s){return s!=null&&typeof s=="object"}var V3=ZFs,XFs=q3,QFs=V3,JFs="[object Symbol]";function e7s(s){return typeof s=="symbol"||QFs(s)&&XFs(s)==JFs}var SU=e7s,t7s=bb,s7s=SU,n7s=/\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,r7s=/^\w*$/;function a7s(s,t){if(t7s(s))return!1;var n=typeof s;return n=="number"||n=="symbol"||n=="boolean"||s==null||s7s(s)?!0:r7s.test(s)||!n7s.test(s)||t!=null&&s in Object(t)}var YVe=a7s;function i7s(s){var t=typeof s;return s!=null&&(t=="object"||t=="function")}var XE=i7s;const CU=Xc(XE);var o7s=q3,l7s=XE,c7s="[object AsyncFunction]",d7s="[object Function]",u7s="[object GeneratorFunction]",h7s="[object Proxy]";function m7s(s){if(!l7s(s))return!1;var t=o7s(s);return t==d7s||t==u7s||t==c7s||t==h7s}var ZVe=m7s;const hl=Xc(ZVe);var p7s=Y5,f7s=p7s["__core-js_shared__"],g7s=f7s,fLe=g7s,Vot=function(){var s=/[^.]+$/.exec(fLe&&fLe.keys&&fLe.keys.IE_PROTO||"");return s?"Symbol(src)_1."+s:""}();function x7s(s){return!!Vot&&Vot in s}var y7s=x7s,v7s=Function.prototype,b7s=v7s.toString;function _7s(s){if(s!=null){try{return b7s.call(s)}catch{}try{return s+""}catch{}}return""}var l6t=_7s,w7s=ZVe,j7s=y7s,N7s=XE,k7s=l6t,S7s=/[\\^$.*+?()[\]{}|]/g,C7s=/^\[object .+?Constructor\]$/,A7s=Function.prototype,T7s=Object.prototype,E7s=A7s.toString,M7s=T7s.hasOwnProperty,L7s=RegExp("^"+E7s.call(M7s).replace(S7s,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$");function P7s(s){if(!N7s(s)||j7s(s))return!1;var t=w7s(s)?L7s:C7s;return t.test(k7s(s))}var I7s=P7s;function D7s(s,t){return s==null?void 0:s[t]}var R7s=D7s,O7s=I7s,F7s=R7s;function z7s(s,t){var n=F7s(s,t);return O7s(n)?n:void 0}var XR=z7s,B7s=XR,$7s=B7s(Object,"create"),H3e=$7s,Hot=H3e;function U7s(){this.__data__=Hot?Hot(null):{},this.size=0}var q7s=U7s;function V7s(s){var t=this.has(s)&&delete this.__data__[s];return this.size-=t?1:0,t}var H7s=V7s,G7s=H3e,W7s="__lodash_hash_undefined__",K7s=Object.prototype,Y7s=K7s.hasOwnProperty;function Z7s(s){var t=this.__data__;if(G7s){var n=t[s];return n===W7s?void 0:n}return Y7s.call(t,s)?t[s]:void 0}var X7s=Z7s,Q7s=H3e,J7s=Object.prototype,e9s=J7s.hasOwnProperty;function t9s(s){var t=this.__data__;return Q7s?t[s]!==void 0:e9s.call(t,s)}var s9s=t9s,n9s=H3e,r9s="__lodash_hash_undefined__";function a9s(s,t){var n=this.__data__;return this.size+=this.has(s)?0:1,n[s]=n9s&&t===void 0?r9s:t,this}var i9s=a9s,o9s=q7s,l9s=H7s,c9s=X7s,d9s=s9s,u9s=i9s;function AU(s){var t=-1,n=s==null?0:s.length;for(this.clear();++t-1}var A9s=C9s,T9s=G3e;function E9s(s,t){var n=this.__data__,r=T9s(n,s);return r<0?(++this.size,n.push([s,t])):n[r][1]=t,this}var M9s=E9s,L9s=p9s,P9s=w9s,I9s=k9s,D9s=A9s,R9s=M9s;function TU(s){var t=-1,n=s==null?0:s.length;for(this.clear();++t0?1:-1},FI=function(t){return mR(t)&&t.indexOf("%")===t.length-1},Ka=function(t){return rBs(t)&&!iJ(t)},lBs=function(t){return Ml(t)},sx=function(t){return Ka(t)||mR(t)},cBs=0,MU=function(t){var n=++cBs;return"".concat(t||"").concat(n)},Bv=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(!Ka(t)&&!mR(t))return r;var i;if(FI(t)){var l=t.indexOf("%");i=n*parseFloat(t.slice(0,l))/100}else i=+t;return iJ(i)&&(i=r),a&&i>n&&(i=n),i},pA=function(t){if(!t)return null;var n=Object.keys(t);return n&&n.length?t[n[0]]:null},dBs=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 xBs(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 LOe(s){"@babel/helpers - typeof";return LOe=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},LOe(s)}var Qot={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"},u3=function(t){return typeof t=="string"?t:t?t.displayName||t.name||"Component":""},Jot=null,xLe=null,iHe=function s(t){if(t===Jot&&Array.isArray(xLe))return xLe;var n=[];return N.Children.forEach(t,function(r){Ml(r)||(Jzs.isFragment(r)?n=n.concat(s(r.props.children)):n.push(r))}),xLe=n,Jot=t,n};function R_(s,t){var n=[],r=[];return Array.isArray(t)?r=t.map(function(a){return u3(a)}):r=[u3(t)],iHe(s).forEach(function(a){var i=D_(a,"type.displayName")||D_(a,"type.name");r.indexOf(i)!==-1&&n.push(a)}),n}function h_(s,t){var n=R_(s,t);return n&&n[0]}var elt=function(t){if(!t||!t.props)return!1;var n=t.props,r=n.width,a=n.height;return!(!Ka(r)||r<=0||!Ka(a)||a<=0)},yBs=["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"],vBs=function(t){return t&&t.type&&mR(t.type)&&yBs.indexOf(t.type)>=0},bBs=function(t){return t&&LOe(t)==="object"&&"clipDot"in t},_Bs=function(t,n,r,a){var i,l=(i=gLe==null?void 0:gLe[a])!==null&&i!==void 0?i:[];return n.startsWith("data-")||!hl(t)&&(a&&l.includes(n)||mBs.includes(n))||r&&aHe.includes(n)},qo=function(t,n,r){if(!t||typeof t=="function"||typeof t=="boolean")return null;var a=t;if(N.isValidElement(t)&&(a=t.props),!CU(a))return null;var i={};return Object.keys(a).forEach(function(l){var o;_Bs((o=a)===null||o===void 0?void 0:o[l],l,n,r)&&(i[l]=a[l])}),i},POe=function s(t,n){if(t===n)return!0;var r=N.Children.count(t);if(r!==N.Children.count(n))return!1;if(r===0)return!0;if(r===1)return tlt(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 SBs(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 DOe(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=kBs(s,NBs),u=a||{width:n,height:r,x:0,y:0},h=Ol("recharts-surface",i);return Rt.createElement("svg",IOe({},qo(d,!0,"svg"),{className:h,width:n,height:r,style:l,viewBox:"".concat(u.x," ").concat(u.y," ").concat(u.width," ").concat(u.height)}),Rt.createElement("title",null,o),Rt.createElement("desc",null,c),t)}var CBs=["children","className"];function ROe(){return ROe=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 TBs(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 Bd=Rt.forwardRef(function(s,t){var n=s.children,r=s.className,a=ABs(s,CBs),i=Ol("recharts-layer",r);return Rt.createElement("g",ROe({className:i},qo(a,!0),{ref:t}),n)}),iN=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:LBs(s,t,n)}var IBs=PBs,DBs="\\ud800-\\udfff",RBs="\\u0300-\\u036f",OBs="\\ufe20-\\ufe2f",FBs="\\u20d0-\\u20ff",zBs=RBs+OBs+FBs,BBs="\\ufe0e\\ufe0f",$Bs="\\u200d",UBs=RegExp("["+$Bs+DBs+zBs+BBs+"]");function qBs(s){return UBs.test(s)}var y6t=qBs;function VBs(s){return s.split("")}var HBs=VBs,v6t="\\ud800-\\udfff",GBs="\\u0300-\\u036f",WBs="\\ufe20-\\ufe2f",KBs="\\u20d0-\\u20ff",YBs=GBs+WBs+KBs,ZBs="\\ufe0e\\ufe0f",XBs="["+v6t+"]",OOe="["+YBs+"]",FOe="\\ud83c[\\udffb-\\udfff]",QBs="(?:"+OOe+"|"+FOe+")",b6t="[^"+v6t+"]",_6t="(?:\\ud83c[\\udde6-\\uddff]){2}",w6t="[\\ud800-\\udbff][\\udc00-\\udfff]",JBs="\\u200d",j6t=QBs+"?",N6t="["+ZBs+"]?",e$s="(?:"+JBs+"(?:"+[b6t,_6t,w6t].join("|")+")"+N6t+j6t+")*",t$s=N6t+j6t+e$s,s$s="(?:"+[b6t+OOe+"?",OOe,_6t,w6t,XBs].join("|")+")",n$s=RegExp(FOe+"(?="+FOe+")|"+s$s+t$s,"g");function r$s(s){return s.match(n$s)||[]}var a$s=r$s,i$s=HBs,o$s=y6t,l$s=a$s;function c$s(s){return o$s(s)?l$s(s):i$s(s)}var d$s=c$s,u$s=IBs,h$s=y6t,m$s=d$s,p$s=h6t;function f$s(s){return function(t){t=p$s(t);var n=h$s(t)?m$s(t):void 0,r=n?n[0]:t.charAt(0),a=n?u$s(n,1).join(""):t.slice(1);return r[s]()+a}}var g$s=f$s,x$s=g$s,y$s=x$s("toUpperCase"),v$s=y$s;const iCe=Xc(v$s);function Ph(s){return function(){return s}}const k6t=Math.cos,xke=Math.sin,wN=Math.sqrt,yke=Math.PI,oCe=2*yke,zOe=Math.PI,BOe=2*zOe,oI=1e-6,b$s=BOe-oI;function S6t(s){this._+=s[0];for(let t=1,n=s.length;t=0))throw new Error(`invalid digits: ${s}`);if(t>15)return S6t;const n=10**t;return function(r){this._+=r[0];for(let a=1,i=r.length;aoI)if(!(Math.abs(h*c-d*u)>oI)||!i)this._append`L${this._x1=t},${this._y1=n}`;else{let f=r-l,g=a-o,y=c*c+d*d,x=f*f+g*g,_=Math.sqrt(y),b=Math.sqrt(m),k=i*Math.tan((zOe-Math.acos((y+m-x)/(2*_*b)))/2),A=k/b,T=k/_;Math.abs(A-1)>oI&&this._append`L${t+A*u},${n+A*h}`,this._append`A${i},${i},0,0,${+(h*f>u*g)},${this._x1=t+T*c},${this._y1=n+T*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)>oI||Math.abs(this._y1-u)>oI)&&this._append`L${d},${u}`,r&&(m<0&&(m=m%BOe+BOe),m>b$s?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>oI&&this._append`A${r},${r},0,${+(m>=zOe)},${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 oHe(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 w$s(t)}function lHe(s){return typeof s=="object"&&"length"in s?s:Array.from(s)}function C6t(s){this._context=s}C6t.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 lCe(s){return new C6t(s)}function A6t(s){return s[0]}function T6t(s){return s[1]}function E6t(s,t){var n=Ph(!0),r=null,a=lCe,i=null,l=oHe(o);s=typeof s=="function"?s:s===void 0?A6t:Ph(s),t=typeof t=="function"?t:t===void 0?T6t:Ph(t);function o(c){var d,u=(c=lHe(c)).length,h,m=!1,f;for(r==null&&(i=a(f=l())),d=0;d<=u;++d)!(d=f;--g)o.point(k[g],A[g]);o.lineEnd(),o.areaEnd()}_&&(k[m]=+s(x,m,h),A[m]=+t(x,m,h),o.point(r?+r(x,m,h):k[m],n?+n(x,m,h):A[m]))}if(b)return o=null,b+""||null}function u(){return E6t().defined(a).curve(l).context(i)}return d.x=function(h){return arguments.length?(s=typeof h=="function"?h:Ph(+h),r=null,d):s},d.x0=function(h){return arguments.length?(s=typeof h=="function"?h:Ph(+h),d):s},d.x1=function(h){return arguments.length?(r=h==null?null:typeof h=="function"?h:Ph(+h),d):r},d.y=function(h){return arguments.length?(t=typeof h=="function"?h:Ph(+h),n=null,d):t},d.y0=function(h){return arguments.length?(t=typeof h=="function"?h:Ph(+h),d):t},d.y1=function(h){return arguments.length?(n=h==null?null:typeof h=="function"?h:Ph(+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:Ph(!!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 M6t{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 j$s(s){return new M6t(s,!0)}function N$s(s){return new M6t(s,!1)}const cHe={draw(s,t){const n=wN(t/yke);s.moveTo(n,0),s.arc(0,0,n,0,oCe)}},k$s={draw(s,t){const n=wN(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()}},L6t=wN(1/3),S$s=L6t*2,C$s={draw(s,t){const n=wN(t/S$s),r=n*L6t;s.moveTo(0,-n),s.lineTo(r,0),s.lineTo(0,n),s.lineTo(-r,0),s.closePath()}},A$s={draw(s,t){const n=wN(t),r=-n/2;s.rect(r,r,n,n)}},T$s=.8908130915292852,P6t=xke(yke/10)/xke(7*yke/10),E$s=xke(oCe/10)*P6t,M$s=-k6t(oCe/10)*P6t,L$s={draw(s,t){const n=wN(t*T$s),r=E$s*n,a=M$s*n;s.moveTo(0,-n),s.lineTo(r,a);for(let i=1;i<5;++i){const l=oCe*i/5,o=k6t(l),c=xke(l);s.lineTo(c*n,-o*n),s.lineTo(o*r-c*a,c*r+o*a)}s.closePath()}},yLe=wN(3),P$s={draw(s,t){const n=-wN(t/(yLe*3));s.moveTo(0,n*2),s.lineTo(-yLe*n,-n),s.lineTo(yLe*n,-n),s.closePath()}},jw=-.5,Nw=wN(3)/2,$Oe=1/wN(12),I$s=($Oe/2+1)*3,D$s={draw(s,t){const n=wN(t/I$s),r=n/2,a=n*$Oe,i=r,l=n*$Oe+n,o=-i,c=l;s.moveTo(r,a),s.lineTo(i,l),s.lineTo(o,c),s.lineTo(jw*r-Nw*a,Nw*r+jw*a),s.lineTo(jw*i-Nw*l,Nw*i+jw*l),s.lineTo(jw*o-Nw*c,Nw*o+jw*c),s.lineTo(jw*r+Nw*a,jw*a-Nw*r),s.lineTo(jw*i+Nw*l,jw*l-Nw*i),s.lineTo(jw*o+Nw*c,jw*c-Nw*o),s.closePath()}};function R$s(s,t){let n=null,r=oHe(a);s=typeof s=="function"?s:Ph(s||cHe),t=typeof t=="function"?t:Ph(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:Ph(i),a):s},a.size=function(i){return arguments.length?(t=typeof i=="function"?i:Ph(+i),a):t},a.context=function(i){return arguments.length?(n=i??null,a):n},a}function vke(){}function bke(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 I6t(s){this._context=s}I6t.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:bke(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:bke(this,s,t);break}this._x0=this._x1,this._x1=s,this._y0=this._y1,this._y1=t}};function O$s(s){return new I6t(s)}function D6t(s){this._context=s}D6t.prototype={areaStart:vke,areaEnd:vke,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:bke(this,s,t);break}this._x0=this._x1,this._x1=s,this._y0=this._y1,this._y1=t}};function F$s(s){return new D6t(s)}function R6t(s){this._context=s}R6t.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:bke(this,s,t);break}this._x0=this._x1,this._x1=s,this._y0=this._y1,this._y1=t}};function z$s(s){return new R6t(s)}function O6t(s){this._context=s}O6t.prototype={areaStart:vke,areaEnd:vke,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 B$s(s){return new O6t(s)}function nlt(s){return s<0?-1:1}function rlt(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(nlt(i)+nlt(l))*Math.min(Math.abs(i),Math.abs(l),.5*Math.abs(o))||0}function alt(s,t){var n=s._x1-s._x0;return n?(3*(s._y1-s._y0)/n-t)/2:t}function vLe(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 _ke(s){this._context=s}_ke.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:vLe(this,this._t0,alt(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,vLe(this,alt(this,n=rlt(this,s,t)),n);break;default:vLe(this,this._t0,n=rlt(this,s,t));break}this._x0=this._x1,this._x1=s,this._y0=this._y1,this._y1=t,this._t0=n}}};function F6t(s){this._context=new z6t(s)}(F6t.prototype=Object.create(_ke.prototype)).point=function(s,t){_ke.prototype.point.call(this,t,s)};function z6t(s){this._context=s}z6t.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 $$s(s){return new _ke(s)}function U$s(s){return new F6t(s)}function B6t(s){this._context=s}B6t.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=ilt(s),a=ilt(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 V$s(s){return new cCe(s,.5)}function H$s(s){return new cCe(s,0)}function G$s(s){return new cCe(s,1)}function JB(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 W$s(s,t){return s[t]}function K$s(s){const t=[];return t.key=s,t}function Y$s(){var s=Ph([]),t=UOe,n=JB,r=W$s;function a(i){var l=Array.from(s.apply(this,arguments),K$s),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 rUs(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 $6t={symbolCircle:cHe,symbolCross:k$s,symbolDiamond:C$s,symbolSquare:A$s,symbolStar:L$s,symbolTriangle:P$s,symbolWye:D$s},aUs=Math.PI/180,iUs=function(t){var n="symbol".concat(iCe(t));return $6t[n]||cHe},oUs=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*aUs;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}},lUs=function(t,n){$6t["symbol".concat(iCe(t))]=n},dHe=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=nUs(t,J$s),d=llt(llt({},c),{},{type:r,size:i,sizeType:o}),u=function(){var x=iUs(r),_=R$s().type(x).size(oUs(i,o,r));return _()},h=d.className,m=d.cx,f=d.cy,g=qo(d,!0);return m===+m&&f===+f&&i===+i?Rt.createElement("path",qOe({},g,{className:Ol("recharts-symbols",h),transform:"translate(".concat(m,", ").concat(f,")"),d:u()})):null};dHe.registerSymbol=lUs;function e$(s){"@babel/helpers - typeof";return e$=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},e$(s)}function VOe(){return VOe=Object.assign?Object.assign.bind():function(s){for(var t=1;t`);var b=f.inactive?d:f.color;return Rt.createElement("li",VOe({className:x,style:h,key:"legend-item-".concat(g)},pR(r.props,f,g)),Rt.createElement(DOe,{width:l,height:l,viewBox:u,style:m},r.renderIcon(f)),Rt.createElement("span",{className:"recharts-legend-item-text",style:{color:b}},y?y(_,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 Rt.createElement("ul",{className:"recharts-default-legend",style:o},this.renderItems())}}])}(N.PureComponent);BY(uHe,"displayName","Legend");BY(uHe,"defaultProps",{iconSize:14,layout:"horizontal",align:"center",verticalAlign:"middle",inactiveColor:"#ccc"});var yUs=W3e;function vUs(){this.__data__=new yUs,this.size=0}var bUs=vUs;function _Us(s){var t=this.__data__,n=t.delete(s);return this.size=t.size,n}var wUs=_Us;function jUs(s){return this.__data__.get(s)}var NUs=jUs;function kUs(s){return this.__data__.has(s)}var SUs=kUs,CUs=W3e,AUs=QVe,TUs=JVe,EUs=200;function MUs(s,t){var n=this.__data__;if(n instanceof CUs){var r=n.__data__;if(!AUs||r.lengtho))return!1;var d=i.get(s),u=i.get(t);if(d&&u)return d==t&&u==s;var h=-1,m=!0,f=n&JUs?new YUs:void 0;for(i.set(s,t),i.set(t,s);++h-1&&s%1==0&&s-1&&s%1==0&&s<=nVs}var fHe=rVs,aVs=q3,iVs=fHe,oVs=V3,lVs="[object Arguments]",cVs="[object Array]",dVs="[object Boolean]",uVs="[object Date]",hVs="[object Error]",mVs="[object Function]",pVs="[object Map]",fVs="[object Number]",gVs="[object Object]",xVs="[object RegExp]",yVs="[object Set]",vVs="[object String]",bVs="[object WeakMap]",_Vs="[object ArrayBuffer]",wVs="[object DataView]",jVs="[object Float32Array]",NVs="[object Float64Array]",kVs="[object Int8Array]",SVs="[object Int16Array]",CVs="[object Int32Array]",AVs="[object Uint8Array]",TVs="[object Uint8ClampedArray]",EVs="[object Uint16Array]",MVs="[object Uint32Array]",sm={};sm[jVs]=sm[NVs]=sm[kVs]=sm[SVs]=sm[CVs]=sm[AVs]=sm[TVs]=sm[EVs]=sm[MVs]=!0;sm[lVs]=sm[cVs]=sm[_Vs]=sm[dVs]=sm[wVs]=sm[uVs]=sm[hVs]=sm[mVs]=sm[pVs]=sm[fVs]=sm[gVs]=sm[xVs]=sm[yVs]=sm[vVs]=sm[bVs]=!1;function LVs(s){return oVs(s)&&iVs(s.length)&&!!sm[aVs(s)]}var PVs=LVs;function IVs(s){return function(t){return s(t)}}var Q6t=IVs,kke={exports:{}};kke.exports;(function(s,t){var n=i6t,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})(kke,kke.exports);var DVs=kke.exports,RVs=PVs,OVs=Q6t,flt=DVs,glt=flt&&flt.isTypedArray,FVs=glt?OVs(glt):RVs,J6t=FVs,zVs=Uqs,BVs=mHe,$Vs=bb,UVs=X6t,qVs=pHe,VVs=J6t,HVs=Object.prototype,GVs=HVs.hasOwnProperty;function WVs(s,t){var n=$Vs(s),r=!n&&BVs(s),a=!n&&!r&&UVs(s),i=!n&&!r&&!a&&VVs(s),l=n||r||a||i,o=l?zVs(s.length,String):[],c=o.length;for(var d in s)(t||GVs.call(s,d))&&!(l&&(d=="length"||a&&(d=="offset"||d=="parent")||i&&(d=="buffer"||d=="byteLength"||d=="byteOffset")||qVs(d,c)))&&o.push(d);return o}var KVs=WVs,YVs=Object.prototype;function ZVs(s){var t=s&&s.constructor,n=typeof t=="function"&&t.prototype||YVs;return s===n}var XVs=ZVs;function QVs(s,t){return function(n){return s(t(n))}}var eMt=QVs,JVs=eMt,eHs=JVs(Object.keys,Object),tHs=eHs,sHs=XVs,nHs=tHs,rHs=Object.prototype,aHs=rHs.hasOwnProperty;function iHs(s){if(!sHs(s))return nHs(s);var t=[];for(var n in Object(s))aHs.call(s,n)&&n!="constructor"&&t.push(n);return t}var oHs=iHs,lHs=ZVe,cHs=fHe;function dHs(s){return s!=null&&cHs(s.length)&&!lHs(s)}var oJ=dHs,uHs=KVs,hHs=oHs,mHs=oJ;function pHs(s){return mHs(s)?uHs(s):hHs(s)}var dCe=pHs,fHs=Eqs,gHs=Bqs,xHs=dCe;function yHs(s){return fHs(s,xHs,gHs)}var vHs=yHs,xlt=vHs,bHs=1,_Hs=Object.prototype,wHs=_Hs.hasOwnProperty;function jHs(s,t,n,r,a,i){var l=n&bHs,o=xlt(s),c=o.length,d=xlt(t),u=d.length;if(c!=u&&!l)return!1;for(var h=c;h--;){var m=o[h];if(!(l?m in t:wHs.call(t,m)))return!1}var f=i.get(s),g=i.get(t);if(f&&g)return f==t&&g==s;var y=!0;i.set(s,t),i.set(t,s);for(var x=l;++h-1}var _Ws=bWs;function wWs(s,t,n){for(var r=-1,a=s==null?0:s.length;++r=OWs){var d=t?null:DWs(s);if(d)return RWs(d);l=!1,a=IWs,c=new MWs}else c=t?[]:o;e:for(;++r=0)&&Object.prototype.propertyIsEnumerable.call(s,r)&&(n[r]=s[r])}return n}function JWs(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 eKs(s){return s.value}function tKs(s,t){if(Rt.isValidElement(s))return Rt.cloneElement(s,t);if(typeof s=="function")return Rt.createElement(s,t);t.ref;var n=QWs(t,VWs);return Rt.createElement(uHe,n)}var Plt=1,ID=function(s){function t(){var n;HWs(this,t);for(var r=arguments.length,a=new Array(r),i=0;iPlt||Math.abs(a.height-this.lastBoundingBox.height)>Plt)&&(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?RS({},this.lastBoundingBox):{width:0,height:0}}},{key:"getDefaultPosition",value:function(r){var a=this.props,i=a.layout,l=a.align,o=a.verticalAlign,c=a.margin,d=a.chartWidth,u=a.chartHeight,h,m;if(!r||(r.left===void 0||r.left===null)&&(r.right===void 0||r.right===null))if(l==="center"&&i==="vertical"){var f=this.getBBoxSnapshot();h={left:((d||0)-f.width)/2}}else h=l==="right"?{right:c&&c.right||0}:{left:c&&c.left||0};if(!r||(r.top===void 0||r.top===null)&&(r.bottom===void 0||r.bottom===null))if(o==="middle"){var g=this.getBBoxSnapshot();m={top:((u||0)-g.height)/2}}else m=o==="bottom"?{bottom:c&&c.bottom||0}:{top:c&&c.top||0};return RS(RS({},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=RS(RS({position:"absolute",width:l||"auto",height:o||"auto"},this.getDefaultPosition(c)),c);return Rt.createElement("div",{className:"recharts-legend-wrapper",style:h,ref:function(f){r.wrapperNode=f}},tKs(i,RS(RS({},this.props),{},{payload:oMt(u,d,eKs)})))}}],[{key:"getWithHeight",value:function(r,a){var i=RS(RS({},this.defaultProps),r.props),l=i.layout;return l==="vertical"&&Ka(r.props.height)?{height:r.props.height}:l==="horizontal"?{width:r.props.width||a}:null}}])}(N.PureComponent);uCe(ID,"displayName","Legend");uCe(ID,"defaultProps",{iconSize:14,layout:"horizontal",align:"center",verticalAlign:"bottom"});var Ilt=aJ,sKs=mHe,nKs=bb,Dlt=Ilt?Ilt.isConcatSpreadable:void 0;function rKs(s){return nKs(s)||sKs(s)||!!(Dlt&&s&&s[Dlt])}var aKs=rKs,iKs=Y6t,oKs=aKs;function dMt(s,t,n,r,a){var i=-1,l=s.length;for(n||(n=oKs),a||(a=[]);++i0&&n(o)?t>1?dMt(o,t-1,n,r,a):iKs(a,o):r||(a[a.length]=o)}return a}var uMt=dMt;function lKs(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 cKs=lKs,dKs=cKs,uKs=dKs(),hKs=uKs,mKs=hKs,pKs=dCe;function fKs(s,t){return s&&mKs(s,t,pKs)}var hMt=fKs,gKs=oJ;function xKs(s,t){return function(n,r){if(n==null)return n;if(!gKs(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 MKs=EKs,jLe=tHe,LKs=sHe,PKs=Z5,IKs=mMt,DKs=SKs,RKs=Q6t,OKs=MKs,FKs=IU,zKs=bb;function BKs(s,t,n){t.length?t=jLe(t,function(i){return zKs(i)?function(l){return LKs(l,i.length===1?i[0]:i)}:i}):t=[FKs];var r=-1;t=jLe(t,RKs(PKs));var a=IKs(s,function(i,l,o){var c=jLe(t,function(d){return d(i)});return{criteria:c,index:++r,value:i}});return DKs(a,function(i,l){return OKs(i,l,n)})}var $Ks=BKs;function UKs(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 qKs=UKs,VKs=qKs,Olt=Math.max;function HKs(s,t,n){return t=Olt(t===void 0?s.length-1:t,0),function(){for(var r=arguments,a=-1,i=Olt(r.length-t,0),l=Array(i);++a0){if(++t>=tYs)return arguments[0]}else t=0;return s.apply(void 0,arguments)}}var aYs=rYs,iYs=eYs,oYs=aYs,lYs=oYs(iYs),cYs=lYs,dYs=IU,uYs=GKs,hYs=cYs;function mYs(s,t){return hYs(uYs(s,t,dYs),s+"")}var pYs=mYs,fYs=XVe,gYs=oJ,xYs=pHe,yYs=XE;function vYs(s,t,n){if(!yYs(n))return!1;var r=typeof t;return(r=="number"?gYs(n)&&xYs(t,n.length):r=="string"&&t in n)?fYs(n[t],s):!1}var hCe=vYs,bYs=uMt,_Ys=$Ks,wYs=pYs,zlt=hCe,jYs=wYs(function(s,t){if(s==null)return[];var n=t.length;return n>1&&zlt(s,t[0],t[1])?t=[]:n>2&&zlt(t[0],t[1],t[2])&&(t=[t[0]]),_Ys(s,bYs(t,1),[])}),NYs=jYs;const yHe=Xc(NYs);function $Y(s){"@babel/helpers - typeof";return $Y=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},$Y(s)}function QOe(){return QOe=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(WV,"-left"),Ka(n)&&t&&Ka(t.x)&&n=t.y),"".concat(WV,"-top"),Ka(r)&&t&&Ka(t.y)&&ry?Math.max(u,c[r]):Math.max(h,c[r])}function zYs(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 BYs(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=Ult({allowEscapeViewBox:t,coordinate:n,key:"x",offsetTopLeft:r,position:a,reverseDirection:i,tooltipDimension:l.width,viewBox:c,viewBoxDimension:c.width}),h=Ult({allowEscapeViewBox:t,coordinate:n,key:"y",offsetTopLeft:r,position:a,reverseDirection:i,tooltipDimension:l.height,viewBox:c,viewBoxDimension:c.height}),d=zYs({translateX:u,translateY:h,useTranslate3d:o})):d=OYs,{cssProperties:d,cssClasses:FYs({translateX:u,translateY:h,coordinate:n})}}function s$(s){"@babel/helpers - typeof";return s$=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},s$(s)}function qlt(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 Vlt(s){for(var t=1;tHlt||Math.abs(r.height-this.state.lastBoundingBox.height)>Hlt)&&this.setState({lastBoundingBox:{width:r.width,height:r.height}})}else(this.state.lastBoundingBox.width!==-1||this.state.lastBoundingBox.height!==-1)&&this.setState({lastBoundingBox:{width:-1,height:-1}})}},{key:"componentDidMount",value:function(){document.addEventListener("keydown",this.handleKeyDown),this.updateBBox()}},{key:"componentWillUnmount",value:function(){document.removeEventListener("keydown",this.handleKeyDown)}},{key:"componentDidUpdate",value:function(){var r,a;this.props.active&&this.updateBBox(),this.state.dismissed&&(((r=this.props.coordinate)===null||r===void 0?void 0:r.x)!==this.state.dismissedAtCoordinate.x||((a=this.props.coordinate)===null||a===void 0?void 0:a.y)!==this.state.dismissedAtCoordinate.y)&&(this.state.dismissed=!1)}},{key:"render",value:function(){var r=this,a=this.props,i=a.active,l=a.allowEscapeViewBox,o=a.animationDuration,c=a.animationEasing,d=a.children,u=a.coordinate,h=a.hasPayload,m=a.isAnimationActive,f=a.offset,g=a.position,y=a.reverseDirection,x=a.useTranslate3d,_=a.viewBox,b=a.wrapperStyle,k=BYs({allowEscapeViewBox:l,coordinate:u,offsetTopLeft:f,position:g,reverseDirection:y,tooltipBox:this.state.lastBoundingBox,useTranslate3d:x,viewBox:_}),A=k.cssClasses,T=k.cssProperties,P=Vlt(Vlt({transition:m&&i?"transform ".concat(o,"ms ").concat(c):void 0},T),{},{pointerEvents:"none",visibility:!this.state.dismissed&&i&&h?"visible":"hidden",position:"absolute",top:0,left:0},b);return Rt.createElement("div",{tabIndex:-1,className:A,style:P,ref:function(M){r.wrapperNode=M}},d)}}])}(N.PureComponent),ZYs=function(){return!(typeof window<"u"&&window.document&&window.document.createElement&&window.setTimeout)},v5={isSsr:ZYs(),get:function(t){return v5[t]},set:function(t,n){if(typeof t=="string")v5[t]=n;else{var r=Object.keys(t);r&&r.length&&r.forEach(function(a){v5[a]=t[a]})}}};function n$(s){"@babel/helpers - typeof";return n$=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},n$(s)}function Glt(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 Wlt(s){for(var t=1;t0;return Rt.createElement(YYs,{allowEscapeViewBox:l,animationDuration:o,animationEasing:c,isAnimationActive:m,active:i,coordinate:u,hasPayload:P,offset:f,position:x,reverseDirection:_,useTranslate3d:b,viewBox:k,wrapperStyle:A},iZs(d,Wlt(Wlt({},this.props),{},{payload:T})))}}])}(N.PureComponent);vHe(Vx,"displayName","Tooltip");vHe(Vx,"defaultProps",{accessibilityLayer:!1,allowEscapeViewBox:{x:!1,y:!1},animationDuration:400,animationEasing:"ease",contentStyle:{},coordinate:{x:0,y:0},cursor:!0,cursorStyle:{},filterNull:!0,isAnimationActive:!v5.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 oZs=Y5,lZs=function(){return oZs.Date.now()},cZs=lZs,dZs=/\s/;function uZs(s){for(var t=s.length;t--&&dZs.test(s.charAt(t)););return t}var hZs=uZs,mZs=hZs,pZs=/^\s+/;function fZs(s){return s&&s.slice(0,mZs(s)+1).replace(pZs,"")}var gZs=fZs,xZs=gZs,Klt=XE,yZs=SU,Ylt=NaN,vZs=/^[-+]0x[0-9a-f]+$/i,bZs=/^0b[01]+$/i,_Zs=/^0o[0-7]+$/i,wZs=parseInt;function jZs(s){if(typeof s=="number")return s;if(yZs(s))return Ylt;if(Klt(s)){var t=typeof s.valueOf=="function"?s.valueOf():s;s=Klt(t)?t+"":t}if(typeof s!="string")return s===0?s:+s;s=xZs(s);var n=bZs.test(s);return n||_Zs.test(s)?wZs(s.slice(2),n?2:8):vZs.test(s)?Ylt:+s}var vMt=jZs,NZs=XE,kLe=cZs,Zlt=vMt,kZs="Expected a function",SZs=Math.max,CZs=Math.min;function AZs(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(kZs);t=Zlt(t)||0,NZs(n)&&(u=!!n.leading,h="maxWait"in n,i=h?SZs(Zlt(n.maxWait)||0,t):i,m="trailing"in n?!!n.trailing:m);function f(P){var I=r,M=a;return r=a=void 0,d=P,l=s.apply(M,I),l}function g(P){return d=P,o=setTimeout(_,t),u?f(P):l}function y(P){var I=P-c,M=P-d,L=t-I;return h?CZs(L,i-M):L}function x(P){var I=P-c,M=P-d;return c===void 0||I>=t||I<0||h&&M>=i}function _(){var P=kLe();if(x(P))return b(P);o=setTimeout(_,y(P))}function b(P){return o=void 0,m&&r?f(P):(r=a=void 0,l)}function k(){o!==void 0&&clearTimeout(o),d=0,r=c=a=o=void 0}function A(){return o===void 0?l:b(kLe())}function T(){var P=kLe(),I=x(P);if(r=arguments,a=this,c=P,I){if(o===void 0)return g(c);if(h)return clearTimeout(o),o=setTimeout(_,t),f(c)}return o===void 0&&(o=setTimeout(_,t)),l}return T.cancel=k,T.flush=A,T}var TZs=AZs,EZs=TZs,MZs=XE,LZs="Expected a function";function PZs(s,t,n){var r=!0,a=!0;if(typeof s!="function")throw new TypeError(LZs);return MZs(n)&&(r="leading"in n?!!n.leading:r,a="trailing"in n?!!n.trailing:a),EZs(s,t,{leading:r,maxWait:t,trailing:a})}var IZs=PZs;const bMt=Xc(IZs);function qY(s){"@babel/helpers - typeof";return qY=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},qY(s)}function Xlt(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 Fse(s){for(var t=1;ts.length)&&(t=s.length);for(var n=0,r=new Array(t);n0&&(W=bMt(W,y,{trailing:!0,leading:!1}));var G=new ResizeObserver(W),X=T.current.getBoundingClientRect(),te=X.width,ne=X.height;return $(te,ne),G.observe(T.current),function(){G.disconnect()}},[$,y]);var V=N.useMemo(function(){var W=L.containerWidth,G=L.containerHeight;if(W<0||G<0)return null;iN(FI(l)||FI(c),`The width(%s) and height(%s) are both fixed numbers, maybe you don't need to use a ResponsiveContainer.`,l,c),iN(!n||n>0,"The aspect(%s) must be greater than zero.",n);var X=FI(l)?W:l,te=FI(c)?G:c;n&&n>0&&(X?te=X/n:te&&(X=te*n),m&&te>m&&(te=m)),iN(X>0||te>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.`,X,te,l,c,u,h,n);var ne=!Array.isArray(f)&&u3(f.type).endsWith("Chart");return Rt.Children.map(f,function(me){return Rt.isValidElement(me)?N.cloneElement(me,Fse({width:X,height:te},ne?{style:Fse({height:"100%",width:"100%",maxHeight:te,maxWidth:X},me.props.style)}:{})):me})},[n,f,c,m,h,u,L,l]);return Rt.createElement("div",{id:x?"".concat(x):void 0,className:Ol("recharts-responsive-container",_),style:Fse(Fse({},A),{},{width:l,height:c,minWidth:u,minHeight:h,maxHeight:m}),ref:T},V)}),DU=function(t){return null};DU.displayName="Cell";function VY(s){"@babel/helpers - typeof";return VY=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},VY(s)}function Jlt(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 sFe(s){for(var t=1;t1&&arguments[1]!==void 0?arguments[1]:{};if(t==null||v5.isSsr)return{width:0,height:0};var r=KZs(n),a=JSON.stringify({text:t,copyStyle:r});if(NF.widthCache[a])return NF.widthCache[a];try{var i=document.getElementById(ect);i||(i=document.createElement("span"),i.setAttribute("id",ect),i.setAttribute("aria-hidden","true"),document.body.appendChild(i));var l=sFe(sFe({},WZs),r);Object.assign(i.style,l),i.textContent="".concat(t);var o=i.getBoundingClientRect(),c={width:o.width,height:o.height};return NF.widthCache[a]=c,++NF.cacheCount>GZs&&(NF.cacheCount=0,NF.widthCache={}),c}catch{return{width:0,height:0}}},YZs=function(t){return{top:t.top+window.scrollY-document.documentElement.clientTop,left:t.left+window.scrollX-document.documentElement.clientLeft}};function HY(s){"@babel/helpers - typeof";return HY=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},HY(s)}function Tke(s,t){return JZs(s)||QZs(s,t)||XZs(s,t)||ZZs()}function ZZs(){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 XZs(s,t){if(s){if(typeof s=="string")return tct(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 tct(s,t)}}function tct(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 mXs(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 oct(s,t){return xXs(s)||gXs(s,t)||fXs(s,t)||pXs()}function pXs(){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 fXs(s,t){if(s){if(typeof s=="string")return lct(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 lct(s,t)}}function lct(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 X.reduce(function(te,ne){var me=ne.word,ue=ne.width,ce=te[te.length-1];if(ce&&(a==null||i||ce.width+ue+rne.width?te:ne})};if(!u)return f;for(var y="…",x=function(X){var te=h.slice(0,X),ne=NMt({breakAll:d,style:c,children:te+y}).wordsWithComputedWidth,me=m(ne),ue=me.length>l||g(me).width>Number(a);return[ue,me]},_=0,b=h.length-1,k=0,A;_<=b&&k<=h.length-1;){var T=Math.floor((_+b)/2),P=T-1,I=x(P),M=oct(I,2),L=M[0],z=M[1],$=x(T),V=oct($,1),W=V[0];if(!L&&!W&&(_=T+1),L&&W&&(b=T-1),!L&&W){A=z;break}k++}return A||f},cct=function(t){var n=Ml(t)?[]:t.toString().split(jMt);return[{words:n}]},vXs=function(t){var n=t.width,r=t.scaleToFit,a=t.children,i=t.style,l=t.breakAll,o=t.maxLines;if((n||r)&&!v5.isSsr){var c,d,u=NMt({breakAll:l,children:a,style:i});if(u){var h=u.wordsWithComputedWidth,m=u.spaceWidth;c=h,d=m}else return cct(a);return yXs({breakAll:l,children:a,maxLines:o,style:i},c,d,n,r)}return cct(a)},dct="#808080",fR=function(t){var n=t.x,r=n===void 0?0:n,a=t.y,i=a===void 0?0:a,l=t.lineHeight,o=l===void 0?"1em":l,c=t.capHeight,d=c===void 0?"0.71em":c,u=t.scaleToFit,h=u===void 0?!1:u,m=t.textAnchor,f=m===void 0?"start":m,g=t.verticalAnchor,y=g===void 0?"end":g,x=t.fill,_=x===void 0?dct:x,b=ict(t,uXs),k=N.useMemo(function(){return vXs({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]),A=b.dx,T=b.dy,P=b.angle,I=b.className,M=b.breakAll,L=ict(b,hXs);if(!sx(r)||!sx(i))return null;var z=r+(Ka(A)?A:0),$=i+(Ka(T)?T:0),V;switch(y){case"start":V=SLe("calc(".concat(d,")"));break;case"middle":V=SLe("calc(".concat((k.length-1)/2," * -").concat(o," + (").concat(d," / 2))"));break;default:V=SLe("calc(".concat(k.length-1," * -").concat(o,")"));break}var W=[];if(h){var G=k[0].width,X=b.width;W.push("scale(".concat((Ka(X)?X/G:1)/G,")"))}return P&&W.push("rotate(".concat(P,", ").concat(z,", ").concat($,")")),W.length&&(L.transform=W.join(" ")),Rt.createElement("text",nFe({},qo(L,!0),{x:z,y:$,className:Ol("recharts-text",I),textAnchor:f,fill:_.includes("url")?dct:_}),k.map(function(te,ne){var me=te.words.join(M?"":" ");return Rt.createElement("tspan",{x:z,dy:ne===0?V:o,key:"".concat(me,"-").concat(ne)},me)}))};function ZT(s,t){return s==null||t==null?NaN:st?1:s>=t?0:NaN}function bXs(s,t){return s==null||t==null?NaN:ts?1:t>=s?0:NaN}function bHe(s){let t,n,r;s.length!==2?(t=ZT,n=(o,c)=>ZT(s(o),c),r=(o,c)=>s(o)-c):(t=s===ZT||s===bXs?s:_Xs,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 _Xs(){return 0}function kMt(s){return s===null?NaN:+s}function*wXs(s,t){for(let n of s)n!=null&&(n=+n)>=n&&(yield n)}const jXs=bHe(ZT),lJ=jXs.right;bHe(kMt).center;class uct extends Map{constructor(t,n=SXs){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(hct(this,t))}has(t){return super.has(hct(this,t))}set(t,n){return super.set(NXs(this,t),n)}delete(t){return super.delete(kXs(this,t))}}function hct({_intern:s,_key:t},n){const r=t(n);return s.has(r)?s.get(r):n}function NXs({_intern:s,_key:t},n){const r=t(n);return s.has(r)?s.get(r):(s.set(r,n),n)}function kXs({_intern:s,_key:t},n){const r=t(n);return s.has(r)&&(n=s.get(r),s.delete(r)),n}function SXs(s){return s!==null&&typeof s=="object"?s.valueOf():s}function CXs(s=ZT){if(s===ZT)return SMt;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 SMt(s,t){return(s==null||!(s>=s))-(t==null||!(t>=t))||(st?1:0)}const AXs=Math.sqrt(50),TXs=Math.sqrt(10),EXs=Math.sqrt(2);function Eke(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>=AXs?10:i>=TXs?5:i>=EXs?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 pct(s,t){let n;for(const r of s)r!=null&&(n>r||n===void 0&&r>=r)&&(n=r);return n}function CMt(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?SMt:CXs(a);r>n;){if(r-n>600){const c=r-n+1,d=t-n+1,u=Math.log(c),h=.5*Math.exp(2*u/3),m=.5*Math.sqrt(u*h*(c-h)/c)*(d-c/2<0?-1:1),f=Math.max(n,Math.floor(t-d*h/c+m)),g=Math.min(r,Math.floor(t+(c-d)*h/c+m));CMt(s,t,f,g,a)}const i=s[t];let l=n,o=r;for(KV(s,n,t),a(s[r],i)>0&&KV(s,n,r);l0;)--o}a(s[n],i)===0?KV(s,n,o):(++o,KV(s,o,r)),o<=t&&(n=o+1),t<=o&&(r=o-1)}return s}function KV(s,t,n){const r=s[t];s[t]=s[n],s[n]=r}function MXs(s,t,n){if(s=Float64Array.from(wXs(s)),!(!(r=s.length)||isNaN(t=+t))){if(t<=0||r<2)return pct(s);if(t>=1)return mct(s);var r,a=(r-1)*t,i=Math.floor(a),l=mct(CMt(s,i).subarray(0,i+1)),o=pct(s.subarray(i+1));return l+(o-l)*(a-i)}}function LXs(s,t,n=kMt){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 PXs(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?Bse(t>>24&255,t>>16&255,t>>8&255,(t&255)/255):n===4?Bse(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=DXs.exec(s))?new Y1(t[1],t[2],t[3],1):(t=RXs.exec(s))?new Y1(t[1]*255/100,t[2]*255/100,t[3]*255/100,1):(t=OXs.exec(s))?Bse(t[1],t[2],t[3],t[4]):(t=FXs.exec(s))?Bse(t[1]*255/100,t[2]*255/100,t[3]*255/100,t[4]):(t=zXs.exec(s))?_ct(t[1],t[2]/100,t[3]/100,1):(t=BXs.exec(s))?_ct(t[1],t[2]/100,t[3]/100,t[4]):fct.hasOwnProperty(s)?yct(fct[s]):s==="transparent"?new Y1(NaN,NaN,NaN,0):null}function yct(s){return new Y1(s>>16&255,s>>8&255,s&255,1)}function Bse(s,t,n,r){return r<=0&&(s=t=n=NaN),new Y1(s,t,n,r)}function qXs(s){return s instanceof cJ||(s=YY(s)),s?(s=s.rgb(),new Y1(s.r,s.g,s.b,s.opacity)):new Y1}function lFe(s,t,n,r){return arguments.length===1?qXs(s):new Y1(s,t,n,r??1)}function Y1(s,t,n,r){this.r=+s,this.g=+t,this.b=+n,this.opacity=+r}wHe(Y1,lFe,TMt(cJ,{brighter(s){return s=s==null?Mke:Math.pow(Mke,s),new Y1(this.r*s,this.g*s,this.b*s,this.opacity)},darker(s){return s=s==null?WY:Math.pow(WY,s),new Y1(this.r*s,this.g*s,this.b*s,this.opacity)},rgb(){return this},clamp(){return new Y1(DD(this.r),DD(this.g),DD(this.b),Lke(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:vct,formatHex:vct,formatHex8:VXs,formatRgb:bct,toString:bct}));function vct(){return`#${zI(this.r)}${zI(this.g)}${zI(this.b)}`}function VXs(){return`#${zI(this.r)}${zI(this.g)}${zI(this.b)}${zI((isNaN(this.opacity)?1:this.opacity)*255)}`}function bct(){const s=Lke(this.opacity);return`${s===1?"rgb(":"rgba("}${DD(this.r)}, ${DD(this.g)}, ${DD(this.b)}${s===1?")":`, ${s})`}`}function Lke(s){return isNaN(s)?1:Math.max(0,Math.min(1,s))}function DD(s){return Math.max(0,Math.min(255,Math.round(s)||0))}function zI(s){return s=DD(s),(s<16?"0":"")+s.toString(16)}function _ct(s,t,n,r){return r<=0?s=t=n=NaN:n<=0||n>=1?s=t=NaN:t<=0&&(s=NaN),new $2(s,t,n,r)}function EMt(s){if(s instanceof $2)return new $2(s.h,s.s,s.l,s.opacity);if(s instanceof cJ||(s=YY(s)),!s)return new $2;if(s instanceof $2)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 $2(l,o,c,s.opacity)}function HXs(s,t,n,r){return arguments.length===1?EMt(s):new $2(s,t,n,r??1)}function $2(s,t,n,r){this.h=+s,this.s=+t,this.l=+n,this.opacity=+r}wHe($2,HXs,TMt(cJ,{brighter(s){return s=s==null?Mke:Math.pow(Mke,s),new $2(this.h,this.s,this.l*s,this.opacity)},darker(s){return s=s==null?WY:Math.pow(WY,s),new $2(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 Y1(CLe(s>=240?s-240:s+120,a,r),CLe(s,a,r),CLe(s<120?s+240:s-120,a,r),this.opacity)},clamp(){return new $2(wct(this.h),$se(this.s),$se(this.l),Lke(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=Lke(this.opacity);return`${s===1?"hsl(":"hsla("}${wct(this.h)}, ${$se(this.s)*100}%, ${$se(this.l)*100}%${s===1?")":`, ${s})`}`}}));function wct(s){return s=(s||0)%360,s<0?s+360:s}function $se(s){return Math.max(0,Math.min(1,s||0))}function CLe(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 jHe=s=>()=>s;function GXs(s,t){return function(n){return s+n*t}}function WXs(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 KXs(s){return(s=+s)==1?MMt:function(t,n){return n-t?WXs(t,n,s):jHe(isNaN(t)?n:t)}}function MMt(s,t){var n=t-s;return n?GXs(s,n):jHe(isNaN(s)?t:s)}const jct=function s(t){var n=KXs(t);function r(a,i){var l=n((a=lFe(a)).r,(i=lFe(i)).r),o=n(a.g,i.g),c=n(a.b,i.b),d=MMt(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 YXs(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:Pke(r,a)})),n=ALe.lastIndex;return nt&&(n=s,s=t,t=n),function(r){return Math.max(s,Math.min(t,r))}}function iQs(s,t,n){var r=s[0],a=s[1],i=t[0],l=t[1];return a2?oQs:iQs,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),Pke)))(m)))},h.domain=function(m){return arguments.length?(s=Array.from(m,Ike),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=NHe,u()},h.clamp=function(m){return arguments.length?(l=m?!0:$v,u()):l!==$v},h.interpolate=function(m){return arguments.length?(n=m,u()):n},h.unknown=function(m){return arguments.length?(i=m,h):i},function(m,f){return r=m,a=f,u()}}function kHe(){return mCe()($v,$v)}function lQs(s){return Math.abs(s=Math.round(s))>=1e21?s.toLocaleString("en").replace(/,/g,""):s.toString(10)}function Dke(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 r$(s){return s=Dke(Math.abs(s)),s?s[1]:NaN}function cQs(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 dQs(s){return function(t){return t.replace(/[0-9]/g,function(n){return s[+n]})}}var uQs=/^(?:(.)?([<>=^]))?([+\-( ])?([$#])?(0)?(\d+)?(,)?(\.\d+)?(~)?([a-z%])?$/i;function ZY(s){if(!(t=uQs.exec(s)))throw new Error("invalid format: "+s);var t;return new SHe({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]})}ZY.prototype=SHe.prototype;function SHe(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+""}SHe.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 hQs(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 LMt;function mQs(s,t){var n=Dke(s,t);if(!n)return s+"";var r=n[0],a=n[1],i=a-(LMt=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")+Dke(s,Math.max(0,t+i-1))[0]}function kct(s,t){var n=Dke(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 Sct={"%":(s,t)=>(s*100).toFixed(t),b:s=>Math.round(s).toString(2),c:s=>s+"",d:lQs,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)=>kct(s*100,t),r:kct,s:mQs,X:s=>Math.round(s).toString(16).toUpperCase(),x:s=>Math.round(s).toString(16)};function Cct(s){return s}var Act=Array.prototype.map,Tct=["y","z","a","f","p","n","µ","m","","k","M","G","T","P","E","Z","Y"];function pQs(s){var t=s.grouping===void 0||s.thousands===void 0?Cct:cQs(Act.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?Cct:dQs(Act.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=ZY(h);var m=h.fill,f=h.align,g=h.sign,y=h.symbol,x=h.zero,_=h.width,b=h.comma,k=h.precision,A=h.trim,T=h.type;T==="n"?(b=!0,T="g"):Sct[T]||(k===void 0&&(k=12),A=!0,T="g"),(x||m==="0"&&f==="=")&&(x=!0,m="0",f="=");var P=y==="$"?n:y==="#"&&/[boxX]/.test(T)?"0"+T.toLowerCase():"",I=y==="$"?r:/[%p]/.test(T)?l:"",M=Sct[T],L=/[defgprs%]/.test(T);k=k===void 0?6:/[gprs]/.test(T)?Math.max(1,Math.min(21,k)):Math.max(0,Math.min(20,k));function z($){var V=P,W=I,G,X,te;if(T==="c")W=M($)+W,$="";else{$=+$;var ne=$<0||1/$<0;if($=isNaN($)?c:M(Math.abs($),k),A&&($=hQs($)),ne&&+$==0&&g!=="+"&&(ne=!1),V=(ne?g==="("?g:o:g==="-"||g==="("?"":g)+V,W=(T==="s"?Tct[8+LMt/3]:"")+W+(ne&&g==="("?")":""),L){for(G=-1,X=$.length;++Gte||te>57){W=(te===46?a+$.slice(G+1):$.slice(G))+W,$=$.slice(0,G);break}}}b&&!x&&($=t($,1/0));var me=V.length+$.length+W.length,ue=me<_?new Array(_-me+1).join(m):"";switch(b&&x&&($=t(ue+$,ue.length?_-W.length:1/0),ue=""),f){case"<":$=V+$+W+ue;break;case"=":$=V+ue+$+W;break;case"^":$=ue.slice(0,me=ue.length>>1)+V+$+W+ue.slice(me);break;default:$=ue+V+$+W;break}return i($)}return z.toString=function(){return h+""},z}function u(h,m){var f=d((h=ZY(h),h.type="f",h)),g=Math.max(-8,Math.min(8,Math.floor(r$(m)/3)))*3,y=Math.pow(10,-g),x=Tct[8+g/3];return function(_){return f(y*_)+x}}return{format:d,formatPrefix:u}}var Use,CHe,PMt;fQs({thousands:",",grouping:[3],currency:["$",""]});function fQs(s){return Use=pQs(s),CHe=Use.format,PMt=Use.formatPrefix,Use}function gQs(s){return Math.max(0,-r$(Math.abs(s)))}function xQs(s,t){return Math.max(0,Math.max(-8,Math.min(8,Math.floor(r$(t)/3)))*3-r$(Math.abs(s)))}function yQs(s,t){return s=Math.abs(s),t=Math.abs(t)-s,Math.max(0,r$(t)-r$(s))+1}function IMt(s,t,n,r){var a=iFe(s,t,n),i;switch(r=ZY(r??",f"),r.type){case"s":{var l=Math.max(Math.abs(s),Math.abs(t));return r.precision==null&&!isNaN(i=xQs(a,l))&&(r.precision=i),PMt(r,l)}case"":case"e":case"g":case"p":case"r":{r.precision==null&&!isNaN(i=yQs(a,Math.max(Math.abs(s),Math.abs(t))))&&(r.precision=i-(r.type==="e"));break}case"f":case"%":{r.precision==null&&!isNaN(i=gQs(a))&&(r.precision=i-(r.type==="%")*2);break}}return CHe(r)}function QE(s){var t=s.domain;return s.ticks=function(n){var r=t();return rFe(r[0],r[r.length-1],n??10)},s.tickFormat=function(n,r){var a=t();return IMt(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=aFe(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 Rke(){var s=kHe();return s.copy=function(){return dJ(s,Rke())},Mj.apply(s,arguments),QE(s)}function DMt(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,Ike),n):s.slice()},n.unknown=function(r){return arguments.length?(t=r,n):t},n.copy=function(){return DMt(s).unknown(t)},s=arguments.length?Array.from(s,Ike):[0,1],QE(n)}function RMt(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 jQs(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 Lct(s){return(t,n)=>-s(-t,n)}function AHe(s){const t=s(Ect,Mct),n=t.domain;let r=10,a,i;function l(){return a=jQs(r),i=wQs(r),n()[0]<0?(a=Lct(a),i=Lct(i),s(vQs,bQs)):s(Ect,Mct),t}return t.base=function(o){return arguments.length?(r=+o,l()):r},t.domain=function(o){return arguments.length?(n(o),l()):n()},t.ticks=o=>{const c=n();let d=c[0],u=c[c.length-1];const h=u0){for(;m<=f;++m)for(g=1;gu)break;_.push(y)}}else for(;m<=f;++m)for(g=r-1;g>=1;--g)if(y=m>0?g/i(-m):g*i(m),!(yu)break;_.push(y)}_.length*2{if(o==null&&(o=10),c==null&&(c=r===10?"s":","),typeof c!="function"&&(!(r%1)&&(c=ZY(c)).precision==null&&(c.trim=!0),c=CHe(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(RMt(n(),{floor:o=>i(Math.floor(a(o))),ceil:o=>i(Math.ceil(a(o)))})),t}function OMt(){const s=AHe(mCe()).domain([1,10]);return s.copy=()=>dJ(s,OMt()).base(s.base()),Mj.apply(s,arguments),s}function Pct(s){return function(t){return Math.sign(t)*Math.log1p(Math.abs(t/s))}}function Ict(s){return function(t){return Math.sign(t)*Math.expm1(Math.abs(t))*s}}function THe(s){var t=1,n=s(Pct(t),Ict(t));return n.constant=function(r){return arguments.length?s(Pct(t=+r),Ict(t)):t},QE(n)}function FMt(){var s=THe(mCe());return s.copy=function(){return dJ(s,FMt()).constant(s.constant())},Mj.apply(s,arguments)}function Dct(s){return function(t){return t<0?-Math.pow(-t,s):Math.pow(t,s)}}function NQs(s){return s<0?-Math.sqrt(-s):Math.sqrt(s)}function kQs(s){return s<0?-s*s:s*s}function EHe(s){var t=s($v,$v),n=1;function r(){return n===1?s($v,$v):n===.5?s(NQs,kQs):s(Dct(n),Dct(1/n))}return t.exponent=function(a){return arguments.length?(n=+a,r()):n},QE(t)}function MHe(){var s=EHe(mCe());return s.copy=function(){return dJ(s,MHe()).exponent(s.exponent())},Mj.apply(s,arguments),s}function SQs(){return MHe.apply(null,arguments).exponent(.5)}function Rct(s){return Math.sign(s)*s*s}function CQs(s){return Math.sign(s)*Math.sqrt(Math.abs(s))}function zMt(){var s=kHe(),t=[0,1],n=!1,r;function a(i){var l=CQs(s(i));return isNaN(l)?r:n?Math.round(l):l}return a.invert=function(i){return s.invert(Rct(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,Ike)).map(Rct)),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 zMt(s.domain(),t).round(n).clamp(s.clamp()).unknown(r)},Mj.apply(a,arguments),QE(a)}function BMt(){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 $Mt().domain([s,t]).range(a).unknown(i)},Mj.apply(QE(l),arguments)}function UMt(){var s=[.5],t=[0,1],n,r=1;function a(i){return i!=null&&i<=i?t[lJ(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 UMt().domain(s).range(t).unknown(n)},Mj.apply(a,arguments)}const TLe=new Date,ELe=new Date;function hx(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(dhx(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)=>(TLe.setTime(+i),ELe.setTime(+l),s(TLe),s(ELe),Math.floor(n(TLe,ELe))),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 Oke=hx(()=>{},(s,t)=>{s.setTime(+s+t)},(s,t)=>t-s);Oke.every=s=>(s=Math.floor(s),!isFinite(s)||!(s>0)?null:s>1?hx(t=>{t.setTime(Math.floor(t/s)*s)},(t,n)=>{t.setTime(+t+n*s)},(t,n)=>(n-t)/s):Oke);Oke.range;const K4=1e3,aj=K4*60,Y4=aj*60,C3=Y4*24,LHe=C3*7,Oct=C3*30,MLe=C3*365,BI=hx(s=>{s.setTime(s-s.getMilliseconds())},(s,t)=>{s.setTime(+s+t*K4)},(s,t)=>(t-s)/K4,s=>s.getUTCSeconds());BI.range;const PHe=hx(s=>{s.setTime(s-s.getMilliseconds()-s.getSeconds()*K4)},(s,t)=>{s.setTime(+s+t*aj)},(s,t)=>(t-s)/aj,s=>s.getMinutes());PHe.range;const IHe=hx(s=>{s.setUTCSeconds(0,0)},(s,t)=>{s.setTime(+s+t*aj)},(s,t)=>(t-s)/aj,s=>s.getUTCMinutes());IHe.range;const DHe=hx(s=>{s.setTime(s-s.getMilliseconds()-s.getSeconds()*K4-s.getMinutes()*aj)},(s,t)=>{s.setTime(+s+t*Y4)},(s,t)=>(t-s)/Y4,s=>s.getHours());DHe.range;const RHe=hx(s=>{s.setUTCMinutes(0,0,0)},(s,t)=>{s.setTime(+s+t*Y4)},(s,t)=>(t-s)/Y4,s=>s.getUTCHours());RHe.range;const uJ=hx(s=>s.setHours(0,0,0,0),(s,t)=>s.setDate(s.getDate()+t),(s,t)=>(t-s-(t.getTimezoneOffset()-s.getTimezoneOffset())*aj)/C3,s=>s.getDate()-1);uJ.range;const pCe=hx(s=>{s.setUTCHours(0,0,0,0)},(s,t)=>{s.setUTCDate(s.getUTCDate()+t)},(s,t)=>(t-s)/C3,s=>s.getUTCDate()-1);pCe.range;const qMt=hx(s=>{s.setUTCHours(0,0,0,0)},(s,t)=>{s.setUTCDate(s.getUTCDate()+t)},(s,t)=>(t-s)/C3,s=>Math.floor(s/C3));qMt.range;function QR(s){return hx(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())*aj)/LHe)}const fCe=QR(0),Fke=QR(1),AQs=QR(2),TQs=QR(3),a$=QR(4),EQs=QR(5),MQs=QR(6);fCe.range;Fke.range;AQs.range;TQs.range;a$.range;EQs.range;MQs.range;function JR(s){return hx(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)/LHe)}const gCe=JR(0),zke=JR(1),LQs=JR(2),PQs=JR(3),i$=JR(4),IQs=JR(5),DQs=JR(6);gCe.range;zke.range;LQs.range;PQs.range;i$.range;IQs.range;DQs.range;const OHe=hx(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());OHe.range;const FHe=hx(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());FHe.range;const A3=hx(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());A3.every=s=>!isFinite(s=Math.floor(s))||!(s>0)?null:hx(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)});A3.range;const T3=hx(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());T3.every=s=>!isFinite(s=Math.floor(s))||!(s>0)?null:hx(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)});T3.range;function VMt(s,t,n,r,a,i){const l=[[BI,1,K4],[BI,5,5*K4],[BI,15,15*K4],[BI,30,30*K4],[i,1,aj],[i,5,5*aj],[i,15,15*aj],[i,30,30*aj],[a,1,Y4],[a,3,3*Y4],[a,6,6*Y4],[a,12,12*Y4],[r,1,C3],[r,2,2*C3],[n,1,LHe],[t,1,Oct],[t,3,3*Oct],[s,1,MLe]];function o(d,u,h){const m=ux).right(l,m);if(f===l.length)return s.every(iFe(d/MLe,u/MLe,h));if(f===0)return Oke.every(Math.max(iFe(d,u,h),1));const[g,y]=l[m/l[f-1][2]53)return null;"w"in Ne||(Ne.w=1),"Z"in Ne?(Ce=PLe(YV(Ne.y,0,1)),Fe=Ce.getUTCDay(),Ce=Fe>4||Fe===0?zke.ceil(Ce):zke(Ce),Ce=pCe.offset(Ce,(Ne.V-1)*7),Ne.y=Ce.getUTCFullYear(),Ne.m=Ce.getUTCMonth(),Ne.d=Ce.getUTCDate()+(Ne.w+6)%7):(Ce=LLe(YV(Ne.y,0,1)),Fe=Ce.getDay(),Ce=Fe>4||Fe===0?Fke.ceil(Ce):Fke(Ce),Ce=uJ.offset(Ce,(Ne.V-1)*7),Ne.y=Ce.getFullYear(),Ne.m=Ce.getMonth(),Ne.d=Ce.getDate()+(Ne.w+6)%7)}else("W"in Ne||"U"in Ne)&&("w"in Ne||(Ne.w="u"in Ne?Ne.u%7:"W"in Ne?1:0),Fe="Z"in Ne?PLe(YV(Ne.y,0,1)).getUTCDay():LLe(YV(Ne.y,0,1)).getDay(),Ne.m=0,Ne.d="W"in Ne?(Ne.w+6)%7+Ne.W*7-(Fe+5)%7:Ne.w+Ne.U*7-(Fe+6)%7);return"Z"in Ne?(Ne.H+=Ne.Z/100|0,Ne.M+=Ne.Z%100,PLe(Ne)):LLe(Ne)}}function M(Me,Re,Be,Ne){for(var Ge=0,Ce=Re.length,Fe=Be.length,Ae,Xe;Ge=Fe)return-1;if(Ae=Re.charCodeAt(Ge++),Ae===37){if(Ae=Re.charAt(Ge++),Xe=T[Ae in Fct?Re.charAt(Ge++):Ae],!Xe||(Ne=Xe(Me,Be,Ne))<0)return-1}else if(Ae!=Be.charCodeAt(Ne++))return-1}return Ne}function L(Me,Re,Be){var Ne=d.exec(Re.slice(Be));return Ne?(Me.p=u.get(Ne[0].toLowerCase()),Be+Ne[0].length):-1}function z(Me,Re,Be){var Ne=f.exec(Re.slice(Be));return Ne?(Me.w=g.get(Ne[0].toLowerCase()),Be+Ne[0].length):-1}function $(Me,Re,Be){var Ne=h.exec(Re.slice(Be));return Ne?(Me.w=m.get(Ne[0].toLowerCase()),Be+Ne[0].length):-1}function V(Me,Re,Be){var Ne=_.exec(Re.slice(Be));return Ne?(Me.m=b.get(Ne[0].toLowerCase()),Be+Ne[0].length):-1}function W(Me,Re,Be){var Ne=y.exec(Re.slice(Be));return Ne?(Me.m=x.get(Ne[0].toLowerCase()),Be+Ne[0].length):-1}function G(Me,Re,Be){return M(Me,t,Re,Be)}function X(Me,Re,Be){return M(Me,n,Re,Be)}function te(Me,Re,Be){return M(Me,r,Re,Be)}function ne(Me){return l[Me.getDay()]}function me(Me){return i[Me.getDay()]}function ue(Me){return c[Me.getMonth()]}function ce(Me){return o[Me.getMonth()]}function ae(Me){return a[+(Me.getHours()>=12)]}function he(Me){return 1+~~(Me.getMonth()/3)}function xe(Me){return l[Me.getUTCDay()]}function ve(Me){return i[Me.getUTCDay()]}function ge(Me){return c[Me.getUTCMonth()]}function be(Me){return o[Me.getUTCMonth()]}function Se(Me){return a[+(Me.getUTCHours()>=12)]}function Ie(Me){return 1+~~(Me.getUTCMonth()/3)}return{format:function(Me){var Re=P(Me+="",k);return Re.toString=function(){return Me},Re},parse:function(Me){var Re=I(Me+="",!1);return Re.toString=function(){return Me},Re},utcFormat:function(Me){var Re=P(Me+="",A);return Re.toString=function(){return Me},Re},utcParse:function(Me){var Re=I(Me+="",!0);return Re.toString=function(){return Me},Re}}}var Fct={"-":"",_:" ",0:"0"},Jx=/^\s*\d+/,$Qs=/^%/,UQs=/[\\^$*+?|[\]().{}]/g;function Hd(s,t,n){var r=s<0?"-":"",a=(r?-s:s)+"",i=a.length;return r+(i[t.toLowerCase(),n]))}function VQs(s,t,n){var r=Jx.exec(t.slice(n,n+1));return r?(s.w=+r[0],n+r[0].length):-1}function HQs(s,t,n){var r=Jx.exec(t.slice(n,n+1));return r?(s.u=+r[0],n+r[0].length):-1}function GQs(s,t,n){var r=Jx.exec(t.slice(n,n+2));return r?(s.U=+r[0],n+r[0].length):-1}function WQs(s,t,n){var r=Jx.exec(t.slice(n,n+2));return r?(s.V=+r[0],n+r[0].length):-1}function KQs(s,t,n){var r=Jx.exec(t.slice(n,n+2));return r?(s.W=+r[0],n+r[0].length):-1}function zct(s,t,n){var r=Jx.exec(t.slice(n,n+4));return r?(s.y=+r[0],n+r[0].length):-1}function Bct(s,t,n){var r=Jx.exec(t.slice(n,n+2));return r?(s.y=+r[0]+(+r[0]>68?1900:2e3),n+r[0].length):-1}function YQs(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 ZQs(s,t,n){var r=Jx.exec(t.slice(n,n+1));return r?(s.q=r[0]*3-3,n+r[0].length):-1}function XQs(s,t,n){var r=Jx.exec(t.slice(n,n+2));return r?(s.m=r[0]-1,n+r[0].length):-1}function $ct(s,t,n){var r=Jx.exec(t.slice(n,n+2));return r?(s.d=+r[0],n+r[0].length):-1}function QQs(s,t,n){var r=Jx.exec(t.slice(n,n+3));return r?(s.m=0,s.d=+r[0],n+r[0].length):-1}function Uct(s,t,n){var r=Jx.exec(t.slice(n,n+2));return r?(s.H=+r[0],n+r[0].length):-1}function JQs(s,t,n){var r=Jx.exec(t.slice(n,n+2));return r?(s.M=+r[0],n+r[0].length):-1}function eJs(s,t,n){var r=Jx.exec(t.slice(n,n+2));return r?(s.S=+r[0],n+r[0].length):-1}function tJs(s,t,n){var r=Jx.exec(t.slice(n,n+3));return r?(s.L=+r[0],n+r[0].length):-1}function sJs(s,t,n){var r=Jx.exec(t.slice(n,n+6));return r?(s.L=Math.floor(r[0]/1e3),n+r[0].length):-1}function nJs(s,t,n){var r=$Qs.exec(t.slice(n,n+1));return r?n+r[0].length:-1}function rJs(s,t,n){var r=Jx.exec(t.slice(n));return r?(s.Q=+r[0],n+r[0].length):-1}function aJs(s,t,n){var r=Jx.exec(t.slice(n));return r?(s.s=+r[0],n+r[0].length):-1}function qct(s,t){return Hd(s.getDate(),t,2)}function iJs(s,t){return Hd(s.getHours(),t,2)}function oJs(s,t){return Hd(s.getHours()%12||12,t,2)}function lJs(s,t){return Hd(1+uJ.count(A3(s),s),t,3)}function HMt(s,t){return Hd(s.getMilliseconds(),t,3)}function cJs(s,t){return HMt(s,t)+"000"}function dJs(s,t){return Hd(s.getMonth()+1,t,2)}function uJs(s,t){return Hd(s.getMinutes(),t,2)}function hJs(s,t){return Hd(s.getSeconds(),t,2)}function mJs(s){var t=s.getDay();return t===0?7:t}function pJs(s,t){return Hd(fCe.count(A3(s)-1,s),t,2)}function GMt(s){var t=s.getDay();return t>=4||t===0?a$(s):a$.ceil(s)}function fJs(s,t){return s=GMt(s),Hd(a$.count(A3(s),s)+(A3(s).getDay()===4),t,2)}function gJs(s){return s.getDay()}function xJs(s,t){return Hd(Fke.count(A3(s)-1,s),t,2)}function yJs(s,t){return Hd(s.getFullYear()%100,t,2)}function vJs(s,t){return s=GMt(s),Hd(s.getFullYear()%100,t,2)}function bJs(s,t){return Hd(s.getFullYear()%1e4,t,4)}function _Js(s,t){var n=s.getDay();return s=n>=4||n===0?a$(s):a$.ceil(s),Hd(s.getFullYear()%1e4,t,4)}function wJs(s){var t=s.getTimezoneOffset();return(t>0?"-":(t*=-1,"+"))+Hd(t/60|0,"0",2)+Hd(t%60,"0",2)}function Vct(s,t){return Hd(s.getUTCDate(),t,2)}function jJs(s,t){return Hd(s.getUTCHours(),t,2)}function NJs(s,t){return Hd(s.getUTCHours()%12||12,t,2)}function kJs(s,t){return Hd(1+pCe.count(T3(s),s),t,3)}function WMt(s,t){return Hd(s.getUTCMilliseconds(),t,3)}function SJs(s,t){return WMt(s,t)+"000"}function CJs(s,t){return Hd(s.getUTCMonth()+1,t,2)}function AJs(s,t){return Hd(s.getUTCMinutes(),t,2)}function TJs(s,t){return Hd(s.getUTCSeconds(),t,2)}function EJs(s){var t=s.getUTCDay();return t===0?7:t}function MJs(s,t){return Hd(gCe.count(T3(s)-1,s),t,2)}function KMt(s){var t=s.getUTCDay();return t>=4||t===0?i$(s):i$.ceil(s)}function LJs(s,t){return s=KMt(s),Hd(i$.count(T3(s),s)+(T3(s).getUTCDay()===4),t,2)}function PJs(s){return s.getUTCDay()}function IJs(s,t){return Hd(zke.count(T3(s)-1,s),t,2)}function DJs(s,t){return Hd(s.getUTCFullYear()%100,t,2)}function RJs(s,t){return s=KMt(s),Hd(s.getUTCFullYear()%100,t,2)}function OJs(s,t){return Hd(s.getUTCFullYear()%1e4,t,4)}function FJs(s,t){var n=s.getUTCDay();return s=n>=4||n===0?i$(s):i$.ceil(s),Hd(s.getUTCFullYear()%1e4,t,4)}function zJs(){return"+0000"}function Hct(){return"%"}function Gct(s){return+s}function Wct(s){return Math.floor(+s/1e3)}var kF,YMt,ZMt;BJs({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 BJs(s){return kF=BQs(s),YMt=kF.format,kF.parse,ZMt=kF.utcFormat,kF.utcParse,kF}function $Js(s){return new Date(s)}function UJs(s){return s instanceof Date?+s:+new Date(+s)}function zHe(s,t,n,r,a,i,l,o,c,d){var u=kHe(),h=u.invert,m=u.domain,f=d(".%L"),g=d(":%S"),y=d("%I:%M"),x=d("%I %p"),_=d("%a %d"),b=d("%b %d"),k=d("%B"),A=d("%Y");function T(P){return(c(P)t(a/(s.length-1)))},n.quantiles=function(r){return Array.from({length:r+1},(a,i)=>MXs(s,i/r))},n.copy=function(){return eLt(t).domain(s)},H3.apply(n,arguments)}function yCe(){var s=0,t=.5,n=1,r=1,a,i,l,o,c,d=$v,u,h=!1,m;function f(y){return isNaN(y=+y)?m:(y=.5+((y=+u(y))-i)*(r*yt}var rLt=YJs,ZJs=vCe,XJs=rLt,QJs=IU;function JJs(s){return s&&s.length?ZJs(s,QJs,XJs):void 0}var een=JJs;const bCe=Xc(een);function ten(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};Hi.decimalPlaces=Hi.dp=function(){var s=this,t=s.d.length-1,n=(t-s.e)*rm;if(t=s.d[t],t)for(;t%10==0;t/=10)n--;return n<0?0:n};Hi.dividedBy=Hi.div=function(s){return h3(this,new this.constructor(s))};Hi.dividedToIntegerBy=Hi.idiv=function(s){var t=this,n=t.constructor;return vh(h3(t,new n(s),0,1),n.precision)};Hi.equals=Hi.eq=function(s){return!this.cmp(s)};Hi.exponent=function(){return wg(this)};Hi.greaterThan=Hi.gt=function(s){return this.cmp(s)>0};Hi.greaterThanOrEqualTo=Hi.gte=function(s){return this.cmp(s)>=0};Hi.isInteger=Hi.isint=function(){return this.e>this.d.length-2};Hi.isNegative=Hi.isneg=function(){return this.s<0};Hi.isPositive=Hi.ispos=function(){return this.s>0};Hi.isZero=function(){return this.s===0};Hi.lessThan=Hi.lt=function(s){return this.cmp(s)<0};Hi.lessThanOrEqualTo=Hi.lte=function(s){return this.cmp(s)<1};Hi.logarithm=Hi.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(j_))throw Error(jj+"NaN");if(n.s<1)throw Error(jj+(n.s?"NaN":"-Infinity"));return n.eq(j_)?new r(0):(Rm=!1,t=h3(XY(n,i),XY(s,i),i),Rm=!0,vh(t,a))};Hi.minus=Hi.sub=function(s){var t=this;return s=new t.constructor(s),t.s==s.s?cLt(t,s):oLt(t,(s.s=-s.s,s))};Hi.modulo=Hi.mod=function(s){var t,n=this,r=n.constructor,a=r.precision;if(s=new r(s),!s.s)throw Error(jj+"NaN");return n.s?(Rm=!1,t=h3(n,s,0,1).times(s),Rm=!0,n.minus(t)):vh(new r(n),a)};Hi.naturalExponential=Hi.exp=function(){return lLt(this)};Hi.naturalLogarithm=Hi.ln=function(){return XY(this)};Hi.negated=Hi.neg=function(){var s=new this.constructor(this);return s.s=-s.s||0,s};Hi.plus=Hi.add=function(s){var t=this;return s=new t.constructor(s),t.s==s.s?oLt(t,s):cLt(t,(s.s=-s.s,s))};Hi.precision=Hi.sd=function(s){var t,n,r,a=this;if(s!==void 0&&s!==!!s&&s!==1&&s!==0)throw Error(RD+s);if(t=wg(a)+1,r=a.d.length-1,n=r*rm+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};Hi.squareRoot=Hi.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(jj+"NaN")}for(s=wg(o),Rm=!1,a=Math.sqrt(+o),a==0||a==1/0?(t=t5(o.d),(t.length+s)%2==0&&(t+="0"),a=Math.sqrt(t),s=FU((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(h3(o,i,l+2)).times(.5),t5(i.d).slice(0,l)===(t=t5(r.d)).slice(0,l)){if(t=t.slice(l-3,l+1),a==l&&t=="4999"){if(vh(i,n+1,0),i.times(i).eq(o)){r=i;break}}else if(t!="9999")break;l+=4}return Rm=!0,vh(r,n)};Hi.times=Hi.mul=function(s){var t,n,r,a,i,l,o,c,d,u=this,h=u.constructor,m=u.d,f=(s=new h(s)).d;if(!u.s||!s.s)return new h(0);for(s.s*=u.s,n=u.e+s.e,c=m.length,d=f.length,c=0;){for(t=0,a=c+r;a>r;)o=i[a]+f[r]*m[a-r-1]+t,i[a--]=o%Fx|0,t=o/Fx|0;i[a]=(i[a]+t)%Fx|0}for(;!i[--l];)i.pop();return t?++n:i.shift(),s.d=i,s.e=n,Rm?vh(s,h.precision):s};Hi.toDecimalPlaces=Hi.todp=function(s,t){var n=this,r=n.constructor;return n=new r(n),s===void 0?n:(P5(s,0,OU),t===void 0?t=r.rounding:P5(t,0,8),vh(n,s+wg(n)+1,t))};Hi.toExponential=function(s,t){var n,r=this,a=r.constructor;return s===void 0?n=gR(r,!0):(P5(s,0,OU),t===void 0?t=a.rounding:P5(t,0,8),r=vh(new a(r),s+1,t),n=gR(r,!0,s+1)),n};Hi.toFixed=function(s,t){var n,r,a=this,i=a.constructor;return s===void 0?gR(a):(P5(s,0,OU),t===void 0?t=i.rounding:P5(t,0,8),r=vh(new i(a),s+wg(a)+1,t),n=gR(r.abs(),!1,s+wg(r)+1),a.isneg()&&!a.isZero()?"-"+n:n)};Hi.toInteger=Hi.toint=function(){var s=this,t=s.constructor;return vh(new t(s),wg(s)+1,t.rounding)};Hi.toNumber=function(){return+this};Hi.toPower=Hi.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(j_);if(o=new c(o),!o.s){if(s.s<1)throw Error(jj+"Infinity");return o}if(o.eq(j_))return o;if(r=c.precision,s.eq(j_))return vh(o,r);if(t=s.e,n=s.d.length-1,l=t>=n,i=o.s,l){if((n=u<0?-u:u)<=iLt){for(a=new c(j_),t=Math.ceil(r/rm+4),Rm=!1;n%2&&(a=a.times(o),Zct(a.d,t)),n=FU(n/2),n!==0;)o=o.times(o),Zct(o.d,t);return Rm=!0,s.s<0?new c(j_).div(a):vh(a,r)}}else if(i<0)throw Error(jj+"NaN");return i=i<0&&s.d[Math.max(t,n)]&1?-1:1,o.s=1,Rm=!1,a=s.times(XY(o,r+d)),Rm=!0,a=lLt(a),a.s=i,a};Hi.toPrecision=function(s,t){var n,r,a=this,i=a.constructor;return s===void 0?(n=wg(a),r=gR(a,n<=i.toExpNeg||n>=i.toExpPos)):(P5(s,1,OU),t===void 0?t=i.rounding:P5(t,0,8),a=vh(new i(a),s,t),n=wg(a),r=gR(a,s<=n||n<=i.toExpNeg,s)),r};Hi.toSignificantDigits=Hi.tosd=function(s,t){var n=this,r=n.constructor;return s===void 0?(s=r.precision,t=r.rounding):(P5(s,1,OU),t===void 0?t=r.rounding:P5(t,0,8)),vh(new r(n),s,t)};Hi.toString=Hi.valueOf=Hi.val=Hi.toJSON=Hi[Symbol.for("nodejs.util.inspect.custom")]=function(){var s=this,t=wg(s),n=s.constructor;return gR(s,t<=n.toExpNeg||t>=n.toExpPos)};function oLt(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)),Rm?vh(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/rm),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)/Fx|0,c[i]%=Fx;for(n&&(c.unshift(n),++a),o=c.length;c[--o]==0;)c.pop();return t.d=c,t.e=a,Rm?vh(t,h):t}function P5(s,t,n){if(s!==~~s||sn)throw Error(RD+s)}function t5(s){var t,n,r,a=s.length-1,i="",l=s[0];if(a>0){for(i+=l,t=1;tl?1:-1;else for(o=c=0;oa[o]?1:-1;break}return c}function n(r,a,i){for(var l=0;i--;)r[i]-=l,l=r[i]1;)r.shift()}return function(r,a,i,l){var o,c,d,u,h,m,f,g,y,x,_,b,k,A,T,P,I,M,L=r.constructor,z=r.s==a.s?1:-1,$=r.d,V=a.d;if(!r.s)return new L(r);if(!a.s)throw Error(jj+"Division by zero");for(c=r.e-a.e,I=V.length,T=$.length,f=new L(z),g=f.d=[],d=0;V[d]==($[d]||0);)++d;if(V[d]>($[d]||0)&&--c,i==null?b=i=L.precision:l?b=i+(wg(r)-wg(a))+1:b=i,b<0)return new L(0);if(b=b/rm+2|0,d=0,I==1)for(u=0,V=V[0],b++;(d1&&(V=s(V,u),$=s($,u),I=V.length,T=$.length),A=I,y=$.slice(0,I),x=y.length;x=Fx/2&&++P;do u=0,o=t(V,y,I,x),o<0?(_=y[0],I!=x&&(_=_*Fx+(y[1]||0)),u=_/P|0,u>1?(u>=Fx&&(u=Fx-1),h=s(V,u),m=h.length,x=y.length,o=t(h,y,m,x),o==1&&(u--,n(h,I16)throw Error(UHe+wg(s));if(!s.s)return new u(j_);for(t==null?(Rm=!1,o=h):o=t,l=new u(.03125);s.abs().gte(.1);)s=s.times(l),d+=5;for(r=Math.log(cI(2,d))/Math.LN10*2+5|0,o+=r,n=a=i=new u(j_),u.precision=o;;){if(a=vh(a.times(s),o),n=n.times(++c),l=i.plus(h3(a,n,o)),t5(l.d).slice(0,o)===t5(i.d).slice(0,o)){for(;d--;)i=vh(i.times(i),o);return u.precision=h,t==null?(Rm=!0,vh(i,h)):i}i=l}}function wg(s){for(var t=s.e*rm,n=s.d[0];n>=10;n/=10)t++;return t}function ILe(s,t,n){if(t>s.LN10.sd())throw Rm=!0,n&&(s.precision=n),Error(jj+"LN10 precision limit exceeded");return vh(new s(s.LN10),t)}function tA(s){for(var t="";s--;)t+="0";return t}function XY(s,t){var n,r,a,i,l,o,c,d,u,h=1,m=10,f=s,g=f.d,y=f.constructor,x=y.precision;if(f.s<1)throw Error(jj+(f.s?"NaN":"-Infinity"));if(f.eq(j_))return new y(0);if(t==null?(Rm=!1,d=x):d=t,f.eq(10))return t==null&&(Rm=!0),ILe(y,d);if(d+=m,y.precision=d,n=t5(g),r=n.charAt(0),i=wg(f),Math.abs(i)<15e14){for(;r<7&&r!=1||r==1&&n.charAt(1)>3;)f=f.times(s),n=t5(f.d),r=n.charAt(0),h++;i=wg(f),r>1?(f=new y("0."+n),i++):f=new y(r+"."+n.slice(1))}else return c=ILe(y,d+2,x).times(i+""),f=XY(new y(r+"."+n.slice(1)),d-m).plus(c),y.precision=x,t==null?(Rm=!0,vh(f,x)):f;for(o=l=f=h3(f.minus(j_),f.plus(j_),d),u=vh(f.times(f),d),a=3;;){if(l=vh(l.times(u),d),c=o.plus(h3(l,new y(a),d)),t5(c.d).slice(0,d)===t5(o.d).slice(0,d))return o=o.times(2),i!==0&&(o=o.plus(ILe(y,d+2,x).times(i+""))),o=h3(o,new y(h),d),y.precision=x,t==null?(Rm=!0,vh(o,x)):o;o=c,a+=2}}function Yct(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=FU(n/rm),s.d=[],r=(n+1)%rm,n<0&&(r+=rm),rBke||s.e<-Bke))throw Error(UHe+n)}else s.s=0,s.e=0,s.d=[0];return s}function vh(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+=rm,a=t,d=h[u=0];else{if(u=Math.ceil((r+1)/rm),i=h.length,u>=i)return s;for(d=i=h[u],l=1;i>=10;i/=10)l++;r%=rm,a=r-rm+l}if(n!==void 0&&(i=cI(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/cI(10,l-a):0:h[u-1])%10&1||n==(s.s<0?8:7))),t<1||!h[0])return c?(i=wg(s),h.length=1,t=t-i-1,h[0]=cI(10,(rm-t%rm)%rm),s.e=FU(-t/rm)||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=cI(10,rm-r),h[u]=a>0?(d/cI(10,l-a)%cI(10,a)|0)*i:0),c)for(;;)if(u==0){(h[0]+=i)==Fx&&(h[0]=1,++s.e);break}else{if(h[u]+=i,h[u]!=Fx)break;h[u--]=0,i=1}for(r=h.length;h[--r]===0;)h.pop();if(Rm&&(s.e>Bke||s.e<-Bke))throw Error(UHe+wg(s));return s}function cLt(s,t){var n,r,a,i,l,o,c,d,u,h,m=s.constructor,f=m.precision;if(!s.s||!t.s)return t.s?t.s=-t.s:t=new m(s),Rm?vh(t,f):t;if(c=s.d,h=t.d,r=t.e,d=s.e,c=c.slice(),l=d-r,l){for(u=l<0,u?(n=c,l=-l,o=h.length):(n=h,r=d,o=c.length),a=Math.max(Math.ceil(f/rm),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)+tA(r):l>1&&(i=i.charAt(0)+"."+i.slice(1)),i=i+(a<0?"e":"e+")+a):a<0?(i="0."+tA(-a-1)+i,n&&(r=n-l)>0&&(i+=tA(r))):a>=l?(i+=tA(a+1-l),n&&(r=n-a-1)>0&&(i=i+"."+tA(r))):((r=a+1)0&&(a+1===l&&(i+="."),i+=tA(r))),s.s<0?"-"+i:i}function Zct(s,t){if(s.length>t)return s.length=t,!0}function dLt(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(RD+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 Yct(l,i.toString())}else if(typeof i!="string")throw Error(RD+i);if(i.charCodeAt(0)===45?(i=i.slice(1),l.s=-1):l.s=1,wen.test(i))Yct(l,i);else throw Error(RD+i)}if(a.prototype=Hi,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=dLt,a.config=a.set=jen,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(RD+n+": "+r);if((r=s[n="LN10"])!==void 0)if(r==Math.LN10)this[n]=new this(r);else throw Error(RD+n+": "+r);return this}var qHe=dLt(_en);j_=new qHe(1);const eh=qHe;function Nen(s){return Aen(s)||Cen(s)||Sen(s)||ken()}function ken(){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 Sen(s,t){if(s){if(typeof s=="string")return uFe(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 uFe(s,t)}}function Cen(s){if(typeof Symbol<"u"&&Symbol.iterator in Object(s))return Array.from(s)}function Aen(s){if(Array.isArray(s))return uFe(s)}function uFe(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,Xct(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 qen(s){if(Array.isArray(s))return s}function fLt(s){var t=QY(s,2),n=t[0],r=t[1],a=n,i=r;return n>r&&(a=r,i=n),[a,i]}function gLt(s,t,n){if(s.lte(0))return new eh(0);var r=jCe.getDigitCount(s.toNumber()),a=new eh(10).pow(r),i=s.div(a),l=r!==1?.05:.1,o=new eh(Math.ceil(i.div(l).toNumber())).add(n).mul(l),c=o.mul(a);return t?c:new eh(Math.ceil(c))}function Ven(s,t,n){var r=1,a=new eh(s);if(!a.isint()&&n){var i=Math.abs(s);i<1?(r=new eh(10).pow(jCe.getDigitCount(s)-1),a=new eh(Math.floor(a.div(r).toNumber())).mul(r)):i>1&&(a=new eh(Math.floor(s)))}else s===0?a=new eh(Math.floor((t-1)/2)):n||(a=new eh(Math.floor(s)));var l=Math.floor((t-1)/2),o=Len(Men(function(c){return a.add(new eh(c-l).mul(r)).toNumber()}),hFe);return o(0,t)}function xLt(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 eh(0),tickMin:new eh(0),tickMax:new eh(0)};var i=gLt(new eh(t).sub(s).div(n-1),r,a),l;s<=0&&t>=0?l=new eh(0):(l=new eh(s).add(t).div(2),l=l.sub(new eh(l).mod(i)));var o=Math.ceil(l.sub(s).div(i).toNumber()),c=Math.ceil(new eh(t).sub(l).div(i).toNumber()),d=o+c+1;return d>n?xLt(s,t,n,r,a+1):(d0?c+(n-d):c,o=t>0?o:o+(n-d)),{step:i,tickMin:l.sub(new eh(o).mul(i)),tickMax:l.add(new eh(c).mul(i))})}function Hen(s){var t=QY(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=fLt([n,r]),c=QY(o,2),d=c[0],u=c[1];if(d===-1/0||u===1/0){var h=u===1/0?[d].concat(pFe(hFe(0,a-1).map(function(){return 1/0}))):[].concat(pFe(hFe(0,a-1).map(function(){return-1/0})),[u]);return n>r?mFe(h):h}if(d===u)return Ven(d,a,i);var m=xLt(d,u,l,i),f=m.step,g=m.tickMin,y=m.tickMax,x=jCe.rangeStep(g,y.add(new eh(.1).mul(f)),f);return n>r?mFe(x):x}function Gen(s,t){var n=QY(s,2),r=n[0],a=n[1],i=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!0,l=fLt([r,a]),o=QY(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=gLt(new eh(d).sub(c).div(u-1),i,0),m=[].concat(pFe(jCe.rangeStep(new eh(c),new eh(d).sub(new eh(.99).mul(h)),h)),[d]);return r>a?mFe(m):m}var Wen=mLt(Hen),Ken=mLt(Gen),Yen="Invariant failed";function xR(s,t){throw new Error(Yen)}var Zen=["offset","layout","width","dataKey","data","dataPointFormatter","xAxis","yAxis"];function o$(s){"@babel/helpers - typeof";return o$=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},o$(s)}function $ke(){return $ke=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 ntn(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 rtn(s,t){if(!(s instanceof t))throw new TypeError("Cannot call a class as a function")}function atn(s,t){for(var n=0;ns.length)&&(t=s.length);for(var n=0,r=new Array(t);n1&&arguments[1]!==void 0?arguments[1]:[],a=arguments.length>2?arguments[2]:void 0,i=arguments.length>3?arguments[3]:void 0,l=-1,o=(n=r==null?void 0:r.length)!==null&&n!==void 0?n:0;if(o<=1)return 0;if(i&&i.axisType==="angleAxis"&&Math.abs(Math.abs(i.range[1]-i.range[0])-360)<=1e-6)for(var c=i.range,d=0;d0?a[d-1].coordinate:a[o-1].coordinate,h=a[d].coordinate,m=d>=o-1?a[0].coordinate:a[d+1].coordinate,f=void 0;if(zv(h-u)!==zv(m-h)){var g=[];if(zv(m-h)===zv(c[1]-c[0])){f=m;var y=h+c[1]-c[0];g[0]=Math.min(y,(y+u)/2),g[1]=Math.max(y,(y+u)/2)}else{f=u;var x=m+c[1]-c[0];g[0]=Math.min(h,(x+h)/2),g[1]=Math.max(h,(x+h)/2)}var _=[Math.min(h,(f+h)/2),Math.max(h,(f+h)/2)];if(t>_[0]&&t<=_[1]||t>=g[0]&&t<=g[1]){l=a[d].index;break}}else{var b=Math.min(u,m),k=Math.max(u,m);if(t>(b+h)/2&&t<=(k+h)/2){l=a[d].index;break}}}else for(var A=0;A0&&A(r[A].coordinate+r[A-1].coordinate)/2&&t<=(r[A].coordinate+r[A+1].coordinate)/2||A===o-1&&t>(r[A].coordinate+r[A-1].coordinate)/2){l=r[A].index;break}return l},VHe=function(t){var n,r=t,a=r.type.displayName,i=(n=t.type)!==null&&n!==void 0&&n.defaultProps?rf(rf({},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},wtn=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(_&&_.length){var b=_[0].type.defaultProps,k=b!==void 0?rf(rf({},b),_[0].props):_[0].props,A=k.barSize,T=k[x];l[T]||(l[T]=[]);var P=Ml(A)?n:A;l[T].push({item:_[0],stackList:_.slice(1),barSize:Ml(P)?void 0:Bv(P,r,0)})}}return l},jtn=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=Bv(n,a,0,!0),u,h=[];if(l[0].barSize===+l[0].barSize){var m=!1,f=a/c,g=l.reduce(function(A,T){return A+T.barSize||0},0);g+=(c-1)*d,g>=a&&(g-=(c-1)*d,d=0),g>=a&&f>0&&(m=!0,f*=.9,g=c*f);var y=(a-g)/2>>0,x={offset:y-d,size:0};u=l.reduce(function(A,T){var P={item:T.item,position:{offset:x.offset+x.size+d,size:m?f:T.barSize}},I=[].concat(edt(A),[P]);return x=I[I.length-1].position,T.stackList&&T.stackList.length&&T.stackList.forEach(function(M){I.push({item:M,position:x})}),I},h)}else{var _=Bv(r,a,0,!0);a-2*_-(c-1)*d<=0&&(d=0);var b=(a-2*_-(c-1)*d)/c;b>1&&(b>>=0);var k=o===+o?Math.min(b,o):b;u=l.reduce(function(A,T,P){var I=[].concat(edt(A),[{item:T.item,position:{offset:_+(b+d)*P+(b-k)/2,size:k}}]);return T.stackList&&T.stackList.length&&T.stackList.forEach(function(M){I.push({item:M,position:I[I.length-1].position})}),I},h)}return u},Ntn=function(t,n,r,a){var i=r.children,l=r.width,o=r.margin,c=l-(o.left||0)-(o.right||0),d=_Lt({children:i,legendWidth:c});if(d){var u=a||{},h=u.width,m=u.height,f=d.align,g=d.verticalAlign,y=d.layout;if((y==="vertical"||y==="horizontal"&&g==="middle")&&f!=="center"&&Ka(t[f]))return rf(rf({},t),{},J9({},f,t[f]+(h||0)));if((y==="horizontal"||y==="vertical"&&f==="center")&&g!=="middle"&&Ka(t[g]))return rf(rf({},t),{},J9({},g,t[g]+(m||0)))}return t},ktn=function(t,n,r){return Ml(n)?!0:t==="horizontal"?n==="yAxis":t==="vertical"||r==="x"?n==="xAxis":r==="y"?n==="yAxis":!0},wLt=function(t,n,r,a,i){var l=n.props.children,o=R_(l,mJ).filter(function(d){return ktn(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=Jg(u,r);if(Ml(h))return d;var m=Array.isArray(h)?[_Ce(h),bCe(h)]:[h,h],f=c.reduce(function(g,y){var x=Jg(u,y,0),_=m[0]-Math.abs(Array.isArray(x)?x[0]:x),b=m[1]+Math.abs(Array.isArray(x)?x[1]:x);return[Math.min(_,g[0]),Math.max(b,g[1])]},[1/0,-1/0]);return[Math.min(f[0],d[0]),Math.max(f[1],d[1])]},[1/0,-1/0])}return null},Stn=function(t,n,r,a,i){var l=n.map(function(o){return wLt(t,o,r,i,a)}).filter(function(o){return!Ml(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},jLt=function(t,n,r,a,i){var l=n.map(function(c){var d=c.props.dataKey;return r==="number"&&d&&wLt(t,c,d,a)||xK(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?zv(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!iJ(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}})},DLe=new WeakMap,qse=function(t,n){if(typeof n!="function")return t;DLe.has(t)||DLe.set(t,new WeakMap);var r=DLe.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},SLt=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:GY(),realScaleType:"band"}:l==="radial"&&o==="angleAxis"?{scale:Rke(),realScaleType:"linear"}:i==="category"&&n&&(n.indexOf("LineChart")>=0||n.indexOf("AreaChart")>=0||n.indexOf("ComposedChart")>=0&&!r)?{scale:gK(),realScaleType:"point"}:i==="category"?{scale:GY(),realScaleType:"band"}:{scale:Rke(),realScaleType:"linear"};if(mR(a)){var c="scale".concat(iCe(a));return{scale:(Kct[c]||gK)(),realScaleType:Kct[c]?c:"point"}}return hl(a)?{scale:a}:{scale:gK(),realScaleType:"point"}},sdt=1e-4,CLt=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])-sdt,l=Math.max(a[0],a[1])+sdt,o=t(n[0]),c=t(n[r-1]);(ol||cl)&&t.domain([n[0],n[r-1]])}},Ctn=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])}},Etn=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)}},Mtn={sign:Ttn,expand:Z$s,none:JB,silhouette:X$s,wiggle:Q$s,positive:Etn},Ltn=function(t,n,r){var a=n.map(function(o){return o.props.dataKey}),i=Mtn[r],l=Y$s().keys(a).value(function(o,c){return+Jg(o,c,0)}).order(UOe).offset(i);return l(t)},Ptn=function(t,n,r,a,i,l){if(!t)return null;var o=l?n.reverse():n,c={},d=o.reduce(function(h,m){var f,g=(f=m.type)!==null&&f!==void 0&&f.defaultProps?rf(rf({},m.type.defaultProps),m.props):m.props,y=g.stackId,x=g.hide;if(x)return h;var _=g[r],b=h[_]||{hasStack:!1,stackGroups:{}};if(sx(y)){var k=b.stackGroups[y]||{numericAxisId:r,cateAxisId:a,items:[]};k.items.push(m),b.hasStack=!0,b.stackGroups[y]=k}else b.stackGroups[MU("_stackId_")]={numericAxisId:r,cateAxisId:a,items:[m]};return rf(rf({},h),{},J9({},_,b))},c),u={};return Object.keys(d).reduce(function(h,m){var f=d[m];if(f.hasStack){var g={};f.stackGroups=Object.keys(f.stackGroups).reduce(function(y,x){var _=f.stackGroups[x];return rf(rf({},y),{},J9({},x,{numericAxisId:r,cateAxisId:a,items:_.items,stackedData:Ltn(t,_.items,i)}))},g)}return rf(rf({},h),{},J9({},m,f))},u)},ALt=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=Wen(d,i,o);return t.domain([_Ce(u),bCe(u)]),{niceTicks:u}}if(i&&a==="number"){var h=t.domain(),m=Ken(h,i,o);return{niceTicks:m}}return null};function ndt(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&&!Ml(a[t.dataKey])){var o=fke(n,"value",a[t.dataKey]);if(o)return o.coordinate+r/2}return n[i]?n[i].coordinate+r/2:null}var c=Jg(a,Ml(l)?t.dataKey:l);return Ml(c)?null:t.scale(c)}var rdt=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=Jg(l,n.dataKey,n.domain[o]);return Ml(c)?null:n.scale(c)-i/2+a},Itn=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]},Dtn=function(t,n){var r,a=(r=t.type)!==null&&r!==void 0&&r.defaultProps?rf(rf({},t.type.defaultProps),t.props):t.props,i=a.stackId;if(sx(i)){var l=n[i];if(l){var o=l.items.indexOf(t);return o>=0?l.stackedData[o]:null}}return null},Rtn=function(t){return t.reduce(function(n,r){return[_Ce(r.concat([n[0]]).filter(Ka)),bCe(r.concat([n[1]]).filter(Ka))]},[1/0,-1/0])},TLt=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=Rtn(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})},adt=/^dataMin[\s]*-[\s]*([0-9]+([.]{1}[0-9]+){0,1})$/,idt=/^dataMax[\s]*\+[\s]*([0-9]+([.]{1}[0-9]+){0,1})$/,yFe=function(t,n,r){if(hl(t))return t(n,r);if(!Array.isArray(t))return n;var a=[];if(Ka(t[0]))a[0]=r?t[0]:Math.min(t[0],n[0]);else if(adt.test(t[0])){var i=+adt.exec(t[0])[1];a[0]=n[0]-i}else hl(t[0])?a[0]=t[0](n[0]):a[0]=n[0];if(Ka(t[1]))a[1]=r?t[1]:Math.max(t[1],n[1]);else if(idt.test(t[1])){var l=+idt.exec(t[1])[1];a[1]=n[1]+l}else hl(t[1])?a[1]=t[1](n[1]):a[1]=n[1];return a},qke=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=yHe(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},Htn=function(t,n,r,a,i){var l=t.width,o=t.height,c=t.startAngle,d=t.endAngle,u=Bv(t.cx,l,l/2),h=Bv(t.cy,o,o/2),m=LLt(l,o,r),f=Bv(t.innerRadius,m,0),g=Bv(t.outerRadius,m,m*.8),y=Object.keys(n);return y.reduce(function(x,_){var b=n[_],k=b.domain,A=b.reversed,T;if(Ml(b.range))a==="angleAxis"?T=[c,d]:a==="radiusAxis"&&(T=[f,g]),A&&(T=[T[1],T[0]]);else{T=b.range;var P=T,I=ztn(P,2);c=I[0],d=I[1]}var M=SLt(b,i),L=M.realScaleType,z=M.scale;z.domain(k).range(T),CLt(z);var $=ALt(z,s4(s4({},b),{},{realScaleType:L})),V=s4(s4(s4({},b),$),{},{range:T,radius:g,realScaleType:L,scale:z,cx:u,cy:h,innerRadius:f,outerRadius:g,startAngle:c,endAngle:d});return s4(s4({},x),{},MLt({},_,V))},{})},Gtn=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))},Wtn=function(t,n){var r=t.x,a=t.y,i=n.cx,l=n.cy,o=Gtn({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:Vtn(d),angleInRadian:d}},Ktn=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}},Ytn=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},ddt=function(t,n){var r=t.x,a=t.y,i=Wtn({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=Ktn(n),h=u.startAngle,m=u.endAngle,f=o,g;if(h<=m){for(;f>m;)f-=360;for(;f=h&&f<=m}else{for(;f>h;)f-=360;for(;f=m&&f<=h}return g?s4(s4({},n),{},{radius:l,angle:Ytn(f,n)}):null},PLt=function(t){return!N.isValidElement(t)&&!hl(t)&&typeof t!="boolean"?t.className:""};function sZ(s){"@babel/helpers - typeof";return sZ=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},sZ(s)}var Ztn=["offset"];function Xtn(s){return tsn(s)||esn(s)||Jtn(s)||Qtn()}function Qtn(){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 Jtn(s,t){if(s){if(typeof s=="string")return vFe(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 vFe(s,t)}}function esn(s){if(typeof Symbol<"u"&&s[Symbol.iterator]!=null||s["@@iterator"]!=null)return Array.from(s)}function tsn(s){if(Array.isArray(s))return vFe(s)}function vFe(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 nsn(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 udt(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 Og(s){for(var t=1;t=0?1:-1,k,A;a==="insideStart"?(k=f+b*l,A=y):a==="insideEnd"?(k=g-b*l,A=!y):a==="end"&&(k=g+b*l,A=y),A=_<=0?A:!A;var T=Fh(d,u,x,k),P=Fh(d,u,x,k+(A?1:-1)*359),I="M".concat(T.x,",").concat(T.y,` A`).concat(x,",").concat(x,",0,1,").concat(A?0:1,`, `).concat(P.x,",").concat(P.y),M=Ml(t.id)?MU("recharts-radial-line-"):t.id;return Rt.createElement("text",nZ({},r,{dominantBaseline:"central",className:Ol("recharts-radial-bar-label",o)}),Rt.createElement("defs",null,Rt.createElement("path",{id:M,d:I})),Rt.createElement("textPath",{xlinkHref:"#".concat(M)},n))},dsn=function(t){var n=t.viewBox,r=t.offset,a=t.position,i=n,l=i.cx,o=i.cy,c=i.innerRadius,d=i.outerRadius,u=i.startAngle,h=i.endAngle,m=(u+h)/2;if(a==="outside"){var f=Fh(l,o,d+r,m),g=f.x,y=f.y;return{x:g,y,textAnchor:g>=l?"start":"end",verticalAnchor:"middle"}}if(a==="center")return{x:l,y:o,textAnchor:"middle",verticalAnchor:"middle"};if(a==="centerTop")return{x:l,y:o,textAnchor:"middle",verticalAnchor:"start"};if(a==="centerBottom")return{x:l,y:o,textAnchor:"middle",verticalAnchor:"end"};var x=(c+d)/2,_=Fh(l,o,x,m),b=_.x,k=_.y;return{x:b,y:k,textAnchor:"middle",verticalAnchor:"middle"}},usn=function(t){var n=t.viewBox,r=t.parentViewBox,a=t.offset,i=t.position,l=n,o=l.x,c=l.y,d=l.width,u=l.height,h=u>=0?1:-1,m=h*a,f=h>0?"end":"start",g=h>0?"start":"end",y=d>=0?1:-1,x=y*a,_=y>0?"end":"start",b=y>0?"start":"end";if(i==="top"){var k={x:o+d/2,y:c-h*a,textAnchor:"middle",verticalAnchor:f};return Og(Og({},k),r?{height:Math.max(c-r.y,0),width:d}:{})}if(i==="bottom"){var A={x:o+d/2,y:c+u+m,textAnchor:"middle",verticalAnchor:g};return Og(Og({},A),r?{height:Math.max(r.y+r.height-(c+u),0),width:d}:{})}if(i==="left"){var T={x:o-x,y:c+u/2,textAnchor:_,verticalAnchor:"middle"};return Og(Og({},T),r?{width:Math.max(T.x-r.x,0),height:u}:{})}if(i==="right"){var P={x:o+d+x,y:c+u/2,textAnchor:b,verticalAnchor:"middle"};return Og(Og({},P),r?{width:Math.max(r.x+r.width-P.x,0),height:u}:{})}var I=r?{width:d,height:u}:{};return i==="insideLeft"?Og({x:o+x,y:c+u/2,textAnchor:b,verticalAnchor:"middle"},I):i==="insideRight"?Og({x:o+d-x,y:c+u/2,textAnchor:_,verticalAnchor:"middle"},I):i==="insideTop"?Og({x:o+d/2,y:c+m,textAnchor:"middle",verticalAnchor:g},I):i==="insideBottom"?Og({x:o+d/2,y:c+u-m,textAnchor:"middle",verticalAnchor:f},I):i==="insideTopLeft"?Og({x:o+x,y:c+m,textAnchor:b,verticalAnchor:g},I):i==="insideTopRight"?Og({x:o+d-x,y:c+m,textAnchor:_,verticalAnchor:g},I):i==="insideBottomLeft"?Og({x:o+x,y:c+u-m,textAnchor:b,verticalAnchor:f},I):i==="insideBottomRight"?Og({x:o+d-x,y:c+u-m,textAnchor:_,verticalAnchor:f},I):CU(i)&&(Ka(i.x)||FI(i.x))&&(Ka(i.y)||FI(i.y))?Og({x:o+Bv(i.x,d),y:c+Bv(i.y,u),textAnchor:"end",verticalAnchor:"end"},I):Og({x:o+d/2,y:c+u/2,textAnchor:"middle",verticalAnchor:"middle"},I)},hsn=function(t){return"cx"in t&&Ka(t.cx)};function Hx(s){var t=s.offset,n=t===void 0?5:t,r=ssn(s,Ztn),a=Og({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||Ml(o)&&Ml(c)&&!N.isValidElement(d)&&!hl(d))return null;if(N.isValidElement(d))return N.cloneElement(d,a);var f;if(hl(d)){if(f=N.createElement(d,a),N.isValidElement(f))return f}else f=osn(a);var g=hsn(i),y=qo(a,!0);if(g&&(l==="insideStart"||l==="insideEnd"||l==="end"))return csn(a,f,y);var x=g?dsn(a):usn(a);return Rt.createElement(fR,nZ({className:Ol("recharts-label",h)},y,x,{breakAll:m}),f)}Hx.displayName="Label";var ILt=function(t){var n=t.cx,r=t.cy,a=t.angle,i=t.startAngle,l=t.endAngle,o=t.r,c=t.radius,d=t.innerRadius,u=t.outerRadius,h=t.x,m=t.y,f=t.top,g=t.left,y=t.width,x=t.height,_=t.clockWise,b=t.labelViewBox;if(b)return b;if(Ka(y)&&Ka(x)){if(Ka(h)&&Ka(m))return{x:h,y:m,width:y,height:x};if(Ka(f)&&Ka(g))return{x:f,y:g,width:y,height:x}}return Ka(h)&&Ka(m)?{x:h,y:m,width:0,height:0}:Ka(n)&&Ka(r)?{cx:n,cy:r,startAngle:i||a||0,endAngle:l||a||0,innerRadius:d||0,outerRadius:u||c||o||0,clockWise:_}:t.viewBox?t.viewBox:{}},msn=function(t,n){return t?t===!0?Rt.createElement(Hx,{key:"label-implicit",viewBox:n}):sx(t)?Rt.createElement(Hx,{key:"label-implicit",viewBox:n,value:t}):N.isValidElement(t)?t.type===Hx?N.cloneElement(t,{key:"label-implicit",viewBox:n}):Rt.createElement(Hx,{key:"label-implicit",content:t,viewBox:n}):hl(t)?Rt.createElement(Hx,{key:"label-implicit",content:t,viewBox:n}):CU(t)?Rt.createElement(Hx,nZ({viewBox:n},t,{key:"label-implicit"})):null:null},psn=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=ILt(t),l=R_(a,Hx).map(function(c,d){return N.cloneElement(c,{viewBox:n||i,key:"label-".concat(d)})});if(!r)return l;var o=msn(t.label,n||i);return[o].concat(Xtn(l))};Hx.parseViewBox=ILt;Hx.renderCallByParent=psn;function fsn(s){var t=s==null?0:s.length;return t?s[t-1]:void 0}var gsn=fsn;const xsn=Xc(gsn);function rZ(s){"@babel/helpers - typeof";return rZ=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},rZ(s)}var ysn=["valueAccessor"],vsn=["data","dataKey","clockWise","id","textBreakAll"];function bsn(s){return Nsn(s)||jsn(s)||wsn(s)||_sn()}function _sn(){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 wsn(s,t){if(s){if(typeof s=="string")return bFe(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 bFe(s,t)}}function jsn(s){if(typeof Symbol<"u"&&s[Symbol.iterator]!=null||s["@@iterator"]!=null)return Array.from(s)}function Nsn(s){if(Array.isArray(s))return bFe(s)}function bFe(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 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 Tsn=function(t){return Array.isArray(t.value)?xsn(t.value):t.value};function m3(s){var t=s.valueAccessor,n=t===void 0?Tsn:t,r=pdt(s,ysn),a=r.data,i=r.dataKey,l=r.clockWise,o=r.id,c=r.textBreakAll,d=pdt(r,vsn);return!a||!a.length?null:Rt.createElement(Bd,{className:"recharts-label-list"},a.map(function(u,h){var m=Ml(i)?n(u,h):Jg(u&&u.payload,i),f=Ml(o)?{}:{id:"".concat(o,"-").concat(h)};return Rt.createElement(Hx,Hke({},qo(u,!0),d,f,{parentViewBox:u.parentViewBox,value:m,textBreakAll:c,viewBox:Hx.parseViewBox(Ml(l)?u:mdt(mdt({},u),{},{clockWise:l})),key:"label-".concat(h),index:h}))}))}m3.displayName="LabelList";function Esn(s,t){return s?s===!0?Rt.createElement(m3,{key:"labelList-implicit",data:t}):Rt.isValidElement(s)||hl(s)?Rt.createElement(m3,{key:"labelList-implicit",data:t,content:s}):CU(s)?Rt.createElement(m3,Hke({data:t},s,{key:"labelList-implicit"})):null:null}function Msn(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=R_(r,m3).map(function(l,o){return N.cloneElement(l,{data:t,key:"labelList-".concat(o)})});if(!n)return a;var i=Esn(s.label,t);return[i].concat(bsn(a))}m3.renderCallByParent=Msn;function aZ(s){"@babel/helpers - typeof";return aZ=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},aZ(s)}function _Fe(){return _Fe=Object.assign?Object.assign.bind():function(s){for(var t=1;t180),",").concat(+(l>d),`, `).concat(h.x,",").concat(h.y,` `);if(a>0){var f=Fh(n,r,a,l),g=Fh(n,r,a,d);m+="L ".concat(g.x,",").concat(g.y,` A `).concat(a,",").concat(a,`,0, `).concat(+(Math.abs(c)>180),",").concat(+(l<=d),`, `).concat(f.x,",").concat(f.y," Z")}else m+="L ".concat(n,",").concat(r," Z");return m},Rsn=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=zv(u-d),m=Vse({cx:n,cy:r,radius:i,angle:d,sign:h,cornerRadius:l,cornerIsExternal:c}),f=m.circleTangency,g=m.lineTangency,y=m.theta,x=Vse({cx:n,cy:r,radius:i,angle:u,sign:-h,cornerRadius:l,cornerIsExternal:c}),_=x.circleTangency,b=x.lineTangency,k=x.theta,A=c?Math.abs(d-u):Math.abs(d-u)-y-k;if(A<0)return o?"M ".concat(g.x,",").concat(g.y,` a`).concat(l,",").concat(l,",0,0,1,").concat(l*2,`,0 a`).concat(l,",").concat(l,",0,0,1,").concat(-l*2,`,0 `):DLt({cx:n,cy:r,innerRadius:a,outerRadius:i,startAngle:d,endAngle:u});var T="M ".concat(g.x,",").concat(g.y,` A`).concat(l,",").concat(l,",0,0,").concat(+(h<0),",").concat(f.x,",").concat(f.y,` A`).concat(i,",").concat(i,",0,").concat(+(A>180),",").concat(+(h<0),",").concat(_.x,",").concat(_.y,` A`).concat(l,",").concat(l,",0,0,").concat(+(h<0),",").concat(b.x,",").concat(b.y,` `);if(a>0){var P=Vse({cx:n,cy:r,radius:a,angle:d,sign:h,isExternal:!0,cornerRadius:l,cornerIsExternal:c}),I=P.circleTangency,M=P.lineTangency,L=P.theta,z=Vse({cx:n,cy:r,radius:a,angle:u,sign:-h,isExternal:!0,cornerRadius:l,cornerIsExternal:c}),$=z.circleTangency,V=z.lineTangency,W=z.theta,G=c?Math.abs(d-u):Math.abs(d-u)-L-W;if(G<0&&l===0)return"".concat(T,"L").concat(n,",").concat(r,"Z");T+="L".concat(V.x,",").concat(V.y,` A`).concat(l,",").concat(l,",0,0,").concat(+(h<0),",").concat($.x,",").concat($.y,` A`).concat(a,",").concat(a,",0,").concat(+(G>180),",").concat(+(h>0),",").concat(I.x,",").concat(I.y,` A`).concat(l,",").concat(l,",0,0,").concat(+(h<0),",").concat(M.x,",").concat(M.y,"Z")}else T+="L".concat(n,",").concat(r,"Z");return T},Osn={cx:0,cy:0,innerRadius:0,outerRadius:0,startAngle:0,endAngle:0,cornerRadius:0,forceCornerRadius:!1,cornerIsExternal:!1},RLt=function(t){var n=gdt(gdt({},Osn),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?x=Rsn({cx:r,cy:a,innerRadius:i,outerRadius:l,cornerRadius:Math.min(y,g/2),forceCornerRadius:c,cornerIsExternal:d,startAngle:u,endAngle:h}):x=DLt({cx:r,cy:a,innerRadius:i,outerRadius:l,startAngle:u,endAngle:h}),Rt.createElement("path",_Fe({},qo(n,!0),{className:f,d:x,role:"img"}))};function iZ(s){"@babel/helpers - typeof";return iZ=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},iZ(s)}function wFe(){return wFe=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 Qsn(s,t){return zU(s.getTime(),t.getTime())}function Ndt(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],f=h[1],g=o.value,y=g[0],x=g[1];!d&&!r[u]&&(d=n.equals(m,y,i,u,s,t,n)&&n.equals(f,x,m,y,s,t,n))&&(r[u]=!0),u++}if(!d)return!1;i++}return!0}function Jsn(s,t,n){var r=jdt(s),a=r.length;if(jdt(t).length!==a)return!1;for(var i;a-- >0;)if(i=r[a],i===$Lt&&(s.$$typeof||t.$$typeof)&&s.$$typeof!==t.$$typeof||!BLt(t,i)||!n.equals(s[i],t[i],i,i,s,t,n))return!1;return!0}function eH(s,t,n){var r=_dt(s),a=r.length;if(_dt(t).length!==a)return!1;for(var i,l,o;a-- >0;)if(i=r[a],i===$Lt&&(s.$$typeof||t.$$typeof)&&s.$$typeof!==t.$$typeof||!BLt(t,i)||!n.equals(s[i],t[i],i,i,s,t,n)||(l=wdt(s,i),o=wdt(t,i),(l||o)&&(!l||!o||l.configurable!==o.configurable||l.enumerable!==o.enumerable||l.writable!==o.writable)))return!1;return!0}function enn(s,t){return zU(s.valueOf(),t.valueOf())}function tnn(s,t){return s.source===t.source&&s.flags===t.flags}function kdt(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 snn(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 nnn="[object Arguments]",rnn="[object Boolean]",ann="[object Date]",inn="[object Map]",onn="[object Number]",lnn="[object Object]",cnn="[object RegExp]",dnn="[object Set]",unn="[object String]",hnn=Array.isArray,Sdt=typeof ArrayBuffer=="function"&&ArrayBuffer.isView?ArrayBuffer.isView:null,Cdt=Object.assign,mnn=Object.prototype.toString.call.bind(Object.prototype.toString);function pnn(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 f=u.constructor;if(f!==h.constructor)return!1;if(f===Object)return a(u,h,m);if(hnn(u))return t(u,h,m);if(Sdt!=null&&Sdt(u))return c(u,h,m);if(f===Date)return n(u,h,m);if(f===RegExp)return l(u,h,m);if(f===Map)return r(u,h,m);if(f===Set)return o(u,h,m);var g=mnn(u);return g===ann?n(u,h,m):g===cnn?l(u,h,m):g===inn?r(u,h,m):g===dnn?o(u,h,m):g===lnn?typeof u.then!="function"&&typeof h.then!="function"&&a(u,h,m):g===nnn?a(u,h,m):g===rnn||g===onn||g===unn?i(u,h,m):!1}}function fnn(s){var t=s.circular,n=s.createCustomConfig,r=s.strict,a={areArraysEqual:r?eH:Xsn,areDatesEqual:Qsn,areMapsEqual:r?bdt(Ndt,eH):Ndt,areObjectsEqual:r?eH:Jsn,arePrimitiveWrappersEqual:enn,areRegExpsEqual:tnn,areSetsEqual:r?bdt(kdt,eH):kdt,areTypedArraysEqual:r?eH:snn};if(n&&(a=Cdt({},a,n(a))),t){var i=Gse(a.areArraysEqual),l=Gse(a.areMapsEqual),o=Gse(a.areObjectsEqual),c=Gse(a.areSetsEqual);a=Cdt({},a,{areArraysEqual:i,areMapsEqual:l,areObjectsEqual:o,areSetsEqual:c})}return a}function gnn(s){return function(t,n,r,a,i,l,o){return s(t,n,o)}}function xnn(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,f=u.meta;return n(c,d,{cache:m,equals:a,meta:f,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 ynn=e6();e6({strict:!0});e6({circular:!0});e6({circular:!0,strict:!0});e6({createInternalComparator:function(){return zU}});e6({strict:!0,createInternalComparator:function(){return zU}});e6({circular:!0,createInternalComparator:function(){return zU}});e6({circular:!0,createInternalComparator:function(){return zU},strict:!0});function e6(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=fnn(s),c=pnn(o),d=r?r(c):gnn(c);return xnn({circular:n,comparator:c,createState:a,equals:d,strict:l})}function vnn(s){typeof requestAnimationFrame<"u"&&requestAnimationFrame(s)}function Adt(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):vnn(a)};requestAnimationFrame(r)}function jFe(s){"@babel/helpers - typeof";return jFe=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},jFe(s)}function bnn(s){return Nnn(s)||jnn(s)||wnn(s)||_nn()}function _nn(){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 wnn(s,t){if(s){if(typeof s=="string")return Tdt(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 Tdt(s,t)}}function Tdt(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:_<0?0:_},y=function(_){for(var b=_>1?1:_,k=b,A=0;A<8;++A){var T=h(k)-b,P=f(k);if(Math.abs(T-b)0&&arguments[0]!==void 0?arguments[0]:{},n=t.stiff,r=n===void 0?100:n,a=t.damping,i=a===void 0?8:a,l=t.dt,o=l===void 0?17:l,c=function(u,h,m){var f=-(u-h)*r,g=m*i,y=m+(f-g)*o/1e3,x=m*o/1e3+u;return Math.abs(x-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 trn(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 RLe(s){return arn(s)||rrn(s)||nrn(s)||srn()}function srn(){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 nrn(s,t){if(s){if(typeof s=="string")return AFe(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 AFe(s,t)}}function rrn(s){if(typeof Symbol<"u"&&s[Symbol.iterator]!=null||s["@@iterator"]!=null)return Array.from(s)}function arn(s){if(Array.isArray(s))return AFe(s)}function AFe(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 Yke(s){return Yke=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(n){return n.__proto__||Object.getPrototypeOf(n)},Yke(s)}var I5=function(s){drn(n,s);var t=urn(n);function n(r,a){var i;irn(this,n),i=t.call(this,r,a);var l=i.props,o=l.isActive,c=l.attributeName,d=l.from,u=l.to,h=l.steps,m=l.children,f=l.duration;if(i.handleStyleChange=i.handleStyleChange.bind(MFe(i)),i.changeStyle=i.changeStyle.bind(MFe(i)),!o||f<=0)return i.state={style:{}},typeof m=="function"&&(i.state={style:u}),EFe(i);if(h&&h.length)i.state={style:h[0].style};else if(d){if(typeof m=="function")return i.state={style:d},EFe(i);i.state={style:c?eG({},c,d):d}}else i.state={style:{}};return i}return lrn(n,[{key:"componentDidMount",value:function(){var a=this.props,i=a.isActive,l=a.canBegin;this.mounted=!0,!(!i||!l)&&this.runAnimation(this.props)}},{key:"componentDidUpdate",value:function(a){var i=this.props,l=i.isActive,o=i.canBegin,c=i.attributeName,d=i.shouldReAnimate,u=i.to,h=i.from,m=this.state.style;if(o){if(!l){var f={style:c?eG({},c,u):u};this.state&&m&&(c&&m[c]!==u||!c&&m!==u)&&this.setState(f);return}if(!(ynn(a.to,u)&&a.canBegin&&a.isActive)){var g=!a.canBegin||!a.isActive;this.manager&&this.manager.stop(),this.stopJSAnimation&&this.stopJSAnimation();var y=g||d?h:a.to;if(this.state&&m){var x={style:c?eG({},c,y):y};(c&&m[c]!==y||!c&&m!==y)&&this.setState(x)}this.runAnimation(r2(r2({},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,f=Qnn(l,o,$nn(d),c,this.changeStyle),g=function(){i.stopJSAnimation=f()};this.manager.start([m,u,g,c,h])}},{key:"runStepAnimation",value:function(a){var i=this,l=a.steps,o=a.begin,c=a.onAnimationStart,d=l[0],u=d.style,h=d.duration,m=h===void 0?0:h,f=function(y,x,_){if(_===0)return y;var b=x.duration,k=x.easing,A=k===void 0?"ease":k,T=x.style,P=x.properties,I=x.onAnimationEnd,M=_>0?l[_-1]:x,L=P||Object.keys(T);if(typeof A=="function"||A==="spring")return[].concat(RLe(y),[i.runJSAnimation.bind(i,{from:M.style,to:T,duration:b,easing:A}),b]);var z=Ldt(L,b,A),$=r2(r2(r2({},M.style),T),{},{transition:z});return[].concat(RLe(y),[$,b,I]).filter(Tnn)};return this.manager.start([c].concat(RLe(l.reduce(f,[u,Math.max(m,o)])),[a.onAnimationEnd]))}},{key:"runAnimation",value:function(a){this.manager||(this.manager=knn());var i=a.begin,l=a.duration,o=a.attributeName,c=a.to,d=a.easing,u=a.onAnimationStart,h=a.onAnimationEnd,m=a.steps,f=a.children,g=this.manager;if(this.unSubscribe=g.subscribe(this.handleStyleChange),typeof d=="function"||typeof f=="function"||d==="spring"){this.runJSAnimation(a);return}if(m.length>1){this.runStepAnimation(a);return}var y=o?eG({},o,c):c,x=Ldt(Object.keys(y),l,d);g.start([u,i,r2(r2({},y),{},{transition:x}),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=ern(a,Jnn),d=N.Children.count(i),u=this.state.style;if(typeof i=="function")return i(u);if(!o||d===0||l<=0)return i;var h=function(f){var g=f.props,y=g.style,x=y===void 0?{}:y,_=g.className,b=N.cloneElement(f,r2(r2({},c),{},{style:r2(r2({},x),u),className:_}));return b};return d===1?h(N.Children.only(i)):Rt.createElement("div",null,N.Children.map(i,function(m){return h(m)}))}}]),n}(N.PureComponent);I5.displayName="Animate";I5.defaultProps={begin:0,duration:1e3,from:"",to:"",attributeName:"",easing:"ease",isActive:!0,canBegin:!0,steps:[],onAnimationEnd:function(){},onAnimationStart:function(){}};I5.propTypes={from:vu.oneOfType([vu.object,vu.string]),to:vu.oneOfType([vu.object,vu.string]),attributeName:vu.string,duration:vu.number,begin:vu.number,easing:vu.oneOfType([vu.string,vu.func]),steps:vu.arrayOf(vu.shape({duration:vu.number.isRequired,style:vu.object.isRequired,easing:vu.oneOfType([vu.oneOf(["ease","ease-in","ease-out","ease-in-out","linear"]),vu.func]),properties:vu.arrayOf("string"),onAnimationEnd:vu.func})),children:vu.oneOfType([vu.node,vu.func]),isActive:vu.bool,canBegin:vu.bool,onAnimationEnd:vu.func,shouldReAnimate:vu.bool,onAnimationStart:vu.func,onAnimationReStart:vu.func};function cZ(s){"@babel/helpers - typeof";return cZ=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},cZ(s)}function Zke(){return Zke=Object.assign?Object.assign.bind():function(s){for(var t=1;ts.length)&&(t=s.length);for(var n=0,r=new Array(t);n=0?1:-1,c=r>=0?1:-1,d=a>=0&&r>=0||a<0&&r<0?1:0,u;if(l>0&&i instanceof Array){for(var h=[0,0,0,0],m=0,f=4;ml?l:i[m];u="M".concat(t,",").concat(n+o*h[0]),h[0]>0&&(u+="A ".concat(h[0],",").concat(h[0],",0,0,").concat(d,",").concat(t+c*h[0],",").concat(n)),u+="L ".concat(t+r-c*h[1],",").concat(n),h[1]>0&&(u+="A ".concat(h[1],",").concat(h[1],",0,0,").concat(d,`, `).concat(t+r,",").concat(n+o*h[1])),u+="L ".concat(t+r,",").concat(n+a-o*h[2]),h[2]>0&&(u+="A ".concat(h[2],",").concat(h[2],",0,0,").concat(d,`, `).concat(t+r-c*h[2],",").concat(n+a)),u+="L ".concat(t+c*h[3],",").concat(n+a),h[3]>0&&(u+="A ".concat(h[3],",").concat(h[3],",0,0,").concat(d,`, `).concat(t,",").concat(n+a-o*h[3])),u+="Z"}else if(l>0&&i===+i&&i>0){var g=Math.min(l,i);u="M ".concat(t,",").concat(n+o*g,` A `).concat(g,",").concat(g,",0,0,").concat(d,",").concat(t+c*g,",").concat(n,` L `).concat(t+r-c*g,",").concat(n,` A `).concat(g,",").concat(g,",0,0,").concat(d,",").concat(t+r,",").concat(n+o*g,` L `).concat(t+r,",").concat(n+a-o*g,` A `).concat(g,",").concat(g,",0,0,").concat(d,",").concat(t+r-c*g,",").concat(n+a,` L `).concat(t+c*g,",").concat(n+a,` A `).concat(g,",").concat(g,",0,0,").concat(d,",").concat(t,",").concat(n+a-o*g," Z")}else u="M ".concat(t,",").concat(n," h ").concat(r," v ").concat(a," h ").concat(-r," Z");return u},_rn=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},wrn={x:0,y:0,width:0,height:0,radius:0,isAnimationActive:!1,isUpdateAnimationActive:!1,animationBegin:0,animationDuration:1500,animationEasing:"ease"},HHe=function(t){var n=Bdt(Bdt({},wrn),t),r=N.useRef(),a=N.useState(-1),i=mrn(a,2),l=i[0],o=i[1];N.useEffect(function(){if(r.current&&r.current.getTotalLength)try{var A=r.current.getTotalLength();A&&o(A)}catch{}},[]);var c=n.x,d=n.y,u=n.width,h=n.height,m=n.radius,f=n.className,g=n.animationEasing,y=n.animationDuration,x=n.animationBegin,_=n.isAnimationActive,b=n.isUpdateAnimationActive;if(c!==+c||d!==+d||u!==+u||h!==+h||u===0||h===0)return null;var k=Ol("recharts-rectangle",f);return b?Rt.createElement(I5,{canBegin:l>0,from:{width:u,height:h,x:c,y:d},to:{width:u,height:h,x:c,y:d},duration:y,animationEasing:g,isActive:b},function(A){var T=A.width,P=A.height,I=A.x,M=A.y;return Rt.createElement(I5,{canBegin:l>0,from:"0px ".concat(l===-1?1:l,"px"),to:"".concat(l,"px 0px"),attributeName:"strokeDasharray",begin:x,duration:y,isActive:_,easing:g},Rt.createElement("path",Zke({},qo(n,!0),{className:k,d:$dt(I,M,T,P,m),ref:r})))}):Rt.createElement("path",Zke({},qo(n,!0),{className:k,d:$dt(c,d,u,h,m)}))},jrn=["points","className","baseLinePoints","connectNulls"];function $7(){return $7=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 krn(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 Udt(s){return Trn(s)||Arn(s)||Crn(s)||Srn()}function Srn(){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 Crn(s,t){if(s){if(typeof s=="string")return LFe(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 LFe(s,t)}}function Arn(s){if(typeof Symbol<"u"&&s[Symbol.iterator]!=null||s["@@iterator"]!=null)return Array.from(s)}function Trn(s){if(Array.isArray(s))return LFe(s)}function LFe(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){qdt(r)?n[n.length-1].push(r):n[n.length-1].length>0&&n.push([])}),qdt(t[0])&&n[n.length-1].push(t[0]),n[n.length-1].length<=0&&(n=n.slice(0,-1)),n},vK=function(t,n){var r=Ern(t);n&&(r=[r.reduce(function(i,l){return[].concat(Udt(i),Udt(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},Mrn=function(t,n,r){var a=vK(t,r);return"".concat(a.slice(-1)==="Z"?a.slice(0,-1):a,"L").concat(vK(n.reverse(),r).slice(1))},Lrn=function(t){var n=t.points,r=t.className,a=t.baseLinePoints,i=t.connectNulls,l=Nrn(t,jrn);if(!n||!n.length)return null;var o=Ol("recharts-polygon",r);if(a&&a.length){var c=l.stroke&&l.stroke!=="none",d=Mrn(n,a,i);return Rt.createElement("g",{className:o},Rt.createElement("path",$7({},qo(l,!0),{fill:d.slice(-1)==="Z"?l.fill:"none",stroke:"none",d})),c?Rt.createElement("path",$7({},qo(l,!0),{fill:"none",d:vK(n,i)})):null,c?Rt.createElement("path",$7({},qo(l,!0),{fill:"none",d:vK(a,i)})):null)}var u=vK(n,i);return Rt.createElement("path",$7({},qo(l,!0),{fill:u.slice(-1)==="Z"?l.fill:"none",className:o,d:u}))};function PFe(){return PFe=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 zrn(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 Brn=function(t,n,r,a,i,l){return"M".concat(t,",").concat(i,"v").concat(a,"M").concat(l,",").concat(n,"h").concat(r)},$rn=function(t){var n=t.x,r=n===void 0?0:n,a=t.y,i=a===void 0?0:a,l=t.top,o=l===void 0?0:l,c=t.left,d=c===void 0?0:c,u=t.width,h=u===void 0?0:u,m=t.height,f=m===void 0?0:m,g=t.className,y=Frn(t,Prn),x=Irn({x:r,y:i,top:o,left:d,width:h,height:f},y);return!Ka(r)||!Ka(i)||!Ka(h)||!Ka(f)||!Ka(o)||!Ka(d)?null:Rt.createElement("path",IFe({},qo(x,!0),{className:Ol("recharts-cross",g),d:Brn(r,i,h,f,o,d)}))},Urn=vCe,qrn=rLt,Vrn=Z5;function Hrn(s,t){return s&&s.length?Urn(s,Vrn(t),qrn):void 0}var Grn=Hrn;const Wrn=Xc(Grn);var Krn=vCe,Yrn=Z5,Zrn=aLt;function Xrn(s,t){return s&&s.length?Krn(s,Yrn(t),Zrn):void 0}var Qrn=Xrn;const Jrn=Xc(Qrn);var ean=["cx","cy","angle","ticks","axisLine"],tan=["ticks","tick","angle","tickFormatter","stroke"];function c$(s){"@babel/helpers - typeof";return c$=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},c$(s)}function bK(){return bK=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 san(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 nan(s,t){if(!(s instanceof t))throw new TypeError("Cannot call a class as a function")}function Wdt(s,t){for(var n=0;nZdt?l=a==="outer"?"start":"end":i<-Zdt?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=U6(U6({},qo(this.props,!1)),{},{fill:"none"},qo(o,!1));if(c==="circle")return Rt.createElement(NCe,wI({className:"recharts-polar-angle-axis-line"},d,{cx:a,cy:i,r:l}));var u=this.props.ticks,h=u.map(function(m){return Fh(a,i,l,m.coordinate)});return Rt.createElement(Lrn,wI({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=qo(this.props,!1),h=qo(l,!1),m=U6(U6({},u),{},{fill:"none"},qo(o,!1)),f=i.map(function(g,y){var x=r.getTickLineCoord(g),_=r.getTickTextAnchor(g),b=U6(U6(U6({textAnchor:_},u),{},{stroke:"none",fill:d},h),{},{index:y,payload:g,x:x.x2,y:x.y2});return Rt.createElement(Bd,wI({className:Ol("recharts-polar-angle-axis-tick",PLt(l)),key:"tick-".concat(g.coordinate)},pR(r.props,g,y)),o&&Rt.createElement("line",wI({className:"recharts-polar-angle-axis-tick-line"},m,x)),l&&t.renderTickItem(l,b,c?c(g.value,y):g.value))});return Rt.createElement(Bd,{className:"recharts-polar-angle-axis-ticks"},f)}},{key:"render",value:function(){var r=this.props,a=r.ticks,i=r.radius,l=r.axisLine;return i<=0||!a||!a.length?null:Rt.createElement(Bd,{className:Ol("recharts-polar-angle-axis",this.props.className)},l&&this.renderAxisLine(),this.renderTicks())}}],[{key:"renderTickItem",value:function(r,a,i){var l;return Rt.isValidElement(r)?l=Rt.cloneElement(r,a):hl(r)?l=r(a):l=Rt.createElement(fR,wI({},a,{className:"recharts-polar-angle-axis-tick-value"}),i),l}}])}(N.PureComponent);CCe(ACe,"displayName","PolarAngleAxis");CCe(ACe,"axisType","angleAxis");CCe(ACe,"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 yan=eMt,van=yan(Object.getPrototypeOf,Object),ban=van,_an=q3,wan=ban,jan=V3,Nan="[object Object]",kan=Function.prototype,San=Object.prototype,QLt=kan.toString,Can=San.hasOwnProperty,Aan=QLt.call(Object);function Tan(s){if(!jan(s)||_an(s)!=Nan)return!1;var t=wan(s);if(t===null)return!0;var n=Can.call(t,"constructor")&&t.constructor;return typeof n=="function"&&n instanceof n&&QLt.call(n)==Aan}var Ean=Tan;const Man=Xc(Ean);var Lan=q3,Pan=V3,Ian="[object Boolean]";function Dan(s){return s===!0||s===!1||Pan(s)&&Lan(s)==Ian}var Ran=Dan;const Oan=Xc(Ran);function uZ(s){"@babel/helpers - typeof";return uZ=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},uZ(s)}function Jke(){return Jke=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:g,isActive:_},function(k){var A=k.upperWidth,T=k.lowerWidth,P=k.height,I=k.x,M=k.y;return Rt.createElement(I5,{canBegin:l>0,from:"0px ".concat(l===-1?1:l,"px"),to:"".concat(l,"px 0px"),attributeName:"strokeDasharray",begin:x,duration:y,easing:g},Rt.createElement("path",Jke({},qo(n,!0),{className:b,d:eut(I,M,A,T,P),ref:r})))}):Rt.createElement("g",null,Rt.createElement("path",Jke({},qo(n,!0),{className:b,d:eut(c,d,u,h,m)})))},Kan=["option","shapeType","propTransformer","activeClassName","isActive"];function hZ(s){"@babel/helpers - typeof";return hZ=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},hZ(s)}function Yan(s,t){if(s==null)return{};var n=Zan(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 Zan(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 tut(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 e5e(s){for(var t=1;t0?D_(k,"paddingAngle",0):0;if(T){var I=x_(T.endAngle-T.startAngle,k.endAngle-k.startAngle),M=Lh(Lh({},k),{},{startAngle:b+P,endAngle:b+I(y)+P});x.push(M),b=M.endAngle}else{var L=k.endAngle,z=k.startAngle,$=x_(0,L-z),V=$(y),W=Lh(Lh({},k),{},{startAngle:b+P,endAngle:b+V+P});x.push(W),b=W.endAngle}}),Rt.createElement(Bd,null,r.renderSectorsStatically(x))})}},{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||!hJ(l,a))?this.renderSectorsWithAnimation():this.renderSectorsStatically(a)}},{key:"componentDidMount",value:function(){this.pieRef&&this.attachKeyboardHandlers(this.pieRef)}},{key:"render",value:function(){var r=this,a=this.props,i=a.hide,l=a.sectors,o=a.className,c=a.label,d=a.cx,u=a.cy,h=a.innerRadius,m=a.outerRadius,f=a.isAnimationActive,g=this.state.isAnimationFinished;if(i||!l||!l.length||!Ka(d)||!Ka(u)||!Ka(h)||!Ka(m))return null;var y=Ol("recharts-pie",o);return Rt.createElement(Bd,{tabIndex:this.props.rootTabIndex,className:y,ref:function(_){r.pieRef=_}},this.renderSectors(),c&&this.renderLabels(l),Hx.renderCallByParent(this.props,null,!1),(!f||g)&&m3.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,A=x-b*f-k,T=a.reduce(function(M,L){var z=Jg(L,_,0);return M+(Ka(z)?z:0)},0),P;if(T>0){var I;P=a.map(function(M,L){var z=Jg(M,_,0),$=Jg(M,u,L),V=(Ka(z)?z:0)/T,W;L?W=I.endAngle+zv(y)*c*(z!==0?1:0):W=l;var G=W+zv(y)*((z!==0?f:0)+V*A),X=(W+G)/2,te=(g.innerRadius+g.outerRadius)/2,ne=[{name:$,value:z,payload:M,dataKey:_,type:m}],me=Fh(g.cx,g.cy,te,X);return I=Lh(Lh(Lh({percent:V,cornerRadius:i,name:$,tooltipPayload:ne,midAngle:X,middleRadius:te,tooltipPosition:me},M),g),{},{value:Jg(M,_),startAngle:W,endAngle:G,payload:M,paddingAngle:zv(y)*c}),I})}return Lh(Lh({},g),{},{sectors:P,data:a})});var xin=Math.ceil,yin=Math.max;function vin(s,t,n,r){for(var a=-1,i=yin(xin((t-s)/(n||1)),0),l=Array(i);i--;)l[r?i:++a]=s,s+=n;return l}var bin=vin,_in=vMt,aut=1/0,win=17976931348623157e292;function jin(s){if(!s)return s===0?s:0;if(s=_in(s),s===aut||s===-aut){var t=s<0?-1:1;return t*win}return s===s?s:0}var sPt=jin,Nin=bin,kin=hCe,OLe=sPt;function Sin(s){return function(t,n,r){return r&&typeof r!="number"&&kin(t,n,r)&&(n=r=void 0),t=OLe(t),n===void 0?(n=t,t=0):n=OLe(n),r=r===void 0?t0&&r.handleDrag(a.changedTouches[0])}),Qb(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()}),Qb(r,"handleLeaveWrapper",function(){(r.state.isTravellerMoving||r.state.isSlideMoving)&&(r.leaveTimer=window.setTimeout(r.handleDragEnd,r.props.leaveTimeOut))}),Qb(r,"handleEnterSlideOrTraveller",function(){r.setState({isTextActive:!0})}),Qb(r,"handleLeaveSlideOrTraveller",function(){r.setState({isTextActive:!1})}),Qb(r,"handleSlideDragStart",function(a){var i=dut(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 Bin(t,s),Rin(t,[{key:"componentWillUnmount",value:function(){this.leaveTimer&&(clearTimeout(this.leaveTimer),this.leaveTimer=null),this.detachDragEndListener()}},{key:"getIndex",value:function(r){var a=r.startX,i=r.endX,l=this.state.scaleValues,o=this.props,c=o.gap,d=o.data,u=d.length-1,h=Math.min(a,i),m=Math.max(a,i),f=t.getIndexInRange(l,h),g=t.getIndexInRange(l,m);return{startIndex:f-f%c,endIndex:g===u?u:g-g%c}}},{key:"getTextOfTick",value:function(r){var a=this.props,i=a.data,l=a.tickFormatter,o=a.dataKey,c=Jg(i[r],o,r);return hl(l)?l(c,r):c}},{key:"attachDragEndListener",value:function(){window.addEventListener("mouseup",this.handleDragEnd,!0),window.addEventListener("touchend",this.handleDragEnd,!0),window.addEventListener("mousemove",this.handleDrag,!0)}},{key:"detachDragEndListener",value:function(){window.removeEventListener("mouseup",this.handleDragEnd,!0),window.removeEventListener("touchend",this.handleDragEnd,!0),window.removeEventListener("mousemove",this.handleDrag,!0)}},{key:"handleSlideDrag",value:function(r){var a=this.state,i=a.slideMoveStartX,l=a.startX,o=a.endX,c=this.props,d=c.x,u=c.width,h=c.travellerWidth,m=c.startIndex,f=c.endIndex,g=c.onChange,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 x=this.getIndex({startX:l+y,endX:o+y});(x.startIndex!==m||x.endIndex!==f)&&g&&g(x),this.setState({startX:l+y,endX:o+y,slideMoveStartX:r.pageX})}},{key:"handleTravellerDragStart",value:function(r,a){var i=dut(a)?a.changedTouches[0]:a;this.setState({isSlideMoving:!1,isTravellerMoving:!0,movingTravellerId:r,brushMoveStartX:i.pageX}),this.attachDragEndListener()}},{key:"handleTravellerMove",value:function(r){var a=this.state,i=a.brushMoveStartX,l=a.movingTravellerId,o=a.endX,c=a.startX,d=this.state[l],u=this.props,h=u.x,m=u.width,f=u.travellerWidth,g=u.onChange,y=u.gap,x=u.data,_={startX:this.state.startX,endX:this.state.endX},b=r.pageX-i;b>0?b=Math.min(b,h+m-f-d):b<0&&(b=Math.max(b,h-d)),_[l]=d+b;var k=this.getIndex(_),A=k.startIndex,T=k.endIndex,P=function(){var M=x.length-1;return l==="startX"&&(o>c?A%y===0:T%y===0)||oc?T%y===0:A%y===0)||o>c&&T===M};this.setState(Qb(Qb({},l,d+b),"brushMoveStartX",r.pageX),function(){g&&P()&&g(k)})}},{key:"handleTravellerMoveKeyboard",value:function(r,a){var i=this,l=this.state,o=l.scaleValues,c=l.startX,d=l.endX,u=this.state[a],h=o.indexOf(u);if(h!==-1){var m=h+r;if(!(m===-1||m>=o.length)){var f=o[m];a==="startX"&&f>=d||a==="endX"&&f<=c||this.setState(Qb({},a,f),function(){i.props.onChange(i.getIndex({startX:i.state.startX,endX:i.state.endX}))})}}}},{key:"renderBackground",value:function(){var r=this.props,a=r.x,i=r.y,l=r.width,o=r.height,c=r.fill,d=r.stroke;return Rt.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=N.Children.only(d);return h?Rt.cloneElement(h,{x:a,y:i,width:l,height:o,margin:u,compact:!0,data:c}):null}},{key:"renderTravellerLayer",value:function(r,a){var i,l,o=this,c=this.props,d=c.y,u=c.travellerWidth,h=c.height,m=c.traveller,f=c.ariaLabel,g=c.data,y=c.startIndex,x=c.endIndex,_=Math.max(r,this.props.x),b=FLe(FLe({},qo(this.props,!1)),{},{x:_,y:d,width:u,height:h}),k=f||"Min value: ".concat((i=g[y])===null||i===void 0?void 0:i.name,", Max value: ").concat((l=g[x])===null||l===void 0?void 0:l.name);return Rt.createElement(Bd,{tabIndex:0,role:"slider","aria-label":k,"aria-valuenow":r,className:"recharts-brush-traveller",onMouseEnter:this.handleEnterSlideOrTraveller,onMouseLeave:this.handleLeaveSlideOrTraveller,onMouseDown:this.travellerDragStartHandlers[a],onTouchStart:this.travellerDragStartHandlers[a],onKeyDown:function(T){["ArrowLeft","ArrowRight"].includes(T.key)&&(T.preventDefault(),T.stopPropagation(),o.handleTravellerMoveKeyboard(T.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 Rt.createElement("rect",{className:"recharts-brush-slide",onMouseEnter:this.handleEnterSlideOrTraveller,onMouseLeave:this.handleLeaveSlideOrTraveller,onMouseDown:this.handleSlideDragStart,onTouchStart:this.handleSlideDragStart,style:{cursor:"move"},stroke:"none",fill:c,fillOpacity:.2,x:u,y:l,width:h,height:o})}},{key:"renderText",value:function(){var r=this.props,a=r.startIndex,i=r.endIndex,l=r.y,o=r.height,c=r.travellerWidth,d=r.stroke,u=this.state,h=u.startX,m=u.endX,f=5,g={pointerEvents:"none",fill:d};return Rt.createElement(Bd,{className:"recharts-brush-texts"},Rt.createElement(fR,n5e({textAnchor:"end",verticalAnchor:"middle",x:Math.min(h,m)-f,y:l+o/2},g),this.getTextOfTick(a)),Rt.createElement(fR,n5e({textAnchor:"start",verticalAnchor:"middle",x:Math.max(h,m)+c+f,y:l+o/2},g),this.getTextOfTick(i)))}},{key:"render",value:function(){var r=this.props,a=r.data,i=r.className,l=r.children,o=r.x,c=r.y,d=r.width,u=r.height,h=r.alwaysShowText,m=this.state,f=m.startX,g=m.endX,y=m.isTextActive,x=m.isSlideMoving,_=m.isTravellerMoving,b=m.isTravellerFocused;if(!a||!a.length||!Ka(o)||!Ka(c)||!Ka(d)||!Ka(u)||d<=0||u<=0)return null;var k=Ol("recharts-brush",i),A=Rt.Children.count(l)===1,T=Iin("userSelect","none");return Rt.createElement(Bd,{className:k,onMouseLeave:this.handleLeaveWrapper,onTouchMove:this.handleTouchMove,style:T},this.renderBackground(),A&&this.renderPanorama(),this.renderSlide(f,g),this.renderTravellerLayer(f,"startX"),this.renderTravellerLayer(g,"endX"),(y||x||_||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 Rt.createElement(Rt.Fragment,null,Rt.createElement("rect",{x:a,y:i,width:l,height:o,fill:c,stroke:"none"}),Rt.createElement("line",{x1:a+1,y1:d,x2:a+l-1,y2:d,fill:"none",stroke:"#fff"}),Rt.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 Rt.isValidElement(r)?i=Rt.cloneElement(r,a):hl(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 FLe({prevData:i,prevTravellerWidth:c,prevUpdateId:d,prevX:o,prevWidth:l},i&&i.length?Uin({data:i,width:l,x:o,travellerWidth:c,startIndex:u,endIndex:h}):{scale:null,scaleValues:null});if(a.scale&&(l!==a.prevWidth||o!==a.prevX||c!==a.prevTravellerWidth)){a.scale.range([o,o+l-c]);var m=a.scale.domain().map(function(f){return a.scale(f)});return{prevData:i,prevTravellerWidth:c,prevUpdateId:d,prevX:o,prevWidth:l,startX:a.scale(r.startIndex),endX:a.scale(r.endIndex),scaleValues:m}}return null}},{key:"getIndexInRange",value:function(r,a){for(var i=r.length,l=0,o=i-1;o-l>1;){var c=Math.floor((l+o)/2);r[c]>a?o=c:l=c}return a>=r[o]?o:l}}])}(N.PureComponent);Qb(m$,"displayName","Brush");Qb(m$,"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 qin=xHe;function Vin(s,t){var n;return qin(s,function(r,a,i){return n=t(r,a,i),!n}),!!n}var Hin=Vin,Gin=G6t,Win=Z5,Kin=Hin,Yin=bb,Zin=hCe;function Xin(s,t,n){var r=Yin(s)?Gin:Kin;return n&&Zin(s,t,n)&&(t=void 0),r(s,Win(t))}var Qin=Xin;const Jin=Xc(Qin);var w5=function(t,n){var r=t.alwaysShow,a=t.ifOverflow;return r&&(a="extendDomain"),a===n},uut=pMt;function eon(s,t,n){t=="__proto__"&&uut?uut(s,t,{configurable:!0,enumerable:!0,value:n,writable:!0}):s[t]=n}var ton=eon,son=ton,non=hMt,ron=Z5;function aon(s,t){var n={};return t=ron(t),non(s,function(r,a,i){son(n,a,t(r,a,i))}),n}var ion=aon;const oon=Xc(ion);function lon(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 kon(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 Son(s,t){var n=s.x,r=s.y,a=Non(s,bon),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 tH(tH(tH(tH(tH({},t),a),l?{x:l}:{}),c?{y:c}:{}),{},{height:u,width:m,name:t.name,radius:t.radius})}function mut(s){return Rt.createElement(JLt,zFe({shapeType:"rectangle",propTransformer:Son,activeClassName:"recharts-active-bar"},s))}var Con=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=Ka(r)||lBs(r);return i?t(r,a):(i||xR(),n)}},Aon=["value","background"],oPt;function p$(s){"@babel/helpers - typeof";return p$=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},p$(s)}function Ton(s,t){if(s==null)return{};var n=Eon(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 Eon(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 a5e(){return a5e=Object.assign?Object.assign.bind():function(s){for(var t=1;t0&&Math.abs(X)0&&Math.abs(G)0&&(W=Math.min((ve||0)-(G[ge-1]||0),W))}),Number.isFinite(W)){var X=W/V,te=y.layout==="vertical"?r.height:r.width;if(y.padding==="gap"&&(I=X*te/2),y.padding==="no-gap"){var ne=Bv(t.barCategoryGap,X*te),me=X*te/2;I=me-ne-(me-ne)/te*ne}}}a==="xAxis"?M=[r.left+(k.left||0)+(I||0),r.left+r.width-(k.right||0)-(I||0)]:a==="yAxis"?M=c==="horizontal"?[r.top+r.height-(k.bottom||0),r.top+(k.top||0)]:[r.top+(k.top||0)+(I||0),r.top+r.height-(k.bottom||0)-(I||0)]:M=y.range,T&&(M=[M[1],M[0]]);var ue=SLt(y,i,m),ce=ue.scale,ae=ue.realScaleType;ce.domain(_).range(M),CLt(ce);var he=ALt(ce,L2(L2({},y),{},{realScaleType:ae}));a==="xAxis"?($=x==="top"&&!A||x==="bottom"&&A,L=r.left,z=h[P]-$*y.height):a==="yAxis"&&($=x==="left"&&!A||x==="right"&&A,L=h[P]-$*y.width,z=r.top);var xe=L2(L2(L2({},y),he),{},{realScaleType:ae,x:L,y:z,scale:ce,width:a==="xAxis"?r.width:y.width,height:a==="yAxis"?r.height:y.height});return xe.bandSize=qke(xe,he),!y.hide&&a==="xAxis"?h[P]+=($?-1:1)*xe.height:y.hide||(h[P]+=($?-1:1)*xe.width),L2(L2({},f),{},MCe({},g,xe))},{})},hPt=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)}},$on=function(t){var n=t.x1,r=t.y1,a=t.x2,i=t.y2;return hPt({x:n,y:r},{x:a,y:i})},mPt=function(){function s(t){Fon(this,s),this.scale=t}return zon(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)}}])}();MCe(mPt,"EPS",1e-4);var GHe=function(t){var n=Object.keys(t).reduce(function(r,a){return L2(L2({},r),{},MCe({},a,mPt.create(t[a])))},{});return L2(L2({},n),{},{apply:function(a){var i=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},l=i.bandAware,o=i.position;return oon(a,function(c,d){return n[d].apply(c,{bandAware:l,position:o})})},isInRange:function(a){return iPt(a,function(i,l){return n[l].isInRange(i)})}})};function Uon(s){return(s%180+180)%180}var qon=function(t){var n=t.width,r=t.height,a=arguments.length>1&&arguments[1]!==void 0?arguments[1]:0,i=Uon(a),l=i*Math.PI/180,o=Math.atan(r/n),c=l>o&&l-1?a[i?t[l]:l]:void 0}}var Kon=Won,Yon=sPt;function Zon(s){var t=Yon(s),n=t%1;return t===t?n?t-n:t:0}var Xon=Zon,Qon=iMt,Jon=Z5,eln=Xon,tln=Math.max;function sln(s,t,n){var r=s==null?0:s.length;if(!r)return-1;var a=n==null?0:eln(n);return a<0&&(a=tln(r+a,0)),Qon(s,Jon(t),a)}var nln=sln,rln=Kon,aln=nln,iln=rln(aln),oln=iln;const lln=Xc(oln);var cln=hzs(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("")}),WHe=N.createContext(void 0),KHe=N.createContext(void 0),pPt=N.createContext(void 0),fPt=N.createContext({}),gPt=N.createContext(void 0),xPt=N.createContext(0),yPt=N.createContext(0),yut=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=cln(i);return Rt.createElement(WHe.Provider,{value:r},Rt.createElement(KHe.Provider,{value:a},Rt.createElement(fPt.Provider,{value:i},Rt.createElement(pPt.Provider,{value:u},Rt.createElement(gPt.Provider,{value:l},Rt.createElement(xPt.Provider,{value:d},Rt.createElement(yPt.Provider,{value:c},o)))))))},dln=function(){return N.useContext(gPt)},vPt=function(t){var n=N.useContext(WHe);n==null&&xR();var r=n[t];return r==null&&xR(),r},uln=function(){var t=N.useContext(WHe);return pA(t)},hln=function(){var t=N.useContext(KHe),n=lln(t,function(r){return iPt(r.domain,Number.isFinite)});return n||pA(t)},bPt=function(t){var n=N.useContext(KHe);n==null&&xR();var r=n[t];return r==null&&xR(),r},mln=function(){var t=N.useContext(pPt);return t},pln=function(){return N.useContext(fPt)},YHe=function(){return N.useContext(yPt)},ZHe=function(){return N.useContext(xPt)};function f$(s){"@babel/helpers - typeof";return f$=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},f$(s)}function fln(s,t){if(!(s instanceof t))throw new TypeError("Cannot call a class as a function")}function gln(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 Xln(s,t){return CPt(s,t+1)}function Qln(s,t,n,r,a){for(var i=(r||[]).slice(),l=t.start,o=t.end,c=0,d=1,u=l,h=function(){var g=r==null?void 0:r[c];if(g===void 0)return{v:CPt(r,d)};var y=c,x,_=function(){return x===void 0&&(x=n(g,y)),x},b=g.coordinate,k=c===0||d5e(s,b,_,u,o);k||(c=0,u=l,d+=1),k&&(u=b+s*(_()/2+a),c+=d)},m;d<=i.length;)if(m=h(),m)return m.v;return[]}function xZ(s){"@babel/helpers - typeof";return xZ=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},xZ(s)}function Sut(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 My(s){for(var t=1;t0?f.coordinate-x*s:f.coordinate})}else i[m]=f=My(My({},f),{},{tickCoord:f.coordinate});var _=d5e(s,f.tickCoord,y,o,c);_&&(c=f.tickCoord-s*(y()/2+a),i[m]=My(My({},f),{},{isShow:!0}))},u=l-1;u>=0;u--)d(u);return i}function ncn(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=My(My({},u),{},{tickCoord:m>0?u.coordinate-m*s:u.coordinate});var f=d5e(s,u.tickCoord,function(){return h},c,d);f&&(d=u.tickCoord-s*(h/2+a),l[o-1]=My(My({},u),{},{isShow:!0}))}for(var g=i?o-1:o,y=function(b){var k=l[b],A,T=function(){return A===void 0&&(A=n(k,b)),A};if(b===0){var P=s*(k.coordinate-s*T()/2-c);l[b]=k=My(My({},k),{},{tickCoord:P<0?k.coordinate-P*s:k.coordinate})}else l[b]=k=My(My({},k),{},{tickCoord:k.coordinate});var I=d5e(s,k.tickCoord,T,c,d);I&&(c=k.tickCoord+s*(T()/2+a),l[b]=My(My({},k),{},{isShow:!0}))},x=0;x=2?zv(a[1].coordinate-a[0].coordinate):1,_=Zln(i,x,f);return c==="equidistantPreserveStart"?Qln(x,_,y,a,l):(c==="preserveStart"||c==="preserveStartEnd"?m=ncn(x,_,y,a,l,c==="preserveStartEnd"):m=scn(x,_,y,a,l),m.filter(function(b){return b.isShow}))}var rcn=["viewBox"],acn=["viewBox"],icn=["ticks"];function y$(s){"@babel/helpers - typeof";return y$=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},y$(s)}function q7(){return q7=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 ocn(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 lcn(s,t){if(!(s instanceof t))throw new TypeError("Cannot call a class as a function")}function Aut(s,t){for(var n=0;n0?c(this.props):c(f)),l<=0||o<=0||!g||!g.length?null:Rt.createElement(Bd,{className:Ol("recharts-cartesian-axis",d),ref:function(x){r.layerReference=x}},i&&this.renderAxisLine(),this.renderTicks(g,this.state.fontSize,this.state.letterSpacing),Hx.renderCallByParent(this.props))}}],[{key:"renderTickItem",value:function(r,a,i){var l,o=Ol(a.className,"recharts-cartesian-axis-tick-value");return Rt.isValidElement(r)?l=Rt.cloneElement(r,Rg(Rg({},a),{},{className:o})):hl(r)?l=r(Rg(Rg({},a),{},{className:o})):l=Rt.createElement(fR,q7({},a,{className:"recharts-cartesian-axis-tick-value"}),i),l}}])}(N.Component);eGe(BU,"displayName","CartesianAxis");eGe(BU,"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 fcn=["x1","y1","x2","y2","key"],gcn=["offset"];function yR(s){"@babel/helpers - typeof";return yR=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},yR(s)}function Tut(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 Dy(s){for(var t=1;t=0)&&Object.prototype.propertyIsEnumerable.call(s,r)&&(n[r]=s[r])}return n}function bcn(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 _cn=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 Rt.createElement("rect",{x:a,y:i,ry:c,width:l,height:o,stroke:"none",fill:n,fillOpacity:r,className:"recharts-cartesian-grid-bg"})};function EPt(s,t){var n;if(Rt.isValidElement(s))n=Rt.cloneElement(s,t);else if(hl(s))n=s(t);else{var r=t.x1,a=t.y1,i=t.x2,l=t.y2,o=t.key,c=Eut(t,fcn),d=qo(c,!1);d.offset;var u=Eut(d,gcn);n=Rt.createElement("line",$I({},u,{x1:r,y1:a,x2:i,y2:l,fill:"none",key:o}))}return n}function wcn(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=Dy(Dy({},s),{},{x1:t,y1:o,x2:t+n,y2:o,key:"line-".concat(c),index:c});return EPt(a,d)});return Rt.createElement("g",{className:"recharts-cartesian-grid-horizontal"},l)}function jcn(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=Dy(Dy({},s),{},{x1:o,y1:t,x2:o,y2:t+n,key:"line-".concat(c),index:c});return EPt(a,d)});return Rt.createElement("g",{className:"recharts-cartesian-grid-vertical"},l)}function Ncn(s){var t=s.horizontalFill,n=s.fillOpacity,r=s.x,a=s.y,i=s.width,l=s.height,o=s.horizontalPoints,c=s.horizontal,d=c===void 0?!0:c;if(!d||!t||!t.length)return null;var u=o.map(function(m){return Math.round(m+a-a)}).sort(function(m,f){return m-f});a!==u[0]&&u.unshift(0);var h=u.map(function(m,f){var g=!u[f+1],y=g?a+l-m:u[f+1]-m;if(y<=0)return null;var x=f%t.length;return Rt.createElement("rect",{key:"react-".concat(f),y:m,x:r,height:y,width:i,stroke:"none",fill:t[x],fillOpacity:n,className:"recharts-cartesian-grid-bg"})});return Rt.createElement("g",{className:"recharts-cartesian-gridstripes-horizontal"},h)}function kcn(s){var t=s.vertical,n=t===void 0?!0:t,r=s.verticalFill,a=s.fillOpacity,i=s.x,l=s.y,o=s.width,c=s.height,d=s.verticalPoints;if(!n||!r||!r.length)return null;var u=d.map(function(m){return Math.round(m+i-i)}).sort(function(m,f){return m-f});i!==u[0]&&u.unshift(0);var h=u.map(function(m,f){var g=!u[f+1],y=g?i+o-m:u[f+1]-m;if(y<=0)return null;var x=f%r.length;return Rt.createElement("rect",{key:"react-".concat(f),x:m,y:l,width:y,height:c,stroke:"none",fill:r[x],fillOpacity:a,className:"recharts-cartesian-grid-bg"})});return Rt.createElement("g",{className:"recharts-cartesian-gridstripes-vertical"},h)}var Scn=function(t,n){var r=t.xAxis,a=t.width,i=t.height,l=t.offset;return kLt(JHe(Dy(Dy(Dy({},BU.defaultProps),r),{},{ticks:Z4(r,!0),viewBox:{x:0,y:0,width:a,height:i}})),l.left,l.left+l.width,n)},Ccn=function(t,n){var r=t.yAxis,a=t.width,i=t.height,l=t.offset;return kLt(JHe(Dy(Dy(Dy({},BU.defaultProps),r),{},{ticks:Z4(r,!0),viewBox:{x:0,y:0,width:a,height:i}})),l.top,l.top+l.height,n)},SF={horizontal:!0,vertical:!0,horizontalPoints:[],verticalPoints:[],stroke:"#ccc",fill:"none",verticalFill:[],horizontalFill:[]};function tGe(s){var t,n,r,a,i,l,o=YHe(),c=ZHe(),d=pln(),u=Dy(Dy({},s),{},{stroke:(t=s.stroke)!==null&&t!==void 0?t:SF.stroke,fill:(n=s.fill)!==null&&n!==void 0?n:SF.fill,horizontal:(r=s.horizontal)!==null&&r!==void 0?r:SF.horizontal,horizontalFill:(a=s.horizontalFill)!==null&&a!==void 0?a:SF.horizontalFill,vertical:(i=s.vertical)!==null&&i!==void 0?i:SF.vertical,verticalFill:(l=s.verticalFill)!==null&&l!==void 0?l:SF.verticalFill,x:Ka(s.x)?s.x:d.left,y:Ka(s.y)?s.y:d.top,width:Ka(s.width)?s.width:d.width,height:Ka(s.height)?s.height:d.height}),h=u.x,m=u.y,f=u.width,g=u.height,y=u.syncWithTicks,x=u.horizontalValues,_=u.verticalValues,b=uln(),k=hln();if(!Ka(f)||f<=0||!Ka(g)||g<=0||!Ka(h)||h!==+h||!Ka(m)||m!==+m)return null;var A=u.verticalCoordinatesGenerator||Scn,T=u.horizontalCoordinatesGenerator||Ccn,P=u.horizontalPoints,I=u.verticalPoints;if((!P||!P.length)&&hl(T)){var M=x&&x.length,L=T({yAxis:k?Dy(Dy({},k),{},{ticks:M?x:k.ticks}):void 0,width:o,height:c,offset:d},M?!0:y);iN(Array.isArray(L),"horizontalCoordinatesGenerator should return Array but instead it returned [".concat(yR(L),"]")),Array.isArray(L)&&(P=L)}if((!I||!I.length)&&hl(A)){var z=_&&_.length,$=A({xAxis:b?Dy(Dy({},b),{},{ticks:z?_:b.ticks}):void 0,width:o,height:c,offset:d},z?!0:y);iN(Array.isArray($),"verticalCoordinatesGenerator should return Array but instead it returned [".concat(yR($),"]")),Array.isArray($)&&(I=$)}return Rt.createElement("g",{className:"recharts-cartesian-grid"},Rt.createElement(_cn,{fill:u.fill,fillOpacity:u.fillOpacity,x:u.x,y:u.y,width:u.width,height:u.height,ry:u.ry}),Rt.createElement(wcn,$I({},u,{offset:d,horizontalPoints:P,xAxis:b,yAxis:k})),Rt.createElement(jcn,$I({},u,{offset:d,verticalPoints:I,xAxis:b,yAxis:k})),Rt.createElement(Ncn,$I({},u,{horizontalPoints:P})),Rt.createElement(kcn,$I({},u,{verticalPoints:I})))}tGe.displayName="CartesianGrid";var Acn=["type","layout","connectNulls","ref"],Tcn=["key"];function v$(s){"@babel/helpers - typeof";return v$=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},v$(s)}function Mut(s,t){if(s==null)return{};var n=Ecn(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 Ecn(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 _K(){return _K=Object.assign?Object.assign.bind():function(s){for(var t=1;ts.length)&&(t=s.length);for(var n=0,r=new Array(t);nh){f=[].concat(CF(c.slice(0,g)),[h-y]);break}var x=f.length%2===0?[0,m]:[m];return[].concat(CF(t.repeat(c,u)),CF(f),x).map(function(_){return"".concat(_,"px")}).join(", ")}),P2(n,"id",MU("recharts-line-")),P2(n,"pathRef",function(l){n.mainCurve=l}),P2(n,"handleAnimationEnd",function(){n.setState({isAnimationFinished:!0}),n.props.onAnimationEnd&&n.props.onAnimationEnd()}),P2(n,"handleAnimationStart",function(){n.setState({isAnimationFinished:!1}),n.props.onAnimationStart&&n.props.onAnimationStart()}),n}return Bcn(t,s),Rcn(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=R_(u,mJ);if(!h)return null;var m=function(y,x){return{x:y.x,y:y.y,value:y.value,errorVal:Jg(y.payload,x)}},f={clipPath:r?"url(#clipPath-".concat(a,")"):null};return Rt.createElement(Bd,f,h.map(function(g){return Rt.cloneElement(g,{key:"bar-".concat(g.props.dataKey),data:l,xAxis:o,yAxis:c,layout:d,dataPointFormatter:m})}))}},{key:"renderDots",value:function(r,a,i){var l=this.props.isAnimationActive;if(l&&!this.state.isAnimationFinished)return null;var o=this.props,c=o.dot,d=o.points,u=o.dataKey,h=qo(this.props,!1),m=qo(c,!0),f=d.map(function(y,x){var _=Yb(Yb(Yb({key:"dot-".concat(x),r:3},h),m),{},{index:x,cx:y.x,cy:y.y,value:y.value,dataKey:u,payload:y.payload,points:d});return t.renderDotItem(c,_)}),g={clipPath:r?"url(#clipPath-".concat(a?"":"dots-").concat(i,")"):null};return Rt.createElement(Bd,_K({className:"recharts-line-dots",key:"dots"},g),f)}},{key:"renderCurveStatically",value:function(r,a,i,l){var o=this.props,c=o.type,d=o.layout,u=o.connectNulls;o.ref;var h=Mut(o,Acn),m=Yb(Yb(Yb({},qo(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 Rt.createElement(Gke,_K({},m,{pathRef:this.pathRef}))}},{key:"renderCurveWithAnimation",value:function(r,a){var i=this,l=this.props,o=l.points,c=l.strokeDasharray,d=l.isAnimationActive,u=l.animationBegin,h=l.animationDuration,m=l.animationEasing,f=l.animationId,g=l.animateNewValues,y=l.width,x=l.height,_=this.state,b=_.prevPoints,k=_.totalLength;return Rt.createElement(I5,{begin:u,duration:h,isActive:d,easing:m,from:{t:0},to:{t:1},key:"line-".concat(f),onAnimationEnd:this.handleAnimationEnd,onAnimationStart:this.handleAnimationStart},function(A){var T=A.t;if(b){var P=b.length/o.length,I=o.map(function(V,W){var G=Math.floor(W*P);if(b[G]){var X=b[G],te=x_(X.x,V.x),ne=x_(X.y,V.y);return Yb(Yb({},V),{},{x:te(T),y:ne(T)})}if(g){var me=x_(y*2,V.x),ue=x_(x/2,V.y);return Yb(Yb({},V),{},{x:me(T),y:ue(T)})}return Yb(Yb({},V),{},{x:V.x,y:V.y})});return i.renderCurveStatically(I,r,a)}var M=x_(0,k),L=M(T),z;if(c){var $="".concat(c).split(/[,\s]+/gim).map(function(V){return parseFloat(V)});z=i.getStrokeDasharray(L,k,$)}else z=i.generateSimpleStrokeDasharray(k,L);return i.renderCurveStatically(o,r,a,{strokeDasharray:z})})}},{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||!hJ(d,l))?this.renderCurveWithAnimation(r,a):this.renderCurveStatically(l,r,a)}},{key:"render",value:function(){var r,a=this.props,i=a.hide,l=a.dot,o=a.points,c=a.className,d=a.xAxis,u=a.yAxis,h=a.top,m=a.left,f=a.width,g=a.height,y=a.isAnimationActive,x=a.id;if(i||!o||!o.length)return null;var _=this.state.isAnimationFinished,b=o.length===1,k=Ol("recharts-line",c),A=d&&d.allowDataOverflow,T=u&&u.allowDataOverflow,P=A||T,I=Ml(x)?this.id:x,M=(r=qo(l,!1))!==null&&r!==void 0?r:{r:3,strokeWidth:2},L=M.r,z=L===void 0?3:L,$=M.strokeWidth,V=$===void 0?2:$,W=bBs(l)?l:{},G=W.clipDot,X=G===void 0?!0:G,te=z*2+V;return Rt.createElement(Bd,{className:k},A||T?Rt.createElement("defs",null,Rt.createElement("clipPath",{id:"clipPath-".concat(I)},Rt.createElement("rect",{x:A?m:m-f/2,y:T?h:h-g/2,width:A?f:f*2,height:T?g:g*2})),!X&&Rt.createElement("clipPath",{id:"clipPath-dots-".concat(I)},Rt.createElement("rect",{x:m-te/2,y:h-te/2,width:f+te,height:g+te}))):null,!b&&this.renderCurve(P,I),this.renderErrorBar(P,I),(b||l)&&this.renderDots(P,X,I),(!y||_)&&m3.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(CF(r),[0]):r,l=[],o=0;os.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 Tdn(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 Edn(s,t){if(!(s instanceof t))throw new TypeError("Cannot call a class as a function")}function Mdn(s,t){for(var n=0;ns.length)&&(t=s.length);for(var n=0,r=new Array(t);n0?l:t&&t.length&&Ka(a)&&Ka(i)?t.slice(a,i+1):[]};function GPt(s){return s==="number"?[0,"auto"]:void 0}var r7e=function(t,n,r,a){var i=t.graphicalItems,l=t.tooltipAxis,o=RCe(n,t);return r<0||!i||!i.length||r>=o.length?null:i.reduce(function(c,d){var u,h=(u=d.props.data)!==null&&u!==void 0?u:n;h&&t.dataStartIndex+t.dataEndIndex!==0&&t.dataEndIndex-t.dataStartIndex>=r&&(h=h.slice(t.dataStartIndex,t.dataEndIndex+1));var m;if(l.dataKey&&!l.allowDuplicatedCategory){var f=h===void 0?o:h;m=fke(f,l.dataKey,a)}else m=h&&h[r]||o[r];return m?[].concat(j$(c),[ELt(d,m)]):c},[])},zut=function(t,n,r,a){var i=a||{x:t.chartX,y:t.chartY},l=qdn(i,r),o=t.orderedTooltipTicks,c=t.tooltipAxis,d=t.tooltipTicks,u=_tn(l,o,d,c);if(u>=0&&d){var h=d[u]&&d[u].value,m=r7e(t,n,u,h),f=Vdn(r,o,u,i);return{activeTooltipIndex:u,activeLabel:h,activePayload:m,activeCoordinate:f}}return null},Hdn=function(t,n){var r=n.axes,a=n.graphicalItems,i=n.axisType,l=n.axisIdKey,o=n.stackGroups,c=n.dataStartIndex,d=n.dataEndIndex,u=t.layout,h=t.children,m=t.stackOffset,f=NLt(u,i);return r.reduce(function(g,y){var x,_=y.type.defaultProps!==void 0?Br(Br({},y.type.defaultProps),y.props):y.props,b=_.type,k=_.dataKey,A=_.allowDataOverflow,T=_.allowDuplicatedCategory,P=_.scale,I=_.ticks,M=_.includeHidden,L=_[l];if(g[L])return g;var z=RCe(t.data,{graphicalItems:a.filter(function(he){var xe,ve=l in he.props?he.props[l]:(xe=he.type.defaultProps)===null||xe===void 0?void 0:xe[l];return ve===L}),dataStartIndex:c,dataEndIndex:d}),$=z.length,V,W,G;xdn(_.domain,A,b)&&(V=yFe(_.domain,null,A),f&&(b==="number"||P!=="auto")&&(G=xK(z,k,"category")));var X=GPt(b);if(!V||V.length===0){var te,ne=(te=_.domain)!==null&&te!==void 0?te:X;if(k){if(V=xK(z,k,b),b==="category"&&f){var me=dBs(V);T&&me?(W=V,V=s5e(0,$)):T||(V=odt(ne,V,y).reduce(function(he,xe){return he.indexOf(xe)>=0?he:[].concat(j$(he),[xe])},[]))}else if(b==="category")T?V=V.filter(function(he){return he!==""&&!Ml(he)}):V=odt(ne,V,y).reduce(function(he,xe){return he.indexOf(xe)>=0||xe===""||Ml(xe)?he:[].concat(j$(he),[xe])},[]);else if(b==="number"){var ue=Stn(z,a.filter(function(he){var xe,ve,ge=l in he.props?he.props[l]:(xe=he.type.defaultProps)===null||xe===void 0?void 0:xe[l],be="hide"in he.props?he.props.hide:(ve=he.type.defaultProps)===null||ve===void 0?void 0:ve.hide;return ge===L&&(M||!be)}),k,i,u);ue&&(V=ue)}f&&(b==="number"||P!=="auto")&&(G=xK(z,k,"category"))}else f?V=s5e(0,$):o&&o[L]&&o[L].hasStack&&b==="number"?V=m==="expand"?[0,1]:TLt(o[L].stackGroups,c,d):V=jLt(z,a.filter(function(he){var xe=l in he.props?he.props[l]:he.type.defaultProps[l],ve="hide"in he.props?he.props.hide:he.type.defaultProps.hide;return xe===L&&(M||!ve)}),b,u,!0);if(b==="number")V=t7e(h,V,L,i,I),ne&&(V=yFe(ne,V,A));else if(b==="category"&&ne){var ce=ne,ae=V.every(function(he){return ce.indexOf(he)>=0});ae&&(V=ce)}}return Br(Br({},g),{},el({},L,Br(Br({},_),{},{axisType:i,domain:V,categoricalDomain:G,duplicateDomain:W,originalDomain:(x=_.domain)!==null&&x!==void 0?x:X,isCategorical:f,layout:u})))},{})},Gdn=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=RCe(t.data,{graphicalItems:r,dataStartIndex:c,dataEndIndex:d}),f=m.length,g=NLt(u,i),y=-1;return r.reduce(function(x,_){var b=_.type.defaultProps!==void 0?Br(Br({},_.type.defaultProps),_.props):_.props,k=b[l],A=GPt("number");if(!x[k]){y++;var T;return g?T=s5e(0,f):o&&o[k]&&o[k].hasStack?(T=TLt(o[k].stackGroups,c,d),T=t7e(h,T,k,i)):(T=yFe(A,jLt(m,r.filter(function(P){var I,M,L=l in P.props?P.props[l]:(I=P.type.defaultProps)===null||I===void 0?void 0:I[l],z="hide"in P.props?P.props.hide:(M=P.type.defaultProps)===null||M===void 0?void 0:M.hide;return L===k&&!z}),"number",u),a.defaultProps.allowDataOverflow),T=t7e(h,T,k,i)),Br(Br({},x),{},el({},k,Br(Br({axisType:i},a.defaultProps),{},{hide:!0,orientation:D_($dn,"".concat(i,".").concat(y%2),null),domain:T,originalDomain:A,isCategorical:g,layout:u})))}return x},{})},Wdn=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=R_(u,i),f={};return m&&m.length?f=Hdn(t,{axes:m,graphicalItems:l,axisType:a,axisIdKey:h,stackGroups:o,dataStartIndex:c,dataEndIndex:d}):l&&l.length&&(f=Gdn(t,{Axis:i,graphicalItems:l,axisType:a,axisIdKey:h,stackGroups:o,dataStartIndex:c,dataEndIndex:d})),f},Kdn=function(t){var n=pA(t),r=Z4(n,!1,!0);return{tooltipTicks:r,orderedTooltipTicks:yHe(r,function(a){return a.coordinate}),tooltipAxis:n,tooltipAxisBandSize:qke(n,r)}},But=function(t){var n=t.children,r=t.defaultShowTooltip,a=h_(n,m$),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}},Ydn=function(t){return!t||!t.length?!1:t.some(function(n){var r=u3(n&&n.type);return r&&r.indexOf("Bar")>=0})},$ut=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"}},Zdn=function(t,n){var r=t.props,a=t.graphicalItems,i=t.xAxisMap,l=i===void 0?{}:i,o=t.yAxisMap,c=o===void 0?{}:o,d=r.width,u=r.height,h=r.children,m=r.margin||{},f=h_(h,m$),g=h_(h,ID),y=Object.keys(c).reduce(function(T,P){var I=c[P],M=I.orientation;return!I.mirror&&!I.hide?Br(Br({},T),{},el({},M,T[M]+I.width)):T},{left:m.left||0,right:m.right||0}),x=Object.keys(l).reduce(function(T,P){var I=l[P],M=I.orientation;return!I.mirror&&!I.hide?Br(Br({},T),{},el({},M,D_(T,"".concat(M))+I.height)):T},{top:m.top||0,bottom:m.bottom||0}),_=Br(Br({},x),y),b=_.bottom;f&&(_.bottom+=f.props.height||m$.defaultProps.height),g&&n&&(_=Ntn(_,a,r,n));var k=d-_.left-_.right,A=u-_.top-_.bottom;return Br(Br({brushBottom:b},_),{},{width:Math.max(k,0),height:Math.max(A,0)})},Xdn=function(t,n){if(n==="xAxis")return t[n].width;if(n==="yAxis")return t[n].height},sGe=function(t){var n=t.chartName,r=t.GraphicalChild,a=t.defaultTooltipEventType,i=a===void 0?"axis":a,l=t.validateTooltipEventTypes,o=l===void 0?["axis"]:l,c=t.axisComponents,d=t.legendContent,u=t.formatAxisMap,h=t.defaultProps,m=function(_,b){var k=b.graphicalItems,A=b.stackGroups,T=b.offset,P=b.updateId,I=b.dataStartIndex,M=b.dataEndIndex,L=_.barSize,z=_.layout,$=_.barGap,V=_.barCategoryGap,W=_.maxBarSize,G=$ut(z),X=G.numericAxisName,te=G.cateAxisName,ne=Ydn(k),me=[];return k.forEach(function(ue,ce){var ae=RCe(_.data,{graphicalItems:[ue],dataStartIndex:I,dataEndIndex:M}),he=ue.type.defaultProps!==void 0?Br(Br({},ue.type.defaultProps),ue.props):ue.props,xe=he.dataKey,ve=he.maxBarSize,ge=he["".concat(X,"Id")],be=he["".concat(te,"Id")],Se={},Ie=c.reduce(function(Ke,st){var rt=b["".concat(st.axisType,"Map")],Ze=he["".concat(st.axisType,"Id")];rt&&rt[Ze]||st.axisType==="zAxis"||xR();var ht=rt[Ze];return Br(Br({},Ke),{},el(el({},st.axisType,ht),"".concat(st.axisType,"Ticks"),Z4(ht)))},Se),Me=Ie[te],Re=Ie["".concat(te,"Ticks")],Be=A&&A[ge]&&A[ge].hasStack&&Dtn(ue,A[ge].stackGroups),Ne=u3(ue.type).indexOf("Bar")>=0,Ge=qke(Me,Re),Ce=[],Fe=ne&&wtn({barSize:L,stackGroups:A,totalSize:Xdn(Ie,te)});if(Ne){var Ae,Xe,$e=Ml(ve)?W:ve,Ye=(Ae=(Xe=qke(Me,Re,!0))!==null&&Xe!==void 0?Xe:$e)!==null&&Ae!==void 0?Ae:0;Ce=jtn({barGap:$,barCategoryGap:V,bandSize:Ye!==Ge?Ye:Ge,sizeList:Fe[be],maxBarSize:$e}),Ye!==Ge&&(Ce=Ce.map(function(Ke){return Br(Br({},Ke),{},{position:Br(Br({},Ke.position),{},{offset:Ke.position.offset-Ye/2})})}))}var Je=ue&&ue.type&&ue.type.getComposedData;Je&&me.push({props:Br(Br({},Je(Br(Br({},Ie),{},{displayedData:ae,props:_,dataKey:xe,item:ue,bandSize:Ge,barPosition:Ce,offset:T,stackedData:Be,layout:z,dataStartIndex:I,dataEndIndex:M}))),{},el(el(el({key:ue.key||"item-".concat(ce)},X,Ie[X]),te,Ie[te]),"animationId",P)),childIndex:jBs(ue,_.children),item:ue})}),me},f=function(_,b){var k=_.props,A=_.dataStartIndex,T=_.dataEndIndex,P=_.updateId;if(!elt({props:k}))return null;var I=k.children,M=k.layout,L=k.stackOffset,z=k.data,$=k.reverseStackOrder,V=$ut(M),W=V.numericAxisName,G=V.cateAxisName,X=R_(I,r),te=Ptn(z,X,"".concat(W,"Id"),"".concat(G,"Id"),L,$),ne=c.reduce(function(he,xe){var ve="".concat(xe.axisType,"Map");return Br(Br({},he),{},el({},ve,Wdn(k,Br(Br({},xe),{},{graphicalItems:X,stackGroups:xe.axisType===W&&te,dataStartIndex:A,dataEndIndex:T}))))},{}),me=Zdn(Br(Br({},ne),{},{props:k,graphicalItems:X}),b==null?void 0:b.legendBBox);Object.keys(ne).forEach(function(he){ne[he]=u(k,ne[he],me,he.replace("Map",""),n)});var ue=ne["".concat(G,"Map")],ce=Kdn(ue),ae=m(k,Br(Br({},ne),{},{dataStartIndex:A,dataEndIndex:T,updateId:P,graphicalItems:X,stackGroups:te,offset:me}));return Br(Br({formattedGraphicalItems:ae,graphicalItems:X,offset:me,stackGroups:te},ce),ne)},g=function(x){function _(b){var k,A,T;return Edn(this,_),T=Pdn(this,_,[b]),el(T,"eventEmitterSymbol",Symbol("rechartsEventEmitter")),el(T,"accessibilityManager",new gdn),el(T,"handleLegendBBoxUpdate",function(P){if(P){var I=T.state,M=I.dataStartIndex,L=I.dataEndIndex,z=I.updateId;T.setState(Br({legendBBox:P},f({props:T.props,dataStartIndex:M,dataEndIndex:L,updateId:z},Br(Br({},T.state),{},{legendBBox:P}))))}}),el(T,"handleReceiveSyncEvent",function(P,I,M){if(T.props.syncId===P){if(M===T.eventEmitterSymbol&&typeof T.props.syncMethod!="function")return;T.applySyncEvent(I)}}),el(T,"handleBrushChange",function(P){var I=P.startIndex,M=P.endIndex;if(I!==T.state.dataStartIndex||M!==T.state.dataEndIndex){var L=T.state.updateId;T.setState(function(){return Br({dataStartIndex:I,dataEndIndex:M},f({props:T.props,dataStartIndex:I,dataEndIndex:M,updateId:L},T.state))}),T.triggerSyncEvent({dataStartIndex:I,dataEndIndex:M})}}),el(T,"handleMouseEnter",function(P){var I=T.getMouseInfo(P);if(I){var M=Br(Br({},I),{},{isTooltipActive:!0});T.setState(M),T.triggerSyncEvent(M);var L=T.props.onMouseEnter;hl(L)&&L(M,P)}}),el(T,"triggeredAfterMouseMove",function(P){var I=T.getMouseInfo(P),M=I?Br(Br({},I),{},{isTooltipActive:!0}):{isTooltipActive:!1};T.setState(M),T.triggerSyncEvent(M);var L=T.props.onMouseMove;hl(L)&&L(M,P)}),el(T,"handleItemMouseEnter",function(P){T.setState(function(){return{isTooltipActive:!0,activeItem:P,activePayload:P.tooltipPayload,activeCoordinate:P.tooltipPosition||{x:P.cx,y:P.cy}}})}),el(T,"handleItemMouseLeave",function(){T.setState(function(){return{isTooltipActive:!1}})}),el(T,"handleMouseMove",function(P){P.persist(),T.throttleTriggeredAfterMouseMove(P)}),el(T,"handleMouseLeave",function(P){T.throttleTriggeredAfterMouseMove.cancel();var I={isTooltipActive:!1};T.setState(I),T.triggerSyncEvent(I);var M=T.props.onMouseLeave;hl(M)&&M(I,P)}),el(T,"handleOuterEvent",function(P){var I=wBs(P),M=D_(T.props,"".concat(I));if(I&&hl(M)){var L,z;/.*touch.*/i.test(I)?z=T.getMouseInfo(P.changedTouches[0]):z=T.getMouseInfo(P),M((L=z)!==null&&L!==void 0?L:{},P)}}),el(T,"handleClick",function(P){var I=T.getMouseInfo(P);if(I){var M=Br(Br({},I),{},{isTooltipActive:!0});T.setState(M),T.triggerSyncEvent(M);var L=T.props.onClick;hl(L)&&L(M,P)}}),el(T,"handleMouseDown",function(P){var I=T.props.onMouseDown;if(hl(I)){var M=T.getMouseInfo(P);I(M,P)}}),el(T,"handleMouseUp",function(P){var I=T.props.onMouseUp;if(hl(I)){var M=T.getMouseInfo(P);I(M,P)}}),el(T,"handleTouchMove",function(P){P.changedTouches!=null&&P.changedTouches.length>0&&T.throttleTriggeredAfterMouseMove(P.changedTouches[0])}),el(T,"handleTouchStart",function(P){P.changedTouches!=null&&P.changedTouches.length>0&&T.handleMouseDown(P.changedTouches[0])}),el(T,"handleTouchEnd",function(P){P.changedTouches!=null&&P.changedTouches.length>0&&T.handleMouseUp(P.changedTouches[0])}),el(T,"handleDoubleClick",function(P){var I=T.props.onDoubleClick;if(hl(I)){var M=T.getMouseInfo(P);I(M,P)}}),el(T,"handleContextMenu",function(P){var I=T.props.onContextMenu;if(hl(I)){var M=T.getMouseInfo(P);I(M,P)}}),el(T,"triggerSyncEvent",function(P){T.props.syncId!==void 0&&BLe.emit($Le,T.props.syncId,P,T.eventEmitterSymbol)}),el(T,"applySyncEvent",function(P){var I=T.props,M=I.layout,L=I.syncMethod,z=T.state.updateId,$=P.dataStartIndex,V=P.dataEndIndex;if(P.dataStartIndex!==void 0||P.dataEndIndex!==void 0)T.setState(Br({dataStartIndex:$,dataEndIndex:V},f({props:T.props,dataStartIndex:$,dataEndIndex:V,updateId:z},T.state)));else if(P.activeTooltipIndex!==void 0){var W=P.chartX,G=P.chartY,X=P.activeTooltipIndex,te=T.state,ne=te.offset,me=te.tooltipTicks;if(!ne)return;if(typeof L=="function")X=L(me,P);else if(L==="value"){X=-1;for(var ue=0;ue=0){var Be,Ne;if(W.dataKey&&!W.allowDuplicatedCategory){var Ge=typeof W.dataKey=="function"?Re:"payload.".concat(W.dataKey.toString());Be=fke(ue,Ge,X),Ne=ce&&ae&&fke(ae,Ge,X)}else Be=ue==null?void 0:ue[G],Ne=ce&&ae&&ae[G];if(be||ge){var Ce=P.props.activeIndex!==void 0?P.props.activeIndex:G;return[N.cloneElement(P,Br(Br(Br({},L.props),Ie),{},{activeIndex:Ce})),null,null]}if(!Ml(Be))return[Me].concat(j$(T.renderActivePoints({item:L,activePoint:Be,basePoint:Ne,childIndex:G,isRange:ce})))}else{var Fe,Ae=(Fe=T.getItemByXY(T.state.activeCoordinate))!==null&&Fe!==void 0?Fe:{graphicalItem:Me},Xe=Ae.graphicalItem,$e=Xe.item,Ye=$e===void 0?P:$e,Je=Xe.childIndex,Ke=Br(Br(Br({},L.props),Ie),{},{activeIndex:Je});return[N.cloneElement(Ye,Ke),null,null]}return ce?[Me,null,null]:[Me,null]}),el(T,"renderCustomized",function(P,I,M){return N.cloneElement(P,Br(Br({key:"recharts-customized-".concat(M)},T.props),T.state))}),el(T,"renderMap",{CartesianGrid:{handler:Kse,once:!0},ReferenceArea:{handler:T.renderReferenceElement},ReferenceLine:{handler:Kse},ReferenceDot:{handler:T.renderReferenceElement},XAxis:{handler:Kse},YAxis:{handler:Kse},Brush:{handler:T.renderBrush,once:!0},Bar:{handler:T.renderGraphicChild},Line:{handler:T.renderGraphicChild},Area:{handler:T.renderGraphicChild},Radar:{handler:T.renderGraphicChild},RadialBar:{handler:T.renderGraphicChild},Scatter:{handler:T.renderGraphicChild},Pie:{handler:T.renderGraphicChild},Funnel:{handler:T.renderGraphicChild},Tooltip:{handler:T.renderCursor,once:!0},PolarGrid:{handler:T.renderPolarGrid,once:!0},PolarAngleAxis:{handler:T.renderPolarAxis},PolarRadiusAxis:{handler:T.renderPolarAxis},Customized:{handler:T.renderCustomized}}),T.clipPathId="".concat((k=b.id)!==null&&k!==void 0?k:MU("recharts"),"-clip"),T.throttleTriggeredAfterMouseMove=bMt(T.triggeredAfterMouseMove,(A=b.throttleDelay)!==null&&A!==void 0?A:1e3/60),T.state={},T}return Rdn(_,x),Ldn(_,[{key:"componentDidMount",value:function(){var k,A;this.addListener(),this.accessibilityManager.setDetails({container:this.container,offset:{left:(k=this.props.margin.left)!==null&&k!==void 0?k:0,top:(A=this.props.margin.top)!==null&&A!==void 0?A:0},coordinateList:this.state.tooltipTicks,mouseHandlerCallback:this.triggeredAfterMouseMove,layout:this.props.layout}),this.displayDefaultTooltip()}},{key:"displayDefaultTooltip",value:function(){var k=this.props,A=k.children,T=k.data,P=k.height,I=k.layout,M=h_(A,Vx);if(M){var L=M.props.defaultIndex;if(!(typeof L!="number"||L<0||L>this.state.tooltipTicks.length-1)){var z=this.state.tooltipTicks[L]&&this.state.tooltipTicks[L].value,$=r7e(this.state,T,L,z),V=this.state.tooltipTicks[L].coordinate,W=(this.state.offset.top+P)/2,G=I==="horizontal",X=G?{x:V,y:W}:{y:V,x:W},te=this.state.formattedGraphicalItems.find(function(me){var ue=me.item;return ue.type.name==="Scatter"});te&&(X=Br(Br({},X),te.props.points[L].tooltipPosition),$=te.props.points[L].tooltipPayload);var ne={activeTooltipIndex:L,isTooltipActive:!0,activeLabel:z,activePayload:$,activeCoordinate:X};this.setState(ne),this.renderCursor(M),this.accessibilityManager.setIndex(L)}}}},{key:"getSnapshotBeforeUpdate",value:function(k,A){if(!this.props.accessibilityLayer)return null;if(this.state.tooltipTicks!==A.tooltipTicks&&this.accessibilityManager.setDetails({coordinateList:this.state.tooltipTicks}),this.props.layout!==k.layout&&this.accessibilityManager.setDetails({layout:this.props.layout}),this.props.margin!==k.margin){var T,P;this.accessibilityManager.setDetails({offset:{left:(T=this.props.margin.left)!==null&&T!==void 0?T:0,top:(P=this.props.margin.top)!==null&&P!==void 0?P:0}})}return null}},{key:"componentDidUpdate",value:function(k){POe([h_(k.children,Vx)],[h_(this.props.children,Vx)])||this.displayDefaultTooltip()}},{key:"componentWillUnmount",value:function(){this.removeListener(),this.throttleTriggeredAfterMouseMove.cancel()}},{key:"getTooltipEventType",value:function(){var k=h_(this.props.children,Vx);if(k&&typeof k.props.shared=="boolean"){var A=k.props.shared?"axis":"item";return o.indexOf(A)>=0?A:i}return i}},{key:"getMouseInfo",value:function(k){if(!this.container)return null;var A=this.container,T=A.getBoundingClientRect(),P=YZs(T),I={chartX:Math.round(k.pageX-P.left),chartY:Math.round(k.pageY-P.top)},M=T.width/A.offsetWidth||1,L=this.inRange(I.chartX,I.chartY,M);if(!L)return null;var z=this.state,$=z.xAxisMap,V=z.yAxisMap,W=this.getTooltipEventType(),G=zut(this.state,this.props.data,this.props.layout,L);if(W!=="axis"&&$&&V){var X=pA($).scale,te=pA(V).scale,ne=X&&X.invert?X.invert(I.chartX):null,me=te&&te.invert?te.invert(I.chartY):null;return Br(Br({},I),{},{xValue:ne,yValue:me},G)}return G?Br(Br({},I),G):null}},{key:"inRange",value:function(k,A){var T=arguments.length>2&&arguments[2]!==void 0?arguments[2]:1,P=this.props.layout,I=k/T,M=A/T;if(P==="horizontal"||P==="vertical"){var L=this.state.offset,z=I>=L.left&&I<=L.left+L.width&&M>=L.top&&M<=L.top+L.height;return z?{x:I,y:M}:null}var $=this.state,V=$.angleAxisMap,W=$.radiusAxisMap;if(V&&W){var G=pA(V);return ddt({x:I,y:M},G)}return null}},{key:"parseEventsOfWrapper",value:function(){var k=this.props.children,A=this.getTooltipEventType(),T=h_(k,Vx),P={};T&&A==="axis"&&(T.props.trigger==="click"?P={onClick:this.handleClick}:P={onMouseEnter:this.handleMouseEnter,onDoubleClick:this.handleDoubleClick,onMouseMove:this.handleMouseMove,onMouseLeave:this.handleMouseLeave,onTouchMove:this.handleTouchMove,onTouchStart:this.handleTouchStart,onTouchEnd:this.handleTouchEnd,onContextMenu:this.handleContextMenu});var I=gke(this.props,this.handleOuterEvent);return Br(Br({},I),P)}},{key:"addListener",value:function(){BLe.on($Le,this.handleReceiveSyncEvent)}},{key:"removeListener",value:function(){BLe.removeListener($Le,this.handleReceiveSyncEvent)}},{key:"filterFormatItem",value:function(k,A,T){for(var P=this.state.formattedGraphicalItems,I=0,M=P.length;I{const{data:b,error:k}=await H.from("email_campaigns").select("*").eq("status","sent").order("sent_at",{ascending:!0});if(k)throw k;return b}}),{data:r}=mt({queryKey:["campaign-agent-profiles"],queryFn:async()=>{const{data:b,error:k}=await H.from("profiles").select("id, name, email");if(k)throw k;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,k)=>b+(k.sent_count||0),0),o=a.reduce((b,k)=>b+(k.open_count||0),0),c=a.reduce((b,k)=>b+(k.click_count||0),0),d=a.reduce((b,k)=>b+(k.bounce_count||0),0),u=a.reduce((b,k)=>b+(k.complaint_count||0),0),h=l>0?(o/l*100).toFixed(1):"0.0",m=l>0?(c/l*100).toFixed(1):"0.0",f=[{label:"Campaigns Sent",value:a.length,icon:Rr,color:"text-foreground"},{label:"Total Emails Sent",value:l,icon:Yn,color:"text-green-600"},{label:"Avg Open Rate",value:`${h}%`,icon:da,color:"text-blue-600"},{label:"Avg Click Rate",value:`${m}%`,icon:Qg,color:"text-purple-600"},{label:"Total Bounces",value:d,icon:xd,color:"text-orange-600"},{label:"Complaints",value:u,icon:ml,color:"text-destructive"}],g=new Map;a.forEach(b=>{var T,P;const k=b.user_id,A=g.get(k)||{name:((T=i.get(k))==null?void 0:T.name)||((P=i.get(k))==null?void 0:P.email)||"Unknown",campaigns:0,sent:0,opens:0,clicks:0};A.campaigns++,A.sent+=b.sent_count||0,A.opens+=b.open_count||0,A.clicks+=b.click_count||0,g.set(k,A)});const y=[...g.entries()].map(([b,k])=>({id:b,...k,openRate:k.sent>0?+(k.opens/k.sent*100).toFixed(1):0})).sort((b,k)=>k.sent-b.sent),x=y.slice(0,6).map(b=>({name:b.name,value:b.sent})),_=a.map(b=>{var k;return{name:b.name.length>20?b.name.slice(0,20)+"…":b.name,agent:((k=i.get(b.user_id))==null?void 0:k.name)||"Unknown",openRate:b.sent_count>0?+(b.open_count/b.sent_count*100).toFixed(1):0,clickRate:b.sent_count>0?+(b.click_count/b.sent_count*100).toFixed(1):0,sent:b.sent_count,date:b.sent_at?Js(new Date(b.sent_at),"MMM d"):""}});return e.jsx("div",{className:"space-y-6",children:a.length===0?e.jsx(_e,{children:e.jsxs(De,{className:"flex flex-col items-center justify-center py-12 text-center",children:[e.jsx(Rr,{className:"h-12 w-12 text-muted-foreground mb-4"}),e.jsx("h3",{className:"text-lg font-semibold mb-1",children:"No campaigns sent yet"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Campaign analytics will appear here after the first send."})]})}):e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"grid grid-cols-2 md:grid-cols-3 lg:grid-cols-6 gap-3",children:f.map(b=>e.jsx(_e,{children:e.jsxs(De,{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(_e,{children:[e.jsx(zt,{children:e.jsx(qt,{className:"text-base",children:"Open & Click Rates by Campaign"})}),e.jsx(De,{children:e.jsx("div",{className:"h-[280px]",children:e.jsx(b5,{width:"100%",height:"100%",children:e.jsxs(rGe,{data:_,children:[e.jsx(R5,{dataKey:"date",fontSize:11}),e.jsx(O5,{fontSize:11,unit:"%"}),e.jsx(Vx,{formatter:b=>`${b}%`}),e.jsx(D5,{dataKey:"openRate",fill:"hsl(220, 70%, 50%)",name:"Open Rate",radius:[2,2,0,0]}),e.jsx(D5,{dataKey:"clickRate",fill:"hsl(270, 70%, 50%)",name:"Click Rate",radius:[2,2,0,0]})]})})})})]}),e.jsxs(_e,{children:[e.jsx(zt,{children:e.jsx(qt,{className:"text-base",children:"Send Volume by Agent"})}),e.jsx(De,{children:e.jsx("div",{className:"h-[280px]",children:e.jsx(b5,{width:"100%",height:"100%",children:e.jsxs(aGe,{children:[e.jsx(jN,{data:x,dataKey:"value",nameKey:"name",cx:"50%",cy:"50%",outerRadius:100,label:({name:b,percent:k})=>`${b} (${(k*100).toFixed(0)}%)`,fontSize:11,children:x.map((b,k)=>e.jsx(DU,{fill:Uut[k%Uut.length]},k))}),e.jsx(Vx,{})]})})})})]})]}),e.jsxs(_e,{children:[e.jsx(zt,{children:e.jsx(qt,{className:"text-base",children:"Send Volume Trend"})}),e.jsx(De,{children:e.jsx("div",{className:"h-[240px]",children:e.jsx(b5,{width:"100%",height:"100%",children:e.jsxs(nGe,{data:_,children:[e.jsx(R5,{dataKey:"date",fontSize:11}),e.jsx(O5,{fontSize:11}),e.jsx(Vx,{}),e.jsx(eO,{type:"monotone",dataKey:"sent",stroke:"hsl(142, 71%, 45%)",strokeWidth:2,name:"Emails Sent",dot:{r:4}})]})})})})]}),e.jsxs(_e,{children:[e.jsx(zt,{children:e.jsx(qt,{className:"text-base",children:"Agent Performance"})}),e.jsx(De,{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(We,{variant:"outline",children:[b.openRate,"%"]})})]},b.id))})]})})})]}),e.jsxs(_e,{children:[e.jsx(zt,{children:e.jsx(qt,{className:"text-base",children:"Campaign Leaderboard"})}),e.jsx(De,{children:e.jsx("div",{className:"space-y-2",children:[...a].sort((b,k)=>{const A=b.sent_count>0?b.open_count/b.sent_count:0;return(k.sent_count>0?k.open_count/k.sent_count:0)-A}).slice(0,10).map((b,k)=>{const A=b.sent_count>0?(b.open_count/b.sent_count*100).toFixed(1):"0.0",T=b.sent_count>0?(b.click_count/b.sent_count*100).toFixed(1):"0.0",P=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:["#",k+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:[(P==null?void 0:P.name)||"Unknown"," · ",b.sent_at?Js(new Date(b.sent_at),"MMM d, yyyy"):""," · ",b.sent_count," sent"]})]}),e.jsxs("div",{className:"flex gap-3 text-xs",children:[e.jsxs(We,{variant:"outline",className:"gap-1",children:[e.jsx(da,{className:"h-3 w-3"})," ",A,"%"]}),e.jsxs(We,{variant:"outline",className:"gap-1",children:[e.jsx(Qg,{className:"h-3 w-3"})," ",T,"%"]})]})]},b.id)})})})]})]})})}const Jdn=()=>{const{toast:s}=Ci(),[t,n]=N.useState(!0),[r,a]=N.useState([]),[i,l]=N.useState([]),[o,c]=N.useState({installs:0,activeAgents:0,impressions30d:0,leads30d:0});N.useEffect(()=>{d()},[]);const d=async()=>{try{n(!0);const u=new Date;u.setDate(u.getDate()-30);const h=u.toISOString(),{data:m}=await H.from("website_apps").select("slug, name").order("sort_order"),f=[];let g=0;for(;;){const{data:T,error:P}=await H.from("agent_website_app_installs").select("user_id, app_slug, enabled").range(g,g+999);if(P)throw P;if(f.push(...T||[]),!T||T.length<1e3)break;g+=1e3}const y=[];for(g=0;;){const{data:T,error:P}=await H.from("widget_events").select("user_id, app_slug, event_type, created_at").gte("created_at",h).order("created_at",{ascending:!1}).range(g,g+999);if(P)throw P;if(y.push(...T||[]),!T||T.length<1e3||(g+=1e3,g>2e4))break}const x=new Map;for(const T of m||[])x.set(T.slug,{app_slug:T.slug,app_name:T.name,installs:0,enabled:0,impressions:0,expands:0,cta_clicks:0,lead_captures:0});for(const T of f){const P=x.get(T.app_slug);P&&(P.installs+=1,T.enabled&&(P.enabled+=1))}for(const T of y){const P=x.get(T.app_slug);P&&(T.event_type==="impression"?P.impressions+=1:T.event_type==="expand"?P.expands+=1:T.event_type==="cta_click"?P.cta_clicks+=1:T.event_type==="lead_capture"&&(P.lead_captures+=1))}const _=new Map;for(const T of f){if(!T.enabled)continue;const P=_.get(T.user_id)||{user_id:T.user_id,name:null,email:null,apps_enabled:[],events_30d:0,leads_30d:0};P.apps_enabled.includes(T.app_slug)||P.apps_enabled.push(T.app_slug),_.set(T.user_id,P)}for(const T of y){const P=_.get(T.user_id);P&&(P.events_30d+=1,T.event_type==="lead_capture"&&(P.leads_30d+=1))}const b=Array.from(_.keys());if(b.length>0){const{data:T}=await H.from("profiles").select("id, name, email").in("id",b);for(const P of T||[]){const I=_.get(P.id);I&&(I.name=P.name,I.email=P.email)}}const k=Array.from(x.values()),A=Array.from(_.values()).sort((T,P)=>P.events_30d-T.events_30d);a(k),l(A),c({installs:k.reduce((T,P)=>T+P.enabled,0),activeAgents:A.length,impressions30d:k.reduce((T,P)=>T+P.impressions,0),leads30d:k.reduce((T,P)=>T+P.lead_captures,0)})}catch(u){console.error(u),s({title:"Error",description:u.message||"Failed to load website app analytics",variant:"destructive"})}finally{n(!1)}};return t?e.jsx(_e,{children:e.jsx(De,{className:"flex items-center justify-center py-8",children:e.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})})}):e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"grid gap-4 md:grid-cols-2 lg:grid-cols-4",children:[e.jsxs(_e,{children:[e.jsxs(zt,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(qt,{className:"text-sm font-medium",children:"Active Installs"}),e.jsx(au,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(De,{children:[e.jsx("div",{className:"text-2xl font-bold",children:o.installs}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Apps turned on across all agents"})]})]}),e.jsxs(_e,{children:[e.jsxs(zt,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(qt,{className:"text-sm font-medium",children:"Agents Using Apps"}),e.jsx(Yn,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(De,{children:[e.jsx("div",{className:"text-2xl font-bold",children:o.activeAgents}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"At least one app enabled"})]})]}),e.jsxs(_e,{children:[e.jsxs(zt,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(qt,{className:"text-sm font-medium",children:"Impressions (30d)"}),e.jsx(da,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(De,{children:[e.jsx("div",{className:"text-2xl font-bold",children:o.impressions30d}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Widget views on lead sites"})]})]}),e.jsxs(_e,{children:[e.jsxs(zt,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(qt,{className:"text-sm font-medium",children:"Leads Captured (30d)"}),e.jsx(mn,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(De,{children:[e.jsx("div",{className:"text-2xl font-bold",children:o.leads30d}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Total submissions"})]})]})]}),e.jsxs(_e,{children:[e.jsx(zt,{children:e.jsx(qt,{children:"App Performance (last 30 days)"})}),e.jsx(De,{children:e.jsxs(Oa,{children:[e.jsx(Fa,{children:e.jsxs(un,{children:[e.jsx(Mt,{children:"App"}),e.jsx(Mt,{className:"text-right",children:"Installs"}),e.jsx(Mt,{className:"text-right",children:"Enabled"}),e.jsx(Mt,{className:"text-right",children:"Impressions"}),e.jsx(Mt,{className:"text-right",children:"Expands"}),e.jsx(Mt,{className:"text-right",children:"CTA Clicks"}),e.jsx(Mt,{className:"text-right",children:"Leads"}),e.jsx(Mt,{className:"text-right",children:"Conv. Rate"})]})}),e.jsxs(za,{children:[r.map(u=>{const h=u.impressions>0?(u.lead_captures/u.impressions*100).toFixed(1):"—";return e.jsxs(un,{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(un,{children:e.jsx(gt,{colSpan:8,className:"text-center text-muted-foreground py-6",children:"No data yet"})})]})]})})]}),e.jsxs(_e,{children:[e.jsx(zt,{children:e.jsx(qt,{children:"Agent Usage (last 30 days)"})}),e.jsxs(De,{children:[e.jsxs(Oa,{children:[e.jsx(Fa,{children:e.jsxs(un,{children:[e.jsx(Mt,{children:"Agent"}),e.jsx(Mt,{children:"Email"}),e.jsx(Mt,{children:"Apps Enabled"}),e.jsx(Mt,{className:"text-right",children:"Events (30d)"}),e.jsx(Mt,{className:"text-right",children:"Leads (30d)"})]})}),e.jsxs(za,{children:[i.slice(0,100).map(u=>e.jsxs(un,{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(We,{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(un,{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."]})]})]})]})},eun=()=>{const[s,t]=N.useState([]),[n,r]=N.useState([]),[a,i]=N.useState({}),[l,o]=N.useState(!0);N.useEffect(()=>{c()},[]);const c=async()=>{o(!0);try{const[{data:h},{data:m}]=await Promise.all([H.rpc("get_extension_usage_summary"),H.from("extension_usage_events").select("id, user_id, action, metadata, created_at").order("created_at",{ascending:!1}).limit(50)]),f=h||[],g=m||[];t(f),r(g);const y=Array.from(new Set(g.map(x=>x.user_id)));if(y.length){const{data:x}=await H.from("profiles").select("id, name, email").in("id",y),_={};(x||[]).forEach(b=>{_[b.id]={name:b.name,email:b.email}}),i(_)}}finally{o(!1)}},d=s.reduce((h,m)=>({users:h.users+1,contacts:h.contacts+Number(m.contacts_saved||0),listings:h.listings+Number(m.listings_imported||0),activities:h.activities+Number(m.activities_logged||0),events:h.events+Number(m.total_events||0)}),{users:0,contacts:0,listings:0,activities:0,events:0});if(l)return e.jsx(_e,{children:e.jsx(De,{className:"flex items-center justify-center py-8",children:e.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})})});const u=h=>{switch(h){case"contact_saved":return"Contact saved";case"listing_imported":return"Listing imported";case"activity_logged":return"Activity logged";case"template_used":return"Template used";case"paired":return"Extension paired";default:return h}};return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"grid gap-4 md:grid-cols-2 lg:grid-cols-5",children:[e.jsxs(_e,{children:[e.jsxs(zt,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(qt,{className:"text-sm font-medium",children:"Active Users"}),e.jsx(Yn,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(De,{children:[e.jsx("div",{className:"text-2xl font-bold",children:d.users}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Using extension"})]})]}),e.jsxs(_e,{children:[e.jsxs(zt,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(qt,{className:"text-sm font-medium",children:"Total Actions"}),e.jsx(lD,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(De,{children:[e.jsx("div",{className:"text-2xl font-bold",children:d.events}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"All events"})]})]}),e.jsxs(_e,{children:[e.jsxs(zt,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(qt,{className:"text-sm font-medium",children:"Contacts Saved"}),e.jsx(Yl,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsx(De,{children:e.jsx("div",{className:"text-2xl font-bold",children:d.contacts})})]}),e.jsxs(_e,{children:[e.jsxs(zt,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(qt,{className:"text-sm font-medium",children:"Listings Imported"}),e.jsx(_a,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsx(De,{children:e.jsx("div",{className:"text-2xl font-bold",children:d.listings})})]}),e.jsxs(_e,{children:[e.jsxs(zt,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(qt,{className:"text-sm font-medium",children:"Activities Logged"}),e.jsx(xo,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsx(De,{children:e.jsx("div",{className:"text-2xl font-bold",children:d.activities})})]})]}),e.jsxs(_e,{children:[e.jsx(zt,{children:e.jsx(qt,{children:"Users by Extension Activity"})}),e.jsx(De,{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(Oa,{children:[e.jsx(Fa,{children:e.jsxs(un,{children:[e.jsx(Mt,{children:"User"}),e.jsx(Mt,{className:"text-right",children:"Total"}),e.jsx(Mt,{className:"text-right",children:"Contacts"}),e.jsx(Mt,{className:"text-right",children:"Listings"}),e.jsx(Mt,{className:"text-right",children:"Activities"}),e.jsx(Mt,{children:"First Used"}),e.jsx(Mt,{children:"Last Used"})]})}),e.jsx(za,{children:s.map(h=>e.jsxs(un,{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?Js(new Date(h.first_event_at),"MMM d, yyyy"):"—"}),e.jsx(gt,{className:"text-xs text-muted-foreground",children:h.last_event_at?Js(new Date(h.last_event_at),"MMM d, h:mm a"):"—"})]},h.user_id))})]})})})]}),e.jsxs(_e,{children:[e.jsx(zt,{children:e.jsx(qt,{children:"Recent Activity"})}),e.jsx(De,{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(We,{variant:"secondary",children:u(h.action)}),e.jsxs("div",{children:[e.jsx("div",{className:"text-sm font-medium",children:(m==null?void 0:m.name)||(m==null?void 0:m.email)||h.user_id.slice(0,8)}),h.metadata&&Object.keys(h.metadata).length>0&&e.jsx("div",{className:"text-xs text-muted-foreground truncate max-w-md",children:JSON.stringify(h.metadata)})]})]}),e.jsx("div",{className:"text-xs text-muted-foreground",children:Js(new Date(h.created_at),"MMM d, h:mm a")})]},h.id)})})})]})]})},tun=()=>e.jsx(Qs,{title:"Analytics",children:e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl font-bold text-foreground",children:"Analytics & Activity"}),e.jsx("p",{className:"text-muted-foreground mt-1",children:"Platform-wide usage statistics and user activity"})]}),e.jsxs(ya,{defaultValue:"analytics",className:"space-y-4",children:[e.jsxs(va,{children:[e.jsx(ls,{value:"analytics",children:"Analytics"}),e.jsx(ls,{value:"website-apps",children:"Website Apps"}),e.jsx(ls,{value:"extension",children:"Chrome Extension"}),e.jsx(ls,{value:"content",children:"Content"}),e.jsx(ls,{value:"email-campaigns",children:"Email Campaigns"}),e.jsx(ls,{value:"activity",children:"Activity"}),e.jsx(ls,{value:"shares",children:"Shares"})]}),e.jsx(_s,{value:"analytics",className:"space-y-4",children:e.jsx(CFs,{})}),e.jsx(_s,{value:"website-apps",className:"space-y-4",children:e.jsx(Jdn,{})}),e.jsx(_s,{value:"extension",className:"space-y-4",children:e.jsx(eun,{})}),e.jsx(_s,{value:"content",className:"space-y-4",children:e.jsx(TFs,{})}),e.jsx(_s,{value:"email-campaigns",className:"space-y-4",children:e.jsx(Qdn,{})}),e.jsx(_s,{value:"activity",className:"space-y-4",children:e.jsx(SFs,{})}),e.jsx(_s,{value:"shares",className:"space-y-4",children:e.jsx(a6t,{})})]})]})});function sun(){const s=as(),[t,n]=N.useState(!1),[r,a]=N.useState(null),[i,l]=N.useState({title:"",description:"",publish_date:new Date().toISOString().split("T")[0],is_published:!1,category_id:""}),[o,c]=N.useState(null),[d,u]=N.useState(""),[h,m]=N.useState([]),[f,g]=N.useState([]),[y,x]=N.useState([]),[_,b]=N.useState(!1),[k,A]=N.useState(null),[T,P]=N.useState(""),{data:I,isLoading:M}=mt({queryKey:["brokerage-resources"],queryFn:async()=>{const{data:Ne,error:Ge}=await H.from("brokerage_resources").select("*").order("publish_date",{ascending:!1});if(Ge)throw Ge;return Ne}}),{data:L}=mt({queryKey:["brokerage-resource-pdfs"],queryFn:async()=>{const{data:Ne,error:Ge}=await H.from("brokerage_resource_pdfs").select("*").order("sort_order",{ascending:!0});if(Ge)throw Ge;return Ne}}),{data:z}=mt({queryKey:["brokerage-resource-videos"],queryFn:async()=>{const{data:Ne,error:Ge}=await H.from("brokerage_resource_videos").select("*").order("sort_order",{ascending:!0});if(Ge)throw Ge;return Ne}}),{data:$}=mt({queryKey:["brokerage-resource-links"],queryFn:async()=>{const{data:Ne,error:Ge}=await H.from("brokerage_resource_links").select("*").order("sort_order",{ascending:!0});if(Ge)throw Ge;return Ne}}),{data:V,isLoading:W}=mt({queryKey:["brokerage-resource-categories"],queryFn:async()=>{const{data:Ne,error:Ge}=await H.from("brokerage_resource_categories").select("*").order("sort_order",{ascending:!0});if(Ge)throw Ge;return Ne}}),G=()=>{l({title:"",description:"",publish_date:new Date().toISOString().split("T")[0],is_published:!1,category_id:""}),c(null),u(""),m([]),g([]),x([]),a(null),P("")},X=Ne=>{a(Ne),l({title:Ne.title,description:Ne.description||"",publish_date:Ne.publish_date.split("T")[0],is_published:Ne.is_published,category_id:Ne.category_id||""}),u(Ne.preview_image_url||""),P("");const Ge=(L==null?void 0:L.filter(Ae=>Ae.resource_id===Ne.id))||[];m(Ge.map(Ae=>({id:Ae.id,name:Ae.name,file_url:Ae.file_url,file_size:Ae.file_size,sort_order:Ae.sort_order})));const Ce=(z==null?void 0:z.filter(Ae=>Ae.resource_id===Ne.id))||[];g(Ce.map(Ae=>({id:Ae.id,title:Ae.title,video_url:Ae.video_url,sort_order:Ae.sort_order})));const Fe=($==null?void 0:$.filter(Ae=>Ae.resource_id===Ne.id))||[];x(Fe.map(Ae=>({id:Ae.id,title:Ae.title,canva_share_link:Ae.canva_share_link,sort_order:Ae.sort_order}))),n(!0)},te=Ne=>{var Ce;const Ge=(Ce=Ne.target.files)==null?void 0:Ce[0];Ge&&(c(Ge),u(URL.createObjectURL(Ge)))},ne=()=>{m([...h,{name:"",file_url:"",sort_order:h.length}])},me=Ne=>{m(h.filter((Ge,Ce)=>Ce!==Ne))},ue=(Ne,Ge,Ce)=>{const Fe=[...h];if(Ge==="file"&&Ce instanceof File){const Ae=Ce.name.replace(/\.[^/.]+$/,"");Fe[Ne]={...Fe[Ne],file:Ce,file_size:Ce.size,name:Fe[Ne].name||Ae}}else Fe[Ne]={...Fe[Ne],[Ge]:Ce};m(Fe)},ce=()=>{g([...f,{title:"",video_url:"",sort_order:f.length}])},ae=Ne=>{g(f.filter((Ge,Ce)=>Ce!==Ne))},he=(Ne,Ge,Ce)=>{const Fe=[...f];Ge==="file"&&Ce instanceof File?Fe[Ne]={...Fe[Ne],file:Ce}:Fe[Ne]={...Fe[Ne],[Ge]:Ce},g(Fe)},xe=()=>{x([...y,{title:"",canva_share_link:"",sort_order:y.length}])},ve=Ne=>{x(y.filter((Ge,Ce)=>Ce!==Ne))},ge=(Ne,Ge,Ce)=>{const Fe=[...y];Fe[Ne]={...Fe[Ne],[Ge]:Ce},x(Fe)},be=async(Ne,Ge)=>{try{const Ce=await H.functions.invoke("bunny-upload",{body:{action:"create",title:Ne.name}});if(Ce.error)throw Ce.error;const{videoId:Fe,uploadUrl:Ae,libraryId:Xe}=Ce.data,$e=await H.functions.invoke("bunny-upload",{body:{action:"upload-url",videoId:Fe,libraryId:Xe}});if($e.error)throw $e.error;const{uploadUrl:Ye,apiKey:Je}=$e.data,Ke=new XMLHttpRequest;return Ke.open("PUT",Ye,!0),Ke.setRequestHeader("AccessKey",Je),Ke.upload.onprogress=st=>{if(st.lengthComputable){const rt=Math.round(st.loaded/st.total*100),Ze=[...f];Ze[Ge]={...Ze[Ge],uploadProgress:rt},g(Ze)}},await new Promise((st,rt)=>{Ke.onload=()=>Ke.status>=200&&Ke.status<300?st():rt(new Error("Upload failed")),Ke.onerror=()=>rt(new Error("Upload failed")),Ke.send(Ne)}),`https://iframe.mediadelivery.net/embed/${Xe}/${Fe}`}catch(Ce){throw console.error("Bunny upload error:",Ce),Ce}},Se=_t({mutationFn:async Ne=>{const{data:Ge,error:Ce}=await H.from("brokerage_resource_categories").insert({name:Ne,sort_order:(V==null?void 0:V.length)||0}).select().single();if(Ce)throw Ce;return Ge},onSuccess:Ne=>{s.invalidateQueries({queryKey:["brokerage-resource-categories"]}),l({...i,category_id:Ne.id}),P(""),ie.success("Category created")},onError:Ne=>{ie.error("Failed to create category: "+Ne.message)}}),Ie=_t({mutationFn:async()=>{b(!0);let Ne=(r==null?void 0:r.preview_image_url)||null;if(o){const Fe=o.name.split(".").pop(),Ae=`${Date.now()}.${Fe}`,{error:Xe}=await H.storage.from("brokerage-resources").upload(`previews/${Ae}`,o);if(Xe)throw Xe;const{data:$e}=H.storage.from("brokerage-resources").getPublicUrl(`previews/${Ae}`);Ne=$e.publicUrl}const Ge={title:i.title,description:i.description||null,preview_image_url:Ne,publish_date:i.publish_date,is_published:i.is_published,category_id:i.category_id||null};let Ce;if(r){const{error:Fe}=await H.from("brokerage_resources").update(Ge).eq("id",r.id);if(Fe)throw Fe;Ce=r.id;const Ae=(L==null?void 0:L.filter(ht=>ht.resource_id===r.id).map(ht=>ht.id))||[],Xe=h.filter(ht=>ht.id).map(ht=>ht.id),$e=Ae.filter(ht=>!Xe.includes(ht));$e.length>0&&await H.from("brokerage_resource_pdfs").delete().in("id",$e);const Ye=(z==null?void 0:z.filter(ht=>ht.resource_id===r.id).map(ht=>ht.id))||[],Je=f.filter(ht=>ht.id).map(ht=>ht.id),Ke=Ye.filter(ht=>!Je.includes(ht));Ke.length>0&&await H.from("brokerage_resource_videos").delete().in("id",Ke);const st=($==null?void 0:$.filter(ht=>ht.resource_id===r.id).map(ht=>ht.id))||[],rt=y.filter(ht=>ht.id).map(ht=>ht.id),Ze=st.filter(ht=>!rt.includes(ht));Ze.length>0&&await H.from("brokerage_resource_links").delete().in("id",Ze)}else{const{data:Fe,error:Ae}=await H.from("brokerage_resources").insert(Ge).select().single();if(Ae)throw Ae;Ce=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"]}),ie.success(r?"Resource updated":"Resource created"),n(!1),G(),b(!1)},onError:Ne=>{ie.error("Failed to save resource: "+Ne.message),b(!1)}}),Me=_t({mutationFn:async Ne=>{const{error:Ge}=await H.from("brokerage_resources").delete().eq("id",Ne);if(Ge)throw Ge},onSuccess:()=>{s.invalidateQueries({queryKey:["brokerage-resources"]}),s.invalidateQueries({queryKey:["brokerage-resource-pdfs"]}),s.invalidateQueries({queryKey:["brokerage-resource-videos"]}),s.invalidateQueries({queryKey:["brokerage-resource-links"]}),ie.success("Resource deleted")},onError:Ne=>{ie.error("Failed to delete: "+Ne.message)}}),Re=Ne=>{if(Ne.preventDefault(),!i.title){ie.error("Please enter a title");return}Ie.mutate()},Be=Ne=>{const Ge=(L==null?void 0:L.filter(Ae=>Ae.resource_id===Ne).length)||0,Ce=(z==null?void 0:z.filter(Ae=>Ae.resource_id===Ne).length)||0,Fe=($==null?void 0:$.filter(Ae=>Ae.resource_id===Ne).length)||0;return{pdfCount:Ge,videoCount:Ce,linkCount:Fe}};return e.jsx(Qs,{title:"Brokerage Resources Management",description:"Create and manage resources for brokerage managers",children:e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex justify-between items-center",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs(_e,{children:[e.jsx(zt,{className:"pb-2",children:e.jsx(qt,{className:"text-sm font-medium text-muted-foreground",children:"Total Resources"})}),e.jsx(De,{children:e.jsx("div",{className:"text-2xl font-bold",children:(I==null?void 0:I.length)||0})})]}),e.jsxs(_e,{children:[e.jsx(zt,{className:"pb-2",children:e.jsx(qt,{className:"text-sm font-medium text-muted-foreground",children:"Published"})}),e.jsx(De,{children:e.jsx("div",{className:"text-2xl font-bold",children:(I==null?void 0:I.filter(Ne=>Ne.is_published).length)||0})})]})]}),e.jsxs(B,{onClick:()=>{G(),n(!0)},children:[e.jsx(nn,{className:"h-4 w-4 mr-2"}),"Add Resource"]})]}),e.jsx(_e,{children:e.jsx(De,{className:"p-0",children:e.jsxs(Oa,{children:[e.jsx(Fa,{children:e.jsxs(un,{children:[e.jsx(Mt,{children:"Title"}),e.jsx(Mt,{children:"Category"}),e.jsx(Mt,{children:"Content"}),e.jsx(Mt,{children:"Publish Date"}),e.jsx(Mt,{children:"Status"}),e.jsx(Mt,{className:"text-right",children:"Actions"})]})}),e.jsx(za,{children:M?e.jsx(un,{children:e.jsx(gt,{colSpan:6,className:"text-center py-8",children:"Loading..."})}):(I==null?void 0:I.length)===0?e.jsx(un,{children:e.jsx(gt,{colSpan:6,className:"text-center py-8 text-muted-foreground",children:"No brokerage resources yet. Create your first one!"})}):I==null?void 0:I.map(Ne=>{const{pdfCount:Ge,videoCount:Ce,linkCount:Fe}=Be(Ne.id),Ae=V==null?void 0:V.find(Xe=>Xe.id===Ne.category_id);return e.jsxs(un,{children:[e.jsx(gt,{children:e.jsxs("div",{className:"flex items-center gap-3",children:[Ne.preview_image_url?e.jsx("img",{src:Ne.preview_image_url,alt:Ne.title,className:"w-10 h-10 rounded object-cover"}):e.jsx("div",{className:"w-10 h-10 rounded bg-muted flex items-center justify-center",children:e.jsx(vg,{className:"h-5 w-5 text-muted-foreground"})}),e.jsxs("div",{children:[e.jsx("div",{className:"font-medium",children:Ne.title}),Ne.description&&e.jsx("div",{className:"text-sm text-muted-foreground line-clamp-1",children:Ne.description})]})]})}),e.jsx(gt,{children:Ae?e.jsx("span",{className:"inline-flex items-center px-2 py-1 rounded-full text-xs font-medium bg-muted",children:Ae.name}):e.jsx("span",{className:"text-muted-foreground text-sm",children:"—"})}),e.jsx(gt,{children:e.jsxs("div",{className:"flex items-center gap-3 text-sm text-muted-foreground",children:[e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Wr,{className:"h-3.5 w-3.5"}),Ge]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(na,{className:"h-3.5 w-3.5"}),Ce]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(gc,{className:"h-3.5 w-3.5"}),Fe]})]})}),e.jsx(gt,{children:Js(new Date(Ne.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 ${Ne.is_published?"bg-green-100 text-green-800":"bg-yellow-100 text-yellow-800"}`,children:Ne.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 Xe=(L==null?void 0:L.filter(Je=>Je.resource_id===Ne.id))||[],$e=(z==null?void 0:z.filter(Je=>Je.resource_id===Ne.id))||[],Ye=($==null?void 0:$.filter(Je=>Je.resource_id===Ne.id))||[];A({...Ne,pdfs:Xe,videos:$e,links:Ye})},children:e.jsx(da,{className:"h-4 w-4"})}),e.jsx(B,{variant:"ghost",size:"icon",onClick:()=>X(Ne),children:e.jsx(Ja,{className:"h-4 w-4"})}),e.jsx(B,{variant:"ghost",size:"icon",onClick:()=>{confirm("Delete this resource?")&&Me.mutate(Ne.id)},children:e.jsx(qn,{className:"h-4 w-4 text-destructive"})})]})})]},Ne.id)})})]})})}),e.jsx(Bs,{open:t,onOpenChange:n,children:e.jsxs(Fs,{className:"max-w-3xl max-h-[90vh] overflow-y-auto",children:[e.jsx(qs,{children:e.jsx($s,{children:r?"Edit Brokerage Resource":"Add Brokerage Resource"})}),e.jsxs("form",{onSubmit:Re,className:"space-y-6",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{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(vg,{className:"h-8 w-8 text-muted-foreground"})}),e.jsx(we,{type:"file",accept:"image/*",onChange:te})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{htmlFor:"title",children:"Title *"}),e.jsx(we,{id:"title",value:i.title,onChange:Ne=>l({...i,title:Ne.target.value}),placeholder:"Resource Title"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs(re,{className:"flex items-center gap-2",children:[e.jsx(pf,{className:"h-4 w-4"}),"Category"]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(Ns,{value:i.category_id,onValueChange:Ne=>l({...i,category_id:Ne}),children:[e.jsx(ws,{className:"flex-1",children:e.jsx(ks,{placeholder:"Select a category"})}),e.jsx(js,{children:V==null?void 0:V.map(Ne=>e.jsx(nt,{value:Ne.id,children:Ne.name},Ne.id))})]}),i.category_id&&e.jsx(B,{type:"button",variant:"ghost",size:"icon",onClick:()=>l({...i,category_id:""}),children:e.jsx(hr,{className:"h-4 w-4"})})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(we,{placeholder:"Or create new category...",value:T,onChange:Ne=>P(Ne.target.value),className:"flex-1"}),e.jsxs(B,{type:"button",variant:"outline",size:"sm",disabled:!T.trim()||Se.isPending,onClick:()=>Se.mutate(T.trim()),children:[e.jsx(nn,{className:"h-4 w-4 mr-1"}),"Add"]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{children:"Description"}),e.jsx(yN,{content:i.description,onChange:Ne=>l({...i,description:Ne}),placeholder:"Brief description of this resource",minHeight:"120px"})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{htmlFor:"publish_date",children:"Publish Date"}),e.jsx(we,{id:"publish_date",type:"date",value:i.publish_date,onChange:Ne=>l({...i,publish_date:Ne.target.value})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{children:"Published"}),e.jsxs("div",{className:"flex items-center space-x-2 pt-2",children:[e.jsx(zn,{checked:i.is_published,onCheckedChange:Ne=>l({...i,is_published:Ne})}),e.jsx("span",{className:"text-sm text-muted-foreground",children:i.is_published?"Visible to brokerage managers":"Hidden from brokerage managers"})]})]})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs(re,{className:"flex items-center gap-2",children:[e.jsx(Wr,{className:"h-4 w-4"}),"PDF Documents (",h.length,")"]}),e.jsxs(B,{type:"button",variant:"outline",size:"sm",onClick:ne,children:[e.jsx(nn,{className:"h-4 w-4 mr-1"}),"Add PDF"]})]}),h.map((Ne,Ge)=>e.jsxs("div",{className:"flex items-center gap-2 p-3 border rounded-lg bg-muted/50",children:[e.jsx(we,{placeholder:"PDF Name",value:Ne.name,onChange:Ce=>ue(Ge,"name",Ce.target.value),className:"flex-1"}),e.jsx(we,{type:"file",accept:".pdf",onChange:Ce=>{var Ae;const Fe=(Ae=Ce.target.files)==null?void 0:Ae[0];Fe&&ue(Ge,"file",Fe)},className:"flex-1"}),Ne.file_url&&!Ne.file&&e.jsx("span",{className:"text-xs text-muted-foreground",children:"Uploaded"}),e.jsx(B,{type:"button",variant:"ghost",size:"icon",onClick:()=>me(Ge),children:e.jsx(hr,{className:"h-4 w-4"})})]},Ge))]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs(re,{className:"flex items-center gap-2",children:[e.jsx(na,{className:"h-4 w-4"}),"Videos (",f.length,")"]}),e.jsxs(B,{type:"button",variant:"outline",size:"sm",onClick:ce,children:[e.jsx(nn,{className:"h-4 w-4 mr-1"}),"Add Video"]})]}),f.map((Ne,Ge)=>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(we,{placeholder:"Video Title",value:Ne.title,onChange:Ce=>he(Ge,"title",Ce.target.value),className:"flex-1"}),e.jsx(B,{type:"button",variant:"ghost",size:"icon",onClick:()=>ae(Ge),children:e.jsx(hr,{className:"h-4 w-4"})})]}),e.jsx(we,{type:"file",accept:"video/*",onChange:Ce=>{var Ae;const Fe=(Ae=Ce.target.files)==null?void 0:Ae[0];Fe&&he(Ge,"file",Fe)}}),Ne.uploadProgress!==void 0&&Ne.uploadProgress>0&&e.jsx("div",{className:"w-full bg-muted rounded-full h-2",children:e.jsx("div",{className:"bg-primary h-2 rounded-full transition-all",style:{width:`${Ne.uploadProgress}%`}})}),Ne.video_url&&!Ne.file&&e.jsx("span",{className:"text-xs text-muted-foreground",children:"Video uploaded"})]},Ge))]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs(re,{className:"flex items-center gap-2",children:[e.jsx(gc,{className:"h-4 w-4"}),"Canva Links (",y.length,")"]}),e.jsxs(B,{type:"button",variant:"outline",size:"sm",onClick:xe,children:[e.jsx(nn,{className:"h-4 w-4 mr-1"}),"Add Link"]})]}),y.map((Ne,Ge)=>e.jsxs("div",{className:"flex items-center gap-2 p-3 border rounded-lg bg-muted/50",children:[e.jsx(we,{placeholder:"Link Title",value:Ne.title,onChange:Ce=>ge(Ge,"title",Ce.target.value),className:"flex-1"}),e.jsx(we,{placeholder:"Canva Share Link",value:Ne.canva_share_link,onChange:Ce=>ge(Ge,"canva_share_link",Ce.target.value),className:"flex-1"}),e.jsx(B,{type:"button",variant:"ghost",size:"icon",onClick:()=>ve(Ge),children:e.jsx(hr,{className:"h-4 w-4"})})]},Ge))]}),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:Ie.isPending||_,children:Ie.isPending||_?"Saving...":r?"Update":"Create"})]})]})]})}),e.jsx(Bs,{open:!!k,onOpenChange:()=>A(null),children:e.jsxs(Fs,{className:"max-w-2xl max-h-[90vh] overflow-y-auto",children:[e.jsx(qs,{children:e.jsx($s,{children:k==null?void 0:k.title})}),k&&e.jsxs("div",{className:"space-y-4",children:[k.preview_image_url&&e.jsx("img",{src:k.preview_image_url,alt:k.title,className:"w-full h-48 object-cover rounded-lg"}),k.description&&e.jsx("p",{className:"text-muted-foreground",children:k.description}),k.pdfs&&k.pdfs.length>0&&e.jsxs("div",{children:[e.jsxs("h4",{className:"font-medium mb-2 flex items-center gap-2",children:[e.jsx(Wr,{className:"h-4 w-4"}),"PDF Documents (",k.pdfs.length,")"]}),e.jsx("div",{className:"space-y-1",children:k.pdfs.map(Ne=>e.jsx("a",{href:Ne.file_url,target:"_blank",rel:"noopener noreferrer",className:"block p-2 border rounded hover:bg-muted",children:Ne.name},Ne.id))})]}),k.videos&&k.videos.length>0&&e.jsxs("div",{children:[e.jsxs("h4",{className:"font-medium mb-2 flex items-center gap-2",children:[e.jsx(na,{className:"h-4 w-4"}),"Videos (",k.videos.length,")"]}),e.jsx("div",{className:"space-y-2",children:k.videos.map(Ne=>e.jsx("div",{className:"p-2 border rounded",children:e.jsx("p",{className:"font-medium text-sm",children:Ne.title})},Ne.id))})]}),k.links&&k.links.length>0&&e.jsxs("div",{children:[e.jsxs("h4",{className:"font-medium mb-2 flex items-center gap-2",children:[e.jsx(gc,{className:"h-4 w-4"}),"Canva Links (",k.links.length,")"]}),e.jsx("div",{className:"space-y-1",children:k.links.map(Ne=>e.jsx("a",{href:Ne.canva_share_link,target:"_blank",rel:"noopener noreferrer",className:"block p-2 border rounded hover:bg-muted",children:Ne.title},Ne.id))})]})]})]})})]})})}const WPt=[{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 nun(){const[s,t]=N.useState([]),[n,r]=N.useState(!0),[a,i]=N.useState(!1),[l,o]=N.useState(!1),[c,d]=N.useState(null),[u,h]=N.useState(!1),[m,f]=N.useState(!1),[g,y]=N.useState(""),[x,_]=N.useState(""),[b,k]=N.useState(""),[A,T]=N.useState(""),[P,I]=N.useState("Learn More"),[M,L]=N.useState("top"),[z,$]=N.useState(""),[V,W]=N.useState(!0),[G,X]=N.useState(""),[te,ne]=N.useState("");N.useEffect(()=>{me()},[]);const me=async()=>{try{const{data:Se,error:Ie}=await H.from("dashboard_banners").select("*").order("placement").order("sort_order");if(Ie)throw Ie;t(Se||[])}catch(Se){ie.error("Failed to load banners: "+Se.message)}finally{r(!1)}},ue=()=>{y(""),_(""),k(""),T(""),I("Learn More"),L("top"),$(""),W(!0),X(""),ne(""),d(null)},ce=Se=>{d(Se),y(Se.title),_(Se.description||""),k(Se.image_url),T(Se.link_url||""),I(Se.link_text||"Learn More"),L(Se.placement),$(Se.section_after||""),W(Se.is_active),X(Se.start_date?Js(new Date(Se.start_date),"yyyy-MM-dd'T'HH:mm"):""),ne(Se.end_date?Js(new Date(Se.end_date),"yyyy-MM-dd'T'HH:mm"):""),i(!0)},ae=async Se=>{var Me;const Ie=(Me=Se.target.files)==null?void 0:Me[0];if(Ie){h(!0);try{const Re=Ie.name.split(".").pop(),Be=`${Date.now()}.${Re}`,{error:Ne}=await H.storage.from("banner-images").upload(Be,Ie);if(Ne)throw Ne;const{data:{publicUrl:Ge}}=H.storage.from("banner-images").getPublicUrl(Be);k(Ge),ie.success("Image uploaded successfully")}catch(Re){ie.error("Failed to upload image: "+Re.message)}finally{h(!1)}}},he=async()=>{if(!g.trim()||!b){ie.error("Please fill in required fields (title and image)");return}f(!0);try{const Se={title:g.trim(),description:x.trim()||null,image_url:b,link_url:A.trim()||null,link_text:P.trim()||"Learn More",placement:M,section_after:M==="between"?z:null,is_active:V,start_date:G?new Date(G).toISOString():null,end_date:te?new Date(te).toISOString():null};if(c){const{error:Ie}=await H.from("dashboard_banners").update(Se).eq("id",c.id);if(Ie)throw Ie;ie.success("Banner updated successfully")}else{const Ie=s.filter(Re=>Re.placement===M).length,{error:Me}=await H.from("dashboard_banners").insert({...Se,sort_order:Ie});if(Me)throw Me;ie.success("Banner created successfully")}i(!1),ue(),me()}catch(Se){ie.error("Failed to save banner: "+Se.message)}finally{f(!1)}},xe=async()=>{if(c)try{const{error:Se}=await H.from("dashboard_banners").delete().eq("id",c.id);if(Se)throw Se;ie.success("Banner deleted successfully"),o(!1),d(null),me()}catch(Se){ie.error("Failed to delete banner: "+Se.message)}},ve=async Se=>{try{const{error:Ie}=await H.from("dashboard_banners").update({is_active:!Se.is_active}).eq("id",Se.id);if(Ie)throw Ie;ie.success(Se.is_active?"Banner deactivated":"Banner activated"),me()}catch(Ie){ie.error("Failed to update banner: "+Ie.message)}},ge=s.filter(Se=>Se.placement==="top"),be=s.filter(Se=>Se.placement==="between");return n?e.jsx(Qs,{title:"Dashboard Management",children:e.jsx("div",{className:"flex items-center justify-center h-64",children:e.jsx("div",{className:"animate-spin rounded-full h-8 w-8 border-b-2 border-primary"})})}):e.jsxs(Qs,{title:"Dashboard Management",description:"Configure dashboard modules and banners",children:[e.jsxs("div",{className:"space-y-8",children:[e.jsxs(_e,{children:[e.jsxs(zt,{className:"flex flex-row items-center justify-between",children:[e.jsxs("div",{children:[e.jsxs(qt,{className:"flex items-center gap-2",children:[e.jsx(pc,{className:"h-5 w-5"}),"Hero Banners (Top of Dashboard)"]}),e.jsx(_r,{children:"These banners appear in a rotating carousel at the top of the dashboard"})]}),e.jsxs(Bs,{open:a&&M==="top",onOpenChange:Se=>{Se||ue(),i(Se),Se&&L("top")},children:[e.jsx(Ao,{asChild:!0,children:e.jsxs(B,{onClick:()=>{ue(),L("top")},children:[e.jsx(nn,{className:"mr-2 h-4 w-4"}),"Add Hero Banner"]})}),e.jsxs(Fs,{className:"max-w-2xl max-h-[90vh] overflow-y-auto",children:[e.jsxs(qs,{children:[e.jsxs($s,{children:[c?"Edit":"Create"," Banner"]}),e.jsx(Ar,{children:"Configure the banner's content and display settings"})]}),e.jsx(qut,{title:g,setTitle:y,description:x,setDescription:_,imageUrl:b,linkUrl:A,setLinkUrl:T,linkText:P,setLinkText:I,placement:M,setPlacement:L,sectionAfter:z,setSectionAfter:$,isActive:V,setIsActive:W,startDate:G,setStartDate:X,endDate:te,setEndDate:ne,handleImageUpload:ae,uploading:u,showPlacementOptions:!1}),e.jsxs(Cr,{children:[e.jsx(B,{variant:"outline",onClick:()=>{i(!1),ue()},children:"Cancel"}),e.jsx(B,{onClick:he,disabled:m,children:m?"Saving...":c?"Update Banner":"Create Banner"})]})]})]})]}),e.jsx(De,{children:ge.length===0?e.jsx("p",{className:"text-muted-foreground text-center py-8",children:"No hero banners yet. Add your first banner above."}):e.jsx("div",{className:"space-y-3",children:ge.map(Se=>e.jsx(Vut,{banner:Se,onEdit:()=>ce(Se),onDelete:()=>{d(Se),o(!0)},onToggleActive:()=>ve(Se)},Se.id))})})]}),e.jsxs(_e,{children:[e.jsxs(zt,{className:"flex flex-row items-center justify-between",children:[e.jsxs("div",{children:[e.jsxs(qt,{className:"flex items-center gap-2",children:[e.jsx(pc,{className:"h-5 w-5"}),"Section Banners"]}),e.jsx(_r,{children:"These banners appear between dashboard content sections"})]}),e.jsxs(Bs,{open:a&&M==="between",onOpenChange:Se=>{Se||ue(),i(Se),Se&&L("between")},children:[e.jsx(Ao,{asChild:!0,children:e.jsxs(B,{onClick:()=>{ue(),L("between")},children:[e.jsx(nn,{className:"mr-2 h-4 w-4"}),"Add Section Banner"]})}),e.jsxs(Fs,{className:"max-w-2xl max-h-[90vh] overflow-y-auto",children:[e.jsxs(qs,{children:[e.jsxs($s,{children:[c?"Edit":"Create"," Section Banner"]}),e.jsx(Ar,{children:"Configure where this banner appears between sections"})]}),e.jsx(qut,{title:g,setTitle:y,description:x,setDescription:_,imageUrl:b,linkUrl:A,setLinkUrl:T,linkText:P,setLinkText:I,placement:M,setPlacement:L,sectionAfter:z,setSectionAfter:$,isActive:V,setIsActive:W,startDate:G,setStartDate:X,endDate:te,setEndDate:ne,handleImageUpload:ae,uploading:u,showPlacementOptions:!0}),e.jsxs(Cr,{children:[e.jsx(B,{variant:"outline",onClick:()=>{i(!1),ue()},children:"Cancel"}),e.jsx(B,{onClick:he,disabled:m,children:m?"Saving...":c?"Update Banner":"Create Banner"})]})]})]})]}),e.jsx(De,{children:be.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:be.map(Se=>e.jsx(Vut,{banner:Se,onEdit:()=>ce(Se),onDelete:()=>{d(Se),o(!0)},onToggleActive:()=>ve(Se),showSection:!0},Se.id))})})]})]}),e.jsx(Bs,{open:l,onOpenChange:o,children:e.jsxs(Fs,{children:[e.jsxs(qs,{children:[e.jsx($s,{children:"Delete Banner"}),e.jsxs(Ar,{children:['Are you sure you want to delete "',c==null?void 0:c.title,'"? This action cannot be undone.']})]}),e.jsxs(Cr,{children:[e.jsx(B,{variant:"outline",onClick:()=>o(!1),children:"Cancel"}),e.jsx(B,{variant:"destructive",onClick:xe,children:"Delete"})]})]})})]})}function qut({title:s,setTitle:t,description:n,setDescription:r,imageUrl:a,linkUrl:i,setLinkUrl:l,linkText:o,setLinkText:c,placement:d,setPlacement:u,sectionAfter:h,setSectionAfter:m,isActive:f,setIsActive:g,startDate:y,setStartDate:x,endDate:_,setEndDate:b,handleImageUpload:k,uploading:A,showPlacementOptions:T}){return e.jsxs("div",{className:"space-y-4 py-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{htmlFor:"title",children:"Title *"}),e.jsx(we,{id:"title",placeholder:"Banner headline...",value:s,onChange:P=>t(P.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{htmlFor:"description",children:"Description"}),e.jsx(Ws,{id:"description",placeholder:"Optional banner description...",value:n,onChange:P=>r(P.target.value),rows:2})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{children:"Banner Image *"}),e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsx(we,{type:"file",accept:"image/*",onChange:k,disabled:A,className:"flex-1"}),A&&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(re,{htmlFor:"linkUrl",children:"Link URL (optional)"}),e.jsx(we,{id:"linkUrl",placeholder:"https://...",value:i,onChange:P=>l(P.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{htmlFor:"linkText",children:"Button Text"}),e.jsx(we,{id:"linkText",placeholder:"Learn More",value:o,onChange:P=>c(P.target.value)})]})]}),T&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{children:"Placement"}),e.jsxs(Ns,{value:h,onValueChange:m,children:[e.jsx(ws,{children:e.jsx(ks,{placeholder:"Select section placement..."})}),e.jsx(js,{children:WPt.map(P=>e.jsx(nt,{value:P.value,children:P.label},P.value))})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsxs(re,{htmlFor:"startDate",className:"flex items-center gap-2",children:[e.jsx(ta,{className:"h-4 w-4"}),"Start Date (optional)"]}),e.jsx(we,{id:"startDate",type:"datetime-local",value:y,onChange:P=>x(P.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs(re,{htmlFor:"endDate",className:"flex items-center gap-2",children:[e.jsx(ta,{className:"h-4 w-4"}),"End Date (optional)"]}),e.jsx(we,{id:"endDate",type:"datetime-local",value:_,onChange:P=>b(P.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(zn,{id:"isActive",checked:f,onCheckedChange:g}),e.jsx(re,{htmlFor:"isActive",children:"Active"})]})})]})}function Vut({banner:s,onEdit:t,onDelete:n,onToggleActive:r,showSection:a=!1}){var c;const i=(c=WPt.find(d=>d.value===s.section_after))==null?void 0:c.label,[l,o]=N.useState(null);return N.useEffect(()=>{(async()=>{const{count:u}=await H.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(Mp,{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(We,{variant:"secondary",children:"Inactive"}),s.start_date&&new Date(s.start_date)>new Date&&e.jsx(We,{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(ru,{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(Tr,{className:"h-4 w-4"})})}),e.jsx(B,{variant:"ghost",size:"icon",onClick:r,children:s.is_active?e.jsx(da,{className:"h-4 w-4"}):e.jsx(V0,{className:"h-4 w-4"})}),e.jsx(B,{variant:"ghost",size:"icon",onClick:t,children:e.jsx(Ja,{className:"h-4 w-4"})}),e.jsx(B,{variant:"ghost",size:"icon",onClick:n,children:e.jsx(qn,{className:"h-4 w-4 text-destructive"})})]})]})}const Yse={open:{label:"Open",icon:Xr,color:"bg-yellow-500"},in_progress:{label:"In Progress",icon:Ud,color:"bg-blue-500"},resolved:{label:"Resolved",icon:Po,color:"bg-green-500"},closed:{label:"Closed",icon:Nu,color:"bg-muted-foreground"}},Hut={general:"General Support",technology:"Technology Support",crm:"CRM Support",marketing:"Marketing Support"};function run(){var M,L;const{user:s}=Ls(),t=as(),[n,r]=N.useState(null),[a,i]=N.useState(""),[l,o]=N.useState([]),[c,d]=N.useState("all"),[u,h]=N.useState("all"),[m,f]=N.useState(!1),{data:g=[],isLoading:y}=mt({queryKey:["admin-support-tickets",c,u],queryFn:async()=>{let z=H.from("support_tickets").select("*, profiles!support_tickets_user_id_fkey(name, email)").order("created_at",{ascending:!1});c!=="all"&&(z=z.eq("status",c)),u!=="all"&&(z=z.eq("category",u));const{data:$,error:V}=await z;if(V)throw V;return $}}),{data:x=[]}=mt({queryKey:["admin-users-notifications"],queryFn:async()=>{const{data:z,error:$}=await H.from("user_roles").select("user_id").eq("role","admin");if($)throw $;const V=z.map(me=>me.user_id),{data:W,error:G}=await H.from("profiles").select("id, name, email").in("id",V);if(G)throw G;const{data:X,error:te}=await H.from("support_notification_settings").select("user_id, receive_notifications");if(te)throw te;const ne=new Map((X==null?void 0:X.map(me=>[me.user_id,me.receive_notifications]))||[]);return W.map(me=>({...me,receives_notifications:ne.get(me.id)||!1}))}}),{data:_=[]}=mt({queryKey:["admin-ticket-replies",n==null?void 0:n.id],queryFn:async()=>{if(!n)return[];const{data:z,error:$}=await H.from("support_ticket_replies").select("*, profiles(name)").eq("ticket_id",n.id).order("created_at",{ascending:!0});if($)throw $;return z},enabled:!!n}),b=_t({mutationFn:async({userId:z,enabled:$})=>{const{data:V}=await H.from("support_notification_settings").select("id").eq("user_id",z).maybeSingle();if(V){const{error:W}=await H.from("support_notification_settings").update({receive_notifications:$}).eq("user_id",z);if(W)throw W}else{const{error:W}=await H.from("support_notification_settings").insert({user_id:z,receive_notifications:$});if(W)throw W}},onSuccess:()=>{t.invalidateQueries({queryKey:["admin-users-notifications"]}),ie.success("Notification settings updated")},onError:()=>{ie.error("Failed to update settings")}}),k=_t({mutationFn:async({ticketId:z,status:$})=>{const{error:V}=await H.from("support_tickets").update({status:$}).eq("id",z);if(V)throw V},onSuccess:()=>{t.invalidateQueries({queryKey:["admin-support-tickets"]}),n&&r({...n,status:n.status}),ie.success("Status updated")},onError:()=>{ie.error("Failed to update status")}}),A=_t({mutationFn:async({ticketId:z,assignedTo:$})=>{const{error:V}=await H.from("support_tickets").update({assigned_to:$}).eq("id",z);if(V)throw V},onSuccess:()=>{t.invalidateQueries({queryKey:["admin-support-tickets"]}),ie.success("Ticket assigned")},onError:()=>{ie.error("Failed to assign ticket")}}),T=_t({mutationFn:async({content:z,attachments:$})=>{var W,G;if(!n||!s)throw new Error("Missing data");const{error:V}=await H.from("support_ticket_replies").insert({ticket_id:n.id,user_id:s.id,content:z,is_admin_reply:!0,attachments:$});if(V)throw V;try{await H.functions.invoke("support-reply-notify",{body:{ticketId:n.id,ticketSubject:n.subject,replyContent:z,userEmail:(W=n.profiles)==null?void 0:W.email,userName:(G=n.profiles)==null?void 0:G.name}})}catch(X){console.error("Failed to send reply notification:",X)}},onSuccess:()=>{t.invalidateQueries({queryKey:["admin-ticket-replies",n==null?void 0:n.id]}),i(""),o([]),ie.success("Reply sent!")},onError:()=>{ie.error("Failed to send reply")}}),P=()=>{!a.trim()&&l.length===0||T.mutate({content:a,attachments:l})};N.useEffect(()=>{const z=H.channel("admin-tickets").on("postgres_changes",{event:"*",schema:"public",table:"support_tickets"},()=>{t.invalidateQueries({queryKey:["admin-support-tickets"]})}).subscribe();return()=>{H.removeChannel(z)}},[t]);const I=g.filter(z=>z.status==="open").length;return n?(Yse[n.status].icon,e.jsx(Qs,{children:e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsx(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(We,{variant:"secondary",children:Hut[n.category]}),e.jsxs("span",{className:"text-sm text-muted-foreground",children:["from ",((M=n.profiles)==null?void 0:M.name)||"Unknown"," (",(L=n.profiles)==null?void 0:L.email,")"]})]})]})]}),e.jsxs("div",{className:"grid gap-4 md:grid-cols-2",children:[e.jsxs(_e,{children:[e.jsx(zt,{className:"pb-2",children:e.jsx(qt,{className:"text-sm",children:"Status"})}),e.jsx(De,{children:e.jsxs(Ns,{value:n.status,onValueChange:z=>{k.mutate({ticketId:n.id,status:z}),r({...n,status:z})},children:[e.jsx(ws,{children:e.jsx(ks,{})}),e.jsxs(js,{children:[e.jsx(nt,{value:"open",children:"Open"}),e.jsx(nt,{value:"in_progress",children:"In Progress"}),e.jsx(nt,{value:"resolved",children:"Resolved"}),e.jsx(nt,{value:"closed",children:"Closed"})]})]})})]}),e.jsxs(_e,{children:[e.jsx(zt,{className:"pb-2",children:e.jsx(qt,{className:"text-sm",children:"Assigned To"})}),e.jsx(De,{children:e.jsxs(Ns,{value:n.assigned_to||"unassigned",onValueChange:z=>{const $=z==="unassigned"?null:z;A.mutate({ticketId:n.id,assignedTo:$}),r({...n,assigned_to:$})},children:[e.jsx(ws,{children:e.jsx(ks,{placeholder:"Unassigned"})}),e.jsxs(js,{children:[e.jsx(nt,{value:"unassigned",children:"Unassigned"}),x.map(z=>e.jsx(nt,{value:z.id,children:z.name},z.id))]})]})})]})]}),e.jsxs(_e,{children:[e.jsx(zt,{children:e.jsxs(_r,{children:["Created on ",Js(new Date(n.created_at),"MMM d, yyyy 'at' h:mm a")]})}),e.jsx(De,{children:e.jsx("p",{className:"text-muted-foreground whitespace-pre-wrap",children:n.description})})]}),e.jsxs(_e,{children:[e.jsx(zt,{children:e.jsx(qt,{className:"text-lg",children:"Conversation"})}),e.jsxs(De,{children:[e.jsx(lo,{className:"h-[300px] pr-4",children:_.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:_.map(z=>{var $,V;return e.jsxs("div",{className:`p-4 rounded-lg ${z.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:z.is_admin_reply?`${(($=z.profiles)==null?void 0:$.name)||"Admin"} (Support)`:((V=z.profiles)==null?void 0:V.name)||"User"}),e.jsx("span",{className:"text-xs text-muted-foreground",children:Js(new Date(z.created_at),"MMM d, h:mm a")})]}),e.jsx("p",{className:"text-sm whitespace-pre-wrap",children:z.content}),z.attachments&&z.attachments.length>0&&e.jsx(CEt,{attachments:z.attachments})]},z.id)})})}),e.jsx(Wl,{className:"my-4"}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex gap-2",children:[e.jsx(Ws,{placeholder:"Type your reply...",value:a,onChange:z=>i(z.target.value),className:"min-h-[80px]"}),e.jsx(B,{onClick:P,disabled:!a.trim()&&l.length===0||T.isPending,className:"self-end",children:e.jsx(Rr,{className:"h-4 w-4"})})]}),e.jsx(SEt,{value:l,onChange:o,disabled:T.isPending})]})]})]})]})})):e.jsx(Qs,{children:e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex justify-between items-center",children:[e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl font-bold",children:"Support Tickets"}),e.jsxs("p",{className:"text-muted-foreground",children:["Manage support requests from agents",I>0&&e.jsxs(We,{variant:"destructive",className:"ml-2",children:[I," open"]})]})]}),e.jsxs(Bs,{open:m,onOpenChange:f,children:[e.jsx(Ao,{asChild:!0,children:e.jsxs(B,{variant:"outline",children:[e.jsx(sc,{className:"h-4 w-4 mr-2"}),"Notification Settings"]})}),e.jsxs(Fs,{children:[e.jsxs(qs,{children:[e.jsx($s,{children:"Email Notification Settings"}),e.jsx(Ar,{children:"Choose which admins receive email notifications for new support tickets."})]}),e.jsx("div",{className:"space-y-4 mt-4",children:x.map(z=>e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(Ro,{className:"h-4 w-4 text-muted-foreground"}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:z.name}),e.jsx("p",{className:"text-sm text-muted-foreground",children:z.email})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[z.receives_notifications?e.jsx(yg,{className:"h-4 w-4 text-primary"}):e.jsx(d5,{className:"h-4 w-4 text-muted-foreground"}),e.jsx(zn,{checked:z.receives_notifications,onCheckedChange:$=>b.mutate({userId:z.id,enabled:$})})]})]},z.id))})]})]})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex flex-wrap gap-4 items-center",children:[e.jsx(ya,{value:c,onValueChange:d,className:"w-auto",children:e.jsxs(va,{children:[e.jsx(ls,{value:"all",children:"All"}),e.jsx(ls,{value:"open",children:"Open"}),e.jsx(ls,{value:"in_progress",children:"In Progress"}),e.jsx(ls,{value:"resolved",children:"Resolved"}),e.jsx(ls,{value:"closed",children:"Closed"})]})}),e.jsxs(Ns,{value:u,onValueChange:h,children:[e.jsx(ws,{className:"w-[180px]",children:e.jsx(ks,{placeholder:"All Categories"})}),e.jsxs(js,{children:[e.jsx(nt,{value:"all",children:"All Categories"}),e.jsx(nt,{value:"general",children:"General Support"}),e.jsx(nt,{value:"technology",children:"Technology Support"}),e.jsx(nt,{value:"crm",children:"CRM Support"}),e.jsx(nt,{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..."}):g.length===0?e.jsx(_e,{children:e.jsxs(De,{className:"text-center py-12",children:[e.jsx(Ud,{className:"h-12 w-12 mx-auto text-muted-foreground mb-4"}),e.jsx("h3",{className:"text-lg font-medium mb-2",children:"No tickets found"}),e.jsx("p",{className:"text-muted-foreground",children:"No support tickets match the current filters."})]})}):e.jsx("div",{className:"space-y-3",children:g.map(z=>{var V,W;const $=Yse[z.status].icon;return e.jsx(_e,{className:"cursor-pointer hover:bg-muted/50 transition-colors",onClick:()=>r(z),children:e.jsx(De,{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:z.subject}),e.jsxs("div",{className:"flex items-center gap-2 mt-1 flex-wrap",children:[e.jsx(We,{variant:"outline",className:"text-xs",children:Hut[z.category]}),e.jsxs("span",{className:"text-xs text-muted-foreground",children:[(V=z.profiles)==null?void 0:V.name," • ",Js(new Date(z.created_at),"MMM d, yyyy")]}),z.assigned_to&&e.jsxs(We,{variant:"secondary",className:"text-xs gap-1",children:[e.jsx(Ro,{className:"h-3 w-3"}),((W=x.find(G=>G.id===z.assigned_to))==null?void 0:W.name)||"Assigned"]})]})]}),e.jsxs(We,{className:Yse[z.status].color,children:[e.jsx($,{className:"h-3 w-3 mr-1"}),Yse[z.status].label]})]})})},z.id)})})})]})]})})}const KPt=sy.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 aun({content:s,onChange:t,variables:n}){const r=qqe({extensions:[Hqe,tVe.configure({openOnClick:!1,HTMLAttributes:{class:"text-primary underline"}}),sVe.configure({types:["heading","paragraph"]}),nVe,KPt],content:s,onUpdate:({editor:l})=>{t(l.getHTML())}});N.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(jT,{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(AT,{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(Kx,{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(dj,{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(nD,{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(sD,{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(rD,{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(gc,{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(cD,{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(BT,{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(RT,{className:"h-4 w-4"})}),e.jsx("div",{className:"flex-1"}),n.length>0&&e.jsxs(qd,{children:[e.jsx(Vd,{asChild:!0,children:e.jsxs(B,{type:"button",variant:"outline",size:"sm",className:"gap-2",children:[e.jsx(P9,{className:"h-4 w-4"}),"Insert Variable"]})}),e.jsx(Ld,{align:"end",className:"w-64",children:n.map(l=>e.jsxs(ba,{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($qe,{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(We,{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 iun(){const s=as(),[t,n]=N.useState(null),[r,a]=N.useState(null),[i,l]=N.useState(""),[o,c]=N.useState(""),[d,u]=N.useState(""),[h,m]=N.useState(!0),[f,g]=N.useState("visual"),{data:y,isLoading:x}=mt({queryKey:["email-templates"],queryFn:async()=>{const{data:T,error:P}=await H.from("email_templates").select("*").order("name");if(P)throw P;return T.map(I=>({...I,available_variables:I.available_variables||[]}))}}),_=_t({mutationFn:async T=>{const{error:P}=await H.from("email_templates").update({subject:T.subject,body_html:T.body_html,description:T.description,is_active:T.is_active}).eq("id",T.id);if(P)throw P},onSuccess:()=>{s.invalidateQueries({queryKey:["email-templates"]}),ie.success("Email template updated successfully"),n(null)},onError:T=>{ie.error("Failed to update template: "+T.message)}}),b=T=>{n(T),l(T.subject),c(T.body_html),u(T.description||""),m(T.is_active),g("visual")},k=()=>{t&&_.mutate({id:t.id,subject:i,body_html:o,description:d,is_active:h})},A=(T,P)=>{let I=T;return P.forEach(M=>{const L=`{{${M.key}}}`,z=`[${M.label}]`;I=I.replace(new RegExp(L.replace(/[{}]/g,"\\$&"),"g"),z)}),I};return t?e.jsxs(Qs,{title:"Edit Email Template",children:[e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsxs(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(da,{className:"h-4 w-4 mr-2"}),"Preview"]}),e.jsxs(B,{onClick:k,disabled:_.isPending,children:[e.jsx(Kl,{className:"h-4 w-4 mr-2"}),_.isPending?"Saving...":"Save Changes"]})]}),e.jsxs(_e,{children:[e.jsx(zt,{children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsxs(qt,{className:"flex items-center gap-2",children:[e.jsx(mn,{className:"h-5 w-5"}),t.name]}),e.jsxs(_r,{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(re,{htmlFor:"active-toggle",children:"Active"}),e.jsx(zn,{id:"active-toggle",checked:h,onCheckedChange:m})]})]})}),e.jsxs(De,{className:"space-y-6",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{htmlFor:"description",children:"Description"}),e.jsx(Ws,{id:"description",value:d,onChange:T=>u(T.target.value),placeholder:"Brief description of when this email is sent",rows:2})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{htmlFor:"subject",children:"Email Subject"}),e.jsx(we,{id:"subject",value:i,onChange:T=>l(T.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(re,{children:"Email Body"}),e.jsx(ya,{value:f,onValueChange:T=>g(T),children:e.jsxs(va,{className:"h-8",children:[e.jsxs(ls,{value:"visual",className:"text-xs px-3 h-6",children:[e.jsx(hj,{className:"h-3 w-3 mr-1"}),"Visual"]}),e.jsxs(ls,{value:"html",className:"text-xs px-3 h-6",children:[e.jsx(cD,{className:"h-3 w-3 mr-1"}),"HTML"]})]})})]}),f==="visual"?e.jsx(aun,{content:o,onChange:c,variables:t.available_variables}):e.jsx(Ws,{value:o,onChange:T=>c(T.target.value),className:"font-mono text-sm min-h-[400px]",placeholder:"HTML email body"})]})]})]})]}),e.jsx(Bs,{open:!!r,onOpenChange:()=>a(null),children:e.jsxs(Fs,{className:"max-w-3xl max-h-[90vh] overflow-auto",children:[e.jsxs(qs,{children:[e.jsx($s,{children:"Email Preview"}),e.jsxs(Ar,{children:["Subject: ",i.replace(/\{\{(\w+)\}\}/g,"[$1]")]})]}),e.jsx("div",{className:"border rounded-lg p-4 bg-white",children:e.jsx("div",{dangerouslySetInnerHTML:{__html:A(o,t.available_variables)}})})]})})]}):e.jsx(Qs,{title:"Email Templates",children:e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl font-bold",children:"Email Templates"}),e.jsx("p",{className:"text-muted-foreground mt-1",children:"Manage and customize system email templates"})]}),x?e.jsx("div",{className:"grid gap-4",children:[...Array(4)].map((T,P)=>e.jsx(_e,{children:e.jsxs(zt,{children:[e.jsx(xn,{className:"h-5 w-48"}),e.jsx(xn,{className:"h-4 w-96"})]})},P))}):e.jsx("div",{className:"grid gap-4",children:y==null?void 0:y.map(T=>e.jsxs(_e,{className:"hover:shadow-md transition-shadow",children:[e.jsx(zt,{children:e.jsxs("div",{className:"flex items-start justify-between",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsxs(qt,{className:"flex items-center gap-2 text-lg",children:[e.jsx(mn,{className:"h-5 w-5 text-muted-foreground"}),T.name,!T.is_active&&e.jsx(We,{variant:"secondary",children:"Inactive"})]}),e.jsx(_r,{children:T.description})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(B,{variant:"outline",size:"sm",onClick:()=>a(T),children:[e.jsx(da,{className:"h-4 w-4 mr-2"}),"Preview"]}),e.jsxs(B,{size:"sm",onClick:()=>b(T),children:[e.jsx(xp,{className:"h-4 w-4 mr-2"}),"Edit"]})]})]})}),e.jsx(De,{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:T.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:T.available_variables.map(P=>e.jsx(We,{variant:"outline",className:"font-mono text-xs",children:`{{${P.key}}}`},P.key))})]})]})})]},T.id))}),e.jsx(Bs,{open:!!r&&!t,onOpenChange:()=>a(null),children:e.jsxs(Fs,{className:"max-w-3xl max-h-[90vh] overflow-auto",children:[e.jsxs(qs,{children:[e.jsxs($s,{children:["Email Preview: ",r==null?void 0:r.name]}),e.jsxs(Ar,{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:A(r.body_html,r.available_variables)}})})]})})]})})}function oun(){const s=as(),[t,n]=N.useState("templates"),[r,a]=N.useState(null),[i,l]=N.useState(null),[o,c]=N.useState(!1),[d,u]=N.useState(!1),[h,m]=N.useState({title:"",subject:"",body:"",description:"",tone:"",category_id:"",is_active:!0}),[f,g]=N.useState({name:"",description:"",icon:"📧"}),{data:y=[]}=mt({queryKey:["agent-email-template-categories"],queryFn:async()=>{const{data:z,error:$}=await H.from("email_template_categories").select("*").order("sort_order");if($)throw $;return z}}),{data:x=[],isLoading:_}=mt({queryKey:["agent-email-templates-admin"],queryFn:async()=>{const{data:z,error:$}=await H.from("agent_email_templates").select("*, category:email_template_categories(*)").order("sort_order");if($)throw $;return z}}),b=_t({mutationFn:async z=>{const $={title:z.title,subject:z.subject,body:z.body,description:z.description||null,tone:z.tone||null,category_id:z.category_id||null,is_active:z.is_active};if(z.id){const{error:V}=await H.from("agent_email_templates").update($).eq("id",z.id);if(V)throw V}else{const{error:V}=await H.from("agent_email_templates").insert($);if(V)throw V}},onSuccess:()=>{s.invalidateQueries({queryKey:["agent-email-templates-admin"]}),c(!1),ie.success(r?"Template updated":"Template created")},onError:()=>ie.error("Failed to save template")}),k=_t({mutationFn:async z=>{const{error:$}=await H.from("agent_email_templates").delete().eq("id",z);if($)throw $},onSuccess:()=>{s.invalidateQueries({queryKey:["agent-email-templates-admin"]}),ie.success("Template deleted")}}),A=_t({mutationFn:async z=>{const $={name:z.name,description:z.description||null,icon:z.icon};if(z.id){const{error:V}=await H.from("email_template_categories").update($).eq("id",z.id);if(V)throw V}else{const V=y.length>0?Math.max(...y.map(G=>G.sort_order))+1:0,{error:W}=await H.from("email_template_categories").insert({...$,sort_order:V});if(W)throw W}},onSuccess:()=>{s.invalidateQueries({queryKey:["agent-email-template-categories"]}),u(!1),ie.success(i?"Category updated":"Category created")},onError:()=>ie.error("Failed to save category")}),T=_t({mutationFn:async z=>{const{error:$}=await H.from("email_template_categories").delete().eq("id",z);if($)throw $},onSuccess:()=>{s.invalidateQueries({queryKey:["agent-email-template-categories"]}),ie.success("Category deleted")}}),P=()=>{a(null),m({title:"",subject:"",body:"",description:"",tone:"",category_id:"",is_active:!0}),c(!0)},I=z=>{a(z),m({title:z.title,subject:z.subject,body:z.body,description:z.description||"",tone:z.tone||"",category_id:z.category_id||"",is_active:z.is_active}),c(!0)},M=()=>{l(null),g({name:"",description:"",icon:"📧"}),u(!0)},L=z=>{l(z),g({name:z.name,description:z.description||"",icon:z.icon}),u(!0)};return e.jsx(Qs,{children:e.jsxs("div",{className:"space-y-6 animate-fade-in",children:[e.jsx(Uh,{title:"Agent Email Templates",description:"Manage email templates that agents use when composing emails from Mission Control."}),e.jsxs(ya,{value:t,onValueChange:n,children:[e.jsxs(va,{children:[e.jsxs(ls,{value:"templates",className:"gap-2",children:[e.jsx(mn,{className:"h-4 w-4"})," Templates"]}),e.jsxs(ls,{value:"categories",className:"gap-2",children:[e.jsx(H0,{className:"h-4 w-4"})," Categories"]})]}),e.jsxs(_s,{value:"templates",className:"space-y-4",children:[e.jsx("div",{className:"flex justify-end",children:e.jsxs(B,{onClick:P,className:"gap-2",children:[e.jsx(nn,{className:"h-4 w-4"})," Add Template"]})}),e.jsx(_e,{children:e.jsx(De,{className:"p-0",children:e.jsxs(Oa,{children:[e.jsx(Fa,{children:e.jsxs(un,{children:[e.jsx(Mt,{children:"Template"}),e.jsx(Mt,{className:"hidden md:table-cell",children:"Category"}),e.jsx(Mt,{className:"hidden md:table-cell",children:"Tone"}),e.jsx(Mt,{children:"Status"}),e.jsx(Mt,{className:"text-right",children:"Actions"})]})}),e.jsx(za,{children:_?e.jsx(un,{children:e.jsx(gt,{colSpan:5,className:"text-center py-8",children:e.jsx(us,{className:"h-6 w-6 animate-spin mx-auto"})})}):x.length===0?e.jsx(un,{children:e.jsx(gt,{colSpan:5,className:"text-center py-8 text-muted-foreground",children:"No templates yet. Create your first one!"})}):x.map(z=>e.jsxs(un,{children:[e.jsx(gt,{children:e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:z.title}),e.jsx("p",{className:"text-xs text-muted-foreground truncate max-w-[300px]",children:z.subject})]})}),e.jsx(gt,{className:"hidden md:table-cell",children:z.category?e.jsxs(We,{variant:"outline",className:"gap-1",children:[z.category.icon," ",z.category.name]}):e.jsx("span",{className:"text-muted-foreground text-sm",children:"—"})}),e.jsx(gt,{className:"hidden md:table-cell",children:z.tone?e.jsx(We,{variant:"secondary",children:z.tone}):"—"}),e.jsx(gt,{children:e.jsx(We,{variant:z.is_active?"default":"secondary",children:z.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:()=>I(z),children:e.jsx(Ja,{className:"h-4 w-4"})}),e.jsx(B,{variant:"ghost",size:"icon",className:"text-destructive hover:text-destructive",onClick:()=>{confirm("Delete this template?")&&k.mutate(z.id)},children:e.jsx(qn,{className:"h-4 w-4"})})]})})]},z.id))})]})})})]}),e.jsxs(_s,{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(nn,{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(z=>e.jsxs(_e,{children:[e.jsx(zt,{className:"pb-2",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs(qt,{className:"text-base flex items-center gap-2",children:[e.jsx("span",{className:"text-lg",children:z.icon})," ",z.name]}),e.jsxs("div",{className:"flex gap-1",children:[e.jsx(B,{variant:"ghost",size:"icon",className:"h-8 w-8",onClick:()=>L(z),children:e.jsx(Ja,{className:"h-3.5 w-3.5"})}),e.jsx(B,{variant:"ghost",size:"icon",className:"h-8 w-8 text-destructive",onClick:()=>{confirm("Delete this category?")&&T.mutate(z.id)},children:e.jsx(qn,{className:"h-3.5 w-3.5"})})]})]})}),e.jsxs(De,{children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:z.description||"No description"}),e.jsxs("p",{className:"text-xs text-muted-foreground mt-2",children:[x.filter($=>$.category_id===z.id).length," templates"]})]})]},z.id))})]})]}),e.jsx(Bs,{open:o,onOpenChange:c,children:e.jsxs(Fs,{className:"sm:max-w-[700px] max-h-[90vh] overflow-y-auto",children:[e.jsx(qs,{children:e.jsx($s,{children:r?"Edit Template":"New Template"})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(re,{children:"Title"}),e.jsx(we,{value:h.title,onChange:z=>m($=>({...$,title:z.target.value})),placeholder:"e.g. Quick Check-in"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(re,{children:"Category"}),e.jsxs(Ns,{value:h.category_id,onValueChange:z=>m($=>({...$,category_id:z})),children:[e.jsx(ws,{children:e.jsx(ks,{placeholder:"Select category"})}),e.jsx(js,{children:y.map(z=>e.jsxs(nt,{value:z.id,children:[z.icon," ",z.name]},z.id))})]})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(re,{children:"Subject Line"}),e.jsx(we,{value:h.subject,onChange:z=>m($=>({...$,subject:z.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(re,{children:"Email Body"}),e.jsx(Ws,{value:h.body,onChange:z=>m($=>({...$,body:z.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(re,{children:"Description (internal)"}),e.jsx(we,{value:h.description,onChange:z=>m($=>({...$,description:z.target.value})),placeholder:"Short description for admin reference"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(re,{children:"Tone"}),e.jsx(we,{value:h.tone,onChange:z=>m($=>({...$,tone:z.target.value})),placeholder:"e.g. Warm & Casual"})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(zn,{checked:h.is_active,onCheckedChange:z=>m($=>({...$,is_active:z}))}),e.jsx(re,{children:"Active"})]})]}),e.jsxs(Cr,{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(us,{className:"h-4 w-4 mr-2 animate-spin"}),r?"Save Changes":"Create Template"]})]})]})}),e.jsx(Bs,{open:d,onOpenChange:u,children:e.jsxs(Fs,{className:"sm:max-w-[450px]",children:[e.jsx(qs,{children:e.jsx($s,{children:i?"Edit Category":"New Category"})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"grid grid-cols-[60px_1fr] gap-3",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(re,{children:"Icon"}),e.jsx(we,{value:f.icon,onChange:z=>g($=>({...$,icon:z.target.value})),className:"text-center text-lg"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(re,{children:"Name"}),e.jsx(we,{value:f.name,onChange:z=>g($=>({...$,name:z.target.value})),placeholder:"e.g. Check-in & Stay in Touch"})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(re,{children:"Description"}),e.jsx(we,{value:f.description,onChange:z=>g($=>({...$,description:z.target.value})),placeholder:"Brief description of this category"})]})]}),e.jsxs(Cr,{children:[e.jsx(B,{variant:"outline",onClick:()=>u(!1),children:"Cancel"}),e.jsxs(B,{onClick:()=>A.mutate({...f,id:i==null?void 0:i.id}),disabled:A.isPending||!f.name,children:[A.isPending&&e.jsx(us,{className:"h-4 w-4 mr-2 animate-spin"}),i?"Save Changes":"Create Category"]})]})]})})]})})}const lun=({brokerageId:s})=>{var sa,xs;const{toast:t}=Ci(),n=tr(),[r,a]=N.useState([]),[i,l]=N.useState(!0),[o,c]=N.useState(""),[d,u]=N.useState("all"),[h,m]=N.useState(new Set),[f,g]=N.useState(!1),[y,x]=N.useState({}),[_,b]=N.useState(!1),[k,A]=N.useState(!1),[T,P]=N.useState({email:"",name:"",password:"",phone:""}),[I,M]=N.useState(!1),[L,z]=N.useState(null),[$,V]=N.useState(!1),[W,G]=N.useState(!1),[X,te]=N.useState(!1),[ne,me]=N.useState(""),[ue,ce]=N.useState(!1),[ae,he]=N.useState([]),[xe,ve]=N.useState(!1),[ge,be]=N.useState(!1),[Se,Ie]=N.useState(null),[Me,Re]=N.useState({name:"",phone:"",email:""}),[Be,Ne]=N.useState(!1),[Ge,Ce]=N.useState(!1),[Fe,Ae]=N.useState(null),[Xe,$e]=N.useState("asc"),[Ye,Je]=N.useState(!1),[Ke,st]=N.useState(null),[rt,Ze]=N.useState(!1),[ht,Bt]=N.useState(null),[Ct,Yt]=N.useState(""),[Kt,Xs]=N.useState(!1),[zs,Vt]=N.useState(null);N.useEffect(()=>{Os(),At()},[s]);const At=async()=>{try{const{data:Ve,error:it}=await H.from("brokerage_manager_assignments").select("user_id").eq("brokerage_id",s);if(it)throw it;he((Ve==null?void 0:Ve.map(ft=>ft.user_id))||[])}catch(Ve){console.error("Error loading brokerage managers:",Ve)}},Os=async()=>{try{l(!0);const{data:Ve,error:it}=await H.functions.invoke("get-brokerage-agents",{body:{brokerageId:s}});if(it)throw it;const ft=Ve.agents||[];if(a(ft),ft.length>0){const kt=ft.map(es=>es.id),{data:Ut}=await H.from("agent_assistant_assignments").select("agent_id, assistant_id").in("agent_id",kt);if(Ut&&Ut.length>0){const es=Ut.map(Zs=>Zs.assistant_id),{data:Ms}=await H.from("profiles").select("id, name, email").in("id",es),bs={};for(const Zs of Ut){const kn=Ms==null?void 0:Ms.find(gn=>gn.id===Zs.assistant_id);kn&&(bs[Zs.agent_id]={name:kn.name||"",email:kn.email||""})}x(bs)}else x({})}}catch(Ve){console.error("Error loading agents:",Ve),t({title:"Error",description:"Failed to load agents",variant:"destructive"})}finally{l(!1)}},Nt=async()=>{if(!T.email||!T.name||!T.password){t({title:"Error",description:"Please fill in all fields",variant:"destructive"});return}A(!0);try{const{data:{session:Ve}}=await H.auth.getSession(),it=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/create-user",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${Ve==null?void 0:Ve.access_token}`},body:JSON.stringify({...T,brokerageId:s})}),ft=await it.json();if(!it.ok)throw new Error(ft.error||"Failed to create agent");t({title:"Success",description:`Agent ${T.email} created successfully`}),P({email:"",name:"",password:"",phone:""}),b(!1),Os()}catch(Ve){console.error("Error creating agent:",Ve),t({title:"Error",description:Ve.message||"Failed to create agent",variant:"destructive"})}finally{A(!1)}},ms=async Ve=>{try{const{data:{session:it}}=await H.auth.getSession(),ft=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/resend-welcome-email",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${it==null?void 0:it.access_token}`},body:JSON.stringify({userId:Ve})}),kt=await ft.json();if(!ft.ok)throw new Error(kt.error||"Failed to resend welcome email");t({title:"Success",description:"Welcome email sent successfully"})}catch(it){console.error("Error resending welcome email:",it),t({title:"Error",description:it.message||"Failed to resend welcome email",variant:"destructive"})}},Ys=async(Ve,it)=>{try{const{error:ft}=await H.functions.invoke("send-password-reset",{body:{email:Ve,redirectTo:window.location.origin}});if(ft)throw ft;t({title:"Password Reset Sent",description:`Password reset email sent to ${it}`})}catch(ft){console.error("Error sending password reset:",ft),t({title:"Error",description:ft.message||"Failed to send password reset email",variant:"destructive"})}},It=Ve=>{z(Ve),M(!0)},Ds=Ve=>{Ie(Ve),Re({name:Ve.name,phone:Ve.phone||"",email:Ve.email}),be(!0)},As=async()=>{if(!Se)return;if(!Me.name.trim()){t({title:"Error",description:"Name is required",variant:"destructive"});return}const Ve=Me.email.trim().toLowerCase()!==Se.email.toLowerCase();Ne(!0);try{if(Ve){if(!Me.email.trim())throw new Error("Email is required");Ce(!0);const{data:{session:ft}}=await H.auth.getSession(),kt=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/update-agent-email",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${ft==null?void 0:ft.access_token}`},body:JSON.stringify({agentId:Se.id,newEmail:Me.email.trim(),brokerageId:s})}),Ut=await kt.json();if(Ce(!1),!kt.ok)throw new Error(Ut.error||"Failed to update email")}const{error:it}=await H.from("profiles").update({name:Me.name.trim(),phone:Me.phone.trim()||null}).eq("id",Se.id);if(it)throw it;t({title:"Success",description:"Agent profile updated successfully"}),be(!1),Ie(null),Os()}catch(it){console.error("Error updating agent:",it),t({title:"Error",description:it.message||"Failed to update agent",variant:"destructive"})}finally{Ne(!1),Ce(!1)}},Hs=async()=>{if(!ne){t({title:"Error",description:"Please select an agent to promote",variant:"destructive"});return}ce(!0);try{const{data:{session:Ve}}=await H.auth.getSession(),it=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/manage-user-roles",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${Ve==null?void 0:Ve.access_token}`},body:JSON.stringify({userId:ne,role:"brokerage_manager",action:"add",brokerageId:s})}),ft=await it.json();if(!it.ok)throw new Error(ft.error||"Failed to add brokerage manager");t({title:"Success",description:"Brokerage manager added successfully"}),te(!1),me(""),At()}catch(Ve){console.error("Error adding brokerage manager:",Ve),t({title:"Error",description:Ve.message||"Failed to add brokerage manager",variant:"destructive"})}finally{ce(!1)}},Rs=async Ve=>{try{const{data:{session:it}}=await H.auth.getSession(),ft=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/manage-user-roles",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${it==null?void 0:it.access_token}`},body:JSON.stringify({userId:Ve,role:"brokerage_manager",action:"remove",brokerageId:s})}),kt=await ft.json();if(!ft.ok)throw new Error(kt.error||"Failed to remove brokerage manager");t({title:"Success",description:"Brokerage manager role removed"}),At()}catch(it){console.error("Error removing brokerage manager:",it),t({title:"Error",description:it.message||"Failed to remove brokerage manager",variant:"destructive"})}},en=Ve=>ae.includes(Ve),Rn=Ve=>{Bt(Ve),Yt(""),Ze(!0)},Bn=async()=>{if(!(!ht||!Ct)){if(Ct.length<6){t({title:"Error",description:"Password must be at least 6 characters",variant:"destructive"});return}Xs(!0);try{const{data:{session:Ve}}=await H.auth.getSession(),it=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/update-agent-email",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${Ve==null?void 0:Ve.access_token}`},body:JSON.stringify({agentId:ht.id,brokerageId:s,action:"set_password",newPassword:Ct})}),ft=await it.json();if(!it.ok)throw new Error(ft.error||"Failed to set password");t({title:"Success",description:`Password set for ${ht.name}`}),Ze(!1),Bt(null),Yt("")}catch(Ve){console.error("Error setting password:",Ve),t({title:"Error",description:Ve.message||"Failed to set password",variant:"destructive"})}finally{Xs(!1)}}},Dn=async Ve=>{Vt(Ve.id);try{const{data:{session:it}}=await H.auth.getSession(),ft=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/update-agent-email",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${it==null?void 0:it.access_token}`},body:JSON.stringify({agentId:Ve.id,brokerageId:s,action:"claim_account"})}),kt=await ft.json();if(!ft.ok)throw new Error(kt.error||"Failed to claim account");t({title:"Success",description:`Account claimed for ${Ve.name}`}),Os()}catch(it){console.error("Error claiming account:",it),t({title:"Error",description:it.message||"Failed to claim account",variant:"destructive"})}finally{Vt(null)}},Jn=async()=>{if(L){V(!0);try{const{data:{session:Ve}}=await H.auth.getSession(),it=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/remove-agent",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${Ve==null?void 0:Ve.access_token}`},body:JSON.stringify({userId:L.id,brokerageId:s})}),ft=await it.json();if(!it.ok)throw new Error(ft.error||"Failed to remove agent");t({title:"Success",description:`${L.name} has been removed from your brokerage`}),M(!1),z(null),Os()}catch(Ve){console.error("Error removing agent:",Ve),t({title:"Error",description:Ve.message||"Failed to remove agent",variant:"destructive"})}finally{V(!1)}}},ua=Ve=>{const it=Ve.trim().split(" ");return it.length>1?it[it.length-1].toLowerCase():Ve.toLowerCase()},Mr=Ve=>{Fe===Ve?$e(Xe==="asc"?"desc":"asc"):(Ae(Ve),$e("asc"))},sn=Ve=>Fe!==Ve?e.jsx(mg,{className:"ml-1 h-4 w-4"}):Xe==="asc"?e.jsx(Om,{className:"ml-1 h-4 w-4"}):e.jsx(Wf,{className:"ml-1 h-4 w-4"}),ki=r.filter(Ve=>{if(d==="active"&&!Ve.claimed||d==="pending"&&Ve.claimed)return!1;if(!o)return!0;const it=o.toLowerCase();return Ve.name.toLowerCase().includes(it)||Ve.email.toLowerCase().includes(it)}),ia=[...ki].sort((Ve,it)=>{if(!Fe)return 0;let ft=0;return Fe==="name"?ft=ua(Ve.name).localeCompare(ua(it.name)):Fe==="status"&&(ft=Ve.claimed===it.claimed?0:Ve.claimed?-1:1),Xe==="asc"?ft:-ft});ki.filter(Ve=>Ve.claimed&&!en(Ve.id));const vr=Ve=>{m(it=>{const ft=new Set(it);return ft.has(Ve)?ft.delete(Ve):ft.add(Ve),ft})},Nr=()=>{h.size===ia.length?m(new Set):m(new Set(ia.map(Ve=>Ve.id)))},rn=()=>{m(new Set)},Zn=async()=>{const Ve=Array.from(h);if(Ve.length===0)return;g(!0);let it=0,ft=0;try{const{data:{session:kt}}=await H.auth.getSession();for(const Ut of Ve)try{(await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/resend-welcome-email",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${kt==null?void 0:kt.access_token}`},body:JSON.stringify({userId:Ut})})).ok?it++:ft++}catch{ft++}it>0?t({title:"Success",description:`Welcome emails sent to ${it} agent${it>1?"s":""}${ft>0?` (${ft} failed)`:""}`}):t({title:"Error",description:"Failed to send welcome emails",variant:"destructive"}),rn()}catch(kt){console.error("Error bulk sending welcome emails:",kt),t({title:"Error",description:kt.message||"Failed to send welcome emails",variant:"destructive"})}finally{g(!1)}};return i?e.jsx(_e,{children:e.jsx(De,{className:"flex items-center justify-center py-8",children:e.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})})}):e.jsxs(e.Fragment,{children:[e.jsxs(_e,{children:[e.jsx(zt,{children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(qt,{children:"Agents"}),e.jsx(_r,{children:"Manage your brokerage's agents"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(B,{variant:"outline",onClick:()=>te(!0),children:[e.jsx(mf,{className:"mr-2 h-4 w-4"}),"Add Brokerage Manager"]}),e.jsxs(B,{variant:"outline",onClick:()=>G(!0),children:[e.jsx(m5,{className:"mr-2 h-4 w-4"}),"Import CSV"]}),e.jsxs(B,{onClick:()=>b(!0),children:[e.jsx(Yl,{className:"mr-2 h-4 w-4"}),"Add Agent"]})]})]})}),e.jsxs(De,{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(Gr,{className:"absolute left-3 top-3 h-4 w-4 text-muted-foreground"}),e.jsx(we,{placeholder:"Search agents...",value:o,onChange:Ve=>c(Ve.target.value),className:"pl-9"})]}),e.jsxs(Ns,{value:d,onValueChange:Ve=>u(Ve),children:[e.jsx(ws,{className:"w-[160px]",children:e.jsx(ks,{placeholder:"Filter by status"})}),e.jsxs(js,{children:[e.jsx(nt,{value:"all",children:"All Agents"}),e.jsx(nt,{value:"active",children:"Active"}),e.jsx(nt,{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 it=r.filter(ft=>h.has(ft.id)&&ft.email).map(ft=>({email:ft.email,name:ft.name}));sessionStorage.setItem("campaign_direct_recipients",JSON.stringify(it)),n("/admin/email-campaigns/new?directMode=1",{state:{directRecipients:it}})},disabled:f,children:[e.jsx(um,{className:"mr-2 h-4 w-4"}),"Email Agents (",h.size,")"]}),e.jsxs(B,{size:"sm",variant:"outline",onClick:Zn,disabled:f,children:[e.jsx(mn,{className:"mr-2 h-4 w-4"}),f?"Sending...":"Resend Welcome Email"]}),e.jsx(B,{size:"sm",variant:"ghost",onClick:rn,children:"Clear"})]}),e.jsx("div",{className:"rounded-md border",children:e.jsxs(Oa,{children:[e.jsx(Fa,{children:e.jsxs(un,{children:[e.jsx(Mt,{className:"w-[40px]",children:e.jsx(Bi,{checked:ia.length>0&&h.size===ia.length,onCheckedChange:Nr,"aria-label":"Select all"})}),e.jsx(Mt,{children:e.jsxs(B,{variant:"ghost",size:"sm",className:"-ml-3 h-8 hover:bg-transparent",onClick:()=>Mr("name"),children:["Name (Last)",sn("name")]})}),e.jsx(Mt,{children:"Email"}),e.jsx(Mt,{children:e.jsxs(B,{variant:"ghost",size:"sm",className:"-ml-3 h-8 hover:bg-transparent",onClick:()=>Mr("status"),children:["Status",sn("status")]})}),e.jsx(Mt,{children:"Actions"})]})}),e.jsx(za,{children:ia.length===0?e.jsx(un,{children:e.jsx(gt,{colSpan:5,className:"text-center text-muted-foreground",children:"No agents found"})}):ia.map(Ve=>e.jsxs(un,{children:[e.jsx(gt,{children:e.jsx(Bi,{checked:h.has(Ve.id),onCheckedChange:()=>vr(Ve.id),"aria-label":`Select ${Ve.name}`})}),e.jsx(gt,{className:"font-medium",children:Ve.name}),e.jsx(gt,{children:Ve.email}),e.jsx(gt,{children:e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[Ve.claimed?e.jsx(We,{variant:"default",children:"Active"}):e.jsx(We,{variant:"secondary",children:"Pending"}),en(Ve.id)&&e.jsxs(We,{variant:"outline",className:"border-primary text-primary",children:[e.jsx(Wv,{className:"mr-1 h-3 w-3"}),"Manager"]}),y[Ve.id]&&e.jsxs(We,{variant:"outline",className:"text-xs",children:[e.jsx(Yn,{className:"mr-1 h-3 w-3"}),"Asst: ",y[Ve.id].name||y[Ve.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:()=>{st(Ve),Je(!0)},title:"Send celebration",className:"text-yellow-500 hover:text-yellow-600 hover:bg-yellow-50",children:e.jsx(uf,{className:"h-4 w-4"})}),e.jsx(B,{size:"sm",variant:"ghost",onClick:()=>Ds(Ve),title:"Edit agent",children:e.jsx(Ja,{className:"h-4 w-4"})}),!Ve.claimed&&e.jsxs(e.Fragment,{children:[e.jsx(B,{size:"sm",variant:"ghost",onClick:()=>ms(Ve.id),title:"Resend welcome email",children:e.jsx(mn,{className:"h-4 w-4"})}),e.jsx(B,{size:"sm",variant:"ghost",onClick:()=>Dn(Ve),title:"Claim account for agent",disabled:zs===Ve.id,className:"text-green-600 hover:text-green-700 hover:bg-green-50",children:e.jsx(tN,{className:"h-4 w-4"})})]}),e.jsx(B,{size:"sm",variant:"ghost",onClick:()=>Rn(Ve),title:"Set password",className:"text-blue-600 hover:text-blue-700 hover:bg-blue-50",children:e.jsx(Au,{className:"h-4 w-4"})}),e.jsx(B,{size:"sm",variant:"ghost",onClick:()=>Ys(Ve.email,Ve.name),title:"Send password reset email",children:e.jsx(TT,{className:"h-4 w-4"})}),en(Ve.id)&&e.jsx(B,{size:"sm",variant:"ghost",onClick:()=>Rs(Ve.id),title:"Remove manager role",className:"text-orange-500 hover:text-orange-600",children:e.jsx(mf,{className:"h-4 w-4"})}),e.jsx(B,{size:"sm",variant:"ghost",onClick:()=>It(Ve),className:"text-destructive hover:text-destructive",title:"Remove agent",children:e.jsx(qn,{className:"h-4 w-4"})})]})})]},Ve.id))})]})})]})]}),e.jsx(Bs,{open:_,onOpenChange:b,children:e.jsxs(Fs,{children:[e.jsxs(qs,{children:[e.jsx($s,{children:"Add New Agent"}),e.jsx(Ar,{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(re,{htmlFor:"name",children:"Name"}),e.jsx(we,{id:"name",value:T.name,onChange:Ve=>P({...T,name:Ve.target.value}),placeholder:"John Doe"})]}),e.jsxs("div",{children:[e.jsx(re,{htmlFor:"email",children:"Email"}),e.jsx(we,{id:"email",type:"email",value:T.email,onChange:Ve=>P({...T,email:Ve.target.value}),placeholder:"john@example.com"})]}),e.jsxs("div",{children:[e.jsx(re,{htmlFor:"phone",children:"Phone (optional)"}),e.jsx(we,{id:"phone",type:"tel",value:T.phone,onChange:Ve=>P({...T,phone:Ve.target.value}),placeholder:"555-123-4567"})]}),e.jsxs("div",{children:[e.jsx(re,{htmlFor:"password",children:"Temporary Password"}),e.jsx(we,{id:"password",type:"password",value:T.password,onChange:Ve=>P({...T,password:Ve.target.value}),placeholder:"Temporary password"})]})]}),e.jsxs(Cr,{children:[e.jsx(B,{variant:"outline",onClick:()=>b(!1),children:"Cancel"}),e.jsx(B,{onClick:Nt,disabled:k,children:k?"Creating...":"Create Agent"})]})]})}),e.jsx(Bs,{open:I,onOpenChange:M,children:e.jsxs(Fs,{children:[e.jsxs(qs,{children:[e.jsx($s,{children:"Remove Agent"}),e.jsxs(Ar,{children:["Are you sure you want to remove ",e.jsx("strong",{children:L==null?void 0:L.name})," from your brokerage? This will revoke their access to the dashboard."]})]}),e.jsxs(Cr,{children:[e.jsx(B,{variant:"outline",onClick:()=>M(!1),children:"Cancel"}),e.jsx(B,{variant:"destructive",onClick:Jn,disabled:$,children:$?"Removing...":"Remove Agent"})]})]})}),e.jsx(AEt,{open:W,onOpenChange:G,fixedBrokerageId:s,onSuccess:Os}),e.jsx(Bs,{open:X,onOpenChange:te,children:e.jsxs(Fs,{children:[e.jsxs(qs,{children:[e.jsx($s,{children:"Add Brokerage Manager"}),e.jsx(Ar,{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(re,{children:"Select Agent"}),e.jsxs(rc,{open:xe,onOpenChange:ve,children:[e.jsx(ac,{asChild:!0,children:e.jsxs(B,{variant:"outline",role:"combobox","aria-expanded":xe,className:"w-full justify-between",children:[ne?((sa=r.find(Ve=>Ve.id===ne))==null?void 0:sa.name)+" ("+((xs=r.find(Ve=>Ve.id===ne))==null?void 0:xs.email)+")":"Select an agent to promote...",e.jsx(sb,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]})}),e.jsx(Zl,{className:"w-full p-0",align:"start",children:e.jsxs(db,{children:[e.jsx(ub,{placeholder:"Search by name or email..."}),e.jsxs(hb,{className:"max-h-[200px]",children:[e.jsx(mb,{children:"No eligible agents found."}),e.jsx(pb,{children:r.filter(Ve=>!en(Ve.id)).map(Ve=>e.jsxs(Ry,{value:`${Ve.name} ${Ve.email}`,onSelect:()=>{me(Ve.id),ve(!1)},children:[e.jsx(pa,{className:`mr-2 h-4 w-4 ${ne===Ve.id?"opacity-100":"opacity-0"}`}),Ve.name," (",Ve.email,")"]},Ve.id))})]})]})})]}),r.filter(Ve=>!en(Ve.id)).length===0&&e.jsx("p",{className:"mt-2 text-sm text-muted-foreground",children:"All agents are already brokerage managers."})]})}),e.jsxs(Cr,{children:[e.jsx(B,{variant:"outline",onClick:()=>te(!1),children:"Cancel"}),e.jsx(B,{onClick:Hs,disabled:ue||!ne,children:ue?"Adding...":"Add as Manager"})]})]})}),e.jsx(Bs,{open:ge,onOpenChange:be,children:e.jsxs(Fs,{children:[e.jsxs(qs,{children:[e.jsx($s,{children:"Edit Agent"}),e.jsxs(Ar,{children:["Update profile information for ",Se==null?void 0:Se.name]})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(re,{htmlFor:"edit-name",children:"Name"}),e.jsx(we,{id:"edit-name",value:Me.name,onChange:Ve=>Re({...Me,name:Ve.target.value}),placeholder:"Agent name"})]}),e.jsxs("div",{children:[e.jsx(re,{htmlFor:"edit-email",children:"Email"}),e.jsx(we,{id:"edit-email",type:"email",value:Me.email,onChange:Ve=>Re({...Me,email:Ve.target.value}),placeholder:"agent@example.com"}),Me.email.trim().toLowerCase()!==(Se==null?void 0:Se.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(re,{htmlFor:"edit-phone",children:"Phone"}),e.jsx(we,{id:"edit-phone",type:"tel",value:Me.phone,onChange:Ve=>Re({...Me,phone:Ve.target.value}),placeholder:"555-123-4567"})]})]}),e.jsxs(Cr,{children:[e.jsx(B,{variant:"outline",onClick:()=>be(!1),children:"Cancel"}),e.jsx(B,{onClick:As,disabled:Be||Ge,children:Ge?"Updating email...":Be?"Saving...":"Save Changes"})]})]})}),Ke&&e.jsx(TEt,{open:Ye,onOpenChange:Ve=>{Je(Ve),Ve||st(null)},userId:Ke.id,userName:Ke.name}),e.jsx(Bs,{open:rt,onOpenChange:Ze,children:e.jsxs(Fs,{children:[e.jsxs(qs,{children:[e.jsx($s,{children:"Set Password"}),e.jsxs(Ar,{children:["Set a new password for ",ht==null?void 0:ht.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(re,{htmlFor:"new-password",children:"New Password"}),e.jsx(we,{id:"new-password",type:"password",value:Ct,onChange:Ve=>Yt(Ve.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(Cr,{children:[e.jsx(B,{variant:"outline",onClick:()=>Ze(!1),children:"Cancel"}),e.jsx(B,{onClick:Bn,disabled:Kt||!Ct||Ct.length<6,children:Kt?"Setting...":"Set Password"})]})]})})]})},cun={academy_video:"Academy Video",template:"Template",toolbox:"Toolbox Resource",newsletter:"Newsletter",social_swag:"Social Swag",event:"Event"},dun={view:"Viewed",click_canva:"Opened Canva",click_pdf:"Downloaded PDF",click_video:"Watched Video",click_link:"Clicked Link",register:"Registered"},uun=s=>{switch(s){case"academy_video":return e.jsx(na,{className:"h-4 w-4"});case"template":return e.jsx(Wr,{className:"h-4 w-4"});case"toolbox":return e.jsx(Wr,{className:"h-4 w-4"});case"newsletter":return e.jsx(E_,{className:"h-4 w-4"});case"social_swag":return e.jsx(Cn,{className:"h-4 w-4"});case"event":return e.jsx(ta,{className:"h-4 w-4"});default:return e.jsx(Tr,{className:"h-4 w-4"})}},hun=({brokerageId:s})=>{const{toast:t}=Ci(),[n,r]=N.useState([]),[a,i]=N.useState([]),[l,o]=N.useState([]),[c,d]=N.useState(!0),[u,h]=N.useState(null);N.useEffect(()=>{m()},[s]);const m=async()=>{try{d(!0);const{data:y,error:x}=await H.from("profiles").select("id, name, email").eq("brokerage_id",s);if(x)throw x;const _=y.map($=>$.id),b=new Map(y.map($=>[$.id,$]));if(_.length===0){r([]),i([]),o([]);return}const{data:k,error:A}=await H.from("activity_logs").select("*").in("user_id",_).order("launched_at",{ascending:!1});if(A)throw A;const T=k.map($=>{var V,W;return{id:$.id,user_id:$.user_id,app_name:$.app_name,launched_at:$.launched_at,user_name:((V=b.get($.user_id))==null?void 0:V.name)||"Unknown",user_email:((W=b.get($.user_id))==null?void 0:W.email)||"Unknown"}});r(T);const{data:P,error:I}=await H.from("content_engagement_logs").select("*").in("user_id",_).order("created_at",{ascending:!1});if(I)throw I;const M=(P||[]).map($=>{var V,W;return{id:$.id,user_id:$.user_id,resource_type:$.resource_type,resource_id:$.resource_id,resource_title:$.resource_title,action_type:$.action_type,created_at:$.created_at,user_name:((V=b.get($.user_id))==null?void 0:V.name)||"Unknown",user_email:((W=b.get($.user_id))==null?void 0:W.email)||"Unknown"}});i(M);const L=new Map;y.forEach($=>{L.set($.id,{user_id:$.id,user_name:$.name,user_email:$.email,app_launches:0,content_views:0,last_activity:""})}),T.forEach($=>{const V=L.get($.user_id);V&&(V.app_launches++,(!V.last_activity||new Date($.launched_at)>new Date(V.last_activity))&&(V.last_activity=$.launched_at))}),M.forEach($=>{const V=L.get($.user_id);V&&(V.content_views++,(!V.last_activity||new Date($.created_at)>new Date(V.last_activity))&&(V.last_activity=$.created_at))});const z=Array.from(L.values()).filter($=>$.app_launches>0||$.content_views>0).sort(($,V)=>new Date(V.last_activity).getTime()-new Date($.last_activity).getTime());o(z)}catch(y){console.error("Error loading activity:",y),t({title:"Error",description:"Failed to load activity logs",variant:"destructive"})}finally{d(!1)}},f=y=>n.filter(x=>x.user_id===y),g=y=>a.filter(x=>x.user_id===y);return c?e.jsx(_e,{children:e.jsx(De,{className:"flex items-center justify-center py-8",children:e.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})})}):e.jsxs(e.Fragment,{children:[e.jsxs(_e,{children:[e.jsxs(zt,{children:[e.jsx(qt,{children:"Agent Activity"}),e.jsx(_r,{children:"Track app usage and content engagement - click an agent for details"})]}),e.jsx(De,{children:e.jsx("div",{className:"rounded-md border",children:e.jsxs(Oa,{children:[e.jsx(Fa,{children:e.jsxs(un,{children:[e.jsx(Mt,{children:"Agent"}),e.jsx(Mt,{className:"text-center",children:"App Launches"}),e.jsx(Mt,{className:"text-center",children:"Content Views"}),e.jsx(Mt,{children:"Last Active"})]})}),e.jsx(za,{children:l.length===0?e.jsx(un,{children:e.jsx(gt,{colSpan:4,className:"text-center text-muted-foreground",children:"No activity yet"})}):l.map(y=>e.jsxs(un,{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(We,{variant:"outline",className:"gap-1",children:[e.jsx(dd,{className:"h-3 w-3"}),y.app_launches]})}),e.jsx(gt,{className:"text-center",children:e.jsxs(We,{variant:"secondary",className:"gap-1",children:[e.jsx(Wr,{className:"h-3 w-3"}),y.content_views]})}),e.jsx(gt,{className:"text-sm text-muted-foreground",children:y.last_activity&&nc(new Date(y.last_activity),{addSuffix:!0})})]},y.user_id))})]})})})]}),e.jsx(Bs,{open:!!u,onOpenChange:y=>!y&&h(null),children:e.jsxs(Fs,{className:"max-w-3xl max-h-[80vh] overflow-hidden flex flex-col",children:[e.jsxs(qs,{children:[e.jsxs($s,{children:[u==null?void 0:u.name,"'s Activity"]}),e.jsx(Ar,{children:u==null?void 0:u.email})]}),e.jsxs(ya,{defaultValue:"content",className:"flex-1 overflow-hidden flex flex-col",children:[e.jsxs(va,{className:"grid w-full grid-cols-2",children:[e.jsx(ls,{value:"content",children:"Content Engagement"}),e.jsx(ls,{value:"apps",children:"App Launches"})]}),e.jsx(_s,{value:"content",className:"flex-1 overflow-auto",children:e.jsx("div",{className:"rounded-md border",children:e.jsxs(Oa,{children:[e.jsx(Fa,{children:e.jsxs(un,{children:[e.jsx(Mt,{children:"Resource"}),e.jsx(Mt,{children:"Type"}),e.jsx(Mt,{children:"Action"}),e.jsx(Mt,{children:"Time"})]})}),e.jsx(za,{children:u&&g(u.id).length===0?e.jsx(un,{children:e.jsx(gt,{colSpan:4,className:"text-center text-muted-foreground",children:"No content engagement yet"})}):u&&g(u.id).map(y=>e.jsxs(un,{children:[e.jsx(gt,{className:"max-w-[200px] truncate font-medium",children:y.resource_title}),e.jsx(gt,{children:e.jsxs(We,{variant:"outline",className:"gap-1",children:[uun(y.resource_type),cun[y.resource_type]||y.resource_type]})}),e.jsx(gt,{children:e.jsx("span",{className:"text-sm text-muted-foreground",children:dun[y.action_type]||y.action_type})}),e.jsx(gt,{className:"text-sm text-muted-foreground",children:nc(new Date(y.created_at),{addSuffix:!0})})]},y.id))})]})})}),e.jsx(_s,{value:"apps",className:"flex-1 overflow-auto",children:e.jsx("div",{className:"rounded-md border",children:e.jsxs(Oa,{children:[e.jsx(Fa,{children:e.jsxs(un,{children:[e.jsx(Mt,{children:"App"}),e.jsx(Mt,{children:"Time"})]})}),e.jsx(za,{children:u&&f(u.id).length===0?e.jsx(un,{children:e.jsx(gt,{colSpan:2,className:"text-center text-muted-foreground",children:"No app launches yet"})}):u&&f(u.id).map(y=>e.jsxs(un,{children:[e.jsx(gt,{children:e.jsx(We,{variant:"outline",children:y.app_name})}),e.jsx(gt,{className:"text-sm text-muted-foreground",children:nc(new Date(y.launched_at),{addSuffix:!0})})]},y.id))})]})})})]})]})})]})},mun=({brokerageId:s})=>{const{toast:t}=Ci(),[n,r]=N.useState({totalAgents:0,activeAgents:0,pendingAgents:0,totalLaunches:0,launchesThisWeek:0,launchesThisMonth:0}),[a,i]=N.useState(!0);N.useEffect(()=>{l()},[s]);const l=async()=>{try{i(!0);const{data:o,error:c}=await H.from("profiles").select("id").eq("brokerage_id",s);if(c)throw c;const d=o.map(T=>T.id),u=d.length;if(d.length===0){i(!1);return}const{data:h,error:m}=await H.from("profiles").select("id, email").in("id",d);if(m)throw m;const{count:f}=await H.from("profiles").select("*",{count:"exact",head:!0}).eq("brokerage_id",s).not("last_login","is",null),g=f||0,y=u-g,{count:x}=await H.from("activity_logs").select("*",{count:"exact",head:!0}).in("user_id",d),_=new Date;_.setDate(_.getDate()-7);const{count:b}=await H.from("activity_logs").select("*",{count:"exact",head:!0}).in("user_id",d).gte("launched_at",_.toISOString()),k=new Date;k.setMonth(k.getMonth()-1);const{count:A}=await H.from("activity_logs").select("*",{count:"exact",head:!0}).in("user_id",d).gte("launched_at",k.toISOString());r({totalAgents:u,activeAgents:g,pendingAgents:y,totalLaunches:x||0,launchesThisWeek:b||0,launchesThisMonth:A||0})}catch(o){console.error("Error loading analytics:",o),t({title:"Error",description:"Failed to load analytics",variant:"destructive"})}finally{i(!1)}};return a?e.jsx(_e,{children:e.jsx(De,{className:"flex items-center justify-center py-8",children:e.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})})}):e.jsxs("div",{className:"grid gap-4 md:grid-cols-2 lg:grid-cols-3",children:[e.jsxs(_e,{children:[e.jsxs(zt,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(qt,{className:"text-sm font-medium",children:"Total Agents"}),e.jsx(Yn,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(De,{children:[e.jsx("div",{className:"text-2xl font-bold",children:n.totalAgents}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[n.activeAgents," active, ",n.pendingAgents," pending"]})]})]}),e.jsxs(_e,{children:[e.jsxs(zt,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(qt,{className:"text-sm font-medium",children:"Active Agents"}),e.jsx(Po,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(De,{children:[e.jsx("div",{className:"text-2xl font-bold",children:n.activeAgents}),e.jsx("p",{className:"text-xs text-muted-foreground",children:n.totalAgents>0?`${Math.round(n.activeAgents/n.totalAgents*100)}% of total`:"0% of total"})]})]}),e.jsxs(_e,{children:[e.jsxs(zt,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(qt,{className:"text-sm font-medium",children:"Pending Invites"}),e.jsx(Xr,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(De,{children:[e.jsx("div",{className:"text-2xl font-bold",children:n.pendingAgents}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Awaiting setup"})]})]}),e.jsxs(_e,{children:[e.jsxs(zt,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(qt,{className:"text-sm font-medium",children:"Total App Launches"}),e.jsx(gg,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(De,{children:[e.jsx("div",{className:"text-2xl font-bold",children:n.totalLaunches}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"All time"})]})]}),e.jsxs(_e,{children:[e.jsxs(zt,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(qt,{className:"text-sm font-medium",children:"This Week"}),e.jsx(gg,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(De,{children:[e.jsx("div",{className:"text-2xl font-bold",children:n.launchesThisWeek}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Last 7 days"})]})]}),e.jsxs(_e,{children:[e.jsxs(zt,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(qt,{className:"text-sm font-medium",children:"This Month"}),e.jsx(gg,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(De,{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"})]})]})]})},pun=({brokerageId:s})=>{const[t,n]=N.useState([]),[r,a]=N.useState(!0),[i,l]=N.useState(!1),[o,c]=N.useState(!1),[d,u]=N.useState({description:"",maxUses:""});N.useEffect(()=>{h()},[s]);const h=async()=>{try{const{data:_,error:b}=await H.from("invite_codes").select("*").eq("brokerage_id",s).order("created_at",{ascending:!1});if(b)throw b;n(_||[])}catch(_){console.error("Error loading invite codes:",_),ie.error("Failed to load invite links")}finally{a(!1)}},m=()=>Math.random().toString(36).substring(2,8).toUpperCase(),f=async()=>{l(!0);try{const _=m(),{error:b}=await H.from("invite_codes").insert({code:_,description:d.description||null,max_uses:d.maxUses?parseInt(d.maxUses):null,brokerage_id:s,is_active:!0});if(b)throw b;ie.success("Invite link created!"),c(!1),u({description:"",maxUses:""}),h()}catch(_){console.error("Error creating invite code:",_),ie.error("Failed to create invite link")}finally{l(!1)}},g=async _=>{try{const{error:b}=await H.from("invite_codes").delete().eq("id",_);if(b)throw b;ie.success("Invite link deleted"),n(t.filter(k=>k.id!==_))}catch(b){console.error("Error deleting invite code:",b),ie.error("Failed to delete invite link")}},y=async(_,b)=>{try{const{error:k}=await H.from("invite_codes").update({is_active:!b}).eq("id",_);if(k)throw k;n(t.map(A=>A.id===_?{...A,is_active:!b}:A)),ie.success(`Invite link ${b?"deactivated":"activated"}`)}catch(k){console.error("Error toggling invite code:",k),ie.error("Failed to update invite link")}},x=_=>{const b=`${window.location.origin}/join?code=${_}`;navigator.clipboard.writeText(b),ie.success("Link copied to clipboard!")};return r?e.jsx(_e,{children:e.jsx(De,{className:"flex items-center justify-center py-8",children:e.jsx(us,{className:"h-6 w-6 animate-spin text-muted-foreground"})})}):e.jsxs(_e,{children:[e.jsxs(zt,{className:"flex flex-row items-center justify-between",children:[e.jsxs("div",{children:[e.jsxs(qt,{className:"flex items-center gap-2",children:[e.jsx(gc,{className:"h-5 w-5"}),"Agent Invite Links"]}),e.jsx(_r,{children:"Create shareable links for agents to join your brokerage"})]}),e.jsxs(Bs,{open:o,onOpenChange:c,children:[e.jsx(Ao,{asChild:!0,children:e.jsxs(B,{size:"sm",children:[e.jsx(nn,{className:"mr-2 h-4 w-4"}),"Create Link"]})}),e.jsxs(Fs,{children:[e.jsxs(qs,{children:[e.jsx($s,{children:"Create Invite Link"}),e.jsx(Ar,{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(re,{htmlFor:"description",children:"Description (optional)"}),e.jsx(we,{id:"description",placeholder:"e.g., New agent recruiting campaign",value:d.description,onChange:_=>u({...d,description:_.target.value})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{htmlFor:"maxUses",children:"Max Uses (optional)"}),e.jsx(we,{id:"maxUses",type:"number",placeholder:"Leave empty for unlimited",value:d.maxUses,onChange:_=>u({...d,maxUses:_.target.value})})]}),e.jsx(B,{onClick:f,disabled:i,className:"w-full",children:i?e.jsxs(e.Fragment,{children:[e.jsx(us,{className:"mr-2 h-4 w-4 animate-spin"}),"Creating..."]}):"Create Invite Link"})]})]})]})]}),e.jsx(De,{children:t.length===0?e.jsxs("div",{className:"text-center py-8 text-muted-foreground",children:[e.jsx(gc,{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(_=>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:_.code}),e.jsx(We,{variant:_.is_active?"default":"secondary",children:_.is_active?"Active":"Inactive"})]}),_.description&&e.jsx("p",{className:"text-sm text-muted-foreground mt-1 truncate",children:_.description}),e.jsxs("p",{className:"text-xs text-muted-foreground mt-1",children:[_.uses_count," uses",_.max_uses&&` / ${_.max_uses} max`]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(B,{variant:"ghost",size:"sm",onClick:()=>x(_.code),title:"Copy link",children:e.jsx(Pa,{className:"h-4 w-4"})}),e.jsx(B,{variant:"ghost",size:"sm",onClick:()=>y(_.id,_.is_active),title:_.is_active?"Deactivate":"Activate",children:_.is_active?"Disable":"Enable"}),e.jsx(B,{variant:"ghost",size:"sm",onClick:()=>g(_.id),className:"text-destructive hover:text-destructive",title:"Delete",children:e.jsx(qn,{className:"h-4 w-4"})})]})]},_.id))})})]})},fun=({open:s,onOpenChange:t,referralCode:n,brokerageId:r,senderName:a,brokerageName:i,onInvitesSent:l})=>{const[o,c]=N.useState(""),[d,u]=N.useState([]),[h,m]=N.useState(""),[f,g]=N.useState(!1),y=A=>/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(A),x=()=>{const A=o.trim().toLowerCase();if(A&&y(A)&&!d.includes(A)){if(d.length>=10){ie.error("Maximum 10 emails per invite");return}u([...d,A]),c("")}else A&&!y(A)?ie.error("Please enter a valid email address"):d.includes(A)&&ie.error("Email already added")},_=A=>{u(d.filter(T=>T!==A))},b=A=>{(A.key==="Enter"||A.key===",")&&(A.preventDefault(),x())},k=async()=>{if(d.length===0){ie.error("Please add at least one email address");return}g(!0);try{const{data:A,error:T}=await H.functions.invoke("send-referral-invite",{body:{emails:d,personalMessage:h.trim()||void 0,referralCode:n,brokerageId:r,senderName:a,brokerageName:i}});if(T)throw T;A.successCount===A.totalCount?ie.success(`${A.successCount} invite${A.successCount>1?"s":""} sent successfully!`):ie.warning(`${A.successCount} of ${A.totalCount} invites sent. Some failed.`),u([]),m(""),t(!1),l==null||l()}catch(A){console.error("Error sending invites:",A),ie.error("Failed to send invites. Please try again.")}finally{g(!1)}};return e.jsx(Bs,{open:s,onOpenChange:t,children:e.jsxs(Fs,{className:"sm:max-w-[550px]",children:[e.jsxs(qs,{children:[e.jsxs($s,{className:"flex items-center gap-2",children:[e.jsx(mn,{className:"h-5 w-5 text-primary"}),"Invite Broker Friends"]}),e.jsx(Ar,{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(Io,{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(re,{htmlFor:"email",children:"Email Addresses (up to 10)"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(we,{id:"email",type:"email",placeholder:"Enter email and press Enter",value:o,onChange:A=>c(A.target.value),onKeyDown:b,onBlur:x}),e.jsx(B,{type:"button",variant:"secondary",onClick:x,children:"Add"})]}),d.length>0&&e.jsx("div",{className:"flex flex-wrap gap-2 mt-2",children:d.map(A=>e.jsxs(We,{variant:"secondary",className:"flex items-center gap-1 pr-1",children:[A,e.jsx("button",{type:"button",onClick:()=>_(A),className:"ml-1 rounded-full p-0.5 hover:bg-muted",children:e.jsx(hr,{className:"h-3 w-3"})})]},A))})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{htmlFor:"message",children:"Personal Message (optional)"}),e.jsx(Ws,{id:"message",placeholder:"Add a personal note that will appear at the top of the email...",value:h,onChange:A=>m(A.target.value),rows:3,maxLength:500}),e.jsxs("p",{className:"text-xs text-muted-foreground text-right",children:[h.length,"/500 characters"]})]}),e.jsxs("div",{className:"bg-muted/50 rounded-lg p-4 space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm font-medium",children:[e.jsx(Cn,{className:"h-4 w-4 text-primary"}),"What they'll receive:"]}),e.jsxs("ul",{className:"text-xs text-muted-foreground space-y-1",children:[e.jsxs("li",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"w-1 h-1 rounded-full bg-primary"}),"Beautiful branded email from you"]}),e.jsxs("li",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"w-1 h-1 rounded-full bg-primary"}),"Your personal message (if added)"]}),e.jsxs("li",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"w-1 h-1 rounded-full bg-primary"}),"Key LevelUp features for brokerages"]}),e.jsxs("li",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"w-1 h-1 rounded-full bg-primary"}),"Direct signup link with your referral code"]})]})]})]}),e.jsxs("div",{className:"flex justify-end gap-2 pt-2",children:[e.jsx(B,{variant:"outline",onClick:()=>t(!1),children:"Cancel"}),e.jsx(B,{onClick:k,disabled:d.length===0||f,children:f?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"h-4 w-4 animate-spin rounded-full border-2 border-current border-t-transparent mr-2"}),"Sending..."]}):e.jsxs(e.Fragment,{children:[e.jsx(Rr,{className:"h-4 w-4 mr-2"}),"Send ",d.length>0&&`(${d.length})`," Invite",d.length!==1?"s":""]})})]})]})})},gun=({brokerageId:s,refreshTrigger:t})=>{const[n,r]=N.useState([]),[a,i]=N.useState(!0);N.useEffect(()=>{l()},[s,t]);const l=async()=>{try{const{data:c,error:d}=await H.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(We,{className:"bg-green-100 text-green-800 gap-1",children:[e.jsx(Po,{className:"h-3 w-3"}),"Signed Up"]});case"expired":return e.jsxs(We,{variant:"outline",className:"text-muted-foreground gap-1",children:[e.jsx(Nu,{className:"h-3 w-3"}),"Expired"]});default:return e.jsxs(We,{variant:"secondary",className:"gap-1",children:[e.jsx(Xr,{className:"h-3 w-3"}),"Pending"]})}};return a?e.jsx("div",{className:"flex justify-center py-4",children:e.jsx("div",{className:"h-5 w-5 animate-spin rounded-full border-2 border-primary border-t-transparent"})}):n.length===0?e.jsxs("div",{className:"text-center py-6 text-muted-foreground",children:[e.jsx(mn,{className:"h-8 w-8 mx-auto mb-2 opacity-50"}),e.jsx("p",{className:"text-sm",children:"No invites sent yet"}),e.jsx("p",{className:"text-xs",children:"Start inviting broker friends to earn rewards!"})]}):e.jsxs("div",{className:"space-y-2",children:[e.jsx("p",{className:"text-sm font-medium mb-3",children:"Recent Invites"}),n.map(c=>e.jsxs("div",{className:"flex items-center justify-between p-2.5 bg-muted/30 rounded-lg",children:[e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("p",{className:"text-sm font-medium truncate",children:c.recipient_email}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Sent ",Js(new Date(c.sent_at),"MMM d, yyyy")]})]}),o(c.status)]},c.id))]})},xun=()=>{const{brokerageId:s,user:t}=Ls(),[n,r]=N.useState(null),[a,i]=N.useState(""),[l,o]=N.useState(""),[c,d]=N.useState([]),[u,h]=N.useState(!0),[m,f]=N.useState(!1),[g,y]=N.useState(0);N.useEffect(()=>{s&&x()},[s]);const x=async()=>{try{const[P,I]=await Promise.all([H.from("brokerages").select("name").eq("id",s).single(),t?H.from("profiles").select("name").eq("id",t.id).single():Promise.resolve({data:null})]);P.data&&i(P.data.name),I.data&&o(I.data.name||"A LevelUp Member");const{data:M}=await H.from("referral_codes").select("code").eq("brokerage_id",s).single();if(M)r(M.code);else{const z=`REF${s==null?void 0:s.slice(0,8).toUpperCase()}`;await H.from("referral_codes").insert({brokerage_id:s,code:z}),r(z)}const{data:L}=await H.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(L||[])}catch(P){console.error("Error fetching referral data:",P)}finally{h(!1)}},_=()=>{const P=`https://dashboard.relevelup.com/?ref=${n}`;navigator.clipboard.writeText(P),ie.success("Referral link copied to clipboard!")},b=c.filter(P=>P.status==="qualified").length,k=c.filter(P=>P.status==="pending").length,A=b*25,T=Math.max(0,Math.ceil((299-A)/25));return u?null:e.jsxs(e.Fragment,{children:[e.jsxs(_e,{className:"overflow-hidden",children:[e.jsx("div",{className:"bg-gradient-to-r from-primary/10 via-primary/5 to-background border-b",children:e.jsxs("div",{className:"px-6 py-6",children:[e.jsxs("div",{className:"flex items-center gap-3 mb-2",children:[e.jsx("div",{className:"bg-primary/20 rounded-full p-2",children:e.jsx(Io,{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:["$",A]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Monthly Savings"})]}),A>0&&e.jsxs("div",{className:"flex items-center gap-1 text-green-600",children:[e.jsx(Po,{className:"h-4 w-4"}),e.jsx("span",{className:"text-sm font-medium",children:"Active"})]})]}),T>0&&A<299&&e.jsxs("div",{className:"text-right",children:[e.jsxs("p",{className:"text-sm font-medium",children:["Refer ",T," 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"})]}),A>=299&&e.jsxs("div",{className:"flex items-center gap-2 text-primary",children:[e.jsx(Cn,{className:"h-5 w-5"}),e.jsx("span",{className:"font-bold",children:"FREE Membership Unlocked!"})]})]})})]})}),e.jsxs(De,{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:()=>f(!0),className:"w-full",size:"lg",children:[e.jsx(mn,{className:"h-4 w-4 mr-2"}),"Invite Broker Friends"]}),e.jsxs(B,{onClick:_,variant:"outline",className:"w-full",size:"lg",children:[e.jsx(Pa,{className:"h-4 w-4 mr-2"}),"Copy Referral Link"]})]}),e.jsxs("div",{className:"p-4 bg-muted/50 rounded-lg",children:[e.jsx("p",{className:"text-xs text-muted-foreground mb-2",children:"Your Referral Link"}),e.jsxs("code",{className:"block px-3 py-2 bg-background rounded border text-sm break-all",children:["https://dashboard.relevelup.com/?ref=",n]})]}),e.jsxs("div",{className:"grid grid-cols-3 gap-4",children:[e.jsxs("div",{className:"text-center p-4 bg-green-50 dark:bg-green-950/20 rounded-lg border border-green-200 dark:border-green-900",children:[e.jsx(Ed,{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:["$",A]}),e.jsx("p",{className:"text-xs text-green-600 dark:text-green-500",children:"Monthly Savings"})]}),e.jsxs("div",{className:"text-center p-4 bg-primary/5 rounded-lg border border-primary/20",children:[e.jsx(Yn,{className:"h-5 w-5 mx-auto text-primary mb-1"}),e.jsx("p",{className:"text-2xl font-bold",children:b}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Qualified Referrals"})]}),e.jsxs("div",{className:"text-center p-4 bg-amber-50 dark:bg-amber-950/20 rounded-lg border border-amber-200 dark:border-amber-900",children:[e.jsx(Xr,{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:k}),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(gun,{brokerageId:s,refreshTrigger:g}),c.length>0&&e.jsxs("div",{className:"space-y-2",children:[e.jsx("p",{className:"text-sm font-medium",children:"Your Referrals"}),c.slice(0,5).map(P=>{var I,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:((I=P.referred_brokerage)==null?void 0:I.name)||((M=P.referred_user)==null?void 0:M.email)||"Pending setup"}),e.jsxs(We,{variant:P.status==="qualified"?"default":P.status==="pending"?"secondary":"destructive",className:P.status==="qualified"?"bg-green-600":"",children:[P.status==="qualified"&&e.jsx(Po,{className:"h-3 w-3 mr-1"}),P.status]})]},P.id)})]})]})]}),e.jsx(fun,{open:m,onOpenChange:f,referralCode:n||"",brokerageId:s||"",senderName:l||"A LevelUp Member",brokerageName:a,onInvitesSent:()=>y(P=>P+1)})]})},yun=({brokerageId:s})=>{const t=tr(),{teams:n,isLoading:r}=ZR(s),{data:a,isLoading:i}=mt({queryKey:["team-aggregate-stats",s,n.map(u=>u.id)],queryFn:async()=>{if(n.length===0)return[];const u=n.map(P=>P.id),{data:h}=await H.from("team_members").select("team_id, user_id, role").in("team_id",u);if(!h||h.length===0)return n.map(P=>({team_id:P.id,team_name:P.name,member_count:0,leader_name:null,leader_avatar:null,total_contacts:0,total_deals:0,total_videos:0}));const m=h.map(P=>P.user_id),f=h.filter(P=>P.role==="team_leader").map(P=>P.user_id),{data:g}=await H.from("profiles").select("id, name, avatar_url").in("id",f),y=new Map((g||[]).map(P=>[P.id,P])),{data:x}=await H.from("innercircle_contacts").select("owner_user_id").in("owner_user_id",m),{data:_}=await H.from("deal_pipeline").select("owner_user_id").in("owner_user_id",m),{data:b}=await H.from("agent_videos").select("owner_user_id").in("owner_user_id",m).eq("is_deleted",!1),k=new Map;(x||[]).forEach(P=>{k.set(P.owner_user_id,(k.get(P.owner_user_id)||0)+1)});const A=new Map;(_||[]).forEach(P=>{A.set(P.owner_user_id,(A.get(P.owner_user_id)||0)+1)});const T=new Map;return(b||[]).forEach(P=>{T.set(P.owner_user_id,(T.get(P.owner_user_id)||0)+1)}),n.map(P=>{const I=h.filter(G=>G.team_id===P.id),M=I.find(G=>G.role==="team_leader"),L=M?y.get(M.user_id):null,z=I.map(G=>G.user_id),$=z.reduce((G,X)=>G+(k.get(X)||0),0),V=z.reduce((G,X)=>G+(A.get(X)||0),0),W=z.reduce((G,X)=>G+(T.get(X)||0),0);return{team_id:P.id,team_name:P.name,member_count:I.length,leader_name:(L==null?void 0:L.name)||null,leader_avatar:(L==null?void 0:L.avatar_url)||null,total_contacts:$,total_deals:V,total_videos:W}})},enabled:n.length>0});if(r||i)return e.jsx("div",{className:"grid gap-4 md:grid-cols-2 lg:grid-cols-3",children:[1,2,3].map(u=>e.jsxs(_e,{children:[e.jsx(zt,{children:e.jsx(xn,{className:"h-5 w-32"})}),e.jsx(De,{children:e.jsx(xn,{className:"h-24 w-full"})})]},u))});if(n.length===0)return e.jsx(_e,{children:e.jsxs(De,{className:"flex flex-col items-center justify-center py-12 text-center",children:[e.jsx(Yn,{className:"h-12 w-12 text-muted-foreground mb-4"}),e.jsx("h3",{className:"text-lg font-semibold mb-2",children:"No Teams Yet"}),e.jsx("p",{className:"text-muted-foreground mb-4",children:"Create teams to organize your agents and track their performance."}),e.jsx(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(_e,{children:e.jsxs(De,{className:"pt-6",children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground mb-1",children:[e.jsx(Yn,{className:"h-4 w-4"})," Teams"]}),e.jsx("p",{className:"text-2xl font-bold",children:n.length})]})}),e.jsx(_e,{children:e.jsxs(De,{className:"pt-6",children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground mb-1",children:[e.jsx(Yn,{className:"h-4 w-4"})," Total Members"]}),e.jsx("p",{className:"text-2xl font-bold",children:o})]})}),e.jsx(_e,{children:e.jsxs(De,{className:"pt-6",children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground mb-1",children:[e.jsx(dD,{className:"h-4 w-4"})," Total Contacts"]}),e.jsx("p",{className:"text-2xl font-bold",children:c.toLocaleString()})]})}),e.jsx(_e,{children:e.jsxs(De,{className:"pt-6",children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground mb-1",children:[e.jsx(vg,{className:"h-4 w-4"})," Total Deals"]}),e.jsx("p",{className:"text-2xl font-bold",children:d.toLocaleString()})]})})]}),e.jsx("div",{className:"grid gap-4 md:grid-cols-2 lg:grid-cols-3",children:(a||[]).map(u=>e.jsxs(_e,{className:"hover:shadow-md transition-shadow",children:[e.jsxs(zt,{className:"pb-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(qt,{className:"text-lg",children:u.team_name}),e.jsxs(We,{variant:"secondary",children:[u.member_count," members"]})]}),u.leader_name&&e.jsxs("div",{className:"flex items-center gap-2 mt-2",children:[e.jsxs(Ua,{className:"h-6 w-6",children:[e.jsx(Gi,{src:u.leader_avatar||""}),e.jsx(qa,{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(q0,{className:"h-3 w-3 text-amber-500"}),u.leader_name]})]})]}),e.jsx(De,{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 →"})})]})},vun=()=>{const{user:s,isBrokerageManager:t,brokerageId:n,isAdmin:r,managedBrokerages:a,selectedBrokerageId:i,setSelectedBrokerageId:l}=Ls(),o=tr(),{toast:c}=Ci(),[d,u]=N.useState(""),[h,m]=N.useState(!0),f=i||(a.length>0?a[0].id:n);N.useEffect(()=>{if(!s||!t&&!r){o("/dashboard");return}!i&&a.length>0&&l(a[0].id),f?g():a.length===0&&!n&&m(!1)},[s,t,r,f,o,a,i]);const g=async()=>{if(!f){m(!1);return}try{const{data:y,error:x}=await H.from("brokerages").select("name").eq("id",f).single();if(x)throw x;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(Qs,{title:"Manage Brokerages",description:"Loading brokerage information...",children:e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})})}):f?e.jsx(Qs,{title:d||"Manage Brokerages",description:"Brokerage Management Dashboard",children:e.jsxs("div",{className:"space-y-6",children:[a.length>1&&e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("span",{className:"text-sm text-muted-foreground",children:"Managing:"}),e.jsxs(Ns,{value:i||"",onValueChange:l,children:[e.jsxs(ws,{className:"w-[280px]",children:[e.jsx(Ti,{className:"mr-2 h-4 w-4"}),e.jsx(ks,{placeholder:"Select brokerage"})]}),e.jsx(js,{children:a.map(y=>e.jsx(nt,{value:y.id,children:y.name},y.id))})]})]}),e.jsxs(ya,{defaultValue:"agents",className:"space-y-4",children:[e.jsxs(va,{className:"grid w-full grid-cols-4 md:grid-cols-8",children:[e.jsx(ls,{value:"agents",children:"Agents"}),e.jsx(ls,{value:"teams",children:"Teams"}),e.jsx(ls,{value:"invite",children:"Invite Links"}),e.jsx(ls,{value:"referrals",children:"Referrals"}),e.jsx(ls,{value:"leaderboard",children:"Leaderboard"}),e.jsx(ls,{value:"activity",children:"Activity"}),e.jsx(ls,{value:"analytics",children:"Analytics"}),e.jsx(ls,{value:"shares",children:"Shares"})]}),e.jsx(_s,{value:"agents",className:"space-y-4",children:e.jsx(lun,{brokerageId:f})}),e.jsx(_s,{value:"teams",className:"space-y-4",children:e.jsx(yun,{brokerageId:f})}),e.jsx(_s,{value:"invite",className:"space-y-4",children:e.jsx(pun,{brokerageId:f})}),e.jsx(_s,{value:"referrals",className:"space-y-4",children:e.jsx(xun,{})}),e.jsx(_s,{value:"leaderboard",className:"space-y-4",children:e.jsx(xAt,{brokerageId:f,title:`${d} Event Leaderboard`,showUserStats:!1})}),e.jsx(_s,{value:"activity",className:"space-y-4",children:e.jsx(hun,{brokerageId:f})}),e.jsx(_s,{value:"analytics",className:"space-y-4",children:e.jsx(mun,{brokerageId:f})}),e.jsx(_s,{value:"shares",className:"space-y-4",children:e.jsx(a6t,{brokerageOnly:!0,brokerageId:f})})]})]})}):e.jsx(Qs,{title:"Manage Brokerages",description:"Brokerage Management",children:e.jsxs("div",{className:"flex flex-col items-center justify-center py-12 text-center",children:[e.jsx(Ti,{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 bun({brokerageId:s,canManage:t}){const{user:n}=Ls(),[r,a]=N.useState([]),[i,l]=N.useState(!0),[o,c]=N.useState(!1),[d,u]=N.useState(null),[h,m]=N.useState(null),[f,g]=N.useState(!1),[y,x]=N.useState(""),[_,b]=N.useState(""),[k,A]=N.useState(!1),T=async()=>{try{const{data:z,error:$}=await H.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($)throw $;const V=z;if(V&&V.length>0){const W=[...new Set(V.map(ne=>ne.created_by))],{data:G}=await H.from("profiles").select("id, name, avatar_url").in("id",W),X=new Map((G==null?void 0:G.map(ne=>[ne.id,ne]))||[]),te=V.map(ne=>({...ne,author:X.get(ne.created_by)||{name:"Unknown",avatar_url:null}}));a(te)}else a([])}catch(z){console.error("Error fetching announcements:",z)}finally{l(!1)}};N.useEffect(()=>{T()},[s]);const P=()=>{x(""),b(""),A(!1),u(null)},I=z=>{z?(u(z),x(z.title),b(z.content),A(z.is_pinned)):P(),c(!0)},M=async()=>{if(!y.trim()||!_.trim()){ie.error("Please fill in all fields");return}g(!0);try{if(d){const{error:z}=await H.from("brokerage_announcements").update({title:y.trim(),content:_.trim(),is_pinned:k,pinned_at:k?new Date().toISOString():null}).eq("id",d.id);if(z)throw z;ie.success("Announcement updated")}else{const{error:z}=await H.from("brokerage_announcements").insert({brokerage_id:s,created_by:n==null?void 0:n.id,title:y.trim(),content:_.trim(),is_pinned:k,pinned_at:k?new Date().toISOString():null});if(z)throw z;ie.success("Announcement created")}c(!1),P(),T()}catch(z){console.error("Error saving announcement:",z),ie.error("Failed to save announcement")}finally{g(!1)}},L=async()=>{if(h)try{const{error:z}=await H.from("brokerage_announcements").delete().eq("id",h);if(z)throw z;ie.success("Announcement deleted"),T()}catch(z){console.error("Error deleting announcement:",z),ie.error("Failed to delete announcement")}finally{m(null)}};return i?e.jsxs(_e,{children:[e.jsx(zt,{children:e.jsxs(qt,{className:"flex items-center gap-2",children:[e.jsx(um,{className:"h-5 w-5"}),"Announcements"]})}),e.jsx(De,{children:e.jsx("div",{className:"animate-pulse space-y-3",children:e.jsx("div",{className:"h-20 bg-muted rounded"})})})]}):e.jsxs(e.Fragment,{children:[e.jsxs(_e,{children:[e.jsxs(zt,{className:"flex flex-row items-center justify-between space-y-0 pb-4",children:[e.jsxs(qt,{className:"flex items-center gap-2",children:[e.jsx(um,{className:"h-5 w-5 text-primary"}),"Announcements"]}),t&&e.jsxs(B,{size:"sm",onClick:()=>I(),className:"gap-1",children:[e.jsx(nn,{className:"h-4 w-4"}),"New"]})]}),e.jsx(De,{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(z=>{var $,V,W,G;return e.jsx("div",{className:`p-4 rounded-lg border ${z.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:[z.is_pinned&&e.jsx(DT,{className:"h-3.5 w-3.5 text-primary shrink-0"}),e.jsx("h4",{className:"font-semibold truncate",children:z.title})]}),e.jsx("p",{className:"text-sm text-muted-foreground whitespace-pre-wrap",children:z.content}),e.jsxs("div",{className:"flex items-center gap-2 mt-3 text-xs text-muted-foreground",children:[e.jsxs(Ua,{className:"h-5 w-5",children:[e.jsx(Gi,{src:(($=z.author)==null?void 0:$.avatar_url)||void 0}),e.jsx(qa,{className:"text-[10px]",children:((W=(V=z.author)==null?void 0:V.name)==null?void 0:W.charAt(0))||"?"})]}),e.jsx("span",{children:(G=z.author)==null?void 0:G.name}),e.jsx("span",{children:"•"}),e.jsx("span",{children:Js(new Date(z.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:()=>I(z),children:e.jsx(Ja,{className:"h-4 w-4"})}),e.jsx(B,{variant:"ghost",size:"icon",className:"h-8 w-8 text-destructive hover:text-destructive",onClick:()=>m(z.id),children:e.jsx(qn,{className:"h-4 w-4"})})]})]})},z.id)})})})]}),e.jsx(Bs,{open:o,onOpenChange:c,children:e.jsxs(Fs,{children:[e.jsx(qs,{children:e.jsx($s,{children:d?"Edit Announcement":"New Announcement"})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{htmlFor:"title",children:"Title"}),e.jsx(we,{id:"title",value:y,onChange:z=>x(z.target.value),placeholder:"Announcement title..."})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{htmlFor:"content",children:"Content"}),e.jsx(Ws,{id:"content",value:_,onChange:z=>b(z.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(zn,{id:"pinned",checked:k,onCheckedChange:A}),e.jsxs(re,{htmlFor:"pinned",className:"flex items-center gap-1 cursor-pointer",children:[e.jsx(DT,{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:f,children:f?"Saving...":d?"Update":"Create"})]})]})]})}),e.jsx(Fl,{open:!!h,onOpenChange:()=>m(null),children:e.jsxs(kl,{children:[e.jsxs(Sl,{children:[e.jsx(Al,{children:"Delete Announcement"}),e.jsx(Tl,{children:"Are you sure you want to delete this announcement? This action cannot be undone."})]}),e.jsxs(Cl,{children:[e.jsx(El,{children:"Cancel"}),e.jsx(wl,{onClick:L,className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:"Delete"})]})]})})]})}function _un({brokerageId:s,canManage:t=!1}){const{startImpersonation:n,isLoading:r}=s4e(),{user:a}=Ls(),[i,l]=N.useState([]),[o,c]=N.useState(!0),[d,u]=N.useState(""),[h,m]=N.useState(new Set);N.useEffect(()=>{(async()=>{try{const{data:y,error:x}=await H.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(x)throw x;if(l(y||[]),y&&y.length>0){const _=y.map(k=>k.id),{data:b}=await H.from("agent_assistant_assignments").select("agent_id").in("agent_id",_);b&&m(new Set(b.map(k=>k.agent_id)))}}catch(y){console.error("Error fetching agents:",y)}finally{c(!1)}})()},[s]);const f=i.filter(g=>{var y,x;return g.name.toLowerCase().includes(d.toLowerCase())||g.email.toLowerCase().includes(d.toLowerCase())||((y=g.title)==null?void 0:y.toLowerCase().includes(d.toLowerCase()))||((x=g.areas_served)==null?void 0:x.toLowerCase().includes(d.toLowerCase()))});return o?e.jsxs(_e,{children:[e.jsx(zt,{children:e.jsxs(qt,{className:"flex items-center gap-2",children:[e.jsx(Yn,{className:"h-5 w-5"}),"Agent Roster"]})}),e.jsx(De,{children:e.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-4",children:[1,2,3,4].map(g=>e.jsx("div",{className:"animate-pulse",children:e.jsx("div",{className:"h-48 bg-muted rounded-lg"})},g))})})]}):e.jsxs(_e,{children:[e.jsxs(zt,{className:"flex flex-col sm:flex-row sm:items-center justify-between gap-4 space-y-0",children:[e.jsxs(qt,{className:"flex items-center gap-2",children:[e.jsx(Yn,{className:"h-5 w-5 text-primary"}),"Agent Roster",e.jsxs("span",{className:"text-sm font-normal text-muted-foreground",children:["(",i.length,")"]})]}),e.jsxs("div",{className:"relative w-full sm:w-64",children:[e.jsx(Gr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(we,{placeholder:"Search agents...",value:d,onChange:g=>u(g.target.value),className:"pl-9"})]})]}),e.jsx(De,{children:f.length===0?e.jsx("p",{className:"text-sm text-muted-foreground text-center py-8",children:d?"No agents match your search":"No agents in this brokerage yet"}):e.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-4",children:f.map(g=>e.jsx(wun,{agent:g,hasAssistant:h.has(g.id),canImpersonate:t&&g.id!==(a==null?void 0:a.id),onImpersonate:()=>n(g.id,"/my-brokerage"),impersonationLoading:r},g.id))})})]})}function wun({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(Ua,{className:"h-20 w-20 mb-3 ring-2 ring-background shadow-md",children:[e.jsx(Gi,{src:s.avatar_url||void 0,alt:s.name}),e.jsx(qa,{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(We,{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(ii,{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(wu,{children:[e.jsx(ju,{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(gD,{className:"h-4 w-4"})})}),e.jsxs(nu,{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(ga,{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(mn,{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(W0,{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(dm,{className:"h-4 w-4"})})})]})]})}function jun({brokerageId:s}){const[t,n]=N.useState([]),[r,a]=N.useState(!0);if(N.useEffect(()=>{(async()=>{try{const{data:c,error:d}=await H.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 H.from("agent_attendance_stats").select("user_id, total_points").in("user_id",u).order("total_points",{ascending:!1});if(m)throw m;const f=new Map(c.map(y=>[y.id,y])),g=(h||[]).filter(y=>y.total_points>0).map(y=>{const x=f.get(y.user_id);return{user_id:y.user_id,total_points:y.total_points,name:(x==null?void 0:x.name)||"Unknown",avatar_url:(x==null?void 0:x.avatar_url)||null}});n(g)}catch(c){console.error("Error fetching leaderboard:",c)}finally{a(!1)}})()},[s]),r)return e.jsxs(_e,{children:[e.jsx(zt,{children:e.jsxs(qt,{className:"flex items-center gap-2",children:[e.jsx(gl,{className:"h-5 w-5"}),"Team Leaderboard"]})}),e.jsx(De,{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(i3,{className:Ot("h-5 w-5",i(o))}):e.jsx("span",{className:"w-5 text-center text-sm text-muted-foreground",children:o});return e.jsxs(_e,{children:[e.jsx(zt,{children:e.jsxs(qt,{className:"flex items-center gap-2",children:[e.jsx(gl,{className:"h-5 w-5 text-primary"}),"Team Leaderboard"]})}),e.jsx(De,{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:Ot("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(Ua,{className:"h-8 w-8",children:[e.jsx(Gi,{src:o.avatar_url||void 0}),e.jsx(qa,{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 Nun({brokerageId:s}){const t=tr(),[n,r]=N.useState([]),[a,i]=N.useState(!0);N.useEffect(()=>{(async()=>{try{const{data:c,error:d}=await H.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:f}=await H.from("listings").select(` id, slug, property_address, city, price, property_type, agent_id, listing_photos(photo_url) `).in("agent_id",u).eq("status","active").order("created_at",{ascending:!1}).limit(6);if(f)throw f;const g=(m||[]).map(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(g)}catch(c){console.error("Error fetching listings:",c)}finally{i(!1)}})()},[s]);const l=o=>new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:0}).format(o);return a?e.jsxs(_e,{children:[e.jsx(zt,{children:e.jsxs(qt,{className:"flex items-center gap-2",children:[e.jsx(_a,{className:"h-5 w-5"}),"Brokerage Listings"]})}),e.jsx(De,{children:e.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-4",children:[1,2].map(o=>e.jsx("div",{className:"animate-pulse",children:e.jsx("div",{className:"h-32 bg-muted rounded-lg"})},o))})})]}):e.jsxs(_e,{children:[e.jsxs(zt,{className:"flex flex-row items-center justify-between space-y-0 pb-4",children:[e.jsxs(qt,{className:"flex items-center gap-2",children:[e.jsx(_a,{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(nn,{className:"h-4 w-4"}),"Add Listing"]})]}),e.jsxs(De,{children:[n.length===0?e.jsxs("div",{className:"text-center py-8",children:[e.jsx(_a,{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(nn,{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(_a,{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(Tr,{className:"h-3 w-3 ml-1"})]})]})]})}function kun(){const{user:s,isAdmin:t,isBrokerageManager:n}=Ls(),r=tr(),[a,i]=N.useState(!0),[l,o]=N.useState(null),[c,d]=N.useState(""),[u,h]=N.useState(0),[m,f]=N.useState(!1),[g,y]=N.useState(!1);return N.useEffect(()=>{(async()=>{if(s)try{const{data:_}=await H.from("profiles").select("brokerage_id").eq("id",s.id).maybeSingle();if(!(_!=null&&_.brokerage_id)){i(!1);return}o(_.brokerage_id);const{data:b}=await H.from("brokerages").select("name").eq("id",_.brokerage_id).maybeSingle();b&&d(b.name);const{count:k}=await H.from("profiles").select("id",{count:"exact",head:!0}).eq("brokerage_id",_.brokerage_id);if(h(k||0),t)f(!0),y(!0);else if(n){const{data:A}=await H.from("brokerage_manager_assignments").select("id").eq("user_id",s.id).eq("brokerage_id",_.brokerage_id).maybeSingle();f(!!A),y(!!A)}}catch(_){console.error("Error fetching brokerage info:",_)}finally{i(!1)}})()},[s,t,n]),a?e.jsx(Qs,{title:"My Brokerage",description:"Loading...",children:e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})})}):l?e.jsx(Qs,{title:c||"My Brokerage",description:"Team Hub",children:e.jsxs("div",{className:"space-y-8",children:[e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-4",children:[e.jsxs("div",{className:"flex items-center gap-2 bg-muted/50 rounded-lg px-4 py-2",children:[e.jsx(Yn,{className:"h-5 w-5 text-primary"}),e.jsxs("span",{className:"font-medium",children:[u," ",u===1?"Agent":"Agents"]})]}),g&&e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(B,{variant:"outline",onClick:()=>r("/brokerage-content"),children:[e.jsx(Ep,{className:"h-4 w-4 mr-2"}),"Brokerage Content"]}),e.jsxs(B,{onClick:()=>r(`/mission-control/listings/new?brokerage=${l}`),children:[e.jsx(_a,{className:"h-4 w-4 mr-2"}),"Add Listing"]})]})]}),e.jsx(bun,{brokerageId:l,canManage:m}),e.jsx(_un,{brokerageId:l,canManage:m}),e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-8",children:[e.jsx(jun,{brokerageId:l}),e.jsx(Nun,{brokerageId:l})]})]})}):e.jsx(Qs,{title:"My Brokerage",description:"Team Hub",children:e.jsxs("div",{className:"flex flex-col items-center justify-center py-12 text-center",children:[e.jsx(Ti,{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 Sun(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 Cun(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 Gut={video:{icon:dd,label:"Video",color:"bg-red-500/10 text-red-600 dark:text-red-400"},pdf:{icon:Wr,label:"Document",color:"bg-blue-500/10 text-blue-600 dark:text-blue-400"},link:{icon:cd,label:"Link",color:"bg-green-500/10 text-green-600 dark:text-green-400"},event:{icon:ta,label:"Event",color:"bg-purple-500/10 text-purple-600 dark:text-purple-400"},graphic:{icon:zc,label:"Graphic",color:"bg-amber-500/10 text-amber-600 dark:text-amber-400"}};function Aun({item:s,canManage:t}){const[n,r]=N.useState(!1),[a,i]=N.useState(null),l=Sjs(),o=tr(),c=Gut[s.content_type]||Gut.link,d=c.icon,u=N.useMemo(()=>s.thumbnail_url?s.thumbnail_url:s.content_type==="graphic"&&s.file_url?s.file_url:s.content_type==="video"?Sun(s.url):null,[s]);N.useEffect(()=>{u||!s.url||s.content_type!=="video"||!Cun(s.url)||fetch(`https://www.youtube.com/oembed?url=${encodeURIComponent(s.url)}&format=json`).then(g=>g.ok?g.json():null).then(g=>{g!=null&&g.thumbnail_url&&i(g.thumbnail_url)}).catch(()=>{})},[s.url,s.content_type,u]);const h=u||a,m=()=>{o(`/brokerage-content/${s.id}`)},f=async()=>{try{await l.mutateAsync(s.id),ie.success("Content deleted")}catch{ie.error("Failed to delete")}r(!1)};return e.jsxs(e.Fragment,{children:[e.jsxs(_e,{className:"group overflow-hidden transition-all duration-200 hover:shadow-lg hover:border-primary/30 cursor-pointer",onClick:m,children:[h?e.jsx("div",{className:"aspect-video bg-muted/50 overflow-hidden",children:e.jsx("img",{src:h,alt:s.title,className:"w-full h-full object-cover group-hover:scale-105 transition-transform duration-300",referrerPolicy:"no-referrer"})}):e.jsx("div",{className:"aspect-video bg-muted/30 flex items-center justify-center",children:e.jsx(d,{className:"h-12 w-12 text-muted-foreground/30"})}),e.jsx(De,{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(We,{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(We,{variant:"outline",className:"text-[10px] px-1.5 py-0",children:[s.category.icon," ",s.category.name]})]}),e.jsx("h3",{className:"font-semibold text-sm text-foreground group-hover:text-primary transition-colors truncate",children:s.title}),s.description&&e.jsx("p",{className:"text-xs text-muted-foreground mt-1 line-clamp-2",children:s.description}),s.content_type==="event"&&s.event_date&&e.jsxs("p",{className:"text-xs text-primary mt-2 font-medium",children:["📅 ",Js(new Date(s.event_date),"MMM d, yyyy · h:mm a")]}),e.jsxs("p",{className:"text-[10px] text-muted-foreground mt-2",children:["Added ",Js(new Date(s.created_at),"MMM d, yyyy")]})]}),t&&e.jsxs(qd,{children:[e.jsx(Vd,{asChild:!0,onClick:g=>g.stopPropagation(),children:e.jsx(B,{variant:"ghost",size:"icon",className:"h-7 w-7 shrink-0",children:e.jsx(Ev,{className:"h-4 w-4"})})}),e.jsx(Ld,{align:"end",children:e.jsxs(ba,{onClick:g=>{g.stopPropagation(),r(!0)},className:"text-destructive",children:[e.jsx(qn,{className:"h-4 w-4 mr-2"}),"Delete"]})})]})]})})]}),e.jsx(Fl,{open:n,onOpenChange:r,children:e.jsxs(kl,{children:[e.jsxs(Sl,{children:[e.jsx(Al,{children:"Delete Content"}),e.jsxs(Tl,{children:['Are you sure you want to delete "',s.title,'"? This cannot be undone.']})]}),e.jsxs(Cl,{children:[e.jsx(El,{children:"Cancel"}),e.jsx(wl,{onClick:f,className:"bg-destructive text-destructive-foreground",children:"Delete"})]})]})})]})}function Tun(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 Wut=[{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 Eun({brokerageId:s,categories:t}){var he;const{user:n}=Ls(),[r,a]=N.useState(!1),[i,l]=N.useState(!1),[o,c]=N.useState(""),[d,u]=N.useState("📁"),[h,m]=N.useState(!1);N.useRef(null);const[f,g]=N.useState("video"),[y,x]=N.useState(""),[_,b]=N.useState(""),[k,A]=N.useState(""),[T,P]=N.useState(""),[I,M]=N.useState(""),[L,z]=N.useState(""),[$,V]=N.useState(""),W=kjs(),G=Cjs(s),X=Ajs(),te=Tjs(s),ne=()=>{g("video"),x(""),b(""),A(""),P(""),M(""),z(""),V("")},me=async(xe,ve)=>{var be;const ge=(be=xe.target.files)==null?void 0:be[0];if(ge){m(!0);try{const Se=ge.name.split(".").pop(),Ie=`${s}/${Date.now()}-${Math.random().toString(36).slice(2)}.${Se}`,{error:Me}=await H.storage.from("brokerage-content").upload(Ie,ge);if(Me)throw Me;const{data:{publicUrl:Re}}=H.storage.from("brokerage-content").getPublicUrl(Ie);ve==="file"?(P(Re),f==="graphic"&&!I&&M(Re)):M(Re),ie.success("File uploaded")}catch(Se){ie.error(Se.message||"Upload failed")}finally{m(!1)}}},ue=async()=>{if(!y.trim()){ie.error("Title is required");return}if(n)try{await W.mutateAsync({brokerage_id:s,category_id:$||null,content_type:f,title:y.trim(),description:_.trim()||null,url:k.trim()||null,file_url:T.trim()||null,thumbnail_url:I.trim()||null,event_date:L?new Date(L).toISOString():null,created_by:n.id}),ie.success("Content added!"),ne(),a(!1)}catch(xe){ie.error(xe.message||"Failed to add content")}},ce=async()=>{if(o.trim())try{await G.mutateAsync({name:o.trim(),icon:d,sort_order:t.length}),c(""),u("📁"),ie.success("Category created")}catch(xe){ie.error(xe.message||"Failed to create category")}},ae=async()=>{try{await te.mutateAsync(),ie.success("Default categories created")}catch{ie.error("Failed to create defaults")}};return e.jsxs("div",{className:"flex flex-wrap items-center gap-3",children:[e.jsxs(Bs,{open:r,onOpenChange:a,children:[e.jsx(Ao,{asChild:!0,children:e.jsxs(B,{children:[e.jsx(nn,{className:"h-4 w-4 mr-2"}),"Add Content"]})}),e.jsxs(Fs,{className:"max-w-lg max-h-[90vh] overflow-y-auto",children:[e.jsx(qs,{children:e.jsx($s,{children:"Add Brokerage Content"})}),e.jsxs("div",{className:"space-y-4 mt-2",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(re,{children:"Content Type"}),e.jsxs(Ns,{value:f,onValueChange:g,children:[e.jsx(ws,{children:e.jsx(ks,{})}),e.jsx(js,{children:Wut.map(xe=>e.jsx(nt,{value:xe.value,children:xe.label},xe.value))})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:(he=Wut.find(xe=>xe.value===f))==null?void 0:he.hint})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(re,{children:"Category"}),e.jsxs(Ns,{value:$,onValueChange:V,children:[e.jsx(ws,{children:e.jsx(ks,{placeholder:"Select category (optional)"})}),e.jsx(js,{children:t.map(xe=>e.jsxs(nt,{value:xe.id,children:[xe.icon," ",xe.name]},xe.id))})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(re,{children:"Title *"}),e.jsx(we,{value:y,onChange:xe=>x(xe.target.value),placeholder:"Content title"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(re,{children:"Description"}),e.jsx(Ws,{value:_,onChange:xe=>b(xe.target.value),placeholder:"Brief description...",rows:2})]}),["video","link","graphic","event"].includes(f)&&e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(re,{children:f==="video"?"Video URL":f==="graphic"?"Canva / Image URL":f==="event"?"Event Link (Zoom, etc.)":"URL"}),e.jsx(we,{value:k,onChange:xe=>{const ve=xe.target.value;if(A(ve),f==="video"&&!I){const ge=Tun(ve);ge&&M(ge)}},placeholder:"https://..."})]}),["pdf","graphic"].includes(f)&&e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(re,{children:f==="pdf"?"Upload PDF":"Upload Image"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(we,{type:"file",accept:f==="pdf"?".pdf,.doc,.docx":"image/*",onChange:xe=>me(xe,"file"),disabled:h}),h&&e.jsx(us,{className:"h-4 w-4 animate-spin"})]}),T&&e.jsx("p",{className:"text-xs text-green-600",children:"✓ File uploaded"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(re,{children:"Thumbnail Image (optional)"}),e.jsx(we,{type:"file",accept:"image/*",onChange:xe=>me(xe,"thumbnail"),disabled:h}),I&&e.jsxs("div",{className:"relative w-20 h-20 rounded overflow-hidden",children:[e.jsx("img",{src:I,className:"w-full h-full object-cover",alt:"thumb"}),e.jsx("button",{onClick:()=>M(""),className:"absolute top-0 right-0 bg-background/80 rounded-bl p-0.5",children:e.jsx(hr,{className:"h-3 w-3"})})]})]}),f==="event"&&e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(re,{children:"Event Date & Time"}),e.jsx(we,{type:"datetime-local",value:L,onChange:xe=>z(xe.target.value)})]}),e.jsxs(B,{onClick:ue,disabled:W.isPending||!y.trim(),className:"w-full",children:[W.isPending?e.jsx(us,{className:"h-4 w-4 animate-spin mr-2"}):e.jsx(nn,{className:"h-4 w-4 mr-2"}),"Add Content"]})]})]})]}),e.jsxs(Bs,{open:i,onOpenChange:l,children:[e.jsx(Ao,{asChild:!0,children:e.jsxs(B,{variant:"outline",size:"sm",children:[e.jsx(sc,{className:"h-4 w-4 mr-2"}),"Categories"]})}),e.jsxs(Fs,{className:"max-w-md",children:[e.jsx(qs,{children:e.jsx($s,{children:"Manage Categories"})}),e.jsxs("div",{className:"space-y-4 mt-2",children:[t.length===0&&e.jsxs("div",{className:"text-center py-4",children:[e.jsx("p",{className:"text-sm text-muted-foreground mb-3",children:"No categories yet"}),e.jsxs(B,{variant:"outline",size:"sm",onClick:ae,disabled:te.isPending,children:[te.isPending?e.jsx(us,{className:"h-4 w-4 animate-spin mr-2"}):null,"Create Default Categories"]})]}),t.map(xe=>e.jsxs("div",{className:"flex items-center justify-between p-2 rounded-lg border",children:[e.jsxs("span",{className:"text-sm",children:[xe.icon," ",xe.name]}),!xe.is_default&&e.jsx(B,{variant:"ghost",size:"icon",className:"h-7 w-7 text-destructive",onClick:async()=>{await X.mutateAsync(xe.id),ie.success("Category deleted")},children:e.jsx(hr,{className:"h-4 w-4"})})]},xe.id)),e.jsxs("div",{className:"flex gap-2 pt-2 border-t",children:[e.jsx(we,{value:d,onChange:xe=>u(xe.target.value),className:"w-14 text-center",maxLength:2}),e.jsx(we,{value:o,onChange:xe=>c(xe.target.value),placeholder:"New category name",className:"flex-1",onKeyDown:xe=>xe.key==="Enter"&&ce()}),e.jsx(B,{size:"sm",onClick:ce,disabled:!o.trim(),children:"Add"})]})]})]})]})]})}function Mun(){const{user:s,isAdmin:t,isBrokerageManager:n}=Ls(),[r,a]=N.useState(!0),[i,l]=N.useState(null),[o,c]=N.useState(""),[d,u]=N.useState(!1),[h,m]=N.useState(null),[f,g]=N.useState("");N.useEffect(()=>{(async()=>{if(s)try{const{data:A}=await H.from("profiles").select("brokerage_id").eq("id",s.id).maybeSingle();if(!(A!=null&&A.brokerage_id)){a(!1);return}l(A.brokerage_id);const{data:T}=await H.from("brokerages").select("name").eq("id",A.brokerage_id).maybeSingle();if(T&&c(T.name),t)u(!0);else if(n){const{data:P}=await H.from("brokerage_manager_assignments").select("id").eq("user_id",s.id).eq("brokerage_id",A.brokerage_id).maybeSingle();u(!!P)}}catch(A){console.error("Error fetching brokerage info:",A)}finally{a(!1)}})()},[s,t,n]);const{data:y=[]}=wjs(i),{data:x=[],isLoading:_}=jjs(i,h),b=N.useMemo(()=>{if(!f.trim())return x;const k=f.toLowerCase();return x.filter(A=>{var T;return A.title.toLowerCase().includes(k)||((T=A.description)==null?void 0:T.toLowerCase().includes(k))||A.content_type.toLowerCase().includes(k)})},[x,f]);return r?e.jsx(Qs,{title:"Brokerage Content",description:"Loading...",children:e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})})}):i?e.jsx(Qs,{title:`${o} Content`,description:"Brokerage Content Hub",children:e.jsxs("div",{className:"space-y-6",children:[d&&i&&e.jsx(Eun,{brokerageId:i,categories:y}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"relative max-w-sm",children:[e.jsx(Gr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(we,{placeholder:"Search content...",value:f,onChange:k=>g(k.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(k=>e.jsxs(B,{variant:h===k.id?"default":"outline",size:"sm",onClick:()=>m(k.id),children:[e.jsx("span",{className:"mr-1",children:k.icon}),k.name]},k.id))]})]}),_?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(_e,{className:"bg-muted/30 border-dashed",children:e.jsxs(De,{className:"flex flex-col items-center justify-center py-12",children:[e.jsx(H0,{className:"h-12 w-12 text-muted-foreground/50 mb-3"}),e.jsx("p",{className:"text-muted-foreground font-medium",children:f.trim()?"No matching content found":"No content yet"}),e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:f.trim()?"Try a different search term or category.":d?"Add your first piece of content above.":"Your brokerage hasn't added content yet."})]})}):e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4",children:b.map(k=>e.jsx(Aun,{item:k,canManage:d},k.id))})]})}):e.jsx(Qs,{title:"Brokerage Content",description:"Content Hub",children:e.jsxs("div",{className:"flex flex-col items-center justify-center py-12 text-center",children:[e.jsx(Ti,{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 Kut={video:{icon:dd,label:"Video",color:"bg-red-500/10 text-red-600 dark:text-red-400"},pdf:{icon:Wr,label:"Document",color:"bg-blue-500/10 text-blue-600 dark:text-blue-400"},link:{icon:cd,label:"Link",color:"bg-green-500/10 text-green-600 dark:text-green-400"},event:{icon:ta,label:"Event",color:"bg-purple-500/10 text-purple-600 dark:text-purple-400"},graphic:{icon:zc,label:"Graphic",color:"bg-amber-500/10 text-amber-600 dark:text-amber-400"}};function Lun(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 Pun(s){try{const t=new URL(s).hostname.replace("www.","");return["youtube.com","youtu.be","m.youtube.com"].includes(t)}catch{return!1}}function Iun(s){try{return new URL(s).hostname.includes("vimeo.com")}catch{return!1}}function Dun(s){try{const t=s.match(/vimeo\.com\/(\d+)/);if(t)return`https://player.vimeo.com/video/${t[1]}`}catch{}return null}function Run(){const{contentId:s}=uo(),{data:t,isLoading:n}=mt({queryKey:["brokerage-content-detail",s],queryFn:async()=>{const{data:d,error:u}=await H.from("brokerage_content").select(` *, category:brokerage_content_categories(*) `).eq("id",s).single();if(u)throw u;return d},enabled:!!s});if(n)return e.jsx(Qs,{title:"Brokerage Content",children:e.jsx("div",{className:"flex justify-center py-12",children:e.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})})});if(!t)return e.jsx(Qs,{title:"Brokerage Content",children:e.jsxs("div",{className:"flex flex-col items-center justify-center py-12 text-center",children:[e.jsx(Ti,{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(cr,{to:"/brokerage-content",children:"Back to Content"})})]})});const r=Kut[t.content_type]||Kut.link,a=r.icon,i=t.url||t.file_url,l=i&&Pun(i)?Lun(i):null,o=i&&Iun(i)?Dun(i):null,c=l||o;return e.jsx(Qs,{title:t.title,children:e.jsxs("div",{className:"space-y-6 max-w-4xl mx-auto",children:[e.jsx(B,{variant:"ghost",size:"sm",asChild:!0,className:"gap-2",children:e.jsxs(cr,{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(We,{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(We,{variant:"outline",className:"text-xs px-2 py-0.5",children:[t.category.icon," ",t.category.name]}),e.jsxs("span",{className:"text-xs text-muted-foreground ml-auto",children:["Added ",Js(new Date(t.created_at),"MMMM d, yyyy")]})]}),e.jsx("h1",{className:"text-2xl font-bold text-foreground",children:t.title}),c&&e.jsx(_e,{className:"overflow-hidden",children:e.jsx("div",{className:"relative w-full bg-black",style:{paddingTop:"56.25%"},children:e.jsx("iframe",{src:c,className:"absolute top-0 left-0 w-full h-full",allow:"accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture",allowFullScreen:!0,title:t.title})})}),t.content_type==="graphic"&&t.file_url&&!c&&e.jsx(_e,{className:"overflow-hidden",children:e.jsx("img",{src:t.file_url,alt:t.title,className:"w-full max-h-[600px] object-contain bg-muted"})}),!c&&t.content_type!=="graphic"&&t.thumbnail_url&&e.jsx(_e,{className:"overflow-hidden",children:e.jsx("img",{src:t.thumbnail_url,alt:t.title,className:"w-full max-h-[400px] object-cover"})}),t.description&&e.jsx(_e,{children:e.jsx(De,{className:"pt-6",children:e.jsx("p",{className:"text-muted-foreground whitespace-pre-wrap",children:t.description})})}),t.content_type==="event"&&t.event_date&&e.jsx(_e,{children:e.jsxs(De,{className:"pt-6 flex items-center gap-3",children:[e.jsx("div",{className:"p-2 rounded-md bg-primary/10",children:e.jsx(ta,{className:"h-5 w-5 text-primary"})}),e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium text-foreground",children:"Event Date"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:Js(new Date(t.event_date),"EEEE, MMMM d, yyyy · h:mm a")})]})]})}),e.jsxs("div",{className:"flex flex-wrap gap-3",children:[t.file_url&&e.jsx(B,{asChild:!0,size:"lg",children:e.jsxs("a",{href:t.file_url,target:"_blank",rel:"noopener noreferrer",children:[e.jsx(oi,{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(Tr,{className:"h-4 w-4 mr-2"}),c?"Open on YouTube":t.content_type==="event"?"Join Event":t.content_type==="graphic"?"Open in Canva":"Open Link"]})})]})]})})}const g5e={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 Oun(s="open"){const{user:t}=Ls();return mt({queryKey:["brokerage-help-requests",s,t==null?void 0:t.id],queryFn:async()=>{if(!t)return[];let n=H.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 H.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 Fun(s){return mt({queryKey:["brokerage-help-request",s],queryFn:async()=>{if(!s)return null;const{data:t,error:n}=await H.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 zun(s){return mt({queryKey:["brokerage-help-claims",s],queryFn:async()=>{if(!s)return[];const{data:t,error:n}=await H.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 Bun(){const s=as(),{user:t,brokerageId:n}=Ls();return _t({mutationFn:async r=>{if(!t||!n)throw new Error("You must be in a brokerage to post.");const{data:a,error:i}=await H.from("brokerage_help_requests").insert({...r,brokerage_id:n,requester_user_id:t.id}).select().single();if(i)throw i;try{await H.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 $un(){const s=as(),{user:t}=Ls();return _t({mutationFn:async({request_id:n,note:r})=>{if(!t)throw new Error("Not signed in");const{data:a,error:i}=await H.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 Uun(){const s=as();return _t({mutationFn:async({claim_id:t,request_id:n,claimant_user_id:r})=>{const{error:a}=await H.from("brokerage_help_claims").update({status:"accepted",responded_at:new Date().toISOString()}).eq("id",t);if(a)throw a;const{error:i}=await H.from("brokerage_help_requests").update({status:"filled",assigned_user_id:r}).eq("id",n);if(i)throw i;try{await H.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 qun(){const s=as();return _t({mutationFn:async({claim_id:t})=>{const{error:n}=await H.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 Vun(){const s=as();return _t({mutationFn:async t=>{const{error:n}=await H.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 Hun(){const s=as();return _t({mutationFn:async t=>{const{error:n}=await H.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 Gun(){const{user:s,brokerageId:t}=Ls(),n=as(),r=mt({queryKey:["brokerage-help-prefs",s==null?void 0:s.id,t],queryFn:async()=>{if(!s||!t)return null;const{data:i,error:l}=await H.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=_t({mutationFn:async i=>{if(!s||!t)throw new Error("No user/brokerage");const{error:l}=await H.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 Wun(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 Kun(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 Yun({req:s,onClick:t}){var i;const n=g5e[s.request_type],r=Wun(s.event_start_at,s.event_end_at),a=[s.address,s.city,s.state].filter(Boolean).join(", ");return e.jsx(_e,{className:"cursor-pointer hover:shadow-md transition group",onClick:t,children:e.jsxs(De,{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(We,{variant:"secondary",className:"text-xs",children:[n.emoji," ",n.label]}),s.status!=="open"&&e.jsx(We,{variant:"outline",className:"text-xs capitalize",children:s.status})]}),e.jsx(Qa,{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(Xr,{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(ii,{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(Ed,{className:"h-3.5 w-3.5 shrink-0"}),e.jsx("span",{children:Kun(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 Zun(){var c;const s=tr(),{brokerageId:t}=Ls(),[n,r]=N.useState("open"),{data:a=[],isLoading:i}=Oun(n),l=Gun(),o=((c=l.data)==null?void 0:c.email_enabled)??!0;return t?e.jsx(Qs,{title:"Help Board",description:"Ask a teammate to cover an open house, showing, or shift.",children:e.jsxs("div",{className:"space-y-5",children:[e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3",children:[e.jsx(ya,{value:n,onValueChange:d=>r(d),children:e.jsxs(va,{children:[e.jsx(ls,{value:"open",children:"Open"}),e.jsx(ls,{value:"mine",children:"My Posts"}),e.jsx(ls,{value:"my_claims",children:"My Claims"}),e.jsx(ls,{value:"filled",children:"Filled"})]})}),e.jsxs(B,{onClick:()=>s("/brokerage/help-board/new"),className:"gap-2",children:[e.jsx(nn,{className:"h-4 w-4"})," Post Request"]})]}),e.jsx(_e,{className:"bg-muted/30 border-dashed",children:e.jsxs(De,{className:"flex items-center justify-between py-3 px-5",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[o?e.jsx(yg,{className:"h-4 w-4 text-primary"}):e.jsx(d5,{className:"h-4 w-4 text-muted-foreground"}),e.jsxs("div",{children:[e.jsx(re,{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(zn,{id:"email-notif",checked:o,disabled:l.isLoading||l.isSaving,onCheckedChange:d=>l.setEmailEnabled(d)})]})}),i?e.jsx("div",{className:"flex items-center justify-center py-16",children:e.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})}):a.length===0?e.jsx(_e,{className:"bg-muted/30 border-dashed",children:e.jsxs(De,{className:"flex flex-col items-center justify-center py-12",children:[e.jsx(R2,{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(Yun,{req:d,onClick:()=>s(`/brokerage/help-board/${d.id}`)},d.id))})]})}):e.jsx(Qs,{title:"Help Board",description:"Brokerage Help Board",children:e.jsxs("div",{className:"flex flex-col items-center justify-center py-16 text-center",children:[e.jsx(R2,{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 Xun(){const s=tr(),{toast:t}=Ci(),n=Bun(),[r,a]=N.useState("open_house"),[i,l]=N.useState(""),[o,c]=N.useState(""),[d,u]=N.useState(""),[h,m]=N.useState(""),[f,g]=N.useState(""),[y,x]=N.useState(""),[_,b]=N.useState(""),[k,A]=N.useState(""),[T,P]=N.useState(""),[I,M]=N.useState(""),[L,z]=N.useState("goodwill"),[$,V]=N.useState(""),[W,G]=N.useState(""),X=r==="open_house"||r==="showing_coverage",te=r!=="general",ne=(ue,ce)=>!ue||!ce?null:`${ue}T${ce}:00`,me=async ue=>{if(ue.preventDefault(),!i.trim()){t({title:"Add a title",description:"Tell teammates what you need help with.",variant:"destructive"});return}try{const ce=ne(d,h),ae=ne(d,f);await n.mutateAsync({request_type:r,title:i.trim(),description:o.trim()||null,event_start_at:ce,event_end_at:ae,address:X&&y.trim()||null,city:X&&_.trim()||null,state:X&&k.trim()||null,zip:X&&T.trim()||null,mls_number:I.trim()||null,compensation_type:L,compensation_amount:$?Number($):null,compensation_notes:W.trim()||null}),t({title:"Posted!",description:"Your teammates have been notified."}),s("/brokerage/help-board")}catch(ce){t({title:"Could not post",description:(ce==null?void 0:ce.message)??"Something went wrong.",variant:"destructive"})}};return e.jsx(Qs,{title:"Post a Help Request",description:"Ask a teammate to cover for you",children:e.jsxs("div",{className:"max-w-2xl mx-auto",children:[e.jsxs(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:me,children:e.jsx(_e,{children:e.jsxs(De,{className:"p-6 space-y-6",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{children:"What do you need help with?"}),e.jsx("div",{className:"grid grid-cols-2 gap-2",children:Object.keys(g5e).map(ue=>{const ce=g5e[ue],ae=ue===r;return e.jsxs("button",{type:"button",onClick:()=>a(ue),className:`text-left p-3 rounded-lg border-2 transition ${ae?"border-primary bg-primary/5":"border-border hover:border-primary/40"}`,children:[e.jsx("div",{className:"text-lg",children:ce.emoji}),e.jsx("div",{className:"font-medium text-sm mt-1",children:ce.label}),e.jsx("div",{className:"text-xs text-muted-foreground line-clamp-1",children:ce.description})]},ue)})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{htmlFor:"title",children:"Title *"}),e.jsx(we,{id:"title",value:i,onChange:ue=>l(ue.target.value),placeholder:r==="open_house"?"Open house at 123 Oak St — Sat 1-3pm":"Quick description",maxLength:120,required:!0})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{htmlFor:"description",children:"Details"}),e.jsx(Ws,{id:"description",value:o,onChange:ue=>c(ue.target.value),placeholder:"Any context — lockbox code instructions later, what to expect, etc.",rows:3,maxLength:1e3})]}),te&&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(re,{htmlFor:"date",children:"Date"}),e.jsx(we,{id:"date",type:"date",value:d,onChange:ue=>u(ue.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{htmlFor:"start",children:"Start"}),e.jsx(we,{id:"start",type:"time",value:h,onChange:ue=>m(ue.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{htmlFor:"end",children:"End"}),e.jsx(we,{id:"end",type:"time",value:f,onChange:ue=>g(ue.target.value)})]})]}),X&&e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{htmlFor:"address",children:"Address"}),e.jsx(we,{id:"address",value:y,onChange:ue=>x(ue.target.value),placeholder:"123 Oak St"})]}),e.jsxs("div",{className:"grid grid-cols-3 gap-3",children:[e.jsxs("div",{className:"space-y-2 col-span-2",children:[e.jsx(re,{htmlFor:"city",children:"City"}),e.jsx(we,{id:"city",value:_,onChange:ue=>b(ue.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{htmlFor:"state",children:"State"}),e.jsx(we,{id:"state",value:k,onChange:ue=>A(ue.target.value.toUpperCase()),maxLength:2})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{htmlFor:"zip",children:"Zip"}),e.jsx(we,{id:"zip",value:T,onChange:ue=>P(ue.target.value),maxLength:10})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{htmlFor:"mls",children:"MLS # (optional)"}),e.jsx(we,{id:"mls",value:I,onChange:ue=>M(ue.target.value)})]})]})]}),e.jsxs("div",{className:"space-y-3 pt-2 border-t",children:[e.jsx(re,{children:"Compensation"}),e.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-3 gap-2",children:[{val:"goodwill",label:"Goodwill",sub:"Pay it forward"},{val:"flat_fee",label:"Flat Fee",sub:"Dollar amount"},{val:"referral_percent",label:"Referral %",sub:"On the deal"}].map(ue=>{const ce=L===ue.val;return e.jsxs("button",{type:"button",onClick:()=>z(ue.val),className:`text-left p-3 rounded-lg border-2 transition ${ce?"border-primary bg-primary/5":"border-border hover:border-primary/40"}`,children:[e.jsx("div",{className:"font-medium text-sm",children:ue.label}),e.jsx("div",{className:"text-xs text-muted-foreground",children:ue.sub})]},ue.val)})}),L!=="goodwill"&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{htmlFor:"amount",children:L==="flat_fee"?"Amount ($)":"Percent (%)"}),e.jsx(we,{id:"amount",type:"number",min:"0",step:L==="referral_percent"?"1":"5",value:$,onChange:ue=>V(ue.target.value),placeholder:L==="flat_fee"?"100":"25"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{htmlFor:"comp-notes",children:"Compensation notes"}),e.jsx(we,{id:"comp-notes",value:W,onChange:ue=>G(ue.target.value),placeholder:"e.g. Venmo same day, or split any leads",maxLength:200})]})]}),e.jsxs("div",{className:"flex justify-end gap-2 pt-2",children:[e.jsx(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(us,{className:"h-4 w-4 animate-spin"}),"Post & Notify Brokerage"]})]})]})})})]})})}function Qun(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 qLe(s){return s?s.split(" ").map(t=>t[0]).slice(0,2).join("").toUpperCase():"?"}function Jun(){var I,M,L,z,$,V,W,G;const{id:s}=uo(),t=tr(),{user:n}=Ls(),{toast:r}=Ci(),{data:a,isLoading:i}=Fun(s),{data:l=[]}=zun(s),o=$un(),c=Uun(),d=qun(),u=Vun(),h=Hun(),[m,f]=N.useState("");if(i)return e.jsx(Qs,{title:"Loading...",description:"",children:e.jsx("div",{className:"flex items-center justify-center py-16",children:e.jsx(us,{className:"h-8 w-8 animate-spin text-primary"})})});if(!a)return e.jsxs(Qs,{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 g=g5e[a.request_type],y=Qun(a.event_start_at,a.event_end_at),x=[a.address,a.city,a.state,a.zip].filter(Boolean).join(", "),_=(n==null?void 0:n.id)===a.requester_user_id,b=l.find(X=>X.claimant_user_id===(n==null?void 0:n.id)),k=l.find(X=>X.status==="accepted"),A=a.status==="open",T=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)",P=async()=>{if(!m.trim()){r({title:"Add a quick note",description:"Let the requester know you're available."});return}try{await o.mutateAsync({request_id:a.id,note:m.trim()}),r({title:"You're in!",description:"The requester will review and pick someone."}),f("")}catch(X){r({title:"Could not submit",description:X==null?void 0:X.message,variant:"destructive"})}};return e.jsx(Qs,{title:a.title,description:`${g.emoji} ${g.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(_e,{children:e.jsxs(De,{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(We,{variant:"secondary",children:[g.emoji," ",g.label]}),e.jsx(We,{variant:A?"default":"outline",className:"capitalize",children:a.status})]}),e.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[e.jsxs(Ua,{className:"h-7 w-7",children:[e.jsx(Gi,{src:((I=a.requester)==null?void 0:I.avatar_url)||void 0}),e.jsx(qa,{children:qLe((M=a.requester)==null?void 0:M.name)})]}),e.jsx("span",{children:((L=a.requester)==null?void 0:L.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(Xr,{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})]})]}),x&&e.jsxs("div",{className:"flex items-start gap-2 text-sm",children:[e.jsx(ii,{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:x})]})]}),e.jsxs("div",{className:"flex items-start gap-2 text-sm",children:[e.jsx(Ed,{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:T})]})]}),a.mls_number&&e.jsxs("div",{className:"flex items-start gap-2 text-sm",children:[e.jsx(CT,{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]})]})}),!_&&A&&!b&&e.jsx(_e,{children:e.jsxs(De,{className:"p-6 space-y-3",children:[e.jsx("h3",{className:"font-semibold",children:"Offer to cover this"}),e.jsx(Ws,{placeholder:"Quick note — e.g. 'I'm 10 min away and free that day'",value:m,onChange:X=>f(X.target.value),rows:3,maxLength:400}),e.jsxs(B,{onClick:P,disabled:o.isPending,className:"gap-2",children:[o.isPending&&e.jsx(us,{className:"h-4 w-4 animate-spin"}),"I can cover this"]})]})}),!_&&b&&e.jsx(_e,{className:"border-primary/30 bg-primary/5",children:e.jsxs(De,{className:"p-4 flex items-center gap-3",children:[e.jsx(pa,{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."]})]})]})}),k&&(_||k.claimant_user_id===(n==null?void 0:n.id))&&e.jsx(_e,{className:"border-primary/30",children:e.jsxs(De,{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(Ua,{className:"h-10 w-10",children:[e.jsx(Gi,{src:((z=k.claimant)==null?void 0:z.avatar_url)||void 0}),e.jsx(qa,{children:qLe(($=k.claimant)==null?void 0:$.name)})]}),e.jsxs("div",{children:[e.jsx("div",{className:"font-medium",children:(V=k.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:[((W=k.claimant)==null?void 0:W.email)&&e.jsxs("a",{href:`mailto:${k.claimant.email}`,className:"flex items-center gap-2 text-primary hover:underline",children:[e.jsx(mn,{className:"h-4 w-4"})," ",k.claimant.email]}),((G=k.claimant)==null?void 0:G.phone)&&e.jsxs("a",{href:`tel:${k.claimant.phone}`,className:"flex items-center gap-2 text-primary hover:underline",children:[e.jsx(ga,{className:"h-4 w-4"})," ",k.claimant.phone]})]})]})}),_&&e.jsx(_e,{children:e.jsxs(De,{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(X=>{var te,ne,me,ue,ce;return e.jsxs("div",{className:"flex items-start gap-3 p-3 rounded-lg border",children:[e.jsxs(Ua,{className:"h-10 w-10",children:[e.jsx(Gi,{src:((te=X.claimant)==null?void 0:te.avatar_url)||void 0}),e.jsx(qa,{children:qLe((ne=X.claimant)==null?void 0:ne.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:((me=X.claimant)==null?void 0:me.name)||"Teammate"}),e.jsx(We,{variant:"outline",className:"capitalize text-xs",children:X.status})]}),X.note&&e.jsxs("p",{className:"text-sm text-muted-foreground mt-1",children:['"',X.note,'"']}),X.status==="pending"&&A&&e.jsxs("div",{className:"flex gap-2 mt-2",children:[e.jsxs(B,{size:"sm",onClick:()=>c.mutate({claim_id:X.id,request_id:a.id,claimant_user_id:X.claimant_user_id}),disabled:c.isPending,className:"gap-1",children:[e.jsx(pa,{className:"h-3.5 w-3.5"})," Pick ",((ce=(ue=X.claimant)==null?void 0:ue.name)==null?void 0:ce.split(" ")[0])||"them"]}),e.jsxs(B,{size:"sm",variant:"ghost",onClick:()=>d.mutate({claim_id:X.id,request_id:a.id}),disabled:d.isPending,className:"gap-1",children:[e.jsx(hr,{className:"h-3.5 w-3.5"})," Pass"]})]})]})]},X.id)}),_&&A&&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"})}),_&&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 YPt({onSelect:s,maxHeight:t="460px"}){const[n,r]=N.useState(""),[a,i]=N.useState("all"),{data:l=[],isLoading:o}=mt({queryKey:["newsletter-graphics-picker"],queryFn:async()=>{const{data:u,error:h}=await H.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=N.useMemo(()=>{const u=new Set;return l.forEach(h=>u.add(h.category||"general")),["all",...Array.from(u).sort()]},[l]),d=N.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(Gr,{className:"absolute left-2.5 top-1/2 -translate-y-1/2 h-3.5 w-3.5 text-muted-foreground"}),e.jsx(we,{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(lo,{style:{maxHeight:t},className:"rounded-md border",children:o?e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsx(us,{className:"h-5 w-5 animate-spin text-muted-foreground"})}):d.length===0?e.jsxs("div",{className:"flex flex-col items-center justify-center py-12 text-center",children:[e.jsx(pc,{className:"h-8 w-8 text-muted-foreground/50 mb-2"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:l.length===0?"No graphics available yet":"No graphics match your search"})]}):e.jsx("div",{className:"grid grid-cols-2 sm:grid-cols-3 gap-2 p-2",children:d.map(u=>e.jsxs("button",{onClick:()=>s(u),className:"group relative rounded-md overflow-hidden border bg-muted/30 hover:ring-2 hover:ring-primary hover:border-primary transition-all text-left",title:u.title,children:[e.jsx("div",{className:"aspect-video bg-muted overflow-hidden",children:e.jsx("img",{src:u.thumbnail_url||u.image_url,alt:u.title,loading:"lazy",className:"w-full h-full object-cover group-hover:scale-105 transition-transform duration-200"})}),u.is_featured&&e.jsxs(We,{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(Wa,{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 ehn=[{key:"search",label:"Search for Properties",icon:Gr,defaultText:"Search for Properties",placeholder:"https://your-website.com/search",helper:"Link to your home search page"},{key:"call",label:"Call Agent",icon:ga,defaultText:"Call Me",hrefPrefix:"tel:",placeholder:"+15555551234",helper:"Your phone number"},{key:"email",label:"Email Agent",icon:mn,defaultText:"Email Me",hrefPrefix:"mailto:",placeholder:"you@email.com",helper:"Your email address"},{key:"schedule",label:"Schedule a Call",icon:ta,defaultText:"Schedule a Call",placeholder:"https://calendly.com/you",helper:"Link to your booking page"},{key:"listings",label:"View My Listings",icon:_a,defaultText:"View My Listings",placeholder:"https://your-website.com/listings",helper:"Link to your listings page"},{key:"valuation",label:"Get Home Value",icon:Ed,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:ii,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:Md,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:ru,defaultText:"Learn More",placeholder:"https://...",helper:"Any link you want"}];function Yut(s){const t=s.match(/(?:youtube\.com\/(?:watch\?v=|embed\/|v\/)|youtu\.be\/)([A-Za-z0-9_-]{11})/);return t?t[1]:null}function thn(s){const t=s.match(/vimeo\.com\/(?:video\/)?(\d+)/);return t?t[1]:null}function ZPt({html:s,onChange:t}){const{user:n}=Ls(),r=N.useRef(null),a=N.useRef(""),i=N.useRef(t);i.current=t;const[l,o]=N.useState("desktop"),c=N.useRef(null),[d,u]=N.useState(!1),[h,m]=N.useState(""),[f,g]=N.useState(""),y=N.useRef(null),x=()=>{var Nt;const At=(Nt=r.current)==null?void 0:Nt.contentDocument,Os=At==null?void 0:At.getSelection();Os&&Os.rangeCount>0&&(At!=null&&At.body.contains(Os.anchorNode))&&(y.current=Os.getRangeAt(0).cloneRange())},_=()=>{var It;const At=c.current,Os=(It=r.current)==null?void 0:It.contentDocument;if(!At||!Os)return;let Nt=h.trim();Nt&&!/^(https?:|mailto:|tel:|#|\/)/i.test(Nt)&&(Nt="https://"+Nt),At.setAttribute("href",Nt),At.setAttribute("target","_blank");const ms=f.trim();ms&&ms!==(At.textContent||"").trim()&&(At.textContent=ms);const Ys=` `+Os.documentElement.outerHTML;a.current=Ys,i.current(Ys),u(!1)};N.useEffect(()=>{var Nt,ms;const At=r.current;if(!At||a.current===s)return;const Os=()=>{const Ys=At.contentDocument;if(!Ys)return;Ys.open(),Ys.write(s||""),Ys.close(),a.current=s;const It=Ys.body;if(!It)return;It.setAttribute("contenteditable","true"),It.style.outline="none",It.style.minHeight="400px",It.style.cursor="text";const Ds=()=>{const Hs=` `+Ys.documentElement.outerHTML;a.current=Hs,i.current(Hs)};It.addEventListener("input",Ds),It.addEventListener("blur",Ds),It.addEventListener("mouseup",x),It.addEventListener("keyup",x),Ys.addEventListener("selectionchange",x);const As=Hs=>{var Jn;const Rs=Hs.target,en=Rs==null?void 0:Rs.closest("a");if(en){if(Hs.metaKey||Hs.ctrlKey||Hs.shiftKey)return;Hs.preventDefault(),Hs.stopPropagation(),c.current=en,m(en.getAttribute("href")||""),g((en.textContent||"").trim()),u(!0);return}const Rn=Ys.getSelection();if(!Rn)return;const Bn=(Jn=Ys.caretRangeFromPoint)==null?void 0:Jn.call(Ys,Hs.clientX,Hs.clientY),Dn=Bn==null?void 0:Bn.startContainer;if(Dn&&Dn.nodeType===Node.TEXT_NODE){const ua=Dn.textContent||"",Mr=Bn.startOffset,sn=ua.lastIndexOf("[",Mr),ki=ua.indexOf("]",Mr);if(sn!==-1&&ki!==-1&&ki>sn){const ia=Ys.createRange();ia.setStart(Dn,sn),ia.setEnd(Dn,ki+1),Rn.removeAllRanges(),Rn.addRange(ia),y.current=ia.cloneRange()}}};It.addEventListener("click",As,!0)};((Nt=At.contentDocument)==null?void 0:Nt.readyState)==="complete"||(ms=At.contentDocument)!=null&&ms.body?Os():At.addEventListener("load",Os,{once:!0})},[s]);const b=(At,Os)=>{var Ys;const Nt=(Ys=r.current)==null?void 0:Ys.contentDocument;if(!Nt)return;Nt.body.focus(),Nt.execCommand(At,!1,Os);const ms=` `+Nt.documentElement.outerHTML;a.current=ms,i.current(ms)},k=()=>{const At=window.prompt("Enter URL (https://...)");At&&b("createLink",At)},A=(At,Os)=>{var Ys;const Nt=(Ys=r.current)==null?void 0:Ys.contentDocument;if(!Nt)return;if(Nt.body.focus(),Os==="cursor"&&y.current&&Nt.body.contains(y.current.startContainer)){const It=Nt.getSelection();if(It){It.removeAllRanges(),It.addRange(y.current),Nt.execCommand("insertHTML",!1,At);const Ds=` `+Nt.documentElement.outerHTML;a.current=Ds,i.current(Ds);return}}Os==="top"?Nt.body.insertAdjacentHTML("afterbegin",At):Nt.body.insertAdjacentHTML("beforeend",At);const ms=` `+Nt.documentElement.outerHTML;a.current=ms,i.current(ms)},[T,P]=N.useState(!1),[I,M]=N.useState(null),[L,z]=N.useState(""),[$,V]=N.useState(""),[W,G]=N.useState("#406E71"),[X,te]=N.useState("cursor"),ne=At=>{M(At),z(At.defaultText),V(""),P(!0)},me=()=>{if(!I)return;const At=$.trim();if(!I.isForward&&!At)return;let Os=At;if(I.isForward){const It=At||"",Ds=encodeURIComponent("You should see this newsletter"),As=encodeURIComponent(It?`I thought you'd like this — take a look: ${It} `:`I thought you'd like this newsletter — take a look! `);Os=`mailto:?subject=${Ds}&body=${As}`}else I.hrefPrefix==="tel:"?Os="tel:"+At.replace(/[^0-9+]/g,""):I.hrefPrefix==="mailto:"?Os="mailto:"+At:/^https?:\/\//i.test(At)||(Os="https://"+At);const Nt=(L||I.defaultText).replace(/[<>]/g,""),ms=W||"#406E71",Ys=`
${Nt}

 

`;A(Ys,X),P(!1)},[ue,ce]=N.useState(!1),[ae,he]=N.useState(""),[xe,ve]=N.useState(""),[ge,be]=N.useState(""),[Se,Ie]=N.useState("cursor"),Me=(()=>{if(xe.trim())return xe.trim();const At=Yut(ae);return At?`https://i.ytimg.com/vi/${At}/hqdefault.jpg`:""})(),Re=()=>{he(""),ve(""),be(""),ce(!0)},Be=()=>{const At=ae.trim();if(!At)return;let Os=At;/^https?:\/\//i.test(Os)||(Os="https://"+Os);const Nt=Yut(Os),ms=Nt?null:thn(Os);let Ys=xe.trim();!Ys&&Nt&&(Ys=`https://i.ytimg.com/vi/${Nt}/hqdefault.jpg`),!Ys&&ms&&(Ys=`https://vumbnail.com/${ms}.jpg`),Ys||(Ys="https://placehold.co/600x340/406E71/ffffff?text=Watch+Video");const It=(ge||"Watch the video").replace(/[<>]/g,""),Ds=`
${It}
▶ ${It}

 

`.trim();A(Ds,Se),ce(!1)},[Ne,Ge]=N.useState(!1),[Ce,Fe]=N.useState(""),[Ae,Xe]=N.useState(""),[$e,Ye]=N.useState("full"),[Je,Ke]=N.useState("cursor"),[st,rt]=N.useState(!1),Ze=N.useRef(null),ht=()=>{Fe(""),Xe(""),Ye("full"),Ge(!0)},Bt=async At=>{var Os;if(!n){ie.error("You must be signed in to upload images");return}if(At.size>10*1024*1024){ie.error("Image must be under 10MB");return}rt(!0);try{const Nt=((Os=At.name.split(".").pop())==null?void 0:Os.toLowerCase())||"png",ms=`${n.id}/newsletters/${Date.now()}-${Math.random().toString(36).slice(2,8)}.${Nt}`,{error:Ys}=await H.storage.from("email-assets").upload(ms,At,{cacheControl:"3600",upsert:!1,contentType:At.type});if(Ys)throw Ys;const{data:It}=H.storage.from("email-assets").getPublicUrl(ms);Fe(It.publicUrl),ie.success("Image uploaded")}catch(Nt){ie.error(Nt.message||"Upload failed")}finally{rt(!1)}},Ct=()=>{if(!Ce.trim())return;const At=(Ae||"").replace(/[<>"]/g,""),Os=$e==="half"?280:560,Nt=`
${At}

 

`.trim();A(Nt,Je),Ge(!1)},{data:Yt,isLoading:Kt}=mt({queryKey:["newsletter-editor-videos",n==null?void 0:n.id],enabled:!!(n!=null&&n.id)&&ue,queryFn:async()=>{const{data:At,error:Os}=await H.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(Os)throw Os;return At||[]}}),Xs=At=>{At.share_token&&(he(`https://video.relevelup.com/share/video/${At.share_token}`),ve(`https://video.relevelup.com/thumb/${At.share_token}`),be(At.title||"Watch the video"))},zs=l==="mobile"?390:"100%",Vt=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(jT,{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(AT,{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(L9,{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(Kx,{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(dj,{className:"h-3.5 w-3.5"})}),e.jsx(B,{type:"button",variant:"ghost",size:"sm",className:"h-7 w-7 p-0",onClick:k,title:"Insert link",children:e.jsx(gc,{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(BT,{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(RT,{className:"h-3.5 w-3.5"})}),e.jsx("div",{className:"w-px h-5 bg-border mx-1"}),e.jsxs(qd,{children:[e.jsx(Vd,{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(ru,{className:"h-3.5 w-3.5"}),e.jsx("span",{className:"text-xs font-medium",children:"CTA Button"})]})}),e.jsxs(Ld,{align:"start",className:"w-56 bg-popover z-50",children:[e.jsx(cE,{children:"Insert a call-to-action"}),e.jsx(s1,{}),ehn.map(At=>{const Os=At.icon;return e.jsxs(ba,{onClick:()=>ne(At),children:[e.jsx(Os,{className:"h-4 w-4 mr-2"}),At.label]},At.key)})]})]}),e.jsxs(B,{type:"button",variant:"ghost",size:"sm",className:"h-7 px-2 gap-1.5",title:"Insert image",onClick:ht,children:[e.jsx(pc,{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:Re,children:[e.jsx(na,{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(Y9,{type:"single",value:l,onValueChange:At=>At&&o(At),size:"sm",className:"h-7",children:[e.jsx(PD,{value:"desktop",className:"h-7 px-2",title:"Desktop preview",children:e.jsx(hj,{className:"h-3.5 w-3.5"})}),e.jsx(PD,{value:"mobile",className:"h-7 px-2",title:"Mobile preview",children:e.jsx($y,{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(ru,{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:zs,maxWidth:Vt,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(Bs,{open:d,onOpenChange:u,children:e.jsxs(Fs,{className:"sm:max-w-md",children:[e.jsx(qs,{children:e.jsx($s,{children:"Edit link"})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{htmlFor:"link-edit-text",children:"Button / link text"}),e.jsx(we,{id:"link-edit-text",value:f,onChange:At=>g(At.target.value),placeholder:"Click here"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{htmlFor:"link-edit-href",children:"Where should this link go?"}),e.jsx(we,{id:"link-edit-href",value:h,onChange:At=>m(At.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(Cr,{children:[e.jsx(B,{type:"button",variant:"outline",onClick:()=>u(!1),children:"Cancel"}),e.jsx(B,{type:"button",onClick:_,disabled:!h.trim(),children:"Save link"})]})]})}),e.jsx(Bs,{open:T,onOpenChange:P,children:e.jsxs(Fs,{className:"sm:max-w-md",children:[e.jsx(qs,{children:e.jsxs($s,{children:["Insert ",(I==null?void 0:I.label)||"CTA Button"]})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{htmlFor:"cta-text",children:"Button text"}),e.jsx(we,{id:"cta-text",value:L,onChange:At=>z(At.target.value),placeholder:I==null?void 0:I.defaultText})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{htmlFor:"cta-value",children:I==null?void 0:I.helper}),e.jsx(we,{id:"cta-value",value:$,onChange:At=>V(At.target.value),placeholder:I==null?void 0:I.placeholder,autoFocus:!0})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{htmlFor:"cta-color",children:"Button color"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(we,{id:"cta-color",type:"color",value:W,onChange:At=>G(At.target.value),className:"h-9 w-16 p-1 cursor-pointer"}),e.jsx(we,{value:W,onChange:At=>G(At.target.value),className:"flex-1"})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{children:"Position"}),e.jsxs(K1,{value:X,onValueChange:At=>te(At),className:"flex gap-4 flex-wrap",children:[e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(Ju,{value:"cursor",id:"cta-cursor"}),e.jsxs(re,{htmlFor:"cta-cursor",className:"flex items-center gap-1.5 cursor-pointer font-normal",children:[e.jsx(ru,{className:"h-3.5 w-3.5"}),"At cursor"]})]}),e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(Ju,{value:"top",id:"cta-top"}),e.jsxs(re,{htmlFor:"cta-top",className:"flex items-center gap-1.5 cursor-pointer font-normal",children:[e.jsx(Om,{className:"h-3.5 w-3.5"}),"Top of newsletter"]})]}),e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(Ju,{value:"bottom",id:"cta-bottom"}),e.jsxs(re,{htmlFor:"cta-bottom",className:"flex items-center gap-1.5 cursor-pointer font-normal",children:[e.jsx(Wf,{className:"h-3.5 w-3.5"}),"Bottom of newsletter"]})]})]})]}),e.jsx("div",{className:"rounded-md border bg-muted/30 p-4 flex justify-center",children:e.jsx("div",{style:{backgroundColor:W,color:"#ffffff",borderRadius:6,padding:"14px 28px",fontFamily:"Arial, sans-serif",fontWeight:600,fontSize:16},children:L||(I==null?void 0:I.defaultText)})})]}),e.jsxs(Cr,{children:[e.jsx(B,{type:"button",variant:"outline",onClick:()=>P(!1),children:"Cancel"}),e.jsx(B,{type:"button",onClick:me,disabled:!(I!=null&&I.isForward)&&!$.trim(),children:"Insert Button"})]})]})}),e.jsx(Bs,{open:ue,onOpenChange:ce,children:e.jsxs(Fs,{className:"sm:max-w-lg max-h-[90vh] overflow-y-auto",children:[e.jsx(qs,{children:e.jsx($s,{children:"Insert Video Block"})}),e.jsxs(ya,{defaultValue:"library",className:"space-y-3",children:[e.jsxs(va,{className:"grid w-full grid-cols-3",children:[e.jsx(ls,{value:"library",children:"My Library"}),e.jsx(ls,{value:"url",children:"From URL"}),e.jsx(ls,{value:"record",children:"Record New"})]}),e.jsxs(_s,{value:"library",className:"space-y-3 mt-2",children:[Kt?e.jsxs("div",{className:"text-center py-8 text-sm text-muted-foreground",children:[e.jsx(us,{className:"h-5 w-5 animate-spin mx-auto mb-2"}),"Loading your videos..."]}):!Yt||Yt.length===0?e.jsxs("div",{className:"text-center py-8 text-sm text-muted-foreground border rounded-md",children:[e.jsx(na,{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:Yt.map(At=>{const Os=ae.includes(At.share_token||"___"),Nt=At.share_token?`https://video.relevelup.com/thumb/${At.share_token}`:At.thumbnail_url||"";return e.jsxs("button",{type:"button",onClick:()=>Xs(At),className:`group text-left rounded-md border-2 overflow-hidden transition-all ${Os?"border-primary ring-2 ring-primary/30":"border-transparent hover:border-primary/40"}`,children:[e.jsxs("div",{className:"aspect-video bg-muted relative",children:[Nt?e.jsx("img",{src:Nt,alt:At.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(na,{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(dd,{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:At.title||"Untitled"})})]},At.id)})}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(re,{htmlFor:"vid-title-lib",className:"text-xs",children:"Caption (optional)"}),e.jsx(we,{id:"vid-title-lib",value:ge,onChange:At=>be(At.target.value),placeholder:"Watch the video"})]})]}),e.jsxs(_s,{value:"url",className:"space-y-3 mt-2",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(re,{htmlFor:"vid-url",children:"Video URL"}),e.jsx(we,{id:"vid-url",value:ae,onChange:At=>he(At.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(re,{htmlFor:"vid-title",children:"Caption (optional)"}),e.jsx(we,{id:"vid-title",value:ge,onChange:At=>be(At.target.value),placeholder:"Watch the video"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(re,{htmlFor:"vid-thumb",children:"Custom thumbnail URL (optional)"}),e.jsx(we,{id:"vid-thumb",value:xe,onChange:At=>ve(At.target.value),placeholder:"https://... (only if not YouTube/Vimeo)"})]})]}),e.jsx(_s,{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(na,{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(re,{children:"Position"}),e.jsxs(K1,{value:Se,onValueChange:At=>Ie(At),className:"flex gap-4 flex-wrap",children:[e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(Ju,{value:"cursor",id:"vid-cursor"}),e.jsxs(re,{htmlFor:"vid-cursor",className:"flex items-center gap-1.5 cursor-pointer font-normal",children:[e.jsx(ru,{className:"h-3.5 w-3.5"}),"At cursor"]})]}),e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(Ju,{value:"top",id:"vid-top"}),e.jsxs(re,{htmlFor:"vid-top",className:"flex items-center gap-1.5 cursor-pointer font-normal",children:[e.jsx(Om,{className:"h-3.5 w-3.5"}),"Top"]})]}),e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(Ju,{value:"bottom",id:"vid-bottom"}),e.jsxs(re,{htmlFor:"vid-bottom",className:"flex items-center gap-1.5 cursor-pointer font-normal",children:[e.jsx(Wf,{className:"h-3.5 w-3.5"}),"Bottom"]})]})]})]}),Me&&e.jsxs("div",{className:"rounded-md border bg-muted/30 p-3",children:[e.jsx("p",{className:"text-xs text-muted-foreground mb-2",children:"Preview"}),e.jsxs("div",{className:"relative",children:[e.jsx("img",{src:Me,alt:"thumbnail",className:"w-full rounded-md",style:{maxHeight:180,objectFit:"cover"},onError:At=>{At.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(Cr,{children:[e.jsx(B,{type:"button",variant:"outline",onClick:()=>ce(!1),children:"Cancel"}),e.jsx(B,{type:"button",onClick:Be,disabled:!ae.trim(),children:"Insert Video"})]})]})}),e.jsx(Bs,{open:Ne,onOpenChange:Ge,children:e.jsxs(Fs,{className:"sm:max-w-md max-h-[90vh] overflow-y-auto",children:[e.jsx(qs,{children:e.jsx($s,{children:"Insert Image"})}),e.jsxs(ya,{defaultValue:"library",className:"space-y-3",children:[e.jsxs(va,{className:"grid w-full grid-cols-3",children:[e.jsx(ls,{value:"library",children:"Library"}),e.jsx(ls,{value:"upload",children:"Upload"}),e.jsx(ls,{value:"url",children:"From URL"})]}),e.jsx(_s,{value:"library",className:"mt-2",children:e.jsx(YPt,{maxHeight:"380px",onSelect:At=>{Fe(At.image_url),Ae||Xe(At.title)}})}),e.jsxs(_s,{value:"upload",className:"space-y-3 mt-2",children:[e.jsx("input",{ref:Ze,type:"file",accept:"image/png,image/jpeg,image/webp,image/gif",className:"hidden",onChange:At=>{var Nt;const Os=(Nt=At.target.files)==null?void 0:Nt[0];Os&&Bt(Os),At.target.value=""}}),Ce?e.jsxs("div",{className:"rounded-md border overflow-hidden bg-muted/30",children:[e.jsx("img",{src:Ce,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 At;return(At=Ze.current)==null?void 0:At.click()},disabled:st,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:st?e.jsxs(e.Fragment,{children:[e.jsx(us,{className:"h-8 w-8 mx-auto mb-2 animate-spin text-primary"}),e.jsx("p",{className:"text-sm",children:"Uploading..."})]}):e.jsxs(e.Fragment,{children:[e.jsx(ni,{className:"h-8 w-8 mx-auto mb-2 text-muted-foreground"}),e.jsx("p",{className:"text-sm font-medium",children:"Click to upload an image"}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:"PNG, JPG, WEBP, GIF · up to 10MB"})]})})]}),e.jsxs(_s,{value:"url",className:"space-y-3 mt-2",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(re,{htmlFor:"img-url",children:"Image URL"}),e.jsx(we,{id:"img-url",value:Ce,onChange:At=>Fe(At.target.value),placeholder:"https://..."})]}),Ce&&/^https?:\/\//i.test(Ce)&&e.jsx("div",{className:"rounded-md border overflow-hidden bg-muted/30",children:e.jsx("img",{src:Ce,alt:"Preview",className:"w-full max-h-48 object-contain",onError:At=>{At.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(re,{htmlFor:"img-alt",children:"Alt text (for accessibility)"}),e.jsx(we,{id:"img-alt",value:Ae,onChange:At=>Xe(At.target.value),placeholder:"Describe the image"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(re,{children:"Size"}),e.jsxs(K1,{value:$e,onValueChange:At=>Ye(At),className:"flex gap-4",children:[e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(Ju,{value:"full",id:"img-full"}),e.jsx(re,{htmlFor:"img-full",className:"cursor-pointer font-normal",children:"Full width"})]}),e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(Ju,{value:"half",id:"img-half"}),e.jsx(re,{htmlFor:"img-half",className:"cursor-pointer font-normal",children:"Half width"})]})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(re,{children:"Position"}),e.jsxs(K1,{value:Je,onValueChange:At=>Ke(At),className:"flex gap-4 flex-wrap",children:[e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(Ju,{value:"cursor",id:"img-cursor"}),e.jsxs(re,{htmlFor:"img-cursor",className:"flex items-center gap-1.5 cursor-pointer font-normal",children:[e.jsx(ru,{className:"h-3.5 w-3.5"}),"At cursor"]})]}),e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(Ju,{value:"top",id:"img-top"}),e.jsxs(re,{htmlFor:"img-top",className:"flex items-center gap-1.5 cursor-pointer font-normal",children:[e.jsx(Om,{className:"h-3.5 w-3.5"}),"Top"]})]}),e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(Ju,{value:"bottom",id:"img-bottom"}),e.jsxs(re,{htmlFor:"img-bottom",className:"flex items-center gap-1.5 cursor-pointer font-normal",children:[e.jsx(Wf,{className:"h-3.5 w-3.5"}),"Bottom"]})]})]})]})]}),e.jsxs(Cr,{children:[e.jsx(B,{type:"button",variant:"outline",onClick:()=>Ge(!1),children:"Cancel"}),e.jsx(B,{type:"button",onClick:Ct,disabled:!Ce.trim()||st,children:"Insert Image"})]})]})})]})}const Zut="newsletter-content",shn="inline-images";function nhn(s,t){const n=atob(s),r=new Array(n.length);for(let a=0;a{const{data:M}=await H.from("team_members").select("team_id, role").eq("user_id",a.id).maybeSingle();return M}}),T=(A==null?void 0:A.role)==="team_leader",P=(A==null?void 0:A.team_id)??null;N.useEffect(()=>{s&&(d((n==null?void 0:n.title)??""),h((n==null?void 0:n.description)??""),f((n==null?void 0:n.html_content)??ihn()),y((n==null?void 0:n.is_template)??!1),_((n==null?void 0:n.share_scope)??"private"))},[s,n]);const I=async()=>{if(a){if(!c.trim()){ie.error("Please enter a title");return}if(!m.trim()){ie.error("Newsletter content is empty");return}k(!0);try{const M=await rhn(m);M!==m&&f(M);const L={user_id:a.id,title:c.trim(),description:u.trim()||null,html_content:M,is_template:g,share_scope:x,shared_team_id:x==="team"?P:null,shared_brokerage_id:x==="brokerage"?o:null};if(x==="team"&&!P){ie.error("You must be a team leader to share with a team"),k(!1);return}if(x==="brokerage"&&!l){ie.error("Only brokerage managers can share to a brokerage"),k(!1);return}if(x==="global"&&!i){ie.error("Only admins can publish global starter templates"),k(!1);return}let z;if(n!=null&&n.id?{error:z}=await H.from("agent_custom_newsletters").update(L).eq("id",n.id):{error:z}=await H.from("agent_custom_newsletters").insert(L),z)throw z;ie.success(n!=null&&n.id?"Saved":"Newsletter created"),r==null||r(),t(!1)}catch(M){ie.error(M.message||"Failed to save")}finally{k(!1)}}};return e.jsx(Bs,{open:s,onOpenChange:t,children:e.jsxs(Fs,{className:"max-w-6xl h-[92vh] flex flex-col p-0",children:[e.jsx(qs,{className:"px-6 pt-6 pb-3 border-b",children:e.jsx($s,{children:n!=null&&n.id?"Edit Newsletter":"Create Newsletter"})}),e.jsxs("div",{className:"flex-1 overflow-y-auto px-6 py-4 space-y-4",children:[e.jsxs("div",{className:"grid sm:grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx(re,{htmlFor:"acn-title",children:"Title *"}),e.jsx(we,{id:"acn-title",value:c,onChange:M=>d(M.target.value),placeholder:"e.g. June Market Update"})]}),e.jsxs("div",{children:[e.jsx(re,{htmlFor:"acn-desc",children:"Description (optional)"}),e.jsx(we,{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(zn,{id:"acn-template",checked:g,onCheckedChange:y}),e.jsx(re,{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"})]}),(T||l||i)&&e.jsxs("div",{className:"rounded-lg border p-4 space-y-3",children:[e.jsx(re,{className:"text-sm font-semibold",children:"Sharing"}),e.jsxs(K1,{value:x,onValueChange:M=>_(M),className:"space-y-2",children:[e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsx(Ju,{value:"private",id:"s-private",className:"mt-0.5"}),e.jsxs(re,{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"})]})]}),T&&e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsx(Ju,{value:"team",id:"s-team",className:"mt-0.5"}),e.jsxs(re,{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(Ju,{value:"brokerage",id:"s-brokerage",className:"mt-0.5"}),e.jsxs(re,{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(Ju,{value:"global",id:"s-global",className:"mt-0.5"}),e.jsxs(re,{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(re,{className:"mb-2 block",children:"Content"}),e.jsx(ZPt,{html:m,onChange:f})]})]}),e.jsxs(Cr,{className:"px-6 py-3 border-t",children:[e.jsx(B,{variant:"outline",onClick:()=>t(!1),disabled:b,children:"Cancel"}),e.jsxs(B,{onClick:I,disabled:b,children:[b?e.jsx(us,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(Kl,{className:"h-4 w-4 mr-2"}),n!=null&&n.id?"Save Changes":"Create"]})]})]})})}function ihn(){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 iGe=/\[[^\]\[<>]{2,80}\]/g;function ohn(s){return s.match(iGe)||[]}function Xut(s){const t=s.toLowerCase();return t.charAt(0).toUpperCase()+t.slice(1)}function lhn(s){const t=[],n=new RegExp(iGe.source,"g");let r;for(;(r=n.exec(s))!==null;)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 · ${Xut(h)}`:`Date ${i[l.token]}`:(m=Xut(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 chn({html:s,onChange:t,originalHtml:n}){const r=N.useMemo(()=>lhn(s),[s]),[a,i]=N.useState({}),[l,o]=N.useState([]),c=N.useRef(null);c.current===null&&s&&(c.current=n??s);const d=N.useRef(!1);N.useEffect(()=>{if(d.current){d.current=!1;return}i({}),o([])},[s]);const u=()=>{const _=new RegExp(iGe.source,"g");let b=0;const k=s.replace(_,A=>{const T=(a[b]||"").trim();return b+=1,T||A});k!==s&&(o(A=>[...A,{html:s,values:a}]),d.current=!0,i({}),t(k))},h=()=>{const _=l[l.length-1];_&&(o(b=>b.slice(0,-1)),d.current=!0,i(_.values),t(_.html))},m=()=>{const _=c.current;!_||_===s||(o([]),d.current=!0,i({}),t(_))},f=l.length>0,g=!!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:!f,children:[e.jsx(TW,{className:"h-3.5 w-3.5 mr-1"}),"Undo last fill"]}),e.jsxs(B,{type:"button",size:"sm",variant:"ghost",onClick:m,disabled:!g,children:[e.jsx(hf,{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(Hr,{className:"h-4 w-4 text-emerald-600 shrink-0"}),e.jsx("span",{className:"text-muted-foreground",children:"All template fields are filled in. Your name, phone, website and brokerage fill in automatically."})]}),(f||g)&&e.jsxs("div",{className:"flex flex-wrap items-center gap-2 pl-6",children:[e.jsx("span",{className:"text-xs text-muted-foreground",children:"Made a typo?"}),y]})]});const x=r.filter(_=>(a[_.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(xd,{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(We,{variant:"secondary",className:"shrink-0",children:[x,"/",r.length," ready"]})]}),e.jsx("div",{className:"grid grid-cols-1 gap-4",children:r.map(_=>e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(re,{className:"text-[11px] uppercase tracking-wide text-muted-foreground",children:_.label}),e.jsx(we,{value:a[_.index]||"",placeholder:_.hint,className:"h-10 text-sm",onChange:b=>i(k=>({...k,[_.index]:b.target.value})),onKeyDown:b=>{b.key==="Enter"&&(b.preventDefault(),u())}})]},_.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(N9,{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 $U(){var a;const{user:s}=Ls(),{data:t,isLoading:n}=mt({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([H.from("mass_email_settings").select("reply_to_email, display_name").eq("user_id",s.id).maybeSingle(),H.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 OCe(){const{user:s}=Ls();return mt({queryKey:["verified-sender-check",s==null?void 0:s.id],enabled:!!s,staleTime:3e4,queryFn:async()=>{const[t,n]=await Promise.all([H.from("user_verified_senders").select("id, email, status").eq("user_id",s.id),H.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 FCe({open:s,onOpenChange:t,hasPending:n,pendingEmails:r}){const a=tr();return e.jsx(Bs,{open:s,onOpenChange:t,children:e.jsxs(Fs,{className:"sm:max-w-md",children:[e.jsxs(qs,{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(Uo,{className:"h-5 w-5"})}),e.jsx($s,{children:"Verify your sending email first"})]}),e.jsx(Ar,{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(Xr,{className:"h-4 w-4"})," Waiting for you to click Amazon's link"]}),r.map(i=>e.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[e.jsx(mn,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{className:"truncate",children:i})]},i)),e.jsx("p",{className:"text-xs text-muted-foreground pt-1",children:"Check that inbox (and your spam folder) for an email from Amazon Web Services and click the verification link."})]}):e.jsx("div",{className:"rounded-lg border bg-muted/40 p-3 text-sm text-muted-foreground",children:"It only takes a minute — add your email address on the Integrations page, then click the verification link Amazon sends you."}),e.jsxs(Cr,{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(Tr,{className:"h-4 w-4 mr-1"}),n?"Manage senders":"Verify my email"]})]})]})})}function UU(){const s=Ya();return mt({queryKey:["custom-tags",s],queryFn:async()=>{const{data:t,error:n}=await H.from("contact_custom_tags").select("*").eq("owner_user_id",s).order("name");if(n)throw n;return t},enabled:!!s})}function dhn(s){return mt({queryKey:["contact-custom-tags",s],queryFn:async()=>{const{data:t,error:n}=await H.from("contact_custom_tag_assignments").select("*, tag:contact_custom_tags(*)").eq("contact_id",s);if(n)throw n;return t},enabled:!!s})}function oGe(){const s=as(),t=Ya();return _t({mutationFn:async({name:n,color:r})=>{const{data:a,error:i}=await H.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 uhn(){const s=as();return _t({mutationFn:async t=>{const{error:n}=await H.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 hhn(){const s=as();return _t({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 H.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 XPt(){const s=as();return _t({mutationFn:async({contactId:t,tagId:n})=>{const{error:r}=await H.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 mhn(){const s=as();return _t({mutationFn:async({contactId:t,tagId:n})=>{const{error:r}=await H.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 zCe(){const s=Ya();return mt({queryKey:["all-contact-custom-tags",s],queryFn:async()=>{const{data:t,error:n}=await H.from("contact_custom_tag_assignments").select("contact_id, tag_id, tag:contact_custom_tags(id, name, color)");if(n)throw n;return t},enabled:!!s})}function lGe(){const{user:s}=Ls();return mt({queryKey:["contact-smart-lists",s==null?void 0:s.id],queryFn:async()=>{const{data:t,error:n}=await H.from("contact_smart_lists").select("*").order("created_at",{ascending:!1});if(n)throw n;return t},enabled:!!s})}function QPt(){const s=as(),{user:t}=Ls();return _t({mutationFn:async({name:n,filters:r,sort_by:a})=>{const{data:i,error:l}=await H.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"]}),xa({title:"Smart filter saved"})},onError:n=>{xa({title:"Error saving smart filter",description:n.message,variant:"destructive"})}})}function JPt(){const s=as();return _t({mutationFn:async t=>{const{error:n}=await H.from("contact_smart_lists").delete().eq("id",t);if(n)throw n},onSuccess:()=>{s.invalidateQueries({queryKey:["contact-smart-lists"]}),xa({title:"Smart filter deleted"})}})}const Qut=s=>s.replace(/&/g,"&").replace(//g,">").replace(/"/g,""");function Jut(s,t,n,r){const a=t.name||`${t.first_name||""} ${t.last_name||""}`.trim()||"there",i=new Date,l=new Intl.DateTimeFormat("en-US",{timeZone:"America/New_York",month:"long",day:"numeric",year:"numeric"}).format(i),o=new Intl.DateTimeFormat("en-US",{timeZone:"America/New_York",year:"numeric"}).format(i),c=(n==null?void 0:n.name)||"",d=c.split(/\s+/).filter(Boolean).map(f=>f[0]).join("").slice(0,2).toUpperCase(),u=((n==null?void 0:n.website_url)||"").trim(),h=[n==null?void 0:n.return_address_line1,[n==null?void 0:n.return_address_city,n==null?void 0:n.return_address_state].filter(Boolean).join(", "),n==null?void 0:n.return_address_zip].filter(Boolean).join(" · "),m={first_name:t.first_name||"there",last_name:t.last_name||"",name:a,full_name:a,email:t.email||"",phone:t.phone||"",address:t.address||"",city:t.city||"",state:t.state||"",zip:t.zip||t.zip_code||"",agent_name:c,agent_first_name:c.split(" ")[0]||"",agent_initials:d,agent_email:(n==null?void 0:n.email)||"",agent_phone:(n==null?void 0:n.phone)||"",agent_title:(n==null?void 0:n.title)||"",agent_website:u.replace(/^https?:\/\//i,"").replace(/\/$/,""),agent_website_url:u?/^https?:\/\//i.test(u)?u:`https://${u}`:"#",market_city:(n==null?void 0:n.market_city)||t.city||"",brokerage:r||(n==null?void 0:n.brokerage_name)||"",brokerage_address:h,current_date:l,current_year:o};return s.replace(/\{\{\s*(\w+)\s*\}\}/g,(f,g)=>m[g]??`{{${g}}}`)}function phn(s,t,n,r){const a=t.trim()?`
${Qut(t).replace(/\n/g,"
")}
`:"",i=n.trim()?`
${Qut(n).replace(/\n/g,"
")}
`:"",l=r?`
${r}
`:"";return`${a} ${s} ${i} ${l}`}function fhn(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 ghn=["free","act now","click here","limited time","urgent","$$$","100% free","guarantee","no obligation","risk-free","winner","cash bonus","make money","earn extra","amazing"];function xhn(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=ghn.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 cGe({open:s,onOpenChange:t,newsletterId:n,newsletterTitle:r,htmlCode:a}){const{user:i}=Ls();_f();const{isReady:l,settings:o}=$U(),{data:c}=OCe(),[d,u]=N.useState(!1),h=Ya(),{data:m}=mt({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:rn}=await H.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 rn}}),[f,g]=N.useState("visual"),[y,x]=N.useState("all"),[_,b]=N.useState(""),[k,A]=N.useState(""),[T,P]=N.useState(""),[I,M]=N.useState(""),[L,z]=N.useState(!0),[$,V]=N.useState([]),[W,G]=N.useState(null),[X,te]=N.useState(new Set),[ne,me]=N.useState(""),[ue,ce]=N.useState(!1),[ae,he]=N.useState(!1),[xe,ve]=N.useState(!1),[ge,be]=N.useState({sent:0,failed:0,total:0,currentName:""}),[Se,Ie]=N.useState(!0),[Me,Re]=N.useState(!1),[Be,Ne]=N.useState([]),[Ge,Ce]=N.useState(!1),[Fe,Ae]=N.useState(new Set),[Xe,$e]=N.useState("now"),[Ye,Je]=N.useState(""),{data:Ke=[]}=UU(),{data:st=[]}=zCe(),{data:rt=[]}=lGe(),{data:Ze=[],isLoading:ht}=mt({queryKey:["newsletter-send-contacts",h],enabled:!!h&&s,queryFn:async()=>{const rn=[];let Zn=0;const sa=1e3;for(;;){const{data:xs,error:Ve}=await H.from("innercircle_contacts").select("id, first_name, last_name, email, phone, address, city, state, zip, zip_code").eq("owner_user_id",h).not("email","is",null).neq("email","").order("first_name").range(Zn,Zn+sa-1);if(Ve)throw Ve;if(!xs||xs.length===0||(rn.push(...xs),xs.length{const{data:rn}=await H.from("ses_suppressed_emails").select("email");return(rn||[]).map(Zn=>Zn.email.toLowerCase())}}),{data:Ct}=mt({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:rn}=await H.from("profiles").select("brokerage_id").eq("id",i.id).maybeSingle();if(!(rn!=null&&rn.brokerage_id))return null;const{data:Zn}=await H.from("brokerages").select("name, city, state").eq("id",rn.brokerage_id).maybeSingle();return Zn}}),{data:Yt}=mt({queryKey:["newsletter-active-lead-site",h],enabled:!!h&&s,staleTime:5*60*1e3,queryFn:async()=>{if(!h)return null;const{data:rn}=await H.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 rn}}),Kt=!!(Yt!=null&&Yt.mls_provider_id),Xs=(Yt==null?void 0:Yt.mls_agent_id)||(Yt==null?void 0:Yt.mls_agent_key)||null,{data:zs=[],isLoading:Vt}=mt({queryKey:["newsletter-agent-listings",h,Xs],enabled:!!h&&!!Xs&&Ge,staleTime:60*1e3,queryFn:async()=>{if(!Xs)return[];const{data:rn}=await H.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",Xs).eq("standard_status","Active").order("modification_timestamp",{ascending:!1}).limit(30);return rn||[]}}),{data:At=[],isLoading:Os}=mt({queryKey:["newsletter-exchange-listings",h],enabled:!!h&&Ge,staleTime:60*1e3,queryFn:async()=>{const{data:rn}=await H.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),Zn=rn||[];if(Zn.length===0)return[];const sa=Zn.map(ft=>ft.id),{data:xs}=await H.from("listing_photos").select("listing_id, photo_url, is_primary, sort_order").in("listing_id",sa),Ve=new Map,it=new Map;for(const ft of xs||[])ft.is_primary&&!Ve.has(ft.listing_id)&&Ve.set(ft.listing_id,ft.photo_url),it.has(ft.listing_id)||it.set(ft.listing_id,ft.photo_url);return Zn.map(ft=>({...ft,_photo:Ve.get(ft.id)||it.get(ft.id)||""}))}}),{data:Nt=!1}=mt({queryKey:["newsletter-exchange-listings-exists",h],enabled:!!h&&s,staleTime:5*60*1e3,queryFn:async()=>{const{count:rn}=await H.from("listings").select("id",{count:"exact",head:!0}).eq("agent_id",h).in("status",["active","coming_soon","office_exclusive","pre_market"]);return(rn||0)>0}}),ms=N.useMemo(()=>{const rn=new Set(Bt);return Ze.filter(Zn=>Zn.email&&Zn.email.includes("@")&&!rn.has(Zn.email.toLowerCase()))},[Ze,Bt]),Ys=N.useMemo(()=>{if($.length===0)return null;const rn=new Set;for(const Zn of st)$.includes(Zn.tag_id)&&rn.add(Zn.contact_id);return rn},[st,$]),It=N.useMemo(()=>rt.find(rn=>rn.id===W)||null,[rt,W]),Ds=N.useMemo(()=>{var rn;if(y==="all")return ms;if(y==="tags")return Ys?ms.filter(Zn=>Ys.has(Zn.id)):[];if(y==="smartlists"){if(!It)return[];const Zn=(((rn=It.filters)==null?void 0:rn.search)||"").toLowerCase().trim();return Zn?ms.filter(sa=>`${sa.first_name||""} ${sa.last_name||""}`.toLowerCase().includes(Zn)||(sa.email||"").toLowerCase().includes(Zn)):ms}return ms.filter(Zn=>X.has(Zn.id))},[y,ms,Ys,It,X]),As=N.useMemo(()=>{if(!ne.trim())return ms;const rn=ne.toLowerCase();return ms.filter(Zn=>`${Zn.first_name||""} ${Zn.last_name||""}`.toLowerCase().includes(rn))},[ms,ne]);N.useEffect(()=>{s&&(b(""),A(`Hi {{first_name}}, Sharing this month's update — hope you find something useful!`),P(`As always, reach out anytime if I can help. Talk soon!`),M(a||""),g("light"),x("all"),V([]),G(null),te(new Set),me(""),ce(!1),z(!0),Ie(!0),Ne([]),$e("now"),Je(""),be({sent:0,failed:0,total:0,currentName:""}))},[s,r,a]);const Hs=l,Rs=N.useMemo(()=>ohn(I||a||""),[I,a]),en=!!(_.trim()&&Hs&&Ds.length>0&&!ae&&Rs.length===0),Rn=rn=>{const Zn=I||a,sa=L&&(m!=null&&m.email_signature)?m.email_signature:null;let xs;return f==="light"?xs=phn(Zn,k,T,sa):xs=sa?`${Zn}
${sa}
`:Zn,Se&&(xs+=fhn(m??null,Ct??null,rn.email)),Jut(xs,rn,m??null,(Ct==null?void 0:Ct.name)??null)},Bn=N.useMemo(()=>Rn({first_name:"Friend",last_name:"",email:"preview@example.com",phone:"",address:"",city:"",state:"",zip:""}),[f,k,T,I,a,L,m,Se,Ct]),Dn=N.useMemo(()=>xhn(_,f==="advanced"||f==="visual"?I:a),[_,f,I,a]),Jn=async()=>{Re(!0),Ne([]);try{const rn=f==="advanced"||f==="visual"?I:a,{data:Zn,error:sa}=await H.functions.invoke("generate-newsletter-subjects",{body:{newsletterTitle:r,bodyHtml:rn,currentSubject:_}});if(sa)throw sa;const xs=Zn==null?void 0:Zn.subjects;if(!Array.isArray(xs)||xs.length===0)throw new Error("No subjects returned");Ne(xs)}catch(rn){const Zn=(rn==null?void 0:rn.message)||"Failed to generate subjects";Zn.includes("credits exhausted")||Zn.includes("402")?ie.error("AI credits exhausted. Please add credits to your workspace."):Zn.includes("Rate limit")||Zn.includes("429")?ie.error("Rate limit hit — try again in a moment."):ie.error(Zn)}finally{Re(!1)}},ua=rn=>rn?"$"+Number(rn).toLocaleString("en-US"):"",Mr=()=>{var it,ft;if(Fe.size===0){ie.error("Pick at least one listing first.");return}const rn=(Yt==null?void 0:Yt.subdomain_slug)||"",Zn=rn?`https://${rn}.relevelup.com`:"https://relevelup.com",sa=[];for(const kt of zs){const Ut=`mls:${kt.listing_key}`;if(!Fe.has(Ut))continue;const es=Array.isArray(kt.photos)&&kt.photos.length>0?typeof kt.photos[0]=="string"?kt.photos[0]:((it=kt.photos[0])==null?void 0:it.MediaURL)||((ft=kt.photos[0])==null?void 0:ft.url)||"":"",Ms=kt.bedrooms?`${kt.bedrooms} bd`:"",bs=kt.bathrooms_total?`${kt.bathrooms_total} ba`:"",Zs=kt.living_area?`${Number(kt.living_area).toLocaleString()} sqft`:"";sa.push({url:`${Zn}/listings/${kt.listing_key}`,photo:es,price:ua(kt.list_price),addr:`${kt.address||""}${kt.city?", "+kt.city:""}`,stats:[Ms,bs,Zs].filter(Boolean).join(" • ")})}for(const kt of At){const Ut=`ex:${kt.id}`;if(!Fe.has(Ut))continue;const es=kt.bedrooms?`${kt.bedrooms} bd`:"",Ms=kt.bathrooms?`${kt.bathrooms} ba`:"",bs=kt.square_footage?`${Number(kt.square_footage).toLocaleString()} sqft`:"";sa.push({url:`https://listings.relevelup.com/${kt.slug||kt.id}`,photo:kt._photo||"",price:ua(kt.price),addr:`${kt.property_address||""}${kt.city?", "+kt.city:""}`,stats:[es,Ms,bs].filter(Boolean).join(" • ")})}const Ve=`

Featured Listings

${sa.map(kt=>`
${kt.photo?`${kt.addr}`:""}
${kt.price}
${kt.addr}
${kt.stats}
`.trim()).join(` `)}
`.trim();M(kt=>(kt||a||"")+` `+Ve),g("visual"),Ae(new Set),Ce(!1),ie.success(`Added ${sa.length} listing${sa.length===1?"":"s"} to your newsletter.`)},sn=()=>Rn({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}}"),ki=()=>Jut(_,{first_name:"__FN__",last_name:"__LN__",email:"__EM__",name:"__NAME__",phone:"__PHONE__",address:"__ADDR__",city:"__CITY__",state:"__STATE__",zip:"__ZIP__"},m??null,(Ct==null?void 0:Ct.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}}"),ia=()=>{if(Rs.length>0){ie.error(`Fill in ${Rs.length} template field${Rs.length===1?"":"s"} before sending.`);return}if(en){if(Xe==="later"){if(!Ye){ie.error("Pick a date and time to schedule.");return}const rn=new Date(Ye).getTime();if(Number.isNaN(rn)||rn{if(!(!en||!i)){ve(!1),he(!0),be({sent:0,failed:0,total:Ds.length,currentName:"Preparing campaign…"});try{const Zn=`${((o==null?void 0:o.display_name)||"ReLevelUp").toLowerCase().replace(/[^a-z]/g,".")}@send.relevelup.com`,sa=sn(),xs=ki(),Ve=Xe==="later",{data:it,error:ft}=await H.from("email_campaigns").insert({user_id:h||i.id,name:`Newsletter: ${r}`,subject:xs,body_html:sa,from_email:Zn,reply_to_email:(o==null?void 0:o.reply_to_email)||null,total_recipients:Ds.length,status:Ve?"scheduled":"draft",scheduled_at:Ve?new Date(Ye).toISOString():null}).select("id").single();if(ft)throw ft;be(Ut=>({...Ut,currentName:"Adding recipients…"}));const kt=Ds.map(Ut=>({campaign_id:it.id,contact_id:Ut.id,email:Ut.email,name:[Ut.first_name,Ut.last_name].filter(Boolean).join(" ")||null,status:"pending"}));for(let Ut=0;Ut({...bs,sent:Math.min(Ut+es.length,kt.length)}))}if(Ve){const{error:Ut}=await H.functions.invoke("ses-schedule-campaign",{body:{action:"schedule",campaign_id:it.id}});if(Ut)throw Ut;ie.success(`Newsletter scheduled for ${new Date(Ye).toLocaleString()}.`)}else{const{error:Ut}=await H.functions.invoke("ses-send-campaign",{body:{action:"send_campaign",campaign_id:it.id}});if(Ut)throw Ut;ie.success(`Sending to ${Ds.length} contact${Ds.length===1?"":"s"}! Open & click tracking will appear in Sent Emails.`)}t(!1)}catch(rn){console.error("Newsletter send failed:",rn),ie.error(`Failed to send: ${rn.message||"Unknown error"}`)}finally{he(!1)}}},Nr=rn=>{te(Zn=>{const sa=new Set(Zn);return sa.has(rn)?sa.delete(rn):sa.add(rn),sa})};return e.jsxs(Bs,{open:s,onOpenChange:rn=>!ae&&t(rn),children:[e.jsxs(Fs,{className:"max-w-5xl max-h-[92vh] overflow-y-auto",children:[e.jsx(qs,{children:e.jsxs($s,{className:"flex items-center gap-2",children:[e.jsx(Rr,{className:"h-5 w-5"})," Send Newsletter"]})}),!Hs&&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(Uo,{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(re,{children:"Subject"}),e.jsxs(B,{type:"button",variant:"ghost",size:"sm",className:"h-7 gap-1 text-xs",onClick:Jn,disabled:Me,title:"Generate subject lines with AI",children:[Me?e.jsx(us,{className:"h-3 w-3 animate-spin"}):e.jsx(Cn,{className:"h-3 w-3"}),"AI Suggestions"]})]}),e.jsx(we,{value:_,onChange:rn=>b(rn.target.value),placeholder:"Newsletter subject"}),Be.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:"}),Be.map((rn,Zn)=>e.jsxs("button",{type:"button",onClick:()=>{b(rn),Ne([])},className:"w-full text-left text-sm px-2 py-1.5 rounded hover:bg-primary/10 transition-colors",children:[e.jsx(Cn,{className:"h-3 w-3 inline-block mr-1.5 text-primary"}),rn]},Zn))]}),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}}"})]})]}),Dn.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(A9,{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:Dn.map((rn,Zn)=>e.jsx("li",{children:rn},Zn))})]}),(Kt||Nt)&&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(_a,{className:"h-3.5 w-3.5 text-primary"}),"Insert your active listings"]}),e.jsx("p",{className:"text-muted-foreground mt-0.5",children:Kt&&Nt?"Pick from your live MLS listings or your Listing Exchange listings.":Kt?"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:()=>Ce(!0),children:"Choose listings"})]}),e.jsx(chn,{html:I||a||"",originalHtml:a||"",onChange:M}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{children:"Editing"}),e.jsxs(ya,{value:f,onValueChange:rn=>g(rn),children:[e.jsxs(va,{className:"grid grid-cols-3 w-full",children:[e.jsxs(ls,{value:"visual",children:[e.jsx(Zg,{className:"h-3 w-3 mr-1"}),"Visual"]}),e.jsxs(ls,{value:"light",children:[e.jsx(Wr,{className:"h-3 w-3 mr-1"}),"Quick edit"]}),e.jsxs(ls,{value:"advanced",children:[e.jsx(l4,{className:"h-3 w-3 mr-1"}),"HTML"]})]}),e.jsx(_s,{value:"visual",className:"mt-3",children:e.jsx(ZPt,{html:I,onChange:M})}),e.jsxs(_s,{value:"light",className:"space-y-3 mt-3",children:[e.jsxs("div",{children:[e.jsx(re,{className:"text-xs text-muted-foreground",children:"Personal intro (above newsletter)"}),e.jsx(Ws,{value:k,onChange:rn=>A(rn.target.value),rows:4,placeholder:"Hi {{first_name}}, ..."})]}),e.jsxs("div",{children:[e.jsx(re,{className:"text-xs text-muted-foreground",children:"Personal outro (below newsletter)"}),e.jsx(Ws,{value:T,onChange:rn=>P(rn.target.value),rows:3,placeholder:"Talk soon!"})]})]}),e.jsxs(_s,{value:"advanced",className:"mt-3",children:[e.jsx(re,{className:"text-xs text-muted-foreground",children:"Edit full HTML"}),e.jsx(Ws,{value:I,onChange:rn=>M(rn.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(zn,{checked:L&&!!(m!=null&&m.email_signature),disabled:!(m!=null&&m.email_signature),onCheckedChange:z})]}),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(zn,{checked:Se,onCheckedChange:Ie})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{children:"Recipients"}),e.jsxs(ya,{value:y,onValueChange:rn=>x(rn),children:[e.jsxs(va,{className:"grid grid-cols-4 w-full",children:[e.jsxs(ls,{value:"all",children:[e.jsx(Yn,{className:"h-3 w-3 mr-1"}),"All"]}),e.jsxs(ls,{value:"tags",children:[e.jsx(pf,{className:"h-3 w-3 mr-1"}),"Tags"]}),e.jsxs(ls,{value:"smartlists",children:[e.jsx(sW,{className:"h-3 w-3 mr-1"}),"Lists"]}),e.jsxs(ls,{value:"individual",children:[e.jsx(Ro,{className:"h-3 w-3 mr-1"}),"Pick"]})]}),e.jsx(_s,{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:ms.length})," contact",ms.length===1?"":"s"," with a valid, non-suppressed email."]})}),e.jsxs(_s,{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(lo,{className:"h-40 rounded-lg border p-2",children:Ke.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."}):Ke.map(rn=>e.jsxs("label",{className:"flex items-center gap-2 p-1.5 hover:bg-muted rounded cursor-pointer",children:[e.jsx(Bi,{checked:$.includes(rn.id),onCheckedChange:Zn=>V(sa=>Zn?[...sa,rn.id]:sa.filter(xs=>xs!==rn.id))}),e.jsx("span",{className:"inline-block h-2 w-2 rounded-full",style:{background:rn.color||"#406E71"}}),e.jsx("span",{className:"text-sm",children:rn.name})]},rn.id))})]}),e.jsxs(_s,{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(lo,{className:"h-40 rounded-lg border p-2",children:rt.length===0?e.jsx("p",{className:"text-xs text-muted-foreground p-2",children:"No smart lists yet. Save one from the contacts page."}):rt.map(rn=>e.jsxs("label",{className:"flex items-center gap-2 p-1.5 hover:bg-muted rounded cursor-pointer",children:[e.jsx("input",{type:"radio",name:"smartlist",checked:W===rn.id,onChange:()=>G(rn.id)}),e.jsx("span",{className:"text-sm",children:rn.name})]},rn.id))})]}),e.jsxs(_s,{value:"individual",className:"mt-3 space-y-2",children:[e.jsx(we,{placeholder:"Search contacts...",value:ne,onChange:rn=>me(rn.target.value)}),e.jsxs("div",{className:"flex items-center justify-between text-xs text-muted-foreground",children:[e.jsxs("span",{children:[X.size," selected"]}),e.jsx("button",{type:"button",className:"underline",onClick:()=>te(new Set),children:"Clear"})]}),e.jsxs(lo,{className:"h-48 rounded-lg border p-2",children:[ht&&e.jsx("p",{className:"text-xs text-muted-foreground p-2",children:"Loading contacts…"}),!ht&&As.length===0&&e.jsx("p",{className:"text-xs text-muted-foreground p-2",children:"No matching contacts."}),As.slice(0,200).map(rn=>e.jsxs("label",{className:"flex items-center gap-2 p-1.5 hover:bg-muted rounded cursor-pointer",children:[e.jsx(Bi,{checked:X.has(rn.id),onCheckedChange:()=>Nr(rn.id)}),e.jsxs("div",{className:"text-sm flex-1 min-w-0",children:[e.jsxs("div",{className:"truncate",children:[rn.first_name," ",rn.last_name||""]}),e.jsx("div",{className:"text-xs text-muted-foreground truncate",children:rn.email})]})]},rn.id)),As.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(We,{variant:"secondary",className:"gap-1",children:[e.jsx(Hr,{className:"h-3 w-3"})," ",Ds.length," recipient",Ds.length===1?"":"s"]}),Hs&&e.jsxs(We,{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(re,{children:"Preview"}),e.jsx(B,{variant:"ghost",size:"sm",onClick:()=>ce(rn=>!rn),children:ue?e.jsxs(e.Fragment,{children:[e.jsx(V0,{className:"h-3 w-3 mr-1"}),"Hide"]}):e.jsxs(e.Fragment,{children:[e.jsx(da,{className:"h-3 w-3 mr-1"}),"Show"]})})]}),ue?e.jsx("div",{className:"rounded-lg border overflow-hidden bg-white",children:e.jsx("iframe",{title:"newsletter-preview",srcDoc:Bn,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)."]})]})]}),ae&&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(us,{className:"h-4 w-4 animate-spin"}),"Sending to ",ge.currentName||"..."]}),e.jsxs("span",{className:"text-muted-foreground",children:[ge.sent+ge.failed," / ",ge.total]})]}),e.jsx(ro,{value:ge.total?(ge.sent+ge.failed)/ge.total*100:0}),ge.failed>0&&e.jsxs("p",{className:"text-xs text-destructive",children:[ge.failed," failed"]})]}),e.jsxs("div",{className:"space-y-3 pt-2 border-t",children:[e.jsxs("div",{className:"rounded-lg border bg-muted/20 p-3 space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm font-medium",children:[e.jsx(Xr,{className:"h-4 w-4"})," When to send"]}),e.jsxs(K1,{value:Xe,onValueChange:rn=>$e(rn),className:"flex flex-col sm:flex-row gap-3",children:[e.jsxs("label",{className:"flex items-center gap-2 cursor-pointer",children:[e.jsx(Ju,{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(Ju,{value:"later",id:"send-later"}),e.jsxs("span",{className:"text-sm flex items-center gap-1",children:[e.jsx(df,{className:"h-3.5 w-3.5"})," Schedule for later"]})]}),Xe==="later"&&e.jsx(we,{type:"datetime-local",value:Ye,onChange:rn=>Je(rn.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:Rs.length>0?`${Rs.length} template field${Rs.length===1?"":"s"} still need${Rs.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:ae,children:"Cancel"}),e.jsx(B,{onClick:ia,disabled:!en,children:ae?e.jsxs(e.Fragment,{children:[e.jsx(us,{className:"h-4 w-4 mr-1 animate-spin"}),"Working…"]}):Xe==="later"?e.jsxs(e.Fragment,{children:[e.jsx(df,{className:"h-4 w-4 mr-1"}),"Schedule for ",Ds.length]}):e.jsxs(e.Fragment,{children:[e.jsx(Rr,{className:"h-4 w-4 mr-1"}),"Send to ",Ds.length]})})]})]})]})]}),e.jsx(Fl,{open:xe,onOpenChange:ve,children:e.jsxs(kl,{children:[e.jsxs(Sl,{children:[e.jsx(Al,{children:Xe==="later"?"Schedule newsletter?":"Send newsletter?"}),e.jsxs(Tl,{children:[Xe==="later"?"Schedule ":"Send ",e.jsxs("span",{className:"font-medium text-foreground",children:['"',_,'"']})," to"," ",e.jsxs("span",{className:"font-medium text-foreground",children:[Ds.length," contact",Ds.length===1?"":"s"]}),Xe==="later"&&Ye?` for ${new Date(Ye).toLocaleString()}`:"","? Suppressed and unsubscribed contacts are skipped automatically."]})]}),e.jsxs(Cl,{children:[e.jsx(El,{children:"Cancel"}),e.jsx(wl,{onClick:vr,children:Xe==="later"?e.jsxs(e.Fragment,{children:[e.jsx(df,{className:"h-4 w-4 mr-1"}),"Schedule"]}):e.jsxs(e.Fragment,{children:[e.jsx(Rr,{className:"h-4 w-4 mr-1"}),"Send to ",Ds.length]})})]})]})}),e.jsx(Bs,{open:Ge,onOpenChange:Ce,children:e.jsxs(Fs,{className:"max-w-2xl max-h-[85vh] overflow-y-auto",children:[e.jsx(qs,{children:e.jsxs($s,{className:"flex items-center gap-2",children:[e.jsx(_a,{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."}),(Vt||Os)&&e.jsxs("div",{className:"text-sm text-muted-foreground p-6 text-center",children:[e.jsx(us,{className:"h-4 w-4 animate-spin inline-block mr-2"}),"Loading your listings…"]}),!Vt&&!Os&&zs.length===0&&At.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."}),zs.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:zs.map(rn=>{var Ve,it;const Zn=`mls:${rn.listing_key}`,sa=Fe.has(Zn),xs=Array.isArray(rn.photos)&&rn.photos.length>0?typeof rn.photos[0]=="string"?rn.photos[0]:((Ve=rn.photos[0])==null?void 0:Ve.MediaURL)||((it=rn.photos[0])==null?void 0:it.url)||"":"";return e.jsxs("button",{type:"button",onClick:()=>{Ae(ft=>{const kt=new Set(ft);return kt.has(Zn)?kt.delete(Zn):kt.size<6?kt.add(Zn):ie.error("Max 6 listings per newsletter"),kt})},className:`relative rounded-lg border-2 overflow-hidden text-left transition-all ${sa?"border-primary ring-2 ring-primary/30":"border-border hover:border-primary/50"}`,children:[xs&&e.jsx("img",{src:xs,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:rn.list_price?`$${Number(rn.list_price).toLocaleString()}`:""}),e.jsx("div",{className:"text-xs truncate",children:rn.address}),e.jsxs("div",{className:"text-[11px] text-muted-foreground truncate",children:[rn.city,rn.state?`, ${rn.state}`:""]})]}),sa&&e.jsx("div",{className:"absolute top-1 right-1 bg-primary text-primary-foreground rounded-full p-0.5",children:e.jsx(Hr,{className:"h-4 w-4"})})]},Zn)})})]}),At.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:At.map(rn=>{const Zn=`ex:${rn.id}`,sa=Fe.has(Zn);return e.jsxs("button",{type:"button",onClick:()=>{Ae(xs=>{const Ve=new Set(xs);return Ve.has(Zn)?Ve.delete(Zn):Ve.size<6?Ve.add(Zn):ie.error("Max 6 listings per newsletter"),Ve})},className:`relative rounded-lg border-2 overflow-hidden text-left transition-all ${sa?"border-primary ring-2 ring-primary/30":"border-border hover:border-primary/50"}`,children:[rn._photo&&e.jsx("img",{src:rn._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:rn.price?`$${Number(rn.price).toLocaleString()}`:""}),e.jsx("div",{className:"text-xs truncate",children:rn.property_address}),e.jsxs("div",{className:"text-[11px] text-muted-foreground truncate",children:[rn.city,rn.state?`, ${rn.state}`:""]})]}),sa&&e.jsx("div",{className:"absolute top-1 right-1 bg-primary text-primary-foreground rounded-full p-0.5",children:e.jsx(Hr,{className:"h-4 w-4"})})]},Zn)})})]})]}),e.jsxs(Cr,{children:[e.jsx(B,{variant:"outline",onClick:()=>Ce(!1),children:"Cancel"}),e.jsxs(B,{onClick:Mr,disabled:Fe.size===0,children:["Insert ",Fe.size>0?Fe.size:""," listing",Fe.size===1?"":"s"]})]})]})}),e.jsx(FCe,{open:d,onOpenChange:u,hasPending:!!(c!=null&&c.hasPendingSes),pendingEmails:c==null?void 0:c.pendingEmails})]})}function yhn(){const{user:s}=Ls(),t=as(),[n,r]=N.useState("starters"),[a,i]=N.useState(!1),[l,o]=N.useState(null),[c,d]=N.useState(null),[u,h]=N.useState(null),{data:m,isLoading:f}=mt({queryKey:["agent-custom-newsletters",s==null?void 0:s.id],enabled:!!(s!=null&&s.id),queryFn:async()=>{const{data:I,error:M}=await H.from("agent_custom_newsletters").select("*").order("updated_at",{ascending:!1});if(M)throw M;return I||[]}}),g=()=>t.invalidateQueries({queryKey:["agent-custom-newsletters"]}),y=(m==null?void 0:m.filter(I=>I.user_id===(s==null?void 0:s.id)&&!I.is_template))??[],x=(m==null?void 0:m.filter(I=>I.user_id===(s==null?void 0:s.id)&&I.is_template))??[],_=(m==null?void 0:m.filter(I=>I.user_id!==(s==null?void 0:s.id)&&I.is_template&&(I.share_scope==="team"||I.share_scope==="brokerage"||I.share_scope==="global")))??[],b=(m==null?void 0:m.filter(I=>I.share_scope==="global"&&I.is_template))??[],k=n==="starters"?b:n==="mine"?y:n==="templates"?x:_.filter(I=>I.share_scope!=="global"),A=async I=>{if(!s)return;const{error:M}=await H.from("agent_custom_newsletters").insert({user_id:s.id,title:`${I.title} (Copy)`,description:I.description,html_content:I.html_content,is_template:!1,share_scope:"private"});if(M){ie.error(M.message);return}ie.success('Duplicated to "My Newsletters"'),g(),r("mine")},T=async I=>{const{error:M}=await H.from("agent_custom_newsletters").delete().eq("id",I);if(M){ie.error(M.message);return}ie.success("Deleted"),h(null),g()},P=I=>I.share_scope==="global"?e.jsxs(We,{variant:"secondary",className:"gap-1",children:[e.jsx(Cn,{className:"h-3 w-3"}),"Starter"]}):I.share_scope==="brokerage"?e.jsxs(We,{variant:"secondary",className:"gap-1",children:[e.jsx(Ti,{className:"h-3 w-3"}),"Brokerage"]}):I.share_scope==="team"?e.jsxs(We,{variant:"secondary",className:"gap-1",children:[e.jsx(Yn,{className:"h-3 w-3"}),"Team"]}):e.jsxs(We,{variant:"outline",className:"gap-1 text-muted-foreground",children:[e.jsx(Au,{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(Cn,{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 (",x.length,")"]}),e.jsxs(B,{variant:n==="shared"?"default":"outline",size:"sm",onClick:()=>r("shared"),children:["Shared with Me (",_.filter(I=>I.share_scope!=="global").length,")"]})]}),e.jsxs(B,{onClick:()=>{o(null),i(!0)},children:[e.jsx(nn,{className:"h-4 w-4 mr-1.5"})," Create Newsletter"]})]}),f&&e.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-4",children:[...Array(3)].map((I,M)=>e.jsx(xn,{className:"h-48 w-full"},M))}),n==="starters"&&!f&&e.jsxs("div",{className:"rounded-lg border border-primary/20 bg-primary/5 px-4 py-3 text-sm flex items-start gap-2",children:[e.jsx(Cn,{className:"h-4 w-4 text-primary mt-0.5 shrink-0"}),e.jsxs("span",{children:["Click ",e.jsx("strong",{children:"Use"}),' on any starter to copy it into your "My Newsletters" — then edit, send, or save as your own template.']})]}),!f&&k.length===0&&e.jsx(_e,{children:e.jsxs(De,{className:"py-12 text-center text-muted-foreground",children:[e.jsx(Wr,{className:"h-10 w-10 mx-auto mb-3 opacity-50"}),n==="starters"&&e.jsx("p",{children:"No starter templates available yet."}),n==="mine"&&e.jsx("p",{children:`You haven't created any newsletters yet. Try a Starter Template or click "Create Newsletter"!`}),n==="templates"&&e.jsx("p",{children:`You haven't saved any templates yet. Toggle "Save as reusable template" when creating a newsletter.`}),n==="shared"&&e.jsx("p",{children:"No team or brokerage templates have been shared with you yet."})]})}),!f&&k.length>0&&e.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-4",children:k.map(I=>{const M=I.user_id===(s==null?void 0:s.id);return e.jsxs(_e,{className:"overflow-hidden hover:shadow-md transition-shadow",children:[e.jsxs("div",{className:"aspect-[3/2] bg-muted relative overflow-hidden",children:[I.thumbnail_url?e.jsx("img",{src:I.thumbnail_url,alt:I.title,className:"w-full h-full object-cover"}):e.jsx("div",{className:"w-full h-full p-3 overflow-hidden pointer-events-none",dangerouslySetInnerHTML:{__html:`
${I.html_content}
`}}),e.jsxs("div",{className:"absolute top-2 right-2 flex gap-1",children:[I.is_template&&e.jsx(We,{className:"bg-primary/90",children:"Template"}),P(I)]})]}),e.jsxs(De,{className:"p-3 space-y-2",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"font-semibold line-clamp-1",children:I.title}),I.description&&e.jsx("p",{className:"text-xs text-muted-foreground line-clamp-1",children:I.description}),e.jsxs("p",{className:"text-xs text-muted-foreground mt-0.5",children:["Updated ",Js(new Date(I.updated_at||I.created_at),"MMM d, yyyy")]})]}),e.jsxs("div",{className:"flex gap-1.5 flex-wrap",children:[e.jsxs(B,{size:"sm",onClick:()=>d(I),className:"flex-1 min-w-[80px]",children:[e.jsx(Rr,{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(I),i(!0)},children:e.jsx(Ja,{className:"h-3.5 w-3.5"})}),e.jsx(B,{size:"sm",variant:"outline",onClick:()=>A(I),children:e.jsx(Pa,{className:"h-3.5 w-3.5"})}),e.jsx(B,{size:"sm",variant:"outline",onClick:()=>h(I.id),children:e.jsx(qn,{className:"h-3.5 w-3.5"})})]}):e.jsxs(B,{size:"sm",variant:"outline",onClick:()=>A(I),children:[e.jsx(Pa,{className:"h-3.5 w-3.5 mr-1"})," Use"]})]})]})]},I.id)})}),e.jsx(ahn,{open:a,onOpenChange:i,initial:l,onSaved:g}),c&&e.jsx(cGe,{open:!!c,onOpenChange:I=>!I&&d(null),newsletterId:c.id,newsletterTitle:c.title,htmlCode:c.html_content}),e.jsx(Fl,{open:!!u,onOpenChange:I=>!I&&h(null),children:e.jsxs(kl,{children:[e.jsxs(Sl,{children:[e.jsx(Al,{children:"Delete this newsletter?"}),e.jsx(Tl,{children:"This cannot be undone."})]}),e.jsxs(Cl,{children:[e.jsx(El,{children:"Cancel"}),e.jsx(wl,{onClick:()=>u&&T(u),children:"Delete"})]})]})})]})}function vhn(){const s=tr(),[t,n]=N.useState(""),[r,a]=N.useState("grid"),[i,l]=N.useState(null),{data:o,isLoading:c}=mt({queryKey:["newsletters"],queryFn:async()=>{const{data:T,error:P}=await H.from("newsletter_content").select("*").eq("is_published",!0).order("publish_date",{ascending:!1});if(P)throw P;return T}}),{data:d}=mt({queryKey:["newsletter-likes-all"],queryFn:async()=>{const{data:T}=await H.from("newsletter_likes").select("newsletter_id");return T||[]}}),{data:u}=mt({queryKey:["newsletter-comments-all"],queryFn:async()=>{const{data:T}=await H.from("newsletter_comments").select("newsletter_id");return T||[]}}),{data:h}=mt({queryKey:["newsletter-resource-counts"],queryFn:async()=>{const[T,P,I,M]=await Promise.all([H.from("newsletter_canva_links").select("newsletter_id"),H.from("newsletter_pdfs").select("newsletter_id"),H.from("newsletter_videos").select("newsletter_id"),H.from("newsletter_drive_links").select("newsletter_id")]);return{canva:T.data||[],pdfs:P.data||[],videos:I.data||[],drives:M.data||[]}}}),m=T=>(d==null?void 0:d.filter(P=>P.newsletter_id===T).length)||0,f=T=>(u==null?void 0:u.filter(P=>P.newsletter_id===T).length)||0,g=T=>{var P;return((P=h==null?void 0:h.canva)==null?void 0:P.filter(I=>I.newsletter_id===T).length)||0},y=T=>{var P;return((P=h==null?void 0:h.pdfs)==null?void 0:P.filter(I=>I.newsletter_id===T).length)||0},x=T=>{var P;return((P=h==null?void 0:h.videos)==null?void 0:P.filter(I=>I.newsletter_id===T).length)||0},_=T=>{var P;return((P=h==null?void 0:h.drives)==null?void 0:P.filter(I=>I.newsletter_id===T).length)||0},b=T=>g(T)+y(T)+x(T)+_(T),k=o==null?void 0:o.filter(T=>{var P;return T.title.toLowerCase().includes(t.toLowerCase())||((P=T.description)==null?void 0:P.toLowerCase().includes(t.toLowerCase()))}),A=T=>{s(`/newsletters/${T}`)};return e.jsx(Qs,{title:"Newsletter Content",children:e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{children:[e.jsx("h1",{className:"font-bold text-foreground text-5xl",children:"Newsletter Content"}),e.jsx("p",{className:"text-muted-foreground mt-1",children:"Monthly templates, plus newsletters you build yourself"})]}),e.jsxs(ya,{defaultValue:"custom",className:"space-y-4",children:[e.jsxs(va,{children:[e.jsx(ls,{value:"custom",children:"Build & Send"}),e.jsx(ls,{value:"curated",children:"Curated Monthly"})]}),e.jsx(_s,{value:"custom",className:"mt-2",children:e.jsx(yhn,{})}),e.jsxs(_s,{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(Gr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(we,{placeholder:"Search newsletters...",value:t,onChange:T=>n(T.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(G0,{className:"h-4 w-4"})}),e.jsx(B,{variant:r==="list"?"secondary":"outline",size:"icon",onClick:()=>a("list"),className:"rounded-full",children:e.jsx(Kx,{className:"h-4 w-4"})})]})]})]}),e.jsxs("div",{className:"text-sm text-muted-foreground",children:[(k==null?void 0:k.length)||0," item",(k==null?void 0:k.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((T,P)=>e.jsx(_e,{children:e.jsxs(De,{className:"p-0",children:[e.jsx(xn,{className:"aspect-[3/2] w-full"}),e.jsxs("div",{className:"p-4 space-y-2",children:[e.jsx(xn,{className:"h-5 w-3/4"}),e.jsx(xn,{className:"h-4 w-full"})]})]})},P))}),!c&&(k==null?void 0:k.length)===0&&e.jsxs("div",{className:"text-center py-12",children:[e.jsx(Wr,{className:"h-12 w-12 mx-auto text-muted-foreground mb-4"}),e.jsx("div",{className:"text-muted-foreground mb-4",children:t?"No newsletters match your search":"No newsletters available yet"}),t&&e.jsx(B,{variant:"outline",onClick:()=>n(""),children:"Clear Search"})]}),!c&&k&&k.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:k.map(T=>{const P=b(T.id),I=g(T.id),M=y(T.id),L=x(T.id);return r==="grid"?e.jsxs(_e,{className:"group overflow-hidden hover:shadow-lg transition-all duration-200 cursor-pointer border-border/50",onClick:()=>A(T.id),children:[e.jsx("div",{className:"relative overflow-hidden bg-muted aspect-[3/2]",children:T.preview_image_url?e.jsx("img",{src:T.preview_image_url,alt:T.title,className:"w-full h-full object-contain group-hover:scale-105 transition-transform duration-300"}):e.jsx("div",{className:"w-full h-full flex items-center justify-center text-muted-foreground",children:e.jsx(Wr,{className:"h-16 w-16"})})}),e.jsxs(De,{className:"p-4 space-y-3",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"font-semibold text-foreground line-clamp-1",children:T.title}),e.jsxs("div",{className:"flex items-center gap-1.5 mt-1 text-xs text-muted-foreground",children:[e.jsx(ta,{className:"h-3 w-3"}),Js(new Date(T.publish_date),"MMM d, yyyy")]})]}),T.description&&e.jsx("p",{className:"text-sm text-muted-foreground line-clamp-2",children:T.description.replace(/<[^>]*>/g,"")}),P>0&&e.jsxs("div",{className:"flex flex-wrap gap-1.5",children:[I>0&&e.jsxs(We,{variant:"secondary",className:"text-xs gap-1 font-normal",children:[e.jsx(zc,{className:"h-3 w-3"})," ",I," Template",I>1?"s":""]}),M>0&&e.jsxs(We,{variant:"secondary",className:"text-xs gap-1 font-normal",children:[e.jsx(oi,{className:"h-3 w-3"})," ",M," PDF",M>1?"s":""]}),L>0&&e.jsxs(We,{variant:"secondary",className:"text-xs gap-1 font-normal",children:[e.jsx(dd,{className:"h-3 w-3"})," ",L," Video",L>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(ax,{className:"h-3 w-3"})," ",m(T.id)]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Ud,{className:"h-3 w-3"})," ",f(T.id)]})]}),T.html_code&&e.jsxs(B,{size:"sm",className:"w-full bg-gradient-to-r from-[#2a4c64] to-[#406E71] text-white hover:opacity-90",onClick:z=>{z.stopPropagation(),l(T)},children:[e.jsx(Rr,{className:"h-4 w-4 mr-1.5"}),"Send Newsletter"]})]})]},T.id):e.jsx(_e,{className:"group overflow-hidden hover:shadow-md transition-all duration-200 cursor-pointer border-border/50",onClick:()=>A(T.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:T.preview_image_url?e.jsx("img",{src:T.preview_image_url,alt:T.title,className:"w-full h-full object-contain group-hover:scale-105 transition-transform duration-300"}):e.jsx("div",{className:"w-full h-full flex items-center justify-center text-muted-foreground min-h-[100px]",children:e.jsx(Wr,{className:"h-10 w-10"})})}),e.jsxs(De,{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:T.title}),e.jsxs("div",{className:"flex items-center gap-1.5 mt-0.5 text-xs text-muted-foreground",children:[e.jsx(ta,{className:"h-3 w-3"}),Js(new Date(T.publish_date),"MMM d, yyyy")]})]}),T.description&&e.jsx("p",{className:"text-sm text-muted-foreground line-clamp-1",children:T.description.replace(/<[^>]*>/g,"")}),e.jsxs("div",{className:"flex items-center gap-4 text-xs text-muted-foreground",children:[P>0&&e.jsxs("span",{children:[P," resource",P>1?"s":""]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(ax,{className:"h-3 w-3"})," ",m(T.id)]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Ud,{className:"h-3 w-3"})," ",f(T.id)]})]})]}),T.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:z=>{z.stopPropagation(),l(T)},children:[e.jsx(Rr,{className:"h-4 w-4 mr-1.5"}),"Send"]})})]})},T.id)})})]})]}),(i==null?void 0:i.html_code)&&e.jsx(cGe,{open:!!i,onOpenChange:T=>!T&&l(null),newsletterId:i.id,newsletterTitle:i.title,htmlCode:i.html_code})]})})}function bhn({rows:s}){if(!s||s.length===0)return null;const t=s.filter(n=>n.columns.some(r=>r.title||r.description||r.image_url));return t.length===0?null:e.jsx("div",{className:"space-y-6",children:t.map((n,r)=>{const a=n.columns.filter(i=>i.title||i.description||i.image_url);return a.length===0?null:e.jsx("div",{className:"grid gap-4",style:{gridTemplateColumns:`repeat(${a.length}, minmax(0, 1fr))`},children:a.map((i,l)=>e.jsxs(_e,{className:"overflow-hidden border-border/50",children:[i.image_url&&e.jsx("img",{src:i.image_url,alt:i.title||"",className:"w-full h-40 object-cover"}),e.jsxs(De,{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 _hn(){const{id:s}=uo(),t=tr(),{user:n}=Ls(),{toast:r}=Ci(),a=as(),{trackEngagement:i}=pU(),[l,o]=N.useState(""),[c,d]=N.useState(!1),{data:u,isLoading:h}=mt({queryKey:["newsletter",s],queryFn:async()=>{const{data:I,error:M}=await H.from("newsletter_content").select("*").eq("id",s).single();if(M)throw M;return I},enabled:!!s});N.useEffect(()=>{u&&i("newsletter",u.id,u.title,"view")},[u==null?void 0:u.id]);const{data:m}=mt({queryKey:["newsletter-drives",s],queryFn:async()=>{const{data:I}=await H.from("newsletter_drive_links").select("*").eq("newsletter_id",s).order("sort_order");return I||[]},enabled:!!s}),{data:f}=mt({queryKey:["newsletter-pdfs",s],queryFn:async()=>{const{data:I}=await H.from("newsletter_pdfs").select("*").eq("newsletter_id",s).order("sort_order");return I||[]},enabled:!!s}),{data:g}=mt({queryKey:["newsletter-videos",s],queryFn:async()=>{const{data:I}=await H.from("newsletter_videos").select("*").eq("newsletter_id",s).order("sort_order");return I||[]},enabled:!!s}),{data:y}=mt({queryKey:["newsletter-canva-links",s],queryFn:async()=>{const{data:I}=await H.from("newsletter_canva_links").select("*").eq("newsletter_id",s).order("sort_order");return I||[]},enabled:!!s}),{data:x}=mt({queryKey:["newsletter-likes",s],queryFn:async()=>{const{data:I}=await H.from("newsletter_likes").select("*").eq("newsletter_id",s);return I||[]},enabled:!!s}),{data:_}=mt({queryKey:["newsletter-comments",s],queryFn:async()=>{const{data:I}=await H.from("newsletter_comments").select("*, profiles:user_id(name)").eq("newsletter_id",s).order("created_at",{ascending:!1});return I||[]},enabled:!!s}),b=x==null?void 0:x.some(I=>I.user_id===(n==null?void 0:n.id)),k=_t({mutationFn:async()=>{b?await H.from("newsletter_likes").delete().eq("newsletter_id",s).eq("user_id",n==null?void 0:n.id):await H.from("newsletter_likes").insert({newsletter_id:s,user_id:n==null?void 0:n.id})},onSuccess:()=>{a.invalidateQueries({queryKey:["newsletter-likes",s]})}}),A=_t({mutationFn:async I=>{const{error:M}=await H.from("newsletter_comments").insert({newsletter_id:s,user_id:n==null?void 0:n.id,content:I});if(M)throw M},onSuccess:()=>{a.invalidateQueries({queryKey:["newsletter-comments",s]}),o(""),r({title:"Comment added"})}}),T=_t({mutationFn:async I=>{const{error:M}=await H.from("newsletter_comments").delete().eq("id",I);if(M)throw M},onSuccess:()=>{a.invalidateQueries({queryKey:["newsletter-comments",s]}),r({title:"Comment deleted"})}}),P=I=>{if(I.includes("player.mediadelivery.net")||I.includes("iframe.mediadelivery.net")){const M=I.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(I.includes("youtube.com")||I.includes("youtu.be")){const M=I.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:I,target:"_blank",rel:"noopener noreferrer",className:"flex items-center gap-2 text-primary hover:underline",children:[e.jsx(dd,{className:"h-4 w-4"})," Watch Video"]})};return h?e.jsx(Qs,{title:"",description:"",children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(xn,{className:"h-8 w-32"}),e.jsx(xn,{className:"h-64 w-full"}),e.jsx(xn,{className:"h-32 w-full"})]})}):u?e.jsx(Qs,{title:"",description:"",children:e.jsxs("div",{className:"max-w-4xl mx-auto space-y-6",children:[e.jsxs(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:Js(new Date(u.publish_date),"MMMM d, yyyy")})]}),u.description&&e.jsx("div",{className:"text-lg text-muted-foreground prose prose-sm max-w-none dark:prose-invert [&_p]:mb-4 [&_p:last-child]:mb-0 whitespace-pre-line",dangerouslySetInnerHTML:{__html:u.description}}),e.jsx(bhn,{rows:u.content_blocks||[]}),e.jsxs("div",{className:"flex items-center gap-4 flex-wrap",children:[e.jsx(yU,{resourceType:"newsletter",resourceId:u.id,resourceTitle:u.title}),e.jsxs(B,{variant:b?"default":"outline",size:"sm",onClick:()=>k.mutate(),children:[e.jsx(co,{className:`h-4 w-4 mr-1 ${b?"fill-current":""}`}),(x==null?void 0:x.length)||0," ",(x==null?void 0:x.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(Rr,{className:"h-4 w-4 mr-1"}),"Send Newsletter"]})]}),u.html_code&&e.jsx(cGe,{open:c,onOpenChange:d,newsletterId:u.id,newsletterTitle:u.title,htmlCode:u.html_code}),y&&y.length>0&&e.jsxs(_e,{children:[e.jsx(zt,{children:e.jsx(qt,{className:"text-lg",children:"Canva Templates"})}),e.jsx(De,{className:"space-y-2",children:y.map(I=>e.jsxs("a",{href:I.canva_share_link,target:"_blank",rel:"noopener noreferrer",onClick:()=>i("newsletter",u.id,u.title,"click_canva"),className:"flex items-center gap-3 p-3 rounded-lg hover:bg-muted transition-colors",children:[e.jsx(zc,{className:"h-5 w-5 text-purple-500"}),e.jsx("span",{className:"font-medium",children:I.title}),e.jsx(Tr,{className:"h-4 w-4 text-muted-foreground ml-auto"})]},I.id))})]}),m&&m.length>0&&e.jsxs(_e,{children:[e.jsx(zt,{children:e.jsx(qt,{className:"text-lg",children:"Google Drive Files"})}),e.jsx(De,{className:"space-y-2",children:m.map(I=>e.jsxs("a",{href:I.drive_url,target:"_blank",rel:"noopener noreferrer",onClick:()=>i("newsletter",u.id,u.title,"click_link"),className:"flex items-center gap-3 p-3 rounded-lg hover:bg-muted transition-colors",children:[e.jsx(Tr,{className:"h-5 w-5 text-primary"}),e.jsx("span",{className:"font-medium",children:I.title})]},I.id))})]}),f&&f.length>0&&e.jsxs(_e,{children:[e.jsx(zt,{children:e.jsx(qt,{className:"text-lg",children:"PDF Downloads"})}),e.jsx(De,{className:"space-y-2",children:f.map(I=>e.jsxs("a",{href:I.file_url,target:"_blank",rel:"noopener noreferrer",onClick:()=>i("newsletter",u.id,u.title,"click_pdf"),className:"flex items-center gap-3 p-3 rounded-lg hover:bg-muted transition-colors",children:[e.jsx(Wr,{className:"h-5 w-5 text-red-500"}),e.jsx("span",{className:"font-medium flex-1",children:I.name}),e.jsx(oi,{className:"h-4 w-4 text-muted-foreground"})]},I.id))})]}),g&&g.length>0&&e.jsxs(_e,{children:[e.jsx(zt,{children:e.jsx(qt,{className:"text-lg",children:"Videos"})}),e.jsx(De,{className:"space-y-6",children:g.map(I=>e.jsxs("div",{className:"space-y-2",children:[e.jsx("h4",{className:"font-medium",children:I.title}),P(I.video_url)]},I.id))})]}),e.jsxs(_e,{children:[e.jsx(zt,{children:e.jsxs(qt,{className:"text-lg",children:["Comments (",(_==null?void 0:_.length)||0,")"]})}),e.jsxs(De,{className:"space-y-4",children:[e.jsxs("div",{className:"flex gap-3",children:[e.jsx(Ws,{placeholder:"Write a comment...",value:l,onChange:I=>o(I.target.value),className:"flex-1"}),e.jsx(B,{onClick:()=>l.trim()&&A.mutate(l),disabled:!l.trim()||A.isPending,children:e.jsx(Rr,{className:"h-4 w-4"})})]}),e.jsx("div",{className:"space-y-4",children:_==null?void 0:_.map(I=>{var M,L,z;return e.jsxs("div",{className:"flex gap-3",children:[e.jsx(Ua,{className:"h-8 w-8",children:e.jsx(qa,{children:((L=(M=I.profiles)==null?void 0:M.name)==null?void 0:L[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:((z=I.profiles)==null?void 0:z.name)||"User"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-xs text-muted-foreground",children:Js(new Date(I.created_at),"MMM d, yyyy")}),I.user_id===(n==null?void 0:n.id)&&e.jsx(B,{variant:"ghost",size:"icon",className:"h-6 w-6",onClick:()=>T.mutate(I.id),children:e.jsx(qn,{className:"h-3 w-3"})})]})]}),e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:I.content})]})]},I.id)})})]})]})]})}):e.jsx(Qs,{title:"Not Found",description:"",children:e.jsxs("div",{className:"text-center py-12",children:[e.jsx("p",{className:"text-muted-foreground",children:"Newsletter not found"}),e.jsx(B,{variant:"link",onClick:()=>t("/newsletters"),children:"Back to Newsletters"})]})})}function whn({rows:s,onChange:t}){const[n,r]=N.useState(null),[a,i]=N.useState(null),l=()=>{t([...s,{columns:[{title:"",description:""},{title:"",description:""},{title:"",description:""}]}])},o=h=>{t(s.filter((m,f)=>f!==h))},c=(h,m,f,g)=>{const y=[...s];y[h]={...y[h],columns:y[h].columns.map((x,_)=>_===m?{...x,[f]:g}:x)},t(y)},d=async(h,m,f)=>{var x;const g=(x=f.target.files)==null?void 0:x[0];if(!g)return;const y=`${h}-${m}`;r(y);try{const _=`content-blocks/${Date.now()}-${g.name}`,{error:b}=await H.storage.from("newsletter-content").upload(_,g);if(!b){const{data:k}=H.storage.from("newsletter-content").getPublicUrl(_);c(h,m,"image_url",k.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(re,{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(nn,{className:"mr-1 h-3 w-3"})," Add Row"]})]}),s.length===0&&e.jsx("p",{className:"text-sm text-muted-foreground",children:"No content block rows yet. Add a row to create a 3-column layout."}),s.map((h,m)=>e.jsxs(_e,{className:"relative",children:[e.jsx(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(hr,{className:"h-4 w-4"})}),e.jsxs(De,{className:"p-4 pt-3",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-3",children:[e.jsx(Mp,{className:"h-4 w-4 text-muted-foreground"}),e.jsxs("span",{className:"text-xs font-medium text-muted-foreground uppercase tracking-wider",children:["Row ",m+1]})]}),e.jsx("div",{className:"grid grid-cols-3 gap-3",children:h.columns.map((f,g)=>{const y=`${m}-${g}`;return e.jsxs("div",{className:"space-y-2 border border-border/50 rounded-md p-3 bg-muted/20",children:[e.jsxs("span",{className:"text-xs text-muted-foreground font-medium",children:["Column ",g+1]}),f.image_url?e.jsxs("div",{className:"relative group",children:[e.jsx("img",{src:f.image_url,alt:"",className:"w-full h-20 object-cover rounded"}),e.jsx(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,g),children:e.jsx(hr,{className:"h-3 w-3"})})]}):e.jsxs("div",{className:"grid grid-cols-2 gap-1.5",children:[e.jsx(we,{type:"file",accept:"image/*",className:"hidden",id:`block-img-${y}`,onChange:x=>d(m,g,x)}),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(pc,{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:g}),children:[e.jsx(rb,{className:"h-3 w-3 mr-1"})," Library"]})]}),e.jsx(we,{placeholder:"Title",value:f.title,onChange:x=>c(m,g,"title",x.target.value),className:"h-8 text-sm"}),e.jsx(Ws,{placeholder:"Description",value:f.description,onChange:x=>c(m,g,"description",x.target.value),className:"text-sm min-h-[60px] resize-none"})]},g)})})]})]},m)),e.jsx(Bs,{open:!!a,onOpenChange:h=>!h&&i(null),children:e.jsxs(Fs,{className:"sm:max-w-2xl",children:[e.jsx(qs,{children:e.jsx($s,{children:"Choose a Graphic"})}),e.jsx(YPt,{onSelect:h=>{a&&(c(a.row,a.col,"image_url",h.image_url),i(null))}})]})})]})}function jhn(){const{toast:s}=Ci(),t=as(),[n,r]=N.useState(!1),[a,i]=N.useState(null),[l,o]=N.useState({title:"",description:"",publish_date:Js(new Date,"yyyy-MM-dd'T'HH:mm"),is_published:!1}),[c,d]=N.useState(null),[u,h]=N.useState(null),[m,f]=N.useState([]),[g,y]=N.useState([]),[x,_]=N.useState([]),[b,k]=N.useState([]),[A,T]=N.useState([]),[P,I]=N.useState(""),[M,L]=N.useState([]),[z,$]=N.useState(!1),{data:V,isLoading:W}=mt({queryKey:["admin-newsletters"],queryFn:async()=>{const{data:Se,error:Ie}=await H.from("newsletter_content").select("*").order("publish_date",{ascending:!1});if(Ie)throw Ie;return Se}}),G=_t({mutationFn:async Se=>{const{data:Ie,error:Me}=await H.from("newsletter_content").insert({title:Se.title,description:Se.description||null,preview_image_url:Se.preview_image_url,publish_date:Se.publish_date,is_published:Se.is_published,content_blocks:Se.content_blocks,html_code:Se.html_code}).select().single();if(Me)throw Me;return Ie},onSuccess:async Se=>{await ne(Se.id),t.invalidateQueries({queryKey:["admin-newsletters"]}),s({title:"Newsletter created successfully"}),Se.is_published&&SRs(Se.title,Se.id),ce()},onError:Se=>{s({title:"Error creating newsletter",description:Se.message,variant:"destructive"})}}),X=_t({mutationFn:async Se=>{const{error:Ie}=await H.from("newsletter_content").update({title:Se.title,description:Se.description||null,preview_image_url:Se.preview_image_url,publish_date:Se.publish_date,is_published:Se.is_published,content_blocks:Se.content_blocks,html_code:Se.html_code}).eq("id",Se.id);if(Ie)throw Ie;return Se.id},onSuccess:async Se=>{await ne(Se),t.invalidateQueries({queryKey:["admin-newsletters"]}),s({title:"Newsletter updated successfully"}),ce()},onError:Se=>{s({title:"Error updating newsletter",description:Se.message,variant:"destructive"})}}),te=_t({mutationFn:async Se=>{const{error:Ie}=await H.from("newsletter_content").delete().eq("id",Se);if(Ie)throw Ie},onSuccess:()=>{t.invalidateQueries({queryKey:["admin-newsletters"]}),s({title:"Newsletter deleted successfully"})},onError:Se=>{s({title:"Error deleting newsletter",description:Se.message,variant:"destructive"})}}),ne=async Se=>{await H.from("newsletter_drive_links").delete().eq("newsletter_id",Se),await H.from("newsletter_pdfs").delete().eq("newsletter_id",Se),await H.from("newsletter_videos").delete().eq("newsletter_id",Se),await H.from("newsletter_canva_links").delete().eq("newsletter_id",Se);for(const Ie of M){const Me=`${Se}/${Date.now()}-${Ie.file.name}`,{error:Re}=await H.storage.from("newsletter-content").upload(Me,Ie.file);if(!Re){const{data:Be}=H.storage.from("newsletter-content").getPublicUrl(Me);g.push({name:Ie.name,file_url:Be.publicUrl,file_size:Ie.file.size,sort_order:g.length})}}m.length>0&&await H.from("newsletter_drive_links").insert(m.map((Ie,Me)=>({newsletter_id:Se,title:Ie.title,drive_url:Ie.drive_url,sort_order:Me}))),g.length>0&&await H.from("newsletter_pdfs").insert(g.map((Ie,Me)=>({newsletter_id:Se,name:Ie.name,file_url:Ie.file_url,file_size:Ie.file_size||null,sort_order:Me}))),x.length>0&&await H.from("newsletter_videos").insert(x.map((Ie,Me)=>({newsletter_id:Se,title:Ie.title,video_url:Ie.video_url,sort_order:Me}))),b.length>0&&await H.from("newsletter_canva_links").insert(b.map((Ie,Me)=>({newsletter_id:Se,title:Ie.title,canva_share_link:Ie.canva_share_link,sort_order:Me})))},me=async Se=>{i(Se),o({title:Se.title,description:Se.description||"",publish_date:Js(new Date(Se.publish_date),"yyyy-MM-dd'T'HH:mm"),is_published:Se.is_published}),h(Se.preview_image_url),T(Se.content_blocks||[]),I(Se.html_code||"");const[Ie,Me,Re,Be]=await Promise.all([H.from("newsletter_drive_links").select("*").eq("newsletter_id",Se.id).order("sort_order"),H.from("newsletter_pdfs").select("*").eq("newsletter_id",Se.id).order("sort_order"),H.from("newsletter_videos").select("*").eq("newsletter_id",Se.id).order("sort_order"),H.from("newsletter_canva_links").select("*").eq("newsletter_id",Se.id).order("sort_order")]);f(Ie.data||[]),y(Me.data||[]),_(Re.data||[]),k(Be.data||[]),L([]),r(!0)},ue=async Se=>{const[Ie,Me,Re,Be]=await Promise.all([H.from("newsletter_drive_links").select("*").eq("newsletter_id",Se.id).order("sort_order"),H.from("newsletter_pdfs").select("*").eq("newsletter_id",Se.id).order("sort_order"),H.from("newsletter_videos").select("*").eq("newsletter_id",Se.id).order("sort_order"),H.from("newsletter_canva_links").select("*").eq("newsletter_id",Se.id).order("sort_order")]);i(null),o({title:`${Se.title} (Copy)`,description:Se.description||"",publish_date:Js(new Date,"yyyy-MM-dd'T'HH:mm"),is_published:!1}),h(Se.preview_image_url),T(Se.content_blocks||[]),I(Se.html_code||""),f((Ie.data||[]).map(({id:Ne,...Ge})=>Ge)),y((Me.data||[]).map(({id:Ne,...Ge})=>Ge)),_((Re.data||[]).map(({id:Ne,...Ge})=>Ge)),k((Be.data||[]).map(({id:Ne,...Ge})=>Ge)),L([]),r(!0)},ce=()=>{r(!1),i(null),o({title:"",description:"",publish_date:Js(new Date,"yyyy-MM-dd'T'HH:mm"),is_published:!1}),d(null),h(null),f([]),y([]),_([]),k([]),T([]),I(""),L([])},ae=async Se=>{var Me;const Ie=(Me=Se.target.files)==null?void 0:Me[0];Ie&&(d(Ie),h(URL.createObjectURL(Ie)))},he=async()=>{if(!l.title){s({title:"Title is required",variant:"destructive"});return}$(!0);let Se=u;if(c){const Ie=`previews/${Date.now()}-${c.name}`,{error:Me}=await H.storage.from("newsletter-content").upload(Ie,c);if(!Me){const{data:Re}=H.storage.from("newsletter-content").getPublicUrl(Ie);Se=Re.publicUrl}}a?X.mutate({id:a.id,...l,preview_image_url:Se,content_blocks:A,html_code:P||null}):G.mutate({...l,preview_image_url:Se,content_blocks:A,html_code:P||null}),$(!1)},xe=()=>f([...m,{title:"",drive_url:"",sort_order:m.length}]),ve=()=>_([...x,{title:"",video_url:"",sort_order:x.length}]),ge=()=>k([...b,{title:"",canva_share_link:"",sort_order:b.length}]),be=Se=>{const Ie=Se.target.files;if(!Ie)return;const Me=Array.from(Ie).map(Re=>({file:Re,name:Re.name.replace(/\.[^/.]+$/,"")}));L([...M,...Me])};return e.jsx(Qs,{title:"Newsletter Content",description:"Manage monthly newsletter templates and resources",children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(Uh,{title:"Newsletter Content",description:"Manage monthly newsletter templates and resources"}),e.jsxs("div",{className:"flex flex-col sm:flex-row justify-between items-start sm:items-center gap-4",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs(_e,{children:[e.jsx(zt,{className:"pb-2",children:e.jsx(qt,{className:"text-sm font-medium text-muted-foreground",children:"Total"})}),e.jsx(De,{children:e.jsx("div",{className:"text-2xl font-bold",children:(V==null?void 0:V.length)||0})})]}),e.jsxs(_e,{children:[e.jsx(zt,{className:"pb-2",children:e.jsx(qt,{className:"text-sm font-medium text-muted-foreground",children:"Published"})}),e.jsx(De,{children:e.jsx("div",{className:"text-2xl font-bold",children:(V==null?void 0:V.filter(Se=>Se.is_published).length)||0})})]})]}),e.jsxs(Bs,{open:n,onOpenChange:Se=>!Se&&ce(),children:[e.jsx(Ao,{asChild:!0,children:e.jsxs(B,{onClick:()=>r(!0),children:[e.jsx(nn,{className:"mr-2 h-4 w-4"})," Add Newsletter"]})}),e.jsxs(Fs,{className:"max-w-4xl max-h-[90vh] overflow-y-auto",children:[e.jsx(qs,{children:e.jsx($s,{children:a?"Edit Newsletter":"Add Newsletter"})}),e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{children:"Title *"}),e.jsx(we,{value:l.title,onChange:Se=>o({...l,title:Se.target.value}),placeholder:"Newsletter title"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{children:"Publish Date"}),e.jsx(we,{type:"datetime-local",value:l.publish_date,onChange:Se=>o({...l,publish_date:Se.target.value})})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{children:"Description"}),e.jsx(yN,{content:l.description,onChange:Se=>o({...l,description:Se}),placeholder:"Newsletter description",minHeight:"120px"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{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(hr,{className:"h-3 w-3"})})]}),e.jsxs("div",{children:[e.jsx(we,{type:"file",accept:"image/*",onChange:ae,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(ni,{className:"mr-2 h-4 w-4"})," Upload Image"]})})]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(zn,{checked:l.is_published,onCheckedChange:Se=>o({...l,is_published:Se})}),e.jsx(re,{children:"Published"})]}),e.jsx(whn,{rows:A,onChange:T}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(re,{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:P,onChange:Se=>I(Se.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(re,{className:"text-base font-medium",children:"Canva Links"}),e.jsxs(B,{type:"button",variant:"outline",size:"sm",onClick:ge,children:[e.jsx(nn,{className:"mr-1 h-3 w-3"})," Add Canva Link"]})]}),b.map((Se,Ie)=>e.jsxs("div",{className:"flex gap-2 items-center",children:[e.jsx(we,{placeholder:"Link title",value:Se.title,onChange:Me=>{const Re=[...b];Re[Ie].title=Me.target.value,k(Re)},className:"w-1/3"}),e.jsx(we,{placeholder:"Canva share link",value:Se.canva_share_link,onChange:Me=>{const Re=[...b];Re[Ie].canva_share_link=Me.target.value,k(Re)},className:"flex-1"}),e.jsx(B,{type:"button",variant:"ghost",size:"icon",onClick:()=>k(b.filter((Me,Re)=>Re!==Ie)),children:e.jsx(hr,{className:"h-4 w-4"})})]},Ie))]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(re,{className:"text-base font-medium",children:"Google Drive Links"}),e.jsxs(B,{type:"button",variant:"outline",size:"sm",onClick:xe,children:[e.jsx(nn,{className:"mr-1 h-3 w-3"})," Add Link"]})]}),m.map((Se,Ie)=>e.jsxs("div",{className:"flex gap-2 items-center",children:[e.jsx(we,{placeholder:"Link title",value:Se.title,onChange:Me=>{const Re=[...m];Re[Ie].title=Me.target.value,f(Re)},className:"w-1/3"}),e.jsx(we,{placeholder:"Google Drive URL",value:Se.drive_url,onChange:Me=>{const Re=[...m];Re[Ie].drive_url=Me.target.value,f(Re)},className:"flex-1"}),e.jsx(B,{type:"button",variant:"ghost",size:"icon",onClick:()=>f(m.filter((Me,Re)=>Re!==Ie)),children:e.jsx(hr,{className:"h-4 w-4"})})]},Ie))]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(re,{className:"text-base font-medium",children:"PDF Files"}),e.jsxs("div",{children:[e.jsx(we,{type:"file",accept:".pdf",multiple:!0,onChange:be,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(ni,{className:"mr-1 h-3 w-3"})," Upload PDF"]})})]})]}),g.map((Se,Ie)=>e.jsxs("div",{className:"flex gap-2 items-center bg-muted/50 p-2 rounded",children:[e.jsx(Wr,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{className:"flex-1 text-sm",children:Se.name}),e.jsx(B,{type:"button",variant:"ghost",size:"icon",onClick:()=>y(g.filter((Me,Re)=>Re!==Ie)),children:e.jsx(hr,{className:"h-4 w-4"})})]},`existing-${Ie}`)),M.map((Se,Ie)=>e.jsxs("div",{className:"flex gap-2 items-center bg-muted/50 p-2 rounded",children:[e.jsx(Wr,{className:"h-4 w-4 text-muted-foreground"}),e.jsx(we,{value:Se.name,onChange:Me=>{const Re=[...M];Re[Ie].name=Me.target.value,L(Re)},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:()=>L(M.filter((Me,Re)=>Re!==Ie)),children:e.jsx(hr,{className:"h-4 w-4"})})]},`pending-${Ie}`))]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(re,{className:"text-base font-medium",children:"Video Links"}),e.jsxs(B,{type:"button",variant:"outline",size:"sm",onClick:ve,children:[e.jsx(nn,{className:"mr-1 h-3 w-3"})," Add Video"]})]}),x.map((Se,Ie)=>e.jsxs("div",{className:"flex gap-2 items-center",children:[e.jsx(we,{placeholder:"Video title",value:Se.title,onChange:Me=>{const Re=[...x];Re[Ie].title=Me.target.value,_(Re)},className:"w-1/3"}),e.jsx(we,{placeholder:"Video URL",value:Se.video_url,onChange:Me=>{const Re=[...x];Re[Ie].video_url=Me.target.value,_(Re)},className:"flex-1"}),e.jsx(B,{type:"button",variant:"ghost",size:"icon",onClick:()=>_(x.filter((Me,Re)=>Re!==Ie)),children:e.jsx(hr,{className:"h-4 w-4"})})]},Ie))]}),e.jsxs("div",{className:"flex justify-end gap-2 pt-4 border-t",children:[e.jsx(B,{variant:"outline",onClick:ce,children:"Cancel"}),e.jsx(B,{onClick:he,disabled:z||G.isPending||X.isPending,children:z?"Uploading...":a?"Update":"Create"})]})]})]})]})]}),e.jsx(_e,{children:e.jsx(De,{className:"p-0",children:e.jsxs(Oa,{children:[e.jsx(Fa,{children:e.jsxs(un,{children:[e.jsx(Mt,{children:"Name"}),e.jsx(Mt,{children:"Publish Date"}),e.jsx(Mt,{children:"Status"}),e.jsx(Mt,{className:"text-right",children:"Actions"})]})}),e.jsx(za,{children:W?e.jsx(un,{children:e.jsx(gt,{colSpan:4,className:"text-center py-8",children:"Loading..."})}):(V==null?void 0:V.length)===0?e.jsx(un,{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(Se=>e.jsxs(un,{children:[e.jsx(gt,{children:e.jsxs("div",{className:"flex items-center gap-3",children:[Se.preview_image_url?e.jsx("img",{src:Se.preview_image_url,alt:Se.title,className:"w-10 h-10 rounded object-cover"}):e.jsx("div",{className:"w-10 h-10 rounded bg-muted flex items-center justify-center",children:e.jsx(Wr,{className:"h-5 w-5 text-muted-foreground"})}),e.jsxs("div",{children:[e.jsx("div",{className:"font-medium",children:Se.title}),Se.description&&e.jsx("div",{className:"text-sm text-muted-foreground line-clamp-1",children:Se.description.replace(/<[^>]*>/g,"")})]})]})}),e.jsx(gt,{children:Js(new Date(Se.publish_date),"MMM d, yyyy")}),e.jsx(gt,{children:e.jsx("span",{className:`inline-flex items-center px-2 py-1 rounded-full text-xs font-medium ${Se.is_published?"bg-green-100 text-green-800 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:Se.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:()=>me(Se),title:"Edit",children:e.jsx(Ja,{className:"h-4 w-4"})}),e.jsx(B,{variant:"ghost",size:"icon",onClick:()=>ue(Se),title:"Duplicate",children:e.jsx(Pa,{className:"h-4 w-4"})}),e.jsx(B,{variant:"ghost",size:"icon",className:"text-destructive hover:text-destructive",title:"Delete",onClick:()=>{confirm("Are you sure you want to delete this newsletter?")&&te.mutate(Se.id)},children:e.jsx(qn,{className:"h-4 w-4"})})]})})]},Se.id))})]})})})]})})}const Nhn=["Headers","Footers","Seasonal","Holidays","Market Updates","Just Sold","Just Listed","Open House","Buyer Tips","Seller Tips","Testimonials","CTAs & Buttons","Dividers","General"];function khn(){const s=as(),t=N.useRef(null),[n,r]=N.useState(""),[a,i]=N.useState("all"),[l,o]=N.useState(null),[c,d]=N.useState(!1),[u,h]=N.useState(!1),[m,f]=N.useState({title:"",description:"",image_url:"",category:"General",tags:"",is_active:!0,is_featured:!1}),{data:g=[],isLoading:y}=mt({queryKey:["admin-newsletter-graphics"],queryFn:async()=>{const{data:$,error:V}=await H.from("newsletter_graphics").select("*").order("is_featured",{ascending:!1}).order("created_at",{ascending:!1});if(V)throw V;return $||[]}}),x=N.useMemo(()=>{const $=new Set(Nhn);return g.forEach(V=>$.add(V.category)),Array.from($).sort()},[g]),_=N.useMemo(()=>{const $=n.trim().toLowerCase();return g.filter(V=>a!=="all"&&V.category!==a?!1:$?V.title.toLowerCase().includes($)||(V.description||"").toLowerCase().includes($)||V.tags.some(W=>W.toLowerCase().includes($)):!0)},[g,n,a]),b=()=>{f({title:"",description:"",image_url:"",category:"General",tags:"",is_active:!0,is_featured:!1}),o(null)},k=()=>{b(),d(!0)},A=$=>{o($),f({title:$.title,description:$.description||"",image_url:$.image_url,category:$.category,tags:$.tags.join(", "),is_active:$.is_active,is_featured:$.is_featured}),d(!0)},T=async $=>{var V;if(!$.type.startsWith("image/")){ie.error("Please choose an image file");return}if($.size>15*1024*1024){ie.error("Image must be under 15MB");return}h(!0);try{const W=((V=$.name.split(".").pop())==null?void 0:V.toLowerCase())||"png",G=`graphics-library/${Date.now()}-${Math.random().toString(36).slice(2,8)}.${W}`,{error:X}=await H.storage.from("newsletter-content").upload(G,$,{cacheControl:"31536000",upsert:!1,contentType:$.type});if(X)throw X;const{data:te}=H.storage.from("newsletter-content").getPublicUrl(G);f(ne=>({...ne,image_url:te.publicUrl,title:ne.title||$.name.replace(/\.[^.]+$/,"").replace(/[-_]/g," ")})),ie.success("Uploaded")}catch(W){ie.error(W.message||"Upload failed")}finally{h(!1),t.current&&(t.current.value="")}},P=_t({mutationFn:async()=>{var W;if(!m.image_url)throw new Error("Please upload an image");if(!m.title.trim())throw new Error("Please add a title");const $=m.tags.split(",").map(G=>G.trim()).filter(Boolean),V={title:m.title.trim(),description:m.description.trim()||null,image_url:m.image_url,category:m.category||"General",tags:$,is_active:m.is_active,is_featured:m.is_featured};if(l){const{error:G}=await H.from("newsletter_graphics").update(V).eq("id",l.id);if(G)throw G}else{const{data:G}=await H.auth.getUser(),{error:X}=await H.from("newsletter_graphics").insert({...V,created_by:(W=G.user)==null?void 0:W.id});if(X)throw X}},onSuccess:()=>{ie.success(l?"Updated":"Graphic added to library"),s.invalidateQueries({queryKey:["admin-newsletter-graphics"]}),s.invalidateQueries({queryKey:["newsletter-graphics-picker"]}),d(!1),b()},onError:$=>ie.error($.message||"Save failed")}),I=_t({mutationFn:async $=>{const{error:V}=await H.from("newsletter_graphics").delete().eq("id",$);if(V)throw V},onSuccess:()=>{ie.success("Deleted"),s.invalidateQueries({queryKey:["admin-newsletter-graphics"]}),s.invalidateQueries({queryKey:["newsletter-graphics-picker"]})},onError:$=>ie.error($.message||"Delete failed")}),M=async $=>{const{error:V}=await H.from("newsletter_graphics").update({is_active:!$.is_active}).eq("id",$.id);V?ie.error(V.message):(s.invalidateQueries({queryKey:["admin-newsletter-graphics"]}),s.invalidateQueries({queryKey:["newsletter-graphics-picker"]}))},L=async $=>{const{error:V}=await H.from("newsletter_graphics").update({is_featured:!$.is_featured}).eq("id",$.id);V?ie.error(V.message):(s.invalidateQueries({queryKey:["admin-newsletter-graphics"]}),s.invalidateQueries({queryKey:["newsletter-graphics-picker"]}))},z=$=>{navigator.clipboard.writeText($),ie.success("URL copied")};return e.jsxs(Qs,{children:[e.jsxs("div",{className:"p-4 md:p-6 max-w-7xl mx-auto space-y-5",children:[e.jsx(Uh,{title:"Newsletter Graphics Library",description:"Upload branded graphics agents can drop into their newsletters and email campaigns."}),e.jsx(_e,{children:e.jsxs(De,{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(Gr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(we,{value:n,onChange:$=>r($.target.value),placeholder:"Search graphics by title, tag, description...",className:"pl-9"})]}),e.jsxs(Ns,{value:a,onValueChange:i,children:[e.jsx(ws,{className:"w-full md:w-56",children:e.jsx(ks,{})}),e.jsxs(js,{children:[e.jsx(nt,{value:"all",children:"All categories"}),x.map($=>e.jsx(nt,{value:$,children:$},$))]})]}),e.jsxs(B,{onClick:k,className:"gap-1.5 whitespace-nowrap",children:[e.jsx(Gv,{className:"h-4 w-4"})," Add Graphic"]})]})}),y?e.jsx("div",{className:"flex justify-center py-16",children:e.jsx(us,{className:"h-6 w-6 animate-spin text-muted-foreground"})}):_.length===0?e.jsx(_e,{children:e.jsxs(De,{className:"py-16 text-center",children:[e.jsx(pc,{className:"h-10 w-10 mx-auto mb-3 text-muted-foreground/50"}),e.jsx("p",{className:"text-sm text-muted-foreground mb-4",children:g.length===0?"No graphics uploaded yet — add your first one to get started.":"No graphics match your filters."}),g.length===0&&e.jsxs(B,{onClick:k,className:"gap-1.5",children:[e.jsx(Gv,{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:_.map($=>e.jsxs(_e,{className:`overflow-hidden group ${$.is_active?"":"opacity-60"}`,children:[e.jsxs("div",{className:"aspect-video bg-muted relative overflow-hidden",children:[e.jsx("img",{src:$.image_url,alt:$.title,loading:"lazy",className:"w-full h-full object-cover"}),$.is_featured&&e.jsxs(We,{className:"absolute top-2 left-2 gap-0.5 bg-amber-500 hover:bg-amber-500 text-white border-0",children:[e.jsx(Wa,{className:"h-3 w-3 fill-current"})," Featured"]}),!$.is_active&&e.jsx(We,{variant:"secondary",className:"absolute top-2 right-2",children:"Hidden"})]}),e.jsxs(De,{className:"p-3 space-y-2",children:[e.jsxs("div",{children:[e.jsx("p",{className:"font-medium text-sm truncate",children:$.title}),e.jsx("p",{className:"text-xs text-muted-foreground",children:$.category})]}),$.tags.length>0&&e.jsx("div",{className:"flex flex-wrap gap-1",children:$.tags.slice(0,3).map(V=>e.jsx(We,{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:()=>A($),title:"Edit",children:e.jsx(Ja,{className:"h-3.5 w-3.5"})}),e.jsx(B,{size:"icon",variant:"ghost",className:"h-7 w-7",onClick:()=>L($),title:$.is_featured?"Unfeature":"Feature",children:e.jsx(Wa,{className:`h-3.5 w-3.5 ${$.is_featured?"fill-amber-500 text-amber-500":""}`})}),e.jsx(B,{size:"icon",variant:"ghost",className:"h-7 w-7",onClick:()=>z($.image_url),title:"Copy URL",children:e.jsx(Pa,{className:"h-3.5 w-3.5"})})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(zn,{checked:$.is_active,onCheckedChange:()=>M($)}),e.jsx(B,{size:"icon",variant:"ghost",className:"h-7 w-7 text-destructive hover:text-destructive",onClick:()=>{confirm(`Delete "${$.title}"?`)&&I.mutate($.id)},children:e.jsx(qn,{className:"h-3.5 w-3.5"})})]})]})]})]},$.id))})]}),e.jsx(Bs,{open:c,onOpenChange:d,children:e.jsxs(Fs,{className:"sm:max-w-lg max-h-[90vh] overflow-y-auto",children:[e.jsx(qs,{children:e.jsx($s,{children:l?"Edit Graphic":"Add New Graphic"})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(re,{children:"Image"}),e.jsx("input",{ref:t,type:"file",accept:"image/*",className:"hidden",onChange:$=>{var W;const V=(W=$.target.files)==null?void 0:W[0];V&&T(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:()=>f($=>({...$,image_url:""})),children:e.jsx(hr,{className:"h-3.5 w-3.5"})})]}):e.jsx("button",{type:"button",onClick:()=>{var $;return($=t.current)==null?void 0:$.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(us,{className:"h-8 w-8 mx-auto mb-2 animate-spin text-primary"}),e.jsx("p",{className:"text-sm",children:"Uploading..."})]}):e.jsxs(e.Fragment,{children:[e.jsx(ni,{className:"h-8 w-8 mx-auto mb-2 text-muted-foreground"}),e.jsx("p",{className:"text-sm font-medium",children:"Click to upload image"}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:"PNG, JPG, WEBP, GIF · up to 15MB"})]})})]}),e.jsxs("div",{children:[e.jsx(re,{htmlFor:"g-title",children:"Title *"}),e.jsx(we,{id:"g-title",value:m.title,onChange:$=>f(V=>({...V,title:$.target.value})),placeholder:"e.g. Fall Market Update Banner"})]}),e.jsxs("div",{children:[e.jsx(re,{htmlFor:"g-desc",children:"Description"}),e.jsx(Ws,{id:"g-desc",value:m.description,onChange:$=>f(V=>({...V,description:$.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(re,{children:"Category"}),e.jsxs(Ns,{value:m.category,onValueChange:$=>f(V=>({...V,category:$})),children:[e.jsx(ws,{children:e.jsx(ks,{})}),e.jsx(js,{children:x.map($=>e.jsx(nt,{value:$,children:$},$))})]})]}),e.jsxs("div",{children:[e.jsx(re,{htmlFor:"g-tags",children:"Tags (comma-separated)"}),e.jsx(we,{id:"g-tags",value:m.tags,onChange:$=>f(V=>({...V,tags:$.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(zn,{checked:m.is_featured,onCheckedChange:$=>f(V=>({...V,is_featured:$}))})]}),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(zn,{checked:m.is_active,onCheckedChange:$=>f(V=>({...V,is_active:$}))})]})]}),e.jsxs(Cr,{children:[e.jsx(B,{variant:"outline",onClick:()=>d(!1),children:"Cancel"}),e.jsxs(B,{onClick:()=>P.mutate(),disabled:P.isPending,children:[P.isPending&&e.jsx(us,{className:"h-3.5 w-3.5 mr-1.5 animate-spin"}),l?"Save Changes":"Add to Library"]})]})]})})]})}const eht={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 Shn(){const{user:s}=Ls(),{toast:t}=Ci(),n=tr(),r=as(),[a,i]=N.useState(""),[l,o]=N.useState("popular"),[c,d]=N.useState(!1),[u,h]=N.useState(""),[m,f]=N.useState(""),[g,y]=N.useState(!1),{data:x=[],isLoading:_}=mt({queryKey:["wishlist-items",l,g],queryFn:async()=>{let P=H.from("wishlist_items").select("*");g&&s&&(P=P.eq("user_id",s.id)),l==="latest"?P=P.order("created_at",{ascending:!1}):l==="popular"?P=P.order("vote_count",{ascending:!1}):l==="trending"&&(P=P.order("vote_count",{ascending:!1}));const{data:I,error:M}=await P;if(M)throw M;const L=[...new Set((I==null?void 0:I.map(te=>te.user_id))||[])],{data:z}=await H.from("profiles").select("id, name").in("id",L),$=new Map((z==null?void 0:z.map(te=>[te.id,te]))||[]);let V=[];if(s){const{data:te}=await H.from("wishlist_votes").select("item_id").eq("user_id",s.id);V=(te==null?void 0:te.map(ne=>ne.item_id))||[]}const W=(I==null?void 0:I.map(te=>te.id))||[],{data:G}=await H.from("wishlist_comments").select("item_id").in("item_id",W),X=new Map;return G==null||G.forEach(te=>{X.set(te.item_id,(X.get(te.item_id)||0)+1)}),I==null?void 0:I.map(te=>{const ne=$.get(te.user_id),me=(ne==null?void 0:ne.name)||"Unknown";return{...te,user_name:me,user_initials:me.split(" ").map(ue=>ue[0]).join("").toUpperCase().slice(0,2),has_voted:V.includes(te.id),comment_count:X.get(te.id)||0}})}}),b=_t({mutationFn:async({title:P,description:I})=>{const{error:M}=await H.from("wishlist_items").insert({user_id:s.id,title:P,description:I});if(M)throw M},onSuccess:()=>{r.invalidateQueries({queryKey:["wishlist-items"]}),d(!1),h(""),f(""),t({title:"Idea submitted!",description:"Your idea has been added to the wishlist."})},onError:P=>{t({title:"Error",description:P.message,variant:"destructive"})}}),k=_t({mutationFn:async({itemId:P,hasVoted:I})=>{if(I){const{error:M}=await H.from("wishlist_votes").delete().eq("item_id",P).eq("user_id",s.id);if(M)throw M;return{itemId:P,wasAdded:!1}}else{const{error:M}=await H.from("wishlist_votes").insert({item_id:P,user_id:s.id});if(M)throw M;return{itemId:P,wasAdded:!0}}},onSuccess:async P=>{if(r.invalidateQueries({queryKey:["wishlist-items"]}),P!=null&&P.wasAdded){const I=x.find(L=>L.id===P.itemId),M=((I==null?void 0:I.vote_count)||0)+1;H.functions.invoke("wishlist-notify",{body:{itemId:P.itemId,voteCount:M}}).catch(console.error)}},onError:P=>{t({title:"Error",description:P.message,variant:"destructive"})}}),A=x.filter(P=>P.title.toLowerCase().includes(a.toLowerCase())||P.description.toLowerCase().includes(a.toLowerCase())),T=()=>{if(!u.trim()||!m.trim()){t({title:"Error",description:"Please fill in both title and description.",variant:"destructive"});return}b.mutate({title:u.trim(),description:m.trim()})};return e.jsx(Qs,{title:"Wishlist",children:e.jsxs("div",{className:"max-w-4xl mx-auto",children:[e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center justify-between gap-4 mb-6",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"p-2 bg-primary/10 rounded-lg",children:e.jsx(Z2,{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(Bs,{open:c,onOpenChange:d,children:[e.jsx(Ao,{asChild:!0,children:e.jsxs(B,{className:"gap-2",children:[e.jsx(nn,{className:"h-4 w-4"}),"Add Idea"]})}),e.jsxs(Fs,{children:[e.jsx(qs,{children:e.jsx($s,{children:"Submit a New Idea"})}),e.jsxs("div",{className:"space-y-4 pt-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{htmlFor:"title",children:"Title"}),e.jsx(we,{id:"title",placeholder:"Give your idea a clear title...",value:u,onChange:P=>h(P.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{htmlFor:"description",children:"Description"}),e.jsx(Ws,{id:"description",placeholder:"Describe your idea in detail. What problem does it solve? How would it help agents?",value:m,onChange:P=>f(P.target.value),rows:4})]}),e.jsx(B,{onClick:T,className:"w-full",disabled:b.isPending,children:b.isPending?e.jsxs(e.Fragment,{children:[e.jsx(us,{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(Gr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(we,{placeholder:"Search ideas...",value:a,onChange:P=>i(P.target.value),className:"pl-10"})]}),e.jsx("div",{className:"flex gap-2",children:e.jsx(ya,{value:l,onValueChange:P=>o(P),children:e.jsxs(va,{children:[e.jsx(ls,{value:"popular",children:"Most Popular"}),e.jsx(ls,{value:"latest",children:"Latest"}),e.jsx(ls,{value:"trending",children:"Trending"})]})})})]}),e.jsx("div",{className:"flex items-center gap-2 mb-4",children:e.jsx(B,{variant:g?"default":"outline",size:"sm",onClick:()=>y(!g),children:g?"Show All Ideas":"My Ideas"})}),_?e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsx(us,{className:"h-8 w-8 animate-spin text-muted-foreground"})}):A.length===0?e.jsxs("div",{className:"text-center py-12 bg-muted/30 rounded-lg",children:[e.jsx(Z2,{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(nn,{className:"h-4 w-4 mr-2"}),"Add Idea"]})]}):e.jsx("div",{className:"space-y-3",children:A.map(P=>e.jsx("div",{className:"bg-card border rounded-lg p-4 hover:shadow-md transition-shadow cursor-pointer",onClick:()=>n(`/wishlist/${P.id}`),children:e.jsxs("div",{className:"flex items-start gap-4",children:[e.jsxs("button",{onClick:I=>{I.stopPropagation(),k.mutate({itemId:P.id,hasVoted:P.has_voted||!1})},className:Ot("flex flex-col items-center justify-center min-w-[50px] py-2 px-3 rounded-lg border transition-colors",P.has_voted?"bg-primary/10 border-primary text-primary":"bg-muted/50 border-border hover:bg-muted"),children:[e.jsx(Om,{className:Ot("h-4 w-4",P.has_voted&&"fill-current")}),e.jsx("span",{className:"text-sm font-semibold",children:P.vote_count})]}),e.jsx(Ua,{className:"h-10 w-10 bg-primary/20",children:e.jsx(qa,{className:"bg-primary/20 text-primary text-sm font-medium",children:P.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:P.title}),e.jsx(We,{className:Ot("text-xs",eht[P.status].color),children:eht[P.status].label})]}),e.jsx("p",{className:"text-muted-foreground text-sm line-clamp-2",children:P.description}),e.jsxs("div",{className:"flex items-center gap-3 mt-2 text-xs text-muted-foreground",children:[e.jsx("span",{children:P.user_name}),e.jsx("span",{children:"•"}),e.jsx("span",{children:new Date(P.created_at).toLocaleDateString()})]})]}),e.jsxs("div",{className:"flex items-center gap-1 text-muted-foreground",children:[e.jsx(xo,{className:"h-4 w-4"}),e.jsx("span",{className:"text-sm",children:P.comment_count})]})]})},P.id))})]})})}const tht={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 Chn(){const{itemId:s}=uo(),t=tr(),{user:n}=Ls(),{toast:r}=Ci(),a=as(),[i,l]=N.useState(""),{data:o=!1}=mt({queryKey:["user-is-admin",n==null?void 0:n.id],queryFn:async()=>{if(!n)return!1;const{data:x,error:_}=await H.from("user_roles").select("role").eq("user_id",n.id).eq("role","admin").maybeSingle();return!_&&!!x},enabled:!!n}),{data:c,isLoading:d}=mt({queryKey:["wishlist-item",s],queryFn:async()=>{const{data:x,error:_}=await H.from("wishlist_items").select("*").eq("id",s).single();if(_)throw _;const{data:b}=await H.from("profiles").select("name").eq("id",x.user_id).single();let k=!1;if(n){const{data:A}=await H.from("wishlist_votes").select("id").eq("item_id",s).eq("user_id",n.id).maybeSingle();k=!!A}return{...x,user_name:(b==null?void 0:b.name)||"Unknown",user_initials:((b==null?void 0:b.name)||"U").split(" ").map(A=>A[0]).join("").toUpperCase().slice(0,2),has_voted:k}}}),{data:u=[],isLoading:h}=mt({queryKey:["wishlist-comments",s],queryFn:async()=>{const{data:x,error:_}=await H.from("wishlist_comments").select("*").eq("item_id",s).order("created_at",{ascending:!0});if(_)throw _;const b=[...new Set((x==null?void 0:x.map(T=>T.user_id))||[])],{data:k}=await H.from("profiles").select("id, name").in("id",b),A=new Map((k==null?void 0:k.map(T=>[T.id,T]))||[]);return x==null?void 0:x.map(T=>{const P=A.get(T.user_id),I=(P==null?void 0:P.name)||"Unknown";return{...T,user_name:I,user_initials:I.split(" ").map(M=>M[0]).join("").toUpperCase().slice(0,2)}})}}),m=_t({mutationFn:async x=>{if(x){const{error:_}=await H.from("wishlist_votes").delete().eq("item_id",s).eq("user_id",n.id);if(_)throw _;return{wasAdded:!1}}else{const{error:_}=await H.from("wishlist_votes").insert({item_id:s,user_id:n.id});if(_)throw _;return{wasAdded:!0}}},onSuccess:async x=>{if(a.invalidateQueries({queryKey:["wishlist-item",s]}),a.invalidateQueries({queryKey:["wishlist-items"]}),x!=null&&x.wasAdded&&c){const _=(c.vote_count||0)+1;H.functions.invoke("wishlist-notify",{body:{itemId:s,voteCount:_}}).catch(console.error)}},onError:x=>{r({title:"Error",description:x.message,variant:"destructive"})}}),f=_t({mutationFn:async x=>{const{error:_}=await H.from("wishlist_comments").insert({item_id:s,user_id:n.id,content:x});if(_)throw _},onSuccess:()=>{a.invalidateQueries({queryKey:["wishlist-comments",s]}),l(""),r({title:"Comment added!"})},onError:x=>{r({title:"Error",description:x.message,variant:"destructive"})}}),g=_t({mutationFn:async x=>{const{error:_}=await H.from("wishlist_comments").delete().eq("id",x);if(_)throw _},onSuccess:()=>{a.invalidateQueries({queryKey:["wishlist-comments",s]}),r({title:"Comment deleted"})},onError:x=>{r({title:"Error",description:x.message,variant:"destructive"})}}),y=()=>{i.trim()&&f.mutate(i.trim())};return d?e.jsx(Qs,{title:"Wishlist",children:e.jsxs("div",{className:"max-w-3xl mx-auto",children:[e.jsx(xn,{className:"h-8 w-32 mb-6"}),e.jsx(xn,{className:"h-48 w-full mb-6"}),e.jsx(xn,{className:"h-32 w-full"})]})}):c?e.jsx(Qs,{title:"Wishlist",children:e.jsxs("div",{className:"max-w-3xl mx-auto",children:[e.jsxs(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:Ot("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(Om,{className:Ot("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(We,{className:Ot("text-xs",tht[c.status].color),children:tht[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(Ua,{className:"h-6 w-6",children:e.jsx(qa,{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(dke,{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()||f.isPending,size:"icon",className:"h-auto",children:f.isPending?e.jsx(us,{className:"h-4 w-4 animate-spin"}):e.jsx(Rr,{className:"h-4 w-4"})})]}),h?e.jsx("div",{className:"space-y-4",children:[1,2].map(x=>e.jsx(xn,{className:"h-20 w-full"},x))}):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(x=>e.jsxs("div",{className:"flex gap-3 p-3 bg-muted/30 rounded-lg",children:[e.jsx(Ua,{className:"h-8 w-8",children:e.jsx(qa,{className:"bg-primary/20 text-primary text-xs",children:x.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:x.user_name}),e.jsx("span",{className:"text-xs text-muted-foreground",children:new Date(x.created_at).toLocaleDateString()})]}),e.jsx(BVe,{content:x.content,className:"text-sm text-foreground"})]}),(n==null?void 0:n.id)===x.user_id&&e.jsx(B,{variant:"ghost",size:"icon",className:"h-8 w-8 text-muted-foreground hover:text-destructive",onClick:()=>g.mutate(x.id),children:e.jsx(qn,{className:"h-4 w-4"})})]},x.id))})]})]})}):e.jsx(Qs,{title:"Wishlist",children:e.jsxs("div",{className:"max-w-3xl mx-auto text-center py-12",children:[e.jsx("p",{className:"text-muted-foreground",children:"Item not found"}),e.jsx(B,{variant:"link",onClick:()=>t("/wishlist"),children:"Go back to Wishlist"})]})})}const sht={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"}},nht=["open","under_review","planned","in_progress","launched","declined"];function Ahn(){const{toast:s}=Ci(),t=tr(),n=as(),[r,a]=N.useState(""),[i,l]=N.useState("all"),[o,c]=N.useState(!1),[d,u]=N.useState(null),{data:h=[],isLoading:m}=mt({queryKey:["admin-wishlist-items"],queryFn:async()=>{const{data:_,error:b}=await H.from("wishlist_items").select("*").order("vote_count",{ascending:!1});if(b)throw b;const k=[...new Set((_==null?void 0:_.map(L=>L.user_id))||[])],{data:A}=await H.from("profiles").select("id, name, email").in("id",k),T=new Map((A==null?void 0:A.map(L=>[L.id,L]))||[]),P=(_==null?void 0:_.map(L=>L.id))||[],{data:I}=await H.from("wishlist_comments").select("item_id").in("item_id",P),M=new Map;return I==null||I.forEach(L=>{M.set(L.item_id,(M.get(L.item_id)||0)+1)}),_==null?void 0:_.map(L=>{const z=T.get(L.user_id);return{...L,user_name:(z==null?void 0:z.name)||"Unknown",user_email:(z==null?void 0:z.email)||"",comment_count:M.get(L.id)||0}})}}),f=_t({mutationFn:async({itemId:_,status:b})=>{const{error:k}=await H.from("wishlist_items").update({status:b}).eq("id",_);if(k)throw k},onSuccess:()=>{n.invalidateQueries({queryKey:["admin-wishlist-items"]}),s({title:"Status updated!"})},onError:_=>{s({title:"Error",description:_.message,variant:"destructive"})}}),g=_t({mutationFn:async _=>{const{error:b}=await H.from("wishlist_items").delete().eq("id",_);if(b)throw b},onSuccess:()=>{n.invalidateQueries({queryKey:["admin-wishlist-items"]}),c(!1),u(null),s({title:"Item deleted!"})},onError:_=>{s({title:"Error",description:_.message,variant:"destructive"})}}),y=h.filter(_=>{const b=_.title.toLowerCase().includes(r.toLowerCase())||_.description.toLowerCase().includes(r.toLowerCase())||_.user_name.toLowerCase().includes(r.toLowerCase()),k=i==="all"||_.status===i;return b&&k}),x={total:h.length,open:h.filter(_=>_.status==="open").length,inProgress:h.filter(_=>_.status==="in_progress").length,launched:h.filter(_=>_.status==="launched").length,highVotes:h.filter(_=>_.vote_count>=10).length};return e.jsx(Qs,{title:"Admin - Wishlist",children:e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsx(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:x.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:x.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:x.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:x.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:x.highVotes})]})]}),e.jsxs("div",{className:"flex flex-col sm:flex-row gap-4",children:[e.jsxs("div",{className:"relative flex-1",children:[e.jsx(Gr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(we,{placeholder:"Search ideas, users...",value:r,onChange:_=>a(_.target.value),className:"pl-10"})]}),e.jsxs(Ns,{value:i,onValueChange:_=>l(_),children:[e.jsx(ws,{className:"w-[180px]",children:e.jsx(ks,{placeholder:"Filter by status"})}),e.jsxs(js,{children:[e.jsx(nt,{value:"all",children:"All Statuses"}),nht.map(_=>e.jsx(nt,{value:_,children:sht[_].label},_))]})]})]}),m?e.jsx("div",{className:"space-y-2",children:[1,2,3,4,5].map(_=>e.jsx(xn,{className:"h-16 w-full"},_))}):e.jsx("div",{className:"bg-card border rounded-lg overflow-hidden",children:e.jsxs(Oa,{children:[e.jsx(Fa,{children:e.jsxs(un,{children:[e.jsx(Mt,{className:"w-[60px]",children:"Votes"}),e.jsx(Mt,{children:"Title"}),e.jsx(Mt,{className:"hidden md:table-cell",children:"Submitted By"}),e.jsx(Mt,{className:"hidden sm:table-cell",children:"Comments"}),e.jsx(Mt,{children:"Status"}),e.jsx(Mt,{className:"w-[100px]",children:"Actions"})]})}),e.jsx(za,{children:y.length===0?e.jsx(un,{children:e.jsx(gt,{colSpan:6,className:"text-center py-8 text-muted-foreground",children:"No items found"})}):y.map(_=>e.jsxs(un,{className:Ot(_.vote_count>=10&&"bg-primary/5"),children:[e.jsx(gt,{children:e.jsx(We,{variant:_.vote_count>=10?"default":"secondary",children:_.vote_count})}),e.jsx(gt,{children:e.jsxs("div",{children:[e.jsx("p",{className:"font-medium line-clamp-1",children:_.title}),e.jsx("p",{className:"text-sm text-muted-foreground line-clamp-1",children:_.description})]})}),e.jsx(gt,{className:"hidden md:table-cell",children:e.jsxs("div",{children:[e.jsx("p",{className:"text-sm",children:_.user_name}),e.jsx("p",{className:"text-xs text-muted-foreground",children:_.user_email})]})}),e.jsx(gt,{className:"hidden sm:table-cell",children:_.comment_count}),e.jsx(gt,{children:e.jsxs(Ns,{value:_.status,onValueChange:b=>f.mutate({itemId:_.id,status:b}),children:[e.jsx(ws,{className:"w-[140px] h-8",children:e.jsx(ks,{})}),e.jsx(js,{children:nht.map(b=>e.jsx(nt,{value:b,children:sht[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/${_.id}`,"_blank"),children:e.jsx(Tr,{className:"h-4 w-4"})}),e.jsx(B,{variant:"ghost",size:"icon",className:"text-destructive",onClick:()=>{u(_.id),c(!0)},children:e.jsx(qn,{className:"h-4 w-4"})})]})})]},_.id))})]})}),e.jsx(Bs,{open:o,onOpenChange:c,children:e.jsxs(Fs,{children:[e.jsx(qs,{children:e.jsx($s,{children:"Delete Wishlist Item"})}),e.jsx("p",{className:"text-muted-foreground",children:"Are you sure you want to delete this idea? This will also delete all votes and comments."}),e.jsxs("div",{className:"flex justify-end gap-2 mt-4",children:[e.jsx(B,{variant:"outline",onClick:()=>c(!1),children:"Cancel"}),e.jsx(B,{variant:"destructive",onClick:()=>d&&g.mutate(d),disabled:g.isPending,children:g.isPending?e.jsxs(e.Fragment,{children:[e.jsx(us,{className:"h-4 w-4 mr-2 animate-spin"}),"Deleting..."]}):"Delete"})]})]})})]})})}function Thn(){const{user:s}=Ls(),[t,n]=N.useState([]),[r,a]=N.useState(!0),[i,l]=N.useState(!1),[o,c]=N.useState(null),[d,u]=N.useState(!1),[h,m]=N.useState(null),[f,g]=N.useState(""),[y,x]=N.useState(""),[_,b]=N.useState(""),[k,A]=N.useState(""),[T,P]=N.useState(""),[I,M]=N.useState(!1),[L,z]=N.useState(""),[$,V]=N.useState("once"),[W,G]=N.useState([]),[X,te]=N.useState([]),[ne,me]=N.useState(!1),[ue,ce]=N.useState(!1),[ae,he]=N.useState([]),[xe,ve]=N.useState({total:0,dismissed:0});N.useEffect(()=>{ge()},[]);const ge=async()=>{const{data:rt,error:Ze}=await H.from("levelup_briefs").select("*").order("created_at",{ascending:!1});Ze?(ie.error("Failed to fetch briefs"),console.error(Ze)):n(rt||[]),a(!1)},be=()=>{g(""),x(""),b(""),A(""),P(""),M(!1),z(new Date().toISOString().slice(0,16)),V("once"),G([]),te([]),c(null)},Se=()=>{be(),l(!0)},Ie=async rt=>{c(rt),g(rt.title),x(rt.description||""),b(rt.video_url||""),A(rt.graphic_url||""),P(rt.graphic_link_url||""),M(rt.is_published),z(rt.publish_date.slice(0,16)),V(rt.show_frequency);const{data:Ze}=await H.from("levelup_brief_links").select("*").eq("brief_id",rt.id).order("sort_order");G((Ze==null?void 0:Ze.map(Bt=>({title:Bt.title,url:Bt.url})))||[]);const{data:ht}=await H.from("levelup_brief_polls").select("*").eq("brief_id",rt.id).order("sort_order");if(ht){const Bt=[];for(const Ct of ht){const{data:Yt}=await H.from("levelup_brief_poll_options").select("*").eq("poll_id",Ct.id).order("sort_order");Bt.push({question:Ct.question,poll_type:Ct.poll_type,options:(Yt==null?void 0:Yt.map(Kt=>Kt.option_text))||[]})}te(Bt)}l(!0)},Me=async rt=>{var ht;const Ze=(ht=rt.target.files)==null?void 0:ht[0];if(Ze){me(!0);try{const Bt=await H.functions.invoke("bunny-upload",{body:{action:"create",title:Ze.name.replace(/\.[^/.]+$/,"")}});if(Bt.error)throw Bt.error;const{videoId:Ct,libraryId:Yt}=Bt.data,Kt=await H.functions.invoke("bunny-upload",{body:{action:"upload-url",videoId:Ct}});if(Kt.error)throw Kt.error;const{uploadUrl:Xs,apiKey:zs}=Kt.data,Vt=new XMLHttpRequest;await new Promise((Os,Nt)=>{Vt.upload.addEventListener("progress",ms=>{if(ms.lengthComputable){const Ys=Math.round(ms.loaded/ms.total*100);console.log("Upload progress:",Ys)}}),Vt.addEventListener("load",()=>{Vt.status>=200&&Vt.status<300?Os():Nt(new Error(`Upload failed with status ${Vt.status}`))}),Vt.addEventListener("error",()=>Nt(new Error("Upload failed"))),Vt.open("PUT",Xs),Vt.setRequestHeader("AccessKey",zs),Vt.send(Ze)});const At=`https://player.mediadelivery.net/embed/${Yt}/${Ct}`;b(At),ie.success("Video uploaded successfully! It may take a few minutes to process.")}catch(Bt){console.error("Upload error:",Bt),ie.error("Failed to upload video")}finally{me(!1)}}},Re=async()=>{if(!f.trim()){ie.error("Title is required");return}try{let rt;if(o){const{error:Ze}=await H.from("levelup_briefs").update({title:f,description:y||null,video_url:_||null,graphic_url:k||null,graphic_link_url:T||null,is_published:I,publish_date:L,show_frequency:$}).eq("id",o.id);if(Ze)throw Ze;rt=o.id,await H.from("levelup_brief_links").delete().eq("brief_id",rt);const{data:ht}=await H.from("levelup_brief_polls").select("id").eq("brief_id",rt);if(ht)for(const Bt of ht)await H.from("levelup_brief_poll_options").delete().eq("poll_id",Bt.id);await H.from("levelup_brief_polls").delete().eq("brief_id",rt)}else{const{data:Ze,error:ht}=await H.from("levelup_briefs").insert({title:f,description:y||null,video_url:_||null,graphic_url:k||null,graphic_link_url:T||null,is_published:I,publish_date:L,show_frequency:$,created_by:s==null?void 0:s.id}).select().single();if(ht)throw ht;rt=Ze.id}if(W.length>0){const Ze=W.map((ht,Bt)=>({brief_id:rt,title:ht.title,url:ht.url,sort_order:Bt}));await H.from("levelup_brief_links").insert(Ze)}for(let Ze=0;Ze0){const Yt=ht.options.map((Kt,Xs)=>({poll_id:Bt.id,option_text:Kt,sort_order:Xs}));await H.from("levelup_brief_poll_options").insert(Yt)}}ie.success(o?"Brief updated":"Brief created"),l(!1),be(),ge()}catch(rt){console.error("Error saving brief:",rt),ie.error("Failed to save brief")}},Be=async rt=>{if(confirm("Are you sure you want to delete this brief?"))try{const{error:Ze}=await H.from("levelup_briefs").delete().eq("id",rt);if(Ze)throw Ze;ie.success("Brief deleted"),ge()}catch(Ze){console.error("Error deleting brief:",Ze),ie.error("Failed to delete brief")}},Ne=async rt=>{m(rt);const{count:Ze}=await H.from("levelup_brief_views").select("*",{count:"exact",head:!0}).eq("brief_id",rt.id),{count:ht}=await H.from("levelup_brief_views").select("*",{count:"exact",head:!0}).eq("brief_id",rt.id).not("dismissed_at","is",null);ve({total:Ze||0,dismissed:ht||0});const{data:Bt}=await H.from("levelup_brief_polls").select("*").eq("brief_id",rt.id).order("sort_order");if(Bt){const Ct=[];for(const Yt of Bt){const{data:Kt}=await H.from("levelup_brief_poll_options").select("*").eq("poll_id",Yt.id).order("sort_order"),{data:Xs}=await H.from("levelup_brief_poll_responses").select("option_id, user_id").eq("poll_id",Yt.id),zs=[...new Set((Xs==null?void 0:Xs.map(ms=>ms.user_id))||[])];let Vt={};if(zs.length>0){const{data:ms}=await H.from("profiles").select("id, name, email").in("id",zs);ms&&ms.forEach(Ys=>{Vt[Ys.id]=Ys.name||Ys.email||"Unknown"})}const At=(Xs||[]).map(ms=>({optionId:ms.option_id,userName:Vt[ms.user_id]||"Unknown",userId:ms.user_id})),Os={};let Nt=0;Kt&&Kt.forEach(ms=>{const Ys=(Xs==null?void 0:Xs.filter(It=>It.option_id===ms.id).length)||0;Os[ms.id]=Ys,Nt+=Ys}),Ct.push({...Yt,options:Kt||[],results:Os,respondents:At,totalResponses:Yt.poll_type==="single"?new Set(Xs==null?void 0:Xs.map(ms=>ms.user_id)).size:Nt})}he(Ct)}u(!0)},Ge=()=>{G([...W,{title:"",url:""}])},Ce=(rt,Ze,ht)=>{const Bt=[...W];Bt[rt][Ze]=ht,G(Bt)},Fe=rt=>{G(W.filter((Ze,ht)=>ht!==rt))},Ae=()=>{te([...X,{question:"",poll_type:"single",options:["",""]}])},Xe=(rt,Ze)=>{const ht=[...X];ht[rt].question=Ze,te(ht)},$e=(rt,Ze)=>{const ht=[...X];ht[rt].poll_type=Ze,te(ht)},Ye=rt=>{const Ze=[...X];Ze[rt].options.push(""),te(Ze)},Je=(rt,Ze,ht)=>{const Bt=[...X];Bt[rt].options[Ze]=ht,te(Bt)},Ke=(rt,Ze)=>{const ht=[...X];ht[rt].options=ht[rt].options.filter((Bt,Ct)=>Ct!==Ze),te(ht)},st=rt=>{te(X.filter((Ze,ht)=>ht!==rt))};return e.jsxs(Qs,{title:"The LevelUp Brief",children:[e.jsxs("div",{className:"space-y-6",children:[e.jsx(Uh,{title:"The LevelUp Brief",description:"Create engaging popup briefs for your agents",children:e.jsxs(B,{onClick:Se,children:[e.jsx(nn,{className:"h-4 w-4 mr-2"}),"Create Brief"]})}),e.jsx(_e,{children:e.jsx(De,{className:"p-0",children:e.jsxs(Oa,{children:[e.jsx(Fa,{children:e.jsxs(un,{children:[e.jsx(Mt,{children:"Title"}),e.jsx(Mt,{children:"Status"}),e.jsx(Mt,{children:"Frequency"}),e.jsx(Mt,{children:"Publish Date"}),e.jsx(Mt,{className:"text-right",children:"Actions"})]})}),e.jsx(za,{children:r?e.jsx(un,{children:e.jsx(gt,{colSpan:5,className:"text-center py-8",children:"Loading..."})}):t.length===0?e.jsx(un,{children:e.jsx(gt,{colSpan:5,className:"text-center py-8 text-muted-foreground",children:"No briefs created yet"})}):t.map(rt=>e.jsxs(un,{children:[e.jsx(gt,{className:"font-medium",children:rt.title}),e.jsx(gt,{children:e.jsx(We,{variant:rt.is_published?"default":"secondary",children:rt.is_published?"Published":"Draft"})}),e.jsx(gt,{className:"capitalize",children:rt.show_frequency.replace("_"," ")}),e.jsx(gt,{children:Js(new Date(rt.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:()=>Ne(rt),children:e.jsx(fl,{className:"h-4 w-4"})}),e.jsx(B,{variant:"ghost",size:"icon",onClick:()=>Ie(rt),children:e.jsx(xp,{className:"h-4 w-4"})}),e.jsx(B,{variant:"ghost",size:"icon",onClick:()=>Be(rt.id),children:e.jsx(qn,{className:"h-4 w-4 text-destructive"})})]})})]},rt.id))})]})})})]}),e.jsx(Bs,{open:i,onOpenChange:l,children:e.jsxs(Fs,{className:"max-w-3xl max-h-[90vh] overflow-y-auto",children:[e.jsx(qs,{children:e.jsx($s,{children:o?"Edit Brief":"Create New Brief"})}),e.jsxs(ya,{defaultValue:"content",className:"w-full",children:[e.jsxs(va,{className:"grid w-full grid-cols-4",children:[e.jsx(ls,{value:"content",children:"Content"}),e.jsx(ls,{value:"media",children:"Media"}),e.jsx(ls,{value:"links",children:"Links"}),e.jsx(ls,{value:"polls",children:"Polls"})]}),e.jsxs(_s,{value:"content",className:"space-y-4 mt-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{children:"Title *"}),e.jsx(we,{value:f,onChange:rt=>g(rt.target.value),placeholder:"What's happening at LevelUp..."})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{children:"Description"}),e.jsx(yN,{content:y,onChange:rt=>x(rt),placeholder:"Brief overview for agents...",minHeight:"120px"})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{children:"Publish Date"}),e.jsx(we,{type:"datetime-local",value:L,onChange:rt=>z(rt.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{children:"Show Frequency"}),e.jsxs(Ns,{value:$,onValueChange:V,children:[e.jsx(ws,{children:e.jsx(ks,{})}),e.jsxs(js,{children:[e.jsx(nt,{value:"once",children:"Once (until dismissed)"}),e.jsx(nt,{value:"every_login",children:"Every login"}),e.jsx(nt,{value:"daily",children:"Daily"})]})]})]})]}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(zn,{checked:I,onCheckedChange:M}),e.jsx(re,{children:"Publish immediately"})]})]}),e.jsxs(_s,{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(re,{children:"Upload Video to Bunny.net"}),e.jsx("div",{className:"flex gap-2",children:e.jsx(we,{type:"file",accept:"video/*",onChange:Me,disabled:ne})}),ne&&e.jsx("p",{className:"text-sm text-muted-foreground",children:"Uploading..."})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{children:"Or paste embed URL"}),e.jsx(we,{value:_,onChange:rt=>b(rt.target.value),placeholder:"https://iframe.mediadelivery.net/embed/..."})]}),_&&e.jsx("div",{className:"aspect-video rounded-lg overflow-hidden bg-muted",children:e.jsx("iframe",{src:_,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(re,{children:"Upload Image"}),e.jsx("div",{className:"flex gap-2",children:e.jsx(we,{type:"file",accept:"image/*",onChange:async rt=>{var ht;const Ze=(ht=rt.target.files)==null?void 0:ht[0];if(Ze){ce(!0);try{const Bt=Ze.name.split(".").pop(),Ct=`brief-graphics/${Date.now()}.${Bt}`,{error:Yt}=await H.storage.from("banner-images").upload(Ct,Ze,{upsert:!0});if(Yt)throw Yt;const{data:Kt}=H.storage.from("banner-images").getPublicUrl(Ct);A(Kt.publicUrl),ie.success("Image uploaded!")}catch(Bt){console.error(Bt),ie.error("Failed to upload image")}finally{ce(!1)}}},disabled:ue})}),ue&&e.jsx("p",{className:"text-sm text-muted-foreground",children:"Uploading..."})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{children:"Or paste Image URL"}),e.jsx(we,{value:k,onChange:rt=>A(rt.target.value),placeholder:"https://example.com/image.png"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{children:"Click-through Link (optional)"}),e.jsx(we,{value:T,onChange:rt=>P(rt.target.value),placeholder:"https://example.com/landing-page"})]}),k&&e.jsx("div",{className:"rounded-lg overflow-hidden bg-muted border",children:e.jsx("img",{src:k,alt:"Brief graphic preview",className:"w-full object-contain max-h-64"})})]})]}),e.jsxs(_s,{value:"links",className:"space-y-4 mt-4",children:[e.jsxs("div",{className:"flex justify-between items-center",children:[e.jsx(re,{children:"Quick Links"}),e.jsxs(B,{variant:"outline",size:"sm",onClick:Ge,children:[e.jsx(nn,{className:"h-4 w-4 mr-1"}),"Add Link"]})]}),W.map((rt,Ze)=>e.jsxs("div",{className:"flex gap-2 items-start",children:[e.jsx(we,{value:rt.title,onChange:ht=>Ce(Ze,"title",ht.target.value),placeholder:"Link title",className:"flex-1"}),e.jsx(we,{value:rt.url,onChange:ht=>Ce(Ze,"url",ht.target.value),placeholder:"https://...",className:"flex-[2]"}),e.jsx(B,{variant:"ghost",size:"icon",onClick:()=>Fe(Ze),children:e.jsx(qn,{className:"h-4 w-4 text-destructive"})})]},Ze)),W.length===0&&e.jsx("p",{className:"text-muted-foreground text-center py-4",children:"No links added yet"})]}),e.jsxs(_s,{value:"polls",className:"space-y-4 mt-4",children:[e.jsxs("div",{className:"flex justify-between items-center",children:[e.jsx(re,{children:"Polls"}),e.jsxs(B,{variant:"outline",size:"sm",onClick:Ae,children:[e.jsx(nn,{className:"h-4 w-4 mr-1"}),"Add Poll"]})]}),X.map((rt,Ze)=>e.jsx(_e,{className:"p-4",children:e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex justify-between items-center",children:[e.jsx(we,{value:rt.question,onChange:ht=>Xe(Ze,ht.target.value),placeholder:"Poll question...",className:"flex-1 mr-2"}),e.jsxs(Ns,{value:rt.poll_type,onValueChange:ht=>$e(Ze,ht),children:[e.jsx(ws,{className:"w-32",children:e.jsx(ks,{})}),e.jsxs(js,{children:[e.jsx(nt,{value:"single",children:"Single"}),e.jsx(nt,{value:"multi",children:"Multi-select"})]})]}),e.jsx(B,{variant:"ghost",size:"icon",onClick:()=>st(Ze),children:e.jsx(qn,{className:"h-4 w-4 text-destructive"})})]}),e.jsxs("div",{className:"space-y-2 pl-4",children:[rt.options.map((ht,Bt)=>e.jsxs("div",{className:"flex gap-2",children:[e.jsx(we,{value:ht,onChange:Ct=>Je(Ze,Bt,Ct.target.value),placeholder:`Option ${Bt+1}`}),rt.options.length>2&&e.jsx(B,{variant:"ghost",size:"icon",onClick:()=>Ke(Ze,Bt),children:e.jsx(qn,{className:"h-4 w-4 text-muted-foreground"})})]},Bt)),e.jsxs(B,{variant:"ghost",size:"sm",onClick:()=>Ye(Ze),children:[e.jsx(nn,{className:"h-4 w-4 mr-1"}),"Add Option"]})]})]})},Ze)),X.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:Re,children:o?"Update Brief":"Create Brief"})]})]})}),e.jsx(Bs,{open:d,onOpenChange:u,children:e.jsxs(Fs,{className:"max-w-2xl",children:[e.jsx(qs,{children:e.jsxs($s,{children:["Results: ",h==null?void 0:h.title]})}),e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs(_e,{children:[e.jsx(zt,{className:"pb-2",children:e.jsx(qt,{className:"text-sm font-medium text-muted-foreground",children:"Total Views"})}),e.jsx(De,{children:e.jsx("p",{className:"text-2xl font-bold",children:xe.total})})]}),e.jsxs(_e,{children:[e.jsx(zt,{className:"pb-2",children:e.jsx(qt,{className:"text-sm font-medium text-muted-foreground",children:"Dismissed"})}),e.jsx(De,{children:e.jsx("p",{className:"text-2xl font-bold",children:xe.dismissed})})]})]}),ae.length>0?e.jsxs("div",{className:"space-y-4",children:[e.jsx("h3",{className:"font-semibold",children:"Poll Results"}),ae.map(rt=>e.jsxs(_e,{className:"p-4",children:[e.jsx("h4",{className:"font-medium mb-3",children:rt.question}),e.jsx("div",{className:"space-y-2",children:rt.options.map(Ze=>{const ht=rt.results[Ze.id]||0,Bt=rt.totalResponses>0?Math.round(ht/rt.totalResponses*100):0;return e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:"flex justify-between text-sm",children:[e.jsx("span",{children:Ze.option_text}),e.jsxs("span",{className:"text-muted-foreground",children:[ht," (",Bt,"%)"]})]}),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:`${Bt}%`}})}),ht>0&&e.jsx("div",{className:"flex flex-wrap gap-1 pt-1",children:(rt.respondents||[]).filter(Ct=>Ct.optionId===Ze.id).map((Ct,Yt)=>e.jsx(We,{variant:"secondary",className:"text-xs font-normal",children:Ct.userName},Yt))})]},Ze.id)})})]},rt.id))]}):e.jsx("p",{className:"text-muted-foreground text-center py-4",children:"No polls in this brief"})]})]})})]})}const Ehn=()=>{const{user:s}=Ls(),{toast:t}=Ci(),n=as(),[r,a]=N.useState(!1),[i,l]=N.useState(null),[o,c]=N.useState({name:"",description:"",signup_link_url:"",publish_date:new Date().toISOString().split("T")[0],is_published:!1}),[d,u]=N.useState(null),[h,m]=N.useState(""),{data:f=[],isLoading:g}=mt({queryKey:["additional-services-admin"],queryFn:async()=>{const{data:T,error:P}=await H.from("additional_services").select("*").order("publish_date",{ascending:!1});if(P)throw P;return T}}),y=_t({mutationFn:async T=>{let P=T.existingImageUrl;if(T.image){const M=T.image.name.split(".").pop(),L=`${Date.now()}-${Math.random().toString(36).substring(7)}.${M}`,{error:z}=await H.storage.from("service-images").upload(L,T.image);if(z)throw z;const{data:$}=H.storage.from("service-images").getPublicUrl(L);P=$.publicUrl}const I={name:T.item.name,description:T.item.description||null,preview_image_url:P,signup_link_url:T.item.signup_link_url,publish_date:T.item.publish_date?new Date(T.item.publish_date).toISOString():new Date().toISOString(),is_published:T.item.is_published,created_by:s==null?void 0:s.id};if(T.itemId){const{error:M}=await H.from("additional_services").update(I).eq("id",T.itemId);if(M)throw M}else{const{error:M}=await H.from("additional_services").insert(I);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),_()},onError:T=>{t({title:"Error saving service",description:T.message,variant:"destructive"})}}),x=_t({mutationFn:async T=>{const{error:P}=await H.from("additional_services").delete().eq("id",T);if(P)throw P},onSuccess:()=>{n.invalidateQueries({queryKey:["additional-services-admin"]}),n.invalidateQueries({queryKey:["additional-services"]}),t({title:"Service deleted"})},onError:T=>{t({title:"Error deleting service",description:T.message,variant:"destructive"})}}),_=()=>{c({name:"",description:"",signup_link_url:"",publish_date:new Date().toISOString().split("T")[0],is_published:!1}),u(null),m(""),l(null)},b=T=>{l(T),c({name:T.name,description:T.description||"",signup_link_url:T.signup_link_url,publish_date:T.publish_date?new Date(T.publish_date).toISOString().split("T")[0]:new Date().toISOString().split("T")[0],is_published:T.is_published}),m(T.preview_image_url||""),a(!0)},k=T=>{var I;const P=(I=T.target.files)==null?void 0:I[0];P&&(u(P),m(URL.createObjectURL(P)))},A=T=>{if(T.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(Qs,{title:"Manage Additional Services",children:e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs(_e,{children:[e.jsx(zt,{className:"pb-2",children:e.jsx(qt,{className:"text-sm font-medium text-muted-foreground",children:"Total Services"})}),e.jsx(De,{children:e.jsx("div",{className:"text-2xl font-bold",children:f.length})})]}),e.jsxs(_e,{children:[e.jsx(zt,{className:"pb-2",children:e.jsx(qt,{className:"text-sm font-medium text-muted-foreground",children:"Published"})}),e.jsx(De,{children:e.jsx("div",{className:"text-2xl font-bold",children:f.filter(T=>T.is_published).length})})]})]}),e.jsxs(Bs,{open:r,onOpenChange:T=>{a(T),T||_()},children:[e.jsx(Ao,{asChild:!0,children:e.jsxs(B,{className:"gap-2",children:[e.jsx(nn,{className:"h-4 w-4"}),"Add Service"]})}),e.jsxs(Fs,{className:"max-w-2xl max-h-[90vh] overflow-y-auto",children:[e.jsx(qs,{children:e.jsx($s,{children:i?"Edit Service":"Add New Service"})}),e.jsxs("form",{onSubmit:A,className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{htmlFor:"name",children:"Name *"}),e.jsx(we,{id:"name",value:o.name,onChange:T=>c({...o,name:T.target.value}),placeholder:"Enter service name"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{children:"Description"}),e.jsx(yN,{content:o.description,onChange:T=>c({...o,description:T}),placeholder:"Enter description",minHeight:"120px"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{htmlFor:"signup_link_url",children:"Signup Link URL *"}),e.jsx(we,{id:"signup_link_url",type:"url",value:o.signup_link_url,onChange:T=>c({...o,signup_link_url:T.target.value}),placeholder:"https://example.com/signup"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{htmlFor:"publish_date",children:"Publish Date"}),e.jsx(we,{id:"publish_date",type:"date",value:o.publish_date,onChange:T=>c({...o,publish_date:T.target.value})})]}),e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(zn,{id:"is_published",checked:o.is_published,onCheckedChange:T=>c({...o,is_published:T})}),e.jsx(re,{htmlFor:"is_published",children:"Published"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{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(hr,{className:"h-3 w-3"})})]}):e.jsxs("div",{className:"border-2 border-dashed rounded-lg p-4 text-center",children:[e.jsx(pc,{className:"h-8 w-8 mx-auto text-muted-foreground mb-2"}),e.jsx(we,{type:"file",accept:"image/*",onChange:k,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(_e,{children:e.jsx(De,{className:"p-0",children:g?e.jsx("div",{className:"flex justify-center py-8",children:e.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})}):f.length===0?e.jsx("div",{className:"text-center py-8 text-muted-foreground",children:'No services yet. Click "Add Service" to create your first one.'}):e.jsxs(Oa,{children:[e.jsx(Fa,{children:e.jsxs(un,{children:[e.jsx(Mt,{className:"w-16",children:"Preview"}),e.jsx(Mt,{children:"Name"}),e.jsx(Mt,{children:"Signup Link"}),e.jsx(Mt,{children:"Publish Date"}),e.jsx(Mt,{children:"Status"}),e.jsx(Mt,{className:"text-right",children:"Actions"})]})}),e.jsx(za,{children:f.map(T=>e.jsxs(un,{children:[e.jsx(gt,{children:T.preview_image_url?e.jsx("img",{src:T.preview_image_url,alt:"",className:"w-12 h-12 object-cover rounded"}):e.jsx("div",{className:"w-12 h-12 bg-muted rounded flex items-center justify-center",children:e.jsx(pc,{className:"h-5 w-5 text-muted-foreground"})})}),e.jsx(gt,{className:"font-medium",children:T.name}),e.jsx(gt,{children:e.jsxs("a",{href:T.signup_link_url,target:"_blank",rel:"noopener noreferrer",className:"text-primary hover:underline flex items-center gap-1",children:[e.jsx(Tr,{className:"h-3 w-3"}),"Link"]})}),e.jsx(gt,{children:new Date(T.publish_date).toLocaleDateString()}),e.jsx(gt,{children:e.jsx(We,{variant:T.is_published?"default":"secondary",children:T.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(T),children:e.jsx(Ja,{className:"h-4 w-4"})}),e.jsx(B,{variant:"ghost",size:"icon",onClick:()=>{confirm("Are you sure you want to delete this service?")&&x.mutate(T.id)},children:e.jsx(qn,{className:"h-4 w-4 text-destructive"})})]})})]},T.id))})]})})})]})})};function Mhn(){const{toast:s}=Ci(),[t,n]=N.useState([]),[r,a]=N.useState(!0),[i,l]=N.useState(!1),[o,c]=N.useState(!1),[d,u]=N.useState({name:"",promotionCode:"",discountType:"percent",percentOff:"",amountOff:"",duration:"once",durationInMonths:""});N.useEffect(()=>{h()},[]);const h=async()=>{try{const{data:x,error:_}=await H.functions.invoke("stripe-manage-coupons",{body:{action:"list"}});if(_)throw _;n(x.coupons||[])}catch(x){console.error("Error fetching coupons:",x),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 x={action:"create",name:d.name,duration:d.duration,promotion_code:d.promotionCode.trim()||void 0};d.discountType==="percent"?x.percent_off=parseFloat(d.percentOff):(x.amount_off=Math.round(parseFloat(d.amountOff)*100),x.currency="usd"),d.duration==="repeating"&&(x.duration_in_months=parseInt(d.durationInMonths));const{data:_,error:b}=await H.functions.invoke("stripe-manage-coupons",{body:x});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(x){console.error("Error creating coupon:",x),s({title:"Error",description:x.message||"Failed to create coupon",variant:"destructive"})}finally{l(!1)}},f=async x=>{if(confirm("Are you sure you want to delete this coupon?"))try{const{error:_}=await H.functions.invoke("stripe-manage-coupons",{body:{action:"delete",couponId:x}});if(_)throw _;s({title:"Success",description:"Coupon deleted successfully"}),h()}catch(_){console.error("Error deleting coupon:",_),s({title:"Error",description:_.message||"Failed to delete coupon",variant:"destructive"})}},g=x=>x.percent_off?`${x.percent_off}% off`:x.amount_off?`$${(x.amount_off/100).toFixed(2)} off`:"N/A",y=x=>{switch(x.duration){case"once":return"Once";case"forever":return"Forever";case"repeating":return`${x.duration_in_months} months`;default:return x.duration}};return e.jsx(Qs,{title:"Subscription Discounts",children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(Uh,{title:"Subscription Discounts",description:"Create and manage discount coupons for subscriptions",children:e.jsxs(Bs,{open:o,onOpenChange:c,children:[e.jsx(Ao,{asChild:!0,children:e.jsxs(B,{children:[e.jsx(nn,{className:"mr-2 h-4 w-4"}),"Create Coupon"]})}),e.jsxs(Fs,{children:[e.jsxs(qs,{children:[e.jsx($s,{children:"Create New Coupon"}),e.jsx(Ar,{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(re,{children:"Promotion Code (what users will type)"}),e.jsx(we,{placeholder:"e.g., BROKERAGE50",value:d.promotionCode,onChange:x=>u({...d,promotionCode:x.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(re,{children:"Coupon Name (internal label)"}),e.jsx(we,{placeholder:"e.g., 50% Off Brokerage Launch",value:d.name,onChange:x=>u({...d,name:x.target.value})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{children:"Discount Type"}),e.jsxs(Ns,{value:d.discountType,onValueChange:x=>{const _=x==="amount"&&d.duration==="forever"?"once":d.duration;u({...d,discountType:x,duration:_})},children:[e.jsx(ws,{children:e.jsx(ks,{})}),e.jsxs(js,{children:[e.jsx(nt,{value:"percent",children:e.jsxs("span",{className:"flex items-center",children:[e.jsx(IT,{className:"mr-2 h-4 w-4"}),"Percentage Off"]})}),e.jsx(nt,{value:"amount",children:e.jsxs("span",{className:"flex items-center",children:[e.jsx(Ed,{className:"mr-2 h-4 w-4"}),"Fixed Amount Off"]})})]})]})]}),d.discountType==="percent"?e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{children:"Percent Off"}),e.jsxs("div",{className:"relative",children:[e.jsx(we,{type:"number",min:"1",max:"100",placeholder:"20",value:d.percentOff,onChange:x=>u({...d,percentOff:x.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(re,{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(we,{type:"number",min:"1",placeholder:"10.00",className:"pl-7",value:d.amountOff,onChange:x=>u({...d,amountOff:x.target.value})})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{children:"Duration"}),e.jsxs(Ns,{value:d.duration,onValueChange:x=>u({...d,duration:x}),children:[e.jsx(ws,{children:e.jsx(ks,{})}),e.jsxs(js,{children:[e.jsx(nt,{value:"once",children:"Once (first payment only)"}),e.jsx(nt,{value:"repeating",children:"Multiple months"}),e.jsxs(nt,{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(re,{children:"Number of Months"}),e.jsx(we,{type:"number",min:"1",placeholder:"3",value:d.durationInMonths,onChange:x=>u({...d,durationInMonths:x.target.value})})]}),e.jsx(B,{onClick:m,disabled:i,className:"w-full",children:i?e.jsxs(e.Fragment,{children:[e.jsx(us,{className:"mr-2 h-4 w-4 animate-spin"}),"Creating..."]}):"Create Coupon"})]})]})]})}),e.jsxs(_e,{children:[e.jsxs(zt,{children:[e.jsx(qt,{children:"Active Coupons"}),e.jsx(_r,{children:"Share coupon codes with users to give them discounts on subscriptions"})]}),e.jsx(De,{children:r?e.jsx("div",{className:"flex items-center justify-center py-8",children:e.jsx(us,{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(Oa,{children:[e.jsx(Fa,{children:e.jsxs(un,{children:[e.jsx(Mt,{children:"Promo Code"}),e.jsx(Mt,{children:"Name"}),e.jsx(Mt,{children:"Discount"}),e.jsx(Mt,{children:"Duration"}),e.jsx(Mt,{children:"Redemptions"}),e.jsx(Mt,{children:"Status"}),e.jsx(Mt,{className:"text-right",children:"Actions"})]})}),e.jsx(za,{children:t.map(x=>{var _;return e.jsxs(un,{children:[e.jsx(gt,{className:"font-mono font-medium",children:((_=x.promotion_codes)==null?void 0:_.length)>0?x.promotion_codes.join(", "):e.jsx("span",{className:"text-muted-foreground text-xs",children:"No promo code"})}),e.jsx(gt,{children:x.name||"-"}),e.jsx(gt,{children:g(x)}),e.jsx(gt,{children:y(x)}),e.jsx(gt,{children:x.times_redeemed}),e.jsx(gt,{children:e.jsx(We,{variant:x.valid?"default":"secondary",children:x.valid?"Active":"Inactive"})}),e.jsx(gt,{className:"text-right",children:e.jsx(B,{variant:"ghost",size:"sm",onClick:()=>f(x.id),children:e.jsx(qn,{className:"h-4 w-4 text-destructive"})})})]},x.id)})})]})})]}),e.jsxs(_e,{children:[e.jsx(zt,{children:e.jsx(qt,{children:"How to Use Coupons"})}),e.jsxs(De,{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 VLe={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 Lhn(){const[s,t]=N.useState(""),[n,r]=N.useState("all"),[a,i]=N.useState("all"),[l,o]=N.useState(null),{data:c,isLoading:d,refetch:u}=mt({queryKey:["admin-subscriptions"],queryFn:async()=>{const{data:_,error:b}=await H.from("profiles").select(` *, brokerages:brokerage_id (id, name) `).order("created_at",{ascending:!1});if(b)throw b;return _}}),{data:h}=mt({queryKey:["admin-brokerages-subscriptions"],queryFn:async()=>{const{data:_,error:b}=await H.from("brokerages").select("*").order("name");if(b)throw b;return await Promise.all((_||[]).map(async A=>{const{data:T}=await H.from("profiles").select("id, name, email, subscription_status, subscription_product_id").eq("brokerage_id",A.id),{data:P}=await H.from("user_roles").select("user_id").eq("role","brokerage_manager"),I=(P==null?void 0:P.map(z=>z.user_id))||[],M=(T==null?void 0:T.filter(z=>I.includes(z.id)))||[],L=(T==null?void 0:T.length)||0;return{...A,managers:M,agentCount:L}}))}}),{data:m}=mt({queryKey:["admin-website-subscriptions"],queryFn:async()=>{const{data:_,error:b}=await H.from("local_move_subscriptions").select("*").order("created_at",{ascending:!1});if(b)throw b;return _}}),f=_=>{if(_.is_grandfathered)return{status:"Grandfathered",badge:"Legacy",variant:"secondary"};if(_.brokerage_id&&!_.subscription_product_id)return{status:"Brokerage",badge:"Team Member",variant:"outline"};if(_.is_trial&&_.trial_expires_at)return new Date(_.trial_expires_at)>new Date?{status:"Trial",badge:"Active Trial",variant:"default"}:{status:"Trial Expired",badge:"Expired",variant:"destructive"};if(_.subscription_status==="active"||_.subscription_status==="trialing"){const b=VLe[_.subscription_product_id];return{status:(b==null?void 0:b.name)||"Active",badge:_.subscription_status==="trialing"?"Trial":"Active",variant:"default"}}return _.subscription_status==="canceled"||_.subscription_status==="past_due"?{status:"Canceled",badge:"Inactive",variant:"destructive"}:{status:"None",badge:"No Subscription",variant:"outline"}},g=c==null?void 0:c.filter(_=>{var k,A;if(!(((k=_.name)==null?void 0:k.toLowerCase().includes(s.toLowerCase()))||((A=_.email)==null?void 0:A.toLowerCase().includes(s.toLowerCase()))))return!1;if(a!=="all"){const T=_.subscription_source||"platform";if(a==="platform"&&T==="local_move_website"||a==="local_move_website"&&T!=="local_move_website")return!1}switch(f(_),n){case"active":return _.subscription_status==="active";case"trialing":return _.subscription_status==="trialing"||_.is_trial&&new Date(_.trial_expires_at)>new Date;case"grandfathered":return _.is_grandfathered;case"brokerage":return _.brokerage_id&&!_.subscription_product_id&&!_.is_grandfathered;case"expired":return _.subscription_status==="canceled"||_.subscription_status==="past_due"||_.is_trial&&new Date(_.trial_expires_at)<=new Date;case"none":return!_.subscription_status||_.subscription_status==="none";default:return!0}}),y={totalUsers:(c==null?void 0:c.length)||0,activeSubscriptions:(c==null?void 0:c.filter(_=>_.subscription_status==="active").length)||0,trials:(c==null?void 0:c.filter(_=>_.subscription_status==="trialing"||_.is_trial&&new Date(_.trial_expires_at)>new Date).length)||0,grandfathered:(c==null?void 0:c.filter(_=>_.is_grandfathered).length)||0,brokerageMembers:(c==null?void 0:c.filter(_=>_.brokerage_id&&!_.subscription_product_id&&!_.is_grandfathered).length)||0,individualSubscribers:(c==null?void 0:c.filter(_=>_.subscription_status==="active"&&_.subscription_product_id==="prod_Tc07cYplXUGNkm").length)||0,brokerageSubscribers:(c==null?void 0:c.filter(_=>_.subscription_status==="active"&&(_.subscription_product_id==="prod_Tc08MupgoVySDG"||_.subscription_product_id==="prod_Tc09N1tJ4RrAFn")).length)||0},x=_=>{window.open(`https://dashboard.stripe.com/customers/${_}`,"_blank")};return e.jsx(Qs,{title:"Subscription Management",children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(Uh,{title:"Subscription Management",description:"Track and manage all subscriptions",children:e.jsxs(B,{onClick:()=>u(),variant:"outline",size:"sm",children:[e.jsx(oo,{className:"h-4 w-4 mr-2"}),"Refresh"]})}),e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 lg:grid-cols-7 gap-4",children:[e.jsx(_e,{children:e.jsxs(De,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Yn,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{className:"text-sm text-muted-foreground",children:"Total Users"})]}),e.jsx("p",{className:"text-2xl font-bold mt-1",children:y.totalUsers})]})}),e.jsx(_e,{className:"border-green-500/50",children:e.jsxs(De,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(U0,{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(_e,{className:"border-blue-500/50",children:e.jsxs(De,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Xr,{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(_e,{className:"border-purple-500/50",children:e.jsxs(De,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(q0,{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(_e,{className:"border-orange-500/50",children:e.jsxs(De,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ti,{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(_e,{children:e.jsxs(De,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(tN,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{className:"text-sm text-muted-foreground",children:"Individual"})]}),e.jsx("p",{className:"text-2xl font-bold mt-1",children:y.individualSubscribers})]})}),e.jsx(_e,{children:e.jsxs(De,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ti,{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(ya,{defaultValue:"users",className:"space-y-4",children:[e.jsxs(va,{children:[e.jsx(ls,{value:"users",children:"All Users"}),e.jsx(ls,{value:"brokerages",children:"Brokerages"}),e.jsxs(ls,{value:"websites",className:"gap-2",children:[e.jsx(au,{className:"h-4 w-4"}),"Website Subscriptions",m&&m.length>0&&e.jsx(We,{variant:"secondary",className:"ml-1",children:m.length})]})]}),e.jsxs(_s,{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(Gr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(we,{placeholder:"Search by name or email...",value:s,onChange:_=>t(_.target.value),className:"pl-9"})]}),e.jsxs(Ns,{value:a,onValueChange:_=>i(_),children:[e.jsx(ws,{className:"w-[200px]",children:e.jsx(ks,{placeholder:"Source"})}),e.jsxs(js,{children:[e.jsx(nt,{value:"all",children:"All Sources"}),e.jsx(nt,{value:"platform",children:"Platform"}),e.jsx(nt,{value:"local_move_website",children:"Local Move Website"})]})]}),e.jsxs(Ns,{value:n,onValueChange:_=>r(_),children:[e.jsx(ws,{className:"w-[200px]",children:e.jsx(ks,{placeholder:"Filter by status"})}),e.jsxs(js,{children:[e.jsx(nt,{value:"all",children:"All Statuses"}),e.jsx(nt,{value:"active",children:"Active Subscriptions"}),e.jsx(nt,{value:"trialing",children:"Trials"}),e.jsx(nt,{value:"grandfathered",children:"Grandfathered"}),e.jsx(nt,{value:"brokerage",children:"Brokerage Members"}),e.jsx(nt,{value:"expired",children:"Expired/Canceled"}),e.jsx(nt,{value:"none",children:"No Subscription"})]})]})]}),e.jsx(_e,{children:e.jsx(De,{className:"p-0",children:e.jsxs(Oa,{children:[e.jsx(Fa,{children:e.jsxs(un,{children:[e.jsx(Mt,{children:"User"}),e.jsx(Mt,{children:"Status"}),e.jsx(Mt,{children:"Plan"}),e.jsx(Mt,{children:"Brokerage"}),e.jsx(Mt,{children:"End Date"}),e.jsx(Mt,{className:"text-right",children:"Actions"})]})}),e.jsx(za,{children:d?e.jsx(un,{children:e.jsx(gt,{colSpan:6,className:"text-center py-8",children:"Loading subscriptions..."})}):(g==null?void 0:g.length)===0?e.jsx(un,{children:e.jsx(gt,{colSpan:6,className:"text-center py-8 text-muted-foreground",children:"No users found"})}):g==null?void 0:g.map(_=>{var A,T;const b=f(_),k=VLe[_.subscription_product_id];return e.jsxs(un,{children:[e.jsx(gt,{children:e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:_.name}),e.jsx("p",{className:"text-sm text-muted-foreground",children:_.email})]})}),e.jsx(gt,{children:e.jsx(We,{variant:b.variant,children:b.badge})}),e.jsx(gt,{children:e.jsx("span",{className:"text-sm",children:_.is_grandfathered?"Legacy Access":_.brokerage_id&&!_.subscription_product_id?"Brokerage Subscription":(k==null?void 0:k.name)||b.status})}),e.jsx(gt,{children:(A=_.brokerages)!=null&&A.name?e.jsx("span",{className:"text-sm",children:_.brokerages.name}):e.jsx("span",{className:"text-sm text-muted-foreground",children:"—"})}),e.jsx(gt,{children:_.subscription_end_date?e.jsx("span",{className:"text-sm",children:Js(new Date(_.subscription_end_date),"MMM d, yyyy")}):_.trial_expires_at?e.jsxs("span",{className:"text-sm text-blue-600",children:["Trial: ",Js(new Date(_.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:[_.stripe_customer_id&&e.jsx(B,{variant:"ghost",size:"sm",onClick:()=>x(_.stripe_customer_id),children:e.jsx(Tr,{className:"h-4 w-4"})}),e.jsxs(Bs,{children:[e.jsx(Ao,{asChild:!0,children:e.jsx(B,{variant:"outline",size:"sm",onClick:()=>o(_),children:"Details"})}),e.jsxs(Fs,{children:[e.jsxs(qs,{children:[e.jsx($s,{children:"Subscription Details"}),e.jsxs(Ar,{children:[_.name," (",_.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(We,{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:_.is_grandfathered?"Grandfathered (Legacy)":_.brokerage_id&&!_.subscription_product_id?"Brokerage Subscription":(k==null?void 0:k.name)||"None"})]}),_.brokerage_id&&e.jsxs("div",{children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Brokerage"}),e.jsx("p",{className:"font-medium",children:((T=_.brokerages)==null?void 0:T.name)||"Unknown"})]}),_.subscription_end_date&&e.jsxs("div",{children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Current Period End"}),e.jsx("p",{className:"font-medium",children:Js(new Date(_.subscription_end_date),"MMMM d, yyyy")})]}),_.trial_expires_at&&e.jsxs("div",{children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Trial Expires"}),e.jsx("p",{className:"font-medium",children:Js(new Date(_.trial_expires_at),"MMMM d, yyyy")})]}),_.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:_.stripe_customer_id})]})]}),_.stripe_customer_id&&e.jsxs(B,{className:"w-full",onClick:()=>x(_.stripe_customer_id),children:[e.jsx(Tr,{className:"h-4 w-4 mr-2"}),"View in Stripe Dashboard"]})]})]})]})]})})]},_.id)})})]})})})]}),e.jsx(_s,{value:"brokerages",className:"space-y-4",children:e.jsx("div",{className:"grid gap-4",children:h==null?void 0:h.map(_=>{var k,A;const b=(k=_.managers)==null?void 0:k.some(T=>T.subscription_status==="active"&&(T.subscription_product_id==="prod_Tc08MupgoVySDG"||T.subscription_product_id==="prod_Tc09N1tJ4RrAFn"));return e.jsxs(_e,{children:[e.jsx(zt,{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(Ti,{className:"h-5 w-5 text-primary"})}),e.jsxs("div",{children:[e.jsx(qt,{className:"text-lg",children:_.name}),e.jsxs(_r,{children:[_.agentCount," agents"]})]})]}),e.jsx(We,{variant:b?"default":"outline",children:b?"Active Subscription":"No Active Subscription"})]})}),e.jsx(De,{children:((A=_.managers)==null?void 0:A.length)>0?e.jsxs("div",{className:"space-y-2",children:[e.jsx("p",{className:"text-sm font-medium text-muted-foreground",children:"Managers:"}),_.managers.map(T=>{const P=VLe[T.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:T.name}),e.jsx("p",{className:"text-sm text-muted-foreground",children:T.email})]}),e.jsx("div",{className:"text-right",children:P?e.jsxs("div",{children:[e.jsx(We,{variant:"default",children:P.name}),e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:P.price})]}):e.jsx(We,{variant:"outline",children:"No Subscription"})})]},T.id)})]}):e.jsx("p",{className:"text-sm text-muted-foreground",children:"No managers assigned"})})]},_.id)})})}),e.jsx(_s,{value:"websites",className:"space-y-4",children:e.jsxs(_e,{children:[e.jsxs(zt,{children:[e.jsxs(qt,{className:"flex items-center gap-2",children:[e.jsx(au,{className:"h-5 w-5 text-primary"}),"Local Move Website Subscriptions"]}),e.jsx(_r,{children:"$249 setup fee + $99/mo subscriptions from TheLocalMove.com agent websites"})]}),e.jsx(De,{className:"p-0",children:e.jsxs(Oa,{children:[e.jsx(Fa,{children:e.jsxs(un,{children:[e.jsx(Mt,{children:"Agent"}),e.jsx(Mt,{children:"Status"}),e.jsx(Mt,{children:"Setup Fee"}),e.jsx(Mt,{children:"Monthly"}),e.jsx(Mt,{children:"Next Renewal"}),e.jsx(Mt,{children:"Started"}),e.jsx(Mt,{className:"text-right",children:"Actions"})]})}),e.jsx(za,{children:m?m.length===0?e.jsx(un,{children:e.jsx(gt,{colSpan:7,className:"text-center py-8 text-muted-foreground",children:"No website subscriptions yet"})}):m.map(_=>e.jsxs(un,{children:[e.jsx(gt,{children:e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:_.agent_name||"—"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:_.agent_email})]})}),e.jsx(gt,{children:e.jsx(We,{variant:_.status==="active"?"default":_.status==="canceled"?"destructive":"outline",children:_.status})}),e.jsx(gt,{children:_.setup_fee_paid?e.jsxs(We,{variant:"secondary",children:["Paid · $",(_.setup_fee_amount_cents/100).toFixed(0)]}):e.jsx(We,{variant:"outline",children:"Unpaid"})}),e.jsxs(gt,{className:"font-medium",children:["$",(_.monthly_amount_cents/100).toFixed(0),"/mo"]}),e.jsx(gt,{children:_.current_period_end?e.jsx("span",{className:"text-sm",children:Js(new Date(_.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:Js(new Date(_.created_at),"MMM d, yyyy")})}),e.jsx(gt,{className:"text-right",children:_.stripe_customer_id&&e.jsx(B,{variant:"ghost",size:"sm",onClick:()=>x(_.stripe_customer_id),children:e.jsx(Tr,{className:"h-4 w-4"})})})]},_.id)):e.jsx(un,{children:e.jsx(gt,{colSpan:7,className:"text-center py-8",children:"Loading…"})})})]})})]})})]})]})})}function Phn(){const[s,t]=N.useState([]),[n,r]=N.useState(!0),[a,i]=N.useState(""),[l,o]=N.useState("all"),[c,d]=N.useState({total:0,qualified:0,pending:0,cancelled:0,totalDiscounts:0});N.useEffect(()=>{u()},[]);const u=async()=>{try{const{data:g,error:y}=await H.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(g||[]);const x=(g==null?void 0:g.filter(k=>k.status==="qualified").length)||0,_=(g==null?void 0:g.filter(k=>k.status==="pending").length)||0,b=(g==null?void 0:g.filter(k=>k.status==="cancelled").length)||0;d({total:(g==null?void 0:g.length)||0,qualified:x,pending:_,cancelled:b,totalDiscounts:x*25})}catch(g){console.error("Error fetching referrals:",g),ie.error("Failed to load referrals")}finally{r(!1)}},h=async()=>{try{ie.loading("Processing qualifications...");const{error:g}=await H.functions.invoke("process-referral-qualifications");if(g)throw g;ie.dismiss(),ie.success("Qualifications processed successfully"),u()}catch(g){ie.dismiss(),console.error("Error processing qualifications:",g),ie.error("Failed to process qualifications")}},m=s.filter(g=>{var _,b,k,A,T,P;const y=((b=(_=g.referrer_brokerage)==null?void 0:_.name)==null?void 0:b.toLowerCase().includes(a.toLowerCase()))||((A=(k=g.referred_brokerage)==null?void 0:k.name)==null?void 0:A.toLowerCase().includes(a.toLowerCase()))||((P=(T=g.referred_user)==null?void 0:T.email)==null?void 0:P.toLowerCase().includes(a.toLowerCase())),x=l==="all"||g.status===l;return y&&x}),f=g=>{switch(g){case"qualified":return e.jsxs(We,{className:"bg-green-100 text-green-800",children:[e.jsx(Po,{className:"h-3 w-3 mr-1"}),"Qualified"]});case"pending":return e.jsxs(We,{variant:"secondary",children:[e.jsx(Xr,{className:"h-3 w-3 mr-1"}),"Pending"]});case"cancelled":return e.jsxs(We,{variant:"destructive",children:[e.jsx(Nu,{className:"h-3 w-3 mr-1"}),"Cancelled"]});default:return e.jsx(We,{children:g})}};return e.jsx(Qs,{title:"Referral Program",children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(Uh,{title:"Referral Program",description:"Track and manage brokerage referrals",children:e.jsxs(B,{onClick:h,variant:"outline",children:[e.jsx(oo,{className:"h-4 w-4 mr-2"}),"Process Qualifications"]})}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-5 gap-4",children:[e.jsx(_e,{children:e.jsx(De,{className:"pt-6",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Yn,{className:"h-5 w-5 text-muted-foreground"}),e.jsxs("div",{children:[e.jsx("p",{className:"text-2xl font-bold",children:c.total}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Total Referrals"})]})]})})}),e.jsx(_e,{children:e.jsx(De,{className:"pt-6",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Po,{className:"h-5 w-5 text-green-600"}),e.jsxs("div",{children:[e.jsx("p",{className:"text-2xl font-bold",children:c.qualified}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Qualified"})]})]})})}),e.jsx(_e,{children:e.jsx(De,{className:"pt-6",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Xr,{className:"h-5 w-5 text-amber-600"}),e.jsxs("div",{children:[e.jsx("p",{className:"text-2xl font-bold",children:c.pending}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Pending"})]})]})})}),e.jsx(_e,{children:e.jsx(De,{className:"pt-6",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Nu,{className:"h-5 w-5 text-red-600"}),e.jsxs("div",{children:[e.jsx("p",{className:"text-2xl font-bold",children:c.cancelled}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Cancelled"})]})]})})}),e.jsx(_e,{children:e.jsx(De,{className:"pt-6",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ed,{className:"h-5 w-5 text-green-600"}),e.jsxs("div",{children:[e.jsxs("p",{className:"text-2xl font-bold",children:["$",c.totalDiscounts]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Monthly Discounts"})]})]})})})]}),e.jsxs(_e,{children:[e.jsxs(zt,{children:[e.jsx(qt,{children:"All Referrals"}),e.jsx(_r,{children:"View and manage all referral relationships"})]}),e.jsxs(De,{children:[e.jsxs("div",{className:"flex gap-4 mb-4",children:[e.jsxs("div",{className:"relative flex-1",children:[e.jsx(Gr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(we,{placeholder:"Search by brokerage or email...",value:a,onChange:g=>i(g.target.value),className:"pl-10"})]}),e.jsxs(Ns,{value:l,onValueChange:o,children:[e.jsx(ws,{className:"w-[180px]",children:e.jsx(ks,{placeholder:"Filter by status"})}),e.jsxs(js,{children:[e.jsx(nt,{value:"all",children:"All Statuses"}),e.jsx(nt,{value:"pending",children:"Pending"}),e.jsx(nt,{value:"qualified",children:"Qualified"}),e.jsx(nt,{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(Oa,{children:[e.jsx(Fa,{children:e.jsxs(un,{children:[e.jsx(Mt,{children:"Referrer"}),e.jsx(Mt,{children:"Referred"}),e.jsx(Mt,{children:"Signup Date"}),e.jsx(Mt,{children:"Status"}),e.jsx(Mt,{children:"Qualified Date"}),e.jsx(Mt,{children:"Discount"})]})}),e.jsx(za,{children:m.length===0?e.jsx(un,{children:e.jsx(gt,{colSpan:6,className:"text-center text-muted-foreground py-8",children:"No referrals found"})}):m.map(g=>{var y,x,_,b;return e.jsxs(un,{children:[e.jsx(gt,{className:"font-medium",children:((y=g.referrer_brokerage)==null?void 0:y.name)||"Unknown"}),e.jsx(gt,{children:e.jsxs("div",{children:[e.jsx("p",{children:((x=g.referred_brokerage)==null?void 0:x.name)||((_=g.referred_user)==null?void 0:_.name)||"Pending setup"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:(b=g.referred_user)==null?void 0:b.email})]})}),e.jsx(gt,{children:Js(new Date(g.signup_date),"MMM d, yyyy")}),e.jsx(gt,{children:f(g.status)}),e.jsx(gt,{children:g.qualified_date?Js(new Date(g.qualified_date),"MMM d, yyyy"):"-"}),e.jsx(gt,{children:g.discount_applied?e.jsx(We,{variant:"outline",className:"text-green-600",children:"$25/mo applied"}):e.jsx("span",{className:"text-muted-foreground",children:"-"})})]},g.id)})})]})]})]})]})})}const HLe=[{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"}],Ihn=[{value:"brokerage_manager",label:"Brokerage Manager"},{value:"agent",label:"Agent"}];function Dhn(){const[s,t]=N.useState([]),[n,r]=N.useState(!0),[a,i]=N.useState(!1),[l,o]=N.useState(null),[c,d]=N.useState({title:"",description:"",action_type:"view_template",target_role:"agent",is_active:!0});N.useEffect(()=>{u()},[]);const u=async()=>{try{const{data:b,error:k}=await H.from("onboarding_checklist_items").select("*").order("target_role").order("sort_order");if(k)throw k;t(b||[])}catch(b){console.error("Error fetching checklist items:",b),ie.error("Failed to load checklist items")}finally{r(!1)}},h=()=>{o(null),d({title:"",description:"",action_type:"view_template",target_role:"agent",is_active:!0}),i(!0)},m=b=>{o(b),d({title:b.title,description:b.description||"",action_type:b.action_type,target_role:b.target_role,is_active:b.is_active}),i(!0)},f=async()=>{if(!c.title.trim()){ie.error("Title is required");return}try{if(l){const{error:b}=await H.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;ie.success("Checklist item updated")}else{const b=s.filter(A=>A.target_role===c.target_role).reduce((A,T)=>Math.max(A,T.sort_order),-1),{error:k}=await H.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(k)throw k;ie.success("Checklist item created")}i(!1),u()}catch(b){console.error("Error saving checklist item:",b),ie.error("Failed to save checklist item")}},g=async b=>{if(confirm("Are you sure you want to delete this checklist item?"))try{const{error:k}=await H.from("onboarding_checklist_items").delete().eq("id",b);if(k)throw k;ie.success("Checklist item deleted"),u()}catch(k){console.error("Error deleting checklist item:",k),ie.error("Failed to delete checklist item")}},y=async b=>{try{const{error:k}=await H.from("onboarding_checklist_items").update({is_active:!b.is_active}).eq("id",b.id);if(k)throw k;ie.success(b.is_active?"Item deactivated":"Item activated"),u()}catch(k){console.error("Error toggling item:",k),ie.error("Failed to update item")}},x=s.filter(b=>b.target_role==="brokerage_manager"),_=s.filter(b=>b.target_role==="agent");return e.jsxs(Qs,{title:"Onboarding Checklist",children:[e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"text-2xl font-bold",children:"Onboarding Checklist"}),e.jsx("p",{className:"text-muted-foreground",children:"Manage checklist items shown to new users on their dashboard"})]}),e.jsxs(B,{onClick:h,className:"gap-2",children:[e.jsx(nn,{className:"h-4 w-4"}),"Add Item"]})]}),e.jsxs(_e,{children:[e.jsx(zt,{children:e.jsxs(qt,{className:"flex items-center gap-2",children:[e.jsx(We,{variant:"secondary",children:"Brokerage Manager"}),"Checklist Items"]})}),e.jsx(De,{children:x.length===0?e.jsx("p",{className:"text-muted-foreground text-center py-4",children:"No checklist items for brokerage managers"}):e.jsxs(Oa,{children:[e.jsx(Fa,{children:e.jsxs(un,{children:[e.jsx(Mt,{className:"w-12",children:"#"}),e.jsx(Mt,{children:"Title"}),e.jsx(Mt,{children:"Action Type"}),e.jsx(Mt,{children:"Status"}),e.jsx(Mt,{className:"text-right",children:"Actions"})]})}),e.jsx(za,{children:x.map((b,k)=>{var A;return e.jsxs(un,{children:[e.jsx(gt,{className:"text-muted-foreground",children:k+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(We,{variant:"outline",children:((A=HLe.find(T=>T.value===b.action_type))==null?void 0:A.label)||b.action_type})}),e.jsx(gt,{children:e.jsx(zn,{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(Ja,{className:"h-4 w-4"})}),e.jsx(B,{variant:"ghost",size:"icon",onClick:()=>g(b.id),children:e.jsx(qn,{className:"h-4 w-4 text-destructive"})})]})})]},b.id)})})]})})]}),e.jsxs(_e,{children:[e.jsx(zt,{children:e.jsxs(qt,{className:"flex items-center gap-2",children:[e.jsx(We,{variant:"secondary",children:"Agent"}),"Checklist Items"]})}),e.jsx(De,{children:_.length===0?e.jsx("p",{className:"text-muted-foreground text-center py-4",children:"No checklist items for agents"}):e.jsxs(Oa,{children:[e.jsx(Fa,{children:e.jsxs(un,{children:[e.jsx(Mt,{className:"w-12",children:"#"}),e.jsx(Mt,{children:"Title"}),e.jsx(Mt,{children:"Action Type"}),e.jsx(Mt,{children:"Status"}),e.jsx(Mt,{className:"text-right",children:"Actions"})]})}),e.jsx(za,{children:_.map((b,k)=>{var A;return e.jsxs(un,{children:[e.jsx(gt,{className:"text-muted-foreground",children:k+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(We,{variant:"outline",children:((A=HLe.find(T=>T.value===b.action_type))==null?void 0:A.label)||b.action_type})}),e.jsx(gt,{children:e.jsx(zn,{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(Ja,{className:"h-4 w-4"})}),e.jsx(B,{variant:"ghost",size:"icon",onClick:()=>g(b.id),children:e.jsx(qn,{className:"h-4 w-4 text-destructive"})})]})})]},b.id)})})]})})]})]}),e.jsx(Bs,{open:a,onOpenChange:i,children:e.jsxs(Fs,{children:[e.jsx(qs,{children:e.jsx($s,{children:l?"Edit Checklist Item":"Add Checklist Item"})}),e.jsxs("div",{className:"space-y-4 py-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{htmlFor:"title",children:"Title *"}),e.jsx(we,{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(re,{htmlFor:"description",children:"Description"}),e.jsx(Ws,{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(re,{children:"Target Role"}),e.jsxs(Ns,{value:c.target_role,onValueChange:b=>d({...c,target_role:b}),children:[e.jsx(ws,{children:e.jsx(ks,{})}),e.jsx(js,{children:Ihn.map(b=>e.jsx(nt,{value:b.value,children:b.label},b.value))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{children:"Action Type"}),e.jsxs(Ns,{value:c.action_type,onValueChange:b=>d({...c,action_type:b}),children:[e.jsx(ws,{children:e.jsx(ks,{})}),e.jsx(js,{children:HLe.map(b=>e.jsx(nt,{value:b.value,children:b.label},b.value))})]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(zn,{id:"is_active",checked:c.is_active,onCheckedChange:b=>d({...c,is_active:b})}),e.jsx(re,{htmlFor:"is_active",children:"Active"})]})]}),e.jsxs(Cr,{children:[e.jsx(B,{variant:"outline",onClick:()=>i(!1),children:"Cancel"}),e.jsx(B,{onClick:f,children:l?"Save Changes":"Create Item"})]})]})})]})}function Rhn(){const[s,t]=N.useState(""),[n,r]=N.useState("all"),[a,i]=N.useState("name"),[l,o]=N.useState("asc"),[c,d]=N.useState(""),[u,h]=N.useState(""),[m,f]=N.useState(""),[g,y]=N.useState(""),{data:x}=mt({queryKey:["admin-brokerages"],queryFn:async()=>{const{data:z,error:$}=await H.from("brokerages").select("id, name").order("name");if($)throw $;return z}}),_=async z=>{let V=[],W=0,G=!0;for(;G;){const{data:X,error:te}=await z(W,W+1e3-1);if(te)throw te;X&&X.length>0?(V=[...V,...X],W+=1e3,G=X.length===1e3):G=!1}return V},{data:b,isLoading:k}=mt({queryKey:["admin-agent-os-user-stats"],queryFn:async()=>{const z=await _((Ie,Me)=>H.from("profiles").select("id, name, email, brokerage_id, created_at").range(Ie,Me)),{data:$}=await H.from("brokerages").select("id, name"),V=new Map(($==null?void 0:$.map(Ie=>[Ie.id,Ie.name]))||[]),[{data:W},{data:G},{data:X},{data:te},{data:ne},{data:me},{data:ue}]=await Promise.all([H.rpc("get_admin_contact_counts"),H.rpc("get_admin_video_counts"),H.rpc("get_admin_popby_counts"),H.rpc("get_admin_listing_counts"),H.rpc("get_admin_deal_counts"),H.rpc("get_admin_portal_counts"),H.rpc("get_admin_sendable_card_counts")]),ce=new Map;W==null||W.forEach(Ie=>ce.set(Ie.owner_user_id,Ie.contact_count));const ae=new Map;G==null||G.forEach(Ie=>ae.set(Ie.owner_user_id,Ie.video_count));const he=new Map;X==null||X.forEach(Ie=>he.set(Ie.owner_user_id,Ie.popby_count));const xe=new Map;te==null||te.forEach(Ie=>xe.set(Ie.agent_id,Ie.listing_count));const ve=new Map;ne==null||ne.forEach(Ie=>ve.set(Ie.owner_user_id,Ie.deal_count));const ge=new Map;me==null||me.forEach(Ie=>ge.set(Ie.owner_user_id,{total:Ie.portal_count,active:Ie.active_portal_count}));const be=new Map;return ue==null||ue.forEach(Ie=>be.set(Ie.owner_user_id,{total:Ie.card_count,sent:Ie.sent_card_count,views:Ie.total_card_views})),z.map(Ie=>{const Me=ge.get(Ie.id),Re=be.get(Ie.id);return{id:Ie.id,name:Ie.name||"Unknown",email:Ie.email||"",brokerage_id:Ie.brokerage_id,brokerage_name:Ie.brokerage_id&&V.get(Ie.brokerage_id)||null,contact_count:ce.get(Ie.id)||0,video_count:ae.get(Ie.id)||0,popby_count:he.get(Ie.id)||0,listing_count:xe.get(Ie.id)||0,deal_count:ve.get(Ie.id)||0,portal_count:(Me==null?void 0:Me.total)||0,active_portal_count:(Me==null?void 0:Me.active)||0,card_count:(Re==null?void 0:Re.total)||0,sent_card_count:(Re==null?void 0:Re.sent)||0,total_card_views:(Re==null?void 0:Re.views)||0,created_at:Ie.created_at}})}}),A=N.useMemo(()=>{if(!b)return[];let z=b.filter($=>{const V=s.toLowerCase(),W=!s||$.name.toLowerCase().includes(V)||$.email.toLowerCase().includes(V),G=n==="all"||n==="none"&&!$.brokerage_id||$.brokerage_id===n,X=parseInt(c)||0,te=parseInt(u)||0,ne=parseInt(m)||0,me=parseInt(g)||0,ue=$.contact_count>=X&&$.video_count>=te&&$.popby_count>=ne&&$.listing_count>=me;return W&&G&&ue});return z.sort(($,V)=>{let W=0;return a==="name"?W=$.name.localeCompare(V.name):W=$[a]-V[a],l==="asc"?W:-W}),z},[b,s,n,a,l,c,u,m,g]),T=z=>{a===z?o(l==="asc"?"desc":"asc"):(i(z),o("desc"))},P=()=>{const z=["Name","Email","Brokerage","Contacts","Videos","Popbys","Listings","Deals","Portals (Active)","Cards Created","Cards Sent","Card Views"],$=A.map(te=>[te.name,te.email,te.brokerage_name||"None",te.contact_count,te.video_count,te.popby_count,te.listing_count,te.deal_count,`${te.portal_count} (${te.active_portal_count})`,te.card_count,te.sent_card_count,te.total_card_views]),V=[z.join(","),...$.map(te=>te.map(ne=>`"${ne}"`).join(","))].join(` `),W=new Blob([V],{type:"text/csv"}),G=URL.createObjectURL(W),X=document.createElement("a");X.href=G,X.download=`agent-os-user-stats-${new Date().toISOString().split("T")[0]}.csv`,X.click(),URL.revokeObjectURL(G)},I=N.useMemo(()=>A.length?A.reduce((z,$)=>({contacts:z.contacts+$.contact_count,videos:z.videos+$.video_count,popbys:z.popbys+$.popby_count,listings:z.listings+$.listing_count,deals:z.deals+$.deal_count,portals:z.portals+$.portal_count,activePortals:z.activePortals+$.active_portal_count,cards:z.cards+$.card_count,sentCards:z.sentCards+$.sent_card_count,cardViews:z.cardViews+$.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},[A]),M=N.useMemo(()=>A.length?{portals:A.filter(z=>z.portal_count>0).length,cards:A.filter(z=>z.card_count>0).length}:{portals:0,cards:0},[A]),L=({field:z,children:$})=>e.jsx(Mt,{className:"cursor-pointer hover:bg-muted/50 select-none",onClick:()=>T(z),children:e.jsxs("div",{className:"flex items-center gap-1",children:[$,e.jsx(mg,{className:`h-3 w-3 ${a===z?"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(_e,{className:"border-blue-500/20 bg-gradient-to-br from-blue-500/5 to-transparent",children:[e.jsx(zt,{className:"pb-2",children:e.jsxs(qt,{className:"text-sm font-medium flex items-center gap-2",children:[e.jsx(h5,{className:"h-4 w-4 text-blue-500"}),"Client Portals"]})}),e.jsx(De,{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:I.portals}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"Total Portals"})]}),e.jsxs("div",{children:[e.jsx("div",{className:"text-2xl font-bold text-emerald-600",children:I.activePortals}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"Active Portals"})]})]})})]}),e.jsxs(_e,{className:"border-violet-500/20 bg-gradient-to-br from-violet-500/5 to-transparent",children:[e.jsx(zt,{className:"pb-2",children:e.jsxs(qt,{className:"text-sm font-medium flex items-center gap-2",children:[e.jsx(mn,{className:"h-4 w-4 text-violet-500"}),"Card Studio"]})}),e.jsx(De,{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:I.cards}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"Cards Created"})]}),e.jsxs("div",{children:[e.jsx("div",{className:"text-2xl font-bold text-emerald-600",children:I.sentCards}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"Cards Sent"})]}),e.jsxs("div",{children:[e.jsx("div",{className:"text-2xl font-bold text-blue-600",children:I.cardViews}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"Total Views"})]})]})})]})]}),e.jsxs(_e,{children:[e.jsx(zt,{children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsxs(qt,{className:"flex items-center gap-2",children:[e.jsx(Yn,{className:"h-5 w-5"}),"User Activity Analytics"]}),e.jsx(_r,{children:"View all users and their Agent OS usage metrics"})]}),e.jsxs(B,{variant:"outline",size:"sm",onClick:P,children:[e.jsx(oi,{className:"h-4 w-4 mr-2"}),"Export CSV"]})]})}),e.jsxs(De,{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(Gr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(we,{placeholder:"Search by name or email...",value:s,onChange:z=>t(z.target.value),className:"pl-9"})]})}),e.jsx("div",{children:e.jsxs(Ns,{value:n,onValueChange:r,children:[e.jsxs(ws,{children:[e.jsx(Ti,{className:"h-4 w-4 mr-2 text-muted-foreground"}),e.jsx(ks,{placeholder:"Brokerage"})]}),e.jsxs(js,{children:[e.jsx(nt,{value:"all",children:"All Brokerages"}),e.jsx(nt,{value:"none",children:"No Brokerage"}),x==null?void 0:x.map(z=>e.jsx(nt,{value:z.id,children:z.name},z.id))]})]})}),e.jsx("div",{children:e.jsx(we,{type:"number",placeholder:"Min contacts",value:c,onChange:z=>d(z.target.value),min:"0"})}),e.jsx("div",{children:e.jsx(we,{type:"number",placeholder:"Min videos",value:u,onChange:z=>h(z.target.value),min:"0"})}),e.jsx("div",{children:e.jsx(we,{type:"number",placeholder:"Min popbys",value:m,onChange:z=>f(z.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:A.length}),e.jsx("div",{className:"text-muted-foreground",children:"Users"})]}),e.jsxs("div",{className:"bg-muted/50 rounded-lg p-3 text-center",children:[e.jsx("div",{className:"text-2xl font-bold",children:I.contacts.toLocaleString()}),e.jsx("div",{className:"text-muted-foreground",children:"Contacts"})]}),e.jsxs("div",{className:"bg-muted/50 rounded-lg p-3 text-center",children:[e.jsx("div",{className:"text-2xl font-bold",children:I.videos.toLocaleString()}),e.jsx("div",{className:"text-muted-foreground",children:"Videos"})]}),e.jsxs("div",{className:"bg-muted/50 rounded-lg p-3 text-center",children:[e.jsx("div",{className:"text-2xl font-bold",children:I.popbys.toLocaleString()}),e.jsx("div",{className:"text-muted-foreground",children:"Popbys"})]}),e.jsxs("div",{className:"bg-muted/50 rounded-lg p-3 text-center",children:[e.jsx("div",{className:"text-2xl font-bold",children:I.listings.toLocaleString()}),e.jsx("div",{className:"text-muted-foreground",children:"Listings"})]}),e.jsxs("div",{className:"bg-muted/50 rounded-lg p-3 text-center",children:[e.jsx("div",{className:"text-2xl font-bold",children:I.deals.toLocaleString()}),e.jsx("div",{className:"text-muted-foreground",children:"Deals"})]}),e.jsxs("div",{className:"bg-blue-500/10 rounded-lg p-3 text-center",children:[e.jsx("div",{className:"text-2xl font-bold",children:I.portals.toLocaleString()}),e.jsx("div",{className:"text-muted-foreground",children:"Portals"})]}),e.jsxs("div",{className:"bg-violet-500/10 rounded-lg p-3 text-center",children:[e.jsx("div",{className:"text-2xl font-bold",children:I.cards.toLocaleString()}),e.jsx("div",{className:"text-muted-foreground",children:"Cards"})]})]}),k?e.jsx("div",{className:"flex justify-center py-12",children:e.jsx(us,{className:"h-8 w-8 animate-spin text-muted-foreground"})}):e.jsx("div",{className:"rounded-md border overflow-x-auto",children:e.jsxs(Oa,{children:[e.jsx(Fa,{children:e.jsxs(un,{children:[e.jsx(L,{field:"name",children:"Name"}),e.jsx(Mt,{children:"Email"}),e.jsx(Mt,{children:"Brokerage"}),e.jsx(L,{field:"contact_count",children:"Contacts"}),e.jsx(L,{field:"video_count",children:"Videos"}),e.jsx(L,{field:"popby_count",children:"Popbys"}),e.jsx(L,{field:"listing_count",children:"Listings"}),e.jsx(L,{field:"deal_count",children:"Deals"}),e.jsx(L,{field:"portal_count",children:e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(h5,{className:"h-3 w-3 text-blue-500"}),"Portals"]})}),e.jsx(L,{field:"card_count",children:e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(mn,{className:"h-3 w-3 text-violet-500"}),"Cards"]})})]})}),e.jsx(za,{children:A.length===0?e.jsx(un,{children:e.jsx(gt,{colSpan:10,className:"text-center py-8 text-muted-foreground",children:"No users found matching your filters"})}):A.map(z=>e.jsxs(un,{children:[e.jsx(gt,{className:"font-medium",children:z.name}),e.jsx(gt,{className:"text-muted-foreground",children:z.email}),e.jsx(gt,{children:z.brokerage_name?e.jsx(We,{variant:"secondary",children:z.brokerage_name}):e.jsx("span",{className:"text-muted-foreground",children:"—"})}),e.jsx(gt,{children:e.jsx(We,{variant:z.contact_count>0?"default":"outline",children:z.contact_count})}),e.jsx(gt,{children:e.jsx(We,{variant:z.video_count>0?"default":"outline",children:z.video_count})}),e.jsx(gt,{children:e.jsx(We,{variant:z.popby_count>0?"default":"outline",children:z.popby_count})}),e.jsx(gt,{children:e.jsx(We,{variant:z.listing_count>0?"default":"outline",children:z.listing_count})}),e.jsx(gt,{children:e.jsx(We,{variant:z.deal_count>0?"default":"outline",children:z.deal_count})}),e.jsx(gt,{children:z.portal_count>0?e.jsxs(wu,{children:[e.jsx(ju,{children:e.jsxs(We,{variant:"default",className:"bg-blue-600 hover:bg-blue-700",children:[z.portal_count,z.active_portal_count>0&&e.jsxs("span",{className:"ml-1 opacity-75",children:["(",z.active_portal_count," active)"]})]})}),e.jsxs(nu,{children:[e.jsxs("p",{children:[z.portal_count," total portals"]}),e.jsxs("p",{children:[z.active_portal_count," currently active"]})]})]}):e.jsx(We,{variant:"outline",children:"0"})}),e.jsx(gt,{children:z.card_count>0?e.jsxs(wu,{children:[e.jsx(ju,{children:e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(We,{variant:"default",className:"bg-violet-600 hover:bg-violet-700",children:z.card_count}),z.sent_card_count>0&&e.jsxs("span",{className:"flex items-center gap-0.5 text-xs text-emerald-600",children:[e.jsx(Rr,{className:"h-3 w-3"}),z.sent_card_count]}),z.total_card_views>0&&e.jsxs("span",{className:"flex items-center gap-0.5 text-xs text-muted-foreground",children:[e.jsx(da,{className:"h-3 w-3"}),z.total_card_views]})]})}),e.jsxs(nu,{children:[e.jsxs("p",{children:[z.card_count," cards created"]}),e.jsxs("p",{children:[z.sent_card_count," sent"]}),e.jsxs("p",{children:[z.total_card_views," total views"]})]})]}):e.jsx(We,{variant:"outline",children:"0"})})]},z.id))})]})})]})]})]})})}function Ohn(){Ci(),as();const[s,t]=N.useState("user-analytics"),{data:n}=mt({queryKey:["admin-feature-flags"],queryFn:async()=>{const{data:f,error:g}=await H.from("feature_flags").select("*").order("key");if(g)throw g;return f}}),{data:r,isLoading:a}=mt({queryKey:["admin-relationship-types"],queryFn:async()=>{const{data:f,error:g}=await H.from("relationship_types").select("*").order("sort_order");if(g)throw g;return f}}),{data:i,isLoading:l}=mt({queryKey:["admin-action-types"],queryFn:async()=>{const{data:f,error:g}=await H.from("action_types").select("*").order("sort_order");if(g)throw g;return f}}),{data:o,isLoading:c}=mt({queryKey:["admin-action-scripts"],queryFn:async()=>{const{data:f,error:g}=await H.from("action_scripts").select("*, action_type:action_types(*)");if(g)throw g;return f}}),{data:d,isLoading:u}=mt({queryKey:["admin-touchpoint-plans"],queryFn:async()=>{const{data:f,error:g}=await H.from("touchpoint_plans").select("*").order("name");if(g)throw g;return f}}),{data:h,isLoading:m}=mt({queryKey:["admin-popby-items"],queryFn:async()=>{const{data:f,error:g}=await H.from("popby_items").select("*").is("owner_user_id",null).order("name");if(g)throw g;return f}});return e.jsx(Qs,{title:"Agent OS Control Center",children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(Uh,{title:"Agent OS Control Center",description:"Manage InnerCircle settings, scripts, and touchpoint plans"}),e.jsxs(ya,{value:s,onValueChange:t,children:[e.jsxs(va,{className:"grid w-full grid-cols-9",children:[e.jsxs(ls,{value:"user-analytics",className:"gap-2",children:[e.jsx(fl,{className:"h-4 w-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Users"})]}),e.jsxs(ls,{value:"relationship-types",className:"gap-2",children:[e.jsx(Yn,{className:"h-4 w-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Relationships"})]}),e.jsxs(ls,{value:"action-types",className:"gap-2",children:[e.jsx(ga,{className:"h-4 w-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Actions"})]}),e.jsxs(ls,{value:"scripts",className:"gap-2",children:[e.jsx(Wr,{className:"h-4 w-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Scripts"})]}),e.jsxs(ls,{value:"video-scripts",className:"gap-2",children:[e.jsx(Rh,{className:"h-4 w-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Video Scripts"})]}),e.jsxs(ls,{value:"plans",className:"gap-2",children:[e.jsx(ta,{className:"h-4 w-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Plans"})]}),e.jsxs(ls,{value:"popbys",className:"gap-2",children:[e.jsx(Io,{className:"h-4 w-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Popbys"})]}),e.jsxs(ls,{value:"settings",className:"gap-2",children:[e.jsx(sc,{className:"h-4 w-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Settings"})]}),e.jsxs(ls,{value:"feature-flags",className:"gap-2",children:[e.jsx(s3,{className:"h-4 w-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Flags"})]})]}),e.jsx(_s,{value:"user-analytics",className:"mt-6",children:e.jsx(Rhn,{})}),e.jsx(_s,{value:"relationship-types",className:"mt-6",children:e.jsx(Fhn,{types:r||[],isLoading:a})}),e.jsx(_s,{value:"action-types",className:"mt-6",children:e.jsx(zhn,{types:i||[],isLoading:l})}),e.jsx(_s,{value:"scripts",className:"mt-6",children:e.jsx(Bhn,{scripts:o||[],actionTypes:i||[],isLoading:c})}),e.jsx(_s,{value:"video-scripts",className:"mt-6",children:e.jsx(Vhn,{})}),e.jsx(_s,{value:"plans",className:"mt-6",children:e.jsx($hn,{plans:d||[],actionTypes:i||[],scripts:o||[],isLoading:u})}),e.jsx(_s,{value:"popbys",className:"mt-6",children:e.jsx(qhn,{items:h||[],isLoading:m})}),e.jsx(_s,{value:"settings",className:"mt-6",children:e.jsx(Hhn,{})}),e.jsx(_s,{value:"feature-flags",className:"mt-6",children:e.jsx(Uhn,{flags:n||[]})})]})]})})}function Fhn({types:s,isLoading:t}){const{toast:n}=Ci(),r=as(),[a,i]=N.useState(null),[l,o]=N.useState(!1),c=_t({mutationFn:async u=>{if(u.id){const{error:h}=await H.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 H.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 H.from("relationship_types").update({active:!u.active}).eq("id",u.id),r.invalidateQueries({queryKey:["admin-relationship-types"]})};return e.jsxs(_e,{children:[e.jsxs(zt,{className:"flex flex-row items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(qt,{children:"Relationship Types"}),e.jsx(_r,{children:"Define the relationship categories for InnerCircle contacts"})]}),e.jsxs(B,{onClick:()=>{i(null),o(!0)},children:[e.jsx(nn,{className:"h-4 w-4 mr-2"}),"Add Type"]})]}),e.jsx(De,{children:t?e.jsx("div",{className:"flex justify-center py-8",children:e.jsx(us,{className:"h-8 w-8 animate-spin text-muted-foreground"})}):e.jsxs(Oa,{children:[e.jsx(Fa,{children:e.jsxs(un,{children:[e.jsx(Mt,{className:"w-12"}),e.jsx(Mt,{children:"Name"}),e.jsx(Mt,{children:"Description"}),e.jsx(Mt,{children:"Status"}),e.jsx(Mt,{className:"w-24",children:"Actions"})]})}),e.jsx(za,{children:s.map(u=>e.jsxs(un,{children:[e.jsx(gt,{children:e.jsx(Mp,{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(zn,{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(Ja,{className:"h-4 w-4"})})})]},u.id))})]})}),e.jsx(Bs,{open:l,onOpenChange:o,children:e.jsxs(Fs,{children:[e.jsx(qs,{children:e.jsxs($s,{children:[a?"Edit":"Add"," Relationship Type"]})}),e.jsxs("form",{onSubmit:u=>{u.preventDefault();const h=new FormData(u.currentTarget);c.mutate({id:a==null?void 0:a.id,name:h.get("name"),description:h.get("description"),icon:h.get("icon")})},children:[e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(re,{htmlFor:"name",children:"Name"}),e.jsx(we,{id:"name",name:"name",defaultValue:a==null?void 0:a.name,required:!0})]}),e.jsxs("div",{children:[e.jsx(re,{htmlFor:"description",children:"Description"}),e.jsx(Ws,{id:"description",name:"description",defaultValue:(a==null?void 0:a.description)||""})]}),e.jsxs("div",{children:[e.jsx(re,{htmlFor:"icon",children:"Icon"}),e.jsx(we,{id:"icon",name:"icon",defaultValue:(a==null?void 0:a.icon)||"",placeholder:"e.g., star, heart, user"})]})]}),e.jsxs(Cr,{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(us,{className:"h-4 w-4 mr-2 animate-spin"}),"Save"]})]})]})]})})]})}function zhn({types:s,isLoading:t}){const{toast:n}=Ci(),r=as(),[a,i]=N.useState(null),[l,o]=N.useState(!1),c=_t({mutationFn:async u=>{if(u.id){const{error:h}=await H.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 H.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 H.from("action_types").update({active:!u.active}).eq("id",u.id),r.invalidateQueries({queryKey:["admin-action-types"]})};return e.jsxs(_e,{children:[e.jsxs(zt,{className:"flex flex-row items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(qt,{children:"Action Types"}),e.jsx(_r,{children:"Define the types of touchpoint actions agents can take"})]}),e.jsxs(B,{onClick:()=>{i(null),o(!0)},children:[e.jsx(nn,{className:"h-4 w-4 mr-2"}),"Add Action"]})]}),e.jsx(De,{children:t?e.jsx("div",{className:"flex justify-center py-8",children:e.jsx(us,{className:"h-8 w-8 animate-spin text-muted-foreground"})}):e.jsxs(Oa,{children:[e.jsx(Fa,{children:e.jsxs(un,{children:[e.jsx(Mt,{children:"Name"}),e.jsx(Mt,{children:"Description"}),e.jsx(Mt,{children:"Color"}),e.jsx(Mt,{children:"Status"}),e.jsx(Mt,{className:"w-24",children:"Actions"})]})}),e.jsx(za,{children:s.map(u=>e.jsxs(un,{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(zn,{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(Ja,{className:"h-4 w-4"})})})]},u.id))})]})}),e.jsx(Bs,{open:l,onOpenChange:o,children:e.jsxs(Fs,{children:[e.jsx(qs,{children:e.jsxs($s,{children:[a?"Edit":"Add"," Action Type"]})}),e.jsxs("form",{onSubmit:u=>{u.preventDefault();const h=new FormData(u.currentTarget);c.mutate({id:a==null?void 0:a.id,name:h.get("name"),description:h.get("description"),icon:h.get("icon"),color:h.get("color")})},children:[e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(re,{htmlFor:"name",children:"Name"}),e.jsx(we,{id:"name",name:"name",defaultValue:a==null?void 0:a.name,required:!0})]}),e.jsxs("div",{children:[e.jsx(re,{htmlFor:"description",children:"Description"}),e.jsx(Ws,{id:"description",name:"description",defaultValue:(a==null?void 0:a.description)||""})]}),e.jsxs("div",{children:[e.jsx(re,{htmlFor:"icon",children:"Icon"}),e.jsx(we,{id:"icon",name:"icon",defaultValue:(a==null?void 0:a.icon)||"",placeholder:"e.g., phone, message"})]}),e.jsxs("div",{children:[e.jsx(re,{htmlFor:"color",children:"Color"}),e.jsx(we,{id:"color",name:"color",type:"color",defaultValue:(a==null?void 0:a.color)||"#6366f1"})]})]}),e.jsxs(Cr,{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(us,{className:"h-4 w-4 mr-2 animate-spin"}),"Save"]})]})]})]})})]})}function Bhn({scripts:s,actionTypes:t,isLoading:n}){const{toast:r}=Ci(),a=as(),[i,l]=N.useState(null),[o,c]=N.useState(!1),d=_t({mutationFn:async h=>{if(h.id){const{error:m}=await H.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 H.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=_t({mutationFn:async h=>{const{error:m}=await H.from("action_scripts").delete().eq("id",h);if(m)throw m},onSuccess:()=>{a.invalidateQueries({queryKey:["admin-action-scripts"]}),r({title:"Deleted successfully"})}});return e.jsxs(_e,{children:[e.jsxs(zt,{className:"flex flex-row items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(qt,{children:"Script Library"}),e.jsx(_r,{children:"Create and manage scripts for each action type"})]}),e.jsxs(B,{onClick:()=>{l(null),c(!0)},children:[e.jsx(nn,{className:"h-4 w-4 mr-2"}),"Add Script"]})]}),e.jsx(De,{children:n?e.jsx("div",{className:"flex justify-center py-8",children:e.jsx(us,{className:"h-8 w-8 animate-spin text-muted-foreground"})}):e.jsxs(Oa,{children:[e.jsx(Fa,{children:e.jsxs(un,{children:[e.jsx(Mt,{children:"Title"}),e.jsx(Mt,{children:"Action Type"}),e.jsx(Mt,{children:"Tone"}),e.jsx(Mt,{children:"Status"}),e.jsx(Mt,{className:"w-24",children:"Actions"})]})}),e.jsx(za,{children:s.map(h=>{var m;return e.jsxs(un,{children:[e.jsx(gt,{className:"font-medium",children:h.title}),e.jsx(gt,{children:e.jsx(We,{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(We,{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(Ja,{className:"h-4 w-4"})}),e.jsx(B,{variant:"ghost",size:"icon",onClick:()=>u.mutate(h.id),children:e.jsx(qn,{className:"h-4 w-4 text-destructive"})})]})]},h.id)})})]})}),e.jsx(Bs,{open:o,onOpenChange:c,children:e.jsxs(Fs,{className:"max-w-2xl",children:[e.jsx(qs,{children:e.jsxs($s,{children:[i?"Edit":"Add"," Script"]})}),e.jsxs("form",{onSubmit:h=>{h.preventDefault();const m=new FormData(h.currentTarget);d.mutate({id:i==null?void 0:i.id,title:m.get("title"),action_type_id:m.get("action_type_id"),tone:m.get("tone"),script_body:m.get("script_body"),active:!0})},children:[e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx(re,{htmlFor:"title",children:"Title"}),e.jsx(we,{id:"title",name:"title",defaultValue:i==null?void 0:i.title,required:!0})]}),e.jsxs("div",{children:[e.jsx(re,{htmlFor:"action_type_id",children:"Action Type"}),e.jsxs(Ns,{name:"action_type_id",defaultValue:i==null?void 0:i.action_type_id,children:[e.jsx(ws,{children:e.jsx(ks,{placeholder:"Select action type"})}),e.jsx(js,{children:t.map(h=>e.jsx(nt,{value:h.id,children:h.name},h.id))})]})]})]}),e.jsxs("div",{children:[e.jsx(re,{htmlFor:"tone",children:"Tone (optional)"}),e.jsx(we,{id:"tone",name:"tone",defaultValue:(i==null?void 0:i.tone)||"",placeholder:"e.g., Friendly, Professional, Casual"})]}),e.jsxs("div",{children:[e.jsx(re,{htmlFor:"script_body",children:"Script Body"}),e.jsx(Ws,{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(Cr,{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(us,{className:"h-4 w-4 mr-2 animate-spin"}),"Save"]})]})]})]})})]})}function $hn({plans:s,actionTypes:t,scripts:n,isLoading:r}){const{toast:a}=Ci(),i=as(),[l,o]=N.useState(null),[c,d]=N.useState(!1),[u,h]=N.useState(null),[m,f]=N.useState(!1),[g,y]=N.useState(null),[x,_]=N.useState(null),{data:b}=mt({queryKey:["plan-items",u],queryFn:async()=>{if(!u)return[];const{data:L,error:z}=await H.from("touchpoint_plan_items").select("*").eq("plan_id",u).order("month_number");if(z)throw z;return L},enabled:!!u}),k=_t({mutationFn:async L=>{if(L.id){const{error:z}=await H.from("touchpoint_plans").update({name:L.name,description:L.description,active:L.active}).eq("id",L.id);if(z)throw z}else{const{error:z}=await H.from("touchpoint_plans").insert([{name:L.name,description:L.description,active:!0}]);if(z)throw z}},onSuccess:()=>{i.invalidateQueries({queryKey:["admin-touchpoint-plans"]}),d(!1),o(null),a({title:"Saved successfully"})},onError:L=>{a({title:"Error",description:L.message,variant:"destructive"})}}),A=_t({mutationFn:async L=>{if(L.id){const{error:z}=await H.from("touchpoint_plan_items").update({action_type_id:L.action_type_id,default_script_id:L.default_script_id,notes:L.notes}).eq("id",L.id);if(z)throw z}else{const{error:z}=await H.from("touchpoint_plan_items").insert([{plan_id:L.plan_id,month_number:L.month_number,action_type_id:L.action_type_id,default_script_id:L.default_script_id,notes:L.notes}]);if(z)throw z}},onSuccess:()=>{i.invalidateQueries({queryKey:["plan-items",u]}),a({title:"Item saved"})}}),T=_t({mutationFn:async L=>{const{error:z}=await H.from("touchpoint_plan_items").delete().eq("id",L);if(z)throw z},onSuccess:()=>{i.invalidateQueries({queryKey:["plan-items",u]})}}),P=_t({mutationFn:async L=>{const{data:z,error:$}=await H.from("action_scripts").insert([{...L,active:!0}]).select().single();if($)throw $;return z},onSuccess:async L=>{i.invalidateQueries({queryKey:["admin-action-scripts"]}),g&&await A.mutateAsync({id:g.itemId,plan_id:u,month_number:g.month,action_type_id:g.actionTypeId,default_script_id:L.id}),f(!1),y(null),a({title:"Script created and assigned"})},onError:L=>{a({title:"Error",description:L.message,variant:"destructive"})}}),I=(L,z,$)=>{y({month:L,actionTypeId:z,itemId:$}),f(!0)},M=L=>n.find(z=>z.id===L);return e.jsxs("div",{className:"space-y-6",children:[e.jsxs(_e,{children:[e.jsxs(zt,{className:"flex flex-row items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(qt,{children:"Touchpoint Plans"}),e.jsx(_r,{children:"Create annual touchpoint plans that agents can apply to their contacts"})]}),e.jsxs(B,{onClick:()=>{o(null),d(!0)},children:[e.jsx(nn,{className:"h-4 w-4 mr-2"}),"Add Plan"]})]}),e.jsx(De,{children:r?e.jsx("div",{className:"flex justify-center py-8",children:e.jsx(us,{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(L=>e.jsxs(_e,{className:`cursor-pointer transition-colors ${u===L.id?"border-primary":""}`,onClick:()=>h(L.id),children:[e.jsx(zt,{className:"pb-2",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(qt,{className:"text-base",children:L.name}),e.jsx(B,{variant:"ghost",size:"icon",onClick:z=>{z.stopPropagation(),o(L),d(!0)},children:e.jsx(Ja,{className:"h-4 w-4"})})]})}),e.jsxs(De,{children:[e.jsx("p",{className:"text-sm text-muted-foreground line-clamp-2",children:L.description}),e.jsx(We,{variant:L.active?"default":"secondary",className:"mt-2",children:L.active?"Active":"Inactive"})]})]},L.id))})})]}),u&&e.jsxs(_e,{children:[e.jsxs(zt,{children:[e.jsx(qt,{children:"Plan Schedule"}),e.jsx(_r,{children:"Configure the monthly touchpoint schedule. Select an action type for each month, then assign or create a script."})]}),e.jsx(De,{children:e.jsx("div",{className:"grid gap-3",children:Array.from({length:12},(L,z)=>z+1).map(L=>{const z=b==null?void 0:b.find(W=>W.month_number===L),$=z!=null&&z.default_script_id?M(z.default_script_id):null,V=n.filter(W=>W.action_type_id===(z==null?void 0:z.action_type_id)&&W.active);return e.jsxs("div",{className:"p-4 border rounded-lg space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsxs("div",{className:"w-20 font-medium text-sm",children:["Month ",L]}),e.jsxs(Ns,{value:(z==null?void 0:z.action_type_id)||"none",onValueChange:W=>{W==="none"&&z?T.mutate(z.id):W!=="none"&&A.mutate({id:z==null?void 0:z.id,plan_id:u,month_number:L,action_type_id:W,default_script_id:null})},children:[e.jsx(ws,{className:"w-40",children:e.jsx(ks,{placeholder:"No action"})}),e.jsxs(js,{children:[e.jsx(nt,{value:"none",children:"No action"}),t.filter(W=>W.active).map(W=>e.jsx(nt,{value:W.id,children:e.jsxs("span",{className:"flex items-center gap-2",children:[W.color&&e.jsx("span",{className:"w-3 h-3 rounded-full",style:{backgroundColor:W.color}}),W.name]})},W.id))]})]}),z&&e.jsxs(e.Fragment,{children:[e.jsxs(Ns,{value:z.default_script_id||"none",onValueChange:W=>{_(null),A.mutate({id:z.id,default_script_id:W==="none"?null:W})},children:[e.jsx(ws,{className:"w-56",children:e.jsx(ks,{placeholder:"Select script"})}),e.jsxs(js,{children:[e.jsx(nt,{value:"none",children:"No default script"}),V.map(W=>e.jsxs(nt,{value:W.id,children:[W.title," ",W.tone&&`(${W.tone})`]},W.id))]})]}),e.jsxs(B,{variant:"outline",size:"sm",onClick:()=>I(L,z.action_type_id,z.id),children:[e.jsx(nn,{className:"h-3 w-3 mr-1"}),"New Script"]}),$&&e.jsx(B,{variant:"ghost",size:"sm",onClick:()=>_((x==null?void 0:x.id)===$.id?null:$),children:(x==null?void 0:x.id)===$.id?"Hide":"Preview"})]})]}),x&&(z==null?void 0:z.default_script_id)===x.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(We,{variant:"outline",children:x.title}),x.tone&&e.jsx(We,{variant:"secondary",children:x.tone})]}),e.jsx("p",{className:"text-muted-foreground whitespace-pre-wrap",children:x.script_body})]})]},L)})})})]}),e.jsx(Bs,{open:c,onOpenChange:d,children:e.jsxs(Fs,{children:[e.jsx(qs,{children:e.jsxs($s,{children:[l?"Edit":"Add"," Touchpoint Plan"]})}),e.jsxs("form",{onSubmit:L=>{L.preventDefault();const z=new FormData(L.currentTarget);k.mutate({id:l==null?void 0:l.id,name:z.get("name"),description:z.get("description"),active:!0})},children:[e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(re,{htmlFor:"name",children:"Name"}),e.jsx(we,{id:"name",name:"name",defaultValue:l==null?void 0:l.name,required:!0})]}),e.jsxs("div",{children:[e.jsx(re,{htmlFor:"description",children:"Description"}),e.jsx(Ws,{id:"description",name:"description",defaultValue:(l==null?void 0:l.description)||"",rows:3})]})]}),e.jsxs(Cr,{className:"mt-4",children:[e.jsx(B,{type:"button",variant:"outline",onClick:()=>d(!1),children:"Cancel"}),e.jsxs(B,{type:"submit",disabled:k.isPending,children:[k.isPending&&e.jsx(us,{className:"h-4 w-4 mr-2 animate-spin"}),"Save"]})]})]})]})}),e.jsx(Bs,{open:m,onOpenChange:f,children:e.jsxs(Fs,{className:"max-w-2xl",children:[e.jsxs(qs,{children:[e.jsx($s,{children:"Create New Script"}),e.jsxs(Ar,{children:["Create a script for Month ",g==null?void 0:g.month,". Use ","{{FirstName}}",", ","{{LastName}}",", and ","{{AgentName}}"," as placeholders."]})]}),e.jsxs("form",{onSubmit:L=>{L.preventDefault();const z=new FormData(L.currentTarget);P.mutate({title:z.get("title"),action_type_id:g.actionTypeId,tone:z.get("tone"),script_body:z.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(re,{htmlFor:"script_title",children:"Title"}),e.jsx(we,{id:"script_title",name:"title",placeholder:"e.g., Warm Check-In",required:!0})]}),e.jsxs("div",{children:[e.jsx(re,{htmlFor:"script_tone",children:"Tone"}),e.jsx(we,{id:"script_tone",name:"tone",placeholder:"e.g., Friendly, Professional"})]})]}),e.jsxs("div",{children:[e.jsx(re,{htmlFor:"script_body",children:"Script Body"}),e.jsx(Ws,{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(Cr,{className:"mt-4",children:[e.jsx(B,{type:"button",variant:"outline",onClick:()=>f(!1),children:"Cancel"}),e.jsxs(B,{type:"submit",disabled:P.isPending,children:[P.isPending&&e.jsx(us,{className:"h-4 w-4 mr-2 animate-spin"}),"Create & Assign"]})]})]})]})})]})}function Uhn({flags:s}){const{toast:t}=Ci(),n=as(),r=async(a,i)=>{const{error:l}=await H.from("feature_flags").update({...i,updated_at:new Date().toISOString()}).eq("id",a.id);l?t({title:"Error",description:l.message,variant:"destructive"}):(n.invalidateQueries({queryKey:["admin-feature-flags"]}),t({title:"Flag updated"}))};return e.jsxs(_e,{children:[e.jsxs(zt,{children:[e.jsx(qt,{children:"Feature Flags"}),e.jsx(_r,{children:"Control which features are enabled for members"})]}),e.jsx(De,{children:e.jsxs(Oa,{children:[e.jsx(Fa,{children:e.jsxs(un,{children:[e.jsx(Mt,{children:"Flag"}),e.jsx(Mt,{children:"Status"}),e.jsx(Mt,{children:"Notes"}),e.jsx(Mt,{children:"Last Updated"})]})}),e.jsx(za,{children:s.map(a=>e.jsxs(un,{children:[e.jsx(gt,{className:"font-mono text-sm",children:a.key}),e.jsx(gt,{children:e.jsx(zn,{checked:a.enabled,onCheckedChange:i=>r(a,{enabled:i})})}),e.jsx(gt,{children:e.jsx(we,{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 qhn({items:s,isLoading:t}){const{toast:n}=Ci(),r=as(),[a,i]=N.useState(null),[l,o]=N.useState(!1),c=_t({mutationFn:async h=>{if(h.id){const{error:m}=await H.from("popby_items").update({name:h.name,description:h.description}).eq("id",h.id);if(m)throw m}else{const{error:m}=await H.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 H.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 H.from("popby_items").delete().eq("id",h),r.invalidateQueries({queryKey:["admin-popby-items"]}),r.invalidateQueries({queryKey:["popby-items"]}),n({title:"Deleted successfully"})};return e.jsxs(_e,{children:[e.jsxs(zt,{className:"flex flex-row items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(qt,{children:"Popby Ideas"}),e.jsx(_r,{children:"Manage global popby ideas that all agents can see"})]}),e.jsxs(B,{onClick:()=>{i(null),o(!0)},children:[e.jsx(nn,{className:"h-4 w-4 mr-2"}),"Add Popby Idea"]})]}),e.jsx(De,{children:t?e.jsx("div",{className:"flex justify-center py-8",children:e.jsx(us,{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(Io,{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(Oa,{children:[e.jsx(Fa,{children:e.jsxs(un,{children:[e.jsx(Mt,{children:"Name"}),e.jsx(Mt,{children:"Description"}),e.jsx(Mt,{children:"Status"}),e.jsx(Mt,{className:"w-24",children:"Actions"})]})}),e.jsx(za,{children:s.map(h=>e.jsxs(un,{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(zn,{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(Ja,{className:"h-4 w-4"})}),e.jsx(B,{variant:"ghost",size:"icon",onClick:()=>u(h.id),children:e.jsx(qn,{className:"h-4 w-4 text-destructive"})})]})})]},h.id))})]})}),e.jsx(Bs,{open:l,onOpenChange:o,children:e.jsxs(Fs,{children:[e.jsx(qs,{children:e.jsxs($s,{children:[a?"Edit":"Add"," Popby Idea"]})}),e.jsxs("form",{onSubmit:h=>{h.preventDefault();const m=new FormData(h.currentTarget);c.mutate({id:a==null?void 0:a.id,name:m.get("name"),description:m.get("description")})},children:[e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(re,{htmlFor:"name",children:"Name"}),e.jsx(we,{id:"name",name:"name",defaultValue:a==null?void 0:a.name,required:!0,placeholder:"e.g., Homemade Cookies"})]}),e.jsxs("div",{children:[e.jsx(re,{htmlFor:"description",children:"Description"}),e.jsx(Ws,{id:"description",name:"description",defaultValue:(a==null?void 0:a.description)||"",placeholder:"Brief description of the popby idea..."})]})]}),e.jsxs(Cr,{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(us,{className:"h-4 w-4 mr-2 animate-spin"}),"Save"]})]})]})]})})]})}function Vhn(){var f;const{toast:s}=Ci(),t=as(),[n,r]=N.useState(null),[a,i]=N.useState(!1),{data:l,isLoading:o}=mt({queryKey:["admin-video-script-categories"],queryFn:async()=>{const{data:g,error:y}=await H.from("video_script_categories").select("*").order("sort_order");if(y)throw y;return g}}),{data:c,isLoading:d}=mt({queryKey:["admin-video-scripts"],queryFn:async()=>{const{data:g,error:y}=await H.from("video_scripts").select("*, category:video_script_categories(*)").order("title");if(y)throw y;return g}}),u=_t({mutationFn:async g=>{var y,x;if(g.id){const{error:_}=await H.from("video_scripts").update({title:g.title,script_text:g.script_text,category_id:g.category_id,tags:((y=g.tags)==null?void 0:y.split(",").map(b=>b.trim()).filter(Boolean))||[]}).eq("id",g.id);if(_)throw _}else{const{error:_}=await H.from("video_scripts").insert([{title:g.title,script_text:g.script_text,category_id:g.category_id||null,tags:((x=g.tags)==null?void 0:x.split(",").map(b=>b.trim()).filter(Boolean))||[]}]);if(_)throw _}},onSuccess:()=>{t.invalidateQueries({queryKey:["admin-video-scripts"]}),i(!1),r(null),s({title:"Video script saved!"})},onError:g=>s({title:"Error",description:g.message,variant:"destructive"})}),h=async g=>{await H.from("video_scripts").update({is_active:!g.is_active}).eq("id",g.id),t.invalidateQueries({queryKey:["admin-video-scripts"]})},m=async g=>{confirm("Delete this video script?")&&(await H.from("video_scripts").delete().eq("id",g),t.invalidateQueries({queryKey:["admin-video-scripts"]}),s({title:"Script deleted"}))};return e.jsxs(_e,{children:[e.jsxs(zt,{className:"flex flex-row items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(qt,{children:"Video Scripts"}),e.jsx(_r,{children:"Manage teleprompter scripts for Quick Video Touch"})]}),e.jsxs(B,{onClick:()=>{r(null),i(!0)},children:[e.jsx(nn,{className:"h-4 w-4 mr-2"}),"Add Script"]})]}),e.jsx(De,{children:d?e.jsx("div",{className:"flex justify-center py-8",children:e.jsx(us,{className:"h-8 w-8 animate-spin text-muted-foreground"})}):e.jsxs(Oa,{children:[e.jsx(Fa,{children:e.jsxs(un,{children:[e.jsx(Mt,{children:"Title"}),e.jsx(Mt,{children:"Category"}),e.jsx(Mt,{children:"Status"}),e.jsx(Mt,{className:"w-24",children:"Actions"})]})}),e.jsx(za,{children:c==null?void 0:c.map(g=>{var y;return e.jsxs(un,{children:[e.jsx(gt,{className:"font-medium",children:g.title}),e.jsx(gt,{className:"text-muted-foreground",children:((y=g.category)==null?void 0:y.name)||"Uncategorized"}),e.jsx(gt,{children:e.jsx(zn,{checked:g.is_active,onCheckedChange:()=>h(g)})}),e.jsxs(gt,{className:"flex gap-1",children:[e.jsx(B,{variant:"ghost",size:"icon",onClick:()=>{r(g),i(!0)},children:e.jsx(Ja,{className:"h-4 w-4"})}),e.jsx(B,{variant:"ghost",size:"icon",onClick:()=>m(g.id),children:e.jsx(qn,{className:"h-4 w-4"})})]})]},g.id)})})]})}),e.jsx(Bs,{open:a,onOpenChange:i,children:e.jsxs(Fs,{className:"max-w-2xl",children:[e.jsx(qs,{children:e.jsxs($s,{children:[n?"Edit":"Add"," Video Script"]})}),e.jsxs("form",{onSubmit:g=>{g.preventDefault();const y=new FormData(g.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(re,{htmlFor:"title",children:"Title"}),e.jsx(we,{id:"title",name:"title",defaultValue:n==null?void 0:n.title,required:!0})]}),e.jsxs("div",{children:[e.jsx(re,{htmlFor:"category_id",children:"Category"}),e.jsxs(Ns,{name:"category_id",defaultValue:(n==null?void 0:n.category_id)||"",children:[e.jsx(ws,{children:e.jsx(ks,{placeholder:"Select category"})}),e.jsx(js,{children:l==null?void 0:l.map(g=>e.jsx(nt,{value:g.id,children:g.name},g.id))})]})]}),e.jsxs("div",{children:[e.jsx(re,{htmlFor:"script_text",children:"Script Text"}),e.jsx(Ws,{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(re,{htmlFor:"tags",children:"Tags (comma-separated)"}),e.jsx(we,{id:"tags",name:"tags",defaultValue:((f=n==null?void 0:n.tags)==null?void 0:f.join(", "))||"",placeholder:"birthday, follow-up, thank-you"})]})]}),e.jsxs(Cr,{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(us,{className:"h-4 w-4 mr-2 animate-spin"}),"Save"]})]})]})]})})]})}function Hhn(){const{toast:s}=Ci(),[t,n]=N.useState(""),[r,a]=N.useState(!0),[i,l]=N.useState(!1);N.useEffect(()=>{(async()=>{a(!0);try{const{data:d}=await H.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 H.from("settings").upsert({key:"mapbox_public_token",value:t.trim()}),s({title:"Mapbox token saved!"})}catch{s({title:"Error saving token",variant:"destructive"})}l(!1)};return r?e.jsx(_e,{children:e.jsx(De,{className:"flex justify-center py-8",children:e.jsx(us,{className:"h-8 w-8 animate-spin text-muted-foreground"})})}):e.jsx("div",{className:"space-y-6",children:e.jsxs(_e,{children:[e.jsxs(zt,{children:[e.jsxs(qt,{className:"flex items-center gap-2",children:[e.jsx(ii,{className:"h-5 w-5"}),"Popby Map Settings"]}),e.jsx(_r,{children:"Configure the map feature for popbys"})]}),e.jsxs(De,{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{htmlFor:"mapbox-token",children:"Mapbox Public Token"}),e.jsx(we,{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(us,{className:"h-4 w-4 mr-2 animate-spin"}),"Save Token"]}),t&&e.jsx(We,{variant:"secondary",className:"ml-2",children:"Token configured"})]})]})})}const Ghn=()=>{const[s,t]=N.useState(""),[n,r]=N.useState("grid"),a=tr(),{data:i=[],isLoading:l}=mt({queryKey:["additional-services"],queryFn:async()=>{const{data:c,error:d}=await H.from("additional_services").select("*").eq("is_published",!0).order("publish_date",{ascending:!1});if(d)throw d;return c}}),o=i.filter(c=>{var u;return c.name.toLowerCase().includes(s.toLowerCase())||((u=c.description)==null?void 0:u.toLowerCase().includes(s.toLowerCase()))});return e.jsx(Qs,{title:"Additional Services",children:e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl font-bold text-foreground",children:"Additional Services"}),e.jsx("p",{className:"text-muted-foreground mt-1",children:"Explore our additional services and offerings"})]}),e.jsxs("div",{className:"flex flex-col sm:flex-row gap-4",children:[e.jsxs("div",{className:"relative flex-1 max-w-sm",children:[e.jsx(Gr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(we,{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(G0,{className:"h-4 w-4"})}),e.jsx(B,{variant:n==="list"?"secondary":"outline",size:"icon",onClick:()=>r("list"),className:"rounded-full",children:e.jsx(Kx,{className:"h-4 w-4"})})]})]})]}),e.jsxs("div",{className:"text-sm text-muted-foreground",children:[o.length," service",o.length!==1?"s":""," found"]}),l&&e.jsx("div",{className:n==="grid"?"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-6":"space-y-4",children:[...Array(4)].map((c,d)=>e.jsx(_e,{children:e.jsxs(De,{className:"p-4",children:[e.jsx(xn,{className:"aspect-[3/2] w-full rounded-lg mb-4"}),e.jsx(xn,{className:"h-5 w-3/4 mb-2"}),e.jsx(xn,{className:"h-4 w-full mb-4"})]})},d))}),!l&&o.length===0&&e.jsxs("div",{className:"text-center py-12",children:[e.jsx("div",{className:"text-muted-foreground mb-4",children:s?"No services match your search":"No additional services available yet"}),s&&e.jsx(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(_e,{className:`group overflow-hidden hover:shadow-lg transition-all duration-200 cursor-pointer ${n==="list"?"flex flex-row":""}`,onClick:()=>a(`/additional-services/${c.id}`),children:[e.jsx("div",{className:`relative overflow-hidden bg-muted ${n==="list"?"w-48 shrink-0":"aspect-[3/2]"}`,children:c.preview_image_url?e.jsx("img",{src:c.preview_image_url,alt:c.name,className:"w-full h-full object-contain group-hover:scale-105 transition-transform duration-300"}):e.jsx("div",{className:"w-full h-full flex items-center justify-center text-muted-foreground",children:e.jsx(Cn,{className:"h-8 w-8"})})}),e.jsxs(De,{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:eY(c.description)})]})]},c.id))})]})})},Whn=()=>{const{serviceId:s}=uo(),t=tr(),{data:n,isLoading:r}=mt({queryKey:["additional-service",s],queryFn:async()=>{const{data:a,error:i}=await H.from("additional_services").select("*").eq("id",s).eq("is_published",!0).single();if(i)throw i;return a},enabled:!!s});return r?e.jsx(Qs,{title:"Loading...",children:e.jsxs("div",{className:"max-w-4xl mx-auto space-y-6",children:[e.jsx(xn,{className:"h-8 w-48"}),e.jsx(xn,{className:"h-64 w-full rounded-lg"}),e.jsx(xn,{className:"h-24 w-full"})]})}):n?e.jsx(Qs,{title:n.name,children:e.jsxs("div",{className:"max-w-4xl mx-auto space-y-6",children:[e.jsxs(B,{variant:"ghost",onClick:()=>t("/additional-services"),className:"gap-2",children:[e.jsx(ka,{className:"h-4 w-4"}),"Back to Services"]}),e.jsx(_e,{className:"overflow-hidden",children:e.jsx("div",{className:"relative bg-muted",children:n.preview_image_url?e.jsx("img",{src:n.preview_image_url,alt:n.name,className:"w-full h-auto max-h-[500px] object-contain mx-auto"}):e.jsx("div",{className:"w-full h-64 flex items-center justify-center text-muted-foreground",children:e.jsx(Cn,{className:"h-16 w-16"})})})}),e.jsx(_e,{children:e.jsxs(De,{className:"p-6 space-y-6",children:[e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl font-bold text-foreground mb-2",children:n.name}),e.jsxs("div",{className:"flex items-center text-sm text-muted-foreground",children:[e.jsx(ta,{className:"h-4 w-4 mr-1"}),"Published ",Js(new Date(n.publish_date),"MMMM d, yyyy")]})]}),n.description&&e.jsx("div",{className:"prose prose-sm max-w-none text-muted-foreground [&_a]:text-primary [&_a]:underline",dangerouslySetInnerHTML:{__html:n.description}}),e.jsx("div",{className:"pt-4 border-t",children:e.jsxs(B,{size:"lg",className:"gap-2",onClick:()=>window.open(n.signup_link_url,"_blank"),children:[e.jsx(Tr,{className:"h-5 w-5"}),"Sign Up Now"]})})]})})]})}):e.jsx(Qs,{title:"Not Found",children:e.jsxs("div",{className:"max-w-4xl mx-auto text-center py-12",children:[e.jsx("h2",{className:"text-2xl font-bold text-foreground mb-4",children:"Service Not Found"}),e.jsx("p",{className:"text-muted-foreground mb-6",children:"The service you're looking for doesn't exist or has been removed."}),e.jsxs(B,{onClick:()=>t("/additional-services"),children:[e.jsx(ka,{className:"h-4 w-4 mr-2"}),"Back to Services"]})]})})},sH=[{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 Khn(){const[s,t]=N.useState(sH[0].id),n=sH.find(r=>r.id===s)||sH[0];return e.jsx(Qs,{title:"AI Toolkit",children:e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"p-2 bg-primary/10 rounded-lg",children:e.jsx(NT,{className:"h-6 w-6 text-primary"})}),e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl font-bold text-foreground",children:"AI Toolkit"}),e.jsx("p",{className:"text-muted-foreground",children:"Powerful AI tools to boost your real estate business"})]})]}),e.jsx("div",{className:"md:hidden",children:e.jsxs(Ns,{value:s,onValueChange:t,children:[e.jsx(ws,{className:"w-full",children:e.jsx(ks,{placeholder:"Select a tool"})}),e.jsx(js,{children:sH.map(r=>e.jsx(nt,{value:r.id,children:r.name},r.id))})]})}),e.jsx("div",{className:"hidden md:block",children:e.jsx(ya,{value:s,onValueChange:t,className:"w-full",children:e.jsx(va,{className:"w-full flex-wrap h-auto gap-1 bg-muted p-1",children:sH.map(r=>e.jsx(ls,{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 Yhn({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 Zse({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:Ot("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(Qa,{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 Zhn({agentName:s,todayDone:t,todayTotal:n,focusLine:r,weekDone:a,weekGoal:i,streak:l,staleCount:o,sphereCount:c,onEditGoal:d,onStaleClick:u,onSphereClick:h}){const m=new Date().getHours(),f=m<12?"Good morning":m<17?"Good afternoon":"Good evening",g=i>0?Math.min(100,Math.round(a/i*100)):0;return e.jsxs("div",{className:"grid gap-4 lg:grid-cols-[minmax(0,1.15fr)_minmax(0,1fr)]",children:[e.jsxs("div",{className:"relative overflow-hidden rounded-2xl border bg-gradient-to-br from-primary/[0.07] via-card to-card p-5 sm:p-6",children:[e.jsx("div",{className:"pointer-events-none absolute -right-16 -top-16 h-48 w-48 rounded-full bg-primary/10 blur-3xl"}),e.jsxs("div",{className:"relative flex flex-col-reverse items-start gap-5 sm:flex-row sm:items-center",children:[e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("p",{className:"text-[11px] font-semibold uppercase tracking-[0.16em] text-primary",children:[f,s?`, ${s}`:""]}),e.jsx("h2",{className:"mt-1.5 text-xl font-semibold leading-snug sm:text-2xl",children:n===0?"Your day is clear — pick a few people to reconnect with.":t>=n?"Today's list is done. That's how referrals get built.":`${n-t} ${n-t===1?"touch":"touches"} left to stay on track.`}),e.jsxs("p",{className:"mt-2 flex items-start gap-1.5 text-sm text-muted-foreground",children:[e.jsx(Cn,{className:"mt-0.5 h-3.5 w-3.5 shrink-0 text-primary"}),e.jsx("span",{children:r})]})]}),e.jsx(Yhn,{done:t,total:n})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsx(Zse,{icon:e.jsx(iu,{className:"h-3.5 w-3.5"}),label:"Weekly goal",value:`${a}/${i}`,hint:`${g}% of your weekly touches`,action:e.jsx("button",{onClick:d,className:"rounded p-0.5 text-muted-foreground transition-colors hover:text-primary","aria-label":"Edit weekly goal",children:e.jsx(sc,{className:"h-3.5 w-3.5"})})}),e.jsx(Zse,{icon:e.jsx(Cu,{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(Zse,{icon:e.jsx(Xr,{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(Zse,{icon:e.jsx(Yn,{className:"h-3.5 w-3.5"}),label:"Your sphere",value:String(c),hint:"People in your database",onClick:h})]})]})}const rht="agent-os-onboarding-completed",Xse=[{icon:By,iconColor:"text-white",bgGradient:"from-primary via-primary/80 to-purple-600",title:"Welcome to Agent OS",description:"You've unlocked a powerful new tool designed to help you build stronger relationships and close more deals. Agent OS is currently in beta, and we're excited for you to try it!",highlights:["Manage your most important relationships","Stay in touch with automated reminders","Track your transactions and goals","Maximize referrals from your sphere"]},{icon:ff,iconColor:"text-white",bgGradient:"from-pink-500 via-rose-500 to-red-500",title:"InnerCircle Home",description:"Your daily command center. See today's action items, track your momentum streak, and get a snapshot of your relationship health—all at a glance.",highlights:["Today's touchpoints and special dates","Momentum stats and streak tracking","Relationship health overview","Quick access to all features"]},{icon:Yn,iconColor:"text-white",bgGradient:"from-blue-500 via-indigo-500 to-purple-500",title:"Contacts",description:"Import and organize your sphere of influence. Tag contacts by relationship type (Top 25, Past Clients, Referral Partners, etc.) to prioritize your outreach.",highlights:["Import contacts via CSV","Tag by relationship type","Track birthdays and home anniversaries","See relationship health scores"]},{icon:ld,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:Io,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:fl,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"]}],Xhn=()=>{const[s,t]=N.useState(!1),[n,r]=N.useState(0),[a,i]=N.useState(!1);N.useEffect(()=>{if(!localStorage.getItem(rht)){const g=setTimeout(()=>t(!0),500);return()=>clearTimeout(g)}},[]);const l=()=>{n{r(n+1),i(!1)},150)):c()},o=()=>{c()},c=()=>{localStorage.setItem(rht,"true"),t(!1)},d=Xse[n],u=d.icon,h=n===Xse.length-1,m=f=>{f||c(),t(f)};return e.jsx(Bs,{open:s,onOpenChange:m,children:e.jsxs(Fs,{className:"sm:max-w-lg overflow-hidden p-0 gap-0",children:[e.jsxs("div",{className:`relative bg-gradient-to-br ${d.bgGradient} p-8 pb-12 transition-all duration-500`,children:[e.jsxs("div",{className:"absolute inset-0 overflow-hidden",children:[e.jsx("div",{className:"absolute -top-4 -right-4 w-32 h-32 bg-white/10 rounded-full blur-2xl animate-pulse"}),e.jsx("div",{className:"absolute -bottom-8 -left-8 w-40 h-40 bg-white/10 rounded-full blur-3xl animate-pulse",style:{animationDelay:"1s"}}),e.jsx("div",{className:"absolute top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2 w-64 h-64 bg-white/5 rounded-full blur-3xl"})]}),e.jsxs("div",{className:`relative mx-auto flex h-20 w-20 items-center justify-center transition-all duration-300 ${a?"scale-75 opacity-0":"scale-100 opacity-100"}`,children:[e.jsx("div",{className:"absolute inset-0 bg-white/20 rounded-2xl blur-xl"}),e.jsx("div",{className:"relative flex h-20 w-20 items-center justify-center rounded-2xl bg-white/20 backdrop-blur-sm border border-white/30 shadow-2xl",children:e.jsx(u,{className:`h-10 w-10 ${d.iconColor} drop-shadow-lg`})})]}),n===0&&e.jsxs("div",{className:"absolute top-4 right-4 px-3 py-1 rounded-full bg-white/20 backdrop-blur-sm border border-white/30 text-white text-xs font-medium flex items-center gap-1.5",children:[e.jsx(Cn,{className:"h-3 w-3"}),"Beta"]})]}),e.jsxs("div",{className:"p-6 pt-4",children:[e.jsxs(qs,{className:"text-center sm:text-center pb-2",children:[e.jsx($s,{className:`text-2xl font-bold transition-all duration-300 ${a?"translate-y-2 opacity-0":"translate-y-0 opacity-100"}`,children:d.title}),e.jsx(Ar,{className:`text-base pt-2 transition-all duration-300 delay-75 ${a?"translate-y-2 opacity-0":"translate-y-0 opacity-100"}`,children:d.description})]}),d.highlights&&e.jsx("div",{className:`space-y-2.5 py-4 transition-all duration-300 delay-100 ${a?"translate-y-2 opacity-0":"translate-y-0 opacity-100"}`,children:d.highlights.map((f,g)=>e.jsxs("div",{className:"flex items-center gap-3 group",style:{transitionDelay:`${150+g*50}ms`},children:[e.jsx("div",{className:`flex h-6 w-6 shrink-0 items-center justify-center rounded-full bg-gradient-to-br ${d.bgGradient} shadow-sm`,children:e.jsx(pa,{className:"h-3.5 w-3.5 text-white"})}),e.jsx("span",{className:"text-sm text-muted-foreground group-hover:text-foreground transition-colors",children:f})]},g))}),e.jsx("div",{className:"flex justify-center gap-2 py-4",children:Xse.map((f,g)=>e.jsx("button",{onClick:()=>{g!==n&&(i(!0),setTimeout(()=>{r(g),i(!1)},150))},className:`h-2 rounded-full transition-all duration-300 ${g===n?"w-8 bg-gradient-to-r "+d.bgGradient:g{const{user:s}=Ls();return mt({queryKey:["contact-snoozes",s==null?void 0:s.id],queryFn:async()=>{const{data:t,error:n}=await H.from("contact_snoozes").select("*").gte("snoozed_until",new Date().toISOString());if(n)throw n;return t},enabled:!!s})},Jhn=()=>{const s=as(),{user:t}=Ls();return _t({mutationFn:async({contactId:n,days:r})=>{if(!(t!=null&&t.id))throw new Error("Not authenticated");const a=Ad(new Date,r);await H.from("contact_snoozes").delete().eq("contact_id",n);const{error:i}=await H.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"]}),xa({title:"Touch snoozed!",description:"Contact has been snoozed."})},onError:n=>{xa({title:"Error snoozing contact",description:n.message,variant:"destructive"})}})},emn=()=>{const s=as();return _t({mutationFn:async t=>{const{error:n}=await H.from("contact_snoozes").delete().eq("contact_id",t);if(n)throw n},onSuccess:()=>{s.invalidateQueries({queryKey:["contact-snoozes"]}),xa({title:"Snooze cancelled"})},onError:t=>{xa({title:"Error cancelling snooze",description:t.message,variant:"destructive"})}})},tmn=[{label:"1 week",days:7},{label:"2 weeks",days:14},{label:"1 month",days:30}];function BCe({open:s,onOpenChange:t,contactId:n,contactName:r}){const[a,i]=N.useState(null),l=Jhn(),o=async()=>{a&&(await l.mutateAsync({contactId:n,days:a}),i(null),t(!1))},c=d=>Js(Ad(new Date,d),"MMM d, yyyy");return e.jsx(Bs,{open:s,onOpenChange:t,children:e.jsxs(Fs,{className:"sm:max-w-md",children:[e.jsxs(qs,{children:[e.jsxs($s,{className:"flex items-center gap-2",children:[e.jsx(Xr,{className:"h-5 w-5"}),"Snooze Touch"]}),e.jsxs(Ar,{children:["Postpone the next scheduled touch for ",r,". Select how long to snooze."]})]}),e.jsx("div",{className:"space-y-3 py-4",children:tmn.map(d=>e.jsxs("button",{type:"button",onClick:()=>i(d.days),className:Ot("w-full flex items-center justify-between p-3 rounded-lg border transition-colors",a===d.days?"border-primary bg-primary/5":"border-border hover:border-primary/50 hover:bg-accent/50"),children:[e.jsx("span",{className:"font-medium",children:d.label}),e.jsxs("span",{className:"text-sm text-muted-foreground flex items-center gap-1",children:[e.jsx(ta,{className:"h-3.5 w-3.5"}),"Until ",c(d.days)]})]},d.days))}),e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx(B,{variant:"outline",onClick:()=>t(!1),children:"Cancel"}),e.jsx(B,{onClick:o,disabled:!a||l.isPending,children:l.isPending?"Snoozing...":"Snooze Touch"})]})]})})}const smn={Crown:q0,FileText:Wr,Users:Yn,Globe:au,Star:Wa,Phone:ga,MessageSquare:xo,PenTool:PT,Video:na,Gift:Io};function nmn({actions:s,onMarkComplete:t,onViewScript:n,isLoading:r,buildSmsLink:a,buildEmailLink:i,onGmailCompose:l}){const o=tr(),[c,d]=N.useState("name"),[u,h]=N.useState("asc"),[m,f]=N.useState(null),[g,y]=N.useState(""),x=T=>{c===T?h(P=>P==="asc"?"desc":"asc"):(d(T),h("asc"))},_=N.useMemo(()=>[...s].sort((T,P)=>{var M,L;let I=0;switch(c){case"name":{const z=`${T.contact.first_name} ${T.contact.last_name||""}`.toLowerCase(),$=`${P.contact.first_name} ${P.contact.last_name||""}`.toLowerCase();I=z.localeCompare($);break}case"relationship_type":I=(T.relationshipTypeName||"").localeCompare(P.relationshipTypeName||"");break;case"action_type":I=(((M=T.actionType)==null?void 0:M.name)||"").localeCompare(((L=P.actionType)==null?void 0:L.name)||"");break;case"last_touch":I=(T.monthNumber||0)-(P.monthNumber||0);break}return u==="asc"?I:-I}),[s,c,u]),b=T=>smn[T||"Phone"]||ga,k=({field:T,children:P})=>e.jsxs(B,{variant:"ghost",size:"sm",className:"h-8 -ml-3 font-medium",onClick:()=>x(T),children:[P,c===T?u==="asc"?e.jsx(Om,{className:"ml-2 h-4 w-4"}):e.jsx(Wf,{className:"ml-2 h-4 w-4"}):e.jsx(mg,{className:"ml-2 h-4 w-4 opacity-50"})]}),A=(T,P,I)=>{f(T),y(`${P} ${I||""}`.trim())};return s.length===0?e.jsxs("div",{className:"text-center py-8 text-muted-foreground",children:[e.jsx("p",{children:"No actions scheduled for today."}),e.jsx("p",{className:"text-sm mt-1",children:"Add contacts and enable touchpoint plans to get started."})]}):e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"border rounded-lg overflow-hidden",children:e.jsxs(Oa,{children:[e.jsx(Fa,{children:e.jsxs(un,{className:"bg-muted/50",children:[e.jsx(Mt,{className:"w-[180px]",children:e.jsx(k,{field:"name",children:"Contact"})}),e.jsx(Mt,{className:"w-[130px]",children:e.jsx(k,{field:"relationship_type",children:"Type"})}),e.jsx(Mt,{className:"w-[120px]",children:e.jsx(k,{field:"action_type",children:"Action"})}),e.jsx(Mt,{className:"w-[130px]",children:"Phone"}),e.jsx(Mt,{className:"w-[200px]",children:"Quick Actions"})]})}),e.jsx(za,{children:_.map((T,P)=>{var V,W,G,X,te,ne;const I=T.isSpecialDate,M=T.specialDateType,L=I?M==="birthday"?Fm:_a:b(((V=T.actionType)==null?void 0:V.icon)||null),z=T.contact.phone,$=T.contact.email;return e.jsxs(un,{className:Ot("hover:bg-muted/50 transition-colors",I&&M==="birthday"&&"bg-pink-50/50 dark:bg-pink-950/20",I&&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/${T.contact.id}`),className:"truncate max-w-[160px] text-left hover:text-primary hover:underline transition-colors",children:[T.contact.first_name," ",T.contact.last_name]})})}),e.jsx(gt,{children:T.relationshipTypeName?e.jsx(We,{variant:"secondary",className:"text-xs",children:T.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:I?e.jsx(We,{className:Ot("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(Fm,{className:"h-3 w-3"})," Birthday"]}):e.jsxs(e.Fragment,{children:[e.jsx(_a,{className:"h-3 w-3"})," Anniversary"]})}):e.jsxs(We,{variant:"outline",className:"gap-1",children:[e.jsx(L,{className:"h-3 w-3"}),(W=T.actionType)==null?void 0:W.name]})})}),e.jsx(gt,{children:z?e.jsx("span",{className:"text-sm font-mono",children:T.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:[z&&e.jsx("a",{href:`tel:${T.contact.phone}`,className:"p-1.5 rounded bg-primary/10 hover:bg-primary/20 text-primary transition-colors",title:"Call",children:e.jsx(ga,{className:"h-3.5 w-3.5"})}),z&&e.jsx("a",{href:a(T.contact.phone,(G=T.script)==null?void 0:G.script_body,T.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(xo,{className:"h-3.5 w-3.5"})}),$&&(l?e.jsx("button",{onClick:()=>l({id:T.contact.id,first_name:T.contact.first_name,last_name:T.contact.last_name,email:T.contact.email}),className:"p-1.5 rounded bg-sky-500/10 hover:bg-sky-500/20 text-sky-600 dark:text-sky-400 transition-colors",title:"Compose Email",children:e.jsx(mn,{className:"h-3.5 w-3.5"})}):e.jsx("a",{href:i(T.contact.email,(X=T.script)==null?void 0:X.script_body,(te=T.script)==null?void 0:te.email_subject,(ne=T.actionType)==null?void 0:ne.name,T.contact),className:"p-1.5 rounded bg-sky-500/10 hover:bg-sky-500/20 text-sky-600 dark:text-sky-400 transition-colors",title:"Email",children:e.jsx(mn,{className:"h-3.5 w-3.5"})})),I&&e.jsxs("button",{onClick:()=>{const me=`${T.contact.first_name}${T.contact.last_name?" "+T.contact.last_name:""}`,ue=M==="birthday"?"birthday":"home_anniversary",ce=new URLSearchParams({cardType:ue,contactId:T.contact.id,name:me,...T.contact.address?{address:T.contact.address}:{},...M==="anniversary"&&T.contact.home_anniversary?{date:T.contact.home_anniversary}:{}});o(`/mission-control/card-studio?${ce.toString()}`)},className:Ot("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(mn,{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:()=>A(T.contact.id,T.contact.first_name,T.contact.last_name),title:"Snooze",children:e.jsx(K0,{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 me;return t(T.contact.id,T.actionType.id,(me=T.script)==null?void 0:me.id)},disabled:r,children:[e.jsx(Hr,{className:"h-3.5 w-3.5 mr-1"}),"Done"]})]})})]},`${T.contact.id}-${P}`)})})]})}),e.jsx(BCe,{open:!!m,onOpenChange:T=>!T&&f(null),contactId:m||"",contactName:g})]})}function rmn({onSelect:s}){const{user:t}=Ls(),[n,r]=N.useState("root"),[a,i]=N.useState(null),{data:l=[],isLoading:o}=mt({queryKey:["agent-email-template-categories"],queryFn:async()=>{const{data:_,error:b}=await H.from("email_template_categories").select("*").order("sort_order");if(b)throw b;return _}}),{data:c=[],isLoading:d}=mt({queryKey:["agent-email-templates",a],enabled:n==="category"&&!!a,queryFn:async()=>{const{data:_,error:b}=await H.from("agent_email_templates").select("*").eq("is_active",!0).eq("category_id",a).order("sort_order");if(b)throw b;return _}}),{data:u=[],isLoading:h}=mt({queryKey:["picker-campaign-templates",t==null?void 0:t.id],enabled:!!t,queryFn:async()=>{const{data:_,error:b}=await H.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 _}}),m=u.filter(_=>_.user_id===(t==null?void 0:t.id)&&!_.is_shared),f=u.filter(_=>_.is_shared),g=l.find(_=>_.id===a);if(o)return e.jsx("div",{className:"flex items-center justify-center py-6",children:e.jsx(us,{className:"h-5 w-5 animate-spin text-muted-foreground"})});const y=_=>{s({title:_.name,subject:_.subject,body:_.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(Ro,{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(Qa,{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(au,{className:"h-4 w-4"})}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium text-sm",children:"Shared Library"}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[f.length," team template",f.length===1?"":"s"]})]})]}),e.jsx(Qa,{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(_=>e.jsxs("button",{onClick:()=>{i(_.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:_.icon}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium text-sm",children:_.name}),_.description&&e.jsx("p",{className:"text-xs text-muted-foreground line-clamp-1",children:_.description})]})]}),e.jsx(Qa,{className:"h-4 w-4 text-muted-foreground shrink-0"})]},_.id))})]})]});const x=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(Fc,{className:"h-3.5 w-3.5"}),"Back"]});return n==="my"?e.jsxs("div",{className:"space-y-2",children:[x,e.jsxs("p",{className:"text-xs font-medium flex items-center gap-1.5",children:[e.jsx(Ro,{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(us,{className:"h-5 w-5 animate-spin text-muted-foreground"})}):m.length===0?e.jsxs("div",{className:"text-center py-6 space-y-2",children:[e.jsx(Cn,{className:"h-6 w-6 text-muted-foreground mx-auto"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"You haven't created any templates yet."}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Create beautiful templates in ",e.jsx("span",{className:"font-medium",children:"Email Templates"})," in the sidebar — they'll appear here."]})]}):e.jsx(lo,{className:"max-h-[280px]",children:e.jsx("div",{className:"space-y-1",children:m.map(_=>e.jsxs("button",{onClick:()=>y(_),className:"w-full p-2.5 rounded-lg border hover:bg-accent transition-colors text-left",children:[e.jsx("p",{className:"font-medium text-sm truncate",children:_.name}),e.jsx("p",{className:"text-xs text-muted-foreground mt-0.5 line-clamp-1",children:_.subject||"(no subject)"})]},_.id))})})]}):n==="shared"?e.jsxs("div",{className:"space-y-2",children:[x,e.jsxs("p",{className:"text-xs font-medium flex items-center gap-1.5",children:[e.jsx(au,{className:"h-3.5 w-3.5"})," Shared Library"]}),h?e.jsx("div",{className:"flex items-center justify-center py-6",children:e.jsx(us,{className:"h-5 w-5 animate-spin text-muted-foreground"})}):f.length===0?e.jsx("p",{className:"text-sm text-muted-foreground py-4 text-center",children:"No shared templates yet."}):e.jsx(lo,{className:"max-h-[280px]",children:e.jsx("div",{className:"space-y-1",children:f.map(_=>e.jsxs("button",{onClick:()=>y(_),className:"w-full p-2.5 rounded-lg border hover:bg-accent transition-colors text-left",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("p",{className:"font-medium text-sm truncate",children:_.name}),e.jsx(We,{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:_.subject||"(no subject)"})]},_.id))})})]}):e.jsxs("div",{className:"space-y-2",children:[x,e.jsxs("p",{className:"text-xs font-medium flex items-center gap-1.5",children:[e.jsx("span",{children:g==null?void 0:g.icon})," ",g==null?void 0:g.name]}),d?e.jsx("div",{className:"flex items-center justify-center py-6",children:e.jsx(us,{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(lo,{className:"max-h-[280px]",children:e.jsx("div",{className:"space-y-1",children:c.map(_=>e.jsxs("button",{onClick:()=>s(_),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:_.title}),_.tone&&e.jsx(We,{variant:"secondary",className:"text-[10px] shrink-0",children:_.tone})]}),e.jsx("p",{className:"text-xs text-muted-foreground mt-0.5 line-clamp-1",children:_.subject})]},_.id))})})]})}function $Ce(){const{user:s}=Ls(),t=as(),{data:n,isLoading:r}=mt({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 H.from("contact_intake_pages").select("*").eq("user_id",s.id).maybeSingle();if(u)throw u;return d},enabled:!!(s!=null&&s.id)}),a=_t({mutationFn:async d=>{if(!(s!=null&&s.id))throw new Error("Not authenticated");const{data:u,error:h}=await H.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"]}),ie.success("Connect page created!")},onError:d=>{var u;(u=d.message)!=null&&u.includes("duplicate")?ie.error("That slug is already taken. Try another."):ie.error("Failed to create page")}}),i=_t({mutationFn:async d=>{if(!(n!=null&&n.id))throw new Error("No intake page");const{error:u}=await H.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"]}),ie.success("Page updated!")},onError:()=>ie.error("Failed to update page")}),{data:l=[],isLoading:o}=mt({queryKey:["contact-intake-submissions",s==null?void 0:s.id],queryFn:async()=>{if(!(s!=null&&s.id))return[];const{data:d,error:u}=await H.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=_t({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 H.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 eIt({value:s,onChange:t,userId:n,placeholder:r}){const[a,i]=N.useState(!1),[l,o]=N.useState([]),[c,d]=N.useState(!1),[u,h]=N.useState(0),m=N.useRef(null),f=N.useRef(null);N.useEffect(()=>{const y=x=>{m.current&&!m.current.contains(x.target)&&i(!1)};return document.addEventListener("mousedown",y),()=>document.removeEventListener("mousedown",y)},[]),N.useEffect(()=>{f.current&&clearTimeout(f.current);const y=s.trim();if(!n||y.length<1||y.includes("@")&&y.indexOf("@")>0&&/\S+@\S+\.\S+/.test(y)){o([]);return}return f.current=setTimeout(async()=>{d(!0);const x=`%${y}%`,_=H,{data:b,error:k}=await _.from("innercircle_contacts").select("id, first_name, last_name, email").eq("owner_user_id",n).not("email","is",null).or(`first_name.ilike.${x},last_name.ilike.${x},email.ilike.${x}`).order("first_name",{ascending:!0}).limit(8);d(!1),!k&&b&&(o(b),h(0),i(b.length>0))},180),()=>{f.current&&clearTimeout(f.current)}},[s,n]);const g=y=>{y.email&&(t(y.email),i(!1))};return e.jsxs("div",{ref:m,className:"relative",children:[e.jsx(we,{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(x=>Math.min(x+1,l.length-1))):y.key==="ArrowUp"?(y.preventDefault(),h(x=>Math.max(x-1,0))):y.key==="Enter"?(y.preventDefault(),g(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(us,{className:"h-3 w-3 animate-spin"})," Searching..."]}):l.map((y,x)=>{const _=[y.first_name,y.last_name].filter(Boolean).join(" ")||"(No name)";return e.jsxs("button",{type:"button",onMouseEnter:()=>h(x),onClick:()=>g(y),className:`w-full flex items-center gap-2 px-3 py-2 text-left text-sm border-b last:border-b-0 ${x===u?"bg-accent":"bg-popover"}`,children:[e.jsx(Ro,{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:_}),e.jsx("div",{className:"text-xs text-muted-foreground truncate",children:y.email})]})]},y.id)})})]})}function amn(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 GLe=25*1024*1024,aht=Math.floor(6.5*1024*1024),imn=750*1024,OS=50,omn=["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 Qse(s){return s<1024?s+" B":s<1024*1024?(s/1024).toFixed(1)+" KB":(s/(1024*1024)).toFixed(1)+" MB"}function lmn(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 cmn(s){if(!s)return"";const t=s.trim();return t.split(/\s+/)[0]||t}function FS(s,t){const n=cmn(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 Y_({open:s,onOpenChange:t,contact:n,bulkContacts:r,defaultSubject:a="",defaultBody:i="",gmailEmail:l,onSendComplete:o,sendSource:c,logTouchpoint:d=!0}){const{user:u}=Ls(),h=as(),{isReady:m,settings:f}=$U(),{data:g}=OCe(),[y,x]=N.useState(!1),{intakePage:_}=$Ce(),b=_?`https://contacts.relevelup.com/${_.slug}`:null,k=!!r&&r.length>0,A=m,T=k?r:n?[n]:[],P=T[0],I=k?Math.ceil(T.length/OS):1,M=k&&T.length>OS,[L,z]=N.useState((P==null?void 0:P.email)||""),[$,V]=N.useState(a),[W,G]=N.useState(i),[X,te]=N.useState(!1),[ne,me]=N.useState(!1),[ue,ce]=N.useState([]),ae=N.useRef(new Map),[he,xe]=N.useState(a),[ve,ge]=N.useState(i),[be,Se]=N.useState("composing"),[Ie,Me]=N.useState(0),[Re,Be]=N.useState(0),[Ne,Ge]=N.useState(0),[Ce,Fe]=N.useState(0),Ae=N.useRef(!1),[Xe,$e]=N.useState(null);N.useEffect(()=>{if(s){const ms=/<[a-z][\s\S]*>/i.test(i),Ys=ms?amn(i):i;rt.current=ms?{plain:Ys,html:i}:null,z((P==null?void 0:P.email)||""),xe(a),ge(Ys),V(FS(a,P||{first_name:""})),G(FS(Ys,P||{first_name:""})),me(!a&&!i),ce([]),ae.current=new Map,Se("composing"),Me(0),Be(0),Ge(0),Fe(0),Ae.current=!1,$e(null)}},[s,P,a,i]);const Ye=async ms=>{const Ys=ms.target.files;if(!Ys)return;const It=ue.reduce((Hs,Rs)=>Hs+Rs.size,0),Ds=[];let As=It;for(const Hs of Array.from(Ys)){if(!omn.includes(Hs.type)){ie.error(`${Hs.name}: Unsupported file type`);continue}if(As+Hs.size>GLe){ie.error(`Total attachments exceed ${Qse(GLe)} limit`);break}try{const Rs=await lmn(Hs);Ds.push({name:Hs.name,type:Hs.type,size:Hs.size,data:Rs}),As+=Hs.size}catch{ie.error(`Failed to read ${Hs.name}`)}}ce(Hs=>[...Hs,...Ds]),ms.target.value=""},Je=ms=>{const Ys=ue[ms];Ys&&ae.current.delete(`${Ys.name}::${Ys.size}`),ce(It=>It.filter((Ds,As)=>As!==ms))},Ke=async()=>{if(ue.length===0||!u)return{inline:[],paths:[]};const ms=[],Ys=[];for(const It of ue){const Ds=`${It.name}::${It.size}`,As=ae.current.get(Ds);if(As){Ys.push(As);continue}if(It.size<=imn){ms.push(It);continue}const Hs=It.name.replace(/[^a-zA-Z0-9._-]/g,"_"),Rs=`${u.id}/${Date.now()}-${Hs}`,en=atob(It.data),Rn=new Uint8Array(en.length);for(let Dn=0;Dn{if(!/<[a-z][\s\S]*>/i.test(ms)||typeof window>"u")return ms;const Ys=ms.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,""),It=document.createElement("div");return It.innerHTML=Ys,(It.textContent||It.innerText||"").replace(/\u00a0/g," ").replace(/\n{3,}/g,` `).trim()},rt=N.useRef(null),Ze=ms=>{const Ys=/<[a-z][\s\S]*>/i.test(ms.body),It=Ys?st(ms.body):ms.body;rt.current=Ys?{plain:It,html:ms.body}:null,xe(ms.subject),ge(It),V(FS(ms.subject,P||{first_name:""})),G(FS(It,P||{first_name:""})),me(!1)},ht=ms=>/<\s*(p|div|span|table|tr|td|img|br|h[1-6]|a|body|html|section|article|ul|ol|li)\b/i.test(ms)?ms:ms.split(/\n\n+/).map(Ys=>`

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

`).join(""),Bt=(ms,Ys)=>{const It="https://relzejiswnotikjgvjhz.supabase.co/functions/v1/bulk-email-track";let Ds=ms.replace(/]*?)href=(["'])(.*?)\2([^>]*)>/gi,(Hs,Rs,en,Rn,Bn)=>{if(!Rn||/^(mailto:|tel:|#)/i.test(Rn)||Rn.includes("/bulk-email-track")||Rn.includes("/ses-campaign-track"))return Hs;const Dn=`${It}?s=${Ys}&t=click&u=${encodeURIComponent(Rn)}`;return``});const As=``;return/<\/body>/i.test(Ds)?Ds=Ds.replace(/<\/body>/i,`${As}`):Ds=`${Ds}${As}`,Ds},Ct=async ms=>{if(!(ms!=null&&ms.email))return ie.error("Please enter a recipient email"),!1;const Ys=ms||{first_name:""},It=FS(he,Ys),Ds=rt.current,As=Ds&&ve===Ds.plain,Hs=FS(As?Ds.html:ve,Ys);let Rs=As?Hs:ht(Hs);const en=u&&ms.id?crypto.randomUUID():null;en&&(Rs=Bt(Rs,en));try{if(u&&ms.email){const Dn=new Date(Date.now()-6e5).toISOString(),{data:Jn}=await H.from("bulk_email_sends").select("id").eq("user_id",u.id).eq("contact_email",ms.email).eq("subject",It).gte("sent_at",Dn).limit(1);if(Jn&&Jn.length>0)return console.log(`Skipping duplicate send to ${ms.email} (same subject within 10 min)`),ie.info(`Skipped ${ms.first_name||ms.email} — already sent this in the last 10 min`),!0}const{inline:Rn,paths:Bn}=await Ke();if(A){const Dn=(f==null?void 0:f.display_name)||"ReLevelUp",Jn=`${Dn.toLowerCase().replace(/[^a-z]/g,".")}@send.relevelup.com`,ua=`${Dn} <${Jn}>`;let Mr=Bn[0];if(!Mr&&Rn.length>0&&u){const ia=Rn[0],vr=ia.name.replace(/[^a-zA-Z0-9._-]/g,"_"),Nr=`${u.id}/${Date.now()}-${vr}`,rn=atob(ia.data),Zn=new Uint8Array(rn.length);for(let xs=0;xs({name:ua,type:Mr,data:sn})),attachment_paths:Bn}});if(Jn)throw Jn;if(!(Dn!=null&&Dn.success))throw new Error((Dn==null?void 0:Dn.error)||"Failed to send")}if(u&&ms.id&&en&&(await H.from("bulk_email_sends").insert({id:en,user_id:u.id,contact_id:ms.id,contact_email:ms.email,subject:It,source:c||(A?"ses_bulk":"sphere_gaps")}),d))try{await H.from("contact_touch_logs").insert({owner_user_id:u.id,contact_id:ms.id,action_type_id:"9a88a47c-cb2a-4401-a2b5-111a76b19f9d",notes:`Mass Email: ${It}`,completed_at:new Date().toISOString()})}catch(Dn){console.warn("touch log insert failed",Dn)}return!0}catch(Rn){return console.error("Send error:",Rn),ie.error("Failed to send to "+ms.first_name+": "+(Rn instanceof Error?Rn.message:"Unknown error")),!1}},Yt=()=>{const ms=Ie*OS;return T.slice(ms,ms+OS)},Kt=async()=>{if(!$||!W){ie.error("Please fill in subject and message");return}const ms=Yt();te(!0),Se("sending");let Ys=0,It=0;for(let As=0;AssetTimeout(Rs,150));Be(As=>As+Ys),Ge(As=>As+It),te(!1),h.invalidateQueries({queryKey:["bulk-email-sends"]}),h.invalidateQueries({queryKey:["contact-touch-logs"]}),h.invalidateQueries({queryKey:["contacts-last-touch"]}),Ie>=I-1||Ae.current?Se("all_done"):Se("batch_complete")},Xs=async()=>{if(!$||!W){ie.error("Please fill in subject and message");return}if(A&&g&&!g.hasVerifiedSes&&!g.hasGmail){x(!0);return}if(!k){const ms=P||{id:"",first_name:"",last_name:"",email:L.trim()};if(!ms.email){ie.error("Please enter a recipient email");return}te(!0);try{await Ct(ms)&&(h.invalidateQueries({queryKey:["bulk-email-sends"]}),ie.success("Email sent successfully!"),t(!1),o==null||o())}finally{te(!1)}return}await Kt()},zs=async()=>{Me(ms=>ms+1),Fe(0),await new Promise(ms=>setTimeout(ms,50)),await Kt()};N.useEffect(()=>{},[Ie]);const Vt=()=>{if(X){Ae.current=!0;return}t(!1),o==null||o()},At=Ie*OS,Os=Math.min(At+OS,T.length),Nt=k&&T.length>0?Math.round((Re+Ne)/T.length*100):0;return e.jsxs(Bs,{open:s,onOpenChange:Vt,children:[e.jsxs(Fs,{className:"sm:max-w-[600px] max-h-[90vh] overflow-y-auto",children:[e.jsxs(qs,{children:[e.jsxs($s,{className:"flex items-center gap-2",children:[e.jsx(mn,{className:`h-5 w-5 ${A?"text-orange-500":"text-red-500"}`}),k?`Send to ${T.length} Contacts`:"Compose Email"]}),A?e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Sending via ",e.jsx("span",{className:"font-medium",children:"Mass Email"})," (reply-to: ",f==null?void 0:f.reply_to_email,")"]}):l?e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Sending from ",e.jsx("span",{className:"font-medium",children:l})]}):null,k&&be==="composing"&&e.jsxs("p",{className:"text-xs text-muted-foreground mt-1",children:["Composing email for ",e.jsxs("span",{className:"font-medium",children:[T.length," contacts"]}),". You'll review each personalized email before sending."]})]}),be==="sending"&&e.jsxs("div",{className:"space-y-4 py-4",children:[e.jsxs("div",{className:"text-center space-y-2",children:[e.jsx(us,{className:"h-8 w-8 animate-spin mx-auto text-primary"}),e.jsxs("p",{className:"font-medium",children:["Sending batch ",Ie+1," of ",I,"..."]}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:[Ce," of ",Yt().length," in this batch"]})]}),e.jsx(ro,{value:Ce/Yt().length*100,className:"h-2"}),e.jsxs("div",{className:"flex justify-between text-xs text-muted-foreground",children:[e.jsxs("span",{children:["Overall: ",Re+Ne," / ",T.length]}),e.jsxs("span",{children:[Re," sent • ",Ne," failed"]})]}),e.jsx(B,{variant:"outline",size:"sm",className:"w-full",onClick:()=>{Ae.current=!0},children:"Stop Sending"})]}),be==="batch_complete"&&e.jsxs("div",{className:"space-y-4 py-4",children:[e.jsxs("div",{className:"text-center space-y-2",children:[e.jsx(Hr,{className:"h-8 w-8 text-emerald-500 mx-auto"}),e.jsxs("p",{className:"font-medium",children:["Batch ",Ie+1," Complete!"]}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:[Re," sent, ",Ne," failed so far"]})]}),e.jsx(ro,{value:Nt,className:"h-2"}),e.jsxs("p",{className:"text-xs text-center text-muted-foreground",children:[T.length-Re-Ne," contacts remaining (",I-Ie-1," batches left)"]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(B,{variant:"outline",className:"flex-1",onClick:Vt,children:"Done for Now"}),e.jsxs(B,{className:"flex-1 gap-2",onClick:zs,children:[e.jsx(Rr,{className:"h-4 w-4"}),"Send Next ",Math.min(OS,T.length-Os)," Contacts"]})]})]}),be==="all_done"&&e.jsxs("div",{className:"space-y-4 py-4",children:[e.jsxs("div",{className:"text-center space-y-2",children:[e.jsx(Hr,{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:[Re," emails sent successfully",Ne>0&&e.jsxs("span",{className:"text-destructive",children:[" • ",Ne," failed"]})]})]}),e.jsx(B,{className:"w-full",onClick:Vt,children:"Close"})]}),be==="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(Wr,{className:"h-4 w-4"})," Choose a Template"]}),e.jsxs(B,{variant:"ghost",size:"sm",onClick:()=>me(!1),className:"h-7 px-2 text-xs",children:[e.jsx(hr,{className:"h-3 w-3 mr-1"})," Write from scratch"]})]}),e.jsx(rmn,{onSelect:Ze})]}):e.jsxs(B,{variant:"outline",size:"sm",className:"gap-2",onClick:()=>me(!0),children:[e.jsx(Wr,{className:"h-4 w-4"}),"Browse Templates"]}),e.jsx(Wl,{}),!k&&e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(re,{htmlFor:"gmail-to",children:"To"}),e.jsx(eIt,{value:L,onChange:z,userId:u==null?void 0:u.id})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(re,{htmlFor:"gmail-subject",children:"Subject"}),e.jsx(we,{id:"gmail-subject",value:$,onChange:ms=>{V(ms.target.value),xe(ms.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(re,{htmlFor:"gmail-body",children:"Message"}),e.jsxs("div",{className:"flex gap-1",children:[e.jsx(We,{variant:"outline",className:"text-[10px] cursor-pointer hover:bg-accent",onClick:()=>{G(ms=>ms+"{{first_name}}"),ge(ms=>ms+"{{first_name}}")},children:"{{first_name}}"}),e.jsx(We,{variant:"outline",className:"text-[10px] cursor-pointer hover:bg-accent",onClick:()=>{G(ms=>ms+"{{last_name}}"),ge(ms=>ms+"{{last_name}}")},children:"{{last_name}}"}),b&&e.jsx(We,{variant:"outline",className:"text-[10px] cursor-pointer hover:bg-primary/10 border-primary/40 text-primary",onClick:()=>{const ms=` When you get a sec, can you share your latest contact info with me? It only takes about a minute: ${b} `;G(Ys=>Ys+ms),ge(Ys=>Ys+ms)},title:"Insert your Connect Page link",children:"+ Connect Page"})]})]}),e.jsx(Ws,{id:"gmail-body",value:W,onChange:ms=>{G(ms.target.value),ge(ms.target.value)},placeholder:"Write your message...",rows:10,className:"resize-y"}),k&&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:"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 ms;return(ms=document.getElementById("gmail-attachments"))==null?void 0:ms.click()},disabled:X,children:[e.jsx(LT,{className:"h-4 w-4"}),"Attach Files"]}),e.jsxs("span",{className:"text-xs text-muted-foreground",children:["PDF, images, Word, Excel (max ",Qse(GLe)," 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:Ye})]}),ue.length>0&&e.jsx("div",{className:"flex flex-wrap gap-2",children:ue.map((ms,Ys)=>e.jsxs(We,{variant:"secondary",className:"gap-1.5 pl-2 pr-1 py-1",children:[e.jsx(LT,{className:"h-3 w-3"}),e.jsx("span",{className:"max-w-[140px] truncate text-xs",children:ms.name}),e.jsxs("span",{className:"text-[10px] text-muted-foreground",children:["(",Qse(ms.size),")"]}),e.jsx("button",{type:"button",onClick:()=>Je(Ys),className:"ml-0.5 rounded-full p-0.5 hover:bg-muted",children:e.jsx(hr,{className:"h-3 w-3"})})]},Ys))}),A&&ue.some(ms=>ms.size>aht)&&e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Files over ",Qse(aht)," 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"}),k?e.jsxs(B,{onClick:()=>{$e(T[0]||null),Se("reviewing")},disabled:!$||!W,className:"gap-2",children:["Review Emails",e.jsx(vi,{className:"h-4 w-4"})]}):e.jsxs(B,{onClick:Xs,disabled:X||!$||!W||!L.trim(),className:"gap-2",children:[X?e.jsx(us,{className:"h-4 w-4 animate-spin"}):e.jsx(Rr,{className:"h-4 w-4"}),X?"Sending...":"Send Email"]})]})]}),be==="reviewing"&&k&&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."]}),M&&e.jsxs("p",{className:"text-xs text-amber-600 bg-amber-500/10 rounded-md px-2.5 py-1.5",children:["📦 ",T.length," contacts will be sent in ",I," batches of up to ",OS,". You'll confirm before each batch."]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs(re,{children:["Recipients (",T.length,")"]}),e.jsx("div",{className:"bg-muted p-1.5 rounded-md space-y-0.5 max-h-32 overflow-y-auto",children:T.map(ms=>e.jsxs("div",{className:`text-sm px-2 py-1 rounded cursor-pointer transition-colors ${(Xe==null?void 0:Xe.id)===ms.id?"bg-primary/10 text-primary font-medium":"text-muted-foreground hover:bg-accent hover:text-foreground"}`,onClick:()=>$e(ms),children:[ms.first_name," ",ms.last_name," — ",ms.email]},ms.id))})]}),Xe&&e.jsxs("div",{className:"border rounded-lg p-3 bg-muted/30 space-y-2 animate-in fade-in slide-in-from-top-1",children:[e.jsx("div",{className:"flex items-center justify-between",children:e.jsxs("p",{className:"text-xs font-semibold text-primary flex items-center gap-1.5",children:[e.jsx(mn,{className:"h-3.5 w-3.5"}),"Preview for ",Xe.first_name," ",Xe.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:"})," ",Xe.email]}),e.jsxs("p",{children:[e.jsx("span",{className:"text-muted-foreground text-xs",children:"Subject:"})," ",FS(he,Xe)]})]}),e.jsx(Wl,{}),e.jsx("div",{className:"text-sm whitespace-pre-wrap bg-background rounded p-2.5 max-h-40 overflow-y-auto border",children:FS(ve,Xe)})]}),e.jsxs("div",{className:"flex justify-end gap-2 pt-2",children:[e.jsxs(B,{variant:"outline",onClick:()=>{Se("composing"),$e(null)},children:[e.jsx(ka,{className:"h-4 w-4 mr-1"}),"Back to Edit"]}),e.jsxs(B,{onClick:Xs,disabled:X,className:"gap-2",children:[X?e.jsx(us,{className:"h-4 w-4 animate-spin"}):e.jsx(Rr,{className:"h-4 w-4"}),M?`Send First ${OS}`:`Send to ${T.length}`]})]})]})]}),e.jsx(FCe,{open:y,onOpenChange:x,hasPending:!!(g!=null&&g.hasPendingSes),pendingEmails:g==null?void 0:g.pendingEmails})]})}function dmn(){const s=tr(),{data:t}=Wy(),{data:n}=fU(),r=qQ(),{isGmailConnected:a,gmailEmail:i}=_f(),[l,o]=N.useState(null),[c,d]=N.useState(!1),[u,h]=N.useState(new Set),m=ey(new Date),f=Ad(m,30),g=T=>{if(!T)return null;const P=T.split(/[-/T]/);if(P.length<3)return null;const I=parseInt(P[1],10)-1,M=parseInt(P[2],10);return isNaN(I)||isNaN(M)?null:new Date(m.getFullYear(),I,M)},y=N.useMemo(()=>{if(!t)return[];const T=[];for(const P of t){if(P.birthday){const I=g(P.birthday);I&&(yd(I,m)||pj(I,m)&&rN(I,f))&&T.push({contact:P,type:"birthday",date:I,daysUntil:Iv(I,m),dateStr:P.birthday})}if(P.home_anniversary){const I=g(P.home_anniversary);I&&(yd(I,m)||pj(I,m)&&rN(I,f))&&T.push({contact:P,type:"anniversary",date:I,daysUntil:Iv(I,m),dateStr:P.home_anniversary})}if(P.wedding_anniversary){const I=g(P.wedding_anniversary);I&&(yd(I,m)||pj(I,m)&&rN(I,f))&&T.push({contact:P,type:"wedding_anniversary",date:I,daysUntil:Iv(I,m),dateStr:P.wedding_anniversary})}}return T.sort((P,I)=>P.daysUntil-I.daysUntil),T},[t]),x=T=>T==="birthday"?"Birthday":T==="wedding_anniversary"?"Wedding Anniversary":"Home Anniversary",_=async T=>{const P=(n==null?void 0:n.find(I=>I.name==="Call"))||(n==null?void 0:n[0]);if(P)try{await r.mutateAsync({contactId:T.contact.id,actionTypeId:P.id,notes:`${x(T.type)} outreach`}),h(I=>new Set(I).add(`${T.contact.id}-${T.type}`)),xa({title:"Touch logged!",description:`Logged outreach for ${T.contact.first_name}`})}catch{xa({title:"Error",description:"Failed to log touch",variant:"destructive"})}},b=T=>{const P=`${T.contact.first_name}${T.contact.last_name?" "+T.contact.last_name:""}`,I=T.type==="birthday"?"birthday":T.type==="wedding_anniversary"?"wedding_anniversary":"home_anniversary",M=new URLSearchParams({cardType:I,contactId:T.contact.id,name:P,...T.contact.address?{address:T.contact.address}:{},...(T.type==="anniversary"||T.type==="wedding_anniversary")&&T.dateStr?{date:T.dateStr}:{}});s(`/mission-control/card-studio?${M.toString()}`)},k=T=>T===0?"Today!":T===1?"Tomorrow":`${T} days`,A=T=>T===0?"bg-red-500/15 text-red-600 dark:text-red-400 border-red-500/30":T<=3?"bg-amber-500/15 text-amber-600 dark:text-amber-400 border-amber-500/30":T<=7?"bg-blue-500/15 text-blue-600 dark:text-blue-400 border-blue-500/30":"bg-muted text-muted-foreground border-border";return e.jsxs(e.Fragment,{children:[e.jsxs(_e,{children:[e.jsx(zt,{className:"pb-3",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs(qt,{className:"text-lg flex items-center gap-2",children:[e.jsx(ld,{className:"h-5 w-5 text-primary"}),"Upcoming Milestones",e.jsx(We,{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(De,{className:"space-y-2",children:[y.length===0&&e.jsxs("div",{className:"text-center py-8 text-muted-foreground",children:[e.jsx(Fm,{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((T,P)=>{var z,$;const I=`${T.contact.id}-${T.type}`,M=u.has(I),L=`${((z=T.contact.first_name)==null?void 0:z[0])||""}${(($=T.contact.last_name)==null?void 0:$[0])||""}`.toUpperCase();return e.jsxs("div",{className:Ot("p-3 rounded-lg border transition-colors",T.daysUntil===0&&T.type==="birthday"?"bg-pink-500/10 border-pink-500/30 dark:bg-pink-900/20 dark:border-pink-800/40":T.daysUntil===0&&(T.type==="anniversary"||T.type==="wedding_anniversary")?"bg-blue-500/10 border-blue-500/30 dark:bg-blue-900/20 dark:border-blue-800/40":T.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(Ua,{className:Ot("h-10 w-10",T.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(qa,{className:Ot("text-xs font-medium",T.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:L})}),e.jsx("span",{className:"absolute -bottom-1.5 -right-1.5 text-base leading-none drop-shadow-sm",children:T.type==="birthday"?"🎂":T.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:[T.contact.first_name," ",T.contact.last_name||""]}),e.jsx(We,{variant:"outline",className:Ot("text-[10px] shrink-0 whitespace-nowrap",A(T.daysUntil)),children:k(T.daysUntil)})]}),e.jsxs("div",{className:Ot("text-xs flex items-center gap-1.5 mt-0.5",T.type==="birthday"?"text-pink-600/80 dark:text-pink-400/80":"text-blue-600/80 dark:text-blue-400/80"),children:[T.type==="birthday"?e.jsxs(e.Fragment,{children:[e.jsx(Fm,{className:"h-3 w-3"})," Birthday"]}):T.type==="wedding_anniversary"?e.jsxs(e.Fragment,{children:[e.jsx(co,{className:"h-3 w-3"})," Wedding Anniversary"]}):e.jsxs(e.Fragment,{children:[e.jsx(_a,{className:"h-3 w-3"})," Home Anniversary"]}),e.jsx("span",{children:"·"}),e.jsx("span",{children:Js(T.date,"MMM d")})]})]})]}),e.jsxs("div",{className:"flex items-center gap-1 mt-2 pl-[52px]",children:[T.contact.phone&&e.jsx(B,{variant:"ghost",size:"icon",className:"h-7 w-7",title:"Call",asChild:!0,children:e.jsx("a",{href:`tel:${T.contact.phone}`,children:e.jsx(ga,{className:"h-3.5 w-3.5"})})}),T.contact.phone&&e.jsx(B,{variant:"ghost",size:"icon",className:"h-7 w-7",title:"Text",asChild:!0,children:e.jsx("a",{href:`sms:${T.contact.phone}`,children:e.jsx(xo,{className:"h-3.5 w-3.5"})})}),T.contact.email&&e.jsx(B,{variant:"ghost",size:"icon",className:"h-7 w-7",title:"Email",onClick:()=>{a?(o({id:T.contact.id,first_name:T.contact.first_name,last_name:T.contact.last_name,email:T.contact.email}),d(!0)):window.location.href=`mailto:${T.contact.email}`},children:e.jsx(mn,{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=${T.contact.id}`),children:e.jsx(na,{className:"h-3.5 w-3.5"})}),e.jsxs(B,{variant:"ghost",size:"sm",className:Ot("h-7 px-2 gap-1 text-xs",T.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 ${T.type==="birthday"?"birthday":"anniversary"} card`,onClick:()=>b(T),children:[e.jsx(Cn,{className:"h-3.5 w-3.5"}),e.jsx("span",{children:"Card"})]}),e.jsx(B,{variant:"ghost",size:"icon",className:Ot("h-7 w-7",M&&"text-green-600"),title:"Log a touch",disabled:M||r.isPending,onClick:()=>_(T),children:e.jsx(Hr,{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/${T.contact.id}`),children:e.jsx(da,{className:"h-3.5 w-3.5"})})]})]},`${I}-${P}`)})]})]}),a&&l&&e.jsx(Y_,{open:c,onOpenChange:d,contact:l,gmailEmail:i})]})}function umn(s){const[t,n]=N.useState([]),[r,a]=N.useState(!1),{data:i,isLoading:l}=mt({queryKey:["active-visitors",s],queryFn:async()=>{if(!s)return[];try{await H.rpc("cleanup_stale_visitors")}catch{}const{data:u}=await H.from("lead_site_active_visitors").select("*").eq("lead_site_id",s).gte("last_seen_at",new Date(Date.now()-2*60*1e3).toISOString()).order("last_seen_at",{ascending:!1});if(!u)return[];const h=u.map(g=>g.contact_id).filter(Boolean);let m={};if(h.length>0){const{data:g}=await H.from("innercircle_contacts").select("id, first_name, last_name, email, phone").in("id",h);(g||[]).forEach(y=>{m[y.id]=y})}const f=u.map(g=>g.auth_user_id).filter(Boolean);if(f.length>0){const{data:g}=await H.from("lead_site_consumer_profiles").select("user_id, name, phone, contact_id").eq("lead_site_id",s).in("user_id",f);(g||[]).forEach(y=>{const x=u.find(_=>_.auth_user_id===y.user_id);x&&!x.contact_id&&y.contact_id&&(x.contact_id=y.contact_id),x&&!m[x.contact_id||""]&&y.name&&(m[x.contact_id||x.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(g=>{var y,x;return{...g,contact_name:m[g.contact_id||g.auth_user_id||""]?`${m[g.contact_id||g.auth_user_id||""].first_name} ${m[g.contact_id||g.auth_user_id||""].last_name||""}`.trim():null,contact_email:((y=m[g.contact_id||g.auth_user_id||""])==null?void 0:y.email)||null,contact_phone:((x=m[g.contact_id||g.auth_user_id||""])==null?void 0:x.phone)||null}})},enabled:!!s,refetchInterval:6e4});N.useEffect(()=>{if(!s)return;const u=H.channel(`active-visitors-${s}`).on("postgres_changes",{event:"*",schema:"public",table:"lead_site_active_visitors",filter:`lead_site_id=eq.${s}`},h=>{h.eventType==="INSERT"?n(m=>m.find(g=>g.id===h.new.id)?m:[h.new,...m]):h.eventType==="UPDATE"?n(m=>m.map(f=>f.id===h.new.id?{...f,...h.new}:f)):h.eventType==="DELETE"&&n(m=>m.filter(f=>f.id!==h.old.id))}).subscribe(h=>{h==="SUBSCRIBED"&&a(!0)});return()=>{H.removeChannel(u)}},[s]);const o=r&&t.length>0?hmn([...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 hmn(s){const t=new Set;return s.filter(n=>t.has(n.id)?!1:(t.add(n.id),!0))}const mmn={property_view:{label:"Viewed",icon:da,color:"text-blue-500",bgColor:"bg-blue-500/10"},new_lead:{label:"New Lead",icon:Yl,color:"text-emerald-500",bgColor:"bg-emerald-500/10"},saved_listing:{label:"Saved",icon:co,color:"text-rose-500",bgColor:"bg-rose-500/10"}};function pmn(){const{user:s}=Ls(),t=tr(),{isGmailConnected:n,gmailEmail:r}=_f(),{leadSite:a}=Qx(),{count:i}=umn(a==null?void 0:a.id),[l,o]=N.useState(!1),[c,d]=N.useState(null),{data:u,isLoading:h}=mt({queryKey:["lead-site-activity",s==null?void 0:s.id],queryFn:async()=>{const{data:_,error:b}=await H.rpc("get_lead_site_activity",{_user_id:s.id});if(b)throw b;return _},enabled:!!s,refetchInterval:6e4});if(h||!(u!=null&&u.has_site))return null;const m=(u.activities||[]).filter(_=>_.visitor_name&&_.visitor_name!=="Site Visitor"),f=m.filter(_=>_.activity_type==="new_lead"),g=(u.activities||[]).filter(_=>_.activity_type==="property_view").length,y=(u.activities||[]).filter(_=>_.activity_type==="saved_listing").length,x=_=>{if(_.visitor_email)if(n){const b=(_.visitor_name||"").split(" ");d({id:_.contact_id||"",first_name:b[0]||"",last_name:b.slice(1).join(" ")||null,email:_.visitor_email}),o(!0)}else window.location.href=`mailto:${_.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(au,{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(vi,{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(Yl,{className:"h-4 w-4 text-emerald-500"}),e.jsxs("div",{children:[e.jsx("p",{className:"text-lg font-bold text-emerald-600 dark:text-emerald-400",children:f.length}),e.jsx("p",{className:"text-[10px] text-muted-foreground",children:"New Leads"})]})]}),e.jsxs("div",{className:"flex items-center gap-2 p-3 rounded-lg bg-blue-500/5 border border-blue-200 dark:border-blue-800",children:[e.jsx(da,{className:"h-4 w-4 text-blue-500"}),e.jsxs("div",{children:[e.jsx("p",{className:"text-lg font-bold text-blue-600 dark:text-blue-400",children:g}),e.jsx("p",{className:"text-[10px] text-muted-foreground",children:"Views"})]})]}),e.jsxs("div",{className:"flex items-center gap-2 p-3 rounded-lg bg-rose-500/5 border border-rose-200 dark:border-rose-800",children:[e.jsx(co,{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((_,b)=>{const k=mmn[_.activity_type],A=k.icon,T=nc(new Date(_.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 ${k.bgColor}`,children:e.jsx(A,{className:`h-3.5 w-3.5 ${k.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:()=>{_.contact_id&&t(`/mission-control/contacts/${_.contact_id}`)},children:_.visitor_name}),e.jsxs("div",{className:"flex items-center gap-2 text-[11px] text-muted-foreground",children:[e.jsx("span",{children:k.label}),_.mls_number&&e.jsxs("span",{children:["· MLS# ",_.mls_number]}),_.lead_type&&e.jsxs("span",{children:["· ",_.lead_type]}),e.jsxs("span",{children:["· ",T]})]})]}),e.jsxs("div",{className:"flex items-center gap-0.5 shrink-0",children:[_.visitor_email&&e.jsx(B,{variant:"ghost",size:"sm",className:"h-7 w-7 p-0 text-primary",onClick:()=>x(_),children:e.jsx(mn,{className:"h-3.5 w-3.5"})}),_.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:${_.visitor_phone}`,children:e.jsx(ga,{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:${_.visitor_phone}`,children:e.jsx(xo,{className:"h-3.5 w-3.5"})})]}),_.contact_id&&e.jsx(B,{variant:"ghost",size:"sm",className:"h-7 w-7 p-0",onClick:()=>t(`/mission-control/contacts/${_.contact_id}`),children:e.jsx(Qa,{className:"h-3.5 w-3.5"})})]})]},`${_.activity_type}-${_.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(vi,{className:"h-3.5 w-3.5 ml-1"})]})]}):e.jsx(_e,{children:e.jsxs(De,{className:"p-6 text-center",children:[e.jsx(gg,{className:"h-8 w-8 text-muted-foreground/30 mx-auto mb-2"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"No actionable website activity yet."}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:g>0?`${g} anonymous listing views recorded.`:"Lead engagement will appear here as visitors interact with your site."}),e.jsxs(B,{variant:"outline",size:"sm",className:"mt-3",onClick:()=>t("/mission-control/website-activity"),children:["View Full Activity",e.jsx(vi,{className:"h-3.5 w-3.5 ml-1"})]})]})}),n&&c&&e.jsx(Y_,{open:l,onOpenChange:o,contact:c,gmailEmail:r})]})}const iht={Crown:q0,FileText:Wr,Users:Yn,Globe:au,Star:Wa,Phone:ga,MessageSquare:xo,PenTool:PT,Video:na,Gift:Io},fmn={"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 gmn(){var Bt,Ct,Yt,Kt,Xs,zs;const s=tr(),{user:t}=Ls(),{data:n}=K_(),{data:r}=N4t(),{data:a}=Wy(),{data:i}=fU(),{data:l}=T4t(),o=bjs(),c=hqe(),d=yjs(90),u=qQ(),[h,m]=N.useState(null),[f,g]=N.useState(null),[y,x]=N.useState(!1),[_,b]=N.useState(""),[k,A]=N.useState(!1),[T,P]=N.useState(""),[I,M]=N.useState(mNe()),[L,z]=N.useState("cards"),[$,V]=N.useState(!1),[W,G]=N.useState(null),[X,te]=N.useState(null),[ne,me]=N.useState(""),{isGmailConnected:ue,gmailEmail:ce}=_f(),ae=()=>{const Vt=parseInt(T,10);if(isNaN(Vt)||Vt<1){xa({title:"Invalid goal",description:"Please enter a number greater than 0",variant:"destructive"});return}M(Vt),A4t(Vt),A(!1),xa({title:"Goal updated",description:`Weekly touch goal set to ${Vt}`})},he=()=>{P(I.toString()),A(!0)};N.useEffect(()=>{(async()=>{if(!(t!=null&&t.id))return;const{data:At}=await H.from("profiles").select("name").eq("id",t.id).single();At!=null&&At.name&&b(At.name.split(" ")[0])})()},[t==null?void 0:t.id]),N.useEffect(()=>{o.mutate()},[]);const xe=ey(new Date),ve=Ad(xe,7),ge=Vt=>{if(!Vt)return null;const At=Vt.split(/[-/T]/);if(At.length<3)return null;const Os=parseInt(At[1],10)-1,Nt=parseInt(At[2],10);return isNaN(Os)||isNaN(Nt)?null:new Date(xe.getFullYear(),Os,Nt)},be=(a==null?void 0:a.filter(Vt=>{const At=ge(Vt.birthday),Os=ge(Vt.home_anniversary);return At&&yd(At,xe)||Os&&yd(Os,xe)}))||[],Se=(a==null?void 0:a.filter(Vt=>{if(!Vt.birthday&&!Vt.home_anniversary)return!1;const At=Os=>{if(!Os)return!1;const Nt=ge(Os);return Nt?pj(Nt,xe)&&rN(Nt,ve):!1};return At(Vt.birthday)||At(Vt.home_anniversary)}).slice(0,5))||[],Ie=[],Me=(i==null?void 0:i.find(Vt=>Vt.name==="Call"))||(i==null?void 0:i[0]);for(const Vt of be){const At=ge(Vt.birthday),Os=ge(Vt.home_anniversary),Nt=At&&yd(At,xe),ms=Os&&yd(Os,xe);Nt&&Ie.push({contact:Vt,actionType:Me||{id:"special-date-birthday",name:"Birthday Call",icon:"Cake",color:"#EC4899",description:"Wish them happy birthday!",active:!0,sort_order:0,created_at:"",updated_at:""},planName:"🎂 Birthday Today!",relationshipTypeName:((Yt=(Ct=(Bt=Vt.tags)==null?void 0:Bt[0])==null?void 0:Ct.relationship_type)==null?void 0:Yt.name)||"",monthNumber:0,isSpecialDate:!0,specialDateType:"birthday"}),ms&&Ie.push({contact:Vt,actionType:Me||{id:"special-date-anniversary",name:"Anniversary Call",icon:"Home",color:"#8B5CF6",description:"Celebrate their home anniversary!",active:!0,sort_order:0,created_at:"",updated_at:""},planName:"🏠 Home Anniversary!",relationshipTypeName:((zs=(Xs=(Kt=Vt.tags)==null?void 0:Kt[0])==null?void 0:Xs.relationship_type)==null?void 0:zs.name)||"",monthNumber:0,isSpecialDate:!0,specialDateType:"anniversary"})}const Be=l!==void 0?l||[]:(a==null?void 0:a.slice(0,5).map((Vt,At)=>{var Nt,ms,Ys;const Os=i==null?void 0:i[At%((i==null?void 0:i.length)||1)];return Os?{contact:Vt,actionType:Os,planName:"Quick Touch",relationshipTypeName:((Ys=(ms=(Nt=Vt.tags)==null?void 0:Nt[0])==null?void 0:ms.relationship_type)==null?void 0:Ys.name)||"",monthNumber:0}:null}).filter(Boolean))||[],Ne=[...Ie,...Be],{data:Ge}=gU(7),Ce=(Ge||[]).filter(Vt=>yd(new Date(Vt.completed_at),xe)).length,Fe=Ce+Ne.length,Ae=(a==null?void 0:a.length)??0,Xe=Ie.length>0?`${Ie.length} celebration${Ie.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.`:Se.length>0?`${Se.length} milestone${Se.length===1?"":"s"} coming up this week — get ahead of them.`:"Consistency beats intensity. A few real conversations today is a win.",$e=async(Vt,At,Os)=>{await u.mutateAsync({contactId:Vt,actionTypeId:At,scriptUsedId:Os}),x(!1),g(null)},Ye=Vt=>{Vt.script?(g(Vt),x(!0)):$e(Vt.contact.id,Vt.actionType.id)},Je=Vt=>iht[Vt||"Phone"]||ga,Ke=Vt=>iht[Vt||"Users"]||Yn,st=(Vt,At)=>Vt.replace(/\{\{FirstName\}\}/g,At.first_name).replace(/\{\{LastName\}\}/g,At.last_name||"").replace(/\{\{AgentName\}\}/g,_||"there"),rt=(Vt,At)=>({Call:`Thinking of you, ${At}!`,Text:`Quick hello, ${At}`,Email:`Checking in, ${At}`,"Handwritten Note":`A note for ${At}`,Video:`Video message for ${At}`,Gift:`Something special for you, ${At}`})[Vt]||`Hello ${At}!`,Ze=(Vt,At,Os)=>{const Nt=`sms:${Vt}`;if(At&&Os){const ms=st(At,Os);return`${Nt}?body=${encodeURIComponent(ms)}`}return Nt},ht=(Vt,At,Os,Nt,ms)=>{const Ys=`mailto:${Vt}`,It=[];if(ms){const Ds=Os||rt(Nt||"Email",ms.first_name);if(It.push(`subject=${encodeURIComponent(Ds)}`),At){const As=st(At,ms);It.push(`body=${encodeURIComponent(As)}`)}}return It.length>0?`${Ys}?${It.join("&")}`:Ys};return e.jsxs(e.Fragment,{children:[e.jsxs(Qs,{title:"Mission Control",description:"Your relationship-first contact system",children:[e.jsxs("div",{className:"space-y-6 overflow-x-hidden",children:[e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3",children:[e.jsxs("div",{className:"flex items-center gap-2.5",children:[e.jsx("h1",{className:"text-2xl font-bold tracking-tight",children:"Mission Control"}),e.jsx("span",{className:"text-[10px] font-semibold uppercase tracking-wide px-1.5 py-0.5 rounded border border-amber-500 text-amber-600 dark:text-amber-400 bg-amber-500/10",children:"Beta"})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsxs(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(Rh,{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(Yn,{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(na,{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(sc,{className:"h-4 w-4"}),"Plans"]})]})]}),e.jsx(Zhn,{agentName:_,todayDone:Ce,todayTotal:Fe,focusLine:Xe,weekDone:c.actionsThisWeek,weekGoal:I,streak:c.streak,staleCount:d.count,sphereCount:Ae,onEditGoal:he,onStaleClick:()=>s("/mission-control/contacts?filter=not-touched-90"),onSphereClick:()=>s("/mission-control/contacts")}),e.jsx(pmn,{}),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(Qa,{className:"h-3 w-3"})]})]}),e.jsx("div",{className:"flex flex-wrap gap-2",children:n==null?void 0:n.filter(Vt=>Vt.active).map(Vt=>{const At=Ke(Vt.icon),Os=(r==null?void 0:r[Vt.id])||0,Nt=h===Vt.id,ms=fmn[Vt.name]||"bg-secondary text-secondary-foreground";return e.jsxs("button",{onClick:()=>{Nt?(m(null),s("/mission-control/contacts")):(m(Vt.id),s(`/mission-control/contacts?type=${Vt.id}`))},className:` inline-flex items-center gap-2 rounded-full border px-3 py-1.5 text-sm transition-all ${Nt?ms:"bg-card hover:bg-accent"} `,children:[e.jsx(At,{className:"h-3.5 w-3.5"}),e.jsx("span",{className:"font-medium",children:Vt.name}),e.jsx("span",{className:`rounded-full px-1.5 py-0.5 text-[11px] tabular-nums ${Nt?"bg-black/15":"bg-muted text-muted-foreground"}`,children:Os})]},Vt.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(We,{variant:"outline",className:"gap-1",children:[e.jsx(Cn,{className:"h-3 w-3"}),"Plan-based"]}),e.jsxs("div",{className:"ml-auto flex items-center gap-1 border rounded-lg p-0.5",children:[e.jsx(B,{variant:L==="cards"?"secondary":"ghost",size:"sm",className:"h-7 px-2",onClick:()=>z("cards"),title:"Card view",children:e.jsx(G0,{className:"h-4 w-4"})}),e.jsx(B,{variant:L==="table"?"secondary":"ghost",size:"sm",className:"h-7 px-2",onClick:()=>z("table"),title:"Table view",children:e.jsx(Kx,{className:"h-4 w-4"})})]})]}),e.jsx(_e,{children:e.jsx(De,{className:"p-4",children:Ne.length===0?e.jsxs("div",{className:"text-center py-8 text-muted-foreground",children:[e.jsx("p",{children:"No actions scheduled for today."}),e.jsx("p",{className:"text-sm mt-1",children:"Add contacts and enable touchpoint plans to get started."}),e.jsx(B,{variant:"outline",className:"mt-4",onClick:()=>s("/mission-control/plans"),children:"Manage Plans"})]}):L==="table"?e.jsx(nmn,{actions:Ne,onMarkComplete:$e,onViewScript:Ye,isLoading:u.isPending,buildSmsLink:Ze,buildEmailLink:ht,onGmailCompose:ue?Vt=>{G(Vt),V(!0)}:void 0}):e.jsxs("div",{className:"flex gap-3 overflow-x-auto pb-2",children:[Ne.map((Vt,At)=>{var Hs,Rs,en,Rn,Bn,Dn,Jn;const Os=Vt.isSpecialDate,Nt=Vt.specialDateType,ms=Os?Nt==="birthday"?Fm:_a:Je(((Hs=Vt.actionType)==null?void 0:Hs.icon)||null),Ys=Vt.contact.phone,It=Vt.contact.email,Ds=Os?Nt==="birthday"?"#EC4899":"#8B5CF6":((Rs=Vt.actionType)==null?void 0:Rs.color)||"#3B82F6",As=Os?Nt==="birthday"?"🎂 Birthday Today!":"🏠 Home Anniversary!":(en=Vt.actionType)==null?void 0:en.name;return e.jsxs("div",{className:`flex-shrink-0 w-[260px] border rounded-lg overflow-hidden ${Os?"ring-2 ring-offset-2":""}`,style:Os?{"--tw-ring-color":Ds}:void 0,children:[e.jsxs("div",{className:"p-3 text-white flex items-center gap-2",style:{backgroundColor:Ds},children:[e.jsx(ms,{className:"h-4 w-4"}),e.jsx("span",{className:"font-medium text-sm",children:As})]}),e.jsxs("div",{className:"p-3 space-y-2",children:[e.jsxs("button",{onClick:()=>s(`/mission-control/contacts/${Vt.contact.id}`),className:"font-medium text-sm hover:text-primary hover:underline transition-colors text-left",children:[Vt.contact.first_name," ",Vt.contact.last_name]}),e.jsxs("div",{className:"flex gap-1.5",children:[Ys&&e.jsxs(e.Fragment,{children:[e.jsxs("a",{href:`tel:${Vt.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(ga,{className:"h-3 w-3"}),"Call"]}),e.jsxs("a",{href:Ze(Vt.contact.phone,(Rn=Vt.script)==null?void 0:Rn.script_body,Vt.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(xo,{className:"h-3 w-3"}),"Text"]})]}),It&&(ue?e.jsxs("button",{onClick:()=>{G({id:Vt.contact.id,first_name:Vt.contact.first_name,last_name:Vt.contact.last_name,email:Vt.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(mn,{className:"h-3 w-3"}),"Email"]}):e.jsxs("a",{href:ht(Vt.contact.email,(Bn=Vt.script)==null?void 0:Bn.script_body,(Dn=Vt.script)==null?void 0:Dn.email_subject,(Jn=Vt.actionType)==null?void 0:Jn.name,Vt.contact),className:"flex-1 flex items-center justify-center gap-1 px-2 py-1.5 bg-sky-500/10 hover:bg-sky-500/20 text-sky-600 dark:text-sky-400 rounded text-xs font-medium transition-colors",title:"Email",children:[e.jsx(mn,{className:"h-3 w-3"}),"Email"]}))]}),Os&&e.jsxs("button",{onClick:()=>{const ua=`${Vt.contact.first_name}${Vt.contact.last_name?" "+Vt.contact.last_name:""}`,Mr=Nt==="birthday"?"birthday":"home_anniversary",sn=new URLSearchParams({cardType:Mr,contactId:Vt.contact.id,name:ua,...Vt.contact.address?{address:Vt.contact.address}:{},...Nt==="anniversary"&&Vt.contact.home_anniversary?{date:Vt.contact.home_anniversary}:{}});s(`/mission-control/card-studio?${sn.toString()}`)},className:"w-full flex items-center justify-center gap-1.5 px-2 py-1.5 rounded text-xs font-semibold bg-gradient-to-r from-pink-500/15 to-violet-500/15 hover:from-pink-500/25 hover:to-violet-500/25 text-pink-600 dark:text-pink-400 transition-colors",children:[e.jsx(mn,{className:"h-3 w-3"}),"Send ",Nt==="birthday"?"Birthday":"Anniversary"," Card"]}),!Ys&&!It&&e.jsx("p",{className:"text-xs text-muted-foreground italic",children:"No contact info"}),e.jsxs("div",{className:"flex gap-1 flex-wrap",children:[Vt.relationshipTypeName&&e.jsx(We,{variant:"secondary",className:"text-xs",children:Vt.relationshipTypeName}),Vt.monthNumber>0&&e.jsxs(We,{variant:"outline",className:"text-xs",children:["Month ",Vt.monthNumber]})]}),Vt.script&&e.jsx(B,{size:"sm",variant:"outline",className:"w-full",onClick:()=>Ye(Vt),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:()=>{te(Vt.contact.id),me(`${Vt.contact.first_name} ${Vt.contact.last_name||""}`.trim())},children:[e.jsx(K0,{className:"h-3.5 w-3.5"}),"Snooze"]}),e.jsx(B,{size:"sm",className:"flex-1",onClick:()=>{var ua;return $e(Vt.contact.id,Vt.actionType.id,(ua=Vt.script)==null?void 0:ua.id)},disabled:u.isPending,children:"Mark Complete"})]})]})]},Vt.contact.id+At)}),e.jsx("div",{className:"flex-shrink-0 w-[100px] border rounded-lg flex items-center justify-center",children:e.jsxs(qd,{children:[e.jsx(Vd,{asChild:!0,children:e.jsxs(B,{variant:"ghost",className:"h-full w-full",children:[e.jsx(Iy,{className:"h-5 w-5 mr-2"}),"More"]})}),e.jsx(Ld,{children:e.jsx(ba,{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(Cu,{className:"h-3.5 w-3.5 text-orange-500"}),"This week's momentum"]}),e.jsxs("span",{className:"text-xs tabular-nums text-muted-foreground",children:[c.actionsThisWeek," of ",I," touches"]})]}),e.jsx(ro,{value:Math.min(c.actionsThisWeek/I*100,100),className:"h-2.5 w-full max-w-full"}),e.jsx("p",{className:"mt-2 text-xs text-muted-foreground",children:c.actionsThisWeek>=I?"Goal hit for the week — anything else is bonus.":`${I-c.actionsThisWeek} more to hit your goal.`})]}),e.jsx(Bs,{open:k,onOpenChange:A,children:e.jsxs(Fs,{className:"sm:max-w-[360px]",children:[e.jsxs(qs,{children:[e.jsx($s,{children:"Set Weekly Goal"}),e.jsx(Ar,{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(re,{htmlFor:"weekly-goal-ic",children:"Weekly touch goal"}),e.jsx(we,{id:"weekly-goal-ic",type:"number",min:"1",value:T,onChange:Vt=>P(Vt.target.value),placeholder:"20",onKeyDown:Vt=>{Vt.key==="Enter"&&ae()}})]}),e.jsx(B,{onClick:ae,className:"w-full",children:"Save Goal"})]})]})}),e.jsxs("div",{className:"grid md:grid-cols-2 gap-6",children:[e.jsx(q4t,{}),e.jsx(dmn,{})]})]}),e.jsx(Bs,{open:y,onOpenChange:x,children:e.jsxs(Fs,{className:"max-w-md",children:[e.jsx(qs,{children:e.jsx($s,{className:"flex items-center gap-2",children:f&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"w-3 h-3 rounded-full",style:{backgroundColor:f.actionType.color||"#3B82F6"}}),f.actionType.name," Script"]})})}),f&&f.script&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"text-sm text-muted-foreground",children:["For: ",e.jsxs("span",{className:"font-medium text-foreground",children:[f.contact.first_name," ",f.contact.last_name]})]}),e.jsx("div",{className:"bg-muted p-4 rounded-lg",children:e.jsx("p",{className:"whitespace-pre-wrap",children:st(f.script.script_body,f.contact)})}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(B,{variant:"outline",className:"flex-1",onClick:()=>x(!1),children:"Close"}),e.jsx(B,{className:"flex-1",onClick:()=>{var Vt;return $e(f.contact.id,f.actionType.id,(Vt=f.script)==null?void 0:Vt.id)},disabled:u.isPending,children:"Mark Complete"})]})]})]})}),e.jsx(Xhn,{})]}),ue&&W&&e.jsx(Y_,{open:$,onOpenChange:V,contact:W,gmailEmail:ce}),e.jsx(BCe,{open:!!X,onOpenChange:Vt=>!Vt&&te(null),contactId:X||"",contactName:ne})]})}const xmn=[{value:"bidirectional",label:"Two-Way",icon:mg,tooltip:"Sync contacts in both directions"},{value:"push_only",label:"Push Only",icon:Om,tooltip:"Only push Agent OS → BoldTrail"},{value:"pull_only",label:"Pull Only",icon:Wf,tooltip:"Only pull BoldTrail → Agent OS"}];function a7e({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(Y9,{type:"single",value:s,onValueChange:a=>{a&&t(a)},className:"justify-start",children:xmn.map(a=>e.jsxs(wu,{children:[e.jsx(ju,{asChild:!0,children:e.jsxs(PD,{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(nu,{children:a.tooltip})]},a.value))})]})}function oht(){const s=as(),[t,n]=N.useState(!1),[r,a]=N.useState(null),[i,l]=N.useState(!1),[o,c]=N.useState(!1),[d,u]=N.useState(null),[h,m]=N.useState(null),[f,g]=N.useState(0),y=N.useRef(!1),{data:x}=mt({queryKey:["boldtrail-status"],queryFn:async()=>{const{data:L,error:z}=await H.functions.invoke("boldtrail-sync",{body:{action:"status"}});if(z)throw z;return L}}),_=(x==null?void 0:x.sync_direction)||"bidirectional",b=d??_,k=_t({mutationFn:async()=>{const{data:L,error:z}=await H.functions.invoke("boldtrail-sync",{body:{action:"sync_preview"}});if(z)throw z;if(L!=null&&L.error)throw new Error(L.error);return L},onSuccess:L=>{u(null),a(L),n(!0)},onError:L=>{ie.error(L.message||"Failed to generate sync preview")}}),A=_t({mutationFn:async()=>{y.current=!1,m("Initializing sync..."),g(5);const{data:L,error:z}=await H.functions.invoke("boldtrail-sync",{body:{action:"sync",phase:"init",sync_direction:b}});if(z)throw z;if(L!=null&&L.error)throw new Error(L.error);const $=L;let V=$.sync_log_id,W=$.next_phase,G=$.next_offset,X=$.push_total||0,te=$.pull_total||0,ne=$.update_total||0,me=0,ue=0,ce=0;for(;W!=="finalize"&&!y.current;){const xe=X+te+ne;W==="fetch_bt"?m("Fetching BoldTrail contacts..."):W==="analyze"?(m("Analyzing contacts..."),g(15)):W==="push"?(m(`Pushing contacts to BoldTrail... (${me}/${X})`),g(xe>0?me/xe*90:0)):W==="pull"?(m(`Pulling contacts from BoldTrail... (${ue}/${te})`),g(xe>0?(X+ue)/xe*90:0)):W==="update"&&(m(`Updating existing contacts... (${ce}/${ne})`),g(xe>0?(X+te+ce)/xe*90:0));const{data:ve,error:ge}=await H.functions.invoke("boldtrail-sync",{body:{action:"sync",phase:W,offset:G,sync_log_id:V,sync_direction:b}});if(ge)throw ge;if(ve!=null&&ve.error)throw new Error(ve.error);const be=ve;me+=be.chunk_pushed||0,ue+=be.chunk_pulled||0,ce+=be.chunk_updated||0,be.push_total!==void 0&&(X=be.push_total||0),be.pull_total!==void 0&&(te=be.pull_total||0),be.update_total!==void 0&&(ne=be.update_total||0),be.progress&&m(be.progress),W=be.next_phase,G=be.next_offset}m("Finalizing sync..."),g(95);const{data:ae,error:he}=await H.functions.invoke("boldtrail-sync",{body:{action:"sync",phase:"finalize",sync_log_id:V,sync_direction:b}});if(he)throw he;return g(100),ae},onSuccess:L=>{m(null),g(0),n(!1),s.invalidateQueries({queryKey:["boldtrail-status"]}),s.invalidateQueries({queryKey:["innercircle-contacts"]}),s.invalidateQueries({queryKey:["innercircle-contact-counts"]}),s.invalidateQueries({queryKey:["contacts-last-touch"]});const z=[`Pushed ${L.contacts_pushed||0}`,`pulled ${L.contacts_pulled||0}`,`updated ${L.contacts_updated||0}`,`skipped ${L.contacts_skipped||0} duplicates`];ie.success(`Sync complete! ${z.join(", ")}.`)},onError:L=>{m(null),g(0),ie.error(L.message||"Sync failed")}});if(!(x!=null&&x.connected))return null;const T=b==="pull_only"?0:(r==null?void 0:r.to_push)??0,P=b==="push_only"?0:(r==null?void 0:r.to_pull)??0,I=(r==null?void 0:r.to_update)??0,M=T>0||P>0||I>0;return e.jsxs(e.Fragment,{children:[e.jsxs(wu,{children:[e.jsx(ju,{asChild:!0,children:e.jsx(B,{variant:"outline",size:"icon",onClick:()=>k.mutate(),disabled:k.isPending,className:"shrink-0",children:k.isPending?e.jsx(oo,{className:"h-4 w-4 animate-spin"}):e.jsx(mg,{className:"h-4 w-4 text-emerald-600"})})}),e.jsx(nu,{children:"Sync with BoldTrail"})]}),e.jsx(Bs,{open:t,onOpenChange:L=>{A.isPending||n(L)},children:e.jsxs(Fs,{className:"sm:max-w-lg",children:[e.jsxs(qs,{children:[e.jsxs($s,{className:"flex items-center gap-2",children:[e.jsx(mg,{className:"h-5 w-5 text-emerald-600"}),"Sync Preview"]}),e.jsx(Ar,{children:"Review what will happen when you sync your contacts."})]}),r&&e.jsxs("div",{className:"space-y-4",children:[e.jsx(a7e,{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:T}),e.jsxs("p",{className:"text-xs text-muted-foreground flex items-center justify-center gap-1",children:[e.jsx(Om,{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:P}),e.jsxs("p",{className:"text-xs text-muted-foreground flex items-center justify-center gap-1",children:[e.jsx(Wf,{className:"h-3 w-3"})," Pull to Agent OS"]})]}),e.jsxs("div",{className:"rounded-lg border p-3 text-center",children:[e.jsx("p",{className:"text-2xl font-bold text-amber-600",children:I}),e.jsxs("p",{className:"text-xs text-muted-foreground flex items-center justify-center gap-1",children:[e.jsx(k9,{className:"h-3 w-3"})," To update"]})]}),e.jsxs("div",{className:"rounded-lg border p-3 text-center",children:[e.jsx("p",{className:"text-2xl font-bold text-muted-foreground",children:r.already_synced}),e.jsxs("p",{className:"text-xs text-muted-foreground flex items-center justify-center gap-1",children:[e.jsx(Yn,{className:"h-3 w-3"})," Already synced"]})]})]}),e.jsxs("div",{className:"text-xs text-muted-foreground text-center",children:["Agent OS: ",r.agent_os_total," contacts · BoldTrail: ",r.boldtrail_total," contacts"]}),I>0&&e.jsxs("div",{className:"text-xs text-muted-foreground text-center bg-amber-50 dark:bg-amber-950/30 rounded-md p-2",children:[e.jsx(k9,{className:"h-3 w-3 inline mr-1"}),I," contacts have missing fields that will be filled from the other system"]}),T>0&&e.jsxs(Kv,{open:i,onOpenChange:l,children:[e.jsx(Yv,{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(Om,{className:"h-3 w-3 text-emerald-600"}),T," contacts to push to BoldTrail"]}),e.jsx(Xo,{className:`h-3 w-3 transition-transform ${i?"rotate-180":""}`})]})}),e.jsx(Zv,{children:e.jsxs("div",{className:"rounded border divide-y max-h-40 overflow-y-auto",children:[r.push_preview.map((L,z)=>e.jsxs("div",{className:"px-3 py-1.5 text-xs flex justify-between",children:[e.jsx("span",{className:"font-medium",children:L.name||"No name"}),e.jsx("span",{className:"text-muted-foreground",children:L.email})]},z)),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"]})]})})]}),P>0&&e.jsxs(Kv,{open:o,onOpenChange:c,children:[e.jsx(Yv,{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(Wf,{className:"h-3 w-3 text-blue-600"}),P," contacts to pull from BoldTrail"]}),e.jsx(Xo,{className:`h-3 w-3 transition-transform ${o?"rotate-180":""}`})]})}),e.jsx(Zv,{children:e.jsxs("div",{className:"rounded border divide-y max-h-40 overflow-y-auto",children:[r.pull_preview.map((L,z)=>e.jsxs("div",{className:"px-3 py-1.5 text-xs flex justify-between",children:[e.jsx("span",{className:"font-medium",children:L.name||"No name"}),e.jsx("span",{className:"text-muted-foreground",children:L.email})]},z)),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&&!A.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."}),A.isPending&&e.jsxs("div",{className:"space-y-2 py-2",children:[e.jsx(ro,{value:f||10,className:"h-2"}),e.jsx("p",{className:"text-xs text-muted-foreground text-center",children:h||"Sync in progress..."})]}),e.jsxs("div",{className:"flex gap-2 justify-end pt-2",children:[e.jsx(B,{variant:"outline",onClick:()=>n(!1),disabled:A.isPending,children:"Cancel"}),e.jsxs(B,{onClick:()=>A.mutate(),disabled:A.isPending||!M,className:"gap-2",children:[A.isPending?e.jsx(oo,{className:"h-4 w-4 animate-spin"}):e.jsx(mg,{className:"h-4 w-4"}),A.isPending?"Syncing...":"Sync Now"]})]})]})]})})]})}const ymn=()=>{const{user:s}=Ls();return mt({queryKey:["popby-items",s==null?void 0:s.id],queryFn:async()=>{const{data:t,error:n}=await H.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})},UCe=s=>{const{user:t}=Ls();return mt({queryKey:["popby-logs",t==null?void 0:t.id,s],queryFn:async()=>{let n=H.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})},dGe=()=>{const{user:s}=Ls();return mt({queryKey:["relationship-type-popby-defaults",s==null?void 0:s.id],queryFn:async()=>{const{data:t,error:n}=await H.from("relationship_type_popby_defaults").select("*");if(n)throw n;return t},enabled:!!s})},tIt=()=>{const{user:s}=Ls();return mt({queryKey:["contact-popby-settings",s==null?void 0:s.id],queryFn:async()=>{const{data:t,error:n}=await H.from("contact_popby_settings").select("*");if(n)throw n;return t},enabled:!!s})},vmn=()=>{const{data:s}=Wy();K_();const{data:t}=UCe(),{data:n}=tIt(),{data:r}=dGe(),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=ey(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(x=>i.get(x.relationship_type_id)).filter(x=>x!==void 0);y.length>0&&(u=Math.min(...y))}const h=a.get(d.id)||null,m=h?wj(o,ey(new Date(h))):null,f=m===null||m>=u,g=f&&m!==null?m-u:0;return{...d,lastPopby:h,daysSinceLastPopby:m,frequencyDays:u,isDue:f,daysOverdue:g}}).sort((d,u)=>u.daysOverdue-d.daysOverdue)},sIt=()=>vmn().filter(t=>t.isDue),bmn=()=>{const s=as(),{user:t}=Ls();return _t({mutationFn:async n=>{const{error:r}=await H.from("popby_items").insert({...n,owner_user_id:t==null?void 0:t.id});if(r)throw r},onSuccess:()=>{s.invalidateQueries({queryKey:["popby-items"]}),xa({title:"Popby item created!"})},onError:n=>{xa({title:"Error creating popby item",description:n.message,variant:"destructive"})}})},_mn=()=>{const s=as(),{user:t}=Ls();return _t({mutationFn:async n=>{const r=new Date().toISOString(),{error:a}=await H.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 H.from("action_types").select("id").ilike("name","Pop-By").eq("active",!0).maybeSingle();i!=null&&i.id&&await H.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"]}),xa({title:"Popby logged!"})},onError:n=>{xa({title:"Error logging popby",description:n.message,variant:"destructive"})}})},wmn=()=>{const s=as(),{user:t}=Ls();return _t({mutationFn:async n=>{const{error:r}=await H.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"]}),xa({title:"Frequency updated!"})},onError:n=>{xa({title:"Error updating frequency",description:n.message,variant:"destructive"})}})},jmn=()=>{const{data:s}=UCe(30),t=sIt(),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 Nmn(){const{user:s}=Ls();return mt({queryKey:["contact-touch-logs",s==null?void 0:s.id],queryFn:async()=>{const{data:t,error:n}=await H.from("contact_touch_logs").select("*").order("completed_at",{ascending:!1});if(n)throw n;return t},enabled:!!s})}function nIt(s){const{data:t}=Nmn(),{data:n}=tIt(),{data:r}=dGe(),{data:a}=Qhn();return N.useMemo(()=>{const i=a==null?void 0:a.find(x=>x.contact_id===s.id),l=i?new Date(i.snoozed_until):null,o=ey(new Date);if(l&&!rN(l,o))return{nextTouchDate:l,daysUntil:wj(l,o),status:"snoozed",frequencyDays:90,lastTouchDate:null,snoozedUntil:l};const d=((t==null?void 0:t.filter(x=>x.contact_id===s.id))||[]).sort((x,_)=>new Date(_.completed_at).getTime()-new Date(x.completed_at).getTime())[0],u=d?new Date(d.completed_at):null;let h=90;const m=n==null?void 0:n.find(x=>x.contact_id===s.id&&x.is_active);if(m)h=m.frequency_days;else if(s.tags&&s.tags.length>0){const x=s.tags.map(_=>{const b=r==null?void 0:r.find(k=>k.relationship_type_id===_.relationship_type_id);return b==null?void 0:b.frequency_days}).filter(_=>_!==void 0);x.length>0&&(h=Math.min(...x))}if(!u)return{nextTouchDate:null,daysUntil:null,status:"never-touched",frequencyDays:h,lastTouchDate:null,snoozedUntil:null};const f=Ad(ey(u),h),g=wj(f,o);let y;return g<0?y="overdue":g<=7?y="due-soon":y="on-track",{nextTouchDate:f,daysUntil:g,status:y,frequencyDays:h,lastTouchDate:u,snoozedUntil:null}},[s,t,n,r,a])}function x5e({contact:s}){const t=nIt(s),r=(()=>{switch(t.status){case"overdue":return{variant:"destructive",icon:Uo,text:`${Math.abs(t.daysUntil)} days overdue`,className:""};case"due-soon":return{variant:"secondary",icon:Xr,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:Hr,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:K0,text:`Snoozed until ${Js(t.snoozedUntil,"MMM d")}`,className:"bg-slate-100 text-slate-700 dark:bg-slate-800 dark:text-slate-300"};case"never-touched":return{variant:"outline",icon:ta,text:"Never touched",className:"border-dashed"}}})(),a=r.icon;return e.jsxs(We,{variant:r.variant,className:Ot("gap-1",r.className),children:[e.jsx(a,{className:"h-3 w-3"}),r.text]})}function kmn({contact:s,onLogTouch:t,onSnooze:n}){const r=nIt(s),a=emn(),[i,l]=N.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(Uo,{className:"h-5 w-5 text-destructive"});case"due-soon":return e.jsx(Xr,{className:"h-5 w-5 text-amber-600 dark:text-amber-400"});case"on-track":return e.jsx(Hr,{className:"h-5 w-5 text-emerald-600 dark:text-emerald-400"});case"snoozed":return e.jsx(K0,{className:"h-5 w-5 text-slate-600 dark:text-slate-400"});case"never-touched":return e.jsx(ta,{className:"h-5 w-5 text-muted-foreground"})}},d=()=>{switch(r.status){case"overdue":return`${Math.abs(r.daysUntil)} days overdue`;case"due-soon":return r.daysUntil===0?"Due today!":`Due in ${r.daysUntil} days`;case"on-track":return`On track - ${r.daysUntil} days remaining`;case"snoozed":return`Snoozed for ${r.daysUntil} more days`;case"never-touched":return"No touches logged yet"}},u=async()=>{await a.mutateAsync(s.id)};return e.jsxs(e.Fragment,{children:[e.jsxs(_e,{children:[e.jsx(zt,{className:"pb-2",children:e.jsxs(qt,{className:"text-sm font-medium flex items-center gap-2",children:[e.jsx(ta,{className:"h-4 w-4"}),"Next Touch"]})}),e.jsxs(De,{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[c(),e.jsx("span",{className:Ot("font-medium",o()),children:d()})]}),r.status==="snoozed"&&r.snoozedUntil&&e.jsxs("div",{className:"text-sm text-muted-foreground",children:[e.jsx("span",{className:"font-medium",children:"Snoozed until:"})," ",Js(r.snoozedUntil,"MMMM d, yyyy")]}),r.status!=="snoozed"&&r.nextTouchDate&&e.jsxs("div",{className:"text-sm text-muted-foreground",children:[e.jsx("span",{className:"font-medium",children:"Scheduled:"})," ",Js(r.nextTouchDate,"MMMM d, yyyy")]}),r.lastTouchDate&&e.jsxs("div",{className:"text-sm text-muted-foreground",children:[e.jsx("span",{className:"font-medium",children:"Last touch:"})," ",Js(r.lastTouchDate,"MMM d, yyyy")]}),r.status!=="snoozed"&&e.jsxs("div",{className:"text-xs text-muted-foreground border-t pt-2",children:["Touch frequency: Every ",r.frequencyDays," days"]}),r.status==="snoozed"&&e.jsxs("div",{className:"flex gap-2 pt-1",children:[e.jsxs(B,{size:"sm",variant:"outline",className:"flex-1",onClick:u,disabled:a.isPending,children:[e.jsx(hr,{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(K0,{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(BCe,{open:i,onOpenChange:l,contactId:s.id,contactName:`${s.first_name} ${s.last_name||""}`.trim()})]})}const WLe=768;function qU(){const[s,t]=N.useState(void 0);return N.useEffect(()=>{const n=window.matchMedia(`(max-width: ${WLe-1}px)`),r=()=>{t(window.innerWidthn.removeEventListener("change",r)},[]),!!s}function Smn(){const{user:s}=Ls(),{hasLeadSite:t,leadSite:n}=Qx(),{data:r,isLoading:a}=mt({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 H.from("lead_site_visitors").select("contact_id").eq("lead_site_id",n.id).not("contact_id","is",null),{data:l}=await H.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 Cmn={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"}},Amn={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 i7e({score:s,showScore:t=!1,showTooltip:n=!0,size:r="sm",className:a}){const i=Cmn[s.status],l=Amn[r],o=e.jsxs("div",{className:Ot("inline-flex items-center rounded-full font-medium",i.bgLightClass,i.textClass,l.badge,l.text,a),children:[e.jsx("span",{className:Ot("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(wu,{children:[e.jsx(ju,{asChild:!0,children:o}),e.jsx(nu,{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:Ot("font-bold",i.textClass),children:[s.score,"/100"]})]}),e.jsx(ro,{value:s.score,className:"h-2"}),e.jsxs("div",{className:"space-y-1.5 text-xs",children:[e.jsxs("div",{className:"flex justify-between",children:[e.jsx("span",{className:"text-muted-foreground",children:"Recency"}),e.jsxs("span",{children:[s.breakdown.recency,"/40"]})]}),e.jsxs("div",{className:"flex justify-between",children:[e.jsx("span",{className:"text-muted-foreground",children:"Touchpoints (12mo)"}),e.jsxs("span",{children:[s.breakdown.touchpoints,"/30"]})]}),e.jsxs("div",{className:"flex justify-between",children:[e.jsx("span",{className:"text-muted-foreground",children:"Transactions"}),e.jsxs("span",{children:[s.breakdown.transactions,"/20"]})]}),e.jsxs("div",{className:"flex justify-between",children:[e.jsx("span",{className:"text-muted-foreground",children:"Referrals"}),e.jsxs("span",{children:[s.breakdown.referrals,"/10"]})]})]}),s.daysSinceTouch!==null&&e.jsxs("p",{className:"text-xs text-muted-foreground pt-1 border-t",children:["Last contact: ",s.daysSinceTouch===0?"Today":`${s.daysSinceTouch} days ago`]}),s.daysSinceTouch===null&&e.jsx("p",{className:"text-xs text-muted-foreground pt-1 border-t italic",children:"Never contacted"})]})})]})}):o}const Tmn=[{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}],Jse=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]},Emn=({open:s,onOpenChange:t,relationshipTypes:n,onSuccess:r})=>{const{user:a}=Ls(),{toast:i}=Ci(),l=N.useRef(null),[o,c]=N.useState("upload"),[d,u]=N.useState([]),[h,m]=N.useState([]),[f,g]=N.useState({}),[y,x]=N.useState([]),[_,b]=N.useState([]),[k,A]=N.useState([]),[T,P]=N.useState(""),[I,M]=N.useState(!1),[L,z]=N.useState([]),[$,V]=N.useState(!1),[W,G]=N.useState(null);N.useEffect(()=>{!s||!(a!=null&&a.id)||(async()=>{const{data:Re}=await H.from("contact_custom_tags").select("id, name, color").eq("owner_user_id",a.id).order("name");b(Re||[])})()},[s,a==null?void 0:a.id]);const X=Re=>{A(Be=>Be.includes(Re)?Be.filter(Ne=>Ne!==Re):[...Be,Re])},te=async()=>{const Re=T.trim();if(!(!Re||!(a!=null&&a.id))){M(!0);try{const{data:Be,error:Ne}=await H.from("contact_custom_tags").insert({owner_user_id:a.id,name:Re}).select("id, name, color").single();if(Ne)throw Ne;Be&&(b(Ge=>[...Ge,Be].sort((Ce,Fe)=>Ce.name.localeCompare(Fe.name))),A(Ge=>[...Ge,Be.id]),P(""))}catch(Be){i({title:"Could not create tag",description:Be.message||"Try a different name.",variant:"destructive"})}finally{M(!1)}}},ne=()=>{c("upload"),u([]),m([]),g({}),x([]),A([]),P(""),z([]),G(null),l.current&&(l.current.value="")},me=()=>{ne(),t(!1)},ue=Re=>{const Be=Re.split(` `).map(Xe=>Xe.trim()).filter(Xe=>Xe);if(Be.length===0)return{headers:[],data:[]};const Ne=Xe=>{const $e=[];let Ye="",Je=!1;for(let Ke=0;Ke0&&(Ge[0]=Ge[0].replace(/^\uFEFF/,""));const Ce=new Map,Fe=Ge.map((Xe,$e)=>{let Ye=(Xe||"").trim();Ye||(Ye=`Column ${$e+1}`);const Je=Ce.get(Ye)||0;return Ce.set(Ye,Je+1),Je===0?Ye:`${Ye} (${Je+1})`}),Ae=Be.slice(1).map(Ne);return{headers:Fe,data:Ae}},ce=Re=>{var Ge;const Be=(Ge=Re.target.files)==null?void 0:Ge[0];if(!Be)return;const Ne=new FileReader;Ne.onload=Ce=>{var Ye;const Fe=(Ye=Ce.target)==null?void 0:Ye.result,{headers:Ae,data:Xe}=ue(Fe);if(Ae.length===0){i({title:"No data found",description:"The CSV file appears to be empty.",variant:"destructive"});return}u(Ae),m(Xe);const $e={};Ae.forEach(Je=>{const Ke=Je.toLowerCase().replace(/[_\s-]/g,"");Ke.includes("firstname")||Ke==="first"?$e.first_name=Je:Ke.includes("lastname")||Ke==="last"?$e.last_name=Je:Ke.includes("spouse")&&Ke.includes("email")?$e.spouse_email=Je:Ke.includes("spouse")||Ke.includes("partner")?$e.spouse_name=Je:Ke.includes("email")?$e.email=Je:Ke.includes("phone")||Ke.includes("mobile")||Ke.includes("cell")?$e.phone=Je:Ke.includes("address")||Ke.includes("street")?$e.address=Je:Ke==="city"?$e.city=Je:Ke==="state"||Ke==="province"?$e.state=Je:Ke==="zip"||Ke==="zipcode"||Ke==="postalcode"?$e.zip=Je:Ke.includes("company")||Ke.includes("organization")||Ke.includes("business")?$e.company_name=Je:Ke.includes("jobtitle")||Ke.includes("title")&&!Ke.includes("spouse")?$e.job_title=Je:Ke.includes("birthday")||Ke.includes("dob")||Ke.includes("birthdate")?$e.birthday=Je:Ke.includes("anniversary")||Ke.includes("homeanniversary")?$e.home_anniversary=Je:(Ke.includes("notes")||Ke.includes("comment"))&&($e.notes=Je)}),g($e),c("mapping")},Ne.readAsText(Be)},ae=(Re,Be)=>{g(Ne=>{if(Be==="none"){const{[Re]:Ge,...Ce}=Ne;return Ce}return{...Ne,[Re]:Be}})},he=Re=>{x(Be=>Be.includes(Re)?Be.filter(Ne=>Ne!==Re):[...Be,Re])},xe=async()=>{if(!(a!=null&&a.id))return;const{data:Re}=await H.from("innercircle_contacts").select("id, email, phone").eq("owner_user_id",a.id),Be=new Set((Re||[]).filter(Ce=>Ce.email).map(Ce=>Ce.email.toLowerCase())),Ne=new Set((Re||[]).filter(Ce=>Ce.phone).map(Ce=>Ce.phone.replace(/[^0-9]/g,""))),Ge=h.map(Ce=>{const Fe=Ke=>{const st=f[Ke];if(!st)return"";const rt=d.indexOf(st);return rt>=0?(Ce[rt]||"").trim():""},Ae=Fe("first_name"),Xe=Fe("email"),$e=Fe("phone"),Ye=Ae.length>0,Je=!!(Xe&&Be.has(Xe.toLowerCase())||$e&&Ne.has($e.replace(/[^0-9]/g,"")));return{first_name:Ae,last_name:Fe("last_name"),email:Xe,phone:$e,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:Ye,isDuplicate:Je,error:Ye?void 0:"First name is required"}});z(Ge),c("preview")},ve=Re=>{const Be=Re.trim().split(/\s+/);return{first_name:Be[0],last_name:Be.length>1?Be.slice(1).join(" "):null}},ge=async()=>{if(!(a!=null&&a.id))return;const Re=L.filter(Ce=>Ce.isValid);if(Re.length===0){i({title:"No valid contacts",description:"There are no valid contacts to import.",variant:"destructive"});return}V(!0);let Be=0,Ne=0,Ge=0;try{for(const Ce of Re)try{let Fe=null;if(Ce.email){const{data:$e}=await H.from("innercircle_contacts").select("id").eq("owner_user_id",a.id).eq("email",Ce.email).maybeSingle();Fe=$e}if(!Fe&&Ce.phone){const $e=Ce.phone.replace(/[^0-9]/g,""),{data:Ye}=await H.from("innercircle_contacts").select("id, phone").eq("owner_user_id",a.id).not("phone","is",null);if(Ye){const Je=Ye.find(Ke=>Ke.phone&&Ke.phone.replace(/[^0-9]/g,"")===$e);Je&&(Fe={id:Je.id})}}const Ae={owner_user_id:a.id,first_name:Ce.first_name,last_name:Ce.last_name||null,email:Ce.email||null,phone:Ce.phone||null,address:Ce.address||null,city:Ce.city||null,state:Ce.state||null,zip:Ce.zip||null,spouse_name:Ce.spouse_name||null,spouse_email:Ce.spouse_email||null,company_name:Ce.company_name||null,job_title:Ce.job_title||null,birthday:Jse(Ce.birthday),home_anniversary:Jse(Ce.home_anniversary),notes:Ce.notes||null};let Xe=null;if(Fe){const{data:$e}=await H.from("innercircle_contacts").select("*").eq("id",Fe.id).single();if($e){const Ye={},Je=["last_name","email","phone","address","city","state","zip","spouse_name","spouse_email","company_name","job_title","birthday","home_anniversary","notes"];for(const Ke of Je){const st=$e[Ke],rt=Ae[Ke];(!st||st==="")&&rt&&(Ye[Ke]=rt)}Object.keys(Ye).length>0&&await H.from("innercircle_contacts").update(Ye).eq("id",Fe.id)}Xe=Fe.id,Ne++}else{const{data:$e,error:Ye}=await H.from("innercircle_contacts").insert(Ae).select("id").single();Ye?(console.error("Insert error for contact:",Ce.first_name,Ye),Ge++):$e?(Xe=$e.id,y.length>0&&await H.from("innercircle_contact_tags").insert(y.map(Je=>({contact_id:$e.id,relationship_type_id:Je}))),Be++):Ge++}if(Xe&&k.length>0&&await H.from("contact_custom_tag_assignments").upsert(k.map($e=>({contact_id:Xe,tag_id:$e})),{onConflict:"contact_id,tag_id",ignoreDuplicates:!0}),Xe&&Ce.spouse_name){const $e=ve(Ce.spouse_name);let Ye=null;if(Ce.spouse_email){const{data:Ke}=await H.from("innercircle_contacts").select("id").eq("owner_user_id",a.id).eq("email",Ce.spouse_email).maybeSingle();Ye=Ke}if(!Ye){const{data:Ke}=await H.from("innercircle_contacts").select("id").eq("owner_user_id",a.id).eq("first_name",$e.first_name).eq("last_name",$e.last_name||Ce.last_name||"").maybeSingle();Ye=Ke}let Je=null;if(Ye){Je=Ye.id;const Ke=Jse(Ce.home_anniversary);Ke&&await H.from("innercircle_contacts").update({home_anniversary:Ke}).eq("id",Ye.id).is("home_anniversary",null)}else{const{data:Ke}=await H.from("innercircle_contacts").insert({owner_user_id:a.id,first_name:$e.first_name,last_name:$e.last_name||Ce.last_name||null,email:Ce.spouse_email||null,address:Ce.address||null,city:Ce.city||null,state:Ce.state||null,zip:Ce.zip||null,home_anniversary:Jse(Ce.home_anniversary),spouse_name:`${Ce.first_name}${Ce.last_name?" "+Ce.last_name:""}`,spouse_email:Ce.email||null,notes:`Spouse of ${Ce.first_name} ${Ce.last_name||""} (imported via CSV)`.trim()}).select("id").single();Ke&&(Je=Ke.id,Be++)}Je&&(await H.from("innercircle_contacts").update({spouse_contact_id:Je}).eq("id",Xe),await H.from("innercircle_contacts").update({spouse_contact_id:Xe}).eq("id",Je))}}catch(Fe){console.error("Error importing contact:",Fe),Ge++}G({created:Be,updated:Ne,failed:Ge}),c("result"),(Be>0||Ne>0)&&r(),i({title:"Import Complete",description:`${Be} created, ${Ne} updated${Ge>0?`, ${Ge} failed`:""}.`})}catch(Ce){console.error("Import error:",Ce),i({title:"Import Failed",description:Ce.message||"Failed to import contacts",variant:"destructive"})}finally{V(!1)}},be=L.filter(Re=>Re.isValid).length,Se=L.filter(Re=>!Re.isValid).length,Ie=L.filter(Re=>Re.isValid&&Re.isDuplicate).length,Me=be-Ie;return e.jsx(Bs,{open:s,onOpenChange:me,children:e.jsxs(Fs,{className:"max-w-3xl max-h-[85vh] overflow-hidden flex flex-col",children:[e.jsxs(qs,{children:[e.jsxs($s,{className:"flex items-center gap-2",children:[e.jsx(m5,{className:"h-5 w-5"}),"Import Contacts from CSV"]}),e.jsx(Ar,{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:ce,className:"hidden"}),e.jsx(ni,{className:"h-10 w-10 mx-auto text-muted-foreground mb-4"}),e.jsx("p",{className:"text-sm text-muted-foreground mb-4",children:"Click to upload or drag and drop a CSV file"}),e.jsx(B,{onClick:()=>{var Re;return(Re=l.current)==null?void 0:Re.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 Re=`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`,Be=new Blob([Re],{type:"text/csv"}),Ne=URL.createObjectURL(Be),Ge=document.createElement("a");Ge.href=Ne,Ge.download="contact_import_template.csv",Ge.click(),URL.revokeObjectURL(Ne)},children:[e.jsx(oi,{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(re,{className:"text-base font-medium",children:"Map CSV Columns to Contact Fields"}),e.jsx("div",{className:"grid gap-3",children:Tmn.map(Re=>e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsxs(re,{className:"w-40 text-sm",children:[Re.label,Re.required&&e.jsx("span",{className:"text-destructive ml-1",children:"*"})]}),e.jsxs(Ns,{value:f[Re.key]||"none",onValueChange:Be=>ae(Re.key,Be),children:[e.jsx(ws,{className:"w-48",children:e.jsx(ks,{placeholder:"Select column..."})}),e.jsxs(js,{children:[e.jsx(nt,{value:"none",children:"-- Not mapped --"}),d.map(Be=>e.jsx(nt,{value:Be,children:Be},Be))]})]})]},Re.key))})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsx(re,{className:"text-base font-medium",children:"Apply Relationship Types (optional)"}),e.jsx("div",{className:"flex flex-wrap gap-2",children:n.map(Re=>e.jsx(We,{variant:y.includes(Re.id)?"default":"outline",className:"cursor-pointer",onClick:()=>he(Re.id),children:Re.name},Re.id))})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsx(re,{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."}),_.length>0&&e.jsx("div",{className:"flex flex-wrap gap-2",children:_.map(Re=>{const Be=k.includes(Re.id);return e.jsxs(We,{variant:Be?"default":"outline",className:"cursor-pointer gap-1",style:Be&&Re.color?{backgroundColor:Re.color,borderColor:Re.color}:void 0,onClick:()=>X(Re.id),children:[Re.name,Be&&e.jsx(hr,{className:"h-3 w-3"})]},Re.id)})}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(we,{placeholder:"Create a new tag (e.g. Open House Oct 2026)",value:T,onChange:Re=>P(Re.target.value),onKeyDown:Re=>{Re.key==="Enter"&&(Re.preventDefault(),te())},className:"max-w-xs"}),e.jsxs(B,{type:"button",variant:"outline",size:"sm",onClick:te,disabled:!T.trim()||I,children:[I?e.jsx(us,{className:"h-4 w-4 animate-spin"}):e.jsx(nn,{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(Hr,{className:"h-4 w-4 text-primary"}),e.jsxs("span",{children:[Me," new"]})]}),Ie>0&&e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground",children:[e.jsx(Uo,{className:"h-4 w-4"}),e.jsxs("span",{children:[Ie," existing (will merge gaps)"]})]}),Se>0&&e.jsxs("div",{className:"flex items-center gap-2 text-destructive",children:[e.jsx(Uo,{className:"h-4 w-4"}),e.jsxs("span",{children:[Se," invalid"]})]})]}),Ie>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(Oa,{children:[e.jsx(Fa,{children:e.jsxs(un,{className:"bg-muted/30",children:[e.jsx(Mt,{children:"First Name"}),e.jsx(Mt,{children:"Last Name"}),e.jsx(Mt,{children:"Email"}),e.jsx(Mt,{children:"Phone"}),e.jsx(Mt,{children:"Status"})]})}),e.jsx(za,{children:L.slice(0,100).map((Re,Be)=>e.jsxs(un,{children:[e.jsx(gt,{children:Re.first_name}),e.jsx(gt,{children:Re.last_name}),e.jsx(gt,{children:Re.email}),e.jsx(gt,{children:Re.phone}),e.jsx(gt,{children:Re.isValid?Re.isDuplicate?e.jsx(We,{variant:"outline",className:"bg-accent text-accent-foreground",children:"Merge"}):e.jsx(We,{variant:"secondary",className:"bg-primary/10 text-primary",children:"New"}):e.jsx(We,{variant:"destructive",children:Re.error||"Invalid"})})]},Be))})]}),L.length>100&&e.jsxs("p",{className:"text-sm text-muted-foreground text-center py-2",children:["Showing first 100 of ",L.length," contacts"]})]})]}),o==="result"&&W&&e.jsxs("div",{className:"space-y-4 py-4 text-center",children:[e.jsx(Hr,{className:"h-12 w-12 mx-auto text-primary"}),e.jsx("h3",{className:"text-lg font-semibold",children:"Import Complete"}),e.jsxs("p",{className:"text-muted-foreground",children:[W.created," created, ",W.updated," merged"]}),W.failed>0&&e.jsxs("p",{className:"text-destructive",children:[W.failed," failed to import"]})]}),e.jsxs(Cr,{children:[o==="upload"&&e.jsx(B,{variant:"outline",onClick:me,children:"Cancel"}),o==="mapping"&&e.jsxs(e.Fragment,{children:[e.jsx(B,{variant:"outline",onClick:ne,children:"Back"}),e.jsx(B,{onClick:xe,disabled:!f.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:ge,disabled:$||be===0,children:$?e.jsxs(e.Fragment,{children:[e.jsx(us,{className:"mr-2 h-4 w-4 animate-spin"}),"Importing..."]}):`Import ${be} Contact${be!==1?"s":""}`})]}),o==="result"&&e.jsx(B,{onClick:me,children:"Done"})]})]})})};function Mmn(){return"contacts"in navigator&&"ContactsManager"in window}function Lmn(s){const t=[],n=s.split("BEGIN:VCARD").filter(r=>r.trim());for(const r of n){const a=r.split(/\r?\n/);let i="",l="",o="",c="",d="";for(const u of a){const h=u.replace(/^\s+/,"");if(h.startsWith("N:")||h.startsWith("N;")){const f=h.substring(h.indexOf(":")+1).split(";");l=(f[0]||"").trim(),i=(f[1]||"").trim()}if((h.startsWith("FN:")||h.startsWith("FN;"))&&!i){const f=h.substring(h.indexOf(":")+1).trim().split(" ");i=f[0]||"",l=f.slice(1).join(" ")}(h.startsWith("EMAIL")||h.match(/^item\d+\.EMAIL/i))&&!o&&(o=h.substring(h.indexOf(":")+1).trim()),(h.startsWith("TEL")||h.match(/^item\d+\.TEL/i))&&!c&&(c=h.substring(h.indexOf(":")+1).trim()),(h.startsWith("ADR")||h.match(/^item\d+\.ADR/i))&&!d&&(d=h.substring(h.indexOf(":")+1).split(";").map(g=>g.trim()).filter(Boolean).join(", "))}(i||l)&&t.push({first_name:i,last_name:l,email:o,phone:c,address:d})}return t}function Pmn({open:s,onOpenChange:t,onComplete:n}){Ls();const{data:r}=Wy(),a=e3e(),i=N.useRef(null),[l,o]=N.useState("choose"),[c,d]=N.useState([]),[u,h]=N.useState(new Set),[m,f]=N.useState(0),[g,y]=N.useState(0),x=Mmn(),_=N.useCallback(z=>{if(!r)return z;const $=new Set(r.filter(W=>W.email).map(W=>W.email.toLowerCase())),V=new Set(r.filter(W=>W.phone).map(W=>W.phone.replace(/\D/g,"")));return z.map(W=>{var te,ne;const G=(te=W.email)==null?void 0:te.toLowerCase(),X=(ne=W.phone)==null?void 0:ne.replace(/\D/g,"");return G&&$.has(G)?{...W,isDuplicate:!0,duplicateField:"email"}:X&&X.length>=7&&V.has(X)?{...W,isDuplicate:!0,duplicateField:"phone"}:W})},[r]),b=async()=>{try{const z=["name","email","tel","address"],$=await navigator.contacts.select(z,{multiple:!0});if(!$||$.length===0)return;const V=$.map(X=>{var me,ue,ce,ae;const ne=(((me=X.name)==null?void 0:me[0])||"").split(" ");return{first_name:ne[0]||"",last_name:ne.slice(1).join(" "),email:((ue=X.email)==null?void 0:ue[0])||"",phone:((ce=X.tel)==null?void 0:ce[0])||"",address:(ae=X.address)!=null&&ae[0]?[X.address[0].streetAddress,X.address[0].city,X.address[0].region,X.address[0].postalCode].filter(Boolean).join(", "):""}}),W=_(V);d(W);const G=new Set;W.forEach((X,te)=>{X.isDuplicate||G.add(te)}),h(G),o("preview")}catch(z){console.error("Contact Picker error:",z),xa({title:"Could not access contacts",description:"Please try the file upload option instead.",variant:"destructive"})}},k=z=>{var W;const $=(W=z.target.files)==null?void 0:W[0];if(!$)return;const V=new FileReader;V.onload=G=>{var ue;const X=(ue=G.target)==null?void 0:ue.result,te=Lmn(X);if(te.length===0){xa({title:"No contacts found",description:"The file didn't contain any valid contacts.",variant:"destructive"});return}const ne=_(te);d(ne);const me=new Set;ne.forEach((ce,ae)=>{ce.isDuplicate||me.add(ae)}),h(me),o("preview")},V.readAsText($),i.current&&(i.current.value="")},A=async()=>{const z=c.filter((V,W)=>u.has(W));if(z.length===0)return;o("importing");let $=0;for(const V of z)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}),$++,y(Math.round($/z.length*100))}catch(W){console.error(`Failed to import ${V.first_name} ${V.last_name}:`,W)}f($),o("done")},T=z=>{h($=>{const V=new Set($);return V.has(z)?V.delete(z):V.add(z),V})},P=()=>{u.size===c.length?h(new Set):h(new Set(c.map((z,$)=>$)))},I=z=>{z||(o("choose"),d([]),h(new Set),f(0),y(0),l==="done"&&n()),t(z)},M=c.filter(z=>z.isDuplicate).length,L=u.size;return e.jsx(Bs,{open:s,onOpenChange:I,children:e.jsxs(Fs,{className:"sm:max-w-lg max-h-[90vh]",children:[e.jsxs(qs,{children:[e.jsxs($s,{className:"flex items-center gap-2",children:[e.jsx($y,{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(Ar,{children:"Add contacts from your phone directly into Agent OS."})]}),l==="choose"&&e.jsxs("div",{className:"space-y-4 pt-2",children:[x&&e.jsxs(B,{onClick:b,className:"w-full h-auto py-4 flex flex-col items-center gap-2",children:[e.jsx($y,{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:[x&&e.jsx("div",{className:"absolute inset-0 flex items-center",children:e.jsx("span",{className:"w-full border-t"})}),x&&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:x?"outline":"default",onClick:()=>{var z;return(z=i.current)==null?void 0:z.click()},className:"w-full h-auto py-4 flex flex-col items-center gap-2",children:[e.jsx(ni,{className:"h-6 w-6"}),e.jsxs("div",{className:"text-center",children:[e.jsx("div",{className:"font-semibold",children:"Upload Contact File"}),e.jsx("div",{className:"text-xs opacity-80",children:x?"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:k,className:"hidden"}),!x&&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:P,children:u.size===c.length?"Deselect All":"Select All"})]}),e.jsx(lo,{className:"h-[350px] rounded-md border",children:e.jsx("div",{className:"divide-y",children:c.map((z,$)=>e.jsxs("div",{className:`flex items-start gap-3 p-3 cursor-pointer hover:bg-accent/50 transition-colors ${z.isDuplicate?"opacity-60":""}`,onClick:()=>T($),children:[e.jsx(Bi,{checked:u.has($),onCheckedChange:()=>T($),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:[z.first_name," ",z.last_name]}),z.isDuplicate&&e.jsxs(We,{variant:"secondary",className:"text-[10px] px-1.5 py-0 bg-amber-500/10 text-amber-600 border-amber-200",children:["Exists (",z.duplicateField,")"]})]}),e.jsxs("div",{className:"text-xs text-muted-foreground space-y-0.5 mt-0.5",children:[z.phone&&e.jsx("div",{children:z.phone}),z.email&&e.jsx("div",{className:"truncate",children:z.email})]})]})]},$))})}),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:A,disabled:L===0,children:["Import ",L," Contact",L!==1?"s":""]})]})]}),l==="importing"&&e.jsxs("div",{className:"flex flex-col items-center gap-4 py-8",children:[e.jsx(us,{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:[g,"% 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:`${g}%`}})})]}),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(pa,{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:()=>I(!1),className:"mt-2",children:"Done"})]})]})})}function Imn(s){return mt({queryKey:["video-share-recipients",s],queryFn:async()=>{if(!s)return[];const{data:t,error:n}=await H.from("video_share_recipients").select("*").eq("video_id",s).order("sent_at",{ascending:!1});if(n)throw n;return t},enabled:!!s})}function Dmn(){const{user:s}=Ls();return mt({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 H.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 Rmn(){const{user:s}=Ls();return mt({queryKey:["video-share-history",s==null?void 0:s.id],queryFn:async()=>{if(!(s!=null&&s.id))return[];const{data:t,error:n}=await H.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 rIt(){const{user:s}=Ls(),t=as();return _t({mutationFn:async n=>{if(!(s!=null&&s.id))throw new Error("Not authenticated");const{data:r,error:a}=await H.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 aIt(s){return`https://relzejiswnotikjgvjhz.supabase.co/functions/v1/track-video-share?t=${s}&e=open`}function iIt(s){return`https://relzejiswnotikjgvjhz.supabase.co/functions/v1/track-video-share?t=${s}&e=click`}const Omn=100;function Fmn({open:s,onOpenChange:t,contacts:n,isGmailConnected:r,isMassEmailReady:a,onSendComplete:i}){const l=tr(),o=Ya(),c=rIt(),[d,u]=N.useState([]),[h,m]=N.useState(!1),[f,g]=N.useState(""),[y,x]=N.useState(null),[_,b]=N.useState(""),[k,A]=N.useState(""),[T,P]=N.useState(!1),[I,M]=N.useState({done:0,total:0,failed:0}),L=n.filter(ne=>!!ne.email),z=n.length-L.length,$=L.length>Omn;N.useEffect(()=>{s&&(x(null),g(""),M({done:0,total:0,failed:0}))},[s]),N.useEffect(()=>{!s||!o||(m(!0),H.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:ne})=>{u(ne||[]),m(!1)}))},[s,o]),N.useEffect(()=>{if(!y)return;const ne=y.title||"a quick video";b(`I recorded a video for you — ${ne}`),A("Hey {{first_name}}! I recorded a quick video just for you. Click below to watch it:")},[y]);const V=d.filter(ne=>!f||(ne.title||"").toLowerCase().includes(f.toLowerCase())),W=(ne,me)=>{if(!y)return"";const ue=y.share_token?`https://video.relevelup.com/share/video/${y.share_token}`:"",ce=y.share_token?`https://video.relevelup.com/thumb/${y.share_token}`:y.thumbnail_url||"",ae=y.title||"Video Message",xe=k.replace(/\{\{first_name\}\}/gi,ne).split(/\n\n+/).map(be=>`

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

`).join(""),ve=me?iIt(me):ue,ge=me?``:"";return`
`},G=async()=>{if(!y)return;P(!0),M({done:0,total:L.length,failed:0});let ne=0,me=0;for(const ue of L)try{let ce;try{ce=(await c.mutateAsync({video_id:y.id,recipient_email:ue.email,recipient_name:`${ue.first_name} ${ue.last_name||""}`.trim(),contact_id:ue.id,sent_via:"gmail"})).share_token}catch(ge){console.warn("Tracking record failed for",ue.email,ge)}const ae=W(ue.first_name,ce),he=_.replace(/\{\{first_name\}\}/gi,ue.first_name),{data:xe,error:ve}=await H.functions.invoke("gmail-send",{body:{to:ue.email,subject:he,body:ae,contactId:ue.id}});if(ve||!(xe!=null&&xe.success))throw new Error((xe==null?void 0:xe.error)||(ve==null?void 0:ve.message)||"Send failed");ne+=1}catch(ce){console.error("Failed to send to",ue.email,ce),me+=1}finally{M({done:ne+me,total:L.length,failed:me}),await new Promise(ce=>setTimeout(ce,250))}P(!1),me===0?ie.success(`Video sent to ${ne} ${ne===1?"contact":"contacts"}!`):ie.warning(`Sent to ${ne}, ${me} failed. Check console for details.`),t(!1),i==null||i()},X=()=>{if(!y)return;const ne=W("there",void 0);l("/admin/email-campaigns/new",{state:{directRecipients:L.map(me=>({email:me.email,name:`${me.first_name} ${me.last_name||""}`.trim()})),initialSubject:_,initialBodyHtml:ne}}),t(!1)},te=!!y&&!!_.trim()&&L.length>0&&($?a:r);return e.jsx(Bs,{open:s,onOpenChange:t,children:e.jsxs(Fs,{className:"sm:max-w-[640px] max-h-[90vh] overflow-y-auto",children:[e.jsxs(qs,{children:[e.jsxs($s,{className:"flex items-center gap-2",children:[e.jsx(na,{className:"h-5 w-5 text-primary"}),"Send Video to ",L.length," ",L.length===1?"Contact":"Contacts"]}),e.jsxs(Ar,{children:[$?e.jsxs("span",{className:"flex items-center gap-1.5 text-amber-600",children:[e.jsx(um,{className:"h-3.5 w-3.5"}),L.length," recipients — will be sent as a Mass Email campaign"]}):e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx(mn,{className:"h-3.5 w-3.5"}),"Sent individually via your connected Gmail"]}),z>0&&e.jsxs("span",{className:"ml-2 text-xs text-muted-foreground",children:["(",z," skipped — no email)"]})]})]}),e.jsxs("div",{className:"space-y-4",children:[$&&!a&&e.jsxs("div",{className:"flex items-start gap-2 p-3 rounded-md bg-destructive/10 text-destructive text-sm",children:[e.jsx(Uo,{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 ",L.length," recipients."]})]}),!$&&!r&&e.jsxs("div",{className:"flex items-start gap-2 p-3 rounded-md bg-destructive/10 text-destructive text-sm",children:[e.jsx(Uo,{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(re,{children:"Choose a video"}),e.jsxs(B,{type:"button",variant:"ghost",size:"sm",className:"gap-1",onClick:()=>l("/innercircle/videos/record"),children:[e.jsx(nn,{className:"h-3.5 w-3.5"})," Record new"]})]}),e.jsxs("div",{className:"relative",children:[e.jsx(Gr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(we,{placeholder:"Search your video library...",value:f,onChange:ne=>g(ne.target.value),className:"pl-10"})]}),e.jsx("div",{className:"max-h-[220px] overflow-y-auto space-y-2 border rounded-md p-2",children:h?e.jsxs(e.Fragment,{children:[e.jsx(xn,{className:"h-14 w-full"}),e.jsx(xn,{className:"h-14 w-full"})]}):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(ne=>{const me=(y==null?void 0:y.id)===ne.id;return e.jsxs("button",{type:"button",onClick:()=>x(ne),className:`w-full flex items-center gap-3 p-2 rounded-md border text-left transition-colors ${me?"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:[ne.thumbnail_url?e.jsx("img",{src:ne.thumbnail_url,alt:"",className:"w-full h-full object-cover",referrerPolicy:"no-referrer"}):e.jsx(Rh,{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(dd,{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:ne.title||"Untitled Video"}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[ne.duration_seconds?`${Math.round(ne.duration_seconds)}s`:"",ne.created_at?` · ${new Date(ne.created_at).toLocaleDateString()}`:""]})]})]},ne.id)})})]}),e.jsx(Wl,{}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(re,{htmlFor:"bulk-video-subject",children:"Subject"}),e.jsx(we,{id:"bulk-video-subject",value:_,onChange:ne=>b(ne.target.value),placeholder:"I recorded a video for you"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs(re,{htmlFor:"bulk-video-message",children:["Personal message ",e.jsxs("span",{className:"text-xs text-muted-foreground",children:["(use ","{{first_name}}"," to personalize)"]})]}),e.jsx(Ws,{id:"bulk-video-message",value:k,onChange:ne=>A(ne.target.value),rows:4,className:"resize-y"})]}),T&&I.total>0&&e.jsxs("div",{className:"p-3 rounded-md bg-muted text-sm",children:["Sending… ",I.done," / ",I.total,I.failed>0&&e.jsxs("span",{className:"text-destructive ml-2",children:["(",I.failed," failed)"]})]}),e.jsxs("div",{className:"flex justify-end gap-2 pt-2",children:[e.jsx(B,{variant:"outline",onClick:()=>t(!1),disabled:T,children:"Cancel"}),$?e.jsxs(B,{onClick:X,disabled:!te,className:"gap-2",children:[e.jsx(um,{className:"h-4 w-4"}),"Continue in Mass Email"]}):e.jsxs(B,{onClick:G,disabled:!te||T,className:"gap-2",children:[T?e.jsx(us,{className:"h-4 w-4 animate-spin"}):e.jsx(Rr,{className:"h-4 w-4"}),T?"Sending…":`Send to ${L.length}`]})]})]})]})})}function pJ(){const s=Ya();return mt({queryKey:["drip-campaigns",s],queryFn:async()=>{if(!s)return[];const{data:t,error:n}=await H.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 zmn(s){return mt({queryKey:["drip-campaign",s],queryFn:async()=>{if(!s)return null;const{data:t,error:n}=await H.from("drip_campaigns").select("*").eq("id",s).maybeSingle();if(n)throw n;return t},enabled:!!s})}function Bmn(){const s=Ya(),t=as();return _t({mutationFn:async n=>{if(!s)throw new Error("Not authenticated");const{data:r,error:a}=await H.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 oIt(){const s=as();return _t({mutationFn:async({id:t,...n})=>{const{data:r,error:a}=await H.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 $mn(){const s=as();return _t({mutationFn:async t=>{const{error:n}=await H.from("drip_campaigns").delete().eq("id",t);if(n)throw n},onSuccess:()=>s.invalidateQueries({queryKey:["drip-campaigns"]})})}function uGe(){const s=Ya(),t=as();return _t({mutationFn:async n=>{if(!s)throw new Error("Not authenticated");const[{data:r,error:a},{data:i,error:l}]=await Promise.all([H.from("drip_campaigns").select("*").eq("id",n).single(),H.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 H.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 H.from("drip_campaign_steps").insert(d);if(u)throw u}return o},onSuccess:()=>t.invalidateQueries({queryKey:["drip-campaigns"]})})}function lIt(s){return mt({queryKey:["drip-campaign-steps",s],queryFn:async()=>{if(!s)return[];const{data:t,error:n}=await H.from("drip_campaign_steps").select("*").eq("campaign_id",s).order("step_order",{ascending:!0});if(n)throw n;return t},enabled:!!s})}function Umn(){const s=as();return _t({mutationFn:async t=>{const{data:n,error:r}=await H.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 qmn(){const s=as();return _t({mutationFn:async({id:t,campaign_id:n,...r})=>{const{data:a,error:i}=await H.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 Vmn(){const s=as();return _t({mutationFn:async({id:t,campaign_id:n})=>{const{error:r}=await H.from("drip_campaign_steps").delete().eq("id",t);if(r)throw r;return n},onSuccess:t=>s.invalidateQueries({queryKey:["drip-campaign-steps",t]})})}function Hmn(s){return mt({queryKey:["campaign-enrollments",s],queryFn:async()=>{if(!s)return[];const{data:t,error:n}=await H.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 Gmn(s){return mt({queryKey:["campaign-enrollment-count",s],queryFn:async()=>{if(!s)return 0;const{count:t,error:n}=await H.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 cIt(){const s=as();return _t({mutationFn:async({campaignId:t,contactIds:n})=>{const{data:r,error:a}=await H.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 Wmn(){const s=as();return _t({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 H.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 Kmn=[{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"}],qCe={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"},Ymn={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 Zmn({open:s,onOpenChange:t,subject:n,body:r,ownerUserId:a,stepLabel:i}){const[l,o]=N.useState(!1),[c,d]=N.useState(""),[u,h]=N.useState(""),[m,f]=N.useState("desktop"),[g,y]=N.useState(""),[x,_]=N.useState(!1);N.useEffect(()=>{if(!s)return;let k=!1;return(async()=>{var A,T;o(!0);try{const{data:P}=await H.auth.getSession();g||y(((T=(A=P==null?void 0:P.session)==null?void 0:A.user)==null?void 0:T.email)||"");const{data:I,error:M}=await H.functions.invoke("process-drip-campaigns",{body:{action:"preview",subject:n,body:r,owner_user_id:a||void 0}});if(M)throw M;if(k)return;d((I==null?void 0:I.html)||""),h((I==null?void 0:I.subject)||n)}catch{k||ie.error("Could not build preview")}finally{k||o(!1)}})(),()=>{k=!0}},[s,n,r,a]);const b=async()=>{if(g.trim()){_(!0);try{const{data:k,error:A}=await H.functions.invoke("process-drip-campaigns",{body:{action:"test_send",subject:n,body:r,to:g.trim(),owner_user_id:a||void 0}});if(A)throw A;k!=null&&k.success?ie.success(`Test email sent to ${g.trim()}`):ie.error((k==null?void 0:k.error)||"Could not send test email",{duration:1e4})}catch{ie.error("Could not send test email")}finally{_(!1)}}};return e.jsx(Bs,{open:s,onOpenChange:t,children:e.jsxs(Fs,{className:"sm:max-w-3xl max-h-[92vh] flex flex-col p-0 gap-0",children:[e.jsxs(qs,{className:"p-5 pb-3 border-b shrink-0",children:[e.jsxs($s,{children:["Email preview",i?` — ${i}`:""]}),e.jsx(Ar,{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:()=>f("desktop"),children:[e.jsx(hj,{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:()=>f("mobile"),children:[e.jsx($y,{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(us,{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(re,{className:"text-xs",children:"Send a test to"}),e.jsx(we,{type:"email",value:g,onChange:k=>y(k.target.value),placeholder:"you@email.com",className:"h-9",onKeyDown:k=>k.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:x||!g.trim(),children:[x?e.jsx(us,{className:"h-4 w-4 mr-1.5 animate-spin"}):e.jsx(Rr,{className:"h-4 w-4 mr-1.5"}),"Send test"]})]})]})]})})}function tO({userId:s,onSelect:t,onSelectVideo:n,triggerLabel:r="Library",triggerSize:a="sm",triggerVariant:i="outline",triggerClassName:l}){const[o,c]=N.useState(!1),[d,u]=N.useState([]),[h,m]=N.useState(!1),[f,g]=N.useState("");N.useEffect(()=>{!o||!s||(m(!0),H.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:x})=>{u(x||[]),m(!1)}))},[o,s]);const y=d.filter(x=>!f||(x.title||x.recipient_name||"").toLowerCase().includes(f.toLowerCase()));return e.jsxs(Bs,{open:o,onOpenChange:c,children:[e.jsx(Ao,{asChild:!0,children:e.jsxs(B,{variant:i,size:a,className:l||"gap-1.5 shrink-0",children:[e.jsx(Rh,{className:"h-3.5 w-3.5"}),r]})}),e.jsxs(Fs,{className:"max-w-lg max-h-[70vh] flex flex-col",children:[e.jsxs(qs,{children:[e.jsx($s,{children:"Select from Video Library"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Choose a video from your library"})]}),e.jsxs("div",{className:"relative mb-3",children:[e.jsx(Gr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(we,{placeholder:"Search videos...",value:f,onChange:x=>g(x.target.value),className:"pl-10"})]}),e.jsx("div",{className:"flex-1 overflow-y-auto space-y-2 min-h-0",children:h?e.jsxs(e.Fragment,{children:[e.jsx(xn,{className:"h-16 w-full"}),e.jsx(xn,{className:"h-16 w-full"})]}):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(x=>e.jsxs("button",{onClick:()=>{t(x.playback_url||""),n==null||n(x),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:x.thumbnail_url?e.jsx("img",{src:x.thumbnail_url,alt:"",className:"w-full h-full object-cover",referrerPolicy:"no-referrer",onError:_=>{const b=_.currentTarget.parentElement;if(b){_.currentTarget.remove();const k=document.createElement("span");k.innerHTML="🎬",k.className="text-lg",b.appendChild(k)}}}):e.jsx(na,{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:x.title||x.recipient_name||"Untitled Video"}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[x.duration_seconds?`${Math.round(x.duration_seconds)}s`:"",x.created_at?` · ${new Date(x.created_at).toLocaleDateString()}`:""]})]})]},x.id))})]})]})}function Xmn(){return mt({queryKey:["video-script-categories"],queryFn:async()=>{const{data:s,error:t}=await H.from("video_script_categories").select("*").order("sort_order");if(t)throw t;return s}})}function Qmn(s){return mt({queryKey:["video-scripts",s],queryFn:async()=>{let t=H.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 Jmn(){const{user:s}=Ls();return mt({queryKey:["user-video-scripts",s==null?void 0:s.id],queryFn:async()=>{if(!(s!=null&&s.id))return[];const{data:t,error:n}=await H.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 epn(){const{user:s}=Ls(),t=as();return _t({mutationFn:async n=>{if(!(s!=null&&s.id))throw new Error("Not authenticated");const{data:r,error:a}=await H.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 tpn(s){const{user:t}=Ls();return mt({queryKey:["agent-videos",t==null?void 0:t.id,s],queryFn:async()=>{if(!(t!=null&&t.id))return[];let n=H.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 spn(s){return mt({queryKey:["agent-video",s],queryFn:async()=>{const{data:t,error:n}=await H.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 G3(){const{user:s}=Ls(),t=as();return _t({mutationFn:async n=>{if(!(s!=null&&s.id))throw new Error("Not authenticated");const{data:r,error:a}=await H.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 npn(){const s=as();return _t({mutationFn:async({id:t,...n})=>{const{data:r,error:a}=await H.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 rpn(){const s=as();return _t({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 H.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 H.from("agent_videos").delete().eq("id",t);if(a)throw a}else{console.log("Soft deleting from database:",t);const{error:a}=await H.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 VCe(){const{user:s}=Ls();return mt({queryKey:["storage-usage",s==null?void 0:s.id],queryFn:async()=>{if(!(s!=null&&s.id))return null;const{data:t,error:n}=await H.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 dIt(){const{data:s,isLoading:t}=VCe(),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 sO(s){const{data:t,error:n}=await H.functions.invoke("bunny-upload",{body:{action:"create",title:s,isAgentVideo:!0}});if(n)throw n;return t}async function nO(s){const{data:t,error:n}=await H.functions.invoke("bunny-upload",{body:{action:"upload-url",videoId:s,isAgentVideo:!0}});if(n)throw n;return t}async function F5(s){const{data:t,error:n}=await H.functions.invoke("bunny-upload",{body:{action:"status",videoId:s,isAgentVideo:!0}});if(n)throw n;return t}function apn(){const{user:s}=Ls(),t=as();return _t({mutationFn:async({contactId:n,videoId:r,notes:a})=>{if(!(s!=null&&s.id))throw new Error("Not authenticated");const{data:i}=await H.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 H.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 uIt({open:s,onOpenChange:t,onUploadComplete:n}){const{data:r}=Wy(),{data:a}=VCe(),i=G3(),l=N.useRef(null),[o,c]=N.useState(null),[d,u]=N.useState(""),[h,m]=N.useState(""),[f,g]=N.useState(""),[y,x]=N.useState(!1),[_,b]=N.useState(0),[k,A]=N.useState("idle"),T=(a==null?void 0:a.total_storage_mb)||0,I=((a==null?void 0:a.max_storage_mb)||1024)-T,M=V=>{var X;const W=(X=V.target.files)==null?void 0:X[0];if(!W)return;if(!W.type.startsWith("video/")){ie.error("Please select a video file");return}const G=W.size/(1024*1024);if(G>500){ie.error("Video file must be less than 500MB");return}if(G>I){ie.error(`Not enough storage. You have ${I.toFixed(1)} MB remaining.`);return}c(W),d||u(W.name.replace(/\.[^/.]+$/,""))},L=async()=>{if(!o){ie.error("Please select a video file");return}x(!0),b(0),A("creating");try{const{data:V,error:W}=await H.functions.invoke("bunny-upload",{body:{action:"create",title:d||o.name,isAgentVideo:!0}});if(W)throw new Error(W.message);const{videoId:G,libraryId:X}=V;A("uploading");const{data:te,error:ne}=await H.functions.invoke("bunny-upload",{body:{action:"upload-url",videoId:G,isAgentVideo:!0}});if(ne)throw new Error(ne.message);await new Promise((ce,ae)=>{const he=new XMLHttpRequest;he.upload.addEventListener("progress",xe=>{if(xe.lengthComputable){const ve=Math.round(xe.loaded/xe.total*100);b(ve)}}),he.addEventListener("load",()=>{he.status>=200&&he.status<300?ce():ae(new Error(`Upload failed with status ${he.status}`))}),he.addEventListener("error",()=>ae(new Error("Upload failed"))),he.open("PUT",te.uploadUrl),he.setRequestHeader("AccessKey",te.apiKey),he.send(o)}),A("processing");const me=o.size/(1024*1024),ue=`https://iframe.mediadelivery.net/embed/${X}/${G}`;await i.mutateAsync({bunny_video_id:G,playback_url:ue,file_size_mb:me,title:d||o.name,notes:h||void 0,contact_id:f||void 0,status:"processing",touch_type:"video_upload"}),ie.success("Video uploaded successfully! Processing may take a few minutes."),n==null||n(ue),z()}catch(V){console.error("Upload error:",V),ie.error(V instanceof Error?V.message:"Failed to upload video")}finally{x(!1),A("idle")}},z=()=>{y||(c(null),u(""),m(""),g(""),b(0),A("idle"),t(!1))},$=()=>{switch(k){case"creating":return"Preparing upload...";case"uploading":return`Uploading... ${_}%`;case"processing":return"Saving video...";default:return""}};return e.jsx(Bs,{open:s,onOpenChange:z,children:e.jsxs(Fs,{className:"sm:max-w-md",children:[e.jsxs(qs,{children:[e.jsx($s,{children:"Upload Video"}),e.jsx(Ar,{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(re,{children:"Video File"}),o?e.jsxs("div",{className:"flex items-center gap-3 p-3 bg-muted rounded-lg",children:[e.jsx(na,{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(hr,{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(ni,{className:"h-8 w-8 mx-auto text-muted-foreground mb-2"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Click to select a video file"}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:"MP4, MOV, WebM (max 500MB)"})]}),e.jsx("input",{ref:l,type:"file",accept:"video/*",className:"hidden",onChange:M,disabled:y})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{htmlFor:"title",children:"Title"}),e.jsx(we,{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(re,{children:"Associate with Contact (optional)"}),e.jsxs(Ns,{value:f||"__none__",onValueChange:V=>g(V==="__none__"?"":V),disabled:y,children:[e.jsx(ws,{children:e.jsx(ks,{placeholder:"Select a contact"})}),e.jsxs(js,{children:[e.jsx(nt,{value:"__none__",children:"No contact"}),r==null?void 0:r.map(V=>e.jsxs(nt,{value:V.id,children:[V.first_name," ",V.last_name||""]},V.id))]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{htmlFor:"notes",children:"Notes (optional)"}),e.jsx(Ws,{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(us,{className:"h-4 w-4 animate-spin"}),e.jsx("span",{children:$()})]}),e.jsx(ro,{value:k==="uploading"?_:k==="processing"?100:10})]})]}),e.jsxs(Cr,{children:[e.jsx(B,{variant:"outline",onClick:z,disabled:y,children:"Cancel"}),e.jsx(B,{onClick:L,disabled:!o||y,children:y?e.jsxs(e.Fragment,{children:[e.jsx(us,{className:"h-4 w-4 mr-2 animate-spin"}),"Uploading..."]}):e.jsxs(e.Fragment,{children:[e.jsx(ni,{className:"h-4 w-4 mr-2"}),"Upload Video"]})})]})]})})}const ipn=["🌱","💎","🏠","🔑","📧","💌","🎂","🥂","🤝","⭐","🎉","📞"],opn={" ":" ","&":"&","<":"<",">":">",""":'"',"'":"'"},lht=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=>opn[t.toLowerCase()]||t).replace(/\n{3,}/g,` `).replace(/[ \t]+\n/g,` `).trim():s:"";function hIt({open:s,onOpenChange:t,campaignId:n}){const[r,a]=N.useState(n??null),[i,l]=N.useState("details");N.useEffect(()=>{a(n??null),l("details")},[n,s]);const o=r,c=!!o,{data:d}=zmn(o||void 0),{data:u,isLoading:h}=lIt(o||void 0),m=Bmn(),f=oIt(),g=Umn(),[y,x]=N.useState(""),[_,b]=N.useState(""),[k,A]=N.useState("nurture"),[T,P]=N.useState("🌱"),[I,M]=N.useState("");N.useEffect(()=>{d?(x(d.name),b(d.description||""),A(d.category),P(d.icon),M(d.goal||"")):c||(x(""),b(""),A("nurture"),P("🌱"),M(""))},[d,c,s]);const L=Ymn[k],z=async()=>{if(!y.trim()){ie.error("Give your campaign a name");return}try{if(c&&o)await f.mutateAsync({id:o,name:y,description:_,category:k,icon:T,goal:I,cover_color:L}),ie.success("Campaign updated");else{const V=await m.mutateAsync({name:y,description:_,category:k,icon:T,goal:I,cover_color:L});return ie.success("Campaign created — now add your first step!"),a(V.id),l("steps"),V}}catch(V){ie.error(V.message||"Failed to save")}},$=async()=>{if(!o){ie.error("Save the campaign first, then add steps");return}const V=((u==null?void 0:u.length)||0)+1;try{await g.mutateAsync({campaign_id:o,step_order:V,channel:"email",subject:"",body:"",delay_type:"relative",delay_days:V===1?0:2,delay_hours:0})}catch{ie.error("Failed to add step")}};return e.jsx(Bs,{open:s,onOpenChange:t,children:e.jsxs(Fs,{className:"max-w-3xl max-h-[90vh] flex flex-col p-0 overflow-hidden",children:[e.jsx("div",{className:`bg-gradient-to-br ${L} 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:T}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx($s,{className:"text-lg font-bold text-white",children:c?"Edit Campaign":"Create New Campaign"}),e.jsx(Ar,{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(ya,{value:i,onValueChange:V=>l(V),className:"flex-1 flex flex-col overflow-hidden min-h-0",children:[e.jsxs(va,{className:"mx-5 mt-4 grid grid-cols-2 w-fit",children:[e.jsx(ls,{value:"details",children:"Details"}),e.jsxs(ls,{value:"steps",disabled:!c,children:["Steps ",u&&u.length>0&&e.jsx(We,{variant:"secondary",className:"ml-1.5 text-[10px]",children:u.length})]})]}),e.jsx(_s,{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(re,{className:"text-xs",children:"Campaign Name *"}),e.jsx(we,{value:y,onChange:V=>x(V.target.value),placeholder:"e.g. New Buyer Lead — 7 Touch Nurture",className:"mt-1"})]}),e.jsxs("div",{children:[e.jsx(re,{className:"text-xs",children:"Description"}),e.jsx(Ws,{value:_,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(re,{className:"text-xs",children:"Goal (optional)"}),e.jsx(we,{value:I,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(re,{className:"text-xs",children:"Category"}),e.jsxs(Ns,{value:k,onValueChange:V=>A(V),children:[e.jsx(ws,{className:"mt-1",children:e.jsx(ks,{})}),e.jsx(js,{children:Object.entries(qCe).map(([V,W])=>e.jsx(nt,{value:V,children:W},V))})]})]}),e.jsxs("div",{children:[e.jsx(re,{className:"text-xs",children:"Icon"}),e.jsx("div",{className:"flex gap-1.5 flex-wrap mt-1",children:ipn.map(V=>e.jsx("button",{type:"button",onClick:()=>P(V),className:`h-8 w-8 rounded-md text-lg flex items-center justify-center transition-all ${T===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(_s,{value:"steps",className:"flex-1 overflow-y-auto overscroll-contain mt-0 min-h-0 data-[state=inactive]:hidden",children:e.jsx("div",{children:e.jsx("div",{className:"p-5 space-y-3",children:h?e.jsx("div",{className:"text-center text-sm text-muted-foreground py-8",children:"Loading steps…"}):!u||u.length===0?e.jsxs("div",{className:"text-center py-10 border border-dashed rounded-xl",children:[e.jsx(Cn,{className:"h-8 w-8 text-muted-foreground/40 mx-auto mb-2"}),e.jsx("p",{className:"text-sm font-medium mb-1",children:"No steps yet"}),e.jsx("p",{className:"text-xs text-muted-foreground mb-3",children:"Build your sequence — each step waits for its delay, then sends."}),e.jsxs(B,{size:"sm",onClick:$,disabled:g.isPending,children:[e.jsx(nn,{className:"h-3.5 w-3.5 mr-1.5"})," Add first step"]})]}):e.jsxs(e.Fragment,{children:[u.map((V,W)=>e.jsx(lpn,{step:V,index:W,totalSteps:u.length},V.id)),e.jsxs(B,{variant:"outline",size:"sm",onClick:$,disabled:g.isPending,className:"w-full",children:[g.isPending?e.jsx(us,{className:"h-3.5 w-3.5 mr-1.5 animate-spin"}):e.jsx(nn,{className:"h-3.5 w-3.5 mr-1.5"}),"Add another step"]})]})})})})]}),e.jsxs(Cr,{className:"border-t p-4 shrink-0",children:[e.jsx(B,{variant:"outline",onClick:()=>t(!1),children:c?"Done":"Cancel"}),e.jsxs(B,{onClick:z,disabled:m.isPending||f.isPending,children:[(m.isPending||f.isPending)&&e.jsx(us,{className:"h-3.5 w-3.5 mr-1.5 animate-spin"}),c?"Save Changes":"Create Campaign"]})]})]})})}function lpn({step:s,index:t,totalSteps:n}){const r=qmn(),a=Vmn(),i=Ya(),[l,o]=N.useState(!1),[c,d]=N.useState(()=>({...s,body:lht(s.body)})),[u,h]=N.useState(!1),[m,f]=N.useState(!1),[g,y]=N.useState(""),[x,_]=N.useState(!1),[b,k]=N.useState(!1);N.useEffect(()=>{d({...s,body:lht(s.body)})},[s]);const A=JSON.stringify(c)!==JSON.stringify(s),T=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}),ie.success(`Step ${t+1} saved`)}catch{ie.error("Failed to save step")}finally{h(!1)}},P=async()=>{if(confirm(`Delete step ${t+1}?`))try{await a.mutateAsync({id:s.id,campaign_id:s.campaign_id}),ie.success("Step deleted")}catch{ie.error("Failed to delete")}},I=L=>{d({...c,body:c.body+L})},M=()=>{if(c.delay_type==="calendar_anchor"){const z=c.anchor_field==="birthday"?"birthday":"home anniversary",$=c.anchor_offset_days||0;return $===0?`On their ${z}`:$<0?`${Math.abs($)}d before ${z}`:`${$}d after ${z}`}if(t===0&&!c.delay_days&&!c.delay_hours)return"Sends immediately";const L=[];return c.delay_days&&L.push(`${c.delay_days}d`),c.delay_hours&&L.push(`${c.delay_hours}h`),t===0?`After ${L.join(" ")||"0"}`:`+${L.join(" ")||"0"}`};return e.jsxs("div",{className:"border rounded-lg bg-card overflow-hidden",children:[e.jsxs("div",{className:"flex items-center gap-2 p-3 hover:bg-muted/30 cursor-pointer",onClick:()=>o(!l),children:[e.jsx("div",{className:"h-7 w-7 shrink-0 rounded-full bg-primary/10 text-primary flex items-center justify-center text-xs font-semibold",children:t+1}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 text-xs text-muted-foreground",children:[c.delay_type==="calendar_anchor"?e.jsx(ta,{className:"h-3 w-3"}):e.jsx(Xr,{className:"h-3 w-3"}),e.jsx("span",{children:M()}),e.jsx("span",{children:"·"}),c.channel==="email"?e.jsx(mn,{className:"h-3 w-3"}):e.jsx(xo,{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(zy,{className:"h-4 w-4 text-muted-foreground"}):e.jsx(Xo,{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(re,{className:"text-xs",children:"Channel"}),e.jsxs(Ns,{value:c.channel,onValueChange:L=>d({...c,channel:L}),children:[e.jsx(ws,{className:"mt-1 h-9",children:e.jsx(ks,{})}),e.jsx(js,{children:e.jsx(nt,{value:"email",children:"📧 Email"})})]})]}),e.jsxs("div",{children:[e.jsx(re,{className:"text-xs",children:"Timing Type"}),e.jsxs(Ns,{value:c.delay_type,onValueChange:L=>d({...c,delay_type:L}),children:[e.jsx(ws,{className:"mt-1 h-9",children:e.jsx(ks,{})}),e.jsxs(js,{children:[e.jsx(nt,{value:"relative",children:"⏱ Relative delay"}),e.jsx(nt,{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(re,{className:"text-xs",children:"Days delay"}),e.jsx(we,{type:"number",min:0,value:c.delay_days,onChange:L=>d({...c,delay_days:parseInt(L.target.value)||0}),className:"mt-1 h-9"})]}),e.jsxs("div",{children:[e.jsx(re,{className:"text-xs",children:"Hours delay"}),e.jsx(we,{type:"number",min:0,max:23,value:c.delay_hours,onChange:L=>d({...c,delay_hours:parseInt(L.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(re,{className:"text-xs",children:"Anchor"}),e.jsxs(Ns,{value:c.anchor_field||"birthday",onValueChange:L=>d({...c,anchor_field:L}),children:[e.jsx(ws,{className:"mt-1 h-9",children:e.jsx(ks,{})}),e.jsxs(js,{children:[e.jsx(nt,{value:"birthday",children:"🎂 Birthday"}),e.jsx(nt,{value:"home_anniversary",children:"🏠 Home Anniversary"})]})]})]}),e.jsxs("div",{children:[e.jsx(re,{className:"text-xs",children:"Offset (days, negative = before)"}),e.jsx(we,{type:"number",value:c.anchor_offset_days||0,onChange:L=>d({...c,anchor_offset_days:parseInt(L.target.value)||0}),className:"mt-1 h-9",placeholder:"0 = on the day, -7 = week before"})]})]}),e.jsxs("div",{children:[e.jsx(re,{className:"text-xs",children:"Subject Line"}),e.jsx(we,{value:c.subject,onChange:L=>d({...c,subject:L.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(re,{className:"text-xs",children:"Email Body"}),e.jsxs("span",{className:"text-[10px] text-muted-foreground",children:[c.body.length," chars"]})]}),e.jsx(Ws,{value:c.body,onChange:L=>d({...c,body:L.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:"}),Kmn.map(L=>e.jsx("button",{type:"button",onClick:()=>I(L.key),className:"text-[10px] px-1.5 py-0.5 rounded bg-primary/10 text-primary hover:bg-primary/20",children:L.label},L.key))]})]}),e.jsxs("div",{children:[e.jsx(re,{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(na,{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(tO,{userId:i||void 0,onSelect:L=>d({...c,video_url:L}),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:()=>_(!0),children:[e.jsx(ni,{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(""),f(!0)},children:[e.jsx(gc,{className:"h-3 w-3"})," Paste URL"]}),e.jsx(uIt,{open:x,onOpenChange:_,onUploadComplete:L=>d({...c,video_url:L})}),e.jsx(Bs,{open:m,onOpenChange:f,children:e.jsxs(Fs,{className:"sm:max-w-md",children:[e.jsxs(qs,{children:[e.jsx($s,{children:"Add video URL"}),e.jsx(Ar,{children:"Paste a YouTube, Loom, or direct video URL."})]}),e.jsx(we,{value:g,onChange:L=>y(L.target.value),placeholder:"https://...",autoFocus:!0,onKeyDown:L=>{L.key==="Enter"&&g.trim()&&(d({...c,video_url:g.trim()}),f(!1))}}),e.jsxs(Cr,{children:[e.jsx(B,{variant:"ghost",onClick:()=>f(!1),children:"Cancel"}),e.jsx(B,{disabled:!g.trim(),onClick:()=>{d({...c,video_url:g.trim()}),f(!1)},children:"Add video"})]})]})})]})]}),e.jsxs("div",{className:"flex items-center justify-between pt-2 border-t",children:[e.jsxs(B,{variant:"ghost",size:"sm",onClick:P,className:"text-destructive hover:text-destructive",children:[e.jsx(qn,{className:"h-3.5 w-3.5 mr-1"})," Delete step"]}),e.jsxs("div",{className:"flex items-center gap-2",children:[c.channel==="email"&&e.jsxs(B,{variant:"outline",size:"sm",onClick:()=>k(!0),children:[e.jsx(da,{className:"h-3.5 w-3.5 mr-1.5"})," Preview"]}),e.jsxs(B,{size:"sm",onClick:T,disabled:!A||u,children:[u&&e.jsx(us,{className:"h-3.5 w-3.5 mr-1.5 animate-spin"}),"Save step"]})]})]}),e.jsx(Zmn,{open:b,onOpenChange:k,subject:c.subject||"",body:c.body||"",ownerUserId:i,stepLabel:`Step ${t+1}`})]})]})}function cpn({open:s,onOpenChange:t,contactIds:n,onSuccess:r}){const{data:a,isLoading:i}=pJ(),l=cIt(),[o,c]=N.useState(""),[d,u]=N.useState(null),[h,m]=N.useState(!1),f=(a||[]).filter(x=>!x.is_starter),g=f.filter(x=>x.name.toLowerCase().includes(o.toLowerCase())||(x.description||"").toLowerCase().includes(o.toLowerCase())),y=async()=>{if(d)try{const x=await l.mutateAsync({campaignId:d,contactIds:n}),_=[`${x.enrolled} enrolled`];x.skipped>0&&_.push(`${x.skipped} skipped`),x.errors>0&&_.push(`${x.errors} errors`),ie.success(_.join(" · ")),t(!1),u(null),r==null||r()}catch(x){ie.error(x.message||"Failed to enroll contacts")}};return e.jsxs(Bs,{open:s,onOpenChange:t,children:[e.jsxs(Fs,{className:"max-w-md",children:[e.jsxs(qs,{children:[e.jsxs($s,{className:"flex items-center gap-2",children:[e.jsx(Cn,{className:"h-4 w-4 text-primary"}),"Enroll in Drip Campaign"]}),e.jsxs(Ar,{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(Gr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-3.5 w-3.5 text-muted-foreground"}),e.jsx(we,{placeholder:"Search campaigns...",value:o,onChange:x=>c(x.target.value),className:"pl-9 h-9"})]}),e.jsx(lo,{className:"h-[320px] -mx-1 px-1",children:i?e.jsx("div",{className:"text-center py-8 text-sm text-muted-foreground",children:"Loading..."}):g.length===0?e.jsx("div",{className:"text-center py-8",children:f.length===0?e.jsxs(e.Fragment,{children:[e.jsx(Cn,{className:"h-8 w-8 text-muted-foreground/40 mx-auto mb-2"}),e.jsx("p",{className:"text-sm font-medium mb-1",children:"No campaigns yet"}),e.jsx("p",{className:"text-xs text-muted-foreground mb-3",children:"Build a custom drip campaign to nurture these contacts on autopilot."}),e.jsxs(B,{size:"sm",onClick:()=>m(!0),children:[e.jsx(nn,{className:"h-3.5 w-3.5 mr-1.5"})," Create campaign"]})]}):e.jsx("p",{className:"text-sm text-muted-foreground",children:"No campaigns match your search."})}):e.jsx("div",{className:"space-y-1.5",children:g.map(x=>e.jsxs("button",{onClick:()=>u(x.id),className:`w-full flex items-start gap-3 p-3 rounded-lg border text-left transition-all ${d===x.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 ${x.cover_color} flex items-center justify-center text-lg`,children:x.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:x.name}),x.is_active&&e.jsx(We,{variant:"outline",className:"text-[9px] bg-emerald-500/10 text-emerald-600 border-emerald-200 px-1 py-0",children:"Active"})]}),x.description&&e.jsx("p",{className:"text-xs text-muted-foreground line-clamp-2 mt-0.5",children:x.description})]}),d===x.id&&e.jsx(pa,{className:"h-4 w-4 text-primary shrink-0 mt-1"})]},x.id))})})]}),e.jsxs(Cr,{className:"gap-2 sm:gap-2",children:[f.length>0&&e.jsxs(B,{variant:"ghost",size:"sm",onClick:()=>m(!0),className:"mr-auto text-xs",children:[e.jsx(nn,{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(us,{className:"h-3.5 w-3.5 mr-1.5 animate-spin"}),"Enroll ",n.length," contact",n.length!==1?"s":""]})]})]}),e.jsx(hIt,{open:h,onOpenChange:m})]})}function dpn({selectedIds:s,contacts:t,onClearSelection:n,onSendToLeadPond:r,showLeadPondAction:a,onTransfer:i,showTransferAction:l}){const o=tr(),{data:c}=K_(),d=uqe(),u=as(),{isGmailConnected:h}=_f(),{isReady:m}=$U(),{data:f}=UU(),g=oGe(),y=XPt(),[x,_]=N.useState(!1),[b,k]=N.useState(!1),[A,T]=N.useState(!1),[P,I]=N.useState(!1),[M,L]=N.useState(!1),[z,$]=N.useState(""),V=s.size;if(V===0)return null;const W=async ce=>{_(!0);try{const he=Array.from(s).map(ve=>({contact_id:ve,relationship_type_id:ce})),{error:xe}=await H.from("innercircle_contact_tags").upsert(he,{onConflict:"contact_id,relationship_type_id",ignoreDuplicates:!0});if(xe)throw xe;u.invalidateQueries({queryKey:["innercircle-contacts"]}),u.invalidateQueries({queryKey:["innercircle-contact-counts"]}),xa({title:`Assigned type to ${V} contacts`}),n()}catch(ae){xa({title:"Error assigning type",description:ae.message,variant:"destructive"})}finally{_(!1)}},G=async ce=>{_(!0);try{const ae=Array.from(s);for(const he of ae)try{await y.mutateAsync({contactId:he,tagId:ce})}catch{}u.invalidateQueries({queryKey:["all-contact-custom-tags"]}),xa({title:`Tagged ${V} contacts`}),L(!1),$("")}catch(ae){xa({title:"Error adding tags",description:ae.message,variant:"destructive"})}finally{_(!1)}},X=async()=>{if(z.trim()){_(!0);try{const ce=await g.mutateAsync({name:z.trim()});await G(ce.id)}catch(ce){xa({title:"Error creating tag",description:ce.message,variant:"destructive"}),_(!1)}}},te=(f==null?void 0:f.filter(ce=>ce.name.toLowerCase().includes(z.toLowerCase())))||[],ne=f==null?void 0:f.find(ce=>ce.name.toLowerCase()===z.trim().toLowerCase()),me=()=>{const ce=t.filter(Se=>s.has(Se.id)),ae=["First Name","Last Name","Email","Phone","Address","Birthday","Home Anniversary","Notes","Relationship Types"],he=ce.map(Se=>{var Ie;return[Se.first_name,Se.last_name||"",Se.email||"",Se.phone||"",Se.address||"",Se.birthday||"",Se.home_anniversary||"",Se.notes||"",((Ie=Se.tags)==null?void 0:Ie.map(Me=>{var Re;return(Re=Me.relationship_type)==null?void 0:Re.name}).join("; "))||""]}),xe=[ae.join(","),...he.map(Se=>Se.map(Ie=>`"${(Ie||"").replace(/"/g,'""')}"`).join(","))].join(` `),ve=new Blob([xe],{type:"text/csv"}),ge=URL.createObjectURL(ve),be=document.createElement("a");be.href=ge,be.download=`contacts-export-${new Date().toISOString().slice(0,10)}.csv`,be.click(),URL.revokeObjectURL(ge),xa({title:`Exported ${V} contacts`})},ue=async()=>{if(confirm(`Are you sure you want to delete ${V} contacts? This cannot be undone.`)){_(!0);try{const ce=Array.from(s);for(const ae of ce)await d.mutateAsync(ae);n()}catch(ce){xa({title:"Error deleting contacts",description:ce.message,variant:"destructive"})}finally{_(!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(We,{variant:"secondary",className:"font-semibold",children:[V," selected"]}),e.jsxs(Ns,{onValueChange:W,disabled:x,children:[e.jsx(ws,{className:"w-[180px] h-8",children:e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(pf,{className:"h-3.5 w-3.5"}),e.jsx("span",{className:"text-sm",children:"Assign Type"})]})}),e.jsx(js,{children:c==null?void 0:c.filter(ce=>ce.active).map(ce=>e.jsx(nt,{value:ce.id,children:ce.name},ce.id))})]}),e.jsxs(rc,{open:M,onOpenChange:L,children:[e.jsx(ac,{asChild:!0,children:e.jsxs(B,{variant:"outline",size:"sm",disabled:x,children:[e.jsx(nn,{className:"h-3.5 w-3.5 mr-1"}),"Add Tag"]})}),e.jsxs(Zl,{className:"w-56 p-2",align:"start",children:[e.jsx(we,{placeholder:"Search or create tag...",value:z,onChange:ce=>$(ce.target.value),onKeyDown:ce=>{ce.key==="Enter"&&z.trim()&&!ne?(ce.preventDefault(),X()):ce.key==="Enter"&&ne&&(ce.preventDefault(),G(ne.id))},className:"h-8 text-sm mb-2"}),e.jsxs("div",{className:"max-h-[200px] overflow-y-auto space-y-0.5",children:[te.map(ce=>e.jsxs("button",{onClick:()=>G(ce.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:ce.color}}),e.jsx("span",{className:"flex-1 text-left truncate",children:ce.name})]},ce.id)),z.trim()&&!ne&&e.jsxs("button",{onClick:X,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(nn,{className:"h-3.5 w-3.5"}),'Create "',z.trim(),'"']}),te.length===0&&!z.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:()=>k(!0),disabled:x,children:[e.jsx(mn,{className:"h-3.5 w-3.5 mr-1"}),"Email"]}),m&&e.jsxs(B,{variant:"outline",size:"sm",onClick:()=>{const ce=Array.from(s).join(",");o(`/admin/email-campaigns/new?contactIds=${ce}`)},disabled:x,children:[e.jsx(um,{className:"h-3.5 w-3.5 mr-1"}),"Mass Email"]}),e.jsxs(B,{variant:"outline",size:"sm",onClick:()=>T(!0),disabled:x,children:[e.jsx(na,{className:"h-3.5 w-3.5 mr-1"}),"Send Video"]}),e.jsxs(B,{variant:"outline",size:"sm",onClick:()=>I(!0),disabled:x,children:[e.jsx(Cn,{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:x,children:[e.jsx(K2,{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:x,children:[e.jsx(c5,{className:"h-3.5 w-3.5 mr-1"}),"Transfer"]}),e.jsxs(B,{variant:"outline",size:"sm",onClick:me,disabled:x,children:[e.jsx(oi,{className:"h-3.5 w-3.5 mr-1"}),"Export"]}),e.jsxs(B,{variant:"outline",size:"sm",onClick:ue,disabled:x,className:"text-destructive hover:text-destructive",children:[e.jsx(qn,{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(hr,{className:"h-3.5 w-3.5 mr-1"}),"Clear"]})]}),e.jsx(cpn,{open:P,onOpenChange:I,contactIds:Array.from(s),onSuccess:n}),e.jsx(Y_,{open:b,onOpenChange:k,bulkContacts:Array.from(s).map(ce=>{const ae=t.find(he=>he.id===ce);return ae?{id:ae.id,first_name:ae.first_name,last_name:ae.last_name,email:ae.email||""}:null}).filter(ce=>ce!==null&&ce.email!==""),onSendComplete:()=>{k(!1),n()}}),e.jsx(Fmn,{open:A,onOpenChange:T,contacts:Array.from(s).map(ce=>t.find(ae=>ae.id===ce)).filter(ce=>!!ce).map(ce=>({id:ce.id,first_name:ce.first_name,last_name:ce.last_name,email:ce.email})),isGmailConnected:!!h,isMassEmailReady:!!m,onSendComplete:()=>{T(!1),n()}})]})}function cht({contact:s,onEdit:t,onDelete:n,onSnooze:r,onSendToLeadPond:a,showLeadPondAction:i,onTransfer:l,showTransferAction:o}){const c=tr(),{isReady:d}=$U(),u=`${s.first_name} ${s.last_name||""}`.trim();return e.jsxs(qd,{children:[e.jsx(Vd,{asChild:!0,children:e.jsx(B,{variant:"ghost",size:"sm",className:"h-8 w-8 p-0",onClick:h=>h.stopPropagation(),children:e.jsx(Iy,{className:"h-4 w-4"})})}),e.jsxs(Ld,{align:"end",onClick:h=>h.stopPropagation(),children:[e.jsxs(ba,{onClick:()=>c(`/mission-control/contacts/${s.id}?tab=activity&action=log`),children:[e.jsx(ga,{className:"h-4 w-4 mr-2"}),"Log Touch"]}),e.jsxs(ba,{onClick:()=>c(`/mission-control/video?contactId=${s.id}`),children:[e.jsx(na,{className:"h-4 w-4 mr-2"}),"Send Video"]}),e.jsxs(ba,{onClick:()=>c(`/mission-control/popbys?contactId=${s.id}`),children:[e.jsx(ii,{className:"h-4 w-4 mr-2"}),"Schedule Pop-by"]}),d&&s.email&&e.jsxs(ba,{onClick:()=>c(`/admin/email-campaigns/new?contactIds=${s.id}`),children:[e.jsx(mn,{className:"h-4 w-4 mr-2"}),"Mass Email"]}),e.jsxs(ba,{onClick:()=>r(s.id,u),children:[e.jsx(K0,{className:"h-4 w-4 mr-2"}),"Snooze"]}),i&&a&&e.jsxs(ba,{onClick:()=>a(s.id),children:[e.jsx(K2,{className:"h-4 w-4 mr-2"}),"Send to Lead Pond"]}),o&&l&&e.jsxs(ba,{onClick:()=>l(s.id),children:[e.jsx(c5,{className:"h-4 w-4 mr-2"}),"Transfer to Team Member"]}),e.jsxs(ba,{onClick:()=>t(s),children:[e.jsx(Ja,{className:"h-4 w-4 mr-2"}),"Edit"]}),e.jsxs(ba,{onClick:()=>n(s.id),className:"text-destructive focus:text-destructive",children:[e.jsx(qn,{className:"h-4 w-4 mr-2"}),"Delete"]})]})]})}function dht({currentFilters:s,currentSortBy:t,onApplySmartList:n}){const{data:r}=lGe(),a=QPt(),i=JPt(),[l,o]=N.useState(!1),[c,d]=N.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(qd,{children:[e.jsx(Vd,{asChild:!0,children:e.jsxs(B,{variant:"outline",size:"sm",className:"gap-1.5",children:[e.jsx(cj,{className:"h-3.5 w-3.5"}),"Smart Filters",r&&r.length>0&&e.jsx(We,{variant:"secondary",className:"h-5 px-1.5 text-[10px]",children:r.length}),e.jsx(Xo,{className:"h-3.5 w-3.5"})]})}),e.jsxs(Ld,{align:"start",className:"w-56",children:[r&&r.length>0?e.jsxs(e.Fragment,{children:[r.map(m=>e.jsxs(ba,{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:f=>{f.stopPropagation(),i.mutate(m.id)},children:e.jsx(qn,{className:"h-3 w-3 text-destructive"})})]},m.id)),e.jsx(s1,{})]}):e.jsx(ba,{disabled:!0,className:"text-muted-foreground text-xs",children:"No saved filters yet"}),u&&e.jsxs(ba,{onClick:()=>o(!0),children:[e.jsx(aD,{className:"h-4 w-4 mr-2"}),"Save Current Filter"]})]})]}),e.jsx(Bs,{open:l,onOpenChange:o,children:e.jsxs(Fs,{className:"max-w-sm",children:[e.jsx(qs,{children:e.jsx($s,{children:"Save Smart Filter"})}),e.jsxs("div",{className:"space-y-4",children:[e.jsx(we,{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 y5e=[{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"}],mIt=[{value:"home_anniversary",label:"Home anniversary"},{value:"wedding_anniversary",label:"Wedding anniversary"}],upn=[{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 hpn({open:s,onOpenChange:t,hasLeadSite:n,behavior:r,onApply:a,selectedType:i,onSelectedTypeChange:l,relationshipTypes:o}){const[c,d]=N.useState(r),[u,h]=N.useState(n?"behavior":"contact"),{data:m}=$R();N.useEffect(()=>{s&&d(r)},[s,r]);const f=y=>d(x=>({...x,...y})),g=Object.entries(c).filter(([,y])=>y!==void 0&&y!==!1&&y!=="").length;return e.jsx(l1,{open:s,onOpenChange:t,children:e.jsxs(Gy,{side:"right",className:"w-full sm:max-w-lg overflow-y-auto",children:[e.jsxs(gb,{children:[e.jsxs(xb,{className:"flex items-center gap-2",children:[e.jsx(Cn,{className:"h-4 w-4 text-primary"}),"Advanced Filters"]}),e.jsx(IQ,{children:"Slice your database by website activity, contact details, and engagement."})]}),e.jsxs(ya,{value:u,onValueChange:y=>h(y),className:"mt-4",children:[e.jsxs(va,{className:"grid w-full grid-cols-3",children:[e.jsxs(ls,{value:"contact",className:"gap-1.5",children:[e.jsx(Yn,{className:"h-3.5 w-3.5"})," Contact"]}),e.jsxs(ls,{value:"behavior",disabled:!n,className:"gap-1.5",children:[e.jsx(gg,{className:"h-3.5 w-3.5"})," Behavior"]}),e.jsx(ls,{value:"engagement",children:"Engagement"})]}),e.jsxs(_s,{value:"contact",className:"space-y-6 mt-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{children:"Contact Type"}),e.jsxs(Ns,{value:i,onValueChange:l,children:[e.jsx(ws,{children:e.jsx(ks,{placeholder:"All types"})}),e.jsxs(js,{children:[e.jsx(nt,{value:"all",children:"All Types"}),o==null?void 0:o.map(y=>e.jsx(nt,{value:y.id,children:y.name},y.id))]})]})]}),e.jsxs(zS,{title:"Contact Info Present",children:[e.jsx(yy,{label:"Has email",checked:c.hasEmail===!0,onChange:y=>f({hasEmail:y||void 0})}),e.jsx(yy,{label:"Has phone",checked:c.hasPhone===!0,onChange:y=>f({hasPhone:y||void 0})}),e.jsx(yy,{label:"Has address",checked:c.hasAddress===!0,onChange:y=>f({hasAddress:y||void 0})}),e.jsx(yy,{label:"Has birthday",checked:c.hasBirthday===!0,onChange:y=>f({hasBirthday:y||void 0})}),e.jsx(yy,{label:"Has spouse",checked:c.hasSpouse===!0,onChange:y=>f({hasSpouse:y||void 0})}),e.jsx(yy,{label:"Has company / job",checked:c.hasCompany===!0,onChange:y=>f({hasCompany:y||void 0})}),e.jsx(yy,{label:"Has notes",checked:c.hasNotes===!0,onChange:y=>f({hasNotes:y||void 0})})]}),e.jsxs(zS,{title:"Location",children:[e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-2",children:[e.jsx(KLe,{label:"City",value:c.city||"",onChange:y=>f({city:y||void 0}),placeholder:"Any city"}),e.jsx(KLe,{label:"State",value:c.state||"",onChange:y=>f({state:y||void 0}),placeholder:"Any state"})]}),e.jsx(KLe,{label:"ZIP / Postal",value:c.zip||"",onChange:y=>f({zip:y||void 0}),placeholder:"Any ZIP"})]}),e.jsxs(zS,{title:"Important Dates",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{className:"text-xs font-semibold uppercase tracking-wide text-muted-foreground",children:"Birthday month"}),e.jsxs(Ns,{value:c.birthdayMonth?String(c.birthdayMonth):"all",onValueChange:y=>f({birthdayMonth:y==="all"?void 0:Number(y)}),children:[e.jsx(ws,{children:e.jsx(ks,{placeholder:"Any month"})}),e.jsxs(js,{children:[e.jsx(nt,{value:"all",children:"Any month"}),y5e.map(y=>e.jsx(nt,{value:String(y.value),children:y.label},y.value))]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{className:"text-xs font-semibold uppercase tracking-wide text-muted-foreground",children:"Anniversary month"}),e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-2",children:[e.jsxs(Ns,{value:c.anniversaryField||"home_anniversary",onValueChange:y=>f({anniversaryField:y}),children:[e.jsx(ws,{children:e.jsx(ks,{placeholder:"Field"})}),e.jsx(js,{children:mIt.map(y=>e.jsx(nt,{value:y.value,children:y.label},y.value))})]}),e.jsxs(Ns,{value:c.anniversaryMonth?String(c.anniversaryMonth):"all",onValueChange:y=>f({anniversaryMonth:y==="all"?void 0:Number(y)}),children:[e.jsx(ws,{children:e.jsx(ks,{placeholder:"Any month"})}),e.jsxs(js,{children:[e.jsx(nt,{value:"all",children:"Any month"}),y5e.map(y=>e.jsx(nt,{value:String(y.value),children:y.label},y.value))]})]})]})]})]}),e.jsx(zS,{title:"Date Added",children:e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-2",children:[e.jsx(uht,{label:"From",value:c.dateAddedFrom,onChange:y=>f({dateAddedFrom:y||void 0})}),e.jsx(uht,{label:"To",value:c.dateAddedTo,onChange:y=>f({dateAddedTo:y||void 0})})]})}),e.jsx(zS,{title:"Lead Source",children:e.jsxs(Ns,{value:c.leadSourceId||"all",onValueChange:y=>f({leadSourceId:y==="all"?void 0:y}),children:[e.jsx(ws,{children:e.jsx(ks,{placeholder:"All sources"})}),e.jsxs(js,{children:[e.jsx(nt,{value:"all",children:"All sources"}),e.jsx(nt,{value:"none",children:"No source"}),m==null?void 0:m.map(y=>e.jsx(nt,{value:y.id,children:y.name},y.id))]})]})})]}),e.jsx(_s,{value:"behavior",className:"space-y-6 mt-4",children:n?e.jsxs(e.Fragment,{children:[e.jsxs(zS,{title:"Last Active On Site",children:[e.jsx(K1,{value:c.lastActive||"",onValueChange:y=>f({lastActive:y||void 0}),className:"grid grid-cols-2 gap-2",children:upn.map(y=>e.jsxs("label",{className:"flex items-center gap-2 rounded-md border px-3 py-2 cursor-pointer hover:bg-accent",children:[e.jsx(Ju,{value:y.value}),e.jsx("span",{className:"text-sm",children:y.label})]},y.value))}),c.lastActive&&e.jsx(B,{variant:"ghost",size:"sm",className:"mt-1 h-7 px-2 text-xs",onClick:()=>f({lastActive:void 0}),children:"Clear"})]}),e.jsxs(zS,{title:"Registration",children:[e.jsx(yy,{label:"Registered on lead site",checked:c.registered==="yes",onChange:y=>f({registered:y?"yes":void 0})}),e.jsx(yy,{label:"Anonymous visitors only",checked:c.registered==="no",onChange:y=>f({registered:y?"no":void 0})})]}),e.jsxs(zS,{title:"Property Activity",children:[e.jsx(yy,{label:"Viewed any listing",checked:c.viewedListing==="any",onChange:y=>f({viewedListing:y?"any":void 0})}),e.jsx(yy,{label:"Hot buyer — 3+ views in last 7 days",checked:c.viewedListing==="multiple7d",onChange:y=>f({viewedListing:y?"multiple7d":void 0})}),e.jsx(yy,{label:"Saved a property",checked:!!c.savedProperty,onChange:y=>f({savedProperty:y||void 0})}),e.jsx(yy,{label:"Has an active saved search / alert",checked:!!c.hasSavedSearch,onChange:y=>f({hasSavedSearch:y||void 0})})]}),e.jsxs(zS,{title:"Requests",children:[e.jsx(yy,{label:"Requested a showing / asked a question",checked:!!c.requestedShowing,onChange:y=>f({requestedShowing:y||void 0})}),e.jsx(yy,{label:"Requested a home valuation",checked:!!c.requestedValuation,onChange:y=>f({requestedValuation:y||void 0})})]})]}):e.jsx("div",{className:"rounded-md border border-dashed p-4 text-sm text-muted-foreground",children:"Connect a Lead Site with MLS to unlock website behavior filters."})}),e.jsxs(_s,{value:"engagement",className:"space-y-4 mt-4",children:[e.jsx(yy,{label:"Any website activity",checked:!!c.websiteActiveOnly,onChange:y=>f({websiteActiveOnly:y||void 0})}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"More engagement filters (last emailed, awaiting response, past-due tasks) are in the pipeline."})]})]}),e.jsxs(ekt,{className:"mt-6 flex-row gap-2 sm:justify-between",children:[e.jsx(B,{variant:"ghost",onClick:()=>d({}),disabled:g===0,children:"Clear behavior filters"}),e.jsx(B,{onClick:()=>{a(c),t(!1)},children:"Apply"})]})]})})}function zS({title:s,children:t}){return e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{className:"text-xs font-semibold uppercase tracking-wide text-muted-foreground",children:s}),e.jsx("div",{className:"space-y-2",children:t})]})}function yy({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(zn,{checked:t,onCheckedChange:n})]})}function KLe({label:s,value:t,onChange:n,placeholder:r}){return e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(re,{className:"text-xs font-semibold uppercase tracking-wide text-muted-foreground",children:s}),e.jsxs("div",{className:"relative",children:[e.jsx(we,{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(hr,{className:"h-3 w-3"})})]})]})}function uht({label:s,value:t,onChange:n}){const[r,a]=N.useState(!1),i=t?jp(t):void 0;return e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(re,{className:"text-xs font-semibold uppercase tracking-wide text-muted-foreground",children:s}),e.jsxs(rc,{open:r,onOpenChange:a,children:[e.jsx(ac,{asChild:!0,children:e.jsxs(B,{variant:"outline",className:Ot("w-full justify-start text-left font-normal h-8",!i&&"text-muted-foreground"),children:[e.jsx(ta,{className:"mr-2 h-3.5 w-3.5"}),i?Js(i,"MMM d, yyyy"):e.jsx("span",{children:"Pick a date"})]})}),e.jsx(Zl,{className:"w-auto p-0",align:"start",children:e.jsx(Xv,{mode:"single",selected:i,onSelect:l=>{n(l?Js(l,"yyyy-MM-dd"):void 0),a(!1)},initialFocus:!0})})]})]})}function mpn({behavior:s,onRemove:t,onClearAll:n}){const r=ppn(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 ppn(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=y5e.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=y5e.find(i=>i.value===s.anniversaryMonth),a=((n=mIt.find(i=>i.value===(s.anniversaryField||"home_anniversary")))==null?void 0:n.label)||"Anniversary";t.push({key:"anniversaryMonth",label:`${a} in ${(r==null?void 0:r.label)||s.anniversaryMonth}`})}return s.dateAddedFrom&&t.push({key:"dateAddedFrom",label:`Added on/after ${Js(jp(s.dateAddedFrom),"MMM d, yyyy")}`}),s.dateAddedTo&&t.push({key:"dateAddedTo",label:`Added on/before ${Js(jp(s.dateAddedTo),"MMM d, yyyy")}`}),s.leadSourceId&&t.push({key:"leadSourceId",label:s.leadSourceId==="none"?"No lead source":"Lead source"}),t}async function AF(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 nH(){return{lastActiveAt:null,registered:!1,propertyViewCount:0,propertyViewCount7d:0,savedListingCount:0,activeSavedSearchCount:0,showingRequests:0,valuationRequests:0,viewedCities:[],viewedZips:[]}}function fpn(){const{user:s}=Ls(),{leadSite:t,hasLeadSite:n}=Qx(),{data:r,isLoading:a}=mt({queryKey:["contact-behavior-summary",s==null?void 0:s.id,t==null?void 0:t.id],queryFn:async()=>{const i=new Map;if(!t)return i;const l=(_,b)=>{const k=i.get(_)||nH();i.set(_,{...k,...b})},o=await AF((_,b)=>H.from("lead_site_visitors").select("id, contact_id, last_seen_at, email").eq("lead_site_id",t.id).not("contact_id","is",null).range(_,b)),c=new Map,d=new Map;o.forEach(_=>{if(!_.contact_id)return;c.set(_.id,_.contact_id),_.email&&d.set(_.email.toLowerCase(),_.contact_id);const b=i.get(_.contact_id);(!b||!b.lastActiveAt||_.last_seen_at>b.lastActiveAt)&&l(_.contact_id,{lastActiveAt:_.last_seen_at})});const u=await AF((_,b)=>H.from("lead_site_consumer_profiles").select("contact_id, user_id").eq("lead_site_id",t.id).not("contact_id","is",null).range(_,b)),h=new Map;u.forEach(_=>{_.contact_id&&(h.set(_.user_id,_.contact_id),l(_.contact_id,{registered:!0}))});const m=new Date(Date.now()-7*24*60*60*1e3).toISOString();return(await AF((_,b)=>H.from("lead_site_property_views").select("visitor_id, viewed_at, property_address").eq("lead_site_id",t.id).not("visitor_id","is",null).range(_,b))).forEach(_=>{const b=_.visitor_id?c.get(_.visitor_id):null;if(!b)return;const k=i.get(b)||nH();k.propertyViewCount+=1,_.viewed_at>=m&&(k.propertyViewCount7d+=1),i.set(b,k)}),(await AF((_,b)=>H.from("lead_site_saved_listings").select("user_id, mls_number").eq("lead_site_id",t.id).range(_,b))).forEach(_=>{const b=h.get(_.user_id);if(!b)return;const k=i.get(b)||nH();k.savedListingCount+=1,i.set(b,k)}),(await AF((_,b)=>H.from("lead_site_saved_searches").select("user_id").eq("lead_site_id",t.id).eq("is_active",!0).range(_,b))).forEach(_=>{const b=h.get(_.user_id);if(!b)return;const k=i.get(b)||nH();k.activeSavedSearchCount+=1,i.set(b,k)}),(await AF((_,b)=>H.from("lead_site_leads").select("email, lead_type").eq("lead_site_id",t.id).not("email","is",null).range(_,b))).forEach(_=>{if(!_.email)return;const b=d.get(_.email.toLowerCase());if(!b)return;const k=i.get(b)||nH(),A=(_.lead_type||"").toLowerCase();(A.includes("showing")||A.includes("question")||A==="contact")&&(k.showingRequests+=1),(A.includes("valuation")||A.includes("cma")||A.includes("home_value"))&&(k.valuationRequests+=1),i.set(b,k)}),i},enabled:!!s&&n,staleTime:5*60*1e3});return{behaviorMap:r??new Map,hasLeadSite:n,isLoading:a}}const pIt="innercircle_geocode_cache_v1";function gpn(){try{return JSON.parse(localStorage.getItem(pIt)||"{}")}catch{return{}}}function xpn(s){try{localStorage.setItem(pIt,JSON.stringify(s))}catch{}}function ypn(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 vpn({open:s,onOpenChange:t,contacts:n,onCitySelect:r}){const a=N.useRef(null),i=N.useRef(null),[l,o]=N.useState(""),[c,d]=N.useState(!0),[u,h]=N.useState([]),[m,f]=N.useState({done:0,total:0}),[g,y]=N.useState(!1),[x,_]=N.useState("heat");N.useEffect(()=>{if(!s)return;let k=!1;return(async()=>{d(!0);const{data:A}=await H.from("settings").select("value").eq("key","mapbox_public_token").maybeSingle();k||(o((A==null?void 0:A.value)||""),d(!1))})(),()=>{k=!0}},[s]),N.useEffect(()=>{if(!s||!l)return;let k=!1;return(async()=>{const T=gpn(),P=n.map(G=>({c:G,addr:ypn(G)})).filter(G=>G.addr),I=[],M=[];for(const{c:G,addr:X}of P){const te=T[X];te!==null&&(te?I.push({id:G.id,name:`${G.first_name||""} ${G.last_name||""}`.trim(),city:G.city||null,state:G.state||null,zip:G.zip||G.zip_code||null,lat:te.lat,lng:te.lng}):M.push({c:G,addr:X}))}if(k||h(I),f({done:I.length,total:P.length}),M.length===0)return;y(!0);const L=6;let z=0;const $={...T},V=[...I],W=async()=>{var G;for(;z{k=!0}},[s,l,n]);const b=N.useMemo(()=>{const k=new Map;for(const A of n){const T=(A.city||"").trim();if(!T)continue;const P=(A.state||"").trim()||null,I=`${T.toLowerCase()}|${P||""}`,M=k.get(I);M?M.count++:k.set(I,{city:T,state:P,count:1})}return Array.from(k.values()).sort((A,T)=>T.count-A.count)},[n]);return N.useEffect(()=>{if(!(!s||!l||!a.current||i.current))return Rc.accessToken=l,i.current=new Rc.Map({container:a.current,style:"mapbox://styles/mapbox/light-v11",center:[-98.5795,39.8283],zoom:3.5}),i.current.addControl(new Rc.NavigationControl,"top-right"),()=>{var k;(k=i.current)==null||k.remove(),i.current=null}},[s,l]),N.useEffect(()=>{const k=i.current;if(!k||u.length===0)return;const A=()=>{const P={type:"FeatureCollection",features:u.map(M=>({type:"Feature",properties:{id:M.id,name:M.name},geometry:{type:"Point",coordinates:[M.lng,M.lat]}}))},I=k.getSource("contacts-src");if(I?I.setData(P):(k.addSource("contacts-src",{type:"geojson",data:P}),k.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]}}),k.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}}),k.on("click","contacts-points",M=>{var $;const L=($=M.features)==null?void 0:$[0];if(!L)return;const z=L.geometry.coordinates.slice();new Rc.Popup({offset:12}).setLngLat(z).setHTML(`
${L.properties.name||"Contact"}
`).addTo(k)}),k.on("mouseenter","contacts-points",()=>{k.getCanvas().style.cursor="pointer"}),k.on("mouseleave","contacts-points",()=>{k.getCanvas().style.cursor=""})),k.getLayer("contacts-heat")&&k.setLayoutProperty("contacts-heat","visibility",x==="heat"?"visible":"none"),k.getLayer("contacts-points")&&(k.setPaintProperty("contacts-points","circle-opacity",x==="points"?.9:0),k.setLayoutProperty("contacts-points","visibility","visible")),u.length>0&&!k._fitDone){const M=new Rc.LngLatBounds;u.forEach(L=>M.extend([L.lng,L.lat]));try{k.fitBounds(M,{padding:60,maxZoom:11,duration:600}),k._fitDone=!0}catch{}}};k.isStyleLoaded()?A():k.once("load",A)},[u,x]),e.jsx(Bs,{open:s,onOpenChange:t,children:e.jsxs(Fs,{className:"max-w-6xl w-[95vw] h-[90vh] p-0 flex flex-col",children:[e.jsx(qs,{className:"p-4 pb-2 border-b",children:e.jsxs($s,{className:"flex items-center gap-2",children:[e.jsx(Cu,{className:"h-5 w-5 text-orange-500"}),"Geographic Heat Map",e.jsxs(We,{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(us,{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:x==="heat"?"default":"ghost",onClick:()=>_("heat"),className:"h-8",children:[e.jsx(Cu,{className:"h-3.5 w-3.5 mr-1"})," Heat"]}),e.jsxs(B,{size:"sm",variant:x==="points"?"default":"ghost",onClick:()=>_("points"),className:"h-8",children:[e.jsx(tW,{className:"h-3.5 w-3.5 mr-1"})," Pins"]})]}),g&&e.jsxs("div",{className:"bg-background/95 backdrop-blur rounded-md shadow-md border px-2.5 py-1.5 text-xs flex items-center gap-2",children:[e.jsx(us,{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(Uo,{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(ii,{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(lo,{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((k,A)=>{var I;const T=((I=b[0])==null?void 0:I.count)||1,P=k.count/T*100;return e.jsx(_e,{className:"cursor-pointer hover:border-primary transition-colors overflow-hidden",onClick:()=>{r==null||r(k.city,k.state),t(!1)},children:e.jsxs(De,{className:"p-2.5 relative",children:[e.jsx("div",{className:"absolute inset-y-0 left-0 bg-primary/10",style:{width:`${P}%`}}),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:[k.city,k.state?`, ${k.state}`:""]}),e.jsx("div",{className:"text-[10px] text-muted-foreground",children:A===0?"🔥 Hottest market":`Rank #${A+1}`})]}),e.jsx(We,{variant:"secondary",className:"shrink-0",children:k.count})]})]})},`${k.city}-${k.state}-${A}`)})]})})]})]})]})})}function dI(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 hht({birthday:s,homeAnniversary:t,weddingAnniversary:n,className:r,contactId:a,contactName:i,contactAddress:l}){const o=tr(),c=YLe(s,"birthday",7),d=YLe(t,"anniversary",7),u=YLe(n||null,"anniversary",7);if(!c&&!d&&!u)return null;const h=(m,f,g)=>{g.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")&&f&&y.set("date",f),y.set("cardType",m),o(`/mission-control/card-studio?${y.toString()}`)};return e.jsxs("div",{className:Ot("flex flex-wrap gap-1",r),children:[c&&e.jsxs("div",{className:"flex items-center gap-0.5",children:[e.jsx(We,{variant:"secondary",className:Ot("text-[10px] gap-0.5 font-medium",c.daysUntil===0?"bg-pink-100 text-pink-700 dark:bg-pink-900/30 dark:text-pink-400 animate-pulse":"bg-pink-50 text-pink-600 dark:bg-pink-900/20 dark:text-pink-400"),children:c.label}),a&&e.jsxs("button",{onClick:m=>h("birthday",s,m),className:"inline-flex items-center gap-0.5 px-1.5 py-0.5 rounded-full text-[9px] font-semibold bg-pink-500/15 text-pink-600 dark:text-pink-400 hover:bg-pink-500/25 transition-colors",title:"Send a birthday card",children:[e.jsx(mn,{className:"h-2.5 w-2.5"}),"Send Card"]})]}),d&&e.jsxs("div",{className:"flex items-center gap-0.5",children:[e.jsx(We,{variant:"secondary",className:Ot("text-[10px] gap-0.5 font-medium",d.daysUntil===0?"bg-blue-100 text-blue-700 dark:bg-blue-900/30 dark:text-blue-400 animate-pulse":"bg-blue-50 text-blue-600 dark:bg-blue-900/20 dark:text-blue-400"),children:d.label}),a&&e.jsxs("button",{onClick:m=>h("home_anniversary",t,m),className:"inline-flex items-center gap-0.5 px-1.5 py-0.5 rounded-full text-[9px] font-semibold bg-blue-500/15 text-blue-600 dark:text-blue-400 hover:bg-blue-500/25 transition-colors",title:"Send an anniversary card",children:[e.jsx(mn,{className:"h-2.5 w-2.5"}),"Send Card"]})]}),u&&e.jsxs("div",{className:"flex items-center gap-0.5",children:[e.jsxs(We,{variant:"secondary",className:Ot("text-[10px] gap-0.5 font-medium",u.daysUntil===0?"bg-rose-100 text-rose-700 dark:bg-rose-900/30 dark:text-rose-400 animate-pulse":"bg-rose-50 text-rose-600 dark:bg-rose-900/20 dark:text-rose-400"),children:["💍 ",u.label.replace(/^[^\w]+/,"")]}),a&&e.jsxs("button",{onClick:m=>h("wedding_anniversary",n||null,m),className:"inline-flex items-center gap-0.5 px-1.5 py-0.5 rounded-full text-[9px] font-semibold bg-rose-500/15 text-rose-600 dark:text-rose-400 hover:bg-rose-500/25 transition-colors",title:"Send a wedding anniversary card",children:[e.jsx(mn,{className:"h-2.5 w-2.5"}),"Send Card"]})]})]})}function o7e({deal:s}){if(!s||!s.stage)return null;const{stage:t}=s;return e.jsxs(We,{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 mht({count:s,className:t}){return!s||s<=0?null:e.jsxs(We,{variant:"outline",className:Ot("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(FT,{className:"h-2.5 w-2.5"}),s===1?"In drip":`${s} drips`]})}function bpn(){const s=Ya();return mt({queryKey:["contacts-campaign-counts",s],queryFn:async()=>{if(!s)return{};const{data:t,error:n}=await H.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 _pn(){const s=Ya();return mt({queryKey:["contact-deals-map",s],queryFn:async()=>{const{data:t,error:n}=await H.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})}function wpn({contactId:s,compact:t=!1}){const{data:n}=UU(),{data:r}=dhn(s),a=oGe(),i=XPt(),l=mhn(),[o,c]=N.useState(!1),[d,u]=N.useState(""),h=N.useRef(null),m=new Set((r==null?void 0:r.map(_=>_.tag_id))||[]),f=(n==null?void 0:n.filter(_=>_.name.toLowerCase().includes(d.toLowerCase())))||[],g=n==null?void 0:n.find(_=>_.name.toLowerCase()===d.trim().toLowerCase()),y=async _=>{m.has(_.id)?await l.mutateAsync({contactId:s,tagId:_.id}):await i.mutateAsync({contactId:s,tagId:_.id})},x=async()=>{if(!(!d.trim()||g))try{const _=await a.mutateAsync({name:d.trim()});await i.mutateAsync({contactId:s,tagId:_.id}),u("")}catch{}};return e.jsxs("div",{className:"flex flex-wrap items-center gap-1.5",children:[r==null?void 0:r.map(_=>{var b,k,A;return e.jsxs(We,{variant:"outline",className:"text-xs gap-1 pr-1",style:{borderColor:((b=_.tag)==null?void 0:b.color)||"#6366F1",color:((k=_.tag)==null?void 0:k.color)||"#6366F1"},children:[e.jsx(pf,{className:"h-2.5 w-2.5"}),(A=_.tag)==null?void 0:A.name,e.jsx("button",{onClick:T=>{T.stopPropagation(),l.mutate({contactId:s,tagId:_.tag_id})},className:"ml-0.5 rounded-full hover:bg-accent p-0.5",children:e.jsx(hr,{className:"h-2.5 w-2.5"})})]},_.id)}),e.jsxs(rc,{open:o,onOpenChange:c,children:[e.jsx(ac,{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:_=>_.stopPropagation(),children:[e.jsx(nn,{className:"h-3 w-3"}),!t&&e.jsx("span",{className:"ml-1",children:"Tag"})]})}),e.jsxs(Zl,{className:"w-56 p-2",align:"start",onClick:_=>_.stopPropagation(),children:[e.jsx(we,{ref:h,placeholder:"Search or create tag...",value:d,onChange:_=>u(_.target.value),onKeyDown:_=>{_.key==="Enter"&&d.trim()&&!g?(_.preventDefault(),x()):_.key==="Enter"&&g&&!m.has(g.id)&&(_.preventDefault(),y(g))},className:"h-8 text-sm mb-2"}),e.jsxs("div",{className:"max-h-[200px] overflow-y-auto space-y-0.5",children:[f.map(_=>e.jsxs("button",{onClick:()=>y(_),className:"flex items-center gap-2 w-full px-2 py-1.5 rounded-md text-sm hover:bg-accent transition-colors",children:[e.jsx("div",{className:"h-3 w-3 rounded-full shrink-0",style:{backgroundColor:_.color}}),e.jsx("span",{className:"flex-1 text-left truncate",children:_.name}),m.has(_.id)&&e.jsx(pa,{className:"h-3.5 w-3.5 text-primary shrink-0"})]},_.id)),d.trim()&&!g&&e.jsxs("button",{onClick:x,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(nn,{className:"h-3.5 w-3.5"}),'Create "',d.trim(),'"']}),f.length===0&&!d.trim()&&e.jsx("p",{className:"text-xs text-muted-foreground text-center py-2",children:"Type to create your first tag"})]})]})]})]})}function pht({contactId:s,tags:t}){return!t||t.length===0?null:e.jsx(e.Fragment,{children:t.map(n=>{var r,a,i;return e.jsx(We,{variant:"outline",className:"text-[10px] gap-0.5",style:{borderColor:((r=n.tag)==null?void 0:r.color)||"#6366F1",color:((a=n.tag)==null?void 0:a.color)||"#6366F1"},children:(i=n.tag)==null?void 0:i.name},n.tag_id)})})}const ene=["#6366F1","#8B5CF6","#EC4899","#EF4444","#F97316","#F59E0B","#10B981","#14B8A6","#06B6D4","#3B82F6","#6B7280","#1F2937"];function jpn({open:s,onOpenChange:t}){const{data:n,isLoading:r}=UU(),a=oGe(),i=hhn(),l=uhn(),[o,c]=N.useState(""),[d,u]=N.useState(ene[0]),[h,m]=N.useState(null),[f,g]=N.useState(""),[y,x]=N.useState(""),_=async()=>{if(o.trim())try{await a.mutateAsync({name:o.trim(),color:d}),c(""),u(ene[0]),xa({title:"Tag created"})}catch(T){xa({title:"Error",description:T.message,variant:"destructive"})}},b=async T=>{if(f.trim())try{await i.mutateAsync({id:T,name:f.trim(),color:y}),m(null),xa({title:"Tag updated"})}catch(P){xa({title:"Error",description:P.message,variant:"destructive"})}},k=async(T,P)=>{if(confirm(`Delete tag "${P}"? It will be removed from all contacts.`))try{await l.mutateAsync(T),xa({title:"Tag deleted"})}catch(I){xa({title:"Error",description:I.message,variant:"destructive"})}},A=T=>{m(T.id),g(T.name),x(T.color)};return e.jsx(Bs,{open:s,onOpenChange:t,children:e.jsxs(Fs,{className:"max-w-md",children:[e.jsx(qs,{children:e.jsx($s,{children:"Manage Tags"})}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex gap-2",children:[e.jsx(we,{placeholder:"New tag name...",value:o,onChange:T=>c(T.target.value),onKeyDown:T=>T.key==="Enter"&&_(),className:"flex-1 h-9"}),e.jsxs(B,{size:"sm",onClick:_,disabled:!o.trim()||a.isPending,className:"h-9",children:[e.jsx(nn,{className:"h-4 w-4 mr-1"}),"Add"]})]}),e.jsx("div",{className:"flex flex-wrap gap-1.5",children:ene.map(T=>e.jsx("button",{onClick:()=>u(T),className:`h-6 w-6 rounded-full border-2 transition-transform ${d===T?"border-foreground scale-110":"border-transparent hover:scale-105"}`,style:{backgroundColor:T}},T))})]}),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(T=>e.jsx("div",{className:"flex items-center gap-2 p-2 rounded-lg hover:bg-accent/50 group",children:h===T.id?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"flex flex-wrap gap-1",children:ene.map(P=>e.jsx("button",{onClick:()=>x(P),className:`h-5 w-5 rounded-full border-2 ${y===P?"border-foreground":"border-transparent"}`,style:{backgroundColor:P}},P))}),e.jsx(we,{value:f,onChange:P=>g(P.target.value),onKeyDown:P=>P.key==="Enter"&&b(T.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(T.id),children:e.jsx(pa,{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(hr,{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:T.color}}),e.jsx("span",{className:"flex-1 text-sm",children:T.name}),e.jsx(B,{variant:"ghost",size:"sm",className:"h-7 w-7 p-0 opacity-0 group-hover:opacity-100 transition-opacity",onClick:()=>A(T),children:e.jsx(Ja,{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:()=>k(T.id,T.name),children:e.jsx(qn,{className:"h-3.5 w-3.5"})})]})},T.id))]})]})})}function Npn({open:s,onOpenChange:t}){const{data:n,isLoading:r}=$R(),a=pqe(),i=s2s(),l=n2s(),[o,c]=N.useState(""),[d,u]=N.useState(null),[h,m]=N.useState(""),f=async()=>{if(o.trim())try{await a.mutateAsync(o.trim()),c("")}catch(_){ie.error(_.message||"Failed to add lead source")}},g=async _=>{if(h.trim())try{await i.mutateAsync({id:_,name:h.trim()}),u(null)}catch(b){ie.error(b.message||"Failed to update")}},y=async(_,b)=>{if(confirm(`Remove lead source "${b}"? Contacts using it will keep the label but it won't appear in new dropdowns.`))try{await l.mutateAsync(_)}catch(k){ie.error(k.message||"Failed to remove")}},x=_=>{u(_.id),m(_.name)};return e.jsx(Bs,{open:s,onOpenChange:t,children:e.jsxs(Fs,{className:"max-w-md",children:[e.jsx(qs,{children:e.jsx($s,{children:"Manage Lead Sources"})}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(we,{placeholder:"New lead source name...",value:o,onChange:_=>c(_.target.value),onKeyDown:_=>_.key==="Enter"&&f(),className:"flex-1 h-9"}),e.jsxs(B,{size:"sm",onClick:f,disabled:!o.trim()||a.isPending,className:"h-9",children:[e.jsx(nn,{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(_=>e.jsx("div",{className:"flex items-center gap-2 p-2 rounded-lg hover:bg-accent/50 group",children:d===_.id?e.jsxs(e.Fragment,{children:[e.jsx(we,{value:h,onChange:b=>m(b.target.value),onKeyDown:b=>b.key==="Enter"&&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:()=>g(_.id),children:e.jsx(pa,{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(hr,{className:"h-4 w-4"})})]}):e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"flex-1 text-sm",children:_.name}),_.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:()=>x(_),children:e.jsx(Ja,{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(_.id,_.name),children:e.jsx(qn,{className:"h-3.5 w-3.5"})})]}),!_.owner_user_id&&e.jsx("span",{className:"text-xs text-muted-foreground",children:"Default"})]})},_.id))]})]})})}function fIt({value:s,onChange:t,label:n="Lead Source"}){const{data:r}=$R(),a=pqe(),[i,l]=N.useState(!1),[o,c]=N.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(re,{children:n}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(Ns,{value:s||"_none",onValueChange:u=>t(u==="_none"?"":u),children:[e.jsx(ws,{className:"flex-1",children:e.jsx(ks,{placeholder:"Select lead source"})}),e.jsxs(js,{children:[e.jsx(nt,{value:"_none",children:"No source"}),r==null?void 0:r.map(u=>e.jsx(nt,{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(hr,{className:"h-4 w-4"}):e.jsx(nn,{className:"h-4 w-4"})})]}),i&&e.jsxs("div",{className:"flex gap-2",children:[e.jsx(we,{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 l7e({contactId:s,currentSpouseContactId:t,currentSpouseName:n,currentSpouseEmail:r,onLink:a,onUnlink:i,isEditing:l}){const o=tr(),c=Ya(),[d,u]=N.useState(!1),[h,m]=N.useState(""),{data:f}=mt({queryKey:["innercircle-contact-spouse",t],queryFn:async()=>{const{data:y,error:x}=await H.from("innercircle_contacts").select("id, first_name, last_name, email, phone, birthday").eq("id",t).maybeSingle();if(x)throw x;return y},enabled:!!t}),{data:g}=mt({queryKey:["spouse-search",c,s,h],queryFn:async()=>{let y=H.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:x,error:_}=await y;if(_)throw _;return x},enabled:d&&!!c});if(t&&f){const y=`${f.first_name} ${f.last_name||""}`.trim();return e.jsxs("div",{className:"space-y-1",children:[e.jsx(re,{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(Ro,{className:"h-4 w-4 text-muted-foreground shrink-0"}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("button",{onClick:()=>o(`/mission-control/contacts/${f.id}`),className:"text-sm font-medium text-primary hover:underline truncate block",children:y}),e.jsx("div",{className:"text-xs text-muted-foreground truncate",children:[f.phone,f.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(kD,{className:"h-3.5 w-3.5 mr-1"}),"Unlink"]}),!l&&e.jsx(B,{variant:"ghost",size:"sm",onClick:()=>o(`/mission-control/contacts/${f.id}`),className:"shrink-0 h-7 px-2",children:e.jsx(vi,{className:"h-3.5 w-3.5"})})]})]})}return!t&&(n||r)?e.jsxs("div",{className:"space-y-1",children:[e.jsx(re,{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(Ro,{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(rc,{open:d,onOpenChange:u,children:[e.jsx(ac,{asChild:!0,children:e.jsxs(B,{variant:"outline",size:"sm",className:"shrink-0 h-7 px-2",children:[e.jsx(cd,{className:"h-3.5 w-3.5 mr-1"}),"Link Contact"]})}),e.jsx(Zl,{className:"w-72 p-2",align:"end",children:e.jsx(fht,{search:h,setSearch:m,results:g,onSelect:y=>{a(y),u(!1),m("")}})})]})]})]}):l?e.jsxs("div",{className:"space-y-1",children:[e.jsx(re,{className:"text-sm font-medium",children:"Spouse / Partner"}),e.jsxs(rc,{open:d,onOpenChange:u,children:[e.jsx(ac,{asChild:!0,children:e.jsxs(B,{variant:"outline",className:"w-full justify-start text-muted-foreground font-normal h-10",children:[e.jsx(cd,{className:"h-4 w-4 mr-2"}),"Link an existing contact as spouse..."]})}),e.jsx(Zl,{className:"w-72 p-2",align:"start",children:e.jsx(fht,{search:h,setSearch:m,results:g,onSelect:y=>{a(y),u(!1),m("")}})})]})]}):null}function fht({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(Gr,{className:"absolute left-2 top-2.5 h-3.5 w-3.5 text-muted-foreground"}),e.jsx(we,{value:s,onChange:a=>t(a.target.value),placeholder:"Search contacts...",className:"pl-7 h-8 text-sm",autoFocus:!0})]}),e.jsx(lo,{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 tne=new Map;async function kpn(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 Spn(s,t=256){const n=s.trim().toLowerCase();if(!n||!n.includes("@"))return null;const r=`${n}|${t}`;if(tne.has(r))return tne.get(r)??null;try{const i=`https://gravatar.com/avatar/${await kpn(n)}?s=${t}&d=404`;return tne.set(r,i),i}catch{return tne.set(r,null),null}}function Cpn(s,t=256){const[n,r]=N.useState(null);return N.useEffect(()=>{let a=!0;if(!s){r(null);return}return Spn(s,t).then(i=>{a&&r(i)}),()=>{a=!1}},[s,t]),n}function hGe({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=Cpn(n?null:r,Math.max(64,a*2)),[u,h]=N.useState(!1);N.useEffect(()=>h(!1),[d]);const m=n||(u?null:d);return e.jsx("div",{className:Ot("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})})}const Apn=5*1024*1024;function gIt({contactId:s,firstName:t,lastName:n,avatarUrl:r,email:a,size:i=88}){const l=N.useRef(null),o=as(),[c,d]=N.useState(!1),u=()=>{o.invalidateQueries({queryKey:["innercircle-contacts"]}),o.invalidateQueries({queryKey:["innercircle-contact"]}),o.invalidateQueries({queryKey:["contact",s]})},h=async g=>{const{error:y}=await H.from("innercircle_contacts").update({avatar_url:g}).eq("id",s);if(y)throw y;u()},m=async g=>{var y;if(!g.type.startsWith("image/")){xa({title:"Please choose an image file",variant:"destructive"});return}if(g.size>Apn){xa({title:"Image too large",description:"Please use an image under 5MB.",variant:"destructive"});return}d(!0);try{const{data:x}=await H.auth.getUser(),_=(y=x.user)==null?void 0:y.id,b=(g.name.split(".").pop()||"jpg").toLowerCase(),k=`contacts/${_}/${s}-${Date.now()}.${b}`,{error:A}=await H.storage.from("avatars").upload(k,g,{upsert:!0,contentType:g.type});if(A)throw A;const{data:T}=H.storage.from("avatars").getPublicUrl(k);await h(T.publicUrl),xa({title:"Photo updated"})}catch(x){xa({title:"Upload failed",description:x.message,variant:"destructive"})}finally{d(!1),l.current&&(l.current.value="")}},f=async()=>{d(!0);try{await h(null),xa({title:"Photo removed"})}catch(g){xa({title:"Could not remove photo",description:g.message,variant:"destructive"})}finally{d(!1)}};return e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs("button",{type:"button",onClick:()=>{var g;return(g=l.current)==null?void 0:g.click()},disabled:c,className:"relative group rounded-full focus:outline-none focus-visible:ring-2 focus-visible:ring-ring","aria-label":r?"Change contact photo":"Upload contact photo",children:[e.jsx(hGe,{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(us,{className:"h-5 w-5 text-background animate-spin"}):e.jsx($0,{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(us,{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:f,disabled:c,children:[e.jsx(qn,{className:"h-3.5 w-3.5"}),"Remove"]}),e.jsx("input",{ref:l,type:"file",accept:"image/*",className:"hidden",onChange:g=>{var x;const y=(x=g.target.files)==null?void 0:x[0];y&&m(y)}})]})}const Tpn={warm:"stroke-emerald-500",cooling:"stroke-amber-500","at-risk":"stroke-red-500"},Epn={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 xIt({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:Ot("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:Tpn[t]})]}),e.jsx("span",{className:Ot("absolute inset-0 flex items-center justify-center font-semibold tabular-nums",Epn[t],n>=56?"text-lg":"text-[11px]"),children:o})]})}function Mpn(s,t){const n=[];if(s.daysSinceTouch===null?n.push({id:"first-touch",label:"Reach out for the first time",detail:"This contact has no logged touches yet. A single call or note starts the clock.",points:40,action:"touch"}):s.daysSinceTouch>14&&n.push({id:"recent-touch",label:"Log a touch this week",detail:`It has been ${s.daysSinceTouch} days. Touching base within 14 days earns full recency credit.`,points:Math.max(0,40-s.breakdown.recency),action:"touch"}),s.touchCountLast12Months<12){const r=12-s.touchCountLast12Months;n.push({id:"cadence",label:`Build to 12 touches a year (${r} to go)`,detail:"Monthly contact is the cadence that turns a name in your database into repeat and referral business.",points:Math.max(0,30-s.breakdown.touchpoints),action:"touch"})}return(!t.birthday||!t.home_anniversary)&&n.push({id:"dates",label:"Add their key dates",detail:!t.birthday&&!t.home_anniversary?"No birthday or home anniversary on file. Add them and the Life Event Autopilot will reach out for you.":t.birthday?"No home anniversary on file. Add it to unlock the anniversary campaign.":"No birthday on file. Add it so the birthday campaign can run automatically.",points:0,action:"edit"}),(!t.email||!t.phone)&&n.push({id:"contact-info",label:t.email?"Add a phone number":"Add an email address",detail:"Missing contact info blocks automated campaigns and quick touches.",points:0,action:"edit"}),s.hasTransaction||n.push({id:"transaction",label:"Link a past transaction",detail:"If you have closed a deal with them, connecting it adds real weight to the relationship.",points:20,action:"edit"}),n.slice(0,4)}function Lpn({score:s,contact:t,onEdit:n,onLogTouch:r}){const a=Mpn(s,t);return a.length===0?e.jsxs("div",{className:"mt-3 flex items-start gap-2 rounded-xl bg-emerald-500/10 px-3 py-2.5",children:[e.jsx(pa,{className:"mt-0.5 h-4 w-4 shrink-0 text-emerald-600 dark:text-emerald-400"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"This relationship is in great shape. Keep the cadence going and the score stays high."})]}):e.jsxs("div",{className:"mt-3 border-t pt-3",children:[e.jsxs("div",{className:"mb-2 flex items-center gap-1.5",children:[e.jsx(Z2,{className:"h-3.5 w-3.5 text-amber-500"}),e.jsx("p",{className:"text-xs font-semibold uppercase tracking-wide text-muted-foreground",children:"How to raise this score"})]}),e.jsx("ul",{className:"space-y-2",children:a.map(i=>e.jsxs("li",{className:"flex items-start gap-2",children:[e.jsx("span",{className:"mt-1.5 h-1.5 w-1.5 shrink-0 rounded-full bg-primary/60"}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("p",{className:"text-sm font-medium leading-tight",children:i.label}),i.points>0&&e.jsxs("span",{className:"shrink-0 rounded-full bg-primary/10 px-1.5 py-0.5 text-[10px] font-semibold text-primary",children:["+",i.points]})]}),e.jsx("p",{className:"mt-0.5 text-xs leading-snug text-muted-foreground",children:i.detail}),i.action==="edit"&&n&&e.jsx(B,{variant:"link",size:"sm",className:"h-auto p-0 text-xs",onClick:n,children:"Update contact"}),i.action==="touch"&&r&&e.jsx(B,{variant:"link",size:"sm",className:"h-auto p-0 text-xs",onClick:r,children:"Log a touch"})]})]},i.id))})]})}const Ppn={warm:"Strong",cooling:"Cooling off","at-risk":"Needs attention"};function Ipn({contact:s,deal:t,open:n,onOpenChange:r,onEdit:a,index:i,total:l,onPrev:o,onNext:c}){var I;const d=tr(),{data:u}=fU(),h=qQ(),[m,f]=N.useState(null),[g,y]=N.useState(!1),{gmailEmail:x}=_f(),_=s==null?void 0:s.spouse_contact_id,{data:b}=mt({queryKey:["innercircle-contact-spouse",_],queryFn:async()=>{const{data:M,error:L}=await H.from("innercircle_contacts").select("id, first_name, last_name, email, phone, birthday, avatar_url").eq("id",_).maybeSingle();if(L)throw L;return M},enabled:!!_&&n});if(!s)return null;const k=async M=>{f(M);try{await h.mutateAsync({contactId:s.id,actionTypeId:M})}finally{f(null)}},A=`${s.first_name||""} ${s.last_name||""}`.trim();A.split(" ").filter(Boolean).map(M=>M[0]).join("").toUpperCase().slice(0,2);const T=[s.city,s.state].filter(Boolean).join(", "),P=s.relationshipScore;return e.jsxs(l1,{open:n,onOpenChange:r,children:[e.jsxs(Gy,{side:"right",className:"w-full sm:max-w-md overflow-y-auto p-0",children:[(o||c)&&e.jsxs("div",{className:"sticky top-0 z-10 flex items-center justify-between gap-2 border-b bg-background/95 px-5 py-2 backdrop-blur",children:[e.jsxs(B,{variant:"ghost",size:"sm",className:"gap-1 px-2",onClick:o,disabled:!o,children:[e.jsx(Fc,{className:"h-4 w-4"}),"Prev"]}),typeof i=="number"&&typeof l=="number"&&e.jsxs("span",{className:"text-xs font-medium text-muted-foreground",children:[i+1," of ",l," on this page"]}),e.jsxs(B,{variant:"ghost",size:"sm",className:"gap-1 px-2",onClick:c,disabled:!c,children:["Next",e.jsx(Qa,{className:"h-4 w-4"})]})]}),e.jsxs("div",{className:"p-5 space-y-5",children:[e.jsxs(gb,{className:"space-y-0 text-left",children:[e.jsx(xb,{className:"sr-only",children:A}),e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx(gIt,{contactId:s.id,firstName:s.first_name,lastName:s.last_name,avatarUrl:s.avatar_url,email:s.email,size:56}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("h2",{className:"text-lg font-bold leading-tight truncate",children:A}),e.jsxs("div",{className:"mt-1.5 space-y-1 text-sm text-muted-foreground",children:[s.email&&e.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[e.jsx(mn,{className:"h-3.5 w-3.5 shrink-0"}),e.jsx("span",{className:"truncate",children:s.email})]}),s.phone&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ga,{className:"h-3.5 w-3.5 shrink-0"}),e.jsx("span",{children:s.phone})]}),T&&e.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[e.jsx(ii,{className:"h-3.5 w-3.5 shrink-0"}),e.jsx("span",{className:"truncate",children:T})]})]})]})]})]}),e.jsxs("div",{className:"rounded-2xl border p-4",children:[e.jsxs("div",{className:"flex items-center justify-between gap-4",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"text-xs font-semibold uppercase tracking-wide text-muted-foreground mb-1",children:"Relationship Health"}),e.jsx("p",{className:"text-base font-semibold",children:Ppn[P.status]??P.status}),e.jsx("p",{className:"text-xs text-muted-foreground mt-0.5",children:P.lastTouchDate?`Last touch ${Js(new Date(P.lastTouchDate),"MMM d, yyyy")}`:"Never contacted"})]}),e.jsx(xIt,{score:P.score,status:P.status,size:64})]}),e.jsx(Lpn,{score:P,contact:s,onEdit:a?()=>a(s):void 0})]}),e.jsxs("div",{className:"rounded-2xl border p-4",children:[e.jsx("p",{className:"text-xs font-semibold uppercase tracking-wide text-muted-foreground mb-2",children:"Suggested Next Action"}),e.jsx(x5e,{contact:s})]}),e.jsxs("div",{className:"grid grid-cols-3 gap-2",children:[e.jsxs(B,{variant:"outline",size:"sm",className:"gap-1.5",disabled:!s.email,onClick:()=>y(!0),children:[e.jsx(mn,{className:"h-4 w-4"})," Email"]}),e.jsx(B,{variant:"outline",size:"sm",className:"gap-1.5",asChild:!0,disabled:!s.phone,children:e.jsxs("a",{href:s.phone?`sms:${s.phone}`:void 0,children:[e.jsx(xo,{className:"h-4 w-4"})," Text"]})}),e.jsx(B,{variant:"outline",size:"sm",className:"gap-1.5",asChild:!0,disabled:!s.phone,children:e.jsxs("a",{href:s.phone?`tel:${s.phone}`:void 0,children:[e.jsx(ga,{className:"h-4 w-4"})," Call"]})})]}),e.jsxs(qd,{children:[e.jsx(Vd,{asChild:!0,children:e.jsxs(B,{variant:"secondary",className:"w-full gap-1.5",disabled:!!m,children:[m?e.jsx(us,{className:"h-4 w-4 animate-spin"}):e.jsx(Hr,{className:"h-4 w-4"}),"Log a touch"]})}),e.jsxs(Ld,{align:"start",className:"w-56 bg-popover z-50",children:[e.jsx(cE,{children:"What did you do?"}),u==null?void 0:u.map(M=>e.jsx(ba,{onClick:()=>k(M.id),children:M.name},M.id))]})]}),(t||s.tags&&s.tags.length>0)&&e.jsxs("div",{className:"flex flex-wrap gap-1.5",children:[e.jsx(o7e,{deal:t}),(I=s.tags)==null?void 0:I.map(M=>{var L;return e.jsx(We,{variant:"secondary",className:"text-xs",children:(L=M.relationship_type)==null?void 0:L.name},M.id)})]}),(b||s.spouse_name)&&e.jsxs("div",{className:"rounded-2xl border p-4",children:[e.jsxs("p",{className:"text-xs font-semibold uppercase tracking-wide text-muted-foreground mb-3 flex items-center gap-1.5",children:[e.jsx(Yn,{className:"h-3.5 w-3.5"})," Spouse / Partner"]}),b?e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(hGe,{firstName:b.first_name,lastName:b.last_name,avatarUrl:b.avatar_url,email:b.email,size:40}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("button",{className:"font-medium hover:underline truncate block text-left",onClick:()=>d(`/mission-control/contacts/${b.id}`),children:`${b.first_name||""} ${b.last_name||""}`.trim()}),e.jsx("p",{className:"text-xs text-muted-foreground truncate",children:[b.phone,b.email].filter(Boolean).join(" · ")||"No contact info"})]}),e.jsx(B,{variant:"ghost",size:"icon","aria-label":"Open spouse record",onClick:()=>d(`/mission-control/contacts/${b.id}`),children:e.jsx(Tr,{className:"h-4 w-4"})})]}):e.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[e.jsx(co,{className:"h-3.5 w-3.5 text-muted-foreground"}),e.jsx("span",{children:s.spouse_name}),s.spouse_email&&e.jsxs("span",{className:"text-xs text-muted-foreground truncate",children:["· ",s.spouse_email]})]}),(s.spouse_birthday||(b==null?void 0:b.birthday))&&e.jsxs("div",{className:"mt-3 flex items-center gap-2 text-sm text-muted-foreground",children:[e.jsx(Fm,{className:"h-3.5 w-3.5"}),"Spouse birthday · ",Js(Tc(s.spouse_birthday||b.birthday),"MMM d, yyyy")]})]}),(s.birthday||s.home_anniversary||s.created_at)&&e.jsxs("div",{className:"rounded-2xl border p-4 space-y-2",children:[e.jsx("p",{className:"text-xs font-semibold uppercase tracking-wide text-muted-foreground",children:"Key Dates"}),s.birthday&&e.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[e.jsx(ta,{className:"h-3.5 w-3.5 text-muted-foreground"}),"Birthday · ",Js(Tc(s.birthday),"MMM d, yyyy")]}),s.home_anniversary&&e.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[e.jsx(_a,{className:"h-3.5 w-3.5 text-muted-foreground"}),"Home anniversary · ",Js(Tc(s.home_anniversary),"MMM d, yyyy")]}),s.created_at&&e.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[e.jsx(Xr,{className:"h-3.5 w-3.5"}),"Added ",Js(new Date(s.created_at),"MMM d, yyyy")]})]}),s.notes&&e.jsxs("div",{className:"rounded-2xl border p-4",children:[e.jsx("p",{className:"text-xs font-semibold uppercase tracking-wide text-muted-foreground mb-2",children:"Notes"}),e.jsx("p",{className:"text-sm whitespace-pre-wrap leading-relaxed",children:s.notes})]}),e.jsxs("div",{className:"flex items-center gap-2 pt-1",children:[e.jsxs(B,{className:"flex-1 gap-1.5",onClick:()=>d(`/mission-control/contacts/${s.id}`),children:[e.jsx(Tr,{className:"h-4 w-4"}),"Open full record"]}),a&&e.jsx(B,{variant:"outline",size:"icon",onClick:()=>a(s),"aria-label":"Edit contact",children:e.jsx(Ja,{className:"h-4 w-4"})})]})]})]}),s.email&&e.jsx(Y_,{open:g,onOpenChange:y,contact:{id:s.id,first_name:s.first_name,last_name:s.last_name,email:s.email},gmailEmail:x})]})}function Dpn({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(wu,{children:[e.jsx(ju,{asChild:!0,children:e.jsx("span",{role:n?"button":void 0,onClick:n?a=>{a.stopPropagation(),n()}:void 0,className:`inline-flex h-5 w-5 shrink-0 items-center justify-center rounded-full bg-muted text-muted-foreground ${n?"cursor-pointer hover:bg-accent hover:text-accent-foreground":""}`,"aria-label":r,children:e.jsx(Yn,{className:"h-3 w-3"})})}),e.jsx(nu,{children:r})]})}function yIt(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 ght(s){if(!s)return null;const t=Tc(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:Yl,color:"text-violet-600 dark:text-violet-400",match:s=>s.relationshipScore.daysSinceTouch===null},{key:"stale-90",title:"Stale 90+ Days",icon:Xr,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:nj,color:"text-cyan-600 dark:text-cyan-400",match:s=>s.relationshipScore.status==="cooling"},{key:"birthdays-soon",title:"Birthdays Soon",icon:Fm,color:"text-pink-600 dark:text-pink-400",match:(s,t)=>t.daysToBirthday!==null&&t.daysToBirthday<=30},{key:"anniversary-soon",title:"Home Anniversary",icon:_a,color:"text-emerald-600 dark:text-emerald-400",match:(s,t)=>t.daysToAnniv!==null&&t.daysToAnniv<=30},{key:"has-deal",title:"Active Deal",icon:vg,color:"text-teal-700 dark:text-teal-400",match:(s,t)=>t.hasDeal},{key:"website-active",title:"Active on Site",icon:au,color:"text-indigo-600 dark:text-indigo-400",match:()=>!1},{key:"vips",title:"VIPs",icon:Cn,color:"text-amber-600 dark:text-amber-300",match:s=>s.relationshipScore.score>=80},{key:"missing-info",title:"Missing Info",icon:xd,color:"text-slate-600 dark:text-slate-400",match:s=>yIt(s)}];function Rpn({contacts:s,contactDealsMap:t,websiteActiveIds:n,totalCount:r,activeKey:a,onSelectSegment:i,currentFilters:l,currentSortBy:o,activeViewId:c,onApplyView:d,onClearAll:u}){const{data:h}=lGe(),m=QPt(),f=JPt(),[g,y]=N.useState(!1),[x,_]=N.useState(""),b=N.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};if(!s)return P;for(const I of s){const M={hasDeal:!!(t&&t[I.id]),daysToBirthday:ght(I.birthday),daysToAnniv:ght(I.home_anniversary)};for(const L of xht)L.key!=="website-active"&&L.match(I,M)&&P[L.key]++}return P},[s,t,n]),k=!!l.search||!!l.type&&l.type!=="all"||!!l.status&&l.status!=="all"||!!l.behavior&&Object.values(l.behavior).some(P=>P!==void 0&&P!==!1),A=async()=>{x.trim()&&(await m.mutateAsync({name:x.trim(),filters:l,sort_by:o}),_(""),y(!1))},T="inline-flex items-center gap-1.5 h-8 shrink-0 rounded-full border px-3 text-xs font-medium transition-colors whitespace-nowrap";return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex items-center gap-2 overflow-x-auto pb-1 -mx-1 px-1 [scrollbar-width:none] [&::-webkit-scrollbar]:hidden",children:[e.jsxs("button",{type:"button",onClick:u,className:Ot(T,!a&&!c?"bg-primary text-primary-foreground border-primary":"bg-card hover:bg-accent border-border"),children:[e.jsx(Yn,{className:"h-3.5 w-3.5"}),"All Contacts",e.jsx("span",{className:"tabular-nums opacity-70",children:r.toLocaleString()})]}),h==null?void 0:h.map(P=>{const I=c===P.id;return e.jsxs("div",{className:Ot(T,"group pr-1",I?"bg-primary text-primary-foreground border-primary":"bg-card hover:bg-accent border-border"),children:[e.jsx("button",{type:"button",onClick:()=>d(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),I&&u()},children:e.jsx(hr,{className:"h-3 w-3"})})]},P.id)}),e.jsx("div",{className:"h-5 w-px bg-border shrink-0"}),xht.map(P=>{const I=P.icon,M=b[P.key],L=a===P.key;return e.jsxs("button",{type:"button",onClick:()=>i(L?null:P.key),"aria-pressed":L,className:Ot(T,L?"bg-primary text-primary-foreground border-primary":"bg-card hover:bg-accent border-border",!L&&M===0&&"opacity-55"),children:[e.jsx(I,{className:Ot("h-3.5 w-3.5",L?"":P.color)}),P.title,e.jsx("span",{className:"tabular-nums opacity-70",children:M.toLocaleString()})]},P.key)}),e.jsxs(B,{variant:"ghost",size:"sm",className:"h-8 gap-1.5 text-xs shrink-0",disabled:!k,onClick:()=>y(!0),children:[e.jsx(aD,{className:"h-3.5 w-3.5"}),"Save view"]})]}),e.jsx(Bs,{open:g,onOpenChange:y,children:e.jsxs(Fs,{className:"sm:max-w-sm",children:[e.jsxs(qs,{children:[e.jsx($s,{children:"Save this view"}),e.jsx(Ar,{children:"Your current search, filters, and sorting are saved as a one-click chip."})]}),e.jsx(we,{autoFocus:!0,placeholder:"e.g. Past clients cooling off",value:x,onChange:P=>_(P.target.value),onKeyDown:P=>P.key==="Enter"&&A()}),e.jsxs(Cr,{children:[e.jsx(B,{variant:"outline",onClick:()=>y(!1),children:"Cancel"}),e.jsx(B,{onClick:A,disabled:!x.trim()||m.isPending,children:"Save view"})]})]})})]})}const yht=[{key:"relationship",label:"Relationship"},{key:"stage",label:"Stage"},{key:"leadSource",label:"Lead Source"},{key:"tags",label:"Tags"},{key:"lastTouch",label:"Last Touch"},{key:"nextAction",label:"Next Action"},{key:"dealValue",label:"Pipeline Value"},{key:"email",label:"Email"},{key:"phone",label:"Phone"},{key:"address",label:"Address"},{key:"birthday",label:"Birthday"}],ZLe={relationship:!0,stage:!0,leadSource:!0,tags:!0,lastTouch:!0,nextAction:!0,dealValue:!0,email:!1,phone:!1,address:!1,birthday:!1},vht="innercircle:contact-columns:v1";function Opn(){const[s,t]=N.useState(()=>{try{const a=localStorage.getItem(vht);if(a)return{...ZLe,...JSON.parse(a)}}catch{}return ZLe});N.useEffect(()=>{try{localStorage.setItem(vht,JSON.stringify(s))}catch{}},[s]);const n=N.useCallback(a=>{t(i=>({...i,[a]:!i[a]}))},[]),r=N.useCallback(()=>t(ZLe),[]);return{columns:s,toggle:n,reset:r}}function Fpn({columns:s,onToggle:t,onReset:n}){const r=yht.filter(a=>s[a.key]).length;return e.jsxs(rc,{children:[e.jsx(ac,{asChild:!0,children:e.jsxs(B,{variant:"outline",size:"sm",className:"h-8 gap-1.5 rounded-lg text-xs",children:[e.jsx(GC,{className:"h-3.5 w-3.5"}),"Columns",e.jsx(We,{variant:"secondary",className:"h-5 px-1.5 text-[10px]",children:r})]})}),e.jsxs(Zl,{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(hf,{className:"h-3 w-3"}),"Reset"]})]}),e.jsx("div",{className:"max-h-[320px] overflow-y-auto space-y-0.5",children:yht.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(Bi,{checked:s[a.key],className:"pointer-events-none"}),e.jsx("span",{className:"flex-1 text-left",children:a.label})]},a.key))}),e.jsx("p",{className:"px-2 pt-2 text-[11px] text-muted-foreground",children:"Name and actions are always shown."})]})]})}function zpn(){var qr;const s=tr(),[t,n]=$c(),{user:r}=Ls(),a=qU(),i=as(),{columns:l,toggle:o,reset:c}=Opn(),d=t.get("type"),u=t.get("filter")??t.get("status"),h=t.get("new")==="true",{contactsWithScores:m,isLoading:f}=n3e(),{activeContactIds:g,hasLeadSite:y}=Smn(),{data:x}=bpn(),{data:_}=K_(),{data:b}=_pn(),{data:k}=UU(),{data:A}=zCe(),[T,P]=N.useState(new Set),[I,M]=N.useState("any"),L=e3e(),z=dqe(),$=uqe(),V=k4t(),[W,G]=N.useState(""),[X,te]=N.useState(!1),[ne,me]=N.useState(d||"all"),[ue,ce]=N.useState(u||"all"),[ae,he]=N.useState("date-added"),[xe,ve]=N.useState("all"),[ge,be]=N.useState({}),Se=N.useMemo(()=>Object.values(ge).filter(Xt=>Xt!==void 0&&Xt!==!1&&Xt!=="").length,[ge]),[Ie,Me]=N.useState(!1),{behaviorMap:Re,hasLeadSite:Be}=fpn(),[Ne,Ge]=N.useState(h),[Ce,Fe]=N.useState(null),[Ae,Xe]=N.useState(!1),[$e,Ye]=N.useState(!1),[Je,Ke]=N.useState(null),[st,rt]=N.useState(""),[Ze,ht]=N.useState(new Set),[Bt,Ct]=N.useState(!1),[Yt,Kt]=N.useState(null),Xs=Math.max(1,parseInt(t.get("page")||"1",10)||1),[zs,Vt]=N.useState(Xs),At=N.useCallback(Xt=>{Vt(Gn=>{const Jr=typeof Xt=="function"?Xt(Gn):Xt;return n(Or=>{const ja=new URLSearchParams(Or);return Jr<=1?ja.delete("page"):ja.set("page",String(Jr)),ja},{replace:!0}),Jr})},[]),[Os,Nt]=N.useState(50),[ms,Ys]=N.useState("my"),[It,Ds]=N.useState(!1),[As,Hs]=N.useState(!1),{data:Rs}=Cj(),{addToLeadPond:en}=EEt(Rs==null?void 0:Rs.teamId),Rn=!!((qr=Rs==null?void 0:Rs.team)!=null&&qr.lead_pond_enabled&&(Rs!=null&&Rs.teamId)),Bn=!!(Rs!=null&&Rs.teamId),[Dn,Jn]=N.useState([]),[ua,Mr]=N.useState(!1),sn=Xt=>{Jn([Xt]),Mr(!0)},ki=Xt=>{Jn(Xt),Mr(!0)},ia=Xt=>{Rs!=null&&Rs.teamId&&en.mutate({contact_id:Xt,team_id:Rs.teamId})},vr=Xt=>{Rs!=null&&Rs.teamId&&Xt.forEach(Gn=>{en.mutate({contact_id:Gn,team_id:Rs.teamId})})},Nr=N.useCallback(Xt=>{Ct(!1),ht(Gn=>{const Jr=new Set(Gn);return Jr.has(Xt)?Jr.delete(Xt):Jr.add(Xt),Jr})},[]);N.useEffect(()=>{if(!(r!=null&&r.id))return;const Xt=H.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()=>{H.removeChannel(Xt)}},[i,r==null?void 0:r.id]),N.useEffect(()=>{u&&ce(u)},[u]);const[rn,Zn]=N.useState({first_name:"",last_name:"",email:"",phone:"",address:"",city:"",state:"",zip_code:"",birthday:"",home_anniversary:"",spouse_name:"",spouse_email:"",lead_source_id:"",notes:"",tagIds:[]});N.useEffect(()=>{h&&Ge(!0)},[h]),N.useEffect(()=>{var Xt;Ce&&Zn({first_name:Ce.first_name||"",last_name:Ce.last_name||"",email:Ce.email||"",phone:Ce.phone||"",address:Ce.address||"",city:Ce.city||"",state:Ce.state||"",zip_code:Ce.zip_code||"",birthday:Ce.birthday||"",home_anniversary:Ce.home_anniversary||"",spouse_name:Ce.spouse_name||"",spouse_email:Ce.spouse_email||"",lead_source_id:Ce.lead_source_id||"",notes:Ce.notes||"",tagIds:((Xt=Ce.tags)==null?void 0:Xt.map(Gn=>Gn.relationship_type_id))||[]})},[Ce]);const sa=N.useMemo(()=>{const Xt=new Set;return k==null||k.forEach(Gn=>{(Gn.name==="Recruits"||Gn.name==="Brokerage Agents")&&Xt.add(Gn.id)}),Xt},[k]),xs=N.useMemo(()=>Array.from(T).some(Xt=>sa.has(Xt)),[T,sa]),Ve=N.useMemo(()=>{const Xt={};return(m||[]).forEach(Gn=>{Xt[Gn.id]=`${Gn.first_name||""} ${Gn.last_name||""}`.trim()}),Xt},[m]),it=N.useMemo(()=>{if(!m)return[];let Xt=m.filter(Or=>{var Ta,Wn,Ra,mo,Ho,No,Go,Dd,Tu,Vm,Uc;if(!xs&&Or.synced_source)return!1;const ja=W===""||`${Or.first_name} ${Or.last_name}`.toLowerCase().includes(W.toLowerCase())||((Ta=Or.email)==null?void 0:Ta.toLowerCase().includes(W.toLowerCase()))||((Wn=Or.phone)==null?void 0:Wn.includes(W))||((Ra=Or.city)==null?void 0:Ra.toLowerCase().includes(W.toLowerCase()))||((mo=Or.state)==null?void 0:mo.toLowerCase().includes(W.toLowerCase()))||((Ho=Or.address)==null?void 0:Ho.toLowerCase().includes(W.toLowerCase()))||((No=Or.zip_code)==null?void 0:No.toLowerCase().includes(W.toLowerCase())),ea=ne==="all"||((Go=Or.tags)==null?void 0:Go.some(Eu=>Eu.relationship_type_id===ne)),dr=T.size===0||(()=>{const Eu=(A==null?void 0:A.filter(Ec=>Ec.contact_id===Or.id).map(Ec=>Ec.tag_id))||[];return I==="any"?Eu.some(Ec=>T.has(Ec)):Array.from(T).every(Ec=>Eu.includes(Ec))})(),Wi=!!((Dd=Or.address)!=null&&Dd.trim()||(Tu=Or.city)!=null&&Tu.trim()||(Vm=Or.state)!=null&&Vm.trim()||(Uc=Or.zip_code)!=null&&Uc.trim()),ho=xe==="all"||xe==="has-address"&&Wi||xe==="no-address"&&!Wi,oa=Or,Ha=ge,$i=(Ha.hasEmail===void 0||!!oa.email===Ha.hasEmail)&&(Ha.hasPhone===void 0||!!oa.phone===Ha.hasPhone)&&(Ha.hasAddress===void 0||Wi===Ha.hasAddress)&&(Ha.hasBirthday===void 0||!!oa.birthday===Ha.hasBirthday)&&(Ha.hasSpouse===void 0||!!(oa.spouse_name||oa.spouse_contact_id||oa.spouse_email)===Ha.hasSpouse)&&(Ha.hasCompany===void 0||!!(oa.company_name||oa.job_title)===Ha.hasCompany)&&(Ha.hasNotes===void 0||!!(oa.notes&&oa.notes.trim())===Ha.hasNotes)&&(!Ha.city||(oa.city||"").toLowerCase().includes(Ha.city.toLowerCase()))&&(!Ha.state||(oa.state||"").toLowerCase().includes(Ha.state.toLowerCase()))&&(!Ha.zip||((oa.zip||"")+(oa.zip_code||"")).toLowerCase().includes(Ha.zip.toLowerCase()))&&(!Ha.birthdayMonth||!!oa.birthday&&Tc(oa.birthday).getMonth()+1===Ha.birthdayMonth)&&(!Ha.anniversaryMonth||((Ha.anniversaryField||"home_anniversary")==="home_anniversary"?!!oa.home_anniversary&&Tc(oa.home_anniversary).getMonth()+1===Ha.anniversaryMonth:!!oa.wedding_anniversary&&Tc(oa.wedding_anniversary).getMonth()+1===Ha.anniversaryMonth))&&(!Ha.dateAddedFrom||!!oa.created_at&&oa.created_at.slice(0,10)>=Ha.dateAddedFrom)&&(!Ha.dateAddedTo||!!oa.created_at&&oa.created_at.slice(0,10)<=Ha.dateAddedTo)&&(!Ha.leadSourceId||oa.lead_source_id===Ha.leadSourceId||!oa.lead_source_id&&Ha.leadSourceId==="none");return ja&&ea&&dr&&ho&&$i});ue==="not-touched-90"?Xt=Xt.filter(Or=>{const ja=Or.relationshipScore.daysSinceTouch;return ja===null||ja>90}):ue==="at-risk"?Xt=Xt.filter(Or=>Or.relationshipScore.status==="at-risk"):ue==="cooling"?Xt=Xt.filter(Or=>Or.relationshipScore.status==="cooling"):ue==="warm"?Xt=Xt.filter(Or=>Or.relationshipScore.status==="warm"):ue==="has-deal"?Xt=Xt.filter(Or=>b&&b[Or.id]):ue==="no-deal"?Xt=Xt.filter(Or=>!b||!b[Or.id]):ue==="open-house"?Xt=Xt.filter(Or=>{var ea;return(((ea=Or.lead_source_ref)==null?void 0:ea.name)||Or.lead_source)==="Open House"}):ue==="website-active"?Xt=Xt.filter(Or=>g.has(Or.id)):ue==="never-contacted"?Xt=Xt.filter(Or=>Or.relationshipScore.daysSinceTouch===null):ue==="vips"?Xt=Xt.filter(Or=>Or.relationshipScore.score>=80):ue==="missing-info"?Xt=Xt.filter(Or=>yIt(Or)):ue==="birthdays-soon"?Xt=Xt.filter(Or=>{const ja=dI(Or.birthday);return ja!==null&&ja<=30}):ue==="anniversary-soon"?Xt=Xt.filter(Or=>{const ja=dI(Or.home_anniversary);return ja!==null&&ja<=30}):ue==="in-drip"?Xt=Xt.filter(Or=>((x==null?void 0:x[Or.id])??0)>0):ue==="not-in-drip"&&(Xt=Xt.filter(Or=>((x==null?void 0:x[Or.id])??0)===0));const Gn=ge;if(Gn.lastActive||Gn.registered||Gn.viewedListing||Gn.savedProperty||Gn.hasSavedSearch||Gn.requestedShowing||Gn.requestedValuation||Gn.websiteActiveOnly){const Or=Date.now(),ja={today:24*60*60*1e3,"7d":7*24*60*60*1e3,"30d":30*24*60*60*1e3,"90d":90*24*60*60*1e3};Xt=Xt.filter(ea=>{const dr=Re.get(ea.id);if(Gn.lastActive==="never"){if(dr!=null&&dr.lastActiveAt)return!1}else if(Gn.lastActive){const Wi=Or-ja[Gn.lastActive];if(!(dr!=null&&dr.lastActiveAt)||new Date(dr.lastActiveAt).getTime()0)||Gn.viewedListing==="multiple7d"&&!(dr&&dr.propertyViewCount7d>=3)||Gn.savedProperty&&!(dr&&dr.savedListingCount>0)||Gn.hasSavedSearch&&!(dr&&dr.activeSavedSearchCount>0)||Gn.requestedShowing&&!(dr&&dr.showingRequests>0)||Gn.requestedValuation&&!(dr&&dr.valuationRequests>0)||Gn.websiteActiveOnly&&!g.has(ea.id))})}return Xt=[...Xt].sort((Or,ja)=>{switch(ae){case"important-dates":{const ea=dI(Or.birthday),dr=dI(ja.birthday),Wi=dI(Or.home_anniversary),ho=dI(ja.home_anniversary),oa=[ea,Wi].filter($i=>$i!==null).sort(($i,Ta)=>($i??1/0)-(Ta??1/0))[0]??1/0,Ha=[dr,ho].filter($i=>$i!==null).sort(($i,Ta)=>($i??1/0)-(Ta??1/0))[0]??1/0;return oa-Ha}case"last-touched":{const ea=Or.relationshipScore.lastTouchDate,dr=ja.relationshipScore.lastTouchDate;return!ea&&!dr?0:ea?dr?new Date(ea).getTime()-new Date(dr).getTime():1:-1}case"next-touch":{const ea=Or.relationshipScore.daysSinceTouch,dr=ja.relationshipScore.daysSinceTouch;return ea===null&&dr===null?0:ea===null?-1:dr===null?1:dr-ea}case"score":return Or.relationshipScore.score-ja.relationshipScore.score;case"date-added":{const ea=Or.created_at,dr=ja.created_at;return!ea&&!dr?0:ea?dr?new Date(dr).getTime()-new Date(ea).getTime():-1:1}case"last-name":{const ea=(Or.last_name||"").toLowerCase(),dr=(ja.last_name||"").toLowerCase();if(ea!==dr)return ea.localeCompare(dr);const Wi=(Or.first_name||"").toLowerCase(),ho=(ja.first_name||"").toLowerCase();return Wi.localeCompare(ho)}case"name":default:{const ea=`${Or.first_name||""} ${Or.last_name||""}`.toLowerCase(),dr=`${ja.first_name||""} ${ja.last_name||""}`.toLowerCase();return ea.localeCompare(dr)}}}),Xt},[m,W,ne,T,I,ue,ae,b,A,g,x,xe,ge,Re,xs]),ft=it.length,kt=Math.max(1,Math.ceil(ft/Os)),Ut=Math.min(zs,kt),es=N.useMemo(()=>{const Xt=(Ut-1)*Os;return it.slice(Xt,Xt+Os)},[it,Ut,Os]),Ms=N.useRef(!1);N.useEffect(()=>{if(!Ms.current){Ms.current=!0;return}At(1)},[W,ne,T,I,ue,ae,xe,ge]);const bs=N.useCallback(()=>{Ct(!1),ht(Xt=>Xt.size>0?new Set:new Set(es.map(Gn=>Gn.id)))},[es]),Zs=N.useCallback(()=>{Ct(!0),ht(new Set(it.map(Xt=>Xt.id)))},[it]),[kn,gn]=N.useState(null),xr=N.useCallback((Xt,Gn)=>{G(Xt.search||""),me(Xt.type||"all"),ce(Xt.status||"all"),be(Xt.behavior||{}),he(Gn||"name")},[]),Kr=()=>{Zn({first_name:"",last_name:"",email:"",phone:"",address:"",city:"",state:"",zip_code:"",birthday:"",home_anniversary:"",spouse_name:"",spouse_email:"",lead_source_id:"",notes:"",tagIds:[]})},ca=async Xt=>{Xt.preventDefault();const Gn={...rn,lead_source_id:rn.lead_source_id||null};Ce?(await z.mutateAsync({id:Ce.id,...Gn}),Fe(null)):(await L.mutateAsync(Gn),Ge(!1)),Kr()},Er=async Xt=>{confirm("Are you sure you want to delete this contact?")&&await $.mutateAsync(Xt)};return e.jsx(Qs,{title:"Contacts",description:"Manage your InnerCircle contacts",children:e.jsxs("div",{className:"space-y-6 overflow-x-hidden",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("h1",{className:"text-2xl font-bold",children:"Contacts"}),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"})]}),Rs&&e.jsxs("div",{className:"flex bg-muted rounded-lg p-1 gap-0.5",children:[e.jsx("button",{onClick:()=>Ys("my"),className:`px-3 py-1.5 rounded-md text-sm font-medium transition-colors ${ms==="my"?"bg-background text-foreground shadow-sm":"text-muted-foreground hover:text-foreground"}`,children:"My Contacts"}),(Rs.team.contact_visibility==="full_team"||Rs.team.contact_visibility==="leader_only"&&Rs.role==="team_leader")&&e.jsxs("button",{onClick:()=>Ys("team"),className:`px-3 py-1.5 rounded-md text-sm font-medium transition-colors flex items-center gap-1.5 ${ms==="team"?"bg-background text-foreground shadow-sm":"text-muted-foreground hover:text-foreground"}`,children:[e.jsx(Yn,{className:"h-3.5 w-3.5"}),"Team"]}),Rs.team.lead_pond_enabled&&e.jsxs("button",{onClick:()=>Ys("lead-pond"),className:`px-3 py-1.5 rounded-md text-sm font-medium transition-colors flex items-center gap-1.5 ${ms==="lead-pond"?"bg-background text-foreground shadow-sm":"text-muted-foreground hover:text-foreground"}`,children:[e.jsx(K2,{className:"h-3.5 w-3.5"}),"Lead Pond"]})]})]}),e.jsx("div",{className:"flex items-center gap-4",children:e.jsxs(B,{variant:"ghost",size:"sm",onClick:()=>s("/mission-control"),children:[e.jsx(Fc,{className:"h-4 w-4 mr-1"}),"Back"]})}),ms==="team"?e.jsx($Ve,{}):ms==="lead-pond"&&Rs?e.jsx(UVe,{teamId:Rs.teamId}):e.jsxs(e.Fragment,{children:[e.jsx(Rpn,{contacts:m,contactDealsMap:b,websiteActiveIds:g,totalCount:(m||[]).length,activeViewId:kn,currentFilters:{search:W,type:ne,status:ue,behavior:ge},currentSortBy:ae,onApplyView:(Xt,Gn,Jr)=>{gn(Xt),xr(Gn,Jr),At(1)},onClearAll:()=>{gn(null),xr({search:"",type:"all",status:"all",behavior:{}},"name"),At(1)},activeKey:{"at-risk":"needs-attention",cooling:"cooling","not-touched-90":"stale-90","never-contacted":"never-contacted","birthdays-soon":"birthdays-soon","anniversary-soon":"anniversary-soon","has-deal":"has-deal","website-active":"website-active",vips:"vips","missing-info":"missing-info"}[ue]??null,onSelectSegment:Xt=>{const Jr=Xt?{"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"}[Xt]:"all";ce(Jr),At(1)}}),e.jsxs(_e,{className:"overflow-hidden",children:[e.jsxs("div",{className:"p-3 sm:p-4 bg-background",children:[e.jsxs("div",{className:"sm:hidden space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("div",{className:"relative flex-1 min-w-0",children:[e.jsx(Gr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(we,{placeholder:"Search contacts...",value:W,onChange:Xt=>G(Xt.target.value),className:"pl-9 h-10 rounded-xl bg-muted/40"})]}),e.jsxs(l1,{children:[e.jsx(PQ,{asChild:!0,children:e.jsxs(B,{variant:"outline",size:"icon",className:"h-10 w-10 rounded-xl relative shrink-0","aria-label":"Filters",children:[e.jsx(OT,{className:"h-4 w-4"}),(()=>{const Xt=(ne!=="all"?1:0)+(ue!=="all"?1:0)+(xe!=="all"?1:0)+T.size+Se;return Xt>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:Xt}):null})()]})}),e.jsxs(Gy,{side:"bottom",className:"h-[85vh] rounded-t-2xl overflow-y-auto",children:[e.jsx(gb,{className:"text-left",children:e.jsx(xb,{children:"Filters & Views"})}),e.jsxs("div",{className:"space-y-5 py-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{className:"text-xs uppercase tracking-wide text-muted-foreground",children:"Type"}),e.jsxs(Ns,{value:ne,onValueChange:me,children:[e.jsx(ws,{className:"h-11 rounded-xl bg-muted/40",children:e.jsx(ks,{placeholder:"All Types"})}),e.jsxs(js,{children:[e.jsx(nt,{value:"all",children:"All Types"}),_==null?void 0:_.filter(Xt=>Xt.active).map(Xt=>e.jsx(nt,{value:Xt.id,children:Xt.name},Xt.id))]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{className:"text-xs uppercase tracking-wide text-muted-foreground",children:"Status"}),e.jsxs(Ns,{value:ue,onValueChange:ce,children:[e.jsx(ws,{className:"h-11 rounded-xl bg-muted/40",children:e.jsx(ks,{placeholder:"All Status"})}),e.jsxs(js,{children:[e.jsx(nt,{value:"all",children:"All Status"}),e.jsx(nt,{value:"warm",children:"🟢 Warm"}),e.jsx(nt,{value:"cooling",children:"🟡 Cooling Off"}),e.jsx(nt,{value:"at-risk",children:"🔴 At Risk"}),e.jsx(nt,{value:"has-deal",children:"📋 Has Deal"}),e.jsx(nt,{value:"no-deal",children:"📭 No Deal"}),e.jsx(nt,{value:"open-house",children:"🏠 Open House"}),y&&e.jsx(nt,{value:"website-active",children:"🌐 Website Active"}),e.jsx(nt,{value:"in-drip",children:"🌱 In Drip Campaign"}),e.jsx(nt,{value:"not-in-drip",children:"🚫 Not In Drip"})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{className:"text-xs uppercase tracking-wide text-muted-foreground",children:"Address"}),e.jsxs(Ns,{value:xe,onValueChange:Xt=>ve(Xt),children:[e.jsx(ws,{className:"h-11 rounded-xl bg-muted/40",children:e.jsx(ks,{placeholder:"All Addresses"})}),e.jsxs(js,{children:[e.jsx(nt,{value:"all",children:"All Addresses"}),e.jsx(nt,{value:"has-address",children:"Has Address"}),e.jsx(nt,{value:"no-address",children:"No Address"})]})]})]}),k&&k.length>0&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(re,{className:"text-xs uppercase tracking-wide text-muted-foreground",children:"Tags"}),e.jsxs("div",{className:"flex items-center gap-1 bg-muted rounded-md p-0.5",children:[e.jsx("button",{onClick:()=>M("any"),className:`px-2 py-0.5 rounded text-xs font-medium ${I==="any"?"bg-background shadow-sm":"text-muted-foreground"}`,children:"Any"}),e.jsx("button",{onClick:()=>M("all"),className:`px-2 py-0.5 rounded text-xs font-medium ${I==="all"?"bg-background shadow-sm":"text-muted-foreground"}`,children:"All"})]})]}),e.jsx("div",{className:"flex flex-wrap gap-2",children:k.map(Xt=>{const Gn=T.has(Xt.id);return e.jsxs("button",{onClick:()=>{P(Jr=>{const Or=new Set(Jr);return Or.has(Xt.id)?Or.delete(Xt.id):Or.add(Xt.id),Or})},className:`inline-flex items-center gap-1.5 px-3 py-1.5 rounded-full text-xs border transition-colors ${Gn?"bg-primary text-primary-foreground border-primary":"bg-background border-border"}`,children:[e.jsx("span",{className:"h-2 w-2 rounded-full",style:{backgroundColor:Xt.color}}),Xt.name]},Xt.id)})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{className:"text-xs uppercase tracking-wide text-muted-foreground",children:"Sort by"}),e.jsxs(Ns,{value:ae,onValueChange:he,children:[e.jsx(ws,{className:"h-11 rounded-xl bg-muted/40",children:e.jsx(ks,{})}),e.jsxs(js,{children:[e.jsx(nt,{value:"name",children:"Name (A-Z)"}),e.jsx(nt,{value:"last-name",children:"Last Name (A-Z)"}),e.jsx(nt,{value:"important-dates",children:"Important Dates"}),e.jsx(nt,{value:"last-touched",children:"Last Touched"}),e.jsx(nt,{value:"next-touch",children:"Next Touch Due"}),e.jsx(nt,{value:"score",children:"Relationship Score"}),e.jsx(nt,{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:()=>Me(!0),children:[e.jsx(Cn,{className:"h-4 w-4"})," Advanced"]}),e.jsxs(B,{variant:"outline",className:"h-11 rounded-xl gap-1.5",onClick:()=>Ds(!0),children:[e.jsx(pf,{className:"h-4 w-4"})," Manage Tags"]})]}),e.jsx("div",{children:e.jsx(dht,{currentFilters:{search:W,type:ne,status:ue,behavior:ge},currentSortBy:ae,onApplySmartList:xr})}),e.jsx(B,{variant:"ghost",className:"w-full h-11 rounded-xl text-muted-foreground",onClick:()=>{me("all"),ce("all"),ve("all"),P(new Set),be({})},children:"Clear all filters"})]})]})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[e.jsxs(B,{onClick:()=>Ge(!0),className:"h-11 rounded-xl",children:[e.jsx(nn,{className:"h-4 w-4 mr-1.5"})," Add Contact"]}),e.jsxs(B,{onClick:()=>te(!0),className:"h-11 rounded-xl bg-gradient-to-r from-orange-500 to-red-500 hover:from-orange-600 hover:to-red-600 text-white border-0",children:[e.jsx(Cu,{className:"h-4 w-4 mr-1.5"})," Heat Map"]})]}),e.jsxs(qd,{children:[e.jsx(Vd,{asChild:!0,children:e.jsxs(B,{variant:"outline",className:"w-full h-10 rounded-xl gap-2",children:[e.jsx(ni,{className:"h-4 w-4"})," Import & Sync"]})}),e.jsxs(Ld,{align:"center",className:"w-[calc(100vw-2rem)] max-w-sm",children:[e.jsxs(ba,{onClick:()=>Xe(!0),children:[e.jsx(ni,{className:"h-4 w-4 mr-2"})," Import CSV"]}),e.jsxs(ba,{onClick:()=>Ye(!0),children:[e.jsx($y,{className:"h-4 w-4 mr-2"})," Import from Phone"]}),e.jsx("div",{className:"px-1 py-1 [&_button]:w-full [&_button]:justify-start [&_button]:h-9",children:e.jsx(oht,{})})]})]})]}),e.jsxs("div",{className:"hidden sm:flex items-center gap-3 flex-wrap",children:[e.jsxs("div",{className:"relative flex-1 min-w-[280px]",children:[e.jsx(Gr,{className:"absolute left-3.5 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(we,{placeholder:"Search by name, email, or phone...",value:W,onChange:Xt=>G(Xt.target.value),className:"pl-10 h-10 rounded-xl bg-muted/40 border-border focus-visible:ring-primary/20"})]}),e.jsxs("div",{className:"inline-flex items-center gap-1 p-1 bg-muted rounded-xl border border-border",children:[e.jsxs("button",{type:"button",className:"inline-flex items-center gap-1.5 px-3 py-1.5 text-xs font-semibold rounded-lg bg-background shadow-sm text-foreground",children:[e.jsx(Yn,{className:"h-3.5 w-3.5"}),"Grid"]}),e.jsxs("button",{type:"button",onClick:()=>te(!0),className:"inline-flex items-center gap-1.5 px-3 py-1.5 text-xs font-medium rounded-lg text-muted-foreground hover:text-foreground hover:bg-background/60 transition-colors",children:[e.jsx(Cu,{className:"h-3.5 w-3.5 text-orange-600"}),"Heat Map"]})]}),e.jsxs("div",{className:"inline-flex rounded-xl overflow-hidden shadow-sm",children:[e.jsxs(B,{onClick:()=>Ge(!0),className:"rounded-none rounded-l-xl h-10 px-4 gap-2 shadow-none",children:[e.jsx(nn,{className:"h-4 w-4"}),"Add Contact"]}),e.jsxs(qd,{children:[e.jsx(Vd,{asChild:!0,children:e.jsx(B,{className:"rounded-none rounded-r-xl h-10 px-2.5 border-l border-primary-foreground/20 shadow-none","aria-label":"More import options",children:e.jsx(Qa,{className:"h-4 w-4 rotate-90"})})}),e.jsxs(Ld,{align:"end",children:[e.jsxs(ba,{onClick:()=>Xe(!0),children:[e.jsx(ni,{className:"h-4 w-4 mr-2"}),"Import CSV"]}),e.jsxs(ba,{onClick:()=>Ye(!0),children:[e.jsx($y,{className:"h-4 w-4 mr-2"}),"Import from Phone"]})]})]})]}),e.jsx(oht,{}),e.jsxs(rc,{children:[e.jsx(ac,{asChild:!0,children:e.jsx(B,{variant:"outline",size:"icon",className:"h-10 w-10 rounded-xl",title:"Sort contacts",children:e.jsx(dj,{className:"h-4 w-4"})})}),e.jsxs(Zl,{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(Xt=>e.jsx("button",{onClick:()=>he(Xt.v),className:`w-full text-left px-2 py-1.5 rounded-md text-sm hover:bg-accent transition-colors ${ae===Xt.v?"bg-accent font-medium text-primary":""}`,children:Xt.l},Xt.v))]})]})]})]}),e.jsxs("div",{className:"hidden sm:flex px-3 sm:px-4 py-3 bg-muted/40 border-t flex-wrap items-center justify-between gap-3",children:[e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsxs(Ns,{value:ne,onValueChange:me,children:[e.jsx(ws,{className:"h-8 text-xs rounded-lg bg-background w-auto min-w-[130px] gap-2",children:e.jsx(ks,{placeholder:"All Types"})}),e.jsxs(js,{children:[e.jsx(nt,{value:"all",children:"All Types"}),_==null?void 0:_.filter(Xt=>Xt.active).map(Xt=>e.jsx(nt,{value:Xt.id,children:Xt.name},Xt.id))]})]}),e.jsxs(Ns,{value:ue,onValueChange:ce,children:[e.jsx(ws,{className:"h-8 text-xs rounded-lg bg-background w-auto min-w-[130px] gap-2",children:e.jsx(ks,{placeholder:"All Status"})}),e.jsxs(js,{children:[e.jsx(nt,{value:"all",children:"All Status"}),e.jsx(nt,{value:"warm",children:"🟢 Warm"}),e.jsx(nt,{value:"cooling",children:"🟡 Cooling Off"}),e.jsx(nt,{value:"at-risk",children:"🔴 At Risk"}),e.jsx(nt,{value:"has-deal",children:"📋 Has Deal"}),e.jsx(nt,{value:"no-deal",children:"📭 No Deal"}),e.jsx(nt,{value:"open-house",children:"🏠 Open House"}),y&&e.jsx(nt,{value:"website-active",children:"🌐 Website Active"}),e.jsx(nt,{value:"in-drip",children:"🌱 In Drip Campaign"}),e.jsx(nt,{value:"not-in-drip",children:"🚫 Not In Drip"})]})]}),e.jsxs(Ns,{value:xe,onValueChange:Xt=>ve(Xt),children:[e.jsx(ws,{className:"h-8 text-xs rounded-lg bg-background w-auto min-w-[130px] gap-2",children:e.jsx(ks,{placeholder:"All Addresses"})}),e.jsxs(js,{children:[e.jsx(nt,{value:"all",children:"All Addresses"}),e.jsx(nt,{value:"has-address",children:"Has Address"}),e.jsx(nt,{value:"no-address",children:"No Address"})]})]}),k&&k.length>0&&e.jsxs("div",{className:"inline-flex items-center bg-background border rounded-lg overflow-hidden h-8",children:[e.jsxs(rc,{children:[e.jsx(ac,{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(pf,{className:"h-3.5 w-3.5"}),T.size===0?"Filter by Tags":`${T.size} tag${T.size>1?"s":""}`]})}),e.jsx(Zl,{className:"w-60 p-3",align:"start",children:e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"text-sm font-medium",children:"Tags"}),e.jsxs("div",{className:"flex items-center gap-1 bg-muted rounded-md p-0.5",children:[e.jsx("button",{onClick:()=>M("any"),className:`px-2 py-0.5 rounded text-xs font-medium transition-colors ${I==="any"?"bg-background text-foreground shadow-sm":"text-muted-foreground"}`,children:"Any"}),e.jsx("button",{onClick:()=>M("all"),className:`px-2 py-0.5 rounded text-xs font-medium transition-colors ${I==="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:k.map(Xt=>{const Gn=T.has(Xt.id);return e.jsxs("button",{onClick:()=>{P(Jr=>{const Or=new Set(Jr);return Or.has(Xt.id)?Or.delete(Xt.id):Or.add(Xt.id),Or})},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(Bi,{checked:Gn,className:"pointer-events-none"}),e.jsx("div",{className:"h-2.5 w-2.5 rounded-full shrink-0",style:{backgroundColor:Xt.color}}),e.jsx("span",{className:"flex-1 text-left truncate",children:Xt.name})]},Xt.id)})}),T.size>0&&e.jsx(B,{variant:"ghost",size:"sm",className:"w-full text-xs",onClick:()=>P(new Set),children:"Clear tags"})]})})]}),e.jsx("div",{className:"w-px h-4 bg-border"}),e.jsxs(qd,{children:[e.jsx(Vd,{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(sc,{className:"h-3.5 w-3.5"})})}),e.jsxs(Ld,{align:"end",children:[e.jsxs(ba,{onClick:()=>Ds(!0),children:[e.jsx(pf,{className:"h-4 w-4 mr-2"}),"Manage Tags"]}),e.jsxs(ba,{onClick:()=>Hs(!0),children:[e.jsx(K2,{className:"h-4 w-4 mr-2"}),"Manage Lead Sources"]})]})]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(dht,{currentFilters:{search:W,type:ne,status:ue,behavior:ge},currentSortBy:ae,onApplySmartList:xr}),e.jsx("div",{className:"h-5 w-px bg-border"}),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:()=>Me(!0),children:[e.jsx(Cn,{className:"h-3.5 w-3.5"}),"Advanced Filters",Se>0&&e.jsx(We,{variant:"secondary",className:"h-5 px-1.5 text-[10px]",children:Se})]}),e.jsx(Fpn,{columns:l,onToggle:o,onReset:c})]})]}),Se>0&&e.jsx("div",{className:"px-3 sm:px-4 py-3 border-t bg-background",children:e.jsx(mpn,{behavior:ge,onRemove:Xt=>be(Gn=>{const Jr={...Gn};return delete Jr[Xt],Jr}),onClearAll:()=>be({})})})]}),e.jsx(hpn,{open:Ie,onOpenChange:Me,hasLeadSite:Be||y,behavior:ge,onApply:be,selectedType:ne,onSelectedTypeChange:me,relationshipTypes:_}),e.jsx(dpn,{selectedIds:Ze,contacts:it,onClearSelection:()=>{ht(new Set),Ct(!1)},showLeadPondAction:Rn,onSendToLeadPond:vr,showTransferAction:Bn,onTransfer:ki}),Ze.size>0&&Ze.size===es.length&&!Bt&&ft>Os&&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 ",es.length," contacts on this page are selected."]}),e.jsxs(B,{variant:"link",size:"sm",className:"h-auto p-0 font-semibold",onClick:Zs,children:["Select all ",ft.toLocaleString()," matching contacts"]})]}),Bt&&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 ",ft.toLocaleString()," matching contacts are selected.",e.jsx(B,{variant:"link",size:"sm",className:"h-auto p-0",onClick:()=>{ht(new Set),Ct(!1)},children:"Clear selection"})]}),ft>Os&&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 ",(Ut-1)*Os+1,"–",Math.min(Ut*Os,ft)," of ",ft.toLocaleString()," contacts"]}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(B,{variant:"outline",size:"sm",disabled:Ut<=1,onClick:()=>At(1),children:"First"}),e.jsx(B,{variant:"outline",size:"sm",disabled:Ut<=1,onClick:()=>At(Xt=>Xt-1),children:e.jsx(Fc,{className:"h-4 w-4"})}),e.jsxs("span",{className:"px-3 text-sm font-medium",children:["Page ",Ut," of ",kt]}),e.jsx(B,{variant:"outline",size:"sm",disabled:Ut>=kt,onClick:()=>At(Xt=>Xt+1),children:e.jsx(Qa,{className:"h-4 w-4"})}),e.jsx(B,{variant:"outline",size:"sm",disabled:Ut>=kt,onClick:()=>At(kt),children:"Last"})]})]}),a?e.jsx("div",{className:"space-y-3",children:f?e.jsx(_e,{className:"p-6 text-center text-muted-foreground",children:"Loading contacts..."}):it.length===0?e.jsx(_e,{className:"p-6 text-center text-muted-foreground",children:W||ne!=="all"||ue!=="all"||xe!=="all"?"No contacts match your search":"No contacts yet. Add your first contact!"}):es.map(Xt=>{var Jr,Or,ja;const{relationshipScore:Gn}=Xt;return e.jsx(_e,{className:"cursor-pointer hover:bg-accent/50 transition-colors",onClick:()=>{const ea=new URLSearchParams;W&&ea.set("search",W),ne!=="all"&&ea.set("type",ne),ue!=="all"&&ea.set("filter",ue),T.size>0&&(ea.set("tags",Array.from(T).join(",")),ea.set("tagMode",I));const dr=ea.toString();s(`/mission-control/contacts/${Xt.id}${dr?`?${dr}`:""}`)},children:e.jsx(De,{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:[Xt.first_name," ",Xt.last_name]}),e.jsx(mht,{count:(x==null?void 0:x[Xt.id])??0}),e.jsx(Qa,{className:"h-4 w-4 text-muted-foreground shrink-0 ml-auto"})]}),e.jsxs("div",{className:"space-y-1 text-sm mb-3",children:[Xt.email&&e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground",children:[e.jsx(mn,{className:"h-3.5 w-3.5 shrink-0"}),e.jsx("span",{className:"truncate",children:Xt.email})]}),Xt.phone&&e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground",children:[e.jsx(ga,{className:"h-3.5 w-3.5 shrink-0"}),e.jsx("span",{children:Xt.phone})]})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-1 mb-2",children:[e.jsx(i7e,{score:Gn,size:"sm"}),e.jsx(x5e,{contact:Xt}),(((Jr=Xt.lead_source_ref)==null?void 0:Jr.name)||Xt.lead_source)&&e.jsx(We,{variant:"outline",className:"text-xs gap-1 border-primary/30 text-primary",children:((Or=Xt.lead_source_ref)==null?void 0:Or.name)||Xt.lead_source}),(ja=Xt.tags)==null?void 0:ja.map(ea=>{var dr;return e.jsx(We,{variant:"secondary",className:"text-xs",children:(dr=ea.relationship_type)==null?void 0:dr.name},ea.id)}),e.jsx(pht,{contactId:Xt.id,tags:A==null?void 0:A.filter(ea=>ea.contact_id===Xt.id)}),e.jsx(o7e,{deal:b==null?void 0:b[Xt.id]})]}),e.jsx(hht,{birthday:Xt.birthday,homeAnniversary:Xt.home_anniversary,weddingAnniversary:Xt.wedding_anniversary,className:"mb-2",contactId:Xt.id,contactName:`${Xt.first_name}${Xt.last_name?" "+Xt.last_name:""}`,contactAddress:[Xt.address,Xt.city,Xt.state].filter(Boolean).join(", ")}),e.jsxs("div",{className:"flex flex-wrap items-center gap-3 text-xs text-muted-foreground",children:[Gn.lastTouchDate?e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(Xr,{className:"h-3 w-3"}),Js(new Date(Gn.lastTouchDate),"MMM d")]}):e.jsx("span",{className:"italic",children:"Never contacted"}),Xt.birthday&&e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(ta,{className:"h-3 w-3"}),Js(Tc(Xt.birthday),"MMM d")]}),Xt.home_anniversary&&e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(_a,{className:"h-3 w-3"}),Js(Tc(Xt.home_anniversary),"MMM d")]}),Xt.created_at&&e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(nn,{className:"h-3 w-3"}),"Added ",Js(new Date(Xt.created_at),"MMM d, yyyy")]})]})]}),e.jsx("div",{className:"ml-2",onClick:ea=>ea.stopPropagation(),children:e.jsx(cht,{contact:Xt,onEdit:Fe,onDelete:Er,onSnooze:(ea,dr)=>{Ke(ea),rt(dr)},showLeadPondAction:Rn,onSendToLeadPond:ia,showTransferAction:Bn,onTransfer:sn})})]})})},Xt.id)})}):e.jsx(_e,{children:e.jsx(De,{className:"p-0 overflow-x-auto",children:e.jsxs(Oa,{className:"min-w-[800px]",children:[e.jsx(Fa,{children:e.jsxs(un,{children:[e.jsx(Mt,{className:"w-[40px]",children:e.jsx(Bi,{checked:es.length>0&&es.every(Xt=>Ze.has(Xt.id)),onCheckedChange:()=>bs()})}),e.jsx(Mt,{children:e.jsxs("button",{onClick:()=>he(Xt=>Xt==="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(Qa,{className:"h-3 w-3 rotate-90 text-primary"}),ae==="last-name"&&e.jsx(Qa,{className:"h-3 w-3 -rotate-90 text-primary"})]})}),l.relationship&&e.jsx(Mt,{children:"Relationship"}),l.stage&&e.jsx(Mt,{children:"Stage"}),l.leadSource&&e.jsx(Mt,{children:"Lead Source"}),l.tags&&e.jsx(Mt,{children:"Tags"}),l.lastTouch&&e.jsx(Mt,{children:"Last Touch"}),l.nextAction&&e.jsx(Mt,{children:"Next Action"}),l.dealValue&&e.jsx(Mt,{title:"Total value of deals linked to this contact in your pipeline",children:"Pipeline Value"}),l.email&&e.jsx(Mt,{children:"Email"}),l.phone&&e.jsx(Mt,{children:"Phone"}),l.address&&e.jsx(Mt,{children:"Address"}),l.birthday&&e.jsx(Mt,{children:"Birthday"}),e.jsx(Mt,{className:"w-[50px]"})]})}),e.jsx(za,{children:f?e.jsx(un,{children:e.jsx(gt,{colSpan:3+Object.values(l).filter(Boolean).length,className:"text-center py-8",children:"Loading contacts..."})}):it.length===0?e.jsx(un,{children:e.jsx(gt,{colSpan:3+Object.values(l).filter(Boolean).length,className:"text-center py-8 text-muted-foreground",children:W||ne!=="all"||ue!=="all"||xe!=="all"?"No contacts match your search":"No contacts yet. Add your first contact!"})}):es.map(Xt=>{var Or;const{relationshipScore:Gn}=Xt,Jr=b==null?void 0:b[Xt.id];return e.jsxs(un,{className:`cursor-pointer hover:bg-accent/50 ${Ze.has(Xt.id)?"bg-accent/30":""}`,onClick:()=>Kt(Xt),children:[e.jsx(gt,{onClick:ja=>ja.stopPropagation(),children:e.jsx(Bi,{checked:Ze.has(Xt.id),onCheckedChange:()=>Nr(Xt.id)})}),e.jsx(gt,{className:"min-w-[220px]",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(hGe,{firstName:Xt.first_name,lastName:Xt.last_name,avatarUrl:Xt.avatar_url,email:Xt.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:[Xt.first_name," ",Xt.last_name]}),e.jsx(Dpn,{linked:!!Xt.spouse_contact_id||!!Xt.spouse_name,spouseName:Xt.spouse_contact_id&&Ve[Xt.spouse_contact_id]||Xt.spouse_name||null}),e.jsx(mht,{count:(x==null?void 0:x[Xt.id])??0})]}),Xt.email&&!l.email&&e.jsx("p",{className:"text-xs text-muted-foreground truncate",children:Xt.email}),Xt.phone&&!l.phone&&e.jsx("p",{className:"text-xs text-muted-foreground",children:Xt.phone})]})]})}),l.relationship&&e.jsx(gt,{children:e.jsxs("div",{className:"flex items-center gap-2.5",children:[e.jsx(xIt,{score:Gn.score,status:Gn.status}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"text-sm font-medium leading-tight",children:Gn.status==="warm"?"Strong":Gn.status==="cooling"?"Cooling":"At Risk"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:Gn.daysSinceTouch===null?"Never contacted":Gn.daysSinceTouch===0?"Touched today":`${Gn.daysSinceTouch}d since touch`})]})]})}),l.stage&&e.jsx(gt,{children:e.jsx(o7e,{deal:Jr})}),l.leadSource&&e.jsx(gt,{className:"text-sm text-muted-foreground max-w-[160px] truncate",children:((Or=Xt.lead_source_ref)==null?void 0:Or.name)||Xt.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(pht,{contactId:Xt.id,tags:A==null?void 0:A.filter(ja=>ja.contact_id===Xt.id)})})}),l.lastTouch&&e.jsx(gt,{children:Gn.lastTouchDate?e.jsxs("div",{className:"flex items-center gap-1.5 text-sm text-muted-foreground",children:[e.jsx(Xr,{className:"h-3.5 w-3.5"}),Js(new Date(Gn.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(x5e,{contact:Xt}),e.jsx(hht,{birthday:Xt.birthday,homeAnniversary:Xt.home_anniversary,weddingAnniversary:Xt.wedding_anniversary,contactId:Xt.id,contactName:`${Xt.first_name}${Xt.last_name?" "+Xt.last_name:""}`,contactAddress:[Xt.address,Xt.city,Xt.state].filter(Boolean).join(", ")})]})}),l.dealValue&&e.jsx(gt,{children:(()=>{const ja=(Jr==null?void 0:Jr.sale_price)??(Jr==null?void 0:Jr.expected_price);return ja?e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-semibold",children:_u(Number(ja))}),(Jr==null?void 0:Jr.deal_type)&&e.jsx("p",{className:"text-xs text-muted-foreground capitalize",children:String(Jr.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:Xt.email||"—"}),l.phone&&e.jsx(gt,{className:"text-sm text-muted-foreground whitespace-nowrap",children:Xt.phone||"—"}),l.address&&e.jsx(gt,{className:"text-sm text-muted-foreground max-w-[220px] truncate",children:[Xt.address,Xt.city,Xt.state].filter(Boolean).join(", ")||"—"}),l.birthday&&e.jsx(gt,{className:"text-sm text-muted-foreground whitespace-nowrap",children:Xt.birthday?(()=>{const[ja,ea,dr]=String(Xt.birthday).split(/[-/T]/).map(Number);return ea&&dr?`${ea}/${dr}${ja&&ja>1900?`/${ja}`:""}`:"—"})():"—"}),e.jsx(gt,{onClick:ja=>ja.stopPropagation(),children:e.jsx(cht,{contact:Xt,onEdit:Fe,onDelete:Er,onSnooze:(ja,ea)=>{Ke(ja),rt(ea)},showLeadPondAction:Rn,onSendToLeadPond:ia,showTransferAction:Bn,onTransfer:sn})})]},Xt.id)})})]})})}),e.jsx(Ipn,{contact:Yt,deal:Yt?b==null?void 0:b[Yt.id]:void 0,open:!!Yt,onOpenChange:Xt=>{Xt||Kt(null)},onEdit:Xt=>{Kt(null),Fe(Xt)},index:Yt?es.findIndex(Xt=>Xt.id===Yt.id):void 0,total:es.length,onPrev:(()=>{if(!Yt)return;const Xt=es.findIndex(Gn=>Gn.id===Yt.id);return Xt>0?()=>Kt(es[Xt-1]):void 0})(),onNext:(()=>{if(!Yt)return;const Xt=es.findIndex(Gn=>Gn.id===Yt.id);return Xt>=0&&XtKt(es[Xt+1]):void 0})()}),ft>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 ",(Ut-1)*Os+1,"–",Math.min(Ut*Os,ft)," of ",ft.toLocaleString()," contacts"]}),e.jsxs(Ns,{value:String(Os),onValueChange:Xt=>{Nt(Number(Xt)),At(1)},children:[e.jsx(ws,{className:"w-[80px] h-8",children:e.jsx(ks,{})}),e.jsxs(js,{children:[e.jsx(nt,{value:"50",children:"50"}),e.jsx(nt,{value:"100",children:"100"}),e.jsx(nt,{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:Ut<=1,onClick:()=>At(1),children:"First"}),e.jsx(B,{variant:"outline",size:"sm",disabled:Ut<=1,onClick:()=>At(Xt=>Xt-1),children:e.jsx(Fc,{className:"h-4 w-4"})}),e.jsxs("span",{className:"px-3 text-sm font-medium",children:["Page ",Ut," of ",kt]}),e.jsx(B,{variant:"outline",size:"sm",disabled:Ut>=kt,onClick:()=>At(Xt=>Xt+1),children:e.jsx(Qa,{className:"h-4 w-4"})}),e.jsx(B,{variant:"outline",size:"sm",disabled:Ut>=kt,onClick:()=>At(kt),children:"Last"})]})]}),e.jsx(Bs,{open:Ne||!!Ce,onOpenChange:Xt=>{Xt||(Ge(!1),Fe(null),Kr())},children:e.jsxs(Fs,{className:"max-w-lg max-h-[90vh] overflow-y-auto",children:[e.jsx(qs,{children:e.jsx($s,{children:Ce?"Edit Contact":"Add Contact"})}),e.jsxs("form",{onSubmit:ca,className:"space-y-4",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx(re,{htmlFor:"first_name",children:"First Name *"}),e.jsx(we,{id:"first_name",value:rn.first_name,onChange:Xt=>Zn({...rn,first_name:Xt.target.value}),required:!0})]}),e.jsxs("div",{children:[e.jsx(re,{htmlFor:"last_name",children:"Last Name"}),e.jsx(we,{id:"last_name",value:rn.last_name,onChange:Xt=>Zn({...rn,last_name:Xt.target.value})})]})]}),e.jsxs("div",{children:[e.jsx(re,{htmlFor:"email",children:"Email"}),e.jsx(we,{id:"email",type:"email",value:rn.email,onChange:Xt=>Zn({...rn,email:Xt.target.value})})]}),e.jsxs("div",{children:[e.jsx(re,{htmlFor:"phone",children:"Phone"}),e.jsx(we,{id:"phone",value:rn.phone,onChange:Xt=>Zn({...rn,phone:Xt.target.value})})]}),e.jsxs("div",{children:[e.jsx(re,{htmlFor:"address",children:"Address"}),e.jsx(we,{id:"address",value:rn.address,onChange:Xt=>Zn({...rn,address:Xt.target.value}),placeholder:"Street address"})]}),e.jsxs("div",{className:"grid grid-cols-3 gap-4",children:[e.jsxs("div",{children:[e.jsx(re,{htmlFor:"city",children:"City"}),e.jsx(we,{id:"city",value:rn.city,onChange:Xt=>Zn({...rn,city:Xt.target.value})})]}),e.jsxs("div",{children:[e.jsx(re,{htmlFor:"state",children:"State"}),e.jsx(we,{id:"state",value:rn.state,onChange:Xt=>Zn({...rn,state:Xt.target.value})})]}),e.jsxs("div",{children:[e.jsx(re,{htmlFor:"zip_code",children:"Zip"}),e.jsx(we,{id:"zip_code",value:rn.zip_code,onChange:Xt=>Zn({...rn,zip_code:Xt.target.value})})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx(re,{htmlFor:"birthday",children:"Birthday"}),e.jsx(we,{id:"birthday",type:"date",value:rn.birthday,onChange:Xt=>Zn({...rn,birthday:Xt.target.value})})]}),e.jsxs("div",{children:[e.jsx(re,{htmlFor:"home_anniversary",children:"Home Anniversary"}),e.jsx(we,{id:"home_anniversary",type:"date",value:rn.home_anniversary,onChange:Xt=>Zn({...rn,home_anniversary:Xt.target.value})})]})]}),Ce&&e.jsx(l7e,{contactId:Ce.id,currentSpouseContactId:(Ce==null?void 0:Ce.spouse_contact_id)||null,currentSpouseName:(Ce==null?void 0:Ce.spouse_name)||null,currentSpouseEmail:(Ce==null?void 0:Ce.spouse_email)||null,onLink:Xt=>V.mutate({contactId:Ce.id,spouseContactId:Xt}),onUnlink:()=>V.mutate({contactId:Ce.id,spouseContactId:null}),isEditing:!0}),e.jsx(fIt,{value:rn.lead_source_id,onChange:Xt=>Zn({...rn,lead_source_id:Xt})}),e.jsxs("div",{children:[e.jsx(re,{children:"Relationship Types"}),e.jsx("div",{className:"flex flex-wrap gap-2 mt-2",children:_==null?void 0:_.filter(Xt=>Xt.active).map(Xt=>e.jsxs("label",{className:"flex items-center gap-2 cursor-pointer",children:[e.jsx(Bi,{checked:rn.tagIds.includes(Xt.id),onCheckedChange:Gn=>{Zn(Gn?{...rn,tagIds:[...rn.tagIds,Xt.id]}:{...rn,tagIds:rn.tagIds.filter(Jr=>Jr!==Xt.id)})}}),e.jsx("span",{className:"text-sm",children:Xt.name})]},Xt.id))})]}),e.jsxs("div",{children:[e.jsx(re,{htmlFor:"notes",children:"Notes"}),e.jsx(Ws,{id:"notes",value:rn.notes,onChange:Xt=>Zn({...rn,notes:Xt.target.value}),rows:3})]}),e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx(B,{type:"button",variant:"outline",onClick:()=>{Ge(!1),Fe(null),Kr()},children:"Cancel"}),e.jsxs(B,{type:"submit",disabled:L.isPending||z.isPending,children:[Ce?"Update":"Create"," Contact"]})]})]})]})}),e.jsx(Emn,{open:Ae,onOpenChange:Xe,relationshipTypes:(_==null?void 0:_.filter(Xt=>Xt.active))||[],onSuccess:()=>{Xe(!1)}}),e.jsx(Pmn,{open:$e,onOpenChange:Ye,onComplete:()=>Ye(!1)}),e.jsx(BCe,{open:!!Je,onOpenChange:Xt=>{Xt||Ke(null)},contactId:Je||"",contactName:st}),e.jsx(jpn,{open:It,onOpenChange:Ds}),e.jsx(Npn,{open:As,onOpenChange:Hs}),e.jsx(vpn,{open:X,onOpenChange:te,contacts:m||[],onCitySelect:Xt=>{G(Xt),At(1)}}),e.jsx(MEt,{open:ua,onOpenChange:Mr,contactIds:Dn,contactNames:Dn.map(Xt=>{const Gn=it.find(Jr=>Jr.id===Xt);return Gn?`${Gn.first_name} ${Gn.last_name||""}`.trim():""}),onComplete:()=>{Jn([]),ht(new Set),Ct(!1)}})]})]})})}const Bpn="9a88a47c-cb2a-4401-a2b5-111a76b19f9d";function $pn({open:s,onOpenChange:t,contact:n}){var V;const{user:r}=Ls(),a=tr(),i=as(),{intakePage:l,isLoading:o}=$Ce(),{isGmailConnected:c,gmailEmail:d}=_f(),u=qQ(),{data:h}=mt({queryKey:["profile-for-invite",r==null?void 0:r.id],enabled:!!(r!=null&&r.id)&&s,queryFn:async()=>{const{data:W}=await H.from("profiles").select("name, email, avatar_url").eq("id",r.id).maybeSingle();return W}}),m=(h==null?void 0:h.name)||((V=r==null?void 0:r.email)==null?void 0:V.split("@")[0])||"Your Agent",f=m.split(" ")[0],g=l?`https://contacts.relevelup.com/${l.slug}`:"",y=N.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]),[x,_]=N.useState("gmail"),[b,k]=N.useState(""),[A,T]=N.useState(""),[P,I]=N.useState(!1);N.useEffect(()=>{s&&(k(`Quick favor, ${n.first_name} — can you update your info?`),T(y),_(c?"gmail":"system"))},[s,y,n.first_name,c]);const M=N.useMemo(()=>A.split(/\n\n+/).map(W=>`

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

`).join(""),[A]),L=()=>`
${h!=null&&h.avatar_url?`${m}`:`
${f.charAt(0)}
`}

A note from ${m}

${M}

Update Your Info

Takes about a minute — promise

Share My Info →

${g}

Sent with care by ${m}

Powered by ReLevelUp

`,z=async()=>{if(!l){ie.error("Set up your Connect Page first",{action:{label:"Set Up",onClick:()=>a("/mission-control/connect-page")}});return}if(!b.trim()||!A.trim()){ie.error("Subject and message are required");return}I(!0);const W=L();try{if(x==="gmail"&&c){const{data:G,error:X}=await H.functions.invoke("gmail-send",{body:{to:n.email,subject:b,body:W,contactId:n.id}});if(X)throw X;if(!(G!=null&&G.success))throw new Error((G==null?void 0:G.error)||"Failed to send")}else{const{data:G,error:X}=await H.functions.invoke("send-connect-invite",{body:{contactEmail:n.email,subject:b,htmlBody:W,replyToEmail:(h==null?void 0:h.email)||(r==null?void 0:r.email),agentName:m}});if(X)throw X;if(!(G!=null&&G.success))throw new Error((G==null?void 0:G.error)||"Failed to send")}try{await u.mutateAsync({contactId:n.id,actionTypeId:Bpn,notes:`Sent Connect Page invite — Subject: "${b}"`})}catch(G){console.warn("Failed to log activity:",G)}i.invalidateQueries({queryKey:["contact-touch-logs"]}),ie.success("Connect Page invite sent!"),t(!1)}catch(G){console.error("Send error:",G),ie.error(G instanceof Error?G.message:"Failed to send invite")}finally{I(!1)}},$=L();return e.jsx(Bs,{open:s,onOpenChange:W=>!P&&t(W),children:e.jsxs(Fs,{className:"sm:max-w-[720px] max-h-[92vh] overflow-y-auto",children:[e.jsxs(qs,{children:[e.jsxs($s,{className:"flex items-center gap-2",children:[e.jsx(Cn,{className:"h-5 w-5 text-primary"}),"Send Connect Page Invite"]}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:["Ask ",e.jsxs("span",{className:"font-medium",children:[n.first_name," ",n.last_name||""]})," to share their latest contact info — takes them about a minute."]})]}),o?e.jsx("div",{className:"flex justify-center py-12",children:e.jsx(us,{className:"h-6 w-6 animate-spin text-primary"})}):l?e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(re,{className:"text-xs uppercase tracking-wide text-muted-foreground",children:"Send From"}),e.jsx(ya,{value:x,onValueChange:W=>_(W),className:"mt-1.5",children:e.jsxs(va,{className:"grid w-full grid-cols-2",children:[e.jsxs(ls,{value:"gmail",disabled:!c,children:[e.jsx(mn,{className:"h-3.5 w-3.5 mr-1.5"}),c?`Gmail (${d})`:"Gmail (not connected)"]}),e.jsxs(ls,{value:"system",children:[e.jsx(Cn,{className:"h-3.5 w-3.5 mr-1.5"}),"System Email"]})]})}),e.jsx("p",{className:"text-[11px] text-muted-foreground mt-1.5",children:x==="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(re,{htmlFor:"invite-subject",children:"Subject"}),e.jsx(we,{id:"invite-subject",value:b,onChange:W=>k(W.target.value),className:"mt-1.5"})]}),e.jsxs("div",{children:[e.jsx(re,{htmlFor:"invite-message",children:"Personal Message"}),e.jsx(Ws,{id:"invite-message",value:A,onChange:W=>T(W.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(re,{className:"text-xs uppercase tracking-wide text-muted-foreground",children:"Preview"}),e.jsxs("a",{href:g,target:"_blank",rel:"noopener noreferrer",className:"text-xs text-primary hover:underline flex items-center gap-1",children:["Open Connect Page ",e.jsx(Tr,{className:"h-3 w-3"})]})]}),e.jsx("div",{className:"rounded-lg border overflow-hidden bg-muted/30",children:e.jsx("iframe",{srcDoc:$,title:"Email preview",sandbox:"",className:"w-full h-[420px] bg-background"})})]}),e.jsxs("div",{className:"flex items-center justify-end gap-2 pt-2",children:[e.jsx(B,{variant:"outline",onClick:()=>t(!1),disabled:P,children:"Cancel"}),e.jsx(B,{onClick:z,disabled:P,children:P?e.jsxs(e.Fragment,{children:[e.jsx(us,{className:"h-4 w-4 mr-1.5 animate-spin"})," Sending…"]}):e.jsxs(e.Fragment,{children:[e.jsx(Rr,{className:"h-4 w-4 mr-1.5"})," Send Invite"]})})]})]}):e.jsxs("div",{className:"space-y-4 py-6 text-center",children:[e.jsx(Uo,{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(cd,{className:"h-4 w-4 mr-1"})," Set Up Connect Page"]})]})]})})}function Upn(){const{user:s}=Ls();return mt({queryKey:["cmas",s==null?void 0:s.id],queryFn:async()=>{const{data:t,error:n}=await H.from("cmas").select("*").eq("agent_id",s.id).order("updated_at",{ascending:!1});if(n)throw n;return t},enabled:!!s})}function qpn(s){return mt({queryKey:["cma",s],queryFn:async()=>{const{data:t,error:n}=await H.from("cmas").select("*").eq("id",s).single();if(n)throw n;return t},enabled:!!s})}function Vpn(s){return mt({queryKey:["cma-comps",s],queryFn:async()=>{const{data:t,error:n}=await H.from("cma_comps").select("*").eq("cma_id",s).order("position",{ascending:!0});if(n)throw n;return t||[]},enabled:!!s})}function vIt(){const s=as(),{user:t}=Ls(),{leadSite:n}=Qx();return _t({mutationFn:async r=>{const{data:a,error:i}=await H.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 Hpn(){const s=as();return _t({mutationFn:async({id:t,patch:n})=>{const{data:r,error:a}=await H.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 Gpn(){const s=as();return _t({mutationFn:async t=>{const{error:n}=await H.from("cmas").delete().eq("id",t);if(n)throw n},onSuccess:()=>s.invalidateQueries({queryKey:["cmas"]})})}function Wpn(){const{leadSite:s}=Qx();return _t({mutationFn:async t=>{const{data:n,error:r}=await H.functions.invoke("cma-subject-lookup",{body:{...t,leadSiteId:(s==null?void 0:s.id)??null}});if(r)throw r;return n}})}function Kpn(){const{leadSite:s}=Qx();return _t({mutationFn:async t=>{const{data:n,error:r}=await H.functions.invoke("cma-comp-search",{body:{...t,leadSiteId:t.leadSiteId??(s==null?void 0:s.id)??null}});if(r)throw r;return n}})}function Ypn(){const s=as();return _t({mutationFn:async({cmaId:t,comps:n})=>{if(await H.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 H.from("cma_comps").insert(r);if(a)throw a},onSuccess:(t,n)=>s.invalidateQueries({queryKey:["cma-comps",n.cmaId]})})}function bht(s,t){const n=t.filter(h=>{var m,f;return h.selected!==!1&&(((m=h.snapshot)==null?void 0:m.sqft)||h.sqft)&&(((f=h.snapshot)==null?void 0:f.price)||h.price)});if(!n.length||!s.sqft)return{low:null,likely:null,high:null,ppsf:null};const r=n.map(h=>{const m=h.snapshot||h;return(m.soldPrice||m.price)/m.sqft}).filter(h=>Number.isFinite(h)&&h>0).sort((h,m)=>h-m);if(!r.length)return{low:null,likely:null,high:null,ppsf:null};const a=r[Math.floor(r.length/2)],i=r.reduce((h,m)=>h+m,0)/r.length,l=r.reduce((h,m)=>h+(m-i)**2,0)/r.length,o=Math.sqrt(l),c=Math.round(a*s.sqft),d=Math.round((a-o)*s.sqft),u=Math.round((a+o)*s.sqft);return{low:d,likely:c,high:u,ppsf:Math.round(a)}}function Zpn(s){return mt({queryKey:["contact-video-replies",s],queryFn:async()=>{if(!s)return[];const{data:t,error:n}=await H.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 Xpn(s){return mt({queryKey:["client-portal",s],queryFn:async()=>{if(!s)return null;const{data:t,error:n}=await H.from("client_portals").select("*").eq("deal_id",s).maybeSingle();if(n)throw n;return t},enabled:!!s})}function mGe(){const s=Ya(),t=as();return _t({mutationFn:async n=>{if(!s)throw new Error("Not authenticated");const{data:r,error:a}=await H.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 VU(){const s=as();return _t({mutationFn:async({id:t,...n})=>{const{data:r,error:a}=await H.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 bIt(){const s=as();return _t({mutationFn:async t=>{const{data:n,error:r}=await H.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 _It(){const s=as();return _t({mutationFn:async t=>{const{data:n,error:r}=await H.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 wIt(){const s=as();return _t({mutationFn:async({id:t,dealId:n})=>{await H.from("portal_updates").delete().eq("portal_id",t);const{error:r}=await H.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 Qpn(s){return mt({queryKey:["portal-updates",s],queryFn:async()=>{if(!s)return[];const{data:t,error:n}=await H.from("portal_updates").select("*").eq("portal_id",s).order("created_at",{ascending:!1});if(n)throw n;return t},enabled:!!s})}function jIt(){const s=as();return _t({mutationFn:async t=>{const{data:n,error:r}=await H.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 Jpn(){const s=Ya();return mt({queryKey:["portal-custom-questions",s],queryFn:async()=>{if(!s)return[];const{data:t,error:n}=await H.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 efn(){const s=Ya(),t=as();return _t({mutationFn:async n=>{if(!s)throw new Error("Not authenticated");const{data:r,error:a}=await H.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 tfn(){const s=as();return _t({mutationFn:async({id:t,...n})=>{const{data:r,error:a}=await H.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 sfn(){const s=as();return _t({mutationFn:async t=>{const{error:n}=await H.from("portal_custom_questions").update({is_active:!1}).eq("id",t);if(n)throw n},onSuccess:()=>{s.invalidateQueries({queryKey:["portal-custom-questions"]})}})}function j5(s){const t=window.location.hostname;return t==="localhost"||t.includes("lovable.app")?`${window.location.origin}/portal/${s}`:`https://clients.relevelup.com/${s}`}function nfn({contactId:s}){const t=tr(),n=as(),[r,a]=N.useState(null),[i,l]=N.useState(!1),[o,c]=N.useState(!1),[d,u]=N.useState(""),[h,m]=N.useState(""),[f,g]=N.useState(null),y=VU(),x=jIt(),{data:_,isLoading:b}=mt({queryKey:["contact-portals",s],queryFn:async()=>{const{data:M,error:L}=await H.from("deal_pipeline").select("id, deal_name, deal_type").eq("contact_id",s);if(L)throw L;if(!M||M.length===0)return[];const z=M.map(W=>W.id),{data:$,error:V}=await H.from("client_portals").select("*").in("deal_id",z).is("archived_at",null);if(V)throw V;return($||[]).map(W=>({...W,deal:M.find(G=>G.id===W.deal_id)}))},enabled:!!s}),k=(_==null?void 0:_.map(M=>M.id))||[],{data:A}=mt({queryKey:["contact-portal-updates",k],queryFn:async()=>{if(k.length===0)return{};const{data:M,error:L}=await H.from("portal_updates").select("*").in("portal_id",k).order("created_at",{ascending:!1});if(L)throw L;const z={};return(M||[]).forEach($=>{z[$.portal_id]||(z[$.portal_id]=$)}),z},enabled:k.length>0}),T=M=>{navigator.clipboard.writeText(j5(M)),a(M),ie.success("Portal link copied!"),setTimeout(()=>a(null),2e3)},P=async M=>{d.trim()&&(await x.mutateAsync({portal_id:M,title:d,content:h||void 0}),c(!1),u(""),m(""),n.invalidateQueries({queryKey:["contact-portal-updates"]}),ie.success("Portal update posted!"))},I=async()=>{f&&(await y.mutateAsync({id:f.id,welcome_message:f.welcome_message,next_step_text:f.next_step_text,is_enabled:f.is_enabled,show_post_close_tips:f.show_post_close_tips,review_url:f.review_url}),l(!1),g(null),n.invalidateQueries({queryKey:["contact-portals",s]}),ie.success("Portal settings updated!"))};return b||!_||_.length===0?null:e.jsxs(_e,{children:[e.jsx(zt,{className:"pb-2",children:e.jsxs(qt,{className:"text-base flex items-center gap-2",children:[e.jsx(au,{className:"h-4 w-4"}),"Client Portal"]})}),e.jsx(De,{className:"space-y-3",children:_.map(M=>{var V,W,G;const L=((V=M.stage_mapping)==null?void 0:V.length)>0?M.stage_mapping:q4e(((W=M.deal)==null?void 0:W.deal_type)||"buyer"),z=L==null?void 0:L[M.current_stage_index??0],$=A==null?void 0:A[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:((G=M.deal)==null?void 0:G.deal_name)||"Portal"}),z&&e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Stage: ",z.label||z.name]})]}),e.jsx(We,{variant:M.is_enabled?"default":"secondary",className:"text-[10px] flex-shrink-0",children:M.is_enabled?"Active":"Disabled"})]}),$&&e.jsxs("div",{className:"bg-muted/50 rounded-md p-2",children:[e.jsx("p",{className:"text-xs font-medium truncate",children:$.title}),e.jsx("p",{className:"text-[10px] text-muted-foreground",children:Js(new Date($.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:()=>T(M.slug),children:[r===M.slug?e.jsx(pa,{className:"h-3 w-3 mr-1"}):e.jsx(Pa,{className:"h-3 w-3 mr-1"}),"Copy Link"]}),e.jsxs(B,{variant:"outline",size:"sm",className:"h-7 text-xs",onClick:()=>window.open(j5(M.slug),"_blank"),children:[e.jsx(Tr,{className:"h-3 w-3 mr-1"}),"View"]}),e.jsxs(Bs,{open:o,onOpenChange:c,children:[e.jsx(Ao,{asChild:!0,children:e.jsxs(B,{variant:"outline",size:"sm",className:"h-7 text-xs",onClick:()=>c(!0),children:[e.jsx(xo,{className:"h-3 w-3 mr-1"}),"Post Update"]})}),e.jsxs(Fs,{children:[e.jsx(qs,{children:e.jsx($s,{children:"Post Portal Update"})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(re,{children:"Title"}),e.jsx(we,{value:d,onChange:X=>u(X.target.value),placeholder:"e.g. Inspection completed!"})]}),e.jsxs("div",{children:[e.jsx(re,{children:"Details (optional)"}),e.jsx(Ws,{value:h,onChange:X=>m(X.target.value),placeholder:"Add more details...",rows:3})]}),e.jsxs(B,{onClick:()=>P(M.id),disabled:!d.trim()||x.isPending,className:"w-full",children:[e.jsx(Rr,{className:"h-4 w-4 mr-1"}),"Post Update"]})]})]})]}),e.jsxs(Bs,{open:i,onOpenChange:l,children:[e.jsx(Ao,{asChild:!0,children:e.jsxs(B,{variant:"outline",size:"sm",className:"h-7 text-xs",onClick:()=>{g({...M}),l(!0)},children:[e.jsx(sc,{className:"h-3 w-3 mr-1"}),"Settings"]})}),e.jsxs(Fs,{children:[e.jsx(qs,{children:e.jsx($s,{children:"Portal Settings"})}),f&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(re,{children:"Portal Enabled"}),e.jsx(zn,{checked:f.is_enabled,onCheckedChange:X=>g({...f,is_enabled:X})})]}),e.jsxs("div",{children:[e.jsx(re,{children:"Welcome Message"}),e.jsx(Ws,{value:f.welcome_message||"",onChange:X=>g({...f,welcome_message:X.target.value}),placeholder:"Welcome to your home journey!",rows:2})]}),e.jsxs("div",{children:[e.jsx(re,{children:"Next Step"}),e.jsx(we,{value:f.next_step_text||"",onChange:X=>g({...f,next_step_text:X.target.value}),placeholder:"What your client should do next..."})]}),e.jsxs("div",{children:[e.jsx(re,{children:"Review URL"}),e.jsx(we,{value:f.review_url||"",onChange:X=>g({...f,review_url:X.target.value}),placeholder:"https://..."})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(re,{children:"Show Post-Close Tips"}),e.jsx(zn,{checked:f.show_post_close_tips,onCheckedChange:X=>g({...f,show_post_close_tips:X})})]}),e.jsx(Wl,{}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(B,{onClick:I,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(vi,{className:"h-4 w-4 mr-1"}),"Full Settings"]})]})]})]})]})]}),_.length>1&&e.jsx(Wl,{})]},M.id)})})]})}function rfn({contactId:s}){const{data:t}=mt({queryKey:["agent-lead-sites-slugs"],queryFn:async()=>{const{data:l,error:o}=await H.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}=mt({queryKey:["contact-property-views",s],queryFn:async()=>{const{data:l,error:o}=await H.rpc("get_contact_property_views",{p_contact_id:s});if(o)throw o;return l||[]},enabled:!!s&&!!n});if(!n||a||!r||r.length===0)return null;const i=l=>{const o=t==null?void 0:t.get(l.lead_site_id);return o?`https://${o}.thelocalmove.com/listing/${l.mls_number}`:null};return e.jsxs(_e,{className:"overflow-hidden",children:[e.jsx(zt,{className:"pb-2",children:e.jsxs(qt,{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(da,{className:"h-4 w-4 text-primary"})}),"Property Activity",e.jsxs(We,{variant:"secondary",className:"text-xs ml-auto",children:[r.length," ",r.length===1?"property":"properties"]})]})}),e.jsx(De,{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(_a,{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(Xr,{className:"h-3 w-3"}),e.jsx("span",{title:Js(new Date(l.viewed_at),"PPp"),children:nc(new Date(l.viewed_at),{addSuffix:!0})})]})]}),o&&e.jsx(Tr,{className:"h-3.5 w-3.5 text-muted-foreground opacity-0 group-hover:opacity-100 transition-opacity"})]},l.mls_number)})})})]})}const afn=["Single Family","Condo","Townhouse","Multi-Family","Land","Commercial"];function _ht({value:s,onChange:t,onAdd:n,suggestions:r,placeholder:a,icon:i}){const[l,o]=N.useState(!1),c=N.useRef(null),d=N.useRef(null);N.useEffect(()=>{const h=m=>{d.current&&!d.current.contains(m.target)&&c.current&&!c.current.contains(m.target)&&o(!1)};return document.addEventListener("mousedown",h),()=>document.removeEventListener("mousedown",h)},[]);const u=r.filter(h=>h.toLowerCase().includes(s.toLowerCase()));return e.jsxs("div",{className:"relative flex-1",children:[e.jsxs("div",{className:"flex gap-2",children:[e.jsxs("div",{className:"relative flex-1",children:[e.jsx(we,{ref:c,value:s,onChange:h=>{t(h.target.value),o(!0)},onFocus:()=>o(!0),placeholder:a,onKeyDown:h=>{h.key==="Enter"&&(h.preventDefault(),u.length>0?n(u[0]):n(s))}}),r.length>0&&e.jsx(Xo,{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:()=>n(s),children:e.jsx(nn,{className:"h-4 w-4"})})]}),l&&u.length>0&&e.jsx("div",{ref:d,className:"absolute z-50 mt-1 w-full max-h-60 overflow-y-auto rounded-md border bg-popover shadow-md",children:u.map(h=>e.jsxs("button",{type:"button",className:"w-full text-left px-3 py-2 text-sm hover:bg-accent hover:text-accent-foreground transition-colors flex items-center gap-2",onClick:()=>{n(h),o(!1)},children:[i||e.jsx(ii,{className:"h-3 w-3 text-muted-foreground flex-shrink-0"}),h]},h))})]})}function ifn({contactId:s,contactName:t}){var ae,he,xe;const{user:n}=Ls(),r=Ya(),{hasLeadSite:a}=Qx(),i=as(),[l,o]=N.useState(!1),[c,d]=N.useState(""),[u,h]=N.useState(""),[m,f]=N.useState(!1),[g,y]=N.useState(""),[x,_]=N.useState(null),[b,k]=N.useState(!1),[A,T]=N.useState(!1),{data:P}=mt({queryKey:["agent-lead-site-config",r],queryFn:async()=>{const{data:ve,error:ge}=await H.from("lead_sites").select("theme_config, mls_market_area").eq("agent_id",r).eq("is_active",!0).order("created_at",{ascending:!0}).limit(1).maybeSingle();if(ge||!ve)return{cities:[],zipCodes:[]};const be=ve.theme_config||{},Se=Array.isArray(be.searchCities)?be.searchCities:[];ve.mls_market_area&&!Se.includes(ve.mls_market_area)&&Se.unshift(ve.mls_market_area);const Ie=Array.isArray(be.searchZipCodes)?be.searchZipCodes:[];return{cities:Se,zipCodes:Ie}},enabled:!!r}),{data:I,isLoading:M}=mt({queryKey:["contact-property-alert",s],queryFn:async()=>{const{data:ve,error:ge}=await H.from("contact_property_alerts").select("*").eq("contact_id",s).maybeSingle();if(ge)throw ge;return ve},enabled:!!s&&!!n}),[L,z]=N.useState({}),$=()=>{z({is_active:(I==null?void 0:I.is_active)??!0,min_price:(I==null?void 0:I.min_price)??null,max_price:(I==null?void 0:I.max_price)??null,min_beds:(I==null?void 0:I.min_beds)??null,min_baths:(I==null?void 0:I.min_baths)??null,min_sqft:(I==null?void 0:I.min_sqft)??null,max_sqft:(I==null?void 0:I.max_sqft)??null,cities:(I==null?void 0:I.cities)??[],zip_codes:(I==null?void 0:I.zip_codes)??[],property_types:(I==null?void 0:I.property_types)??[],frequency:(I==null?void 0:I.frequency)??"daily"}),o(!0)},V=_t({mutationFn:async()=>{const ve={contact_id:s,owner_user_id:r,is_active:L.is_active??!0,min_price:L.min_price||null,max_price:L.max_price||null,min_beds:L.min_beds||null,min_baths:L.min_baths||null,min_sqft:L.min_sqft||null,max_sqft:L.max_sqft||null,cities:L.cities||[],zip_codes:L.zip_codes||[],property_types:L.property_types||[],frequency:L.frequency||"daily"};if(I!=null&&I.id){const{error:ge}=await H.from("contact_property_alerts").update(ve).eq("id",I.id);if(ge)throw ge}else{const{error:ge}=await H.from("contact_property_alerts").insert(ve);if(ge)throw ge}},onSuccess:()=>{i.invalidateQueries({queryKey:["contact-property-alert",s]}),o(!1),ie.success("Property alert saved!")},onError:ve=>{ie.error(ve.message||"Failed to save alert")}}),W=_t({mutationFn:async()=>{if(!(I!=null&&I.id))return;const{error:ve}=await H.from("contact_property_alerts").delete().eq("id",I.id);if(ve)throw ve},onSuccess:()=>{i.invalidateQueries({queryKey:["contact-property-alert",s]}),o(!1),ie.success("Property alert removed")}}),G=ve=>{var be;const ge=ve.trim();ge&&!((be=L.cities)!=null&&be.includes(ge))&&z(Se=>({...Se,cities:[...Se.cities||[],ge]})),d("")},X=ve=>{var be;const ge=ve.trim();ge&&!((be=L.zip_codes)!=null&&be.includes(ge))&&z(Se=>({...Se,zip_codes:[...Se.zip_codes||[],ge]})),h("")},te=ve=>{z(ge=>{const be=ge.property_types||[];return{...ge,property_types:be.includes(ve)?be.filter(Se=>Se!==ve):[...be,ve]}})},ne=async()=>{if(I!=null&&I.id){k(!0),f(!0),y(""),_(null);try{const{data:ve,error:ge}=await H.functions.invoke("process-property-alerts",{body:{alert_id:I.id,mode:"preview"}});if(ge)throw ge;ve!=null&&ve.html?(y(ve.html),_({count:ve.listings_count||0,recipient:ve.recipient,subject:ve.subject})):_({count:0,message:(ve==null?void 0:ve.message)||"No matching listings found right now."})}catch(ve){ie.error(ve.message||"Failed to generate preview"),f(!1)}finally{k(!1)}}},me=async()=>{if(I!=null&&I.id&&confirm(`Send property alert email to ${t} now?`)){T(!0);try{const{data:ve,error:ge}=await H.functions.invoke("process-property-alerts",{body:{alert_id:I.id,mode:"send"}});if(ge)throw ge;ve!=null&&ve.sent_count?(ie.success(`Sent ${ve.sent_count} ${ve.sent_count===1?"listing":"listings"} to ${ve.recipient}`),i.invalidateQueries({queryKey:["contact-property-alert",s]})):ie.info((ve==null?void 0:ve.message)||"No new matching listings to send right now.")}catch(ve){ie.error(ve.message||"Failed to send alert")}finally{T(!1)}}};if(!a||M)return null;if(I&&!l)return e.jsxs(e.Fragment,{children:[e.jsxs(_e,{className:"overflow-hidden",children:[e.jsx(zt,{className:"pb-2",children:e.jsxs(qt,{className:"text-base flex items-center gap-2",children:[e.jsx("div",{className:`h-7 w-7 rounded-lg flex items-center justify-center ${I.is_active?"bg-green-500/10":"bg-muted"}`,children:I.is_active?e.jsx(yg,{className:"h-4 w-4 text-green-600"}):e.jsx(d5,{className:"h-4 w-4 text-muted-foreground"})}),"Property Alerts",e.jsxs(We,{variant:I.is_active?"default":"secondary",className:"text-xs ml-auto",children:[I.is_active?"Active":"Paused"," · ",I.frequency]})]})}),e.jsxs(De,{className:"pt-0 space-y-2",children:[e.jsxs("div",{className:"flex flex-wrap gap-1.5 text-xs",children:[I.min_price||I.max_price?e.jsxs(We,{variant:"outline",className:"gap-1",children:[e.jsx(Ed,{className:"h-3 w-3"}),I.min_price?`$${(I.min_price/1e3).toFixed(0)}k`:"$0"," - ",I.max_price?`$${(I.max_price/1e3).toFixed(0)}k`:"Any"]}):null,I.min_beds?e.jsxs(We,{variant:"outline",className:"gap-1",children:[e.jsx(J4,{className:"h-3 w-3"}),I.min_beds,"+ beds"]}):null,I.min_baths?e.jsxs(We,{variant:"outline",className:"gap-1",children:[e.jsx(Wx,{className:"h-3 w-3"}),I.min_baths,"+ baths"]}):null,(ae=I.cities)==null?void 0:ae.map(ve=>e.jsxs(We,{variant:"outline",className:"gap-1",children:[e.jsx(ii,{className:"h-3 w-3"}),ve]},ve)),(he=I.zip_codes)==null?void 0:he.map(ve=>e.jsx(We,{variant:"outline",children:ve},ve)),(xe=I.property_types)==null?void 0:xe.map(ve=>e.jsx(We,{variant:"outline",children:ve},ve))]}),I.last_sent_at&&e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Last sent: ",new Date(I.last_sent_at).toLocaleDateString()]}),e.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[e.jsxs(B,{variant:"outline",size:"sm",onClick:ne,disabled:b,children:[b?e.jsx(us,{className:"h-4 w-4 mr-1 animate-spin"}):e.jsx(da,{className:"h-4 w-4 mr-1"}),"Preview Email"]}),e.jsxs(B,{size:"sm",onClick:me,disabled:A||!I.is_active,title:I.is_active?"Send this alert email now":"Activate alert to send",children:[A?e.jsx(us,{className:"h-4 w-4 mr-1 animate-spin"}):e.jsx(Rr,{className:"h-4 w-4 mr-1"}),"Send Now"]}),e.jsx(B,{variant:"outline",size:"sm",onClick:$,children:"Manage Alert"}),e.jsxs(B,{variant:"destructive",size:"sm",onClick:()=>W.mutate(),disabled:W.isPending,children:[W.isPending?e.jsx(us,{className:"h-4 w-4 mr-1 animate-spin"}):e.jsx(hr,{className:"h-4 w-4 mr-1"}),"Remove"]})]})]})]}),e.jsx(Bs,{open:m,onOpenChange:f,children:e.jsxs(Fs,{className:"max-w-3xl max-h-[90vh] flex flex-col",children:[e.jsxs(qs,{children:[e.jsx($s,{children:"Property Alert Email Preview"}),(x==null?void 0:x.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:"})," ",x.recipient]}),e.jsxs("div",{children:[e.jsx("span",{className:"font-medium",children:"Subject:"})," ",x.subject]}),e.jsxs("div",{children:[e.jsx("span",{className:"font-medium",children:"Listings:"})," ",x.count]})]})]}),e.jsx("div",{className:"flex-1 overflow-hidden border rounded-md bg-muted/30",children:b?e.jsxs("div",{className:"flex items-center justify-center h-96 text-muted-foreground",children:[e.jsx(us,{className:"h-5 w-5 mr-2 animate-spin"})," Building preview…"]}):g?e.jsx("iframe",{srcDoc:g,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:(x==null?void 0:x.message)||"No matching listings found right now."})}),e.jsxs(Cr,{children:[e.jsx(B,{variant:"outline",onClick:()=>f(!1),children:"Close"}),g&&e.jsxs(B,{onClick:()=>{f(!1),me()},disabled:A||!I.is_active,children:[e.jsx(Rr,{className:"h-4 w-4 mr-1"}),"Send to ",t]})]})]})})]});const ue=((P==null?void 0:P.cities)||[]).filter(ve=>{var ge;return!((ge=L.cities)!=null&&ge.includes(ve))}),ce=((P==null?void 0:P.zipCodes)||[]).filter(ve=>{var ge;return!((ge=L.zip_codes)!=null&&ge.includes(ve))});return l?e.jsxs(_e,{children:[e.jsx(zt,{className:"pb-3",children:e.jsxs(qt,{className:"text-base flex items-center gap-2",children:[e.jsx(yg,{className:"h-4 w-4 text-primary"}),I?"Edit":"Setup"," Property Alert for ",t]})}),e.jsxs(De,{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(re,{children:"Alert Active"}),e.jsx(zn,{checked:L.is_active??!0,onCheckedChange:ve=>z(ge=>({...ge,is_active:ve}))})]}),e.jsxs("div",{children:[e.jsxs(re,{className:"flex items-center gap-1 mb-1.5",children:[e.jsx(Ed,{className:"h-3.5 w-3.5"})," Price Range"]}),e.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[e.jsx(we,{type:"number",placeholder:"Min price",value:L.min_price??"",onChange:ve=>z(ge=>({...ge,min_price:ve.target.value?Number(ve.target.value):null}))}),e.jsx(we,{type:"number",placeholder:"Max price",value:L.max_price??"",onChange:ve=>z(ge=>({...ge,max_price:ve.target.value?Number(ve.target.value):null}))})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsxs(re,{className:"flex items-center gap-1 mb-1.5",children:[e.jsx(J4,{className:"h-3.5 w-3.5"})," Min Beds"]}),e.jsxs(Ns,{value:L.min_beds?String(L.min_beds):"any",onValueChange:ve=>z(ge=>({...ge,min_beds:ve==="any"?null:Number(ve)})),children:[e.jsx(ws,{children:e.jsx(ks,{placeholder:"Any"})}),e.jsxs(js,{children:[e.jsx(nt,{value:"any",children:"Any"}),[1,2,3,4,5].map(ve=>e.jsxs(nt,{value:String(ve),children:[ve,"+"]},ve))]})]})]}),e.jsxs("div",{children:[e.jsxs(re,{className:"flex items-center gap-1 mb-1.5",children:[e.jsx(Wx,{className:"h-3.5 w-3.5"})," Min Baths"]}),e.jsxs(Ns,{value:L.min_baths?String(L.min_baths):"any",onValueChange:ve=>z(ge=>({...ge,min_baths:ve==="any"?null:Number(ve)})),children:[e.jsx(ws,{children:e.jsx(ks,{placeholder:"Any"})}),e.jsxs(js,{children:[e.jsx(nt,{value:"any",children:"Any"}),[1,1.5,2,2.5,3,4].map(ve=>e.jsxs(nt,{value:String(ve),children:[ve,"+"]},ve))]})]})]})]}),e.jsxs("div",{children:[e.jsxs(re,{className:"flex items-center gap-1 mb-1.5",children:[e.jsx(l3,{className:"h-3.5 w-3.5"})," Square Feet"]}),e.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[e.jsx(we,{type:"number",placeholder:"Min sqft",value:L.min_sqft??"",onChange:ve=>z(ge=>({...ge,min_sqft:ve.target.value?Number(ve.target.value):null}))}),e.jsx(we,{type:"number",placeholder:"Max sqft",value:L.max_sqft??"",onChange:ve=>z(ge=>({...ge,max_sqft:ve.target.value?Number(ve.target.value):null}))})]})]}),e.jsxs("div",{children:[e.jsxs(re,{className:"flex items-center gap-1 mb-1.5",children:[e.jsx(ii,{className:"h-3.5 w-3.5"})," Cities"]}),e.jsx(_ht,{value:c,onChange:d,onAdd:G,suggestions:ue,placeholder:"Type to search cities..."}),L.cities&&L.cities.length>0&&e.jsx("div",{className:"flex flex-wrap gap-1 mt-2",children:L.cities.map(ve=>e.jsxs(We,{variant:"secondary",className:"gap-1",children:[ve,e.jsx("button",{onClick:()=>z(ge=>{var be;return{...ge,cities:(be=ge.cities)==null?void 0:be.filter(Se=>Se!==ve)}}),children:e.jsx(hr,{className:"h-3 w-3"})})]},ve))})]}),e.jsxs("div",{children:[e.jsx(re,{className:"mb-1.5",children:"Zip Codes"}),e.jsx(_ht,{value:u,onChange:h,onAdd:X,suggestions:ce,placeholder:"Type to search zip codes...",icon:e.jsx("span",{className:"text-xs text-muted-foreground font-mono",children:"#"})}),L.zip_codes&&L.zip_codes.length>0&&e.jsx("div",{className:"flex flex-wrap gap-1 mt-2",children:L.zip_codes.map(ve=>e.jsxs(We,{variant:"secondary",className:"gap-1",children:[ve,e.jsx("button",{onClick:()=>z(ge=>{var be;return{...ge,zip_codes:(be=ge.zip_codes)==null?void 0:be.filter(Se=>Se!==ve)}}),children:e.jsx(hr,{className:"h-3 w-3"})})]},ve))})]}),e.jsxs("div",{children:[e.jsxs(re,{className:"flex items-center gap-1 mb-1.5",children:[e.jsx(_a,{className:"h-3.5 w-3.5"})," Property Types"]}),e.jsx("div",{className:"flex flex-wrap gap-1.5",children:afn.map(ve=>{var ge;return e.jsx(We,{variant:(ge=L.property_types)!=null&&ge.includes(ve)?"default":"outline",className:"cursor-pointer",onClick:()=>te(ve),children:ve},ve)})})]}),e.jsxs("div",{children:[e.jsx(re,{className:"mb-1.5",children:"Frequency"}),e.jsxs(Ns,{value:L.frequency||"daily",onValueChange:ve=>z(ge=>({...ge,frequency:ve})),children:[e.jsx(ws,{children:e.jsx(ks,{})}),e.jsxs(js,{children:[e.jsx(nt,{value:"daily",children:"Daily"}),e.jsx(nt,{value:"weekly",children:"Weekly"})]})]})]}),e.jsxs("div",{className:"flex gap-2 pt-2",children:[e.jsxs(B,{onClick:()=>V.mutate(),disabled:V.isPending,className:"flex-1",children:[V.isPending?e.jsx(us,{className:"h-4 w-4 mr-1 animate-spin"}):e.jsx(Kl,{className:"h-4 w-4 mr-1"}),"Save Alert"]}),e.jsx(B,{variant:"outline",onClick:()=>o(!1),children:"Cancel"}),I&&e.jsx(B,{variant:"destructive",size:"icon",onClick:()=>W.mutate(),disabled:W.isPending,children:e.jsx(hr,{className:"h-4 w-4"})})]})]})]}):e.jsx(_e,{className:"overflow-hidden",children:e.jsx(De,{className:"p-4",children:e.jsxs("button",{onClick:$,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(yg,{className:"h-4 w-4 text-primary"})}),e.jsxs("div",{className:"text-left",children:[e.jsx("p",{className:"font-medium text-sm",children:"Set Up Property Alerts"}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Automatically email ",t," new listings matching their criteria"]})]})]})})})}function ofn({contactId:s,contactName:t}){var te;const{user:n}=Ls(),r=Ya(),{hasLeadSite:a}=Qx(),i=as(),[l,o]=N.useState(!1),[c,d]=N.useState(""),[u,h]=N.useState([]),[m,f]=N.useState(!1),[g,y]=N.useState(!1),[x,_]=N.useState(!1),[b,k]=N.useState(""),A=N.useRef(null),T=N.useRef(null),{data:P}=mt({queryKey:["agent-lead-site-cities",r],queryFn:async()=>{const{data:ne,error:me}=await H.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(me||!ne)return[];const ue=ne.theme_config||{},ce=Array.isArray(ue.searchCities)?ue.searchCities:[];return ne.mls_market_area&&!ce.includes(ne.mls_market_area)&&ce.unshift(ne.mls_market_area),ce},enabled:!!r}),{data:I,isLoading:M}=mt({queryKey:["contact-market-report",s],queryFn:async()=>{const{data:ne,error:me}=await H.from("innercircle_contacts").select("market_report_enabled, market_report_cities").eq("id",s).single();if(me)throw me;return ne},enabled:!!s&&!!n});N.useEffect(()=>{const ne=me=>{T.current&&!T.current.contains(me.target)&&A.current&&!A.current.contains(me.target)&&y(!1)};return document.addEventListener("mousedown",ne),()=>document.removeEventListener("mousedown",ne)},[]);const L=()=>{f((I==null?void 0:I.market_report_enabled)??!1),h((I==null?void 0:I.market_report_cities)??[]),o(!0)},z=ne=>{const me=(ne||c).trim();me&&!u.includes(me)&&h([...u,me]),d(""),y(!1)},$=(P||[]).filter(ne=>!u.includes(ne)&&ne.toLowerCase().includes(c.toLowerCase())),V=_t({mutationFn:async()=>{const{data:ne,error:me}=await H.functions.invoke("send-market-report",{body:{action:"preview",agentId:r,cities:(I==null?void 0:I.market_report_cities)??[]}});if(me)throw new Error(me.message||"Failed to generate preview");if(ne&&!ne.ok&&ne.error)throw new Error(ne.error);return ne},onSuccess:ne=>{k(ne.html),_(!0)},onError:ne=>{ie.error(ne.message||"Failed to generate preview")}}),W=_t({mutationFn:async()=>{const{data:ne,error:me}=await H.functions.invoke("send-market-report",{body:{action:"send",agentId:r,cities:(I==null?void 0:I.market_report_cities)??[],contactIds:[s]}});if(me)throw new Error(me.message||"Failed to send report");if(ne&&!ne.ok&&ne.error)throw new Error(ne.error);return ne},onSuccess:()=>{ie.success(`Market report sent to ${t}!`)},onError:ne=>{ie.error(ne.message||"Failed to send report")}}),G=_t({mutationFn:async()=>{const{error:ne}=await H.from("innercircle_contacts").update({market_report_enabled:m,market_report_cities:u}).eq("id",s);if(ne)throw ne},onSuccess:()=>{i.invalidateQueries({queryKey:["contact-market-report",s]}),o(!1),ie.success(m?"Monthly market report enabled!":"Market report disabled")},onError:ne=>{ie.error(ne.message||"Failed to save")}}),X=_t({mutationFn:async()=>{const{error:ne}=await H.from("innercircle_contacts").update({market_report_enabled:!1,market_report_cities:[]}).eq("id",s);if(ne)throw ne},onSuccess:()=>{i.invalidateQueries({queryKey:["contact-market-report",s]}),o(!1),f(!1),h([]),ie.success("Market report removed")},onError:ne=>{ie.error(ne.message||"Failed to remove market report")}});return!a||M?null:I!=null&&I.market_report_enabled&&!l?e.jsxs(_e,{className:"overflow-hidden",children:[e.jsx(zt,{className:"pb-2",children:e.jsxs(qt,{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(fl,{className:"h-4 w-4 text-primary"})}),"Monthly Market Report",e.jsx(We,{variant:"default",className:"text-xs ml-auto",children:"Active"})]})}),e.jsxs(De,{className:"pt-0 space-y-2",children:[e.jsx("div",{className:"flex flex-wrap gap-1.5 text-xs",children:((te=I.market_report_cities)==null?void 0:te.length)>0?I.market_report_cities.map(ne=>e.jsxs(We,{variant:"outline",className:"gap-1",children:[e.jsx(ii,{className:"h-3 w-3"}),ne]},ne)):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(us,{className:"h-4 w-4 mr-1 animate-spin"}):e.jsx(da,{className:"h-4 w-4 mr-1"}),"Preview"]}),e.jsxs(B,{variant:"default",size:"sm",onClick:()=>W.mutate(),disabled:W.isPending,className:"flex-1",children:[W.isPending?e.jsx(us,{className:"h-4 w-4 mr-1 animate-spin"}):e.jsx(Rr,{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:L,className:"flex-1",children:"Manage"}),e.jsxs(B,{variant:"destructive",size:"sm",onClick:()=>X.mutate(),disabled:X.isPending,className:"flex-1",children:[X.isPending?e.jsx(us,{className:"h-4 w-4 mr-1 animate-spin"}):e.jsx(hr,{className:"h-4 w-4 mr-1"}),"Remove"]})]}),e.jsx(Bs,{open:x,onOpenChange:_,children:e.jsxs(Fs,{className:"max-w-3xl max-h-[85vh] overflow-hidden flex flex-col",children:[e.jsx(qs,{children:e.jsxs($s,{className:"flex items-center gap-2",children:[e.jsx(fl,{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:()=>{_(!1),W.mutate()},disabled:W.isPending,className:"flex-1",children:[W.isPending?e.jsx(us,{className:"h-4 w-4 mr-1 animate-spin"}):e.jsx(Rr,{className:"h-4 w-4 mr-1"}),"Send to ",t]}),e.jsx(B,{variant:"outline",onClick:()=>_(!1),children:"Close"})]})]})})]})]}):l?e.jsxs(_e,{children:[e.jsx(zt,{className:"pb-3",children:e.jsxs(qt,{className:"text-base flex items-center gap-2",children:[e.jsx(fl,{className:"h-4 w-4 text-primary"}),"Market Report for ",t]})}),e.jsxs(De,{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(re,{children:"Send Monthly Report"}),e.jsx(zn,{checked:m,onCheckedChange:f})]}),m&&e.jsxs("div",{children:[e.jsxs(re,{className:"flex items-center gap-1 mb-1.5",children:[e.jsx(ii,{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(we,{ref:A,value:c,onChange:ne=>{d(ne.target.value),y(!0)},onFocus:()=>y(!0),placeholder:"Type to search cities...",onKeyDown:ne=>{ne.key==="Enter"&&(ne.preventDefault(),$.length>0?z($[0]):z())}}),e.jsx(Xo,{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:()=>z(),children:e.jsx(nn,{className:"h-4 w-4"})})]}),g&&$.length>0&&e.jsx("div",{ref:T,className:"absolute z-50 mt-1 w-full max-h-60 overflow-y-auto rounded-md border bg-popover shadow-md",children:$.map(ne=>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:()=>z(ne),children:[e.jsx(ii,{className:"h-3 w-3 text-muted-foreground flex-shrink-0"}),ne]},ne))})]}),u.length>0&&e.jsx("div",{className:"flex flex-wrap gap-1 mt-2",children:u.map(ne=>e.jsxs(We,{variant:"secondary",className:"gap-1",children:[ne,e.jsx("button",{onClick:()=>h(u.filter(me=>me!==ne)),children:e.jsx(hr,{className:"h-3 w-3"})})]},ne))})]}),e.jsxs("div",{className:"flex gap-2 pt-2",children:[e.jsxs(B,{onClick:()=>G.mutate(),disabled:G.isPending,className:"flex-1",children:[G.isPending?e.jsx(us,{className:"h-4 w-4 mr-1 animate-spin"}):e.jsx(Kl,{className:"h-4 w-4 mr-1"}),"Save"]}),e.jsx(B,{variant:"outline",onClick:()=>o(!1),children:"Cancel"})]})]})]}):e.jsx(_e,{className:"overflow-hidden",children:e.jsx(De,{className:"p-4",children:e.jsxs("button",{onClick:L,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(fl,{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 lfn(s){return mt({queryKey:["contact-drip-activity",s],queryFn:async()=>{if(!s)return{enrollments:[],stepLogs:[]};const{data:t,error:n}=await H.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 H.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 H.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 cfn(s){switch(s){case"active":return e.jsx(We,{variant:"secondary",className:"bg-emerald-500/10 text-emerald-600 border-emerald-500/20",children:"Active"});case"paused":return e.jsx(We,{variant:"secondary",className:"bg-amber-500/10 text-amber-600 border-amber-500/20",children:"Paused"});case"completed":return e.jsx(We,{variant:"secondary",className:"bg-sky-500/10 text-sky-600 border-sky-500/20",children:"Completed"});case"exited":return e.jsx(We,{variant:"outline",children:"Exited"});default:return e.jsx(We,{variant:"outline",children:s})}}function wht(s){return s==="sent"?e.jsx(Hr,{className:"h-4 w-4 text-emerald-500"}):s==="failed"?e.jsx(xd,{className:"h-4 w-4 text-destructive"}):s==="skipped"?e.jsx(K0,{className:"h-4 w-4 text-muted-foreground"}):e.jsx(Xr,{className:"h-4 w-4 text-muted-foreground"})}function dfn({contactId:s}){const t=tr(),{data:n,isLoading:r}=lfn(s),[a,i]=N.useState(null);if(r)return null;const l=(n==null?void 0:n.enrollments)||[],o=(n==null?void 0:n.stepLogs)||[];return l.length===0&&o.length===0?null:e.jsxs(_e,{children:[e.jsx(zt,{children:e.jsxs(qt,{className:"flex items-center gap-2 text-base",children:[e.jsx(FT,{className:"h-5 w-5 text-emerald-500"}),"Drip Campaign Activity"]})}),e.jsxs(De,{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(FT,{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"}),cfn(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: ",nc(new Date(c.next_send_at),{addSuffix:!0})]}),c.completed_at&&e.jsxs(e.Fragment,{children:[" · Completed ",nc(new Date(c.completed_at),{addSuffix:!0})]}),c.exited_at&&!c.completed_at&&e.jsxs(e.Fragment,{children:[" · ",c.exit_reason||"Exited"," ",nc(new Date(c.exited_at),{addSuffix:!0})]})]})]}),e.jsx(Qa,{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(Bs,{open:(a==null?void 0:a.id)===c.id,onOpenChange:h=>!h&&i(null),children:[e.jsx(Ao,{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:wht(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(xo,{className:"h-3 w-3 text-muted-foreground flex-shrink-0"}):e.jsx(mn,{className:"h-3 w-3 text-muted-foreground flex-shrink-0"}),e.jsx("p",{className:"text-sm truncate",children:c.subject||`${c.channel.toUpperCase()} step ${c.step_order+1}`})]}),e.jsxs("p",{className:"text-xs text-muted-foreground mt-0.5 truncate",children:[((d=c.campaign)==null?void 0:d.name)||"Campaign"," · ",Js(new Date(c.sent_at),"MMM d, h:mm a")]}),c.status==="failed"&&c.error_message&&e.jsx("p",{className:"text-xs text-destructive mt-0.5 truncate",children:c.error_message})]})]})}),e.jsxs(Fs,{className:"max-w-lg",children:[e.jsx(qs,{children:e.jsxs($s,{className:"flex items-center gap-2",children:[wht(c.status),c.subject||"Drip step"]})}),e.jsxs("div",{className:"space-y-2 text-sm",children:[e.jsxs("div",{className:"flex justify-between",children:[e.jsx("span",{className:"text-muted-foreground",children:"Campaign"}),e.jsx("span",{className:"font-medium",children:((u=c.campaign)==null?void 0:u.name)||"—"})]}),e.jsxs("div",{className:"flex justify-between",children:[e.jsx("span",{className:"text-muted-foreground",children:"Channel"}),e.jsx("span",{className:"font-medium uppercase",children:c.channel})]}),e.jsxs("div",{className:"flex justify-between",children:[e.jsx("span",{className:"text-muted-foreground",children:"Step"}),e.jsxs("span",{className:"font-medium",children:["#",c.step_order+1]})]}),e.jsxs("div",{className:"flex justify-between",children:[e.jsx("span",{className:"text-muted-foreground",children:"Recipient"}),e.jsx("span",{className:"font-medium",children:c.recipient_email||"—"})]}),e.jsxs("div",{className:"flex justify-between",children:[e.jsx("span",{className:"text-muted-foreground",children:"Status"}),e.jsx("span",{className:"font-medium capitalize",children:c.status})]}),e.jsxs("div",{className:"flex justify-between",children:[e.jsx("span",{className:"text-muted-foreground",children:"Sent"}),e.jsx("span",{className:"font-medium",children:Js(new Date(c.sent_at),"MMM d, yyyy h:mm a")})]}),c.error_message&&e.jsx("div",{className:"rounded-md border border-destructive/30 bg-destructive/5 p-2 text-destructive text-xs",children:c.error_message})]})]})]},c.id)}),o.length>8&&e.jsx(B,{variant:"ghost",size:"sm",className:"w-full text-xs",onClick:()=>t("/mission-control/smart-drips"),children:"View all in Smart Drips"})]})]})]})]})}function NIt({contactId:s}={}){const{user:t}=Ls();return mt({queryKey:["sent-emails",t==null?void 0:t.id,s??"all"],enabled:!!t,queryFn:async()=>{const n=t.id;let r=H.from("gmail_sent_emails").select("id, contact_id, to_email, subject, sent_at, source").eq("user_id",n).or("source.is.null,source.neq.drip_campaign").order("sent_at",{ascending:!1}).limit(1e3);s&&(r=r.eq("contact_id",s));let a=H.from("bulk_email_sends").select("id, contact_id, contact_email, subject, sent_at, source, opened_at, clicked_at").eq("user_id",n).order("sent_at",{ascending:!1}).limit(1e3);s&&(a=a.eq("contact_id",s));const i=await H.from("email_campaigns").select("id, subject").eq("user_id",n),l=(i.data||[]).map(y=>y.id),o=new Map((i.data||[]).map(y=>[y.id,y.subject]));let c=[];if(l.length>0){let y=H.from("email_campaign_recipients").select("id, contact_id, email, sent_at, campaign_id, opened_at, clicked_at").in("campaign_id",l).eq("status","sent").not("sent_at","is",null).order("sent_at",{ascending:!1}).limit(1e3);s&&(y=y.eq("contact_id",s)),c=(await y).data||[]}const[d,u]=await Promise.all([r,a]),h=(d.data||[]).map(y=>({id:`g-${y.id}`,channel:y.source==="portal_invite"?"Client Portal Invite":"Gmail",subject:y.subject,to_email:y.to_email,contact_id:y.contact_id,sent_at:y.sent_at,source:y.source})),m=(u.data||[]).map(y=>({id:`b-${y.id}`,channel:"Mass Email",subject:y.subject,to_email:y.contact_email,contact_id:y.contact_id,sent_at:y.sent_at,source:y.source,opened_at:y.opened_at,clicked_at:y.clicked_at})),f=c.map(y=>({id:`c-${y.id}`,channel:"Campaign",subject:o.get(y.campaign_id)||"(campaign)",to_email:y.email,contact_id:y.contact_id,sent_at:y.sent_at,source:null,campaign_id:y.campaign_id,opened_at:y.opened_at,clicked_at:y.clicked_at})),g=[...h,...m,...f];return g.sort((y,x)=>y.sent_at0&&e.jsx(We,{variant:"secondary",className:"ml-1",children:t.length})]})}),e.jsx(De,{children:n?e.jsx("p",{className:"text-sm text-muted-foreground",children:"Loading..."}):t.length===0?e.jsxs("div",{className:"text-center py-6 text-sm text-muted-foreground",children:[e.jsx(mn,{className:"h-8 w-8 mx-auto mb-2 opacity-50"}),"No emails sent to this contact yet."]}):e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"space-y-2",children:i.map(l=>e.jsx("div",{className:"flex items-start justify-between gap-3 p-3 rounded-lg border hover:bg-muted/30",children:e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[e.jsx(We,{variant:"outline",className:`text-xs ${ufn[l.channel]}`,children:l.channel}),e.jsx("span",{className:"text-xs text-muted-foreground",children:Js(new Date(l.sent_at),"MMM d, yyyy h:mm a")})]}),e.jsx("p",{className:"text-sm font-medium truncate",children:l.subject}),e.jsxs("p",{className:"text-xs text-muted-foreground truncate",children:["to ",l.to_email]})]})},l.id))}),t.length>5&&e.jsx(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(cr,{to:"/mission-control/sent-emails",className:"text-xs text-primary hover:underline",children:"View all sent emails →"})})]})})]})}function mfn({videoId:s}){var l;const{data:t,isLoading:n,error:r}=spn(s);if(n)return e.jsxs("div",{className:"space-y-4",children:[e.jsx(xn,{className:"w-full aspect-video rounded-lg"}),e.jsx(xn,{className:"h-4 w-1/3"})]});if(r||!t||t.is_deleted)return e.jsxs("div",{className:"flex flex-col items-center justify-center py-8 text-center",children:[e.jsx(xd,{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 pfn({contactId:s}){const t=tr(),[n,r]=N.useState(!1),{data:a,isLoading:i}=mt({queryKey:["deal-tasks","contact",s],queryFn:async()=>{const{data:h,error:m}=await H.from("deal_tasks").select(` id, title, priority, status, due_date, completed_at, deal:deal_pipeline(id, deal_name) `).eq("contact_id",s).order("status").order("due_date",{ascending:!0,nullsFirst:!1});if(m)throw m;return h},enabled:!!s}),l=async(h,m)=>{const f=m==="done"?"todo":"done";await H.from("deal_tasks").update({status:f,completed_at:f==="done"?new Date().toISOString():null}).eq("id",h),window.dispatchEvent(new CustomEvent("refetch-contact-tasks"))},{refetch:o}=mt({queryKey:["deal-tasks","contact",s],queryFn:async()=>{const{data:h,error:m}=await H.from("deal_tasks").select(` id, title, priority, status, due_date, completed_at, deal:deal_pipeline(id, deal_name) `).eq("contact_id",s).order("status").order("due_date",{ascending:!0,nullsFirst:!1});if(m)throw m;return h},enabled:!!s}),c={urgent:"🔴",high:"🟠",medium:"🟡",low:"🟢"},d=(a==null?void 0:a.filter(h=>h.status!=="done"))||[],u=(a==null?void 0:a.filter(h=>h.status==="done"))||[];return e.jsxs(_e,{children:[e.jsx(zt,{className:"pb-2",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs(qt,{className:"text-base flex items-center gap-2",children:[e.jsx(pa,{className:"h-4 w-4"}),"Tasks",d.length>0&&e.jsx(We,{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(nn,{className:"h-3.5 w-3.5"})})]})]})}),e.jsx(De,{className:"space-y-1",children:i?e.jsx(xn,{className:"h-8 w-full"}):d.length===0&&u.length===0?e.jsx("p",{className:"text-sm text-muted-foreground text-center py-4",children:"No tasks yet"}):e.jsxs(e.Fragment,{children:[d.map(h=>e.jsxs("button",{onClick:async()=>{await l(h.id,h.status),o()},className:"w-full text-left flex items-center gap-2 px-2 py-1.5 rounded hover:bg-muted/50 transition-colors group",children:[e.jsx("div",{className:"h-4 w-4 rounded-full border-2 border-muted-foreground/30 shrink-0 group-hover:border-primary"}),e.jsxs("span",{className:"text-sm flex-1 truncate",children:[c[h.priority]," ",h.title]}),h.due_date&&e.jsx("span",{className:"text-[10px] text-muted-foreground",children:Js(new Date(h.due_date),"MMM d")})]},h.id)),u.length>0&&e.jsx("div",{className:"pt-1 border-t mt-1",children:e.jsxs("p",{className:"text-[10px] text-muted-foreground px-2 py-1",children:[u.length," completed"]})})]})}),n&&e.jsx(ffn,{contactId:s,open:n,onOpenChange:h=>{r(h),h||o()}})]})}function ffn({contactId:s,open:t,onOpenChange:n}){const[r,a]=N.useState(""),[i,l]=N.useState("medium"),[o,c]=N.useState(),{data:d}=mt({queryKey:["session"],queryFn:async()=>{const{data:h}=await H.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 H.from("deal_tasks").insert([{owner_user_id:d.user.id,contact_id:s,title:r.trim(),priority:i,status:"todo",due_date:o?Js(o,"yyyy-MM-dd"):null}]);if(h){console.error("Task create error:",h);return}n(!1)};return e.jsx(Bs,{open:t,onOpenChange:n,children:e.jsxs(Fs,{className:"sm:max-w-[400px]",children:[e.jsx(qs,{children:e.jsx($s,{children:"Add Task"})}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{children:[e.jsx(re,{children:"Title"}),e.jsx(we,{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(re,{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(re,{children:"Due Date"}),e.jsx(we,{type:"date",value:o?Js(o,"yyyy-MM-dd"):"",onChange:h=>c(h.target.value?new Date(h.target.value+"T00:00:00"):void 0)})]})]}),e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx(B,{variant:"outline",onClick:()=>n(!1),children:"Cancel"}),e.jsx(B,{onClick:u,disabled:!r.trim(),children:"Create Task"})]})]})]})})}function gfn({contactId:s}){const t=tr(),{data:n,isLoading:r}=mt({queryKey:["contact-linked-deals",s],queryFn:async()=>{const{data:a,error:i}=await H.from("deal_pipeline").select(` id, deal_name, deal_type, expected_price, property_address, stage:deal_pipeline_stages(id, name, color, icon, is_won_stage, is_lost_stage) `).eq("contact_id",s).order("updated_at",{ascending:!1});if(i)throw i;return a},enabled:!!s});return r||!n||n.length===0?null:e.jsxs(_e,{children:[e.jsx(zt,{className:"pb-2",children:e.jsxs(qt,{className:"text-base flex items-center gap-2",children:[e.jsx(vg,{className:"h-4 w-4"}),"Linked Deals"]})}),e.jsx(De,{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(We,{variant:"outline",className:"text-[10px] capitalize",children:a.deal_type}),i&&e.jsxs(We,{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(vi,{className:"h-4 w-4 text-muted-foreground group-hover:text-primary transition-colors flex-shrink-0"})]})},a.id)})})]})}function xfn(){var At,Os,Nt,ms,Ys;const{contactId:s}=uo(),t=tr(),[n]=$c(),r=n.get("search")||"",a=n.get("type")||"all",i=n.get("status")||n.get("filter")||"all",l=n.get("tags")||"",o=n.get("tagMode")==="all"?"all":"any",c=N.useMemo(()=>new Set(l.split(",").map(It=>It.trim()).filter(Boolean)),[l]),{data:d,isLoading:u}=ojs(s||""),{data:h}=K_(),{data:m}=fU(),{data:f}=gU(3650),{data:g}=UCe(365),{data:y}=Zpn(s),{contactsWithScores:x}=n3e(),{data:_}=zCe(),b=dqe(),k=uqe(),A=qQ(),T=k4t(),[P,I]=N.useState(!1),[M,L]=N.useState({}),[z,$]=N.useState(!1),[V,W]=N.useState(null),[G,X]=N.useState(""),[te,ne]=N.useState(void 0),[me,ue]=N.useState(""),[ce,ae]=N.useState(null),[he,xe]=N.useState(!1),[ve,ge]=N.useState(null),[be,Se]=N.useState(!1),{isGmailConnected:Ie,gmailEmail:Me}=_f(),{isReady:Re}=$U(),Be=Re||Ie,Ne=vIt(),[Ge,Ce]=N.useState(!1),{data:Fe}=mt({queryKey:["cma-eligible"],queryFn:async()=>{const{data:{user:It}}=await H.auth.getUser();if(!It)return!1;const{data:Ds}=await H.from("lead_sites").select("id, mls_provider_id, no_mls_mode, is_active").eq("agent_id",It.id);return(Ds||[]).some(As=>As.is_active&&As.mls_provider_id&&!As.no_mls_mode)}}),Ae=async()=>{var Rs,en,Rn,Bn;if(!d)return;const It=(Rs=d.address)==null?void 0:Rs.trim(),Ds=(en=d.city)==null?void 0:en.trim(),As=(Rn=d.state)==null?void 0:Rn.trim().toUpperCase(),Hs=((Bn=d.zip_code)==null?void 0:Bn.trim())||"";if(!It||!Ds||!As){ie.error("Add a full address (street, city, state) before creating a CMA.");return}try{Ce(!0);const Dn=await Ne.mutateAsync({subject:{address:It,city:Ds,state:As,zip:Hs},contactId:d.id,title:`${d.first_name||""} ${d.last_name||""}`.trim()+" — "+It});t(`/mission-control/cma/${Dn.id}`)}catch(Dn){ie.error("Could not create CMA: "+((Dn==null?void 0:Dn.message)||"unknown error"))}finally{Ce(!1)}},{data:Xe}=mt({queryKey:["gmail-sent-emails",s],queryFn:async()=>{const{data:It,error:Ds}=await H.from("gmail_sent_emails").select("*").eq("contact_id",s).order("sent_at",{ascending:!1});if(Ds)throw Ds;return It},enabled:!!s}),$e=It=>{if(!It)return null;const Ds=It.match(/Video ID:\s*([a-f0-9-]+)/i);return Ds?Ds[1]:null},Ye=N.useMemo(()=>{if(!x)return[];const It=new Map;if(c.size>0&&_)for(const As of _)It.has(As.contact_id)||It.set(As.contact_id,new Set),It.get(As.contact_id).add(As.tag_id);let Ds=x.filter(As=>{var Rn,Bn,Dn;const Hs=r===""||`${As.first_name} ${As.last_name}`.toLowerCase().includes(r.toLowerCase())||((Rn=As.email)==null?void 0:Rn.toLowerCase().includes(r.toLowerCase()))||((Bn=As.phone)==null?void 0:Bn.includes(r)),Rs=a==="all"||((Dn=As.tags)==null?void 0:Dn.some(Jn=>Jn.relationship_type_id===a));let en=!0;if(c.size>0){const Jn=It.get(As.id)||new Set;o==="all"?en=Array.from(c).every(ua=>Jn.has(ua)):en=Array.from(c).some(ua=>Jn.has(ua))}return Hs&&Rs&&en});return i==="not-touched-90"?Ds=Ds.filter(As=>{const Hs=As.relationshipScore.daysSinceTouch;return Hs===null||Hs>90}):i==="at-risk"?Ds=Ds.filter(As=>As.relationshipScore.status==="at-risk"):i==="cooling"?Ds=Ds.filter(As=>As.relationshipScore.status==="cooling"):i==="warm"&&(Ds=Ds.filter(As=>As.relationshipScore.status==="warm")),Ds.map(As=>As.id)},[x,r,a,i,c,o,_]),Je=Ye.indexOf(s||""),Ke=Je>0?Ye[Je-1]:null,st=Je1&&Je!==-1,Ze=It=>{const Ds=new URLSearchParams;r&&Ds.set("search",r),a!=="all"&&Ds.set("type",a),i!=="all"&&Ds.set("status",i),c.size>0&&(Ds.set("tags",Array.from(c).join(",")),Ds.set("tagMode",o));const As=Ds.toString();return`/mission-control/contacts/${It}${As?`?${As}`:""}`},ht=N.useMemo(()=>{const It=((f==null?void 0:f.filter(As=>As.contact_id===s))||[]).map(As=>{var Rn,Bn,Dn;const Hs=$e(As.notes);let Rs=((Rn=As.action_type)==null?void 0:Rn.name)||"Touch",en=As.notes;if(Rs==="Other"&&((Bn=As.notes)!=null&&Bn.startsWith("["))){const Jn=As.notes.indexOf("]");Jn>0&&(Rs=As.notes.substring(1,Jn),en=As.notes.substring(Jn+1).replace(/^\s*—\s*/,"").trim()||null)}return{id:As.id,type:"touch",completed_at:As.completed_at,name:Rs,color:((Dn=As.action_type)==null?void 0:Dn.color)||"#3B82F6",notes:en,videoId:Hs}}),Ds=((g==null?void 0:g.filter(As=>As.contact_id===s))||[]).map(As=>({id:As.id,type:"popby",completed_at:As.completed_at,name:"Pop-by",color:"#F97316",notes:As.notes,videoId:null}));return[...It,...Ds].sort((As,Hs)=>new Date(Hs.completed_at).getTime()-new Date(As.completed_at).getTime())},[f,g,s]),Bt=()=>{var It;d&&(L({first_name:d.first_name||"",last_name:d.last_name||"",email:d.email||"",phone:d.phone||"",address:d.address||"",city:d.city||"",state:d.state||"",zip_code:d.zip_code||"",birthday:d.birthday||"",home_anniversary:d.home_anniversary||"",wedding_anniversary:d.wedding_anniversary||"",spouse_birthday:d.spouse_birthday||"",spouse_name:d.spouse_name||"",spouse_email:d.spouse_email||"",company_name:d.company_name||"",job_title:d.job_title||"",lead_source_id:d.lead_source_id||"",notes:d.notes||"",tagIds:((It=d.tags)==null?void 0:It.map(Ds=>Ds.relationship_type_id))||[]}),I(!0))},Ct=async()=>{await b.mutateAsync({id:s,...M,lead_source_id:M.lead_source_id||null}),I(!1)},Yt=async()=>{confirm("Are you sure you want to delete this contact?")&&(await k.mutateAsync(s),t("/mission-control/contacts"))},Xs=((At=m==null?void 0:m.find(It=>It.id===V))==null?void 0:At.name)==="Other",zs=async()=>{if(!V||Xs&&!me.trim())return;const It=te?new Date(te.getFullYear(),te.getMonth(),te.getDate(),12,0,0).toISOString():void 0,Ds=Xs?`[${me.trim()}]${G?" — "+G:""}`:G;await A.mutateAsync({contactId:s,actionTypeId:V,notes:Ds,completedAt:It}),$(!1),W(null),X(""),ne(void 0),ue("")},Vt=(It,Ds)=>{Be&&d?(ge({email:It,name:Ds||`${d.first_name} ${d.last_name||""}`.trim()}),xe(!0)):window.location.href=`mailto:${It}`};return u?e.jsx(Qs,{title:"Contact Details",children:e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsx("div",{className:"animate-spin h-8 w-8 border-4 border-primary border-t-transparent rounded-full"})})}):d?e.jsxs(e.Fragment,{children:[e.jsx(Qs,{title:`${d.first_name} ${d.last_name||""}`,description:"Contact details and activity",children:e.jsxs("div",{className:"space-y-6 overflow-x-hidden",children:[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 items-center gap-2",children:[e.jsxs(B,{variant:"ghost",size:"sm",onClick:()=>{window.history.length>1?t(-1):t("/mission-control/contacts")},children:[e.jsx(Fc,{className:"h-4 w-4 mr-1"}),"Back to Contacts"]}),rt&&e.jsxs("div",{className:"flex items-center gap-1 ml-2 border-l pl-2",children:[e.jsxs(B,{variant:"ghost",size:"sm",onClick:()=>Ke&&t(Ze(Ke)),disabled:!Ke,className:"px-2",children:[e.jsx(Fc,{className:"h-4 w-4"}),e.jsx("span",{className:"sr-only sm:not-sr-only sm:ml-1",children:"Prev"})]}),e.jsxs("span",{className:"text-xs text-muted-foreground whitespace-nowrap",children:[Je+1," of ",Ye.length]}),e.jsxs(B,{variant:"ghost",size:"sm",onClick:()=>st&&t(Ze(st)),disabled:!st,className:"px-2",children:[e.jsx("span",{className:"sr-only sm:not-sr-only sm:mr-1",children:"Next"}),e.jsx(Qa,{className:"h-4 w-4"})]})]})]}),e.jsxs("div",{className:"flex items-center gap-2 w-full sm:w-auto justify-end flex-wrap",children:[d.phone&&e.jsxs(B,{variant:"outline",onClick:()=>window.location.href=`sms:${d.phone}`,className:"border-blue-500/30 text-blue-600 hover:bg-blue-500/10",children:[e.jsx(xo,{className:"h-4 w-4 mr-1"}),"Text"]}),d.email&&e.jsxs(B,{variant:"outline",onClick:()=>Vt(d.email,`${d.first_name} ${d.last_name||""}`.trim()),children:[e.jsx(mn,{className:"h-4 w-4 mr-1"}),"Email"]}),d.email&&e.jsxs(B,{variant:"outline",onClick:()=>Se(!0),className:"border-primary/40 text-primary hover:bg-primary/10",children:[e.jsx(Cn,{className:"h-4 w-4 mr-1"}),"Send Connect Page"]}),e.jsxs(B,{variant:"default",onClick:()=>t(`/mission-control/video/record?contact_id=${s}`),className:"bg-gradient-to-r from-primary to-primary/80",children:[e.jsx(na,{className:"h-4 w-4 mr-1"}),"Quick Video Touch"]}),e.jsxs(Bs,{open:z,onOpenChange:$,children:[e.jsx(Ao,{asChild:!0,children:e.jsxs(B,{variant:"outline",children:[e.jsx(nn,{className:"h-4 w-4 mr-1"}),"Log Action"]})}),e.jsxs(Fs,{className:"max-h-[85vh] overflow-y-auto",children:[e.jsx(qs,{children:e.jsx($s,{children:"Log an Action"})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(re,{children:"Action Type"}),e.jsx("div",{className:"grid grid-cols-2 gap-2 mt-2",children:m==null?void 0:m.filter(It=>It.active).map(It=>e.jsxs("button",{onClick:()=>W(It.id),className:` p-3 rounded-lg border text-left transition-all ${V===It.id?"border-primary bg-primary/10":"hover:bg-accent"} `,children:[e.jsx("div",{className:"font-medium",children:It.name}),e.jsx("div",{className:"text-xs text-muted-foreground",children:It.description})]},It.id))}),Xs&&e.jsxs("div",{className:"mt-3",children:[e.jsx(re,{htmlFor:"custom-action-name",children:"What did you do?"}),e.jsx(we,{id:"custom-action-name",value:me,onChange:It=>ue(It.target.value),placeholder:"e.g. Met a client for lunch, Dropped off a gift...",className:"mt-1"})]})]}),e.jsxs("div",{children:[e.jsx(re,{children:"Date (optional — backdate if needed)"}),e.jsxs(rc,{children:[e.jsx(ac,{asChild:!0,children:e.jsxs(B,{variant:"outline",className:Ot("w-full justify-start text-left font-normal mt-2",!te&&"text-muted-foreground"),children:[e.jsx(ta,{className:"h-4 w-4 mr-2"}),te?Js(te,"PPP"):"Today (default)"]})}),e.jsx(Zl,{className:"w-auto p-0",align:"start",children:e.jsx(Xv,{mode:"single",selected:te,onSelect:ne,disabled:It=>It>new Date,initialFocus:!0,className:Ot("p-3 pointer-events-auto")})})]})]}),e.jsxs("div",{children:[e.jsx(re,{htmlFor:"action-notes",children:"Notes (optional)"}),e.jsx(Ws,{id:"action-notes",value:G,onChange:It=>X(It.target.value),placeholder:"Add any notes about this interaction...",rows:3})]}),e.jsxs(B,{onClick:zs,disabled:!V||Xs&&!me.trim()||A.isPending,className:"w-full",children:[e.jsx(pa,{className:"h-4 w-4 mr-1"}),"Complete Action"]})]})]})]}),e.jsxs(B,{variant:"outline",onClick:Bt,children:[e.jsx(xp,{className:"h-4 w-4 mr-1"}),"Edit"]}),e.jsx(B,{variant:"destructive",size:"icon",onClick:Yt,children:e.jsx(qn,{className:"h-4 w-4"})})]})]}),e.jsx("div",{className:"bg-card border rounded-lg p-4 sm:p-6",children:e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center gap-4",children:[e.jsx(gIt,{contactId:d.id,firstName:d.first_name,lastName:d.last_name,avatarUrl:d.avatar_url,email:d.email,size:88}),e.jsxs("div",{className:"flex-1",children:[e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsxs("h1",{className:"text-2xl sm:text-3xl font-bold",children:[d.first_name," ",d.last_name||""]}),(((Os=d.lead_source_ref)==null?void 0:Os.name)||d.lead_source)&&e.jsx(We,{variant:"outline",className:"text-xs border-primary/30 text-primary",children:((Nt=d.lead_source_ref)==null?void 0:Nt.name)||d.lead_source})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-3 mt-2 text-muted-foreground",children:[d.email&&e.jsxs("button",{onClick:()=>Vt(d.email),className:"flex items-center gap-1 hover:text-primary transition-colors",children:[e.jsx(mn,{className:"h-4 w-4"}),e.jsx("span",{className:"text-sm",children:d.email})]}),d.phone&&e.jsxs("a",{href:`tel:${d.phone}`,className:"flex items-center gap-1 hover:text-primary transition-colors",children:[e.jsx(ga,{className:"h-4 w-4"}),e.jsx("span",{className:"text-sm",children:d.phone})]})]})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx(x5e,{contact:d}),(ms=d.tags)==null?void 0:ms.map(It=>{const Ds=h==null?void 0:h.find(As=>As.id===It.relationship_type_id);return Ds?e.jsx(We,{variant:"secondary",className:"text-xs",children:Ds.name},It.id):null})]}),e.jsx("div",{className:"mt-2",children:e.jsx(wpn,{contactId:s})})]})}),e.jsxs("div",{className:"grid md:grid-cols-3 gap-6",children:[e.jsxs(_e,{className:"md:col-span-2",children:[e.jsx(zt,{children:e.jsx(qt,{children:"Contact Information"})}),e.jsx(De,{children:P?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(re,{htmlFor:"first_name",children:"First Name"}),e.jsx(we,{id:"first_name",value:M.first_name,onChange:It=>L({...M,first_name:It.target.value})})]}),e.jsxs("div",{children:[e.jsx(re,{htmlFor:"last_name",children:"Last Name"}),e.jsx(we,{id:"last_name",value:M.last_name,onChange:It=>L({...M,last_name:It.target.value})})]})]}),e.jsxs("div",{children:[e.jsx(re,{htmlFor:"email",children:"Email"}),e.jsx(we,{id:"email",type:"email",value:M.email,onChange:It=>L({...M,email:It.target.value})})]}),e.jsxs("div",{children:[e.jsx(re,{htmlFor:"phone",children:"Phone"}),e.jsx(we,{id:"phone",value:M.phone,onChange:It=>L({...M,phone:It.target.value})})]}),e.jsxs("div",{children:[e.jsx(re,{htmlFor:"address",children:"Street Address"}),e.jsx(we,{id:"address",value:M.address,onChange:It=>L({...M,address:It.target.value}),placeholder:"123 Main St"})]}),e.jsxs("div",{className:"grid grid-cols-2 sm:grid-cols-4 gap-4",children:[e.jsxs("div",{className:"col-span-2",children:[e.jsx(re,{htmlFor:"city",children:"City"}),e.jsx(we,{id:"city",value:M.city,onChange:It=>L({...M,city:It.target.value}),placeholder:"City"})]}),e.jsxs("div",{children:[e.jsx(re,{htmlFor:"state",children:"State"}),e.jsx(we,{id:"state",value:M.state,onChange:It=>L({...M,state:It.target.value}),placeholder:"TX",maxLength:2})]}),e.jsxs("div",{children:[e.jsx(re,{htmlFor:"zip_code",children:"Zip Code"}),e.jsx(we,{id:"zip_code",value:M.zip_code,onChange:It=>L({...M,zip_code:It.target.value}),placeholder:"12345"})]})]}),e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx(re,{htmlFor:"birthday",children:"Birthday"}),e.jsx(we,{id:"birthday",type:"date",value:M.birthday,onChange:It=>L({...M,birthday:It.target.value})})]}),e.jsxs("div",{children:[e.jsx(re,{htmlFor:"home_anniversary",children:"Home Anniversary"}),e.jsx(we,{id:"home_anniversary",type:"date",value:M.home_anniversary,onChange:It=>L({...M,home_anniversary:It.target.value})})]}),e.jsxs("div",{children:[e.jsx(re,{htmlFor:"wedding_anniversary",children:"Wedding Anniversary"}),e.jsx(we,{id:"wedding_anniversary",type:"date",value:M.wedding_anniversary||"",onChange:It=>L({...M,wedding_anniversary:It.target.value})})]}),e.jsxs("div",{children:[e.jsx(re,{htmlFor:"spouse_birthday",children:"Spouse Birthday"}),e.jsx(we,{id:"spouse_birthday",type:"date",value:M.spouse_birthday,onChange:It=>L({...M,spouse_birthday:It.target.value})})]})]}),e.jsx(Wl,{}),e.jsx(l7e,{contactId:s,currentSpouseContactId:(d==null?void 0:d.spouse_contact_id)||null,currentSpouseName:(d==null?void 0:d.spouse_name)||null,currentSpouseEmail:(d==null?void 0:d.spouse_email)||null,onLink:It=>T.mutate({contactId:s,spouseContactId:It}),onUnlink:()=>T.mutate({contactId:s,spouseContactId:null}),isEditing:!0}),e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx(re,{htmlFor:"company_name",children:"Company"}),e.jsx(we,{id:"company_name",value:M.company_name,onChange:It=>L({...M,company_name:It.target.value}),placeholder:"Enter company name"})]}),e.jsxs("div",{children:[e.jsx(re,{htmlFor:"job_title",children:"Job Title"}),e.jsx(we,{id:"job_title",value:M.job_title,onChange:It=>L({...M,job_title:It.target.value}),placeholder:"Enter job title"})]})]}),e.jsx(fIt,{value:M.lead_source_id||"",onChange:It=>L({...M,lead_source_id:It})}),e.jsxs("div",{children:[e.jsx(re,{children:"Relationship Types"}),e.jsx("div",{className:"flex flex-wrap gap-2 mt-2",children:h==null?void 0:h.filter(It=>It.active).map(It=>{var Ds;return e.jsxs("label",{className:"flex items-center gap-2 cursor-pointer",children:[e.jsx(Bi,{checked:(Ds=M.tagIds)==null?void 0:Ds.includes(It.id),onCheckedChange:As=>{var Hs;L(As?{...M,tagIds:[...M.tagIds||[],It.id]}:{...M,tagIds:(Hs=M.tagIds)==null?void 0:Hs.filter(Rs=>Rs!==It.id)})}}),e.jsx("span",{className:"text-sm",children:It.name})]},It.id)})})]}),e.jsxs("div",{children:[e.jsx(re,{htmlFor:"notes",children:"Notes"}),e.jsx(Ws,{id:"notes",value:M.notes,onChange:It=>L({...M,notes:It.target.value}),rows:4})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(B,{onClick:Ct,disabled:b.isPending,children:"Save Changes"}),e.jsx(B,{variant:"outline",onClick:()=>I(!1),children:"Cancel"})]})]}):e.jsxs("div",{className:"space-y-4",children:[ht.length>0&&e.jsxs("div",{className:"bg-muted/50 rounded-lg p-3 flex items-center gap-2",children:[e.jsx(ta,{className:"h-4 w-4 text-primary"}),e.jsxs("span",{className:"text-sm",children:[e.jsx("span",{className:"font-medium",children:"Last Contacted:"})," ",Js(new Date(ht[0].completed_at),"MMM d, yyyy")," ","(",ht[0].name,")"]})]}),e.jsxs("div",{className:"flex flex-col sm:flex-row sm:gap-6 gap-2",children:[d.email&&e.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[e.jsx(mn,{className:"h-4 w-4 text-muted-foreground flex-shrink-0"}),e.jsx("button",{onClick:()=>Vt(d.email),className:"text-primary hover:underline truncate text-left",children:d.email})]}),d.phone&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ga,{className:"h-4 w-4 text-muted-foreground flex-shrink-0"}),e.jsx("a",{href:`tel:${d.phone}`,className:"text-primary hover:underline",children:d.phone}),e.jsx("button",{onClick:()=>window.location.href=`sms:${d.phone}`,className:"h-6 px-2 rounded-full bg-blue-500/10 text-blue-600 text-xs font-medium hover:bg-blue-500/20 transition-colors",children:"Text"})]})]}),(d.address||d.city||d.state||d.zip_code)&&e.jsxs("div",{className:"flex items-start justify-between gap-2 flex-wrap",children:[e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsx(ii,{className:"h-4 w-4 text-muted-foreground mt-0.5"}),e.jsxs("div",{className:"flex flex-col",children:[d.address&&e.jsx("span",{children:d.address}),(d.city||d.state||d.zip_code)&&e.jsxs("span",{className:"text-muted-foreground",children:[[d.city,d.state].filter(Boolean).join(", "),d.zip_code&&` ${d.zip_code}`]})]})]}),Fe&&d.address&&d.city&&d.state&&e.jsxs(B,{size:"sm",variant:"outline",onClick:Ae,disabled:Ge,children:[Ge?e.jsx(us,{className:"h-4 w-4 mr-1 animate-spin"}):e.jsx(u5,{className:"h-4 w-4 mr-1"}),"Create CMA"]})]}),e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-4",children:[d.birthday&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ta,{className:"h-4 w-4 text-muted-foreground"}),e.jsxs("span",{children:["Birthday: ",Js(Tc(d.birthday),Tc(d.birthday).getFullYear()===1900?"MMMM d":"MMMM d, yyyy")]})]}),d.home_anniversary&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(_a,{className:"h-4 w-4 text-muted-foreground"}),e.jsxs("span",{children:["Home Anniversary: ",Js(Tc(d.home_anniversary),Tc(d.home_anniversary).getFullYear()===1900?"MMMM d":"MMMM d, yyyy")]})]}),d.spouse_birthday&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(co,{className:"h-4 w-4 text-muted-foreground"}),e.jsxs("span",{children:["Spouse Birthday: ",Js(Tc(d.spouse_birthday),Tc(d.spouse_birthday).getFullYear()===1900?"MMMM d":"MMMM d, yyyy")]})]}),d.wedding_anniversary&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(co,{className:"h-4 w-4 text-muted-foreground"}),e.jsxs("span",{children:["Wedding Anniversary: ",Js(Tc(d.wedding_anniversary),Tc(d.wedding_anniversary).getFullYear()===1900?"MMMM d":"MMMM d, yyyy")]})]}),d.created_at&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(nn,{className:"h-4 w-4 text-muted-foreground"}),e.jsxs("span",{children:["Date Added: ",Js(new Date(d.created_at),"MMMM d, yyyy")]})]})]}),e.jsx(Wl,{}),e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-4",children:[e.jsx(l7e,{contactId:s,currentSpouseContactId:(d==null?void 0:d.spouse_contact_id)||null,currentSpouseName:d.spouse_name||null,currentSpouseEmail:d.spouse_email||null,onLink:It=>T.mutate({contactId:s,spouseContactId:It}),onUnlink:()=>T.mutate({contactId:s,spouseContactId:null}),isEditing:!1}),(d.company_name||d.job_title)&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ti,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:d.job_title&&d.company_name?`${d.job_title} at ${d.company_name}`:d.job_title||d.company_name})]})]}),e.jsx(Wl,{}),e.jsxs("div",{children:[e.jsx("h4",{className:"font-medium mb-2",children:"Relationship Types"}),e.jsx("div",{className:"flex flex-wrap gap-2",children:(Ys=d.tags)!=null&&Ys.length?d.tags.map(It=>{var Ds;return e.jsx(We,{variant:"secondary",children:(Ds=It.relationship_type)==null?void 0:Ds.name},It.id)}):e.jsx("span",{className:"text-sm text-muted-foreground",children:"No relationship types assigned"})})]}),d.notes&&e.jsxs(e.Fragment,{children:[e.jsx(Wl,{}),e.jsxs("div",{children:[e.jsx("h4",{className:"font-medium mb-2",children:"Notes"}),e.jsx("p",{className:"text-sm text-muted-foreground whitespace-pre-wrap",children:d.notes})]})]})]})})]}),e.jsxs("div",{className:"space-y-6",children:[e.jsx(kmn,{contact:d,onLogTouch:()=>$(!0)}),e.jsx(gfn,{contactId:s}),e.jsx(nfn,{contactId:s}),e.jsx(rfn,{contactId:s}),e.jsx(ifn,{contactId:s,contactName:d.first_name}),e.jsx(ofn,{contactId:s,contactName:d.first_name}),e.jsx(pfn,{contactId:s}),e.jsx(dfn,{contactId:s}),e.jsx(hfn,{contactId:s}),e.jsxs(_e,{children:[e.jsx(zt,{children:e.jsx(qt,{children:"Activity Log"})}),e.jsx(De,{children:ht.length>0?e.jsx("div",{className:"space-y-4",children:ht.map(It=>{var Ds;return e.jsxs("div",{className:"flex items-start gap-3 pb-3 border-b last:border-0",children:[e.jsx("div",{className:"h-8 w-8 rounded-full flex items-center justify-center text-white text-xs",style:{backgroundColor:It.color},children:It.type==="popby"?e.jsx(Io,{className:"h-4 w-4"}):(Ds=It.name)==null?void 0:Ds.charAt(0)}),e.jsxs("div",{className:"flex-1",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"font-medium text-sm",children:It.name}),It.videoId&&e.jsxs(B,{variant:"ghost",size:"sm",className:"h-6 px-2 text-xs",onClick:()=>ae(It.videoId),children:[e.jsx(dd,{className:"h-3 w-3 mr-1"}),"Preview"]})]}),e.jsx("div",{className:"text-xs text-muted-foreground",children:Js(new Date(It.completed_at),"MMM d, yyyy h:mm a")}),It.notes&&!It.videoId&&e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:It.notes})]})]},It.id)})}):e.jsx("p",{className:"text-sm text-muted-foreground text-center py-4",children:"No activity logged yet"})})]}),y&&y.length>0&&e.jsxs(_e,{children:[e.jsx(zt,{children:e.jsxs(qt,{className:"flex items-center gap-2",children:[e.jsx(xo,{className:"h-5 w-5 text-primary"}),"Video Replies"]})}),e.jsx(De,{children:e.jsx("div",{className:"space-y-4",children:y.map(It=>{var Ds,As;return e.jsxs("div",{className:"flex items-start gap-3 pb-3 border-b last:border-0",children:[(Ds=It.video)!=null&&Ds.thumbnail_url?e.jsx("img",{src:It.video.thumbnail_url,alt:It.video.title||"Video",className:"h-12 w-16 object-cover rounded cursor-pointer hover:opacity-80 transition-opacity",onClick:()=>ae(It.video_id)}):e.jsx("div",{className:"h-12 w-16 bg-muted rounded flex items-center justify-center cursor-pointer hover:bg-muted/80 transition-colors",onClick:()=>ae(It.video_id),children:e.jsx(na,{className:"h-5 w-5 text-muted-foreground"})}),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:["Replied to: ",((As=It.video)==null?void 0:As.title)||"Untitled Video"]}),e.jsxs(B,{variant:"ghost",size:"sm",className:"h-6 px-2 text-xs flex-shrink-0",onClick:()=>ae(It.video_id),children:[e.jsx(dd,{className:"h-3 w-3 mr-1"}),"Watch"]})]}),e.jsx("div",{className:"text-xs text-muted-foreground",children:Js(new Date(It.created_at),"MMM d, yyyy h:mm a")}),It.message&&e.jsxs("p",{className:"text-sm text-muted-foreground mt-1 line-clamp-2",children:['"',It.message,'"']})]})]},It.id)})})})]}),Xe&&Xe.length>0&&e.jsxs(_e,{children:[e.jsx(zt,{children:e.jsxs(qt,{className:"flex items-center gap-2",children:[e.jsx(Rr,{className:"h-5 w-5 text-sky-500"}),"Sent Emails"]})}),e.jsx(De,{children:e.jsx("div",{className:"space-y-3",children:Xe.map(It=>e.jsxs(Bs,{children:[e.jsx(Ao,{asChild:!0,children:e.jsxs("button",{className:"w-full text-left flex items-start gap-3 p-3 rounded-lg border hover:bg-muted/50 transition-colors cursor-pointer",children:[e.jsx("div",{className:"h-8 w-8 rounded-full bg-sky-500/10 flex items-center justify-center text-sky-600 flex-shrink-0",children:e.jsx(mn,{className:"h-4 w-4"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"font-medium text-sm truncate",children:It.subject}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:["To: ",It.to_email," · ",Js(new Date(It.sent_at),"MMM d, yyyy h:mm a")]})]}),e.jsx(Qa,{className:"h-4 w-4 text-muted-foreground mt-1 flex-shrink-0"})]})}),e.jsxs(Fs,{className:"max-w-2xl max-h-[85vh] flex flex-col",children:[e.jsxs(qs,{children:[e.jsxs($s,{className:"flex items-center gap-2",children:[e.jsx(mn,{className:"h-5 w-5 text-sky-500"}),It.subject]}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:["To: ",It.to_email," · ",Js(new Date(It.sent_at),"MMM d, yyyy h:mm a")]})]}),e.jsx("div",{className:"flex-1 min-h-0 overflow-hidden rounded-lg border bg-white",children:e.jsx("iframe",{srcDoc:It.body,className:"w-full h-[400px] border-0",sandbox:"",title:`Email: ${It.subject}`})})]})]},It.id))})})]})]}),e.jsx(Bs,{open:!!ce,onOpenChange:It=>!It&&ae(null),children:e.jsxs(Fs,{className:"max-w-2xl",children:[e.jsx(qs,{children:e.jsx($s,{children:"Video Preview"})}),ce&&e.jsx(mfn,{videoId:ce})]})})]})]})}),Be&&d&&ve&&e.jsx(Y_,{open:he,onOpenChange:xe,contact:{id:d.id,first_name:d.first_name,last_name:d.last_name,email:ve.email},gmailEmail:Me}),d&&d.email&&e.jsx($pn,{open:be,onOpenChange:Se,contact:{id:d.id,first_name:d.first_name,last_name:d.last_name,email:d.email}})]}):e.jsx(Qs,{title:"Contact Not Found",children:e.jsxs("div",{className:"text-center py-12",children:[e.jsx("p",{className:"text-muted-foreground mb-4",children:"This contact was not found."}),e.jsx(B,{onClick:()=>t("/mission-control/contacts"),children:"Back to Contacts"})]})})}function yfn({rangeDays:s}){const{user:t}=Ls(),n=as(),[r,a]=N.useState(null),[i,l]=N.useState(null),[o,c]=N.useState(!1),{data:d=[],isLoading:u}=mt({queryKey:["newsletter-campaigns",t==null?void 0:t.id,s],enabled:!!t,queryFn:async()=>{let f=H.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 x=new Date(Date.now()-s*864e5).toISOString();f=f.gte("created_at",x)}const{data:g,error:y}=await f;if(y)throw y;return g||[]}}),{data:h}=mt({queryKey:["newsletter-campaign-recipients",r],enabled:!!r,queryFn:async()=>{const{data:f,error:g}=await H.from("email_campaign_recipients").select("id, email, name, status, sent_at, opened_at, clicked_at, error_message").eq("campaign_id",r).order("sent_at",{ascending:!1}).limit(2e3);if(g)throw g;return f||[]}}),m=async()=>{if(!(!i||!t)){c(!0);try{const{data:f,error:g}=await H.from("email_campaign_recipients").select("email, name, contact_id").eq("campaign_id",i.id).eq("status","sent").is("opened_at",null).limit(5e3);if(g)throw g;if(!f||f.length===0){ie.info("All recipients opened — nothing to resend!"),l(null),c(!1);return}const{data:y}=await H.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:x,error:_}=await H.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:f.length,status:"draft"}).select("id").single();if(_)throw _;const b=f.map(A=>({campaign_id:x.id,contact_id:A.contact_id,email:A.email,name:A.name,status:"pending"}));for(let A=0;A{const g=f.sent_count||0,y=g>0?f.open_count/g*100:0,x=g>0?f.click_count/g*100:0,_=f.sent_at?wj(new Date,new Date(f.sent_at)):0,b=f.status==="sent"&&_>=3&&g>0&&f.open_counta(f.id),children:[e.jsx(da,{className:"h-3.5 w-3.5 mr-1"})," Details"]}),b&&e.jsxs(B,{variant:"outline",size:"sm",onClick:()=>l(f),children:[e.jsx(wD,{className:"h-3.5 w-3.5 mr-1"})," Resend"]})]})]}),f.status==="sent"&&g>0&&e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-3 mt-3",children:[e.jsx(sne,{icon:e.jsx(Rr,{className:"h-3.5 w-3.5"}),label:"Sent",value:g,sub:`of ${f.total_recipients}`}),e.jsx(sne,{icon:e.jsx(da,{className:"h-3.5 w-3.5 text-blue-600"}),label:"Opens",value:f.open_count,sub:`${y.toFixed(1)}%`,children:e.jsx(ro,{value:y,className:"h-1 mt-1"})}),e.jsx(sne,{icon:e.jsx(ru,{className:"h-3.5 w-3.5 text-purple-600"}),label:"Clicks",value:f.click_count,sub:`${x.toFixed(1)}%`,children:e.jsx(ro,{value:x,className:"h-1 mt-1"})}),e.jsx(sne,{icon:e.jsx(y9,{className:"h-3.5 w-3.5 text-orange-600"}),label:"Bounces",value:f.bounce_count,sub:f.bounce_count>0?"review":"none"})]})]},f.id)})})]})}),e.jsx(l1,{open:!!r,onOpenChange:f=>!f&&a(null),children:e.jsxs(Gy,{className:"w-full sm:max-w-2xl overflow-y-auto",children:[e.jsx(gb,{children:e.jsx(xb,{children:"Recipient Activity"})}),e.jsx("div",{className:"mt-4 space-y-1",children:h?h.length===0?e.jsx("p",{className:"text-sm text-muted-foreground",children:"No recipients yet."}):e.jsxs("table",{className:"w-full text-sm",children:[e.jsx("thead",{className:"text-xs uppercase text-muted-foreground border-b",children:e.jsxs("tr",{children:[e.jsx("th",{className:"text-left py-2",children:"Recipient"}),e.jsx("th",{className:"text-left py-2",children:"Opened"}),e.jsx("th",{className:"text-left py-2",children:"Clicked"}),e.jsx("th",{className:"text-left py-2",children:"Status"})]})}),e.jsx("tbody",{children:h.map(f=>e.jsxs("tr",{className:"border-b last:border-0",children:[e.jsxs("td",{className:"py-2",children:[e.jsx("div",{className:"font-medium truncate max-w-[180px]",children:f.name||"—"}),e.jsx("div",{className:"text-xs text-muted-foreground truncate max-w-[180px]",children:f.email})]}),e.jsx("td",{className:"py-2 text-xs",children:f.opened_at?e.jsx(We,{variant:"default",className:"text-xs",children:Js(new Date(f.opened_at),"MMM d")}):e.jsx("span",{className:"text-muted-foreground",children:"—"})}),e.jsx("td",{className:"py-2 text-xs",children:f.clicked_at?e.jsx(We,{variant:"default",className:"text-xs bg-purple-600",children:Js(new Date(f.clicked_at),"MMM d")}):e.jsx("span",{className:"text-muted-foreground",children:"—"})}),e.jsxs("td",{className:"py-2 text-xs",children:[f.status==="sent"&&e.jsx(We,{variant:"outline",className:"text-xs",children:"sent"}),f.status==="pending"&&e.jsx(We,{variant:"secondary",className:"text-xs",children:"queued"}),f.status==="failed"&&e.jsx(We,{variant:"destructive",className:"text-xs",title:f.error_message||"",children:"failed"}),f.status==="suppressed"&&e.jsx(We,{variant:"outline",className:"text-xs",children:"suppressed"})]})]},f.id))})]}):e.jsx("p",{className:"text-sm text-muted-foreground",children:"Loading…"})})]})}),e.jsx(Fl,{open:!!i,onOpenChange:f=>!f&&l(null),children:e.jsxs(kl,{children:[e.jsxs(Sl,{children:[e.jsx(Al,{children:"Resend to non-openers?"}),e.jsxs(Tl,{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(Cl,{children:[e.jsx(El,{disabled:o,children:"Cancel"}),e.jsx(wl,{onClick:m,disabled:o,children:o?e.jsxs(e.Fragment,{children:[e.jsx(us,{className:"h-4 w-4 mr-1 animate-spin"}),"Resending…"]}):e.jsxs(e.Fragment,{children:[e.jsx(wD,{className:"h-4 w-4 mr-1"}),"Resend"]})})]})]})})]})}function sne({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 bZ(){var r;const{data:{session:s}}=await H.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 H.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 vfn(){const{user:s}=Ls(),t=tr(),n=as(),{data:r=[],isLoading:a}=mt({queryKey:["scheduled-email-campaigns",s==null?void 0:s.id],enabled:!!s,queryFn:async()=>{const{data:d,error:u}=await H.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 bZ(),f=await(await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/ses-schedule-campaign",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${h}`},body:JSON.stringify({action:d,campaign_id:u})})).json();if(!f.success)throw new Error(f.error||`Failed to ${d}`);return f},l=_t({mutationFn:d=>i("cancel",d),onSuccess:()=>{ie.success("Schedule cancelled — saved as draft"),n.invalidateQueries({queryKey:["scheduled-email-campaigns"]})},onError:d=>ie.error(d.message)}),o=_t({mutationFn:d=>i("delete",d),onSuccess:()=>{ie.success("Scheduled email deleted"),n.invalidateQueries({queryKey:["scheduled-email-campaigns"]})},onError:d=>ie.error(d.message)}),c=_t({mutationFn:async({id:d,iso:u})=>{const{error:h}=await H.from("email_campaigns").update({scheduled_at:u,status:"scheduled"}).eq("id",d);if(h)throw h;await i("schedule",d)},onSuccess:()=>{ie.success("Send time updated"),n.invalidateQueries({queryKey:["scheduled-email-campaigns"]})},onError:d=>ie.error(d.message)});return a?e.jsx("div",{className:"text-center py-12 text-muted-foreground",children:"Loading scheduled emails..."}):r.length===0?e.jsx(_e,{children:e.jsxs(De,{className:"flex flex-col items-center justify-center py-12 text-center",children:[e.jsx(Xr,{className:"h-12 w-12 text-muted-foreground mb-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(bfn,{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 bfn({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]=N.useState(!1),[d,u]=N.useState(l||void 0),[h,m]=N.useState(l?`${String(l.getHours()).padStart(2,"0")}:${String(l.getMinutes()).padStart(2,"0")}`:"09:00"),f=()=>{if(!d)return ie.error("Pick a date");const g=new Date(`${Js(d,"yyyy-MM-dd")}T${h}:00`).toISOString();if(new Date(g).getTime()gm(g.target.value)})]})]}),e.jsxs(Cr,{children:[e.jsx(B,{variant:"ghost",onClick:()=>c(!1),children:"Cancel"}),e.jsxs(B,{onClick:f,disabled:i,children:[i&&e.jsx(us,{className:"h-4 w-4 mr-1.5 animate-spin"}),"Save new time"]})]})]})]}),e.jsxs(Fl,{children:[e.jsx(Gf,{asChild:!0,children:e.jsxs(B,{size:"sm",variant:"outline",disabled:i,children:[e.jsx(Nu,{className:"h-3.5 w-3.5 mr-1.5"})," Cancel Send"]})}),e.jsxs(kl,{children:[e.jsxs(Sl,{children:[e.jsx(Al,{children:"Cancel this scheduled send?"}),e.jsxs(Tl,{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(Cl,{children:[e.jsx(El,{children:"Keep scheduled"}),e.jsx(wl,{onClick:n,children:"Cancel send"})]})]})]}),e.jsxs(Fl,{children:[e.jsx(Gf,{asChild:!0,children:e.jsxs(B,{size:"sm",variant:"ghost",className:"text-destructive hover:text-destructive",disabled:i,children:[e.jsx(qn,{className:"h-3.5 w-3.5 mr-1.5"})," Delete"]})}),e.jsxs(kl,{children:[e.jsxs(Sl,{children:[e.jsx(Al,{children:"Delete this scheduled email?"}),e.jsx(Tl,{children:"This permanently removes the scheduled email and all its recipient records. This can't be undone."})]}),e.jsxs(Cl,{children:[e.jsx(El,{children:"Keep"}),e.jsx(wl,{onClick:r,className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:"Delete permanently"})]})]})]})]})]})})})}function _fn({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 nne({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:Ot("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(Qa,{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 wfn({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(_fn,{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(nne,{icon:e.jsx(Hr,{className:"h-3.5 w-3.5"}),label:"Delivered",value:s.toLocaleString(),hint:"All sends completed"}),e.jsx(nne,{icon:e.jsx(da,{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(nne,{icon:e.jsx(ru,{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(nne,{icon:e.jsx(Xr,{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 jht=["Gmail","Mass Email","Campaign","Client Portal Invite"],jfn={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 Nfn(){const{user:s}=Ls(),[t,n]=$c(),{data:r=[],isLoading:a}=NIt(),[i,l]=N.useState(""),[o,c]=N.useState("all"),[d,u]=N.useState("30"),[h,m]=N.useState(!1),[f,g]=N.useState(t.get("tab")==="scheduled"?"scheduled":"sent"),{gmailEmail:y}=_f(),{data:x=0}=mt({queryKey:["scheduled-email-count",s==null?void 0:s.id],enabled:!!s,queryFn:async()=>{const{count:I}=await H.from("email_campaigns").select("id",{count:"exact",head:!0}).eq("user_id",s.id).eq("status","scheduled");return I||0},refetchInterval:3e4});N.useEffect(()=>{const I=new URLSearchParams(t);f==="scheduled"?I.set("tab","scheduled"):I.delete("tab"),n(I,{replace:!0})},[f]);const _=N.useMemo(()=>Array.from(new Set(r.map(I=>I.contact_id).filter(Boolean))),[r]),{data:b}=mt({queryKey:["sent-emails-contact-names",s==null?void 0:s.id,_.length],enabled:_.length>0,queryFn:async()=>{const{data:I}=await H.from("innercircle_contacts").select("id, first_name, last_name").in("id",_),M=new Map;return(I||[]).forEach(L=>{M.set(L.id,[L.first_name,L.last_name].filter(Boolean).join(" ")||"Contact")}),M}}),k=N.useMemo(()=>{const I=d==="all"?null:Date.now()-parseInt(d)*864e5,M=i.trim().toLowerCase();return r.filter(L=>{if(o!=="all"&&L.channel!==o||I&&new Date(L.sent_at).getTime(){const I={};let M=0,L=0,z=0;return k.forEach($=>{I[$.channel]=(I[$.channel]||0)+1,($.channel==="Campaign"||$.channel==="Mass Email")&&(z++,$.opened_at&&M++,$.clicked_at&&L++)}),{byChannel:I,opened:M,clicked:L,trackable:z}},[k]),T=d==="all"?"All time":`Last ${d} days`,P=jht.map(I=>A.byChannel[I]?`${A.byChannel[I]} ${I}`:null).filter(Boolean).join(" · ");return e.jsx(Qs,{children:e.jsxs("div",{className:"space-y-5 p-4 md:p-8",children:[e.jsxs("div",{className:"flex flex-col gap-3 md:flex-row md:items-center md:justify-between",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsxs("h1",{className:"text-2xl font-bold flex items-center gap-2",children:[e.jsx(Rr,{className:"h-6 w-6"})," Sent Emails"]}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Every send in one place — Gmail, mass emails, campaigns, and portal invites."})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("div",{className:"inline-flex rounded-full border bg-muted/40 p-1",children:[e.jsxs("button",{onClick:()=>g("sent"),className:`inline-flex items-center gap-1.5 rounded-full px-3 py-1.5 text-sm transition-colors ${f==="sent"?"bg-background shadow-sm font-medium":"text-muted-foreground hover:text-foreground"}`,children:[e.jsx(Rr,{className:"h-3.5 w-3.5"})," Sent"]}),e.jsxs("button",{onClick:()=>g("scheduled"),className:`inline-flex items-center gap-1.5 rounded-full px-3 py-1.5 text-sm transition-colors ${f==="scheduled"?"bg-background shadow-sm font-medium":"text-muted-foreground hover:text-foreground"}`,children:[e.jsx(Xr,{className:"h-3.5 w-3.5"})," Scheduled",x>0&&e.jsx(We,{variant:"secondary",className:"ml-0.5 h-5 min-w-5 px-1.5 text-xs",children:x})]})]}),e.jsxs(B,{onClick:()=>m(!0),className:"rounded-full",children:[e.jsx(mn,{className:"h-4 w-4 mr-2"})," Send Email"]})]})]}),e.jsxs(ya,{value:f,onValueChange:I=>g(I),className:"space-y-5",children:[e.jsxs(_s,{value:"sent",className:"space-y-5 mt-0",children:[e.jsx(wfn,{total:k.length,opened:A.opened,clicked:A.clicked,trackable:A.trackable,scheduled:x,rangeLabel:T,channelSummary:P,onScheduledClick:()=>g("scheduled")}),e.jsxs("div",{className:"flex flex-col gap-2 rounded-2xl border bg-card p-2 md:flex-row md:items-center",children:[e.jsxs("div",{className:"relative flex-1",children:[e.jsx(Gr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(we,{placeholder:"Search subject, recipient, contact...",value:i,onChange:I=>l(I.target.value),className:"pl-9 border-0 bg-transparent shadow-none focus-visible:ring-0"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(Ns,{value:o,onValueChange:c,children:[e.jsx(ws,{className:"w-[170px] rounded-full h-9",children:e.jsx(ks,{})}),e.jsxs(js,{children:[e.jsx(nt,{value:"all",children:"All Channels"}),jht.map(I=>e.jsx(nt,{value:I,children:I},I))]})]}),e.jsxs(Ns,{value:d,onValueChange:u,children:[e.jsx(ws,{className:"w-[150px] rounded-full h-9",children:e.jsx(ks,{})}),e.jsxs(js,{children:[e.jsx(nt,{value:"7",children:"Last 7 days"}),e.jsx(nt,{value:"30",children:"Last 30 days"}),e.jsx(nt,{value:"90",children:"Last 90 days"}),e.jsx(nt,{value:"365",children:"Last year"}),e.jsx(nt,{value:"all",children:"All time"})]})]})]})]}),e.jsxs("p",{className:"text-xs text-muted-foreground -mt-3 px-1",children:[e.jsx(p5,{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(yfn,{rangeDays:d==="all"?null:parseInt(d)}),a?e.jsx("div",{className:"text-center py-12 text-muted-foreground",children:"Loading..."}):k.length===0?e.jsx(_e,{className:"rounded-2xl",children:e.jsxs(De,{className:"flex flex-col items-center justify-center py-12 text-center",children:[e.jsx(mn,{className:"h-12 w-12 text-muted-foreground mb-3"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"No sent emails match your filters."})]})}):e.jsx(_e,{className:"rounded-2xl overflow-hidden",children:e.jsx(De,{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(wu,{children:[e.jsxs(ju,{className:"inline-flex items-center gap-1",children:["Engagement ",e.jsx(p5,{className:"h-3 w-3"})]}),e.jsx(nu,{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:k.slice(0,500).map(I=>{const M=I.contact_id?b==null?void 0:b.get(I.contact_id):null,L=I.channel==="Campaign"||I.channel==="Mass Email";return e.jsxs("tr",{className:"border-t hover:bg-muted/30",children:[e.jsx("td",{className:"py-3 px-4 whitespace-nowrap text-muted-foreground",children:Js(new Date(I.sent_at),"MMM d, yyyy h:mm a")}),e.jsx("td",{className:"py-3 px-4",children:e.jsx(We,{variant:"outline",className:jfn[I.channel],children:I.channel})}),e.jsx("td",{className:"py-3 px-4 max-w-xs truncate font-medium",children:I.subject}),e.jsx("td",{className:"py-3 px-4 text-muted-foreground",children:I.to_email}),e.jsx("td",{className:"py-3 px-4",children:I.contact_id&&M?e.jsx(cr,{to:`/mission-control/contacts/${I.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:L?e.jsxs("div",{className:"flex flex-wrap gap-1",children:[e.jsxs(We,{variant:"outline",className:"bg-slate-50 text-slate-700 border-slate-200 gap-1",children:[e.jsx(Hr,{className:"h-3 w-3"})," Delivered"]}),I.opened_at&&e.jsxs(We,{variant:"outline",className:"bg-blue-50 text-blue-700 border-blue-200 gap-1",children:[e.jsx(da,{className:"h-3 w-3"})," Opened"]}),I.clicked_at&&e.jsxs(We,{variant:"outline",className:"bg-emerald-50 text-emerald-700 border-emerald-200 gap-1",children:[e.jsx(ru,{className:"h-3 w-3"})," Clicked"]})]}):e.jsx("span",{className:"text-xs text-muted-foreground",children:"Not tracked"})})]},I.id)})})]}),k.length>500&&e.jsxs("p",{className:"text-xs text-muted-foreground text-center py-3 border-t",children:["Showing first 500 of ",k.length," — narrow your filters to see more."]})]})})})]}),e.jsx(_s,{value:"scheduled",className:"mt-0",children:e.jsx(vfn,{})})]}),e.jsx(Y_,{open:h,onOpenChange:m,gmailEmail:y})]})})}const Nht={Crown:q0,FileText:Wr,Users:Yn,Globe:au,Star:Wa,Phone:ga,MessageSquare:xo,PenTool:PT,Video:na,Gift:Io},rne=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];function kfn(){var Ct,Yt;const s=tr(),{user:t}=Ls(),{data:n}=K_(),{data:r}=cjs(),{data:a}=gjs(),{data:i}=N4t(),{data:l}=fU(),{data:o}=ljs(),c=xjs(),d=djs(),u=hjs(),h=mjs(),m=pjs(),f=fjs(),g=ujs(),[y,x]=N.useState(null),[_,b]=N.useState(!1),[k,A]=N.useState(null),[T,P]=N.useState(""),[I,M]=N.useState(""),[L,z]=N.useState([]),[$,V]=N.useState(null),[W,G]=N.useState(null),[X,te]=N.useState(null),[ne,me]=N.useState(!1),[ue,ce]=N.useState(""),[ae,he]=N.useState(""),[xe,ve]=N.useState(""),[ge,be]=N.useState(""),Se=(Kt,Xs)=>a==null?void 0:a.some(zs=>zs.plan_id===Kt&&zs.relationship_type_id===Xs&&zs.active),Ie=Kt=>a==null?void 0:a.find(Xs=>Xs.relationship_type_id===Kt&&Xs.active),Me=async(Kt,Xs)=>{const zs=Se(Kt,Xs);await c.mutateAsync({planId:Kt,relationshipTypeId:Xs,active:!zs})},Re=(r==null?void 0:r.filter(Kt=>Kt.active&&!Kt.owner_user_id))||[],Be=(r==null?void 0:r.filter(Kt=>Kt.owner_user_id===(t==null?void 0:t.id)))||[],Ne=n==null?void 0:n.find(Kt=>Kt.id===y),Ge=y?Ie(y):null,Ce=r==null?void 0:r.find(Kt=>Kt.id===(Ge==null?void 0:Ge.plan_id)),Fe=async()=>{if(!T.trim())return;const Kt=await d.mutateAsync({name:T,description:I});Kt&&L.length>0&&await m.mutateAsync({planId:Kt.id,items:L}),Ye()},Ae=async()=>{!T.trim()||!k||(await u.mutateAsync({id:k,name:T,description:I}),await m.mutateAsync({planId:k,items:L}),Ye())},Xe=Kt=>{var Xs;A(Kt.id),P(Kt.name),M(Kt.description||""),z(((Xs=Kt.items)==null?void 0:Xs.map(zs=>({month_number:zs.month_number,action_type_id:zs.action_type_id,default_script_id:zs.default_script_id||void 0,notes:zs.notes||void 0})))||[]),b(!0)},$e=async(Kt,Xs)=>{if(Kt.owner_user_id===(t==null?void 0:t.id)){Xe(Kt);return}try{const zs=await g.mutateAsync({sourcePlanId:Kt.id,newName:`${Kt.name} (My Copy)`});if(!zs)return;await c.mutateAsync({planId:Kt.id,relationshipTypeId:Xs,active:!1}),await c.mutateAsync({planId:zs.id,relationshipTypeId:Xs,active:!0}),A(zs.id),P(zs.name),M(zs.description||""),z((Kt.items||[]).map(Vt=>({month_number:Vt.month_number,action_type_id:Vt.action_type_id,default_script_id:Vt.default_script_id||void 0,notes:Vt.notes||void 0}))),b(!0)}catch{}},Ye=()=>{b(!1),A(null),P(""),M(""),z([])},Je=(Kt,Xs)=>{G(Xs)},Ke=(Kt,Xs,zs)=>{z(Vt=>[...Vt.filter(Os=>Os.month_number!==Kt),{month_number:Kt,action_type_id:Xs,default_script_id:zs}]),V(null),G(null)},st=Kt=>{z(Xs=>Xs.filter(zs=>zs.month_number!==Kt))},rt=async()=>{if(!ue.trim()||!ae.trim()||!W)return;const Kt=await f.mutateAsync({actionTypeId:W,title:ue,scriptBody:ae,emailSubject:xe||void 0,tone:ge||void 0});Kt&&$!==null&&Ke($,W,Kt.id),me(!1),ce(""),he(""),ve(""),be("")},Ze=W?o==null?void 0:o.filter(Kt=>Kt.action_type_id===W&&Kt.active):[],ht=Kt=>Nht[Kt||"Phone"]||ga,Bt=Kt=>Nht[Kt||"Users"]||Yn;return e.jsxs(Qs,{title:"Touchpoint Plans",description:"Assign plans to your contact groups",children:[e.jsxs("div",{className:"space-y-6 overflow-x-hidden",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("h1",{className:"text-2xl font-bold",children:"Touchpoint Plans"}),e.jsx("span",{className:"text-[10px] font-semibold uppercase tracking-wide px-1.5 py-0.5 rounded border border-amber-500 text-amber-600 dark:text-amber-400 bg-amber-500/10",children:"Beta"})]}),e.jsxs("div",{className:"flex flex-col sm:flex-row items-start sm:items-center justify-between gap-3",children:[e.jsxs(B,{variant:"ghost",size:"sm",onClick:()=>s("/mission-control"),children:[e.jsx(Fc,{className:"h-4 w-4 mr-1"}),"Back"]}),e.jsxs(B,{onClick:()=>b(!0),className:"w-full sm:w-auto",children:[e.jsx(nn,{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(Kt=>Kt.active).map(Kt=>{const Xs=Bt(Kt.icon),zs=(i==null?void 0:i[Kt.id])||0,Vt=Ie(Kt.id),At=r==null?void 0:r.find(Nt=>Nt.id===(Vt==null?void 0:Vt.plan_id)),Os=y===Kt.id;return e.jsxs("button",{onClick:()=>x(Kt.id),className:` w-full flex items-center gap-3 p-4 rounded-lg border text-left transition-all ${Os?"border-primary bg-primary/5 ring-2 ring-primary":"hover:bg-accent"} `,children:[e.jsx(Xs,{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:Kt.name}),e.jsxs("div",{className:"text-sm text-muted-foreground",children:[zs," contacts"]})]}),At?e.jsxs(We,{variant:"secondary",className:"text-xs",children:[e.jsx(Po,{className:"h-3 w-3 mr-1"}),At.name.split(" ")[0]]}):e.jsx(We,{variant:"outline",className:"text-xs text-muted-foreground",children:"No plan"})]},Kt.id)})]}),e.jsx("div",{className:"lg:col-span-2",children:y&&Ne?e.jsxs(_e,{children:[e.jsxs(zt,{children:[e.jsxs(qt,{className:"flex items-center gap-2",children:[(()=>{const Kt=Bt(Ne.icon);return e.jsx(Kt,{className:"h-5 w-5"})})(),Ne.name," Touchpoint Plan"]}),e.jsxs(_r,{children:["Choose a plan for your ",Ne.name," contacts"]})]}),e.jsxs(De,{className:"space-y-6",children:[Ce&&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(Po,{className:"h-4 w-4 text-green-500"}),"Currently using: ",Ce.name]}),Ce.description&&e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:Ce.description})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(B,{variant:"outline",size:"sm",disabled:g.isPending||c.isPending,onClick:()=>$e(Ce,y),children:[e.jsx(Ww,{className:"h-4 w-4 mr-1"}),"Edit Steps"]}),e.jsx(B,{variant:"outline",size:"sm",onClick:()=>Me(Ce.id,y),children:"Disable"})]})]}),Ce.items&&Ce.items.length>0&&e.jsxs("div",{className:"mt-4",children:[e.jsxs("div",{className:"text-sm font-medium mb-2 flex items-center gap-2",children:[e.jsx(ta,{className:"h-4 w-4"}),"12-Month Schedule"]}),e.jsx("div",{className:"grid grid-cols-4 sm:grid-cols-6 gap-2",children:rne.map((Kt,Xs)=>{var Os,Nt;const zs=((Os=Ce.items)==null?void 0:Os.filter(ms=>ms.month_number===Xs+1))||[],Vt=(Nt=zs[0])==null?void 0:Nt.action_type,At=Vt?ht(Vt.icon):null;return e.jsxs("div",{className:` p-2 rounded border text-center ${zs.length>0?"bg-primary/10 border-primary":"bg-muted"} `,children:[e.jsx("div",{className:"text-xs text-muted-foreground",children:Kt}),At&&e.jsx(At,{className:"h-4 w-4 mx-auto mt-1",style:{color:(Vt==null?void 0:Vt.color)||"#3B82F6"}})]},Xs)})})]})]}),e.jsxs("div",{children:[e.jsx("h4",{className:"font-medium mb-3",children:Ce?"Switch to a Different Plan":"Choose a Plan"}),Re.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"}),Re.map(Kt=>{var zs;const Xs=(Ce==null?void 0:Ce.id)===Kt.id;return e.jsxs("div",{className:` flex items-center justify-between p-3 rounded-lg border ${Xs?"opacity-50":"hover:bg-accent"} `,children:[e.jsxs("div",{children:[e.jsx("div",{className:"font-medium",children:Kt.name}),e.jsxs("div",{className:"text-sm text-muted-foreground",children:[((zs=Kt.items)==null?void 0:zs.length)||0," touchpoints/year"]})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(B,{size:"sm",variant:"ghost",title:"View plan details",onClick:()=>te(Kt.id),children:e.jsx(da,{className:"h-4 w-4"})}),e.jsx(B,{size:"sm",variant:"ghost",title:"Duplicate as my own plan",disabled:g.isPending,onClick:()=>{const Vt=`${Kt.name} (Copy)`;g.mutate({sourcePlanId:Kt.id,newName:Vt})},children:e.jsx(Pa,{className:"h-4 w-4"})}),e.jsx(B,{size:"sm",variant:Xs?"outline":"default",disabled:Xs||c.isPending,onClick:()=>Me(Kt.id,y),children:Xs?"Active":"Use This"})]})]},Kt.id)})]}),Be.length>0&&e.jsxs("div",{className:"space-y-2",children:[e.jsx("div",{className:"text-sm text-muted-foreground",children:"My Custom Plans"}),Be.map(Kt=>{var zs;const Xs=(Ce==null?void 0:Ce.id)===Kt.id;return e.jsxs("div",{className:` flex items-center justify-between p-3 rounded-lg border ${Xs?"opacity-50":"hover:bg-accent"} `,children:[e.jsxs("div",{children:[e.jsx("div",{className:"font-medium",children:Kt.name}),e.jsxs("div",{className:"text-sm text-muted-foreground",children:[((zs=Kt.items)==null?void 0:zs.length)||0," touchpoints/year"]})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(B,{size:"sm",variant:"ghost",title:"View plan details",onClick:()=>te(Kt.id),children:e.jsx(da,{className:"h-4 w-4"})}),e.jsx(B,{size:"sm",variant:"ghost",title:"Edit plan",onClick:()=>Xe(Kt),children:e.jsx(Ww,{className:"h-4 w-4"})}),e.jsx(B,{size:"sm",variant:"ghost",title:"Delete plan",onClick:()=>h.mutate(Kt.id),children:e.jsx(qn,{className:"h-4 w-4 text-destructive"})}),e.jsx(B,{size:"sm",variant:Xs?"outline":"default",disabled:Xs||c.isPending,onClick:()=>Me(Kt.id,y),children:Xs?"Active":"Use This"})]})]},Kt.id)})]}),Re.length===0&&Be.length===0&&e.jsx("p",{className:"text-sm text-muted-foreground text-center py-4",children:"No plans available. Create a custom plan to get started."})]})]})]}):e.jsx(_e,{children:e.jsxs(De,{className:"py-12 text-center text-muted-foreground",children:[e.jsx(ta,{className:"h-12 w-12 mx-auto mb-4 opacity-50"}),e.jsx("p",{children:"Select a contact group to view and assign plans"})]})})})]}),e.jsx(_e,{className:"bg-muted/50",children:e.jsx(De,{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(Bs,{open:_,onOpenChange:Kt=>{Kt?b(!0):Ye()},children:e.jsxs(Fs,{className:"max-w-2xl max-h-[90vh] overflow-y-auto",children:[e.jsx(qs,{children:e.jsx($s,{children:k?"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(re,{htmlFor:"plan-name",children:"Plan Name"}),e.jsx(we,{id:"plan-name",value:T,onChange:Kt=>P(Kt.target.value),placeholder:"e.g., My VIP Plan"})]}),e.jsxs("div",{children:[e.jsx(re,{htmlFor:"plan-description",children:"Description (optional)"}),e.jsx(Ws,{id:"plan-description",value:I,onChange:Kt=>M(Kt.target.value),placeholder:"Describe your plan...",rows:2})]})]}),e.jsxs("div",{children:[e.jsx(re,{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:rne.map((Kt,Xs)=>{const zs=Xs+1,Vt=L.find(Nt=>Nt.month_number===zs),At=Vt?l==null?void 0:l.find(Nt=>Nt.id===Vt.action_type_id):null,Os=At?ht(At.icon):null;return e.jsxs("div",{className:"relative",children:[e.jsxs("button",{type:"button",onClick:()=>V($===zs?null:zs),className:` w-full p-3 rounded-lg border text-center transition-all ${Vt?"bg-primary/10 border-primary":"bg-muted hover:bg-accent"} ${$===zs?"ring-2 ring-primary":""} `,children:[e.jsx("div",{className:"text-xs text-muted-foreground font-medium",children:Kt}),Os?e.jsx(Os,{className:"h-5 w-5 mx-auto mt-1",style:{color:(At==null?void 0:At.color)||"#3B82F6"}}):e.jsx(nn,{className:"h-5 w-5 mx-auto mt-1 text-muted-foreground/50"})]}),Vt&&e.jsx("button",{type:"button",onClick:Nt=>{Nt.stopPropagation(),st(zs)},className:"absolute -top-1 -right-1 p-1 bg-destructive text-destructive-foreground rounded-full",children:e.jsx(hr,{className:"h-3 w-3"})})]},Xs)})}),$!==null&&!W&&e.jsxs("div",{className:"mt-4 p-3 bg-muted rounded-lg",children:[e.jsxs("div",{className:"text-sm font-medium mb-2",children:["Step 1: Select action for ",rne[$-1],":"]}),e.jsx("div",{className:"flex flex-wrap gap-2",children:l==null?void 0:l.filter(Kt=>Kt.active).map(Kt=>{const Xs=ht(Kt.icon);return e.jsxs("button",{type:"button",onClick:()=>Je($,Kt.id),className:"flex items-center gap-2 px-3 py-2 rounded-lg border bg-background hover:bg-accent transition-colors",children:[e.jsx(Xs,{className:"h-4 w-4",style:{color:Kt.color||"#3B82F6"}}),e.jsx("span",{className:"text-sm",children:Kt.name})]},Kt.id)})})]}),$!==null&&W&&e.jsxs("div",{className:"mt-4 p-3 bg-muted rounded-lg space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("div",{className:"text-sm font-medium",children:"Step 2: Select a script (optional)"}),e.jsxs(B,{variant:"ghost",size:"sm",onClick:()=>G(null),children:[e.jsx(Fc,{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:()=>Ke($,W),className:"w-full flex items-center gap-3 p-3 rounded-lg border bg-background hover:bg-accent transition-colors text-left",children:e.jsxs("div",{className:"flex-1",children:[e.jsx("div",{className:"font-medium text-sm",children:"No Script"}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"Use without a predefined script"})]})}),Ze==null?void 0:Ze.map(Kt=>e.jsx("button",{type:"button",onClick:()=>Ke($,W,Kt.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:Kt.title}),Kt.tone&&e.jsx(We,{variant:"secondary",className:"text-xs mt-1",children:Kt.tone}),e.jsxs("div",{className:"text-xs text-muted-foreground mt-1 line-clamp-2",children:[Kt.script_body.substring(0,100),"..."]})]})},Kt.id)),e.jsxs("button",{type:"button",onClick:()=>me(!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(nn,{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"})]})]})]})]})]}),L.length>0&&e.jsxs("div",{className:"text-sm text-muted-foreground",children:[L.length," touchpoint",L.length!==1?"s":""," per year"]})]}),e.jsxs(Cr,{children:[e.jsx(B,{variant:"outline",onClick:Ye,children:"Cancel"}),e.jsxs(B,{onClick:k?Ae:Fe,disabled:!T.trim()||d.isPending||u.isPending,children:[e.jsx(Kl,{className:"h-4 w-4 mr-2"}),k?"Save Changes":"Create Plan"]})]})]})}),e.jsx(Bs,{open:ne,onOpenChange:me,children:e.jsxs(Fs,{className:"max-w-lg",children:[e.jsx(qs,{children:e.jsx($s,{children:"Create Custom Script"})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(re,{htmlFor:"script-title",children:"Script Title"}),e.jsx(we,{id:"script-title",value:ue,onChange:Kt=>ce(Kt.target.value),placeholder:"e.g., Friendly Check-in Call"})]}),e.jsxs("div",{children:[e.jsx(re,{htmlFor:"script-tone",children:"Tone (optional)"}),e.jsxs(Ns,{value:ge,onValueChange:be,children:[e.jsx(ws,{children:e.jsx(ks,{placeholder:"Select tone..."})}),e.jsxs(js,{children:[e.jsx(nt,{value:"friendly",children:"Friendly"}),e.jsx(nt,{value:"professional",children:"Professional"}),e.jsx(nt,{value:"casual",children:"Casual"}),e.jsx(nt,{value:"formal",children:"Formal"})]})]})]}),((Yt=(Ct=l==null?void 0:l.find(Kt=>Kt.id===W))==null?void 0:Ct.name)==null?void 0:Yt.toLowerCase().includes("email"))&&e.jsxs("div",{children:[e.jsx(re,{htmlFor:"script-email-subject",children:"Email Subject"}),e.jsx(we,{id:"script-email-subject",value:xe,onChange:Kt=>ve(Kt.target.value),placeholder:"e.g., Quick Hello!"})]}),e.jsxs("div",{children:[e.jsx(re,{htmlFor:"script-body",children:"Script Content"}),e.jsx(Ws,{id:"script-body",value:ae,onChange:Kt=>he(Kt.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(Cr,{children:[e.jsx(B,{variant:"outline",onClick:()=>me(!1),children:"Cancel"}),e.jsxs(B,{onClick:rt,disabled:!ue.trim()||!ae.trim()||f.isPending,children:[e.jsx(Kl,{className:"h-4 w-4 mr-2"}),"Create & Use Script"]})]})]})}),e.jsx(Bs,{open:!!X,onOpenChange:Kt=>{Kt||te(null)},children:e.jsx(Fs,{className:"max-w-3xl max-h-[90vh] overflow-y-auto",children:(()=>{const Kt=r==null?void 0:r.find(Vt=>Vt.id===X);if(!Kt)return null;const Xs=Kt.owner_user_id===(t==null?void 0:t.id),zs=[...Kt.items||[]].sort((Vt,At)=>Vt.month_number-At.month_number);return e.jsxs(e.Fragment,{children:[e.jsxs(qs,{children:[e.jsxs($s,{className:"flex items-center gap-2",children:[Kt.name,!Xs&&e.jsx(We,{variant:"secondary",children:"Template"})]}),Kt.description&&e.jsx("p",{className:"text-sm text-muted-foreground",children:Kt.description})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"text-sm text-muted-foreground",children:[zs.length," touchpoint",zs.length!==1?"s":""," per year"]}),e.jsx("div",{className:"space-y-2",children:Array.from({length:12},(Vt,At)=>At+1).map(Vt=>{const At=zs.find(Ys=>Ys.month_number===Vt),Os=At?l==null?void 0:l.find(Ys=>Ys.id===At.action_type_id):null,Nt=At!=null&&At.default_script_id?o==null?void 0:o.find(Ys=>Ys.id===At.default_script_id):null,ms=Os?ht(Os.icon):null;return e.jsxs("div",{className:`p-3 rounded-lg border flex items-start gap-3 ${At?"bg-muted/30":"opacity-60"}`,children:[e.jsx("div",{className:"w-16 shrink-0 font-medium text-sm",children:rne[Vt-1]}),At&&Os?e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[ms&&e.jsx(ms,{className:"h-4 w-4",style:{color:Os.color||"#3B82F6"}}),e.jsx("span",{className:"font-medium text-sm",children:Os.name}),Nt&&e.jsx(We,{variant:"outline",className:"text-xs",children:Nt.title})]}),Nt&&e.jsx("div",{className:"mt-2 text-sm text-muted-foreground whitespace-pre-wrap bg-background p-2 rounded border",children:Nt.script_body}),At.notes&&e.jsx("div",{className:"mt-1 text-xs text-muted-foreground italic",children:At.notes})]}):e.jsx("div",{className:"flex-1 text-sm text-muted-foreground",children:"No touchpoint scheduled"})]},Vt)})})]}),e.jsxs(Cr,{children:[e.jsx(B,{variant:"outline",onClick:()=>te(null),children:"Close"}),Xs?e.jsxs(B,{onClick:()=>{const Vt=r==null?void 0:r.find(At=>At.id===X);Vt&&(te(null),Xe(Vt))},children:[e.jsx(Ww,{className:"h-4 w-4 mr-2"}),"Edit Plan"]}):e.jsxs(B,{disabled:g.isPending,onClick:()=>{g.mutate({sourcePlanId:Kt.id,newName:`${Kt.name} (Copy)`}),te(null)},children:[e.jsx(Pa,{className:"h-4 w-4 mr-2"}),"Duplicate to Edit"]})]})]})})()})})]})}const XLe="https://cma.relevelup.com";function kIt({open:s,onOpenChange:t,cma:n}){var te;const{user:r}=Ls(),{toast:a}=Ci(),[i,l]=N.useState([]),[o,c]=N.useState(null),[d,u]=N.useState(!1),[h,m]=N.useState(""),[f,g]=N.useState(""),[y,x]=N.useState(""),[_,b]=N.useState(!1),[k,A]=N.useState(null),[T,P]=N.useState(!1),[I,M]=N.useState(!1),[L,z]=N.useState(null);N.useEffect(()=>{!s||!r||(async()=>{var ve;const[ne,me,ue,ce,ae]=await Promise.all([H.from("innercircle_contacts").select("id, first_name, last_name, email").eq("owner_user_id",r.id).not("email","is",null).order("first_name"),H.from("profiles").select("name, email, phone, brokerage_name, avatar_url, email_signature").eq("id",r.id).maybeSingle(),H.from("gmail_integrations").select("id, is_active").eq("user_id",r.id).maybeSingle(),H.from("ses_verified_emails").select("email, status").eq("user_id",r.id).eq("status","Success").limit(1),H.from("mass_email_settings").select("*").eq("user_id",r.id).maybeSingle()]),he=(ne.data||[]).filter(ge=>ge.email&&ge.email.includes("@"));l(he),A(me.data||null),P(!!((ve=ue.data)!=null&&ve.is_active)),M(!!(ce.data&&ce.data.length>0)),z(ae.data||null);const xe=n.contact_id?he.find(ge=>ge.id===n.contact_id):null;xe&&(c(xe),m(xe.email))})()},[s,r,n.contact_id]),N.useEffect(()=>{var ce;if(!s)return;const ne=((ce=n.subject)==null?void 0:ce.address)||"your home",me=((k==null?void 0:k.name)||"").split(" ")[0]||"your agent",ue=(o==null?void 0:o.first_name)||"there";g(`Your home value report for ${ne}`),x(`Hi ${ue}, I put together a fresh market analysis for ${ne}. 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, ${(k==null?void 0:k.name)||me}`)},[s,o==null?void 0:o.id,k==null?void 0:k.name,(te=n.subject)==null?void 0:te.address]);const $=N.useMemo(()=>T?"Gmail (your inbox)":I?"Amazon SES":null,[T,I]),V=!!(h.trim()&&f.trim()&&y.trim()&&$&&!_),W=ne=>{c(ne),m(ne.email||""),u(!1)},G=ne=>{const me=`${XLe}/${n.share_token}?e=${ne}`,ae=y.replace(/&/g,"&").replace(//g,">").replace(/\{\{cma_link\}\}/g,`View Your Home Value Report`).split(/\n{2,}/).map(ve=>`

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

`).join(""),he=k!=null&&k.use_email_signature&&(k!=null&&k.email_signature)?`
${k.email_signature}
`:`
${k!=null&&k.name?`
${k.name}
`:""} ${k!=null&&k.brokerage_name?`
${k.brokerage_name}
`:""} ${k!=null&&k.phone?`
${k.phone}
`:""} ${k!=null&&k.email?``:""}
`,xe=``;return`
${ae} ${he}
Prepared with LevelUp · ReLevelUp Real Estate
${xe}
`},X=async()=>{if(!(!r||!V)){b(!0);try{const{data:ne,error:me}=await H.from("cma_email_sends").insert({cma_id:n.id,agent_id:r.id,contact_id:(o==null?void 0:o.id)??null,recipient_email:h.trim(),subject:f.trim(),sent_via:T?"gmail":"ses"}).select("id").single();if(me)throw me;const ue=G(ne.id);if(T){const{data:ce,error:ae}=await H.functions.invoke("gmail-send",{body:{to:h.trim(),subject:f.trim(),body:ue}});if(ae)throw ae;if(!(ce!=null&&ce.success))throw new Error((ce==null?void 0:ce.error)||"Gmail send failed")}else if(I){const ce=(L==null?void 0:L.display_name)||(k==null?void 0:k.name)||"ReLevelUp",ae=`${ce.toLowerCase().replace(/[^a-z]/g,".").replace(/^\.+|\.+$/g,"")||"noreply"}@send.relevelup.com`,{data:he,error:xe}=await H.functions.invoke("ses-send-campaign",{body:{action:"test_send",to:h.trim(),from_email:`${ce} <${ae}>`,subject:f.trim(),body_html:ue,reply_to:(L==null?void 0:L.reply_to_email)||(k==null?void 0:k.email)||void 0}});if(xe)throw xe;if(!(he!=null&&he.success))throw new Error((he==null?void 0:he.error)||"SES send failed")}o&&!n.contact_id&&await H.from("cmas").update({contact_id:o.id}).eq("id",n.id),a({title:"CMA sent",description:`Delivered to ${h.trim()}`}),t(!1)}catch(ne){console.error("Send CMA error:",ne),a({title:"Send failed",description:ne.message||"Could not send email",variant:"destructive"})}finally{b(!1)}}};return e.jsx(Bs,{open:s,onOpenChange:t,children:e.jsxs(Fs,{className:"max-w-2xl max-h-[90vh] overflow-y-auto",children:[e.jsx(qs,{children:e.jsxs($s,{className:"flex items-center gap-2",children:[e.jsx(mn,{className:"w-5 h-5"}),"Send CMA to contact"]})}),$?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:$})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{children:"Contact"}),e.jsxs(rc,{open:d,onOpenChange:u,children:[e.jsx(ac,{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(sb,{className:"w-4 h-4 opacity-50"})]})}),e.jsx(Zl,{className:"w-[--radix-popover-trigger-width] p-0",align:"start",children:e.jsxs(db,{children:[e.jsx(ub,{placeholder:"Search contacts…"}),e.jsxs(hb,{children:[e.jsx(mb,{children:"No contacts with email found."}),e.jsx(pb,{children:i.map(ne=>e.jsxs(Ry,{value:`${ne.first_name} ${ne.last_name||""} ${ne.email}`,onSelect:()=>W(ne),children:[e.jsx(pa,{className:Ot("w-4 h-4 mr-2",(o==null?void 0:o.id)===ne.id?"opacity-100":"opacity-0")}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"font-medium",children:[ne.first_name," ",ne.last_name||""]}),e.jsx("div",{className:"text-xs text-muted-foreground truncate",children:ne.email})]})]},ne.id))})]})]})})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{children:"To email"}),e.jsx(we,{type:"email",value:h,onChange:ne=>m(ne.target.value),placeholder:"client@example.com"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{children:"Subject"}),e.jsx(we,{value:f,onChange:ne=>g(ne.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{children:"Message"}),e.jsx(Ws,{rows:10,value:y,onChange:ne=>x(ne.target.value)}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[e.jsx("code",{children:"{{cma_link}}"})," will be replaced with a styled button linking to ",e.jsxs("code",{children:["cma.relevelup.com/",n.share_token]}),". Email opens are tracked and shown on the contact's Signals."]})]}),e.jsxs("div",{className:"rounded border bg-muted/40 p-3 text-sm flex items-center gap-2",children:[e.jsx(Tr,{className:"w-4 h-4 text-muted-foreground"}),e.jsx("span",{className:"text-muted-foreground",children:"Public link:"}),e.jsx("a",{className:"text-primary underline truncate",href:`${XLe}/${n.share_token}`,target:"_blank",rel:"noreferrer",children:`${XLe}/${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(Cr,{children:[e.jsx(B,{variant:"ghost",onClick:()=>t(!1),children:"Cancel"}),e.jsxs(B,{onClick:X,disabled:!V,children:[_?e.jsx(us,{className:"w-4 h-4 mr-2 animate-spin"}):e.jsx(Rr,{className:"w-4 h-4 mr-2"}),"Send CMA"]})]})]})})}function Sfn({onCreated:s}){const[t,n]=N.useState(!1),[r,a]=N.useState(""),[i,l]=N.useState(""),[o,c]=N.useState(""),[d,u]=N.useState(""),h=Wpn(),m=vIt(),{toast:f}=Ci(),[g,y]=N.useState([]),x=async()=>{var k;y([]);try{const A=await h.mutateAsync({address:r,city:i,state:o,zip:d});y(A.matches||[]),(k=A.matches)!=null&&k.length||f({title:"No MLS match",description:'Use "Create from manual entry" below.'})}catch(A){f({title:"Search failed",description:A.message,variant:"destructive"})}},_=async k=>{const A=await m.mutateAsync({subject:k});n(!1),s(A.id)},b=async()=>{if(!r||!i||!o){f({title:"Address, city, state required"});return}const k=await m.mutateAsync({subject:{address:r,city:i,state:o,zip:d}});n(!1),s(k.id)};return e.jsxs(Bs,{open:t,onOpenChange:n,children:[e.jsx(Ao,{asChild:!0,children:e.jsxs(B,{children:[e.jsx(nn,{className:"w-4 h-4 mr-2"}),"New CMA"]})}),e.jsxs(Fs,{className:"max-w-2xl",children:[e.jsx(qs,{children:e.jsx($s,{children:"Start a CMA"})}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-4 gap-2",children:[e.jsx(we,{className:"md:col-span-2",placeholder:"Street address",value:r,onChange:k=>a(k.target.value)}),e.jsx(we,{placeholder:"City",value:i,onChange:k=>l(k.target.value)}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(we,{placeholder:"ST",maxLength:2,value:o,onChange:k=>c(k.target.value.toUpperCase())}),e.jsx(we,{placeholder:"ZIP",value:d,onChange:k=>u(k.target.value)})]})]}),e.jsxs(B,{onClick:x,disabled:!r||h.isPending,className:"w-full",children:[h.isPending?e.jsx(us,{className:"w-4 h-4 mr-2 animate-spin"}):e.jsx(Gr,{className:"w-4 h-4 mr-2"}),"Find in MLS"]}),g.length>0&&e.jsxs("div",{className:"space-y-2 max-h-80 overflow-y-auto",children:[e.jsxs("p",{className:"text-sm text-muted-foreground",children:[g.length," match(es) — pick the subject property:"]}),g.map((k,A)=>{var T;return e.jsxs("button",{onClick:()=>_(k),className:"w-full text-left p-3 border rounded hover:bg-accent transition",children:[e.jsx("div",{className:"font-medium",children:k.address}),e.jsxs("div",{className:"text-xs text-muted-foreground",children:[k.city,", ",k.state," ",k.zip," · ",k.bedrooms??"?"," bd / ",k.bathrooms??"?"," ba · ",((T=k.sqft)==null?void 0:T.toLocaleString())??"?"," sqft",k.mlsNumber?` · MLS# ${k.mlsNumber}`:""," · ",k.source_provider]})]},A)})]}),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(_a,{className:"w-4 h-4 mr-2"}),"Create from manual entry"]})})]})]})]})}function Cfn(){const{data:s,isLoading:t}=Upn(),n=Gpn(),r=tr(),{toast:a}=Ci(),[i,l]=N.useState(null);return e.jsx(Qs,{children:e.jsxs("div",{className:"container mx-auto p-4 md:p-6 max-w-6xl",children:[e.jsxs("div",{className:"flex items-center justify-between mb-6",children:[e.jsxs("div",{children:[e.jsxs("h1",{className:"text-2xl md:text-3xl font-bold flex items-center gap-2",children:[e.jsx(Wr,{className:"w-7 h-7"})," CMAs"]}),e.jsx("p",{className:"text-muted-foreground text-sm",children:"Comparative Market Analyses — interactive, shareable, no static PDFs."})]}),e.jsx(Sfn,{onCreated:o=>r(`/mission-control/cma/${o}`)})]}),t?e.jsx("p",{className:"text-muted-foreground",children:"Loading…"}):s!=null&&s.length?e.jsx("div",{className:"grid gap-3",children:s.map(o=>{var c,d,u;return e.jsx(_e,{className:"hover:shadow-md transition",children:e.jsxs(De,{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:o.title||((c=o.subject)==null?void 0:c.address)||"Untitled CMA"}),e.jsxs("div",{className:"text-xs text-muted-foreground",children:[(d=o.subject)==null?void 0:d.city,", ",(u=o.subject)==null?void 0:u.state," · ",o.buyer_mode?"Buyer":"Seller"," ·"," ",e.jsx(We,{variant:o.status==="shared"?"default":"secondary",className:"ml-1",children:o.status})]}),o.price_likely?e.jsxs("div",{className:"text-sm mt-1",children:["Suggested: ",e.jsxs("span",{className:"font-medium",children:["$",o.price_likely.toLocaleString()]}),o.price_low&&o.price_high?e.jsxs("span",{className:"text-muted-foreground",children:[" · $",o.price_low.toLocaleString(),"–$",o.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/${o.id}`),children:"Open"}),o.status==="shared"&&e.jsxs(e.Fragment,{children:[e.jsx(B,{variant:"ghost",size:"sm",onClick:()=>{const h=`https://cma.relevelup.com/${o.share_token}`;navigator.clipboard.writeText(h),a({title:"Share link copied"})},children:e.jsx(Tr,{className:"w-4 h-4"})}),e.jsxs(B,{variant:"secondary",size:"sm",onClick:()=>l(o),children:[e.jsx(mn,{className:"w-4 h-4 mr-1"}),"Send"]})]}),e.jsx(B,{variant:"ghost",size:"sm",onClick:()=>{confirm("Delete this CMA?")&&n.mutate(o.id)},children:e.jsx(qn,{className:"w-4 h-4"})})]})]})},o.id)})}):e.jsx(_e,{children:e.jsx(De,{className:"py-12 text-center text-muted-foreground",children:"No CMAs yet. Start one above."})}),i&&e.jsx(kIt,{open:!!i,onOpenChange:o=>!o&&l(null),cma:i})]})})}function Afn(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 kht(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 Tfn({subject:s,comps:t,radiusMiles:n,onMarkerClick:r}){const a=N.useRef(null),i=N.useRef(null),l=N.useRef([]),[o,c]=N.useState(null);N.useEffect(()=>{let u=!1;return(async()=>{const{data:h}=await H.from("settings").select("value").eq("key","mapbox_public_token").maybeSingle();!u&&(h!=null&&h.value)&&c(h.value)})(),()=>{u=!0}},[]);const d=N.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 N.useEffect(()=>{if(!o||!a.current||i.current||!d)return;Rc.accessToken=o;const u=new Rc.Map({container:a.current,style:"mapbox://styles/mapbox/light-v11",center:[d.lng,d.lat],zoom:12});return u.addControl(new Rc.NavigationControl({showCompass:!1}),"top-right"),u.on("load",()=>{u.addSource("radius",{type:"geojson",data:kht(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]),N.useEffect(()=>{const u=i.current;if(!u||!d)return;const h=()=>{const m=u.getSource("radius");m&&m.setData(kht(d.lat,d.lng,n))};u.isStyleLoaded()?h():u.once("load",h)},[n,d]),N.useEffect(()=>{const u=i.current;if(!u||!d)return;l.current.forEach(x=>x.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 Rc.Marker({element:h}).setLngLat([d.lng,d.lat]).setPopup(new Rc.Popup({offset:18}).setHTML(`Subject
${s.address??""}`)).addTo(u);l.current.push(m);const f=new Rc.LngLatBounds;f.extend([d.lng,d.lat]),t.forEach((x,_)=>{const b=Number(x.latitude),k=Number(x.longitude);if(!Number.isFinite(b)||!Number.isFinite(k))return;const A=Afn(x.status),T=document.createElement("div");T.style.cssText="width:22px;height:22px;";const P=document.createElement("div");P.style.cssText=` width: 22px; height: 22px; border-radius: 50%; background: ${A}; border: 2px solid white; box-shadow: 0 2px 6px rgba(0,0,0,0.25); cursor: pointer; opacity: ${x.selected===!1?.4:1}; transition: transform 0.15s; transform-origin: center; `,P.onmouseenter=()=>{P.style.transform="scale(1.25)"},P.onmouseleave=()=>{P.style.transform="scale(1)"},r&&(P.onclick=()=>r(_)),T.appendChild(P);const I=x.soldPrice||x.price,M=new Rc.Popup({offset:14}).setHTML(`
${x.address??""}
${x.status??""}`+(I?` · $${I.toLocaleString()}`:"")+"
"),L=new Rc.Marker({element:T}).setLngLat([k,b]).setPopup(M).addTo(u);l.current.push(L),f.extend([k,b])});const y=n*1.60934/110.574;f.extend([d.lng,d.lat+y]),f.extend([d.lng,d.lat-y]);try{u.fitBounds(f,{padding:60,maxZoom:14,duration:600})}catch{}},[t,d,n,s.address,r]),d?e.jsxs("div",{className:"relative w-full h-[420px] rounded-xl overflow-hidden border shadow-sm",children:[e.jsx("div",{ref:a,className:"absolute inset-0"}),!o&&e.jsx("div",{className:"absolute inset-0 flex items-center justify-center bg-muted/40 text-sm text-muted-foreground",children:"Loading map…"}),e.jsxs("div",{className:"absolute bottom-3 left-3 bg-background/95 backdrop-blur rounded-lg shadow-md border px-3 py-2 text-xs space-y-1",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"inline-block w-3 h-3 rounded-full",style:{background:"hsl(222 47% 11%)"}}),"Subject"]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"inline-block w-3 h-3 rounded-full",style:{background:"#2563eb"}}),"Active"]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"inline-block w-3 h-3 rounded-full",style:{background:"#f59e0b"}}),"Pending"]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"inline-block w-3 h-3 rounded-full",style:{background:"#16a34a"}}),"Closed"]})]})]}):e.jsx("div",{className:"w-full h-[420px] rounded-xl border bg-muted/30 flex items-center justify-center text-sm text-muted-foreground",children:"Subject property has no coordinates — map unavailable."})}let T1=null;function Efn(){if(T1)return T1;try{const s=document.createElement("canvas"),t=s.getContext("webgl2")||s.getContext("webgl");if(!t)return T1={canRunVirtualBg:!1,reason:"WebGL is not supported on this device"},T1;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 T1={canRunVirtualBg:!1,reason:"Your device uses a software renderer which may cause lag",renderer:r},T1;const o=performance;return o.memory&&o.memory.jsHeapSizeLimit<256*1024*1024?(T1={canRunVirtualBg:!1,reason:"Limited device memory detected",renderer:r},T1):navigator.hardwareConcurrency&&navigator.hardwareConcurrency<2?(T1={canRunVirtualBg:!1,reason:"Single-core device detected — virtual backgrounds may cause lag",renderer:r},T1):(T1={canRunVirtualBg:!0,renderer:r},T1)}catch{return T1={canRunVirtualBg:!0},T1}}const Mfn=[{type:"none",label:"Off"},{type:"blur",label:"Blur"}];function Lfn({value:s,onChange:t,isLoading:n=!1,disabled:r=!1,className:a}){const i=N.useRef(null),[l,o]=N.useState(!1),[c]=N.useState(()=>Efn()),d=!c.canRunVirtualBg,{data:u=[],refetch:h}=mt({queryKey:["video-backgrounds"],queryFn:async()=>{const{data:{user:x}}=await H.auth.getUser();if(!x)return[];const{data:_,error:b}=await H.from("video_backgrounds").select("*").eq("is_active",!0).order("sort_order",{ascending:!0});return b?(console.error("Failed to load backgrounds:",b),[]):_||[]}}),m=u.map(x=>({type:"image",label:x.name,imageUrl:x.image_url,thumbnail:x.thumbnail_url||x.image_url})),f=[...Mfn,...m],g=x=>x.type!==s.type?!1:x.type==="image"?x.imageUrl===s.imageUrl:!0,y=async x=>{var b;const _=(b=x.target.files)==null?void 0:b[0];if(_){if(!_.type.startsWith("image/")){ie.error("Please select an image file");return}if(_.size>5*1024*1024){ie.error("Image must be under 5MB");return}o(!0);try{const{data:{user:k}}=await H.auth.getUser();if(!k)throw new Error("Not authenticated");const A=_.name.split(".").pop()||"jpg",T=`${k.id}/${crypto.randomUUID()}.${A}`,{error:P}=await H.storage.from("video-backgrounds").upload(T,_,{contentType:_.type});if(P)throw P;const{data:I}=H.storage.from("video-backgrounds").getPublicUrl(T),M=I.publicUrl,{error:L}=await H.from("video_backgrounds").insert({name:_.name.replace(/\.[^.]+$/,""),image_url:M,thumbnail_url:M,category:"custom",is_stock:!1,user_id:k.id});if(L)throw L;await h(),t({type:"image",imageUrl:M,blurRadius:15}),ie.success("Background uploaded!")}catch(k){console.error("Upload error:",k),ie.error("Failed to upload background")}finally{o(!1),i.current&&(i.current.value="")}}};return e.jsxs("div",{className:Ot("flex flex-col gap-1",a),children:[d&&e.jsxs("div",{className:"flex items-center gap-1.5 text-xs text-amber-600 bg-amber-50 dark:bg-amber-950/30 dark:text-amber-400 rounded px-2 py-1",children:[e.jsx(xd,{className:"h-3 w-3 flex-shrink-0"}),e.jsx("span",{children:c.reason||"Virtual backgrounds may cause lag on this device"})]}),e.jsxs("div",{className:"flex items-center gap-2 overflow-x-auto py-2 px-1 scrollbar-none",children:[e.jsx("span",{className:"text-xs text-muted-foreground whitespace-nowrap mr-1 font-medium",children:"Background:"}),n&&e.jsxs("div",{className:"flex items-center gap-1 text-xs text-muted-foreground",children:[e.jsx(us,{className:"h-3 w-3 animate-spin"}),e.jsx("span",{children:"Loading…"})]}),f.map((x,_)=>{const b=g(x);return e.jsxs("button",{type:"button",disabled:r,onClick:()=>t({type:x.type,imageUrl:x.imageUrl,blurRadius:15}),className:Ot("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",b?"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:[x.type==="none"&&e.jsx(o9,{className:"h-4 w-4 text-muted-foreground"}),x.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"})}),x.type==="image"&&x.thumbnail&&e.jsx("img",{src:x.thumbnail,alt:x.label,className:"w-full h-full object-cover"})]}),e.jsx("span",{className:"text-[10px] text-muted-foreground truncate max-w-14",children:x.label})]},`${x.type}-${x.imageUrl||_}`)}),e.jsxs("button",{type:"button",disabled:r||l,onClick:()=>{var x;return(x=i.current)==null?void 0:x.click()},className:Ot("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(us,{className:"h-4 w-4 animate-spin text-muted-foreground"}):e.jsx(nn,{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:y}),e.jsxs("button",{type:"button",disabled:r,onClick:()=>t({...s,mirror:!s.mirror}),className:Ot("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(YG,{className:"h-4 w-4 text-muted-foreground"})}),e.jsx("span",{className:"text-[10px] text-muted-foreground",children:"Mirror"})]})]})]})}var N$=typeof self<"u"?self:{};function SIt(s,t){e:{for(var n=["CLOSURE_FLAGS"],r=N$,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 AIt(s){N$.setTimeout(()=>{throw s},0)}var c7e,Rfn=SIt(610401301,!1),Cht=SIt(748402147,!0);function Aht(){var s=N$.navigator;return s&&(s=s.userAgent)?s:""}const Tht=N$.navigator;function HCe(s){return HCe[" "](s),s}c7e=Tht&&Tht.userAgentData||null,HCe[" "]=function(){};const TIt={};let tG=null;function Ofn(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 EIt(){if(!tG){tG={};var s="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789".split(""),t=["+/=","+/","-_=","-_.","-_"];for(let n=0;n<5;n++){const r=s.concat(t[n].split(""));TIt[n]=r;for(let a=0;a0)&&(Aht().indexOf("Trident")!=-1||Aht().indexOf("MSIE")!=-1))&&typeof btoa=="function";const Eht=/[-_.]/g,zfn={"-":"+",_:"/",".":"="};function Bfn(s){return zfn[s]||""}function LIt(s){if(!MIt)return Ofn(s);s=Eht.test(s)?s.replace(Eht,Bfn):s,s=atob(s);const t=new Uint8Array(s.length);for(let n=0;n=t||(n[s]=r+1,IIt(s=Error(),"incident"),AIt(s))}}function HU(){return typeof BigInt=="function"}var GU=typeof Symbol=="function"&&typeof Symbol()=="symbol";function X5(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 qfn=X5("jas",void 0,!0),Mht=X5(void 0,"0di"),rH=X5(void 0,"1oa"),O_=X5(void 0,Symbol()),Vfn=X5(void 0,"0ub"),Hfn=X5(void 0,"0ubs"),u7e=X5(void 0,"0ubsb"),Gfn=X5(void 0,"0actk"),C$=X5("m_m","Pa",!0),Lht=X5();const DIt={Ga:{value:0,configurable:!0,writable:!0,enumerable:!1}},RIt=Object.defineProperties,yo=GU?qfn:"Ga";var rO;const Pht=[];function fJ(s,t){GU||yo in s||RIt(s,DIt),s[yo]|=t}function cx(s,t){GU||yo in s||RIt(s,DIt),s[yo]=t}function gJ(s){return fJ(s,34),s}function _Z(s){return fJ(s,8192),s}cx(Pht,7),rO=Object.freeze(Pht);var A$={};function U_(s,t){return t===void 0?s.h!==bR&&!!(2&(0|s.v[yo])):!!(2&t)&&s.h!==bR}const bR={};function gGe(s,t){if(s!=null){if(typeof s=="string")s=s?new N5(s,k$):vR();else if(s.constructor!==N5)if(pGe(s))s=s.length?new N5(new Uint8Array(s),k$):vR();else{if(!t)throw Error();s=void 0}}return s}let Iht=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 Wfn=Object.freeze({});function OIt(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"),Dht=GCe(s=>typeof s=="string"),Yfn=GCe(s=>typeof s=="boolean"),WCe=typeof N$.BigInt=="function"&&typeof N$.BigInt(0)=="bigint";function F_(s){var t=s;if(Dht(t)){if(!/^\s*(?:-?[1-9]\d*|0)?\s*$/.test(t))throw Error(String(t))}else if(Kfn(t)&&!Number.isSafeInteger(t))throw Error(String(t));return WCe?BigInt(s):s=Yfn(s)?s?"1":"0":Dht(s)?s.trim()||"0":String(s)}var h7e=GCe(s=>WCe?s>=Xfn&&s<=Jfn:s[0]==="-"?Rht(s,Zfn):Rht(s,Qfn));const Zfn=Number.MIN_SAFE_INTEGER.toString(),Xfn=WCe?BigInt(Number.MIN_SAFE_INTEGER):void 0,Qfn=Number.MAX_SAFE_INTEGER.toString(),Jfn=WCe?BigInt(Number.MAX_SAFE_INTEGER):void 0;function Rht(s,t){if(s.length>t.length)return!1;if(s.lengtha)return!1;if(r>>0;vp=t,ug=(s-t)/4294967296>>>0}function T$(s){if(s<0){Oht(-s);const[t,n]=vGe(vp,ug);vp=t>>>0,ug=n>>>0}else Oht(s)}function xGe(s){const t=tgn||(tgn=new DataView(new ArrayBuffer(8)));t.setFloat32(0,+s,!0),ug=0,vp=t.getUint32(0,!0)}function zIt(s,t){const n=4294967296*t+(s>>>0);return Number.isSafeInteger(n)?n:wZ(s,t)}function sgn(s,t){return F_(HU()?BigInt.asUintN(64,(BigInt(t>>>0)<>>0)):wZ(s,t))}function BIt(s,t){return HU()?F_(BigInt.asIntN(64,(BigInt.asUintN(32,BigInt(t))<>>=0,(t>>>=0)<=2097151)var n=""+(4294967296*t+s);else HU()?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+Fht(n)+Fht(s));return n}function Fht(s){return s=String(s),"0000000".slice(s.length)+s}function yGe(s,t){if(2147483648&t)if(HU())s=""+(BigInt(0|t)<>>0));else{const[n,r]=vGe(s,t);s="-"+wZ(n,r)}else s=wZ(s,t);return s}function KCe(s){if(s.length<16)T$(Number(s));else if(HU())s=BigInt(s),vp=Number(s&BigInt(4294967295))>>>0,ug=Number(s>>BigInt(32)&BigInt(4294967295));else{const t=+(s[0]==="-");ug=vp=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));ug*=1e6,vp=1e6*vp+i,vp>=4294967296&&(ug+=Math.trunc(vp/4294967296),ug>>>=0,vp>>>=0)}if(t){const[r,a]=vGe(vp,ug);vp=r,ug=a}}}function vGe(s,t){return t=~t,s?s=1+~s:t+=1,[s,t]}function oN(s){return Array.prototype.slice.call(s)}const xJ=typeof BigInt=="function"?BigInt.asIntN:void 0,ngn=typeof BigInt=="function"?BigInt.asUintN:void 0,_R=Number.isSafeInteger,YCe=Number.isFinite,E$=Math.trunc,rgn=F_(0);function sG(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 s5(s){return s==null||typeof s=="number"?s:s==="NaN"||s==="Infinity"||s==="-Infinity"?Number(s):void 0}function jZ(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 $It(s){return s==null||typeof s=="boolean"?s:typeof s=="number"?!!s:void 0}const agn=/^-?([1-9][0-9]*|0)(\.[0-9]+)?$/;function yJ(s){switch(typeof s){case"bigint":return!0;case"number":return YCe(s);case"string":return agn.test(s);default:return!1}}function KU(s){if(s==null)return s;if(typeof s=="string"&&s)s=+s;else if(typeof s!="number")return;return YCe(s)?0|s:void 0}function UIt(s){if(s==null)return s;if(typeof s=="string"&&s)s=+s;else if(typeof s!="number")return;return YCe(s)?s>>>0:void 0}function qIt(s){const t=s.length;return(s[0]==="-"?t<20||t===20&&s<="-9223372036854775808":t<19||t===19&&s<="9223372036854775807")?s:(KCe(s),yGe(vp,ug))}function bGe(s){if(s=E$(s),!_R(s)){T$(s);var t=vp,n=ug;(s=2147483648&n)&&(n=~n>>>0,(t=1+~t>>>0)==0&&(n=n+1>>>0)),s=typeof(t=zIt(t,n))=="number"?s?-t:t:s?"-"+t:t}return s}function VIt(s){var t=E$(Number(s));return _R(t)?String(t):((t=s.indexOf("."))!==-1&&(s=s.substring(0,t)),qIt(s))}function HIt(s){var t=E$(Number(s));return _R(t)?F_(t):((t=s.indexOf("."))!==-1&&(s=s.substring(0,t)),HU()?F_(xJ(64,BigInt(s))):F_(qIt(s)))}function GIt(s){return _R(s)?s=F_(bGe(s)):(s=E$(s),_R(s)?s=String(s):(T$(s),s=yGe(vp,ug)),s=F_(s)),s}function v5e(s){const t=typeof s;return s==null?s:t==="bigint"?F_(xJ(64,s)):yJ(s)?t==="string"?HIt(s):GIt(s):void 0}function WIt(s){if(typeof s!="string")throw Error();return s}function vJ(s){if(s!=null&&typeof s!="string")throw Error();return s}function Z0(s){return s==null||typeof s=="string"?s:void 0}function _Ge(s,t,n,r){return s!=null&&s[C$]===A$?s:Array.isArray(s)?((r=(n=0|s[yo])|32&r|2&r)!==n&&cx(s,r),new t(s)):(n?2&r?((s=t[Mht])||(gJ((s=new t).v),s=t[Mht]=s),t=s):t=new t:t=void 0,t)}function ign(s,t,n){if(t)e:{if(!yJ(t=s))throw d7e("int64");switch(typeof t){case"string":t=HIt(t);break e;case"bigint":t=F_(xJ(64,t));break e;default:t=GIt(t)}}else t=v5e(s);return(s=t)==null?n?rgn:void 0:s}const ogn={};let lgn=function(){try{return HCe(new class extends Map{constructor(){super()}}),!1}catch{return!0}}(),JLe=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 cgn=lgn?(Object.setPrototypeOf(JLe.prototype,Map.prototype),Object.defineProperties(JLe.prototype,{size:{value:0,configurable:!0,enumerable:!0,writable:!0}}),JLe):class extends Map{constructor(){super()}};function zht(s){return s}function ePe(s){if(2&s.J)throw Error("Cannot mutate an immutable Map")}var E3=class extends cgn{constructor(s,t,n=zht,r=zht){super(),this.J=0|s[yo],this.K=t,this.S=n,this.fa=this.K?dgn:r;for(let a=0;a{s.call(t,a.get(r),r,a)}):super.forEach(s,t)}set(s,t){return ePe(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 dgn(s,t,n,r,a,i){return s=_Ge(s,r,n,i),a&&(s=jGe(s)),s}function ugn(s){return[s,this.get(s)]}let hgn;function Bht(){return hgn||(hgn=new E3(gJ([]),void 0,void 0,void 0,ogn))}function ZCe(s){return O_?s[O_]:void 0}function b5e(s,t){for(const n in s)!isNaN(n)&&t(s,+n,s[n])}E3.prototype.toJSON=void 0;var m7e=class{};const mgn={Ka:!0};function pgn(s,t){t<100||S$(Hfn,1)}function XCe(s,t,n,r){const a=r!==void 0;r=!!r;var i,l=O_;!a&&GU&&l&&(i=s[l])&&b5e(i,pgn),l=[];var o=s.length;let c;i=4294967295;let d=!1;const u=!!(64&t),h=u?128&t?0:-1:void 0;1&t||(c=o&&s[o-1],c!=null&&typeof c=="object"&&c.constructor===Object?i=--o:c=void 0,!u||128&t||a||(d=!0,i=i-h+h)),t=void 0;for(var m=0;m=i){const g=m-h;(t??(t={}))[g]=f}else l[m]=f}if(c)for(let f in c){if((o=c[f])==null||(o=n(o,r))==null)continue;let g;m=+f,u&&!Number.isNaN(m)&&(g=m+h){g[x]=oN(_)}),g.da=f.da,g}(s)),l}function fgn(s){return s[0]=NZ(s[0]),s[1]=NZ(s[1]),s}function NZ(s){switch(typeof s){case"number":return Number.isFinite(s)?s:""+s;case"bigint":return h7e(s)?Number(s):""+s;case"boolean":return s?1:0;case"object":if(Array.isArray(s)){var t=0|s[yo];return s.length===0&&1&t?void 0:XCe(s,t,NZ)}if(s!=null&&s[C$]===A$)return KIt(s);if(s instanceof N5){if((t=s.g)==null)s="";else if(typeof t=="string")s=t;else{if(MIt){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 E3?s=s.size!==0?s.V(fgn):void 0:void 0}return s}let ggn,xgn;function KIt(s){return XCe(s=s.v,0|s[yo],NZ)}function OD(s,t){return YIt(s,t[0],t[1])}function YIt(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[yo],Cht&&1&a)throw Error("rfarr");if(2048&a&&!(2&a)&&function(){if(Cht)throw Error("carr");S$(Gfn,5)}(),256&a)throw Error("farr");if(64&a)return(a|r)!==a&&cx(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 cx(s,64|a|r),s}function ygn(s,t){if(typeof s!="object")return s;if(Array.isArray(s)){var n=0|s[yo];return s.length===0&&1&n?void 0:$ht(s,n,t)}if(s!=null&&s[C$]===A$)return Uht(s);if(s instanceof E3){if(2&(t=s.J))return s;if(!s.size)return;if(n=gJ(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 sh(s,t,n,r){XU(s),ix(s=s.v,0|s[yo],t,n,r)}function ix(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[yo]))>>14&1023||536870912)?r!=null&&(s[l+(a?0:-1)]={[n]:r}):s[i]=r),t)}function UI(){return Wfn===void 0?2:4}function qI(s,t,n,r,a){let i=s.v,l=0|i[yo];r=U_(s,l)?1:r,a=!!a||r===3,r===2&&ZU(s)&&(i=s.v,l=0|i[yo]);let o=(s=kGe(i,t))===rO?7:0|s[yo],c=SGe(o,l);var d=!(4&c);if(d){4&c&&(s=oN(s),o=0,c=zD(c,l),l=ix(i,l,t,s));let u=0,h=0;for(;u{const o=_Ge(l,n,!1,t);return i=o!==l&&o!=null,o}))!=null)return i&&!U_(r)&&aO(s,t),r}function $d(s,t,n,r){let a=s.v,i=0|a[yo];if((t=t8t(a,i,t,n,r))==null)return t;if(i=0|a[yo],!U_(s,i)){const l=jGe(t);l!==t&&(ZU(s)&&(a=s.v,i=0|a[yo]),i=ix(a,i,n,t=l,r),aO(a,i))}return t}function s8t(s,t,n,r,a,i,l,o){var c=U_(s,n);i=c?1:i,l=!!l||i===3,c=o&&!c,(i===2||c)&&ZU(s)&&(n=0|(t=s.v)[yo]);var d=(s=kGe(t,a))===rO?7:0|s[yo],u=SGe(d,n);if(o=!(4&u)){var h=s,m=n;const f=!!(2&u);f&&(m|=2);let g=!f,y=!0,x=0,_=0;for(;x32)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 PGe(s){let t=0,n=s.g;const r=n+10,a=s.h;for(;n>>0}function w5e(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],BD(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 vgn(s){return gE(s)}function BD(s,t){if(s.g=t,t>s.l)throw Error()}function r8t(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 a8t(s,t){if(t==0)return vR();var n=r8t(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):egn?s.slice(n,t):new Uint8Array(s.subarray(n,t))),n.length==0?vR():new N5(n,k$)}var qht=[];function i8t(s,t,n,r){if(j5e.length){const a=j5e.pop();return a.o(r),a.g.init(s,t,n,r),a}return new bgn(s,t,n,r)}function o8t(s){s.g.clear(),s.l=-1,s.h=-1,j5e.length<100&&j5e.push(s)}function l8t(s){var t=s.g;if(t.g==t.l)return!1;s.m=s.g.g;var n=z5(s.g);if(t=n>>>3,!((n&=7)>=0&&n<=5)||t<1)throw Error();return s.l=t,s.h=n,!0}function eje(s){switch(s.h){case 0:s.h!=0?eje(s):PGe(s.g);break;case 1:BD(s=s.g,s.g+8);break;case 2:if(s.h!=2)eje(s);else{var t=z5(s.g);BD(s=s.g,s.g+t)}break;case 5:BD(s=s.g,s.g+4);break;case 3:for(t=s.l;;){if(!l8t(s))throw Error();if(s.h==4){if(s.l!=t)throw Error();break}eje(s)}break;default:throw Error()}}function bJ(s,t,n){const r=s.g.l;var a=z5(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 IGe(s){var t=z5(s.g),n=r8t(s=s.g,t);if(s=s.h,Pfn){var r,a=s;(r=QLe)||(r=QLe=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(ane===void 0){try{r.decode(new Uint8Array([128]))}catch{}try{r.decode(new Uint8Array([97])),ane=!0}catch{ane=!1}}throw!ane&&(QLe=void 0),o}}else{t=(i=n)+t,n=[];let o,c=null;for(;i=t?q6():(o=s[i++],l<194||(192&o)!=128?(i--,q6()):n.push((31&l)<<6|63&o)):l<240?i>=t-1?q6():(o=s[i++],(192&o)!=128||l===224&&o<160||l===237&&o>=160||(192&(r=s[i++]))!=128?(i--,q6()):n.push((15&l)<<12|(63&o)<<6|63&r)):l<=244?i>=t-2?q6():(o=s[i++],(192&o)!=128||o-144+(l<<28)>>30||(192&(r=s[i++]))!=128||(192&(a=s[i++]))!=128?(i--,q6()):(l=(7&l)<<18|(63&o)<<12|(63&r)<<6|63&a,l-=65536,n.push(55296+(l>>10&1023),56320+(1023&l)))):q6(),n.length>=8192&&(c=Sht(c,n),n.length=0)}i=Sht(c,n)}return i}function c8t(s){const t=z5(s.g);return a8t(s.g,t)}function JCe(s,t,n){var r=z5(s.g);for(r=s.g.g+r;s.g.g>>0,this.g=t>>>0}};let _gn;function Hht(s){return s?/^-?\d+$/.test(s)?(KCe(s),new f7e(vp,ug)):null:wgn||(wgn=new f7e(0,0))}var f7e=class{constructor(s,t){this.h=s>>>0,this.g=t>>>0}};let wgn;function ez(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 JU(s,t){for(;t>127;)s.g.push(127&t|128),t>>>=7;s.g.push(t)}function eAe(s,t){if(t>=0)JU(s,t);else{for(let n=0;n<9;n++)s.g.push(127&t|128),t>>=7;s.g.push(1)}}function DGe(s){var t=vp;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 M$(s,t){t.length!==0&&(s.l.push(t),s.h+=t.length)}function Lj(s,t,n){JU(s.g,8*t+n)}function RGe(s,t){return Lj(s,t,2),t=s.g.end(),M$(s,t),t.push(s.h),t}function OGe(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 tAe(s,t,n){Lj(s,t,2),JU(s.g,n.length),M$(s,s.g.end()),M$(s,n)}function N5e(s,t,n,r){n!=null&&(t=RGe(s,t),r(n,s),OGe(s,t))}function Q5(){const s=class{constructor(){throw Error()}};return Object.setPrototypeOf(s,s.prototype),s}var FGe=Q5(),d8t=Q5(),zGe=Q5(),BGe=Q5(),$Ge=Q5(),u8t=Q5(),jgn=Q5(),sAe=Q5(),h8t=Q5(),m8t=Q5();function J5(s,t,n){var r=s.v;O_&&O_ in r&&(r=r[O_])&&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 vo=class{constructor(s,t){this.v=YIt(s,t,void 0,2048)}toJSON(){return KIt(this)}j(){var a;var s=rxn,t=this.v,n=s.g,r=O_;if(GU&&r&&((a=t[r])==null?void 0:a[n])!=null&&S$(Vfn,3),t=s.g,Lht&&O_&&Lht===void 0&&(r=(n=this.v)[O_])&&(r=r.da))try{r(n,t,mgn)}catch(i){AIt(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[yo];return NGe(this,s,t)?wGe(this,s,!0):new this.constructor(YU(s,t,!1))}};vo.prototype[C$]=A$,vo.prototype.toString=function(){return this.v.toString()};var eq=class{constructor(s,t,n){this.g=s,this.h=t,s=FGe,this.l=!!s&&n===s||!1}};function nAe(s,t){return new eq(s,t,FGe)}function p8t(s,t,n,r,a){N5e(s,n,y8t(t,r),a)}const Ngn=nAe(function(s,t,n,r,a){return s.h===2&&(bJ(s,TGe(t,r,n),a),!0)},p8t),kgn=nAe(function(s,t,n,r,a){return s.h===2&&(bJ(s,TGe(t,r,n),a),!0)},p8t);var rAe=Symbol(),aAe=Symbol(),g7e=Symbol(),Ght=Symbol(),Wht=Symbol();let f8t,g8t;function iO(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 ggn||(ggn=[0,void 0,!0]);case"number":return h>0?void 0:h===0?xgn||(xgn=[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,f8t??(f8t=i),g8t??(g8t=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 qGe(s,t,n,r,a){const i=n.g;let l,o;s[t]=(c,d,u)=>i(c,d,u,o||(o=iO(aAe,UGe,qGe,r).T),l||(l=VGe(r)),a)}function VGe(s){let t=s[g7e];if(t!=null)return t;const n=iO(aAe,UGe,qGe,s);return t=n.ma?(r,a)=>f8t(r,a,n):(r,a)=>{for(;l8t(a)&&a.h!=4;){var i=a.l,l=n[i];if(l==null){var o=n.ba;o&&(o=o[i])&&(o=Cgn(o))!=null&&(l=n[i]=o)}if(l==null||!l(a,r,i)){if(l=(o=a).m,eje(o),o.ha)var c=void 0;else c=o.g.g-l,o.g.g=l,c=a8t(o.g,c);l=void 0,o=r,c&&((l=o[O_]??(o[O_]=new m7e))[i]??(l[i]=[])).push(c)}}return(r=ZCe(r))&&(r.da=n.qa[Wht]),!0},s[g7e]=t,s[Wht]=Sgn.bind(s),t}function Sgn(s,t,n,r){var a=this[aAe];const i=this[g7e],l=OD(void 0,a.T),o=ZCe(s);if(o){var c=!1,d=a.ba;if(d){if(a=(u,h,m)=>{if(m.length!==0)if(d[h])for(const f of m){u=i8t(f);try{c=!0,i(l,u)}finally{o8t(u)}}else r==null||r(s,h,m)},t==null)b5e(o,a);else if(o!=null){const u=o[t];u&&a(o,t,u)}if(c){let u=0|s[yo];if(2&u&&2048&u&&!(n!=null&&n.Ka))throw Error();const h=WU(u),m=(f,g)=>{if(M3(s,f,h)!=null){if((n==null?void 0:n.Qa)===1)return;throw Error()}g!=null&&(u=ix(s,u,f,g,h)),delete o[f]};t==null?OIt(l,0|l[yo],(f,g)=>{m(f,g)}):m(t,M3(l,t,h))}}}}function Cgn(s){const t=(s=x8t(s))[0].g;if(s=s[1]){const n=VGe(s),r=iO(aAe,UGe,qGe,s).T;return(a,i,l)=>t(a,i,l,r,n)}return t}function iAe(s,t,n){s[t]=n.h}function oAe(s,t,n,r){let a,i;const l=n.h;s[t]=(o,c,d)=>l(o,c,d,i||(i=iO(rAe,iAe,oAe,r).T),a||(a=v8t(r)))}function v8t(s){let t=s[Ght];if(!t){const n=iO(rAe,iAe,oAe,s);t=(r,a)=>b8t(r,a,n),s[Ght]=t}return t}function b8t(s,t,n){OIt(s,0|s[yo],(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=x8t(c))[0].h;if(c=c[1]){const u=v8t(c),h=iO(rAe,iAe,oAe,c).T;c=l.ma?g8t(h,u):(m,f,g)=>d(m,f,g,h,u)}else c=d;return l[o]=c}}(n,r);i?i(t,a,r):r<500||S$(u7e,3)}}),(s=ZCe(s))&&b5e(s,(r,a,i)=>{for(M$(t,t.g.end()),r=0;r{N5e(s,n,OD([l,i],r),a)});else if(Array.isArray(t)){for(let i=0;i>BigInt(32))),ez(s.g,n.h,n.g);break;default:n=Hht(t),ez(s.g,n.h,n.g)}}function j8t(s,t,n){(t=KU(t))!=null&&t!=null&&(Lj(s,n,0),eAe(s.g,t))}function N8t(s,t,n){(t=$It(t))!=null&&(Lj(s,n,0),s.g.g.push(t?1:0))}function k8t(s,t,n){(t=Z0(t))!=null&&tAe(s,n,CIt(t))}function S8t(s,t,n,r,a){N5e(s,n,y8t(t,r),a)}function C8t(s,t,n){(t=t==null||typeof t=="string"||t instanceof N5?t:void 0)!=null&&tAe(s,n,MGe(t,!0).buffer)}function A8t(s,t,n){(t=UIt(t))!=null&&t!=null&&(Lj(s,n,0),JU(s.g,t))}function T8t(s,t,n){return(s.h===5||s.h===2)&&(t=QU(t,0|t[yo],n),s.h==2?JCe(s,w5e,t):t.push(w5e(s.g)),!0)}var fg=Xy(function(s,t,n){return s.h===5&&(Qy(t,n,w5e(s.g)),!0)},_8t,sAe),Egn=sq(T8t,function(s,t,n){if((t=tq(s5,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"))||(KCe(r),r=wZ(vp,ug))),r;if(a==="number")return(r=E$(r))>=0&&_R(r)||(T$(r),r=zIt(vp,ug)),r}}(t),t!=null&&(typeof t=="string"&&Vht(t),t!=null))switch(Lj(s,n,0),typeof t){case"number":s=s.g,T$(t),ez(s,vp,ug);break;case"bigint":n=BigInt.asUintN(64,t),n=new p7e(Number(n&BigInt(4294967295)),Number(n>>BigInt(32))),ez(s.g,n.h,n.g);break;default:n=Vht(t),ez(s.g,n.h,n.g)}},jgn),nx=Xy(function(s,t,n){return s.h===0&&(Qy(t,n,gE(s.g)),!0)},j8t,BGe),_J=sq(function(s,t,n){return(s.h===0||s.h===2)&&(t=QU(t,0|t[yo],n),s.h==2?JCe(s,gE,t):t.push(gE(s.g)),!0)},function(s,t,n){if((t=tq(KU,t))!=null&&t.length){n=RGe(s,n);for(let r=0;r{{const i={ea:!0};r&&Object.assign(i,r),n=i8t(n,void 0,void 0,i);try{const l=new s,o=l.v;VGe(t)(o,n);var a=l}finally{o8t(n)}}return a}}function lAe(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}}}};b8t(this.v,t,iO(rAe,iAe,oAe,s)),M$(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=Zht.createPolicy("goog#html",{createHTML:r,createScript:r,createScriptURL:r})}catch{}return n}()),s=(t=nPe)?t.createScriptURL(s):s,new class{constructor(n){this.g=n}toString(){return this.g+""}}(s)}function ine(s,...t){if(t.length===0)return Xht(s[0]);let n=s[0];for(let r=0;r({index:ij(r,1)??0??-1,score:Df(r,2)??0,categoryName:Z0(Sp(r,3))??""??"",displayName:Z0(Sp(r,4))??""??""})),headIndex:t,headName:n}}function lxn(s){const t={classifications:L3(s,qgn,1).map(n=>{var r;return JGe(((r=$d(n,F8t,4))==null?void 0:r.g())??[],ij(n,2)??0,Z0(Sp(n,3))??"")})};return function(n){return n==null?n:typeof n=="bigint"?(h7e(n)?n=Number(n):(n=xJ(64,n),n=h7e(n)?Number(n):String(n)),n):yJ(n)?typeof n=="number"?bGe(n):VIt(n):void 0}(Sp(s,2,void 0,void 0,v5e))!=null&&(t.timestampMs=uDt(Sp(s,2,void 0,void 0,v5e)??ZIt)),t}function hDt(s){var l,o;var t=qI(s,3,s5,UI()),n=qI(s,2,KU,UI()),r=qI(s,1,Z0,UI()),a=qI(s,9,Z0,UI());const i={categories:[],keypoints:[]};for(let c=0;ct>127?t-256:t)}function cmt(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 dmt(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 fDt(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 _o(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 umt(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]=fDt(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 hmt(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 sk(s,t,n){s.i.simpleListeners=s.i.simpleListeners||{},s.i.simpleListeners[t]=n}function NC(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)}}a7.forVisionTasks=function(s,t=!1){return lne("vision",s??ine``,t)},a7.forTextTasks=function(s,t=!1){return lne("text",s??ine``,t)},a7.forGenAiTasks=function(s,t=!1){return lne("genai",s??ine``,t)},a7.forAudioTasks=function(s,t=!1){return lne("audio",s??ine``,t)},a7.isSimdSupported=function(s=!1){return mDt(s)};async function dxn(s,t,n,r){return s=await(async(a,i,l,o,c)=>{if(i&&await dmt(i),!self.ModuleFactory||l&&(await dmt(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 iPe(s,t){const n=$d(s.baseOptions,k5e,1)||new k5e;typeof t=="string"?(sh(n,2,vJ(t)),sh(n,1)):t instanceof Uint8Array&&(sh(n,1,gGe(t,!1)),sh(n,2)),Zo(s.baseOptions,0,1,n)}function mmt(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 to(s,t){s.C=Math.max(s.C,t)}function hAe(s,t){s.B=new _b,q_(s.B,2,"PassThroughCalculator"),Bm(s.B,"free_memory"),gd(s.B,"free_memory_unused_out"),Pp(t,"free_memory"),Pj(t,s.B)}function L$(s,t){Bm(s.B,t),gd(s.B,t+"_unused_out")}function mAe(s){s.g.addBoolToStream(!0,"free_memory",s.C)}var _7e=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=$d(this.baseOptions,k5e,1))!=null&&a.g()||(i=$d(this.baseOptions,k5e,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=$d(d.baseOptions,rmt,3);if(!h){var m=h=new rmt,f=new Qht;wK(m,4,tje,f)}"delegate"in u&&(u.delegate==="GPU"?(u=h,m=new Rgn,wK(u,2,tje,m)):(u=h,m=new Qht,wK(u,4,tje,m))),Zo(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),iPe(this,"/model.dat"),this.m(),this.L()});if(c.modelAssetBuffer instanceof Uint8Array)iPe(this,c.modelAssetBuffer);else if(c.modelAssetBuffer)return async function(d){const u=[];for(var h=0;;){const{done:m,value:f}=await d.read();if(m)break;u.push(f),h+=f.length}if(u.length===0)return new Uint8Array(0);if(u.length===1)return u[0];d=new Uint8Array(h),h=0;for(const m of u)d.set(m,h),h+=m.length;return d}(c.modelAssetBuffer).then(d=>{iPe(this,d),this.m(),this.L()})}return this.m(),this.L(),Promise.resolve()}L(){}ca(){let s;if(this.g.ca(t=>{s=Ogn(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,mmt(this)}finishProcessing(){this.g.finishProcessing(),mmt(this)}close(){this.B=void 0,this.g.closeGraph()}};function XT(s,t){if(!s)throw Error(`Unable to obtain required WebGL resource: ${t}`);return s}_7e.prototype.close=_7e.prototype.close;class uxn{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 pmt(s,t,n){const r=s.g;if(n=XT(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 fmt(s,t){const n=s.g,r=XT(n.createVertexArray(),"Failed to create vertex array");n.bindVertexArray(r);const a=XT(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=XT(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 uxn(n,r,a,i)}function eWe(s,t){if(s.g){if(t!==s.g)throw Error("Cannot change GL context once initialized")}else s.g=t}function hxn(s,t,n,r){return eWe(s,t),s.h||(s.m(),s.D()),n?(s.u||(s.u=fmt(s,!0)),n=s.u):(s.A||(s.A=fmt(s,!1)),n=s.A),t.useProgram(s.h),n.bind(),s.l(),s=r(),n.g.bindVertexArray(null),s}function gDt(s,t,n){return eWe(s,t),s=XT(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 xDt(s,t,n){eWe(s,t),s.B||(s.B=XT(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 mxn(s){var t;(t=s.g)==null||t.bindFramebuffer(s.g.FRAMEBUFFER,null)}var yDt=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=XT(s.createProgram(),"Failed to create WebGL program"),this.X=pmt(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=pmt(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 B4(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 w7e(s){var t=B4(s,1);if(!t){if(t=B4(s,0))t=new Float32Array(t).map(r=>r/255);else{t=new Float32Array(s.width*s.height);const r=P$(s);var n=tWe(s);if(xDt(n,r,vDt(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 w7e(this)}N(){return vDt(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=P$(this),a=tWe(this);r.activeTexture(r.TEXTURE1),n=gDt(a,r,this.m?r.LINEAR:r.NEAREST),r.bindTexture(r.TEXTURE_2D,n);const i=bDt(this);r.texImage2D(r.TEXTURE_2D,0,i,this.width,this.height,0,r.RED,r.FLOAT,null),r.bindTexture(r.TEXTURE_2D,null),xDt(a,r,n),hxn(a,r,!1,()=>{_Dt(this),r.clearColor(0,0,0,0),r.clear(r.COLOR_BUFFER_BIT),r.drawArrays(r.TRIANGLE_FAN,0,4),j7e(this)}),mxn(a),j7e(this)}}s.push(n)}return new Ex(s,this.m,this.R(),this.canvas,this.l,this.width,this.height)}close(){this.j&&P$(this).deleteTexture(B4(this,2)),gmt=-1}};Ex.prototype.close=Ex.prototype.close,Ex.prototype.clone=Ex.prototype.clone,Ex.prototype.getAsWebGLTexture=Ex.prototype.N,Ex.prototype.getAsFloat32Array=Ex.prototype.ia,Ex.prototype.getAsUint8Array=Ex.prototype.ja,Ex.prototype.hasWebGLTexture=Ex.prototype.R,Ex.prototype.hasFloat32Array=Ex.prototype.ka,Ex.prototype.hasUint8Array=Ex.prototype.Fa;var gmt=250;function NN(...s){return s.map(([t,n])=>({start:t,end:n}))}const pxn=function(s){return class extends s{Ja(){this.i._registerModelResourcesGraphService()}}}((xmt=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:pDt()?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?'),_o(this,r||"input_audio",i=>{_o(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){sk(this,"__graph_config__",t=>{s(t)}),_o(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),_o(this,r,l=>{this.i._addAudioToInputStream(this.g,t,n,l,a)})}addGpuBufferToStream(s,t,n){_o(this,t,r=>{const[a,i]=umt(this,s,r);this.i._addBoundTextureToStream(r,a,i,n)})}addBoolToStream(s,t,n){_o(this,t,r=>{this.i._addBoolToInputStream(s,r,n)})}addDoubleToStream(s,t,n){_o(this,t,r=>{this.i._addDoubleToInputStream(s,r,n)})}addFloatToStream(s,t,n){_o(this,t,r=>{this.i._addFloatToInputStream(s,r,n)})}addIntToStream(s,t,n){_o(this,t,r=>{this.i._addIntToInputStream(s,r,n)})}addUintToStream(s,t,n){_o(this,t,r=>{this.i._addUintToInputStream(s,r,n)})}addStringToStream(s,t,n){_o(this,t,r=>{_o(this,s,a=>{this.i._addStringToInputStream(a,r,n)})})}addStringRecordToStream(s,t,n){_o(this,t,r=>{hmt(this,Object.keys(s),a=>{hmt(this,Object.values(s),i=>{this.i._addFlatHashMapToInputStream(a,i,Object.keys(s).length,r,n)})})})}addProtoToStream(s,t,n,r){_o(this,n,a=>{_o(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){_o(this,s,n=>{this.i._addEmptyPacketToInputStream(n,t)})}addBoolVectorToStream(s,t,n){_o(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){_o(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){_o(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){_o(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){_o(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){_o(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)_o(this,i,l=>{this.i._addStringVectorEntry(a,l)});this.i._addStringVectorToInputStream(a,r,n)})}addBoolToInputSidePacket(s,t){_o(this,t,n=>{this.i._addBoolToInputSidePacket(s,n)})}addDoubleToInputSidePacket(s,t){_o(this,t,n=>{this.i._addDoubleToInputSidePacket(s,n)})}addFloatToInputSidePacket(s,t){_o(this,t,n=>{this.i._addFloatToInputSidePacket(s,n)})}addIntToInputSidePacket(s,t){_o(this,t,n=>{this.i._addIntToInputSidePacket(s,n)})}addUintToInputSidePacket(s,t){_o(this,t,n=>{this.i._addUintToInputSidePacket(s,n)})}addStringToInputSidePacket(s,t){_o(this,t,n=>{_o(this,s,r=>{this.i._addStringToInputSidePacket(r,n)})})}addProtoToInputSidePacket(s,t,n){_o(this,n,r=>{_o(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){_o(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){_o(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){_o(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){_o(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){_o(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){_o(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)_o(this,a,i=>{this.i._addStringVectorEntry(r,i)});this.i._addStringVectorToInputSidePacket(r,n)})}attachBoolListener(s,t){sk(this,s,t),_o(this,s,n=>{this.i._attachBoolListener(n)})}attachBoolVectorListener(s,t){NC(this,s,t),_o(this,s,n=>{this.i._attachBoolVectorListener(n)})}attachIntListener(s,t){sk(this,s,t),_o(this,s,n=>{this.i._attachIntListener(n)})}attachIntVectorListener(s,t){NC(this,s,t),_o(this,s,n=>{this.i._attachIntVectorListener(n)})}attachUintListener(s,t){sk(this,s,t),_o(this,s,n=>{this.i._attachUintListener(n)})}attachUintVectorListener(s,t){NC(this,s,t),_o(this,s,n=>{this.i._attachUintVectorListener(n)})}attachDoubleListener(s,t){sk(this,s,t),_o(this,s,n=>{this.i._attachDoubleListener(n)})}attachDoubleVectorListener(s,t){NC(this,s,t),_o(this,s,n=>{this.i._attachDoubleVectorListener(n)})}attachFloatListener(s,t){sk(this,s,t),_o(this,s,n=>{this.i._attachFloatListener(n)})}attachFloatVectorListener(s,t){NC(this,s,t),_o(this,s,n=>{this.i._attachFloatVectorListener(n)})}attachStringListener(s,t){sk(this,s,t),_o(this,s,n=>{this.i._attachStringListener(n)})}attachStringVectorListener(s,t){NC(this,s,t),_o(this,s,n=>{this.i._attachStringVectorListener(n)})}attachProtoListener(s,t,n){sk(this,s,t),_o(this,s,r=>{this.i._attachProtoListener(r,n||!1)})}attachProtoVectorListener(s,t,n){NC(this,s,t),_o(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?'),sk(this,s,(r,a)=>{r=new Float32Array(r.buffer,r.byteOffset,r.length/4),t(r,a)}),_o(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 xmt{get ga(){return this.i}pa(s,t,n){_o(this,t,r=>{const[a,i]=umt(this,s,r);this.ga._addBoundTextureAsImageToStream(r,a,i,n)})}Z(s,t){sk(this,s,t),_o(this,s,n=>{this.ga._attachImageListener(n)})}aa(s,t){NC(this,s,t),_o(this,s,n=>{this.ga._attachImageVectorListener(n)})}}));var xmt,kN=class extends pxn{};async function Pd(s,t,n){return async function(r,a,i,l){return dxn(r,a,i,l)}(s,n.canvas??(pDt()?void 0:document.createElement("canvas")),t,n)}function wDt(s,t,n,r){if(s.U){const i=new q8t;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].");Co(i,1,(a.left+a.right)/2),Co(i,2,(a.top+a.bottom)/2),Co(i,4,a.right-a.left),Co(i,3,a.bottom-a.top)}else Co(i,1,.5),Co(i,2,.5),Co(i,4,1),Co(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(Co(i,5,-Math.PI*n.rotationDegrees/180),(n==null?void 0:n.rotationDegrees)%180!=0){const[l,o]=fDt(t);n=Df(i,3)*o/l,a=Df(i,4)*l/o,Co(i,4,n),Co(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 SN(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'.");wDt(s,t,n,s.C+1)}function tS(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'.");wDt(s,t,n,r)}function I$(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 Ex([a],n,!1,s.g.i.canvas,s.P,i,t),r?s.clone():s}var V_=class extends _7e{constructor(s,t,n,r){super(s),this.g=s,this.X=t,this.U=n,this.oa=r,this.P=new yDt}l(s,t=!0){if("runningMode"in s&&sh(this.baseOptions,2,jZ(!!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()}};V_.prototype.close=V_.prototype.close;var Sw=class extends V_{constructor(s,t){super(new kN(s,t),"image_in","norm_rect_in",!1),this.j={detections:[]},Zo(s=this.h=new dAe,0,1,t=new yf),Co(this.h,2,.5),Co(this.h,3,.3)}get baseOptions(){return $d(this.h,yf,1)}set baseOptions(s){Zo(this.h,0,1,s)}o(s){return"minDetectionConfidence"in s&&Co(this.h,2,s.minDetectionConfidence??.5),"minSuppressionThreshold"in s&&Co(this.h,3,s.minSuppressionThreshold??.3),this.l(s)}F(s,t){return this.j={detections:[]},SN(this,s,t),this.j}G(s,t,n){return this.j={detections:[]},tS(this,s,n,t),this.j}m(){var s=new X_;Pp(s,"image_in"),Pp(s,"norm_rect_in"),su(s,"detections");const t=new Z_;J5(t,Ygn,this.h);const n=new _b;q_(n,2,"mediapipe.tasks.vision.face_detector.FaceDetectorGraph"),Bm(n,"IMAGE:image_in"),Bm(n,"NORM_RECT:norm_rect_in"),gd(n,"DETECTIONS:detections"),n.o(t),Pj(s,n),this.g.attachProtoVectorListener("detections",(r,a)=>{for(const i of r)r=B8t(i),this.j.detections.push(hDt(r));to(this,a)}),this.g.attachEmptyPacketListener("detections",r=>{to(this,r)}),s=s.g(),this.setGraph(new Uint8Array(s),!0)}};Sw.prototype.detectForVideo=Sw.prototype.G,Sw.prototype.detect=Sw.prototype.F,Sw.prototype.setOptions=Sw.prototype.o,Sw.createFromModelPath=async function(s,t){return Pd(Sw,s,{baseOptions:{modelAssetPath:t}})},Sw.createFromModelBuffer=function(s,t){return Pd(Sw,s,{baseOptions:{modelAssetBuffer:t}})},Sw.createFromOptions=function(s,t){return Pd(Sw,s,t)};var sWe=NN([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]),nWe=NN([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]),rWe=NN([276,283],[283,282],[282,295],[295,285],[300,293],[293,334],[334,296],[296,336]),jDt=NN([474,475],[475,476],[476,477],[477,474]),aWe=NN([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]),iWe=NN([46,53],[53,52],[52,65],[65,55],[70,63],[63,105],[105,66],[66,107]),NDt=NN([469,470],[470,471],[471,472],[472,469]),oWe=NN([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]),kDt=[...sWe,...nWe,...rWe,...aWe,...iWe,...oWe],SDt=NN([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 ymt(s){s.j={faceLandmarks:[],faceBlendshapes:[],facialTransformationMatrixes:[]}}var Zp=class extends V_{constructor(s,t){super(new kN(s,t),"image_in","norm_rect",!1),this.j={faceLandmarks:[],faceBlendshapes:[],facialTransformationMatrixes:[]},this.outputFacialTransformationMatrixes=this.outputFaceBlendshapes=!1,Zo(s=this.h=new K8t,0,1,t=new yf),this.A=new W8t,Zo(this.h,0,3,this.A),this.u=new dAe,Zo(this.h,0,2,this.u),P3(this.u,4,1),Co(this.u,2,.5),Co(this.A,2,.5),Co(this.h,4,.5)}get baseOptions(){return $d(this.h,yf,1)}set baseOptions(s){Zo(this.h,0,1,s)}o(s){return"numFaces"in s&&P3(this.u,4,s.numFaces??1),"minFaceDetectionConfidence"in s&&Co(this.u,2,s.minFaceDetectionConfidence??.5),"minTrackingConfidence"in s&&Co(this.h,4,s.minTrackingConfidence??.5),"minFacePresenceConfidence"in s&&Co(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 ymt(this),SN(this,s,t),this.j}G(s,t,n){return ymt(this),tS(this,s,n,t),this.j}m(){var s=new X_;Pp(s,"image_in"),Pp(s,"norm_rect"),su(s,"face_landmarks");const t=new Z_;J5(t,Xgn,this.h);const n=new _b;q_(n,2,"mediapipe.tasks.vision.face_landmarker.FaceLandmarkerGraph"),Bm(n,"IMAGE:image_in"),Bm(n,"NORM_RECT:norm_rect"),gd(n,"NORM_LANDMARKS:face_landmarks"),n.o(t),Pj(s,n),this.g.attachProtoVectorListener("face_landmarks",(r,a)=>{for(const i of r)r=wJ(i),this.j.faceLandmarks.push(uAe(r));to(this,a)}),this.g.attachEmptyPacketListener("face_landmarks",r=>{to(this,r)}),this.outputFaceBlendshapes&&(su(s,"blendshapes"),gd(n,"BLENDSHAPES:blendshapes"),this.g.attachProtoVectorListener("blendshapes",(r,a)=>{if(this.outputFaceBlendshapes)for(const i of r)r=cAe(i),this.j.faceBlendshapes.push(JGe(r.g()??[]));to(this,a)}),this.g.attachEmptyPacketListener("blendshapes",r=>{to(this,r)})),this.outputFacialTransformationMatrixes&&(su(s,"face_geometry"),gd(n,"FACE_GEOMETRY:face_geometry"),this.g.attachProtoVectorListener("face_geometry",(r,a)=>{if(this.outputFacialTransformationMatrixes)for(const i of r)(r=$d(r=Zgn(i),$gn,2))&&this.j.facialTransformationMatrixes.push({rows:ij(r,1)??0??0,columns:ij(r,2)??0??0,data:qI(r,3,s5,UI()).slice()??[]});to(this,a)}),this.g.attachEmptyPacketListener("face_geometry",r=>{to(this,r)})),s=s.g(),this.setGraph(new Uint8Array(s),!0)}};Zp.prototype.detectForVideo=Zp.prototype.G,Zp.prototype.detect=Zp.prototype.F,Zp.prototype.setOptions=Zp.prototype.o,Zp.createFromModelPath=function(s,t){return Pd(Zp,s,{baseOptions:{modelAssetPath:t}})},Zp.createFromModelBuffer=function(s,t){return Pd(Zp,s,{baseOptions:{modelAssetBuffer:t}})},Zp.createFromOptions=function(s,t){return Pd(Zp,s,t)},Zp.FACE_LANDMARKS_LIPS=sWe,Zp.FACE_LANDMARKS_LEFT_EYE=nWe,Zp.FACE_LANDMARKS_LEFT_EYEBROW=rWe,Zp.FACE_LANDMARKS_LEFT_IRIS=jDt,Zp.FACE_LANDMARKS_RIGHT_EYE=aWe,Zp.FACE_LANDMARKS_RIGHT_EYEBROW=iWe,Zp.FACE_LANDMARKS_RIGHT_IRIS=NDt,Zp.FACE_LANDMARKS_FACE_OVAL=oWe,Zp.FACE_LANDMARKS_CONTOURS=kDt,Zp.FACE_LANDMARKS_TESSELATION=SDt;var lWe=NN([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 vmt(s){s.gestures=[],s.landmarks=[],s.worldLandmarks=[],s.handedness=[]}function bmt(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 _mt(s,t=!0){const n=[];for(const a of s){var r=cAe(a);s=[];for(const i of r.g())r=t&&ij(i,1)!=null?ij(i,1)??0:-1,s.push({score:Df(i,2)??0,index:r,categoryName:Z0(Sp(i,3))??""??"",displayName:Z0(Sp(i,4))??""??""});n.push(s)}return n}var Ub=class extends V_{constructor(s,t){super(new kN(s,t),"image_in","norm_rect",!1),this.gestures=[],this.landmarks=[],this.worldLandmarks=[],this.handedness=[],Zo(s=this.j=new X8t,0,1,t=new yf),this.u=new YGe,Zo(this.j,0,2,this.u),this.D=new KGe,Zo(this.u,0,3,this.D),this.A=new Z8t,Zo(this.u,0,2,this.A),this.h=new Qgn,Zo(this.j,0,3,this.h),Co(this.A,2,.5),Co(this.u,4,.5),Co(this.D,2,.5)}get baseOptions(){return $d(this.j,yf,1)}set baseOptions(s){Zo(this.j,0,1,s)}o(s){var a,i,l,o;if(P3(this.A,3,s.numHands??1),"minHandDetectionConfidence"in s&&Co(this.A,2,s.minHandDetectionConfidence??.5),"minTrackingConfidence"in s&&Co(this.u,4,s.minTrackingConfidence??.5),"minHandPresenceConfidence"in s&&Co(this.D,2,s.minHandPresenceConfidence??.5),s.cannedGesturesClassifierOptions){var t=new EF,n=t,r=b7e(s.cannedGesturesClassifierOptions,(a=$d(this.h,EF,3))==null?void 0:a.l());Zo(n,0,2,r),Zo(this.h,0,3,t)}else s.cannedGesturesClassifierOptions===void 0&&((i=$d(this.h,EF,3))==null||i.g());return s.customGesturesClassifierOptions?(Zo(n=t=new EF,0,2,r=b7e(s.customGesturesClassifierOptions,(l=$d(this.h,EF,4))==null?void 0:l.l())),Zo(this.h,0,4,t)):s.customGesturesClassifierOptions===void 0&&((o=$d(this.h,EF,4))==null||o.g()),this.l(s)}Ha(s,t){return vmt(this),SN(this,s,t),bmt(this)}Ia(s,t,n){return vmt(this),tS(this,s,n,t),bmt(this)}m(){var s=new X_;Pp(s,"image_in"),Pp(s,"norm_rect"),su(s,"hand_gestures"),su(s,"hand_landmarks"),su(s,"world_hand_landmarks"),su(s,"handedness");const t=new Z_;J5(t,Jgn,this.j);const n=new _b;q_(n,2,"mediapipe.tasks.vision.gesture_recognizer.GestureRecognizerGraph"),Bm(n,"IMAGE:image_in"),Bm(n,"NORM_RECT:norm_rect"),gd(n,"HAND_GESTURES:hand_gestures"),gd(n,"LANDMARKS:hand_landmarks"),gd(n,"WORLD_LANDMARKS:world_hand_landmarks"),gd(n,"HANDEDNESS:handedness"),n.o(t),Pj(s,n),this.g.attachProtoVectorListener("hand_landmarks",(r,a)=>{for(const i of r){r=wJ(i);const l=[];for(const o of L3(r,U8t,1))l.push({x:Df(o,1)??0,y:Df(o,2)??0,z:Df(o,3)??0,visibility:Df(o,4)??0});this.landmarks.push(l)}to(this,a)}),this.g.attachEmptyPacketListener("hand_landmarks",r=>{to(this,r)}),this.g.attachProtoVectorListener("world_hand_landmarks",(r,a)=>{for(const i of r){r=tz(i);const l=[];for(const o of L3(r,$8t,1))l.push({x:Df(o,1)??0,y:Df(o,2)??0,z:Df(o,3)??0,visibility:Df(o,4)??0});this.worldLandmarks.push(l)}to(this,a)}),this.g.attachEmptyPacketListener("world_hand_landmarks",r=>{to(this,r)}),this.g.attachProtoVectorListener("hand_gestures",(r,a)=>{this.gestures.push(..._mt(r,!1)),to(this,a)}),this.g.attachEmptyPacketListener("hand_gestures",r=>{to(this,r)}),this.g.attachProtoVectorListener("handedness",(r,a)=>{this.handedness.push(..._mt(r)),to(this,a)}),this.g.attachEmptyPacketListener("handedness",r=>{to(this,r)}),s=s.g(),this.setGraph(new Uint8Array(s),!0)}};function wmt(s){return{landmarks:s.landmarks,worldLandmarks:s.worldLandmarks,handednesses:s.handedness,handedness:s.handedness}}Ub.prototype.recognizeForVideo=Ub.prototype.Ia,Ub.prototype.recognize=Ub.prototype.Ha,Ub.prototype.setOptions=Ub.prototype.o,Ub.createFromModelPath=function(s,t){return Pd(Ub,s,{baseOptions:{modelAssetPath:t}})},Ub.createFromModelBuffer=function(s,t){return Pd(Ub,s,{baseOptions:{modelAssetBuffer:t}})},Ub.createFromOptions=function(s,t){return Pd(Ub,s,t)},Ub.HAND_CONNECTIONS=lWe;var qb=class extends V_{constructor(s,t){super(new kN(s,t),"image_in","norm_rect",!1),this.landmarks=[],this.worldLandmarks=[],this.handedness=[],Zo(s=this.h=new YGe,0,1,t=new yf),this.u=new KGe,Zo(this.h,0,3,this.u),this.j=new Z8t,Zo(this.h,0,2,this.j),P3(this.j,3,1),Co(this.j,2,.5),Co(this.u,2,.5),Co(this.h,4,.5)}get baseOptions(){return $d(this.h,yf,1)}set baseOptions(s){Zo(this.h,0,1,s)}o(s){return"numHands"in s&&P3(this.j,3,s.numHands??1),"minHandDetectionConfidence"in s&&Co(this.j,2,s.minHandDetectionConfidence??.5),"minTrackingConfidence"in s&&Co(this.h,4,s.minTrackingConfidence??.5),"minHandPresenceConfidence"in s&&Co(this.u,2,s.minHandPresenceConfidence??.5),this.l(s)}F(s,t){return this.landmarks=[],this.worldLandmarks=[],this.handedness=[],SN(this,s,t),wmt(this)}G(s,t,n){return this.landmarks=[],this.worldLandmarks=[],this.handedness=[],tS(this,s,n,t),wmt(this)}m(){var s=new X_;Pp(s,"image_in"),Pp(s,"norm_rect"),su(s,"hand_landmarks"),su(s,"world_hand_landmarks"),su(s,"handedness");const t=new Z_;J5(t,exn,this.h);const n=new _b;q_(n,2,"mediapipe.tasks.vision.hand_landmarker.HandLandmarkerGraph"),Bm(n,"IMAGE:image_in"),Bm(n,"NORM_RECT:norm_rect"),gd(n,"LANDMARKS:hand_landmarks"),gd(n,"WORLD_LANDMARKS:world_hand_landmarks"),gd(n,"HANDEDNESS:handedness"),n.o(t),Pj(s,n),this.g.attachProtoVectorListener("hand_landmarks",(r,a)=>{for(const i of r)r=wJ(i),this.landmarks.push(uAe(r));to(this,a)}),this.g.attachEmptyPacketListener("hand_landmarks",r=>{to(this,r)}),this.g.attachProtoVectorListener("world_hand_landmarks",(r,a)=>{for(const i of r)r=tz(i),this.worldLandmarks.push(NK(r));to(this,a)}),this.g.attachEmptyPacketListener("world_hand_landmarks",r=>{to(this,r)}),this.g.attachProtoVectorListener("handedness",(r,a)=>{var i=this.handedness,l=i.push;const o=[];for(const c of r){r=cAe(c);const d=[];for(const u of r.g())d.push({score:Df(u,2)??0,index:ij(u,1)??0??-1,categoryName:Z0(Sp(u,3))??""??"",displayName:Z0(Sp(u,4))??""??""});o.push(d)}l.call(i,...o),to(this,a)}),this.g.attachEmptyPacketListener("handedness",r=>{to(this,r)}),s=s.g(),this.setGraph(new Uint8Array(s),!0)}};qb.prototype.detectForVideo=qb.prototype.G,qb.prototype.detect=qb.prototype.F,qb.prototype.setOptions=qb.prototype.o,qb.createFromModelPath=function(s,t){return Pd(qb,s,{baseOptions:{modelAssetPath:t}})},qb.createFromModelBuffer=function(s,t){return Pd(qb,s,{baseOptions:{modelAssetBuffer:t}})},qb.createFromOptions=function(s,t){return Pd(qb,s,t)},qb.HAND_CONNECTIONS=lWe;var CDt=NN([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 jmt(s){s.h={faceLandmarks:[],faceBlendshapes:[],poseLandmarks:[],poseWorldLandmarks:[],poseSegmentationMasks:[],leftHandLandmarks:[],leftHandWorldLandmarks:[],rightHandLandmarks:[],rightHandWorldLandmarks:[]}}function Nmt(s){try{if(!s.D)return s.h;s.D(s.h)}finally{mAe(s)}}function dne(s,t){s=wJ(s),t.push(uAe(s))}var km=class extends V_{constructor(s,t){super(new kN(s,t),"input_frames_image",null,!1),this.h={faceLandmarks:[],faceBlendshapes:[],poseLandmarks:[],poseWorldLandmarks:[],poseSegmentationMasks:[],leftHandLandmarks:[],leftHandWorldLandmarks:[],rightHandLandmarks:[],rightHandWorldLandmarks:[]},this.outputPoseSegmentationMasks=this.outputFaceBlendshapes=!1,Zo(s=this.j=new sDt,0,1,t=new yf),this.I=new KGe,Zo(this.j,0,2,this.I),this.W=new txn,Zo(this.j,0,3,this.W),this.u=new dAe,Zo(this.j,0,4,this.u),this.O=new W8t,Zo(this.j,0,5,this.O),this.A=new eDt,Zo(this.j,0,6,this.A),this.M=new tDt,Zo(this.j,0,7,this.M),Co(this.u,2,.5),Co(this.u,3,.3),Co(this.O,2,.5),Co(this.A,2,.5),Co(this.A,3,.3),Co(this.M,2,.5),Co(this.I,2,.5)}get baseOptions(){return $d(this.j,yf,1)}set baseOptions(s){Zo(this.j,0,1,s)}o(s){return"minFaceDetectionConfidence"in s&&Co(this.u,2,s.minFaceDetectionConfidence??.5),"minFaceSuppressionThreshold"in s&&Co(this.u,3,s.minFaceSuppressionThreshold??.3),"minFacePresenceConfidence"in s&&Co(this.O,2,s.minFacePresenceConfidence??.5),"outputFaceBlendshapes"in s&&(this.outputFaceBlendshapes=!!s.outputFaceBlendshapes),"minPoseDetectionConfidence"in s&&Co(this.A,2,s.minPoseDetectionConfidence??.5),"minPoseSuppressionThreshold"in s&&Co(this.A,3,s.minPoseSuppressionThreshold??.3),"minPosePresenceConfidence"in s&&Co(this.M,2,s.minPosePresenceConfidence??.5),"outputPoseSegmentationMasks"in s&&(this.outputPoseSegmentationMasks=!!s.outputPoseSegmentationMasks),"minHandLandmarksConfidence"in s&&Co(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,jmt(this),SN(this,s,r),Nmt(this)}G(s,t,n,r){const a=typeof n!="function"?n:{};return this.D=typeof n=="function"?n:r,jmt(this),tS(this,s,a,t),Nmt(this)}m(){var s=new X_;Pp(s,"input_frames_image"),su(s,"pose_landmarks"),su(s,"pose_world_landmarks"),su(s,"face_landmarks"),su(s,"left_hand_landmarks"),su(s,"left_hand_world_landmarks"),su(s,"right_hand_landmarks"),su(s,"right_hand_world_landmarks");const t=new Z_,n=new Kht;q_(n,1,"type.googleapis.com/mediapipe.tasks.vision.holistic_landmarker.proto.HolisticLandmarkerGraphOptions"),function(a,i){if(i!=null)if(Array.isArray(i))sh(a,2,XCe(i,0,NZ));else{if(!(typeof i=="string"||i instanceof N5||pGe(i)))throw Error("invalid value in Any.value field: "+i+" expected a ByteString, a base64 encoded string, a Uint8Array or a jspb array");sA(a,2,gGe(i,!1),vR())}}(n,this.j.g());const r=new _b;q_(r,2,"mediapipe.tasks.vision.holistic_landmarker.HolisticLandmarkerGraph"),EGe(r,8,Kht,n),Bm(r,"IMAGE:input_frames_image"),gd(r,"POSE_LANDMARKS:pose_landmarks"),gd(r,"POSE_WORLD_LANDMARKS:pose_world_landmarks"),gd(r,"FACE_LANDMARKS:face_landmarks"),gd(r,"LEFT_HAND_LANDMARKS:left_hand_landmarks"),gd(r,"LEFT_HAND_WORLD_LANDMARKS:left_hand_world_landmarks"),gd(r,"RIGHT_HAND_LANDMARKS:right_hand_landmarks"),gd(r,"RIGHT_HAND_WORLD_LANDMARKS:right_hand_world_landmarks"),r.o(t),Pj(s,r),hAe(this,s),this.g.attachProtoListener("pose_landmarks",(a,i)=>{dne(a,this.h.poseLandmarks),to(this,i)}),this.g.attachEmptyPacketListener("pose_landmarks",a=>{to(this,a)}),this.g.attachProtoListener("pose_world_landmarks",(a,i)=>{var l=this.h.poseWorldLandmarks;a=tz(a),l.push(NK(a)),to(this,i)}),this.g.attachEmptyPacketListener("pose_world_landmarks",a=>{to(this,a)}),this.outputPoseSegmentationMasks&&(gd(r,"POSE_SEGMENTATION_MASK:pose_segmentation_mask"),L$(this,"pose_segmentation_mask"),this.g.Z("pose_segmentation_mask",(a,i)=>{this.h.poseSegmentationMasks=[I$(this,a,!0,!this.D)],to(this,i)}),this.g.attachEmptyPacketListener("pose_segmentation_mask",a=>{this.h.poseSegmentationMasks=[],to(this,a)})),this.g.attachProtoListener("face_landmarks",(a,i)=>{dne(a,this.h.faceLandmarks),to(this,i)}),this.g.attachEmptyPacketListener("face_landmarks",a=>{to(this,a)}),this.outputFaceBlendshapes&&(su(s,"extra_blendshapes"),gd(r,"FACE_BLENDSHAPES:extra_blendshapes"),this.g.attachProtoListener("extra_blendshapes",(a,i)=>{var l=this.h.faceBlendshapes;this.outputFaceBlendshapes&&(a=cAe(a),l.push(JGe(a.g()??[]))),to(this,i)}),this.g.attachEmptyPacketListener("extra_blendshapes",a=>{to(this,a)})),this.g.attachProtoListener("left_hand_landmarks",(a,i)=>{dne(a,this.h.leftHandLandmarks),to(this,i)}),this.g.attachEmptyPacketListener("left_hand_landmarks",a=>{to(this,a)}),this.g.attachProtoListener("left_hand_world_landmarks",(a,i)=>{var l=this.h.leftHandWorldLandmarks;a=tz(a),l.push(NK(a)),to(this,i)}),this.g.attachEmptyPacketListener("left_hand_world_landmarks",a=>{to(this,a)}),this.g.attachProtoListener("right_hand_landmarks",(a,i)=>{dne(a,this.h.rightHandLandmarks),to(this,i)}),this.g.attachEmptyPacketListener("right_hand_landmarks",a=>{to(this,a)}),this.g.attachProtoListener("right_hand_world_landmarks",(a,i)=>{var l=this.h.rightHandWorldLandmarks;a=tz(a),l.push(NK(a)),to(this,i)}),this.g.attachEmptyPacketListener("right_hand_world_landmarks",a=>{to(this,a)}),s=s.g(),this.setGraph(new Uint8Array(s),!0)}};km.prototype.detectForVideo=km.prototype.G,km.prototype.detect=km.prototype.F,km.prototype.setOptions=km.prototype.o,km.createFromModelPath=function(s,t){return Pd(km,s,{baseOptions:{modelAssetPath:t}})},km.createFromModelBuffer=function(s,t){return Pd(km,s,{baseOptions:{modelAssetBuffer:t}})},km.createFromOptions=function(s,t){return Pd(km,s,t)},km.HAND_CONNECTIONS=lWe,km.POSE_CONNECTIONS=CDt,km.FACE_LANDMARKS_LIPS=sWe,km.FACE_LANDMARKS_LEFT_EYE=nWe,km.FACE_LANDMARKS_LEFT_EYEBROW=rWe,km.FACE_LANDMARKS_LEFT_IRIS=jDt,km.FACE_LANDMARKS_RIGHT_EYE=aWe,km.FACE_LANDMARKS_RIGHT_EYEBROW=iWe,km.FACE_LANDMARKS_RIGHT_IRIS=NDt,km.FACE_LANDMARKS_FACE_OVAL=oWe,km.FACE_LANDMARKS_CONTOURS=kDt,km.FACE_LANDMARKS_TESSELATION=SDt;var Cw=class extends V_{constructor(s,t){super(new kN(s,t),"input_image","norm_rect",!0),this.j={classifications:[]},Zo(s=this.h=new nDt,0,1,t=new yf)}get baseOptions(){return $d(this.h,yf,1)}set baseOptions(s){Zo(this.h,0,1,s)}o(s){return Zo(this.h,0,2,b7e(s,$d(this.h,GGe,2))),this.l(s)}sa(s,t){return this.j={classifications:[]},SN(this,s,t),this.j}ta(s,t,n){return this.j={classifications:[]},tS(this,s,n,t),this.j}m(){var s=new X_;Pp(s,"input_image"),Pp(s,"norm_rect"),su(s,"classifications");const t=new Z_;J5(t,sxn,this.h);const n=new _b;q_(n,2,"mediapipe.tasks.vision.image_classifier.ImageClassifierGraph"),Bm(n,"IMAGE:input_image"),Bm(n,"NORM_RECT:norm_rect"),gd(n,"CLASSIFICATIONS:classifications"),n.o(t),Pj(s,n),this.g.attachProtoListener("classifications",(r,a)=>{this.j=lxn(Vgn(r)),to(this,a)}),this.g.attachEmptyPacketListener("classifications",r=>{to(this,r)}),s=s.g(),this.setGraph(new Uint8Array(s),!0)}};Cw.prototype.classifyForVideo=Cw.prototype.ta,Cw.prototype.classify=Cw.prototype.sa,Cw.prototype.setOptions=Cw.prototype.o,Cw.createFromModelPath=function(s,t){return Pd(Cw,s,{baseOptions:{modelAssetPath:t}})},Cw.createFromModelBuffer=function(s,t){return Pd(Cw,s,{baseOptions:{modelAssetBuffer:t}})},Cw.createFromOptions=function(s,t){return Pd(Cw,s,t)};var Vb=class extends V_{constructor(s,t){super(new kN(s,t),"image_in","norm_rect",!0),this.h=new rDt,this.embeddings={embeddings:[]},Zo(s=this.h,0,1,t=new yf)}get baseOptions(){return $d(this.h,yf,1)}set baseOptions(s){Zo(this.h,0,1,s)}o(s){var t=this.h,n=$d(this.h,nmt,2);return n=n?n.clone():new nmt,s.l2Normalize!==void 0?sh(n,1,jZ(s.l2Normalize)):"l2Normalize"in s&&sh(n,1),s.quantize!==void 0?sh(n,2,jZ(s.quantize)):"quantize"in s&&sh(n,2),Zo(t,0,2,n),this.l(s)}za(s,t){return SN(this,s,t),this.embeddings}Aa(s,t,n){return tS(this,s,n,t),this.embeddings}m(){var s=new X_;Pp(s,"image_in"),Pp(s,"norm_rect"),su(s,"embeddings_out");const t=new Z_;J5(t,nxn,this.h);const n=new _b;q_(n,2,"mediapipe.tasks.vision.image_embedder.ImageEmbedderGraph"),Bm(n,"IMAGE:image_in"),Bm(n,"NORM_RECT:norm_rect"),gd(n,"EMBEDDINGS:embeddings_out"),n.o(t),Pj(s,n),this.g.attachProtoListener("embeddings_out",(r,a)=>{r=Wgn(r),this.embeddings=function(i){return{embeddings:L3(i,Ggn,1).map(l=>{var d,u;const o={headIndex:ij(l,3)??0??-1,headName:Z0(Sp(l,4))??""??""};var c=l.v;return t8t(c,0|c[yo],smt,tPe(l,1))!==void 0?(l=qI(l=$d(l,smt,tPe(l,1),void 0),1,s5,UI()),o.floatEmbedding=l.slice()):(c=new Uint8Array(0),o.quantizedEmbedding=((u=(d=$d(l,Hgn,tPe(l,2),void 0))==null?void 0:d.na())==null?void 0:u.h())??c),o}),timestampMs:uDt(Sp(i,2,void 0,void 0,v5e)??ZIt)}}(r),to(this,a)}),this.g.attachEmptyPacketListener("embeddings_out",r=>{to(this,r)}),s=s.g(),this.setGraph(new Uint8Array(s),!0)}};Vb.cosineSimilarity=function(s,t){if(s.floatEmbedding&&t.floatEmbedding)s=cmt(s.floatEmbedding,t.floatEmbedding);else{if(!s.quantizedEmbedding||!t.quantizedEmbedding)throw Error("Cannot compute cosine similarity between quantized and float embeddings.");s=cmt(lmt(s.quantizedEmbedding),lmt(t.quantizedEmbedding))}return s},Vb.prototype.embedForVideo=Vb.prototype.Aa,Vb.prototype.embed=Vb.prototype.za,Vb.prototype.setOptions=Vb.prototype.o,Vb.createFromModelPath=function(s,t){return Pd(Vb,s,{baseOptions:{modelAssetPath:t}})},Vb.createFromModelBuffer=function(s,t){return Pd(Vb,s,{baseOptions:{modelAssetBuffer:t}})},Vb.createFromOptions=function(s,t){return Pd(Vb,s,t)};var N7e=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 fxn(s){var n,r;const t=function(a){return L3(a,_b,1)}(s.ca()).filter(a=>(Z0(Sp(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=$d(t[0],Z_,7))==null?void 0:n.j())==null?void 0:r.g())??new Map).forEach((a,i)=>{s.u[Number(i)]=Z0(Sp(a,1))??""})}function kmt(s){s.categoryMask=void 0,s.confidenceMasks=void 0,s.qualityScores=void 0}function Smt(s){try{const t=new N7e(s.confidenceMasks,s.categoryMask,s.qualityScores);if(!s.j)return t;s.j(t)}finally{mAe(s)}}N7e.prototype.close=N7e.prototype.close;var _v=class extends V_{constructor(s,t){super(new kN(s,t),"image_in","norm_rect",!1),this.u=[],this.outputCategoryMask=!1,this.outputConfidenceMasks=!0,this.h=new QGe,this.A=new aDt,Zo(this.h,0,3,this.A),Zo(s=this.h,0,1,t=new yf)}get baseOptions(){return $d(this.h,yf,1)}set baseOptions(s){Zo(this.h,0,1,s)}o(s){return s.displayNamesLocale!==void 0?sh(this.h,2,vJ(s.displayNamesLocale)):"displayNamesLocale"in s&&sh(this.h,2),"outputCategoryMask"in s&&(this.outputCategoryMask=s.outputCategoryMask??!1),"outputConfidenceMasks"in s&&(this.outputConfidenceMasks=s.outputConfidenceMasks??!0),super.l(s)}L(){fxn(this)}segment(s,t,n){const r=typeof t!="function"?t:{};return this.j=typeof t=="function"?t:n,kmt(this),SN(this,s,r),Smt(this)}La(s,t,n,r){const a=typeof n!="function"?n:{};return this.j=typeof n=="function"?n:r,kmt(this),tS(this,s,a,t),Smt(this)}Da(){return this.u}m(){var s=new X_;Pp(s,"image_in"),Pp(s,"norm_rect");const t=new Z_;J5(t,oDt,this.h);const n=new _b;q_(n,2,"mediapipe.tasks.vision.image_segmenter.ImageSegmenterGraph"),Bm(n,"IMAGE:image_in"),Bm(n,"NORM_RECT:norm_rect"),n.o(t),Pj(s,n),hAe(this,s),this.outputConfidenceMasks&&(su(s,"confidence_masks"),gd(n,"CONFIDENCE_MASKS:confidence_masks"),L$(this,"confidence_masks"),this.g.aa("confidence_masks",(r,a)=>{this.confidenceMasks=r.map(i=>I$(this,i,!0,!this.j)),to(this,a)}),this.g.attachEmptyPacketListener("confidence_masks",r=>{this.confidenceMasks=[],to(this,r)})),this.outputCategoryMask&&(su(s,"category_mask"),gd(n,"CATEGORY_MASK:category_mask"),L$(this,"category_mask"),this.g.Z("category_mask",(r,a)=>{this.categoryMask=I$(this,r,!1,!this.j),to(this,a)}),this.g.attachEmptyPacketListener("category_mask",r=>{this.categoryMask=void 0,to(this,r)})),su(s,"quality_scores"),gd(n,"QUALITY_SCORES:quality_scores"),this.g.attachFloatVectorListener("quality_scores",(r,a)=>{this.qualityScores=r,to(this,a)}),this.g.attachEmptyPacketListener("quality_scores",r=>{this.categoryMask=void 0,to(this,r)}),s=s.g(),this.setGraph(new Uint8Array(s),!0)}};_v.prototype.getLabels=_v.prototype.Da,_v.prototype.segmentForVideo=_v.prototype.La,_v.prototype.segment=_v.prototype.segment,_v.prototype.setOptions=_v.prototype.o,_v.createFromModelPath=function(s,t){return Pd(_v,s,{baseOptions:{modelAssetPath:t}})},_v.createFromModelBuffer=function(s,t){return Pd(_v,s,{baseOptions:{modelAssetBuffer:t}})},_v.createFromOptions=function(s,t){return Pd(_v,s,t)};var k7e=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()}};k7e.prototype.close=k7e.prototype.close;var nk=class extends V_{constructor(s,t){super(new kN(s,t),"image_in","norm_rect_in",!1),this.outputCategoryMask=!1,this.outputConfidenceMasks=!0,this.h=new QGe,this.u=new aDt,Zo(this.h,0,3,this.u),Zo(s=this.h,0,1,t=new yf)}get baseOptions(){return $d(this.h,yf,1)}set baseOptions(s){Zo(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 lDt,t.keypoint&&t.scribble)throw Error("Cannot provide both keypoint and scribble.");if(t.keypoint){var i=new aPe;sA(i,3,jZ(!0),!1),sA(i,1,sG(t.keypoint.x),0),sA(i,2,sG(t.keypoint.y),0),wK(r,1,v7e,i)}else{if(!t.scribble)throw Error("Must provide either a keypoint or a scribble.");{const o=new axn;for(i of t.scribble)sA(t=new aPe,3,jZ(!0),!1),sA(t,1,sG(i.x),0),sA(t,2,sG(i.y),0),EGe(o,1,aPe,t);wK(r,2,v7e,o)}}this.g.addProtoToStream(r.g(),"mediapipe.tasks.vision.interactive_segmenter.proto.RegionOfInterest","roi_in",n),SN(this,s,a);e:{try{const o=new k7e(this.confidenceMasks,this.categoryMask,this.qualityScores);if(!this.j){var l=o;break e}this.j(o)}finally{mAe(this)}l=void 0}return l}m(){var s=new X_;Pp(s,"image_in"),Pp(s,"roi_in"),Pp(s,"norm_rect_in");const t=new Z_;J5(t,oDt,this.h);const n=new _b;q_(n,2,"mediapipe.tasks.vision.interactive_segmenter.InteractiveSegmenterGraphV2"),Bm(n,"IMAGE:image_in"),Bm(n,"ROI:roi_in"),Bm(n,"NORM_RECT:norm_rect_in"),n.o(t),Pj(s,n),hAe(this,s),this.outputConfidenceMasks&&(su(s,"confidence_masks"),gd(n,"CONFIDENCE_MASKS:confidence_masks"),L$(this,"confidence_masks"),this.g.aa("confidence_masks",(r,a)=>{this.confidenceMasks=r.map(i=>I$(this,i,!0,!this.j)),to(this,a)}),this.g.attachEmptyPacketListener("confidence_masks",r=>{this.confidenceMasks=[],to(this,r)})),this.outputCategoryMask&&(su(s,"category_mask"),gd(n,"CATEGORY_MASK:category_mask"),L$(this,"category_mask"),this.g.Z("category_mask",(r,a)=>{this.categoryMask=I$(this,r,!1,!this.j),to(this,a)}),this.g.attachEmptyPacketListener("category_mask",r=>{this.categoryMask=void 0,to(this,r)})),su(s,"quality_scores"),gd(n,"QUALITY_SCORES:quality_scores"),this.g.attachFloatVectorListener("quality_scores",(r,a)=>{this.qualityScores=r,to(this,a)}),this.g.attachEmptyPacketListener("quality_scores",r=>{this.categoryMask=void 0,to(this,r)}),s=s.g(),this.setGraph(new Uint8Array(s),!0)}};nk.prototype.segment=nk.prototype.segment,nk.prototype.setOptions=nk.prototype.o,nk.createFromModelPath=function(s,t){return Pd(nk,s,{baseOptions:{modelAssetPath:t}})},nk.createFromModelBuffer=function(s,t){return Pd(nk,s,{baseOptions:{modelAssetBuffer:t}})},nk.createFromOptions=function(s,t){return Pd(nk,s,t)};var Aw=class extends V_{constructor(s,t){super(new kN(s,t),"input_frame_gpu","norm_rect",!1),this.j={detections:[]},Zo(s=this.h=new cDt,0,1,t=new yf)}get baseOptions(){return $d(this.h,yf,1)}set baseOptions(s){Zo(this.h,0,1,s)}o(s){return s.displayNamesLocale!==void 0?sh(this.h,2,vJ(s.displayNamesLocale)):"displayNamesLocale"in s&&sh(this.h,2),s.maxResults!==void 0?P3(this.h,3,s.maxResults):"maxResults"in s&&sh(this.h,3),s.scoreThreshold!==void 0?Co(this.h,4,s.scoreThreshold):"scoreThreshold"in s&&sh(this.h,4),s.categoryAllowlist!==void 0?_5e(this.h,5,s.categoryAllowlist):"categoryAllowlist"in s&&sh(this.h,5),s.categoryDenylist!==void 0?_5e(this.h,6,s.categoryDenylist):"categoryDenylist"in s&&sh(this.h,6),this.l(s)}F(s,t){return this.j={detections:[]},SN(this,s,t),this.j}G(s,t,n){return this.j={detections:[]},tS(this,s,n,t),this.j}m(){var s=new X_;Pp(s,"input_frame_gpu"),Pp(s,"norm_rect"),su(s,"detections");const t=new Z_;J5(t,ixn,this.h);const n=new _b;q_(n,2,"mediapipe.tasks.vision.ObjectDetectorGraph"),Bm(n,"IMAGE:input_frame_gpu"),Bm(n,"NORM_RECT:norm_rect"),gd(n,"DETECTIONS:detections"),n.o(t),Pj(s,n),this.g.attachProtoVectorListener("detections",(r,a)=>{for(const i of r)r=B8t(i),this.j.detections.push(hDt(r));to(this,a)}),this.g.attachEmptyPacketListener("detections",r=>{to(this,r)}),s=s.g(),this.setGraph(new Uint8Array(s),!0)}};Aw.prototype.detectForVideo=Aw.prototype.G,Aw.prototype.detect=Aw.prototype.F,Aw.prototype.setOptions=Aw.prototype.o,Aw.createFromModelPath=async function(s,t){return Pd(Aw,s,{baseOptions:{modelAssetPath:t}})},Aw.createFromModelBuffer=function(s,t){return Pd(Aw,s,{baseOptions:{modelAssetBuffer:t}})},Aw.createFromOptions=function(s,t){return Pd(Aw,s,t)};var S7e=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 Cmt(s){s.landmarks=[],s.worldLandmarks=[],s.segmentationMasks=void 0}function Amt(s){try{const t=new S7e(s.landmarks,s.worldLandmarks,s.segmentationMasks);if(!s.u)return t;s.u(t)}finally{mAe(s)}}S7e.prototype.close=S7e.prototype.close;var Hb=class extends V_{constructor(s,t){super(new kN(s,t),"image_in","norm_rect",!1),this.landmarks=[],this.worldLandmarks=[],this.outputSegmentationMasks=!1,Zo(s=this.h=new dDt,0,1,t=new yf),this.A=new tDt,Zo(this.h,0,3,this.A),this.j=new eDt,Zo(this.h,0,2,this.j),P3(this.j,4,1),Co(this.j,2,.5),Co(this.A,2,.5),Co(this.h,4,.5)}get baseOptions(){return $d(this.h,yf,1)}set baseOptions(s){Zo(this.h,0,1,s)}o(s){return"numPoses"in s&&P3(this.j,4,s.numPoses??1),"minPoseDetectionConfidence"in s&&Co(this.j,2,s.minPoseDetectionConfidence??.5),"minTrackingConfidence"in s&&Co(this.h,4,s.minTrackingConfidence??.5),"minPosePresenceConfidence"in s&&Co(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,Cmt(this),SN(this,s,r),Amt(this)}G(s,t,n,r){const a=typeof n!="function"?n:{};return this.u=typeof n=="function"?n:r,Cmt(this),tS(this,s,a,t),Amt(this)}m(){var s=new X_;Pp(s,"image_in"),Pp(s,"norm_rect"),su(s,"normalized_landmarks"),su(s,"world_landmarks"),su(s,"segmentation_masks");const t=new Z_;J5(t,oxn,this.h);const n=new _b;q_(n,2,"mediapipe.tasks.vision.pose_landmarker.PoseLandmarkerGraph"),Bm(n,"IMAGE:image_in"),Bm(n,"NORM_RECT:norm_rect"),gd(n,"NORM_LANDMARKS:normalized_landmarks"),gd(n,"WORLD_LANDMARKS:world_landmarks"),n.o(t),Pj(s,n),hAe(this,s),this.g.attachProtoVectorListener("normalized_landmarks",(r,a)=>{this.landmarks=[];for(const i of r)r=wJ(i),this.landmarks.push(uAe(r));to(this,a)}),this.g.attachEmptyPacketListener("normalized_landmarks",r=>{this.landmarks=[],to(this,r)}),this.g.attachProtoVectorListener("world_landmarks",(r,a)=>{this.worldLandmarks=[];for(const i of r)r=tz(i),this.worldLandmarks.push(NK(r));to(this,a)}),this.g.attachEmptyPacketListener("world_landmarks",r=>{this.worldLandmarks=[],to(this,r)}),this.outputSegmentationMasks&&(gd(n,"SEGMENTATION_MASK:segmentation_masks"),L$(this,"segmentation_masks"),this.g.aa("segmentation_masks",(r,a)=>{this.segmentationMasks=r.map(i=>I$(this,i,!0,!this.u)),to(this,a)}),this.g.attachEmptyPacketListener("segmentation_masks",r=>{this.segmentationMasks=[],to(this,r)})),s=s.g(),this.setGraph(new Uint8Array(s),!0)}};Hb.prototype.detectForVideo=Hb.prototype.G,Hb.prototype.detect=Hb.prototype.F,Hb.prototype.setOptions=Hb.prototype.o,Hb.createFromModelPath=function(s,t){return Pd(Hb,s,{baseOptions:{modelAssetPath:t}})},Hb.createFromModelBuffer=function(s,t){return Pd(Hb,s,{baseOptions:{modelAssetBuffer:t}})},Hb.createFromOptions=function(s,t){return Pd(Hb,s,t)},Hb.POSE_CONNECTIONS=CDt;let VI=null,nG=null;async function gxn(){return VI||nG||(nG=(async()=>{const s=await a7.forVisionTasks("https://cdn.jsdelivr.net/npm/@mediapipe/tasks-vision@latest/wasm");return VI=await _v.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}),VI})(),nG)}function xxn(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 yxn(){VI&&(VI.close(),VI=null,nG=null)}function vxn(s,t){const n=N.useRef(null),r=N.useRef(null),a=N.useRef(null),i=N.useRef(null),l=N.useRef(0);N.useRef(0);const[o,c]=N.useState(null),[d,u]=N.useState(!1),[h,m]=N.useState(null),f=t.type!=="none"&&s!==null;return N.useEffect(()=>{if(t.type==="image"&&t.imageUrl){const g=new Image;g.crossOrigin="anonymous",g.src=t.imageUrl,g.onload=()=>{i.current=g}}else i.current=null},[t.type,t.imageUrl]),N.useEffect(()=>{if(!f||!s){a.current&&(a.current.srcObject=null,a.current=null);return}const g=document.createElement("video");return g.srcObject=s,g.muted=!0,g.playsInline=!0,g.autoplay=!0,g.play().catch(()=>{}),a.current=g,()=>{g.srcObject=null,a.current=null}},[f,s]),N.useEffect(()=>{if(!f){c(null),m(null);return}let g=!1;return(async()=>{u(!0),m(null);try{const x=await gxn();if(g)return;u(!1);const _=a.current;if(!_||(await new Promise(Se=>{if(_.videoWidth>0)return Se();_.onloadedmetadata=()=>Se(),setTimeout(Se,2e3)}),g))return;const b=_.videoWidth||640,k=_.videoHeight||480,A=n.current;if(!A)return;A.width=b,A.height=k;const T=A.getContext("2d",{willReadFrequently:!1,alpha:!1});r.current||(r.current=document.createElement("canvas"));const P=r.current;P.width=b,P.height=k;const I=P.getContext("2d",{willReadFrequently:!1}),M=document.createElement("canvas");M.width=b,M.height=k;const L=M.getContext("2d",{alpha:!1}),z=document.createElement("canvas");z.width=b,z.height=k;const $=z.getContext("2d",{willReadFrequently:!1}),V=$.createImageData(b,k),W=V.data;for(let Se=0;SeG.addTrack(Se)),g||c(G);const te=t.blurRadius??15,ne=t.mirror??!1,me=new Float32Array(b*k),ue=new Float32Array(b*k),ce=new Float32Array(b*k);let ae=!1;const he=4,xe=.35,ve=typeof _.requestVideoFrameCallback=="function",ge=()=>{if(g||!a.current)return;const Se=a.current;if(Se.readyState<2){be(Se);return}try{const Ie=performance.now(),Re=x.segmentForVideo(Se,Ie).confidenceMasks;if(Re&&Re.length>0){ue.fill(0);for(let Be=1;Be1?1:Fe}}if(xxn(ue,me,b,k,he),ae)for(let Be=0;Be=1?255:Ge*255|0}if($.putImageData(V,0,0),t.type==="blur")L.filter=`blur(${te}px)`,L.drawImage(Se,0,0,b,k),L.filter="none",T.drawImage(M,0,0);else if(t.type==="image"&&i.current){const Be=i.current,Ne=Be.width/Be.height,Ge=b/k;let Ce=0,Fe=0,Ae=Be.width,Xe=Be.height;Ne>Ge?(Ae=Be.height*Ge,Ce=(Be.width-Ae)/2):(Xe=Be.width/Ge,Fe=(Be.height-Xe)/2),T.drawImage(Be,Ce,Fe,Ae,Xe,0,0,b,k)}else T.fillStyle="#000",T.fillRect(0,0,b,k);I.globalCompositeOperation="source-over",I.clearRect(0,0,b,k),I.drawImage(Se,0,0,b,k),I.globalCompositeOperation="destination-in",I.drawImage(z,0,0),I.globalCompositeOperation="source-over",ne?(T.save(),T.translate(b,0),T.scale(-1,1),T.drawImage(P,0,0),T.restore()):T.drawImage(P,0,0);for(const Be of Re)Be.close()}else T.drawImage(Se,0,0,b,k)}catch{T.drawImage(Se,0,0,b,k)}be(Se)},be=Se=>{g||(ve?Se.requestVideoFrameCallback(()=>ge()):l.current=requestAnimationFrame(ge))};be(_)}catch(x){console.error("[useVirtualBackground] init error:",x),g||(u(!1),m(x.message||"Failed to initialize virtual background"))}})(),()=>{g=!0,l.current&&cancelAnimationFrame(l.current),c(null)}},[f,t.type,t.blurRadius,t.imageUrl,s]),N.useEffect(()=>()=>{yxn()},[]),{canvasRef:n,compositedStream:o,isLoading:d,isActive:f,error:h}}function oO({maxDurationSeconds:s=600,onRecordingComplete:t,onError:n,onRecordingStateChange:r,className:a,teleprompterContent:i}){const l=N.useRef(null),o=N.useRef(null),c=N.useRef(null),[d,u]=N.useState(null),h=N.useRef([]),m=N.useRef(null),f=N.useRef(null),g=N.useRef(null),y=N.useRef(null),x=qU(),[_,b]=N.useState("camera"),k=N.useRef(null),A=N.useRef(null),T=N.useRef(null),P=N.useRef(null),I=N.useRef(null),M=N.useRef(null),[L,z]=N.useState(!0),[$,V]=N.useState(!0),[W,G]=N.useState(null),[X,te]=N.useState(!1),[ne,me]=N.useState(!1),[ue,ce]=N.useState(null),[ae,he]=N.useState(null),[xe,ve]=N.useState(0),[ge,be]=N.useState("user"),[Se,Ie]=N.useState(0),[Me,Re]=N.useState(!1),[Be,Ne]=N.useState(!0),[Ge,Ce]=N.useState(null),[Fe,Ae]=N.useState(!1),[Xe,$e]=N.useState(null),Ye=N.useRef(null),[Je,Ke]=N.useState(()=>{try{const vr=localStorage.getItem("video-bg-config");if(vr)return JSON.parse(vr)}catch{}return{type:"none"}});N.useEffect(()=>{try{localStorage.setItem("video-bg-config",JSON.stringify(Je))}catch{}},[Je]);const[st,rt]=N.useState([]),[Ze,ht]=N.useState([]),[Bt,Ct]=N.useState(()=>{try{return localStorage.getItem("video-mic-id")||""}catch{return""}}),[Yt,Kt]=N.useState(()=>{try{return localStorage.getItem("video-cam-id")||""}catch{return""}});N.useEffect(()=>{try{localStorage.setItem("video-mic-id",Bt)}catch{}},[Bt]),N.useEffect(()=>{try{localStorage.setItem("video-cam-id",Yt)}catch{}},[Yt]),N.useEffect(()=>{var Nr,rn,Zn;if(!((Nr=navigator.mediaDevices)!=null&&Nr.enumerateDevices))return;const vr=async()=>{try{const sa=await navigator.mediaDevices.enumerateDevices();rt(sa.filter(xs=>xs.kind==="audioinput")),ht(sa.filter(xs=>xs.kind==="videoinput"))}catch(sa){console.warn("[VideoRecorder] enumerateDevices failed",sa)}};return vr(),(Zn=(rn=navigator.mediaDevices).addEventListener)==null||Zn.call(rn,"devicechange",vr),()=>{var sa,xs;return(xs=(sa=navigator.mediaDevices).removeEventListener)==null?void 0:xs.call(sa,"devicechange",vr)}},[W]);const{canvasRef:Xs,compositedStream:zs,isLoading:Vt,isActive:At,error:Os}=vxn(d,Je),Nt=N.useRef(n);Nt.current=n;const ms=N.useCallback(vr=>{z(vr)},[]),Ys=N.useRef(L),It=N.useCallback(()=>{T.current&&(cancelAnimationFrame(T.current),T.current=null),P.current&&(P.current.terminate(),P.current=null),k.current&&(k.current.getTracks().forEach(vr=>vr.stop()),k.current=null),I.current&&(I.current.getTracks().forEach(vr=>vr.stop()),I.current=null),M.current&&(M.current.srcObject=null,M.current=null)},[]),Ds=N.useCallback(async()=>{var vr;try{const Nr=await navigator.mediaDevices.getDisplayMedia({video:{width:{ideal:1920},height:{ideal:1080}},audio:!0});k.current=Nr;let rn=null;try{rn=await navigator.mediaDevices.getUserMedia({video:Yt?{deviceId:{exact:Yt},width:{ideal:320},height:{ideal:240}}:{width:{ideal:320},height:{ideal:240}},audio:!1})}catch{console.warn("[VideoRecorder] No webcam for PiP overlay")}let Zn=null;try{Zn=await navigator.mediaDevices.getUserMedia({audio:{echoCancellation:!0,noiseSuppression:!0,...Bt?{deviceId:{exact:Bt}}:{}}}),console.log("[VideoRecorder] mic acquired for screen recording",Zn.getAudioTracks().map(Er=>Er.label))}catch(Er){console.warn("[VideoRecorder] No mic audio for screen recording",Er);try{Zn=await navigator.mediaDevices.getUserMedia({audio:!0})}catch{}}const sa=Nr.getVideoTracks()[0],xs=sa.getSettings(),Ve=xs.width||1920,it=xs.height||1080,ft=document.createElement("canvas");ft.width=Ve,ft.height=it,A.current=ft;const kt=ft.getContext("2d");let Ut=null;rn&&(Ut=document.createElement("video"),Ut.srcObject=rn,Ut.muted=!0,Ut.playsInline=!0,Ut.autoplay=!0,await Ut.play(),M.current=Ut);const es=document.createElement("video");es.srcObject=Nr,es.muted=!0,es.playsInline=!0,es.autoplay=!0,await es.play();const Ms=()=>{if(kt.drawImage(es,0,0,Ve,it),Ut&&Ut.readyState>=2){const Er=Math.round(Ve*.2),qr=Math.round(Er*(Ut.videoHeight/Ut.videoWidth||.75)),Xt=Ve-Er-20,Gn=it-qr-20,Jr=12;kt.save(),kt.beginPath(),kt.moveTo(Xt+Jr,Gn),kt.lineTo(Xt+Er-Jr,Gn),kt.quadraticCurveTo(Xt+Er,Gn,Xt+Er,Gn+Jr),kt.lineTo(Xt+Er,Gn+qr-Jr),kt.quadraticCurveTo(Xt+Er,Gn+qr,Xt+Er-Jr,Gn+qr),kt.lineTo(Xt+Jr,Gn+qr),kt.quadraticCurveTo(Xt,Gn+qr,Xt,Gn+qr-Jr),kt.lineTo(Xt,Gn+Jr),kt.quadraticCurveTo(Xt,Gn,Xt+Jr,Gn),kt.closePath(),kt.clip(),kt.translate(Xt+Er,Gn),kt.scale(-1,1),kt.drawImage(Ut,0,0,Er,qr),kt.restore(),kt.strokeStyle="rgba(255,255,255,0.6)",kt.lineWidth=2,kt.beginPath(),kt.moveTo(Xt+Jr,Gn),kt.lineTo(Xt+Er-Jr,Gn),kt.quadraticCurveTo(Xt+Er,Gn,Xt+Er,Gn+Jr),kt.lineTo(Xt+Er,Gn+qr-Jr),kt.quadraticCurveTo(Xt+Er,Gn+qr,Xt+Er-Jr,Gn+qr),kt.lineTo(Xt+Jr,Gn+qr),kt.quadraticCurveTo(Xt,Gn+qr,Xt,Gn+qr-Jr),kt.lineTo(Xt,Gn+Jr),kt.quadraticCurveTo(Xt,Gn,Xt+Jr,Gn),kt.closePath(),kt.stroke()}},bs="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}}",Zs=new Blob([bs],{type:"application/javascript"}),kn=new Worker(URL.createObjectURL(Zs));P.current=kn,kn.onmessage=()=>Ms(),kn.postMessage({type:"start",fps:30}),Ms();const gn=ft.captureStream(30),xr=[],Kr=Nr.getAudioTracks();Kr.length&&xr.push(...Kr),Zn&&xr.push(...Zn.getAudioTracks());const ca=new MediaStream([...gn.getVideoTracks(),...xr]);return I.current=ca,sa.onended=()=>{o.current&&o.current.state!=="inactive"&&o.current.stop(),It()},ca}catch(Nr){return console.error("[VideoRecorder] Screen capture error:",Nr),Nr.name!=="NotAllowedError"&&((vr=Nt.current)==null||vr.call(Nt,"Failed to start screen capture: "+(Nr.message||"Unknown error"))),null}},[It]),As=N.useCallback(async()=>{var Nr,rn;V(!0),Ce(null);const vr=x&&L;console.log("[VideoRecorder] initCamera start",{isMobile:x,usePortraitMode:L,shouldBePortrait:vr,facingMode:ge});try{if(!navigator.mediaDevices||!navigator.mediaDevices.getUserMedia)throw new Error("Camera not available in this browser or context. Try opening in a new tab.");c.current&&(console.log("[VideoRecorder] stopping existing stream"),c.current.getTracks().forEach(kt=>kt.stop()));const Zn=x&&vr?{width:{ideal:720},height:{ideal:1280}}:{width:{ideal:1280},height:{ideal:720}},sa=Yt?{...Zn,deviceId:{exact:Yt}}:{...Zn,facingMode:{ideal:ge}},xs={echoCancellation:!0,noiseSuppression:!0,...Bt?{deviceId:{exact:Bt}}:{}};console.log("[VideoRecorder] requesting getUserMedia",sa);const Ve=await navigator.mediaDevices.getUserMedia({video:sa,audio:xs});if(console.log("[VideoRecorder] getUserMedia success"),Ve.getVideoTracks().length===0)throw new Error("Camera stream started but no video track was provided.");c.current=Ve,u(Ve),G(!0);const ft=Ve.getVideoTracks()[0].getSettings();if(console.log("[VideoRecorder] Camera initialized with dimensions:",ft.width,"x",ft.height),l.current){const kt=l.current;kt.srcObject=Ve,kt.muted=!0,kt.playsInline=!0,kt.autoplay=!0,kt.setAttribute("muted",""),kt.setAttribute("playsinline",""),kt.setAttribute("autoplay","");try{(Nr=kt.load)==null||Nr.call(kt)}catch(es){console.warn("[VideoRecorder] videoEl.load failed",es)}const Ut=async()=>{try{return await kt.play(),console.log("[VideoRecorder] preview play ok"),Ae(!1),setTimeout(()=>{console.debug("[VideoRecorder] preview metrics",{readyState:kt.readyState,videoWidth:kt.videoWidth,videoHeight:kt.videoHeight})},300),!0}catch(es){return console.warn("[VideoRecorder] preview play blocked",es),Ae(!0),!1}};await new Promise(es=>{let Ms=!1;const bs=()=>{Ms||(Ms=!0,es())},Zs=()=>{Ut().finally(bs)};kt.onloadedmetadata=Zs,kt.onloadeddata=Zs,setTimeout(bs,1500)})}try{f.current=new AudioContext;const kt=f.current.createMediaStreamSource(Ve);g.current=f.current.createAnalyser(),g.current.fftSize=256,kt.connect(g.current);const Ut=()=>{if(g.current){const es=new Uint8Array(g.current.frequencyBinCount);g.current.getByteFrequencyData(es);const Ms=es.reduce((bs,Zs)=>bs+Zs)/es.length;Ie(Math.min(100,Ms/128*100))}y.current=requestAnimationFrame(Ut)};Ut()}catch(kt){console.warn("Audio context not available:",kt)}}catch(Zn){console.error("Camera initialization error:",Zn),G(!1);let sa="Failed to access camera or microphone.";Zn.name==="NotAllowedError"?sa="Camera permission denied. Please allow camera access in your browser settings.":Zn.name==="NotFoundError"?sa="No camera found. Please connect a camera and try again.":Zn.name==="NotReadableError"?sa="Camera is in use by another application. Please close other apps using the camera.":Zn.message&&(sa=Zn.message),Ce(sa),(rn=Nt.current)==null||rn.call(Nt,sa)}finally{V(!1)}},[ge,x,L,Bt,Yt]);N.useEffect(()=>{Ys.current!==L&&W&&!X&&!ae&&(Ys.current=L,As())},[L,W,X,ae,As]),N.useEffect(()=>(As(),()=>{c.current&&c.current.getTracks().forEach(vr=>vr.stop()),m.current&&clearInterval(m.current),y.current&&cancelAnimationFrame(y.current),f.current&&f.current.close(),Ye.current&&clearInterval(Ye.current),ae&&URL.revokeObjectURL(ae),It()}),[As,ae]),N.useEffect(()=>{if($||W!==!0||ae)return;const vr=c.current,Nr=l.current;!vr||!Nr||At||(Nr.srcObject!==vr&&(Nr.srcObject=vr,Nr.muted=!0,Nr.playsInline=!0,Nr.autoplay=!0,Nr.setAttribute("muted",""),Nr.setAttribute("playsinline",""),Nr.setAttribute("autoplay","")),Nr.play().then(()=>Ae(!1)).catch(rn=>{Ae(!0),console.warn("Live preview play blocked on mount:",rn)}))},[W,$,ae,At]),N.useEffect(()=>{r==null||r(X)},[X,r]);const Hs=N.useCallback(async()=>{if(ae)return;const vr=l.current;if(vr)try{await vr.play(),Ae(!1)}catch(Nr){Ae(!0),console.warn("Live preview still blocked (needs user gesture):",Nr)}},[ae]),Rs=N.useCallback(()=>{o.current&&o.current.state!=="inactive"&&o.current.stop(),m.current&&(clearInterval(m.current),m.current=null),It(),te(!1),me(!1)},[It]),en=N.useCallback(async()=>{let vr=null;if(_==="screen"){if(vr=await Ds(),!vr)return}else vr=At&&zs?zs:c.current;if(!vr)return;Hs(),h.current=[],ve(0);const rn=["video/webm;codecs=vp9,opus","video/webm;codecs=vp8,opus","video/webm;codecs=vp9","video/webm;codecs=vp8","video/webm","video/mp4"].find(sa=>MediaRecorder.isTypeSupported(sa)),Zn=new MediaRecorder(vr,rn?{mimeType:rn,videoBitsPerSecond:_==="screen"?4e6:25e5}:{videoBitsPerSecond:_==="screen"?4e6:25e5});Zn.ondataavailable=sa=>{sa.data.size>0&&h.current.push(sa.data)},Zn.onstop=()=>{var it;const sa=Zn.mimeType||rn||((it=h.current[0])==null?void 0:it.type)||"video/webm",xs=new Blob(h.current,{type:sa});ce(xs);const Ve=URL.createObjectURL(xs);he(Ve)},o.current=Zn,Zn.start(100),te(!0),m.current=setInterval(()=>{ve(sa=>sa>=s-1?(Rs(),s):sa+1)},1e3)},[Hs,s,Rs,At,zs,_,Ds]),Rn=N.useCallback(()=>{Ye.current&&(clearInterval(Ye.current),Ye.current=null),$e(3);let vr=3;Ye.current=setInterval(()=>{vr-=1,vr<=0?(Ye.current&&clearInterval(Ye.current),Ye.current=null,$e(null),en()):$e(vr)},1e3)},[en]),Bn=N.useCallback(()=>{o.current&&o.current.state==="recording"&&(o.current.pause(),me(!0),m.current&&clearInterval(m.current))},[]),Dn=N.useCallback(()=>{o.current&&o.current.state==="paused"&&(o.current.resume(),me(!1),m.current=setInterval(()=>{ve(vr=>vr>=s-1?(Rs(),s):vr+1)},1e3))},[s,Rs]),Jn=N.useCallback(()=>{ae&&URL.revokeObjectURL(ae),ce(null),he(null),ve(0),Re(!1),Ne(!0),l.current&&c.current&&!At&&(l.current.srcObject=c.current,l.current.muted=!0,Hs())},[Hs,ae,At]),ua=N.useCallback(()=>{be(vr=>vr==="user"?"environment":"user")},[]),Mr=N.useCallback(()=>{ue&&t(ue,xe)},[ue,xe,t]),sn=N.useCallback(()=>{l.current&&ae&&(Me?l.current.pause():(Ne(!1),l.current.muted=!1,l.current.play()),Re(!Me))},[ae,Me]);N.useEffect(()=>{if(!ae)return;const vr=l.current;if(!vr)return;Ne(!1),vr.pause(),vr.removeAttribute("src"),vr.srcObject=null,vr.load(),vr.src=ae,vr.currentTime=0,vr.playsInline=!0,vr.muted=!1,vr.onended=()=>Re(!1);const Nr=()=>{var sa;const rn=vr.error,Zn=rn?`Recorded video failed to play (code ${rn.code}). Likely unsupported format/codec in this browser.`:"Recorded video failed to play.";console.warn("[VideoRecorder] recorded playback error",rn),(sa=Nt.current)==null||sa.call(Nt,Zn)};return vr.addEventListener("error",Nr),vr.load(),()=>{vr.removeEventListener("error",Nr)}},[ae]);const ki=vr=>{const Nr=Math.floor(vr/60),rn=vr%60;return`${Nr}:${rn.toString().padStart(2,"0")}`},ia=_==="screen"?"aspect-video":x&&L?"aspect-[9/16]":"aspect-video";return $?e.jsx("div",{className:Ot("flex items-center justify-center bg-black rounded-lg",ia,a),children:e.jsxs("div",{className:"text-center text-white",children:[e.jsx(us,{className:"h-12 w-12 animate-spin mx-auto mb-4"}),e.jsx("p",{children:"Initializing camera..."})]})}):W===!1?e.jsx("div",{className:Ot("flex items-center justify-center bg-black rounded-lg",ia,a),children:e.jsxs("div",{className:"text-center text-white p-8 max-w-md",children:[e.jsx(Uo,{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:Ge||"Please allow camera and microphone access to record videos."}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs(B,{onClick:()=>As(),variant:"secondary",className:"w-full",children:[e.jsx(oo,{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:Ot("flex flex-col gap-2",a),children:[!X&&!ae&&e.jsxs("div",{className:"flex items-center justify-center gap-1 p-1 bg-muted rounded-lg",children:[e.jsxs(B,{variant:_==="camera"?"default":"ghost",size:"sm",className:"gap-1.5 flex-1",onClick:()=>b("camera"),children:[e.jsx($0,{className:"h-4 w-4"}),"Camera"]}),e.jsxs(B,{variant:_==="screen"?"default":"ghost",size:"sm",className:"gap-1.5 flex-1",onClick:()=>b("screen"),children:[e.jsx(bD,{className:"h-4 w-4"}),"Screen"]})]}),_==="camera"&&!X&&!ae&&e.jsx(Lfn,{value:Je,onChange:Ke,isLoading:Vt,disabled:X}),!X&&!ae&&(st.length>0||Ze.length>0)&&e.jsxs("div",{className:"flex flex-wrap items-center gap-3 px-3 py-2 bg-muted/40 rounded-lg",children:[st.length>0&&e.jsxs("div",{className:"flex items-center gap-2 flex-1 min-w-[200px]",children:[e.jsx(uj,{className:"h-4 w-4 text-muted-foreground shrink-0"}),e.jsxs(Ns,{value:Bt||"default",onValueChange:vr=>Ct(vr==="default"?"":vr),children:[e.jsx(ws,{className:"h-8 text-xs",children:e.jsx(ks,{placeholder:"Default microphone"})}),e.jsxs(js,{children:[e.jsx(nt,{value:"default",children:"Default microphone"}),st.map(vr=>e.jsx(nt,{value:vr.deviceId,children:vr.label||`Microphone ${vr.deviceId.slice(0,6)}`},vr.deviceId))]})]})]}),Ze.length>1&&_==="camera"&&e.jsxs("div",{className:"flex items-center gap-2 flex-1 min-w-[200px]",children:[e.jsx($0,{className:"h-4 w-4 text-muted-foreground shrink-0"}),e.jsxs(Ns,{value:Yt||"default",onValueChange:vr=>Kt(vr==="default"?"":vr),children:[e.jsx(ws,{className:"h-8 text-xs",children:e.jsx(ks,{placeholder:"Default camera"})}),e.jsxs(js,{children:[e.jsx(nt,{value:"default",children:"Default camera"}),Ze.map(vr=>e.jsx(nt,{value:vr.deviceId,children:vr.label||`Camera ${vr.deviceId.slice(0,6)}`},vr.deviceId))]})]})]})]}),_==="camera"&&x&&!X&&!ae&&e.jsxs("div",{className:"flex items-center justify-center gap-3 py-2 bg-muted/50 rounded-lg",children:[e.jsx(hj,{className:Ot("h-4 w-4",L?"text-muted-foreground":"text-primary")}),e.jsx(re,{htmlFor:"orientation-toggle",className:"text-sm text-muted-foreground",children:"Landscape"}),e.jsx(zn,{id:"orientation-toggle",checked:L,onCheckedChange:ms}),e.jsx(re,{htmlFor:"orientation-toggle",className:"text-sm text-muted-foreground",children:"Portrait"}),e.jsx($y,{className:Ot("h-4 w-4",L?"text-primary":"text-muted-foreground")})]}),_==="screen"&&!X&&!ae&&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(bD,{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:Ot("relative bg-black rounded-lg overflow-hidden"),onPointerDown:()=>{Hs()},children:[e.jsx("video",{ref:l,src:ae??void 0,className:Ot("w-full bg-black",L&&!ae?"object-contain":"object-cover",ia,!ae&&ge==="user"!==(Je.mirror??!1)&&"scale-x-[-1]",At&&!ae&&"hidden"),playsInline:!0,controls:!!ae,muted:ae?Be:!0,autoPlay:!ae},ae??"live"),At&&!ae&&e.jsx("canvas",{ref:Xs,className:Ot("w-full bg-black",L?"object-contain":"object-cover",ia,ge==="user"!==(Je.mirror??!1)&&"scale-x-[-1]")}),At&&Vt&&!ae&&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(us,{className:"h-8 w-8 animate-spin mx-auto mb-2"}),e.jsx("p",{className:"text-sm",children:"Loading virtual background…"})]})}),!ae&&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 Hs(),className:"bg-white/20 hover:bg-white/30 text-white",children:"Tap to enable preview"})}),i&&!ae&&e.jsx("div",{className:"absolute inset-0 pointer-events-none",children:i}),Xe!==null&&!ae&&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:Xe},Xe),e.jsx("p",{className:"text-white/80 text-lg font-medium drop-shadow-md",children:"Get ready…"})]})}),X&&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:Ot("w-3 h-3 rounded-full",ne?"bg-yellow-500":"bg-red-500 animate-pulse")}),e.jsxs("span",{className:"text-white text-sm font-medium",children:[ki(xe)," / ",ki(s)]})]}),X&&e.jsx("div",{className:"absolute top-0 left-0 right-0",children:e.jsx(ro,{value:xe/s*100,className:"h-1 rounded-none"})}),!ae&&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(uj,{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:`${Se}%`}})})]}),e.jsx("div",{className:"absolute bottom-4 left-0 right-0 flex justify-center gap-3 px-4",children:ae?e.jsxs(e.Fragment,{children:[e.jsxs(B,{variant:"secondary",size:"lg",className:"bg-white/20 hover:bg-white/30 text-white",onClick:Jn,children:[e.jsx(oo,{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:sn,children:Me?e.jsx(K0,{className:"h-5 w-5"}):e.jsx(dd,{className:"h-5 w-5"})}),e.jsxs(B,{size:"lg",className:"bg-green-500 hover:bg-green-600 text-white",onClick:Mr,children:[e.jsx(pa,{className:"h-5 w-5 mr-2"}),"Use This Video"]})]}):e.jsxs(e.Fragment,{children:[_==="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:ua,disabled:X||Xe!==null,children:e.jsx(hf,{className:"h-5 w-5"})}):e.jsx("div",{className:"h-12 w-12"}),!X&&Xe===null?e.jsx(B,{size:"icon",className:"h-16 w-16 rounded-full bg-red-500 hover:bg-red-600 text-white",onClick:_==="screen"?en:Rn,children:_==="screen"?e.jsx(bD,{className:"h-6 w-6"}):e.jsx(na,{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:ne?Dn:Bn,children:ne?e.jsx(dd,{className:"h-5 w-5"}):e.jsx(K0,{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:Rs,children:e.jsx(L_,{className:"h-6 w-6 fill-current"})})]}),e.jsx("div",{className:"h-12 w-12"})]})})]})]})}function bxn({open:s,onOpenChange:t,onUploaded:n}){const{user:r}=Ls(),{toast:a}=Ci(),[i,l]=N.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 H.storage.from("cma-videos").upload(h,c,{contentType:c.type||"video/webm",upsert:!1});if(m)throw m;const{data:f,error:g}=await H.storage.from("cma-videos").createSignedUrl(h,60*60*24*365*5);if(g||!(f!=null&&f.signedUrl))throw g||new Error("Could not sign video URL");n(f.signedUrl,Math.round(d)),a({title:"Video added to your CMA"}),t(!1)}catch(u){a({title:"Upload failed",description:u==null?void 0:u.message,variant:"destructive"})}finally{l(!1)}}};return e.jsx(Bs,{open:s,onOpenChange:c=>!i&&t(c),children:e.jsxs(Fs,{className:"max-w-2xl",children:[e.jsxs(qs,{children:[e.jsx($s,{children:"Record a personal message"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"A 30-second hello goes a long way. Welcome your client, explain the price, and invite their reply."})]}),i?e.jsxs("div",{className:"py-12 flex flex-col items-center gap-3",children:[e.jsx(us,{className:"w-8 h-8 animate-spin text-primary"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Uploading your video…"})]}):e.jsx(oO,{maxDurationSeconds:180,onRecordingComplete:o})]})})}function _xn({value:s,onChange:t}){const{user:n}=Ls(),[r,a]=N.useState(!1);return e.jsxs(_e,{children:[e.jsxs(zt,{children:[e.jsxs(qt,{className:"text-base flex items-center gap-2",children:[e.jsx(na,{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(De,{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(hr,{className:"w-3.5 h-3.5"})})]}),e.jsxs("p",{className:"text-xs text-emerald-700 flex items-center gap-1",children:[e.jsx(dd,{className:"w-3 h-3"})," Video attached"]})]}):e.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[e.jsx(tO,{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(na,{className:"w-4 h-4"}),"Record New"]})]}),e.jsx(bxn,{open:r,onOpenChange:a,onUploaded:i=>t({url:i,label:"Personal message"})})]})]})}function I2(s){const t=Number(String(s).replace(/[^0-9.]/g,""));return Number.isFinite(t)&&t>0?t:null}function wxn({open:s,onOpenChange:t,subject:n,onSave:r,isSaving:a}){const[i,l]=N.useState({bedrooms:"",bathrooms:"",sqft:"",yearBuilt:"",propertyType:"",propertySubType:""});N.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:I2(i.bedrooms),bathrooms:I2(i.bathrooms),sqft:I2(i.sqft),yearBuilt:I2(i.yearBuilt),propertyType:i.propertyType||null,propertySubType:i.propertySubType||null}),t(!1)};return e.jsx(Bs,{open:s,onOpenChange:t,children:e.jsxs(Fs,{className:"max-w-lg",children:[e.jsx(qs,{children:e.jsx($s,{children:"Fill in the subject property basics"})}),e.jsxs("div",{className:"space-y-4",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"When the MLS feed does not return the home details, add the basics here and LevelUp will keep the CMA moving."}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(re,{className:"text-xs",children:"Beds"}),e.jsx(we,{inputMode:"decimal",value:i.bedrooms,onChange:c=>l(d=>({...d,bedrooms:c.target.value})),placeholder:"3"})]}),e.jsxs("div",{children:[e.jsx(re,{className:"text-xs",children:"Baths"}),e.jsx(we,{inputMode:"decimal",value:i.bathrooms,onChange:c=>l(d=>({...d,bathrooms:c.target.value})),placeholder:"2"})]}),e.jsxs("div",{children:[e.jsx(re,{className:"text-xs",children:"Sq Ft"}),e.jsx(we,{inputMode:"numeric",value:i.sqft,onChange:c=>l(d=>({...d,sqft:c.target.value})),placeholder:"1850"})]}),e.jsxs("div",{children:[e.jsx(re,{className:"text-xs",children:"Year Built"}),e.jsx(we,{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(re,{className:"text-xs",children:"Property Type"}),e.jsx(we,{value:i.propertyType,onChange:c=>l(d=>({...d,propertyType:c.target.value})),placeholder:"Residential"})]}),e.jsxs("div",{children:[e.jsx(re,{className:"text-xs",children:"Subtype"}),e.jsx(we,{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(us,{className:"w-4 h-4 mr-2 animate-spin"}):e.jsx(Kl,{className:"w-4 h-4 mr-2"}),"Save subject details"]})]})]})})}function jxn({open:s,onOpenChange:t,subject:n,onAdd:r}){const[a,i]=N.useState({address:"",city:"",state:"",status:"Closed",price:"",bedrooms:"",bathrooms:"",sqft:"",yearBuilt:""});N.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=I2(a.price),c=I2(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:I2(a.bedrooms),bathrooms:I2(a.bathrooms),sqft:c,yearBuilt:I2(a.yearBuilt),photos:[]}),t(!1))};return e.jsx(Bs,{open:s,onOpenChange:t,children:e.jsxs(Fs,{className:"max-w-2xl",children:[e.jsx(qs,{children:e.jsx($s,{children:"Add a comparable manually"})}),e.jsxs("div",{className:"space-y-4",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Use this when the MLS feed misses a property or you already know the best comp. Add at least the address, price, and square footage."}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-4 gap-3",children:[e.jsxs("div",{className:"md:col-span-2",children:[e.jsx(re,{className:"text-xs",children:"Address"}),e.jsx(we,{value:a.address,onChange:o=>i(c=>({...c,address:o.target.value})),placeholder:"123 Comparable St"})]}),e.jsxs("div",{children:[e.jsx(re,{className:"text-xs",children:"City"}),e.jsx(we,{value:a.city,onChange:o=>i(c=>({...c,city:o.target.value}))})]}),e.jsxs("div",{children:[e.jsx(re,{className:"text-xs",children:"State"}),e.jsx(we,{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(re,{className:"text-xs",children:"Status"}),e.jsx(we,{value:a.status,onChange:o=>i(c=>({...c,status:o.target.value})),placeholder:"Closed"})]}),e.jsxs("div",{children:[e.jsx(re,{className:"text-xs",children:"Price"}),e.jsx(we,{inputMode:"numeric",value:a.price,onChange:o=>i(c=>({...c,price:o.target.value})),placeholder:"525000"})]}),e.jsxs("div",{children:[e.jsx(re,{className:"text-xs",children:"Sq Ft"}),e.jsx(we,{inputMode:"numeric",value:a.sqft,onChange:o=>i(c=>({...c,sqft:o.target.value})),placeholder:"1800"})]}),e.jsxs("div",{children:[e.jsx(re,{className:"text-xs",children:"Beds"}),e.jsx(we,{inputMode:"decimal",value:a.bedrooms,onChange:o=>i(c=>({...c,bedrooms:o.target.value})),placeholder:"3"})]}),e.jsxs("div",{children:[e.jsx(re,{className:"text-xs",children:"Baths"}),e.jsx(we,{inputMode:"decimal",value:a.bathrooms,onChange:o=>i(c=>({...c,bathrooms:o.target.value})),placeholder:"2"})]})]}),e.jsxs("div",{children:[e.jsx(re,{className:"text-xs",children:"Year Built"}),e.jsx(we,{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()||!I2(a.price)||!I2(a.sqft),children:[e.jsx(nn,{className:"w-4 h-4 mr-2"}),"Add comp to CMA"]})]})]})})}function Nxn(){var be,Se,Ie,Me,Re,Be,Ne;const{id:s}=uo(),t=tr(),{toast:n}=Ci(),{data:r,isLoading:a}=qpn(s),{data:i}=Vpn(s),l=Hpn(),o=Kpn(),c=Ypn(),{leadSite:d,isLoading:u}=Qx(),[h,m]=N.useState([]),[f,g]=N.useState({sqftPct:.2,monthsBack:6,maxMiles:5,statuses:["Active","Pending","Closed"]}),[y,x]=N.useState(null),[_,b]=N.useState(!1),[k,A]=N.useState({low:"",likely:"",high:"",note:""}),[T,P]=N.useState(!1),[I,M]=N.useState(!1),[L,z]=N.useState(!1),[$,V]=N.useState(null),W=async Ge=>{var Ye,Je;if(!r||!(Ge!=null&&Ge.address)||!(Ge!=null&&Ge.city)||!(Ge!=null&&Ge.state))return Ge;let Ce={...Ge};const Fe=async Ke=>{const{data:st,error:rt}=await H.functions.invoke("cma-subject-lookup",{body:{address:Ke.address,city:Ke.city,state:Ke.state,zip:Ke.zip,latitude:Ke.latitude,longitude:Ke.longitude,leadSiteId:(d==null?void 0:d.id)??r.lead_site_id}});if(rt)throw rt;return(st==null?void 0:st.matches)||[]},Ae=Ke=>{const rt=Ke.find(Ct=>Number.isFinite(Number(Ct.latitude))&&Number.isFinite(Number(Ct.longitude)))||Ke[0];if(!rt)return;const Ze=typeof rt.match_type=="string"&&rt.match_type.startsWith("nearby-"),ht=Ze&&Number.isFinite(Number(Ce.latitude))&&Number.isFinite(Number(Ce.longitude)),Bt=Ct=>rt[Ct]!==void 0&&rt[Ct]!==null&&rt[Ct]!==""&&rt[Ct]!==0?rt[Ct]:Ce[Ct];Ce={...Ce,bedrooms:Bt("bedrooms"),bathrooms:Bt("bathrooms"),sqft:Bt("sqft"),yearBuilt:Bt("yearBuilt"),lotSize:Bt("lotSize"),propertyType:Bt("propertyType"),propertySubType:Bt("propertySubType"),source_provider:rt.source_provider??Ce.source_provider,match_type:rt.match_type??Ce.match_type,matched_mls_address:Ze?rt.address:Ce.matched_mls_address,latitude:ht?Ce.latitude:rt.latitude??Ce.latitude,longitude:ht?Ce.longitude:rt.longitude??Ce.longitude,mlsNumber:Ze?Ce.mlsNumber:rt.mlsNumber??Ce.mlsNumber,photos:!Ze&&Array.isArray(rt.photos)&&rt.photos.length?rt.photos:Ce.photos}};Ae(await Fe(Ce));const Xe=()=>Number.isFinite(Number(Ce.latitude))&&Number.isFinite(Number(Ce.longitude));if(!Xe()){const{data:Ke}=await H.from("settings").select("value").eq("key","mapbox_public_token").maybeSingle(),st=Ke==null?void 0:Ke.value;if(st){const rt=encodeURIComponent(`${Ce.address}, ${Ce.city}, ${Ce.state} ${Ce.zip||""}`.trim()),ht=await(await fetch(`https://api.mapbox.com/geocoding/v5/mapbox.places/${rt}.json?access_token=${st}&limit=1&country=us`)).json(),Bt=(Je=(Ye=ht==null?void 0:ht.features)==null?void 0:Ye[0])==null?void 0:Je.center;Array.isArray(Bt)&&Bt.length===2&&(Ce.longitude=Bt[0],Ce.latitude=Bt[1])}}if((!Ce.bedrooms||!Ce.bathrooms||!Ce.sqft||!Ce.yearBuilt)&&Xe())try{Ae(await Fe(Ce))}catch(Ke){console.warn("second-pass subject lookup failed",Ke)}return JSON.stringify(Ce)!==JSON.stringify(Ge)&&await l.mutateAsync({id:r.id,patch:{subject:Ce}}),Ce};N.useEffect(()=>{var Fe,Ae;r!=null&&r.settings&&g({sqftPct:r.settings.sqftPct??.2,monthsBack:r.settings.monthsBack??6,maxMiles:r.settings.maxMiles??5,statuses:r.settings.statuses??["Active","Pending","Closed"]});const Ge=(Fe=r==null?void 0:r.settings)==null?void 0:Fe.priceOverride;Ge!=null&&Ge.enabled&&(b(!0),A({low:Ge.low!=null?String(Ge.low):"",likely:Ge.likely!=null?String(Ge.likely):"",high:Ge.high!=null?String(Ge.high):"",note:Ge.note??""}));const Ce=(Ae=r==null?void 0:r.settings)==null?void 0:Ae.personalVideo;Ce!=null&&Ce.url&&V({url:Ce.url,thumb:Ce.thumb,label:Ce.label})},[r==null?void 0:r.id]);const G=N.useRef(!1);N.useEffect(()=>{G.current||i!=null&&i.length&&(m(i.map(Ge=>({...Ge.snapshot,selected:Ge.selected,manual:Ge.manual,score:Ge.score}))),G.current=!0)},[i]);const X=N.useRef(null);N.useEffect(()=>{if(!r||u)return;const Ge=r.subject||{},Ce=Number.isFinite(Number(Ge.latitude))&&Number.isFinite(Number(Ge.longitude)),Fe=!!(Number(Ge.bedrooms)||Number(Ge.bathrooms)||Number(Ge.sqft)||Number(Ge.yearBuilt));if(Ce&&Fe)return;const Ae=`${r.id}:${(d==null?void 0:d.id)??r.lead_site_id??"no-site"}`;X.current!==Ae&&(!Ge.address||!Ge.city||!Ge.state||(X.current=Ae,(async()=>{try{await W(Ge)}catch(Xe){console.warn("subject enrich failed",Xe)}})()))},[r==null?void 0:r.id,r==null?void 0:r.lead_site_id,d==null?void 0:d.id,u]);const te=N.useMemo(()=>r?bht(r.subject,h):null,[r,h]),ne=async()=>{if(r)try{const Ge=await W(r.subject),Ce=await o.mutateAsync({subject:Ge,filters:f,leadSiteId:(d==null?void 0:d.id)??r.lead_site_id});m(Ce.comps.map(Fe=>({...Fe,selected:!0})).slice(0,12)),n({title:`Found ${Ce.comps.length} comps`,description:`Top ${Math.min(12,Ce.comps.length)} auto-selected.`})}catch(Ge){n({title:"Search failed",description:Ge.message,variant:"destructive"})}},me=Ge=>{m(Ce=>Ce.map((Fe,Ae)=>Ae===Ge?{...Fe,selected:!Fe.selected}:Fe))},ue=Ge=>{m(Ce=>Ce.filter((Fe,Ae)=>Ae!==Ge))},ce=async Ge=>{if(!r)return;const Ce=Object.fromEntries(Object.entries(Ge).filter(([,Ae])=>Ae!=null&&Ae!=="")),Fe={...r.subject,...Ce,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."})},ae=Ge=>{m(Ce=>[{...Ge,selected:!0,manual:!0},...Ce]),n({title:"Manual comp added"})},he=async(Ge=!1)=>{if(!r)return;const Ce=bht(r.subject,h),Fe=Je=>{const Ke=Number(String(Je).replace(/[^0-9.]/g,""));return Number.isFinite(Ke)&&Ke>0?Math.round(Ke):null},Ae=_?Fe(k.likely):null,Xe=_?Fe(k.low):null,$e=_?Fe(k.high):null,Ye=_&&Ae;await l.mutateAsync({id:r.id,patch:{settings:{...f,priceOverride:{enabled:_,low:Xe,likely:Ae,high:$e,note:k.note||null},personalVideo:$},price_low:Ye?Xe??Ae:Ce.low??null,price_likely:Ye?Ae:Ce.likely??null,price_high:Ye?$e??Ae:Ce.high??null,status:Ge?"shared":r.status}}),await c.mutateAsync({cmaId:r.id,comps:h}),n({title:Ge?"CMA published":"CMA saved"})},xe=r?`https://cma.relevelup.com/${r.share_token}`:"";if(a||!r)return e.jsx(Qs,{children:e.jsx("div",{className:"p-6",children:e.jsx(us,{className:"w-6 h-6 animate-spin"})})});const ve=h.filter(Ge=>Ge.selected).length,ge=!((be=r.subject)!=null&&be.bedrooms)||!((Se=r.subject)!=null&&Se.bathrooms)||!((Ie=r.subject)!=null&&Ie.sqft)||!((Me=r.subject)!=null&&Me.yearBuilt);return e.jsx(Qs,{children:e.jsxs("div",{className:"container mx-auto p-4 md:p-6 max-w-7xl",children:[e.jsxs("div",{className:"flex items-center justify-between mb-4 gap-2 flex-wrap",children:[e.jsxs(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:()=>he(!1),disabled:l.isPending,children:[e.jsx(Kl,{className:"w-4 h-4 mr-1"}),"Save"]}),e.jsxs(B,{onClick:()=>he(!0),disabled:l.isPending,children:[e.jsx(Md,{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(xe),n({title:"Link copied"})},children:[e.jsx(Tr,{className:"w-4 h-4 mr-1"}),"Copy Link"]}),e.jsxs(B,{onClick:()=>P(!0),children:[e.jsx(mn,{className:"w-4 h-4 mr-1"}),"Send to Contact"]})]})]})]}),e.jsxs("div",{className:"grid lg:grid-cols-3 gap-4",children:[e.jsxs("div",{className:"lg:col-span-1 space-y-4",children:[e.jsxs(_e,{children:[e.jsx(zt,{children:e.jsx(qt,{className:"text-base",children:"Subject Property"})}),e.jsxs(De,{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:"})," ",((Re=r.subject.sqft)==null?void 0:Re.toLocaleString())??"—"]}),e.jsxs("div",{children:[e.jsx("span",{className:"text-muted-foreground",children:"Year:"})," ",r.subject.yearBuilt??"—"]})]}),ge&&e.jsxs("div",{className:"rounded-lg border border-amber-200 bg-amber-50 p-3 text-amber-950 space-y-2",children:[e.jsx("p",{className:"font-medium",children:"No panic — we can still build this."}),e.jsx("p",{className:"text-xs leading-relaxed",children:"If the MLS/feed does not return beds, baths, sqft, or year, add them manually and LevelUp will use them for comps and pricing."}),e.jsxs(B,{size:"sm",variant:"outline",className:"bg-white",onClick:()=>M(!0),children:[e.jsx(Ja,{className:"w-3.5 h-3.5 mr-1"}),"Fill in property details"]})]}),!ge&&e.jsxs(B,{size:"sm",variant:"ghost",className:"px-0",onClick:()=>M(!0),children:[e.jsx(Ja,{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(re,{className:"text-xs",children:"Subject SqFt (needed for price band)"}),e.jsx(we,{type:"number",defaultValue:"",onBlur:async Ge=>{const Ce=Number(Ge.target.value);Ce>0&&await l.mutateAsync({id:r.id,patch:{subject:{...r.subject,sqft:Ce}}})}})]})]})]}),e.jsxs(_e,{children:[e.jsx(zt,{children:e.jsxs(qt,{className:"text-base flex items-center gap-2",children:[e.jsx(u5,{className:"w-4 h-4"}),"Suggested Price"]})}),e.jsxs(De,{className:"space-y-3",children:[te!=null&&te.likely?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"text-3xl font-bold",children:["$",(_&&Number(k.likely)>0?Number(k.likely):te.likely).toLocaleString()]}),e.jsxs("div",{className:"text-xs text-muted-foreground mt-1",children:["Comps suggest: $",(Be=te.low)==null?void 0:Be.toLocaleString()," – $",(Ne=te.high)==null?void 0:Ne.toLocaleString()]}),e.jsxs("div",{className:"text-xs text-muted-foreground",children:["$",te.ppsf,"/sqft median · ",ve," comps"]})]}):e.jsx("p",{className:"text-sm text-muted-foreground",children:"Add comps with sqft + price to see suggested pricing."}),e.jsxs("div",{className:"pt-3 border-t space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(re,{htmlFor:"override-toggle",className:"text-sm font-medium",children:"Override with my price"}),e.jsx(zn,{id:"override-toggle",checked:_,onCheckedChange:b})]}),_&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{children:[e.jsx(re,{className:"text-xs",children:"My suggested price"}),e.jsx(we,{type:"number",placeholder:"e.g. 750000",value:k.likely,onChange:Ge=>A(Ce=>({...Ce,likely:Ge.target.value}))})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[e.jsxs("div",{children:[e.jsx(re,{className:"text-xs",children:"Range low"}),e.jsx(we,{type:"number",placeholder:"optional",value:k.low,onChange:Ge=>A(Ce=>({...Ce,low:Ge.target.value}))})]}),e.jsxs("div",{children:[e.jsx(re,{className:"text-xs",children:"Range high"}),e.jsx(we,{type:"number",placeholder:"optional",value:k.high,onChange:Ge=>A(Ce=>({...Ce,high:Ge.target.value}))})]})]}),e.jsxs("div",{children:[e.jsx(re,{className:"text-xs",children:"Why this price (optional)"}),e.jsx(Ws,{rows:2,maxLength:500,placeholder:"Notes shown to your client",value:k.note,onChange:Ge=>A(Ce=>({...Ce,note:Ge.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(_xn,{value:$,onChange:V}),e.jsxs(_e,{children:[e.jsx(zt,{children:e.jsx(qt,{className:"text-base",children:"Filters"})}),e.jsxs(De,{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsxs(re,{className:"text-xs",children:["SqFt tolerance: ±",Math.round(f.sqftPct*100),"%"]}),e.jsx(qf,{value:[f.sqftPct*100],min:5,max:50,step:5,onValueChange:([Ge])=>g(Ce=>({...Ce,sqftPct:Ge/100}))})]}),e.jsxs("div",{children:[e.jsxs(re,{className:"text-xs",children:["Search radius: ",f.maxMiles," mi"]}),e.jsx(qf,{value:[f.maxMiles],min:1,max:25,step:1,onValueChange:([Ge])=>g(Ce=>({...Ce,maxMiles:Ge}))})]}),e.jsxs("div",{children:[e.jsxs(re,{className:"text-xs",children:["Sold within: ",f.monthsBack," months"]}),e.jsx(qf,{value:[f.monthsBack],min:1,max:24,step:1,onValueChange:([Ge])=>g(Ce=>({...Ce,monthsBack:Ge}))})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{className:"text-xs",children:"Status"}),["Active","Pending","Closed"].map(Ge=>e.jsxs("label",{className:"flex items-center gap-2 text-sm",children:[e.jsx(Bi,{checked:f.statuses.includes(Ge),onCheckedChange:Ce=>g(Fe=>({...Fe,statuses:Ce?[...Fe.statuses,Ge]:Fe.statuses.filter(Ae=>Ae!==Ge)}))})," ",Ge]},Ge))]}),e.jsxs(B,{className:"w-full",onClick:ne,disabled:o.isPending,children:[o.isPending?e.jsx(us,{className:"w-4 h-4 animate-spin mr-2"}):e.jsx(Cn,{className:"w-4 h-4 mr-2"}),"Find Comps"]}),e.jsxs(B,{variant:"outline",className:"w-full",onClick:()=>z(!0),children:[e.jsx(nn,{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(Tfn,{subject:r.subject,comps:h,radiusMiles:f.maxMiles,onMarkerClick:Ge=>x(Ge)}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("h2",{className:"text-lg font-semibold",children:["Comparables (",h.length,")"]}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:[ve," selected"]})]}),h.length?e.jsx("div",{className:"space-y-2",children:h.map((Ge,Ce)=>{var Fe;return e.jsx(_e,{className:Ge.selected?"":"opacity-50",children:e.jsxs(De,{className:"p-3 flex gap-3 items-center",children:[e.jsx(Bi,{checked:Ge.selected,onCheckedChange:()=>me(Ce)}),e.jsxs("button",{type:"button",onClick:()=>x(Ce),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(iNe,{photos:Ge.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:Ge.address}),e.jsxs("div",{className:"text-xs text-muted-foreground",children:[Ge.city,", ",Ge.state," · ",Ge.bedrooms??"?","bd/",Ge.bathrooms??"?","ba · ",((Fe=Ge.sqft)==null?void 0:Fe.toLocaleString())??"?"," sqft",Ge.yearBuilt?` · ${Ge.yearBuilt}`:""]}),e.jsxs("div",{className:"text-xs mt-0.5",children:[e.jsx(We,{variant:"outline",className:"mr-1",children:Ge.status}),Ge.score!=null&&e.jsxs("span",{className:"text-muted-foreground",children:["Score ",Ge.score]})]})]}),e.jsxs("div",{className:"text-right",children:[e.jsxs("div",{className:"font-semibold",children:["$",(Ge.soldPrice||Ge.price||0).toLocaleString()]}),Ge.sqft&&(Ge.soldPrice||Ge.price)?e.jsxs("div",{className:"text-xs text-muted-foreground",children:["$",Math.round((Ge.soldPrice||Ge.price)/Ge.sqft),"/sqft"]}):null]})]}),e.jsx(B,{variant:"ghost",size:"icon",onClick:()=>x(Ce),title:"View details",children:e.jsx(da,{className:"w-4 h-4"})}),e.jsx(B,{variant:"ghost",size:"icon",onClick:()=>ue(Ce),title:"Remove",children:e.jsx(qn,{className:"w-4 h-4"})})]})},Ce)})}):e.jsx(_e,{children:e.jsx(De,{className:"py-12 text-center text-muted-foreground",children:e.jsxs("div",{className:"max-w-md mx-auto space-y-3",children:[e.jsxs("p",{children:["Click ",e.jsx("strong",{children:"Find Comps"})," to auto-pull from your MLS."]}),e.jsx("p",{className:"text-sm",children:"If nothing comes back, you are not stuck — use LevelUp's fallback template: enter the subject details, add 2–3 known comps, then set your suggested price."}),e.jsxs("div",{className:"flex flex-wrap justify-center gap-2",children:[ge&&e.jsx(B,{variant:"outline",size:"sm",onClick:()=>M(!0),children:"Fill subject details"}),e.jsx(B,{variant:"outline",size:"sm",onClick:()=>z(!0),children:"Add manual comp"})]})]})})})]})]}),e.jsx(gSt,{comp:y!=null?h[y]:null,open:y!=null,onClose:()=>x(null)}),e.jsx(wxn,{open:I,onOpenChange:M,subject:r.subject,onSave:ce,isSaving:l.isPending}),e.jsx(jxn,{open:L,onOpenChange:z,subject:r.subject,onAdd:ae}),e.jsx(kIt,{open:T,onOpenChange:P,cma:r})]})})}const yE="listing-presentations";function ADt(){const{user:s}=Ls(),t=as(),n=mt({queryKey:["listing-presentation-saved-templates",s==null?void 0:s.id],enabled:!!s,queryFn:async()=>{const{data:o,error:c}=await H.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=_t({mutationFn:async o=>{const{data:c,error:d}=await H.from("listing_presentation_saved_templates").insert({...o,owner_user_id:s.id}).select().single();if(d)throw d;return c},onSuccess:()=>{r(),ie.success("Template saved")},onError:o=>ie.error(o.message||"Could not save the template")}),i=_t({mutationFn:async({id:o,...c})=>{const{error:d}=await H.from("listing_presentation_saved_templates").update(c).eq("id",o);if(d)throw d},onSuccess:()=>{r(),ie.success("Template updated")},onError:o=>ie.error(o.message||"Could not update the template")}),l=_t({mutationFn:async o=>{const{error:c}=await H.from("listing_presentation_saved_templates").delete().eq("id",o);if(c)throw c},onSuccess:()=>{r(),ie.success("Template deleted")},onError:o=>ie.error(o.message||"Could not delete the template")});return{savedTemplates:n.data??[],isLoading:n.isLoading,save:a,update:i,remove:l}}function kxn(){return mt({queryKey:["listing-presentation-templates"],staleTime:10*60*1e3,queryFn:async()=>{const{data:s,error:t}=await H.from("listing_presentation_templates").select("*").eq("is_active",!0).order("sort_order",{ascending:!0});if(t)throw t;return s}})}function TDt(){const{user:s}=Ls(),t=as(),n=mt({queryKey:["listing-presentations",s==null?void 0:s.id],enabled:!!s,queryFn:async()=>{const{data:c,error:d}=await H.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=_t({mutationFn:async c=>{const{data:d,error:u}=await H.from("listing_presentations").insert({...c,owner_user_id:s.id}).select().single();if(u)throw u;return d},onSuccess:r,onError:c=>ie.error(c.message||"Could not create presentation")}),i=_t({mutationFn:async({id:c,...d})=>{const{data:u,error:h}=await H.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=>ie.error(c.message||"Could not save presentation")}),l=_t({mutationFn:async c=>{let d=null;const{data:u,error:h}=await H.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 H.storage.from(yE).copy(c.property_photo_path,d);m||await H.from("listing_presentations").update({property_photo_path:d}).eq("id",u.id)}return u},onSuccess:()=>{r(),ie.success("Presentation duplicated")},onError:c=>ie.error(c.message||"Could not duplicate")}),o=_t({mutationFn:async c=>{const d=[c.property_photo_path,c.pdf_path,c.thumbnail_path].filter(Boolean);d.length&&await H.storage.from(yE).remove(d);const{error:u}=await H.from("listing_presentations").delete().eq("id",c.id);if(u)throw u},onSuccess:()=>{r(),ie.success("Presentation deleted")},onError:c=>ie.error(c.message||"Could not delete")});return{presentations:n.data??[],isLoading:n.isLoading,create:a,update:i,duplicate:l,remove:o}}function Sxn(s){return mt({queryKey:["listing-presentation",s],enabled:!!s,queryFn:async()=>{const{data:t,error:n}=await H.from("listing_presentations").select("*").eq("id",s).maybeSingle();if(n)throw n;return t}})}async function Cxn(s,t=3600){if(!s)return null;const{data:n,error:r}=await H.storage.from(yE).createSignedUrl(s,t);return r?null:(n==null?void 0:n.signedUrl)??null}const Axn="#2a4c64",Txn="#B8965A";function EDt(){const{user:s}=Ls();return mt({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([H.from("profiles").select("name, email, phone, avatar_url, website_url, title, brokerage_name, brokerage_id").eq("id",t).maybeSingle(),H.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),H.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 H.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||Axn,accentColor:o.accent_color||Txn,tagline:c.positioning_statement||i.title||c.title||null}}})}const C7e={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."}},Exn={cover:"Cover",welcome:"Marketing commitment",agent:"About your agent",overview:"Marketing plan overview",closing:"Closing commitment"};function MDt(s,t){var i;const n=((i=s==null?void 0:s.copy)==null?void 0:i[t])||{},r=C7e[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 LDt={enabled:!1,name:"",title:null,headshotUrl:null,phone:null,email:null,brokerageName:null,licenseNumber:null,bio:null};function PDt(s){return{...LDt,...s||{}}}const oPe=[{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."}],IDt=()=>typeof crypto<"u"&&"randomUUID"in crypto?crypto.randomUUID():`cp_${Math.random().toString(36).slice(2)}`;function cWe(s,t=0){const n={id:IDt(),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 DDt(s){return Array.isArray(s)?s.filter(t=>t&&typeof t=="object").map((t,n)=>({...cWe(t.layout||"story",n),...t,id:t.id||IDt(),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 A7e={hidden:["overview"]},T7e={x:.5,y:.5},_c=(s,t,n=!0)=>({key:s,label:t,enabled:n}),S5e=[{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:[_c("hdr","Full HDR interior and exterior photo set"),_c("drone","Aerial drone photography of the home and lot"),_c("twilight","Twilight exterior session for the hero image"),_c("staging","Virtual staging for vacant or transitional rooms",!1),_c("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:[_c("walkthrough","Cinematic full-property walkthrough video"),_c("reels","Vertical short-form cuts for Reels, Shorts, and TikTok"),_c("oncamera","On-camera agent introduction to the home"),_c("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:[_c("data","Complete, accurate MLS data so your home shows in every filter"),_c("copy","Copywriting that leads with the features buyers pay for"),_c("pricing","Pricing built on live comparable and absorption data"),_c("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:[_c("zillow","Zillow — the highest-traffic buyer search portal"),_c("realtor","Realtor.com — direct MLS-sourced listing feed"),_c("homes","Homes.com — agent-attributed listing exposure"),_c("others","Redfin, Trulia, Movoto, and hundreds of partner sites"),_c("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:[_c("gallery","Full-screen gallery, video, and floor plan in one place"),_c("mobile","Mobile-first design with a one-tap inquiry form"),_c("link","Shareable link used across ads, email, and QR signage"),_c("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:[_c("organic","Just-listed launch across feed, stories, and reels"),_c("ads","Geo-targeted paid campaigns aimed at active buyers"),_c("retarget","Retargeting so interested viewers keep seeing your home"),_c("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:[_c("database","Direct email to my buyer and past-client database"),_c("agents","Broadcast to area agents with matching buyers"),_c("referral","Referral partner network notified at launch"),_c("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:[_c("public","Strategically timed public open houses"),_c("broker","Broker open house for agents with active buyers"),_c("signin","Digital sign-in that captures every visitor"),_c("neighbors","Neighbor invitations and just-listed mailers"),_c("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:[_c("weekly","Weekly seller report on the schedule you prefer"),_c("feedback","Showing feedback delivered as it comes in"),_c("analytics","Online traffic and engagement analytics"),_c("access","Direct access to me by call, text, or email")]}],Mxn=Object.fromEntries(S5e.map(s=>[s.key,(s.options||[]).map(t=>t.label)]));function E7e(s){return s!=null&&s.length?S5e.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}}):S5e.map(t=>{var n;return{...t,options:(n=t.options)==null?void 0:n.map(r=>({...r}))}})}const Lxn={welcome:"Marketing commitment",agent:"About your agent",overview:"Marketing plan overview",closing:"Closing commitment"};function Vu(s){"@babel/helpers - typeof";return Vu=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},Vu(s)}var pN=Uint8Array,k_=Uint16Array,dWe=Int32Array,uWe=new pN([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]),hWe=new pN([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]),Tmt=new pN([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),RDt=function(s,t){for(var n=new k_(31),r=0;r<31;++r)n[r]=t+=1<>1|(om&21845)<<1;kC=(kC&52428)>>2|(kC&13107)<<2,kC=(kC&61680)>>4|(kC&3855)<<4,L7e[om]=((kC&65280)>>8|(kC&255)<<8)>>1}var kK=function(s,t,n){for(var r=s.length,a=0,i=new k_(t);a>c]=d}else for(o=new k_(r),a=0;a>15-s[a]);return o},wR=new pN(288);for(var om=0;om<144;++om)wR[om]=8;for(var om=144;om<256;++om)wR[om]=9;for(var om=256;om<280;++om)wR[om]=7;for(var om=280;om<288;++om)wR[om]=8;var C5e=new pN(32);for(var om=0;om<32;++om)C5e[om]=5;var Dxn=kK(wR,9,0),Rxn=kK(C5e,5,0),FDt=function(s){return(s+7)/8|0},Oxn=function(s,t,n){return(n==null||n>s.length)&&(n=s.length),new pN(s.subarray(t,n))},BS=function(s,t,n){n<<=t&7;var r=t/8|0;s[r]|=n,s[r+1]|=n>>8},aH=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},lPe=function(s,t){for(var n=[],r=0;rm&&(m=i[r].s);var f=new k_(m+1),g=P7e(n[u-1],f,0);if(g>t){var r=0,y=0,x=g-t,_=1<t)y+=_-(1<>=x;y>0;){var k=i[r].s;f[k]=0&&y;--r){var A=i[r].s;f[A]==t&&(--f[A],++y)}g=t}return{t:new pN(f),l:g}},P7e=function(s,t,n){return s.s==-1?Math.max(P7e(s.l,t,n+1),P7e(s.r,t,n+1)):t[s.s]=n},Mmt=function(s){for(var t=s.length;t&&!s[--t];);for(var n=new k_(++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}},iH=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&&!z[Tmt[V-1]];--V);var W=d+5<<3,G=iH(a,wR)+iH(i,C5e)+l,X=iH(a,m)+iH(i,y)+l+14+3*V+iH(I,z)+2*I[16]+3*I[17]+7*I[18];if(c>=0&&W<=G&&W<=X)return zDt(t,u,s.subarray(c,c+d));var te,ne,me,ue;if(BS(t,u,1+(X15&&(BS(t,u,xe[M]>>5&127),u+=xe[M]>>12)}}else te=Dxn,ne=wR,me=Rxn,ue=C5e;for(var M=0;M255){var ve=ge>>18&31;aH(t,u,te[ve+257]),u+=ne[ve+257],ve>7&&(BS(t,u,ge>>23&31),u+=uWe[ve]);var be=ge&31;aH(t,u,me[be]),u+=ue[be],be>3&&(aH(t,u,ge>>5&8191),u+=hWe[be])}else aH(t,u,te[ge]),u+=ne[ge]}return aH(t,u,te[256]),u+ne[256]},Fxn=new dWe([65540,131080,131088,131104,262176,1048704,1048832,2114560,2117632]),BDt=new pN(0),zxn=function(s,t,n,r,a,i){var l=i.z||s.length,o=new pN(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=Fxn[t-1],m=h>>13,f=h&8191,g=(1<7e3||z>24576)&&(te>423||!d)){u=Lmt(s,c,0,A,T,P,M,z,V,L-V,u),z=I=M=0,V=L;for(var ne=0;ne<286;++ne)T[ne]=0;for(var ne=0;ne<30;++ne)P[ne]=0}var me=2,ue=0,ce=f,ae=G-X&32767;if(te>2&&W==k(L-ae))for(var he=Math.min(m,te)-1,xe=Math.min(32767,L),ve=Math.min(258,te);ae<=xe&&--ce&&G!=X;){if(s[L+me]==s[L+me-ae]){for(var ge=0;geme){if(me=ge,ue=ae,ge>he)break;for(var be=Math.min(ae,ge-2),Se=0,ne=0;neSe&&(Se=Re,X=Ie)}}}G=X,X=y[G],ae+=G-X&32767}if(ue){A[z++]=268435456|M7e[me]<<18|Emt[ue];var Be=M7e[me]&31,Ne=Emt[ue]&31;M+=uWe[Be]+hWe[Ne],++T[257+Be],++P[Ne],$=L+me,++I}else A[z++]=s[L],++T[s[L]]}}for(L=Math.max(L,$);L=l&&(c[u/8|0]=d,Ge=l),u=zDt(c,u+1,s.subarray(L,Ge))}i.i=l}return Oxn(o,0,r+FDt(u)+a)},$Dt=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}}},Bxn=function(s,t,n,r,a){if(!a&&(a={l:1},t.dictionary)){var i=t.dictionary.subarray(-32768),l=new pN(i.length+s.length);l.set(i),l.set(s,i.length),s=l,a.w=i.length}return zxn(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)},UDt=function(s,t,n){for(;n;++t)s[t]=n,n>>>=8},$xn=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=$Dt();a.p(t.dictionary),UDt(s,2,a.d())}};function I7e(s,t){t||(t={});var n=$Dt();n.p(s);var r=Bxn(s,t,t.dictionary?6:2,4);return $xn(r,t),UDt(r,r.length-4,n.d()),r}var Uxn=typeof TextDecoder<"u"&&new TextDecoder,qxn=0;try{Uxn.decode(BDt,{stream:!0}),qxn=1}catch{}function Vxn(s){if(Array.isArray(s))return s}function Hxn(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 Pmt(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])})(),cPe={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 mWe{constructor(t=Zxn,n={}){jr(this,"buffer");jr(this,"byteLength");jr(this,"byteOffset");jr(this,"length");jr(this,"offset");jr(this,"lastWrittenByte");jr(this,"littleEndian");jr(this,"_data");jr(this,"_mark");jr(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 mWe)&&(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=cPe[n].BYTES_PER_ELEMENT*t,a=this.byteOffset+this.offset,i=this.buffer.slice(a,a+r);if(this.littleEndian===Xxn&&n!=="uint8"&&n!=="int8"){const o=new Uint8Array(this.buffer.slice(a,a+r));o.reverse();const c=new cPe[n](o.buffer);return this.offset+=r,c.reverse(),c}const l=new cPe[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 Qxn=4,Rmt=0,Omt=1,Jxn=2;function nq(s){let t=s.length;for(;--t>=0;)s[t]=0}const e0n=0,qDt=1,t0n=2,s0n=3,n0n=258,pWe=29,jJ=256,kZ=jJ+1+pWe,sz=30,fWe=19,VDt=2*kZ+1,HI=15,dPe=16,r0n=7,gWe=256,HDt=16,GDt=17,WDt=18,D7e=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]),sje=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]),a0n=new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7]),KDt=new Uint8Array([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),i0n=512,u4=new Array((kZ+2)*2);nq(u4);const SK=new Array(sz*2);nq(SK);const SZ=new Array(i0n);nq(SZ);const CZ=new Array(n0n-s0n+1);nq(CZ);const xWe=new Array(pWe);nq(xWe);const A5e=new Array(sz);nq(A5e);function uPe(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 YDt,ZDt,XDt;function hPe(s,t){this.dyn_tree=s,this.max_code=0,this.stat_desc=t}const QDt=s=>s<256?SZ[s]:SZ[256+(s>>>7)],AZ=(s,t)=>{s.pending_buf[s.pending++]=t&255,s.pending_buf[s.pending++]=t>>>8&255},Z1=(s,t,n)=>{s.bi_valid>dPe-n?(s.bi_buf|=t<>dPe-s.bi_valid,s.bi_valid+=n-dPe):(s.bi_buf|=t<{Z1(s,n[t*2],n[t*2+1])},JDt=(s,t)=>{let n=0;do n|=s&1,s>>>=1,n<<=1;while(--t>0);return n>>>1},o0n=s=>{s.bi_valid===16?(AZ(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)},l0n=(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,f,g,y=0;for(m=0;m<=HI;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]++,f=0,u>=o&&(f=l[u-o]),g=n[u*2],s.opt_len+=g*(m+f),i&&(s.static_len+=g*(a[u*2+1]+f)));if(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--)}},eRt=(s,t,n)=>{const r=new Array(HI+1);let a=0,i,l;for(i=1;i<=HI;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]=JDt(r[o]++,o))}},c0n=()=>{let s,t,n,r,a;const i=new Array(HI+1);for(n=0,r=0;r>=7;r{let t;for(t=0;t{s.bi_valid>8?AZ(s,s.bi_buf):s.bi_valid>0&&(s.pending_buf[s.pending++]=s.bi_buf),s.bi_buf=0,s.bi_valid=0},Fmt=(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?Zk(s,a,t):(l=CZ[a],Zk(s,l+jJ+1,t),o=D7e[l],o!==0&&(a-=xWe[l],Z1(s,a,o)),r--,l=QDt(r),Zk(s,l,n),o=sje[l],o!==0&&(r-=A5e[l],Z1(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=VDt,l=0;l>1;l>=1;l--)mPe(s,n,l);d=i;do l=s.heap[1],s.heap[1]=s.heap[s.heap_len--],mPe(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++,mPe(s,n,1);while(s.heap_len>=2);s.heap[--s.heap_max]=s.heap[1],l0n(s,t),eRt(n,c,s.bl_count)},Bmt=(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(Bmt(s,s.dyn_ltree,s.l_desc.max_code),Bmt(s,s.dyn_dtree,s.d_desc.max_code),R7e(s,s.bl_desc),t=fWe-1;t>=3&&s.bl_tree[KDt[t]*2+1]===0;t--);return s.opt_len+=3*(t+1)+5+5+4,t},u0n=(s,t,n,r)=>{let a;for(Z1(s,t-257,5),Z1(s,n-1,5),Z1(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 Rmt;if(s.dyn_ltree[9*2]!==0||s.dyn_ltree[10*2]!==0||s.dyn_ltree[13*2]!==0)return Omt;for(n=32;n{Umt||(c0n(),Umt=!0),s.l_desc=new hPe(s.dyn_ltree,YDt),s.d_desc=new hPe(s.dyn_dtree,ZDt),s.bl_desc=new hPe(s.bl_tree,XDt),s.bi_buf=0,s.bi_valid=0,tRt(s)},nRt=(s,t,n,r)=>{Z1(s,(e0n<<1)+(r?1:0),3),sRt(s),AZ(s,n),AZ(s,~n),n&&s.pending_buf.set(s.window.subarray(t,t+n),s.pending),s.pending+=n},p0n=s=>{Z1(s,qDt<<1,3),Zk(s,gWe,u4),o0n(s)},f0n=(s,t,n,r)=>{let a,i,l=0;s.level>0?(s.strm.data_type===Jxn&&(s.strm.data_type=h0n(s)),R7e(s,s.l_desc),R7e(s,s.d_desc),l=d0n(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?nRt(s,t,n,r):s.strategy===Qxn||i===a?(Z1(s,(qDt<<1)+(r?1:0),3),zmt(s,u4,SK)):(Z1(s,(t0n<<1)+(r?1:0),3),u0n(s,s.l_desc.max_code+1,s.d_desc.max_code+1,l+1),zmt(s,s.dyn_ltree,s.dyn_dtree)),tRt(s),r&&sRt(s)},g0n=(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[(CZ[n]+jJ+1)*2]++,s.dyn_dtree[QDt(t)*2]++),s.sym_next===s.sym_end);var x0n=m0n,y0n=nRt,v0n=f0n,b0n=g0n,_0n=p0n,w0n={_tr_init:x0n,_tr_stored_block:y0n,_tr_flush_block:v0n,_tr_tally:b0n,_tr_align:_0n};const j0n=(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 TZ=j0n;const N0n=()=>{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},k0n=new Uint32Array(N0n()),S0n=(s,t,n,r)=>{const a=k0n,i=r+n;s^=-1;for(let l=r;l>>8^a[(s^t[l])&255];return s^-1};var Ox=S0n,D$={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"},NJ={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:C0n,_tr_stored_block:O7e,_tr_flush_block:A0n,_tr_tally:QT,_tr_align:T0n}=w0n,{Z_NO_FLUSH:JT,Z_PARTIAL_FLUSH:E0n,Z_FULL_FLUSH:M0n,Z_FINISH:Qw,Z_BLOCK:qmt,Z_OK:T0,Z_STREAM_END:Vmt,Z_STREAM_ERROR:k5,Z_DATA_ERROR:L0n,Z_BUF_ERROR:pPe,Z_DEFAULT_COMPRESSION:P0n,Z_FILTERED:I0n,Z_HUFFMAN_ONLY:une,Z_RLE:D0n,Z_FIXED:R0n,Z_DEFAULT_STRATEGY:O0n,Z_UNKNOWN:F0n,Z_DEFLATED:pAe}=NJ,z0n=9,B0n=15,$0n=8,U0n=29,q0n=256,F7e=q0n+1+U0n,V0n=30,H0n=19,G0n=2*F7e+1,W0n=15,id=3,uT=258,S5=uT+id+1,K0n=32,R$=42,yWe=57,z7e=69,B7e=73,$7e=91,U7e=103,GI=113,rG=666,Uv=1,rq=2,jR=3,aq=4,Y0n=3,WI=(s,t)=>(s.msg=D$[t],t),Hmt=s=>s*2-(s>4?9:0),gA=s=>{let t=s.length;for(;--t>=0;)s[t]=0},Z0n=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 X0n=(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))},S_=(s,t)=>{A0n(s,s.block_start>=0?s.block_start:-1,s.strstart-s.block_start,t),s.block_start=s.strstart,Jb(s.strm)},eu=(s,t)=>{s.pending_buf[s.pending++]=t},oH=(s,t)=>{s.pending_buf[s.pending++]=t>>>8&255,s.pending_buf[s.pending++]=t&255},q7e=(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=TZ(s.adler,t,a,n):s.state.wrap===2&&(s.adler=Ox(s.adler,t,a,n)),s.next_in+=a,s.total_in+=a,a)},rRt=(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-S5?s.strstart-(s.w_size-S5):0,d=s.window,u=s.w_mask,h=s.prev,m=s.strstart+uT;let f=d[r+l-1],g=d[r+l];s.prev_length>=s.good_match&&(n>>=2),o>s.lookahead&&(o=s.lookahead);do if(a=t,!(d[a+l]!==g||d[a+l-1]!==f||d[a]!==d[r]||d[++a]!==d[r+1])){r+=2,a++;do;while(d[++r]===d[++a]&&d[++r]===d[++a]&&d[++r]===d[++a]&&d[++r]===d[++a]&&d[++r]===d[++a]&&d[++r]===d[++a]&&d[++r]===d[++a]&&d[++r]===d[++a]&&rl){if(s.match_start=t,l=i,i>=o)break;f=d[r+l-1],g=d[r+l]}}while((t=h[t&u])>c&&--n!==0);return l<=s.lookahead?l:s.lookahead},O$=s=>{const t=s.w_size;let n,r,a;do{if(r=s.window_size-s.lookahead-s.strstart,s.strstart>=t+(t-S5)&&(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),Z0n(s),r+=t),s.strm.avail_in===0)break;if(n=q7e(s.strm,s.window,s.strstart+s.lookahead,r),s.lookahead+=n,s.lookahead+s.insert>=id)for(a=s.strstart-s.insert,s.ins_h=s.window[a],s.ins_h=eE(s,s.ins_h,s.window[a+1]);s.insert&&(s.ins_h=eE(s,s.ins_h,s.window[a+id-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,Jb(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&&(q7e(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&&(q7e(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===Qw)&&t!==JT&&s.strm.avail_in===0&&a<=i)&&(r=a>i?i:a,l=t===Qw&&s.strm.avail_in===0&&r===a?1:0,O7e(s,s.block_start,r,l),s.block_start+=r,Jb(s.strm)),l?jR:Uv)},fPe=(s,t)=>{let n,r;for(;;){if(s.lookahead=id&&(s.ins_h=eE(s,s.ins_h,s.window[s.strstart+id-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-S5&&(s.match_length=rRt(s,n)),s.match_length>=id)if(r=QT(s,s.strstart-s.match_start,s.match_length-id),s.lookahead-=s.match_length,s.match_length<=s.max_lazy_match&&s.lookahead>=id){s.match_length--;do s.strstart++,s.ins_h=eE(s,s.ins_h,s.window[s.strstart+id-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=eE(s,s.ins_h,s.window[s.strstart+1]);else r=QT(s,0,s.window[s.strstart]),s.lookahead--,s.strstart++;if(r&&(S_(s,!1),s.strm.avail_out===0))return Uv}return s.insert=s.strstart{let n,r,a;for(;;){if(s.lookahead=id&&(s.ins_h=eE(s,s.ins_h,s.window[s.strstart+id-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=id-1,n!==0&&s.prev_length4096)&&(s.match_length=id-1)),s.prev_length>=id&&s.match_length<=s.prev_length){a=s.strstart+s.lookahead-id,r=QT(s,s.strstart-1-s.prev_match,s.prev_length-id),s.lookahead-=s.prev_length-1,s.prev_length-=2;do++s.strstart<=a&&(s.ins_h=eE(s,s.ins_h,s.window[s.strstart+id-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=id-1,s.strstart++,r&&(S_(s,!1),s.strm.avail_out===0))return Uv}else if(s.match_available){if(r=QT(s,0,s.window[s.strstart-1]),r&&S_(s,!1),s.strstart++,s.lookahead--,s.strm.avail_out===0)return Uv}else s.match_available=1,s.strstart++,s.lookahead--}return s.match_available&&(r=QT(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<=uT){if(O$(s),s.lookahead<=uT&&t===JT)return Uv;if(s.lookahead===0)break}if(s.match_length=0,s.lookahead>=id&&s.strstart>0&&(a=s.strstart-1,r=l[a],r===l[++a]&&r===l[++a]&&r===l[++a])){i=s.strstart+uT;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>=id?(n=QT(s,1,s.match_length-id),s.lookahead-=s.match_length,s.strstart+=s.match_length,s.match_length=0):(n=QT(s,0,s.window[s.strstart]),s.lookahead--,s.strstart++),n&&(S_(s,!1),s.strm.avail_out===0))return Uv}return s.insert=0,t===Qw?(S_(s,!0),s.strm.avail_out===0?jR:aq):s.sym_next&&(S_(s,!1),s.strm.avail_out===0)?Uv:rq},J0n=(s,t)=>{let n;for(;;){if(s.lookahead===0&&(O$(s),s.lookahead===0)){if(t===JT)return Uv;break}if(s.match_length=0,n=QT(s,0,s.window[s.strstart]),s.lookahead--,s.strstart++,n&&(S_(s,!1),s.strm.avail_out===0))return Uv}return s.insert=0,t===Qw?(S_(s,!0),s.strm.avail_out===0?jR:aq):s.sym_next&&(S_(s,!1),s.strm.avail_out===0)?Uv:rq};function rk(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 aG=[new rk(0,0,0,0,aRt),new rk(4,4,8,4,fPe),new rk(4,5,16,8,fPe),new rk(4,6,32,32,fPe),new rk(4,4,16,16,MF),new rk(8,16,32,32,MF),new rk(8,16,128,128,MF),new rk(8,32,128,256,MF),new rk(32,128,258,1024,MF),new rk(32,258,258,4096,MF)],eyn=s=>{s.window_size=2*s.w_size,gA(s.head),s.max_lazy_match=aG[s.level].max_lazy,s.good_match=aG[s.level].good_length,s.nice_match=aG[s.level].nice_length,s.max_chain_length=aG[s.level].max_chain,s.strstart=0,s.block_start=0,s.lookahead=0,s.insert=0,s.match_length=s.prev_length=id-1,s.match_available=0,s.ins_h=0};function tyn(){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=pAe,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(G0n*2),this.dyn_dtree=new Uint16Array((2*V0n+1)*2),this.bl_tree=new Uint16Array((2*H0n+1)*2),gA(this.dyn_ltree),gA(this.dyn_dtree),gA(this.bl_tree),this.l_desc=null,this.d_desc=null,this.bl_desc=null,this.bl_count=new Uint16Array(W0n+1),this.heap=new Uint16Array(2*F7e+1),gA(this.heap),this.heap_len=0,this.heap_max=0,this.depth=new Uint16Array(2*F7e+1),gA(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 kJ=s=>{if(!s)return 1;const t=s.state;return!t||t.strm!==s||t.status!==R$&&t.status!==yWe&&t.status!==z7e&&t.status!==B7e&&t.status!==$7e&&t.status!==U7e&&t.status!==GI&&t.status!==rG?1:0},iRt=s=>{if(kJ(s))return WI(s,k5);s.total_in=s.total_out=0,s.data_type=F0n;const t=s.state;return t.pending=0,t.pending_out=0,t.wrap<0&&(t.wrap=-t.wrap),t.status=t.wrap===2?yWe:t.wrap?R$:GI,s.adler=t.wrap===2?0:1,t.last_flush=-2,C0n(t),T0},oRt=s=>{const t=iRt(s);return t===T0&&eyn(s.state),t},syn=(s,t)=>kJ(s)||s.state.wrap!==2?k5:(s.state.gzhead=t,T0),lRt=(s,t,n,r,a,i)=>{if(!s)return k5;let l=1;if(t===P0n&&(t=6),r<0?(l=0,r=-r):r>15&&(l=2,r-=16),a<1||a>z0n||n!==pAe||r<8||r>15||t<0||t>9||i<0||i>R0n||r===8&&l!==1)return WI(s,k5);r===8&&(r=9);const o=new tyn;return s.state=o,o.strm=s,o.status=R$,o.wrap=l,o.gzhead=null,o.w_bits=r,o.w_size=1<lRt(s,t,pAe,B0n,$0n,O0n),ryn=(s,t)=>{if(kJ(s)||t>qmt||t<0)return s?WI(s,k5):k5;const n=s.state;if(!s.output||s.avail_in!==0&&!s.input||n.status===rG&&t!==Qw)return WI(s,s.avail_out===0?pPe:k5);const r=n.last_flush;if(n.last_flush=t,n.pending!==0){if(Jb(s),s.avail_out===0)return n.last_flush=-1,T0}else if(s.avail_in===0&&Hmt(t)<=Hmt(r)&&t!==Qw)return WI(s,pPe);if(n.status===rG&&s.avail_in!==0)return WI(s,pPe);if(n.status===R$&&n.wrap===0&&(n.status=GI),n.status===R$){let a=pAe+(n.w_bits-8<<4)<<8,i=-1;if(n.strategy>=une||n.level<2?i=0:n.level<6?i=1:n.level===6?i=2:i=3,a|=i<<6,n.strstart!==0&&(a|=K0n),a+=31-a%31,oH(n,a),n.strstart!==0&&(oH(n,s.adler>>>16),oH(n,s.adler&65535)),s.adler=1,n.status=GI,Jb(s),n.pending!==0)return n.last_flush=-1,T0}if(n.status===yWe){if(s.adler=0,eu(n,31),eu(n,139),eu(n,8),n.gzhead)eu(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)),eu(n,n.gzhead.time&255),eu(n,n.gzhead.time>>8&255),eu(n,n.gzhead.time>>16&255),eu(n,n.gzhead.time>>24&255),eu(n,n.level===9?2:n.strategy>=une||n.level<2?4:0),eu(n,n.gzhead.os&255),n.gzhead.extra&&n.gzhead.extra.length&&(eu(n,n.gzhead.extra.length&255),eu(n,n.gzhead.extra.length>>8&255)),n.gzhead.hcrc&&(s.adler=Ox(s.adler,n.pending_buf,n.pending,0)),n.gzindex=0,n.status=z7e;else if(eu(n,0),eu(n,0),eu(n,0),eu(n,0),eu(n,0),eu(n,n.level===9?2:n.strategy>=une||n.level<2?4:0),eu(n,Y0n),n.status=GI,Jb(s),n.pending!==0)return n.last_flush=-1,T0}if(n.status===z7e){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=Ox(s.adler,n.pending_buf,n.pending-a,a)),n.gzindex+=o,Jb(s),n.pending!==0)return n.last_flush=-1,T0;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=Ox(s.adler,n.pending_buf,n.pending-a,a)),n.gzindex=0}n.status=B7e}if(n.status===B7e){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=Ox(s.adler,n.pending_buf,n.pending-a,a)),Jb(s),n.pending!==0)return n.last_flush=-1,T0;a=0}n.gzindexa&&(s.adler=Ox(s.adler,n.pending_buf,n.pending-a,a)),n.gzindex=0}n.status=$7e}if(n.status===$7e){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=Ox(s.adler,n.pending_buf,n.pending-a,a)),Jb(s),n.pending!==0)return n.last_flush=-1,T0;a=0}n.gzindexa&&(s.adler=Ox(s.adler,n.pending_buf,n.pending-a,a))}n.status=U7e}if(n.status===U7e){if(n.gzhead.hcrc){if(n.pending+2>n.pending_buf_size&&(Jb(s),n.pending!==0))return n.last_flush=-1,T0;eu(n,s.adler&255),eu(n,s.adler>>8&255),s.adler=0}if(n.status=GI,Jb(s),n.pending!==0)return n.last_flush=-1,T0}if(s.avail_in!==0||n.lookahead!==0||t!==JT&&n.status!==rG){let a=n.level===0?aRt(n,t):n.strategy===une?J0n(n,t):n.strategy===D0n?Q0n(n,t):aG[n.level].func(n,t);if((a===jR||a===aq)&&(n.status=rG),a===Uv||a===jR)return s.avail_out===0&&(n.last_flush=-1),T0;if(a===rq&&(t===E0n?T0n(n):t!==qmt&&(O7e(n,0,0,!1),t===M0n&&(gA(n.head),n.lookahead===0&&(n.strstart=0,n.block_start=0,n.insert=0))),Jb(s),s.avail_out===0))return n.last_flush=-1,T0}return t!==Qw?T0:n.wrap<=0?Vmt:(n.wrap===2?(eu(n,s.adler&255),eu(n,s.adler>>8&255),eu(n,s.adler>>16&255),eu(n,s.adler>>24&255),eu(n,s.total_in&255),eu(n,s.total_in>>8&255),eu(n,s.total_in>>16&255),eu(n,s.total_in>>24&255)):(oH(n,s.adler>>>16),oH(n,s.adler&65535)),Jb(s),n.wrap>0&&(n.wrap=-n.wrap),n.pending!==0?T0:Vmt)},ayn=s=>{if(kJ(s))return k5;const t=s.state.status;return s.state=null,t===GI?WI(s,L0n):T0},iyn=(s,t)=>{let n=t.length;if(kJ(s))return k5;const r=s.state,a=r.wrap;if(a===2||a===1&&r.status!==R$||r.lookahead)return k5;if(a===1&&(s.adler=TZ(s.adler,t,n,0)),r.wrap=0,n>=r.w_size){a===0&&(gA(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,O$(r);r.lookahead>=id;){let c=r.strstart,d=r.lookahead-(id-1);do r.ins_h=eE(r,r.ins_h,r.window[c+id-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=id-1,O$(r)}return r.strstart+=r.lookahead,r.block_start=r.strstart,r.insert=r.lookahead,r.lookahead=0,r.match_length=r.prev_length=id-1,r.match_available=0,s.next_in=l,s.input=o,s.avail_in=i,r.wrap=a,T0};var oyn=nyn,lyn=lRt,cyn=oRt,dyn=iRt,uyn=syn,hyn=ryn,myn=ayn,pyn=iyn,fyn="pako deflate (from Nodeca project)",CK={deflateInit:oyn,deflateInit2:lyn,deflateReset:cyn,deflateResetKeep:dyn,deflateSetHeader:uyn,deflate:hyn,deflateEnd:myn,deflateSetDictionary:pyn,deflateInfo:fyn};const gyn=(s,t)=>Object.prototype.hasOwnProperty.call(s,t);var xyn=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)gyn(n,r)&&(s[r]=n[r])}}return s},yyn=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;EZ[254]=EZ[254]=1;var vyn=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 byn=(s,t)=>{if(t<65534&&s.subarray&&cRt)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 byn(i,a)},wyn=(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+EZ[s[n]]>t?n:t},MZ={string2buf:vyn,buf2string:_yn,utf8border:wyn};function jyn(){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 dRt=jyn;const uRt=Object.prototype.toString,{Z_NO_FLUSH:Nyn,Z_SYNC_FLUSH:kyn,Z_FULL_FLUSH:Syn,Z_FINISH:Cyn,Z_OK:T5e,Z_STREAM_END:Ayn,Z_DEFAULT_COMPRESSION:Tyn,Z_DEFAULT_STRATEGY:Eyn,Z_DEFLATED:Myn}=NJ;function vWe(s){this.options=fAe.assign({level:Tyn,method:Myn,chunkSize:16384,windowBits:15,memLevel:8,strategy:Eyn},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 dRt,this.strm.avail_out=0;let n=CK.deflateInit2(this.strm,t.level,t.method,t.windowBits,t.memLevel,t.strategy);if(n!==T5e)throw new Error(D$[n]);if(t.header&&CK.deflateSetHeader(this.strm,t.header),t.dictionary){let r;if(typeof t.dictionary=="string"?r=MZ.string2buf(t.dictionary):uRt.call(t.dictionary)==="[object ArrayBuffer]"?r=new Uint8Array(t.dictionary):r=t.dictionary,n=CK.deflateSetDictionary(this.strm,r),n!==T5e)throw new Error(D$[n]);this._dict_set=!0}}vWe.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?Cyn:Nyn,typeof s=="string"?n.input=MZ.string2buf(s):uRt.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===kyn||i===Syn)&&n.avail_out<=6){this.onData(n.output.subarray(0,n.next_out)),n.avail_out=0;continue}if(a=CK.deflate(n,i),a===Ayn)return n.next_out>0&&this.onData(n.output.subarray(0,n.next_out)),a=CK.deflateEnd(this.strm),this.onEnd(a),this.ended=!0,a===T5e;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};vWe.prototype.onData=function(s){this.chunks.push(s)};vWe.prototype.onEnd=function(s){s===T5e&&(this.result=fAe.flattenChunks(this.chunks)),this.chunks=[],this.err=s,this.msg=this.strm.msg};const hne=16209,Lyn=16191;var Pyn=function(t,n){let r,a,i,l,o,c,d,u,h,m,f,g,y,x,_,b,k,A,T,P,I,M,L,z;const $=t.state;r=t.next_in,L=t.input,a=r+(t.avail_in-5),i=t.next_out,z=t.output,l=i-(n-t.avail_out),o=i+(t.avail_out-257),c=$.dmax,d=$.wsize,u=$.whave,h=$.wnext,m=$.window,f=$.hold,g=$.bits,y=$.lencode,x=$.distcode,_=(1<<$.lenbits)-1,b=(1<<$.distbits)-1;e:do{g<15&&(f+=L[r++]<>>24,f>>>=A,g-=A,A=k>>>16&255,A===0)z[i++]=k&65535;else if(A&16){T=k&65535,A&=15,A&&(g>>=A,g-=A),g<15&&(f+=L[r++]<>>24,f>>>=A,g-=A,A=k>>>16&255,A&16){if(P=k&65535,A&=15,gc){t.msg="invalid distance too far back",$.mode=hne;break e}if(f>>>=A,g-=A,A=i-l,P>A){if(A=P-A,A>u&&$.sane){t.msg="invalid distance too far back",$.mode=hne;break e}if(I=0,M=m,h===0){if(I+=d-A,A2;)z[i++]=M[I++],z[i++]=M[I++],z[i++]=M[I++],T-=3;T&&(z[i++]=M[I++],T>1&&(z[i++]=M[I++]))}else{I=i-P;do z[i++]=z[I++],z[i++]=z[I++],z[i++]=z[I++],T-=3;while(T>2);T&&(z[i++]=z[I++],T>1&&(z[i++]=z[I++]))}}else if(A&64){t.msg="invalid distance code",$.mode=hne;break e}else{k=x[(k&65535)+(f&(1<>3,r-=T,g-=T<<3,f&=(1<{const c=o.bits;let d=0,u=0,h=0,m=0,f=0,g=0,y=0,x=0,_=0,b=0,k,A,T,P,I,M=null,L;const z=new Uint16Array(LF+1),$=new Uint16Array(LF+1);let V=null,W,G,X;for(d=0;d<=LF;d++)z[d]=0;for(u=0;u=1&&z[m]===0;m--);if(f>m&&(f=m),m===0)return a[i++]=1<<24|64<<16|0,a[i++]=1<<24|64<<16|0,o.bits=1,0;for(h=1;h0&&(s===Kmt||m!==1))return-1;for($[1]=0,d=1;dGmt||s===Ymt&&_>Wmt)return 1;for(;;){W=d-y,l[u]+1=L?(G=V[l[u]-L],X=M[l[u]-L]):(G=96,X=0),k=1<>y)+A]=W<<24|G<<16|X|0;while(A!==0);for(k=1<>=1;if(k!==0?(b&=k-1,b+=k):b=0,u++,--z[d]===0){if(d===m)break;d=t[n+l[u]]}if(d>f&&(b&P)!==T){for(y===0&&(y=f),I+=h,g=d-y,x=1<Gmt||s===Ymt&&_>Wmt)return 1;T=b&P,a[T]=f<<24|g<<16|I-i|0}}return b!==0&&(a[I+b]=d-y<<24|64<<16|0),o.bits=f,0};var AK=Fyn;const zyn=0,hRt=1,mRt=2,{Z_FINISH:Zmt,Z_BLOCK:Byn,Z_TREES:mne,Z_OK:NR,Z_STREAM_END:$yn,Z_NEED_DICT:Uyn,Z_STREAM_ERROR:Nj,Z_DATA_ERROR:pRt,Z_MEM_ERROR:fRt,Z_BUF_ERROR:qyn,Z_DEFLATED:Xmt}=NJ,gAe=16180,Qmt=16181,Jmt=16182,ept=16183,tpt=16184,spt=16185,npt=16186,rpt=16187,apt=16188,ipt=16189,E5e=16190,$S=16191,xPe=16192,opt=16193,yPe=16194,lpt=16195,cpt=16196,dpt=16197,upt=16198,pne=16199,fne=16200,hpt=16201,mpt=16202,ppt=16203,fpt=16204,gpt=16205,vPe=16206,xpt=16207,ypt=16208,Sm=16209,gRt=16210,xRt=16211,Vyn=852,Hyn=592,Gyn=15,Wyn=Gyn,vpt=s=>(s>>>24&255)+(s>>>8&65280)+((s&65280)<<8)+((s&255)<<24);function Kyn(){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 lO=s=>{if(!s)return 1;const t=s.state;return!t||t.strm!==s||t.modexRt?1:0},yRt=s=>{if(lO(s))return Nj;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=gAe,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(Vyn),t.distcode=t.distdyn=new Int32Array(Hyn),t.sane=1,t.back=-1,NR},vRt=s=>{if(lO(s))return Nj;const t=s.state;return t.wsize=0,t.whave=0,t.wnext=0,yRt(s)},bRt=(s,t)=>{let n;if(lO(s))return Nj;const r=s.state;return t<0?(n=0,t=-t):(n=(t>>4)+5,t<48&&(t&=15)),t&&(t<8||t>15)?Nj:(r.window!==null&&r.wbits!==t&&(r.window=null),r.wrap=n,r.wbits=t,vRt(s))},_Rt=(s,t)=>{if(!s)return Nj;const n=new Kyn;s.state=n,n.strm=s,n.window=null,n.mode=gAe;const r=bRt(s,t);return r!==NR&&(s.state=null),r},Yyn=s=>_Rt(s,Wyn);let bpt=!0,bPe,_Pe;const Zyn=s=>{if(bpt){bPe=new Int32Array(512),_Pe=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(AK(hRt,s.lens,0,288,bPe,0,s.work,{bits:9}),t=0;t<32;)s.lens[t++]=5;AK(mRt,s.lens,0,32,_Pe,0,s.work,{bits:5}),bpt=!1}s.lencode=bPe,s.lenbits=9,s.distcode=_Pe,s.distbits=5},wRt=(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,f,g,y,x=0,_,b,k,A,T,P,I,M;const L=new Uint8Array(4);let z,$;const V=new Uint8Array([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]);if(lO(s)||!s.output||!s.input&&s.avail_in!==0)return Nj;n=s.state,n.mode===$S&&(n.mode=xPe),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=NR;e:for(;;)switch(n.mode){case gAe:if(n.wrap===0){n.mode=xPe;break}for(;u<16;){if(o===0)break e;o--,d+=r[i++]<>>8&255,n.check=Ox(n.check,L,2,0),d=0,u=0,n.mode=Qmt;break}if(n.head&&(n.head.done=!1),!(n.wrap&1)||(((d&255)<<8)+(d>>8))%31){s.msg="incorrect header check",n.mode=Sm;break}if((d&15)!==Xmt){s.msg="unknown compression method",n.mode=Sm;break}if(d>>>=4,u-=4,I=(d&15)+8,n.wbits===0&&(n.wbits=I),I>15||I>n.wbits){s.msg="invalid window size",n.mode=Sm;break}n.dmax=1<>8&1),n.flags&512&&n.wrap&4&&(L[0]=d&255,L[1]=d>>>8&255,n.check=Ox(n.check,L,2,0)),d=0,u=0,n.mode=Jmt;case Jmt:for(;u<32;){if(o===0)break e;o--,d+=r[i++]<>>8&255,L[2]=d>>>16&255,L[3]=d>>>24&255,n.check=Ox(n.check,L,4,0)),d=0,u=0,n.mode=ept;case ept:for(;u<16;){if(o===0)break e;o--,d+=r[i++]<>8),n.flags&512&&n.wrap&4&&(L[0]=d&255,L[1]=d>>>8&255,n.check=Ox(n.check,L,2,0)),d=0,u=0,n.mode=tpt;case tpt:if(n.flags&1024){for(;u<16;){if(o===0)break e;o--,d+=r[i++]<>>8&255,n.check=Ox(n.check,L,2,0)),d=0,u=0}else n.head&&(n.head.extra=null);n.mode=spt;case spt:if(n.flags&1024&&(f=n.length,f>o&&(f=o),f&&(n.head&&(I=n.head.extra_len-n.length,n.head.extra||(n.head.extra=new Uint8Array(n.head.extra_len)),n.head.extra.set(r.subarray(i,i+f),I)),n.flags&512&&n.wrap&4&&(n.check=Ox(n.check,r,f,i)),o-=f,i+=f,n.length-=f),n.length))break e;n.length=0,n.mode=npt;case npt:if(n.flags&2048){if(o===0)break e;f=0;do I=r[i+f++],n.head&&I&&n.length<65536&&(n.head.name+=String.fromCharCode(I));while(I&&f>9&1,n.head.done=!0),s.adler=n.check=0,n.mode=$S;break;case ipt:for(;u<32;){if(o===0)break e;o--,d+=r[i++]<>>=u&7,u-=u&7,n.mode=vPe;break}for(;u<3;){if(o===0)break e;o--,d+=r[i++]<>>=1,u-=1,d&3){case 0:n.mode=opt;break;case 1:if(Zyn(n),n.mode=pne,t===mne){d>>>=2,u-=2;break e}break;case 2:n.mode=cpt;break;case 3:s.msg="invalid block type",n.mode=Sm}d>>>=2,u-=2;break;case opt: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=Sm;break}if(n.length=d&65535,d=0,u=0,n.mode=yPe,t===mne)break e;case yPe:n.mode=lpt;case lpt:if(f=n.length,f){if(f>o&&(f=o),f>c&&(f=c),f===0)break e;a.set(r.subarray(i,i+f),l),o-=f,i+=f,c-=f,l+=f,n.length-=f;break}n.mode=$S;break;case cpt: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=Sm;break}n.have=0,n.mode=dpt;case dpt:for(;n.have>>=3,u-=3}for(;n.have<19;)n.lens[V[n.have++]]=0;if(n.lencode=n.lendyn,n.lenbits=7,z={bits:n.lenbits},M=AK(zyn,n.lens,0,19,n.lencode,0,n.work,z),n.lenbits=z.bits,M){s.msg="invalid code lengths set",n.mode=Sm;break}n.have=0,n.mode=upt;case upt:for(;n.have>>24,b=x>>>16&255,k=x&65535,!(_<=u);){if(o===0)break e;o--,d+=r[i++]<>>=_,u-=_,n.lens[n.have++]=k;else{if(k===16){for($=_+2;u<$;){if(o===0)break e;o--,d+=r[i++]<>>=_,u-=_,n.have===0){s.msg="invalid bit length repeat",n.mode=Sm;break}I=n.lens[n.have-1],f=3+(d&3),d>>>=2,u-=2}else if(k===17){for($=_+3;u<$;){if(o===0)break e;o--,d+=r[i++]<>>=_,u-=_,I=0,f=3+(d&7),d>>>=3,u-=3}else{for($=_+7;u<$;){if(o===0)break e;o--,d+=r[i++]<>>=_,u-=_,I=0,f=11+(d&127),d>>>=7,u-=7}if(n.have+f>n.nlen+n.ndist){s.msg="invalid bit length repeat",n.mode=Sm;break}for(;f--;)n.lens[n.have++]=I}}if(n.mode===Sm)break;if(n.lens[256]===0){s.msg="invalid code -- missing end-of-block",n.mode=Sm;break}if(n.lenbits=9,z={bits:n.lenbits},M=AK(hRt,n.lens,0,n.nlen,n.lencode,0,n.work,z),n.lenbits=z.bits,M){s.msg="invalid literal/lengths set",n.mode=Sm;break}if(n.distbits=6,n.distcode=n.distdyn,z={bits:n.distbits},M=AK(mRt,n.lens,n.nlen,n.ndist,n.distcode,0,n.work,z),n.distbits=z.bits,M){s.msg="invalid distances set",n.mode=Sm;break}if(n.mode=pne,t===mne)break e;case pne:n.mode=fne;case fne: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===$S&&(n.back=-1);break}for(n.back=0;x=n.lencode[d&(1<>>24,b=x>>>16&255,k=x&65535,!(_<=u);){if(o===0)break e;o--,d+=r[i++]<>A)],_=x>>>24,b=x>>>16&255,k=x&65535,!(A+_<=u);){if(o===0)break e;o--,d+=r[i++]<>>=A,u-=A,n.back+=A}if(d>>>=_,u-=_,n.back+=_,n.length=k,b===0){n.mode=gpt;break}if(b&32){n.back=-1,n.mode=$S;break}if(b&64){s.msg="invalid literal/length code",n.mode=Sm;break}n.extra=b&15,n.mode=hpt;case hpt:if(n.extra){for($=n.extra;u<$;){if(o===0)break e;o--,d+=r[i++]<>>=n.extra,u-=n.extra,n.back+=n.extra}n.was=n.length,n.mode=mpt;case mpt:for(;x=n.distcode[d&(1<>>24,b=x>>>16&255,k=x&65535,!(_<=u);){if(o===0)break e;o--,d+=r[i++]<>A)],_=x>>>24,b=x>>>16&255,k=x&65535,!(A+_<=u);){if(o===0)break e;o--,d+=r[i++]<>>=A,u-=A,n.back+=A}if(d>>>=_,u-=_,n.back+=_,b&64){s.msg="invalid distance code",n.mode=Sm;break}n.offset=k,n.extra=b&15,n.mode=ppt;case ppt:if(n.extra){for($=n.extra;u<$;){if(o===0)break e;o--,d+=r[i++]<>>=n.extra,u-=n.extra,n.back+=n.extra}if(n.offset>n.dmax){s.msg="invalid distance too far back",n.mode=Sm;break}n.mode=fpt;case fpt:if(c===0)break e;if(f=m-c,n.offset>f){if(f=n.offset-f,f>n.whave&&n.sane){s.msg="invalid distance too far back",n.mode=Sm;break}f>n.wnext?(f-=n.wnext,g=n.wsize-f):g=n.wnext-f,f>n.length&&(f=n.length),y=n.window}else y=a,g=l-n.offset,f=n.length;f>c&&(f=c),c-=f,n.length-=f;do a[l++]=y[g++];while(--f);n.length===0&&(n.mode=fne);break;case gpt:if(c===0)break e;a[l++]=n.length,c--,n.mode=fne;break;case vPe:if(n.wrap){for(;u<32;){if(o===0)break e;o--,d|=r[i++]<{if(lO(s))return Nj;let t=s.state;return t.window&&(t.window=null),s.state=null,NR},Jyn=(s,t)=>{if(lO(s))return Nj;const n=s.state;return n.wrap&2?(n.head=t,t.done=!1,NR):Nj},evn=(s,t)=>{const n=t.length;let r,a,i;return lO(s)||(r=s.state,r.wrap!==0&&r.mode!==E5e)?Nj:r.mode===E5e&&(a=1,a=TZ(a,t,n,0),a!==r.check)?pRt:(i=wRt(s,t,n,n),i?(r.mode=gRt,fRt):(r.havedict=1,NR))};var tvn=vRt,svn=bRt,nvn=yRt,rvn=Yyn,avn=_Rt,ivn=Xyn,ovn=Qyn,lvn=Jyn,cvn=evn,dvn="pako inflate (from Nodeca project)",h4={inflateReset:tvn,inflateReset2:svn,inflateResetKeep:nvn,inflateInit:rvn,inflateInit2:avn,inflate:ivn,inflateEnd:ovn,inflateGetHeader:lvn,inflateSetDictionary:cvn,inflateInfo:dvn};function uvn(){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 hvn=uvn;const jRt=Object.prototype.toString,{Z_NO_FLUSH:mvn,Z_FINISH:pvn,Z_OK:LZ,Z_STREAM_END:wPe,Z_NEED_DICT:jPe,Z_STREAM_ERROR:fvn,Z_DATA_ERROR:_pt,Z_MEM_ERROR:gvn}=NJ;function SJ(s){this.options=fAe.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 dRt,this.strm.avail_out=0;let n=h4.inflateInit2(this.strm,t.windowBits);if(n!==LZ)throw new Error(D$[n]);if(this.header=new hvn,h4.inflateGetHeader(this.strm,this.header),t.dictionary&&(typeof t.dictionary=="string"?t.dictionary=MZ.string2buf(t.dictionary):jRt.call(t.dictionary)==="[object ArrayBuffer]"&&(t.dictionary=new Uint8Array(t.dictionary)),t.raw&&(n=h4.inflateSetDictionary(this.strm,t.dictionary),n!==LZ)))throw new Error(D$[n])}SJ.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?pvn:mvn,jRt.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=h4.inflate(n,l),i===jPe&&a&&(i=h4.inflateSetDictionary(n,a),i===LZ?i=h4.inflate(n,l):i===_pt&&(i=jPe));n.avail_in>0&&i===wPe&&n.state.wrap>0&&s[n.next_in]!==0;)h4.inflateReset(n),i=h4.inflate(n,l);switch(i){case fvn:case _pt:case jPe:case gvn:return this.onEnd(i),this.ended=!0,!1}if(o=n.avail_out,n.next_out&&(n.avail_out===0||i===wPe))if(this.options.to==="string"){let c=MZ.utf8border(n.output,n.next_out),d=n.next_out-c,u=MZ.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===LZ&&o===0)){if(i===wPe)return i=h4.inflateEnd(this.strm),this.onEnd(i),this.ended=!0,!0;if(n.avail_in===0)break}}return!0};SJ.prototype.onData=function(s){this.chunks.push(s)};SJ.prototype.onEnd=function(s){s===LZ&&(this.options.to==="string"?this.result=this.chunks.join(""):this.result=fAe.flattenChunks(this.chunks)),this.chunks=[],this.err=s,this.msg=this.strm.msg};function bWe(s,t){const n=new SJ(t);if(n.push(s),n.err)throw n.msg||D$[n.err];return n.result}function xvn(s,t){return t=t||{},t.raw=!0,bWe(s,t)}var yvn=SJ,vvn=bWe,bvn=xvn,_vn=bWe,wvn=NJ,jvn={Inflate:yvn,inflate:vvn,inflateRaw:bvn,ungzip:_vn,constants:wvn};const{Inflate:Nvn,inflate:kvn,inflateRaw:kFn,ungzip:SFn}=jvn;var wpt=Nvn,Svn=kvn;const NRt=[];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;NRt[s]=t}const jpt=4294967295;function Cvn(s,t,n){let r=s;for(let a=0;a>>8;return r}function Avn(s,t){return(Cvn(jpt,s,t)^jpt)>>>0}function Npt(s,t,n){const r=s.readUint32(),a=Avn(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 kRt(s,t,n){for(let r=0;r>1)&255}else{for(;i>1)&255;for(;i>1)&255}}function TRt(s,t,n,r,a){let i=0;if(n.length===0){for(;i=n||P>=r))for(let I=0;I>8&255}const Rvn=new Uint16Array([255]),Ovn=new Uint8Array(Rvn.buffer),Fvn=Ovn[0]===255,zvn=new Uint8Array(0);function kpt(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=zvn,u=0,h,m;for(let f=0;f>8&255}const nje=Uint8Array.of(137,80,78,71,13,10,26,10);function Spt(s){if(!$vn(s.readBytes(nje.length)))throw new Error("wrong PNG signature")}function $vn(s){if(s.length79)throw new Error("keyword length must be between 1 and 79")}const Hvn=/^[\u0000-\u00FF]*$/;function Gvn(s){if(!Hvn.test(s))throw new Error("invalid latin1 text")}function Wvn(s,t,n){const r=MRt(t);s[r]=Kvn(t,n-r.length-1)}function MRt(s){for(s.mark();s.readByte()!==qvn;);const t=s.offset;s.reset();const n=ERt.decode(s.readBytes(t-s.offset-1));return s.skip(1),Vvn(n),n}function Kvn(s,t){return ERt.decode(s.readBytes(t))}const Gb={UNKNOWN:-1,GREYSCALE:0,TRUECOLOUR:2,INDEXED_COLOUR:3,GREYSCALE_ALPHA:4,TRUECOLOUR_ALPHA:6},NPe={UNKNOWN:-1,DEFLATE:0},Cpt={UNKNOWN:-1,ADAPTIVE:0},kPe={UNKNOWN:-1,NO_INTERLACE:0,ADAM7:1},gne={NONE:0,BACKGROUND:1,PREVIOUS:2},SPe={SOURCE:0,OVER:1};class Yvn extends mWe{constructor(n,r={}){super(n);jr(this,"_checkCrc");jr(this,"_inflator");jr(this,"_png");jr(this,"_apng");jr(this,"_end");jr(this,"_hasPalette");jr(this,"_palette");jr(this,"_hasTransparency");jr(this,"_transparency");jr(this,"_compressionMethod");jr(this,"_filterMethod");jr(this,"_interlaceMethod");jr(this,"_colorType");jr(this,"_isAnimated");jr(this,"_numberOfFrames");jr(this,"_numberOfPlays");jr(this,"_frames");jr(this,"_writingDataChunks");const{checkCrc:a=!1}=r;this._checkCrc=a,this._inflator=new wpt,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=NPe.UNKNOWN,this._filterMethod=Cpt.UNKNOWN,this._interlaceMethod=kPe.UNKNOWN,this._colorType=Gb.UNKNOWN,this._isAnimated=!1,this._numberOfFrames=1,this._numberOfPlays=0,this._frames=[],this._writingDataChunks=!1,this.setBigEndian()}decode(){for(Spt(this);!this._end;){const n=this.readUint32(),r=this.readChars(4);this.decodeChunk(n,r)}return this.decodeImage(),this._png}decodeApng(){for(Spt(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 Uvn:Wvn(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?Npt(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?Npt(this,n+4,r):this.skip(4)}decodeIHDR(){const n=this._png;n.width=this.readUint32(),n.height=this.readUint32(),n.depth=Zvn(this.readUint8());const r=this.readUint8();this._colorType=r;let a;switch(r){case Gb.GREYSCALE:a=1;break;case Gb.TRUECOLOUR:a=3;break;case Gb.INDEXED_COLOUR:a=1;break;case Gb.GREYSCALE_ALPHA:a=2;break;case Gb.TRUECOLOUR_ALPHA:a=4;break;case Gb.UNKNOWN:default:throw new Error(`Unknown color type: ${r}`)}if(this._png.channels=a,this._compressionMethod=this.readUint8(),this._compressionMethod!==NPe.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 SPe.SOURCE:for(let l=0;l=200&&t.status<=299}function xne(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 uI=dl.saveAs||((typeof window>"u"?"undefined":Vu(window))!=="object"||window!==dl?function(){}:typeof HTMLAnchorElement<"u"&&"download"in HTMLAnchorElement.prototype?function(s,t,n){var r=dl.URL||dl.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?Tpt(a.href)?APe(s,t,n):xne(a,a.target="_blank"):xne(a)):(a.href=r.createObjectURL(s),setTimeout(function(){r.revokeObjectURL(a.href)},4e4),setTimeout(function(){xne(a)},0))}:"msSaveOrOpenBlob"in navigator?function(s,t,n){if(t=t||s.name||"download",typeof s=="string")if(Tpt(s))APe(s,t,n);else{var r=document.createElement("a");r.href=s,r.target="_blank",setTimeout(function(){xne(r)})}else navigator.msSaveOrOpenBlob(function(a,i){return i===void 0?i={autoBom:!1}:Vu(i)!=="object"&&(ph.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 APe(s,t,n);var a=s.type==="application/octet-stream",i=/constructor/i.test(dl.HTMLElement)||dl.safari,l=/CriOS\/[\d]+/.test(navigator.userAgent);if((l||a&&i)&&(typeof FileReader>"u"?"undefined":Vu(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=dl.URL||dl.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 LRt(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 rje=dl.atob.bind(dl),Ept=dl.btoa.bind(dl);/** * @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 TPe(s,t){var n=s[0],r=s[1],a=s[2],i=s[3];n=vy(n,r,a,i,t[0],7,-680876936),i=vy(i,n,r,a,t[1],12,-389564586),a=vy(a,i,n,r,t[2],17,606105819),r=vy(r,a,i,n,t[3],22,-1044525330),n=vy(n,r,a,i,t[4],7,-176418897),i=vy(i,n,r,a,t[5],12,1200080426),a=vy(a,i,n,r,t[6],17,-1473231341),r=vy(r,a,i,n,t[7],22,-45705983),n=vy(n,r,a,i,t[8],7,1770035416),i=vy(i,n,r,a,t[9],12,-1958414417),a=vy(a,i,n,r,t[10],17,-42063),r=vy(r,a,i,n,t[11],22,-1990404162),n=vy(n,r,a,i,t[12],7,1804603682),i=vy(i,n,r,a,t[13],12,-40341101),a=vy(a,i,n,r,t[14],17,-1502002290),n=by(n,r=vy(r,a,i,n,t[15],22,1236535329),a,i,t[1],5,-165796510),i=by(i,n,r,a,t[6],9,-1069501632),a=by(a,i,n,r,t[11],14,643717713),r=by(r,a,i,n,t[0],20,-373897302),n=by(n,r,a,i,t[5],5,-701558691),i=by(i,n,r,a,t[10],9,38016083),a=by(a,i,n,r,t[15],14,-660478335),r=by(r,a,i,n,t[4],20,-405537848),n=by(n,r,a,i,t[9],5,568446438),i=by(i,n,r,a,t[14],9,-1019803690),a=by(a,i,n,r,t[3],14,-187363961),r=by(r,a,i,n,t[8],20,1163531501),n=by(n,r,a,i,t[13],5,-1444681467),i=by(i,n,r,a,t[2],9,-51403784),a=by(a,i,n,r,t[7],14,1735328473),n=_y(n,r=by(r,a,i,n,t[12],20,-1926607734),a,i,t[5],4,-378558),i=_y(i,n,r,a,t[8],11,-2022574463),a=_y(a,i,n,r,t[11],16,1839030562),r=_y(r,a,i,n,t[14],23,-35309556),n=_y(n,r,a,i,t[1],4,-1530992060),i=_y(i,n,r,a,t[4],11,1272893353),a=_y(a,i,n,r,t[7],16,-155497632),r=_y(r,a,i,n,t[10],23,-1094730640),n=_y(n,r,a,i,t[13],4,681279174),i=_y(i,n,r,a,t[0],11,-358537222),a=_y(a,i,n,r,t[3],16,-722521979),r=_y(r,a,i,n,t[6],23,76029189),n=_y(n,r,a,i,t[9],4,-640364487),i=_y(i,n,r,a,t[12],11,-421815835),a=_y(a,i,n,r,t[15],16,530742520),n=wy(n,r=_y(r,a,i,n,t[2],23,-995338651),a,i,t[0],6,-198630844),i=wy(i,n,r,a,t[7],10,1126891415),a=wy(a,i,n,r,t[14],15,-1416354905),r=wy(r,a,i,n,t[5],21,-57434055),n=wy(n,r,a,i,t[12],6,1700485571),i=wy(i,n,r,a,t[3],10,-1894986606),a=wy(a,i,n,r,t[10],15,-1051523),r=wy(r,a,i,n,t[1],21,-2054922799),n=wy(n,r,a,i,t[8],6,1873313359),i=wy(i,n,r,a,t[15],10,-30611744),a=wy(a,i,n,r,t[6],15,-1560198380),r=wy(r,a,i,n,t[13],21,1309151649),n=wy(n,r,a,i,t[4],6,-145523070),i=wy(i,n,r,a,t[11],10,-1120210379),a=wy(a,i,n,r,t[2],15,718787259),r=wy(r,a,i,n,t[9],21,-343485551),s[0]=hT(n,s[0]),s[1]=hT(r,s[1]),s[2]=hT(a,s[2]),s[3]=hT(i,s[3])}function xAe(s,t,n,r,a,i){return t=hT(hT(t,s),hT(r,i)),hT(t<>>32-a,n)}function vy(s,t,n,r,a,i,l){return xAe(t&n|~t&r,s,t,a,i,l)}function by(s,t,n,r,a,i,l){return xAe(t&r|n&~r,s,t,a,i,l)}function _y(s,t,n,r,a,i,l){return xAe(t^n^r,s,t,a,i,l)}function wy(s,t,n,r,a,i,l){return xAe(n^(t|~r),s,t,a,i,l)}function PRt(s){var t,n=s.length,r=[1732584193,-271733879,-1732584194,271733878];for(t=64;t<=s.length;t+=64)TPe(r,Qvn(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(TPe(r,a),t=0;t<16;t++)a[t]=0;return a[14]=8*n,TPe(r,a),r}function Qvn(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 Mpt="0123456789abcdef".split("");function Jvn(s){for(var t="",n=0;n<4;n++)t+=Mpt[s>>8*n+4&15]+Mpt[s>>8*n&15];return t}function e1n(s){return String.fromCharCode(255&s,(65280&s)>>8,(16711680&s)>>16,(4278190080&s)>>24)}function V7e(s){return PRt(s).map(e1n).join("")}var t1n=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 H7e(s,t){var n,r,a,i;if(s!==n){for(var l=(a=s,i=1+(256/s.length|0),new Array(i+1).join(a)),o=[],c=0;c<256;c++)o[c]=c;var d=0;for(c=0;c<256;c++){var u=o[c];d=(d+u+l.charCodeAt(c))%256,o[c]=o[d],o[d]=u}n=s,r=o}else o=r;var h=t.length,m=0,f=0,g="";for(c=0;c€/\f©þdSiz";var i=(t+this.padding).substr(0,32),l=(n+this.padding).substr(0,32);this.O=this.processOwnerPassword(i,l),this.P=-(1+(255^a)),this.encryptionKey=V7e(i+this.O+this.lsbFirstWord(this.P)+this.hexToBytes(r)).substr(0,5),this.U=H7e(this.encryptionKey,this.padding)}function o7(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 Ppt(s){if(Vu(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){dl.console&&ph.error("jsPDF PubSub Error",o.message,o)}l[1]&&a.push(i)}a.length&&a.forEach(this.unsubscribe)}},this.getTopics=function(){return t}}function M5e(s){if(!(this instanceof M5e))return new M5e(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 IRt(s,t){this.gState=s,this.matrix=t,this.id="",this.objectNumber=-1}function jI(s,t,n,r,a){if(!(this instanceof jI))return new jI(s,t,n,r,a);this.type=s==="axial"?2:3,this.coords=t,this.colors=n,IRt.call(this,r,a)}function G7(s,t,n,r,a){if(!(this instanceof G7))return new G7(s,t,n,r,a);this.boundingBox=s,this.xStep=t,this.yStep=n,this.stream="",this.cloneIndex=0,IRt.call(this,r,a)}function wo(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;Vu(s=s||{})==="object"&&(n=s.orientation,r=s.unit||r,a=s.format||a,i=s.compress||s.compressPdf||i,(u=s.encryption||null)!==null&&(u.userPassword=u.userPassword||"",u.ownerPassword=u.ownerPassword||"",u.userPermissions=u.userPermissions||[]),o=typeof s.userUnit=="number"?Math.abs(s.userUnit):1,s.precision!==void 0&&(t=s.precision),s.floatPrecision!==void 0&&(c=s.floatPrecision),d=s.defaultPathOperation||"S"),l=s.filters||(i===!0?["FlateEncode"]:l),r=r||"mm",n=(""+(n||"P")).toLowerCase();var h=s.putOnlyUsedFonts||!1,m={},f={internal:{},__private__:{}};f.__private__.PubSub=Ppt;var g="1.3",y=f.__private__.getPdfVersion=function(){return g};f.__private__.setPdfVersion=function(ze){g=ze};var x={a0:[2383.94,3370.39],a1:[1683.78,2383.94],a2:[1190.55,1683.78],a3:[841.89,1190.55],a4:[595.28,841.89],a5:[419.53,595.28],a6:[297.64,419.53],a7:[209.76,297.64],a8:[147.4,209.76],a9:[104.88,147.4],a10:[73.7,104.88],b0:[2834.65,4008.19],b1:[2004.09,2834.65],b2:[1417.32,2004.09],b3:[1000.63,1417.32],b4:[708.66,1000.63],b5:[498.9,708.66],b6:[354.33,498.9],b7:[249.45,354.33],b8:[175.75,249.45],b9:[124.72,175.75],b10:[87.87,124.72],c0:[2599.37,3676.54],c1:[1836.85,2599.37],c2:[1298.27,1836.85],c3:[918.43,1298.27],c4:[649.13,918.43],c5:[459.21,649.13],c6:[323.15,459.21],c7:[229.61,323.15],c8:[161.57,229.61],c9:[113.39,161.57],c10:[79.37,113.39],dl:[311.81,623.62],letter:[612,792],"government-letter":[576,756],legal:[612,1008],"junior-legal":[576,360],ledger:[1224,792],tabloid:[792,1224],"credit-card":[153,243]};f.__private__.getPageFormats=function(){return x};var _=f.__private__.getPageFormat=function(ze){return x[ze]};a=a||"a4";var b="compat",k="advanced",A=b;function T(){this.saveGraphicsState(),Fe(new Mr(Xs,0,0,-Xs,0,Hh()*Xs).toString()+" cm"),this.setFontSize(this.getFontSize()/Xs),d="n",A=k}function P(){this.restoreGraphicsState(),d="S",A=b}var I=f.__private__.combineFontStyleAndFontWeight=function(ze,xt){if(ze=="bold"&&xt=="normal"||ze=="bold"&&xt==400||ze=="normal"&&xt=="italic"||ze=="bold"&&xt=="italic")throw new Error("Invalid Combination of fontweight and fontstyle");return xt&&(ze=xt==400||xt==="normal"?ze==="italic"?"italic":"normal":xt!=700&&xt!=="bold"||ze!=="normal"?(xt==700?"bold":xt)+""+ze:"bold"),ze};f.advancedAPI=function(ze){var xt=A===b;return xt&&T.call(this),typeof ze!="function"||(ze(this),xt&&P.call(this)),this},f.compatAPI=function(ze){var xt=A===k;return xt&&P.call(this),typeof ze!="function"||(ze(this),xt&&T.call(this)),this},f.isAdvancedAPI=function(){return A===k};var M,L=function(ze){if(A!==k)throw new Error(ze+" is only available in 'advanced' API mode. You need to call advancedAPI() first.")},z=f.roundToPrecision=f.__private__.roundToPrecision=function(ze,xt){var ss=t||xt;if(isNaN(ze)||isNaN(ss))throw new Error("Invalid argument passed to jsPDF.roundToPrecision");return ze.toFixed(ss).replace(/0+$/,"")};M=f.hpf=f.__private__.hpf=typeof c=="number"?function(ze){if(isNaN(ze))throw new Error("Invalid argument passed to jsPDF.hpf");return z(ze,c)}:c==="smart"?function(ze){if(isNaN(ze))throw new Error("Invalid argument passed to jsPDF.hpf");return z(ze,ze>-1&&ze<1?16:5)}:function(ze){if(isNaN(ze))throw new Error("Invalid argument passed to jsPDF.hpf");return z(ze,16)};var $=f.f2=f.__private__.f2=function(ze){if(isNaN(ze))throw new Error("Invalid argument passed to jsPDF.f2");return z(ze,2)},V=f.__private__.f3=function(ze){if(isNaN(ze))throw new Error("Invalid argument passed to jsPDF.f3");return z(ze,3)},W=f.scale=f.__private__.scale=function(ze){if(isNaN(ze))throw new Error("Invalid argument passed to jsPDF.scale");return A===b?ze*Xs:A===k?ze:void 0},G=function(ze){return W(function(xt){return A===b?Hh()-xt:A===k?xt:void 0}(ze))};f.__private__.setPrecision=f.setPrecision=function(ze){typeof parseInt(ze,10)=="number"&&(t=parseInt(ze,10))};var X,te="00000000000000000000000000000000",ne=f.__private__.getFileId=function(){return te},me=f.__private__.setFileId=function(ze){return te=ze!==void 0&&/^[a-fA-F0-9]{32}$/.test(ze)?ze.toUpperCase():te.split("").map(function(){return"ABCDEF0123456789".charAt(Math.floor(16*Math.random()))}).join(""),u!==null&&(No=new i7(u.userPermissions,u.userPassword,u.ownerPassword,te)),te};f.setFileId=function(ze){return me(ze),this},f.getFileId=function(){return ne()};var ue=f.__private__.convertDateToPDFDate=function(ze){var xt=ze.getTimezoneOffset(),ss=xt<0?"+":"-",cs=Math.floor(Math.abs(xt/60)),tn=Math.abs(xt%60),Mn=[ss,ve(cs),"'",ve(tn),"'"].join("");return["D:",ze.getFullYear(),ve(ze.getMonth()+1),ve(ze.getDate()),ve(ze.getHours()),ve(ze.getMinutes()),ve(ze.getSeconds()),Mn].join("")},ce=f.__private__.convertPDFDateToDate=function(ze){var xt=parseInt(ze.substr(2,4),10),ss=parseInt(ze.substr(6,2),10)-1,cs=parseInt(ze.substr(8,2),10),tn=parseInt(ze.substr(10,2),10),Mn=parseInt(ze.substr(12,2),10),Xn=parseInt(ze.substr(14,2),10);return new Date(xt,ss,cs,tn,Mn,Xn,0)},ae=f.__private__.setCreationDate=function(ze){var xt;if(ze===void 0&&(ze=new Date),ze instanceof Date)xt=ue(ze);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(ze))throw new Error("Invalid argument passed to jsPDF.setCreationDate");xt=ze}return X=xt},he=f.__private__.getCreationDate=function(ze){var xt=X;return ze==="jsDate"&&(xt=ce(X)),xt};f.setCreationDate=function(ze){return ae(ze),this},f.getCreationDate=function(ze){return he(ze)};var xe,ve=f.__private__.padd2=function(ze){return("0"+parseInt(ze)).slice(-2)},ge=f.__private__.padd2Hex=function(ze){return("00"+(ze=ze.toString())).substr(ze.length)},be=0,Se=[],Ie=[],Me=0,Re=[],Be=[],Ne=!1,Ge=Ie;f.__private__.setCustomOutputDestination=function(ze){Ne=!0,Ge=ze};var Ce=function(ze){Ne||(Ge=ze)};f.__private__.resetCustomOutputDestination=function(){Ne=!1,Ge=Ie};var Fe=f.__private__.out=function(ze){return ze=ze.toString(),Me+=ze.length+1,Ge.push(ze),Ge},Ae=f.__private__.write=function(ze){return Fe(arguments.length===1?ze.toString():Array.prototype.join.call(arguments," "))},Xe=f.__private__.getArrayBuffer=function(ze){for(var xt=ze.length,ss=new ArrayBuffer(xt),cs=new Uint8Array(ss);xt--;)cs[xt]=ze.charCodeAt(xt);return ss},$e=[["Helvetica","helvetica","normal","WinAnsiEncoding"],["Helvetica-Bold","helvetica","bold","WinAnsiEncoding"],["Helvetica-Oblique","helvetica","italic","WinAnsiEncoding"],["Helvetica-BoldOblique","helvetica","bolditalic","WinAnsiEncoding"],["Courier","courier","normal","WinAnsiEncoding"],["Courier-Bold","courier","bold","WinAnsiEncoding"],["Courier-Oblique","courier","italic","WinAnsiEncoding"],["Courier-BoldOblique","courier","bolditalic","WinAnsiEncoding"],["Times-Roman","times","normal","WinAnsiEncoding"],["Times-Bold","times","bold","WinAnsiEncoding"],["Times-Italic","times","italic","WinAnsiEncoding"],["Times-BoldItalic","times","bolditalic","WinAnsiEncoding"],["ZapfDingbats","zapfdingbats","normal",null],["Symbol","symbol","normal",null]];f.__private__.getStandardFonts=function(){return $e};var Ye=s.fontSize||16;f.__private__.setFontSize=f.setFontSize=function(ze){return Ye=A===k?ze/Xs:ze,this};var Je,Ke=f.__private__.getFontSize=f.getFontSize=function(){return A===b?Ye:Ye*Xs},st=s.R2L||!1;f.__private__.setR2L=f.setR2L=function(ze){return st=ze,this},f.__private__.getR2L=f.getR2L=function(){return st};var rt,Ze=f.__private__.setZoomMode=function(ze){if(/^(?:\d+\.\d*|\d*\.\d+|\d+)%$/.test(ze))Je=ze;else if(isNaN(ze)){if([void 0,null,"fullwidth","fullheight","fullpage","original"].indexOf(ze)===-1)throw new Error('zoom must be Integer (e.g. 2), a percentage Value (e.g. 300%) or fullwidth, fullheight, fullpage, original. "'+ze+'" is not recognized.');Je=ze}else Je=parseInt(ze,10)};f.__private__.getZoomMode=function(){return Je};var ht,Bt=f.__private__.setPageMode=function(ze){if([void 0,null,"UseNone","UseOutlines","UseThumbs","FullScreen"].indexOf(ze)==-1)throw new Error('Page mode must be one of UseNone, UseOutlines, UseThumbs, or FullScreen. "'+ze+'" is not recognized.');rt=ze};f.__private__.getPageMode=function(){return rt};var Ct=f.__private__.setLayoutMode=function(ze){if([void 0,null,"continuous","single","twoleft","tworight","two"].indexOf(ze)==-1)throw new Error('Layout mode must be one of continuous, single, twoleft, tworight. "'+ze+'" is not recognized.');ht=ze};f.__private__.getLayoutMode=function(){return ht},f.__private__.setDisplayMode=f.setDisplayMode=function(ze,xt,ss){return Ze(ze),Ct(xt),Bt(ss),this};var Yt={title:"",subject:"",author:"",keywords:"",creator:""};f.__private__.getDocumentProperty=function(ze){if(Object.keys(Yt).indexOf(ze)===-1)throw new Error("Invalid argument passed to jsPDF.getDocumentProperty");return Yt[ze]},f.__private__.getDocumentProperties=function(){return Yt},f.__private__.setDocumentProperties=f.setProperties=f.setDocumentProperties=function(ze){for(var xt in Yt)Yt.hasOwnProperty(xt)&&ze[xt]&&(Yt[xt]=ze[xt]);return this},f.__private__.setDocumentProperty=function(ze,xt){if(Object.keys(Yt).indexOf(ze)===-1)throw new Error("Invalid arguments passed to jsPDF.setDocumentProperty");return Yt[ze]=xt};var Kt,Xs,zs,Vt,At,Os={},Nt={},ms=[],Ys={},It={},Ds={},As={},Hs=null,Rs=0,en=[],Rn=new Ppt(f),Bn=s.hotfixes||[],Dn={},Jn={},ua=[],Mr=function ze(xt,ss,cs,tn,Mn,Xn){if(!(this instanceof ze))return new ze(xt,ss,cs,tn,Mn,Xn);isNaN(xt)&&(xt=1),isNaN(ss)&&(ss=0),isNaN(cs)&&(cs=0),isNaN(tn)&&(tn=1),isNaN(Mn)&&(Mn=0),isNaN(Xn)&&(Xn=0),this._matrix=[xt,ss,cs,tn,Mn,Xn]};Object.defineProperty(Mr.prototype,"sx",{get:function(){return this._matrix[0]},set:function(ze){this._matrix[0]=ze}}),Object.defineProperty(Mr.prototype,"shy",{get:function(){return this._matrix[1]},set:function(ze){this._matrix[1]=ze}}),Object.defineProperty(Mr.prototype,"shx",{get:function(){return this._matrix[2]},set:function(ze){this._matrix[2]=ze}}),Object.defineProperty(Mr.prototype,"sy",{get:function(){return this._matrix[3]},set:function(ze){this._matrix[3]=ze}}),Object.defineProperty(Mr.prototype,"tx",{get:function(){return this._matrix[4]},set:function(ze){this._matrix[4]=ze}}),Object.defineProperty(Mr.prototype,"ty",{get:function(){return this._matrix[5]},set:function(ze){this._matrix[5]=ze}}),Object.defineProperty(Mr.prototype,"a",{get:function(){return this._matrix[0]},set:function(ze){this._matrix[0]=ze}}),Object.defineProperty(Mr.prototype,"b",{get:function(){return this._matrix[1]},set:function(ze){this._matrix[1]=ze}}),Object.defineProperty(Mr.prototype,"c",{get:function(){return this._matrix[2]},set:function(ze){this._matrix[2]=ze}}),Object.defineProperty(Mr.prototype,"d",{get:function(){return this._matrix[3]},set:function(ze){this._matrix[3]=ze}}),Object.defineProperty(Mr.prototype,"e",{get:function(){return this._matrix[4]},set:function(ze){this._matrix[4]=ze}}),Object.defineProperty(Mr.prototype,"f",{get:function(){return this._matrix[5]},set:function(ze){this._matrix[5]=ze}}),Object.defineProperty(Mr.prototype,"rotation",{get:function(){return Math.atan2(this.shx,this.sx)}}),Object.defineProperty(Mr.prototype,"scaleX",{get:function(){return this.decompose().scale.sx}}),Object.defineProperty(Mr.prototype,"scaleY",{get:function(){return this.decompose().scale.sy}}),Object.defineProperty(Mr.prototype,"isIdentity",{get:function(){return this.sx===1&&this.shy===0&&this.shx===0&&this.sy===1&&this.tx===0&&this.ty===0}}),Mr.prototype.join=function(ze){return[this.sx,this.shy,this.shx,this.sy,this.tx,this.ty].map(M).join(ze)},Mr.prototype.multiply=function(ze){var xt=ze.sx*this.sx+ze.shy*this.shx,ss=ze.sx*this.shy+ze.shy*this.sy,cs=ze.shx*this.sx+ze.sy*this.shx,tn=ze.shx*this.shy+ze.sy*this.sy,Mn=ze.tx*this.sx+ze.ty*this.shx+this.tx,Xn=ze.tx*this.shy+ze.ty*this.sy+this.ty;return new Mr(xt,ss,cs,tn,Mn,Xn)},Mr.prototype.decompose=function(){var ze=this.sx,xt=this.shy,ss=this.shx,cs=this.sy,tn=this.tx,Mn=this.ty,Xn=Math.sqrt(ze*ze+xt*xt),mr=(ze/=Xn)*ss+(xt/=Xn)*cs;ss-=ze*mr,cs-=xt*mr;var Ba=Math.sqrt(ss*ss+cs*cs);return mr/=Ba,ze*(cs/=Ba)>16&255,cs=Ba>>8&255,tn=255&Ba}if(cs===void 0||Mn===void 0&&ss===cs&&cs===tn)xt=typeof ss=="string"?ss+" "+Xn[0]:ze.precision===2?$(ss/255)+" "+Xn[0]:V(ss/255)+" "+Xn[0];else if(Mn===void 0||Vu(Mn)==="object"){if(Mn&&!isNaN(Mn.a)&&Mn.a===0)return["1.","1.","1.",Xn[1]].join(" ");xt=typeof ss=="string"?[ss,cs,tn,Xn[1]].join(" "):ze.precision===2?[$(ss/255),$(cs/255),$(tn/255),Xn[1]].join(" "):[V(ss/255),V(cs/255),V(tn/255),Xn[1]].join(" ")}else xt=typeof ss=="string"?[ss,cs,tn,Mn,Xn[2]].join(" "):ze.precision===2?[$(ss),$(cs),$(tn),$(Mn),Xn[2]].join(" "):[V(ss),V(cs),V(tn),V(Mn),Xn[2]].join(" ");return xt},kt=f.__private__.getFilters=function(){return l},Ut=f.__private__.putStream=function(ze){var xt=(ze=ze||{}).data||"",ss=ze.filters||kt(),cs=ze.alreadyAppliedFilters||[],tn=ze.addLength1||!1,Mn=xt.length,Xn=ze.objectId,mr=function(ci){return ci};if(u!==null&&Xn===void 0)throw new Error("ObjectId must be passed to putStream for file encryption");u!==null&&(mr=No.encryptor(Xn,0));var Ba={};ss===!0&&(ss=["FlateEncode"]);var Ki=ze.additionalKeyValues||[],Ui=(Ba=wo.API.processDataByFilters!==void 0?wo.API.processDataByFilters(xt,ss):{data:xt,reverseChain:[]}).reverseChain+(Array.isArray(cs)?cs.join(" "):cs.toString());if(Ba.data.length!==0&&(Ki.push({key:"Length",value:Ba.data.length}),tn===!0&&Ki.push({key:"Length1",value:Mn})),Ui.length!=0)if(Ui.split("/").length-1==1)Ki.push({key:"Filter",value:Ui});else{Ki.push({key:"Filter",value:"["+Ui+"]"});for(var tl=0;tl>"),Ba.data.length!==0&&(Fe("stream"),Fe(mr(Ba.data)),Fe("endstream"))},es=f.__private__.putPage=function(ze){var xt=ze.number,ss=ze.data,cs=ze.objId,tn=ze.contentsObjId;Zn(cs,!0),Fe("<>"),Fe("endobj");var Mn=ss.join(` `);return A===k&&(Mn+=` Q`),Zn(tn,!0),Ut({data:Mn,filters:kt(),objectId:tn}),Fe("endobj"),cs},Ms=f.__private__.putPages=function(){var ze,xt,ss=[];for(ze=1;ze<=Rs;ze++)en[ze].objId=rn(),en[ze].contentsObjId=rn();for(ze=1;ze<=Rs;ze++)ss.push(es({number:ze,data:Be[ze],objId:en[ze].objId,contentsObjId:en[ze].contentsObjId,mediaBox:en[ze].mediaBox,cropBox:en[ze].cropBox,bleedBox:en[ze].bleedBox,trimBox:en[ze].trimBox,artBox:en[ze].artBox,userUnit:en[ze].userUnit,rootDictionaryObjId:xs,resourceDictionaryObjId:Ve}));Zn(xs,!0),Fe("<>"),Fe("endobj"),Rn.publish("postPutPages")},bs=function(ze){Rn.publish("putFont",{font:ze,out:Fe,newObject:Nr,putStream:Ut}),ze.isAlreadyPutted!==!0&&(ze.objectNumber=Nr(),Fe("<<"),Fe("/Type /Font"),Fe("/BaseFont /"+o7(ze.postScriptName)),Fe("/Subtype /Type1"),typeof ze.encoding=="string"&&Fe("/Encoding /"+ze.encoding),Fe("/FirstChar 32"),Fe("/LastChar 255"),Fe(">>"),Fe("endobj"))},Zs=function(ze){ze.objectNumber=Nr();var xt=[];xt.push({key:"Type",value:"/XObject"}),xt.push({key:"Subtype",value:"/Form"}),xt.push({key:"BBox",value:"["+[M(ze.x),M(ze.y),M(ze.x+ze.width),M(ze.y+ze.height)].join(" ")+"]"}),xt.push({key:"Matrix",value:"["+ze.matrix.toString()+"]"});var ss=ze.pages[1].join(` `);Ut({data:ss,additionalKeyValues:xt,objectId:ze.objectNumber}),Fe("endobj")},kn=function(ze,xt){xt||(xt=21);var ss=Nr(),cs=function(Xn,mr){var Ba,Ki=[],Ui=1/(mr-1);for(Ba=0;Ba<1;Ba+=Ui)Ki.push(Ba);if(Ki.push(1),Xn[0].offset!=0){var tl={offset:0,color:Xn[0].color};Xn.unshift(tl)}if(Xn[Xn.length-1].offset!=1){var Mc={offset:1,color:Xn[Xn.length-1].color};Xn.push(Mc)}for(var Lr="",Za=0,ci=0;ciXn[Za+1].offset;)Za++;var jl=Xn[Za].offset,xc=(Ba-jl)/(Xn[Za+1].offset-jl),qi=Xn[Za].color,Gh=Xn[Za+1].color;Lr+=ge(Math.round((1-xc)*qi[0]+xc*Gh[0]).toString(16))+ge(Math.round((1-xc)*qi[1]+xc*Gh[1]).toString(16))+ge(Math.round((1-xc)*qi[2]+xc*Gh[2]).toString(16))}return Lr.trim()}(ze.colors,xt),tn=[];tn.push({key:"FunctionType",value:"0"}),tn.push({key:"Domain",value:"[0.0 1.0]"}),tn.push({key:"Size",value:"["+xt+"]"}),tn.push({key:"BitsPerSample",value:"8"}),tn.push({key:"Range",value:"[0.0 1.0 0.0 1.0 0.0 1.0]"}),tn.push({key:"Decode",value:"[0.0 1.0 0.0 1.0 0.0 1.0]"}),Ut({data:cs,additionalKeyValues:tn,alreadyAppliedFilters:["/ASCIIHexDecode"],objectId:ss}),Fe("endobj"),ze.objectNumber=Nr(),Fe("<< /ShadingType "+ze.type),Fe("/ColorSpace /DeviceRGB");var Mn="/Coords ["+M(parseFloat(ze.coords[0]))+" "+M(parseFloat(ze.coords[1]))+" ";ze.type===2?Mn+=M(parseFloat(ze.coords[2]))+" "+M(parseFloat(ze.coords[3])):Mn+=M(parseFloat(ze.coords[2]))+" "+M(parseFloat(ze.coords[3]))+" "+M(parseFloat(ze.coords[4]))+" "+M(parseFloat(ze.coords[5])),Fe(Mn+="]"),ze.matrix&&Fe("/Matrix ["+ze.matrix.toString()+"]"),Fe("/Function "+ss+" 0 R"),Fe("/Extend [true true]"),Fe(">>"),Fe("endobj")},gn=function(ze,xt){var ss=rn(),cs=Nr();xt.push({resourcesOid:ss,objectOid:cs}),ze.objectNumber=cs;var tn=[];tn.push({key:"Type",value:"/Pattern"}),tn.push({key:"PatternType",value:"1"}),tn.push({key:"PaintType",value:"1"}),tn.push({key:"TilingType",value:"1"}),tn.push({key:"BBox",value:"["+ze.boundingBox.map(M).join(" ")+"]"}),tn.push({key:"XStep",value:M(ze.xStep)}),tn.push({key:"YStep",value:M(ze.yStep)}),tn.push({key:"Resources",value:ss+" 0 R"}),ze.matrix&&tn.push({key:"Matrix",value:"["+ze.matrix.toString()+"]"}),Ut({data:ze.stream,additionalKeyValues:tn,objectId:ze.objectNumber}),Fe("endobj")},xr=function(ze){for(var xt in ze.objectNumber=Nr(),Fe("<<"),ze)switch(xt){case"opacity":Fe("/ca "+$(ze[xt]));break;case"stroke-opacity":Fe("/CA "+$(ze[xt]))}Fe(">>"),Fe("endobj")},Kr=function(ze){Zn(ze.resourcesOid,!0),Fe("<<"),Fe("/ProcSet [/PDF /Text /ImageB /ImageC /ImageI]"),function(){for(var xt in Fe("/Font <<"),Os)Os.hasOwnProperty(xt)&&(h===!1||h===!0&&m.hasOwnProperty(xt))&&Fe("/"+xt+" "+Os[xt].objectNumber+" 0 R");Fe(">>")}(),function(){if(Object.keys(Ys).length>0){for(var xt in Fe("/Shading <<"),Ys)Ys.hasOwnProperty(xt)&&Ys[xt]instanceof jI&&Ys[xt].objectNumber>=0&&Fe("/"+xt+" "+Ys[xt].objectNumber+" 0 R");Rn.publish("putShadingPatternDict"),Fe(">>")}}(),function(xt){if(Object.keys(Ys).length>0){for(var ss in Fe("/Pattern <<"),Ys)Ys.hasOwnProperty(ss)&&Ys[ss]instanceof f.TilingPattern&&Ys[ss].objectNumber>=0&&Ys[ss].objectNumber>")}}(ze.objectOid),function(){if(Object.keys(Ds).length>0){var xt;for(xt in Fe("/ExtGState <<"),Ds)Ds.hasOwnProperty(xt)&&Ds[xt].objectNumber>=0&&Fe("/"+xt+" "+Ds[xt].objectNumber+" 0 R");Rn.publish("putGStateDict"),Fe(">>")}}(),function(){for(var xt in Fe("/XObject <<"),Dn)Dn.hasOwnProperty(xt)&&Dn[xt].objectNumber>=0&&Fe("/"+xt+" "+Dn[xt].objectNumber+" 0 R");Rn.publish("putXobjectDict"),Fe(">>")}(),Fe(">>"),Fe("endobj")},ca=function(ze){Nt[ze.fontName]=Nt[ze.fontName]||{},Nt[ze.fontName][ze.fontStyle]=ze.id},Er=function(ze,xt,ss,cs,tn){var Mn={id:"F"+(Object.keys(Os).length+1).toString(10),postScriptName:ze,fontName:xt,fontStyle:ss,encoding:cs,isStandardFont:tn||!1,metadata:{}};return Rn.publish("addFont",{font:Mn,instance:this}),Os[Mn.id]=Mn,ca(Mn),Mn.id},qr=f.__private__.pdfEscape=f.pdfEscape=function(ze,xt){return function(ss,cs){var tn,Mn,Xn,mr,Ba,Ki,Ui,tl,Mc;if(Xn=(cs=cs||{}).sourceEncoding||"Unicode",Ba=cs.outputEncoding,(cs.autoencode||Ba)&&Os[Kt].metadata&&Os[Kt].metadata[Xn]&&Os[Kt].metadata[Xn].encoding&&(mr=Os[Kt].metadata[Xn].encoding,!Ba&&Os[Kt].encoding&&(Ba=Os[Kt].encoding),!Ba&&mr.codePages&&(Ba=mr.codePages[0]),typeof Ba=="string"&&(Ba=mr[Ba]),Ba)){for(Ui=!1,Ki=[],tn=0,Mn=ss.length;tn>8&&(Ui=!0);ss=Ki.join("")}for(tn=ss.length;Ui===void 0&&tn!==0;)ss.charCodeAt(tn-1)>>8&&(Ui=!0),tn--;if(!Ui)return ss;for(Ki=cs.noBOM?[]:[254,255],tn=0,Mn=ss.length;tn>8)>>8)throw new Error("Character at position "+tn+" of string '"+ss+"' exceeds 16bits. Cannot be encoded into UCS-2 BE");Ki.push(Mc),Ki.push(tl-(Mc<<8))}return String.fromCharCode.apply(void 0,Ki)}(ze,xt).replace(/\\/g,"\\\\").replace(/\(/g,"\\(").replace(/\)/g,"\\)")},Xt=f.__private__.beginPage=function(ze){Be[++Rs]=[],en[Rs]={objId:0,contentsObjId:0,userUnit:Number(o),artBox:null,bleedBox:null,cropBox:null,trimBox:null,mediaBox:{bottomLeftX:0,bottomLeftY:0,topRightX:Number(ze[0]),topRightY:Number(ze[1])}},Or(Rs),Ce(Be[xe])},Gn=function(ze,xt){var ss,cs,tn;switch(n=xt||n,typeof ze=="string"&&(ss=_(ze.toLowerCase()),Array.isArray(ss)&&(cs=ss[0],tn=ss[1])),Array.isArray(ze)&&(cs=ze[0]*Xs,tn=ze[1]*Xs),isNaN(cs)&&(cs=a[0],tn=a[1]),(cs>14400||tn>14400)&&(ph.warn("A page in a PDF can not be wider or taller than 14400 userUnit. jsPDF limits the width/height to 14400"),cs=Math.min(14400,cs),tn=Math.min(14400,tn)),a=[cs,tn],n.substr(0,1)){case"l":tn>cs&&(a=[tn,cs]);break;case"p":cs>tn&&(a=[tn,cs])}Xt(a),hm(po),Fe(Km),Zm!==0&&Fe(Zm+" J"),mm!==0&&Fe(mm+" j"),Rn.publish("addPage",{pageNumber:Rs})},Jr=function(ze){ze>0&&ze<=Rs&&(Be.splice(ze,1),en.splice(ze,1),Rs--,xe>Rs&&(xe=Rs),this.setPage(xe))},Or=function(ze){ze>0&&ze<=Rs&&(xe=ze)},ja=f.__private__.getNumberOfPages=f.getNumberOfPages=function(){return Be.length-1},ea=function(ze,xt,ss){var cs,tn=void 0;return ss=ss||{},ze=ze!==void 0?ze:Os[Kt].fontName,xt=xt!==void 0?xt:Os[Kt].fontStyle,cs=ze.toLowerCase(),Nt[cs]!==void 0&&Nt[cs][xt]!==void 0?tn=Nt[cs][xt]:Nt[ze]!==void 0&&Nt[ze][xt]!==void 0?tn=Nt[ze][xt]:ss.disableWarning===!1&&ph.warn("Unable to look up font label for font '"+ze+"', '"+xt+"'. Refer to getFontList() for available fonts."),tn||ss.noFallback||(tn=Nt.times[xt])==null&&(tn=Nt.times.normal),tn},dr=f.__private__.putInfo=function(){var ze=Nr(),xt=function(cs){return cs};for(var ss in u!==null&&(xt=No.encryptor(ze,0)),Fe("<<"),Fe("/Producer ("+qr(xt("jsPDF "+wo.version))+")"),Yt)Yt.hasOwnProperty(ss)&&Yt[ss]&&Fe("/"+ss.substr(0,1).toUpperCase()+ss.substr(1)+" ("+qr(xt(Yt[ss]))+")");Fe("/CreationDate ("+qr(xt(X))+")"),Fe(">>"),Fe("endobj")},Wi=f.__private__.putCatalog=function(ze){var xt=(ze=ze||{}).rootDictionaryObjId||xs;switch(Nr(),Fe("<<"),Fe("/Type /Catalog"),Fe("/Pages "+xt+" 0 R"),Je||(Je="fullwidth"),Je){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 ss=""+Je;ss.substr(ss.length-1)==="%"&&(Je=parseInt(Je)/100),typeof Je=="number"&&Fe("/OpenAction [3 0 R /XYZ null null "+$(Je)+"]")}switch(ht||(ht="continuous"),ht){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")}rt&&Fe("/PageMode /"+rt),Rn.publish("putCatalog"),Fe(">>"),Fe("endobj")},ho=f.__private__.putTrailer=function(){Fe("trailer"),Fe("<<"),Fe("/Size "+(be+1)),Fe("/Root "+be+" 0 R"),Fe("/Info "+(be-1)+" 0 R"),u!==null&&Fe("/Encrypt "+No.oid+" 0 R"),Fe("/ID [ <"+te+"> <"+te+"> ]"),Fe(">>")},oa=f.__private__.putHeader=function(){Fe("%PDF-"+g),Fe("%ºß¬à")},Ha=f.__private__.putXRef=function(){var ze="0000000000";Fe("xref"),Fe("0 "+(be+1)),Fe("0000000000 65535 f ");for(var xt=1;xt<=be;xt++)typeof Se[xt]=="function"?Fe((ze+Se[xt]()).slice(-10)+" 00000 n "):Se[xt]!==void 0?Fe((ze+Se[xt]).slice(-10)+" 00000 n "):Fe("0000000000 00000 n ")},$i=f.__private__.buildDocument=function(){var ze;be=0,Me=0,Ie=[],Se=[],Re=[],xs=rn(),Ve=rn(),Ce(Ie),Rn.publish("buildDocument"),oa(),Ms(),function(){Rn.publish("putAdditionalObjects");for(var ss=0;ss"),Fe("/O <"+No.toHexString(No.O)+">"),Fe("/P "+No.P),Fe(">>"),Fe("endobj")),dr(),Wi();var xt=Me;return Ha(),ho(),Fe("startxref"),Fe(""+xt),Fe("%%EOF"),Ce(Be[xe]),Ie.join(` `)},Ta=f.__private__.getBlob=function(ze){return new Blob([Xe(ze)],{type:"application/pdf"})},Wn=function(ze){for(;ze.firstChild;)ze.removeChild(ze.firstChild)},Ra=function(ze){var xt,ss=ze.document,cs=ss.documentElement,tn=ss.head,Mn=ss.body;return tn||(tn=ss.createElement("head"),cs.appendChild(tn)),Mn||(Mn=ss.createElement("body"),cs.appendChild(Mn)),Wn(tn),Wn(Mn),(xt=ss.createElement("style")).appendChild(ss.createTextNode("html, body { padding: 0; margin: 0; } iframe { width: 100%; height: 100%; border: 0;}")),tn.appendChild(xt),{document:ss,body:Mn}},mo=f.output=f.__private__.output=(vr=function(ze,xt){switch(typeof(xt=xt||{})=="string"?xt={filename:xt}:xt.filename=xt.filename||"generated.pdf",ze){case void 0:return $i();case"save":f.save(xt.filename);break;case"arraybuffer":return Xe($i());case"blob":return Ta($i());case"bloburi":case"bloburl":if(dl.URL!==void 0&&typeof dl.URL.createObjectURL=="function")return dl.URL&&dl.URL.createObjectURL(Ta($i()))||void 0;ph.warn("bloburl is not supported by your system, because URL.createObjectURL is not supported by your browser.");break;case"datauristring":case"dataurlstring":var ss="",cs=$i();try{ss=Ept(cs)}catch{ss=Ept(unescape(encodeURIComponent(cs)))}return"data:application/pdf;filename="+encodeURIComponent(xt.filename)+";base64,"+ss;case"pdfobjectnewwindow":if(Object.prototype.toString.call(dl)==="[object Window]"){var tn="https://cdnjs.cloudflare.com/ajax/libs/pdfobject/2.1.1/pdfobject.min.js",Mn=!xt.pdfObjectUrl;Mn||(tn=xt.pdfObjectUrl);var Xn=dl.open();if(Xn!==null){var mr=Ra(Xn),Ba=mr.document.createElement("script"),Ki=this;Ba.src=tn,Mn&&(Ba.integrity="sha512-4ze/a9/4jqu+tX9dfOqJYSvyYd5M6qum/3HpCLr+/Jqf0whc37VUbkpNGHR7/8pSnCFw47T1fmIpwBV7UySh3g==",Ba.crossOrigin="anonymous"),Ba.onload=function(){Xn.PDFObject.embed(Ki.output("dataurlstring"),xt)},mr.body.appendChild(Ba)}return Xn}throw new Error("The option pdfobjectnewwindow just works in a browser-environment.");case"pdfjsnewwindow":if(Object.prototype.toString.call(dl)==="[object Window]"){var Ui=xt.pdfJsUrl||"examples/PDF.js/web/viewer.html",tl=dl.open();if(tl!==null){var Mc=Ra(tl),Lr=Mc.document.createElement("iframe"),Za=Ui.indexOf("?")===-1?"?":"&";Ki=this,Lr.id="pdfViewer",Lr.width="500px",Lr.height="400px",Lr.src=Ui+Za+"file=&downloadName="+encodeURIComponent(xt.filename),Lr.onload=function(){tl.document.title=xt.filename,Lr.contentWindow.PDFViewerApplication.open(Ki.output("bloburl"))},Mc.body.appendChild(Lr)}return tl}throw new Error("The option pdfjsnewwindow just works in a browser-environment.");case"dataurlnewwindow":if(Object.prototype.toString.call(dl)!=="[object Window]")throw new Error("The option dataurlnewwindow just works in a browser-environment.");var ci=dl.open();if(ci!==null){var jl=Ra(ci),xc=jl.document.createElement("iframe");xc.src=this.output("datauristring",xt),jl.body.appendChild(xc),ci.document.title=xt.filename}if(ci||typeof safari>"u")return ci;break;case"datauri":case"dataurl":return dl.document.location.href=this.output("datauristring",xt);default:return null}},vr.foo=function(){try{return vr.apply(this,arguments)}catch(ss){var ze=ss.stack||"";~ze.indexOf(" at ")&&(ze=ze.split(" at ")[1]);var xt="Error in function "+ze.split(` `)[0].split("<")[0]+": "+ss.message;if(!dl.console)throw new Error(xt);dl.console.error(xt,ss),dl.alert&&alert(xt)}},vr.foo.bar=vr,vr.foo),Ho=function(ze){return Array.isArray(Bn)===!0&&Bn.indexOf(ze)>-1};switch(r){case"pt":Xs=1;break;case"mm":Xs=72/25.4;break;case"cm":Xs=72/2.54;break;case"in":Xs=72;break;case"px":Xs=Ho("px_scaling")==1?.75:96/72;break;case"pc":case"em":Xs=12;break;case"ex":Xs=6;break;default:if(typeof r!="number")throw new Error("Invalid unit: "+r);Xs=r}var No=null;ae(),me();var Go=f.__private__.getPageInfo=f.getPageInfo=function(ze){if(isNaN(ze)||ze%1!=0)throw new Error("Invalid argument passed to jsPDF.getPageInfo");return{objId:en[ze].objId,pageNumber:ze,pageContext:en[ze]}},Dd=f.__private__.getPageInfoByObjId=function(ze){if(isNaN(ze)||ze%1!=0)throw new Error("Invalid argument passed to jsPDF.getPageInfoByObjId");for(var xt in en)if(en[xt].objId===ze)break;return Go(xt)},Tu=f.__private__.getCurrentPageInfo=f.getCurrentPageInfo=function(){return{objId:en[xe].objId,pageNumber:xe,pageContext:en[xe]}};f.addPage=function(){return Gn.apply(this,arguments),this},f.setPage=function(){return Or.apply(this,arguments),Ce.call(this,Be[xe]),this},f.insertPage=function(ze){return this.addPage(),this.movePage(xe,ze),this},f.movePage=function(ze,xt){var ss,cs;if(ze>xt){ss=Be[ze],cs=en[ze];for(var tn=ze;tn>xt;tn--)Be[tn]=Be[tn-1],en[tn]=en[tn-1];Be[xt]=ss,en[xt]=cs,this.setPage(xt)}else if(ze0&&(typeof ze=="string"?ze=Za.splitTextToSize(ze,Ui):Object.prototype.toString.call(ze)==="[object Array]"&&(ze=ze.reduce(function(Wo,Oo){return Wo.concat(Za.splitTextToSize(Oo,Ui))},[]))),Mn={text:ze,x:xt,y:ss,options:cs,mutex:{pdfEscape:qr,activeFontKey:Kt,fonts:Os,activeFontSize:Ye}},Rn.publish("preProcessText",Mn),ze=Mn.text,mr=(cs=Mn.options).angle,Lr instanceof Mr==0&&mr&&typeof mr=="number"){mr*=Math.PI/180,cs.rotationDirection===0&&(mr=-mr),A===k&&(mr=-mr);var oy=Math.cos(mr),ed=Math.sin(mr);Lr=new Mr(oy,ed,-ed,oy,0,0)}else mr&&mr instanceof Mr&&(Lr=mr);A!==k||Lr||(Lr=ki),(Ki=cs.charSpace||qh)!==void 0&&(xc+=M(W(Ki))+` Tc `,this.setCharSpace(this.getCharSpace()||0)),(Mc=cs.horizontalScale)!==void 0&&(xc+=M(100*Mc)+` Tz `),cs.lang;var ud=-1,Mu=cs.renderingMode!==void 0?cs.renderingMode:cs.stroke,pm=Za.internal.getCurrentPageInfo().pageContext;switch(Mu){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 Nf=pm.usedRenderingMode!==void 0?pm.usedRenderingMode:-1;ud!==-1?xc+=ud+` Tr `:Nf!==-1&&(xc+=`0 Tr `),ud!==-1&&(pm.usedRenderingMode=ud),Ba=cs.align||"left";var il,wa=Ye*qi,Ir=Za.internal.pageSize.getWidth(),Pl=Os[Kt];Ki=cs.charSpace||qh,Ui=cs.maxWidth||0,tl=Object.assign({autoencode:!0,noBOM:!0},cs.flags);var Na=[],fm=function(Wo){return Za.getStringUnitWidth(Wo,{font:Pl,charSpace:Ki,fontSize:Ye,doKerning:!1})*Ye/Gh};if(Object.prototype.toString.call(ze)==="[object Array]"){var td;Xn=fx(ze),Ba!=="left"&&(il=Xn.map(fm));var ra,Eg=0;if(Ba==="right"){xt-=il[0],ze=[],Od=Xn.length;for(var gx=0;gx0?(Ui-il[Lc])/sp:0;Lc":")"),yc=parseFloat(Xn[hu][1]),Mg=parseFloat(Xn[hu][2]);break;case 0:o0=(jl?"<":"(")+Xn[hu]+(jl?">":")"),yc=Wm(xt),Mg=bd(ss)}Na!==void 0&&Na[hu]!==void 0&&(Sf=Na[hu]+` Tw `),hu===0?ze.push(Sf+d1(yc,Mg,Lr)+o0):oh===0?ze.push(Sf+o0):oh===1&&ze.push(Sf+d1(yc,Mg,Lr)+o0)}ze=oh===0?ze.join(` Tj T* `):ze.join(` Tj `),ze+=` Tj `;var Il=`BT /`;return Il+=Kt+" "+Ye+` Tf `,Il+=M(Ye*qi)+` TL `,Il+=Ym+` `,Il+=xc,Il+=ze,Fe(Il+="ET"),m[Kt]=!0,Za};var Vm=f.__private__.clip=f.clip=function(ze){return Fe(ze==="evenodd"?"W*":"W"),this};f.clipEvenOdd=function(){return Vm("evenodd")},f.__private__.discardPath=f.discardPath=function(){return Fe("n"),this};var Uc=f.__private__.isValidStyle=function(ze){var xt=!1;return[void 0,null,"S","D","F","DF","FD","f","f*","B","B*","n"].indexOf(ze)!==-1&&(xt=!0),xt};f.__private__.setDefaultPathOperation=f.setDefaultPathOperation=function(ze){return Uc(ze)&&(d=ze),this};var Eu=f.__private__.getStyle=f.getStyle=function(ze){var xt=d;switch(ze){case"D":case"S":xt="S";break;case"F":xt="f";break;case"FD":case"DF":xt="B";break;case"f":case"f*":case"B":case"B*":xt=ze}return xt},Ec=f.close=function(){return Fe("h"),this};f.stroke=function(){return Fe("S"),this},f.fill=function(ze){return Gd("f",ze),this},f.fillEvenOdd=function(ze){return Gd("f*",ze),this},f.fillStroke=function(ze){return Gd("B",ze),this},f.fillStrokeEvenOdd=function(ze){return Gd("B*",ze),this};var Gd=function(ze,xt){Vu(xt)==="object"?Hm(xt,ze):Fe(ze)},s0=function(ze){ze===null||A===k&&ze===void 0||(ze=Eu(ze),Fe(ze))};function Nb(ze,xt,ss,cs,tn){var Mn=new G7(xt||this.boundingBox,ss||this.xStep,cs||this.yStep,this.gState,tn||this.matrix);Mn.stream=this.stream;var Xn=ze+"$$"+this.cloneIndex+++"$$";return ia(Xn,Mn),Mn}var Hm=function(ze,xt){var ss=It[ze.key],cs=Ys[ss];if(cs instanceof jI)Fe("q"),Fe(ay(xt)),cs.gState&&f.setGState(cs.gState),Fe(ze.matrix.toString()+" cm"),Fe("/"+ss+" sh"),Fe("Q");else if(cs instanceof G7){var tn=new Mr(1,0,0,-1,0,Hh());ze.matrix&&(tn=tn.multiply(ze.matrix||ki),ss=Nb.call(cs,ze.key,ze.boundingBox,ze.xStep,ze.yStep,tn).id),Fe("q"),Fe("/Pattern cs"),Fe("/"+ss+" scn"),cs.gState&&f.setGState(cs.gState),Fe(xt),Fe("Q")}},ay=function(ze){switch(ze){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"}},wf=f.moveTo=function(ze,xt){return Fe(M(W(ze))+" "+M(G(xt))+" m"),this},jf=f.lineTo=function(ze,xt){return Fe(M(W(ze))+" "+M(G(xt))+" l"),this},cu=f.curveTo=function(ze,xt,ss,cs,tn,Mn){return Fe([M(W(ze)),M(G(xt)),M(W(ss)),M(G(cs)),M(W(tn)),M(G(Mn)),"c"].join(" ")),this};f.__private__.line=f.line=function(ze,xt,ss,cs,tn){if(isNaN(ze)||isNaN(xt)||isNaN(ss)||isNaN(cs)||!Uc(tn))throw new Error("Invalid arguments passed to jsPDF.line");return A===b?this.lines([[ss-ze,cs-xt]],ze,xt,[1,1],tn||"S"):this.lines([[ss-ze,cs-xt]],ze,xt,[1,1]).stroke()},f.__private__.lines=f.lines=function(ze,xt,ss,cs,tn,Mn){var Xn,mr,Ba,Ki,Ui,tl,Mc,Lr,Za,ci,jl,xc;if(typeof ze=="number"&&(xc=ss,ss=xt,xt=ze,ze=xc),cs=cs||[1,1],Mn=Mn||!1,isNaN(xt)||isNaN(ss)||!Array.isArray(ze)||!Array.isArray(cs)||!Uc(tn)||typeof Mn!="boolean")throw new Error("Invalid arguments passed to jsPDF.lines");for(wf(xt,ss),Xn=cs[0],mr=cs[1],Ki=ze.length,ci=xt,jl=ss,Ba=0;Ba>8&255,s>>16&255,s>>24&255)},i7.prototype.toHexString=function(s){return s.split("").map(function(t){return("0"+(255&t.charCodeAt(0)).toString(16)).slice(-2)}).join("")},i7.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 H7e(n,r)}},M5e.prototype.equals=function(s){var t,n="id,objectNumber,equals";if(!s||Vu(s)!==Vu(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},wo.API={events:[]},wo.version="4.2.1";var sf=wo.API,_We=1,cO=function(s){return s.replace(/\\/g,"\\\\").replace(/\(/g,"\\(").replace(/\)/g,"\\)")},PF=function(s){return s.replace(/\\\\/g,"\\").replace(/\\\(/g,"(").replace(/\\\)/g,")")},kR=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)})},Nl=function(s){return s.toFixed(2)},SC=function(s){return s.toFixed(5)};sf.__acroform__={};var wb=function(s,t){s.prototype=Object.create(t.prototype),s.prototype.constructor=s},Ipt=function(s){return s*_We},hk=function(s){var t=new RRt,n=Ji.internal.getHeight(s)||0,r=Ji.internal.getWidth(s)||0;return t.BBox=[0,0,Number(Nl(r)),Number(Nl(n))],t},s1n=sf.__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=yne("3",s,i).height,m=s.multiline?l-i:(l-h)/2,f=m+=2,g=0,y=0,x=0;if(i<=0){t=`(...) Tj `,t+="% Width of Text: "+yne(t,s,i=12).width+", FieldWidth:"+o+` `;break}for(var _="",b=0,k=0;kl)continue e;_+=a[k][x],A=!0,y=k,k--}else{_=(_+=a[k][x]+" ").substr(_.length-1)==" "?_.substr(0,_.length-1):_;var T=parseInt(k),P=c(T,_,i),I=k>=a.length-1;if(P&&!I){_+=" ",x=0;continue}if(P||I){if(I)y=T;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=T}}for(var M="",L=g;L<=y;L++){var z=a[L];if(s.multiline){if(L===y){M+=z[x]+" ",x=(x+1)%z.length;continue}if(L===g){M+=z[z.length-1]+" ";continue}}M+=z[0]+" "}switch(M=M.substr(M.length-1)==" "?M.substr(0,M.length-1):M,u=yne(M,s,i).width,s.textAlign){case"right":d=o-u-2;break;case"center":d=(o-u)/2;break;default:d=2}t+=Nl(d)+" "+Nl(f)+` Td `,t+="("+cO(M)+`) Tj `,t+=-Nl(d)+` 0 Td `,f=-(i+2),u=0,g=A?y:y+1,b++,_=""}break}return r.text=t,r.fontSize=i,r},yne=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}},o1n={fields:[],xForms:[],acroFormDictionaryRoot:null,printedOut:!1,internal:null,isInitialized:!1},l1n=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)},c1n=function(s,t){if(t.scope=s,s.internal!==void 0&&(s.internal.acroformPlugin===void 0||s.internal.acroformPlugin.isInitialized===!1)){if(CN.FieldNum=0,s.internal.acroformPlugin=JSON.parse(JSON.stringify(o1n)),s.internal.acroformPlugin.acroFormDictionaryRoot)throw new Error("Exception while creating AcroformDictionary");_We=s.internal.scaleFactor,s.internal.acroformPlugin.acroFormDictionaryRoot=new ORt,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&&l1n(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=a1n(o.Rect,a)),a.internal.newObjectDeferredBegin(o.objId,!0),o.DA=Ji.createDefaultAppearanceStream(o),Vu(o)==="object"&&typeof o.getKeyValueListForStream=="function"&&(c=o.getKeyValueListForStream()),o.Rect=d,o.hasAppearanceStream&&!o.appearanceStreamContent){var u=i1n(o);c.push({key:"AP",value:"<>"}),a.internal.acroformPlugin.xForms.push(u)}if(o.appearanceStreamContent){var h="";for(var m in o.appearanceStreamContent)if(o.appearanceStreamContent.hasOwnProperty(m)){var f=o.appearanceStreamContent[m];if(h+="/"+m+" ",h+="<<",Object.keys(f).length>=1||Array.isArray(f)){for(var l in f)if(f.hasOwnProperty(l)){var g=f[l];typeof g=="function"&&(g=g.call(a,o)),h+="/"+l+" "+g+" ",a.internal.acroformPlugin.xForms.indexOf(g)>=0||a.internal.acroformPlugin.xForms.push(g)}}else typeof(g=f)=="function"&&(g=g.call(a,o)),h+="/"+l+" "+g,a.internal.acroformPlugin.xForms.indexOf(g)>=0||a.internal.acroformPlugin.xForms.push(g);h+=">>"}c.push({key:"AP",value:`<< `+h+">>"})}a.internal.putStream({additionalKeyValues:c,objectId:o.objId}),a.internal.out("endobj")}i&&function(y,x){for(var _ in y)if(y.hasOwnProperty(_)){var b=_,k=y[_];x.internal.newObjectDeferredBegin(k.objId,!0),Vu(k)==="object"&&typeof k.putStream=="function"&&k.putStream(),delete y[b]}}(a.internal.acroformPlugin.xForms,a)})(n,s)}),s.internal.acroformPlugin.isInitialized=!0}},DRt=sf.__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)),"("+cO(n(s))+")"}},set:function(n){s=n}})};wb(ORt,n5);var CN=function s(){n5.call(this);var t=4;Object.defineProperty(this,"F",{enumerable:!1,configurable:!1,get:function(){return t},set:function(_){if(isNaN(_))throw new Error('Invalid value "'+_+'" for attribute F supplied.');t=_}}),Object.defineProperty(this,"showWhenPrinted",{enumerable:!0,configurable:!0,get:function(){return!!Of(t,3)},set:function(_){_?this.F=Ff(t,3):this.F=zf(t,3)}});var n=0;Object.defineProperty(this,"Ff",{enumerable:!1,configurable:!1,get:function(){return n},set:function(_){if(isNaN(_))throw new Error('Invalid value "'+_+'" for attribute Ff supplied.');n=_}});var r=[];Object.defineProperty(this,"Rect",{enumerable:!1,configurable:!1,get:function(){if(r.length!==0)return r},set:function(_){r=_!==void 0?_:[]}}),Object.defineProperty(this,"x",{enumerable:!0,configurable:!0,get:function(){return!r||isNaN(r[0])?0:r[0]},set:function(_){r[0]=_}}),Object.defineProperty(this,"y",{enumerable:!0,configurable:!0,get:function(){return!r||isNaN(r[1])?0:r[1]},set:function(_){r[1]=_}}),Object.defineProperty(this,"width",{enumerable:!0,configurable:!0,get:function(){return!r||isNaN(r[2])?0:r[2]},set:function(_){r[2]=_}}),Object.defineProperty(this,"height",{enumerable:!0,configurable:!0,get:function(){return!r||isNaN(r[3])?0:r[3]},set:function(_){r[3]=_}});var a="";Object.defineProperty(this,"FT",{enumerable:!0,configurable:!1,get:function(){return a},set:function(_){switch(_){case"/Btn":case"/Tx":case"/Ch":case"/Sig":a=_;break;default:throw new Error('Invalid value "'+_+'" 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 L5e)return;i="FieldObject"+s.FieldNum++}var _=function(b){return b};return this.scope&&(_=this.scope.internal.getEncryptor(this.objId)),"("+cO(_(i))+")"},set:function(_){i=_.toString()}}),Object.defineProperty(this,"fieldName",{configurable:!0,enumerable:!0,get:function(){return i},set:function(_){i=_}});var l="helvetica";Object.defineProperty(this,"fontName",{enumerable:!0,configurable:!0,get:function(){return l},set:function(_){l=_}});var o="normal";Object.defineProperty(this,"fontStyle",{enumerable:!0,configurable:!0,get:function(){return o},set:function(_){o=_}});var c=0;Object.defineProperty(this,"fontSize",{enumerable:!0,configurable:!0,get:function(){return c},set:function(_){c=_}});var d=void 0;Object.defineProperty(this,"maxFontSize",{enumerable:!0,configurable:!0,get:function(){return d===void 0?50/_We:d},set:function(_){d=_}});var u="black";Object.defineProperty(this,"color",{enumerable:!0,configurable:!0,get:function(){return u},set:function(_){u=_}});var h="/F1 0 Tf 0 g";Object.defineProperty(this,"DA",{enumerable:!0,configurable:!1,get:function(){if(!(!h||this instanceof L5e||this instanceof UD))return EPe(h,this.objId,this.scope)},set:function(_){_=_.toString(),h=_}});var m=null;Object.defineProperty(this,"DV",{enumerable:!1,configurable:!1,get:function(){if(m)return this instanceof Ux==0?EPe(m,this.objId,this.scope):m},set:function(_){_=_.toString(),m=this instanceof Ux==0?_.substr(0,1)==="("?PF(_.substr(1,_.length-2)):PF(_):_}}),Object.defineProperty(this,"defaultValue",{enumerable:!0,configurable:!0,get:function(){return this instanceof Ux==1?PF(m.substr(1,m.length-1)):m},set:function(_){_=_.toString(),m=this instanceof Ux==1?"/"+kR(_):_}});var f=null;Object.defineProperty(this,"_V",{enumerable:!1,configurable:!1,get:function(){if(f)return f},set:function(_){this.V=_}}),Object.defineProperty(this,"V",{enumerable:!1,configurable:!1,get:function(){if(f)return this instanceof Ux==0?EPe(f,this.objId,this.scope):f},set:function(_){_=_.toString(),f=this instanceof Ux==0?_.substr(0,1)==="("?PF(_.substr(1,_.length-2)):PF(_):_}}),Object.defineProperty(this,"value",{enumerable:!0,configurable:!0,get:function(){return this instanceof Ux==1?PF(f.substr(1,f.length-1)):f},set:function(_){_=_.toString(),f=this instanceof Ux==1?"/"+kR(_):_}}),Object.defineProperty(this,"hasAnnotation",{enumerable:!0,configurable:!0,get:function(){return this.Rect}}),Object.defineProperty(this,"Type",{enumerable:!0,configurable:!1,get:function(){return this.hasAnnotation?"/Annot":null}}),Object.defineProperty(this,"Subtype",{enumerable:!0,configurable:!1,get:function(){return this.hasAnnotation?"/Widget":null}});var g,y=!1;Object.defineProperty(this,"hasAppearanceStream",{enumerable:!0,configurable:!0,get:function(){return y},set:function(_){_=!!_,y=_}}),Object.defineProperty(this,"page",{enumerable:!0,configurable:!0,get:function(){if(g)return g},set:function(_){g=_}}),Object.defineProperty(this,"readOnly",{enumerable:!0,configurable:!0,get:function(){return!!Of(this.Ff,1)},set:function(_){_?this.Ff=Ff(this.Ff,1):this.Ff=zf(this.Ff,1)}}),Object.defineProperty(this,"required",{enumerable:!0,configurable:!0,get:function(){return!!Of(this.Ff,2)},set:function(_){_?this.Ff=Ff(this.Ff,2):this.Ff=zf(this.Ff,2)}}),Object.defineProperty(this,"noExport",{enumerable:!0,configurable:!0,get:function(){return!!Of(this.Ff,3)},set:function(_){_?this.Ff=Ff(this.Ff,3):this.Ff=zf(this.Ff,3)}});var x=null;Object.defineProperty(this,"Q",{enumerable:!0,configurable:!1,get:function(){if(x!==null)return x},set:function(_){if([0,1,2].indexOf(_)===-1)throw new Error('Invalid value "'+_+'" for attribute Q supplied.');x=_}}),Object.defineProperty(this,"textAlign",{get:function(){var _;switch(x){case 0:default:_="left";break;case 1:_="center";break;case 2:_="right"}return _},configurable:!0,enumerable:!0,set:function(_){switch(_){case"right":case 2:x=2;break;case"center":case 1:x=1;break;default:x=0}}})};wb(CN,n5);var nz=function(){CN.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 DRt(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!!Of(this.Ff,18)},set:function(n){n?this.Ff=Ff(this.Ff,18):this.Ff=zf(this.Ff,18)}}),Object.defineProperty(this,"edit",{enumerable:!0,configurable:!0,get:function(){return!!Of(this.Ff,19)},set:function(n){this.combo===!0&&(n?this.Ff=Ff(this.Ff,19):this.Ff=zf(this.Ff,19))}}),Object.defineProperty(this,"sort",{enumerable:!0,configurable:!0,get:function(){return!!Of(this.Ff,20)},set:function(n){n?(this.Ff=Ff(this.Ff,20),t.sort()):this.Ff=zf(this.Ff,20)}}),Object.defineProperty(this,"multiSelect",{enumerable:!0,configurable:!0,get:function(){return!!Of(this.Ff,22)},set:function(n){n?this.Ff=Ff(this.Ff,22):this.Ff=zf(this.Ff,22)}}),Object.defineProperty(this,"doNotSpellCheck",{enumerable:!0,configurable:!0,get:function(){return!!Of(this.Ff,23)},set:function(n){n?this.Ff=Ff(this.Ff,23):this.Ff=zf(this.Ff,23)}}),Object.defineProperty(this,"commitOnSelChange",{enumerable:!0,configurable:!0,get:function(){return!!Of(this.Ff,27)},set:function(n){n?this.Ff=Ff(this.Ff,27):this.Ff=zf(this.Ff,27)}}),this.hasAppearanceStream=!1};wb(nz,CN);var rz=function(){nz.call(this),this.fontName="helvetica",this.combo=!1};wb(rz,nz);var az=function(){rz.call(this),this.combo=!0};wb(az,rz);var aje=function(){az.call(this),this.edit=!0};wb(aje,az);var Ux=function(){CN.call(this),this.FT="/Btn",Object.defineProperty(this,"noToggleToOff",{enumerable:!0,configurable:!0,get:function(){return!!Of(this.Ff,15)},set:function(n){n?this.Ff=Ff(this.Ff,15):this.Ff=zf(this.Ff,15)}}),Object.defineProperty(this,"radio",{enumerable:!0,configurable:!0,get:function(){return!!Of(this.Ff,16)},set:function(n){n?this.Ff=Ff(this.Ff,16):this.Ff=zf(this.Ff,16)}}),Object.defineProperty(this,"pushButton",{enumerable:!0,configurable:!0,get:function(){return!!Of(this.Ff,17)},set:function(n){n?this.Ff=Ff(this.Ff,17):this.Ff=zf(this.Ff,17)}}),Object.defineProperty(this,"radioIsUnison",{enumerable:!0,configurable:!0,get:function(){return!!Of(this.Ff,26)},set:function(n){n?this.Ff=Ff(this.Ff,26):this.Ff=zf(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+" ("+cO(n(t[r]))+")");return a.push(">>"),a.join(` `)}},set:function(n){Vu(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="/"+kR(r)}}),Object.defineProperty(this,"appearanceState",{enumerable:!0,configurable:!0,get:function(){return s.substr(1,s.length-1)},set:function(n){s="/"+kR(n)}})};wb(Ux,CN);var ije=function(){Ux.call(this),this.pushButton=!0};wb(ije,Ux);var iz=function(){Ux.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:[]}})};wb(iz,Ux);var L5e=function(){var s,t;CN.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+" ("+cO(a(r[i]))+")");return l.push(">>"),l.join(` `)},set:function(a){Vu(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="/"+kR(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="/"+kR(i)}}),this.caption="l",this.appearanceState="Off",this._AppearanceType=Ji.RadioButton.Circle,this.appearanceStreamContent=this._AppearanceType.createAppearanceStream(this.optionName)};wb(L5e,CN),iz.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()}},iz.prototype.createOption=function(s){var t=new L5e;return t.Parent=this,t.optionName=s,this.Kids.push(t),d1n.call(this.scope,t),t};var oje=function(){Ux.call(this),this.fontName="zapfdingbats",this.caption="3",this.appearanceState="On",this.value="On",this.textAlign="center",this.appearanceStreamContent=Ji.CheckBox.createAppearanceStream()};wb(oje,Ux);var UD=function(){CN.call(this),this.FT="/Tx",Object.defineProperty(this,"multiline",{enumerable:!0,configurable:!0,get:function(){return!!Of(this.Ff,13)},set:function(t){t?this.Ff=Ff(this.Ff,13):this.Ff=zf(this.Ff,13)}}),Object.defineProperty(this,"fileSelect",{enumerable:!0,configurable:!0,get:function(){return!!Of(this.Ff,21)},set:function(t){t?this.Ff=Ff(this.Ff,21):this.Ff=zf(this.Ff,21)}}),Object.defineProperty(this,"doNotSpellCheck",{enumerable:!0,configurable:!0,get:function(){return!!Of(this.Ff,23)},set:function(t){t?this.Ff=Ff(this.Ff,23):this.Ff=zf(this.Ff,23)}}),Object.defineProperty(this,"doNotScroll",{enumerable:!0,configurable:!0,get:function(){return!!Of(this.Ff,24)},set:function(t){t?this.Ff=Ff(this.Ff,24):this.Ff=zf(this.Ff,24)}}),Object.defineProperty(this,"comb",{enumerable:!0,configurable:!0,get:function(){return!!Of(this.Ff,25)},set:function(t){t?this.Ff=Ff(this.Ff,25):this.Ff=zf(this.Ff,25)}}),Object.defineProperty(this,"richText",{enumerable:!0,configurable:!0,get:function(){return!!Of(this.Ff,26)},set:function(t){t?this.Ff=Ff(this.Ff,26):this.Ff=zf(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}})};wb(UD,CN);var lje=function(){UD.call(this),Object.defineProperty(this,"password",{enumerable:!0,configurable:!0,get:function(){return!!Of(this.Ff,14)},set:function(s){s?this.Ff=Ff(this.Ff,14):this.Ff=zf(this.Ff,14)}}),this.password=!0};wb(lje,UD);var Ji={CheckBox:{createAppearanceStream:function(){return{N:{On:Ji.CheckBox.YesNormal},D:{On:Ji.CheckBox.YesPushDown,Off:Ji.CheckBox.OffPushDown}}},YesPushDown:function(s){var t=hk(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=G7e(s,s.caption);return n.push("0.749023 g"),n.push("0 0 "+Nl(Ji.internal.getWidth(s))+" "+Nl(Ji.internal.getHeight(s))+" re"),n.push("f"),n.push("BMC"),n.push("q"),n.push("0 0 1 rg"),n.push("/"+r+" "+Nl(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=hk(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=Ji.internal.getHeight(s),l=Ji.internal.getWidth(s),o=G7e(s,s.caption);return a.push("1 g"),a.push("0 0 "+Nl(l)+" "+Nl(i)+" re"),a.push("f"),a.push("q"),a.push("0 0 1 rg"),a.push("0 0 "+Nl(l-1)+" "+Nl(i-1)+" re"),a.push("W"),a.push("n"),a.push("0 g"),a.push("BT"),a.push("/"+n+" "+Nl(o.fontSize)+" Tf "+r),a.push(o.text),a.push("ET"),a.push("Q"),t.stream=a.join(` `),t},OffPushDown:function(s){var t=hk(s);t.scope=s.scope;var n=[];return n.push("0.749023 g"),n.push("0 0 "+Nl(Ji.internal.getWidth(s))+" "+Nl(Ji.internal.getHeight(s))+" re"),n.push("f"),t.stream=n.join(` `),t}},RadioButton:{Circle:{createAppearanceStream:function(s){var t={D:{Off:Ji.RadioButton.Circle.OffPushDown},N:{}};return t.N[s]=Ji.RadioButton.Circle.YesNormal,t.D[s]=Ji.RadioButton.Circle.YesPushDown,t},getCA:function(){return"l"},YesNormal:function(s){var t=hk(s);t.scope=s.scope;var n=[],r=Ji.internal.getWidth(s)<=Ji.internal.getHeight(s)?Ji.internal.getWidth(s)/4:Ji.internal.getHeight(s)/4;r=Number((.9*r).toFixed(5));var a=Ji.internal.Bezier_C,i=Number((r*a).toFixed(5));return n.push("q"),n.push("1 0 0 1 "+SC(Ji.internal.getWidth(s)/2)+" "+SC(Ji.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=hk(s);t.scope=s.scope;var n=[],r=Ji.internal.getWidth(s)<=Ji.internal.getHeight(s)?Ji.internal.getWidth(s)/4:Ji.internal.getHeight(s)/4;r=Number((.9*r).toFixed(5));var a=Number((2*r).toFixed(5)),i=Number((a*Ji.internal.Bezier_C).toFixed(5)),l=Number((r*Ji.internal.Bezier_C).toFixed(5));return n.push("0.749023 g"),n.push("q"),n.push("1 0 0 1 "+SC(Ji.internal.getWidth(s)/2)+" "+SC(Ji.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 "+SC(Ji.internal.getWidth(s)/2)+" "+SC(Ji.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=hk(s);t.scope=s.scope;var n=[],r=Ji.internal.getWidth(s)<=Ji.internal.getHeight(s)?Ji.internal.getWidth(s)/4:Ji.internal.getHeight(s)/4;r=Number((.9*r).toFixed(5));var a=Number((2*r).toFixed(5)),i=Number((a*Ji.internal.Bezier_C).toFixed(5));return n.push("0.749023 g"),n.push("q"),n.push("1 0 0 1 "+SC(Ji.internal.getWidth(s)/2)+" "+SC(Ji.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:Ji.RadioButton.Cross.OffPushDown},N:{}};return t.N[s]=Ji.RadioButton.Cross.YesNormal,t.D[s]=Ji.RadioButton.Cross.YesPushDown,t},getCA:function(){return"8"},YesNormal:function(s){var t=hk(s);t.scope=s.scope;var n=[],r=Ji.internal.calculateCross(s);return n.push("q"),n.push("1 1 "+Nl(Ji.internal.getWidth(s)-2)+" "+Nl(Ji.internal.getHeight(s)-2)+" re"),n.push("W"),n.push("n"),n.push(Nl(r.x1.x)+" "+Nl(r.x1.y)+" m"),n.push(Nl(r.x2.x)+" "+Nl(r.x2.y)+" l"),n.push(Nl(r.x4.x)+" "+Nl(r.x4.y)+" m"),n.push(Nl(r.x3.x)+" "+Nl(r.x3.y)+" l"),n.push("s"),n.push("Q"),t.stream=n.join(` `),t},YesPushDown:function(s){var t=hk(s);t.scope=s.scope;var n=Ji.internal.calculateCross(s),r=[];return r.push("0.749023 g"),r.push("0 0 "+Nl(Ji.internal.getWidth(s))+" "+Nl(Ji.internal.getHeight(s))+" re"),r.push("f"),r.push("q"),r.push("1 1 "+Nl(Ji.internal.getWidth(s)-2)+" "+Nl(Ji.internal.getHeight(s)-2)+" re"),r.push("W"),r.push("n"),r.push(Nl(n.x1.x)+" "+Nl(n.x1.y)+" m"),r.push(Nl(n.x2.x)+" "+Nl(n.x2.y)+" l"),r.push(Nl(n.x4.x)+" "+Nl(n.x4.y)+" m"),r.push(Nl(n.x3.x)+" "+Nl(n.x3.y)+" l"),r.push("s"),r.push("Q"),t.stream=r.join(` `),t},OffPushDown:function(s){var t=hk(s);t.scope=s.scope;var n=[];return n.push("0.749023 g"),n.push("0 0 "+Nl(Ji.internal.getWidth(s))+" "+Nl(Ji.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}};Ji.internal={Bezier_C:.551915024494,calculateCross:function(s){var t=Ji.internal.getWidth(s),n=Ji.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}}}},Ji.internal.getWidth=function(s){var t=0;return Vu(s)==="object"&&(t=Ipt(s.Rect[2])),t},Ji.internal.getHeight=function(s){var t=0;return Vu(s)==="object"&&(t=Ipt(s.Rect[3])),t};var d1n=sf.addField=function(s){if(c1n(this,s),!(s instanceof CN))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};sf.AcroFormChoiceField=nz,sf.AcroFormListBox=rz,sf.AcroFormComboBox=az,sf.AcroFormEditBox=aje,sf.AcroFormButton=Ux,sf.AcroFormPushButton=ije,sf.AcroFormRadioButton=iz,sf.AcroFormCheckBox=oje,sf.AcroFormTextField=UD,sf.AcroFormPasswordField=lje,sf.AcroFormAppearance=Ji,sf.AcroForm={ChoiceField:nz,ListBox:rz,ComboBox:az,EditBox:aje,Button:Ux,PushButton:ije,RadioButton:iz,CheckBox:oje,TextField:UD,PasswordField:lje,Appearance:Ji},wo.AcroForm={ChoiceField:nz,ListBox:rz,ComboBox:az,EditBox:aje,Button:Ux,PushButton:ije,RadioButton:iz,CheckBox:oje,TextField:UD,PasswordField:lje,Appearance:Ji};function FRt(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($,V){var W,G,X,te,ne,me=n;if((V=V||n)==="RGBA"||$.data!==void 0&&$.data instanceof Uint8ClampedArray&&"height"in $&&"width"in $)return"RGBA";if(P($))for(ne in r)for(X=r[ne],W=0;W>"}),"transparency"in V&&Array.isArray(V.transparency)&&V.transparency.length>0){for(var ne="",me=0,ue=V.transparency.length;me>",y.content=i;var k=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 x=0,_=n,b="",k=0;for(x=0;x>"),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}])}(wo.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 f=arguments[5];Object.defineProperty(this,"lineNumber",{enumerable:!0,get:function(){return f},set:function(y){f=y}});var g=arguments[6];return Object.defineProperty(this,"align",{enumerable:!0,get:function(){return g},set:function(y){g=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,f=0,g=0,y=0,x=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 _=d.maxWidth;_>0?typeof c=="string"?c=this.splitTextToSize(c,_):Object.prototype.toString.call(c)==="[object Array]"&&(c=c.reduce(function(k,A){return k.concat(x.splitTextToSize(A,_))},[])):c=Array.isArray(c)?c:[c];for(var b=0;bthis.getPageHeight()?(this.cellAddPage(),c.y=h.top,f&&m&&(this.printHeaderRow(c.lineNumber,!0),c.y+=m[0].height)):c.y=d.y+d.height||c.y),c.text[0]!==void 0&&(this.rect(c.x,c.y,c.width,c.height,n===!0?"FD":void 0),c.align==="right"?this.text(c.text,c.x+c.width-u,c.y+u,{align:"right",baseline:"top"}):c.align==="center"?this.text(c.text,c.x+c.width/2,c.y+u,{align:"center",baseline:"top",maxWidth:c.width-u-u}):this.text(c.text,c.x+u,c.y+u,{align:"left",baseline:"top",maxWidth:c.width-u-u})),this.internal.__cell__.lastCell=c,this};s.table=function(c,d,u,h,m){if(r.call(this),!u)throw new Error("No data for PDF table.");var f,g,y,x,_=[],b=[],k=[],A={},T={},P=[],I=[],M=(m=m||{}).autoSize||!1,L=m.printHeaders!==!1,z=m.css&&m.css["font-size"]!==void 0?16*m.css["font-size"]:m.fontSize||12,$=m.margins||Object.assign({width:this.getPageWidth()},t),V=typeof m.padding=="number"?m.padding:3,W=m.headerBackgroundColor||"#c8c8c8",G=m.headerTextColor||"#000";if(a.call(this),this.internal.__cell__.printHeaders=L,this.internal.__cell__.margins=$,this.internal.__cell__.table_font_size=z,this.internal.__cell__.padding=V,this.internal.__cell__.headerBackgroundColor=W,this.internal.__cell__.headerTextColor=G,this.setFontSize(z),h==null)b=_=Object.keys(u[0]),k=_.map(function(){return"left"});else if(Array.isArray(h)&&Vu(h[0])==="object")for(_=h.map(function(ce){return ce.name}),b=h.map(function(ce){return ce.prompt||ce.name||""}),k=h.map(function(ce){return ce.align||"left"}),f=0;f0&&this.setTableHeaderRow(m),this.setFont(void 0,"normal"),n=!1}}(wo.API);var zRt={italic:["italic","oblique","normal"],oblique:["oblique","italic","normal"],normal:["normal","oblique","italic"]},BRt=["ultra-condensed","extra-condensed","condensed","semi-condensed","normal","semi-expanded","expanded","extra-expanded","ultra-expanded"],W7e=FRt(BRt),$Rt=[100,200,300,400,500,600,700,800,900],u1n=FRt($Rt);function MPe(s){var t=s.family.replace(/"|'/g,"").toLowerCase(),n=function(i){return zRt[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 W7e[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 Dpt(s,t,n,r){var a;for(a=n;a>=0&&a=0&&a>>1)&255}return a}function Gpt(s,t,n){var r=s.length,a=[];a[0]=4;for(var i=0;i>i&l}function Wpt(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,URt(s,i)&~(o<>7,l=1<<1+(7&a);s[t++],s[t++];var o=null,c=null;i&&(o=t,c=l,t+=3*l);var d=!0,u=[],h=0,m=null,f=0,g=null;for(this.width=n,this.height=r;d&&t=0))throw Error("Invalid block size");if($===0)break;t+=$}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),f=y>>2&7,t++;break;case 254:for(;;){if(!(($=s[t++])>=0))throw Error("Invalid block size");if($===0)break;t+=$}break;default:throw new Error("Unknown graphic control label: 0x"+s[t-1].toString(16))}break;case 44:var x=s[t++]|s[t++]<<8,_=s[t++]|s[t++]<<8,b=s[t++]|s[t++]<<8,k=s[t++]|s[t++]<<8,A=s[t++],T=A>>6&1,P=1<<1+(7&A),I=o,M=c,L=!1;A>>7&&(L=!0,I=t,M=P,t+=3*P);var z=t;for(t++;;){var $;if(!(($=s[t++])>=0))throw Error("Invalid block size");if($===0)break;t+=$}u.push({x,y:_,width:b,height:k,has_local_palette:L,palette_offset:I,palette_size:M,data_offset:z,data_length:t-z,transparent_index:m,interlaced:!!T,delay:h,disposal:f});break;case 59:d=!1;break;default:throw new Error("Unknown gif block: 0x"+s[t-1].toString(16))}this.numFrames=function(){return u.length},this.loopCount=function(){return g},this.frameInfo=function(V){if(V<0||V>=u.length)throw new Error("Frame index out of range.");return u[V]},this.decodeAndBlitFrameBGRA=function(V,W){var G=this.frameInfo(V),X=G.width*G.height;if(X>536870912)throw new Error("Image dimensions exceed 512MB, which is too large.");var te=new Uint8Array(X);Kpt(s,G.data_offset,te,X);var ne=G.palette_offset,me=G.transparent_index;me===null&&(me=256);var ue=G.width,ce=n-ue,ae=ue,he=4*(G.y*n+G.x),xe=4*((G.y+G.height)*n+G.x),ve=he,ge=4*ce;G.interlaced===!0&&(ge+=4*n*7);for(var be=8,Se=0,Ie=te.length;Se=xe&&(ge=4*ce+4*n*(be-1),ve=he+(ue+ce)*(be<<1),be>>=1)),Me===me)ve+=4;else{var Re=s[ne+3*Me],Be=s[ne+3*Me+1],Ne=s[ne+3*Me+2];W[ve++]=Ne,W[ve++]=Be,W[ve++]=Re,W[ve++]=255}--ae}},this.decodeAndBlitFrameRGBA=function(V,W){var G=this.frameInfo(V),X=G.width*G.height;if(X>536870912)throw new Error("Image dimensions exceed 512MB, which is too large.");var te=new Uint8Array(X);Kpt(s,G.data_offset,te,X);var ne=G.palette_offset,me=G.transparent_index;me===null&&(me=256);var ue=G.width,ce=n-ue,ae=ue,he=4*(G.y*n+G.x),xe=4*((G.y+G.height)*n+G.x),ve=he,ge=4*ce;G.interlaced===!0&&(ge+=4*n*7);for(var be=8,Se=0,Ie=te.length;Se=xe&&(ge=4*ce+4*n*(be-1),ve=he+(ue+ce)*(be<<1),be>>=1)),Me===me)ve+=4;else{var Re=s[ne+3*Me],Be=s[ne+3*Me+1],Ne=s[ne+3*Me+2];W[ve++]=Re,W[ve++]=Be,W[ve++]=Ne,W[ve++]=255}--ae}}}function Kpt(s,t,n,r){for(var a=s[t++],i=1<>=c,u-=c,x!==i){if(x===l)break;for(var _=xi;)k=g[k]>>8,++b;var A=k;if(m+b+(_!==x?1:0)>r)return void ph.log("Warning, gif stream longer than expected.");n[m++]=A;var T=m+=b;for(_!==x&&(n[m++]=A),k=_;b--;)k=g[k],n[--T]=255&k,k>>=8;y!==null&&o<4096&&(g[o++]=y<<8|A,o>=d+1&&c<12&&(++c,d=d<<1|1)),y=x}else o=l+1,d=(1<<(c=a+1))-1,y=null}return m!==r&&ph.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 IPe(s){var t,n,r,a,i,l=Math.floor,o=new Array(64),c=new Array(64),d=new Array(64),u=new Array(64),h=new Array(65535),m=new Array(65535),f=new Array(64),g=new Array(64),y=[],x=0,_=7,b=new Array(64),k=new Array(64),A=new Array(64),T=new Array(256),P=new Array(2048),I=[0,1,5,6,14,15,27,28,2,4,7,13,16,26,29,42,3,8,12,17,25,30,41,43,9,11,18,24,31,40,44,53,10,19,23,32,39,45,52,54,20,22,33,38,46,51,55,60,21,34,37,47,50,56,59,61,35,36,48,49,57,58,62,63],M=[0,0,1,5,1,1,1,1,1,1,0,0,0,0,0,0,0],L=[0,1,2,3,4,5,6,7,8,9,10,11],z=[0,0,2,1,3,3,2,4,3,5,5,4,4,0,0,1,125],$=[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],W=[0,1,2,3,4,5,6,7,8,9,10,11],G=[0,0,2,1,2,4,4,3,4,7,5,4,4,0,1,2,119],X=[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 te(he,xe){for(var ve=0,ge=0,be=new Array,Se=1;Se<=16;Se++){for(var Ie=1;Ie<=he[Se];Ie++)be[xe[ge]]=[],be[xe[ge]][0]=ve,be[xe[ge]][1]=Se,ge++,ve++;ve*=2}return be}function ne(he){for(var xe=he[0],ve=he[1]-1;ve>=0;)xe&1<>8&255),me(255&he)}function ce(he,xe,ve,ge,be){for(var Se,Ie=be[0],Me=be[240],Re=function(Ye,Je){var Ke,st,rt,Ze,ht,Bt,Ct,Yt,Kt,Xs,zs=0;for(Kt=0;Kt<8;++Kt){Ke=Ye[zs],st=Ye[zs+1],rt=Ye[zs+2],Ze=Ye[zs+3],ht=Ye[zs+4],Bt=Ye[zs+5],Ct=Ye[zs+6];var Vt=Ke+(Yt=Ye[zs+7]),At=Ke-Yt,Os=st+Ct,Nt=st-Ct,ms=rt+Bt,Ys=rt-Bt,It=Ze+ht,Ds=Ze-ht,As=Vt+It,Hs=Vt-It,Rs=Os+ms,en=Os-ms;Ye[zs]=As+Rs,Ye[zs+4]=As-Rs;var Rn=.707106781*(en+Hs);Ye[zs+2]=Hs+Rn,Ye[zs+6]=Hs-Rn;var Bn=.382683433*((As=Ds+Ys)-(en=Nt+At)),Dn=.5411961*As+Bn,Jn=1.306562965*en+Bn,ua=.707106781*(Rs=Ys+Nt),Mr=At+ua,sn=At-ua;Ye[zs+5]=sn+Dn,Ye[zs+3]=sn-Dn,Ye[zs+1]=Mr+Jn,Ye[zs+7]=Mr-Jn,zs+=8}for(zs=0,Kt=0;Kt<8;++Kt){Ke=Ye[zs],st=Ye[zs+8],rt=Ye[zs+16],Ze=Ye[zs+24],ht=Ye[zs+32],Bt=Ye[zs+40],Ct=Ye[zs+48];var ki=Ke+(Yt=Ye[zs+56]),ia=Ke-Yt,vr=st+Ct,Nr=st-Ct,rn=rt+Bt,Zn=rt-Bt,sa=Ze+ht,xs=Ze-ht,Ve=ki+sa,it=ki-sa,ft=vr+rn,kt=vr-rn;Ye[zs]=Ve+ft,Ye[zs+32]=Ve-ft;var Ut=.707106781*(kt+it);Ye[zs+16]=it+Ut,Ye[zs+48]=it-Ut;var es=.382683433*((Ve=xs+Zn)-(kt=Nr+ia)),Ms=.5411961*Ve+es,bs=1.306562965*kt+es,Zs=.707106781*(ft=Zn+Nr),kn=ia+Zs,gn=ia-Zs;Ye[zs+40]=gn+Ms,Ye[zs+24]=gn-Ms,Ye[zs+8]=kn+bs,Ye[zs+56]=kn-bs,zs++}for(Kt=0;Kt<64;++Kt)Xs=Ye[Kt]*Je[Kt],f[Kt]=Xs>0?Xs+.5|0:Xs-.5|0;return f}(he,xe),Be=0;Be<64;++Be)g[I[Be]]=Re[Be];var Ne=g[0]-ve;ve=g[0],Ne==0?ne(ge[0]):(ne(ge[m[Se=32767+Ne]]),ne(h[Se]));for(var Ge=63;Ge>0&&g[Ge]==0;)Ge--;if(Ge==0)return ne(Ie),ve;for(var Ce,Fe=1;Fe<=Ge;){for(var Ae=Fe;g[Fe]==0&&Fe<=Ge;)++Fe;var Xe=Fe-Ae;if(Xe>=16){Ce=Xe>>4;for(var $e=1;$e<=Ce;++$e)ne(Me);Xe&=15}Se=32767+g[Fe],ne(be[(Xe<<4)+m[Se]]),ne(h[Se]),Fe++}return Ge!=63&&ne(Ie),ve}function ae(he){he=Math.min(Math.max(he,1),100),i!=he&&(function(xe){for(var ve=[16,11,10,16,24,40,51,61,12,12,14,19,26,58,60,55,14,13,16,24,40,57,69,56,14,17,22,29,51,87,80,62,18,22,37,56,68,109,103,77,24,35,55,64,81,104,113,92,49,64,78,87,103,121,120,101,72,92,95,98,112,100,103,99],ge=0;ge<64;ge++){var be=l((ve[ge]*xe+50)/100);be=Math.min(Math.max(be,1),255),o[I[ge]]=be}for(var Se=[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],Ie=0;Ie<64;Ie++){var Me=l((Se[Ie]*xe+50)/100);Me=Math.min(Math.max(Me,1),255),c[I[Ie]]=Me}for(var Re=[1,1.387039845,1.306562965,1.175875602,1,.785694958,.5411961,.275899379],Be=0,Ne=0;Ne<8;Ne++)for(var Ge=0;Ge<8;Ge++)d[Be]=1/(o[I[Be]]*Re[Ne]*Re[Ge]*8),u[Be]=1/(c[I[Be]]*Re[Ne]*Re[Ge]*8),Be++}(he<50?Math.floor(5e3/he):Math.floor(200-2*he)),i=he)}this.encode=function(he,xe){xe&&ae(xe),y=new Array,x=0,_=7,ue(65496),ue(65504),ue(16),me(74),me(70),me(73),me(70),me(0),me(1),me(1),me(0),ue(1),ue(1),me(0),me(0),function(){ue(65499),ue(132),me(0);for(var st=0;st<64;st++)me(o[st]);me(1);for(var rt=0;rt<64;rt++)me(c[rt])}(),function(st,rt){ue(65472),ue(17),me(8),ue(rt),ue(st),me(3),me(1),me(17),me(0),me(2),me(17),me(1),me(3),me(17),me(1)}(he.width,he.height),function(){ue(65476),ue(418),me(0);for(var st=0;st<16;st++)me(M[st+1]);for(var rt=0;rt<=11;rt++)me(L[rt]);me(16);for(var Ze=0;Ze<16;Ze++)me(z[Ze+1]);for(var ht=0;ht<=161;ht++)me($[ht]);me(1);for(var Bt=0;Bt<16;Bt++)me(V[Bt+1]);for(var Ct=0;Ct<=11;Ct++)me(W[Ct]);me(17);for(var Yt=0;Yt<16;Yt++)me(G[Yt+1]);for(var Kt=0;Kt<=161;Kt++)me(X[Kt])}(),ue(65498),ue(12),me(3),me(1),me(0),me(2),me(17),me(3),me(17),me(0),me(63),me(0);var ve=0,ge=0,be=0;x=0,_=7,this.encode.displayName="_encode_";for(var Se,Ie,Me,Re,Be,Ne,Ge,Ce,Fe,Ae=he.data,Xe=he.width,$e=he.height,Ye=4*Xe,Je=0;Je<$e;){for(Se=0;Se>3)*Ye+(Ge=4*(7&Fe)),Je+Ce>=$e&&(Ne-=Ye*(Je+1+Ce-$e)),Se+Ge>=Ye&&(Ne-=Se+Ge-Ye+4),Ie=Ae[Ne++],Me=Ae[Ne++],Re=Ae[Ne++],b[Fe]=(P[Ie]+P[Me+256|0]+P[Re+512|0]>>16)-128,k[Fe]=(P[Ie+768|0]+P[Me+1024|0]+P[Re+1280|0]>>16)-128,A[Fe]=(P[Ie+1280|0]+P[Me+1536|0]+P[Re+1792|0]>>16)-128;ve=ce(b,d,ve,t,r),ge=ce(k,u,ge,n,a),be=ce(A,u,be,n,a),Se+=32}Je+=8}if(_>=0){var Ke=[];Ke[1]=_+1,Ke[0]=(1<<_+1)-1,ne(Ke)}return ue(65497),new Uint8Array(y)},s=s||50,function(){for(var he=String.fromCharCode,xe=0;xe<256;xe++)T[xe]=he(xe)}(),t=te(M,L),n=te(V,W),r=te(z,$),a=te(G,X),function(){for(var he=1,xe=2,ve=1;ve<=15;ve++){for(var ge=he;geV;V++)if(L[z+V]!=$.charCodeAt(V))return!0;return!1}function r(L,z,$,V,W){for(var G=0;GG+1?[]:new z),!(X.length>>0;ke&ut;)ut>>>=1;return ut?(ke&ut-1)+ut:ke}function $(ke,Oe,ut,yt,Gt){t(!(yt%ut));do ke[Oe+(yt-=ut)]=Gt;while(0=Gt),512>=Gt)var ns=i(512);else if((ns=i(Gt))==null)return 0;return function(ds,vs,Ts,Vs,bn,$n){var Gs,En,Kn=vs,wr=1<Gs;++Gs){if(ur[Gs]>1<(Ko-=ur[Gs]))return 0;for(;0=Gs;++Gs,bn<<=1){if(hi+=Ko<<=1,0>(Ko-=ur[Gs]))return 0;for(;0ha&&!(0>=(Pr-=ur[ha]));)++ha,Pr<<=1;wr+=wi=1<<(Pr=ha-Ts),ds[vs+(ha=Ei&aa)].g=Pr+Ts,ds[vs+ha].value=Kn-vs-ha}Vs.g=Gs-Ts,Vs.value=$n[En++],$(ds,Kn+(Ei>>Ts),bn,wi,Vs),Ei=z(Ei,Gs)}}return hi!=2*Ln[15]-1?0:wr}(ke,Oe,ut,yt,Gt,ns)}function W(){this.value=this.g=0}function G(){this.value=this.g=0}function X(){this.G=l(5,W),this.H=i(5),this.jc=this.Qb=this.qb=this.nd=0,this.pd=l(Pl,G)}function te(ke,Oe,ut,yt){t(ke!=null),t(Oe!=null),t(2147483648>yt),ke.Ca=254,ke.I=0,ke.b=-8,ke.Ka=0,ke.oa=Oe,ke.pa=ut,ke.Jd=Oe,ke.Yc=ut+yt,ke.Zc=4<=yt?ut+yt-4+1:ut,Ie(ke)}function ne(ke,Oe){for(var ut=0;0yt),ke.Sb=yt,ke.Ra=0,ke.u=0,ke.h=0,4>>=8,ke.Ra+=ke.oa[ke.pa+ke.bb]<>>0,++ke.bb,ke.u-=8;ge(ke)&&(ke.h=1,ke.u=0)}function ae(ke,Oe){if(t(0<=Oe),!ke.h&&Oe<=fm){var ut=ve(ke)&Na[Oe];return ke.u+=Oe,ce(ke),ut}return ke.h=1,ke.u=0}function he(){this.b=this.Ca=this.I=0,this.oa=[],this.pa=0,this.Jd=[],this.Yc=0,this.Zc=[],this.Ka=0}function xe(){this.Ra=0,this.oa=[],this.h=this.u=this.bb=this.Sb=this.pa=0}function ve(ke){return ke.Ra>>>(ke.u&td-1)>>>0}function ge(ke){return t(ke.bb<=ke.Sb),ke.h||ke.bb==ke.Sb&&ke.u>td}function be(ke,Oe){ke.u=Oe,ke.h=ge(ke)}function Se(ke){ke.u>=ra&&(t(ke.u>=ra),ce(ke))}function Ie(ke){t(ke!=null&&ke.oa!=null),ke.pa>>0,ke.b+=8):(t(ke!=null&&ke.oa!=null),ke.pake.b&&Ie(ke);var yt=ke.b,Gt=ut*Oe>>>8,ns=(ke.I>>>yt>Gt)+0;for(ns?(ut-=Gt,ke.I-=Gt+1<>>0):ut=Gt+1,yt=ut,Gt=0;256<=yt;)Gt+=8,yt>>=8;return yt=7^Gt+Eg[yt],ke.b-=yt,ke.Ca=(ut<>24&255,ke[Oe+1]=ut>>16&255,ke[Oe+2]=ut>>8&255,ke[Oe+3]=255&ut}function Ne(ke,Oe){return ke[Oe+0]|ke[Oe+1]<<8}function Ge(ke,Oe){return Ne(ke,Oe)|ke[Oe+2]<<16}function Ce(ke,Oe){return Ne(ke,Oe)|Ne(ke,Oe+2)<<16}function Fe(ke,Oe){var ut=1<=Gt||0>=ns?0:(ut[0]=Gt,yt[0]=ns,1)}function Ye(ke,Oe){return ke+(1<>>Oe}function Je(ke,Oe){return((4278255360&ke)+(4278255360&Oe)>>>0&4278255360)+((16711935&ke)+(16711935&Oe)>>>0&16711935)>>>0}function Ke(ke,Oe){L[Oe]=function(ut,yt,Gt,ns,ds,vs,Ts){var Vs;for(Vs=0;Vs>>1)+(ke&Oe)>>>0}function Ze(ke){return 0<=ke&&256>ke?ke:0>ke?0:255>1))}function Bt(ke,Oe,ut){return Math.abs(Oe-ut)-Math.abs(ke-ut)}function Ct(ke,Oe,ut,yt,Gt,ns,ds){for(yt=ns[ds-1],ut=0;ut>8&255,Ts=16711935&(Ts=(Ts=16711935&ds)+((vs<<16)+vs));yt[Gt+ns]=(4278255360&ds)+Ts>>>0}}function Kt(ke,Oe){Oe.jd=255&ke,Oe.hd=ke>>8&255,Oe.ud=ke>>16&255}function Xs(ke,Oe,ut,yt,Gt,ns){var ds;for(ds=0;ds>>8,Vs=vs,bn=255&(bn=(bn=vs>>>16)+((ke.jd<<24>>24)*(Ts<<24>>24)>>>5));Vs=255&(Vs=(Vs+=(ke.hd<<24>>24)*(Ts<<24>>24)>>>5)+((ke.ud<<24>>24)*(bn<<24>>24)>>>5)),Gt[ns+ds]=(4278255360&vs)+(bn<<16)+Vs}}function zs(ke,Oe,ut,yt,Gt){L[Oe]=function(ns,ds,vs,Ts,Vs,bn,$n,Gs,En){for(Ts=$n;Ts>ns.b,En=ns.Ea,Kn=ns.K[0],wr=ns.w;if(8>Gs)for(ns=(1<>=Gs}else L["VP8LMapColor"+ut](Ts,Vs,Kn,wr,bn,$n,ds,vs,En)}}function Vt(ke,Oe,ut,yt,Gt){for(ut=Oe+ut;Oe>16&255,yt[Gt++]=ns>>8&255,yt[Gt++]=255&ns}}function At(ke,Oe,ut,yt,Gt){for(ut=Oe+ut;Oe>16&255,yt[Gt++]=ns>>8&255,yt[Gt++]=255&ns,yt[Gt++]=ns>>24&255}}function Os(ke,Oe,ut,yt,Gt){for(ut=Oe+ut;Oe>16&240|ds>>12&15,ds=240&ds|ds>>28&15;yt[Gt++]=ns,yt[Gt++]=ds}}function Nt(ke,Oe,ut,yt,Gt){for(ut=Oe+ut;Oe>16&248|ds>>13&7,ds=ds>>5&224|ds>>3&31;yt[Gt++]=ns,yt[Gt++]=ds}}function ms(ke,Oe,ut,yt,Gt){for(ut=Oe+ut;Oe>8&255,yt[Gt++]=ns>>16&255}}function Ys(ke,Oe,ut,yt,Gt,ns){if(ns==0)for(ut=Oe+ut;Oe>24|ns[1]>>8&65280|ns[2]<<8&16711680|ns[3]<<24)>>>0),Gt+=32;else r(yt,Gt,ke,Oe,ut)}function It(ke,Oe){L[Oe][0]=L[ke+"0"],L[Oe][1]=L[ke+"1"],L[Oe][2]=L[ke+"2"],L[Oe][3]=L[ke+"3"],L[Oe][4]=L[ke+"4"],L[Oe][5]=L[ke+"5"],L[Oe][6]=L[ke+"6"],L[Oe][7]=L[ke+"7"],L[Oe][8]=L[ke+"8"],L[Oe][9]=L[ke+"9"],L[Oe][10]=L[ke+"10"],L[Oe][11]=L[ke+"11"],L[Oe][12]=L[ke+"12"],L[Oe][13]=L[ke+"13"],L[Oe][14]=L[ke+"0"],L[Oe][15]=L[ke+"0"]}function Ds(ke){return ke==nv||ke==Fj||ke==tw||ke==xx}function As(){this.eb=[],this.size=this.A=this.fb=0}function Hs(){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 Rs(){this.Rd=this.height=this.width=this.S=0,this.f={},this.f.RGBA=new As,this.f.kb=new Hs,this.sd=null}function en(){this.width=[0],this.height=[0],this.Pd=[0],this.Qd=[0],this.format=[0]}function Rn(){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 Bn(ke){return alert("todo:WebPSamplerProcessPlane"),ke.T}function Dn(ke,Oe){var ut=ke.T,yt=Oe.ba.f.RGBA,Gt=yt.eb,ns=yt.fb+ke.ka*yt.A,ds=$p[Oe.ba.S],vs=ke.y,Ts=ke.O,Vs=ke.f,bn=ke.N,$n=ke.ea,Gs=ke.W,En=Oe.cc,Kn=Oe.dc,wr=Oe.Mc,ur=Oe.Nc,Ln=ke.ka,Pr=ke.ka+ke.T,ha=ke.U,aa=ha+1>>1;for(Ln==0?ds(vs,Ts,null,null,Vs,bn,$n,Gs,Vs,bn,$n,Gs,Gt,ns,null,null,ha):(ds(Oe.ec,Oe.fc,vs,Ts,En,Kn,wr,ur,Vs,bn,$n,Gs,Gt,ns-yt.A,Gt,ns,ha),++ut);Ln+2ut,Gt=ut==p1||ut==Bp||ut==ly||ut==u0||ut==12||Ds(ut);if(Oe.memory=null,Oe.Ib=null,Oe.Jb=null,Oe.Nd=null,!il(Oe.Oa,ke,Gt?11:12))return 0;if(Gt&&Ds(ut)&&Gh(),ke.da)alert("todo:use_scaling");else{if(yt){if(Oe.Ib=Bn,ke.Kb){if(ut=ke.U+1>>1,Oe.memory=i(ke.U+2*ut),Oe.memory==null)return 0;Oe.ec=Oe.memory,Oe.fc=0,Oe.cc=Oe.ec,Oe.dc=Oe.fc+ke.U,Oe.Mc=Oe.cc,Oe.Nc=Oe.dc+ut,Oe.Ib=Dn,Gh()}}else alert("todo:EmitYUV");Gt&&(Oe.Jb=Jn,yt&&xc())}if(yt&&!ow){for(ke=0;256>ke;++ke)lw[ke]=89858*(ke-128)+aw>>cy,DN[ke]=-22014*(ke-128)+aw,$j[ke]=-45773*(ke-128),Pb[ke]=113618*(ke-128)+aw>>cy;for(ke=iw;ke>cy,K3[ke-iw]=dr(Oe,255),Ib[ke-iw]=dr(Oe+8>>4,15);ow=1}return 1}function Mr(ke){var Oe=ke.ma,ut=ke.U,yt=ke.T;return t(!(1&ke.ka)),0>=ut||0>=yt?0:(ut=Oe.Ib(ke,Oe),Oe.Jb!=null&&Oe.Jb(ke,Oe,ut),Oe.Dc+=ut,1)}function sn(ke){ke.ma.memory=null}function ki(ke,Oe,ut,yt){return ae(ke,8)!=47?0:(Oe[0]=ae(ke,14)+1,ut[0]=ae(ke,14)+1,yt[0]=ae(ke,1),ae(ke,3)!=0?0:!ke.h)}function ia(ke,Oe){if(4>ke)return ke+1;var ut=ke-2>>1;return(2+(1&ke)<>4)*ke+(8-(15&ut)))?ut:1;var ut}function Nr(ke,Oe,ut){var yt=ve(ut),Gt=ke[Oe+=255&yt].g-8;return 0>>0,t(8>=ut.g),ke.g}function Zn(ke,Oe,ut){var yt=ke.xc;return t((Oe=yt==0?0:ke.vc[ke.md*(ut>>yt)+(Oe>>yt)])>wi.b)*hi;wrha&&(Si=ha),(0,uu[xl[_d++]>>8&15])(Gs,En+ +Yo,Ln,Pr+Yo-ha,Si-Yo,Ln,Pr+Yo),Yo=Si}En+=ha,Pr+=ha,++wr&Ei||(wi+=hi)}$n!=Vs.nc&&r(Ts,vs-Kn,Ts,vs+($n-bn-1)*Kn,Kn);break;case 1:for(Kn=Gs,ur=En,ha=(Gs=Vs.Ea)-(Pr=Gs&~(Ln=(En=1<>Vs.b)*wr;bn<$n;){for(Ei=aa,hi=Vs,Ko=new st,wi=ur+Pr,xl=ur+Gs;ur=Gt),0ns.o&&(yt=ns.o),ut=yt?ut=0:(Gt[0]+=4*ns.v,ns.ka=ut-ns.j,ns.U=ns.va-ns.v,ns.T=yt-ut,ut=1),ut){if(vs=vs[0],11>(ut=ke.ca).S){var bn=ut.f.RGBA,$n=(yt=ut.S,Gt=ns.U,ns=ns.T,Vs=bn.eb,bn.A),Gs=ns;for(bn=bn.fb+ke.Ma*bn.A;0yt){var Gt=ke.l.width,ns=ut.ca,ds=ut.tb+Gt*yt,vs=ke.V,Ts=ke.Ba+ke.c*yt,Vs=ke.gc;t(ke.ab==1),t(Vs[0].hc==3),tp(Vs[0],yt,Oe,vs,Ts,ns,ds),it(ut,yt,Oe,ns,ds,Gt)}ke.C=ke.Ma=Oe}function kt(ke,Oe,ut,yt,Gt,ns,ds){var vs=ke.$/yt,Ts=ke.$%yt,Vs=ke.m,bn=ke.s,$n=ut+ke.$,Gs=$n;Gt=ut+yt*Gt;var En=ut+yt*ns,Kn=280+bn.ua,wr=ke.Pb?vs:16777216,ur=0=wr){var Ei=$n-ut;t((wr=ke).Pb),wr.wd=wr.m,wr.xd=Ei,0Ko.g?(be(aa,aa.u+Ko.g),Ei[hi]=Ko.value,aa=0):(be(aa,aa.u+Ko.g-256),t(256<=Ko.value),aa=Ko.value),aa==0&&(ha=!0)}else aa=Nr(Pr.G[0],Pr.H[0],Vs);if(Vs.h)break;if(ha||256>aa){if(!ha)if(Pr.nd)Oe[$n]=(Pr.qb|aa<<8)>>>0;else{if(Se(Vs),ha=Nr(Pr.G[1],Pr.H[1],Vs),Se(Vs),Ei=Nr(Pr.G[2],Pr.H[2],Vs),hi=Nr(Pr.G[3],Pr.H[3],Vs),Vs.h)break;Oe[$n]=(hi<<24|ha<<16|aa<<8|Ei)>>>0}if(ha=!1,++$n,++Ts>=yt&&(Ts=0,++vs,ds!=null&&vs<=ns&&!(vs%16)&&ds(ke,vs),ur!=null))for(;Gs<$n;)aa=Oe[Gs++],ur.X[(506832829*aa&4294967295)>>>ur.Mb]=aa}else if(280>aa){if(aa=ia(aa-256,Vs),Ei=Nr(Pr.G[4],Pr.H[4],Vs),Se(Vs),Ei=vr(yt,Ei=ia(Ei,Vs)),Vs.h)break;if($n-ut=yt;)Ts-=yt,++vs,ds!=null&&vs<=ns&&!(vs%16)&&ds(ke,vs);if(t($n<=Gt),Ts&Ln&&(Pr=Zn(bn,Ts,vs)),ur!=null)for(;Gs<$n;)aa=Oe[Gs++],ur.X[(506832829*aa&4294967295)>>>ur.Mb]=aa}else{if(!(aa>>ur.Mb]=aa;aa=$n,t(!(ha>>>(Ei=ur).Xa)),Oe[aa]=Ei.X[ha],ha=!0}ha||t(Vs.h==ge(Vs))}if(ke.Pb&&Vs.h&&$nns?ns:vs),ke.a=0,ke.$=$n-ut}return 1}return ke.a=3,0}function Ut(ke){t(ke!=null),ke.vc=null,ke.yc=null,ke.Ya=null;var Oe=ke.Wa;Oe!=null&&(Oe.X=null),ke.vb=null,t(ke!=null)}function es(){var ke=new mr;return ke==null?null:(ke.a=0,ke.xb=cS,It("Predictor","VP8LPredictors"),It("Predictor","VP8LPredictors_C"),It("PredictorAdd","VP8LPredictorsAdd"),It("PredictorAdd","VP8LPredictorsAdd_C"),i0=Yt,qc=Xs,sp=Vt,ev=At,tv=Os,yc=Nt,Mg=ms,L.VP8LMapColor32b=Lc,L.VP8LMapColor8b=ih,ke)}function Ms(ke,Oe,ut,yt,Gt){var ns=1,ds=[ke],vs=[Oe],Ts=yt.m,Vs=yt.s,bn=null,$n=0;e:for(;;){if(ut)for(;ns&&ae(Ts,1);){var Gs=ds,En=vs,Kn=yt,wr=1,ur=Kn.m,Ln=Kn.gc[Kn.ab],Pr=ae(ur,2);if(Kn.Oc&1<=Kn.ab),Pr){case 0:case 1:Ln.b=ae(ur,3)+2,wr=Ms(Ye(Ln.Ea,Ln.b),Ye(Ln.nc,Ln.b),0,Kn,Ln.K),Ln.K=Ln.K[0];break;case 3:var ha,aa=ae(ur,8)+1,Ei=16>wi.b),_d=i(xl);if(_d==null)ha=0;else{var Yo=wi.K[0],Si=wi.w;for(_d[0]=wi.K[0][0],hi=1;hi<1*Ko;++hi)_d[hi]=Je(Yo[Si+hi],_d[hi-1]);for(;hi<4*xl;++hi)_d[hi]=0;wi.K[0]=null,wi.K[0]=_d,ha=1}}wr=ha;break;case 2:break;default:t(0)}ns=wr}}if(ds=ds[0],vs=vs[0],ns&&ae(Ts,1)&&!(ns=1<=($n=ae(Ts,4))&&11>=$n)){yt.a=3;break e}var Ga;if(Ga=ns)t:{var Qo,so,zo,hd=yt,jh=ds,md=vs,Kd=$n,zd=ut,qp=hd.m,sd=hd.s,oc=[null],Hc=1,pu=0,bc=W3[Kd];s:for(;;){if(zd&&ae(qp,1)){var Lu=ae(qp,3)+2,gm=Ye(jh,Lu),Pc=Ye(md,Lu),Zu=gm*Pc;if(!Ms(gm,Pc,0,hd,oc))break s;for(oc=oc[0],sd.xc=Lu,Qo=0;Qo>8&65535;oc[Qo]=Dl,Dl>=Hc&&(Hc=Dl+1)}}if(qp.h)break s;for(so=0;5>so;++so){var Pu=TN[so];!so&&0=wd),Hp=Vp;var ym=i(pu);if(Hp==null||ym==null||xm==null){hd.a=1;break s}var dh=xm;for(Qo=zo=0;Qoso;++so){Pu=TN[so],pr[so]=dh,fo[so]=zo,!so&&0b1)break n}else hy=b1;for(sg=0;sgw1)pw[sg++]=w1,w1!=0&&(p0=w1);else{var hS=w1==16,RN=w1-16,iv=no[RN],ov=ae(fu,aS[RN])+iv;if(sg+ov>b1)break n;for(var mS=hS?p0:0;0=so){var lv,_x=ym[0];for(lv=1;lv_x&&(_x=ym[lv]);cc+=_x}}if(lc.nd=Xl,lc.Qb=0,Xl&&(lc.qb=(pr[3][fo[3]+0].value<<24|pr[1][fo[1]+0].value<<16|pr[2][fo[2]+0].value)>>>0,kc==0&&256>pr[0][fo[0]+0].value&&(lc.Qb=1,lc.qb+=pr[0][fo[0]+0].value<<8)),lc.jc=!lc.Qb&&6>cc,lc.jc){var Uj,Iu=lc;for(Uj=0;Uj>=rn(Kp,8,jd),Yh>>=rn(Iu.G[1][Iu.H[1]+Yh],16,jd),Yh>>=rn(Iu.G[2][Iu.H[2]+Yh],0,jd),rn(Iu.G[3][Iu.H[3]+Yh],24,jd))}}}sd.vc=oc,sd.Wb=Hc,sd.Ya=Hp,sd.yc=xm,Ga=1;break t}Ga=0}if(!(ns=Ga)){yt.a=3;break e}if(0<$n){if(Vs.ua=1<<$n,!Fe(Vs.Wa,$n)){yt.a=1,ns=0;break e}}else Vs.ua=0;var ON=yt,qj=ds,FN=vs,f0=ON.s,zN=f0.xc;if(ON.c=qj,ON.i=FN,f0.md=Ye(qj,zN),f0.wc=zN==0?-1:(1<yt+1?[]:0),!(Gt.lengthke?0:ke>Oe?Oe:ke}function Wi(){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 ho(){var ke=new ea;return ke!=null&&(ke.a=0,ke.sc="OK",ke.cb=0,ke.Xb=0,f1||(f1=Ta)),ke}function oa(ke,Oe,ut){return ke.a==0&&(ke.a=Oe,ke.sc=ut,ke.cb=0),0}function Ha(ke,Oe,ut){return 3<=ut&&ke[Oe+0]==157&&ke[Oe+1]==1&&ke[Oe+2]==42}function $i(ke,Oe){if(ke==null)return 0;if(ke.a=0,ke.sc="OK",Oe==null)return oa(ke,2,"null VP8Io passed to VP8GetHeaders()");var ut=Oe.data,yt=Oe.w,Gt=Oe.ha;if(4>Gt)return oa(ke,7,"Truncated header.");var ns=ut[yt+0]|ut[yt+1]<<8|ut[yt+2]<<16,ds=ke.Od;if(ds.Rb=!(1&ns),ds.td=ns>>1&7,ds.yd=ns>>4&1,ds.ub=ns>>5,3Gt)return oa(ke,7,"cannot parse picture header");if(!Ha(ut,yt,Gt))return oa(ke,3,"Bad code word");vs.c=16383&(ut[yt+4]<<8|ut[yt+3]),vs.Td=ut[yt+4]>>6,vs.i=16383&(ut[yt+6]<<8|ut[yt+5]),vs.Ud=ut[yt+6]>>6,yt+=7,Gt-=7,ke.za=vs.c+15>>4,ke.Ub=vs.i+15>>4,Oe.width=vs.c,Oe.height=vs.i,Oe.Da=0,Oe.j=0,Oe.v=0,Oe.va=Oe.width,Oe.o=Oe.height,Oe.da=0,Oe.ib=Oe.width,Oe.hb=Oe.height,Oe.U=Oe.width,Oe.T=Oe.height,a((ns=ke.Pa).jb,0,255,ns.jb.length),t((ns=ke.Qa)!=null),ns.Cb=0,ns.Bb=0,ns.Fb=1,a(ns.Zb,0,0,ns.Zb.length),a(ns.Lb,0,0,ns.Lb)}if(ds.ub>Gt)return oa(ke,7,"bad partition length");te(ns=ke.m,ut,yt,ds.ub),yt+=ds.ub,Gt-=ds.ub,ds.Rb&&(vs.Ld=Me(ns),vs.Kd=Me(ns)),vs=ke.Qa;var Ts,Vs=ke.Pa;if(t(ns!=null),t(vs!=null),vs.Cb=Me(ns),vs.Cb){if(vs.Bb=Me(ns),Me(ns)){for(vs.Fb=Me(ns),Ts=0;4>Ts;++Ts)vs.Zb[Ts]=Me(ns)?me(ns,7):0;for(Ts=0;4>Ts;++Ts)vs.Lb[Ts]=Me(ns)?me(ns,6):0}if(vs.Bb)for(Ts=0;3>Ts;++Ts)Vs.jb[Ts]=Me(ns)?ne(ns,8):255}else vs.Bb=0;if(ns.Ka)return oa(ke,3,"cannot parse segment header");if((vs=ke.ed).zd=Me(ns),vs.Tb=ne(ns,6),vs.wb=ne(ns,3),vs.Pc=Me(ns),vs.Pc&&Me(ns)){for(Vs=0;4>Vs;++Vs)Me(ns)&&(vs.vd[Vs]=me(ns,6));for(Vs=0;4>Vs;++Vs)Me(ns)&&(vs.od[Vs]=me(ns,6))}if(ke.L=vs.Tb==0?0:vs.zd?1:2,ns.Ka)return oa(ke,3,"cannot parse filter header");var bn=Gt;if(Gt=Ts=yt,yt=Ts+bn,vs=bn,ke.Xb=(1<vs&&($n=vs),te(ke.Jc[+bn],ut,Ts,$n),Ts+=$n,vs-=$n,Gt+=3}te(ke.Jc[+Vs],ut,Ts,vs),ut=Ts$n;++$n){if(bn.Cb){var Gs=bn.Zb[$n];bn.Fb||(Gs+=ut)}else{if(0<$n){ke.pb[$n]=ke.pb[0];continue}Gs=ut}var En=ke.pb[$n];En.Sc[0]=Mb[dr(Gs+Gt,127)],En.Sc[1]=lS[dr(Gs+0,127)],En.Eb[0]=2*Mb[dr(Gs+yt,127)],En.Eb[1]=101581*lS[dr(Gs+vs,127)]>>16,8>En.Eb[1]&&(En.Eb[1]=8),En.Qc[0]=Mb[dr(Gs+Vs,117)],En.Qc[1]=lS[dr(Gs+Ts,127)],En.lc=Gs+Ts}if(!ds.Rb)return oa(ke,4,"Not a key frame.");for(Me(ns),ds=ke.Pa,ut=0;4>ut;++ut){for(Gt=0;8>Gt;++Gt)for(yt=0;3>yt;++yt)for(vs=0;11>vs;++vs)Vs=Re(ns,g1[ut][Gt][yt][vs])?ne(ns,8):Lb[ut][Gt][yt][vs],ds.Wc[ut][Gt].Yb[yt][vs]=Vs;for(Gt=0;17>Gt;++Gt)ds.Xc[ut][Gt]=ds.Wc[ut][x1[Gt]]}return ke.kc=Me(ns),ke.kc&&(ke.Bd=ne(ns,8)),ke.cb=1}function Ta(ke,Oe,ut,yt,Gt,ns,ds){var vs=Oe[Gt].Yb[ut];for(ut=0;16>Gt;++Gt){if(!Re(ke,vs[ut+0]))return Gt;for(;!Re(ke,vs[ut+1]);)if(vs=Oe[++Gt].Yb[0],ut=0,Gt==16)return 16;var Ts=Oe[Gt+1].Yb;if(Re(ke,vs[ut+2])){var Vs=ke,bn=0;if(Re(Vs,(Gs=vs)[($n=ut)+3]))if(Re(Vs,Gs[$n+6])){for(vs=0,$n=2*(bn=Re(Vs,Gs[$n+8]))+(Gs=Re(Vs,Gs[$n+9+bn])),bn=0,Gs=i6[$n];Gs[vs];++vs)bn+=bn+Re(Vs,Gs[vs]);bn+=3+(8<<$n)}else Re(Vs,Gs[$n+7])?(bn=7+2*Re(Vs,165),bn+=Re(Vs,145)):bn=5+Re(Vs,159);else bn=Re(Vs,Gs[$n+4])?3+Re(Vs,Gs[$n+5]):2;vs=Ts[2]}else bn=1,vs=Ts[1];Ts=ds+yx[Gt],0>(Vs=ke).b&&Ie(Vs);var $n,Gs=Vs.b,En=($n=Vs.Ca>>1)-(Vs.I>>Gs)>>31;--Vs.b,Vs.Ca+=En,Vs.Ca|=1,Vs.I-=($n+1&En)<>3),ke[Oe+ut+32*yt]=-256&Gt?0>Gt?0:255:Gt}function mo(ke,Oe,ut,yt,Gt,ns){Ra(ke,Oe,0,ut,yt+Gt),Ra(ke,Oe,1,ut,yt+ns),Ra(ke,Oe,2,ut,yt-ns),Ra(ke,Oe,3,ut,yt-Gt)}function Ho(ke){return(20091*ke>>16)+ke}function No(ke,Oe,ut,yt){var Gt,ns=0,ds=i(16);for(Gt=0;4>Gt;++Gt){var vs=ke[Oe+0]+ke[Oe+8],Ts=ke[Oe+0]-ke[Oe+8],Vs=(35468*ke[Oe+4]>>16)-Ho(ke[Oe+12]),bn=Ho(ke[Oe+4])+(35468*ke[Oe+12]>>16);ds[ns+0]=vs+bn,ds[ns+1]=Ts+Vs,ds[ns+2]=Ts-Vs,ds[ns+3]=vs-bn,ns+=4,Oe++}for(Gt=ns=0;4>Gt;++Gt)vs=(ke=ds[ns+0]+4)+ds[ns+8],Ts=ke-ds[ns+8],Vs=(35468*ds[ns+4]>>16)-Ho(ds[ns+12]),Ra(ut,yt,0,0,vs+(bn=Ho(ds[ns+4])+(35468*ds[ns+12]>>16))),Ra(ut,yt,1,0,Ts+Vs),Ra(ut,yt,2,0,Ts-Vs),Ra(ut,yt,3,0,vs-bn),ns++,yt+=32}function Go(ke,Oe,ut,yt){var Gt=ke[Oe+0]+4,ns=35468*ke[Oe+4]>>16,ds=Ho(ke[Oe+4]),vs=35468*ke[Oe+1]>>16;mo(ut,yt,0,Gt+ds,ke=Ho(ke[Oe+1]),vs),mo(ut,yt,1,Gt+ns,ke,vs),mo(ut,yt,2,Gt-ns,ke,vs),mo(ut,yt,3,Gt-ds,ke,vs)}function Dd(ke,Oe,ut,yt,Gt){No(ke,Oe,ut,yt),Gt&&No(ke,Oe+16,ut,yt+4)}function Tu(ke,Oe,ut,yt){oh(ke,Oe+0,ut,yt,1),oh(ke,Oe+32,ut,yt+128,1)}function Vm(ke,Oe,ut,yt){var Gt;for(ke=ke[Oe+0]+4,Gt=0;4>Gt;++Gt)for(Oe=0;4>Oe;++Oe)Ra(ut,yt,Oe,Gt,ke)}function Uc(ke,Oe,ut,yt){ke[Oe+0]&&hu(ke,Oe+0,ut,yt),ke[Oe+16]&&hu(ke,Oe+16,ut,yt+4),ke[Oe+32]&&hu(ke,Oe+32,ut,yt+128),ke[Oe+48]&&hu(ke,Oe+48,ut,yt+128+4)}function Eu(ke,Oe,ut,yt){var Gt,ns=i(16);for(Gt=0;4>Gt;++Gt){var ds=ke[Oe+0+Gt]+ke[Oe+12+Gt],vs=ke[Oe+4+Gt]+ke[Oe+8+Gt],Ts=ke[Oe+4+Gt]-ke[Oe+8+Gt],Vs=ke[Oe+0+Gt]-ke[Oe+12+Gt];ns[0+Gt]=ds+vs,ns[8+Gt]=ds-vs,ns[4+Gt]=Vs+Ts,ns[12+Gt]=Vs-Ts}for(Gt=0;4>Gt;++Gt)ds=(ke=ns[0+4*Gt]+3)+ns[3+4*Gt],vs=ns[1+4*Gt]+ns[2+4*Gt],Ts=ns[1+4*Gt]-ns[2+4*Gt],Vs=ke-ns[3+4*Gt],ut[yt+0]=ds+vs>>3,ut[yt+16]=Vs+Ts>>3,ut[yt+32]=ds-vs>>3,ut[yt+48]=Vs-Ts>>3,yt+=64}function Ec(ke,Oe,ut){var yt,Gt=Oe-32,ns=ch,ds=255-ke[Gt-1];for(yt=0;ytut;++ut)r(ke,Oe+32*ut,ke,Oe-32,16)}function ay(ke,Oe){var ut;for(ut=16;0yt;++yt)a(Oe,ut+32*yt,ke,16)}function jf(ke,Oe){var ut,yt=16;for(ut=0;16>ut;++ut)yt+=ke[Oe-1+32*ut]+ke[Oe+ut-32];wf(yt>>5,ke,Oe)}function cu(ke,Oe){var ut,yt=8;for(ut=0;16>ut;++ut)yt+=ke[Oe-1+32*ut];wf(yt>>4,ke,Oe)}function Sg(ke,Oe){var ut,yt=8;for(ut=0;16>ut;++ut)yt+=ke[Oe+ut-32];wf(yt>>4,ke,Oe)}function Eo(ke,Oe){wf(128,ke,Oe)}function po(ke,Oe,ut){return ke+2*Oe+ut+2>>2}function Gm(ke,Oe){var ut,yt=Oe-32;for(yt=new Uint8Array([po(ke[yt-1],ke[yt+0],ke[yt+1]),po(ke[yt+0],ke[yt+1],ke[yt+2]),po(ke[yt+1],ke[yt+2],ke[yt+3]),po(ke[yt+2],ke[yt+3],ke[yt+4])]),ut=0;4>ut;++ut)r(ke,Oe+32*ut,yt,0,yt.length)}function hm(ke,Oe){var ut=ke[Oe-1],yt=ke[Oe-1+32],Gt=ke[Oe-1+64],ns=ke[Oe-1+96];Be(ke,Oe+0,16843009*po(ke[Oe-1-32],ut,yt)),Be(ke,Oe+32,16843009*po(ut,yt,Gt)),Be(ke,Oe+64,16843009*po(yt,Gt,ns)),Be(ke,Oe+96,16843009*po(Gt,ns,ns))}function Cg(ke,Oe){var ut,yt=4;for(ut=0;4>ut;++ut)yt+=ke[Oe+ut-32]+ke[Oe-1+32*ut];for(yt>>=3,ut=0;4>ut;++ut)a(ke,Oe+32*ut,yt,4)}function wh(ke,Oe){var ut=ke[Oe-1+0],yt=ke[Oe-1+32],Gt=ke[Oe-1+64],ns=ke[Oe-1-32],ds=ke[Oe+0-32],vs=ke[Oe+1-32],Ts=ke[Oe+2-32],Vs=ke[Oe+3-32];ke[Oe+0+96]=po(yt,Gt,ke[Oe-1+96]),ke[Oe+1+96]=ke[Oe+0+64]=po(ut,yt,Gt),ke[Oe+2+96]=ke[Oe+1+64]=ke[Oe+0+32]=po(ns,ut,yt),ke[Oe+3+96]=ke[Oe+2+64]=ke[Oe+1+32]=ke[Oe+0+0]=po(ds,ns,ut),ke[Oe+3+64]=ke[Oe+2+32]=ke[Oe+1+0]=po(vs,ds,ns),ke[Oe+3+32]=ke[Oe+2+0]=po(Ts,vs,ds),ke[Oe+3+0]=po(Vs,Ts,vs)}function Bl(ke,Oe){var ut=ke[Oe+1-32],yt=ke[Oe+2-32],Gt=ke[Oe+3-32],ns=ke[Oe+4-32],ds=ke[Oe+5-32],vs=ke[Oe+6-32],Ts=ke[Oe+7-32];ke[Oe+0+0]=po(ke[Oe+0-32],ut,yt),ke[Oe+1+0]=ke[Oe+0+32]=po(ut,yt,Gt),ke[Oe+2+0]=ke[Oe+1+32]=ke[Oe+0+64]=po(yt,Gt,ns),ke[Oe+3+0]=ke[Oe+2+32]=ke[Oe+1+64]=ke[Oe+0+96]=po(Gt,ns,ds),ke[Oe+3+32]=ke[Oe+2+64]=ke[Oe+1+96]=po(ns,ds,vs),ke[Oe+3+64]=ke[Oe+2+96]=po(ds,vs,Ts),ke[Oe+3+96]=po(vs,Ts,Ts)}function Wm(ke,Oe){var ut=ke[Oe-1+0],yt=ke[Oe-1+32],Gt=ke[Oe-1+64],ns=ke[Oe-1-32],ds=ke[Oe+0-32],vs=ke[Oe+1-32],Ts=ke[Oe+2-32],Vs=ke[Oe+3-32];ke[Oe+0+0]=ke[Oe+1+64]=ns+ds+1>>1,ke[Oe+1+0]=ke[Oe+2+64]=ds+vs+1>>1,ke[Oe+2+0]=ke[Oe+3+64]=vs+Ts+1>>1,ke[Oe+3+0]=Ts+Vs+1>>1,ke[Oe+0+96]=po(Gt,yt,ut),ke[Oe+0+64]=po(yt,ut,ns),ke[Oe+0+32]=ke[Oe+1+96]=po(ut,ns,ds),ke[Oe+1+32]=ke[Oe+2+96]=po(ns,ds,vs),ke[Oe+2+32]=ke[Oe+3+96]=po(ds,vs,Ts),ke[Oe+3+32]=po(vs,Ts,Vs)}function bd(ke,Oe){var ut=ke[Oe+0-32],yt=ke[Oe+1-32],Gt=ke[Oe+2-32],ns=ke[Oe+3-32],ds=ke[Oe+4-32],vs=ke[Oe+5-32],Ts=ke[Oe+6-32],Vs=ke[Oe+7-32];ke[Oe+0+0]=ut+yt+1>>1,ke[Oe+1+0]=ke[Oe+0+64]=yt+Gt+1>>1,ke[Oe+2+0]=ke[Oe+1+64]=Gt+ns+1>>1,ke[Oe+3+0]=ke[Oe+2+64]=ns+ds+1>>1,ke[Oe+0+32]=po(ut,yt,Gt),ke[Oe+1+32]=ke[Oe+0+96]=po(yt,Gt,ns),ke[Oe+2+32]=ke[Oe+1+96]=po(Gt,ns,ds),ke[Oe+3+32]=ke[Oe+2+96]=po(ns,ds,vs),ke[Oe+3+64]=po(ds,vs,Ts),ke[Oe+3+96]=po(vs,Ts,Vs)}function n0(ke,Oe){var ut=ke[Oe-1+0],yt=ke[Oe-1+32],Gt=ke[Oe-1+64],ns=ke[Oe-1+96];ke[Oe+0+0]=ut+yt+1>>1,ke[Oe+2+0]=ke[Oe+0+32]=yt+Gt+1>>1,ke[Oe+2+32]=ke[Oe+0+64]=Gt+ns+1>>1,ke[Oe+1+0]=po(ut,yt,Gt),ke[Oe+3+0]=ke[Oe+1+32]=po(yt,Gt,ns),ke[Oe+3+32]=ke[Oe+1+64]=po(Gt,ns,ns),ke[Oe+3+64]=ke[Oe+2+64]=ke[Oe+0+96]=ke[Oe+1+96]=ke[Oe+2+96]=ke[Oe+3+96]=ns}function kb(ke,Oe){var ut=ke[Oe-1+0],yt=ke[Oe-1+32],Gt=ke[Oe-1+64],ns=ke[Oe-1+96],ds=ke[Oe-1-32],vs=ke[Oe+0-32],Ts=ke[Oe+1-32],Vs=ke[Oe+2-32];ke[Oe+0+0]=ke[Oe+2+32]=ut+ds+1>>1,ke[Oe+0+32]=ke[Oe+2+64]=yt+ut+1>>1,ke[Oe+0+64]=ke[Oe+2+96]=Gt+yt+1>>1,ke[Oe+0+96]=ns+Gt+1>>1,ke[Oe+3+0]=po(vs,Ts,Vs),ke[Oe+2+0]=po(ds,vs,Ts),ke[Oe+1+0]=ke[Oe+3+32]=po(ut,ds,vs),ke[Oe+1+32]=ke[Oe+3+64]=po(yt,ut,ds),ke[Oe+1+64]=ke[Oe+3+96]=po(Gt,yt,ut),ke[Oe+1+96]=po(ns,Gt,yt)}function Km(ke,Oe){var ut;for(ut=0;8>ut;++ut)r(ke,Oe+32*ut,ke,Oe-32,8)}function _i(ke,Oe){var ut;for(ut=0;8>ut;++ut)a(ke,Oe,ke[Oe-1],8),Oe+=32}function Ym(ke,Oe,ut){var yt;for(yt=0;8>yt;++yt)a(Oe,ut+32*yt,ke,8)}function iy(ke,Oe){var ut,yt=8;for(ut=0;8>ut;++ut)yt+=ke[Oe+ut-32]+ke[Oe-1+32*ut];Ym(yt>>4,ke,Oe)}function qh(ke,Oe){var ut,yt=4;for(ut=0;8>ut;++ut)yt+=ke[Oe+ut-32];Ym(yt>>3,ke,Oe)}function Fp(ke,Oe){var ut,yt=4;for(ut=0;8>ut;++ut)yt+=ke[Oe-1+32*ut];Ym(yt>>3,ke,Oe)}function Zm(ke,Oe){Ym(128,ke,Oe)}function mm(ke,Oe,ut){var yt=ke[Oe-ut],Gt=ke[Oe+0],ns=3*(Gt-yt)+Tb[1020+ke[Oe-2*ut]-ke[Oe+ut]],ds=np[112+(ns+4>>3)];ke[Oe-ut]=ch[255+yt+np[112+(ns+3>>3)]],ke[Oe+0]=ch[255+Gt-ds]}function Qf(ke,Oe,ut,yt){var Gt=ke[Oe+0],ns=ke[Oe+ut];return sr[255+ke[Oe-2*ut]-ke[Oe-ut]]>yt||sr[255+ns-Gt]>yt}function mx(ke,Oe,ut,yt){return 4*sr[255+ke[Oe-ut]-ke[Oe+0]]+sr[255+ke[Oe-2*ut]-ke[Oe+ut]]<=yt}function Xm(ke,Oe,ut,yt,Gt){var ns=ke[Oe-3*ut],ds=ke[Oe-2*ut],vs=ke[Oe-ut],Ts=ke[Oe+0],Vs=ke[Oe+ut],bn=ke[Oe+2*ut],$n=ke[Oe+3*ut];return 4*sr[255+vs-Ts]+sr[255+ds-Vs]>yt?0:sr[255+ke[Oe-4*ut]-ns]<=Gt&&sr[255+ns-ds]<=Gt&&sr[255+ds-vs]<=Gt&&sr[255+$n-bn]<=Gt&&sr[255+bn-Vs]<=Gt&&sr[255+Vs-Ts]<=Gt}function Vh(ke,Oe,ut,yt){var Gt=2*yt+1;for(yt=0;16>yt;++yt)mx(ke,Oe+yt,ut,Gt)&&mm(ke,Oe+yt,ut)}function zp(ke,Oe,ut,yt){var Gt=2*yt+1;for(yt=0;16>yt;++yt)mx(ke,Oe+yt*ut,1,Gt)&&mm(ke,Oe+yt*ut,1)}function Ag(ke,Oe,ut,yt){var Gt;for(Gt=3;0>7,Ln=18*Pr+63>>7,Pr=9*Pr+63>>7;Ts[Vs-3*bn]=ch[255+Ts[Vs-3*bn]+Pr],Ts[Vs-2*bn]=ch[255+$n+Ln],Ts[Vs-bn]=ch[255+Gs+ur],Ts[Vs+0]=ch[255+En-ur],Ts[Vs+bn]=ch[255+Kn-Ln],Ts[Vs+2*bn]=ch[255+wr-Pr]}Oe+=yt}}function Nc(ke,Oe,ut,yt,Gt,ns,ds,vs){for(ns=2*ns+1;0>3)],wr=np[112+(wr+3>>3)],ur=Kn+1>>1;Ts[Vs-2*bn]=ch[255+Ts[Vs-2*bn]+ur],Ts[Vs-bn]=ch[255+$n+wr],Ts[Vs+0]=ch[255+Gs-Kn],Ts[Vs+bn]=ch[255+En-ur]}Oe+=yt}}function Qm(ke,Oe,ut,yt,Gt,ns){Jc(ke,Oe,ut,1,16,yt,Gt,ns)}function Rd(ke,Oe,ut,yt,Gt,ns){Jc(ke,Oe,1,ut,16,yt,Gt,ns)}function Jm(ke,Oe,ut,yt,Gt,ns){var ds;for(ds=3;0Vs?0:255:Vs)&255,Vs=Ts,Gt[ns+vs]=bn}}function Mc(ke,Oe,ut,yt){var Gt=Oe.width,ns=Oe.o;if(t(ke!=null&&Oe!=null),0>ut||0>=yt||ut+yt>ns)return null;if(!ke.Cc){if(ke.ga==null){var ds;if(ke.ga=new Ba,(ds=ke.ga==null)||(ds=Oe.width*Oe.o,t(ke.Gb.length==0),ke.Gb=i(ds),ke.Uc=0,ke.Gb==null?ds=0:(ke.mb=ke.Gb,ke.nb=ke.Uc,ke.rc=null,ds=1),ds=!ds),!ds){ds=ke.ga;var vs=ke.Fa,Ts=ke.P,Vs=ke.qc,bn=ke.mb,$n=ke.nb,Gs=Ts+1,En=Vs-1,Kn=ds.l;if(t(vs!=null&&bn!=null&&Oe!=null),eg[0]=null,eg[1]=Ki,eg[2]=Ui,eg[3]=tl,ds.ca=bn,ds.tb=$n,ds.c=Oe.width,ds.i=Oe.height,t(0=Vs)Oe=0;else if(ds.$a=3&vs[Ts+0],ds.Z=vs[Ts+0]>>2&3,ds.Lc=vs[Ts+0]>>4&3,Ts=vs[Ts+0]>>6&3,0>ds.$a||1=ds.c*ds.i;ds=!Oe}if(ds)return null;ke.ga.Lc!=1?ke.Ga=0:yt=ns-ut}t(ke.ga!=null),t(ut+yt<=ns);e:{if(Oe=(vs=ke.ga).c,ns=vs.l.o,vs.$a==0){if(Gs=ke.rc,En=ke.Vc,Kn=ke.Fa,Ts=ke.P+1+ut*Oe,Vs=ke.mb,bn=ke.nb+ut*Oe,t(Ts<=ke.P+ke.qc),vs.Z!=0)for(t(eg[vs.Z]!=null),ds=0;ds=Oe)Oe=1;else if(vs.ic||xc(),vs.ic){vs=ds.V,Gs=ds.Ba,En=ds.c;var wr=ds.i,ur=(Kn=1,Ts=ds.$/En,Vs=ds.$%En,bn=ds.m,$n=ds.s,ds.$),Ln=En*wr,Pr=En*Oe,ha=$n.wc,aa=ur(wr=Nr(aa.G[0],aa.H[0],bn)))vs[Gs+ur]=wr,++ur,++Vs>=En&&(Vs=0,++Ts<=Oe&&!(Ts%16)&&ft(ds,Ts));else{if(!(280>wr)){Kn=0;break t}wr=ia(wr-256,bn);var Ei,hi=Nr(aa.G[4],aa.H[4],bn);if(Se(bn),!(ur>=(hi=vr(En,hi=ia(hi,bn)))&&Ln-ur>=wr)){Kn=0;break t}for(Ei=0;Ei=En;)Vs-=En,++Ts<=Oe&&!(Ts%16)&&ft(ds,Ts);urOe?Oe:Ts);break t}!Kn||bn.h&&ur=ns&&(ke.Cc=1),yt=1}if(!yt)return null;if(ke.Cc&&((yt=ke.ga)!=null&&(yt.mc=null),ke.ga=null,0>23,vs[Ts+4*ds+1]=vs[Ts+4*ds+1]*$n>>23,vs[Ts+4*ds+2]=vs[Ts+4*ds+2]*$n>>23)}Oe+=ns}}function Za(ke,Oe,ut,yt,Gt){for(;0>4)*Ts>>16;ke[Oe+2*ns+0]=(240&ds|ds>>4)*Ts>>16&240|(15&ds|ds<<4)*Ts>>16>>4&15,ke[Oe+2*ns+1]=240&Vs|vs}Oe+=Gt}}function ci(ke,Oe,ut,yt,Gt,ns,ds,vs){var Ts,Vs,bn=255;for(Vs=0;Vs>8}function xc(){c0=Lr,ew=Za,d0=ci,Ab=jl}function qi(ke,Oe,ut){L[ke]=function(yt,Gt,ns,ds,vs,Ts,Vs,bn,$n,Gs,En,Kn,wr,ur,Ln,Pr,ha){var aa,Ei=ha-1>>1,hi=vs[Ts+0]|Vs[bn+0]<<16,Ko=$n[Gs+0]|En[Kn+0]<<16;t(yt!=null);var wi=3*hi+Ko+131074>>2;for(Oe(yt[Gt+0],255&wi,wi>>16,wr,ur),ns!=null&&(wi=3*Ko+hi+131074>>2,Oe(ns[ds+0],255&wi,wi>>16,Ln,Pr)),aa=1;aa<=Ei;++aa){var xl=vs[Ts+aa]|Vs[bn+aa]<<16,_d=$n[Gs+aa]|En[Kn+aa]<<16,Yo=hi+xl+Ko+_d+524296,Si=Yo+2*(xl+Ko)>>3;wi=Si+hi>>1,hi=(Yo=Yo+2*(hi+_d)>>3)+xl>>1,Oe(yt[Gt+2*aa-1],255&wi,wi>>16,wr,ur+(2*aa-1)*ut),Oe(yt[Gt+2*aa-0],255&hi,hi>>16,wr,ur+(2*aa-0)*ut),ns!=null&&(wi=Yo+Ko>>1,hi=Si+_d>>1,Oe(ns[ds+2*aa-1],255&wi,wi>>16,Ln,Pr+(2*aa-1)*ut),Oe(ns[ds+2*aa+0],255&hi,hi>>16,Ln,Pr+(2*aa+0)*ut)),hi=xl,Ko=_d}1&ha||(wi=3*hi+Ko+131074>>2,Oe(yt[Gt+ha-1],255&wi,wi>>16,wr,ur+(ha-1)*ut),ns!=null&&(wi=3*Ko+hi+131074>>2,Oe(ns[ds+ha-1],255&wi,wi>>16,Ln,Pr+(ha-1)*ut)))}}function Gh(){$p[m1]=Bj,$p[p1]=nw,$p[sv]=MN,$p[Bp]=rw,$p[ly]=Up,$p[u0]=rp,$p[Eb]=dS,$p[nv]=nw,$p[Fj]=rw,$p[tw]=Up,$p[xx]=rp}function px(ke){return ke&~IN?0>ke?0:255:ke>>PN}function fx(ke,Oe){return px((19077*ke>>8)+(26149*Oe>>8)-14234)}function du(ke,Oe,ut){return px((19077*ke>>8)-(6419*Oe>>8)-(13320*ut>>8)+8708)}function $l(ke,Oe){return px((19077*ke>>8)+(33050*Oe>>8)-17685)}function c1(ke,Oe,ut,yt,Gt){yt[Gt+0]=fx(ke,ut),yt[Gt+1]=du(ke,Oe,ut),yt[Gt+2]=$l(ke,Oe)}function Tg(ke,Oe,ut,yt,Gt){yt[Gt+0]=$l(ke,Oe),yt[Gt+1]=du(ke,Oe,ut),yt[Gt+2]=fx(ke,ut)}function r0(ke,Oe,ut,yt,Gt){var ns=du(ke,Oe,ut);Oe=ns<<3&224|$l(ke,Oe)>>3,yt[Gt+0]=248&fx(ke,ut)|ns>>5,yt[Gt+1]=Oe}function Od(ke,Oe,ut,yt,Gt){var ns=240&$l(ke,Oe)|15;yt[Gt+0]=240&fx(ke,ut)|du(ke,Oe,ut)>>4,yt[Gt+1]=ns}function ep(ke,Oe,ut,yt,Gt){yt[Gt+0]=255,c1(ke,Oe,ut,yt,Gt+1)}function a0(ke,Oe,ut,yt,Gt){Tg(ke,Oe,ut,yt,Gt),yt[Gt+3]=255}function oy(ke,Oe,ut,yt,Gt){c1(ke,Oe,ut,yt,Gt),yt[Gt+3]=255}function ed(ke,Oe,ut){L[ke]=function(yt,Gt,ns,ds,vs,Ts,Vs,bn,$n){for(var Gs=bn+(-2&$n)*ut;bn!=Gs;)Oe(yt[Gt+0],ns[ds+0],vs[Ts+0],Vs,bn),Oe(yt[Gt+1],ns[ds+0],vs[Ts+0],Vs,bn+ut),Gt+=2,++ds,++Ts,bn+=2*ut;1&$n&&Oe(yt[Gt+0],ns[ds+0],vs[Ts+0],Vs,bn)}}function ud(ke,Oe,ut){return ut==0?ke==0?Oe==0?6:5:Oe==0?4:0:ut}function Mu(ke,Oe,ut,yt,Gt){switch(ke>>>30){case 3:oh(Oe,ut,yt,Gt,0);break;case 2:Sf(Oe,ut,yt,Gt);break;case 1:hu(Oe,ut,yt,Gt)}}function pm(ke,Oe){var ut,yt,Gt=Oe.M,ns=Oe.Nb,ds=ke.oc,vs=ke.pc+40,Ts=ke.oc,Vs=ke.pc+584,bn=ke.oc,$n=ke.pc+600;for(ut=0;16>ut;++ut)ds[vs+32*ut-1]=129;for(ut=0;8>ut;++ut)Ts[Vs+32*ut-1]=129,bn[$n+32*ut-1]=129;for(0ut;++ut)r(ds,vs+32*ut-4,ds,vs+32*ut+12,4);for(ut=-1;8>ut;++ut)r(Ts,Vs+32*ut-4,Ts,Vs+32*ut+4,4),r(bn,$n+32*ut-4,bn,$n+32*ut+4,4)}var En=ke.Gd,Kn=ke.Hd+yt,wr=Gs.ad,ur=Gs.Hc;if(0=ke.za-1?a(Ln,Pr,En[Kn].y[15],4):r(Ln,Pr,En[Kn+1].y,0,4)),ut=0;4>ut;ut++)Ln[Pr+128+ut]=Ln[Pr+256+ut]=Ln[Pr+384+ut]=Ln[Pr+0+ut];for(ut=0;16>ut;++ut,ur<<=2)Ln=ds,Pr=vs+dy[ut],Wd[Gs.Ob[ut]](Ln,Pr),Mu(ur,wr,16*+ut,Ln,Pr)}else if(Ln=ud(yt,Gt,Gs.Ob[0]),Cf[Ln](ds,vs),ur!=0)for(ut=0;16>ut;++ut,ur<<=2)Mu(ur,wr,16*+ut,ds,vs+dy[ut]);for(ut=Gs.Gc,Ln=ud(yt,Gt,Gs.Dd),vx[Ln](Ts,Vs),vx[Ln](bn,$n),ur=wr,Ln=Ts,Pr=Vs,255&(Gs=0|ut)&&(170&Gs?d1(ur,256,Ln,Pr):Il(ur,256,Ln,Pr)),Gs=bn,ur=$n,255&(ut>>=8)&&(170&ut?d1(wr,320,Gs,ur):Il(wr,320,Gs,ur)),Gtut;++ut)r(En,Kn+ut*ke.R,ds,vs+32*ut,16);for(ut=0;8>ut;++ut)r(wr,Gs+ut*ke.B,Ts,Vs+32*ut,8),r(ur,Ln+ut*ke.B,bn,$n+32*ut,8)}}function Nf(ke,Oe,ut,yt,Gt,ns,ds,vs,Ts){var Vs=[0],bn=[0],$n=0,Gs=Ts!=null?Ts.kd:0,En=Ts??new tn;if(ke==null||12>ut)return 7;En.data=ke,En.w=Oe,En.ha=ut,Oe=[Oe],ut=[ut],En.gb=[En.gb];e:{var Kn=Oe,wr=ut,ur=En.gb;if(t(ke!=null),t(wr!=null),t(ur!=null),ur[0]=0,12<=wr[0]&&!n(ke,Kn[0],"RIFF")){if(n(ke,Kn[0]+8,"WEBP")){ur=3;break e}var Ln=Ce(ke,Kn[0]+4);if(12>Ln||4294967286wr[0]-8){ur=7;break e}ur[0]=Ln,Kn[0]+=12,wr[0]-=12}ur=0}if(ur!=0)return ur;for(Ln=0ur[0])ur=7;else{if(!n(Pr,wr[0],"VP8X")){if(Ce(Pr,wr[0]+4)!=10){ur=3;break e}if(18>ur[0]){ur=7;break e}var hi=Ce(Pr,wr[0]+8),Ko=1+Ge(Pr,wr[0]+12);if(2147483648<=Ko*(Pr=1+Ge(Pr,wr[0]+15))){ur=3;break e}Ei!=null&&(Ei[0]=hi),ha!=null&&(ha[0]=Ko),aa!=null&&(aa[0]=Pr),wr[0]+=18,ur[0]-=18,wi[0]=1}ur=0}}if($n=$n[0],Kn=Kn[0],ur!=0)return ur;if(wr=!!(2&Kn),!Ln&&$n)return 3;if(ns!=null&&(ns[0]=!!(16&Kn)),ds!=null&&(ds[0]=wr),vs!=null&&(vs[0]=0),ds=Vs[0],Kn=bn[0],$n&&wr&&Ts==null){ur=0;break}if(4>ut){ur=7;break}if(Ln&&$n||!Ln&&!$n&&!n(ke,Oe[0],"ALPH")){ut=[ut],En.na=[En.na],En.P=[En.P],En.Sa=[En.Sa];e:{hi=ke,ur=Oe,Ln=ut;var wi=En.gb;ha=En.na,aa=En.P,Ei=En.Sa,Ko=22,t(hi!=null),t(Ln!=null),Pr=ur[0];var xl=Ln[0];for(t(ha!=null),t(Ei!=null),ha[0]=null,aa[0]=null,Ei[0]=0;;){if(ur[0]=Pr,Ln[0]=xl,8>xl){ur=7;break e}var _d=Ce(hi,Pr+4);if(4294967286<_d){ur=3;break e}var Yo=8+_d+1&-2;if(Ko+=Yo,0wi){ur=3;break e}if(!n(hi,Pr,"VP8 ")||!n(hi,Pr,"VP8L")){ur=0;break e}if(xl[0]Ln[0])ur=7;else{if(Pr||Ko){if(wi=Ce(wi,hi+4),12<=ha&&wi>ha-12){ur=3;break e}if(Gs&&wi>Ln[0]-8){ur=7;break e}aa[0]=wi,ur[0]+=8,Ln[0]-=8,Ei[0]=Ko}else Ei[0]=5<=Ln[0]&&wi[hi+0]==47&&!(wi[hi+4]>>5),aa[0]=Ln[0];ur=0}if(ut=ut[0],En.Ja=En.Ja[0],En.xa=En.xa[0],Oe=Oe[0],ur!=0)break;if(4294967286ut){ur=7;break}vs=ds,Gs=Kn,wr=ns,ke==null||5>ut?ke=0:5<=ut&&ke[Oe+0]==47&&!(ke[Oe+4]>>5)?(Ln=[0],wi=[0],ha=[0],ue(aa=new xe,ke,Oe,ut),ki(aa,Ln,wi,ha)?(vs!=null&&(vs[0]=Ln[0]),Gs!=null&&(Gs[0]=wi[0]),wr!=null&&(wr[0]=ha[0]),ke=1):ke=0):ke=0}else{if(10>ut){ur=7;break}vs=Kn,ke==null||10>ut||!Ha(ke,Oe+3,ut-3)?ke=0:(Gs=ke[Oe+0]|ke[Oe+1]<<8|ke[Oe+2]<<16,wr=16383&(ke[Oe+7]<<8|ke[Oe+6]),ke=16383&(ke[Oe+9]<<8|ke[Oe+8]),1&Gs||3<(Gs>>1&7)||!(Gs>>4&1)||Gs>>5>=En.Ja||!wr||!ke?ke=0:(ds&&(ds[0]=wr),vs&&(vs[0]=ke),ke=1))}if(!ke||(ds=ds[0],Kn=Kn[0],$n&&(Vs[0]!=ds||bn[0]!=Kn)))return 3;Ts!=null&&(Ts[0]=En,Ts.offset=Oe-Ts.w,t(4294967286>Oe-Ts.w),t(Ts.offset==Ts.ha-ut));break}return ur==0||ur==7&&$n&&Ts==null?(ns!=null&&(ns[0]|=En.na!=null&&0ut||(ns&=-2,ds&=-2),0>ns||0>ds||0>=vs||0>=Ts||ns+vs>yt||ds+Ts>Gt))return 0;if(Oe.v=ns,Oe.j=ds,Oe.va=ns+vs,Oe.o=ds+Ts,Oe.U=vs,Oe.T=Ts,Oe.da=ke!=null&&0ke.S){var Oe=ke.f.RGBA;Oe.fb+=(ke.height-1)*Oe.A,Oe.A=-Oe.A}else Oe=ke.f.kb,ke=ke.height,Oe.O+=(ke-1)*Oe.fa,Oe.fa=-Oe.fa,Oe.N+=(ke-1>>1)*Oe.Ab,Oe.Ab=-Oe.Ab,Oe.W+=(ke-1>>1)*Oe.Db,Oe.Db=-Oe.Db,Oe.F!=null&&(Oe.J+=(ke-1)*Oe.lb,Oe.lb=-Oe.lb);return 0}function Ir(ke,Oe,ut,yt){if(yt==null||0>=ke||0>=Oe)return 2;if(ut!=null){if(ut.Da){var Gt=ut.cd,ns=ut.bd,ds=-2&ut.v,vs=-2&ut.j;if(0>ds||0>vs||0>=Gt||0>=ns||ds+Gt>ke||vs+ns>Oe)return 2;ke=Gt,Oe=ns}if(ut.da){if(!$e(ke,Oe,Gt=[ut.ib],ns=[ut.hb]))return 2;ke=Gt[0],Oe=ns[0]}}yt.width=ke,yt.height=Oe;e:{var Ts=yt.width,Vs=yt.height;if(ke=yt.S,0>=Ts||0>=Vs||!(ke>=m1&&13>ke))ke=2;else{if(0>=yt.Rd&&yt.sd==null){ds=ns=Gt=Oe=0;var bn=(vs=Ts*Db[ke])*Vs;if(11>ke||(ns=(Vs+1)/2*(Oe=(Ts+1)/2),ke==12&&(ds=(Gt=Ts)*Vs)),(Vs=i(bn+2*ns+ds))==null){ke=1;break e}yt.sd=Vs,11>ke?((Ts=yt.f.RGBA).eb=Vs,Ts.fb=0,Ts.A=vs,Ts.size=bn):((Ts=yt.f.kb).y=Vs,Ts.O=0,Ts.fa=vs,Ts.Fd=bn,Ts.f=Vs,Ts.N=0+bn,Ts.Ab=Oe,Ts.Cd=ns,Ts.ea=Vs,Ts.W=0+bn+ns,Ts.Db=Oe,Ts.Ed=ns,ke==12&&(Ts.F=Vs,Ts.J=0+bn+2*ns),Ts.Tc=ds,Ts.lb=Gt)}if(Oe=1,Gt=yt.S,ns=yt.width,ds=yt.height,Gt>=m1&&13>Gt)if(11>Gt)ke=yt.f.RGBA,Oe&=(vs=Math.abs(ke.A))*(ds-1)+ns<=ke.size,Oe&=vs>=ns*Db[Gt],Oe&=ke.eb!=null;else{ke=yt.f.kb,vs=(ns+1)/2,bn=(ds+1)/2,Ts=Math.abs(ke.fa),Vs=Math.abs(ke.Ab);var $n=Math.abs(ke.Db),Gs=Math.abs(ke.lb),En=Gs*(ds-1)+ns;Oe&=Ts*(ds-1)+ns<=ke.Fd,Oe&=Vs*(bn-1)+vs<=ke.Cd,Oe=(Oe&=$n*(bn-1)+vs<=ke.Ed)&Ts>=ns&Vs>=vs&$n>=vs,Oe&=ke.y!=null,Oe&=ke.f!=null,Oe&=ke.ea!=null,Gt==12&&(Oe&=Gs>=ns,Oe&=En<=ke.Tc,Oe&=ke.F!=null)}else Oe=0;ke=Oe?0:2}}return ke!=0||ut!=null&&ut.fd&&(ke=wa(yt)),ke}var Pl=64,Na=[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],fm=24,td=32,ra=8,Eg=[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];Ke("Predictor0","PredictorAdd0"),L.Predictor0=function(){return 4278190080},L.Predictor1=function(ke){return ke},L.Predictor2=function(ke,Oe,ut){return Oe[ut+0]},L.Predictor3=function(ke,Oe,ut){return Oe[ut+1]},L.Predictor4=function(ke,Oe,ut){return Oe[ut-1]},L.Predictor5=function(ke,Oe,ut){return rt(rt(ke,Oe[ut+1]),Oe[ut+0])},L.Predictor6=function(ke,Oe,ut){return rt(ke,Oe[ut-1])},L.Predictor7=function(ke,Oe,ut){return rt(ke,Oe[ut+0])},L.Predictor8=function(ke,Oe,ut){return rt(Oe[ut-1],Oe[ut+0])},L.Predictor9=function(ke,Oe,ut){return rt(Oe[ut+0],Oe[ut+1])},L.Predictor10=function(ke,Oe,ut){return rt(rt(ke,Oe[ut-1]),rt(Oe[ut+0],Oe[ut+1]))},L.Predictor11=function(ke,Oe,ut){var yt=Oe[ut+0];return 0>=Bt(yt>>24&255,ke>>24&255,(Oe=Oe[ut-1])>>24&255)+Bt(yt>>16&255,ke>>16&255,Oe>>16&255)+Bt(yt>>8&255,ke>>8&255,Oe>>8&255)+Bt(255&yt,255&ke,255&Oe)?yt:ke},L.Predictor12=function(ke,Oe,ut){var yt=Oe[ut+0];return(Ze((ke>>24&255)+(yt>>24&255)-((Oe=Oe[ut-1])>>24&255))<<24|Ze((ke>>16&255)+(yt>>16&255)-(Oe>>16&255))<<16|Ze((ke>>8&255)+(yt>>8&255)-(Oe>>8&255))<<8|Ze((255&ke)+(255&yt)-(255&Oe)))>>>0},L.Predictor13=function(ke,Oe,ut){var yt=Oe[ut-1];return(ht((ke=rt(ke,Oe[ut+0]))>>24&255,yt>>24&255)<<24|ht(ke>>16&255,yt>>16&255)<<16|ht(ke>>8&255,yt>>8&255)<<8|ht(255&ke,255&yt))>>>0};var gx=L.PredictorAdd0;L.PredictorAdd1=Ct,Ke("Predictor2","PredictorAdd2"),Ke("Predictor3","PredictorAdd3"),Ke("Predictor4","PredictorAdd4"),Ke("Predictor5","PredictorAdd5"),Ke("Predictor6","PredictorAdd6"),Ke("Predictor7","PredictorAdd7"),Ke("Predictor8","PredictorAdd8"),Ke("Predictor9","PredictorAdd9"),Ke("Predictor10","PredictorAdd10"),Ke("Predictor11","PredictorAdd11"),Ke("Predictor12","PredictorAdd12"),Ke("Predictor13","PredictorAdd13");var Jf=L.PredictorAdd2;zs("ColorIndexInverseTransform","MapARGB","32b",function(ke){return ke>>8&255},function(ke){return ke}),zs("VP8LColorIndexInverseTransformAlpha","MapAlpha","8b",function(ke){return ke},function(ke){return ke>>8&255});var i0,kf=L.ColorIndexInverseTransform,Lc=L.MapARGB,tp=L.VP8LColorIndexInverseTransformAlpha,ih=L.MapAlpha,uu=L.VP8LPredictorsAdd=[];uu.length=16,(L.VP8LPredictors=[]).length=16,(L.VP8LPredictorsAdd_C=[]).length=16,(L.VP8LPredictors_C=[]).length=16;var qc,sp,ev,tv,yc,Mg,o0,oh,Sf,d1,hu,Il,Wo,Oo,Fd,Vc,Lg,l0,lh,Sb,J_,Cb,Pg,mu,c0,ew,d0,Ab,Dj=i(511),Rj=i(2041),u1=i(225),h1=i(767),Oj=0,Tb=Rj,np=u1,ch=h1,sr=Dj,m1=0,p1=1,sv=2,Bp=3,ly=4,u0=5,Eb=6,nv=7,Fj=8,tw=9,xx=10,aS=[2,3,7],no=[3,3,11],TN=[280,256,256,256,40],iS=[0,1,1,1,0],a6=[17,18,0,1,2,3,4,5,16,6,7,8,9,10,11,12,13,14,15],oS=[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],W3=[2954,2956,2958,2962,2970,2986,3018,3082,3212,3468,3980,5004],vc=8,Mb=[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],lS=[4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,60,62,64,66,68,70,72,74,76,78,80,82,84,86,88,90,92,94,96,98,100,102,104,106,108,110,112,114,116,119,122,125,128,131,134,137,140,143,146,149,152,155,158,161,164,167,170,173,177,181,185,189,193,197,201,205,209,213,217,221,225,229,234,239,245,249,254,259,264,269,274,279,284],f1=null,i6=[[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]],yx=[0,1,4,8,5,2,3,6,9,12,13,10,7,11,14,15],sw=[-0,1,-1,2,-2,3,4,6,-3,5,-4,-5,-6,7,-7,8,-8,-9],Lb=[[[[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]]]],EN=[[[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]]],g1=[[[[255,255,255,255,255,255,255,255,255,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]]]],x1=[0,1,2,3,6,4,5,6,6,6,6,6,6,6,6,7,0],Cf=[],Wd=[],vx=[],zj=1,cS=2,eg=[],$p=[];qi("UpsampleRgbLinePair",c1,3),qi("UpsampleBgrLinePair",Tg,3),qi("UpsampleRgbaLinePair",oy,4),qi("UpsampleBgraLinePair",a0,4),qi("UpsampleArgbLinePair",ep,4),qi("UpsampleRgba4444LinePair",Od,2),qi("UpsampleRgb565LinePair",r0,2);var Bj=L.UpsampleRgbLinePair,MN=L.UpsampleBgrLinePair,nw=L.UpsampleRgbaLinePair,rw=L.UpsampleBgraLinePair,Up=L.UpsampleArgbLinePair,rp=L.UpsampleRgba4444LinePair,dS=L.UpsampleRgb565LinePair,cy=16,aw=1<yt.ca.S||(alert("todo:WebPInitConvertARGBToYUV"),yt.ca.f.kb.F!=null&&xc()),yt.Pb&&0(Ts=ut.Md)?0:100Vs;++Vs)12>($n=Gt.pb[Vs]).lc&&($n.ia=Ts*Wh[0>$n.lc?0:$n.lc]>>3),bn|=$n.ia;bn&&(alert("todo:VP8InitRandom"),Gt.ia=1)}Gt.Ga=ut.Id,100Gt.Ga&&(Gt.Ga=0)}(function(Gs,En){if(Gs==null)return 0;if(En==null)return oa(Gs,2,"NULL VP8Io parameter in VP8Decode().");if(!Gs.cb&&!$i(Gs,En))return 0;if(t(Gs.cb),En.ac==null||En.ac(En)){En.ob&&(Gs.L=0);var Kn=cw[Gs.L];if(Gs.L==2?(Gs.yb=0,Gs.zb=0):(Gs.yb=En.v-Kn>>4,Gs.zb=En.j-Kn>>4,0>Gs.yb&&(Gs.yb=0),0>Gs.zb&&(Gs.zb=0)),Gs.Va=En.o+15+Kn>>4,Gs.Hb=En.va+15+Kn>>4,Gs.Hb>Gs.za&&(Gs.Hb=Gs.za),Gs.Va>Gs.Ub&&(Gs.Va=Gs.Ub),0Kn;++Kn){var ur;if(Gs.Qa.Cb){var Ln=Gs.Qa.Lb[Kn];Gs.Qa.Fb||(Ln+=wr.Tb)}else Ln=wr.Tb;for(ur=0;1>=ur;++ur){var Pr=Gs.gd[Kn][ur],ha=Ln;if(wr.Pc&&(ha+=wr.vd[0],ur&&(ha+=wr.od[0])),0<(ha=0>ha?0:63>2:aa>>1)>9-wr.wb&&(aa=9-wr.wb),1>aa&&(aa=1),Pr.dd=aa,Pr.tc=2*ha+aa,Pr.ld=40<=ha?2:15<=ha?1:0}else Pr.tc=0;Pr.La=ur}}}Kn=0}else oa(Gs,6,"Frame setup failed"),Kn=Gs.a;if(Kn=Kn==0){if(Kn){Gs.$c=0,0Gs.Vb){if(Gs.Vb=0,Gs.Ec=i(Pr),Gs.Fc=0,Gs.Ec==null){Kn=oa(Gs,1,"no memory during frame initialization.");break t}Gs.Vb=Pr}Pr=Gs.Ec,ha=Gs.Fc,Gs.Ac=Pr,Gs.Bc=ha,ha+=wr,Gs.Gd=l(Ei,ja),Gs.Hd=0,Gs.rb=l(hi+1,Xt),Gs.sb=1,Gs.wa=Ko?l(Ko,qr):null,Gs.Y=0,Gs.D.Nb=0,Gs.D.wa=Gs.wa,Gs.D.Y=Gs.Y,0=Kn;++Kn)Dj[255+Kn]=0>Kn?-Kn:Kn;for(Kn=-1020;1020>=Kn;++Kn)Rj[1020+Kn]=-128>Kn?-128:127=Kn;++Kn)u1[112+Kn]=-16>Kn?-16:15=Kn;++Kn)h1[255+Kn]=0>Kn?0:255zo;++zo){var sd,oc=md[0+zo];for(sd=0;4>sd;++sd){oc=EN[hd[jh+sd]][oc];for(var Hc=sw[Re(so,oc[0])];0>3;for(Hc=0;256>Hc;Hc+=16)zo[zd+Hc]=Zu}Lu=1,gm=jh[0]}var Dl=15&so.la,Pu=15&qp.la;for(Hc=0;4>Hc;++Hc){var xm=1&Pu;for(Zu=bc=0;4>Zu;++Zu)Dl=Dl>>1|(xm=(Pc=f1(hd,gm,Pc=xm+(1&Dl),Kd.Sc,Lu,zo,zd))>Lu)<<7,bc=bc<<2|(3>=4,Pu=Pu>>1|xm<<7,sd=(sd<<8|bc)>>>0}for(gm=Dl,Lu=Pu>>4,pu=0;4>pu;pu+=2){for(bc=0,Dl=so.la>>4+pu,Pu=qp.la>>4+pu,Hc=0;2>Hc;++Hc){for(xm=1&Pu,Zu=0;2>Zu;++Zu)Pc=xm+(1&Dl),Dl=Dl>>1|(xm=0<(Pc=f1(hd,jh[2],Pc,Kd.Qc,0,zo,zd)))<<3,bc=bc<<2|(3>=2,Pu=Pu>>1|xm<<5}oc|=bc<<4*pu,gm|=Dl<<4<=Si.zb&&Si.M<=Si.Va,Si.Aa==0)t:{if(Yo.M=Si.M,Yo.uc=so,pm(Si,Yo),Qo=1,Yo=(bc=Si.D).Nb,so=(oc=cw[Si.L])*Si.R,hd=oc/2*Si.B,Hc=16*Yo*Si.R,Zu=8*Yo*Si.B,jh=Si.sa,md=Si.ta-so+Hc,Kd=Si.qa,zo=Si.ra-hd+Zu,zd=Si.Ha,qp=Si.Ia-hd+Zu,Pu=(Dl=bc.M)==0,sd=Dl>=Si.Va-1,Si.Aa==2&&pm(Si,bc),bc.uc)for(xm=(Pc=Si).D.M,t(Pc.D.uc),bc=Pc.yb;bcGa.o&&(Dl=Ga.o),Ga.F=null,Ga.J=null,Si.Fa!=null&&0>1),Ga.W+=Si.B*(oc>>1),Ga.F!=null&&(Ga.J+=Ga.width*oc)),bc>1,Ga.W+=Ga.v>>1,Ga.F!=null&&(Ga.J+=Ga.v),Ga.ka=bc-Ga.j,Ga.U=Ga.va-Ga.v,Ga.T=Dl-bc,Qo=Ga.put(Ga))}Yo+1!=Si.Ic||sd||(r(Si.sa,Si.ta-so,jh,md+16*Si.R,so),r(Si.qa,Si.ra-hd,Kd,zo+8*Si.B,hd),r(Si.Ha,Si.Ia-hd,zd,qp+8*Si.B,hd))}if(!Qo)return oa(xl,6,"Output aborted.")}return 1}(Gs,En)),En.bc!=null&&En.bc(En),Kn&=1}return Kn?(Gs.cb=0,Kn):0})(ke,yt)||(Oe=ke.a)}}else Oe=ke.a}Oe==0&&ds.Oa!=null&&ds.Oa.fd&&(Oe=wa(ds.ba))}ds=Oe}ns=ds!=0?null:11>ns?vs.f.RGBA.eb:vs.f.kb.y}else ns=null;return ns};var Db=[3,4,3,4,4,2,2,4,4,4,2,1,1]};function d(L,z){for(var $="",V=0;V<4;V++)$+=String.fromCharCode(L[z++]);return $}function u(L,z){return L[z+0]|L[z+1]<<8}function h(L,z){return(L[z+0]|L[z+1]<<8|L[z+2]<<16)>>>0}function m(L,z){return(L[z+0]|L[z+1]<<8|L[z+2]<<16|L[z+3]<<24)>>>0}new c;var f=[0],g=[0],y=[],x=new c,_=s,b=function(L,z){var $={},V=0,W=!1,G=0,X=0;if($.frames=[],!function(he,xe){for(var ve=0;ve<4;ve++)if(he[xe+ve]!="RIFF".charCodeAt(ve))return!0;return!1}(L,z)){for(m(L,z+=4),z+=8;z>1&1}te!="ANMF"&&(z+=me)}return $}}(_,0);b.response=_,b.rgbaoutput=!0,b.dataurl=!1;var k=b.header?b.header:null,A=b.frames?b.frames:null;if(k){k.loop_counter=k.loop_count,f=[k.canvas_height],g=[k.canvas_width];for(var T=0;T'+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 b1n(){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(he){return he=he||{},this.isStrokeTransparent=he.isStrokeTransparent||!1,this.strokeOpacity=he.strokeOpacity||1,this.strokeStyle=he.strokeStyle||"#000000",this.fillStyle=he.fillStyle||"#000000",this.isFillTransparent=he.isFillTransparent||!1,this.fillOpacity=he.fillOpacity||1,this.font=he.font||"10px sans-serif",this.textBaseline=he.textBaseline||"alphabetic",this.textAlign=he.textAlign||"left",this.lineWidth=he.lineWidth||1,this.lineJoin=he.lineJoin||"miter",this.lineCap=he.lineCap||"butt",this.path=he.path||[],this.transform=he.transform!==void 0?he.transform.clone():new c,this.globalCompositeOperation=he.globalCompositeOperation||"normal",this.globalAlpha=he.globalAlpha||1,this.clip_path=he.clip_path||[],this.currentPoint=he.currentPoint||new l,this.miterLimit=he.miterLimit||10,this.lastPoint=he.lastPoint||new l,this.lineDashOffset=he.lineDashOffset||0,this.lineDash=he.lineDash||[],this.margin=he.margin||[0,0,0,0],this.prevPageLastElemOffset=he.prevPageLastElemOffset||0,this.ignoreClearRect=typeof he.ignoreClearRect!="boolean"||he.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(he){Object.defineProperty(this,"canvas",{get:function(){return{parentNode:!1,style:!1}}});var xe=he;Object.defineProperty(this,"pdf",{get:function(){return xe}});var ve=!1;Object.defineProperty(this,"pageWrapXEnabled",{get:function(){return ve},set:function(Fe){ve=!!Fe}});var ge=!1;Object.defineProperty(this,"pageWrapYEnabled",{get:function(){return ge},set:function(Fe){ge=!!Fe}});var be=0;Object.defineProperty(this,"posX",{get:function(){return be},set:function(Fe){isNaN(Fe)||(be=Fe)}});var Se=0;Object.defineProperty(this,"posY",{get:function(){return Se},set:function(Fe){isNaN(Fe)||(Se=Fe)}}),Object.defineProperty(this,"margin",{get:function(){return d.margin},set:function(Fe){var Ae;typeof Fe=="number"?Ae=[Fe,Fe,Fe,Fe]:((Ae=new Array(4))[0]=Fe[0],Ae[1]=Fe.length>=2?Fe[1]:Ae[0],Ae[2]=Fe.length>=3?Fe[2]:Ae[0],Ae[3]=Fe.length>=4?Fe[3]:Ae[1]),d.margin=Ae}});var Ie=!1;Object.defineProperty(this,"autoPaging",{get:function(){return Ie},set:function(Fe){Ie=Fe}});var Me=0;Object.defineProperty(this,"lastBreak",{get:function(){return Me},set:function(Fe){Me=Fe}});var Re=[];Object.defineProperty(this,"pageBreaks",{get:function(){return Re},set:function(Fe){Re=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 Be=[];Object.defineProperty(this,"ctxStack",{get:function(){return Be},set:function(Fe){Be=Fe}}),Object.defineProperty(this,"fillStyle",{get:function(){return this.ctx.fillStyle},set:function(Fe){var Ae;Ae=m(Fe),this.ctx.fillStyle=Ae.style,this.ctx.isFillTransparent=Ae.a===0,this.ctx.fillOpacity=Ae.a,this.pdf.setFillColor(Ae.r,Ae.g,Ae.b,{a:Ae.a}),this.pdf.setTextColor(Ae.r,Ae.g,Ae.b,{a:Ae.a})}}),Object.defineProperty(this,"strokeStyle",{get:function(){return this.ctx.strokeStyle},set:function(Fe){var Ae=m(Fe);this.ctx.strokeStyle=Ae.style,this.ctx.isStrokeTransparent=Ae.a===0,this.ctx.strokeOpacity=Ae.a,Ae.a===0?this.pdf.setDrawColor(255,255,255):(Ae.a,this.pdf.setDrawColor(Ae.r,Ae.g,Ae.b))}}),Object.defineProperty(this,"lineCap",{get:function(){return this.ctx.lineCap},set:function(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 Ne=null,Ge=null,Ce=null;Object.defineProperty(this,"fontFaces",{get:function(){return Ce},set:function(Fe){Ne=null,Ge=null,Ce=Fe}}),Object.defineProperty(this,"font",{get:function(){return this.ctx.font},set:function(Fe){var Ae;if(this.ctx.font=Fe,(Ae=/^\s*(?=(?:(?:[-a-z]+\s*){0,2}(italic|oblique))?)(?=(?:(?:[-a-z]+\s*){0,2}(small-caps))?)(?=(?:(?:[-a-z]+\s*){0,2}(bold(?:er)?|lighter|[1-9]00))?)(?:(?:normal|\1|\2|\3)\s*){0,3}((?:xx?-)?(?:small|large)|medium|smaller|larger|[.\d]+(?:\%|in|[cem]m|ex|p[ctx]))(?:\s*\/\s*(normal|[.\d]+(?:\%|in|[cem]m|ex|p[ctx])))?\s*([-_,\"\'\sa-z0-9]+?)\s*$/i.exec(Fe))!==null){var Xe=Ae[1];Ae[2];var $e=Ae[3],Ye=Ae[4];Ae[5];var Je=Ae[6],Ke=/^([.\d]+)((?:%|in|[cem]m|ex|p[ctx]))$/i.exec(Ye)[2];Ye=Math.floor(Ke==="px"?parseFloat(Ye)*this.pdf.internal.scaleFactor:Ke==="em"?parseFloat(Ye)*this.pdf.getFontSize():parseFloat(Ye)*this.pdf.internal.scaleFactor),this.pdf.setFontSize(Ye);var st=function(zs){var Vt,At,Os=[],Nt=zs.trim();if(Nt==="")return LPe;if(Nt in Rpt)return[Rpt[Nt]];for(;Nt!=="";){switch(At=null,Vt=(Nt=Fpt(Nt)).charAt(0)){case'"':case"'":At=m1n(Nt.substring(1),Vt);break;default:At=p1n(Nt)}if(At===null||(Os.push(At[0]),(Nt=Fpt(At[1]))!==""&&Nt.charAt(0)!==","))return LPe;Nt=Nt.replace(/^,/,"")}return Os}(Je);if(this.fontFaces){var rt=function(zs,Vt){var At=zs.getFontList(),Os=JSON.stringify(At);if(Ne===null||Ge!==Os){var Nt=function(ms){var Ys=[];return Object.keys(ms).forEach(function(It){ms[It].forEach(function(Ds){var As=null;switch(Ds){case"bold":As={family:It,weight:"bold"};break;case"italic":As={family:It,style:"italic"};break;case"bolditalic":As={family:It,weight:"bold",style:"italic"};break;case"":case"normal":As={family:It}}As!==null&&(As.ref={name:It,style:Ds},Ys.push(As))})}),Ys}(At);Ne=function(ms){for(var Ys={},It=0;It=700||Xe==="bold")&&(Bt="bold"),Xe==="italic"&&(Bt+="italic"),Bt.length===0&&(Bt="normal");for(var Ct="",Yt={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"},Kt=0;Kt=2*Math.PI&&(ge=0,be=2*Math.PI),this.path.push({type:"arc",x:he,y:xe,radius:ve,startAngle:ge,endAngle:be,counterclockwise:Se})},h.prototype.arcTo=function(he,xe,ve,ge,be){throw new Error("arcTo not implemented.")},h.prototype.rect=function(he,xe,ve,ge){if(isNaN(he)||isNaN(xe)||isNaN(ve)||isNaN(ge))throw ph.error("jsPDF.context2d.rect: Invalid arguments",arguments),new Error("Invalid arguments passed to jsPDF.context2d.rect");this.moveTo(he,xe),this.lineTo(he+ve,xe),this.lineTo(he+ve,xe+ge),this.lineTo(he,xe+ge),this.lineTo(he,xe),this.lineTo(he+ve,xe),this.lineTo(he,xe)},h.prototype.fillRect=function(he,xe,ve,ge){if(isNaN(he)||isNaN(xe)||isNaN(ve)||isNaN(ge))throw ph.error("jsPDF.context2d.fillRect: Invalid arguments",arguments),new Error("Invalid arguments passed to jsPDF.context2d.fillRect");if(!f.call(this)){var be={};this.lineCap!=="butt"&&(be.lineCap=this.lineCap,this.lineCap="butt"),this.lineJoin!=="miter"&&(be.lineJoin=this.lineJoin,this.lineJoin="miter"),this.beginPath(),this.rect(he,xe,ve,ge),this.fill(),be.hasOwnProperty("lineCap")&&(this.lineCap=be.lineCap),be.hasOwnProperty("lineJoin")&&(this.lineJoin=be.lineJoin)}},h.prototype.strokeRect=function(he,xe,ve,ge){if(isNaN(he)||isNaN(xe)||isNaN(ve)||isNaN(ge))throw ph.error("jsPDF.context2d.strokeRect: Invalid arguments",arguments),new Error("Invalid arguments passed to jsPDF.context2d.strokeRect");g.call(this)||(this.beginPath(),this.rect(he,xe,ve,ge),this.stroke())},h.prototype.clearRect=function(he,xe,ve,ge){if(isNaN(he)||isNaN(xe)||isNaN(ve)||isNaN(ge))throw ph.error("jsPDF.context2d.clearRect: Invalid arguments",arguments),new Error("Invalid arguments passed to jsPDF.context2d.clearRect");this.ignoreClearRect||(this.fillStyle="#ffffff",this.fillRect(he,xe,ve,ge))},h.prototype.save=function(he){he=typeof he!="boolean"||he;for(var xe=this.pdf.internal.getCurrentPageInfo().pageNumber,ve=0;ve0||this.margin[1]>0||this.margin[2]>0||this.margin[3]>0};h.prototype.drawImage=function(he,xe,ve,ge,be,Se,Ie,Me,Re){var Be=this.pdf.getImageProperties(he),Ne=1,Ge=1,Ce=1,Fe=1;ge!==void 0&&Me!==void 0&&(Ce=Me/ge,Fe=Re/be,Ne=Be.width/ge*Me/ge,Ge=Be.height/be*Re/be),Se===void 0&&(Se=xe,Ie=ve,xe=0,ve=0),ge!==void 0&&Me===void 0&&(Me=ge,Re=be),ge===void 0&&Me===void 0&&(Me=Be.width,Re=Be.height);var Ae=this.ctx.transform.decompose(),Xe=me(Ae.rotate.shx),$e=new c,Ye=($e=($e=($e=$e.multiply(Ae.translate)).multiply(Ae.skew)).multiply(Ae.scale)).applyToRectangle(new o(Se-xe*Ce,Ie-ve*Fe,ge*Ne,be*Ge));if(this.autoPaging){for(var Je,Ke=x.call(this,Ye),st=[],rt=0;rtZe||BtYe||Ke0)){for(;Re>=0;Re--)if(be[Re-1].close!==!0&&be[Re-1].begin!==!0){be[Re-1].deltas.push(ve),be[Re-1].abs.push(Me);break}}break;case"bct":ve=[Me.x1-Se[Ie-1].x,Me.y1-Se[Ie-1].y,Me.x2-Se[Ie-1].x,Me.y2-Se[Ie-1].y,Me.x-Se[Ie-1].x,Me.y-Se[Ie-1].y],be[be.length-1].deltas.push(ve);break;case"qct":var Be=Se[Ie-1].x+2/3*(Me.x1-Se[Ie-1].x),Ne=Se[Ie-1].y+2/3*(Me.y1-Se[Ie-1].y),Ge=Me.x+2/3*(Me.x1-Me.x),Ce=Me.y+2/3*(Me.y1-Me.y),Fe=Me.x,Ae=Me.y;ve=[Be-Se[Ie-1].x,Ne-Se[Ie-1].y,Ge-Se[Ie-1].x,Ce-Se[Ie-1].y,Fe-Se[Ie-1].x,Ae-Se[Ie-1].y],be[be.length-1].deltas.push(ve);break;case"arc":be.push({deltas:[],abs:[],arc:!0}),Array.isArray(be[be.length-1].abs)&&be[be.length-1].abs.push(Me)}}ge=xe?null:he==="stroke"?"stroke":"fill";for(var Xe=!1,$e=0;$e=.01&&(ge=this.pdf.internal.getFontSize(),this.pdf.setFontSize(ge*he.scale),be=this.lineWidth,this.lineWidth=be*he.scale);var Xs=this.autoPaging!=="text";if(Xs||Kt.y+Kt.h<=rt){if(Xs||Kt.y>=Ke&&Kt.x<=ht){var zs=Xs?he.text:this.pdf.splitTextToSize(he.text,he.maxWidth||ht-Kt.x)[0],Vt=b([JSON.parse(JSON.stringify(Ge))],this.posX+this.margin[3],-Ct+Ke+this.ctx.prevPageLastElemOffset)[0],At=Xs&&(Je>$e||Je=.01&&(this.pdf.setFontSize(ge),this.lineWidth=be)}}else he.scale>=.01&&(ge=this.pdf.internal.getFontSize(),this.pdf.setFontSize(ge*he.scale),be=this.lineWidth,this.lineWidth=be*he.scale),this.pdf.text(he.text,Re.x+this.posX,Re.y+this.posY,{angle:he.angle,align:xe,renderingMode:he.renderingMode,maxWidth:he.maxWidth}),he.scale>=.01&&(this.pdf.setFontSize(ge),this.lineWidth=be)},W=function(he,xe,ve,ge){ve=ve||0,ge=ge||0,this.pdf.internal.out(n(he+ve)+" "+r(xe+ge)+" l")},G=function(he,xe,ve){return this.pdf.lines(he,xe,ve,null,null)},X=function(he,xe,ve,ge,be,Se,Ie,Me){this.pdf.internal.out([t(a(ve+he)),t(i(ge+xe)),t(a(be+he)),t(i(Se+xe)),t(a(Ie+he)),t(i(Me+xe)),"c"].join(" "))},te=function(he,xe,ve,ge){for(var be=2*Math.PI,Se=Math.PI/2;xe>ve;)xe-=be;var Ie=Math.abs(ve-xe);Ie1e-5;){var Ne=Be+Re*Math.min(Ie,Se);Me.push(ne.call(this,he,Be,Ne)),Ie-=Math.abs(Ne-Be),Be=Ne}return Me},ne=function(he,xe,ve){var ge=(ve-xe)/2,be=he*Math.cos(ge),Se=he*Math.sin(ge),Ie=be,Me=-Se,Re=Ie*Ie+Me*Me,Be=Re+Ie*be+Me*Se,Ne=4/3*(Math.sqrt(2*Re*Be)-Be)/(Ie*Se-Me*be),Ge=Ie-Ne*Me,Ce=Me+Ne*Ie,Fe=Ge,Ae=-Ce,Xe=ge+xe,$e=Math.cos(Xe),Ye=Math.sin(Xe);return{x1:he*Math.cos(xe),y1:he*Math.sin(xe),x2:Ge*$e-Ce*Ye,y2:Ge*Ye+Ce*$e,x3:Fe*$e-Ae*Ye,y3:Fe*Ye+Ae*$e,x4:he*Math.cos(ve),y4:he*Math.sin(ve)}},me=function(he){return 180*he/Math.PI},ue=function(he,xe,ve,ge,be,Se){var Ie=he+.5*(ve-he),Me=xe+.5*(ge-xe),Re=be+.5*(ve-be),Be=Se+.5*(ge-Se),Ne=Math.min(he,be,Ie,Re),Ge=Math.max(he,be,Ie,Re),Ce=Math.min(xe,Se,Me,Be),Fe=Math.max(xe,Se,Me,Be);return new o(Ne,Ce,Ge-Ne,Fe-Ce)},ce=function(he,xe,ve,ge,be,Se,Ie,Me){var Re,Be,Ne,Ge,Ce,Fe,Ae,Xe,$e,Ye,Je,Ke,st,rt,Ze=ve-he,ht=ge-xe,Bt=be-ve,Ct=Se-ge,Yt=Ie-be,Kt=Me-Se;for(Be=0;Be<41;Be++)$e=(Ae=(Ne=he+(Re=Be/40)*Ze)+Re*((Ce=ve+Re*Bt)-Ne))+Re*(Ce+Re*(be+Re*Yt-Ce)-Ae),Ye=(Xe=(Ge=xe+Re*ht)+Re*((Fe=ge+Re*Ct)-Ge))+Re*(Fe+Re*(Se+Re*Kt-Fe)-Xe),Be==0?(Je=$e,Ke=Ye,st=$e,rt=Ye):(Je=Math.min(Je,$e),Ke=Math.min(Ke,Ye),st=Math.max(st,$e),rt=Math.max(rt,Ye));return new o(Math.round(Je),Math.round(Ke),Math.round(st-Je),Math.round(rt-Ke))},ae=function(){if(this.prevLineDash||this.ctx.lineDash.length||this.ctx.lineDashOffset){var he,xe,ve=(he=this.ctx.lineDash,xe=this.ctx.lineDashOffset,JSON.stringify({lineDash:he,lineDashOffset:xe}));this.prevLineDash!==ve&&(this.pdf.setLineDash(this.ctx.lineDash,this.ctx.lineDashOffset),this.prevLineDash=ve)}}})(wo.API),function(s){var t=function(l){var o,c,d,u,h,m,f,g,y,x;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-(x=h%85))/85)-(y=h%85))/85)-(g=h%85))/85)-(f=h%85))/85)%85,c.push(m+33,f+33,g+33,y+33,x+33)):c.push(122);return function(_,b){for(var k=b;k>0;k--)_.pop()}(c,o.length),String.fromCharCode.apply(String,c)+"~>"},n=function(l){var o,c,d,u,h,m=String,f="length",g=255,y="charCodeAt",x="slice",_="replace";for(l[x](-2),l=l[x](0,-2)[_](/\s/g,"")[_]("z","!!!!!"),d=[],u=0,h=(l+=o="uuuuu"[x](l[f]%5||5))[f];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(g&c>>24,g&c>>16,g&c>>8,g&c);return function(b,k){for(var A=k;A>0;A--)b.pop()}(d,o[f]),m.fromCharCode.apply(m,d)},r=function(l){return l.split("").map(function(o){return("0"+o.charCodeAt().toString(16)).slice(-2)}).join("")+">"},a=function(l){var o=new RegExp(/^([0-9A-Fa-f]{2})+$/);if((l=l.replace(/\s/g,"")).indexOf(">")!==-1&&(l=l.substr(0,l.indexOf(">"))),l.length%2&&(l+="0"),o.test(l)===!1)return"";for(var c="",d=0;dimport("./html2canvas.esm-CBrSDip1.js"),[])).catch(function(o){return Promise.reject(new Error("Could not load html2canvas: "+o))}).then(function(o){return o.default?o.default:o})}function n(){return(dl.DOMPurify?Promise.resolve(dl.DOMPurify):Fi(()=>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=Vu(o);return c==="undefined"?"undefined":c==="string"||o instanceof String?"string":c==="number"||o instanceof Number?"number":c==="function"||o instanceof Function?"function":o&&o.constructor===Array?"array":o&&o.nodeType===1?"element":c==="object"?"object":"unknown"},a=function(o,c){var d=document.createElement(o);for(var u in c.className&&(d.className=c.className),c.innerHTML&&c.dompurify&&(d.innerHTML=c.dompurify.sanitize(c.innerHTML)),c.style)d.style[u]=c.style[u];return d},i=function o(c,d){for(var u=c.nodeType===3?document.createTextNode(c.nodeValue):c.cloneNode(!1),h=c.firstChild;h;h=h.nextSibling)d!==!0&&h.nodeType===1&&h.nodeName==="SCRIPT"||u.appendChild(o(h,d));return c.nodeType===1&&(c.nodeName==="CANVAS"?(u.width=c.width,u.height=c.height,u.getContext("2d").drawImage(c,0,0)):c.nodeName!=="TEXTAREA"&&c.nodeName!=="SELECT"||(u.value=c.value),u.addEventListener("load",function(){u.scrollTop=c.scrollTop,u.scrollLeft=c.scrollLeft},!0)),u},l=function o(c){var d=Object.assign(o.convert(Promise.resolve()),JSON.parse(JSON.stringify(o.template))),u=o.convert(Promise.resolve(),d);return(u=u.setProgress(1,o,1,[o])).set(c)};(l.prototype=Object.create(Promise.prototype)).constructor=l,l.convert=function(o,c){return o.__proto__=c||l.prototype,o},l.template={prop:{src:null,container:null,overlay:null,canvas:null,img:null,pdf:null,pageSize:null,callback:function(){}},progress:{val:0,state:null,n:0,stack:[]},opt:{filename:"file.pdf",margin:[0,0,0,0],enableLinks:!0,x:0,y:0,html2canvas:{},jsPDF:{},backgroundColor:"transparent"}},l.prototype.from=function(o,c){return this.then(function(){switch(c=c||function(d){switch(r(d)){case"string":return"string";case"element":return d.nodeName.toLowerCase()==="canvas"?"canvas":"element";default:return"unknown"}}(o),c){case"string":return this.then(n).then(function(d){return this.set({src:a("div",{innerHTML:o,dompurify:d})})});case"element":return this.set({src:o});case"canvas":return this.set({canvas:o});case"img":return this.set({img:o});default:return this.error("Unknown source type.")}})},l.prototype.to=function(o){switch(o){case"container":return this.toContainer();case"canvas":return this.toCanvas();case"img":return this.toImg();case"pdf":return this.toPdf();default:return this.error("Invalid target.")}},l.prototype.toContainer=function(){return this.thenList([function(){return this.prop.src||this.error("Cannot duplicate - no source HTML.")},function(){return this.prop.pageSize||this.setPageSize()}]).then(function(){var o={position:"relative",display:"inline-block",width:(typeof this.opt.width!="number"||isNaN(this.opt.width)||typeof this.opt.windowWidth!="number"||isNaN(this.opt.windowWidth)?Math.max(this.prop.src.clientWidth,this.prop.src.scrollWidth,this.prop.src.offsetWidth):this.opt.windowWidth)+"px",left:0,right:0,top:0,margin:"auto",backgroundColor:this.opt.backgroundColor},c=i(this.prop.src,this.opt.html2canvas.javascriptEnabled);c.tagName==="BODY"&&(o.height=Math.max(document.body.scrollHeight,document.body.offsetHeight,document.documentElement.clientHeight,document.documentElement.scrollHeight,document.documentElement.offsetHeight)+"px"),this.prop.overlay=a("div",{className:"html2pdf__overlay",style:{position:"fixed",overflow:"hidden",zIndex:1e3,left:"-100000px",right:0,bottom:0,top:0}}),this.prop.container=a("div",{className:"html2pdf__container",style:o}),this.prop.container.appendChild(c),this.prop.container.firstChild.appendChild(a("div",{style:{clear:"both",border:"0 none transparent",margin:0,padding:0,height:0}})),this.prop.container.style.float="none",this.prop.overlay.appendChild(this.prop.container),document.body.appendChild(this.prop.overlay),this.prop.container.firstChild.style.position="relative",this.prop.container.height=Math.max(this.prop.container.firstChild.clientHeight,this.prop.container.firstChild.scrollHeight,this.prop.container.firstChild.offsetHeight)+"px"})},l.prototype.toCanvas=function(){var o=[function(){return document.body.contains(this.prop.container)||this.toContainer()}];return this.thenList(o).then(t).then(function(c){var d=Object.assign({},this.opt.html2canvas);return delete d.onrendered,c(this.prop.container,d)}).then(function(c){(this.opt.html2canvas.onrendered||function(){})(c),this.prop.canvas=c,document.body.removeChild(this.prop.overlay)})},l.prototype.toContext2d=function(){var o=[function(){return document.body.contains(this.prop.container)||this.toContainer()}];return this.thenList(o).then(t).then(function(c){var d=this.opt.jsPDF,u=this.opt.fontFaces,h=typeof this.opt.width!="number"||isNaN(this.opt.width)||typeof this.opt.windowWidth!="number"||isNaN(this.opt.windowWidth)?1:this.opt.width/this.opt.windowWidth,m=Object.assign({async:!0,allowTaint:!0,scale:h,scrollX:this.opt.scrollX||0,scrollY:this.opt.scrollY||0,backgroundColor:"#ffffff",imageTimeout:15e3,logging:!0,proxy:null,removeContainer:!0,foreignObjectRendering:!1,useCORS:!1},this.opt.html2canvas);if(delete m.onrendered,d.context2d.autoPaging=this.opt.autoPaging===void 0||this.opt.autoPaging,d.context2d.posX=this.opt.x,d.context2d.posY=this.opt.y,d.context2d.margin=this.opt.margin,d.context2d.fontFaces=u,u)for(var f=0;fy&&(g=x,x=y,y=g);else{if(o!=="l"&&o!=="landscape")throw"Invalid orientation: "+o;o="l",y>x&&(g=x,x=y,y=g)}return{width:x,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(MPe):null;var d=new l(c);return c.worker?d:d.from(o).doCallback()}}(wo.API),wo.API.addJS=function(s){var t,n,r=function(a){for(var i="",l=0;l=0&&a[d]==="\\";d--)c++;i+=c%2==0?"\\"+o:o}else i+=o}return i}(s);return this.internal.events.subscribe("postPutResources",function(){t=this.internal.newObject(),this.internal.out("<<"),this.internal.out("/Names [(EmbeddedJS) "+(t+1)+" 0 R]"),this.internal.out(">>"),this.internal.out("endobj"),n=this.internal.newObject(),this.internal.out("<<"),this.internal.out("/S /JavaScript"),this.internal.out("/JS ("+r+")"),this.internal.out(">>"),this.internal.out("endobj")}),this.internal.events.subscribe("putCatalog",function(){t!==void 0&&n!==void 0&&this.internal.out("/Names <>")}),this},function(s){var t;s.events.push(["postPutResources",function(){var n=this,r=/^(\d+) 0 obj$/;if(this.outline.root.children.length>0)for(var a=n.outline.render().split(/\r\n/),i=0;i> endobj")}var f=n.internal.newObject();for(n.internal.write("<< /Names [ "),i=0;i>","endobj"),t=n.internal.newObject(),n.internal.write("<< /Dests "+f+" 0 R"),n.internal.write(">>","endobj")}}]),s.events.push(["putCatalog",function(){var n=this;n.outline.root.children.length>0&&(n.internal.write("/Outlines",this.outline.makeRef(this.outline.root)),this.outline.createNamedDestinations&&n.internal.write("/Names "+t+" 0 R"))}]),s.events.push(["initialized",function(){var n=this;n.outline={createNamedDestinations:!1,root:{children:[]}},n.outline.add=function(r,a,i){var l={title:a,options:i,children:[]};return r==null&&(r=this.root),r.children.push(l),l},n.outline.render=function(){return this.ctx={},this.ctx.val="",this.ctx.pdf=n,this.genIds_r(this.root),this.renderRoot(this.root),this.renderItems(this.root),this.ctx.val},n.outline.genIds_r=function(r){r.id=n.internal.newObjectDeferred();for(var a=0;a0&&(this.line("/First "+this.makeRef(r.children[0])),this.line("/Last "+this.makeRef(r.children[r.children.length-1]))),this.line("/Count "+this.count_r({count:0},r)),this.objEnd()},n.outline.renderItems=function(r){for(var a=this.ctx.pdf.internal.getVerticalCoordinateString,i=0;i0&&this.line("/Prev "+this.makeRef(r.children[i-1])),i0&&(this.line("/First "+this.makeRef(l.children[0])),this.line("/Last "+this.makeRef(l.children[l.children.length-1])));var o=this.count=this.count_r({count:0},l);if(o>0&&this.line("/Count "+o),l.options&&l.options.pageNumber){var c=n.internal.getPageInfo(l.options.pageNumber);this.line("/Dest ["+c.objId+" 0 R /XYZ 0 "+a(0)+" 0]")}this.objEnd()}for(var d=0;d> \r endobj\r `},n.outline.count_r=function(r,a){for(var i=0;i1){G=!0,te=void 0;var be=L*z;ne=new Uint8Array(be);for(var Se=new DataView($.buffer),Ie=0;Ie536870912)throw new Error("Image dimensions exceed 512MB, which is too large.");this.data=new Uint8Array(t);try{this[s]()}catch(n){ph.log("bit decode error:"+n)}},a2.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)}},a2.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)}},a2.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}},a2.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}},a2.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},$pt=function(s,t,n){n||(n={});var r,a,i,l,o,c,d,u=[],h=[u],m=n.textIndent||0,f=0,g=0,y=s.split(" "),x=vne.apply(this,[" ",n])[0];if(c=n.lineIndent===-1?y[0].length+2:n.lineIndent||0){var _=Array(c).join(" "),b=[];y.map(function(A){(A=A.split(/\s*\n/)).length>1?b=b.concat(A.map(function(T,P){return(P&&T.length?` `:"")+T})):b.push(A[0])}),y=b,c=zpt.apply(this,[_,n])}for(i=0,l=y.length;it||k){if(g>t){for(o=Bpt.apply(this,[r,a,t-(m+f),t]),u.push(o.shift()),u=[o.pop()];o.length;)h.push([o.shift()]);g=a.slice(r.length-(u[0]?u[0].length:0)).reduce(function(A,T){return A+T},0)}else u=[r];h.push(u),m=g+c,f=x}else u.push(r),m+=f+g,f=x}return d=c?function(A,T){return(T?_:"")+A.join(" ")}:function(A){return A.join(" ")},h.map(d)},IF.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-D9v1V313.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)})},wo.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},wo.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",b1n),this.internal.events.subscribe("postPutResources",v1n)),this},function(s){var t=s.API,n=t.pdfEscape16=function(i,l){for(var o,c=l.metadata.Unicode.widths,d=["","0","00","000","0000"],u=[""],h=0,m=i.length;h> def /CMapName /Adobe-Identity-UCS def /CMapType 2 def 1 begincodespacerange <0000> endcodespacerange`,c=[],h=0,m=(o=Object.keys(i).sort(function(f,g){return f-g})).length;h=100&&(u+=` `+c.length+` beginbfchar `+c.join(` `)+` endbfchar`,c=[]),i[l]!==void 0&&i[l]!==null&&typeof i[l].toString=="function"&&(d=("0000"+i[l].toString(16)).slice(-4),l=("0000"+(+l).toString(16)).slice(-4),c.push("<"+l+"><"+d+">"));return c.length&&(u+=` `+c.length+` beginbfchar `+c.join(` `)+` endbfchar `),u+`endcmap CMapName currentdict /CMap defineresource pop end end`};t.events.push(["putFont",function(i){(function(l){var o=l.font,c=l.out,d=l.newObject,u=l.putStream;if(o.metadata instanceof s.API.TTFFont&&o.encoding==="Identity-H"){for(var h=o.metadata.Unicode.widths,m=o.metadata.subset.encode(o.metadata.glyIdsUsed,1),f="",g=0;g>"),c("endobj");var b=d();c("<<"),c("/Type /Font"),c("/BaseFont /"+o7(o.fontName)),c("/FontDescriptor "+_+" 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 "+x+" 0 R"),c("/BaseFont /"+o7(o.fontName)),c("/Encoding /"+o.encoding),c("/DescendantFonts ["+b+" 0 R]"),c(">>"),c("endobj"),o.isAlreadyPutted=!0}})(i)}]),t.events.push(["putFont",function(i){(function(l){var o=l.font,c=l.out,d=l.newObject,u=l.putStream;if(o.metadata instanceof s.API.TTFFont&&o.encoding==="WinAnsiEncoding"){for(var h=o.metadata.rawData,m="",f=0;f>"),c("endobj"),o.objectNumber=d();for(var _=0;_>"),c("endobj"),o.isAlreadyPutted=!0}})(i)}]);var a=function(i){var l,o=i.text||"",c=i.x,d=i.y,u=i.options||{},h=i.mutex||{},m=h.pdfEscape,f=h.activeFontKey,g=h.fonts,y=f,x="",_=0,b="",k=g[y].encoding;if(g[y].encoding!=="Identity-H")return{text:o,x:c,y:d,options:u,mutex:h};for(b=o,y=f,Array.isArray(o)&&(b=o[0]),_=0;_","<","[","]","[","{","}","{","«","»","«","‹","›","‹","⁅","⁆","⁅","⁽","⁾","⁽","₍","₎","₍","≤","≥","≤","〈","〉","〈","﹙","﹚","﹙","﹛","﹜","﹛","﹝","﹞","﹝","﹤","﹥","﹤"],_=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,k=0;this.__bidiEngine__={};var A=function($){var V=$.charCodeAt(),W=V>>8,G=y[W];return G!==void 0?h[256*G+(255&V)]:W===252||W===253?"AL":_.test(W)?"L":W===8?"R":"N"},T=function($){for(var V,W=0;W<$.length;W++){if((V=A($.charAt(W)))==="L")return!1;if(V==="R")return!0}return!1},P=function($,V,W,G){var X,te,ne,me,ue=V[G];switch(ue){case"L":case"R":case"LRE":case"RLE":case"LRO":case"RLO":case"PDF":b=!1;break;case"N":case"AN":break;case"EN":b&&(ue="AN");break;case"AL":b=!0,ue="R";break;case"WS":case"BN":ue="N";break;case"CS":G<1||G+1>=V.length||(X=W[G-1])!=="EN"&&X!=="AN"||(te=V[G+1])!=="EN"&&te!=="AN"?ue="N":b&&(te="AN"),ue=te===X?te:"N";break;case"ES":ue=(X=G>0?W[G-1]:"B")==="EN"&&G+10&&W[G-1]==="EN"){ue="EN";break}if(b){ue="N";break}for(ne=G+1,me=V.length;ne=1425&&ce<=2303||ce===64286;if(X=V[ne],ae&&(X==="R"||X==="AL")){ue="R";break}}}ue=G<1||(X=V[G-1])==="B"?"N":W[G-1];break;case"B":b=!1,a=!0,ue=k;break;case"S":i=!0,ue="N"}return ue},I=function($,V,W){var G=$.split("");return W&&M(G,W,{hiLevel:k}),G.reverse(),V&&V.reverse(),G.join("")},M=function($,V,W){var G,X,te,ne,me,ue=-1,ce=$.length,ae=0,he=[],xe=k?f:m,ve=[];for(b=!1,a=!1,i=!1,X=0;X0)if(G===16){for(X=ue;X-1){for(X=ue;X=0&&ge[Me]==="WS";Me--)be[Me]=k}}(ve,V,ce)},L=function($,V,W,G,X){if(!(X.hiLevel<$)){if($===1&&k===1&&!a)return V.reverse(),void(W&&W.reverse());for(var te,ne,me,ue,ce=V.length,ae=0;ae=$){for(me=ae+1;me=$;)me++;for(ue=ae,ne=me-1;ue=0&&(te[ce]=x[ue+1])}(G,W,X),L(2,G,V,W,X),L(1,G,V,W,X),G.join("")};return this.__bidiEngine__.doBidiReorder=function($,V,W){if(function(X,te){if(te)for(var ne=0;ne>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 AN,vE=function(){function s(t){this.data=t??[],this.pos=0,this.length=this.data.length}return s.prototype.readByte=function(){return this.data[this.pos++]},s.prototype.writeByte=function(t){return this.data[this.pos++]=t},s.prototype.readUInt32=function(){return 16777216*this.readByte()+(this.readByte()<<16)+(this.readByte()<<8)+this.readByte()},s.prototype.writeUInt32=function(t){return this.writeByte(t>>>24&255),this.writeByte(t>>16&255),this.writeByte(t>>8&255),this.writeByte(255&t)},s.prototype.readInt32=function(){var t;return(t=this.readUInt32())>=2147483648?t-4294967296:t},s.prototype.writeInt32=function(t){return t<0&&(t+=4294967296),this.writeUInt32(t)},s.prototype.readUInt16=function(){return this.readByte()<<8|this.readByte()},s.prototype.writeUInt16=function(t){return this.writeByte(t>>8&255),this.writeByte(255&t)},s.prototype.readInt16=function(){var t;return(t=this.readUInt16())>=32768?t-65536:t},s.prototype.writeInt16=function(t){return t<0&&(t+=65536),this.writeUInt16(t)},s.prototype.readString=function(t){var n,r;for(r=[],n=0;0<=t?nt;n=0<=t?++n:--n)r[n]=String.fromCharCode(this.readByte());return r.join("")},s.prototype.writeString=function(t){var n,r,a;for(a=[],n=0,r=t.length;0<=r?nr;n=0<=r?++n:--n)a.push(this.writeByte(t.charCodeAt(n)));return a},s.prototype.readShort=function(){return this.readInt16()},s.prototype.writeShort=function(t){return this.writeInt16(t)},s.prototype.readLongLong=function(){var t,n,r,a,i,l,o,c;return t=this.readByte(),n=this.readByte(),r=this.readByte(),a=this.readByte(),i=this.readByte(),l=this.readByte(),o=this.readByte(),c=this.readByte(),128&t?-1*(72057594037927940*(255^t)+281474976710656*(255^n)+1099511627776*(255^r)+4294967296*(255^a)+16777216*(255^i)+65536*(255^l)+256*(255^o)+(255^c)+1):72057594037927940*t+281474976710656*n+1099511627776*r+4294967296*a+16777216*i+65536*l+256*o+c},s.prototype.writeLongLong=function(t){var n,r;return n=Math.floor(t/4294967296),r=4294967295&t,this.writeByte(n>>24&255),this.writeByte(n>>16&255),this.writeByte(n>>8&255),this.writeByte(255&n),this.writeByte(r>>24&255),this.writeByte(r>>16&255),this.writeByte(r>>8&255),this.writeByte(255&r)},s.prototype.readInt=function(){return this.readInt32()},s.prototype.writeInt=function(t){return this.writeInt32(t)},s.prototype.read=function(t){var n,r;for(n=[],r=0;0<=t?rt;r=0<=t?++r:--r)n.push(this.readByte());return n},s.prototype.write=function(t){var n,r,a,i;for(i=[],r=0,a=t.length;ri;a=0<=i?++a:--a)r={tag:n.readString(4),checksum:n.readInt(),offset:n.readInt(),length:n.readInt()},this.tables[r.tag]=r}return t.prototype.encode=function(n){var r,a,i,l,o,c,d,u,h,m,f,g,y;for(y in f=Object.keys(n).length,c=Math.log(2),h=16*Math.floor(Math.log(f)/c),l=Math.floor(h/c),u=16*f-h,(a=new vE).writeInt(this.scalarType),a.writeShort(f),a.writeShort(h),a.writeShort(l),a.writeShort(u),i=16*f,d=a.pos+i,o=null,g=[],n)for(m=n[y],a.writeString(y),a.writeInt(s(m)),a.writeInt(d),a.writeInt(m.length),g=g.concat(m),y==="head"&&(o=d),d+=m.length;d%4;)g.push(0),d++;return a.write(g),r=2981146554-s(a.data),a.pos=o+8,a.writeUInt32(r),a.data},s=function(n){var r,a,i,l;for(n=VRt.call(n);n.length%4;)n.push(0);for(i=new vE(n),a=0,r=0,l=n.length;rm;c=0<=m?++A:--A)T.push(t.readUInt16());return T}(),t.pos+=2,y=function(){var A,T;for(T=[],c=A=0;0<=m?Am;c=0<=m?++A:--A)T.push(t.readUInt16());return T}(),d=function(){var A,T;for(T=[],c=A=0;0<=m?Am;c=0<=m?++A:--A)T.push(t.readUInt16());return T}(),u=function(){var A,T;for(T=[],c=A=0;0<=m?Am;c=0<=m?++A:--A)T.push(t.readUInt16());return T}(),a=(this.length-t.pos+this.offset)/2,o=function(){var A,T;for(T=[],c=A=0;0<=a?Aa;c=0<=a?++A:--A)T.push(t.readUInt16());return T}(),c=_=0,k=i.length;_=x;r=g<=x?++b:--b)u[c]===0?l=r+d[c]:(l=o[u[c]/2+(r-g)-(m-c)]||0)!==0&&(l+=d[c]),this.codeMap[r]=65535&l}t.pos=h}return s.encode=function(t,n){var r,a,i,l,o,c,d,u,h,m,f,g,y,x,_,b,k,A,T,P,I,M,L,z,$,V,W,G,X,te,ne,me,ue,ce,ae,he,xe,ve,ge,be,Se,Ie,Me,Re,Be,Ne;switch(G=new vE,l=Object.keys(t).sort(function(Ge,Ce){return Ge-Ce}),n){case"macroman":for(y=0,x=function(){var Ge=[];for(g=0;g<256;++g)Ge.push(0);return Ge}(),b={0:0},i={},X=0,ue=l.length;X=32768)for(c.push(0),P.push(2*(f.length+L-g)),a=me=$;$<=u?me<=u:me>=u;a=$<=u?++me:--me)f.push(r[a].new);else c.push(W-$),P.push(0)}for(G.writeUInt16(3),G.writeUInt16(1),G.writeUInt32(12),G.writeUInt16(4),G.writeUInt16(16+8*L+2*f.length),G.writeUInt16(0),G.writeUInt16(z),G.writeUInt16(M),G.writeUInt16(m),G.writeUInt16(I),Se=0,he=h.length;Sea;r=0<=a?++r:--r)n=new Zpt(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=Zpt.encode(t,n),(a=new vE).writeUInt16(0),a.writeUInt16(1),r.table=a.data.concat(r.subtable),r},s}(),N1n=function(){function s(){return s.__super__.constructor.apply(this,arguments)}return sS(s,AN),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}(),k1n=function(){function s(){return s.__super__.constructor.apply(this,arguments)}return sS(s,AN),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}(),S1n=function(){function s(){return s.__super__.constructor.apply(this,arguments)}return sS(s,AN),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}(),C1n=function(s,t){this.raw=s,this.length=s.length,this.platformID=t.platformID,this.encodingID=t.encodingID,this.languageID=t.languageID},A1n=function(){function s(){return s.__super__.constructor.apply(this,arguments)}return sS(s,AN),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}(),VRt=[].slice,M1n=function(){function s(){return s.__super__.constructor.apply(this,arguments)}return sS(s,AN),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 vE(n.read(a))).readShort(),d=o.readShort(),h=o.readShort(),c=o.readShort(),u=o.readShort(),this.cache[t]=l===-1?new P1n(o,d,h,c,u):new L1n(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}(),D1n=function(){function s(t){this.font=t,this.subset={},this.unicodes={},this.next=33}return s.prototype.generateCmap=function(){var t,n,r,a,i;for(n in a=this.font.cmap.tables[0].codeMap,t={},i=this.subset)r=i[n],t[n]=a[r];return t},s.prototype.glyphsFor=function(t){var n,r,a,i,l,o,c;for(a={},l=0,o=t.length;l0)for(i in c=this.glyphsFor(n))r=c[i],a[i]=r;return a},s.prototype.encode=function(t,n){var r,a,i,l,o,c,d,u,h,m,f,g,y,x,_;for(a in r=qRt.encode(this.generateCmap(),"unicode"),l=this.glyphsFor(t),f={0:0},_=r.charMap)f[(c=_[a]).old]=c.new;for(g in m=r.maxGlyphID,l)g in f||(f[g]=m++);return u=function(b){var k,A;for(k in A={},b)A[b[k]]=k;return A}(f),h=Object.keys(u).sort(function(b,k){return b-k}),y=function(){var b,k,A;for(A=[],b=0,k=h.length;b>"),i.join(` `)}return""+n},t}();const K7e=[{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}],R1n="signature";function O1n(s){return K7e.find(t=>t.id===s)||K7e[0]}const zl=792,Ih=612,$r=52;function DF(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 Ap(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 nS=[22,24,28],Qv=[124,128,136],io=[255,255,255];function F1n(s){return s==null||!Number.isFinite(Number(s))?null:new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:0}).format(Number(s))}const DPe="https://relzejiswnotikjgvjhz.supabase.co";function z1n(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(DPe).origin?s:`${DPe}/functions/v1/image-proxy?url=${encodeURIComponent(t.toString())}`}catch{return s}}async function lH(s,t=2e3){if(!s)return null;try{const n=await fetch(z1n(s),{mode:"cors"});if(!n.ok)return null;const r=await n.blob(),a=URL.createObjectURL(r),i=await new Promise((y,x)=>{const _=new Image;_.crossOrigin="anonymous",_.onload=()=>y(_),_.onerror=x,_.src=a}),l=Math.min(1,t/i.naturalWidth),o=Math.max(1,Math.round(i.naturalWidth*l)),c=Math.max(1,Math.round(i.naturalHeight*l)),d=document.createElement("canvas");d.width=o,d.height=c,d.getContext("2d").drawImage(i,0,0,o,c),URL.revokeObjectURL(a);const h=r.type.includes("png"),m=h?"PNG":"JPEG",f=d.toDataURL(h?"image/png":"image/jpeg",.92);return{el:await new Promise(y=>{const x=new Image;x.onload=()=>y(x),x.onerror=()=>y(x),x.src=f}),dataUrl:f,w:o,h:c,format:m}}catch{return null}}let HRt={x:.5,y:.5};function B1n(s){HRt={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 CJ(s,t,n,r,a,i,l={}){const o=l.dpi??2,c=Math.max(1,Math.round(a*o)),d=Math.max(1,Math.round(i*o)),u=document.createElement("canvas");u.width=c,u.height=d;const h=u.getContext("2d"),m=t.w/t.h,f=a/i;let g=0,y=0,x=t.w,_=t.h;const b=l.focal??HRt;if(m>f?(x=t.h*f,g=Math.min(Math.max(0,t.w*b.x-x/2),t.w-x)):(_=t.w/f,y=Math.min(Math.max(0,t.h*b.y-_/2),t.h-_)),l.radius&&l.radius>0){const T=Math.min(l.radius*o,c/2,d/2);h.beginPath(),h.moveTo(T,0),h.arcTo(c,0,c,d,T),h.arcTo(c,d,0,d,T),h.arcTo(0,d,0,0,T),h.arcTo(0,0,c,0,T),h.closePath(),h.clip()}const k=[];l.grayscale&&k.push("grayscale(1)"),l.blur&&k.push(`blur(${l.blur*o}px)`),k.length&&(h.filter=k.join(" "));try{h.drawImage(t.el,g,y,x,_,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[T,P,I]=l.tint.color;h.globalCompositeOperation="multiply",h.fillStyle=`rgba(${T},${P},${I},${Math.min(1,l.tint.amount)})`,h.fillRect(0,0,c,d),h.globalCompositeOperation="source-over"}if(l.darken&&l.darken>0&&(h.fillStyle=`rgba(0,0,0,${Math.min(.9,l.darken)})`,h.fillRect(0,0,c,d)),l.gradient==="bottom"){const T=h.createLinearGradient(0,0,0,d);T.addColorStop(0,"rgba(0,0,0,0)"),T.addColorStop(.45,"rgba(0,0,0,0.05)"),T.addColorStop(1,"rgba(0,0,0,0.8)"),h.fillStyle=T,h.fillRect(0,0,c,d)}else if(l.gradient==="full"){const T=h.createLinearGradient(0,0,0,d);T.addColorStop(0,"rgba(0,0,0,0.4)"),T.addColorStop(.5,"rgba(0,0,0,0.18)"),T.addColorStop(1,"rgba(0,0,0,0.85)"),h.fillStyle=T,h.fillRect(0,0,c,d)}else if(l.gradient==="left"){const T=h.createLinearGradient(0,0,c,0);T.addColorStop(0,"rgba(0,0,0,0.75)"),T.addColorStop(.6,"rgba(0,0,0,0.15)"),T.addColorStop(1,"rgba(0,0,0,0)"),h.fillStyle=T,h.fillRect(0,0,c,d)}const A=u.toDataURL("image/jpeg",.92);s.addImage(A,"JPEG",n,r,a,i,void 0,"FAST")}function qD(s,t,n,r,a,i=3){const l=a*2,o=Math.max(1,Math.round(l*i)),c=document.createElement("canvas");c.width=o,c.height=o;const d=c.getContext("2d");d.fillStyle="#ffffff",d.fillRect(0,0,o,o),d.save(),d.beginPath(),d.arc(o/2,o/2,o/2,0,Math.PI*2),d.closePath(),d.clip();const u=t.w/t.h;let h=0,m=0,f=t.w,g=t.h;u>1?(f=t.h,h=(t.w-f)/2):(g=t.w,m=(t.h-g)/2);try{d.drawImage(t.el,h,m,f,g,0,0,o,o)}catch{}d.restore(),s.addImage(c.toDataURL("image/jpeg",.92),"JPEG",n-a,r-a,l,l,void 0,"FAST")}function wWe(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 U1(s,t){const n=s.GState;n&&s.setGState(new n({opacity:t}))}function $1n(s,t,n,r,a,i={font:"helvetica",size:10,color:nS}){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 iq(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=$1n(s,c,n+13,l,a-13,{font:i.font,size:i.size,color:i.color,leading:o})+(i.gap??7)}),l}function Hy(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 dO='',uO='',U1n={title:"Facebook",slug:"facebook",get svg(){return dO+"Facebook"+uO+this.path+hO},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"},q1n={title:"Instagram",slug:"instagram",get svg(){return dO+"Instagram"+uO+this.path+hO},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"},V1n={title:"Pinterest",slug:"pinterest",get svg(){return dO+"Pinterest"+uO+this.path+hO},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"},H1n={title:"TikTok",slug:"tiktok",get svg(){return dO+"TikTok"+uO+this.path+hO},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"},G1n={title:"trulia",slug:"trulia",get svg(){return dO+"trulia"+uO+this.path+hO},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"},W1n={title:"YouTube",slug:"youtube",get svg(){return dO+"YouTube"+uO+this.path+hO},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"},K1n={title:"Zillow",slug:"zillow",get svg(){return dO+"Zillow"+uO+this.path+hO},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"},Y1n={facebook:U1n,instagram:q1n,youtube:W1n,tiktok:H1n,pinterest:V1n,zillow:K1n,trulia:G1n},Xpt=new Map;function Z1n(s,t,n){return`${s}|${t}|${n}`}function X1n(s,t,n=128){const r=s.toLowerCase().replace(/[^a-z]/g,""),a=Y1n[r];if(!a)return null;const i=Z1n(r,t,n),l=Xpt.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 Xpt.set(i,d),d}catch{return null}}const Zc="helvetica";let F$="helvetica";function GRt(s,t,n,r,a,i){const l=`#${n.map(d=>Math.round(d).toString(16).padStart(2,"0")).join("")}`,o=X1n(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(Zc,"bold"),s.setFontSize(c*1.15),s.setTextColor(...io),s.text(t.charAt(0).toUpperCase(),r,a+c*.42,{align:"center"})}let AJ=[252,251,248],SR=[244,247,250],cb=[223,228,234],ny=[72,78,88];function TJ(s,t){return MDt(s.data.pages,t)}function jWe(s){var n;const t=s.coAgent;return t!=null&&t.enabled&&((n=t.name)!=null&&n.trim())?t:null}function WRt(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 Q1n(s){return[s.agent.brokerageName,s.agent.phone,s.agent.email].filter(Boolean).join(" | ")}function Bf(s,t,n,r,a,i,l){const o=l.font||Zc,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 ou(s,t,n,r,a,i){s.setFont(Zc,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 oq(s,t,n,r,a,i){const{doc:l}=s;l.setFont(Zc,"bold"),l.setFontSize(7.5),l.setTextColor(...a||s.accent),l.text(t.toUpperCase(),n,r,{charSpace:1.8,align:i})}function e0(s,t=AJ){s.doc.addPage("letter","landscape"),s.pageNo+=1,s.doc.setFillColor(...t),s.doc.rect(0,0,zl,Ih,"F")}function ry(s,t,n,r,a={}){const{doc:i}=s,l=!!a.dark,o=a.width??zl-$r*2-60;oq(s,t,$r,62,s.accent),i.setFont(F$,"bold"),i.setFontSize(F$==="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,$r,96+h*29));let d=96+(c.length-1)*29;return r&&(d=ou(i,r,$r,d+26,Math.min(o+40,zl-$r*2),{size:10,color:l?Ap(io,s.deep,.28):Qv,leading:15,maxLines:2})),d+34}function t0(s,t=!1){const{doc:n,data:r}=s,a=t?Ap(io,s.deep,.7):cb;n.setDrawColor(...a),n.setLineWidth(.6),n.line($r,Ih-46,zl-$r,Ih-46);const i=Ih-30;n.setFont(Zc,"bold"),n.setFontSize(7),n.setTextColor(...t?io:s.brand),t&&U1(n,.9),n.text((r.agent.name||"").toUpperCase(),$r,i,{charSpace:1.4});const l=Q1n(r);l&&(n.setFont(Zc,"normal"),n.setFontSize(7),n.setTextColor(...t?io:Qv),Bf(n,l,zl/2,i,zl/2-$r-40,7,{color:t?io:Qv,align:"center"})),n.setFont(Zc,"normal"),n.setFontSize(7),n.setTextColor(...t?io:Qv),n.text(String(s.pageNo).padStart(2,"0"),zl-$r,i,{align:"right"}),t&&U1(n,1)}function KRt(s,t,n,r,a){const{doc:i}=s;i.setFont(Zc,"bold"),i.setFontSize(8);const l=i.splitTextToSize(t,a-28),o=16+l.length*12;return Hy(i,n,r,a,o,6,Ap(s.accent,io,.86)),i.setTextColor(...Ap(s.brand,nS,.2)),l.forEach((c,d)=>i.text(c,n+14,r+20+d*12)),r+o}function NWe(s,t,n,r,a,i={}){const{doc:l}=s;s.hero?CJ(l,s.hero,t,n,r,a,{radius:10,dpi:s.dpi,tint:i.tint?{color:s.deep,amount:i.tint}:void 0}):Hy(l,t,n,r,a,10,Ap(s.deep,io,.12))}function J1n(s){const{doc:t,data:n}=s,{line1:r,line2:a}=WRt(n),i=336;s.hero?CJ(t,s.hero,0,0,zl,Ih,{dpi:s.dpi,darken:.12}):(t.setFillColor(...s.deep),t.rect(0,0,zl,Ih,"F")),t.setFillColor(...s.deep),t.rect(0,0,i,Ih,"F"),t.setFillColor(...s.accent),t.rect(i-3,0,3,Ih,"F");const l=TJ(s,"cover");oq(s,l.kicker,$r,66),t.setFont(F$,"bold"),t.setFontSize(F$==="times"?29:26),t.setTextColor(...io);const o=t.splitTextToSize(r,i-$r*2).slice(0,3);o.forEach((x,_)=>t.text(x,$r,102+_*30));let c=102+(o.length-1)*30;a&&(t.setFont(Zc,"normal"),t.setFontSize(9),U1(t,.9),Bf(t,a.toUpperCase(),$r,c+22,i-$r*2,9,{color:io,charSpace:1.4}),U1(t,1),c+=22),c=ou(t,l.body,$r,c+34,i-$r*2,{size:10,color:Ap(io,s.deep,.22),leading:16});const d=[F1n(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($r,c+30,$r+40,c+30),Bf(t,d.join(" · "),$r,c+54,i-$r*2,10,{style:"bold",color:io,charSpace:1}));const u=jWe(n),h=Ih-(u?152:128);let m=$r;s.headshot&&(qD(t,s.headshot,$r+22,h+18,22),u&&s.coHeadshot?(qD(t,s.coHeadshot,$r+56,h+18,22),m=$r+90):m=$r+56),Bf(t,u?`${n.agent.name} + ${u.name}`:n.agent.name,m,h+12,i-m-24,14,{style:"bold",color:io}),t.setFont(Zc,"normal"),t.setFontSize(8),U1(t,.85);const f=[n.agent.brokerageName].filter(Boolean).join("");f&&Bf(t,f,m,h+26,i-m-24,8,{color:io});const g=[n.agent.phone,n.agent.email].filter(Boolean).join(" · ");if(g&&Bf(t,g,m,h+38,i-m-24,8,{color:io}),u){const x=[u.title||"Co-listing agent",u.phone].filter(Boolean).join(" · ");x&&Bf(t,x,$r,h+56,i-$r-24,8,{color:io})}U1(t,1),s.logo&&(U1(t,.95),wWe(t,s.logo,$r,Ih-74,132,30,"left"),U1(t,1));const y=n.sellerName?`PREPARED FOR ${n.sellerName.toUpperCase()}`:"PREPARED FOR YOUR HOME";t.setFont(Zc,"bold"),t.setFontSize(7.5),t.setTextColor(...io),U1(t,.9),t.text(y,zl-$r,Ih-34,{align:"right",charSpace:1.6}),U1(t,1)}function ebn(s){e0(s);const{doc:t}=s,n=TJ(s,"welcome"),r=ry(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(...Ap(s.accent,io,.85)),t.circle($r+13,i-3,13,"F"),t.setFont(Zc,"bold"),t.setFontSize(9),t.setTextColor(...s.brand),t.text(String(c+1).padStart(2,"0"),$r+13,i,{align:"center"});const d=$r+44,u=zl-d-$r-40;t.setFont(Zc,"bold"),t.setFontSize(11.5),t.setTextColor(...nS),t.text(l,d,i),ou(t,o,d,i+18,u,{size:9.5,color:ny,leading:14,maxLines:2}),i+=88}),t0(s)}function tbn(s){e0(s,io);const{doc:t,data:n}=s,r=TJ(s,"agent"),a=ry(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=jWe(n),l=zl-$r-260,o=a-6,c=262;if(i){const g=(y,x,_,b)=>{Hy(t,l,y,260,124,10,SR,"FD",cb),t.setFillColor(...s.accent),t.rect(l,y,260,3,"F");let k=l+18;_&&(qD(t,_,l+48,y+62+2,30),k=l+90);const A=260-(k-l)-18;Bf(t,x,k,y+40,A,13,{style:"bold",color:s.brand});let T=y+56;b.filter(Boolean).slice(0,4).forEach(P=>{Bf(t,String(P),k,T,A,8,{color:Qv}),T+=13})};g(o,n.agent.name,s.headshot,[n.agent.brokerageName,n.agent.phone,n.agent.email]),g(o+124+14,i.name,s.coHeadshot,[i.title||"Co-listing agent",i.brokerageName||n.agent.brokerageName,i.phone,i.email])}else{Hy(t,l,o,260,c,10,SR,"FD",cb),t.setFillColor(...s.accent),t.rect(l,o,260,3,"F"),s.headshot&&qD(t,s.headshot,l+130,o+72,42),Bf(t,n.agent.name,l+130,o+(s.headshot?138:70),216,16,{style:"bold",color:s.brand,align:"center"});let m=o+(s.headshot?158:92);[n.agent.brokerageName,n.agent.phone,n.agent.email,n.agent.website].filter(Boolean).slice(0,4).forEach(f=>{Bf(t,String(f),l+130,m,220,8.5,{color:Qv,align:"center"}),m+=14}),s.logo&&wWe(t,s.logo,l+80,o+c-44,100,28,"left")}const d=l-$r-44;let u=ou(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.",$r,a+4,d,{size:10,color:ny,leading:16,maxLines:5});u+=34,[["Phone",n.agent.phone],["Email",n.agent.email],["Website",n.agent.website],["Brokerage",n.agent.brokerageName],["License",n.agent.licenseNumber?`${n.agent.licenseNumber}${n.agent.licenseState?` · ${n.agent.licenseState}`:""}`:null],i?["Co-listing",[i.name,i.licenseNumber].filter(Boolean).join(" · ")]:["",null]].filter(([m,f])=>!!m&&!!f).forEach(([m,f])=>{t.setFont(Zc,"bold"),t.setFontSize(7),t.setTextColor(...Qv),t.text(m.toUpperCase(),$r,u,{charSpace:1.4}),Bf(t,f,$r+86,u,d-86,10.5,{color:nS}),t.setDrawColor(...cb),t.setLineWidth(.5),t.line($r,u+11,$r+d,u+11),u+=36}),t0(s)}function sbn(s,t){e0(s);const{doc:n}=s,r=TJ(s,"overview"),a=ry(s,r.kicker,r.headline,r.subhead||null),i=4,l=14,o=(zl-$r*2-l*(i-1))/i,c=96;t.slice(0,8).forEach((d,u)=>{const h=$r+u%i*(o+l),m=a+Math.floor(u/i)*(c+l);Hy(n,h,m,o,c,8,io,"FD",cb),n.setFillColor(...s.accent),n.rect(h,m,3,c,"F"),n.setFont(Zc,"bold"),n.setFontSize(15),n.setTextColor(...Ap(s.brand,io,.55)),n.text(String(u+1).padStart(2,"0"),h+16,m+30),ou(n,d.title,h+16,m+52,o-30,{size:9.5,style:"bold",color:nS,leading:13,maxLines:3})}),t0(s)}function s6(s,t=5){var n;return(((n=s.options)==null?void 0:n.filter(r=>r.enabled).map(r=>r.label))??Mxn[s.key]??[]).slice(0,t)}function Qpt(s,t,n){e0(s,n.dark?s.deep:AJ);const{doc:r}=s,a=ry(s,n.kicker,n.headline,n.sub,{dark:n.dark}),i=404,l=272,o=!!n.flip,c=o?zl-$r-i:$r,d=o?$r:$r+i+40,u=zl-$r*2-i-40;NWe(s,c,a,i,l,{tint:n.dark?.1:0}),oq(s,t.title,d,a+12);let h=ou(r,t.body,d,a+32,u,{size:9.5,color:n.dark?Ap(io,s.deep,.2):ny,leading:15,maxLines:4});const m=s6(t,5);if(m.length&&(h=iq(r,m,d,h+28,u,{font:Zc,size:9.5,color:n.dark?io:nS,accent:s.accent,gap:7})),n.note&&!n.dark){const f=Math.min(h+14,Ih-120);KRt(s,n.note,d,f,u)}else n.note&&(r.setFont(Zc,"bold"),r.setFontSize(9.5),r.setTextColor(...io),U1(r,.9),ou(r,n.note,$r,Ih-78,zl-$r*2,{size:9.5,style:"bold",color:io,leading:13,maxLines:1}),U1(r,1));t0(s,n.dark)}function nbn(s,t){e0(s);const{doc:n}=s,r=ry(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=s6(t,4),i=["Price + position","MLS story","Media ready","Go live"],l=Math.max(1,a.length||4),o=16,c=(zl-$r*2-o*(l-1))/l,d=176;(a.length?a:i).forEach((u,h)=>{const m=$r+h*(c+o);Hy(n,m,r,c,d,8,io,"FD",cb),n.setFont(Zc,"bold"),n.setFontSize(16),n.setTextColor(...s.accent),n.text(String(h+1),m+16,r+34),n.setFont(Zc,"bold"),n.setFontSize(7.5),n.setTextColor(...Qv),n.text((i[h]||`STEP ${h+1}`).toUpperCase(),m+16,r+56,{charSpace:1.2}),ou(n,u,m+16,r+76,c-32,{size:9,color:ny,leading:13,maxLines:5})}),ou(n,t.body,$r,r+d+34,zl-$r*2-120,{size:10,style:"bold",color:s.brand,leading:15,maxLines:2}),t0(s)}function rbn(s,t){e0(s);const{doc:n}=s,r=ry(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=(zl-$r*2-l*(i-1))/i,c=68;a.forEach(([u,h],m)=>{const f=$r+m%i*(o+l),g=r+Math.floor(m/i)*(c+l);Hy(n,f,g,o,c,8,io,"FD",cb),GRt(n,u,h,f+28,g+c/2,20),Bf(n,u,f+48,g+c/2+4,o-64,13,{style:"bold",color:h})});const d=r+2*(c+l)+22;ou(n,t.body,$r,d,zl-$r*2-140,{size:9.5,color:ny,leading:14,maxLines:3}),n.setFont(Zc,"normal"),n.setFontSize(7.5),n.setTextColor(...Qv),n.text("Distribution varies by MLS, market, and portal policies.",$r,Ih-62),t0(s)}function abn(s,t){e0(s,SR);const{doc:n,data:r}=s,{line1:a}=WRt(r),i=ry(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;Hy(n,$r,i,l,o,10,io,"FD",cb),Hy(n,$r,i,l,22,10,s.deep),n.setFillColor(...s.deep),n.rect($r,i+12,l,10,"F"),n.setFont(Zc,"bold"),n.setFontSize(7),n.setTextColor(...io);const c=(r.agent.website||`${a}`).replace(/^https?:\/\//,"").toUpperCase();Bf(n,c,$r+14,i+15,l-28,7,{style:"bold",color:io,charSpace:1}),NWe(s,$r+14,i+36,186,142);const d=$r+214,u=l-228;Bf(n,a,d,i+54,u,12,{style:"bold",color:s.brand}),ou(n,"Welcome home.",d,i+72,u,{size:9,color:s.accent,leading:12,maxLines:1}),ou(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:ny,leading:12,maxLines:5}),KRt(s,"Shareable. Trackable. Memorable.",$r+14,i+o-46,l-28);const h=$r+l+40,m=zl-h-$r;oq(s,t.title,h,i+12);let f=ou(n,t.body,h,i+32,m,{size:9.5,color:ny,leading:15,maxLines:5});const g=s6(t,5);g.length&&iq(n,g,h,f+26,m,{font:Zc,size:9,color:nS,accent:s.accent,gap:7}),t0(s)}function ibn(s,t){e0(s,s.deep);const{doc:n}=s,r=ry(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=$r+h*(i+l);Hy(n,m,r,i,i,12,io),GRt(n,d,u,m+i/2,r+i/2-4,30),n.setFont(Zc,"bold"),n.setFontSize(6.5),n.setTextColor(...Qv),n.text(d.toUpperCase(),m+i/2,r+i-8,{align:"center",charSpace:.6})});const o=$r+5*(i+l)+14,c=zl-o-$r;oq(s,"The campaign can include",o,r+12),iq(n,s6(t,5),o,r+32,c,{font:Zc,size:9,color:io,accent:s.accent,gap:7}),ou(n,t.body,$r,r+i+44,420,{size:9.5,color:Ap(io,s.deep,.2),leading:15,maxLines:4}),ou(n,"Every post sends attention back to the property.",$r,Ih-84,460,{size:11,style:"bold",color:io,leading:14,maxLines:1}),t0(s,!0)}function obn(s,t){e0(s);const{doc:n}=s,r=ry(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=s6(t,4),i=["Email announcement","Agent-to-agent outreach","Database follow-up","Local community visibility"];let l=r+6;a.forEach((o,c)=>{Hy(n,$r,l-14,34,34,8,Ap(s.accent,io,.85)),n.setFont(Zc,"bold"),n.setFontSize(11),n.setTextColor(...s.brand),n.text(String(c+1),$r+17,l+7,{align:"center"});const d=$r+52,u=zl-d-$r-20;n.setFont(Zc,"bold"),n.setFontSize(8),n.setTextColor(...s.brand),n.text((i[c]||t.title).toUpperCase(),d,l-2,{charSpace:1.2}),ou(n,o,d,l+14,u,{size:9.5,color:ny,leading:14,maxLines:2}),l+=76}),ou(n,t.body,$r,Math.min(l+8,Ih-92),zl-$r*2-120,{size:9.5,color:Qv,leading:14,maxLines:2}),t0(s)}function lbn(s,t){e0(s);const{doc:n}=s,r=ry(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=s6(t,4),i=["Open house","Signage","Neighborhood","Follow-up"],l=2,o=20,c=(zl-$r*2-o)/l,d=112;a.forEach((u,h)=>{const m=$r+h%l*(c+o),f=r+Math.floor(h/l)*(d+o);Hy(n,m,f,c,d,8,SR,"FD",cb),n.setFont(Zc,"bold"),n.setFontSize(7.5),n.setTextColor(...s.brand),n.text((i[h]||t.title).toUpperCase(),m+16,f+24,{charSpace:1.2}),ou(n,u,m+16,f+46,c-32,{size:9.5,color:ny,leading:14,maxLines:3})}),t0(s)}function cbn(s,t){e0(s,SR);const{doc:n}=s,r=ry(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=s6(t,4),i=["Weekly update","Market check","Smart adjustments","Direct access"];let l=r+10;a.forEach((o,c)=>{n.setFont(Zc,"bold"),n.setFontSize(11),n.setTextColor(...s.accent),n.text(String(c+1).padStart(2,"0"),$r,l),n.setFont(Zc,"bold"),n.setFontSize(9),n.setTextColor(...s.brand),n.text((i[c]||"").toUpperCase(),$r+48,l,{charSpace:1.2}),ou(n,o,$r+250,l-1,zl-$r-250-$r,{size:9.5,color:ny,leading:13,maxLines:2}),n.setDrawColor(...cb),n.setLineWidth(.5),n.line($r,l+22,zl-$r,l+22),l+=62}),ou(n,"Marketing creates opportunity. Communication helps us act on it.",$r,Math.min(l+18,Ih-84),520,{size:11,style:"bold",color:s.brand,leading:14,maxLines:1}),t0(s)}function dbn(s){e0(s,s.deep);const{doc:t,data:n}=s;s.hero&&CJ(t,s.hero,0,0,zl,Ih,{tint:{color:s.deep,amount:.92},darken:.25,dpi:s.dpi});const r=TJ(s,"closing"),a=ry(s,r.kicker,r.headline,r.subhead||null,{dark:!0,width:520}),i=420;let l=ou(t,r.body,$r,a,i,{size:10.5,color:Ap(io,s.deep,.18),leading:17});l+=30,iq(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"],$r,l,i,{font:Zc,size:9.5,color:io,accent:s.accent,gap:8});const o=jWe(n),c=250,d=zl-$r-c,u=a-20,h=o?300:258;Hy(t,d,u,c,h,10,io),t.setFillColor(...s.accent),t.rect(d,u,c,3,"F"),s.headshot&&(o&&s.coHeadshot?(qD(t,s.headshot,d+c/2-34,u+70,32),qD(t,s.coHeadshot,d+c/2+34,u+70,32)):qD(t,s.headshot,d+c/2,u+70,38)),Bf(t,o?`${n.agent.name} + ${o.name}`:n.agent.name,d+c/2,u+(s.headshot?132:68),c-30,16,{style:"bold",color:s.brand,align:"center"});let m=u+(s.headshot?152:90);[n.agent.brokerageName,n.agent.phone,n.agent.email,n.agent.website,n.agent.licenseNumber?`License ${n.agent.licenseNumber}${n.agent.licenseState?` · ${n.agent.licenseState}`:""}`:null].filter(Boolean).slice(0,5).forEach(f=>{Bf(t,String(f),d+c/2,m,c-30,8.5,{color:Qv,align:"center"}),m+=14}),o?(m+=6,t.setDrawColor(...cb),t.setLineWidth(.5),t.line(d+24,m-8,d+c-24,m-8),Bf(t,o.name,d+c/2,m+8,c-30,10,{style:"bold",color:s.brand,align:"center"}),m+=22,[o.title||"Co-listing agent",o.phone,o.email].filter(Boolean).slice(0,3).forEach(f=>{Bf(t,String(f),d+c/2,m,c-30,8.5,{color:Qv,align:"center"}),m+=13})):s.logo&&wWe(t,s.logo,d+c/2-50,u+h-44,100,28,"left"),t.setFont(Zc,"bold"),t.setFontSize(9),t.setTextColor(...io),U1(t,.9),t.text("LET'S MAKE YOUR HOME THE ONE BUYERS REMEMBER.",$r,Ih-72,{charSpace:1.4}),U1(t,1),t0(s,!0)}function kWe(s,t){return s.customImages[t.id]||null}function YRt(s,t,n,r,a,i){const l=kWe(s,t);l?CJ(s.doc,l,n,r,a,i,{radius:10,dpi:s.dpi}):NWe(s,n,r,a,i)}function ubn(s,t){e0(s,t.dark?s.deep:AJ);const{doc:n}=s,r=ry(s,t.kicker||"About",t.headline,t.subhead||null,{dark:t.dark}),a=300,i=t.imageSide!=="left",l=i?zl-$r-a:$r,o=i?$r:$r+a+40,c=zl-$r*2-a-40;YRt(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=ou(n,h,o,u,c,{size:10,color:t.dark?Ap(io,s.deep,.2):ny,leading:16,maxLines:7}),u+=26}),t.bullets.length&&iq(n,t.bullets.slice(0,5),o,Math.min(u,Ih-150),c,{font:Zc,size:9.5,color:t.dark?io:nS,accent:s.accent,gap:7}),t0(s,t.dark)}function hbn(s,t){e0(s,t.dark?s.deep:SR);const{doc:n}=s,r=ry(s,t.kicker||"What others are saying",t.headline,t.subhead||null,{dark:t.dark}),a=t.testimonials.filter(m=>{var f;return(f=m.quote)==null?void 0:f.trim()}).slice(0,6),i=a.length<=2?a.length||1:a.length>4?3:2,l=18,o=(zl-$r*2-l*(i-1))/i,c=Math.ceil(a.length/i)||1,d=Ih-72-r,u=c>1?Math.min(150,(d-l*(c-1))/c):Math.min(200,d),h=c>1?i===3?4:3:7;a.forEach((m,f)=>{const g=$r+f%i*(o+l),y=r+Math.floor(f/i)*(u+l);Hy(n,g,y,o,u,10,t.dark?Ap(s.deep,io,.08):io,"FD",cb),n.setFillColor(...s.accent),n.rect(g,y,3,u,"F"),n.setFont(F$,"bold"),n.setFontSize(30),n.setTextColor(...Ap(s.accent,t.dark?s.deep:io,.4)),n.text("“",g+18,y+40),ou(n,m.quote,g+18,y+56,o-40,{size:9.5,color:t.dark?Ap(io,s.deep,.2):ny,leading:14,maxLines:h}),n.setDrawColor(...s.accent),n.setLineWidth(1.2),n.line(g+18,y+u-32,g+42,y+u-32),n.setFont(Zc,"bold"),n.setFontSize(8),n.setTextColor(...s.brand);const x=[m.name,m.detail].filter(Boolean).join(" · ");x&&Bf(n,x.toUpperCase(),g+18,y+u-16,o-36,8,{style:"bold",color:t.dark?io:s.brand,charSpace:1.1})}),t.body&&ou(n,t.body,$r,Math.min(r+c*(u+l)+14,Ih-88),zl-$r*2-120,{size:9.5,color:t.dark?Ap(io,s.deep,.2):Qv,leading:14,maxLines:2}),t0(s,t.dark)}function mbn(s,t){e0(s,t.dark?s.deep:AJ);const{doc:n}=s,r=ry(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=(zl-$r*2-18*(a.length-1))/a.length,o=150;a.forEach((c,d)=>{const u=$r+d*(l+18);Hy(n,u,r,l,o,10,t.dark?Ap(s.deep,io,.1):io,"FD",cb),n.setFillColor(...s.accent),n.rect(u,r,l,3,"F"),Bf(n,c.value||"—",u+l/2,r+76,l-28,34,{style:"bold",color:t.dark?io:s.brand,align:"center"}),ou(n,c.label||"",u+20,r+100,l-40,{size:9,color:t.dark?Ap(io,s.deep,.3):Qv,leading:12,maxLines:2,align:"center"})}),t.body&&ou(n,t.body,$r,r+o+40,zl-$r*2-140,{size:10,color:t.dark?Ap(io,s.deep,.2):ny,leading:15,maxLines:3})}else t.body&&ou(n,t.body,$r,r,zl-$r*2-140,{size:10.5,color:t.dark?io:ny,leading:16});t0(s,t.dark)}function pbn(s,t){e0(s,t.dark?s.deep:io);const{doc:n}=s,r=ry(s,t.kicker||"Our promise",t.headline,t.subhead||null,{dark:t.dark}),i=!!kWe(s,t)||!!s.hero,l=i?zl-$r*2-280:zl-$r*2-140;let o=r;t.body&&(o=ou(n,t.body,$r,o,l,{size:10,color:t.dark?Ap(io,s.deep,.2):ny,leading:15,maxLines:3})+28),t.bullets.filter(d=>d==null?void 0:d.trim()).slice(0,7).forEach(d=>{Hy(n,$r,o-9,14,14,4,s.accent),n.setFont(Zc,"bold"),n.setFontSize(8),n.setTextColor(...io),n.text("✓",$r+7,o+1,{align:"center"}),o=ou(n,d,$r+26,o,l-26,{size:10,color:t.dark?io:nS,leading:14,maxLines:2})+22}),i&&YRt(s,t,zl-$r-240,r,240,250),t0(s,t.dark)}function fbn(s,t){e0(s,s.deep);const{doc:n}=s,r=kWe(s,t)||s.hero;r&&CJ(n,r,0,0,zl,Ih,{tint:{color:s.deep,amount:.82},darken:.28,dpi:s.dpi}),oq(s,t.kicker||"Our approach",$r,Ih/2-84),n.setFont(Zc,"bold"),n.setFontSize(30),n.setTextColor(...io);const a=n.splitTextToSize(t.headline||"",zl-$r*2-140).slice(0,4);a.forEach((i,l)=>n.text(i,$r,Ih/2-44+l*38)),t.body&&ou(n,t.body,$r,Ih/2+a.length*38-24,480,{size:10.5,color:Ap(io,s.deep,.2),leading:16,maxLines:4}),t0(s,!0)}function Jpt(s,t){switch(t.layout){case"testimonials":return hbn(s,t);case"stats":return mbn(s,t);case"checklist":return pbn(s,t);case"statement":return fbn(s,t);case"story":default:return ubn(s,t)}}async function gbn(s,t,n){var I,M,L,z;const r=n==="print"?4:2,a=n==="print"?2600:1600,i=O1n((I=t.pages)==null?void 0:I.theme);AJ=DF(i.paper),SR=DF(i.paperCool),cb=DF(i.softLine),ny=DF(i.bodyInk),F$=i.headFont;const l=DF((i.useAgentColors?t.agent.brandColor:i.brand)||i.brand||"#0E1B2C"),o=DF((i.useAgentColors?t.agent.accentColor:i.accent)||i.accent||"#B8965A"),c=Ap(l,[0,0,0],i.id==="luxury"?.35:.2),d=(M=t.coAgent)!=null&&M.enabled&&((L=t.coAgent.name)!=null&&L.trim())?t.coAgent:null,u=(t.customPages||[]).filter($=>$.enabled).sort(($,V)=>$.order-V.order),[h,m,f,g,...y]=await Promise.all([lH(t.property.photoUrl,a),lH(t.agent.headshotUrl,700),lH(t.agent.brokerageLogoUrl,800),lH((d==null?void 0:d.headshotUrl)||null,700),...u.map($=>lH($.imageUrl||null,a))]),x={};u.forEach(($,V)=>{x[$.id]=y[V]??null}),B1n(t.focal);const _={doc:s,data:t,brand:l,accent:o,deep:c,hero:h,headshot:m,coHeadshot:g,logo:f,customImages:x,dpi:r,pageNo:1},b=new Set(((z=t.pages)==null?void 0:z.hidden)||[]),k=[...t.services].filter($=>$.enabled).sort(($,V)=>$.order-V.order),A=$=>k.find(V=>V.key===$);J1n(_),b.has("welcome")||ebn(_),b.has("agent")||tbn(_),u.filter($=>$.placement!=="end").forEach($=>Jpt(_,$)),b.has("overview")||sbn(_,k);const T=new Set,P=($,V)=>{const W=A($);W&&(T.add($),V(W))};P("photography",$=>Qpt(_,$,{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."})),P("video",$=>Qpt(_,$,{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})),P("mls",$=>nbn(_,$)),P("syndication",$=>rbn(_,$)),P("website",$=>abn(_,$)),P("social",$=>ibn(_,$)),P("email",$=>obn(_,$)),P("openhouse",$=>lbn(_,$)),P("communication",$=>cbn(_,$)),k.filter($=>!T.has($.key)).forEach($=>{e0(_);const V=ry(_,"Marketing",$.title,null),W=s6($,6),G=ou(s,$.body,$r,V,zl-$r*2-160,{size:10.5,color:ny,leading:16});W.length&&iq(s,W,$r,G+30,zl-$r*2-160,{font:Zc,size:9.5,color:nS,accent:_.accent,gap:8}),t0(_)}),u.filter($=>$.placement==="end").forEach($=>Jpt(_,$)),b.has("closing")||dbn(_)}const eft=[{id:"signature",name:"Signature",description:"Editorial full-bleed cover with a brand-tinted photo motif throughout.",render:gbn}];function xbn(s){return eft.find(t=>t.id===s)||eft[0]}async function ZRt(s,t,n="screen"){const r=new wo({unit:"pt",format:"letter",orientation:"landscape",compress:!0});return await xbn(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 ybn(s){return`${(s.property.addressLine1||s.title||"listing-presentation").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,"")||"listing-presentation"}-presentation.pdf`}const vbn={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 P5e(s){if(!s)return null;const{data:t}=await H.storage.from(yE).createSignedUrl(s,3600);return(t==null?void 0:t.signedUrl)??null}function I5e(s,t,n){const r=s.agent_snapshot||{},a={...vbn,...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:PDt(s.co_agent),customPages:DDt(s.custom_pages),services:E7e(s.services),pages:s.page_settings&&Object.keys(s.page_settings).length?s.page_settings:A7e,focal:s.photo_focal||T7e}}async function XRt(s,t){if(s.property.photoUrl||!t)return s;const n=await P5e(t);return{...s,property:{...s.property,photoUrl:n}}}async function QRt(s,t,n){const r=await XRt(s,n);return(await ZRt(r,t,"screen")).output("blob")}async function JRt(s,t,n="print",r){const a=await XRt(s,r),l=(await ZRt(a,t,n)).output("blob"),o=URL.createObjectURL(l),c=document.createElement("a");return c.href=o,c.download=ybn(a),document.body.appendChild(c),c.click(),c.remove(),setTimeout(()=>URL.revokeObjectURL(o),4e3),l}async function eOt(s,t,n){const r=`${s}/${t}/presentation.pdf`,{error:a}=await H.storage.from(yE).upload(r,n,{upsert:!0,contentType:"application/pdf"});return a?null:(await H.from("listing_presentations").update({pdf_path:r,last_generated_at:new Date().toISOString(),status:"final"}).eq("id",t),r)}async function tOt(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 bbn(s,t,n){const r=await tOt(n),a=`${s}/${t}/photo.jpg`,{error:i}=await H.storage.from(yE).upload(a,r,{upsert:!0,contentType:"image/jpeg"});if(i)throw i;return a}async function _bn(s,t,n="presentation",r=1800){const a=await tOt(t,r),i=`${s}/${n}-${Date.now()}.jpg`,{error:l}=await H.storage.from("avatars").upload(i,a,{upsert:!0,contentType:"image/jpeg"});if(l)throw l;const{data:o}=H.storage.from("avatars").getPublicUrl(i);return o.publicUrl}function wbn({path:s,alt:t}){const[n,r]=N.useState(null),[a,i]=N.useState(!1);return N.useEffect(()=>{let l=!0;if(r(null),i(!1),!!s)return Cxn(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(_a,{className:"h-8 w-8 text-primary/50"})})}const tft=60*60*24*30;function sOt({open:s,onOpenChange:t,row:n,brand:r,photoUrl:a}){const{user:i}=Ls(),[l,o]=N.useState([]),[c,d]=N.useState(""),[u,h]=N.useState([]),[m,f]=N.useState(!1),[g,y]=N.useState(""),[x,_]=N.useState(""),[b,k]=N.useState(!1),A=N.useRef(null),T=(n==null?void 0:n.property_address_line1)||(n==null?void 0:n.title)||"your home";N.useEffect(()=>{!s||!n||(o([]),d(""),h([]),y(`Your listing presentation for ${T}`),_(`Hi {{first_name}}, Thank you for the opportunity to talk about selling ${T}. 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]),N.useEffect(()=>{A.current&&clearTimeout(A.current);const z=c.trim();if(!i||z.length<2||/\S+@\S+\.\S+/.test(z)){h([]);return}return A.current=setTimeout(async()=>{f(!0);const $=`%${z}%`,V=H,{data:W}=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.${$},last_name.ilike.${$},email.ilike.${$}`).order("first_name",{ascending:!0}).limit(6);f(!1),h(W||[])},200),()=>{A.current&&clearTimeout(A.current)}},[c,i==null?void 0:i.id]);const P=z=>{z.email&&(o($=>$.some(V=>V.email.toLowerCase()===z.email.toLowerCase())?$:[...$,z]),d(""),h([]))},I=()=>{const z=c.trim();if(!/\S+@\S+\.\S+/.test(z)){ie.error("Enter a valid email address");return}P({email:z})},M=N.useMemo(()=>!!n&&l.length>0&&g.trim().length>0&&!b,[n,l,g,b]),L=async()=>{if(!(!n||!i)){if(!n.property_photo_path){ie.error("Add the primary exterior photo before emailing the presentation");return}k(!0);try{const z=await QRt(I5e(n,r,a??null),n.template_id,n.property_photo_path),$=await eOt(i.id,n.id,z)||n.pdf_path;if(!$)throw new Error("Could not save the presentation PDF");const{data:V,error:W}=await H.storage.from(yE).createSignedUrl($,tft);if(W||!(V!=null&&V.signedUrl))throw new Error("Could not create a share link");const G=await P5e(n.property_photo_path).then(me=>me).catch(()=>null),{data:X}=await H.storage.from(yE).createSignedUrl(n.property_photo_path,tft),{data:te,error:ne}=await H.functions.invoke("listing-presentation-email",{body:{presentation_id:n.id,subject:g,message:x,pdf_url:V.signedUrl,photo_url:(X==null?void 0:X.signedUrl)||G,recipients:l}});if(ne)throw ne;if(!(te!=null&&te.success))throw new Error((te==null?void 0:te.error)||"Could not send the email");ie.success(te.failed?`Sent to ${te.sent} · ${te.failed} failed`:`Presentation emailed to ${te.sent} ${te.sent===1?"contact":"contacts"}`),t(!1)}catch(z){ie.error((z==null?void 0:z.message)||"Could not send the presentation")}finally{k(!1)}}};return e.jsx(Bs,{open:s,onOpenChange:t,children:e.jsxs(Fs,{className:"max-w-lg",children:[e.jsxs(qs,{children:[e.jsxs($s,{className:"flex items-center gap-2",children:[e.jsx(mn,{className:"h-4 w-4"})," Email this presentation"]}),e.jsxs(Ar,{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(re,{children:"To"}),l.length>0&&e.jsx("div",{className:"flex flex-wrap gap-1.5",children:l.map(z=>e.jsxs(We,{variant:"secondary",className:"gap-1 py-1",children:[[z.first_name,z.last_name].filter(Boolean).join(" ")||z.email,e.jsx("button",{type:"button",onClick:()=>o($=>$.filter(V=>V.email!==z.email)),"aria-label":`Remove ${z.email}`,children:e.jsx(hr,{className:"h-3 w-3"})})]},z.email))}),e.jsxs("div",{className:"relative",children:[e.jsxs("div",{className:"flex gap-2",children:[e.jsx(we,{value:c,onChange:z=>d(z.target.value),onKeyDown:z=>{z.key==="Enter"&&(z.preventDefault(),I())},placeholder:"Search contacts or type an email"}),e.jsx(B,{type:"button",variant:"outline",size:"icon",onClick:I,children:e.jsx(nn,{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(us,{className:"h-3 w-3 animate-spin"})," Searching…"]}),u.map(z=>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:()=>P({email:z.email,first_name:z.first_name,last_name:z.last_name,contact_id:z.id}),children:[e.jsx(Ro,{className:"h-3.5 w-3.5 text-muted-foreground"}),e.jsx("span",{className:"truncate",children:[z.first_name,z.last_name].filter(Boolean).join(" ")||z.email}),e.jsx("span",{className:"ml-auto truncate text-xs text-muted-foreground",children:z.email})]},z.id))]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{htmlFor:"pres-subject",children:"Subject"}),e.jsx(we,{id:"pres-subject",value:g,onChange:z=>y(z.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{htmlFor:"pres-message",children:"Message"}),e.jsx(Ws,{id:"pres-message",rows:7,value:x,onChange:z=>_(z.target.value)})]})]}),e.jsxs(Cr,{children:[e.jsx(B,{variant:"outline",onClick:()=>t(!1),disabled:b,children:"Cancel"}),e.jsxs(B,{onClick:L,disabled:!M,className:"gap-2",children:[b?e.jsx(us,{className:"h-4 w-4 animate-spin"}):e.jsx(Rr,{className:"h-4 w-4"}),b?"Sending…":`Send${l.length?` (${l.length})`:""}`]})]})]})})}const jbn=()=>{const s=tr(),{presentations:t,isLoading:n,create:r,duplicate:a,remove:i,update:l}=TDt(),{data:o}=kxn(),{data:c}=EDt(),{savedTemplates:d,remove:u}=ADt(),[h,m]=N.useState(null),[f,g]=N.useState(""),[y,x]=N.useState(null),[_,b]=N.useState(null),[k,A]=N.useState(null),T=N.useMemo(()=>{var L,z;return(z=(L=o==null?void 0:o[0])==null?void 0:L.default_services)!=null&&z.length?o[0].default_services:S5e},[o]),P=async()=>{var z;if(!c)return;const L=await r.mutateAsync({title:"Untitled Presentation",template_id:((z=o==null?void 0:o[0])==null?void 0:z.slug)||"signature",agent_snapshot:c,services:T});s(`/apps/listing-presentation-studio/${L.id}`)},I=async L=>{var $;const z=await r.mutateAsync({title:`${L.name} — new listing`,template_id:L.template_id||"signature",agent_snapshot:L.agent_snapshot,co_agent:L.co_agent,custom_pages:L.custom_pages,services:($=L.services)!=null&&$.length?L.services:T,page_settings:L.page_settings});s(`/apps/listing-presentation-studio/${z.id}`)},M=async L=>{try{b(L.id),await JRt(I5e(L,c),L.template_id,"print",L.property_photo_path)}catch(z){ie.error((z==null?void 0:z.message)||"Could not build the PDF")}finally{b(null)}};return e.jsxs(Qs,{children:[e.jsxs("div",{className:"space-y-8",children:[e.jsx("div",{className:"relative overflow-hidden rounded-2xl border bg-gradient-to-br from-primary/10 via-background to-accent/10 p-8",children:e.jsxs("div",{className:"flex flex-col gap-6 md:flex-row md:items-center md:justify-between",children:[e.jsxs("div",{className:"space-y-3",children:[e.jsxs(We,{variant:"secondary",className:"gap-1",children:[e.jsx(Cn,{className:"h-3 w-3"})," Listing Presentation Studio"]}),e.jsx("h1",{className:"text-3xl font-semibold tracking-tight",children:"Win the listing before you walk in"}),e.jsx("p",{className:"max-w-2xl text-sm text-muted-foreground",children:"Enter an address, drop in one exterior photo, and get a beautiful 12-page seller presentation branded with your profile — ready to present or print in under two minutes."})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(B,{size:"lg",onClick:P,disabled:r.isPending||!c,className:"gap-2",children:[r.isPending?e.jsx(us,{className:"h-4 w-4 animate-spin"}):e.jsx(nn,{className:"h-4 w-4"}),"New presentation"]}),d.length>0&&e.jsxs(qd,{children:[e.jsx(Vd,{asChild:!0,children:e.jsxs(B,{size:"lg",variant:"outline",className:"gap-2",children:[e.jsx(Hv,{className:"h-4 w-4"})," From template",e.jsx(Xo,{className:"h-4 w-4"})]})}),e.jsx(Ld,{align:"end",className:"w-64",children:d.map(L=>e.jsxs(ba,{onClick:()=>I(L),children:[e.jsx(Hv,{className:"mr-2 h-4 w-4 shrink-0"}),e.jsx("span",{className:"truncate",children:L.name})]},L.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(L=>e.jsx(_e,{className:"transition-shadow hover:shadow-md",children:e.jsxs(De,{className:"flex items-start justify-between gap-3 p-4",children:[e.jsxs("button",{className:"min-w-0 flex-1 text-left",onClick:()=>I(L),disabled:r.isPending,children:[e.jsxs("p",{className:"flex items-center gap-2 truncate font-medium",children:[e.jsx(Hv,{className:"h-4 w-4 shrink-0 text-muted-foreground"}),L.name]}),e.jsx("p",{className:"mt-1 line-clamp-2 text-xs text-muted-foreground",children:L.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(L.id),children:e.jsx(qn,{className:"h-4 w-4"})})]})},L.id))})]}),n?e.jsx("div",{className:"grid gap-5 sm:grid-cols-2 lg:grid-cols-3",children:[0,1,2].map(L=>e.jsx(xn,{className:"h-56 rounded-xl"},L))}):t.length===0?e.jsx(_e,{className:"border-dashed",children:e.jsxs(De,{className:"flex flex-col items-center gap-4 py-16 text-center",children:[e.jsx("div",{className:"flex h-14 w-14 items-center justify-center rounded-full bg-muted",children:e.jsx(Wr,{className:"h-7 w-7 text-muted-foreground"})}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:"No presentations yet"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Create your first seller presentation — it takes about two minutes."})]}),e.jsxs(B,{onClick:P,disabled:r.isPending||!c,className:"gap-2",children:[e.jsx(nn,{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(L=>{const z=L.property_address_line1||"No address yet",$=[L.city,L.state].filter(Boolean).join(", ");return e.jsxs(_e,{className:"group overflow-hidden transition-shadow hover:shadow-lg",children:[e.jsx("button",{className:"block w-full text-left",onClick:()=>s(`/apps/listing-presentation-studio/${L.id}`),children:e.jsx(wbn,{path:L.property_photo_path,alt:`${z} property photo`})}),e.jsxs(De,{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:L.title}),e.jsxs("p",{className:"truncate text-xs text-muted-foreground",children:[z,$?` · ${$}`:""]})]}),e.jsxs(qd,{children:[e.jsx(Vd,{asChild:!0,children:e.jsx(B,{variant:"ghost",size:"icon",className:"h-8 w-8 shrink-0",children:e.jsx(Ev,{className:"h-4 w-4"})})}),e.jsxs(Ld,{align:"end",children:[e.jsxs(ba,{onClick:()=>s(`/apps/listing-presentation-studio/${L.id}`),children:[e.jsx(Ja,{className:"mr-2 h-4 w-4"})," Open"]}),e.jsxs(ba,{onClick:()=>{m(L),g(L.title)},children:[e.jsx(Wr,{className:"mr-2 h-4 w-4"})," Rename"]}),e.jsxs(ba,{onClick:()=>a.mutate(L),children:[e.jsx(Pa,{className:"mr-2 h-4 w-4"})," Duplicate"]}),e.jsxs(ba,{onClick:()=>M(L),children:[e.jsx(oi,{className:"mr-2 h-4 w-4"})," Download PDF"]}),e.jsxs(ba,{onClick:()=>A(L),children:[e.jsx(mn,{className:"mr-2 h-4 w-4"})," Email to a contact"]}),e.jsx(s1,{}),e.jsxs(ba,{className:"text-destructive",onClick:()=>x(L),children:[e.jsx(qn,{className:"mr-2 h-4 w-4"})," Delete"]})]})]})]}),e.jsxs("div",{className:"flex items-center justify-between text-xs text-muted-foreground",children:[e.jsxs("span",{children:["Updated ",Js(new Date(L.updated_at),"MMM d, yyyy")]}),L.last_generated_at?e.jsx(We,{variant:"secondary",className:"text-[10px]",children:"PDF ready"}):e.jsx(We,{variant:"outline",className:"text-[10px]",children:"Draft"})]}),e.jsxs(B,{variant:"outline",size:"sm",className:"w-full gap-2",disabled:_===L.id,onClick:()=>M(L),children:[_===L.id?e.jsx(us,{className:"h-4 w-4 animate-spin"}):e.jsx(oi,{className:"h-4 w-4"}),"Download PDF"]})]})]},L.id)})})]}),e.jsx(Bs,{open:!!h,onOpenChange:L=>!L&&m(null),children:e.jsxs(Fs,{className:"sm:max-w-md",children:[e.jsx(qs,{children:e.jsx($s,{children:"Rename presentation"})}),e.jsx(we,{value:f,onChange:L=>g(L.target.value),autoFocus:!0}),e.jsxs(Cr,{children:[e.jsx(B,{variant:"outline",onClick:()=>m(null),children:"Cancel"}),e.jsx(B,{onClick:async()=>{h&&(await l.mutateAsync({id:h.id,title:f.trim()||"Untitled Presentation"}),m(null),ie.success("Renamed"))},children:"Save"})]})]})}),e.jsx(Fl,{open:!!y,onOpenChange:L=>!L&&x(null),children:e.jsxs(kl,{children:[e.jsxs(Sl,{children:[e.jsx(Al,{children:"Delete this presentation?"}),e.jsx(Tl,{children:"This permanently removes the presentation, its property photo, and the generated PDF."})]}),e.jsxs(Cl,{children:[e.jsx(El,{children:"Cancel"}),e.jsx(wl,{className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",onClick:()=>{y&&i.mutate(y),x(null)},children:"Delete"})]})]})}),e.jsx(sOt,{open:!!k,onOpenChange:L=>!L&&A(null),row:k,brand:c})]})};var TK={};TK.d=(s,t)=>{for(var n in t)TK.o(t,n)&&!TK.o(s,n)&&Object.defineProperty(s,n,{enumerable:!0,get:t[n]})};TK.o=(s,t)=>Object.prototype.hasOwnProperty.call(s,t);var Ll=globalThis.pdfjsLib={};TK.d(Ll,{AbortException:()=>pO,AnnotationEditorLayer:()=>aze,AnnotationEditorParamsType:()=>bl,AnnotationEditorType:()=>tc,AnnotationEditorUIManager:()=>AR,AnnotationLayer:()=>_wn,AnnotationMode:()=>xA,ColorPicker:()=>F5e,DOMSVGFactory:()=>OWe,DrawLayer:()=>cze,FeatureTest:()=>Jv,GlobalWorkerOptions:()=>$4,ImageKind:()=>cje,InvalidPDFException:()=>rOt,MissingPDFException:()=>mO,OPS:()=>m2,OutputScale:()=>J7e,PDFDataRangeTransport:()=>eFt,PDFDateString:()=>EWe,PDFWorker:()=>lz,PasswordResponses:()=>Cbn,PermissionFlag:()=>Sbn,PixelsPerInch:()=>bE,RenderingCancelledException:()=>AWe,TextLayer:()=>PZ,UnexpectedResponseException:()=>_Ae,Util:()=>go,VerbosityLevel:()=>yAe,XfaLayer:()=>sFt,build:()=>twn,createValidAbsoluteUrl:()=>Mbn,fetchData:()=>jAe,getDocument:()=>G_n,getFilenameFromUrl:()=>Bbn,getPdfFilenameFromUrl:()=>$bn,getXfaPageViewport:()=>Ubn,isDataScheme:()=>NAe,isPdfFile:()=>TWe,noContextMenu:()=>kj,normalizeUnicode:()=>Obn,setLayerDimensions:()=>CR,shadow:()=>od,version:()=>ewn});const Fy=typeof process=="object"&&process+""=="[object process]"&&!process.versions.nw&&!(process.versions.electron&&process.type&&process.type!=="browser"),nOt=[1,0,0,1,0,0],Y7e=[.001,0,0,.001,0,0],Nbn=1e7,RPe=1.35,c_={ANY:1,DISPLAY:2,PRINT:4,SAVE:8,ANNOTATIONS_FORMS:16,ANNOTATIONS_STORAGE:32,ANNOTATIONS_DISABLE:64,IS_EDITING:128,OPLIST:256},xA={DISABLE:0,ENABLE:1,ENABLE_FORMS:2,ENABLE_STORAGE:3},kbn="pdfjs_internal_editor_",tc={DISABLE:-1,NONE:0,FREETEXT:3,HIGHLIGHT:9,STAMP:13,INK:15},bl={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},Sbn={PRINT:4,MODIFY_CONTENTS:8,COPY:16,MODIFY_ANNOTATIONS:32,FILL_INTERACTIVE_FORMS:256,COPY_FOR_ACCESSIBILITY:512,ASSEMBLE:1024,PRINT_HIGH_QUALITY:2048},jy={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},cje={GRAYSCALE_1BPP:1,RGB_24BPP:2,RGBA_32BPP:3},Fg={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},cH={SOLID:1,DASHED:2,BEVELED:3,INSET:4,UNDERLINE:5},yAe={ERRORS:0,WARNINGS:1,INFOS:5},m2={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},Cbn={NEED_PASSWORD:1,INCORRECT_PASSWORD:2};let vAe=yAe.WARNINGS;function Abn(s){Number.isInteger(s)&&(vAe=s)}function Tbn(){return vAe}function bAe(s){vAe>=yAe.INFOS&&console.log(`Info: ${s}`)}function jc(s){vAe>=yAe.WARNINGS&&console.log(`Warning: ${s}`)}function lm(s){throw new Error(s)}function ex(s,t){s||lm(t)}function Ebn(s){switch(s==null?void 0:s.protocol){case"http:":case"https:":case"ftp:":case"mailto:":case"tel:":return!0;default:return!1}}function Mbn(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=Rbn(s)}catch{}}const r=t?new URL(s,t):new URL(s);if(Ebn(r))return r}catch{}return null}function od(s,t,n,r=!1){return Object.defineProperty(s,t,{value:n,enumerable:!r,configurable:!0,writable:!1}),n}const n6=function(){function t(n,r){this.message=n,this.name=r}return t.prototype=new Error,t.constructor=t,t}();class Z7e extends n6{constructor(t,n){super(t,"PasswordException"),this.code=n}}class X7e extends n6{constructor(t,n){super(t,"UnknownErrorException"),this.details=n}}class rOt extends n6{constructor(t){super(t,"InvalidPDFException")}}class mO extends n6{constructor(t){super(t,"MissingPDFException")}}class _Ae extends n6{constructor(t,n){super(t,"UnexpectedResponseException"),this.status=n}}class Lbn extends n6{constructor(t){super(t,"FormatError")}}class pO extends n6{constructor(t){super(t,"AbortException")}}function aOt(s){(typeof s!="object"||(s==null?void 0:s.length)===void 0)&&lm("Invalid argument for bytesToString");const t=s.length,n=8192;if(t>24&255,s>>16&255,s>>8&255,s&255)}function SWe(s){const t=Object.create(null);for(const[n,r]of s)t[n]=r;return t}function Ibn(){const s=new Uint8Array(4);return s[0]=1,new Uint32Array(s.buffer,0,1)[0]===1}function Dbn(){try{return new Function(""),!0}catch{return!1}}class Jv{static get isLittleEndian(){return od(this,"isLittleEndian",Ibn())}static get isEvalSupported(){return od(this,"isEvalSupported",Dbn())}static get isOffscreenCanvasSupported(){return od(this,"isOffscreenCanvasSupported",typeof OffscreenCanvas<"u")}static get platform(){return typeof navigator<"u"&&typeof(navigator==null?void 0:navigator.platform)=="string"?od(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")}):od(this,"platform",{isMac:!1,isWindows:!1,isFirefox:!1})}static get isCSSRoundSupported(){var t,n;return od(this,"isCSSRoundSupported",(n=(t=globalThis.CSS)==null?void 0:t.supports)==null?void 0:n.call(t,"width: round(1.5px, 1px)"))}}const OPe=Array.from(Array(256).keys(),s=>s.toString(16).padStart(2,"0"));var x3,dje,Q7e;class go{static makeHexColor(t,n,r){return`#${OPe[t]}${OPe[n]}${OPe[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)],Ht(this,x3,Q7e).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),Ht(this,x3,Q7e).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}}x3=new WeakSet,dje=function(t,n,r,a,i,l,o,c,d,u){if(d<=0||d>=1)return;const h=1-d,m=d*d,f=m*d,g=h*(h*(h*t+3*d*n)+3*m*r)+f*a,y=h*(h*(h*i+3*d*l)+3*m*o)+f*c;u[0]=Math.min(u[0],g),u[1]=Math.min(u[1],y),u[2]=Math.max(u[2],g),u[3]=Math.max(u[3],y)},Q7e=function(t,n,r,a,i,l,o,c,d,u,h,m){if(Math.abs(d)<1e-12){Math.abs(u)>=1e-12&&Ht(this,x3,dje).call(this,t,n,r,a,i,l,o,c,-h/u,m);return}const f=u**2-4*h*d;if(f<0)return;const g=Math.sqrt(f),y=2*d;Ht(this,x3,dje).call(this,t,n,r,a,i,l,o,c,(-u+g)/y,m),Ht(this,x3,dje).call(this,t,n,r,a,i,l,o,c,(-u-g)/y,m)},ts(go,x3);function Rbn(s){return decodeURIComponent(escape(s))}let FPe=null,sft=null;function Obn(s){return FPe||(FPe=/([\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,sft=new Map([["ſt","ſt"]])),s.replaceAll(FPe,(t,n,r)=>n?n.normalize("NFKC"):sft.get(r))}function Fbn(){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 aOt(s)}const CWe="pdfjs_internal_id_",US={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 zbn(s){return Uint8Array.prototype.toBase64?s.toBase64():btoa(aOt(s))}const XS="http://www.w3.org/2000/svg",NI=class NI{};jr(NI,"CSS",96),jr(NI,"PDF",72),jr(NI,"PDF_TO_CSS_UNITS",NI.CSS/NI.PDF);let bE=NI;async function jAe(s,t="text"){if(iG(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 EJ{constructor({viewBox:t,scale:n,rotation:r,offsetX:a=0,offsetY:i=0,dontFlip:l=!1}){this.viewBox=t,this.scale=n,this.rotation=r,this.offsetX=a,this.offsetY=i;const o=(t[2]+t[0])/2,c=(t[3]+t[1])/2;let d,u,h,m;switch(r%=360,r<0&&(r+=360),r){case 180:d=-1,u=0,h=0,m=1;break;case 90:d=0,u=1,h=1,m=0;break;case 270:d=0,u=-1,h=-1,m=0;break;case 0:d=1,u=0,h=0,m=-1;break;default:throw new Error("PageViewport: Invalid rotation, must be a multiple of 90 degrees.")}l&&(h=-h,m=-m);let f,g,y,x;d===0?(f=Math.abs(c-t[1])*n+a,g=Math.abs(o-t[0])*n+i,y=(t[3]-t[1])*n,x=(t[2]-t[0])*n):(f=Math.abs(o-t[0])*n+a,g=Math.abs(c-t[1])*n+i,y=(t[2]-t[0])*n,x=(t[3]-t[1])*n),this.transform=[d*n,u*n,h*n,m*n,f-d*n*o-h*n*c,g-u*n*o-m*n*c],this.width=y,this.height=x}get rawDims(){const{viewBox:t}=this;return od(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 EJ({viewBox:this.viewBox.slice(),scale:t,rotation:n,offsetX:r,offsetY:a,dontFlip:i})}convertToViewportPoint(t,n){return go.applyTransform([t,n],this.transform)}convertToViewportRectangle(t){const n=go.applyTransform([t[0],t[1]],this.transform),r=go.applyTransform([t[2],t[3]],this.transform);return[n[0],n[1],r[0],r[1]]}convertToPdfPoint(t,n){return go.applyInverseTransform([t,n],this.transform)}}class AWe extends n6{constructor(t,n=0){super(t,"RenderingCancelledException"),this.extraDelay=n}}function NAe(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))}}WZ=new WeakMap,ts(EWe,WZ);function Ubn(s,{scale:t=1,rotation:n=0}){const{width:r,height:a}=s.attributes.style,i=[0,0,parseInt(r),parseInt(a)];return new EJ({viewBox:i,scale:t,rotation:n})}function MWe(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):(jc(`Not a valid color format: "${s}"`),[0,0,0])}function qbn(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,MWe(r))}t.remove()}function pp(s){const{a:t,b:n,c:r,d:a,e:i,f:l}=s.getTransform();return[t,n,r,a,i,l]}function qS(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 CR(s,t,n=!1,r=!0){if(t instanceof EJ){const{pageWidth:a,pageHeight:i}=t.rawDims,{style:l}=s,o=Jv.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 J7e{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 AA,r8,g2,a8,KZ,YZ,rSe,iOt,e1,oOt,lOt,uje,cOt,t9e;const a4=class a4{constructor(t){ts(this,e1);ts(this,AA,null);ts(this,r8,null);ts(this,g2);ts(this,a8,null);ts(this,KZ,null);Dt(this,g2,t),de(a4,YZ)||Dt(a4,YZ,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=Dt(this,AA,document.createElement("div"));t.classList.add("editToolbar","hidden"),t.setAttribute("role","toolbar");const n=de(this,g2)._uiManager._signal;t.addEventListener("contextmenu",kj,{signal:n}),t.addEventListener("pointerdown",Ht(a4,rSe,iOt),{signal:n});const r=Dt(this,a8,document.createElement("div"));r.className="buttons",t.append(r);const a=de(this,g2).toolbarPosition;if(a){const{style:i}=t,l=de(this,g2)._uiManager.direction==="ltr"?1-a[0]:a[0];i.insetInlineEnd=`${100*l}%`,i.top=`calc(${100*a[1]}% + var(--editor-toolbar-vert-offset))`}return Ht(this,e1,cOt).call(this),t}get div(){return de(this,AA)}hide(){var t;de(this,AA).classList.add("hidden"),(t=de(this,r8))==null||t.hideDropdown()}show(){var t;de(this,AA).classList.remove("hidden"),(t=de(this,KZ))==null||t.shown()}async addAltText(t){const n=await t.render();Ht(this,e1,uje).call(this,n),de(this,a8).prepend(n,de(this,e1,t9e)),Dt(this,KZ,t)}addColorPicker(t){Dt(this,r8,t);const n=t.renderButton();Ht(this,e1,uje).call(this,n),de(this,a8).prepend(n,de(this,e1,t9e))}remove(){var t;de(this,AA).remove(),(t=de(this,r8))==null||t.destroy(),Dt(this,r8,null)}};AA=new WeakMap,r8=new WeakMap,g2=new WeakMap,a8=new WeakMap,KZ=new WeakMap,YZ=new WeakMap,rSe=new WeakSet,iOt=function(t){t.stopPropagation()},e1=new WeakSet,oOt=function(t){de(this,g2)._focusEventsAllowed=!1,t.preventDefault(),t.stopPropagation()},lOt=function(t){de(this,g2)._focusEventsAllowed=!0,t.preventDefault(),t.stopPropagation()},uje=function(t){const n=de(this,g2)._uiManager._signal;t.addEventListener("focusin",Ht(this,e1,oOt).bind(this),{capture:!0,signal:n}),t.addEventListener("focusout",Ht(this,e1,lOt).bind(this),{capture:!0,signal:n}),t.addEventListener("contextmenu",kj,{signal:n})},cOt=function(){const{editorType:t,_uiManager:n}=de(this,g2),r=document.createElement("button");r.className="delete",r.tabIndex=0,r.setAttribute("data-l10n-id",de(a4,YZ)[t]),Ht(this,e1,uje).call(this,r),r.addEventListener("click",a=>{n.delete()},{signal:n._signal}),de(this,a8).append(r)},t9e=function(){const t=document.createElement("div");return t.className="divider",t},ts(a4,rSe),ts(a4,YZ,null);let e9e=a4;var ZZ,i8,o8,NE,dOt,uOt,hOt;class Vbn{constructor(t){ts(this,NE);ts(this,ZZ,null);ts(this,i8,null);ts(this,o8);Dt(this,o8,t)}show(t,n,r){const[a,i]=Ht(this,NE,uOt).call(this,n,r),{style:l}=de(this,i8)||Dt(this,i8,Ht(this,NE,dOt).call(this));t.append(de(this,i8)),l.insetInlineEnd=`${100*a}%`,l.top=`calc(${100*i}% + var(--editor-toolbar-vert-offset))`}hide(){de(this,i8).remove()}}ZZ=new WeakMap,i8=new WeakMap,o8=new WeakMap,NE=new WeakSet,dOt=function(){const t=Dt(this,i8,document.createElement("div"));t.className="editToolbar",t.setAttribute("role","toolbar"),t.addEventListener("contextmenu",kj,{signal:de(this,o8)._signal});const n=Dt(this,ZZ,document.createElement("div"));return n.className="buttons",t.append(n),Ht(this,NE,hOt).call(this),t},uOt=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{de(this,o8).highlightSelection("floating_button")},{signal:r}),de(this,ZZ).append(t)};function D5e(s,t,n){for(const r of n)t.addEventListener(r,s[r].bind(s))}function Hbn(s){return Math.round(Math.min(255,Math.max(1,255*s))).toString(16).padStart(2,"0")}var aSe;class Gbn{constructor(){ts(this,aSe,0)}get id(){return`${kbn}${Sx(this,aSe)._++}`}}aSe=new WeakMap;var Sz,XZ,Sy,Cz,hje;const VKe=class VKe{constructor(){ts(this,Cz);ts(this,Sz,Fbn());ts(this,XZ,0);ts(this,Sy,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 od(this,"_isSVGFittingCanvas",i)}async getFromFile(t){const{lastModified:n,name:r,size:a,type:i}=t;return Ht(this,Cz,hje).call(this,`${n}_${r}_${a}_${i}`,t)}async getFromUrl(t){return Ht(this,Cz,hje).call(this,t,t)}async getFromBlob(t,n){const r=await n;return Ht(this,Cz,hje).call(this,t,r)}async getFromId(t){de(this,Sy)||Dt(this,Sy,new Map);const n=de(this,Sy).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){de(this,Sy)||Dt(this,Sy,new Map);let r=de(this,Sy).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_${de(this,Sz)}_${Sx(this,XZ)._++}`,refCounter:1,isSvg:!1},de(this,Sy).set(t,r),de(this,Sy).set(r.id,r),r}getSvgUrl(t){const n=de(this,Sy).get(t);return n!=null&&n.isSvg?n.svgUrl:null}deleteId(t){var a;de(this,Sy)||Dt(this,Sy,new Map);const n=de(this,Sy).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_${de(this,Sz)}_`)}};Sz=new WeakMap,XZ=new WeakMap,Sy=new WeakMap,Cz=new WeakSet,hje=async function(t,n){de(this,Sy)||Dt(this,Sy,new Map);let r=de(this,Sy).get(t);if(r===null)return null;if(r!=null&&r.bitmap)return r.refCounter+=1,r;try{r||(r={bitmap:null,id:`image_${de(this,Sz)}_${Sx(this,XZ)._++}`,refCounter:0,isSvg:!1});let a;if(typeof n=="string"?(r.url=n,a=await jAe(n,"blob")):n instanceof File?a=r.file=n:n instanceof Blob&&(a=n),a.type==="image/svg+xml"){const i=VKe._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 de(this,Sy).set(t,r),r&&de(this,Sy).set(r.id,r),r};let s9e=VKe;var Mx,TA,QZ,Lx;class Wbn{constructor(t=128){ts(this,Mx,[]);ts(this,TA,!1);ts(this,QZ);ts(this,Lx,-1);Dt(this,QZ,t)}add({cmd:t,undo:n,post:r,mustExec:a,type:i=NaN,overwriteIfSameType:l=!1,keepUndo:o=!1}){if(a&&t(),de(this,TA))return;const c={cmd:t,undo:n,post:r,type:i};if(de(this,Lx)===-1){de(this,Mx).length>0&&(de(this,Mx).length=0),Dt(this,Lx,0),de(this,Mx).push(c);return}if(l&&de(this,Mx)[de(this,Lx)].type===i){o&&(c.undo=de(this,Mx)[de(this,Lx)].undo),de(this,Mx)[de(this,Lx)]=c;return}const d=de(this,Lx)+1;d===de(this,QZ)?de(this,Mx).splice(0,1):(Dt(this,Lx,d),di===n[l]))return oSe._colorsMapping.get(r);return n}getHexCode(t){const n=this._colors.get(t);return n?go.makeHexColor(...n):t}};jr(oSe,"_colorsMapping",new Map([["CanvasText",[0,0,0]],["Canvas",[255,255,255]]]));let n9e=oSe;var Az,t_,$g,j0,Tz,f4,Ez,x2,EA,Mz,l8,Nk,y2,c8,JZ,eX,Lz,tX,kk,MA,Pz,LA,Sk,lSe,PA,sX,IA,d8,nX,rX,Px,Ou,g4,u8,aX,iX,DA,Ck,x4,oX,Ow,gi,mje,r9e,pOt,fOt,pje,gOt,xOt,yOt,a9e,vOt,i9e,o9e,bOt,wv,UC,_Ot,wOt,l9e,jOt,oG,c9e;const Q7=class Q7{constructor(t,n,r,a,i,l,o,c,d,u,h){ts(this,gi);ts(this,Az,new AbortController);ts(this,t_,null);ts(this,$g,new Map);ts(this,j0,new Map);ts(this,Tz,null);ts(this,f4,null);ts(this,Ez,null);ts(this,x2,new Wbn);ts(this,EA,null);ts(this,Mz,0);ts(this,l8,new Set);ts(this,Nk,null);ts(this,y2,null);ts(this,c8,new Set);ts(this,JZ,!1);ts(this,eX,!1);ts(this,Lz,!1);ts(this,tX,null);ts(this,kk,null);ts(this,MA,null);ts(this,Pz,null);ts(this,LA,!1);ts(this,Sk,null);ts(this,lSe,new Gbn);ts(this,PA,!1);ts(this,sX,!1);ts(this,IA,null);ts(this,d8,null);ts(this,nX,null);ts(this,rX,null);ts(this,Px,tc.NONE);ts(this,Ou,new Set);ts(this,g4,null);ts(this,u8,null);ts(this,aX,null);ts(this,iX,{isEditing:!1,isEmpty:!0,hasSomethingToUndo:!1,hasSomethingToRedo:!1,hasSelectedEditor:!1,hasSelectedText:!1});ts(this,DA,[0,0]);ts(this,Ck,null);ts(this,x4,null);ts(this,oX,null);ts(this,Ow,null);const m=this._signal=de(this,Az).signal;Dt(this,x4,t),Dt(this,oX,n),Dt(this,Tz,r),this._eventBus=a,a._on("editingaction",this.onEditingAction.bind(this),{signal:m}),a._on("pagechanging",this.onPageChanging.bind(this),{signal:m}),a._on("scalechanging",this.onScaleChanging.bind(this),{signal:m}),a._on("rotationchanging",this.onRotationChanging.bind(this),{signal:m}),a._on("setpreference",this.onSetPreference.bind(this),{signal:m}),a._on("switchannotationeditorparams",f=>this.updateParams(f.type,f.value),{signal:m}),Ht(this,gi,gOt).call(this),Ht(this,gi,bOt).call(this),Ht(this,gi,a9e).call(this),Dt(this,f4,i.annotationStorage),Dt(this,tX,i.filterFactory),Dt(this,u8,l),Dt(this,Pz,o||null),Dt(this,JZ,c),Dt(this,eX,d),Dt(this,Lz,u),Dt(this,rX,h||null),this.viewParameters={realScale:bE.PDF_TO_CSS_UNITS,rotation:0},this.isShiftKeyDown=!1}static get _keyboardManager(){const t=Q7.prototype,n=l=>de(l,x4).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 od(this,"_keyboardManager",new MJ([[["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)&&de(l,x4).contains(o)&&!l.isEnterHandled}],[[" ","mac+ "],t.addNewEditorFromKeyboard,{checker:(l,{target:o})=>!(o instanceof HTMLButtonElement)&&de(l,x4).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=de(this,Ow))==null||t.resolve(),Dt(this,Ow,null),(n=de(this,Az))==null||n.abort(),Dt(this,Az,null),this._signal=null;for(const i of de(this,j0).values())i.destroy();de(this,j0).clear(),de(this,$g).clear(),de(this,c8).clear(),Dt(this,t_,null),de(this,Ou).clear(),de(this,x2).destroy(),(r=de(this,Tz))==null||r.destroy(),(a=de(this,Sk))==null||a.hide(),Dt(this,Sk,null),de(this,kk)&&(clearTimeout(de(this,kk)),Dt(this,kk,null)),de(this,Ck)&&(clearTimeout(de(this,Ck)),Dt(this,Ck,null))}combinedSignal(t){return AbortSignal.any([this._signal,t.signal])}get mlManager(){return de(this,rX)}get useNewAltTextFlow(){return de(this,eX)}get useNewAltTextWhenAddingImage(){return de(this,Lz)}get hcmFilter(){return od(this,"hcmFilter",de(this,u8)?de(this,tX).addHCMFilter(de(this,u8).foreground,de(this,u8).background):"none")}get direction(){return od(this,"direction",getComputedStyle(de(this,x4)).direction)}get highlightColors(){return od(this,"highlightColors",de(this,Pz)?new Map(de(this,Pz).split(",").map(t=>t.split("=").map(n=>n.trim()))):null)}get highlightColorNames(){return od(this,"highlightColorNames",this.highlightColors?new Map(Array.from(this.highlightColors,t=>t.reverse())):null)}setMainHighlightColorPicker(t){Dt(this,nX,t)}editAltText(t,n=!1){var r;(r=de(this,Tz))==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":Dt(this,Lz,n);break}}onPageChanging({pageNumber:t}){Dt(this,Mz,t-1)}focusMainContainer(){de(this,x4).focus()}findParent(t,n){for(const r of de(this,j0).values()){const{x:a,y:i,width:l,height:o}=r.div.getBoundingClientRect();if(t>=a&&t<=a+l&&n>=i&&n<=i+o)return r}return null}disableUserSelect(t=!1){de(this,oX).classList.toggle("noUserSelect",t)}addShouldRescale(t){de(this,c8).add(t)}removeShouldRescale(t){de(this,c8).delete(t)}onScaleChanging({scale:t}){this.commitOrRemove(),this.viewParameters.realScale=t*bE.PDF_TO_CSS_UNITS;for(const n of de(this,c8))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=Ht(this,gi,mje).call(this,n).closest(".textLayer"),u=this.getSelectionBoxes(d);if(!u)return;n.empty();const h=Ht(this,gi,r9e).call(this,d),m=de(this,Px)===tc.NONE,f=()=>{h==null||h.createAndAddNewEditor({x:0,y:0},!1,{methodOfCreation:t,boxes:u,anchorNode:r,anchorOffset:a,focusNode:i,focusOffset:l,text:o}),m&&this.showAllEditors("highlight",!0,!0)};if(m){this.switchToMode(tc.HIGHLIGHT,f);return}f()}addToAnnotationStorage(t){!t.isEmpty()&&de(this,f4)&&!de(this,f4).has(t.id)&&de(this,f4).setValue(t.id,t)}blur(){if(this.isShiftKeyDown=!1,de(this,LA)&&(Dt(this,LA,!1),Ht(this,gi,pje).call(this,"main_toolbar")),!this.hasSelection)return;const{activeElement:t}=document;for(const n of de(this,Ou))if(n.div.contains(t)){Dt(this,d8,[n,t]),n._focusEventsAllowed=!1;break}}focus(){if(!de(this,d8))return;const[t,n]=de(this,d8);Dt(this,d8,null),n.addEventListener("focusin",()=>{t._focusEventsAllowed=!0},{once:!0,signal:this._signal}),n.focus()}addEditListeners(){Ht(this,gi,a9e).call(this),Ht(this,gi,i9e).call(this)}removeEditListeners(){Ht(this,gi,vOt).call(this),Ht(this,gi,o9e).call(this)}dragOver(t){for(const{type:n}of t.dataTransfer.items)for(const r of de(this,y2))if(r.isHandlingMimeForPasting(n)){t.dataTransfer.dropEffect="copy",t.preventDefault();return}}drop(t){for(const n of t.dataTransfer.items)for(const r of de(this,y2))if(r.isHandlingMimeForPasting(n.type)){r.paste(n,this.currentLayer),t.preventDefault();return}}copy(t){var r;if(t.preventDefault(),(r=de(this,t_))==null||r.commitOrRemove(),!this.hasSelection)return;const n=[];for(const a of de(this,Ou)){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 de(this,y2))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){jc(`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)Ht(this,gi,l9e).call(this,c);Ht(this,gi,c9e).call(this,i)},o=()=>{for(const c of i)c.remove()};this.addCommands({cmd:l,undo:o,mustExec:!0})}catch(i){jc(`paste: "${i.message}".`)}}keydown(t){!this.isShiftKeyDown&&t.key==="Shift"&&(this.isShiftKeyDown=!0),de(this,Px)!==tc.NONE&&!this.isEditorHandlingKeyboard&&Q7._keyboardManager.exec(this,t)}keyup(t){this.isShiftKeyDown&&t.key==="Shift"&&(this.isShiftKeyDown=!1,de(this,LA)&&(Dt(this,LA,!1),Ht(this,gi,pje).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?(Ht(this,gi,xOt).call(this),Ht(this,gi,i9e).call(this),Ht(this,gi,wv).call(this,{isEditing:de(this,Px)!==tc.NONE,isEmpty:Ht(this,gi,oG).call(this),hasSomethingToUndo:de(this,x2).hasSomethingToUndo(),hasSomethingToRedo:de(this,x2).hasSomethingToRedo(),hasSelectedEditor:!1})):(Ht(this,gi,yOt).call(this),Ht(this,gi,o9e).call(this),Ht(this,gi,wv).call(this,{isEditing:!1}),this.disableUserSelect(!1))}registerEditorTypes(t){if(!de(this,y2)){Dt(this,y2,t);for(const n of de(this,y2))Ht(this,gi,UC).call(this,n.defaultPropertiesToUpdate)}}getId(){return de(this,lSe).id}get currentLayer(){return de(this,j0).get(de(this,Mz))}getLayer(t){return de(this,j0).get(t)}get currentPageIndex(){return de(this,Mz)}addLayer(t){de(this,j0).set(t.pageIndex,t),de(this,PA)?t.enable():t.disable()}removeLayer(t){de(this,j0).delete(t.pageIndex)}async updateMode(t,n=null,r=!1){if(de(this,Px)!==t&&!(de(this,Ow)&&(await de(this,Ow).promise,!de(this,Ow)))){if(Dt(this,Ow,Promise.withResolvers()),Dt(this,Px,t),t===tc.NONE){this.setEditingState(!1),Ht(this,gi,wOt).call(this),de(this,Ow).resolve();return}this.setEditingState(!0),await Ht(this,gi,_Ot).call(this),this.unselectAll();for(const a of de(this,j0).values())a.updateMode(t);if(!n){r&&this.addNewEditorFromKeyboard(),de(this,Ow).resolve();return}for(const a of de(this,$g).values())a.annotationElementId===n?(this.setSelected(a),a.enterInEditMode()):a.unselect();de(this,Ow).resolve()}}addNewEditorFromKeyboard(){this.currentLayer.canCreateNewEmptyEditor()&&this.currentLayer.addNewEditor()}updateToolbar(t){t!==de(this,Px)&&this._eventBus.dispatch("switchannotationeditormode",{source:this,mode:t})}updateParams(t,n){var r;if(de(this,y2)){switch(t){case bl.CREATE:this.currentLayer.addNewEditor();return;case bl.HIGHLIGHT_DEFAULT_COLOR:(r=de(this,nX))==null||r.updateColor(n);break;case bl.HIGHLIGHT_SHOW_ALL:this._eventBus.dispatch("reporttelemetry",{source:this,details:{type:"editing",data:{type:"highlight",action:"toggle_visibility"}}}),(de(this,aX)||Dt(this,aX,new Map)).set(t,n),this.showAllEditors("highlight",n);break}for(const a of de(this,Ou))a.updateParams(t,n);for(const a of de(this,y2))a.updateDefaultParams(t,n)}}showAllEditors(t,n,r=!1){var i;for(const l of de(this,$g).values())l.editorType===t&&l.show(n);(((i=de(this,aX))==null?void 0:i.get(bl.HIGHLIGHT_SHOW_ALL))??!0)!==n&&Ht(this,gi,UC).call(this,[[bl.HIGHLIGHT_SHOW_ALL,n]])}enableWaiting(t=!1){if(de(this,sX)!==t){Dt(this,sX,t);for(const n of de(this,j0).values())t?n.disableClick():n.enableClick(),n.div.classList.toggle("waiting",t)}}getEditors(t){const n=[];for(const r of de(this,$g).values())r.pageIndex===t&&n.push(r);return n}getEditor(t){return de(this,$g).get(t)}addEditor(t){de(this,$g).set(t.id,t)}removeEditor(t){var n;t.div.contains(document.activeElement)&&(de(this,kk)&&clearTimeout(de(this,kk)),Dt(this,kk,setTimeout(()=>{this.focusMainContainer(),Dt(this,kk,null)},0))),de(this,$g).delete(t.id),this.unselect(t),(!t.annotationElementId||!de(this,l8).has(t.annotationElementId))&&((n=de(this,f4))==null||n.remove(t.id))}addDeletedAnnotationElement(t){de(this,l8).add(t.annotationElementId),this.addChangedExistingAnnotation(t),t.deleted=!0}isDeletedAnnotationElement(t){return de(this,l8).has(t)}removeDeletedAnnotationElement(t){de(this,l8).delete(t.annotationElementId),this.removeChangedExistingAnnotation(t),t.deleted=!1}setActiveEditor(t){de(this,t_)!==t&&(Dt(this,t_,t),t&&Ht(this,gi,UC).call(this,t.propertiesToUpdate))}updateUI(t){de(this,gi,jOt)===t&&Ht(this,gi,UC).call(this,t.propertiesToUpdate)}toggleSelected(t){if(de(this,Ou).has(t)){de(this,Ou).delete(t),t.unselect(),Ht(this,gi,wv).call(this,{hasSelectedEditor:this.hasSelection});return}de(this,Ou).add(t),t.select(),Ht(this,gi,UC).call(this,t.propertiesToUpdate),Ht(this,gi,wv).call(this,{hasSelectedEditor:!0})}setSelected(t){for(const n of de(this,Ou))n!==t&&n.unselect();de(this,Ou).clear(),de(this,Ou).add(t),t.select(),Ht(this,gi,UC).call(this,t.propertiesToUpdate),Ht(this,gi,wv).call(this,{hasSelectedEditor:!0})}isSelected(t){return de(this,Ou).has(t)}get firstSelectedEditor(){return de(this,Ou).values().next().value}unselect(t){t.unselect(),de(this,Ou).delete(t),Ht(this,gi,wv).call(this,{hasSelectedEditor:this.hasSelection})}get hasSelection(){return de(this,Ou).size!==0}get isEnterHandled(){return de(this,Ou).size===1&&this.firstSelectedEditor.isEnterHandled}undo(){de(this,x2).undo(),Ht(this,gi,wv).call(this,{hasSomethingToUndo:de(this,x2).hasSomethingToUndo(),hasSomethingToRedo:!0,isEmpty:Ht(this,gi,oG).call(this)})}redo(){de(this,x2).redo(),Ht(this,gi,wv).call(this,{hasSomethingToUndo:!0,hasSomethingToRedo:de(this,x2).hasSomethingToRedo(),isEmpty:Ht(this,gi,oG).call(this)})}addCommands(t){de(this,x2).add(t),Ht(this,gi,wv).call(this,{hasSomethingToUndo:!0,hasSomethingToRedo:!1,isEmpty:Ht(this,gi,oG).call(this)})}delete(){if(this.commitOrRemove(),!this.hasSelection)return;const t=[...de(this,Ou)],n=()=>{for(const a of t)a.remove()},r=()=>{for(const a of t)Ht(this,gi,l9e).call(this,a)};this.addCommands({cmd:n,undo:r,mustExec:!0})}commitOrRemove(){var t;(t=de(this,t_))==null||t.commitOrRemove()}hasSomethingToControl(){return de(this,t_)||this.hasSelection}selectAll(){for(const t of de(this,Ou))t.commit();Ht(this,gi,c9e).call(this,de(this,$g).values())}unselectAll(){if(!(de(this,t_)&&(de(this,t_).commitOrRemove(),de(this,Px)!==tc.NONE))&&this.hasSelection){for(const t of de(this,Ou))t.unselect();de(this,Ou).clear(),Ht(this,gi,wv).call(this,{hasSelectedEditor:!1})}}translateSelectedEditors(t,n,r=!1){if(r||this.commitOrRemove(),!this.hasSelection)return;de(this,DA)[0]+=t,de(this,DA)[1]+=n;const[a,i]=de(this,DA),l=[...de(this,Ou)],o=1e3;de(this,Ck)&&clearTimeout(de(this,Ck)),Dt(this,Ck,setTimeout(()=>{Dt(this,Ck,null),de(this,DA)[0]=de(this,DA)[1]=0,this.addCommands({cmd:()=>{for(const c of l)de(this,$g).has(c.id)&&c.translateInPage(a,i)},undo:()=>{for(const c of l)de(this,$g).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),Dt(this,Nk,new Map);for(const t of de(this,Ou))de(this,Nk).set(t,{savedX:t.x,savedY:t.y,savedPageIndex:t.pageIndex,newX:0,newY:0,newPageIndex:-1})}}endDragSession(){if(!de(this,Nk))return!1;this.disableUserSelect(!1);const t=de(this,Nk);Dt(this,Nk,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(de(this,$g).has(a.id)){const c=de(this,j0).get(o);c?a._setParentAndPosition(c,i,l):(a.pageIndex=o,a.x=i,a.y=l)}};return this.addCommands({cmd:()=>{for(const[a,{newX:i,newY:l,newPageIndex:o}]of t)r(a,i,l,o)},undo:()=>{for(const[a,{savedX:i,savedY:l,savedPageIndex:o}]of t)r(a,i,l,o)},mustExec:!0}),!0}dragSelectedEditors(t,n){if(de(this,Nk))for(const r of de(this,Nk).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())||de(this,Ou).size===1&&this.firstSelectedEditor.shouldGetKeyboardEvents()}isActive(t){return de(this,t_)===t}getActive(){return de(this,t_)}getMode(){return de(this,Px)}get imageManager(){return od(this,"imageManager",new s9e)}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"&&Ht(this,gi,pje).call(this,"main_toolbar"))};window.addEventListener("pointerup",h,{signal:u}),window.addEventListener("blur",h,{signal:u})}},pje=function(t=""){de(this,Px)===tc.HIGHLIGHT?this.highlightSelection(t):de(this,JZ)&&Ht(this,gi,pOt).call(this)},gOt=function(){document.addEventListener("selectionchange",Ht(this,gi,fOt).bind(this),{signal:this._signal})},xOt=function(){if(de(this,MA))return;Dt(this,MA,new AbortController);const t=this.combinedSignal(de(this,MA));window.addEventListener("focus",this.focus.bind(this),{signal:t}),window.addEventListener("blur",this.blur.bind(this),{signal:t})},yOt=function(){var t;(t=de(this,MA))==null||t.abort(),Dt(this,MA,null)},a9e=function(){if(de(this,IA))return;Dt(this,IA,new AbortController);const t=this.combinedSignal(de(this,IA));window.addEventListener("keydown",this.keydown.bind(this),{signal:t}),window.addEventListener("keyup",this.keyup.bind(this),{signal:t})},vOt=function(){var t;(t=de(this,IA))==null||t.abort(),Dt(this,IA,null)},i9e=function(){if(de(this,EA))return;Dt(this,EA,new AbortController);const t=this.combinedSignal(de(this,EA));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})},o9e=function(){var t;(t=de(this,EA))==null||t.abort(),Dt(this,EA,null)},bOt=function(){const t=this._signal;document.addEventListener("dragover",this.dragOver.bind(this),{signal:t}),document.addEventListener("drop",this.drop.bind(this),{signal:t})},wv=function(t){Object.entries(t).some(([r,a])=>de(this,iX)[r]!==a)&&(this._eventBus.dispatch("annotationeditorstateschanged",{source:this,details:Object.assign(de(this,iX),t)}),de(this,Px)===tc.HIGHLIGHT&&t.hasSelectedEditor===!1&&Ht(this,gi,UC).call(this,[[bl.HIGHLIGHT_FREE,!0]]))},UC=function(t){this._eventBus.dispatch("annotationeditorparamschanged",{source:this,details:t})},_Ot=async function(){if(!de(this,PA)){Dt(this,PA,!0);const t=[];for(const n of de(this,j0).values())t.push(n.enable());await Promise.all(t);for(const n of de(this,$g).values())n.enable()}},wOt=function(){if(this.unselectAll(),de(this,PA)){Dt(this,PA,!1);for(const t of de(this,j0).values())t.disable();for(const t of de(this,$g).values())t.disable()}},l9e=function(t){const n=de(this,j0).get(t.pageIndex);n?n.addOrRebuild(t):(this.addEditor(t),this.addToAnnotationStorage(t))},jOt=function(){let t=null;for(t of de(this,Ou));return t},oG=function(){if(de(this,$g).size===0)return!0;if(de(this,$g).size===1)for(const t of de(this,$g).values())return t.isEmpty();return!1},c9e=function(t){for(const n of de(this,Ou))n.unselect();de(this,Ou).clear();for(const n of t)n.isEmpty()||(de(this,Ou).add(n),n.select());Ht(this,gi,wv).call(this,{hasSelectedEditor:this.hasSelection})},jr(Q7,"TRANSLATE_SMALL",1),jr(Q7,"TRANSLATE_BIG",10);let AR=Q7;var Ix,Ak,v2,Iz,Tk,s_,Dz,Ek,R1,y4,h8,Mk,RA,V2,lG,fje;const Nv=class Nv{constructor(t){ts(this,V2);ts(this,Ix,null);ts(this,Ak,!1);ts(this,v2,null);ts(this,Iz,null);ts(this,Tk,null);ts(this,s_,null);ts(this,Dz,!1);ts(this,Ek,null);ts(this,R1,null);ts(this,y4,null);ts(this,h8,null);ts(this,Mk,!1);Dt(this,R1,t),Dt(this,Mk,t._uiManager.useNewAltTextFlow),de(Nv,RA)||Dt(Nv,RA,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){Nv._l10n??(Nv._l10n=t)}async render(){const t=Dt(this,v2,document.createElement("button"));t.className="altText",t.tabIndex="0";const n=Dt(this,Iz,document.createElement("span"));t.append(n),de(this,Mk)?(t.classList.add("new"),t.setAttribute("data-l10n-id",de(Nv,RA).missing),n.setAttribute("data-l10n-id",de(Nv,RA)["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=de(this,R1)._uiManager._signal;t.addEventListener("contextmenu",kj,{signal:r}),t.addEventListener("pointerdown",i=>i.stopPropagation(),{signal:r});const a=i=>{i.preventDefault(),de(this,R1)._uiManager.editAltText(de(this,R1)),de(this,Mk)&&de(this,R1)._reportTelemetry({action:"pdfjs.image.alt_text.image_status_label_clicked",data:{label:de(this,V2,lG)}})};return t.addEventListener("click",a,{capture:!0,signal:r}),t.addEventListener("keydown",i=>{i.target===t&&i.key==="Enter"&&(Dt(this,Dz,!0),a(i))},{signal:r}),await Ht(this,V2,fje).call(this),t}finish(){de(this,v2)&&(de(this,v2).focus({focusVisible:de(this,Dz)}),Dt(this,Dz,!1))}isEmpty(){return de(this,Mk)?de(this,Ix)===null:!de(this,Ix)&&!de(this,Ak)}hasData(){return de(this,Mk)?de(this,Ix)!==null||!!de(this,y4):this.isEmpty()}get guessedText(){return de(this,y4)}async setGuessedText(t){de(this,Ix)===null&&(Dt(this,y4,t),Dt(this,h8,await Nv._l10n.get("pdfjs-editor-new-alt-text-generated-alt-text-with-disclaimer",{generatedAltText:t})),Ht(this,V2,fje).call(this))}toggleAltTextBadge(t=!1){var n;if(!de(this,Mk)||de(this,Ix)){(n=de(this,Ek))==null||n.remove(),Dt(this,Ek,null);return}if(!de(this,Ek)){const r=Dt(this,Ek,document.createElement("div"));r.className="noAltTextBadge",de(this,R1).div.append(r)}de(this,Ek).classList.toggle("hidden",!t)}serialize(t){let n=de(this,Ix);return!t&&de(this,y4)===n&&(n=de(this,h8)),{altText:n,decorative:de(this,Ak),guessedText:de(this,y4),textWithDisclaimer:de(this,h8)}}get data(){return{altText:de(this,Ix),decorative:de(this,Ak)}}set data({altText:t,decorative:n,guessedText:r,textWithDisclaimer:a,cancel:i=!1}){r&&(Dt(this,y4,r),Dt(this,h8,a)),!(de(this,Ix)===t&&de(this,Ak)===n)&&(i||(Dt(this,Ix,t),Dt(this,Ak,n)),Ht(this,V2,fje).call(this))}toggle(t=!1){de(this,v2)&&(!t&&de(this,s_)&&(clearTimeout(de(this,s_)),Dt(this,s_,null)),de(this,v2).disabled=!t)}shown(){de(this,R1)._reportTelemetry({action:"pdfjs.image.alt_text.image_status_label_displayed",data:{label:de(this,V2,lG)}})}destroy(){var t,n;(t=de(this,v2))==null||t.remove(),Dt(this,v2,null),Dt(this,Iz,null),Dt(this,Tk,null),(n=de(this,Ek))==null||n.remove(),Dt(this,Ek,null)}};Ix=new WeakMap,Ak=new WeakMap,v2=new WeakMap,Iz=new WeakMap,Tk=new WeakMap,s_=new WeakMap,Dz=new WeakMap,Ek=new WeakMap,R1=new WeakMap,y4=new WeakMap,h8=new WeakMap,Mk=new WeakMap,RA=new WeakMap,V2=new WeakSet,lG=function(){return de(this,Ix)&&"added"||de(this,Ix)===null&&this.guessedText&&"review"||"missing"},fje=async function(){var a,i,l;const t=de(this,v2);if(!t)return;if(de(this,Mk)){if(t.classList.toggle("done",!!de(this,Ix)),t.setAttribute("data-l10n-id",de(Nv,RA)[de(this,V2,lG)]),(a=de(this,Iz))==null||a.setAttribute("data-l10n-id",de(Nv,RA)[`${de(this,V2,lG)}-label`]),!de(this,Ix)){(i=de(this,Tk))==null||i.remove();return}}else{if(!de(this,Ix)&&!de(this,Ak)){t.classList.remove("done"),(l=de(this,Tk))==null||l.remove();return}t.classList.add("done"),t.setAttribute("data-l10n-id","pdfjs-editor-alt-text-edit-button")}let n=de(this,Tk);if(!n){Dt(this,Tk,n=document.createElement("span")),n.className="tooltip",n.setAttribute("role","tooltip"),n.id=`alt-text-tooltip-${de(this,R1).id}`;const o=100,c=de(this,R1)._uiManager._signal;c.addEventListener("abort",()=>{clearTimeout(de(this,s_)),Dt(this,s_,null)},{once:!0}),t.addEventListener("mouseenter",()=>{Dt(this,s_,setTimeout(()=>{Dt(this,s_,null),de(this,Tk).classList.add("show"),de(this,R1)._reportTelemetry({action:"alt_text_tooltip"})},o))},{signal:c}),t.addEventListener("mouseleave",()=>{var d;de(this,s_)&&(clearTimeout(de(this,s_)),Dt(this,s_,null)),(d=de(this,Tk))==null||d.classList.remove("show")},{signal:c})}de(this,Ak)?n.setAttribute("data-l10n-id","pdfjs-editor-alt-text-decorative-tooltip"):(n.removeAttribute("data-l10n-id"),n.textContent=de(this,Ix)),n.parentNode||t.append(n);const r=de(this,R1).getImageForAltText();r==null||r.setAttribute("aria-describedby",n.id)},ts(Nv,RA,null),jr(Nv,"_l10n",null);let R5e=Nv;var m8,b2,hp,Rz,p8,N0,f8,OA,lX,g8,FA,cX,x8,v4,Lk,Oz,Fz,Fw,dX,cSe,fc,d9e,uX,u9e,h9e,NOt,kOt,m9e,p9e,f9e,SOt,g9e,COt,AOt,TOt,x9e,cG;const bu=class bu{constructor(t){ts(this,fc);ts(this,m8,null);ts(this,b2,null);ts(this,hp,null);ts(this,Rz,!1);ts(this,p8,!1);ts(this,N0,null);ts(this,f8,null);ts(this,OA,null);ts(this,lX,"");ts(this,g8,!1);ts(this,FA,null);ts(this,cX,!1);ts(this,x8,!1);ts(this,v4,!1);ts(this,Lk,null);ts(this,Oz,0);ts(this,Fz,0);ts(this,Fw,null);jr(this,"_editToolbar",null);jr(this,"_initialOptions",Object.create(null));jr(this,"_initialData",null);jr(this,"_isVisible",!0);jr(this,"_uiManager",null);jr(this,"_focusEventsAllowed",!0);ts(this,dX,!1);ts(this,cSe,bu._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=bu.prototype._resizeWithKeyboard,n=AR.TRANSLATE_SMALL,r=AR.TRANSLATE_BIG;return od(this,"_resizerKeyboardManager",new MJ([[["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"],bu.prototype._stopResizingWithKeyboard]]))}get editorType(){return Object.getPrototypeOf(this).constructor._type}static get _defaultLineColor(){return od(this,"_defaultLineColor",this._colorManager.getHexCode("CanvasText"))}static deleteAnnotationElement(t){const n=new Kbn({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(bu._l10n??(bu._l10n=t),bu._l10nResizer||(bu._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"})),bu._borderLineWidth!==-1)return;const r=getComputedStyle(document.documentElement);bu._borderLineWidth=parseFloat(r.getPropertyValue("--outline-width"))||0}static updateDefaultParams(t,n){}static get defaultPropertiesToUpdate(){return[]}static isHandlingMimeForPasting(t){return!1}static paste(t,n){lm("Not implemented")}get propertiesToUpdate(){return[]}get _isDraggable(){return de(this,dX)}set _isDraggable(t){var n;Dt(this,dX,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=de(this,cSe)}setParent(t){t!==null?(this.pageIndex=t.pageIndex,this.pageDimensions=t.pageDimensions):Ht(this,fc,cG).call(this),this.parent=t}focusin(t){this._focusEventsAllowed&&(de(this,g8)?Dt(this,g8,!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){Ht(this,fc,d9e).call(this,this.parentDimensions,t,n)}translateInPage(t,n){de(this,FA)||Dt(this,FA,[this.x,this.y]),Ht(this,fc,d9e).call(this,this.pageDimensions,t,n),this.div.scrollIntoView({block:"nearest"})}drag(t,n){de(this,FA)||Dt(this,FA,[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!!de(this,FA)&&(de(this,FA)[0]!==this.x||de(this,FA)[1]!==this.y)}getBaseTranslation(){const[t,n]=this.parentDimensions,{_borderLineWidth:r}=bu,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 Ht(r=bu,uX,u9e).call(r,t,n,this.parentRotation)}pageTranslationToScreen(t,n){var r;return Ht(r=bu,uX,u9e).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)}%`,de(this,p8)||(this.div.style.height=`${(100*n/a).toFixed(2)}%`)}fixDims(){const{style:t}=this.div,{height:n,width:r}=t,a=r.endsWith("%"),i=!de(this,p8)&&n.endsWith("%");if(a&&i)return;const[l,o]=this.parentDimensions;a||(t.width=`${(100*parseFloat(r)/l).toFixed(2)}%`),!de(this,p8)&&!i&&(t.height=`${(100*parseFloat(n)/o).toFixed(2)}%`)}getInitialTranslation(){return[0,0]}altTextFinish(){var t;(t=de(this,hp))==null||t.finish()}async addEditToolbar(){return this._editToolbar||de(this,x8)?this._editToolbar:(this._editToolbar=new e9e(this),this.div.append(this._editToolbar.render()),de(this,hp)&&await this._editToolbar.addAltText(de(this,hp)),this._editToolbar)}removeEditToolbar(){var t;this._editToolbar&&(this._editToolbar.remove(),this._editToolbar=null,(t=de(this,hp))==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(){de(this,hp)||(R5e.initialize(bu._l10n),Dt(this,hp,new R5e(this)),de(this,m8)&&(de(this,hp).data=de(this,m8),Dt(this,m8,null)),await this.addEditToolbar())}get altTextData(){var t;return(t=de(this,hp))==null?void 0:t.data}set altTextData(t){de(this,hp)&&(de(this,hp).data=t)}get guessedAltText(){var t;return(t=de(this,hp))==null?void 0:t.guessedText}async setGuessedAltText(t){var n;await((n=de(this,hp))==null?void 0:n.setGuessedText(t))}serializeAltText(t){var n;return(n=de(this,hp))==null?void 0:n.serialize(t)}hasAltText(){return!!de(this,hp)&&!de(this,hp).isEmpty()}hasAltTextData(){var t;return((t=de(this,hp))==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=de(this,Rz)?-1:0,this._isVisible||this.div.classList.add("hidden"),this.setInForeground(),Ht(this,fc,g9e).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),D5e(this,this.div,["pointerdown"]),this.div}pointerdown(t){const{isMac:n}=Jv.platform;if(t.button!==0||t.ctrlKey&&n){t.preventDefault();return}if(Dt(this,g8,!0),this._isDraggable){Ht(this,fc,SOt).call(this,t);return}Ht(this,fc,f9e).call(this,t)}get isSelected(){return this._uiManager.isSelected(this)}moveInDOM(){de(this,Lk)&&clearTimeout(de(this,Lk)),Dt(this,Lk,setTimeout(()=>{var t;Dt(this,Lk,null),(t=this.parent)==null||t.moveEditorInDOM(this)},0))}_setParentAndPosition(t,n,r){t.changeParent(this),this.x=n,this.y=r,this.fixAndSetPosition()}getRect(t,n,r=this.rotation){const a=this.parentScale,[i,l]=this.pageDimensions,[o,c]=this.pageTranslation,d=t/a,u=n/a,h=this.x*i,m=this.y*l,f=this.width*i,g=this.height*l;switch(r){case 0:return[h+d+o,l-m-u-g+c,h+d+f+o,l-m-u+c];case 90:return[h+u+o,l-m+d+c,h+u+g+o,l-m+d+f+c];case 180:return[h-d-f+o,l-m+u+c,h-d+o,l-m+u+g+c];case 270:return[h-u-g+o,l-m-d-f+c,h-u+o,l-m-d+c];default:throw new Error("Invalid rotation")}}getRectInCurrentCoords(t,n){const[r,a,i,l]=t,o=i-r,c=l-a;switch(this.rotation){case 0:return[r,n-l,o,c];case 90:return[r,n-a,c,o];case 180:return[i,n-a,o,c];case 270:return[i,n-l,c,o];default:throw new Error("Invalid rotation")}}onceAdded(){}isEmpty(){return!1}enableEditMode(){Dt(this,x8,!0)}disableEditMode(){Dt(this,x8,!1)}isInEditMode(){return de(this,x8)}shouldGetKeyboardEvents(){return de(this,v4)}needsToBeRebuilt(){return this.div&&!this.isAttachedToDOM}rebuild(){Ht(this,fc,g9e).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){lm("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,Dt(a,m8,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=de(this,OA))==null||t.abort(),Dt(this,OA,null),this.isEmpty()||this.commit(),this.parent?this.parent.remove(this):this._uiManager.removeEditor(this),de(this,Lk)&&(clearTimeout(de(this,Lk)),Dt(this,Lk,null)),Ht(this,fc,cG).call(this),this.removeEditToolbar(),de(this,Fw)){for(const n of de(this,Fw).values())clearTimeout(n);Dt(this,Fw,null)}this.parent=null}get isResizable(){return!1}makeResizable(){this.isResizable&&(Ht(this,fc,NOt).call(this),de(this,N0).classList.remove("hidden"),D5e(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),Dt(this,f8,{savedX:this.x,savedY:this.y,savedWidth:this.width,savedHeight:this.height});const n=de(this,N0).children;if(!de(this,b2)){Dt(this,b2,Array.from(n));const l=Ht(this,fc,COt).bind(this),o=Ht(this,fc,AOt).bind(this),c=this._uiManager._signal;for(const d of de(this,b2)){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",Ht(this,fc,TOt).bind(this,u),{signal:c}),d.setAttribute("data-l10n-id",bu._l10nResizer[u])}}const r=de(this,b2)[0];let a=0;for(const l of n){if(l===r)break;a++}const i=(360-this.rotation+this.parentRotation)%360/90*(de(this,b2).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=de(this,hp))==null||r.toggleAltTextBadge(!1)}unselect(){var t,n,r,a,i;(t=de(this,N0))==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=de(this,hp))==null||i.toggleAltTextBadge(!0)}updateParams(t,n){}disableEditing(){}enableEditing(){}enterInEditMode(){}getImageForAltText(){return null}get contentDiv(){return this.div}get isEditing(){return de(this,cX)}set isEditing(t){Dt(this,cX,t),this.parent&&(t?(this.parent.setSelected(this),this.parent.setActiveEditor(this)):this.parent.setActiveEditor(null))}setAspectRatio(t,n){Dt(this,p8,!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){de(this,Fw)||Dt(this,Fw,new Map);const{action:r}=t;let a=de(this,Fw).get(r);a&&clearTimeout(a),a=setTimeout(()=>{this._reportTelemetry(t),de(this,Fw).delete(r),de(this,Fw).size===0&&Dt(this,Fw,null)},bu._telemetryTimeout),de(this,Fw).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),Dt(this,Rz,!1)}disable(){this.div&&(this.div.tabIndex=-1),Dt(this,Rz,!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()}};m8=new WeakMap,b2=new WeakMap,hp=new WeakMap,Rz=new WeakMap,p8=new WeakMap,N0=new WeakMap,f8=new WeakMap,OA=new WeakMap,lX=new WeakMap,g8=new WeakMap,FA=new WeakMap,cX=new WeakMap,x8=new WeakMap,v4=new WeakMap,Lk=new WeakMap,Oz=new WeakMap,Fz=new WeakMap,Fw=new WeakMap,dX=new WeakMap,cSe=new WeakMap,fc=new WeakSet,d9e=function([t,n],r,a){[r,a]=this.screenToPageTranslation(r,a),this.x+=r/t,this.y+=a/n,this.fixAndSetPosition()},uX=new WeakSet,u9e=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]}},h9e=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]}},NOt=function(){if(de(this,N0))return;Dt(this,N0,document.createElement("div")),de(this,N0).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");de(this,N0).append(a),a.classList.add("resizer",r),a.setAttribute("data-resizer-name",r),a.addEventListener("pointerdown",Ht(this,fc,kOt).bind(this,r),{signal:n}),a.addEventListener("contextmenu",kj,{signal:n}),a.tabIndex=-1}this.div.prepend(de(this,N0))},kOt=function(t,n){var g;n.preventDefault();const{isMac:r}=Jv.platform;if(n.button!==0||n.ctrlKey&&r)return;(g=de(this,hp))==null||g.toggle(!1);const a=this._isDraggable;this._isDraggable=!1;const i=new AbortController,l=this._uiManager.combinedSignal(i);this.parent.togglePointerEvents(!1),window.addEventListener("pointermove",Ht(this,fc,p9e).bind(this,t),{passive:!0,capture:!0,signal:l}),window.addEventListener("contextmenu",kj,{signal:l});const o=this.x,c=this.y,d=this.width,u=this.height,h=this.parent.div.style.cursor,m=this.div.style.cursor;this.div.style.cursor=this.parent.div.style.cursor=window.getComputedStyle(n.target).cursor;const f=()=>{var y;i.abort(),this.parent.togglePointerEvents(!0),(y=de(this,hp))==null||y.toggle(!0),this._isDraggable=a,this.parent.div.style.cursor=h,this.div.style.cursor=m,Ht(this,fc,m9e).call(this,o,c,d,u)};window.addEventListener("pointerup",f,{signal:l}),window.addEventListener("blur",f,{signal:l})},m9e=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})},p9e=function(t,n){const[r,a]=this.parentDimensions,i=this.x,l=this.y,o=this.width,c=this.height,d=bu.MIN_SIZE/r,u=bu.MIN_SIZE/a,h=ne=>Math.round(ne*1e4)/1e4,m=Ht(this,fc,h9e).call(this,this.rotation),f=(ne,me)=>[m[0]*ne+m[2]*me,m[1]*ne+m[3]*me],g=Ht(this,fc,h9e).call(this,360-this.rotation),y=(ne,me)=>[g[0]*ne+g[2]*me,g[1]*ne+g[3]*me];let x,_,b=!1,k=!1;switch(t){case"topLeft":b=!0,x=(ne,me)=>[0,0],_=(ne,me)=>[ne,me];break;case"topMiddle":x=(ne,me)=>[ne/2,0],_=(ne,me)=>[ne/2,me];break;case"topRight":b=!0,x=(ne,me)=>[ne,0],_=(ne,me)=>[0,me];break;case"middleRight":k=!0,x=(ne,me)=>[ne,me/2],_=(ne,me)=>[0,me/2];break;case"bottomRight":b=!0,x=(ne,me)=>[ne,me],_=(ne,me)=>[0,0];break;case"bottomMiddle":x=(ne,me)=>[ne/2,me],_=(ne,me)=>[ne/2,0];break;case"bottomLeft":b=!0,x=(ne,me)=>[0,me],_=(ne,me)=>[ne,0];break;case"middleLeft":k=!0,x=(ne,me)=>[0,me/2],_=(ne,me)=>[ne,me/2];break}const A=x(o,c),T=_(o,c);let P=f(...T);const I=h(i+P[0]),M=h(l+P[1]);let L=1,z=1,[$,V]=this.screenToPageTranslation(n.movementX,n.movementY);if([$,V]=y($/r,V/a),b){const ne=Math.hypot(o,c);L=z=Math.max(Math.min(Math.hypot(T[0]-A[0]-$,T[1]-A[1]-V)/ne,1/o,1/c),d/o,u/c)}else k?L=Math.max(d,Math.min(1,Math.abs(T[0]-A[0]-$)))/o:z=Math.max(u,Math.min(1,Math.abs(T[1]-A[1]-V)))/c;const W=h(o*L),G=h(c*z);P=f(..._(W,G));const X=I-P[0],te=M-P[1];this.width=W,this.height=G,this.x=X,this.y=te,this.setDims(r*W,a*G),this.fixAndSetPosition()},f9e=function(t){const{isMac:n}=Jv.platform;t.ctrlKey&&!n||t.shiftKey||t.metaKey&&n?this.parent.toggleSelected(this):this.parent.setSelected(this)},SOt=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"),Dt(this,Oz,t.clientX),Dt(this,Fz,t.clientY);const l=o=>{const{clientX:c,clientY:d}=o,[u,h]=this.screenToPageTranslation(c-de(this,Oz),d-de(this,Fz));Dt(this,Oz,c),Dt(this,Fz,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"),Dt(this,g8,!1),this._uiManager.endDragSession()||Ht(this,fc,f9e).call(this,t)};window.addEventListener("pointerup",i,{signal:a}),window.addEventListener("blur",i,{signal:a})},g9e=function(){if(de(this,OA)||!this.div)return;Dt(this,OA,new AbortController);const t=this._uiManager.combinedSignal(de(this,OA));this.div.addEventListener("focusin",this.focusin.bind(this),{signal:t}),this.div.addEventListener("focusout",this.focusout.bind(this),{signal:t})},COt=function(t){bu._resizerKeyboardManager.exec(this,t)},AOt=function(t){var n;de(this,v4)&&((n=t.relatedTarget)==null?void 0:n.parentNode)!==de(this,N0)&&Ht(this,fc,cG).call(this)},TOt=function(t){Dt(this,lX,de(this,v4)?t:"")},x9e=function(t){if(de(this,b2))for(const n of de(this,b2))n.tabIndex=t},cG=function(){if(Dt(this,v4,!1),Ht(this,fc,x9e).call(this,-1),de(this,f8)){const{savedX:t,savedY:n,savedWidth:r,savedHeight:a}=de(this,f8);Ht(this,fc,m9e).call(this,t,n,r,a),Dt(this,f8,null)}},ts(bu,uX),jr(bu,"_l10n",null),jr(bu,"_l10nResizer",null),jr(bu,"_borderLineWidth",-1),jr(bu,"_colorManager",new n9e),jr(bu,"_zIndex",1),jr(bu,"_telemetryTimeout",1e3);let Uu=bu;class Kbn extends Uu{constructor(t){super(t),this.annotationElementId=t.annotationElementId,this.deleted=!0}serialize(){return this.serializeDeleted()}}const aft=3285377520,Tw=4294901760,ak=65535;class EOt{constructor(t){this.h1=t?t&4294967295:aft,this.h2=t?t&4294967295:aft}update(t){let n,r;if(typeof t=="string"){n=new Uint8Array(t.length*2),r=0;for(let y=0,x=t.length;y>>8,n[r++]=_&255)}}else if(ArrayBuffer.isView(t))n=t.slice(),r=n.byteLength;else throw new Error("Invalid data format, must be a string or TypedArray.");const a=r>>2,i=r-a*4,l=new Uint32Array(n.buffer,0,a);let o=0,c=0,d=this.h1,u=this.h2;const h=3432918353,m=461845907,f=h&ak,g=m&ak;for(let y=0;y>>17,o=o*m&Tw|o*g&ak,d^=o,d=d<<13|d>>>19,d=d*5+3864292196):(c=l[y],c=c*h&Tw|c*f&ak,c=c<<15|c>>>17,c=c*m&Tw|c*g&ak,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&Tw|o*f&ak,o=o<<15|o>>>17,o=o*m&Tw|o*g&ak,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&Tw|t*36045&ak,n=n*4283543511&Tw|((n<<16|t>>>16)*2950163797&Tw)>>>16,t^=n>>>1,t=t*444984403&Tw|t*60499&ak,n=n*3301882366&Tw|((n<<16|t>>>16)*3120437893&Tw)>>>16,t^=n>>>1,(t>>>0).toString(16).padStart(8,"0")+(n>>>0).toString(16).padStart(8,"0")}}const y9e=Object.freeze({map:null,hash:"",transfer:void 0});var y8,v8,Dx,dSe,MOt;class LWe{constructor(){ts(this,dSe);ts(this,y8,!1);ts(this,v8,null);ts(this,Dx,new Map);this.onSetModified=null,this.onResetModified=null,this.onAnnotationEditor=null}getValue(t,n){const r=de(this,Dx).get(t);return r===void 0?n:Object.assign(n,r)}getRawValue(t){return de(this,Dx).get(t)}remove(t){if(de(this,Dx).delete(t),de(this,Dx).size===0&&this.resetModified(),typeof this.onAnnotationEditor=="function"){for(const n of de(this,Dx).values())if(n instanceof Uu)return;this.onAnnotationEditor(null)}}setValue(t,n){const r=de(this,Dx).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,de(this,Dx).set(t,n);a&&Ht(this,dSe,MOt).call(this),n instanceof Uu&&typeof this.onAnnotationEditor=="function"&&this.onAnnotationEditor(n.constructor._type)}has(t){return de(this,Dx).has(t)}getAll(){return de(this,Dx).size>0?SWe(de(this,Dx)):null}setAll(t){for(const[n,r]of Object.entries(t))this.setValue(n,r)}get size(){return de(this,Dx).size}resetModified(){de(this,y8)&&(Dt(this,y8,!1),typeof this.onResetModified=="function"&&this.onResetModified())}get print(){return new LOt(this)}get serializable(){if(de(this,Dx).size===0)return y9e;const t=new Map,n=new EOt,r=[],a=Object.create(null);let i=!1;for(const[l,o]of de(this,Dx)){const c=o instanceof Uu?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}:y9e}get editorStats(){let t=null;const n=new Map;for(const r of de(this,Dx).values()){if(!(r instanceof Uu))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(){Dt(this,v8,null)}get modifiedIds(){if(de(this,v8))return de(this,v8);const t=[];for(const n of de(this,Dx).values())!(n instanceof Uu)||!n.annotationElementId||!n.serialize()||t.push(n.annotationElementId);return Dt(this,v8,{ids:new Set(t),hash:t.join(",")})}}y8=new WeakMap,v8=new WeakMap,Dx=new WeakMap,dSe=new WeakSet,MOt=function(){de(this,y8)||(Dt(this,y8,!0),typeof this.onSetModified=="function"&&this.onSetModified())};var hX;class LOt extends LWe{constructor(n){super();ts(this,hX);const{map:r,hash:a,transfer:i}=n.serializable,l=structuredClone(r,i?{transfer:i}:null);Dt(this,hX,{map:l,hash:a,transfer:i})}get print(){lm("Should not call PrintAnnotationStorage.print")}get serializable(){return de(this,hX)}get modifiedIds(){return od(this,"modifiedIds",{ids:new Set,hash:""})}}hX=new WeakMap;var zz;class Ybn{constructor({ownerDocument:t=globalThis.document,styleElement:n=null}){ts(this,zz,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(),de(this,zz).clear(),this.styleElement&&(this.styleElement.remove(),this.styleElement=null)}async loadSystemFont({systemFontInfo:t,_inspectFont:n}){if(!(!t||de(this,zz).has(t.loadedName))){if(ex(!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(),de(this,zz).add(r),n==null||n(t)}catch{jc(`Cannot load system font: ${t.baseFontName}, installing it could help to improve PDF rendering.`),this.removeNativeFontFace(l)}return}lm("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 jc(`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 od(this,"isFontLoadingAPISupported",t)}get isSyncFontLoadingSupported(){let t=!1;return(Fy||typeof navigator<"u"&&typeof(navigator==null?void 0:navigator.userAgent)=="string"&&/Mozilla\/5.0.*?rv:\d+.*? Gecko/.test(navigator.userAgent))&&(t=!0),od(this,"isSyncFontLoadingSupported",t)}_queueLoadingCallback(t){function n(){for(ex(!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 od(this,"_loadTestFont",t)}_prepareFontLoadEvent(t,n){function r(A,T){return A.charCodeAt(T)<<24|A.charCodeAt(T+1)<<16|A.charCodeAt(T+2)<<8|A.charCodeAt(T+3)&255}function a(A,T,P,I){const M=A.substring(0,T),L=A.substring(T+P);return M+I+L}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(A,T){if(++d>30){jc("Load test font never loaded."),T();return}if(c.font="30px "+A,c.fillText(".",0,20),c.getImageData(0,0,1,1).data[3]>0){T();return}setTimeout(u.bind(null,A,T))}const h=`lt${Date.now()}${this.loadTestFontId++}`;let m=this._loadTestFont;m=a(m,976,h.length,h);const g=16,y=1482184792;let x=r(m,g);for(i=0,l=h.length-3;i{k.remove(),n.complete()})}}zz=new WeakMap;class Zbn{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,${zbn(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){jc(`getPathGenerator - ignoring character: "${i}".`)}if(!Array.isArray(r)||r.length===0)return this.compiledGlyphs[n]=function(i,l){};const a=[];for(let i=0,l=r.length;if.bezierCurveTo(o,c,d,u,h,m)),i+=6}break;case US.MOVE_TO:{const[o,c]=r.slice(i,i+2);a.push(d=>d.moveTo(o,c)),i+=2}break;case US.LINE_TO:{const[o,c]=r.slice(i,i+2);a.push(d=>d.lineTo(o,c)),i+=2}break;case US.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 US.RESTORE:a.push(o=>o.restore());break;case US.SAVE:a.push(o=>o.save());break;case US.SCALE:ex(a.length===2,"Scale command is only valid at the third position.");break;case US.TRANSFORM:{const[o,c,d,u,h,m]=r.slice(i,i+6);a.push(f=>f.transform(o,c,d,u,h,m)),i+=6}break;case US.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){lm("Abstract method `_fetch` called.")}}class DOt extends IOt{async _fetch(t){const n=await jAe(t,this.isCompressed?"arraybuffer":"text");return n instanceof ArrayBuffer?new Uint8Array(n):wAe(n)}}class ROt{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 b8,_8,Pk,b4,Cy,uSe,w8,Di,Ny,l7,c7,gje,d7,OOt,v9e,u7,dG,uG,b9e,hG;class Qbn extends ROt{constructor({docId:n,ownerDocument:r=globalThis.document}){super();ts(this,Di);ts(this,b8);ts(this,_8);ts(this,Pk);ts(this,b4);ts(this,Cy);ts(this,uSe);ts(this,w8,0);Dt(this,b4,n),Dt(this,Cy,r)}addFilter(n){if(!n)return"none";let r=de(this,Di,Ny).get(n);if(r)return r;const[a,i,l]=Ht(this,Di,gje).call(this,n),o=n.length===1?a:`${a}${i}${l}`;if(r=de(this,Di,Ny).get(o),r)return de(this,Di,Ny).set(n,r),r;const c=`g_${de(this,b4)}_transfer_map_${Sx(this,w8)._++}`,d=Ht(this,Di,d7).call(this,c);de(this,Di,Ny).set(n,d),de(this,Di,Ny).set(o,d);const u=Ht(this,Di,u7).call(this,c);return Ht(this,Di,uG).call(this,a,i,l,u),d}addHCMFilter(n,r){var g;const a=`${n}-${r}`,i="base";let l=de(this,Di,l7).get(i);if((l==null?void 0:l.key)===a||(l?((g=l.filter)==null||g.remove(),l.key=a,l.url="none",l.filter=null):(l={key:a,url:"none",filter:null},de(this,Di,l7).set(i,l)),!n||!r))return l.url;const o=Ht(this,Di,hG).call(this,n);n=go.makeHexColor(...o);const c=Ht(this,Di,hG).call(this,r);if(r=go.makeHexColor(...c),de(this,Di,c7).style.color="",n==="#000000"&&r==="#ffffff"||n===r)return l.url;const d=new Array(256);for(let y=0;y<=255;y++){const x=y/255;d[y]=x<=.03928?x/12.92:((x+.055)/1.055)**2.4}const u=d.join(","),h=`g_${de(this,b4)}_hcm_filter`,m=l.filter=Ht(this,Di,u7).call(this,h);Ht(this,Di,uG).call(this,u,u,u,m),Ht(this,Di,v9e).call(this,m);const f=(y,x)=>{const _=o[y]/255,b=c[y]/255,k=new Array(x+1);for(let A=0;A<=x;A++)k[A]=_+A/x*(b-_);return k.join(",")};return Ht(this,Di,uG).call(this,f(0,5),f(1,5),f(2,5),m),l.url=Ht(this,Di,d7).call(this,h),l.url}addAlphaFilter(n){let r=de(this,Di,Ny).get(n);if(r)return r;const[a]=Ht(this,Di,gje).call(this,[n]),i=`alpha_${a}`;if(r=de(this,Di,Ny).get(i),r)return de(this,Di,Ny).set(n,r),r;const l=`g_${de(this,b4)}_alpha_map_${Sx(this,w8)._++}`,o=Ht(this,Di,d7).call(this,l);de(this,Di,Ny).set(n,o),de(this,Di,Ny).set(i,o);const c=Ht(this,Di,u7).call(this,l);return Ht(this,Di,b9e).call(this,a,c),o}addLuminosityFilter(n){let r=de(this,Di,Ny).get(n||"luminosity");if(r)return r;let a,i;if(n?([a]=Ht(this,Di,gje).call(this,[n]),i=`luminosity_${a}`):i="luminosity",r=de(this,Di,Ny).get(i),r)return de(this,Di,Ny).set(n,r),r;const l=`g_${de(this,b4)}_luminosity_map_${Sx(this,w8)._++}`,o=Ht(this,Di,d7).call(this,l);de(this,Di,Ny).set(n,o),de(this,Di,Ny).set(i,o);const c=Ht(this,Di,u7).call(this,l);return Ht(this,Di,OOt).call(this,c),n&&Ht(this,Di,b9e).call(this,a,c),o}addHighlightHCMFilter(n,r,a,i,l){var b;const o=`${r}-${a}-${i}-${l}`;let c=de(this,Di,l7).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},de(this,Di,l7).set(n,c)),!r||!a))return c.url;const[d,u]=[r,a].map(Ht(this,Di,hG).bind(this));let h=Math.round(.2126*d[0]+.7152*d[1]+.0722*d[2]),m=Math.round(.2126*u[0]+.7152*u[1]+.0722*u[2]),[f,g]=[i,l].map(Ht(this,Di,hG).bind(this));m{const P=new Array(256),I=(m-h)/T,M=k/255,L=(A-k)/(255*T);let z=0;for(let $=0;$<=T;$++){const V=Math.round(h+$*I),W=M+$*L;for(let G=z;G<=V;G++)P[G]=W;z=V+1}for(let $=z;$<256;$++)P[$]=P[z-1];return P.join(",")},x=`g_${de(this,b4)}_hcm_${n}_filter`,_=c.filter=Ht(this,Di,u7).call(this,x);return Ht(this,Di,v9e).call(this,_),Ht(this,Di,uG).call(this,y(f[0],g[0],5),y(f[1],g[1],5),y(f[2],g[2],5),_),c.url=Ht(this,Di,d7).call(this,x),c.url}destroy(n=!1){n&&de(this,Di,l7).size!==0||(de(this,Pk)&&(de(this,Pk).parentNode.parentNode.remove(),Dt(this,Pk,null)),de(this,_8)&&(de(this,_8).clear(),Dt(this,_8,null)),Dt(this,w8,0))}}b8=new WeakMap,_8=new WeakMap,Pk=new WeakMap,b4=new WeakMap,Cy=new WeakMap,uSe=new WeakMap,w8=new WeakMap,Di=new WeakSet,Ny=function(){return de(this,_8)||Dt(this,_8,new Map)},l7=function(){return de(this,uSe)||Dt(this,uSe,new Map)},c7=function(){if(!de(this,Pk)){const n=de(this,Cy).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=de(this,Cy).createElementNS(XS,"svg");a.setAttribute("width",0),a.setAttribute("height",0),Dt(this,Pk,de(this,Cy).createElementNS(XS,"defs")),n.append(a),a.append(de(this,Pk)),de(this,Cy).body.append(n)}return de(this,Pk)},gje=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(",")]},d7=function(n){if(de(this,b8)===void 0){Dt(this,b8,"");const r=de(this,Cy).URL;r!==de(this,Cy).baseURI&&(NAe(r)?jc('#createUrl: ignore "data:"-URL for performance reasons.'):Dt(this,b8,r.split("#",1)[0]))}return`url(${de(this,b8)}#${n})`},OOt=function(n){const r=de(this,Cy).createElementNS(XS,"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)},v9e=function(n){const r=de(this,Cy).createElementNS(XS,"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)},u7=function(n){const r=de(this,Cy).createElementNS(XS,"filter");return r.setAttribute("color-interpolation-filters","sRGB"),r.setAttribute("id",n),de(this,Di,c7).append(r),r},dG=function(n,r,a){const i=de(this,Cy).createElementNS(XS,r);i.setAttribute("type","discrete"),i.setAttribute("tableValues",a),n.append(i)},uG=function(n,r,a,i){const l=de(this,Cy).createElementNS(XS,"feComponentTransfer");i.append(l),Ht(this,Di,dG).call(this,l,"feFuncR",n),Ht(this,Di,dG).call(this,l,"feFuncG",r),Ht(this,Di,dG).call(this,l,"feFuncB",a)},b9e=function(n,r){const a=de(this,Cy).createElementNS(XS,"feComponentTransfer");r.append(a),Ht(this,Di,dG).call(this,a,"feFuncA",n)},hG=function(n){return de(this,Di,c7).style.color=n,MWe(getComputedStyle(de(this,Di,c7)).getPropertyValue("color"))};class FOt{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){lm("Abstract method `_fetch` called.")}}class zOt extends FOt{async _fetch(t){const n=await jAe(t,"arraybuffer");return new Uint8Array(n)}}if(Fy){var _9e=Promise.withResolvers(),EK=null;(async()=>{const t=await Fi(()=>import("./__vite-browser-external-BIHI7g3E.js"),[]),n=await Fi(()=>import("./__vite-browser-external-BIHI7g3E.js"),[]),r=await Fi(()=>import("./__vite-browser-external-BIHI7g3E.js"),[]),a=await Fi(()=>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=>{EK=t,_9e.resolve()},t=>{jc(`loadPackages: ${t}`),EK=new Map,_9e.resolve()})}class _E{static get promise(){return _9e.promise}static get(t){return EK==null?void 0:EK.get(t)}}async function BOt(s){const n=await _E.get("fs").promises.readFile(s);return new Uint8Array(n)}class Jbn extends ROt{}class e_n extends POt{_createCanvas(t,n){return _E.get("canvas").createCanvas(t,n)}}class t_n extends IOt{async _fetch(t){return BOt(t)}}class s_n extends FOt{async _fetch(t){return BOt(t)}}const Mv={FILL:"Fill",STROKE:"Stroke",SHADING:"Shading"};function w9e(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 PWe{getPattern(){lm("Abstract method `getPattern` called.")}}class n_n extends PWe{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===Mv.STROKE||a===Mv.FILL){const l=n.current.getClippedPathBoundingBox(a,pp(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=go.transform(r,[1,0,0,1,l[0],l[1]]),u.transform(...n.baseTransform),this.matrix&&u.transform(...this.matrix),w9e(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 w9e(t,this._bbox),i=this._createGradient(t);return i}}function zPe(s,t,n,r,a,i,l,o){const c=t.coords,d=t.colors,u=s.data,h=s.width*4;let m;c[n+1]>c[r+1]&&(m=n,n=r,r=m,m=i,i=l,l=m),c[r+1]>c[a+1]&&(m=r,r=a,a=m,m=l,l=o,o=m),c[n+1]>c[r+1]&&(m=n,n=r,r=m,m=i,i=l,l=m);const f=(c[n]+t.offsetX)*t.scaleX,g=(c[n+1]+t.offsetY)*t.scaleY,y=(c[r]+t.offsetX)*t.scaleX,x=(c[r+1]+t.offsetY)*t.scaleY,_=(c[a]+t.offsetX)*t.scaleX,b=(c[a+1]+t.offsetY)*t.scaleY;if(g>=b)return;const k=d[i],A=d[i+1],T=d[i+2],P=d[l],I=d[l+1],M=d[l+2],L=d[o],z=d[o+1],$=d[o+2],V=Math.round(g),W=Math.round(b);let G,X,te,ne,me,ue,ce,ae;for(let he=V;he<=W;he++){if(heb?Se=1:x===b?Se=0:Se=(x-he)/(x-b),G=y-(y-_)*Se,X=P-(P-L)*Se,te=I-(I-z)*Se,ne=M-(M-$)*Se}let xe;heb?xe=1:xe=(g-he)/(g-b),me=f-(f-_)*xe,ue=k-(k-L)*xe,ce=A-(A-z)*xe,ae=T-(T-$)*xe;const ve=Math.round(Math.min(G,me)),ge=Math.round(Math.max(G,me));let be=h*he+ve*4;for(let Se=ve;Se<=ge;Se++)xe=(G-Se)/(G-me),xe<0?xe=0:xe>1&&(xe=1),u[be++]=X-(X-ue)*xe|0,u[be++]=te-(te-ce)*xe|0,u[be++]=ne-(ne-ae)*xe|0,u[be++]=255}}function r_n(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=z?A=c:P=!0,L>=$?T=d:I=!0;const V=this.getSizeAndScale(A,this.ctx.canvas.width,b),W=this.getSizeAndScale(T,this.ctx.canvas.height,k),G=t.cachedCanvases.getCanvas("pattern",V.size,W.size),X=G.context,te=o.createCanvasGraphics(X);if(te.groupLevel=t.groupLevel,this.setFillAndStrokeStyleToContext(te,a,l),X.translate(-V.scale*u,-W.scale*h),te.transform(V.scale,0,0,W.scale,0,0),X.save(),this.clipBbox(te,u,h,m,f),te.baseTransform=pp(te.ctx),te.executeOperatorList(r),te.endDrawing(),X.restore(),P||I){const ne=G.canvas;P&&(A=c),I&&(T=d);const me=this.getSizeAndScale(A,this.ctx.canvas.width,b),ue=this.getSizeAndScale(T,this.ctx.canvas.height,k),ce=me.size,ae=ue.size,he=t.cachedCanvases.getCanvas("pattern-workaround",ce,ae),xe=he.context,ve=P?Math.floor(g/c):0,ge=I?Math.floor(y/d):0;for(let be=0;be<=ve;be++)for(let Se=0;Se<=ge;Se++)xe.drawImage(ne,ce*be,ae*Se,ce,ae,0,0,ce,ae);return{canvas:he.canvas,scaleX:me.scale,scaleY:ue.scale,offsetX:u,offsetY:h}}return{canvas:G.canvas,scaleX:V.scale,scaleY:W.scale,offsetX:u,offsetY:h}}getSizeAndScale(t,n,r){const a=Math.max(hSe.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(pp(t.ctx),[n,r,a,i]),t.clip(),t.endPath()}setFillAndStrokeStyleToContext(t,n,r){const a=t.ctx,i=t.current;switch(n){case ift.COLORED:const l=this.ctx;a.fillStyle=l.fillStyle,a.strokeStyle=l.strokeStyle,i.fillColor=l.fillStyle,i.strokeColor=l.strokeStyle;break;case ift.UNCOLORED:const o=go.makeHexColor(r[0],r[1],r[2]);a.fillStyle=o,a.strokeStyle=o,i.fillColor=o,i.strokeColor=o;break;default:throw new Lbn(`Unsupported paint type: ${n}`)}}getPattern(t,n,r,a){let i=r;a!==Mv.SHADING&&(i=go.transform(i,n.baseTransform),this.matrix&&(i=go.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}};jr(hSe,"MAX_PATTERN_SIZE",3e3);let j9e=hSe;function l_n({src:s,srcPos:t=0,dest:n,width:r,height:a,nonBlackColor:i=4294967295,inverseDecode:l=!1}){const o=Jv.isLittleEndian?4278190080:255,[c,d]=l?[i,o]:[o,i],u=r>>3,h=r&7,m=s.length;n=new Uint32Array(n.buffer);let f=0;for(let g=0;g{s.save=s.__originalSave,s.restore=s.__originalRestore,s.rotate=s.__originalRotate,s.scale=s.__originalScale,s.translate=s.__originalTranslate,s.transform=s.__originalTransform,s.setTransform=s.__originalSetTransform,s.resetTransform=s.__originalResetTransform,s.clip=s.__originalClip,s.moveTo=s.__originalMoveTo,s.lineTo=s.__originalLineTo,s.bezierCurveTo=s.__originalBezierCurveTo,s.rect=s.__originalRect,s.closePath=s.__originalClosePath,s.beginPath=s.__originalBeginPath,delete s._removeMirroring},s.save=function(){t.save(),this.__originalSave()},s.restore=function(){t.restore(),this.__originalRestore()},s.translate=function(r,a){t.translate(r,a),this.__originalTranslate(r,a)},s.scale=function(r,a){t.scale(r,a),this.__originalScale(r,a)},s.transform=function(r,a,i,l,o,c){t.transform(r,a,i,l,o,c),this.__originalTransform(r,a,i,l,o,c)},s.setTransform=function(r,a,i,l,o,c){t.setTransform(r,a,i,l,o,c),this.__originalSetTransform(r,a,i,l,o,c)},s.resetTransform=function(){t.resetTransform(),this.__originalResetTransform()},s.rotate=function(r){t.rotate(r),this.__originalRotate(r)},s.clip=function(r){t.clip(r),this.__originalClip(r)},s.moveTo=function(n,r){t.moveTo(n,r),this.__originalMoveTo(n,r)},s.lineTo=function(n,r){t.lineTo(n,r),this.__originalLineTo(n,r)},s.bezierCurveTo=function(n,r,a,i,l,o){t.bezierCurveTo(n,r,a,i,l,o),this.__originalBezierCurveTo(n,r,a,i,l,o)},s.rect=function(n,r,a,i){t.rect(n,r,a,i),this.__originalRect(n,r,a,i)},s.closePath=function(){t.closePath(),this.__originalClosePath()},s.beginPath=function(){t.beginPath(),this.__originalBeginPath()}}class u_n{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 bne(s,t,n,r,a,i,l,o,c,d){const[u,h,m,f,g,y]=pp(s);if(h===0&&m===0){const b=l*u+g,k=Math.round(b),A=o*f+y,T=Math.round(A),P=(l+c)*u+g,I=Math.abs(Math.round(P)-k)||1,M=(o+d)*f+y,L=Math.abs(Math.round(M)-T)||1;return s.setTransform(Math.sign(u),0,0,Math.sign(f),k,T),s.drawImage(t,n,r,a,i,0,0,I,L),s.setTransform(u,h,m,f,g,y),[I,L]}if(u===0&&f===0){const b=o*m+g,k=Math.round(b),A=l*h+y,T=Math.round(A),P=(o+d)*m+g,I=Math.abs(Math.round(P)-k)||1,M=(l+c)*h+y,L=Math.abs(Math.round(M)-T)||1;return s.setTransform(0,Math.sign(h),Math.sign(m),0,k,T),s.drawImage(t,n,r,a,i,0,0,L,I),s.setTransform(u,h,m,f,g,y),[L,I]}s.drawImage(t,n,r,a,i,l,o,c,d);const x=Math.hypot(u,h),_=Math.hypot(m,f);return[x*c,_*d]}function h_n(s){const{width:t,height:n}=s;if(t>dft||n>dft)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 _ of s.data){let b=128;for(;b>0;)h[m++]=_&b?0:255,b>>=1}let f=0;for(m=0,h[m]!==0&&(l[0]=1,++f),c=1;c>2)+(h[m+1]?4:0)+(h[m-u+1]?8:0),a[_]&&(l[d+c]=a[_],++f),m++;if(h[m-u]!==h[m]&&(l[d+c]=h[m]?2:4,++f),f>r)return null}for(m=u*(n-1),d=o*i,h[m]!==0&&(l[d]=8,++f),c=1;cr)return null;const g=new Int32Array([0,i,-1,0,-i,0,0,0,1]),y=new Path2D;for(o=0;f&&o<=n;o++){let _=o*i;const b=_+t;for(;_>4,l[_]&=A>>2|A<<2),y.lineTo(_%i,_/i|0),l[_]||--f}while(k!==_);--o}return h=null,l=null,function(_){_.save(),_.scale(1/t,-1/n),_.translate(0,-n),_.fill(y),_.beginPath(),_.restore()}}class uft{constructor(t,n){this.alphaIsShape=!1,this.fontSize=0,this.fontSizeScale=1,this.textMatrix=nOt,this.textMatrixScale=1,this.fontMatrix=Y7e,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=jy.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]=go.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=go.applyTransform(n,t),a=go.applyTransform(n.slice(2),t),i=go.applyTransform([n[0],n[3]],t),l=go.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){go.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=go.bezierBoundingBox(n,r,a,i,l,o,c,d,u);u||this.updateRectMinMax(t,h)}getPathBoundingBox(t=Mv.FILL,n=null){const r=[this.minX,this.minY,this.maxX,this.maxY];if(t===Mv.STROKE){n||lm("Stroke bounding box must include transform.");const a=go.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=go.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=Mv.FILL,n=null){return go.intersect(this.clipBox,this.getPathBoundingBox(t,n))}}function hft(s,t){if(typeof ImageData<"u"&&t instanceof ImageData){s.putImageData(t,0,0);return}const n=t.height,r=t.width,a=n%$1,i=(n-a)/$1,l=a===0?i:i+1,o=s.createImageData(r,$1);let c=0,d;const u=t.data,h=o.data;let m,f,g,y;if(t.kind===cje.GRAYSCALE_1BPP){const x=u.byteLength,_=new Uint32Array(h.buffer,0,h.byteLength>>2),b=_.length,k=r+7>>3,A=4294967295,T=Jv.isLittleEndian?4278190080:255;for(m=0;mk?r:P*8-7,L=M&-8;let z=0,$=0;for(;I>=1}for(;d=i&&(g=a,y=r*g),d=0,f=y;f--;)h[d++]=u[c++],h[d++]=u[c++],h[d++]=u[c++],h[d++]=255;s.putImageData(o,0,m*$1)}else throw new Error(`bad image kind: ${t.kind}`)}function mft(s,t){if(t.bitmap){s.drawImage(t.bitmap,0,0);return}const n=t.height,r=t.width,a=n%$1,i=(n-a)/$1,l=a===0?i:i+1,o=s.createImageData(r,$1);let c=0;const d=t.data,u=o.data;for(let h=0;hcft&&typeof r=="function",u=d?Date.now()+c_n:0;let h=0;const m=this.commonObjs,f=this.objs;let g;for(;;){if(a!==void 0&&o===a.nextBreakPoint)return a.breakIt(o,r),o;if(g=l[o],g!==m2.dependency)this[g].apply(this,i[o]);else for(const y of i[o]){const x=y.startsWith("g_")?m:f;if(!x.has(y))return x.get(y,r),o}if(o++,o===c)return o;if(d&&++h>cft){if(Date.now()>u)return r(),o;h=0}}}endDrawing(){Ht(this,kE,N9e).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(),Ht(this,kE,k9e).call(this)}_scaleImage(t,n){const r=t.width??t.displayWidth,a=t.height??t.displayHeight;let i=Math.max(Math.hypot(n[0],n[1]),1),l=Math.max(Math.hypot(n[2],n[3]),1),o=r,c=a,d="prescale1",u,h;for(;i>2&&o>1||l>2&&c>1;){let m=o,f=c;i>2&&o>1&&(m=o>=16384?Math.floor(o/2)-1||1:Math.ceil(o/2),i/=o/m),l>2&&c>1&&(f=c>=16384?Math.floor(c/2)-1||1:Math.ceil(c)/2,l/=c/f),u=this.cachedCanvases.getCanvas(d,m,f),h=u.context,h.clearRect(0,0,m,f),h.drawImage(t,0,0,o,c,0,0,m,f),t=u.canvas,o=m,c=f,d=d==="prescale1"?"prescale2":"prescale1"}return{img:t,paintWidth:o,paintHeight:c}}_createMaskCanvas(t){const n=this.ctx,{width:r,height:a}=t,i=this.current.fillColor,l=this.current.patternFill,o=pp(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 L=c.get(d);if(L&&!l){const z=Math.round(Math.min(o[0],o[2])+o[4]),$=Math.round(Math.min(o[1],o[3])+o[5]);return{canvas:L,offsetX:z,offsetY:$}}u=L}u||(h=this.cachedCanvases.getCanvas("maskCanvas",r,a),mft(h.context,t));let m=go.transform(o,[1/r,0,0,-1/a,0,0]);m=go.transform(m,[1,0,0,1,0,-a]);const[f,g,y,x]=go.getAxialAlignedBoundingBox([0,0,r,a],m),_=Math.round(y-f)||1,b=Math.round(x-g)||1,k=this.cachedCanvases.getCanvas("fillCanvas",_,b),A=k.context,T=f,P=g;A.translate(-T,-P),A.transform(...m),u||(u=this._scaleImage(h.canvas,qS(A)),u=u.img,c&&l&&c.set(d,u)),A.imageSmoothingEnabled=pft(pp(A),t.interpolate),bne(A,u,0,0,u.width,u.height,0,0,r,a),A.globalCompositeOperation="source-in";const I=go.transform(qS(A),[1,0,0,1,-T,-P]);return A.fillStyle=l?i.getPattern(n,this,I,Mv.FILL):i,A.fillRect(0,0,r,a),c&&!l&&(this.cachedCanvases.delete("fillCanvas"),c.set(d,k.canvas)),{canvas:k.canvas,offsetX:Math.round(T),offsetY:Math.round(P)}}setLineWidth(t){t!==this.current.lineWidth&&(this._cachedScaleForStroking[0]=-1),this.current.lineWidth=t,this.ctx.lineWidth=t}setLineCap(t){this.ctx.lineCap=m_n[t]}setLineJoin(t){this.ctx.lineJoin=p_n[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(...pp(this.suspendedCtx)),dH(this.suspendedCtx,i),d_n(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(),dH(this.ctx,this.suspendedCtx),this.ctx=this.suspendedCtx,this.suspendedCtx=null}compose(t){if(!this.current.activeSMask)return;t?(t[0]=Math.floor(t[0]),t[1]=Math.floor(t[1]),t[2]=Math.ceil(t[2]),t[3]=Math.ceil(t[3])):t=[0,0,this.ctx.canvas.width,this.ctx.canvas.height];const n=this.current.activeSMask,r=this.suspendedCtx;this.composeSMask(r,n,this.ctx,t),this.ctx.save(),this.ctx.setTransform(1,0,0,1,0,0),this.ctx.clearRect(0,0,this.ctx.canvas.width,this.ctx.canvas.height),this.ctx.restore()}composeSMask(t,n,r,a){const i=a[0],l=a[1],o=a[2]-i,c=a[3]-l;o===0||c===0||(this.genericComposeSMask(n.context,r,o,c,n.subtype,n.backdrop,n.transferMap,i,l,n.offsetX,n.offsetY),t.save(),t.globalAlpha=1,t.globalCompositeOperation="source-over",t.setTransform(1,0,0,1,0,0),t.drawImage(r.canvas,0,0),t.restore())}genericComposeSMask(t,n,r,a,i,l,o,c,d,u,h){let m=t.canvas,f=c-u,g=d-h;if(l){const x=go.makeHexColor(...l);if(f<0||g<0||f+r>m.width||g+a>m.height){const _=this.cachedCanvases.getCanvas("maskExtension",r,a),b=_.context;b.drawImage(m,-f,-g),b.globalCompositeOperation="destination-atop",b.fillStyle=x,b.fillRect(0,0,r,a),b.globalCompositeOperation="source-over",m=_.canvas,f=g=0}else{t.save(),t.globalAlpha=1,t.setTransform(1,0,0,1,0,0);const _=new Path2D;_.rect(f,g,r,a),t.clip(_),t.globalCompositeOperation="destination-atop",t.fillStyle=x,t.fillRect(f,g,r,a),t.restore()}}n.save(),n.globalAlpha=1,n.setTransform(1,0,0,1,0,0),i==="Alpha"&&o?n.filter=this.filterFactory.addAlphaFilter(o):i==="Luminosity"&&(n.filter=this.filterFactory.addLuminosityFilter(o));const y=new Path2D;y.rect(c,d,r,a),n.clip(y),n.globalCompositeOperation="destination-in",n.drawImage(m,f,g,r,a,c,d,r,a),n.restore()}save(){this.inSMaskMode?(dH(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(),dH(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=pp(a),h=u[0]===0&&u[3]===0||u[1]===0&&u[2]===0,m=h?r.slice(0):null;for(let f=0,g=0,y=t.length;flft&&(d=lft),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&jy.FILL_STROKE_MASK,h=!!(c&jy.ADD_TO_PATH_FLAG),m=l.patternFill&&!o.missingFile;let f;(o.disableFontFace||h||m)&&(f=o.getPathGenerator(this.commonObjs,t)),o.disableFontFace||m?(i.save(),i.translate(n,r),i.beginPath(),f(i,d),a&&i.setTransform(...a),(u===jy.FILL||u===jy.FILL_STROKE)&&i.fill(),(u===jy.STROKE||u===jy.FILL_STROKE)&&i.stroke(),i.restore()):((u===jy.FILL||u===jy.FILL_STROKE)&&i.fillText(t,n,r),(u===jy.STROKE||u===jy.FILL_STROKE)&&i.strokeText(t,n,r)),h&&(this.pendingTextPaths||(this.pendingTextPaths=[])).push({transform:pp(i),x:n,y:r,fontSize:d,addToPath:f})}get isFontSubpixelAAEnabled(){const{context:t}=this.cachedCanvases.getCanvas("isFontSubpixelAAEnabled",10,10);t.scale(1.5,1),t.fillText("I",0,10);const n=t.getImageData(0,0,10,10).data;let r=!1;for(let a=3;a0&&n[a]<255){r=!0;break}return od(this,"isFontSubpixelAAEnabled",r)}showText(t){const n=this.current,r=n.font;if(r.isType3Font)return this.showType3Text(t);const a=n.fontSize;if(a===0)return;const i=this.ctx,l=n.fontSizeScale,o=n.charSpacing,c=n.wordSpacing,d=n.fontDirection,u=n.textHScale*d,h=t.length,m=r.vertical,f=m?1:-1,g=r.defaultVMetrics,y=a*n.fontMatrix[0],x=n.textRenderingMode===jy.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 _;if(n.patternFill){i.save();const P=n.fillColor.getPattern(i,this,qS(i),Mv.FILL);_=pp(i),i.restore(),i.fillStyle=P}let b=n.lineWidth;const k=n.textMatrixScale;if(k===0||b===0){const P=n.textRenderingMode&jy.FILL_STROKE_MASK;(P===jy.STROKE||P===jy.FILL_STROKE)&&(b=this.getSinglePixelWidth())}else b/=k;if(l!==1&&(i.scale(l,l),b/=l),i.lineWidth=b,r.isInvalidPDFjsFont){const P=[];let I=0;for(const M of t)P.push(M.unicode),I+=M.width;i.fillText(P.join(""),0,0),n.x+=I*y*u,i.restore(),this.compose();return}let A=0,T;for(T=0;T0){const X=i.measureText(L).width*1e3/a*l;if(Wnew HKe(l,this.commonObjs,this.objs,this.canvasFactory,this.filterFactory,{optionalContentConfig:this.optionalContentConfig,markedContentStack:this.markedContentStack})};n=new j9e(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=go.makeHexColor(t,n,r)}setStrokeTransparent(){this.ctx.strokeStyle=this.current.strokeColor="transparent"}setFillRGBColor(t,n,r){this.ctx.fillStyle=this.current.fillColor=go.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=o_n(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,qS(n),Mv.SHADING);const a=qS(n);if(a){const{width:i,height:l}=n.canvas,[o,c,d,u]=go.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(){lm("Should not call beginInlineImage")}beginImageData(){lm("Should not call beginImageData")}paintFormXObjectBegin(t,n){if(this.contentVisible&&(this.save(),this.baseTransformStack.push(this.baseTransform),t&&this.transform(...t),this.baseTransform=pp(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(pp(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||bAe("TODO: Support non-isolated groups."),t.knockout&&jc("Knockout groups not supported.");const r=pp(n);if(t.matrix&&n.transform(...t.matrix),!t.bbox)throw new Error("Bounding box is required.");let a=go.getAxialAlignedBoundingBox(t.bbox,pp(n));const i=[0,0,n.canvas.width,n.canvas.height];a=go.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()),dH(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=pp(this.ctx);this.restore(),this.ctx.save(),this.ctx.setTransform(...a);const i=go.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(Ht(this,kE,N9e).call(this),_ne(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]=go.singularValueDecompose2dScale(pp(this.ctx)),{viewportScale:u}=this,h=Math.ceil(l*this.outputScaleX*u),m=Math.ceil(o*this.outputScaleY*u);this.annotationCanvas=this.canvasFactory.create(h,m);const{canvas:f,context:g}=this.annotationCanvas;this.annotationCanvasMap.set(t,f),this.annotationCanvas.savedCtx=this.ctx,this.ctx=g,this.ctx.save(),this.ctx.setTransform(c,0,0,-d,0,o*d),_ne(this.ctx)}else _ne(this.ctx),this.endPath(),this.ctx.rect(n[0],n[1],l,o),this.ctx.clip(),this.ctx.beginPath()}this.current=new uft(this.ctx.canvas.width,this.ctx.canvas.height),this.transform(...r),this.transform(...a)}endAnnotation(){this.annotationCanvas&&(this.ctx.restore(),Ht(this,kE,k9e).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=h_n(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=pp(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}};kE=new WeakSet,N9e=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)},k9e=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 oz=HKe;for(const s in m2)oz.prototype[s]!==void 0&&(oz.prototype[m2[s]]=oz.prototype[s]);var pX,fX;class $4{static get workerPort(){return de(this,pX)}static set workerPort(t){if(!(typeof Worker<"u"&&t instanceof Worker)&&t!==null)throw new Error("Invalid `workerPort` type.");Dt(this,pX,t)}static get workerSrc(){return de(this,fX)}static set workerSrc(t){if(typeof t!="string")throw new Error("Invalid `workerSrc` type.");Dt(this,fX,t)}}pX=new WeakMap,fX=new WeakMap,ts($4,pX,null),ts($4,fX,"");const wne={UNKNOWN:0,DATA:1,ERROR:2},ag={UNKNOWN:0,CANCEL:1,CANCEL_COMPLETE:2,CLOSE:3,ENQUEUE:4,ERROR:5,PULL:6,PULL_COMPLETE:7,START_COMPLETE:8};function Wb(s){switch(s instanceof Error||typeof s=="object"&&s!==null||lm('wrapReason: Expected "reason" to be a (possibly cloned) Error.'),s.name){case"AbortException":return new pO(s.message);case"MissingPDFException":return new mO(s.message);case"PasswordException":return new Z7e(s.message,s.code);case"UnexpectedResponseException":return new _Ae(s.message,s.status);case"UnknownErrorException":return new X7e(s.message,s.details);default:return new X7e(s.message,s.toString())}}var Bz,vj,$Ot,UOt,qOt,xje;class mG{constructor(t,n,r){ts(this,vj);ts(this,Bz,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",Ht(this,vj,$Ot).bind(this),{signal:de(this,Bz).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:ag.PULL,streamId:i,desiredSize:d.desiredSize}),u.promise},cancel:d=>{ex(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:ag.CANCEL,streamId:i,reason:Wb(d)}),u.promise}},r)}destroy(){var t;(t=de(this,Bz))==null||t.abort(),Dt(this,Bz,null)}}Bz=new WeakMap,vj=new WeakSet,$Ot=function({data:t}){if(t.targetName!==this.sourceName)return;if(t.stream){Ht(this,vj,qOt).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===wne.DATA)a.resolve(t.data);else if(t.callback===wne.ERROR)a.reject(Wb(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:wne.DATA,callbackId:t.callbackId,data:l})},function(l){i.postMessage({sourceName:r,targetName:a,callback:wne.ERROR,callbackId:t.callbackId,reason:Wb(l)})});return}if(t.streamId){Ht(this,vj,UOt).call(this,t);return}n(t.data)},UOt=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:ag.ENQUEUE,streamId:n,chunk:d},h)},close(){this.isCancelled||(this.isCancelled=!0,i.postMessage({sourceName:r,targetName:a,stream:ag.CLOSE,streamId:n}),delete l.streamSinks[n])},error(d){ex(d instanceof Error,"error must have a valid reason"),!this.isCancelled&&(this.isCancelled=!0,i.postMessage({sourceName:r,targetName:a,stream:ag.ERROR,streamId:n,reason:Wb(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:ag.START_COMPLETE,streamId:n,success:!0})},function(d){i.postMessage({sourceName:r,targetName:a,stream:ag.START_COMPLETE,streamId:n,reason:Wb(d)})})},qOt=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 ag.START_COMPLETE:t.success?l.startCall.resolve():l.startCall.reject(Wb(t.reason));break;case ag.PULL_COMPLETE:t.success?l.pullCall.resolve():l.pullCall.reject(Wb(t.reason));break;case ag.PULL:if(!o){i.postMessage({sourceName:r,targetName:a,stream:ag.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:ag.PULL_COMPLETE,streamId:n,success:!0})},function(c){i.postMessage({sourceName:r,targetName:a,stream:ag.PULL_COMPLETE,streamId:n,reason:Wb(c)})});break;case ag.ENQUEUE:if(ex(l,"enqueue should have stream controller"),l.isClosed)break;l.controller.enqueue(t.chunk);break;case ag.CLOSE:if(ex(l,"close should have stream controller"),l.isClosed)break;l.isClosed=!0,l.controller.close(),Ht(this,vj,xje).call(this,l,n);break;case ag.ERROR:ex(l,"error should have stream controller"),l.controller.error(Wb(t.reason)),Ht(this,vj,xje).call(this,l,n);break;case ag.CANCEL_COMPLETE:t.success?l.cancelCall.resolve():l.cancelCall.reject(Wb(t.reason)),Ht(this,vj,xje).call(this,l,n);break;case ag.CANCEL:if(!o)break;new Promise(function(c){var d;c((d=o.onCancel)==null?void 0:d.call(o,Wb(t.reason)))}).then(function(){i.postMessage({sourceName:r,targetName:a,stream:ag.CANCEL_COMPLETE,streamId:n,success:!0})},function(c){i.postMessage({sourceName:r,targetName:a,stream:ag.CANCEL_COMPLETE,streamId:n,reason:Wb(c)})}),o.sinkCapability.reject(Wb(t.reason)),o.isCancelled=!0,delete this.streamSinks[n];break;default:throw new Error("Unexpected stream case")}},xje=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 j8,gX;class g_n{constructor({parsedData:t,rawData:n}){ts(this,j8);ts(this,gX);Dt(this,j8,t),Dt(this,gX,n)}getRaw(){return de(this,gX)}get(t){return de(this,j8).get(t)??null}getAll(){return SWe(de(this,j8))}has(t){return de(this,j8).has(t)}}j8=new WeakMap,gX=new WeakMap;const h7=Symbol("INTERNAL");var xX,yX,vX,$z;class x_n{constructor(t,{name:n,intent:r,usage:a,rbGroups:i}){ts(this,xX,!1);ts(this,yX,!1);ts(this,vX,!1);ts(this,$z,!0);Dt(this,xX,!!(t&c_.DISPLAY)),Dt(this,yX,!!(t&c_.PRINT)),this.name=n,this.intent=r,this.usage=a,this.rbGroups=i}get visible(){if(de(this,vX))return de(this,$z);if(!de(this,$z))return!1;const{print:t,view:n}=this.usage;return de(this,xX)?(n==null?void 0:n.viewState)!=="OFF":de(this,yX)?(t==null?void 0:t.printState)!=="OFF":!0}_setVisible(t,n,r=!1){t!==h7&&lm("Internal method `_setVisible` called."),Dt(this,vX,r),Dt(this,$z,n)}}xX=new WeakMap,yX=new WeakMap,vX=new WeakMap,$z=new WeakMap;var zA,Fu,Uz,qz,bX,S9e;class y_n{constructor(t,n=c_.DISPLAY){ts(this,bX);ts(this,zA,null);ts(this,Fu,new Map);ts(this,Uz,null);ts(this,qz,null);if(this.renderingIntent=n,this.name=null,this.creator=null,t!==null){this.name=t.name,this.creator=t.creator,Dt(this,qz,t.order);for(const r of t.groups)de(this,Fu).set(r.id,new x_n(n,r));if(t.baseState==="OFF")for(const r of de(this,Fu).values())r._setVisible(h7,!1);for(const r of t.on)de(this,Fu).get(r)._setVisible(h7,!0);for(const r of t.off)de(this,Fu).get(r)._setVisible(h7,!1);Dt(this,Uz,this.getHash())}}isVisible(t){if(de(this,Fu).size===0)return!0;if(!t)return bAe("Optional content group not defined."),!0;if(t.type==="OCG")return de(this,Fu).has(t.id)?de(this,Fu).get(t.id).visible:(jc(`Optional content group not found: ${t.id}`),!0);if(t.type==="OCMD"){if(t.expression)return Ht(this,bX,S9e).call(this,t.expression);if(!t.policy||t.policy==="AnyOn"){for(const n of t.ids){if(!de(this,Fu).has(n))return jc(`Optional content group not found: ${n}`),!0;if(de(this,Fu).get(n).visible)return!0}return!1}else if(t.policy==="AllOn"){for(const n of t.ids){if(!de(this,Fu).has(n))return jc(`Optional content group not found: ${n}`),!0;if(!de(this,Fu).get(n).visible)return!1}return!0}else if(t.policy==="AnyOff"){for(const n of t.ids){if(!de(this,Fu).has(n))return jc(`Optional content group not found: ${n}`),!0;if(!de(this,Fu).get(n).visible)return!0}return!1}else if(t.policy==="AllOff"){for(const n of t.ids){if(!de(this,Fu).has(n))return jc(`Optional content group not found: ${n}`),!0;if(de(this,Fu).get(n).visible)return!1}return!0}return jc(`Unknown optional content policy ${t.policy}.`),!0}return jc(`Unknown group type ${t.type}.`),!0}setVisibility(t,n=!0,r=!0){var i;const a=de(this,Fu).get(t);if(!a){jc(`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=de(this,Fu).get(o))==null||i._setVisible(h7,!1,!0));a._setVisible(h7,!!n,!0),Dt(this,zA,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=de(this,Fu).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}}Dt(this,zA,null)}get hasInitialVisibility(){return de(this,Uz)===null||this.getHash()===de(this,Uz)}getOrder(){return de(this,Fu).size?de(this,qz)?de(this,qz).slice():[...de(this,Fu).keys()]:null}getGroups(){return de(this,Fu).size>0?SWe(de(this,Fu)):null}getGroup(t){return de(this,Fu).get(t)||null}getHash(){if(de(this,zA)!==null)return de(this,zA);const t=new EOt;for(const[n,r]of de(this,Fu))t.update(`${n}:${r.visible}`);return Dt(this,zA,t.hexdigest())}}zA=new WeakMap,Fu=new WeakMap,Uz=new WeakMap,qz=new WeakMap,bX=new WeakSet,S9e=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)});ex(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(){ex(!this._fullRequestReader,"PDFDataTransportStream.getFullReader can only be called once.");const t=this._queuedChunks;return this._queuedChunks=null,new b_n(this,t,this._progressiveDone,this._contentDispositionFilename)}getRangeReader(t,n){if(n<=this._progressiveDataLength)return null;const r=new __n(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 b_n{constructor(t,n,r=!1,a=null){this._stream=t,this._done=r||!1,this._filename=TWe(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 __n{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 w_n(s){let t=!0,n=r("filename\\*","i").exec(s);if(n){n=n[1];let u=o(n);return u=unescape(u),u=c(u),u=d(u),i(u)}if(n=l(s),n){const u=d(n);return i(u)}if(n=r("filename","i").exec(s),n){n=n[1];let u=o(n);return u=d(u),i(u)}function r(u,h){return new RegExp("(?:^|;)\\s*"+u+'\\s*=\\s*([^";\\s][^;\\s]*|"(?:[^"\\\\]|\\\\"?)+"?)',h)}function a(u,h){if(u){if(!/^[\x00-\xFF]+$/.test(h))return h;try{const m=new TextDecoder(u,{fatal:!0}),f=wAe(h);h=m.decode(f),t=!1}catch{}}return h}function i(u){return t&&/[\x80-\xff]/.test(u)&&(u=a("utf-8",u),t&&(u=a("iso-8859-1",u))),u}function l(u){const h=[];let m;const f=r("filename\\*((?!0\\d)\\d+)(\\*?)","ig");for(;(m=f.exec(u))!==null;){let[,y,x,_]=m;if(y=parseInt(y,10),y in h){if(y===0)break;continue}h[y]=[x,_]}const g=[];for(let y=0;y{if(!VOt(i.status))throw kAe(i.status,a);this._reader=i.body.getReader(),this._headersCapability.resolve();const l=i.headers,{allowRangeRequests:o,suggestedLength:c}=DWe({responseHeaders:l,isHttp:t.isHttp,rangeChunkSize:this._rangeChunkSize,disableRange:this._disableRange});this._isRangeSupported=o,this._contentLength=c||this._contentLength,this._filename=RWe(l),!this._isStreamingSupported&&this._isRangeSupported&&this.cancel(new pO("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:GOt(t),done:!1})}cancel(t){var n;(n=this._reader)==null||n.cancel(t),this._abortController.abort()}}class N_n{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,HOt(i,this._withCredentials,this._abortController)).then(o=>{if(!VOt(o.status))throw kAe(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:GOt(t),done:!1})}cancel(t){var n;(n=this._reader)==null||n.cancel(t),this._abortController.abort()}}const BPe=200,$Pe=206;function k_n(s){const t=s.response;return typeof t!="string"?t:wAe(t).buffer}class S_n{constructor({url:t,httpHeaders:n,withCredentials:r}){this.url=t,this.isHttp=/^https?:/i.test(t),this.headers=IWe(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=$Pe):a.expectedStatus=BPe,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||BPe;if(!(i===BPe&&r.expectedStatus===$Pe)&&i!==r.expectedStatus){(d=r.onError)==null||d.call(r,a.status);return}const o=k_n(a);if(i===$Pe){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 C_n{constructor(t){this._source=t,this._manager=new S_n(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 ex(!this._fullRequestReader,"PDFNetworkStream.getFullReader can only be called once."),this._fullRequestReader=new A_n(this._manager,this._source),this._fullRequestReader}getRangeReader(t,n){const r=new T_n(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 A_n{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}=DWe({responseHeaders:r,isHttp:this._manager.isHttp,rangeChunkSize:this._rangeChunkSize,disableRange:this._disableRange});a&&(this._isRangeSupported=!0),this._contentLength=i||this._contentLength,this._filename=RWe(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=kAe(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 T_n{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=kAe(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 E_n=/^[a-z][a-z0-9\-+.]+:/i;function M_n(s){if(E_n.test(s))return new URL(s);const t=_E.get("url");return new URL(t.pathToFileURL(s))}function WOt(s,t,n){return s.protocol==="http:"?_E.get("http").request(s,{headers:t},n):_E.get("https").request(s,{headers:t},n)}class L_n{constructor(t){this.source=t,this.url=M_n(t.url),this.isHttp=this.url.protocol==="http:"||this.url.protocol==="https:",this.isFsUrl=this.url.protocol==="file:",this.headers=IWe(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 ex(!this._fullRequestReader,"PDFNodeStream.getFullReader can only be called once."),this._fullRequestReader=this.isFsUrl?new D_n(this):new P_n(this),this._fullRequestReader}getRangeReader(t,n){if(n<=this._progressiveDataLength)return null;const r=this.isFsUrl?new R_n(this,t,n):new I_n(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 KOt{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 pO("streaming is disabled")),this._storedError&&this._readableStream.destroy(this._storedError)}}class YOt{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 P_n extends KOt{constructor(t){super(t);const n=Object.fromEntries(t.headers),r=a=>{if(a.statusCode===404){const c=new mO(`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}=DWe({responseHeaders:i,isHttp:t.isHttp,rangeChunkSize:this._rangeChunkSize,disableRange:this._disableRange});this._isRangeSupported=l,this._contentLength=o||this._contentLength,this._filename=RWe(i)};this._request=WOt(this._url,n,r),this._request.on("error",a=>{this._storedError=a,this._headersCapability.reject(a)}),this._request.end()}}class I_n extends YOt{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 mO(`Missing PDF "${this._url}".`);this._storedError=o;return}this._setReadableStream(l)};this._request=WOt(this._url,a,i),this._request.on("error",l=>{this._storedError=l}),this._request.end()}}class D_n extends KOt{constructor(t){super(t);const n=_E.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 mO(`Missing PDF "${this._url}".`)),this._storedError=r,this._headersCapability.reject(r)})}}class R_n extends YOt{constructor(t,n,r){super(t);const a=_E.get("fs");this._setReadableStream(a.createReadStream(this._url,{start:n,end:r-1}))}}const O_n=1e5,E1=30,F_n=.8;var uyt,BA,O1,_X,wX,N8,_4,jX,NX,k8,Vz,Hz,$A,Gz,kX,Wz,S8,SX,CX,C8,A8,AX,UA,Kz,I3,ZOt,XOt,C9e,B_,yje,A9e,QOt,JOt;const Bg=class Bg{constructor({textContentSource:t,container:n,viewport:r}){ts(this,I3);ts(this,BA,Promise.withResolvers());ts(this,O1,null);ts(this,_X,!1);ts(this,wX,!!((uyt=globalThis.FontInspector)!=null&&uyt.enabled));ts(this,N8,null);ts(this,_4,null);ts(this,jX,0);ts(this,NX,0);ts(this,k8,null);ts(this,Vz,null);ts(this,Hz,0);ts(this,$A,0);ts(this,Gz,Object.create(null));ts(this,kX,[]);ts(this,Wz,null);ts(this,S8,[]);ts(this,SX,new WeakMap);ts(this,CX,null);var c;if(t instanceof ReadableStream)Dt(this,Wz,t);else if(typeof t=="object")Dt(this,Wz,new ReadableStream({start(d){d.enqueue(t),d.close()}}));else throw new Error('No "textContentSource" parameter specified.');Dt(this,O1,Dt(this,Vz,n)),Dt(this,$A,r.scale*(globalThis.devicePixelRatio||1)),Dt(this,Hz,r.rotation),Dt(this,_4,{div:null,properties:null,ctx:null});const{pageWidth:a,pageHeight:i,pageX:l,pageY:o}=r.rawDims;Dt(this,CX,[1,0,0,-1,-l,o+i]),Dt(this,NX,a),Dt(this,jX,i),Ht(c=Bg,B_,QOt).call(c),CR(n,r),de(this,BA).promise.finally(()=>{de(Bg,Kz).delete(this),Dt(this,_4,null),Dt(this,Gz,null)}).catch(()=>{})}static get fontFamilyMap(){const{isWindows:t,isFirefox:n}=Jv.platform;return od(this,"fontFamilyMap",new Map([["sans-serif",`${t&&n?"Calibri, ":""}sans-serif`],["monospace",`${t&&n?"Lucida Console, ":""}monospace`]]))}render(){const t=()=>{de(this,k8).read().then(({value:n,done:r})=>{if(r){de(this,BA).resolve();return}de(this,N8)??Dt(this,N8,n.lang),Object.assign(de(this,Gz),n.styles),Ht(this,I3,ZOt).call(this,n.items),t()},de(this,BA).reject)};return Dt(this,k8,de(this,Wz).getReader()),de(Bg,Kz).add(this),t(),de(this,BA).promise}update({viewport:t,onBefore:n=null}){var i;const r=t.scale*(globalThis.devicePixelRatio||1),a=t.rotation;if(a!==de(this,Hz)&&(n==null||n(),Dt(this,Hz,a),CR(de(this,Vz),{rotation:a})),r!==de(this,$A)){n==null||n(),Dt(this,$A,r);const l={div:null,properties:null,ctx:Ht(i=Bg,B_,yje).call(i,de(this,N8))};for(const o of de(this,S8))l.properties=de(this,SX).get(o),l.div=o,Ht(this,I3,C9e).call(this,l)}}cancel(){var n;const t=new pO("TextLayer task cancelled.");(n=de(this,k8))==null||n.cancel(t).catch(()=>{}),Dt(this,k8,null),de(this,BA).reject(t)}get textDivs(){return de(this,S8)}get textContentItemsStr(){return de(this,kX)}static cleanup(){if(!(de(this,Kz).size>0)){de(this,C8).clear();for(const{canvas:t}of de(this,A8).values())t.remove();de(this,A8).clear()}}};BA=new WeakMap,O1=new WeakMap,_X=new WeakMap,wX=new WeakMap,N8=new WeakMap,_4=new WeakMap,jX=new WeakMap,NX=new WeakMap,k8=new WeakMap,Vz=new WeakMap,Hz=new WeakMap,$A=new WeakMap,Gz=new WeakMap,kX=new WeakMap,Wz=new WeakMap,S8=new WeakMap,SX=new WeakMap,CX=new WeakMap,C8=new WeakMap,A8=new WeakMap,AX=new WeakMap,UA=new WeakMap,Kz=new WeakMap,I3=new WeakSet,ZOt=function(t){var a,i;if(de(this,_X))return;(i=de(this,_4)).ctx??(i.ctx=Ht(a=Bg,B_,yje).call(a,de(this,N8)));const n=de(this,S8),r=de(this,kX);for(const l of t){if(n.length>O_n){jc("Ignoring additional textDivs for performance reasons."),Dt(this,_X,!0);return}if(l.str===void 0){if(l.type==="beginMarkedContentProps"||l.type==="beginMarkedContent"){const o=de(this,O1);Dt(this,O1,document.createElement("span")),de(this,O1).classList.add("markedContent"),l.id!==null&&de(this,O1).setAttribute("id",`${l.id}`),o.append(de(this,O1))}else l.type==="endMarkedContent"&&Dt(this,O1,de(this,O1).parentNode);continue}r.push(l.str),Ht(this,I3,XOt).call(this,l)}},XOt=function(t){var y;const n=document.createElement("span"),r={angle:0,canvasWidth:0,hasText:t.str!=="",hasEOL:t.hasEOL,fontSize:0};de(this,S8).push(n);const a=go.transform(de(this,CX),t.transform);let i=Math.atan2(a[1],a[0]);const l=de(this,Gz)[t.fontName];l.vertical&&(i+=Math.PI/2);let o=de(this,wX)&&l.fontSubstitution||l.fontFamily;o=Bg.fontFamilyMap.get(o)||o;const c=Math.hypot(a[2],a[3]),d=c*Ht(y=Bg,B_,JOt).call(y,o,de(this,N8));let u,h;i===0?(u=a[4],h=a[5]-d):(u=a[4]+d*Math.sin(i),h=a[5]-d*Math.cos(i));const m="calc(var(--scale-factor)*",f=n.style;de(this,O1)===de(this,Vz)?(f.left=`${(100*u/de(this,NX)).toFixed(2)}%`,f.top=`${(100*h/de(this,jX)).toFixed(2)}%`):(f.left=`${m}${u.toFixed(2)}px)`,f.top=`${m}${h.toFixed(2)}px)`),f.fontSize=`${m}${(de(Bg,UA)*c).toFixed(2)}px)`,f.fontFamily=o,r.fontSize=c,n.setAttribute("role","presentation"),n.textContent=t.str,n.dir=t.dir,de(this,wX)&&(n.dataset.fontName=l.fontSubstitutionLoadedName||t.fontName),i!==0&&(r.angle=i*(180/Math.PI));let g=!1;if(t.str.length>1)g=!0;else if(t.str!==" "&&t.transform[0]!==t.transform[3]){const x=Math.abs(t.transform[0]),_=Math.abs(t.transform[3]);x!==_&&Math.max(x,_)/Math.min(x,_)>1.5&&(g=!0)}if(g&&(r.canvasWidth=l.vertical?t.height:t.width),de(this,SX).set(n,r),de(this,_4).div=n,de(this,_4).properties=r,Ht(this,I3,C9e).call(this,de(this,_4)),r.hasText&&de(this,O1).append(n),r.hasEOL){const x=document.createElement("br");x.setAttribute("role","presentation"),de(this,O1).append(x)}},C9e=function(t){var o;const{div:n,properties:r,ctx:a}=t,{style:i}=n;let l="";if(de(Bg,UA)>1&&(l=`scale(${1/de(Bg,UA)})`),r.canvasWidth!==0&&r.hasText){const{fontFamily:c}=i,{canvasWidth:d,fontSize:u}=r;Ht(o=Bg,B_,A9e).call(o,a,u*de(this,$A),c);const{width:h}=a.measureText(n.textContent);h>0&&(l=`scaleX(${d*de(this,$A)/h}) ${l}`)}r.angle!==0&&(l=`rotate(${r.angle}deg) ${l}`),l.length>0&&(i.transform=l)},B_=new WeakSet,yje=function(t=null){let n=de(this,A8).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}),de(this,A8).set(t,n),de(this,AX).set(n,{size:0,family:""})}return n},A9e=function(t,n,r){const a=de(this,AX).get(t);n===a.size&&r===a.family||(t.font=`${n}px ${r}`,a.size=n,a.family=r)},QOt=function(){if(de(this,UA)!==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),Dt(this,UA,t.getBoundingClientRect().height),t.remove()},JOt=function(t,n){const r=de(this,C8).get(t);if(r)return r;const a=Ht(this,B_,yje).call(this,n);a.canvas.width=a.canvas.height=E1,Ht(this,B_,A9e).call(this,a,E1,t);const i=a.measureText("");let l=i.fontBoundingBoxAscent,o=Math.abs(i.fontBoundingBoxDescent);if(l){const u=l/(l+o);return de(this,C8).set(t,u),a.canvas.width=a.canvas.height=0,u}a.strokeStyle="red",a.clearRect(0,0,E1,E1),a.strokeText("g",0,0);let c=a.getImageData(0,0,E1,E1).data;o=0;for(let u=c.length-1-3;u>=0;u-=4)if(c[u]>0){o=Math.ceil(u/4/E1);break}a.clearRect(0,0,E1,E1),a.strokeText("A",0,E1),c=a.getImageData(0,0,E1,E1).data,l=0;for(let u=0,h=c.length;u0){l=E1-Math.floor(u/4/E1);break}a.canvas.width=a.canvas.height=0;const d=l?l/(l+o):F_n;return de(this,C8).set(t,d),d},ts(Bg,B_),ts(Bg,C8,new Map),ts(Bg,A8,new Map),ts(Bg,AX,new WeakMap),ts(Bg,UA,null),ts(Bg,Kz,new Set);let PZ=Bg;class IZ{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(IZ.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 z_n=65536,B_n=100,$_n=5e3,U_n=Fy?e_n:Xbn,q_n=Fy?t_n:DOt,V_n=Fy?Jbn:Qbn,H_n=Fy?s_n:zOt;function G_n(s={}){typeof s=="string"||s instanceof URL?s={url:s}:(s instanceof ArrayBuffer||ArrayBuffer.isView(s))&&(s={data:s});const t=new T9e,{docId:n}=t,r=s.url?W_n(s.url):null,a=s.data?K_n(s.data):null,i=s.httpHeaders||null,l=s.withCredentials===!0,o=s.password??null,c=s.range instanceof eFt?s.range:null,d=Number.isInteger(s.rangeChunkSize)&&s.rangeChunkSize>0?s.rangeChunkSize:z_n;let u=s.worker instanceof lz?s.worker:null;const h=s.verbosity,m=typeof s.docBaseUrl=="string"&&!NAe(s.docBaseUrl)?s.docBaseUrl:null,f=typeof s.cMapUrl=="string"?s.cMapUrl:null,g=s.cMapPacked!==!1,y=s.CMapReaderFactory||q_n,x=typeof s.standardFontDataUrl=="string"?s.standardFontDataUrl:null,_=s.StandardFontDataFactory||H_n,b=s.stopAtErrors!==!0,k=Number.isInteger(s.maxImageSize)&&s.maxImageSize>-1?s.maxImageSize:-1,A=s.isEvalSupported!==!1,T=typeof s.isOffscreenCanvasSupported=="boolean"?s.isOffscreenCanvasSupported:!Fy,P=typeof s.isChrome=="boolean"?s.isChrome:!Jv.platform.isFirefox&&typeof window<"u"&&!!(window!=null&&window.chrome),I=Number.isInteger(s.canvasMaxAreaInBytes)?s.canvasMaxAreaInBytes:-1,M=typeof s.disableFontFace=="boolean"?s.disableFontFace:Fy,L=s.fontExtraProperties===!0,z=s.enableXfa===!0,$=s.ownerDocument||globalThis.document,V=s.disableRange===!0,W=s.disableStream===!0,G=s.disableAutoFetch===!0,X=s.pdfBug===!0,te=s.CanvasFactory||U_n,ne=s.FilterFactory||V_n,me=s.enableHWA===!0,ue=c?c.length:s.length??NaN,ce=typeof s.useSystemFonts=="boolean"?s.useSystemFonts:!Fy&&!M,ae=typeof s.useWorkerFetch=="boolean"?s.useWorkerFetch:y===DOt&&_===zOt&&f&&x&&iG(f,document.baseURI)&&iG(x,document.baseURI);s.canvasFactory&&rft("`canvasFactory`-instance option, please use `CanvasFactory` instead."),s.filterFactory&&rft("`filterFactory`-instance option, please use `FilterFactory` instead.");const he=null;Abn(h);const xe={canvasFactory:new te({ownerDocument:$,enableHWA:me}),filterFactory:new ne({docId:n,ownerDocument:$}),cMapReaderFactory:ae?null:new y({baseUrl:f,isCompressed:g}),standardFontDataFactory:ae?null:new _({baseUrl:x})};if(!u){const be={verbosity:h,port:$4.workerPort};u=be.port?lz.fromPort(be):new lz(be),t._worker=u}const ve={docId:n,apiVersion:"4.8.69",data:a,password:o,disableAutoFetch:G,rangeChunkSize:d,length:ue,docBaseUrl:m,enableXfa:z,evaluatorOptions:{maxImageSize:k,disableFontFace:M,ignoreErrors:b,isEvalSupported:A,isOffscreenCanvasSupported:T,isChrome:P,canvasMaxAreaInBytes:I,fontExtraProperties:L,useSystemFonts:ce,cMapUrl:ae?f:null,standardFontDataUrl:ae?x:null}},ge={disableFontFace:M,fontExtraProperties:L,ownerDocument:$,pdfBug:X,styleElement:he,loadingParams:{disableAutoFetch:G,enableXfa:z}};return u.promise.then(function(){if(t.destroyed)throw new Error("Loading aborted");if(u.destroyed)throw new Error("Worker was destroyed");const be=u.messageHandler.sendWithPromise("GetDocRequest",ve,a?[a.buffer]:null);let Se;if(c)Se=new v_n(c,{disableRange:V,disableStream:W});else if(!a){if(!r)throw new Error("getDocument - no `url` parameter provided.");let Ie;Fy?Ie=typeof fetch<"u"&&typeof Response<"u"&&"body"in Response.prototype&&iG(r)?gft:L_n:Ie=iG(r)?gft:C_n,Se=new Ie({url:r,length:ue,httpHeaders:i,withCredentials:l,rangeChunkSize:d,disableRange:V,disableStream:W})}return be.then(Ie=>{if(t.destroyed)throw new Error("Loading aborted");if(u.destroyed)throw new Error("Worker was destroyed");const Me=new mG(n,Ie,u.port),Re=new Q_n(Me,t,Se,ge,xe);t._transport=Re,Me.send("Ready",null)})}).catch(t._capability.reject),t}function W_n(s){if(s instanceof URL)return s.href;try{return new URL(s,window.location).href}catch{if(Fy&&typeof s=="string")return s}throw new Error("Invalid PDF url data: either string or URL-object is expected in the url property.")}function K_n(s){if(Fy&&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 wAe(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 xft(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 mSe;const pSe=class pSe{constructor(){this._capability=Promise.withResolvers(),this._transport=null,this._worker=null,this.docId=`d${Sx(pSe,mSe)._++}`,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)}};mSe=new WeakMap,ts(pSe,mSe,0);let T9e=pSe;class eFt{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){lm("Abstract method PDFDataRangeTransport.requestDataRange")}abort(){}}class Y_n{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 od(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 qA,w4,ej,m7,vje;class Z_n{constructor(t,n,r,a=!1){ts(this,ej);ts(this,qA,null);ts(this,w4,!1);this._pageIndex=t,this._pageInfo=n,this._transport=r,this._stats=a?new nft:null,this._pdfBug=a,this.commonObjs=r.commonObjs,this.objs=new tFt,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 EJ({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 od(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=xA.ENABLE,transform:i=null,background:l=null,optionalContentConfigPromise:o=null,annotationCanvasMap:c=null,pageColors:d=null,printAnnotationStorage:u=null,isEditing:h=!1}){var A,T;(A=this._stats)==null||A.time("Overall");const m=this._transport.getRenderingIntent(r,a,u,h),{renderingIntent:f,cacheKey:g}=m;Dt(this,w4,!1),Ht(this,ej,vje).call(this),o||(o=this._transport.getOptionalContentConfig(f));let y=this._intentStates.get(g);y||(y=Object.create(null),this._intentStates.set(g,y)),y.streamReaderCancelTimeout&&(clearTimeout(y.streamReaderCancelTimeout),y.streamReaderCancelTimeout=null);const x=!!(f&c_.PRINT);y.displayReadyCapability||(y.displayReadyCapability=Promise.withResolvers(),y.operatorList={fnArray:[],argsArray:[],lastChunk:!1,separateAnnots:null},(T=this._stats)==null||T.time("Page Request"),this._pumpOperatorList(m));const _=P=>{var I;y.renderTasks.delete(b),(this._maybeCleanupAfterRender||x)&&Dt(this,w4,!0),Ht(this,ej,m7).call(this,!x),P?(b.capability.reject(P),this._abortOperatorList({intentState:y,reason:P instanceof Error?P:new Error(P)})):b.capability.resolve(),this._stats&&(this._stats.timeEnd("Rendering"),this._stats.timeEnd("Overall"),(I=globalThis.Stats)!=null&&I.enabled&&globalThis.Stats.add(this.pageNumber,this._stats))},b=new M9e({callback:_,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:!x,pdfBug:this._pdfBug,pageColors:d});(y.renderTasks||(y.renderTasks=new Set)).add(b);const k=b.task;return Promise.all([y.displayReadyCapability.promise,o]).then(([P,I])=>{var M;if(this.destroyed){_();return}if((M=this._stats)==null||M.time("Rendering"),!(I.renderingIntent&f))throw new Error("Must use the same `intent`-argument when calling the `PDFPageProxy.render` and `PDFDocumentProxy.getOptionalContentConfig` methods.");b.initializeGraphics({transparency:P,optionalContentConfig:I}),b.operatorListChanged()}).catch(_),k}getOperatorList({intent:t="display",annotationMode:n=xA.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=>IZ.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(),Dt(this,w4,!1),Ht(this,ej,vje).call(this),Promise.all(t)}cleanup(t=!1){Dt(this,w4,!0);const n=Ht(this,ej,m7).call(this,!1);return t&&n&&this._stats&&(this._stats=new nft),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();Ht(this,ej,m7).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 AWe){let a=B_n;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 pO(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}}qA=new WeakMap,w4=new WeakMap,ej=new WeakSet,m7=function(t=!1){if(Ht(this,ej,vje).call(this),!de(this,w4)||this.destroyed)return!1;if(t)return Dt(this,qA,setTimeout(()=>{Dt(this,qA,null),Ht(this,ej,m7).call(this,!1)},$_n)),!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(),Dt(this,w4,!1),!0},vje=function(){de(this,qA)&&(clearTimeout(de(this,qA)),Dt(this,qA,null))};var j4,fSe;class X_n{constructor(){ts(this,j4,new Map);ts(this,fSe,Promise.resolve())}postMessage(t,n){const r={data:structuredClone(t,n?{transfer:n}:null)};de(this,fSe).then(()=>{for(const[a]of de(this,j4))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){jc("LoopbackPort - cannot use an `aborted` signal.");return}const l=()=>this.removeEventListener(t,n);a=()=>i.removeEventListener("abort",l),i.addEventListener("abort",l)}de(this,j4).set(n,a)}removeEventListener(t,n){const r=de(this,j4).get(n);r==null||r(),de(this,j4).delete(n)}terminate(){for(const[,t]of de(this,j4))t==null||t();de(this,j4).clear()}}j4=new WeakMap,fSe=new WeakMap;var gSe,T8,E8,Yz,bje,Zz,_je;const Tm=class Tm{constructor({name:t=null,port:n=null,verbosity:r=Tbn()}={}){ts(this,Yz);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=de(Tm,E8))!=null&&a.has(n))throw new Error("Cannot use more than one PDFWorker per port.");(de(Tm,E8)||Dt(Tm,E8,new WeakMap)).set(n,this),this._initializeFromPort(n);return}this._initialize()}get promise(){return Fy?Promise.all([_E.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 mG("main","worker",t),this._messageHandler.on("ready",function(){}),Ht(this,Yz,bje).call(this)}_initialize(){if(de(Tm,T8)||de(Tm,Zz,_je)){this._setupFakeWorker();return}let{workerSrc:t}=Tm;try{Tm._isSameOrigin(window.location.href,t)||(t=Tm._createCDNWrapper(new URL(t,window.location).href));const n=new Worker(t,{type:"module"}),r=new mG("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,Ht(this,Yz,bje).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{bAe("The worker has been disabled.")}this._setupFakeWorker()}_setupFakeWorker(){de(Tm,T8)||(jc("Setting up fake worker."),Dt(Tm,T8,!0)),Tm._setupFakeWorkerGlobal.then(t=>{if(this.destroyed){this._readyCapability.reject(new Error("Worker was destroyed"));return}const n=new X_n;this._port=n;const r=`fake${Sx(Tm,gSe)._++}`,a=new mG(r+"_worker",r,n);t.setup(a,n),this._messageHandler=new mG(r,r+"_worker",n),Ht(this,Yz,bje).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=de(Tm,E8))==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=de(this,E8))==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 Tm(t)}static get workerSrc(){if($4.workerSrc)return $4.workerSrc;throw new Error('No "GlobalWorkerOptions.workerSrc" specified.')}static get _setupFakeWorkerGlobal(){return od(this,"_setupFakeWorkerGlobal",(async()=>de(this,Zz,_je)?de(this,Zz,_je):(await import(this.workerSrc)).WorkerMessageHandler)())}};gSe=new WeakMap,T8=new WeakMap,E8=new WeakMap,Yz=new WeakSet,bje=function(){this._readyCapability.resolve(),this._messageHandler.send("configure",{verbosity:this.verbosity})},Zz=new WeakSet,_je=function(){var t;try{return((t=globalThis.pdfjsWorker)==null?void 0:t.WorkerMessageHandler)||null}catch{return null}},ts(Tm,Zz),ts(Tm,gSe,0),ts(Tm,T8,!1),ts(Tm,E8),Fy&&(Dt(Tm,T8,!0),$4.workerSrc||($4.workerSrc="./pdf.worker.mjs")),Tm._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},Tm._createCDNWrapper=t=>{const n=`await import("${t}");`;return URL.createObjectURL(new Blob([n],{type:"text/javascript"}))};let lz=Tm;var N4,Ik,Xz,Qz,Dk,M8,pG;class Q_n{constructor(t,n,r,a,i){ts(this,M8);ts(this,N4,new Map);ts(this,Ik,new Map);ts(this,Xz,new Map);ts(this,Qz,new Map);ts(this,Dk,null);this.messageHandler=t,this.loadingTask=n,this.commonObjs=new tFt,this.fontLoader=new Ybn({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 od(this,"annotationStorage",new LWe)}getRenderingIntent(t,n=xA.ENABLE,r=null,a=!1,i=!1){let l=c_.DISPLAY,o=y9e;switch(t){case"any":l=c_.ANY;break;case"display":break;case"print":l=c_.PRINT;break;default:jc(`getRenderingIntent - invalid intent: ${t}`)}const c=l&c_.PRINT&&r instanceof LOt?r:this.annotationStorage;switch(n){case xA.DISABLE:l+=c_.ANNOTATIONS_DISABLE;break;case xA.ENABLE:break;case xA.ENABLE_FORMS:l+=c_.ANNOTATIONS_FORMS;break;case xA.ENABLE_STORAGE:l+=c_.ANNOTATIONS_STORAGE,o=c.serializable;break;default:jc(`getRenderingIntent - invalid annotationMode: ${n}`)}a&&(l+=c_.IS_EDITING),i&&(l+=c_.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=de(this,Dk))==null||r.reject(new Error("Worker was destroyed during onPassword callback"));const t=[];for(const a of de(this,Ik).values())t.push(a._destroy());de(this,Ik).clear(),de(this,Xz).clear(),de(this,Qz).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(),de(this,N4).clear(),this.filterFactory.destroy(),PZ.cleanup(),(a=this._networkStream)==null||a.cancelAllRequests(new pO("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)=>{ex(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}ex(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)=>{ex(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}ex(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 Y_n(r,this))}),t.on("DocException",function(r){let a;switch(r.name){case"PasswordException":a=new Z7e(r.message,r.code);break;case"InvalidPDFException":a=new rOt(r.message);break;case"MissingPDFException":a=new mO(r.message);break;case"UnexpectedResponseException":a=new _Ae(r.message,r.status);break;case"UnknownErrorException":a=new X7e(r.message,r.details);break;default:lm("DocException - expected a valid Error.")}n._capability.reject(a)}),t.on("PasswordRequest",r=>{if(Dt(this,Dk,Promise.withResolvers()),n.onPassword){const a=i=>{i instanceof Error?de(this,Dk).reject(i):de(this,Dk).resolve({password:i})};try{n.onPassword(a,r.code)}catch(i){de(this,Dk).reject(i)}}else de(this,Dk).reject(new Z7e(r.message,r.code));return de(this,Dk).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;de(this,Ik).get(r.pageIndex)._startRenderPage(r.transparency,r.cacheKey)}),t.on("commonobj",([r,a,i])=>{var l;if(this.destroyed||this.commonObjs.has(r))return null;switch(a){case"Font":const{disableFontFace:o,fontExtraProperties:c,pdfBug:d}=this._params;if("error"in i){const f=i.error;jc(`Error during font loading: ${f}`),this.commonObjs.resolve(r,f);break}const u=d&&((l=globalThis.FontInspector)!=null&&l.enabled)?(f,g)=>globalThis.FontInspector.fontAdded(f,g):null,h=new Zbn(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;ex(m,"The imageRef must be defined.");for(const f of de(this,Ik).values())for(const[,g]of f.objs)if((g==null?void 0:g.ref)===m)return g.dataLen?(this.commonObjs.resolve(r,structuredClone(g)),g.dataLen):null;break;case"FontPath":case"Image":case"Pattern":this.commonObjs.resolve(r,i);break;default:throw new Error(`Got unknown common object type ${a}`)}return null}),t.on("obj",([r,a,i,l])=>{var c;if(this.destroyed)return;const o=de(this,Ik).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)>Nbn&&(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&&jc("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=de(this,Xz).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&&de(this,Qz).set(i.refStr,t);const l=new Z_n(n,i,this,this._params.pdfBug);return de(this,Ik).set(n,l),l});return de(this,Xz).set(n,a),a}getPageIndex(t){return xft(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 Ht(this,M8,pG).call(this,"GetFieldObjects")}hasJSActions(){return Ht(this,M8,pG).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 Ht(this,M8,pG).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 Ht(this,M8,pG).call(this,"GetOptionalContentConfig").then(n=>new y_n(n,t))}getPermissions(){return this.messageHandler.sendWithPromise("GetPermissions",null)}getMetadata(){const t="GetMetadata",n=de(this,N4).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 g_n(a[1]):null,contentDispositionFilename:((i=this._fullReader)==null?void 0:i.filename)??null,contentLength:((l=this._fullReader)==null?void 0:l.contentLength)??null}});return de(this,N4).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 de(this,Ik).values())if(!n.cleanup())throw new Error(`startCleanup: Page ${n.pageNumber} is currently rendering.`);this.commonObjs.clear(),t||this.fontLoader.clear(),de(this,N4).clear(),this.filterFactory.destroy(!0),PZ.cleanup()}}cachedPageNumber(t){if(!xft(t))return null;const n=t.gen===0?`${t.num}R`:`${t.num}R${t.gen}`;return de(this,Qz).get(n)??null}}N4=new WeakMap,Ik=new WeakMap,Xz=new WeakMap,Qz=new WeakMap,Dk=new WeakMap,M8=new WeakSet,pG=function(t,n=null){const r=de(this,N4).get(t);if(r)return r;const a=this.messageHandler.sendWithPromise(t,n);return de(this,N4).set(t,a),a};const jne=Symbol("INITIAL_DATA");var _2,TX,E9e;class tFt{constructor(){ts(this,TX);ts(this,_2,Object.create(null))}get(t,n=null){if(n){const a=Ht(this,TX,E9e).call(this,t);return a.promise.then(()=>n(a.data)),null}const r=de(this,_2)[t];if(!r||r.data===jne)throw new Error(`Requesting object that isn't resolved yet ${t}.`);return r.data}has(t){const n=de(this,_2)[t];return!!n&&n.data!==jne}resolve(t,n=null){const r=Ht(this,TX,E9e).call(this,t);r.data=n,r.resolve()}clear(){var t;for(const n in de(this,_2)){const{data:r}=de(this,_2)[n];(t=r==null?void 0:r.bitmap)==null||t.close()}Dt(this,_2,Object.create(null))}*[Symbol.iterator](){for(const t in de(this,_2)){const{data:n}=de(this,_2)[t];n!==jne&&(yield[t,n])}}}_2=new WeakMap,TX=new WeakSet,E9e=function(t){var n;return(n=de(this,_2))[t]||(n[t]={...Promise.withResolvers(),data:jne})};var VA;class J_n{constructor(t){ts(this,VA,null);Dt(this,VA,t),this.onContinue=null}get promise(){return de(this,VA).capability.promise}cancel(t=0){de(this,VA).cancel(null,t)}get separateAnnots(){const{separateAnnots:t}=de(this,VA).operatorList;if(!t)return!1;const{annotationCanvasMap:n}=de(this,VA);return t.form||t.canvas&&(n==null?void 0:n.size)>0}}VA=new WeakMap;var HA,L8;const kI=class kI{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}){ts(this,HA,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 J_n(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(de(kI,L8).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.");de(kI,L8).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 oz(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(),de(this,HA)&&(window.cancelAnimationFrame(de(this,HA)),Dt(this,HA,null)),de(kI,L8).delete(this._canvas),this.callback(t||new AWe(`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?Dt(this,HA,window.requestAnimationFrame(()=>{Dt(this,HA,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(),de(kI,L8).delete(this._canvas),this.callback())))}};HA=new WeakMap,L8=new WeakMap,ts(kI,L8,new WeakSet);let M9e=kI;const ewn="4.8.69",twn="3634dab10";function yft(s){return Math.floor(Math.max(0,Math.min(1,s))*255).toString(16).padStart(2,"0")}function uH(s){return Math.max(0,Math.min(255,255*s))}class vft{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=uH(t),[t,t,t]}static G_HTML([t]){const n=yft(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(uH)}static RGB_HTML(t){return`#${t.map(yft).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[uH(1-Math.min(1,t+a)),uH(1-Math.min(1,r+a)),uH(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 swn{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){lm("Abstract method `_createSVG` called.")}}class OWe extends swn{_createSVG(t){return document.createElementNS(XS,t)}}class sFt{static setupStorage(t,n,r,a,i){const l=a.getValue(n,{value:null});switch(r.name){case"textarea":if(l.value!==null&&(t.textContent=l.value),i==="print")break;t.addEventListener("input",o=>{a.setValue(n,{value:o.target.value})});break;case"input":if(r.attributes.type==="radio"||r.attributes.type==="checkbox"){if(l.value===r.attributes.xfaOn?t.setAttribute("checked",!0):l.value===r.attributes.xfaOff&&t.removeAttribute("checked"),i==="print")break;t.addEventListener("change",o=>{a.setValue(n,{value:o.target.checked?o.target.getAttribute("xfaOn"):o.target.getAttribute("xfaOff")})})}else{if(l.value!==null&&t.setAttribute("value",l.value),i==="print")break;t.addEventListener("input",o=>{a.setValue(n,{value:o.target.value})})}break;case"select":if(l.value!==null){t.setAttribute("value",l.value);for(const o of r.children)o.attributes.value===l.value?o.attributes.selected=!0:o.attributes.hasOwnProperty("selected")&&delete o.attributes.selected}t.addEventListener("input",o=>{const c=o.target.options,d=c.selectedIndex===-1?"":c[c.selectedIndex].value;a.setValue(n,{value:d})});break}}static setAttributes({html:t,element:n,storage:r=null,intent:a,linkService:i}){const{attributes:l}=n,o=t instanceof HTMLAnchorElement;l.type==="radio"&&(l.name=`${l.name}-${a}`);for(const[c,d]of Object.entries(l))if(d!=null)switch(c){case"class":d.length&&t.setAttribute(c,d.join(" "));break;case"dataId":break;case"id":t.setAttribute("data-element-id",d);break;case"style":Object.assign(t.style,d);break;case"textContent":t.textContent=d;break;default:(!o||c!=="href"&&c!=="newWindow")&&t.setAttribute(c,d)}o&&i.addLinkAttributes(t,l.href,l.newWindow),r&&l.dataId&&this.setupStorage(t,l.dataId,n,r)}static render(t){var h,m;const n=t.annotationStorage,r=t.linkService,a=t.xfaHtml,i=t.intent||"display",l=document.createElement(a.name);a.attributes&&this.setAttributes({html:l,element:a,intent:i,linkService:r});const o=i!=="richText",c=t.div;if(c.append(l),t.viewport){const f=`matrix(${t.viewport.transform.join(",")})`;c.style.transform=f}o&&c.setAttribute("class","xfaLayer xfaFont");const d=[];if(a.children.length===0){if(a.value){const f=document.createTextNode(a.value);l.append(f),o&&IZ.shouldBuildText(a.name)&&d.push(f)}return{textDivs:d}}const u=[[a,-1,l]];for(;u.length>0;){const[f,g,y]=u.at(-1);if(g+1===f.children.length){u.pop();continue}const x=f.children[++u.at(-1)[1]];if(x===null)continue;const{name:_}=x;if(_==="#text"){const k=document.createTextNode(x.value);d.push(k),y.append(k);continue}const b=(h=x==null?void 0:x.attributes)!=null&&h.xmlns?document.createElementNS(x.attributes.xmlns,_):document.createElement(_);if(y.append(b),x.attributes&&this.setAttributes({html:b,element:x,storage:n,intent:i,linkService:r}),((m=x.children)==null?void 0:m.length)>0)u.push([x,-1,b]);else if(x.value){const k=document.createTextNode(x.value);o&&IZ.shouldBuildText(_)&&d.push(k),b.append(k)}}for(const f of c.querySelectorAll(".xfaNonInteractive input, .xfaNonInteractive textarea"))f.setAttribute("readOnly",!0);return{textDivs:d}}static update(t){const n=`matrix(${t.viewport.transform.join(",")})`;t.div.style.transform=n,t.div.hidden=!1}}const LJ=1e3,nwn=9,TR=new WeakSet;function p3(s){return{width:s[2]-s[0],height:s[3]-s[1]}}class rwn{static create(t){switch(t.data.annotationType){case Fg.LINK:return new nFt(t);case Fg.TEXT:return new awn(t);case Fg.WIDGET:switch(t.data.fieldType){case"Tx":return new iwn(t);case"Btn":return t.data.radioButton?new iFt(t):t.data.checkBox?new lwn(t):new cwn(t);case"Ch":return new dwn(t);case"Sig":return new own(t)}return new fO(t);case Fg.POPUP:return new P9e(t);case Fg.FREETEXT:return new uFt(t);case Fg.LINE:return new hwn(t);case Fg.SQUARE:return new mwn(t);case Fg.CIRCLE:return new pwn(t);case Fg.POLYLINE:return new hFt(t);case Fg.CARET:return new gwn(t);case Fg.INK:return new FWe(t);case Fg.POLYGON:return new fwn(t);case Fg.HIGHLIGHT:return new mFt(t);case Fg.UNDERLINE:return new xwn(t);case Fg.SQUIGGLY:return new ywn(t);case Fg.STRIKEOUT:return new vwn(t);case Fg.STAMP:return new pFt(t);case Fg.FILEATTACHMENT:return new bwn(t);default:return new Zf(t)}}}var P8,Jz,eB,EX,L9e;const GKe=class GKe{constructor(t,{isRenderable:n=!1,ignoreBorder:r=!1,createQuadrilaterals:a=!1}={}){ts(this,EX);ts(this,P8,null);ts(this,Jz,!1);ts(this,eB,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 GKe._hasPopupData(this.data)}updateEdited(t){var r;if(!this.container)return;de(this,P8)||Dt(this,P8,{rect:this.data.rect.slice(0)});const{rect:n}=t;n&&Ht(this,EX,L9e).call(this,n),(r=de(this,eB))==null||r.popup.updateEdited(t)}resetEdited(){var t;de(this,P8)&&(Ht(this,EX,L9e).call(this,de(this,P8).rect),(t=de(this,eB))==null||t.popup.resetEdited(),Dt(this,P8,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 fO||(i.tabIndex=LJ);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 P9e){const{rotation:y}=n;return!n.hasOwnCanvas&&y!==0&&this.setRotation(y,i),i}const{width:o,height:c}=p3(n.rect);if(!t&&n.borderStyle.width>0){l.borderWidth=`${n.borderStyle.width}px`;const y=n.borderStyle.horizontalCornerRadius,x=n.borderStyle.verticalCornerRadius;if(y>0||x>0){const b=`calc(${y}px * var(--scale-factor)) / calc(${x}px * var(--scale-factor))`;l.borderRadius=b}else if(this instanceof iFt){const b=`calc(${o}px * var(--scale-factor)) / calc(${c}px * var(--scale-factor))`;l.borderRadius=b}switch(n.borderStyle.style){case cH.SOLID:l.borderStyle="solid";break;case cH.DASHED:l.borderStyle="dashed";break;case cH.BEVELED:jc("Unimplemented border style: beveled");break;case cH.INSET:jc("Unimplemented border style: inset");break;case cH.UNDERLINE:l.borderBottomStyle="solid";break}const _=n.borderColor||null;_?(Dt(this,Jz,!0),l.borderColor=go.makeHexColor(_[0]|0,_[1]|0,_[2]|0)):l.borderWidth=0}const d=go.normalizeRect([n.rect[0],r.view[3]-n.rect[1]+r.view[1],n.rect[2],r.view[3]-n.rect[3]+r.view[1]]),{pageWidth:u,pageHeight:h,pageX:m,pageY:f}=a.rawDims;l.left=`${100*(d[0]-m)/u}%`,l.top=`${100*(d[1]-f)/h}%`;const{rotation:g}=n;return n.hasOwnCanvas||g===0?(l.width=`${100*o/u}%`,l.height=`${100*c/h}%`):this.setRotation(g,i),i}setRotation(t,n=this.container){if(!this.data.rect)return;const{pageWidth:r,pageHeight:a}=this.parent.viewport.rawDims,{width:i,height:l}=p3(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]=vft[`${l}_HTML`](o),this.annotationStorage.setValue(this.data.id,{[r]:vft[`${l}_rgb`](o)})};return od(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,x,_,b]=t.subarray(2,6);if(a===y&&i===x&&n===_&&r===b)return}const{style:l}=this.container;let o;if(de(this,Jz)){const{borderColor:y,borderWidth:x}=l;l.borderWidth=0,o=["url('data:image/svg+xml;utf8,",'',``],this.container.classList.add("hasBorder")}const c=a-n,d=i-r,{svgFactory:u}=this,h=u.createElement("svg");h.classList.add("quadrilateralsContainer"),h.setAttribute("width",0),h.setAttribute("height",0);const m=u.createElement("defs");h.append(m);const f=u.createElement("clipPath"),g=`clippath_${this.data.id}`;f.setAttribute("id",g),f.setAttribute("clipPathUnits","objectBoundingBox"),m.append(f);for(let y=2,x=t.length;y`)}de(this,Jz)&&(o.push("')"),l.backgroundImage=o.join("")),this.container.append(h),this.container.style.clipPath=`url(#${g})`}_createPopup(){const{data:t}=this,n=Dt(this,eB,new P9e({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(){lm("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&&!TR.has(d)){jc(`_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&&TR.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})})}};P8=new WeakMap,Jz=new WeakMap,eB=new WeakMap,EX=new WeakSet,L9e=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}=p3(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 Zf=GKe;var v_,hI,rFt,aFt;class nFt extends Zf{constructor(n,r=null){super(n,{isRenderable:!0,ignoreBorder:!!(r!=null&&r.ignoreBorder),createQuadrilaterals:!0});ts(this,v_);this.isTooltipOnly=n.data.isTooltipOnly}render(){const{data:n,linkService:r}=this,a=document.createElement("a");a.setAttribute("data-element-id",n.id);let i=!1;return n.url?(r.addLinkAttributes(a,n.url,n.newWindow),i=!0):n.action?(this._bindNamedAction(a,n.action),i=!0):n.attachment?(Ht(this,v_,rFt).call(this,a,n.attachment,n.attachmentDest),i=!0):n.setOCGState?(Ht(this,v_,aFt).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==="")&&Ht(this,v_,hI).call(this)}_bindNamedAction(n,r){n.href=this.linkService.getAnchorUrl(""),n.onclick=()=>(this.linkService.executeNamedAction(r),!1),Ht(this,v_,hI).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),Ht(this,v_,hI).call(this)}_bindResetFormAction(n,r){const a=n.onclick;if(a||(n.href=this.linkService.getAnchorUrl("")),Ht(this,v_,hI).call(this),!this._fieldObjects){jc('_bindResetFormAction - "resetForm" action not supported, ensure that the `fieldObjects` parameter is provided.'),a||(n.onclick=()=>!1);return}n.onclick=()=>{var h;a==null||a();const{fields:i,refs:l,include:o}=r,c=[];if(i.length!==0||l.length!==0){const m=new Set(l);for(const f of i){const g=this._fieldObjects[f]||[];for(const{id:y}of g)m.add(y)}for(const f of Object.values(this._fieldObjects))for(const g of f)m.has(g.id)===o&&c.push(g)}else for(const m of Object.values(this._fieldObjects))c.push(...m);const d=this.annotationStorage,u=[];for(const m of c){const{id:f}=m;switch(u.push(f),m.type){case"text":{const y=m.defaultValue||"";d.setValue(f,{value:y});break}case"checkbox":case"radiobutton":{const y=m.defaultValue===m.exportValues;d.setValue(f,{value:y});break}case"combobox":case"listbox":{const y=m.defaultValue||"";d.setValue(f,{value:y});break}default:continue}const g=document.querySelector(`[data-element-id="${f}"]`);if(g){if(!TR.has(g)){jc(`_bindResetFormAction - element not allowed: ${f}`);continue}}else continue;g.dispatchEvent(new Event("resetform"))}return this.enableScripting&&((h=this.linkService.eventBus)==null||h.dispatch("dispatcheventinsandbox",{source:this,detail:{id:"app",ids:u,name:"ResetForm"}})),!1}}}v_=new WeakSet,hI=function(){this.container.setAttribute("data-internal-link","")},rFt=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},Ht(this,v_,hI).call(this)},aFt=function(n,r){n.href=this.linkService.getAnchorUrl(""),n.onclick=()=>(this.linkService.executeSetOCGState(r),!1),Ht(this,v_,hI).call(this)};class awn extends Zf{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 fO extends Zf{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 Jv.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":go.makeHexColor(n[0],n[1],n[2])}_setTextStyle(t){const n=["left","center","right"],{fontColor:r}=this.data.defaultAppearanceData,a=this.data.defaultAppearanceData.fontSize||nwn,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/(RPe*a))||1,h=d/u;l=Math.min(a,c(h/RPe))}else{const d=Math.abs(this.data.rect[3]-this.data.rect[1]-o);l=Math.min(a,c(d/RPe))}i.fontSize=`calc(${l}px * var(--scale-factor))`,i.color=go.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 iwn extends fO{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),TR.add(r),r.setAttribute("data-element-id",n),r.disabled=this.data.readOnly,r.name=this.data.fieldName,r.tabIndex=LJ,this._setRequired(r,this.data.required),c&&(r.maxLength=c),r.addEventListener("input",m=>{t.setValue(n,{value:m.target.value}),this.setPropertyOnSiblings(r,"value",m.target.value,"value"),u.formattedValue=null}),r.addEventListener("resetform",m=>{const f=this.data.defaultFieldValue??"";r.value=u.userValue=f,u.formattedValue=null});let h=m=>{const{formattedValue:f}=u;f!=null&&(m.target.value=f),m.target.scrollLeft=0};if(this.enableScripting&&this.hasJSActions){r.addEventListener("focus",f=>{var y;if(u.focused)return;const{target:g}=f;u.userValue&&(g.value=u.userValue),u.lastCommittedValue=g.value,u.commitKey=1,(y=this.data.actions)!=null&&y.Focus||(u.focused=!0)}),r.addEventListener("updatefromsandbox",f=>{this.showElementAndHideCanvas(f.target);const g={value(y){u.userValue=y.detail.value??"",t.setValue(n,{value:u.userValue.toString()}),y.target.value=u.userValue},formattedValue(y){const{formattedValue:x}=y.detail;u.formattedValue=x,x!=null&&y.target!==document.activeElement&&(y.target.value=x),t.setValue(n,{formattedValue:x})},selRange(y){y.target.setSelectionRange(...y.detail.selRange)},charLimit:y=>{var k;const{charLimit:x}=y.detail,{target:_}=y;if(x===0){_.removeAttribute("maxLength");return}_.setAttribute("maxLength",x);let b=u.userValue;!b||b.length<=x||(b=b.slice(0,x),_.value=u.userValue=b,t.setValue(n,{value:b}),(k=this.linkService.eventBus)==null||k.dispatch("dispatcheventinsandbox",{source:this,detail:{id:n,name:"Keystroke",value:b,willCommit:!0,commitKey:1,selStart:_.selectionStart,selEnd:_.selectionEnd}}))}};this._dispatchEventFromSandbox(g,f)}),r.addEventListener("keydown",f=>{var x;u.commitKey=1;let g=-1;if(f.key==="Escape"?g=0:f.key==="Enter"&&!this.data.multiLine?g=2:f.key==="Tab"&&(u.commitKey=3),g===-1)return;const{value:y}=f.target;u.lastCommittedValue!==y&&(u.lastCommittedValue=y,u.userValue=y,(x=this.linkService.eventBus)==null||x.dispatch("dispatcheventinsandbox",{source:this,detail:{id:n,name:"Keystroke",value:y,willCommit:!0,commitKey:g,selStart:f.target.selectionStart,selEnd:f.target.selectionEnd}}))});const m=h;h=null,r.addEventListener("blur",f=>{var y,x;if(!u.focused||!f.relatedTarget)return;(y=this.data.actions)!=null&&y.Blur||(u.focused=!1);const{value:g}=f.target;u.userValue=g,u.lastCommittedValue!==g&&((x=this.linkService.eventBus)==null||x.dispatch("dispatcheventinsandbox",{source:this,detail:{id:n,name:"Keystroke",value:g,willCommit:!0,commitKey:u.commitKey,selStart:f.target.selectionStart,selEnd:f.target.selectionEnd}})),m(f)}),(i=this.data.actions)!=null&&i.Keystroke&&r.addEventListener("beforeinput",f=>{var T;u.lastCommittedValue=null;const{data:g,target:y}=f,{value:x,selectionStart:_,selectionEnd:b}=y;let k=_,A=b;switch(f.inputType){case"deleteWordBackward":{const P=x.substring(0,_).match(/\w*[^\w]*$/);P&&(k-=P[0].length);break}case"deleteWordForward":{const P=x.substring(_).match(/^[^\w]*\w*/);P&&(A+=P[0].length);break}case"deleteContentBackward":_===b&&(k-=1);break;case"deleteContentForward":_===b&&(A+=1);break}f.preventDefault(),(T=this.linkService.eventBus)==null||T.dispatch("dispatcheventinsandbox",{source:this,detail:{id:n,name:"Keystroke",value:x,change:g||"",willCommit:!1,selStart:k,selEnd:A}})}),this._setEventListeners(r,u,[["focus","Focus"],["blur","Blur"],["mousedown","Mouse Down"],["mouseenter","Mouse Enter"],["mouseleave","Mouse Exit"],["mouseup","Mouse Up"]],f=>f.target.value)}if(h&&r.addEventListener("blur",h),this.data.comb){const f=(this.data.rect[2]-this.data.rect[0])/c;r.classList.add("comb"),r.style.letterSpacing=`calc(${f}px * var(--scale-factor) - 1ch)`}}else r=document.createElement("div"),r.textContent=this.data.fieldValue,r.style.verticalAlign="middle",r.style.display="table-cell",this.data.hasOwnCanvas&&(r.hidden=!0);return this._setTextStyle(r),this._setBackgroundColor(r),this._setDefaultPropertiesFromJS(r),this.container.append(r),this.container}}class own extends fO{constructor(t){super(t,{isRenderable:!!t.data.hasOwnCanvas})}}class lwn extends fO{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 TR.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=LJ,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 iFt extends fO{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(TR.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=LJ,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 cwn extends nFt{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 dwn extends fO{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");TR.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=LJ;let i=this.data.combo&&this.data.options.length>0;this.data.combo||(a.size=this.data.options.length,this.data.multiSelect&&(a.multiple=!0)),a.addEventListener("resetform",u=>{const h=this.data.defaultFieldValue;for(const m of a.options)m.selected=m.value===h});for(const u of this.data.options){const h=document.createElement("option");h.textContent=u.displayValue,h.value=u.exportValue,r.value.includes(u.exportValue)&&(h.setAttribute("selected",!0),i=!1),a.append(h)}let l=null;if(i){const u=document.createElement("option");u.value=" ",u.setAttribute("hidden",!0),u.setAttribute("selected",!0),a.prepend(u),l=()=>{u.remove(),a.removeEventListener("input",l),l=null},a.addEventListener("input",l)}const o=u=>{const h=u?"value":"textContent",{options:m,multiple:f}=a;return f?Array.prototype.filter.call(m,g=>g.selected).map(g=>g[h]):m.selectedIndex===-1?null:m[m.selectedIndex][h]};let c=o(!1);const d=u=>{const h=u.target.options;return Array.prototype.map.call(h,m=>({displayValue:m.textContent,exportValue:m.value}))};return this.enableScripting&&this.hasJSActions?(a.addEventListener("updatefromsandbox",u=>{const h={value(m){l==null||l();const f=m.detail.value,g=new Set(Array.isArray(f)?f:[f]);for(const y of a.options)y.selected=g.has(y.value);t.setValue(n,{value:o(!0)}),c=o(!1)},multipleSelection(m){a.multiple=!0},remove(m){const f=a.options,g=m.detail.remove;f[g].selected=!1,a.remove(g),f.length>0&&Array.prototype.findIndex.call(f,x=>x.selected)===-1&&(f[0].selected=!0),t.setValue(n,{value:o(!0),items:d(m)}),c=o(!1)},clear(m){for(;a.length!==0;)a.remove(0);t.setValue(n,{value:null,items:[]}),c=o(!1)},insert(m){const{index:f,displayValue:g,exportValue:y}=m.detail.insert,x=a.children[f],_=document.createElement("option");_.textContent=g,_.value=y,x?x.before(_):a.append(_),t.setValue(n,{value:o(!0),items:d(m)}),c=o(!1)},items(m){const{items:f}=m.detail;for(;a.length!==0;)a.remove(0);for(const g of f){const{displayValue:y,exportValue:x}=g,_=document.createElement("option");_.textContent=y,_.value=x,a.append(_)}a.options.length>0&&(a.options[0].selected=!0),t.setValue(n,{value:o(!0),items:d(m)}),c=o(!1)},indices(m){const f=new Set(m.detail.indices);for(const g of m.target.options)g.selected=f.has(g.index);t.setValue(n,{value:o(!0)}),c=o(!1)},editable(m){m.target.disabled=!m.detail.editable}};this._dispatchEventFromSandbox(h,u)}),a.addEventListener("input",u=>{var f;const h=o(!0),m=o(!1);t.setValue(n,{value:h}),u.preventDefault(),(f=this.linkService.eventBus)==null||f.dispatch("dispatcheventinsandbox",{source:this,detail:{id:n,name:"Keystroke",value:c,change:m,changeEx:h,willCommit:!1,commitKey:1,keyDown:!1}})}),this._setEventListeners(a,null,[["focus","Focus"],["blur","Blur"],["mousedown","Mouse Down"],["mouseenter","Mouse Enter"],["mouseleave","Mouse Exit"],["mouseup","Mouse Up"],["input","Action"],["input","Validate"]],u=>u.target.value)):a.addEventListener("input",function(u){t.setValue(n,{value:o(!0)})}),this.data.combo&&this._setTextStyle(a),this._setBackgroundColor(a),this._setDefaultPropertiesFromJS(a),this.container.append(a),this.container}}class P9e extends Zf{constructor(t){const{data:n,elements:r}=t;super(t,{isRenderable:Zf._hasPopupData(n)}),this.elements=r,this.popup=null}render(){this.container.classList.add("popupAnnotation");const t=this.popup=new uwn({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=>`${CWe}${r}`).join(",")),this.container}}var tB,xSe,ySe,sB,I8,tf,k4,nB,MX,LX,rB,S4,w2,C4,PX,A4,IX,D8,R8,ah,wje,I9e,oFt,lFt,cFt,dFt,jje,Nje,D9e;class uwn{constructor({container:t,color:n,elements:r,titleObj:a,modificationDate:i,contentsObj:l,richText:o,parent:c,rect:d,parentRect:u,open:h}){ts(this,ah);ts(this,tB,Ht(this,ah,cFt).bind(this));ts(this,xSe,Ht(this,ah,D9e).bind(this));ts(this,ySe,Ht(this,ah,Nje).bind(this));ts(this,sB,Ht(this,ah,jje).bind(this));ts(this,I8,null);ts(this,tf,null);ts(this,k4,null);ts(this,nB,null);ts(this,MX,null);ts(this,LX,null);ts(this,rB,null);ts(this,S4,!1);ts(this,w2,null);ts(this,C4,null);ts(this,PX,null);ts(this,A4,null);ts(this,IX,null);ts(this,D8,null);ts(this,R8,!1);var m;Dt(this,tf,t),Dt(this,IX,a),Dt(this,k4,l),Dt(this,A4,o),Dt(this,LX,c),Dt(this,I8,n),Dt(this,PX,d),Dt(this,rB,u),Dt(this,MX,r),Dt(this,nB,EWe.toDateObject(i)),this.trigger=r.flatMap(f=>f.getElementsToTriggerPopup());for(const f of this.trigger)f.addEventListener("click",de(this,sB)),f.addEventListener("mouseenter",de(this,ySe)),f.addEventListener("mouseleave",de(this,xSe)),f.classList.add("popupTriggerArea");for(const f of r)(m=f.container)==null||m.addEventListener("keydown",de(this,tB));de(this,tf).hidden=!0,h&&Ht(this,ah,jje).call(this)}render(){if(de(this,w2))return;const t=Dt(this,w2,document.createElement("div"));if(t.className="popup",de(this,I8)){const i=t.style.outlineColor=go.makeHexColor(...de(this,I8));CSS.supports("background-color","color-mix(in srgb, red 30%, white)")?t.style.backgroundColor=`color-mix(in srgb, ${i} 30%, white)`:t.style.backgroundColor=go.makeHexColor(...de(this,I8).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}=de(this,IX),t.append(n),de(this,nB)){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:de(this,nB).valueOf()})),n.append(i)}const a=de(this,ah,wje);if(a)sFt.render({xfaHtml:a,intent:"richText",div:t}),t.lastChild.classList.add("richText","popupContent");else{const i=this._formatContents(de(this,k4));t.append(i)}de(this,tf).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)&&Ht(this,$X,R9e).call(this)}),!r.popupRef&&this.hasPopupData?this._createPopup():a.classList.add("popupTriggerArea"),n.append(a),n}getElementsToTriggerPopup(){return de(this,BX)}addHighlightArea(){this.container.classList.add("highlightArea")}}BX=new WeakMap,$X=new WeakSet,R9e=function(){var n;(n=this.downloadManager)==null||n.openOrDownloadData(this.content,this.filename)};var UX,O8,F8,qX,LR,fFt,O9e;class _wn{constructor({div:t,accessibilityManager:n,annotationCanvasMap:r,annotationEditorUIManager:a,page:i,viewport:l,structTreeLayer:o}){ts(this,LR);ts(this,UX,null);ts(this,O8,null);ts(this,F8,new Map);ts(this,qX,null);this.div=t,Dt(this,UX,n),Dt(this,O8,r),Dt(this,qX,o||null),this.page=i,this.viewport=l,this.zIndex=0,this._annotationEditorUIManager=a}hasEditableAnnotations(){return de(this,F8).size>0}async render(t){var l;const{annotations:n}=t,r=this.div;CR(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 OWe,annotationStorage:t.annotationStorage||new LWe,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===Fg.POPUP;if(c){const h=a.get(o.id);if(!h)continue;i.elements=h}else{const{width:h,height:m}=p3(o.rect);if(h<=0||m<=0)continue}i.data=o;const d=rwn.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 Ht(this,LR,fFt).call(this,u,o.id),d._isEditable&&(de(this,F8).set(d.data.id,d),(l=this._annotationEditorUIManager)==null||l.renderAnnotationElement(d))}Ht(this,LR,O9e).call(this)}update({viewport:t}){const n=this.div;this.viewport=t,CR(n,{rotation:t.rotation}),Ht(this,LR,O9e).call(this),n.hidden=!1}getEditableAnnotations(){return Array.from(de(this,F8).values())}getEditableAnnotation(t){return de(this,F8).get(t)}}UX=new WeakMap,O8=new WeakMap,F8=new WeakMap,qX=new WeakMap,LR=new WeakSet,fFt=async function(t,n){var l,o;const r=t.firstChild||t,a=r.id=`${CWe}${n}`,i=await((l=de(this,qX))==null?void 0:l.getAriaAttributes(a));if(i)for(const[c,d]of i)r.setAttribute(c,d);this.div.append(t),(o=de(this,UX))==null||o.moveElementInDOM(this.div,t,r,!1)},O9e=function(){if(!de(this,O8))return;const t=this.div;for(const[n,r]of de(this,O8)){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)}de(this,O8).clear()};const Nne=/\r\n?|\n/g;var j2,n_,VX,z8,r_,jg,gFt,xFt,yFt,kje,y3,Sje,Cje,vFt,z9e,bFt;const Th=class Th extends Uu{constructor(n){super({...n,name:"freeTextEditor"});ts(this,jg);ts(this,j2);ts(this,n_,"");ts(this,VX,`${this.id}-editor`);ts(this,z8,null);ts(this,r_);Dt(this,j2,n.color||Th._defaultColor||Uu._defaultLineColor),Dt(this,r_,n.fontSize||Th._defaultFontSize)}static get _keyboardManager(){const n=Th.prototype,r=l=>l.isEmpty(),a=AR.TRANSLATE_SMALL,i=AR.TRANSLATE_BIG;return od(this,"_keyboardManager",new MJ([[["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){Uu.initialize(n,r);const a=getComputedStyle(document.documentElement);this._internalPadding=parseFloat(a.getPropertyValue("--freetext-padding"))}static updateDefaultParams(n,r){switch(n){case bl.FREETEXT_SIZE:Th._defaultFontSize=r;break;case bl.FREETEXT_COLOR:Th._defaultColor=r;break}}updateParams(n,r){switch(n){case bl.FREETEXT_SIZE:Ht(this,jg,gFt).call(this,r);break;case bl.FREETEXT_COLOR:Ht(this,jg,xFt).call(this,r);break}}static get defaultPropertiesToUpdate(){return[[bl.FREETEXT_SIZE,Th._defaultFontSize],[bl.FREETEXT_COLOR,Th._defaultColor||Uu._defaultLineColor]]}get propertiesToUpdate(){return[[bl.FREETEXT_SIZE,de(this,r_)],[bl.FREETEXT_COLOR,de(this,j2)]]}_translateEmpty(n,r){this._uiManager.translateSelectedEditors(n,r,!0)}getInitialTranslation(){const n=this.parentScale;return[-Th._internalPadding*n,-(Th._internalPadding+de(this,r_))*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(tc.FREETEXT),super.enableEditMode(),this.overlayDiv.classList.remove("enabled"),this.editorDiv.contentEditable=!0,this._isDraggable=!1,this.div.removeAttribute("aria-activedescendant"),Dt(this,z8,new AbortController);const n=this._uiManager.combinedSignal(de(this,z8));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",de(this,VX)),this._isDraggable=!0,(n=de(this,z8))==null||n.abort(),Dt(this,z8,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=de(this,n_),r=Dt(this,n_,Ht(this,jg,yFt).call(this).trimEnd());if(n===r)return;const a=i=>{if(Dt(this,n_,i),!i){this.remove();return}Ht(this,jg,Cje).call(this),this._uiManager.rebuild(this),Ht(this,jg,kje).call(this)};this.addCommands({cmd:()=>{a(r)},undo:()=>{a(n)},mustExec:!1}),Ht(this,jg,kje).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){Th._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",de(this,VX)),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(${de(this,r_)}px * var(--scale-factor))`,a.color=de(this,j2),this.div.append(this.editorDiv),this.overlayDiv=document.createElement("div"),this.overlayDiv.classList.add("overlay","enabled"),this.div.append(this.overlayDiv),D5e(this,this.div,["dblclick","keydown"]),this.width){const[i,l]=this.parentDimensions;if(this.annotationElementId){const{position:o}=this._initialData;let[c,d]=this.getInitialTranslation();[c,d]=this.pageTranslationToScreen(c,d);const[u,h]=this.pageDimensions,[m,f]=this.pageTranslation;let g,y;switch(this.rotation){case 0:g=n+(o[0]-m)/u,y=r+this.height-(o[1]-f)/h;break;case 90:g=n+(o[0]-m)/u,y=r-(o[1]-f)/h,[c,d]=[d,-c];break;case 180:g=n-this.width+(o[0]-m)/u,y=r-(o[1]-f)/h,[c,d]=[-c,-d];break;case 270:g=n+(o[0]-m-this.height*h)/u,y=r+(o[1]-f-this.width*u)/h,[c,d]=[-d,c];break}this.setAt(g*i,y*l,c,d)}else this.setAt(n*i,r*l,this.width*i,this.height*l);Ht(this,jg,Cje).call(this),this._isDraggable=!0,this.editorDiv.contentEditable=!1}else this._isDraggable=!1,this.editorDiv.contentEditable=!0;return this.div}editorDivPaste(n){var g,y,x;const r=n.clipboardData||window.clipboardData,{types:a}=r;if(a.length===1&&a[0]==="text/plain")return;n.preventDefault();const i=Ht(g=Th,y3,z9e).call(g,r.getData("text")||"").replaceAll(Nne,` `);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 _=c.parentElement;if(h.push(c.nodeValue.slice(d).replaceAll(Nne,"")),_!==this.editorDiv){let b=u;for(const k of this.editorDiv.childNodes){if(k===_){b=h;continue}b.push(Ht(y=Th,y3,Sje).call(y,k))}}u.push(c.nodeValue.slice(0,d).replaceAll(Nne,""))}else if(c===this.editorDiv){let _=u,b=0;for(const k of this.editorDiv.childNodes)b++===d&&(_=h),_.push(Ht(x=Th,y3,Sje).call(x,k))}Dt(this,n_,`${u.join(` `)}${i}${h.join(` `)}`),Ht(this,jg,Cje).call(this);const m=new Range;let f=u.reduce((_,b)=>_+b.length,0);for(const{firstChild:_}of this.editorDiv.childNodes)if(_.nodeType===Node.TEXT_NODE){const b=_.nodeValue.length;if(f<=b){m.setStart(_,f),m.setEnd(_,f);break}f-=b}l.removeAllRanges(),l.addRange(m)}get contentDiv(){return this.editorDiv}static async deserialize(n,r,a){var o;let i=null;if(n instanceof uFt){const{data:{defaultAppearanceData:{fontSize:c,fontColor:d},rect:u,rotation:h,id:m,popupRef:f},textContent:g,textPosition:y,parent:{page:{pageNumber:x}}}=n;if(!g||g.length===0)return null;i=n={annotationType:tc.FREETEXT,color:Array.from(d),fontSize:c,value:g.join(` `),position:y,pageIndex:x-1,rect:u.slice(0),rotation:h,id:m,deleted:!1,popupRef:f}}const l=await super.deserialize(n,r,a);return Dt(l,r_,n.fontSize),Dt(l,j2,go.makeHexColor(...n.color)),Dt(l,n_,Ht(o=Th,y3,z9e).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=Th._internalPadding*this.parentScale,a=this.getRect(r,r),i=Uu._colorManager.convert(this.isAttachedToDOM?getComputedStyle(this.editorDiv).color:de(this,j2)),l={annotationType:tc.FREETEXT,color:i,fontSize:de(this,r_),value:Ht(this,jg,vFt).call(this),pageIndex:this.pageIndex,rect:a,rotation:this.rotation,structTreeParentId:this._structTreeParentId};return n?l:this.annotationElementId&&!Ht(this,jg,bFt).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(${de(this,r_)}px * var(--scale-factor))`,a.color=de(this,j2),r.replaceChildren();for(const l of de(this,n_).split(` `)){const o=document.createElement("div");o.append(l?document.createTextNode(l):document.createElement("br")),r.append(o)}const i=Th._internalPadding*this.parentScale;return n.updateEdited({rect:this.getRect(i,i),popupContent:de(this,n_)}),r}resetAnnotationElement(n){super.resetAnnotationElement(n),n.resetEdited()}};j2=new WeakMap,n_=new WeakMap,VX=new WeakMap,z8=new WeakMap,r_=new WeakMap,jg=new WeakSet,gFt=function(n){const r=i=>{this.editorDiv.style.fontSize=`calc(${i}px * var(--scale-factor))`,this.translate(0,-(i-de(this,r_))*this.parentScale),Dt(this,r_,i),Ht(this,jg,kje).call(this)},a=de(this,r_);this.addCommands({cmd:r.bind(this,n),undo:r.bind(this,a),post:this._uiManager.updateUI.bind(this._uiManager,this),mustExec:!0,type:bl.FREETEXT_SIZE,overwriteIfSameType:!0,keepUndo:!0})},xFt=function(n){const r=i=>{Dt(this,j2,this.editorDiv.style.color=i)},a=de(this,j2);this.addCommands({cmd:r.bind(this,n),undo:r.bind(this,a),post:this._uiManager.updateUI.bind(this._uiManager,this),mustExec:!0,type:bl.FREETEXT_COLOR,overwriteIfSameType:!0,keepUndo:!0})},yFt=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(Ht(a=Th,y3,Sje).call(a,i)),r=i);return n.join(` `)},kje=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()},y3=new WeakSet,Sje=function(n){return(n.nodeType===Node.TEXT_NODE?n.nodeValue:n.innerText).replaceAll(Nne,"")},Cje=function(){if(this.editorDiv.replaceChildren(),!!de(this,n_))for(const n of de(this,n_).split(` `)){const r=document.createElement("div");r.append(n?document.createTextNode(n):document.createElement("br")),this.editorDiv.append(r)}},vFt=function(){return de(this,n_).replaceAll(" "," ")},z9e=function(n){return n.replaceAll(" "," ")},bFt=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},ts(Th,y3),jr(Th,"_freeTextDefaultContent",""),jr(Th,"_internalPadding",0),jr(Th,"_defaultColor",null),jr(Th,"_defaultFontSize",10),jr(Th,"_type","freetext"),jr(Th,"_editorType",tc.FREETEXT);let F9e=Th;class _Ft{toSVGPath(){lm("Abstract method `toSVGPath` must be implemented.")}get box(){lm("Abstract getter `box` must be implemented.")}serialize(t,n){lm("Abstract method `serialize` must be implemented.")}get classNamesForDrawing(){lm("Abstract getter `classNamesForDrawing` must be implemented.")}get classNamesForOutlining(){lm("Abstract getter `classNamesForOutlining` must be implemented.")}get mustRemoveSelfIntersections(){return!1}}var a_,N2,aB,iB,Rk,Cc,B8,$8,HX,GX,oB,lB,GA,WX,vSe,bSe,rx,fG,wFt,jFt,NFt,kFt,SFt,CFt;const i4=class i4{constructor({x:t,y:n},r,a,i,l,o=0){ts(this,rx);ts(this,a_);ts(this,N2,[]);ts(this,aB);ts(this,iB);ts(this,Rk,[]);ts(this,Cc,new Float64Array(18));ts(this,B8);ts(this,$8);ts(this,HX);ts(this,GX);ts(this,oB);ts(this,lB);ts(this,GA,[]);Dt(this,a_,r),Dt(this,lB,i*a),Dt(this,iB,l),de(this,Cc).set([NaN,NaN,NaN,NaN,t,n],6),Dt(this,aB,o),Dt(this,GX,de(i4,WX)*a),Dt(this,HX,de(i4,bSe)*a),Dt(this,oB,a),de(this,GA).push(t,n)}isEmpty(){return isNaN(de(this,Cc)[8])}add({x:t,y:n}){var L;Dt(this,B8,t),Dt(this,$8,n);const[r,a,i,l]=de(this,a_);let[o,c,d,u]=de(this,Cc).subarray(8,12);const h=t-d,m=n-u,f=Math.hypot(h,m);if(f=6;a-=6)isNaN(n[a])?r.push(`L${n[a+4]} ${n[a+5]}`):r.push(`C${n[a]} ${n[a+1]} ${n[a+2]} ${n[a+3]} ${n[a+4]} ${n[a+5]}`);return Ht(this,rx,jFt).call(this,r),r.join(" ")}newFreeDrawOutline(t,n,r,a,i,l){return new AFt(t,n,r,a,i,l)}getOutlines(){var h;const t=de(this,Rk),n=de(this,N2),r=de(this,Cc),[a,i,l,o]=de(this,a_),c=new Float64Array((((h=de(this,GA))==null?void 0:h.length)??0)+2);for(let m=0,f=c.length-2;m=6;m-=6)for(let f=0;f<6;f+=2){if(isNaN(n[m+f])){d[u]=d[u+1]=NaN,u+=2;continue}d[u]=n[m+f],d[u+1]=n[m+f+1],u+=2}return Ht(this,rx,SFt).call(this,d,u),this.newFreeDrawOutline(d,c,de(this,a_),de(this,oB),de(this,aB),de(this,iB))}};a_=new WeakMap,N2=new WeakMap,aB=new WeakMap,iB=new WeakMap,Rk=new WeakMap,Cc=new WeakMap,B8=new WeakMap,$8=new WeakMap,HX=new WeakMap,GX=new WeakMap,oB=new WeakMap,lB=new WeakMap,GA=new WeakMap,WX=new WeakMap,vSe=new WeakMap,bSe=new WeakMap,rx=new WeakSet,fG=function(){const t=de(this,Cc).subarray(4,6),n=de(this,Cc).subarray(16,18),[r,a,i,l]=de(this,a_);return[(de(this,B8)+(t[0]-n[0])/2-r)/i,(de(this,$8)+(t[1]-n[1])/2-a)/l,(de(this,B8)+(n[0]-t[0])/2-r)/i,(de(this,$8)+(n[1]-t[1])/2-a)/l]},wFt=function(){const[t,n,r,a]=de(this,a_),[i,l,o,c]=Ht(this,rx,fG).call(this);return`M${(de(this,Cc)[2]-t)/r} ${(de(this,Cc)[3]-n)/a} L${(de(this,Cc)[4]-t)/r} ${(de(this,Cc)[5]-n)/a} L${i} ${l} L${o} ${c} L${(de(this,Cc)[16]-t)/r} ${(de(this,Cc)[17]-n)/a} L${(de(this,Cc)[14]-t)/r} ${(de(this,Cc)[15]-n)/a} Z`},jFt=function(t){const n=de(this,N2);t.push(`L${n[4]} ${n[5]} Z`)},NFt=function(t){const[n,r,a,i]=de(this,a_),l=de(this,Cc).subarray(4,6),o=de(this,Cc).subarray(16,18),[c,d,u,h]=Ht(this,rx,fG).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}`)},kFt=function(t){const n=de(this,Cc),[r,a,i,l]=de(this,a_),[o,c,d,u]=Ht(this,rx,fG).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,de(this,a_),de(this,oB),de(this,aB),de(this,iB))},SFt=function(t,n){const r=de(this,N2);return t.set([NaN,NaN,NaN,NaN,r[4],r[5]],n),n+=6},CFt=function(t,n){const r=de(this,Cc).subarray(4,6),a=de(this,Cc).subarray(16,18),[i,l,o,c]=de(this,a_),[d,u,h,m]=Ht(this,rx,fG).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},ts(i4,WX,8),ts(i4,vSe,2),ts(i4,bSe,de(i4,WX)+de(i4,vSe));let O5e=i4;var cB,U8,T4,KX,i_,YX,Pf,Q1,gG,xG,TFt;class AFt extends _Ft{constructor(n,r,a,i,l,o){super();ts(this,Q1);ts(this,cB);ts(this,U8,null);ts(this,T4);ts(this,KX);ts(this,i_);ts(this,YX);ts(this,Pf);Dt(this,Pf,n),Dt(this,i_,r),Dt(this,cB,a),Dt(this,YX,i),Dt(this,T4,l),Dt(this,KX,o),Ht(this,Q1,TFt).call(this,o);const{x:c,y:d,width:u,height:h}=de(this,U8);for(let m=0,f=n.length;mn[0]-r[0]||n[1]-r[1]||n[2]-r[2]);const t=[];for(const n of de(this,WA))n[3]?(t.push(...Ht(this,t1,B9e).call(this,n)),Ht(this,t1,MFt).call(this,n)):(Ht(this,t1,LFt).call(this,n),t.push(...Ht(this,t1,B9e).call(this,n)));return Ht(this,t1,EFt).call(this,t)}}ZX=new WeakMap,WA=new WeakMap,k2=new WeakMap,t1=new WeakSet,EFt=function(t){const n=[],r=new Set;for(const l of t){const[o,c,d]=l;n.push([o,c,l],[o,d,l])}n.sort((l,o)=>l[1]-o[1]||l[0]-o[0]);for(let l=0,o=n.length;l0;){const l=r.values().next().value;let[o,c,d,u,h]=l;r.delete(l);let m=o,f=c;for(i=[o,d],a.push(i);;){let g;if(r.has(u))g=u;else if(r.has(h))g=h;else break;r.delete(g),[o,c,d,u,h]=g,m!==o&&(i.push(m,f,o,f===c?c:d),m=o),f=f===c?d:c}i.push(m,f)}return new wwn(a,de(this,ZX))},Aje=function(t){const n=de(this,k2);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]=de(this,k2)[a];if(i!==t)break;if(i===t&&l===n){de(this,k2).splice(a,1);return}}},B9e=function(t){const[n,r,a]=t,i=[[n,r,a]],l=Ht(this,t1,Aje).call(this,a);for(let o=0;o=c){if(f>d)i[u][1]=d;else{if(h===1)return[];i.splice(u,1),u--,h--}continue}i[u][2]=c,f>d&&i.push([n,d,f])}}}return i};var XX,dB;class wwn extends _Ft{constructor(n,r){super();ts(this,XX);ts(this,dB);Dt(this,dB,n),Dt(this,XX,r)}toSVGPath(){const n=[];for(const r of de(this,dB)){let[a,i]=r;n.push(`M${a} ${i}`);for(let l=2;l-1?(Dt(this,F1,!0),Ht(this,Gl,Tje).call(this,n),Ht(this,Gl,pI).call(this)):de(this,E4)&&(Dt(this,pB,n.anchorNode),Dt(this,sQ,n.anchorOffset),Dt(this,nQ,n.focusNode),Dt(this,rQ,n.focusOffset),Ht(this,Gl,H9e).call(this),Ht(this,Gl,pI).call(this),this.rotate(this.rotation))}static get _keyboardManager(){const n=tu.prototype;return od(this,"_keyboardManager",new MJ([[["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:de(this,F1)?"free_highlight":"highlight",color:this._uiManager.highlightColorNames.get(this.color),thickness:de(this,Bw),methodOfCreation:de(this,aQ)}}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;Uu.initialize(n,r),tu._defaultColor||(tu._defaultColor=((a=r.highlightColors)==null?void 0:a.values().next().value)||"#fff066")}static updateDefaultParams(n,r){switch(n){case bl.HIGHLIGHT_DEFAULT_COLOR:tu._defaultColor=r;break;case bl.HIGHLIGHT_THICKNESS:tu._defaultThickness=r;break}}translateInPage(n,r){}get toolbarPosition(){return de(this,gB)}updateParams(n,r){switch(n){case bl.HIGHLIGHT_COLOR:Ht(this,Gl,IFt).call(this,r);break;case bl.HIGHLIGHT_THICKNESS:Ht(this,Gl,DFt).call(this,r);break}}static get defaultPropertiesToUpdate(){return[[bl.HIGHLIGHT_DEFAULT_COLOR,tu._defaultColor],[bl.HIGHLIGHT_THICKNESS,tu._defaultThickness]]}get propertiesToUpdate(){return[[bl.HIGHLIGHT_COLOR,this.color||tu._defaultColor],[bl.HIGHLIGHT_THICKNESS,de(this,Bw)||tu._defaultThickness],[bl.HIGHLIGHT_FREE,de(this,F1)]]}async addEditToolbar(){const n=await super.addEditToolbar();return n?(this._uiManager.highlightColors&&(Dt(this,fB,new F5e({editor:this})),n.addColorPicker(de(this,fB))),n):null}disableEditing(){super.disableEditing(),this.div.classList.toggle("disabled",!0)}enableEditing(){super.enableEditing(),this.div.classList.toggle("disabled",!1)}fixAndSetPosition(){return super.fixAndSetPosition(Ht(this,Gl,yG).call(this))}getBaseTranslation(){return[0,0]}getRect(n,r){return super.getRect(n,r,Ht(this,Gl,yG).call(this))}onceAdded(){this.annotationElementId||this.parent.addUndoableEditor(this),this.div.focus()}remove(){Ht(this,Gl,G9e).call(this),this._reportTelemetry({action:"deleted"}),super.remove()}rebuild(){this.parent&&(super.rebuild(),this.div!==null&&(Ht(this,Gl,pI).call(this),this.isAttachedToDOM||this.parent.add(this)))}setParent(n){var a;let r=!1;this.parent&&!n?Ht(this,Gl,G9e).call(this):n&&(Ht(this,Gl,pI).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;de(this,F1)?(n=(n-this.rotation+360)%360,a=Ht(i=tu,tj,p7).call(i,de(this,A2).box,n)):a=Ht(l=tu,tj,p7).call(l,this,n),r.rotate(de(this,Ay),n),r.rotate(de(this,qg),n),r.updateBox(de(this,Ay),a),r.updateBox(de(this,qg),Ht(o=tu,tj,p7).call(o,de(this,zw).box,n))}render(){if(this.div)return this.div;const n=super.render();de(this,xB)&&(n.setAttribute("aria-label",de(this,xB)),n.setAttribute("role","mark")),de(this,F1)?n.classList.add("free"):this.div.addEventListener("keydown",Ht(this,Gl,OFt).bind(this),{signal:this._uiManager._signal});const r=Dt(this,H8,document.createElement("div"));n.append(r),r.setAttribute("aria-hidden","true"),r.className="internal",r.style.clipPath=de(this,V8);const[a,i]=this.parentDimensions;return this.setDims(this.width*a,this.height*i),D5e(this,de(this,H8),["pointerover","pointerleave"]),this.enableEditing(),n}pointerover(){this.isSelected||this.parent.drawLayer.addClass(de(this,qg),"hovered")}pointerleave(){this.isSelected||this.parent.drawLayer.removeClass(de(this,qg),"hovered")}_moveCaret(n){switch(this.parent.unselect(this),n){case 0:case 2:Ht(this,Gl,Eje).call(this,!0);break;case 1:case 3:Ht(this,Gl,Eje).call(this,!1);break}}select(){var n,r;super.select(),de(this,qg)&&((n=this.parent)==null||n.drawLayer.removeClass(de(this,qg),"hovered"),(r=this.parent)==null||r.drawLayer.addClass(de(this,qg),"selected"))}unselect(){var n;super.unselect(),de(this,qg)&&((n=this.parent)==null||n.drawLayer.removeClass(de(this,qg),"selected"),de(this,F1)||Ht(this,Gl,Eje).call(this,!1))}get _mustFixPosition(){return!de(this,F1)}show(n=this._isVisible){super.show(n),this.parent&&(this.parent.drawLayer.show(de(this,Ay),n),this.parent.drawLayer.show(de(this,qg),n))}static startHighlighting(n,r,{target:a,x:i,y:l}){const{x:o,y:c,width:d,height:u}=a.getBoundingClientRect(),h=new AbortController,m=n.combinedSignal(h),f=y=>{y.preventDefault(),y.stopPropagation()},g=y=>{h.abort(),Ht(this,tj,$Ft).call(this,n,y)};window.addEventListener("blur",g,{signal:m}),window.addEventListener("pointerup",g,{signal:m}),window.addEventListener("pointerdown",f,{capture:!0,passive:!1,signal:m}),window.addEventListener("contextmenu",kj,{signal:m}),a.addEventListener("pointermove",Ht(this,tj,BFt).bind(this,n),{signal:m}),this._freeHighlight=new $9e({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,x,_,b;let i=null;if(n instanceof mFt){const{data:{quadPoints:k,rect:A,rotation:T,id:P,color:I,opacity:M,popupRef:L},parent:{page:{pageNumber:z}}}=n;i=n={annotationType:tc.HIGHLIGHT,color:Array.from(I),opacity:M,quadPoints:k,boxes:null,pageIndex:z-1,rect:A.slice(0),rotation:T,id:P,deleted:!1,popupRef:L}}else if(n instanceof FWe){const{data:{inkLists:k,rect:A,rotation:T,id:P,color:I,borderStyle:{rawWidth:M},popupRef:L},parent:{page:{pageNumber:z}}}=n;i=n={annotationType:tc.HIGHLIGHT,color:Array.from(I),thickness:M,inkLists:k,boxes:null,pageIndex:z-1,rect:A.slice(0),rotation:T,id:P,deleted:!1,popupRef:L}}const{color:l,quadPoints:o,inkLists:c,opacity:d}=n,u=await super.deserialize(n,r,a);u.color=go.makeHexColor(...l),Dt(u,M4,d||1),c&&Dt(u,Bw,n.thickness),u.annotationElementId=n.id||null,u._initialData=i;const[h,m]=u.pageDimensions,[f,g]=u.pageTranslation;if(o){const k=Dt(u,E4,[]);for(let A=0;A=0)Dt(this,Ay,r),Dt(this,V8,a),this.parent.drawLayer.finalizeLine(r,n),Dt(this,qg,this.parent.drawLayer.drawOutline(de(this,zw)));else if(this.parent){const f=this.parent.viewport.rotation;this.parent.drawLayer.updateLine(de(this,Ay),n),this.parent.drawLayer.updateBox(de(this,Ay),Ht(h=tu,tj,p7).call(h,de(this,A2).box,(f-this.rotation+360)%360)),this.parent.drawLayer.updateLine(de(this,qg),de(this,zw)),this.parent.drawLayer.updateBox(de(this,qg),Ht(m=tu,tj,p7).call(m,de(this,zw).box,f))}const{x:l,y:o,width:c,height:d}=n.box;switch(this.rotation){case 0:this.x=l,this.y=o,this.width=c,this.height=d;break;case 90:{const[f,g]=this.parentDimensions;this.x=o,this.y=1-l,this.width=c*g/f,this.height=d*f/g;break}case 180:this.x=1-l,this.y=1-o,this.width=c,this.height=d;break;case 270:{const[f,g]=this.parentDimensions;this.x=1-o,this.y=l,this.width=c*g/f,this.height=d*f/g;break}}const{lastPoint:u}=de(this,zw).box;Dt(this,gB,[(u[0]-l)/c,(u[1]-o)/d])},IFt=function(n){const r=(l,o)=>{var c,d,u;this.color=l,(c=this.parent)==null||c.drawLayer.changeColor(de(this,Ay),l),(d=de(this,fB))==null||d.updateColor(l),Dt(this,M4,o),(u=this.parent)==null||u.drawLayer.changeOpacity(de(this,Ay),o)},a=this.color,i=de(this,M4);this.addCommands({cmd:r.bind(this,n,tu._defaultOpacity),undo:r.bind(this,a,i),post:this._uiManager.updateUI.bind(this._uiManager,this),mustExec:!0,type:bl.HIGHLIGHT_COLOR,overwriteIfSameType:!0,keepUndo:!0}),this._reportTelemetry({action:"color_changed",color:this._uiManager.highlightColorNames.get(n)},!0)},DFt=function(n){const r=de(this,Bw),a=i=>{Dt(this,Bw,i),Ht(this,Gl,RFt).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:bl.INK_THICKNESS,overwriteIfSameType:!0,keepUndo:!0}),this._reportTelemetry({action:"thickness_changed",thickness:n},!0)},RFt=function(n){if(!de(this,F1))return;Ht(this,Gl,Tje).call(this,{highlightOutlines:de(this,A2).getNewOutline(n/2)}),this.fixAndSetPosition();const[r,a]=this.parentDimensions;this.setDims(this.width*r,this.height*a)},G9e=function(){de(this,Ay)===null||!this.parent||(this.parent.drawLayer.remove(de(this,Ay)),Dt(this,Ay,null),this.parent.drawLayer.remove(de(this,qg)),Dt(this,qg,null))},pI=function(n=this.parent){de(this,Ay)===null&&({id:Sx(this,Ay)._,clipPathId:Sx(this,V8)._}=n.drawLayer.draw(de(this,A2),this.color,de(this,M4)),Dt(this,qg,n.drawLayer.drawOutline(de(this,zw))),de(this,H8)&&(de(this,H8).style.clipPath=de(this,V8)))},tj=new WeakSet,p7=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}},OFt=function(n){tu._keyboardManager.exec(this,n)},Eje=function(n){if(!de(this,pB))return;const r=window.getSelection();n?r.setPosition(de(this,pB),de(this,sQ)):r.setPosition(de(this,nQ),de(this,rQ))},yG=function(){return de(this,F1)?this.rotation:0},FFt=function(){if(de(this,F1))return null;const[n,r]=this.pageDimensions,[a,i]=this.pageTranslation,l=de(this,E4),o=new Float32Array(l.length*8);let c=0;for(const{x:d,y:u,width:h,height:m}of l){const f=d*n+a,g=(1-u-m)*r+i;o[c]=o[c+4]=f,o[c+1]=o[c+3]=g,o[c+2]=o[c+6]=f+h*n,o[c+5]=o[c+7]=g+m*r,c+=8}return o},zFt=function(n){return de(this,A2).serialize(n,Ht(this,Gl,yG).call(this))},BFt=function(n,r){this._freeHighlight.add(r)&&n.drawLayer.updatePath(this._freeHighlightId,this._freeHighlight)},$Ft=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=""},UFt=function(n){const{color:r}=this._initialData;return n.color.some((a,i)=>a!==r[i])},ts(tu,tj),jr(tu,"_defaultColor",null),jr(tu,"_defaultOpacity",1),jr(tu,"_defaultThickness",12),jr(tu,"_type","highlight"),jr(tu,"_editorType",tc.HIGHLIGHT),jr(tu,"_freeHighlightId",-1),jr(tu,"_freeHighlight",null),jr(tu,"_freeHighlightClipId","");let z5e=tu;var G8,W8,Ok,L4,$w,K8,Y8,Z8,P4,yB,X8,Q8,YA,ai,qFt,VFt,HFt,GFt,K9e,WFt,Y9e,KFt,YFt,ZFt,XFt,QFt,fI,Z9e,X9e,Q9e,Mje,Lje,f7,J9e,Pje,D3,JFt,eze,e7t,t7t,tze,Ije,vG;const up=class up extends Uu{constructor(n){super({...n,name:"inkEditor"});ts(this,ai);ts(this,G8,0);ts(this,W8,0);ts(this,Ok,null);ts(this,L4,new Path2D);ts(this,$w,!1);ts(this,K8,null);ts(this,Y8,!1);ts(this,Z8,!1);ts(this,P4,null);ts(this,yB,null);ts(this,X8,0);ts(this,Q8,0);ts(this,YA,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){Uu.initialize(n,r)}static updateDefaultParams(n,r){switch(n){case bl.INK_THICKNESS:up._defaultThickness=r;break;case bl.INK_COLOR:up._defaultColor=r;break;case bl.INK_OPACITY:up._defaultOpacity=r/100;break}}updateParams(n,r){switch(n){case bl.INK_THICKNESS:Ht(this,ai,qFt).call(this,r);break;case bl.INK_COLOR:Ht(this,ai,VFt).call(this,r);break;case bl.INK_OPACITY:Ht(this,ai,HFt).call(this,r);break}}static get defaultPropertiesToUpdate(){return[[bl.INK_THICKNESS,up._defaultThickness],[bl.INK_COLOR,up._defaultColor||Uu._defaultLineColor],[bl.INK_OPACITY,Math.round(up._defaultOpacity*100)]]}get propertiesToUpdate(){return[[bl.INK_THICKNESS,this.thickness||up._defaultThickness],[bl.INK_COLOR,this.color||up._defaultColor||Uu._defaultLineColor],[bl.INK_OPACITY,Math.round(100*(this.opacity??up._defaultOpacity))]]}rebuild(){this.parent&&(super.rebuild(),this.div!==null&&(this.canvas||(Ht(this,ai,Mje).call(this),Ht(this,ai,Lje).call(this)),this.isAttachedToDOM||(this.parent.add(this),Ht(this,ai,f7).call(this)),Ht(this,ai,vG).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,de(this,Ok)&&(clearTimeout(de(this,Ok)),Dt(this,Ok,null)),(n=de(this,P4))==null||n.disconnect(),Dt(this,P4,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(){de(this,$w)||this.canvas===null||(super.enableEditMode(),this._isDraggable=!1,Ht(this,ai,Z9e).call(this))}disableEditMode(){!this.isInEditMode()||this.canvas===null||(super.disableEditMode(),this._isDraggable=!this.isEmpty(),this.div.classList.remove("editing"),Ht(this,ai,X9e).call(this))}onceAdded(){this._isDraggable=!this.isEmpty()}isEmpty(){return this.paths.length===0||this.paths.length===1&&this.paths[0].length===0}commit(){de(this,$w)||(super.commit(),this.isEditing=!1,this.disableEditMode(),this.setInForeground(),Dt(this,$w,!0),this.div.classList.add("disabled"),Ht(this,ai,vG).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()||de(this,$w)||(this.setInForeground(),n.preventDefault(),this.div.contains(document.activeElement)||this.div.focus({preventScroll:!0}),Ht(this,ai,WFt).call(this,n.offsetX,n.offsetY))}canvasPointermove(n){n.preventDefault(),Ht(this,ai,Y9e).call(this,n.offsetX,n.offsetY)}canvasPointerup(n){n.preventDefault(),Ht(this,ai,Q9e).call(this,n)}canvasPointerleave(n){Ht(this,ai,Q9e).call(this,n)}get isResizable(){return!this.isEmpty()&&de(this,$w)}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]=Ht(this,ai,GFt).call(this);if(this.setAt(a,i,0,0),this.setDims(l,o),Ht(this,ai,Mje).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),Dt(this,Z8,!0),Ht(this,ai,f7).call(this),this.setDims(this.width*c,this.height*d),Ht(this,ai,fI).call(this),this.div.classList.add("disabled")}else this.div.classList.add("editing"),this.enableEditMode();return Ht(this,ai,Lje).call(this),this.div}setDimensions(n,r){const a=Math.round(n),i=Math.round(r);if(de(this,X8)===a&&de(this,Q8)===i)return;Dt(this,X8,a),Dt(this,Q8,i),this.canvas.style.visibility="hidden";const[l,o]=this.parentDimensions;this.width=n/l,this.height=r/o,this.fixAndSetPosition(),de(this,$w)&&Ht(this,ai,J9e).call(this,n,r),Ht(this,ai,f7).call(this),Ht(this,ai,fI).call(this),this.canvas.style.visibility="visible",this.fixDims()}static async deserialize(n,r,a){var x,_,b;if(n instanceof FWe)return null;const i=await super.deserialize(n,r,a);i.thickness=n.thickness,i.color=go.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;Dt(i,$w,!0),Dt(i,X8,Math.round(c)),Dt(i,Q8,Math.round(d));const{paths:m,rect:f,rotation:g}=n;for(let{bezier:k}of m){k=Ht(x=up,D3,e7t).call(x,k,f,g);const A=[];i.paths.push(A);let T=u*(k[0]-h),P=u*(k[1]-h);for(let M=2,L=k.length;M{this.thickness=i,Ht(this,ai,vG).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:bl.INK_THICKNESS,overwriteIfSameType:!0,keepUndo:!0})},VFt=function(n){const r=i=>{this.color=i,Ht(this,ai,fI).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:bl.INK_COLOR,overwriteIfSameType:!0,keepUndo:!0})},HFt=function(n){const r=i=>{this.opacity=i,Ht(this,ai,fI).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:bl.INK_OPACITY,overwriteIfSameType:!0,keepUndo:!0})},GFt=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]}},K9e=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}${Hbn(a)}`},WFt=function(n,r){this.canvas.addEventListener("contextmenu",kj,{signal:this._uiManager._signal}),Ht(this,ai,X9e).call(this),Dt(this,K8,new AbortController);const a=this._uiManager.combinedSignal(de(this,K8));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,de(this,Z8)||(Dt(this,Z8,!0),Ht(this,ai,f7).call(this),this.thickness||(this.thickness=up._defaultThickness),this.color||(this.color=up._defaultColor||Uu._defaultLineColor),this.opacity??(this.opacity=up._defaultOpacity)),this.currentPath.push([n,r]),Dt(this,Y8,!1),Ht(this,ai,K9e).call(this),Dt(this,YA,()=>{Ht(this,ai,ZFt).call(this),de(this,YA)&&window.requestAnimationFrame(de(this,YA))}),window.requestAnimationFrame(de(this,YA))},Y9e=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=de(this,L4);if(l.push([n,r]),Dt(this,Y8,!0),l.length<=2){o.moveTo(...l[0]),o.lineTo(n,r);return}l.length===3&&(Dt(this,L4,o=new Path2D),o.moveTo(...l[0])),Ht(this,ai,XFt).call(this,o,...l.at(-3),...l.at(-2),n,r)},KFt=function(){if(this.currentPath.length===0)return;const n=this.currentPath.at(-1);de(this,L4).lineTo(...n)},YFt=function(n,r){Dt(this,YA,null),n=Math.min(Math.max(n,0),this.canvas.width),r=Math.min(Math.max(r,0),this.canvas.height),Ht(this,ai,Y9e).call(this,n,r),Ht(this,ai,KFt).call(this);let a;if(this.currentPath.length!==1)a=Ht(this,ai,QFt).call(this);else{const d=[n,r];a=[[d,d.slice(),d.slice(),d]]}const i=de(this,L4),l=this.currentPath;this.currentPath=[],Dt(this,L4,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||(Ht(this,ai,Mje).call(this),Ht(this,ai,Lje).call(this)),Ht(this,ai,vG).call(this))};this.addCommands({cmd:o,undo:c,mustExec:!0})},ZFt=function(){if(!de(this,Y8))return;Dt(this,Y8,!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(de(this,L4)),l.restore()},XFt=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)},QFt=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{Dt(this,Ok,null),this.canvas.removeEventListener("contextmenu",kj)},10)),Ht(this,ai,YFt).call(this,n.offsetX,n.offsetY),this.addToAnnotationStorage(),this.setInBackground()},Mje=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")},Lje=function(){Dt(this,P4,new ResizeObserver(n=>{const r=n[0].contentRect;r.width&&r.height&&this.setDimensions(r.width,r.height)})),de(this,P4).observe(this.div),this._uiManager._signal.addEventListener("abort",()=>{var n;(n=de(this,P4))==null||n.disconnect(),Dt(this,P4,null)},{once:!0})},f7=function(){if(!de(this,Z8))return;const[n,r]=this.parentDimensions;this.canvas.width=Math.ceil(this.width*n),this.canvas.height=Math.ceil(this.height*r),Ht(this,ai,Pje).call(this)},J9e=function(n,r){const a=Ht(this,ai,Ije).call(this),i=(n-a)/de(this,W8),l=(r-a)/de(this,G8);this.scaleFactor=Math.min(i,l)},Pje=function(){const n=Ht(this,ai,Ije).call(this)/2;this.ctx.setTransform(this.scaleFactor,0,0,this.scaleFactor,this.translationX*this.scaleFactor+n,this.translationY*this.scaleFactor+n)},D3=new WeakSet,JFt=function(n){const r=new Path2D;for(let a=0,i=n.length;a`image/${r}`))}static get supportedTypesStr(){return od(this,"supportedTypesStr",this.supportedTypes.join(","))}static isHandlingMimeForPasting(n){return this.supportedTypes.includes(n)}static paste(n,r){r.pasteEditor(tc.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;de(this,k0)&&(Dt(this,mp,null),this._uiManager.imageManager.deleteId(de(this,k0)),(n=de(this,Fk))==null||n.remove(),Dt(this,Fk,null),(r=de(this,D4))==null||r.disconnect(),Dt(this,D4,null),de(this,zk)&&(clearTimeout(de(this,zk)),Dt(this,zk,null))),super.remove()}rebuild(){if(!this.parent){de(this,k0)&&Ht(this,Yc,Dje).call(this);return}super.rebuild(),this.div!==null&&(de(this,k0)&&de(this,Fk)===null&&Ht(this,Yc,Dje).call(this),this.isAttachedToDOM||this.parent.add(this))}onceAdded(){this._isDraggable=!0,this.div.focus()}isEmpty(){return!(de(this,ZA)||de(this,mp)||de(this,I4)||de(this,XA)||de(this,k0))}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(),de(this,mp)?Ht(this,Yc,nze).call(this):Ht(this,Yc,Dje).call(this),this.width&&!this.annotationElementId){const[a,i]=this.parentDimensions;this.setAt(n*a,r*i,this.width*a,this.height*i)}return this.div}copyCanvas(n,r,a=!1){var f;n||(n=224);const{width:i,height:l}=de(this,mp),o=new J7e;let c=de(this,mp),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 g=h.width=Math.ceil(d*o.sx),y=h.height=Math.ceil(u*o.sy);de(this,o_)||(c=Ht(this,Yc,Rje).call(this,g,y));const x=h.getContext("2d");x.filter=this._uiManager.hcmFilter;let _="white",b="#cfcfd8";this._uiManager.hcmFilter!=="none"?b="black":(f=window.matchMedia)!=null&&f.call(window,"(prefers-color-scheme: dark)").matches&&(_="#8f8f9d",b="#42414d");const k=15,A=k*o.sx,T=k*o.sy,P=new OffscreenCanvas(A*2,T*2),I=P.getContext("2d");I.fillStyle=_,I.fillRect(0,0,A*2,T*2),I.fillStyle=b,I.fillRect(0,0,A,T),I.fillRect(A,T,A,T),x.fillStyle=x.createPattern(P,"repeat"),x.fillRect(0,0,g,y),x.drawImage(c,0,0,c.width,c.height,0,0,g,y)}let m=null;if(a){let g,y;if(o.symmetric&&c.widthn||l>n){const b=Math.min(n/i,n/l);g=Math.floor(i*b),y=Math.floor(l*b),de(this,o_)||(c=Ht(this,Yc,Rje).call(this,g,y))}const _=new OffscreenCanvas(g,y).getContext("2d",{willReadFrequently:!0});_.drawImage(c,0,0,c.width,c.height,0,0,g,y),m={width:g,height:y,data:_.getImageData(0,0,g,y).data}}return{canvas:h,width:d,height:u,imageData:m}}getImageForAltText(){return de(this,Fk)}static async deserialize(n,r,a){var y;let i=null;if(n instanceof pFt){const{data:{rect:x,rotation:_,id:b,structParent:k,popupRef:A},container:T,parent:{page:{pageNumber:P}}}=n,I=T.querySelector("canvas"),M=a.imageManager.getFromCanvas(T.id,I);I.remove();const L=((y=await r._structTree.getAriaAttributes(`${CWe}${b}`))==null?void 0:y.get("aria-label"))||"";i=n={annotationType:tc.STAMP,bitmapId:M.id,bitmap:M.bitmap,pageIndex:P-1,rect:x.slice(0),rotation:_,id:b,deleted:!1,accessibilityData:{decorative:!1,altText:L},isSvg:!1,structParent:k,popupRef:A}}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)?(Dt(l,k0,u),c&&Dt(l,mp,c)):Dt(l,I4,d),Dt(l,o_,h);const[f,g]=l.pageDimensions;return l.width=(o[2]-o[0])/f,l.height=(o[3]-o[1])/g,l.annotationElementId=n.id||null,m&&(l.altTextData=m),l._initialData=i,Dt(l,bB,!!i),l}serialize(n=!1,r=null){if(this.isEmpty())return null;if(this.deleted)return this.serializeDeleted();const a={annotationType:tc.STAMP,bitmapId:de(this,k0),pageIndex:this.pageIndex,rect:this.getRect(0,0),rotation:this.rotation,isSvg:de(this,o_),structTreeParentId:this._structTreeParentId};if(n)return a.bitmapUrl=Ht(this,Yc,Oje).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=Ht(this,Yc,r7t).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=de(this,o_)?(a.rect[2]-a.rect[0])*(a.rect[3]-a.rect[1]):null;if(!r.stamps.has(de(this,k0)))r.stamps.set(de(this,k0),{area:o,serialized:a}),a.bitmap=Ht(this,Yc,Oje).call(this,!1);else if(de(this,o_)){const c=r.stamps.get(de(this,k0));o>c.area&&(c.area=o,c.serialized.bitmap.close(),c.serialized.bitmap=Ht(this,Yc,Oje).call(this,!1))}return a}renderAnnotationElement(n){return n.updateEdited({rect:this.getRect(0,0)}),null}};mp=new WeakMap,k0=new WeakMap,ZA=new WeakMap,I4=new WeakMap,XA=new WeakMap,vB=new WeakMap,Fk=new WeakMap,D4=new WeakMap,zk=new WeakMap,o_=new WeakMap,bB=new WeakMap,Yc=new WeakSet,bG=function(n,r=!1){if(!n){this.remove();return}Dt(this,mp,n.bitmap),r||(Dt(this,k0,n.id),Dt(this,o_,n.isSvg)),n.file&&Dt(this,vB,n.file.name),Ht(this,Yc,nze).call(this)},_G=function(){if(Dt(this,ZA,null),this._uiManager.enableWaiting(!1),!!de(this,Fk)){if(this._uiManager.useNewAltTextWhenAddingImage&&this._uiManager.useNewAltTextFlow&&de(this,mp)){this._editToolbar.hide(),this._uiManager.editAltText(this,!0);return}if(!this._uiManager.useNewAltTextWhenAddingImage&&this._uiManager.useNewAltTextFlow&&de(this,mp)){this._reportTelemetry({action:"pdfjs.image.image_added",data:{alt_text_modal:!1,alt_text_type:"empty"}});try{this.mlGuessAltText()}catch{}}this.div.focus()}},Dje=function(){if(de(this,k0)){this._uiManager.enableWaiting(!0),this._uiManager.imageManager.getFromId(de(this,k0)).then(a=>Ht(this,Yc,bG).call(this,a,!0)).finally(()=>Ht(this,Yc,_G).call(this));return}if(de(this,I4)){const a=de(this,I4);Dt(this,I4,null),this._uiManager.enableWaiting(!0),Dt(this,ZA,this._uiManager.imageManager.getFromUrl(a).then(i=>Ht(this,Yc,bG).call(this,i)).finally(()=>Ht(this,Yc,_G).call(this)));return}if(de(this,XA)){const a=de(this,XA);Dt(this,XA,null),this._uiManager.enableWaiting(!0),Dt(this,ZA,this._uiManager.imageManager.getFromFile(a).then(i=>Ht(this,Yc,bG).call(this,i)).finally(()=>Ht(this,Yc,_G).call(this)));return}const n=document.createElement("input");n.type="file",n.accept=RK.supportedTypesStr;const r=this._uiManager._signal;Dt(this,ZA,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}}),Ht(this,Yc,bG).call(this,i)}a()},{signal:r}),n.addEventListener("cancel",()=>{this.remove(),a()},{signal:r})}).finally(()=>Ht(this,Yc,_G).call(this))),n.click()},nze=function(){const{div:n}=this;let{width:r,height:a}=de(this,mp);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=Dt(this,Fk,document.createElement("canvas"));u.setAttribute("role","img"),this.addContainer(u),(!this._uiManager.useNewAltTextWhenAddingImage||!this._uiManager.useNewAltTextFlow||this.annotationElementId)&&(n.hidden=!1),Ht(this,Yc,rze).call(this,r,a),Ht(this,Yc,n7t).call(this),de(this,bB)||(this.parent.addUndoableEditor(this),Dt(this,bB,!0)),this._reportTelemetry({action:"inserted_image"}),de(this,vB)&&u.setAttribute("aria-label",de(this,vB))},s7t=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,de(this,zk)!==null&&clearTimeout(de(this,zk)),Dt(this,zk,setTimeout(()=>{Dt(this,zk,null),Ht(this,Yc,rze).call(this,n,r)},200))},Rje=function(n,r){const{width:a,height:i}=de(this,mp);let l=a,o=i,c=de(this,mp);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},rze=function(n,r){const a=new J7e,i=Math.ceil(n*a.sx),l=Math.ceil(r*a.sy),o=de(this,Fk);if(!o||o.width===i&&o.height===l)return;o.width=i,o.height=l;const c=de(this,o_)?de(this,mp):Ht(this,Yc,Rje).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)},Oje=function(n){if(n){if(de(this,o_)){const i=this._uiManager.imageManager.getSvgUrl(de(this,k0));if(i)return i}const r=document.createElement("canvas");return{width:r.width,height:r.height}=de(this,mp),r.getContext("2d").drawImage(de(this,mp),0,0),r.toDataURL()}if(de(this,o_)){const[r,a]=this.pageDimensions,i=Math.round(this.width*r*bE.PDF_TO_CSS_UNITS),l=Math.round(this.height*a*bE.PDF_TO_CSS_UNITS),o=new OffscreenCanvas(i,l);return o.getContext("2d").drawImage(de(this,mp),0,0,de(this,mp).width,de(this,mp).height,0,0,i,l),o.transferToImageBitmap()}return structuredClone(de(this,mp))},n7t=function(){this._uiManager._signal&&(Dt(this,D4,new ResizeObserver(n=>{const r=n[0].contentRect;r.width&&r.height&&Ht(this,Yc,s7t).call(this,r.width,r.height)})),de(this,D4).observe(this.div),this._uiManager._signal.addEventListener("abort",()=>{var n;(n=de(this,D4))==null||n.disconnect(),Dt(this,D4,null)},{once:!0}))},r7t=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}},jr(RK,"_type","stamp"),jr(RK,"_editorType",tc.STAMP);let sze=RK;var J8,_B,Bk,QA,R4,l_,JA,wB,jB,Ty,O4,Lo,eT,X0,a7t,ize,oze,lze,Fje;const u2=class u2{constructor({uiManager:t,pageIndex:n,div:r,structTreeLayer:a,accessibilityManager:i,annotationLayer:l,drawLayer:o,textLayer:c,viewport:d,l10n:u}){ts(this,X0);ts(this,J8);ts(this,_B,!1);ts(this,Bk,null);ts(this,QA,null);ts(this,R4,null);ts(this,l_,new Map);ts(this,JA,!1);ts(this,wB,!1);ts(this,jB,!1);ts(this,Ty,null);ts(this,O4,null);ts(this,Lo);const h=[...de(u2,eT).values()];if(!u2._initialized){u2._initialized=!0;for(const m of h)m.initialize(u,t)}t.registerEditorTypes(h),Dt(this,Lo,t),this.pageIndex=n,this.div=r,Dt(this,J8,i),Dt(this,Bk,l),this.viewport=d,Dt(this,Ty,c),this.drawLayer=o,this._structTree=a,de(this,Lo).addLayer(this)}get isEmpty(){return de(this,l_).size===0}get isInvisible(){return this.isEmpty&&de(this,Lo).getMode()===tc.NONE}updateToolbar(t){de(this,Lo).updateToolbar(t)}updateMode(t=de(this,Lo).getMode()){switch(Ht(this,X0,Fje).call(this),t){case tc.NONE:this.disableTextSelection(),this.togglePointerEvents(!1),this.toggleAnnotationLayerPointerEvents(!0),this.disableClick();return;case tc.INK:this.addInkEditorIfNeeded(!1),this.disableTextSelection(),this.togglePointerEvents(!0),this.disableClick();break;case tc.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 de(u2,eT).values())n.toggle(`${r._type}Editing`,t===r._editorType);this.div.hidden=!1}hasTextLayer(t){var n;return t===((n=de(this,Ty))==null?void 0:n.div)}addInkEditorIfNeeded(t){if(de(this,Lo).getMode()!==tc.INK)return;if(!t){for(const r of de(this,l_).values())if(r.isEmpty()){r.setInBackground();return}}this.createAndAddNewEditor({offsetX:0,offsetY:0},!1).setInBackground()}setEditingState(t){de(this,Lo).setEditingState(t)}addCommands(t){de(this,Lo).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=de(this,Bk))==null||n.div.classList.toggle("disabled",!t)}async enable(){this.div.tabIndex=0,this.togglePointerEvents(!0);const t=new Set;for(const r of de(this,l_).values())r.enableEditing(),r.show(!0),r.annotationElementId&&(de(this,Lo).removeChangedExistingAnnotation(r),t.add(r.annotationElementId));if(!de(this,Bk))return;const n=de(this,Bk).getEditableAnnotations();for(const r of n){if(r.hide(),de(this,Lo).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;Dt(this,jB,!0),this.div.tabIndex=-1,this.togglePointerEvents(!1);const t=new Map,n=new Map;for(const i of de(this,l_).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(de(this,Bk)){const i=de(this,Bk).getEditableAnnotations();for(const l of i){const{id:o}=l.data;if(de(this,Lo).isDeletedAnnotationElement(o))continue;let c=n.get(o);if(c){c.resetAnnotationElement(l),c.show(!1),l.show();continue}c=t.get(o),c&&(de(this,Lo).addChangedExistingAnnotation(c),c.renderAnnotationElement(l)&&c.show(!1)),l.show()}}Ht(this,X0,Fje).call(this),this.isEmpty&&(this.div.hidden=!0);const{classList:r}=this.div;for(const i of de(u2,eT).values())r.remove(`${i._type}Editing`);this.disableTextSelection(),this.toggleAnnotationLayerPointerEvents(!0),Dt(this,jB,!1)}getEditableAnnotation(t){var n;return((n=de(this,Bk))==null?void 0:n.getEditableAnnotation(t))||null}setActiveEditor(t){de(this,Lo).getActive()!==t&&de(this,Lo).setActiveEditor(t)}enableTextSelection(){var t;if(this.div.tabIndex=-1,(t=de(this,Ty))!=null&&t.div&&!de(this,O4)){Dt(this,O4,new AbortController);const n=de(this,Lo).combinedSignal(de(this,O4));de(this,Ty).div.addEventListener("pointerdown",Ht(this,X0,a7t).bind(this),{signal:n}),de(this,Ty).div.classList.add("highlighting")}}disableTextSelection(){var t;this.div.tabIndex=0,(t=de(this,Ty))!=null&&t.div&&de(this,O4)&&(de(this,O4).abort(),Dt(this,O4,null),de(this,Ty).div.classList.remove("highlighting"))}enableClick(){if(de(this,QA))return;Dt(this,QA,new AbortController);const t=de(this,Lo).combinedSignal(de(this,QA));this.div.addEventListener("pointerdown",this.pointerdown.bind(this),{signal:t}),this.div.addEventListener("pointerup",this.pointerup.bind(this),{signal:t})}disableClick(){var t;(t=de(this,QA))==null||t.abort(),Dt(this,QA,null)}attach(t){de(this,l_).set(t.id,t);const{annotationElementId:n}=t;n&&de(this,Lo).isDeletedAnnotationElement(n)&&de(this,Lo).removeDeletedAnnotationElement(t)}detach(t){var n;de(this,l_).delete(t.id),(n=de(this,J8))==null||n.removePointerInTextLayer(t.contentDiv),!de(this,jB)&&t.annotationElementId&&de(this,Lo).addDeletedAnnotationElement(t)}remove(t){this.detach(t),de(this,Lo).removeEditor(t),t.div.remove(),t.isAttachedToDOM=!1,de(this,wB)||this.addInkEditorIfNeeded(!1)}changeParent(t){var n;t.parent!==this&&(t.parent&&t.annotationElementId&&(de(this,Lo).addDeletedAnnotationElement(t.annotationElementId),Uu.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),de(this,Lo).addEditor(t),this.attach(t),!t.isAttachedToDOM){const n=t.render();this.div.append(n),t.isAttachedToDOM=!0}t.fixAndSetPosition(),t.onceAdded(),de(this,Lo).addToAnnotationStorage(t),t._reportTelemetry(t.telemetryInitialData)}}moveEditorInDOM(t){var r;if(!t.isAttachedToDOM)return;const{activeElement:n}=document;t.div.contains(n)&&!de(this,R4)&&(t._focusEventsAllowed=!1,Dt(this,R4,setTimeout(()=>{Dt(this,R4,null),t.div.contains(document.activeElement)?t._focusEventsAllowed=!0:(t.div.addEventListener("focusin",()=>{t._focusEventsAllowed=!0},{once:!0,signal:de(this,Lo)._signal}),n.focus())},0))),t._structTreeParentId=(r=de(this,J8))==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 de(this,Lo).getId()}combinedSignal(t){return de(this,Lo).combinedSignal(t)}canCreateNewEmptyEditor(){var t;return(t=de(this,X0,ize))==null?void 0:t.canCreateNewEmptyEditor()}pasteEditor(t,n){de(this,Lo).updateToolbar(t),de(this,Lo).updateMode(t);const{offsetX:r,offsetY:a}=Ht(this,X0,lze).call(this),i=this.getNextId(),l=Ht(this,X0,oze).call(this,{parent:this,id:i,x:r,y:a,uiManager:de(this,Lo),isCentered:!0,...n});l&&this.add(l)}async deserialize(t){var n;return await((n=de(u2,eT).get(t.annotationType??t.annotationEditorType))==null?void 0:n.deserialize(t,this,de(this,Lo)))||null}createAndAddNewEditor(t,n,r={}){const a=this.getNextId(),i=Ht(this,X0,oze).call(this,{parent:this,id:a,x:t.offsetX,y:t.offsetY,uiManager:de(this,Lo),isCentered:n,...r});return i&&this.add(i),i}addNewEditor(){this.createAndAddNewEditor(Ht(this,X0,lze).call(this),!0)}setSelected(t){de(this,Lo).setSelected(t)}toggleSelected(t){de(this,Lo).toggleSelected(t)}unselect(t){de(this,Lo).unselect(t)}pointerup(t){const{isMac:n}=Jv.platform;if(!(t.button!==0||t.ctrlKey&&n)&&t.target===this.div&&de(this,JA)){if(Dt(this,JA,!1),!de(this,_B)){Dt(this,_B,!0);return}if(de(this,Lo).getMode()===tc.STAMP){de(this,Lo).unselectAll();return}this.createAndAddNewEditor(t,!1)}}pointerdown(t){if(de(this,Lo).getMode()===tc.HIGHLIGHT&&this.enableTextSelection(),de(this,JA)){Dt(this,JA,!1);return}const{isMac:n}=Jv.platform;if(t.button!==0||t.ctrlKey&&n||t.target!==this.div)return;Dt(this,JA,!0);const r=de(this,Lo).getActive();Dt(this,_B,!r||r.isEmpty())}findNewParent(t,n,r){const a=de(this,Lo).findParent(n,r);return a===null||a===this?!1:(a.changeParent(t),!0)}destroy(){var t,n;((t=de(this,Lo).getActive())==null?void 0:t.parent)===this&&(de(this,Lo).commitOrRemove(),de(this,Lo).setActiveEditor(null)),de(this,R4)&&(clearTimeout(de(this,R4)),Dt(this,R4,null));for(const r of de(this,l_).values())(n=de(this,J8))==null||n.removePointerInTextLayer(r.contentDiv),r.setParent(null),r.isAttachedToDOM=!1,r.div.remove();this.div=null,de(this,l_).clear(),de(this,Lo).removeLayer(this)}render({viewport:t}){this.viewport=t,CR(this.div,t);for(const n of de(this,Lo).getEditors(this.pageIndex))this.add(n),n.rebuild();this.updateMode()}update({viewport:t}){de(this,Lo).commitOrRemove(),Ht(this,X0,Fje).call(this);const n=this.viewport.rotation,r=t.rotation;if(this.viewport=t,CR(this.div,{rotation:r}),n!==r)for(const a of de(this,l_).values())a.rotate(r);this.addInkEditorIfNeeded(!1)}get pageDimensions(){const{pageWidth:t,pageHeight:n}=this.viewport.rawDims;return[t,n]}get scale(){return de(this,Lo).viewParameters.realScale}};J8=new WeakMap,_B=new WeakMap,Bk=new WeakMap,QA=new WeakMap,R4=new WeakMap,l_=new WeakMap,JA=new WeakMap,wB=new WeakMap,jB=new WeakMap,Ty=new WeakMap,O4=new WeakMap,Lo=new WeakMap,eT=new WeakMap,X0=new WeakSet,a7t=function(t){de(this,Lo).unselectAll();const{target:n}=t;if(n===de(this,Ty).div||(n.getAttribute("role")==="img"||n.classList.contains("endOfContent"))&&de(this,Ty).div.contains(n)){const{isMac:r}=Jv.platform;if(t.button!==0||t.ctrlKey&&r)return;de(this,Lo).showAllEditors("highlight",!0,!0),de(this,Ty).div.classList.add("free"),this.toggleDrawing(),z5e.startHighlighting(this,de(this,Lo).direction==="ltr",{target:de(this,Ty).div,x:t.x,y:t.y}),de(this,Ty).div.addEventListener("pointerup",()=>{de(this,Ty).div.classList.remove("free"),this.toggleDrawing(!0)},{once:!0,signal:de(this,Lo)._signal}),t.preventDefault()}},ize=function(){return de(u2,eT).get(de(this,Lo).getMode())},oze=function(t){const n=de(this,X0,ize);return n?new n.prototype.constructor(t):null},lze=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}},Fje=function(){Dt(this,wB,!0);for(const t of de(this,l_).values())t.isEmpty()&&t.remove();Dt(this,wB,!1)},jr(u2,"_initialized",!1),ts(u2,eT,new Map([F9e,W9e,sze,z5e].map(t=>[t._editorType,t])));let aze=u2;var $k,iQ,og,F4,oQ,dze,PR,uze,i7t;const w0=class w0{constructor({pageIndex:t}){ts(this,PR);ts(this,$k,null);ts(this,iQ,0);ts(this,og,new Map);ts(this,F4,new Map);this.pageIndex=t}setParent(t){if(!de(this,$k)){Dt(this,$k,t);return}if(de(this,$k)!==t){if(de(this,og).size>0)for(const n of de(this,og).values())n.remove(),t.append(n);Dt(this,$k,t)}}static get _svgFactory(){return od(this,"_svgFactory",new OWe)}draw(t,n,r,a=!1){const i=Sx(this,iQ)._++,l=Ht(this,PR,uze).call(this,t.box);l.classList.add(...t.classNamesForDrawing);const o=w0._svgFactory.createElement("defs");l.append(o);const c=w0._svgFactory.createElement("path");o.append(c);const d=`path_p${this.pageIndex}_${i}`;c.setAttribute("id",d),c.setAttribute("d",t.toSVGPath()),a&&de(this,F4).set(i,c);const u=Ht(this,PR,i7t).call(this,o,d),h=w0._svgFactory.createElement("use");return l.append(h),l.setAttribute("fill",n),l.setAttribute("fill-opacity",r),h.setAttribute("href",`#${d}`),de(this,og).set(i,l),{id:i,clipPathId:`url(#${u})`}}drawOutline(t){const n=Sx(this,iQ)._++,r=Ht(this,PR,uze).call(this,t.box);r.classList.add(...t.classNamesForOutlining);const a=w0._svgFactory.createElement("defs");r.append(a);const i=w0._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=w0._svgFactory.createElement("mask");a.append(u),o=`mask_p${this.pageIndex}_${n}`,u.setAttribute("id",o),u.setAttribute("maskUnits","objectBoundingBox");const h=w0._svgFactory.createElement("rect");u.append(h),h.setAttribute("width","1"),h.setAttribute("height","1"),h.setAttribute("fill","white");const m=w0._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=w0._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"),de(this,og).set(n,r),n}finalizeLine(t,n){const r=de(this,F4).get(t);de(this,F4).delete(t),this.updateBox(t,n.box),r.setAttribute("d",n.toSVGPath())}updateLine(t,n){de(this,og).get(t).firstChild.firstChild.setAttribute("d",n.toSVGPath())}updatePath(t,n){de(this,F4).get(t).setAttribute("d",n.toSVGPath())}updateBox(t,n){var r;Ht(r=w0,oQ,dze).call(r,de(this,og).get(t),n)}show(t,n){de(this,og).get(t).classList.toggle("hidden",!n)}rotate(t,n){de(this,og).get(t).setAttribute("data-main-rotation",n)}changeColor(t,n){de(this,og).get(t).setAttribute("fill",n)}changeOpacity(t,n){de(this,og).get(t).setAttribute("fill-opacity",n)}addClass(t,n){de(this,og).get(t).classList.add(n)}removeClass(t,n){de(this,og).get(t).classList.remove(n)}getSVGRoot(t){return de(this,og).get(t)}remove(t){de(this,F4).delete(t),de(this,$k)!==null&&(de(this,og).get(t).remove(),de(this,og).delete(t))}destroy(){Dt(this,$k,null);for(const t of de(this,og).values())t.remove();de(this,og).clear(),de(this,F4).clear()}};$k=new WeakMap,iQ=new WeakMap,og=new WeakMap,F4=new WeakMap,oQ=new WeakSet,dze=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}%`},PR=new WeakSet,uze=function(t){var r;const n=w0._svgFactory.create(1,1,!0);return de(this,$k).append(n),n.setAttribute("aria-hidden",!0),Ht(r=w0,oQ,dze).call(r,n,t),n},i7t=function(t,n){const r=w0._svgFactory.createElement("clipPath");t.append(r);const a=`clip_${n}`;r.setAttribute("id",a),r.setAttribute("clipPathUnits","objectBoundingBox");const i=w0._svgFactory.createElement("use");return r.append(i),i.setAttribute("href",`#${n}`),i.classList.add("clip"),a},ts(w0,oQ);let cze=w0;Ll.AbortException;Ll.AnnotationEditorLayer;Ll.AnnotationEditorParamsType;Ll.AnnotationEditorType;Ll.AnnotationEditorUIManager;Ll.AnnotationLayer;Ll.AnnotationMode;Ll.ColorPicker;Ll.DOMSVGFactory;Ll.DrawLayer;Ll.FeatureTest;var Nwn=Ll.GlobalWorkerOptions;Ll.ImageKind;Ll.InvalidPDFException;Ll.MissingPDFException;Ll.OPS;Ll.OutputScale;Ll.PDFDataRangeTransport;Ll.PDFDateString;Ll.PDFWorker;Ll.PasswordResponses;Ll.PermissionFlag;Ll.PixelsPerInch;Ll.RenderingCancelledException;Ll.TextLayer;Ll.UnexpectedResponseException;Ll.Util;Ll.VerbosityLevel;Ll.XfaLayer;Ll.build;Ll.createValidAbsoluteUrl;Ll.fetchData;var kwn=Ll.getDocument;Ll.getFilenameFromUrl;Ll.getPdfFilenameFromUrl;Ll.getXfaPageViewport;Ll.isDataScheme;Ll.isPdfFile;Ll.noContextMenu;Ll.normalizeUnicode;Ll.setLayerDimensions;Ll.shadow;Ll.version;const Swn="/assets/pdf.worker.min-GB3t0DcA.mjs";Nwn.workerSrc=Swn;const Cwn=({blob:s,scale:t=1.5})=>{const n=N.useRef(null),[r,a]=N.useState(!1),[i,l]=N.useState(null);return N.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 kwn({data:u}).promise;if(o)return;c.innerHTML="";for(let m=1;m<=h.numPages;m+=1){const f=await h.getPage(m);if(o)return;const g=f.getViewport({scale:t}),y=document.createElement("canvas");y.width=Math.floor(g.width),y.height=Math.floor(g.height),y.className="mx-auto w-full max-w-[900px] rounded-md border border-border bg-white shadow-sm";const x=y.getContext("2d");x&&(c.appendChild(y),await f.render({canvasContext:x,viewport:g}).promise)}}catch(u){o||l((u==null?void 0:u.message)||"Could not render the preview")}finally{o||a(!1)}})(),()=>{o=!0})},[s,t]),e.jsxs("div",{className:"relative h-full overflow-y-auto bg-muted/40 p-4",children:[r&&e.jsx("div",{className:"absolute inset-0 z-10 flex items-center justify-center bg-background/70",children:e.jsx(us,{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 o7t({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}=Ls(),d=N.useRef(null),[u,h]=N.useState(!1),m=async f=>{if(!(!f||!c)){if(!f.type.startsWith("image/")){ie.error("Please choose an image file");return}if(f.size>20*1024*1024){ie.error("That photo is larger than 20 MB");return}h(!0);try{const g=await _bn(c.id,f,r);n(g),ie.success("Photo uploaded")}catch(g){ie.error((g==null?void 0:g.message)||"Upload failed")}finally{h(!1),d.current&&(d.current.value="")}}};return e.jsxs("div",{className:Ot("space-y-2",o),children:[e.jsx(re,{className:"text-xs",children:s}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:Ot("relative shrink-0 overflow-hidden border bg-muted",l?"h-16 w-16 rounded-full":"h-16 w-24 rounded-md"),children:t?e.jsx("img",{src:t,alt:s,className:"h-full w-full object-cover"}):e.jsx("div",{className:"flex h-full w-full items-center justify-center text-muted-foreground",children:e.jsx(pc,{className:"h-5 w-5"})})}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx("input",{ref:d,type:"file",accept:"image/*",className:"hidden",onChange:f=>{var g;return m((g=f.target.files)==null?void 0:g[0])}}),e.jsxs(B,{type:"button",variant:"outline",size:"sm",className:"gap-2",disabled:u,onClick:()=>{var f;return(f=d.current)==null?void 0:f.click()},children:[u?e.jsx(us,{className:"h-4 w-4 animate-spin"}):e.jsx(Gv,{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(hr,{className:"h-4 w-4"})," Remove"]})]})]}),e.jsx(we,{value:t||"",onChange:f=>n(f.target.value||null),placeholder:i}),a&&e.jsx("p",{className:"text-xs text-muted-foreground",children:a})]})}function Awn({value:s,onChange:t}){return e.jsxs(_e,{children:[e.jsxs(zt,{className:"pb-3",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Yn,{className:"h-4 w-4 text-muted-foreground"}),e.jsx(qt,{className:"text-base",children:"Co-listing agent"})]}),e.jsx(zn,{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(De,{className:"space-y-3",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(re,{children:"Name"}),e.jsx(we,{value:s.name,onChange:n=>t({name:n.target.value}),placeholder:"Jordan Ellis"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(re,{children:"Title"}),e.jsx(we,{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(re,{children:"Phone"}),e.jsx(we,{value:s.phone||"",onChange:n=>t({phone:n.target.value})})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(re,{children:"Email"}),e.jsx(we,{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(re,{children:"Brokerage"}),e.jsx(we,{value:s.brokerageName||"",onChange:n=>t({brokerageName:n.target.value})})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(re,{children:"License #"}),e.jsx(we,{value:s.licenseNumber||"",onChange:n=>t({licenseNumber:n.target.value})})]})]}),e.jsx(o7t,{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(re,{children:"Shared bio (optional)"}),e.jsx(Ws,{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 Twn({value:s,onChange:t}){return e.jsxs(_e,{children:[e.jsxs(zt,{className:"pb-3",children:[e.jsx(qt,{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(De,{className:"grid gap-2 sm:grid-cols-2",children:K7e.map(n=>{const r=n.id===s;return e.jsxs("button",{type:"button",onClick:()=>t(n.id),className:Ot("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(pa,{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 Ewn={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}]},Mwn=["cover","welcome","agent","overview","closing"];function Lwn({pages:s,onChange:t}){const n=new Set(s.hidden||[]),r=(i,l,o)=>{t({...s,copy:{...s.copy||{},[i]:{...(s.copy||{})[i]||{},[l]:o}}})},a=i=>{const l={...s.copy||{}};delete l[i],t({...s,copy:l})};return e.jsxs(_e,{children:[e.jsxs(zt,{className:"pb-3",children:[e.jsx(qt,{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(De,{children:e.jsx(qR,{type:"multiple",className:"w-full",children:Mwn.filter(i=>i==="cover"||!n.has(i)).map(i=>{const l=MDt(s,i);return e.jsxs($E,{value:i,children:[e.jsx(UE,{className:"text-sm",children:Exn[i]}),e.jsxs(qE,{className:"space-y-3 pt-1",children:[Ewn[i].map(o=>e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(re,{className:"text-xs",children:o.label}),o.long?e.jsx(Ws,{rows:2,value:l[o.key]||"",placeholder:C7e[i][o.key],onChange:c=>r(i,o.key,c.target.value)}):e.jsx(we,{value:l[o.key]||"",placeholder:C7e[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(hf,{className:"h-3.5 w-3.5"})," Reset to default wording"]})]})]},i)})})})]})}function Pwn({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,cWe(o,n.length)]),i=o=>t(n.filter(c=>c.id!==o).map((c,d)=>({...c,order:d}))),l=(o,c)=>{const d=n.findIndex(m=>m.id===o),u=d+c;if(d<0||u<0||u>=n.length)return;const h=[...n];[h[d],h[u]]=[h[u],h[d]],t(h.map((m,f)=>({...m,order:f})))};return e.jsxs(_e,{children:[e.jsxs(zt,{className:"pb-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(a3,{className:"h-4 w-4 text-muted-foreground"}),e.jsx(qt,{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(De,{className:"space-y-4",children:[e.jsx("div",{className:"grid gap-2 sm:grid-cols-2",children:oPe.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(nn,{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(Wl,{}),e.jsx(qR,{type:"multiple",className:"w-full",children:n.map((o,c)=>{var d,u,h;return e.jsxs($E,{value:o.id,children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(zn,{checked:o.enabled,onCheckedChange:m=>r(o.id,{enabled:m})}),e.jsx(UE,{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=oPe.find(m=>m.layout===o.layout))==null?void 0:u.name),e.jsx(We,{variant:"secondary",className:"text-[10px]",children:(h=oPe.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(Om,{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(Wf,{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(qn,{className:"h-3.5 w-3.5"})})]}),e.jsxs(qE,{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(re,{className:"text-xs",children:"Placement"}),e.jsxs(Ns,{value:o.placement,onValueChange:m=>r(o.id,{placement:m}),children:[e.jsx(ws,{children:e.jsx(ks,{})}),e.jsxs(js,{children:[e.jsx(nt,{value:"after-agent",children:'After "About your agent"'}),e.jsx(nt,{value:"end",children:"Before the closing page"})]})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(re,{className:"text-xs",children:"Style"}),e.jsxs("div",{className:"flex h-10 items-center gap-2 rounded-md border px-3",children:[e.jsx(zn,{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(re,{className:"text-xs",children:"Eyebrow"}),e.jsx(we,{value:o.kicker,onChange:m=>r(o.id,{kicker:m.target.value})})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(re,{className:"text-xs",children:"Headline"}),e.jsx(we,{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(re,{className:"text-xs",children:"Subhead"}),e.jsx(we,{value:o.subhead,onChange:m=>r(o.id,{subhead:m.target.value})})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(re,{className:"text-xs",children:"Body copy"}),e.jsx(Ws,{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(o7t,{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(re,{className:"text-xs",children:"Photo side"}),e.jsxs(Ns,{value:o.imageSide,onValueChange:m=>r(o.id,{imageSide:m}),children:[e.jsx(ws,{children:e.jsx(ks,{})}),e.jsxs(js,{children:[e.jsx(nt,{value:"right",children:"Right"}),e.jsx(nt,{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(re,{className:"text-xs uppercase tracking-wide text-muted-foreground",children:"List items"}),o.bullets.map((m,f)=>e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(we,{value:m,onChange:g=>{const y=[...o.bullets];y[f]=g.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((g,y)=>y!==f)}),children:e.jsx(qn,{className:"h-3.5 w-3.5"})})]},f)),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(nn,{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(re,{className:"text-xs uppercase tracking-wide text-muted-foreground",children:"Testimonials (up to 4)"}),o.testimonials.map((m,f)=>e.jsxs("div",{className:"space-y-2 rounded-md border bg-background p-3",children:[e.jsx(Ws,{rows:3,value:m.quote,placeholder:"Client quote",onChange:g=>{const y=[...o.testimonials];y[f]={...m,quote:g.target.value},r(o.id,{testimonials:y})}}),e.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[e.jsx(we,{value:m.name,placeholder:"Name",onChange:g=>{const y=[...o.testimonials];y[f]={...m,name:g.target.value},r(o.id,{testimonials:y})}}),e.jsx(we,{value:m.detail,placeholder:"Neighborhood or year",onChange:g=>{const y=[...o.testimonials];y[f]={...m,detail:g.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((g,y)=>y!==f)}),children:[e.jsx(qn,{className:"h-3.5 w-3.5"})," Remove"]})]},f)),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(nn,{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(re,{className:"text-xs uppercase tracking-wide text-muted-foreground",children:"Stats (up to 4)"}),o.stats.map((m,f)=>e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(we,{className:"w-28",value:m.value,placeholder:"27",onChange:g=>{const y=[...o.stats];y[f]={...m,value:g.target.value},r(o.id,{stats:y})}}),e.jsx(we,{value:m.label,placeholder:"Homes sold",onChange:g=>{const y=[...o.stats];y[f]={...m,label:g.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((g,y)=>y!==f)}),children:e.jsx(qn,{className:"h-3.5 w-3.5"})})]},f)),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(nn,{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 Iwn({open:s,onOpenChange:t,defaultName:n,saving:r,onSave:a}){const[i,l]=N.useState(""),[o,c]=N.useState("");return N.useEffect(()=>{s&&(l((n==null?void 0:n.trim())||"My listing presentation"),c(""))},[s,n]),e.jsx(Bs,{open:s,onOpenChange:t,children:e.jsxs(Fs,{className:"sm:max-w-md",children:[e.jsxs(qs,{children:[e.jsx($s,{children:"Save as a reusable template"}),e.jsx(Ar,{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(re,{children:"Template name"}),e.jsx(we,{value:i,onChange:d=>l(d.target.value),autoFocus:!0})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(re,{children:"Notes (optional)"}),e.jsx(Ws,{rows:2,value:o,onChange:d=>c(d.target.value),placeholder:"Luxury version with co-listing agent and testimonials"})]})]}),e.jsxs(Cr,{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(us,{className:"h-4 w-4 animate-spin"})," Save template"]})]})]})})}const _ft=["welcome","agent","overview","closing"],Dwn=()=>{const{id:s}=uo(),t=tr(),{user:n}=Ls(),{data:r}=EDt(),{data:a,isLoading:i,refetch:l}=Sxn(s),{update:o}=TDt(),{save:c}=ADt(),[d,u]=N.useState(null),[h,m]=N.useState(null),[f,g]=N.useState(E7e(null)),[y,x]=N.useState(LDt),[_,b]=N.useState([]),[k,A]=N.useState(A7e),[T,P]=N.useState(T7e),[I,M]=N.useState(null),[L,z]=N.useState(null),[$,V]=N.useState(!1),[W,G]=N.useState(!1),[X,te]=N.useState(null),[ne,me]=N.useState(!1),[ue,ce]=N.useState(!1),[ae,he]=N.useState(!1),[xe,ve]=N.useState(!1),[ge,be]=N.useState(!0),[Se,Ie]=N.useState(!1),Me=N.useRef(null);N.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 Ke=a.agent_snapshot;m({...r,...Ke||{}}),g(E7e(a.services)),x(PDt(a.co_agent)),b(DDt(a.custom_pages)),A(a.page_settings&&Object.keys(a.page_settings).length?a.page_settings:A7e),P(a.photo_focal||T7e),M(a.property_photo_path)},[a,r,d]),N.useEffect(()=>{let Ke=!1;return I?P5e(I).then(st=>{Ke||z(st)}):z(null),()=>{Ke=!0}},[I]);const Re=N.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:_,services:f,page_settings:k,photo_focal:T,property_photo_path:I},[a,d,h,y,_,f,k,T,I]),Be=Ke=>u(st=>st&&{...st,...Ke}),Ne=Ke=>m(st=>st&&{...st,...Ke}),Ge=Ke=>(k.hidden||[]).includes(Ke),Ce=(Ke,st)=>A(rt=>{const Ze=new Set(rt.hidden||[]);return st?Ze.delete(Ke):Ze.add(Ke),{...rt,hidden:Array.from(Ze)}}),Fe=f.filter(Ke=>Ke.enabled),Ae=1+_ft.filter(Ke=>!Ge(Ke)&&Ke!=="overview").length+(Ge("overview")?0:1)+Fe.filter(Ke=>Ke.key!=="communication").length+_.filter(Ke=>Ke.enabled).length,Xe=async(Ke=!1)=>{if(Re){ve(!0);try{await o.mutateAsync({id:Re.id,title:Re.title||"Untitled Presentation",property_address_line1:Re.property_address_line1,city:Re.city,state:Re.state,postal_code:Re.postal_code,list_price:Re.list_price,beds:Re.beds,baths:Re.baths,sqft:Re.sqft,agent_snapshot:Re.agent_snapshot,co_agent:Re.co_agent,custom_pages:Re.custom_pages,services:Re.services,page_settings:Re.page_settings,photo_focal:Re.photo_focal,property_photo_path:Re.property_photo_path}),Ke||ie.success("Presentation saved")}finally{ve(!1)}}},$e=async Ke=>{if(!(!n||!s)){if(!Ke.type.startsWith("image/")){ie.error("Please choose a JPG or PNG photo");return}if(Ke.size>25*1024*1024){ie.error("That photo is larger than 25 MB");return}V(!0);try{const st=await bbn(n.id,s,Ke);M(st);const rt=await P5e(st);z(rt?`${rt}${rt.includes("?")?"&":"?"}v=${Date.now()}`:null),await o.mutateAsync({id:s,property_photo_path:st}),ie.success("Photo uploaded")}catch(st){ie.error((st==null?void 0:st.message)||"Upload failed")}finally{V(!1)}}},Ye=async()=>{if(Re){me(!0);try{const Ke=await QRt(I5e(Re,r,L),Re.template_id,I);te(Ke)}catch(Ke){ie.error((Ke==null?void 0:Ke.message)||"Could not build the preview")}finally{me(!1)}}};N.useEffect(()=>{if(!ge||!Re)return;const Ke=setTimeout(()=>{Ye()},900);return()=>clearTimeout(Ke)},[ge,Re]);const Je=async()=>{if(!(!Re||!n)){if(!Re.property_photo_path){ie.error("Add the primary exterior photo before generating the PDF");return}ce(!0);try{await Xe(!0);const Ke=await JRt(I5e(Re,r,L),Re.template_id,"print",I);await eOt(n.id,Re.id,Ke),await l(),ie.success("Presentation downloaded")}catch(Ke){ie.error((Ke==null?void 0:Ke.message)||"Could not build the PDF")}finally{ce(!1)}}};return i||!d||!a?e.jsx(Qs,{children:e.jsxs("div",{className:"space-y-4",children:[e.jsx(xn,{className:"h-10 w-64"}),e.jsx(xn,{className:"h-[60vh] w-full rounded-xl"})]})}):e.jsxs(Qs,{children:[e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(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(we,{value:d.title,onChange:Ke=>Be({title:Ke.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 · ",Ae," pages"]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(B,{variant:"outline",onClick:()=>Xe(),disabled:xe,className:"gap-2",children:[xe?e.jsx(us,{className:"h-4 w-4 animate-spin"}):e.jsx(Kl,{className:"h-4 w-4"})," Save"]}),e.jsxs(B,{variant:"outline",onClick:()=>Ie(!0),className:"gap-2",children:[e.jsx(aD,{className:"h-4 w-4"})," Save as template"]}),e.jsxs(B,{variant:"outline",onClick:Ye,disabled:ne,className:"gap-2",children:[ne?e.jsx(us,{className:"h-4 w-4 animate-spin"}):e.jsx(da,{className:"h-4 w-4"})," Preview"]}),e.jsxs(B,{variant:"outline",onClick:async()=>{await Xe(!0),he(!0)},className:"gap-2",children:[e.jsx(mn,{className:"h-4 w-4"})," Email"]}),e.jsxs(B,{onClick:Je,disabled:ue,className:"gap-2",children:[ue?e.jsx(us,{className:"h-4 w-4 animate-spin"}):e.jsx(oi,{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(ya,{defaultValue:"property",className:"space-y-4",children:[e.jsxs(va,{className:"grid w-full grid-cols-4",children:[e.jsx(ls,{value:"property",children:"Property"}),e.jsx(ls,{value:"branding",children:"Branding"}),e.jsx(ls,{value:"plan",children:"Plan"}),e.jsx(ls,{value:"pages",children:"Pages"})]}),e.jsxs(_s,{value:"property",className:"space-y-4",children:[e.jsxs(_e,{children:[e.jsx(zt,{className:"pb-3",children:e.jsx(qt,{className:"text-base",children:"Property address"})}),e.jsxs(De,{className:"space-y-3",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(re,{children:"Street address"}),e.jsx(we,{value:d.addressLine1,onChange:Ke=>Be({addressLine1:Ke.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(re,{children:"City"}),e.jsx(we,{value:d.city,onChange:Ke=>Be({city:Ke.target.value})})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(re,{children:"State"}),e.jsx(we,{value:d.state,onChange:Ke=>Be({state:Ke.target.value})})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(re,{children:"ZIP"}),e.jsx(we,{value:d.postalCode,onChange:Ke=>Be({postalCode:Ke.target.value})})]}),e.jsx(Wl,{}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(re,{children:"List price (optional)"}),e.jsx(we,{inputMode:"numeric",value:d.listPrice,onChange:Ke=>Be({listPrice:Ke.target.value.replace(/[^0-9.]/g,"")}),placeholder:"649000"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(re,{children:"Square feet"}),e.jsx(we,{inputMode:"numeric",value:d.sqft,onChange:Ke=>Be({sqft:Ke.target.value.replace(/[^0-9]/g,"")})})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(re,{children:"Beds"}),e.jsx(we,{inputMode:"numeric",value:d.beds,onChange:Ke=>Be({beds:Ke.target.value.replace(/[^0-9.]/g,"")})})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(re,{children:"Baths"}),e.jsx(we,{inputMode:"numeric",value:d.baths,onChange:Ke=>Be({baths:Ke.target.value.replace(/[^0-9.]/g,"")})})]})]})]})]}),e.jsxs(_e,{children:[e.jsx(zt,{className:"pb-3",children:e.jsxs(qt,{className:"text-base",children:["Primary exterior photo ",e.jsx("span",{className:"text-destructive",children:"*"})]})}),e.jsxs(De,{className:"space-y-3",children:[e.jsx("div",{role:"button",tabIndex:0,onClick:()=>{var Ke;return(Ke=Me.current)==null?void 0:Ke.click()},onKeyDown:Ke=>{var st;return Ke.key==="Enter"&&((st=Me.current)==null?void 0:st.click())},onDragOver:Ke=>{Ke.preventDefault(),G(!0)},onDragLeave:()=>G(!1),onDrop:Ke=>{var rt;Ke.preventDefault(),G(!1);const st=(rt=Ke.dataTransfer.files)==null?void 0:rt[0];st&&$e(st)},className:Ot("relative flex h-48 w-full cursor-pointer items-center justify-center overflow-hidden rounded-lg border border-dashed bg-muted/40 transition-colors hover:bg-muted",W&&"border-primary bg-primary/10"),children:L?e.jsx("img",{src:L,alt:"Property exterior",className:"h-full w-full object-cover",style:{objectPosition:`${T.x*100}% ${T.y*100}%`}}):e.jsxs("div",{className:"flex flex-col items-center gap-2 text-muted-foreground",children:[$?e.jsx(us,{className:"h-6 w-6 animate-spin"}):e.jsx(Gv,{className:"h-6 w-6"}),e.jsx("span",{className:"text-sm",children:"Drag & drop the front exterior photo"}),e.jsx("span",{className:"text-xs",children:"or click to browse · JPG or PNG · landscape works best"})]})}),e.jsx("input",{ref:Me,type:"file",accept:"image/*",className:"hidden",onChange:Ke=>{var rt;const st=(rt=Ke.target.files)==null?void 0:rt[0];st&&$e(st),Ke.target.value=""}}),L&&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(oW,{className:"h-3.5 w-3.5"})," Reposition crop"]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(re,{className:"text-xs",children:"Horizontal"}),e.jsx(qf,{value:[T.x*100],min:0,max:100,step:1,onValueChange:([Ke])=>P(st=>({...st,x:Ke/100}))})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(re,{className:"text-xs",children:"Vertical"}),e.jsx(qf,{value:[T.y*100],min:0,max:100,step:1,onValueChange:([Ke])=>P(st=>({...st,y:Ke/100}))})]})]}),e.jsxs(B,{variant:"outline",size:"sm",className:"w-full gap-2",onClick:()=>{var Ke;return(Ke=Me.current)==null?void 0:Ke.click()},disabled:$,children:[e.jsx(oo,{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(_s,{value:"branding",className:"space-y-4",children:[e.jsx(Twn,{value:k.theme||R1n,onChange:Ke=>A(st=>({...st,theme:Ke}))}),e.jsxs(_e,{children:[e.jsx(zt,{className:"pb-3",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(qt,{className:"text-base",children:"Your details"}),e.jsx(We,{variant:"secondary",className:"text-[10px]",children:"Loaded from your LevelUp profile"})]})}),e.jsx(De,{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(re,{children:"Name"}),e.jsx(we,{value:h.name,onChange:Ke=>Ne({name:Ke.target.value})})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(re,{children:"Tagline"}),e.jsx(we,{value:h.tagline||"",onChange:Ke=>Ne({tagline:Ke.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(re,{children:"Phone"}),e.jsx(we,{value:h.phone||"",onChange:Ke=>Ne({phone:Ke.target.value})})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(re,{children:"Email"}),e.jsx(we,{value:h.email||"",onChange:Ke=>Ne({email:Ke.target.value})})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(re,{children:"Website"}),e.jsx(we,{value:h.website||"",onChange:Ke=>Ne({website:Ke.target.value})})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(re,{children:"Brokerage"}),e.jsx(we,{value:h.brokerageName||"",onChange:Ke=>Ne({brokerageName:Ke.target.value})})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(re,{children:"License #"}),e.jsx(we,{value:h.licenseNumber||"",onChange:Ke=>Ne({licenseNumber:Ke.target.value})})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(re,{children:"License state"}),e.jsx(we,{value:h.licenseState||"",onChange:Ke=>Ne({licenseState:Ke.target.value})})]})]}),e.jsx(Wl,{}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(re,{children:"Primary color"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("input",{type:"color",value:h.brandColor,onChange:Ke=>Ne({brandColor:Ke.target.value}),className:"h-9 w-12 cursor-pointer rounded border bg-transparent"}),e.jsx(we,{value:h.brandColor,onChange:Ke=>Ne({brandColor:Ke.target.value})})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(re,{children:"Accent color"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("input",{type:"color",value:h.accentColor,onChange:Ke=>Ne({accentColor:Ke.target.value}),className:"h-9 w-12 cursor-pointer rounded border bg-transparent"}),e.jsx(we,{value:h.accentColor,onChange:Ke=>Ne({accentColor:Ke.target.value})})]})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(re,{children:"Headshot URL"}),e.jsx(we,{value:h.headshotUrl||"",onChange:Ke=>Ne({headshotUrl:Ke.target.value}),placeholder:"Pulled from your profile photo"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(re,{children:"Brokerage logo URL"}),e.jsx(we,{value:h.brokerageLogoUrl||"",onChange:Ke=>Ne({brokerageLogoUrl:Ke.target.value})})]}),r&&e.jsxs(B,{variant:"outline",size:"sm",className:"w-full gap-2",onClick:()=>m({...r}),children:[e.jsx(oo,{className:"h-4 w-4"})," Reset to my LevelUp profile"]})]})})]}),e.jsx(Awn,{value:y,onChange:Ke=>x(st=>({...st,...Ke}))})]}),e.jsx(_s,{value:"plan",className:"space-y-4",children:e.jsxs(_e,{children:[e.jsxs(zt,{className:"pb-3",children:[e.jsx(qt,{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(De,{children:e.jsx(qR,{type:"multiple",className:"w-full",children:f.slice().sort((Ke,st)=>Ke.order-st.order).map(Ke=>{var st;return e.jsxs($E,{value:Ke.key,children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(zn,{checked:Ke.enabled,onCheckedChange:rt=>g(Ze=>Ze.map(ht=>ht.key===Ke.key?{...ht,enabled:rt}:ht))}),e.jsx(UE,{className:"flex-1 text-left text-sm",children:Ke.title})]}),e.jsxs(qE,{className:"space-y-3 pt-2",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(re,{children:"Headline"}),e.jsx(we,{value:Ke.title,onChange:rt=>g(Ze=>Ze.map(ht=>ht.key===Ke.key?{...ht,title:rt.target.value}:ht))})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(re,{children:"Description"}),e.jsx(Ws,{rows:4,value:Ke.body,onChange:rt=>g(Ze=>Ze.map(ht=>ht.key===Ke.key?{...ht,body:rt.target.value}:ht))})]}),!!((st=Ke.options)!=null&&st.length)&&e.jsxs("div",{className:"space-y-2 rounded-lg border bg-muted/30 p-3",children:[e.jsx(re,{className:"text-xs uppercase tracking-wide text-muted-foreground",children:"Included in this page"}),Ke.options.map(rt=>e.jsxs("label",{className:"flex items-start gap-2 text-sm",children:[e.jsx(Bi,{className:"mt-0.5",checked:rt.enabled,onCheckedChange:Ze=>g(ht=>ht.map(Bt=>{var Ct;return Bt.key===Ke.key?{...Bt,options:(Ct=Bt.options)==null?void 0:Ct.map(Yt=>Yt.key===rt.key?{...Yt,enabled:!!Ze}:Yt)}:Bt}))}),e.jsx("span",{className:"leading-snug",children:rt.label})]},rt.key))]})]})]},Ke.key)})})})]})}),e.jsxs(_s,{value:"pages",className:"space-y-4",children:[e.jsxs(_e,{children:[e.jsxs(zt,{className:"pb-3",children:[e.jsx(qt,{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(De,{className:"space-y-3",children:[_ft.map(Ke=>e.jsxs("div",{className:"flex items-center justify-between rounded-lg border p-3",children:[e.jsx("span",{className:"text-sm",children:Lxn[Ke]}),e.jsx(zn,{checked:!Ge(Ke),onCheckedChange:st=>Ce(Ke,st)})]},Ke)),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"}),!Ge("welcome")&&e.jsx("li",{children:"Marketing commitment"}),!Ge("agent")&&e.jsx("li",{children:"About your agent"}),_.filter(Ke=>Ke.enabled&&Ke.placement!=="end").sort((Ke,st)=>Ke.order-st.order).map(Ke=>e.jsx("li",{children:Ke.headline||"Custom page"},Ke.id)),!Ge("overview")&&e.jsx("li",{children:"Marketing plan overview"}),Fe.filter(Ke=>Ke.key!=="communication").map(Ke=>e.jsx("li",{children:Ke.title},Ke.key)),_.filter(Ke=>Ke.enabled&&Ke.placement==="end").sort((Ke,st)=>Ke.order-st.order).map(Ke=>e.jsx("li",{children:Ke.headline||"Custom page"},Ke.id)),!Ge("closing")&&e.jsx("li",{children:"Communication & closing commitment"})]})]})]})]}),e.jsx(Lwn,{pages:k,onChange:A}),e.jsxs(_e,{children:[e.jsxs(zt,{className:"pb-3",children:[e.jsx(qt,{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(De,{children:e.jsx(B,{variant:"outline",size:"sm",className:"w-full",onClick:()=>b(Ke=>[...Ke,{...cWe("testimonials",Ke.length),placement:"end"}]),children:`Add a "What they're saying" page`})})]}),e.jsx(Pwn,{pages:_,onChange:b})]})]}),e.jsxs(_e,{className:"min-h-[70vh] overflow-hidden",children:[e.jsxs(zt,{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(qt,{className:"text-base",children:"Live preview"}),e.jsxs("label",{className:"flex items-center gap-1.5 text-xs text-muted-foreground",children:[e.jsx(zn,{checked:ge,onCheckedChange:be}),"Auto-update"]})]}),e.jsxs(B,{variant:"ghost",size:"sm",onClick:Ye,disabled:ne,className:"gap-2",children:[ne?e.jsx(us,{className:"h-4 w-4 animate-spin"}):e.jsx(oo,{className:"h-4 w-4"}),"Refresh"]})]}),e.jsx(De,{className:"h-[calc(70vh-60px)] p-0",children:X?e.jsx(Cwn,{blob:X}):e.jsxs("div",{className:"flex h-full flex-col items-center justify-center gap-3 bg-muted/30 text-center",children:[e.jsx(da,{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:Ye,disabled:ne,className:"gap-2",children:[ne?e.jsx(us,{className:"h-4 w-4 animate-spin"}):e.jsx(da,{className:"h-4 w-4"}),"Generate preview"]})]})})]})]})]}),e.jsx(Iwn,{open:Se,onOpenChange:Ie,defaultName:d.title,saving:c.isPending,onSave:async(Ke,st)=>{await c.mutateAsync({name:Ke,description:st||null,template_id:a.template_id,agent_snapshot:h||{},co_agent:y,custom_pages:_,services:f,page_settings:k})}}),e.jsx(sOt,{open:ae,onOpenChange:he,row:Re,brand:r,photoUrl:L})]})};function Rwn(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 l7t="popby_geocode_cache_v1";function Own(){try{return JSON.parse(localStorage.getItem(l7t)||"{}")}catch{return{}}}function Fwn(s){try{localStorage.setItem(l7t,JSON.stringify(s))}catch{}}function zwn({contacts:s,onLogPopby:t}){const[n,r]=N.useState(null),[a,i]=N.useState("idle"),[l,o]=N.useState(5),[c,d]=N.useState(""),[u,h]=N.useState(new Map),[m,f]=N.useState(!1);N.useEffect(()=>{(async()=>{const{data:b}=await H.from("settings").select("value").eq("key","mapbox_public_token").maybeSingle();b!=null&&b.value&&d(b.value)})()},[]);const g=N.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})};N.useEffect(()=>{if(!c||!n||g.length===0)return;let b=!1;const k=Own(),A=new Map;g.forEach(P=>{const I=[P.address,P.city,P.state,P.zip].filter(Boolean).join("|").toLowerCase();k[I]&&A.set(P.id,k[I])}),h(new Map(A));const T=g.filter(P=>!([P.address,P.city,P.state,P.zip].filter(Boolean).join("|").toLowerCase()in k));if(T.length!==0)return f(!0),(async()=>{const P=[...T],I=async()=>{var M,L;for(;P.length&&!b;){const z=P.shift(),$=[z.address,z.city,z.state,z.zip].filter(Boolean),V=$.join("|").toLowerCase(),W=$.join(", ");try{const X=await(await fetch(`https://api.mapbox.com/geocoding/v5/mapbox.places/${encodeURIComponent(W)}.json?limit=1&access_token=${c}`)).json();if((L=(M=X==null?void 0:X.features)==null?void 0:M[0])!=null&&L.center){const[te,ne]=X.features[0].center;k[V]={lat:ne,lng:te},A.set(z.id,{lat:ne,lng:te})}else k[V]=null}catch{}}};await Promise.all([I(),I(),I(),I()]),b||(Fwn(k),h(new Map(A)),f(!1))})(),()=>{b=!0}},[c,n,g]);const x=N.useMemo(()=>{if(!n)return[];const b=[];return g.forEach(k=>{const A=u.get(k.id);if(!A)return;const T=Rwn(n.lat,n.lng,A.lat,A.lng);T<=l&&b.push({...k,distanceMiles:T,lat:A.lat,lng:A.lng})}),b.sort((k,A)=>k.distanceMiles-A.distanceMiles)},[n,g,u,l]),_=b=>{const A=/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(A,"_blank","noopener")};return e.jsxs(_e,{className:"border-primary/30 bg-gradient-to-br from-primary/5 to-transparent",children:[e.jsx(zt,{className:"pb-3",children:e.jsxs("div",{className:"flex items-start justify-between gap-3 flex-wrap",children:[e.jsxs("div",{children:[e.jsxs(qt,{className:"flex items-center gap-2 text-lg",children:[e.jsx(f9,{className:"h-5 w-5 text-primary"}),"Nearby Now"]}),e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:"Due contacts within driving distance — perfect for errand-day pop-bys."})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(Ns,{value:String(l),onValueChange:b=>o(Number(b)),children:[e.jsx(ws,{className:"w-[110px] h-9",children:e.jsx(ks,{})}),e.jsxs(js,{children:[e.jsx(nt,{value:"2",children:"2 miles"}),e.jsx(nt,{value:"5",children:"5 miles"}),e.jsx(nt,{value:"10",children:"10 miles"}),e.jsx(nt,{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(oo,{className:"h-4 w-4 mr-1 animate-spin"}):e.jsx(f9,{className:"h-4 w-4 mr-1"}),a==="ok"?"Refresh":"Use my location"]})]})]})}),e.jsxs(De,{className:"space-y-3",children:[a==="idle"&&e.jsxs("div",{className:"text-center py-6 text-sm text-muted-foreground",children:[e.jsx(ii,{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(Uo,{className:"h-6 w-6"}),"Location access was blocked. Enable it in your browser to use Nearby Now."]}),a==="unavailable"&&e.jsx("div",{className:"text-center py-6 text-sm text-muted-foreground",children:"Geolocation isn't available on this device."}),a==="ok"&&!c&&e.jsx("div",{className:"text-center py-6 text-sm text-muted-foreground",children:"Mapping isn't configured yet — ask an admin to add the Mapbox token."}),a==="ok"&&c&&g.length===0&&e.jsx("div",{className:"text-center py-6 text-sm text-muted-foreground",children:"No due contacts have addresses yet. Add street addresses to your sphere to power this."}),a==="ok"&&c&&g.length>0&&m&&x.length===0&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(xn,{className:"h-14 w-full"}),e.jsx(xn,{className:"h-14 w-full"}),e.jsx("p",{className:"text-xs text-muted-foreground text-center",children:"Locating contacts…"})]}),a==="ok"&&c&&!m&&x.length===0&&g.length>0&&e.jsxs("div",{className:"text-center py-6 text-sm text-muted-foreground",children:["No due contacts within ",l," miles. Try widening the radius."]}),x.length>0&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs(We,{variant:"secondary",className:"font-medium",children:[x.length," nearby"]}),m&&e.jsxs("span",{className:"text-xs text-muted-foreground flex items-center gap-1",children:[e.jsx(oo,{className:"h-3 w-3 animate-spin"})," still locating…"]})]}),e.jsx("div",{className:"space-y-2",children:x.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(We,{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(We,{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(ga,{className:"h-4 w-4"})})}),e.jsx(B,{size:"icon",variant:"ghost",onClick:()=>_(b),className:"h-9 w-9",title:"Directions",children:e.jsx(lW,{className:"h-4 w-4"})}),e.jsxs(B,{size:"sm",onClick:()=>t(b),children:[e.jsx(Io,{className:"h-4 w-4 mr-1"}),"Log"]})]})]},b.id))})]})]})]})}const Bwn="0dde5abb-0005-4c8c-a471-30d0cbc9e280",$wn=[{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 Uwn(){const s=tr(),t=sIt(),{data:n}=ymn(),{data:r}=K_(),{data:a}=dGe(),{data:i}=UCe(90),{data:l}=Wy(),o=jmn(),c=_mn(),d=bmn(),u=wmn(),{data:h=[],isLoading:m}=mt({queryKey:["popby-templates"],queryFn:async()=>{const{data:X,error:te}=await H.from("canva_templates").select(` *, category:template_categories(id, name), type:template_types(id, name) `).eq("category_id",Bwn).order("publish_date",{ascending:!1});if(te)throw te;const{data:ne}=await H.from("template_likes").select("template_id"),{data:me}=await H.from("template_comments").select("template_id"),ue=new Map;ne==null||ne.forEach(ae=>{ue.set(ae.template_id,(ue.get(ae.template_id)||0)+1)});const ce=new Map;return me==null||me.forEach(ae=>{ce.set(ae.template_id,(ce.get(ae.template_id)||0)+1)}),(X||[]).map(ae=>({...ae,likesCount:ue.get(ae.id)||0,commentsCount:ce.get(ae.id)||0}))}}),f=X=>{const te=l==null?void 0:l.find(ne=>ne.id===X);return te?`${te.first_name} ${te.last_name||""}`.trim():"Unknown"},g=X=>{if(!X)return null;const te=n==null?void 0:n.find(ne=>ne.id===X);return(te==null?void 0:te.name)||null},[y,x]=N.useState(null),[_,b]=N.useState(!1),[k,A]=N.useState(!1),[T,P]=N.useState(!1),[I,M]=N.useState({popby_item_id:"",notes:""}),[L,z]=N.useState({name:"",description:""}),$=async()=>{y&&(await c.mutateAsync({contact_id:y.id,popby_item_id:I.popby_item_id||void 0,notes:I.notes||void 0}),b(!1),x(null),M({popby_item_id:"",notes:""}))},V=async()=>{L.name.trim()&&(await d.mutateAsync({name:L.name.trim(),description:L.description.trim()||void 0}),P(!1),z({name:"",description:""}))},W=async(X,te)=>{await u.mutateAsync({relationship_type_id:X,frequency_days:parseInt(te)})},G=X=>{var ne;const te=a==null?void 0:a.find(me=>me.relationship_type_id===X);return((ne=te==null?void 0:te.frequency_days)==null?void 0:ne.toString())||"90"};return e.jsx(Qs,{title:"Popbys",description:"Drop off gifts to stay top of mind",children:e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("h1",{className:"text-2xl font-bold",children:"Popbys"}),e.jsx("span",{className:"text-[10px] font-semibold uppercase tracking-wide px-1.5 py-0.5 rounded border border-amber-500 text-amber-600 dark:text-amber-400 bg-amber-500/10",children:"Beta"})]}),e.jsxs("div",{className:"grid grid-cols-3 gap-4",children:[e.jsx(_e,{children:e.jsxs(De,{className:"p-4 text-center",children:[e.jsx("div",{className:"text-3xl font-bold text-primary",children:o.thisWeekCount}),e.jsx("div",{className:"text-sm text-muted-foreground",children:"This Week"})]})}),e.jsx(_e,{children:e.jsxs(De,{className:"p-4 text-center",children:[e.jsx("div",{className:"text-3xl font-bold text-emerald-500",children:o.thisMonthCount}),e.jsx("div",{className:"text-sm text-muted-foreground",children:"This Month"})]})}),e.jsx(_e,{children:e.jsxs(De,{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(ii,{className:"h-4 w-4 mr-2"}),"View Map"]}),e.jsxs(B,{variant:"outline",onClick:()=>A(!0),children:[e.jsx(sc,{className:"h-4 w-4 mr-2"}),"Frequency Settings"]}),e.jsxs(B,{variant:"outline",onClick:()=>P(!0),children:[e.jsx(nn,{className:"h-4 w-4 mr-2"}),"Add Popby Idea"]})]}),e.jsxs(ya,{defaultValue:"due",children:[e.jsxs(va,{children:[e.jsx(ls,{value:"due",children:"Due for Popby"}),e.jsx(ls,{value:"activity",children:"Recent Activity"}),e.jsx(ls,{value:"library",children:"Popby Library"}),e.jsx(ls,{value:"templates",children:"Popby Templates"})]}),e.jsxs(_s,{value:"due",className:"space-y-4 mt-4",children:[e.jsx(zwn,{contacts:t||[],onLogPopby:X=>{x(X),b(!0)}}),!t||t.length===0?e.jsx(_e,{children:e.jsxs(De,{className:"p-8 text-center text-muted-foreground",children:[e.jsx(Io,{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(X=>e.jsx(_e,{className:"hover:shadow-md transition-shadow",children:e.jsx(De,{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:[X.first_name," ",X.last_name]}),X.daysOverdue>0&&e.jsxs(We,{variant:"destructive",className:"text-xs",children:[X.daysOverdue,"+ days overdue"]}),X.daysSinceLastPopby===null&&e.jsx(We,{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:[X.address&&e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(ii,{className:"h-3 w-3"}),X.city||X.address]}),X.tags&&X.tags.length>0&&e.jsx("span",{children:X.tags.map(te=>{var ne;return(ne=te.relationship_type)==null?void 0:ne.name}).join(", ")})]}),X.lastPopby&&e.jsxs("p",{className:"text-xs text-muted-foreground mt-1",children:["Last popby: ",Js(new Date(X.lastPopby),"MMM d, yyyy")]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[X.phone&&e.jsx(B,{size:"sm",variant:"ghost",asChild:!0,children:e.jsx("a",{href:`tel:${X.phone}`,children:e.jsx(ga,{className:"h-4 w-4"})})}),e.jsxs(B,{size:"sm",onClick:()=>{x(X),b(!0)},children:[e.jsx(Po,{className:"h-4 w-4 mr-1"}),"Log Popby"]})]})]})})},X.id))})]}),e.jsx(_s,{value:"activity",className:"space-y-4 mt-4",children:!i||i.length===0?e.jsx(_e,{children:e.jsxs(De,{className:"p-8 text-center text-muted-foreground",children:[e.jsx(Xr,{className:"h-12 w-12 mx-auto mb-4 opacity-50"}),e.jsx("p",{children:"No popby activity yet!"}),e.jsx("p",{className:"text-sm mt-1",children:"Start logging popbys to see your history here."})]})}):e.jsxs(_e,{children:[e.jsx(zt,{children:e.jsx(qt,{className:"text-lg",children:"Recent Popby Log"})}),e.jsx(De,{className:"space-y-3",children:i.map(X=>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(Io,{className:"h-5 w-5 text-orange-500"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsx("span",{className:"font-medium",children:f(X.contact_id)}),g(X.popby_item_id)&&e.jsx(We,{variant:"secondary",className:"text-xs",children:g(X.popby_item_id)})]}),e.jsx("div",{className:"text-sm text-muted-foreground",children:Js(new Date(X.completed_at),"MMM d, yyyy h:mm a")}),X.notes&&e.jsx("p",{className:"text-sm text-muted-foreground mt-1 line-clamp-2",children:X.notes})]})]},X.id))})]})}),e.jsx(_s,{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(X=>e.jsx(_e,{children:e.jsx(De,{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(Io,{className:"h-5 w-5 text-primary"})}),e.jsxs("div",{className:"flex-1",children:[e.jsx("h3",{className:"font-medium",children:X.name}),X.description&&e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:X.description}),!X.owner_user_id&&e.jsx(We,{variant:"secondary",className:"mt-2 text-xs",children:"Shared"})]})]})})},X.id)),e.jsx(_e,{className:"border-dashed cursor-pointer hover:bg-muted/50 transition-colors",onClick:()=>P(!0),children:e.jsx(De,{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(nn,{className:"h-8 w-8 mx-auto mb-2"}),e.jsx("p",{children:"Add New Popby Idea"})]})})})]})}),e.jsxs(_s,{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((X,te)=>e.jsx(_e,{children:e.jsxs(De,{className:"p-4",children:[e.jsx(xn,{className:"aspect-[3/2] w-full rounded-lg mb-4"}),e.jsx(xn,{className:"h-5 w-3/4 mb-2"}),e.jsx(xn,{className:"h-4 w-full mb-4"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(xn,{className:"h-5 w-16"}),e.jsx(xn,{className:"h-5 w-20"})]})]})},te))}),!m&&h.length===0&&e.jsx(_e,{children:e.jsxs(De,{className:"p-8 text-center text-muted-foreground",children:[e.jsx(Ku,{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(X=>e.jsxs(_e,{className:"group overflow-hidden hover:shadow-lg transition-all duration-200 cursor-pointer",onClick:()=>s(`/templates/${X.id}`),children:[e.jsx("div",{className:"relative overflow-hidden bg-muted aspect-[3/2]",children:X.preview_image_url?e.jsx("img",{src:X.preview_image_url,alt:X.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(De,{className:"p-4 flex flex-col",children:[e.jsx("h3",{className:"font-semibold text-foreground line-clamp-1 mb-1",children:X.name}),X.description&&e.jsx("p",{className:"text-sm text-muted-foreground line-clamp-2 mb-3 flex-1",children:eY(X.description)}),e.jsx("div",{className:"flex flex-wrap gap-2 mb-3",children:e.jsx(We,{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(ax,{className:"h-3.5 w-3.5"}),X.likesCount]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Ud,{className:"h-3.5 w-3.5"}),X.commentsCount]})]}),e.jsxs(B,{size:"sm",className:"w-full gap-2",onClick:te=>{te.stopPropagation(),s(`/templates/${X.id}`)},children:[e.jsx(Tr,{className:"h-4 w-4"}),"View Template"]})]})]},X.id))})]})]}),e.jsx(Bs,{open:_,onOpenChange:b,children:e.jsxs(Fs,{children:[e.jsx(qs,{children:e.jsxs($s,{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(re,{children:"Popby Item (optional)"}),e.jsxs(Ns,{value:I.popby_item_id,onValueChange:X=>M(te=>({...te,popby_item_id:X})),children:[e.jsx(ws,{children:e.jsx(ks,{placeholder:"Select a popby item..."})}),e.jsx(js,{children:n==null?void 0:n.map(X=>e.jsx(nt,{value:X.id,children:X.name},X.id))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{children:"Notes (optional)"}),e.jsx(Ws,{placeholder:"Any notes about this popby...",value:I.notes,onChange:X=>M(te=>({...te,notes:X.target.value}))})]})]}),e.jsxs(Cr,{children:[e.jsx(B,{variant:"outline",onClick:()=>b(!1),children:"Cancel"}),e.jsx(B,{onClick:$,disabled:c.isPending,children:"Log Popby"})]})]})}),e.jsx(Bs,{open:k,onOpenChange:A,children:e.jsxs(Fs,{className:"max-w-md",children:[e.jsx(qs,{children:e.jsx($s,{children:"Popby Frequency Settings"})}),e.jsxs("div",{className:"space-y-4 py-4",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Set default popby frequency for each relationship type. You can override these per-contact."}),r==null?void 0:r.map(X=>e.jsxs("div",{className:"flex items-center justify-between gap-4",children:[e.jsx(re,{className:"font-medium",children:X.name}),e.jsxs(Ns,{value:G(X.id),onValueChange:te=>W(X.id,te),children:[e.jsx(ws,{className:"w-[180px]",children:e.jsx(ks,{})}),e.jsx(js,{children:$wn.map(te=>e.jsx(nt,{value:te.value,children:te.label},te.value))})]})]},X.id))]}),e.jsx(Cr,{children:e.jsx(B,{onClick:()=>A(!1),children:"Done"})})]})}),e.jsx(Bs,{open:T,onOpenChange:P,children:e.jsxs(Fs,{children:[e.jsx(qs,{children:e.jsx($s,{children:"Add Popby Idea"})}),e.jsxs("div",{className:"space-y-4 py-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{children:"Name *"}),e.jsx(we,{placeholder:"e.g., Homemade cookies",value:L.name,onChange:X=>z(te=>({...te,name:X.target.value}))})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{children:"Description"}),e.jsx(Ws,{placeholder:"Optional description...",value:L.description,onChange:X=>z(te=>({...te,description:X.target.value}))})]})]}),e.jsxs(Cr,{children:[e.jsx(B,{variant:"outline",onClick:()=>P(!1),children:"Cancel"}),e.jsx(B,{onClick:V,disabled:!L.name.trim()||d.isPending,children:"Add Item"})]})]})})]})})}const qwn=H5({property_address:pl().min(1,"Property address is required"),city:pl().optional(),state:pl().optional(),zip:pl().optional(),transaction_type:dUe(["buyer","seller"]),close_date:pl().min(1,"Close date is required"),sale_price:UW().min(0,"Sale price must be positive"),commission_amount:UW().optional(),lead_source_id:pl().optional(),client_type_id:pl().optional(),contact_id:pl().optional(),notes:pl().optional(),is_win:_ps()});function c7t({open:s,onOpenChange:t,transaction:n}){const[r,a]=N.useState(!1),[i,l]=N.useState(""),[o,c]=N.useState(!1),[d,u]=N.useState(""),h=t3e(),m=r2s(),{data:f}=$R(),{data:g}=K_(),{data:y}=Wy(),x=e3e(),_=pqe(),{data:b}=s3e(),k=(b==null?void 0:b.show_commission)??!0,A=W4e({resolver:K4e(qwn),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}});N.useEffect(()=>{n?A.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}):A.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,A]);const T=async L=>{const z={property_address:L.property_address,transaction_type:L.transaction_type,close_date:L.close_date,sale_price:L.sale_price,is_win:L.is_win,commission_amount:L.commission_amount||null,lead_source_id:L.lead_source_id||null,client_type_id:L.client_type_id||null,contact_id:L.contact_id||null,city:L.city||null,state:L.state||null,zip:L.zip||null,notes:L.notes||null};n?await m.mutateAsync({id:n.id,...z}):await h.mutateAsync(z),t(!1)},P=async()=>{if(!i.trim())return;const[L,...z]=i.trim().split(" "),$=z.join(" ")||null,V=await x.mutateAsync({first_name:L,last_name:$,tagIds:[]});V&&(A.setValue("contact_id",V.id),l(""),c(!1),a(!1))},I=async()=>{if(!d.trim())return;const L=await _.mutateAsync(d.trim());L&&(A.setValue("lead_source_id",L.id),u(""))},M=y==null?void 0:y.find(L=>L.id===A.watch("contact_id"));return e.jsx(Bs,{open:s,onOpenChange:t,children:e.jsxs(Fs,{className:"max-w-lg max-h-[90vh]",children:[e.jsx(qs,{children:e.jsx($s,{children:n?"Edit Transaction":"Add Transaction"})}),e.jsx(lo,{className:"max-h-[70vh] pr-4",children:e.jsx(Y4e,{...A,children:e.jsxs("form",{onSubmit:A.handleSubmit(T),className:"space-y-4",children:[e.jsx(gp,{control:A.control,name:"property_address",render:({field:L})=>e.jsxs(Mm,{children:[e.jsx(Lm,{children:"Property Address *"}),e.jsx(Pm,{children:e.jsx(we,{placeholder:"123 Main St",...L})}),e.jsx(Ov,{})]})}),e.jsxs("div",{className:"grid grid-cols-3 gap-2",children:[e.jsx(gp,{control:A.control,name:"city",render:({field:L})=>e.jsxs(Mm,{children:[e.jsx(Lm,{children:"City"}),e.jsx(Pm,{children:e.jsx(we,{placeholder:"City",...L})})]})}),e.jsx(gp,{control:A.control,name:"state",render:({field:L})=>e.jsxs(Mm,{children:[e.jsx(Lm,{children:"State"}),e.jsx(Pm,{children:e.jsx(we,{placeholder:"TX",...L})})]})}),e.jsx(gp,{control:A.control,name:"zip",render:({field:L})=>e.jsxs(Mm,{children:[e.jsx(Lm,{children:"Zip"}),e.jsx(Pm,{children:e.jsx(we,{placeholder:"75001",...L})})]})})]}),e.jsx(gp,{control:A.control,name:"transaction_type",render:({field:L})=>e.jsxs(Mm,{children:[e.jsx(Lm,{children:"Transaction Type *"}),e.jsxs(Ns,{onValueChange:L.onChange,value:L.value,children:[e.jsx(Pm,{children:e.jsx(ws,{children:e.jsx(ks,{placeholder:"Select type"})})}),e.jsxs(js,{children:[e.jsx(nt,{value:"buyer",children:"Buyer"}),e.jsx(nt,{value:"seller",children:"Seller"})]})]}),e.jsx(Ov,{})]})}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsx(gp,{control:A.control,name:"close_date",render:({field:L})=>e.jsxs(Mm,{children:[e.jsx(Lm,{children:"Close Date *"}),e.jsx(Pm,{children:e.jsx(we,{type:"date",...L})}),e.jsx(Ov,{})]})}),e.jsx(gp,{control:A.control,name:"sale_price",render:({field:L})=>e.jsxs(Mm,{children:[e.jsx(Lm,{children:"Sale Price *"}),e.jsx(Pm,{children:e.jsx(we,{type:"number",placeholder:"0",...L,onChange:z=>L.onChange(Number(z.target.value))})}),e.jsx(Ov,{})]})})]}),k&&e.jsx(gp,{control:A.control,name:"commission_amount",render:({field:L})=>e.jsxs(Mm,{children:[e.jsx(Lm,{children:"Commission"}),e.jsx(Pm,{children:e.jsx(we,{type:"number",placeholder:"0",...L,value:L.value??"",onChange:z=>L.onChange(z.target.value?Number(z.target.value):void 0)})})]})}),e.jsx(gp,{control:A.control,name:"lead_source_id",render:({field:L})=>e.jsxs(Mm,{children:[e.jsx(Lm,{children:"Lead Source"}),e.jsxs(Ns,{onValueChange:L.onChange,value:L.value||"",children:[e.jsx(Pm,{children:e.jsx(ws,{children:e.jsx(ks,{placeholder:"Select source"})})}),e.jsx(js,{children:f==null?void 0:f.map(z=>e.jsx(nt,{value:z.id,children:z.name},z.id))})]})]})}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(we,{placeholder:"Add custom source...",value:d,onChange:L=>u(L.target.value),className:"flex-1"}),e.jsx(B,{type:"button",variant:"outline",size:"icon",onClick:I,disabled:!d.trim(),children:e.jsx(nn,{className:"h-4 w-4"})})]}),e.jsx(gp,{control:A.control,name:"client_type_id",render:({field:L})=>e.jsxs(Mm,{children:[e.jsx(Lm,{children:"Client Type"}),e.jsxs(Ns,{onValueChange:L.onChange,value:L.value||"",children:[e.jsx(Pm,{children:e.jsx(ws,{children:e.jsx(ks,{placeholder:"Select client type"})})}),e.jsx(js,{children:g==null?void 0:g.map(z=>e.jsx(nt,{value:z.id,children:z.name},z.id))})]})]})}),e.jsx(gp,{control:A.control,name:"contact_id",render:({field:L})=>e.jsxs(Mm,{children:[e.jsx(Lm,{children:"Client Contact"}),e.jsxs(rc,{open:r,onOpenChange:a,children:[e.jsx(ac,{asChild:!0,children:e.jsx(Pm,{children:e.jsxs(B,{variant:"outline",role:"combobox",className:Ot("w-full justify-between",!L.value&&"text-muted-foreground"),children:[M?`${M.first_name} ${M.last_name||""}`.trim():"Select contact",e.jsx(sb,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]})})}),e.jsxs(Zl,{className:"w-full p-0",align:"start",children:[e.jsxs(db,{children:[e.jsx(ub,{placeholder:"Search contacts..."}),e.jsxs(hb,{children:[e.jsx(mb,{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(nn,{className:"h-4 w-4 mr-2"}),"Add New Contact"]})]})}),e.jsx(pb,{children:y==null?void 0:y.map(z=>e.jsxs(Ry,{value:`${z.first_name} ${z.last_name||""}`,onSelect:()=>{L.onChange(z.id),a(!1)},children:[e.jsx(pa,{className:Ot("mr-2 h-4 w-4",z.id===L.value?"opacity-100":"opacity-0")}),z.first_name," ",z.last_name||""]},z.id))})]})]}),o&&e.jsxs("div",{className:"p-2 border-t space-y-2",children:[e.jsx(we,{placeholder:"Enter contact name...",value:i,onChange:z=>l(z.target.value)}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(B,{size:"sm",onClick:P,disabled:!i.trim()||x.isPending,children:"Add Contact"}),e.jsx(B,{size:"sm",variant:"outline",onClick:()=>{c(!1),l("")},children:"Cancel"})]})]})]})]})]})}),e.jsx(gp,{control:A.control,name:"notes",render:({field:L})=>e.jsxs(Mm,{children:[e.jsx(Lm,{children:"Notes"}),e.jsx(Pm,{children:e.jsx(Ws,{placeholder:"Any notes about this transaction...",...L})})]})}),e.jsx(gp,{control:A.control,name:"is_win",render:({field:L})=>e.jsxs(Mm,{className:"flex items-center justify-between rounded-lg border p-3",children:[e.jsxs("div",{className:"space-y-0.5",children:[e.jsx(Lm,{children:"Mark as Win 🏆"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Highlight this as a notable success"})]}),e.jsx(Pm,{children:e.jsx(zn,{checked:L.value,onCheckedChange:L.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 zWe({transactions:s,showCommission:t,isLoading:n,agentNameMap:r,readOnly:a}){const[i,l]=N.useState(null),[o,c]=N.useState(null),[d,u]=N.useState(""),[h,m]=N.useState("all"),[f,g]=N.useState("all"),[y,x]=N.useState("all"),[_,b]=N.useState(!1),k=a2s(),A=t3e(),{data:T}=$R();K_();const P=qU(),I=z=>{const{id:$,created_at:V,updated_at:W,lead_source:G,client_type:X,contact:te,...ne}=z;A.mutate(ne)},M=()=>{o&&(k.mutate(o),c(null))},L=s.filter(z=>{var te,ne,me,ue;const $=d===""||z.property_address.toLowerCase().includes(d.toLowerCase())||((ne=(te=z.contact)==null?void 0:te.first_name)==null?void 0:ne.toLowerCase().includes(d.toLowerCase()))||((ue=(me=z.contact)==null?void 0:me.last_name)==null?void 0:ue.toLowerCase().includes(d.toLowerCase())),V=h==="all"||z.transaction_type===h,W=f==="all"||z.lead_source_id===f,G=y==="all"||z.client_type_id===y,X=!_||z.is_win;return $&&V&&W&&G&&X});return n?e.jsx(_e,{children:e.jsx(De,{className:"p-6 space-y-4",children:[1,2,3].map(z=>e.jsx(xn,{className:"h-16 w-full"},z))})}):e.jsxs(e.Fragment,{children:[e.jsxs(_e,{children:[e.jsx(zt,{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(qt,{children:["Transactions (",L.length,")"]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsxs("div",{className:"relative",children:[e.jsx(Gr,{className:"absolute left-2.5 top-2.5 h-4 w-4 text-muted-foreground"}),e.jsx(we,{placeholder:"Search...",value:d,onChange:z=>u(z.target.value),className:"pl-8 w-[150px]"})]}),e.jsxs(Ns,{value:h,onValueChange:m,children:[e.jsx(ws,{className:"w-[100px]",children:e.jsx(ks,{placeholder:"Type"})}),e.jsxs(js,{children:[e.jsx(nt,{value:"all",children:"All Types"}),e.jsx(nt,{value:"buyer",children:"Buyer"}),e.jsx(nt,{value:"seller",children:"Seller"})]})]}),e.jsxs(Ns,{value:f,onValueChange:g,children:[e.jsx(ws,{className:"w-[130px]",children:e.jsx(ks,{placeholder:"Lead Source"})}),e.jsxs(js,{children:[e.jsx(nt,{value:"all",children:"All Sources"}),T==null?void 0:T.map(z=>e.jsx(nt,{value:z.id,children:z.name},z.id))]})]}),e.jsxs(B,{variant:_?"default":"outline",size:"sm",onClick:()=>b(!_),children:[e.jsx(ku,{className:"h-4 w-4 mr-1"}),"Wins"]})]})]})}),e.jsx(De,{children:L.length===0?e.jsx("p",{className:"text-center text-muted-foreground py-8",children:"No transactions found"}):P?e.jsx("div",{className:"space-y-3",children:L.map(z=>e.jsxs(_e,{className:"p-4",children:[e.jsxs("div",{className:"flex items-start justify-between gap-2",children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[e.jsx("span",{className:"font-medium truncate",children:z.property_address}),z.is_win&&e.jsx(ku,{className:"h-4 w-4 text-yellow-500 flex-shrink-0"})]}),e.jsxs("div",{className:"text-sm text-muted-foreground",children:[z.city,z.state?`, ${z.state}`:""]})]}),e.jsx(We,{variant:z.transaction_type==="buyer"?"default":"secondary",children:z.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: "}),Cet(z.close_date)]}),e.jsxs("div",{children:[e.jsx("span",{className:"text-muted-foreground",children:"Price: "}),_u(z.sale_price)]}),t&&z.commission_amount&&e.jsxs("div",{children:[e.jsx("span",{className:"text-muted-foreground",children:"Commission: "}),_u(z.commission_amount)]}),z.lead_source&&e.jsxs("div",{children:[e.jsx("span",{className:"text-muted-foreground",children:"Source: "}),z.lead_source.name]}),z.contact&&e.jsxs("div",{className:"col-span-2",children:[e.jsx("span",{className:"text-muted-foreground",children:"Client: "}),z.contact.first_name," ",z.contact.last_name]}),r&&e.jsxs("div",{className:"col-span-2",children:[e.jsx("span",{className:"text-muted-foreground",children:"Agent: "}),r[z.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(z),children:e.jsx(xp,{className:"h-4 w-4"})}),e.jsx(B,{variant:"ghost",size:"sm",onClick:()=>I(z),children:e.jsx(Pa,{className:"h-4 w-4"})}),e.jsx(B,{variant:"ghost",size:"sm",onClick:()=>c(z.id),children:e.jsx(qn,{className:"h-4 w-4 text-destructive"})})]})]},z.id))}):e.jsx("div",{className:"overflow-x-auto",children:e.jsxs(Oa,{children:[e.jsx(Fa,{children:e.jsxs(un,{children:[r&&e.jsx(Mt,{children:"Agent"}),e.jsx(Mt,{children:"Property"}),e.jsx(Mt,{children:"Type"}),e.jsx(Mt,{children:"Close Date"}),e.jsx(Mt,{children:"Sale Price"}),t&&e.jsx(Mt,{children:"Commission"}),e.jsx(Mt,{children:"Lead Source"}),e.jsx(Mt,{children:"Client"}),!a&&e.jsx(Mt,{className:"w-[50px]"})]})}),e.jsx(za,{children:L.map(z=>{var $;return e.jsxs(un,{children:[r&&e.jsx(gt,{className:"font-medium text-sm",children:r[z.owner_user_id]||"Unknown"}),e.jsx(gt,{children:e.jsxs("div",{className:"flex items-center gap-2",children:[z.is_win&&e.jsx(ku,{className:"h-4 w-4 text-yellow-500"}),e.jsxs("div",{children:[e.jsx("div",{className:"font-medium",children:z.property_address}),e.jsxs("div",{className:"text-sm text-muted-foreground",children:[z.city,z.state?`, ${z.state}`:""]})]})]})}),e.jsx(gt,{children:e.jsx(We,{variant:z.transaction_type==="buyer"?"default":"secondary",children:z.transaction_type})}),e.jsx(gt,{children:Cet(z.close_date)}),e.jsx(gt,{children:_u(z.sale_price)}),t&&e.jsx(gt,{children:z.commission_amount?_u(z.commission_amount):"-"}),e.jsx(gt,{children:(($=z.lead_source)==null?void 0:$.name)||"-"}),e.jsx(gt,{children:z.contact?`${z.contact.first_name} ${z.contact.last_name||""}`.trim():"-"}),!a&&e.jsx(gt,{children:e.jsxs(qd,{children:[e.jsx(Vd,{asChild:!0,children:e.jsx(B,{variant:"ghost",size:"icon",children:e.jsx(Ev,{className:"h-4 w-4"})})}),e.jsxs(Ld,{align:"end",children:[e.jsxs(ba,{onClick:()=>l(z),children:[e.jsx(xp,{className:"h-4 w-4 mr-2"}),"Edit"]}),e.jsxs(ba,{onClick:()=>I(z),children:[e.jsx(Pa,{className:"h-4 w-4 mr-2"}),"Duplicate"]}),e.jsxs(ba,{onClick:()=>c(z.id),className:"text-destructive",children:[e.jsx(qn,{className:"h-4 w-4 mr-2"}),"Delete"]})]})]})})]},z.id)})})]})})})]}),e.jsx(c7t,{open:!!i,onOpenChange:z=>!z&&l(null),transaction:i||void 0}),e.jsx(Fl,{open:!!o,onOpenChange:z=>!z&&c(null),children:e.jsxs(kl,{children:[e.jsxs(Sl,{children:[e.jsx(Al,{children:"Delete Transaction?"}),e.jsx(Tl,{children:"This action cannot be undone. This will permanently delete this transaction."})]}),e.jsxs(Cl,{children:[e.jsx(El,{children:"Cancel"}),e.jsx(wl,{onClick:M,className:"bg-destructive text-destructive-foreground",children:"Delete"})]})]})})]})}function d7t({goals:s,stats:t,year:n,showCommission:r}){const a=new Date().getMonth()+1,i=new Date().getFullYear()===n?a:12,l=12-i,o=(m,f)=>{if(!f||f===0)return null;const g=Math.min(m/f*100,100),y=Math.max(f-m,0),x=l>0?y/l:0,_=i/12*100,b=g>=_?"ahead":g>=_*.8?"on-track":"behind";return{percent:g,remaining:y,pace:x,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(We,{className:"bg-green-500 text-white",children:[e.jsx(ml,{className:"h-3 w-3 mr-1"}),"Ahead"]});case"on-track":return e.jsxs(We,{variant:"secondary",children:[e.jsx(X2,{className:"h-3 w-3 mr-1"}),"On Track"]});case"behind":return e.jsxs(We,{variant:"destructive",children:[e.jsx(eN,{className:"h-3 w-3 mr-1"}),"Behind"]});default:return null}};return!s.transactions_goal&&!s.volume_goal&&!s.gci_goal?null:e.jsxs(_e,{children:[e.jsx(zt,{className:"pb-3",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(iu,{className:"h-5 w-5 text-primary"}),e.jsxs(qt,{children:[n," Goals Progress"]})]})}),e.jsx(De,{children:e.jsxs("div",{className:"grid md:grid-cols-3 gap-6",children:[s.transactions_goal&&c&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"text-sm font-medium",children:"Transactions"}),h(c.status)]}),e.jsx(ro,{value:c.percent,className:"h-2"}),e.jsxs("div",{className:"flex justify-between text-sm text-muted-foreground",children:[e.jsxs("span",{children:[t.totalTransactions," of ",s.transactions_goal]}),e.jsxs("span",{children:[Math.round(c.percent),"%"]})]}),c.remaining>0&&l>0&&e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Need ",Math.ceil(c.pace),"/month to hit goal"]})]}),s.volume_goal&&d&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"text-sm font-medium",children:"Volume"}),h(d.status)]}),e.jsx(ro,{value:d.percent,className:"h-2"}),e.jsxs("div",{className:"flex justify-between text-sm text-muted-foreground",children:[e.jsxs("span",{children:[_u(t.totalVolume,!0)," of ",_u(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 ",_u(d.pace,!0),"/month"]})]}),r&&s.gci_goal&&u&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"text-sm font-medium",children:"GCI"}),h(u.status)]}),e.jsx(ro,{value:u.percent,className:"h-2"}),e.jsxs("div",{className:"flex justify-between text-sm text-muted-foreground",children:[e.jsxs("span",{children:[_u(t.totalCommission,!0)," of ",_u(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 ",_u(u.pace,!0),"/month"]})]})]})})]})}const Vwn={light:"",dark:".dark"},u7t=N.createContext(null);function h7t(){const s=N.useContext(u7t);if(!s)throw new Error("useChart must be used within a ");return s}const m7t=N.forwardRef(({id:s,className:t,children:n,config:r,...a},i)=>{const l=N.useId(),o=`chart-${s||l.replace(/:/g,"")}`;return e.jsx(u7t.Provider,{value:{config:r},children:e.jsxs("div",{"data-chart":o,ref:i,className:Ot("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(Hwn,{id:o,config:r}),e.jsx(b5,{children:n})]})})});m7t.displayName="Chart";const Hwn=({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(Vwn).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},p7t=N.forwardRef(({active:s,payload:t,className:n,indicator:r="dot",hideLabel:a=!1,hideIndicator:i=!1,label:l,labelFormatter:o,labelClassName:c,formatter:d,color:u,nameKey:h,labelKey:m},f)=>{const{config:g}=h7t(),y=N.useMemo(()=>{var T;if(a||!(t!=null&&t.length))return null;const[_]=t,b=`${m||_.dataKey||_.name||"value"}`,k=hze(g,_,b),A=!m&&typeof l=="string"?((T=g[l])==null?void 0:T.label)||l:k==null?void 0:k.label;return o?e.jsx("div",{className:Ot("font-medium",c),children:o(A,t)}):A?e.jsx("div",{className:Ot("font-medium",c),children:A}):null},[l,o,t,a,c,g,m]);if(!s||!(t!=null&&t.length))return null;const x=t.length===1&&r!=="dot";return e.jsxs("div",{ref:f,className:Ot("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:[x?null:y,e.jsx("div",{className:"grid gap-1.5",children:t.map((_,b)=>{const k=`${h||_.name||_.dataKey||"value"}`,A=hze(g,_,k),T=u||_.payload.fill||_.color;return e.jsx("div",{className:Ot("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&&(_==null?void 0:_.value)!==void 0&&_.name?d(_.value,_.name,_,b,_.payload):e.jsxs(e.Fragment,{children:[A!=null&&A.icon?e.jsx(A.icon,{}):!i&&e.jsx("div",{className:Ot("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":x&&r==="dashed"}),style:{"--color-bg":T,"--color-border":T}}),e.jsxs("div",{className:Ot("flex flex-1 justify-between leading-none",x?"items-end":"items-center"),children:[e.jsxs("div",{className:"grid gap-1.5",children:[x?y:null,e.jsx("span",{className:"text-muted-foreground",children:(A==null?void 0:A.label)||_.name})]}),_.value&&e.jsx("span",{className:"font-mono font-medium tabular-nums text-foreground",children:_.value.toLocaleString()})]})]})},_.dataKey)})})]})});p7t.displayName="ChartTooltip";const Gwn=N.forwardRef(({className:s,hideIcon:t=!1,payload:n,verticalAlign:r="bottom",nameKey:a},i)=>{const{config:l}=h7t();return n!=null&&n.length?e.jsx("div",{ref:i,className:Ot("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=hze(l,o,c);return e.jsxs("div",{className:Ot("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});Gwn.displayName="ChartLegend";function hze(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 kne=["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 BWe({stats:s,year:t}){const n=s.transactionsByMonth.some(a=>a.count>0),r=s.leadSourceBreakdown.length>0;return!n&&!r?e.jsx(_e,{children:e.jsx(De,{className:"py-12 text-center text-muted-foreground",children:"Add transactions to see your performance charts"})}):e.jsxs("div",{className:"grid gap-6",children:[n&&e.jsxs(_e,{className:"overflow-hidden",children:[e.jsx(zt,{children:e.jsx(qt,{className:"text-base",children:"Transactions by Month"})}),e.jsx(De,{className:"overflow-hidden",children:e.jsx(m7t,{config:{count:{label:"Transactions",color:"hsl(var(--primary))"}},className:"h-[250px]",children:e.jsx(b5,{width:"100%",height:"100%",children:e.jsxs(rGe,{data:s.transactionsByMonth,margin:{top:5,right:10,left:0,bottom:5},children:[e.jsx(tGe,{strokeDasharray:"3 3",className:"stroke-muted"}),e.jsx(R5,{dataKey:"month",tick:{fontSize:11},className:"fill-muted-foreground",interval:0}),e.jsx(O5,{allowDecimals:!1,tick:{fontSize:12},className:"fill-muted-foreground",width:30}),e.jsx(Vx,{content:e.jsx(p7t,{})}),e.jsx(D5,{dataKey:"count",fill:"hsl(var(--primary))",radius:[4,4,0,0],name:"Transactions"})]})})})})]}),r&&e.jsxs(_e,{children:[e.jsx(zt,{children:e.jsx(qt,{className:"text-base",children:"Lead Sources"})}),e.jsxs(De,{children:[e.jsx("div",{className:"h-[250px]",children:e.jsx(b5,{width:"100%",height:"100%",children:e.jsxs(aGe,{children:[e.jsx(jN,{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(DU,{fill:kne[i%kne.length]},`cell-${i}`))}),e.jsx(Vx,{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:kne[i%kne.length]}}),e.jsx("span",{className:"text-muted-foreground",children:a.name})]},a.name))})]})]})]})}function Wwn(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=tUe(t,r,new Date);if($De(a))return Js(a,"yyyy-MM-dd")}catch{}try{const r=new Date(t);if($De(r))return Js(r,"yyyy-MM-dd")}catch{}return null}const Kwn=["property_address","city","state","zip","transaction_type","close_date","sale_price","commission_amount","lead_source","client_type","is_win","notes"];function Ywn({open:s,onOpenChange:t}){const[n,r]=N.useState([]),[a,i]=N.useState(!1),[l,o]=N.useState(0),{data:c}=$R(),{data:d}=K_(),u=t3e(),h=()=>{const _=Kwn.join(","),b=["123 Main St","Dallas","TX","75001","buyer","2024-06-15","450000","13500","Referral","Past Client","yes","Great transaction!"].join(","),k=`${_} ${b}`,A=new Blob([k],{type:"text/csv"}),T=URL.createObjectURL(A),P=document.createElement("a");P.href=T,P.download="transaction-import-template.csv",P.click(),URL.revokeObjectURL(T)},m=_=>{const b=_.split(` `).filter(A=>A.trim());if(b.length<2)return[];const k=b[0].split(",").map(A=>A.trim().toLowerCase().replace(/['"]/g,""));return b.slice(1).map((A,T)=>{var ne,me,ue,ce;const P=[];let I="",M=!1;for(const ae of A)ae==='"'?M=!M:ae===","&&!M?(P.push(I.trim()),I=""):I+=ae;P.push(I.trim());const L=ae=>{var xe;const he=k.indexOf(ae);return he>=0?(xe=P[he])==null?void 0:xe.replace(/^["']|["']$/g,"").trim():""},z=(ne=L("transaction_type"))==null?void 0:ne.toLowerCase(),$=(me=L("sale_price"))==null?void 0:me.replace(/[$,]/g,""),V=(ue=L("commission_amount"))==null?void 0:ue.replace(/[$,]/g,""),W=(ce=L("is_win"))==null?void 0:ce.toLowerCase(),G=L("close_date"),X=Wwn(G);let te;return L("property_address")?["buyer","seller"].includes(z)?X?(!$||isNaN(Number($)))&&(te="Invalid sale price"):te=`Invalid date format: "${G}" - use MM/DD/YYYY or YYYY-MM-DD`:te='Transaction type must be "buyer" or "seller"':te="Missing property address",{property_address:L("property_address"),city:L("city"),state:L("state"),zip:L("zip"),transaction_type:z==="seller"?"seller":"buyer",close_date:X||"",sale_price:Number($)||0,commission_amount:V?Number(V):null,lead_source_name:L("lead_source"),client_type_name:L("client_type"),is_win:["yes","true","1"].includes(W),notes:L("notes"),error:te}})},f=_=>{var A;const b=(A=_.target.files)==null?void 0:A[0];if(!b)return;const k=new FileReader;k.onload=T=>{var M;const P=(M=T.target)==null?void 0:M.result,I=m(P);r(I)},k.readAsText(b)},g=async()=>{const _=n.filter(A=>!A.error);if(_.length===0){ie.error("No valid transactions to import");return}i(!0),o(0);let b=0,k=0;for(let A=0;A<_.length;A++){const T=_[A];try{const P=c==null?void 0:c.find(M=>M.name.toLowerCase()===T.lead_source_name.toLowerCase()),I=d==null?void 0:d.find(M=>M.name.toLowerCase()===T.client_type_name.toLowerCase());await u.mutateAsync({property_address:T.property_address,city:T.city||null,state:T.state||null,zip:T.zip||null,transaction_type:T.transaction_type,close_date:T.close_date,sale_price:T.sale_price,commission_amount:T.commission_amount,lead_source_id:(P==null?void 0:P.id)||null,client_type_id:(I==null?void 0:I.id)||null,contact_id:null,notes:T.notes||null,is_win:T.is_win}),b++}catch(P){k++,console.error("Failed to import transaction:",P)}o(Math.round((A+1)/_.length*100))}i(!1),b>0&&ie.success(`Imported ${b} transaction${b>1?"s":""}`),k>0&&ie.error(`Failed to import ${k} transaction${k>1?"s":""}`),r([]),t(!1)},y=n.filter(_=>!_.error).length,x=n.filter(_=>_.error).length;return e.jsx(Bs,{open:s,onOpenChange:t,children:e.jsxs(Fs,{className:"max-w-2xl max-h-[90vh]",children:[e.jsxs(qs,{children:[e.jsx($s,{children:"Import Transactions"}),e.jsx(Ar,{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(oi,{className:"h-4 w-4 mr-2"}),"Template"]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{htmlFor:"csv-file",children:"Upload CSV File"}),e.jsx(we,{id:"csv-file",type:"file",accept:".csv",onChange:f})]}),n.length>0&&e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(We,{variant:"outline",children:[n.length," rows found"]}),y>0&&e.jsxs(We,{className:"bg-green-500 text-white",children:[e.jsx(pa,{className:"h-3 w-3 mr-1"}),y," valid"]}),x>0&&e.jsxs(We,{variant:"destructive",children:[e.jsx(Uo,{className:"h-3 w-3 mr-1"}),x," errors"]})]}),e.jsx(lo,{className:"h-[200px] border rounded-lg",children:e.jsxs("div",{className:"p-2 space-y-2",children:[n.slice(0,10).map((_,b)=>e.jsxs("div",{className:`p-2 rounded text-sm ${_.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:_.property_address||"(no address)"}),e.jsx(We,{variant:_.transaction_type==="buyer"?"default":"secondary",children:_.transaction_type})]}),e.jsxs("div",{className:"text-muted-foreground",children:[_.close_date," • $",_.sale_price.toLocaleString()]}),_.error&&e.jsx(bVe,{variant:"destructive",className:"mt-1 py-1",children:e.jsx(_Ve,{className:"text-xs",children:_.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:g,disabled:y===0||a,children:[e.jsx(ni,{className:"h-4 w-4 mr-2"}),"Import ",y," Transaction",y!==1?"s":""]})]})]})]})})}const Zwn=H5({transactions_goal:UW().min(0).optional(),volume_goal:UW().min(0).optional(),gci_goal:UW().min(0).optional()});function Xwn({open:s,onOpenChange:t,year:n,existingGoals:r}){const a=i2s(),{data:i}=s3e(),l=(i==null?void 0:i.show_commission)??!0,o=W4e({resolver:K4e(Zwn),defaultValues:{transactions_goal:void 0,volume_goal:void 0,gci_goal:void 0}});N.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(Bs,{open:s,onOpenChange:t,children:e.jsxs(Fs,{className:"max-w-md",children:[e.jsxs(qs,{children:[e.jsxs($s,{children:[n," Goals"]}),e.jsx(Ar,{children:"Set your annual targets to track your progress throughout the year."})]}),e.jsx(Y4e,{...o,children:e.jsxs("form",{onSubmit:o.handleSubmit(c),className:"space-y-4",children:[e.jsx(gp,{control:o.control,name:"transactions_goal",render:({field:d})=>e.jsxs(Mm,{children:[e.jsx(Lm,{children:"Transactions Goal"}),e.jsx(Pm,{children:e.jsx(we,{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(Bwe,{children:"Total number of deals you want to close"}),e.jsx(Ov,{})]})}),e.jsx(gp,{control:o.control,name:"volume_goal",render:({field:d})=>e.jsxs(Mm,{children:[e.jsx(Lm,{children:"Volume Goal ($)"}),e.jsx(Pm,{children:e.jsx(we,{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(Bwe,{children:"Total sales volume you want to achieve"}),e.jsx(Ov,{})]})}),l&&e.jsx(gp,{control:o.control,name:"gci_goal",render:({field:d})=>e.jsxs(Mm,{children:[e.jsx(Lm,{children:"GCI Goal ($)"}),e.jsx(Pm,{children:e.jsx(we,{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(Bwe,{children:"Gross commission income target"}),e.jsx(Ov,{})]})}),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 $We({transactions:s,isLoading:t}){const n=N.useRef(null),r=N.useRef(null),a=N.useRef([]),i=N.useRef(null),{isAdmin:l}=Ls(),[o,c]=N.useState(""),[d,u]=N.useState(!0),[h,m]=N.useState(0),[f,g]=N.useState(!1),y=s.filter(_=>_.latitude!=null&&_.longitude!=null),x=s.filter(_=>_.latitude==null||_.longitude==null);return N.useEffect(()=>{(async()=>{u(!0);try{const{data:b}=await H.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)})()},[]),N.useEffect(()=>{if(!o||x.length===0||f)return;(async()=>{var k;g(!0);let b=0;for(const A of x){const T=[A.property_address,A.city,A.state,A.zip].filter(Boolean).join(", ");if(T)try{const I=await(await fetch(`https://api.mapbox.com/geocoding/v5/mapbox.places/${encodeURIComponent(T)}.json?access_token=${o}&limit=1`)).json();if((k=I.features)!=null&&k[0]){const[M,L]=I.features[0].center;await H.from("scorecard_transactions").update({latitude:L,longitude:M}).eq("id",A.id),A.latitude=L,A.longitude=M,b++}}catch(P){console.error("Geocode error:",P)}}m(b),g(!1)})()},[o,s]),N.useEffect(()=>{if(!n.current||!o||r.current)return;Rc.accessToken=o;const _=s.filter(A=>A.latitude!=null&&A.longitude!=null);let b=[-98.5795,39.8283],k=4;if(_.length>0){const A=_.reduce((P,I)=>P+I.longitude,0)/_.length,T=_.reduce((P,I)=>P+I.latitude,0)/_.length;b=[A,T],k=_.length===1?12:10}return r.current=new Rc.Map({container:n.current,style:"mapbox://styles/mapbox/light-v11",zoom:k,center:b}),r.current.addControl(new Rc.NavigationControl,"top-right"),()=>{var A;(A=r.current)==null||A.remove(),r.current=null}},[o]),N.useEffect(()=>{var b;if(!r.current||!o)return;a.current.forEach(k=>k.remove()),a.current=[],(b=i.current)==null||b.remove();const _=s.filter(k=>k.latitude!=null&&k.longitude!=null);if(_.forEach(k=>{var L;const A=k.transaction_type==="buyer",T=A?"#3B82F6":"#10B981",P=document.createElement("div");P.className="cursor-pointer",P.innerHTML=`
${A?'':''}
`;const I=new Rc.Popup({offset:25,closeButton:!0}).setHTML(`
${k.property_address}
${k.city?`
${k.city}${k.state?", "+k.state:""} ${k.zip||""}
`:""}
${A?"Buyer":"Seller"} $${Number(k.sale_price).toLocaleString()}
Closed: ${Tc(k.close_date).toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric"})} ${(L=k.lead_source)!=null&&L.name?" · "+k.lead_source.name:""}
${k.contact?`
Client: ${k.contact.first_name} ${k.contact.last_name||""}
`:""}
`),M=new Rc.Marker(P).setLngLat([k.longitude,k.latitude]).setPopup(I).addTo(r.current);a.current.push(M)}),_.length>1){const k=new Rc.LngLatBounds;_.forEach(A=>k.extend([A.longitude,A.latitude])),r.current.fitBounds(k,{padding:60,maxZoom:13})}else _.length===1&&r.current.flyTo({center:[_[0].longitude,_[0].latitude],zoom:12})},[s,o,f]),d||t?e.jsx(_e,{children:e.jsx(De,{className:"flex items-center justify-center h-[50vh]",children:e.jsx("div",{className:"animate-spin rounded-full h-8 w-8 border-b-2 border-primary"})})}):o?s.length===0?e.jsx(_e,{children:e.jsxs(De,{className:"flex flex-col items-center justify-center h-[50vh] text-center gap-3",children:[e.jsx(ii,{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",f&&" · Geocoding..."]})]}),e.jsx("div",{ref:n,className:"w-full h-[55vh] rounded-lg shadow-lg border"})]}):e.jsx(_e,{children:e.jsxs(De,{className:"flex flex-col items-center justify-center h-[50vh] text-center gap-3",children:[e.jsx(Uo,{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 f7t=()=>{const{data:s}=Cj();return mt({queryKey:["team-scorecard-members",s==null?void 0:s.teamId],queryFn:async()=>{const{data:t,error:n}=await H.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 H.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"})},Qwn=s=>{const{data:t}=Cj(),{data:n}=f7t();return mt({queryKey:["team-scorecard-transactions",t==null?void 0:t.teamId,s],queryFn:async()=>{const r=n.map(o=>o.id);let a=H.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 Jwn(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 ejn(s,t){return s?s.split(" ").map(n=>n[0]).join("").toUpperCase().slice(0,2):t[0].toUpperCase()}function tjn({year:s}){var m;const{data:t,isLoading:n}=f7t(),{data:r,isLoading:a}=Qwn(s),i=tr(),l=n||a,{aggregate:o,memberStats:c,topPerformer:d,agentNameMap:u,teamChartStats:h}=N.useMemo(()=>{if(!t||!r)return{aggregate:null,memberStats:[],topPerformer:null,agentNameMap:{},teamChartStats:null};const f=t.map(z=>Jwn(z,r));f.sort((z,$)=>$.totalVolume-z.totalVolume);const g={};t.forEach(z=>{g[z.id]=z.name||z.email});const y=r.length,x=r.reduce((z,$)=>z+Number($.sale_price),0),_=r.reduce((z,$)=>z+(Number($.commission_amount)||0),0),b=r.filter(z=>z.transaction_type==="buyer").length,k=r.filter(z=>z.transaction_type==="seller").length,A={};r.forEach(z=>{var V;const $=((V=z.lead_source)==null?void 0:V.name)||"Unknown";A[$]=(A[$]||0)+1});const T=Object.entries(A).sort((z,$)=>$[1]-z[1])[0],P={};r.forEach(z=>{const $=Tc(z.close_date).toLocaleString("default",{month:"short"});P[$]=(P[$]||0)+1});const M=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"].map(z=>({month:z,count:P[z]||0})),L=Object.entries(A).map(([z,$])=>({name:z,count:$})).sort((z,$)=>$.count-z.count);return{aggregate:{totalTxns:y,buyerCount:b,sellerCount:k,totalVolume:x,avgPrice:y>0?x/y:0,totalGCI:_,topSource:T?{name:T[0],count:T[1]}:null,memberCount:t.length},memberStats:f,topPerformer:f[0]||null,agentNameMap:g,teamChartStats:{transactionsByMonth:M,leadSourceBreakdown:L}}},[t,r]);return l?e.jsxs("div",{className:"space-y-6",children:[e.jsx("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4",children:[1,2,3,4].map(f=>e.jsx(xn,{className:"h-24"},f))}),e.jsx(xn,{className:"h-64"})]}):!o||c.length===0?e.jsx(_e,{className:"py-12",children:e.jsxs(De,{className:"text-center space-y-2",children:[e.jsx(Yn,{className:"h-10 w-10 mx-auto text-muted-foreground"}),e.jsx("h3",{className:"text-lg font-semibold",children:"No Team Data"}),e.jsxs("p",{className:"text-muted-foreground",children:["No scorecard transactions found for your team members in ",s,"."]})]})}):e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 lg:grid-cols-6 gap-4",children:[e.jsx(_e,{children:e.jsxs(De,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[e.jsx(Yn,{className:"h-4 w-4"}),e.jsx("span",{className:"text-xs font-medium",children:"Members"})]}),e.jsx("p",{className:"text-2xl font-bold",children:o.memberCount})]})}),e.jsx(_e,{children:e.jsxs(De,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[e.jsx(_a,{className:"h-4 w-4"}),e.jsx("span",{className:"text-xs font-medium",children:"Team Transactions"})]}),e.jsx("p",{className:"text-2xl font-bold",children:o.totalTxns}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[o.buyerCount,"B / ",o.sellerCount,"S"]})]})}),e.jsx(_e,{children:e.jsxs(De,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[e.jsx(Ed,{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:_u(o.totalVolume,!0)})]})}),e.jsx(_e,{children:e.jsxs(De,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[e.jsx(ml,{className:"h-4 w-4"}),e.jsx("span",{className:"text-xs font-medium",children:"Avg Price"})]}),e.jsx("p",{className:"text-2xl font-bold",children:_u(o.avgPrice,!0)})]})}),e.jsx(_e,{children:e.jsxs(De,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[e.jsx(Ed,{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:_u(o.totalGCI,!0)})]})}),e.jsx(_e,{children:e.jsxs(De,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[e.jsx(ku,{className:"h-4 w-4"}),e.jsx("span",{className:"text-xs font-medium",children:"Top Source"})]}),e.jsx("p",{className:"text-lg font-bold truncate",children:((m=o.topSource)==null?void 0:m.name)||"-"}),o.topSource&&e.jsxs("p",{className:"text-xs text-muted-foreground",children:[o.topSource.count," deals"]})]})})]}),d&&d.totalTransactions>0&&e.jsx(_e,{className:"border-primary/30 bg-primary/5",children:e.jsxs(De,{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(gl,{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:_u(d.totalVolume,!0)})]})]})}),e.jsxs(_e,{children:[e.jsx(zt,{children:e.jsx(qt,{className:"text-lg",children:"Member Performance"})}),e.jsx(De,{children:e.jsx("div",{className:"overflow-x-auto",children:e.jsxs(Oa,{children:[e.jsx(Fa,{children:e.jsxs(un,{children:[e.jsx(Mt,{children:"Agent"}),e.jsx(Mt,{className:"text-center",children:"Transactions"}),e.jsx(Mt,{className:"text-center",children:"B / S"}),e.jsx(Mt,{className:"text-right",children:"Volume"}),e.jsx(Mt,{className:"text-right",children:"Avg Price"}),e.jsx(Mt,{className:"text-right",children:"GCI"}),e.jsx(Mt,{className:"text-right"})]})}),e.jsx(za,{children:c.map((f,g)=>e.jsxs(un,{children:[e.jsx(gt,{children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs("div",{className:"relative",children:[g===0&&f.totalTransactions>0&&e.jsx(gl,{className:"absolute -top-2 -right-2 h-3.5 w-3.5 text-amber-500"}),e.jsxs(Ua,{className:"h-8 w-8",children:[e.jsx(Gi,{src:f.member.avatar_url||void 0}),e.jsx(qa,{className:"text-xs",children:ejn(f.member.name,f.member.email)})]})]}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium text-sm",children:f.member.name||f.member.email}),f.member.name&&e.jsx("p",{className:"text-xs text-muted-foreground",children:f.member.email})]})]})}),e.jsx(gt,{className:"text-center font-semibold",children:f.totalTransactions}),e.jsxs(gt,{className:"text-center text-sm",children:[f.buyerCount," / ",f.sellerCount]}),e.jsx(gt,{className:"text-right font-medium",children:_u(f.totalVolume,!0)}),e.jsx(gt,{className:"text-right text-sm",children:_u(f.averagePrice,!0)}),e.jsx(gt,{className:"text-right font-medium",children:_u(f.totalGCI,!0)}),e.jsx(gt,{className:"text-right",children:e.jsx(B,{variant:"ghost",size:"sm",onClick:()=>i(`/mission-control/scorecard/${f.member.id}`),children:e.jsx(da,{className:"h-4 w-4"})})})]},f.member.id))})]})})})]}),e.jsxs(ya,{defaultValue:"transactions",className:"space-y-4",children:[e.jsxs(va,{children:[e.jsxs(ls,{value:"transactions",children:[e.jsx(Kx,{className:"h-4 w-4 mr-1"}),"All Transactions"]}),e.jsxs(ls,{value:"charts",children:[e.jsx(fl,{className:"h-4 w-4 mr-1"}),"Charts"]}),e.jsxs(ls,{value:"map",children:[e.jsx(ii,{className:"h-4 w-4 mr-1"}),"Map"]})]}),e.jsx(_s,{value:"transactions",children:e.jsx(zWe,{transactions:r||[],showCommission:!0,isLoading:a,agentNameMap:u,readOnly:!0})}),e.jsx(_s,{value:"charts",children:h&&e.jsx(BWe,{stats:h,year:s})}),e.jsx(_s,{value:"map",children:e.jsx($We,{transactions:r||[],isLoading:a})})]})]})}const zje=new Date().getFullYear(),wft=Array.from({length:10},(s,t)=>zje-t),Sne="all";function sjn(){var V;const[s,t]=N.useState(zje),n=s===null?Sne:String(s),r=W=>t(W===Sne?null:Number(W)),[a,i]=N.useState(!1),[l,o]=N.useState(!1),[c,d]=N.useState(!1),[u,h]=N.useState(!1),[m,f]=N.useState("my"),{data:g}=Cj(),y=(g==null?void 0:g.role)==="team_leader",{data:x,isLoading:_}=fqe(s??void 0),{yearStats:b,lifetimeStats:k,isLoading:A,showCommission:T}=U4t(s??void 0),{data:P,isLoading:I}=$4t(s??zje),{data:M}=s3e(),L=o2s(),z=()=>{if(!x||x.length===0)return;const W=["Property Address","City","State","Zip","Transaction Type","Close Date","Sale Price",...T?["Commission"]:[],"Lead Source","Client Type","Contact Name","Is Win","Notes"],G=x.map(ue=>{var ce,ae;return[ue.property_address,ue.city||"",ue.state||"",ue.zip||"",ue.transaction_type,ue.close_date,ue.sale_price,...T?[ue.commission_amount||""]:[],((ce=ue.lead_source)==null?void 0:ce.name)||"",((ae=ue.client_type)==null?void 0:ae.name)||"",ue.contact?`${ue.contact.first_name} ${ue.contact.last_name||""}`.trim():"",ue.is_win?"Yes":"No",ue.notes||""]}),X=[W,...G].map(ue=>ue.map(ce=>`"${String(ce).replace(/"/g,'""')}"`).join(",")).join(` `),te=new Blob([X],{type:"text/csv"}),ne=URL.createObjectURL(te),me=document.createElement("a");me.href=ne,me.download=s===null?"transactions-all.csv":`transactions-${s}.csv`,me.click(),URL.revokeObjectURL(ne)},$=!x||x.length===0;return e.jsxs(Qs,{title:"Scorecard",children:[e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("h1",{className:"text-2xl font-bold",children:"Scorecard"}),e.jsx("span",{className:"text-[10px] font-semibold uppercase tracking-wide px-1.5 py-0.5 rounded border border-amber-500/50 text-amber-600 dark:text-amber-400 bg-amber-500/10",children:"Beta"})]}),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:()=>f("my"),className:"h-8",children:"My Scorecard"}),e.jsxs(B,{variant:m==="team"?"default":"ghost",size:"sm",onClick:()=>f("team"),className:"h-8",children:[e.jsx(Yn,{className:"h-4 w-4 mr-1.5"}),"Team"]})]}),m==="team"&&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(Ns,{value:n,onValueChange:r,children:[e.jsx(ws,{className:"w-[140px]",children:e.jsx(ks,{})}),e.jsxs(js,{children:[e.jsx(nt,{value:Sne,children:"All Years"}),wft.map(W=>e.jsx(nt,{value:String(W),children:W},W))]})]})]}),e.jsx(tjn,{year:s??void 0})]}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4",children:[e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl font-bold text-foreground",children:"Business Scorecard"}),e.jsx("p",{className:"text-muted-foreground",children:"Track your transactions, goals, and performance"})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsxs(Ns,{value:n,onValueChange:r,children:[e.jsx(ws,{className:"w-[140px]",children:e.jsx(ks,{})}),e.jsxs(js,{children:[e.jsx(nt,{value:Sne,children:"All Years"}),wft.map(W=>e.jsx(nt,{value:String(W),children:W},W))]})]}),e.jsx(B,{variant:"outline",size:"icon",onClick:()=>h(!u),children:e.jsx(sc,{className:"h-4 w-4"})})]})]}),u&&e.jsxs(_e,{children:[e.jsx(zt,{className:"pb-3",children:e.jsx(qt,{className:"text-lg",children:"Settings"})}),e.jsx(De,{children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"space-y-0.5",children:[e.jsx(re,{children:"Show Commission"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Display commission fields and include in stats"})]}),e.jsx(zn,{checked:(M==null?void 0:M.show_commission)??!0,onCheckedChange:W=>L.mutate({show_commission:W})})]})})]}),$&&!_?e.jsx(_e,{className:"py-12",children:e.jsxs(De,{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(fl,{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(nn,{className:"h-4 w-4 mr-2"}),"Add Your First Transaction"]}),e.jsxs(B,{variant:"outline",onClick:()=>o(!0),children:[e.jsx(ni,{className:"h-4 w-4 mr-2"}),"Import CSV"]})]}),e.jsxs("div",{className:"pt-4 border-t mt-4",children:[e.jsx("p",{className:"text-sm text-muted-foreground mb-2",children:"Need help formatting your data?"}),e.jsx(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(oi,{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(nn,{className:"h-4 w-4 mr-2"}),"Add Transaction"]}),e.jsxs(B,{variant:"outline",onClick:()=>d(!0),children:[e.jsx(iu,{className:"h-4 w-4 mr-2"}),"Set Goals"]}),e.jsxs(B,{variant:"outline",onClick:()=>o(!0),children:[e.jsx(ni,{className:"h-4 w-4 mr-2"}),"Import"]}),e.jsxs(B,{variant:"outline",onClick:z,disabled:$,children:[e.jsx(oi,{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(oi,{className:"h-4 w-4 mr-2"}),"CSV Template"]})})]}),e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 lg:grid-cols-7 gap-4",children:[e.jsx(_e,{children:e.jsxs(De,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[e.jsx(_a,{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:[k.totalTransactions," lifetime"]})]})}),e.jsx(_e,{children:e.jsxs(De,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[e.jsx(Yn,{className:"h-4 w-4"}),e.jsx("span",{className:"text-xs font-medium",children:"Buyer/Seller"})]}),e.jsxs("p",{className:"text-2xl font-bold",children:[b.buyerCount,"/",b.sellerCount]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"B/S split"})]})}),e.jsx(_e,{children:e.jsxs(De,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[e.jsx(Ed,{className:"h-4 w-4"}),e.jsx("span",{className:"text-xs font-medium",children:"Volume"})]}),e.jsx("p",{className:"text-2xl font-bold",children:_u(b.totalVolume,!0)}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[_u(k.totalVolume,!0)," lifetime"]})]})}),e.jsx(_e,{children:e.jsxs(De,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[e.jsx(ml,{className:"h-4 w-4"}),e.jsx("span",{className:"text-xs font-medium",children:"Avg Price"})]}),e.jsx("p",{className:"text-2xl font-bold",children:_u(b.averagePrice,!0)})]})}),e.jsx(_e,{children:e.jsxs(De,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[e.jsx(ku,{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"]})]})}),T&&e.jsx(_e,{children:e.jsxs(De,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[e.jsx(Ed,{className:"h-4 w-4"}),e.jsx("span",{className:"text-xs font-medium",children:"GCI"})]}),e.jsx("p",{className:"text-2xl font-bold",children:_u(b.totalCommission,!0)}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[_u(k.totalCommission,!0)," lifetime"]})]})}),T&&b.totalNetToAgent>0&&b.totalNetToAgent!==b.totalCommission&&e.jsx(_e,{children:e.jsxs(De,{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(Ed,{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:_u(b.totalNetToAgent,!0)}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[_u(k.totalNetToAgent,!0)," lifetime"]})]})})]}),s!==null&&P&&e.jsx(d7t,{goals:P,stats:b,year:s,showCommission:T}),e.jsxs(ya,{defaultValue:"transactions",className:"space-y-4",children:[e.jsxs(va,{children:[e.jsx(ls,{value:"transactions",children:"Transactions"}),e.jsx(ls,{value:"charts",children:"Charts"}),e.jsxs(ls,{value:"map",children:[e.jsx(ii,{className:"h-4 w-4 mr-1"}),"Map"]})]}),e.jsx(_s,{value:"transactions",children:e.jsx(zWe,{transactions:x||[],showCommission:T,isLoading:_})}),e.jsx(_s,{value:"charts",children:e.jsx(BWe,{stats:b,year:s??void 0})}),e.jsx(_s,{value:"map",children:e.jsx($We,{transactions:x||[],isLoading:_})})]})]})]})]}),e.jsx(c7t,{open:a,onOpenChange:i}),e.jsx(Ywn,{open:l,onOpenChange:o}),e.jsx(Xwn,{open:c,onOpenChange:d,year:s??zje,existingGoals:P})]})}function g7t({open:s,onOpenChange:t,listingId:n,listingSlug:r,listingTitle:a}){const{user:i}=Ls(),[l,o]=N.useState(null),[c,d]=N.useState(!1),[u,h]=N.useState(!1);N.useEffect(()=>{(async()=>{if(!(!s||!i)){d(!0);try{const{data:x,error:_}=await H.from("listing_shares").select("id, share_token, click_count, lead_count").eq("listing_id",n).eq("sharing_agent_id",i.id).order("created_at",{ascending:!1}).limit(1).maybeSingle();if(_)throw _;if(x&&x.share_token)o(x);else if(x&&!x.share_token){const{data:b,error:k}=await H.from("listing_shares").update({share_type:"referral_link"}).eq("id",x.id).select("id, share_token, click_count, lead_count").single();if(k)throw k;o(b)}else{const{data:b,error:k}=await H.from("listing_shares").insert({listing_id:n,sharing_agent_id:i.id,share_type:"referral_link"}).select("id, share_token, click_count, lead_count").single();if(k)throw k;o(b)}}catch(x){console.error("Error creating share link:",x),ie.error("Failed to generate share link")}finally{d(!1)}}})()},[s,i,n]);const m=l!=null&&l.share_token?`https://listings.relevelup.com/${r||n}?ref=${l.share_token}`:"",f=async()=>{try{await navigator.clipboard.writeText(m),h(!0),ie.success("Link copied to clipboard!"),setTimeout(()=>h(!1),2e3)}catch{ie.error("Failed to copy link")}},g=y=>{const x=encodeURIComponent(m),_=encodeURIComponent(`Check out this listing: ${a}`);switch(y){case"email":window.open(`mailto:?subject=${_}&body=${x}`);break;case"text":window.open(`sms:?body=${_}%20${x}`);break;case"facebook":window.open(`https://www.facebook.com/sharer/sharer.php?u=${x}`,"_blank");break}};return e.jsx(Bs,{open:s,onOpenChange:t,children:e.jsxs(Fs,{className:"sm:max-w-md",children:[e.jsxs(qs,{children:[e.jsxs($s,{className:"flex items-center gap-2",children:[e.jsx(Cn,{className:"h-5 w-5 text-amber-500"}),"Share & Earn Leads"]}),e.jsx(Ar,{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(re,{children:"Your Referral Link"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(we,{value:c?"Generating...":m,readOnly:!0,className:"font-mono text-sm"}),e.jsx(B,{onClick:f,disabled:c||!m,variant:u?"default":"outline",children:u?e.jsx(pa,{className:"h-4 w-4"}):e.jsx(Pa,{className:"h-4 w-4"})})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{children:"Share via"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(B,{variant:"outline",className:"flex-1",onClick:()=>g("email"),disabled:c,children:[e.jsx(mn,{className:"h-4 w-4 mr-2"}),"Email"]}),e.jsxs(B,{variant:"outline",className:"flex-1",onClick:()=>g("text"),disabled:c,children:[e.jsx(xo,{className:"h-4 w-4 mr-2"}),"Text"]}),e.jsxs(B,{variant:"outline",className:"flex-1",onClick:()=>g("facebook"),disabled:c,children:[e.jsx(Kf,{className:"h-4 w-4 mr-2"}),"Facebook"]})]})]}),l&&(l.click_count>0||l.lead_count>0)&&e.jsxs("div",{className:"pt-4 border-t",children:[e.jsx(re,{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(da,{className:"h-4 w-4"}),e.jsx("span",{className:"text-xs",children:"Clicks"})]}),e.jsx("p",{className:"text-2xl font-bold",children:l.click_count})]}),e.jsxs("div",{className:"bg-primary/10 rounded-lg p-3 text-center",children:[e.jsxs("div",{className:"flex items-center justify-center gap-1 text-primary mb-1",children:[e.jsx(Yn,{className:"h-4 w-4"}),e.jsx("span",{className:"text-xs",children:"Leads"})]}),e.jsx("p",{className:"text-2xl font-bold text-primary",children:l.lead_count})]})]})]})]})]})})}const njn={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"},rjn={active:"Active",coming_soon:"Coming Soon",office_exclusive:"Office Exclusive",pre_market:"Pre-Market",price_improvement:"Price Improvement",under_contract:"Under Contract",sold:"Sold"},ajn={single_family:"Single Family",condo:"Condo",townhouse:"Townhouse",land:"Land",multi_family:"Multi-Family",luxury:"Luxury",commercial:"Commercial",other:"Other"};function ijn({listing:s,onClick:t,onEdit:n,onDelete:r,onCreateMusicVideo:a,showActions:i}){var x,_;const{user:l}=Ls(),{data:o}=D4t(s.id),c=I4t(),[d,u]=N.useState(!1),h=b=>new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:0}).format(b),m=((x=s.photos)==null?void 0:x.find(b=>b.is_primary))||((_=s.photos)==null?void 0:_[0]),f=(l==null?void 0:l.id)===s.agent_id,g=async b=>{b.stopPropagation();try{const k=await c.mutateAsync(s.id);ie.success(k.saved?"Listing saved!":"Listing removed from saved")}catch{ie.error("Failed to save listing")}},y=b=>{if(b.stopPropagation(),l)u(!0);else{const k=`https://listings.relevelup.com/${s.slug||s.id}`;navigator.clipboard.writeText(k),ie.success("Link copied to clipboard!")}};return e.jsxs(_e,{className:"overflow-hidden hover:shadow-lg transition-shadow cursor-pointer group",onClick:t,children:[e.jsxs("div",{className:"relative aspect-[4/3] bg-muted",children:[m?e.jsx("img",{src:m.photo_url,alt:s.property_address||s.city,className:"w-full h-full object-cover group-hover:scale-105 transition-transform duration-300"}):e.jsx("div",{className:"w-full h-full flex items-center justify-center text-muted-foreground",children:e.jsx(L_,{className:"h-12 w-12"})}),e.jsx(We,{className:`absolute top-2 left-2 ${njn[s.status]} text-white border-0`,children:rjn[s.status]}),s.is_featured&&e.jsx("div",{className:"absolute top-2 right-2 p-1.5 bg-amber-500 rounded-full",children:e.jsx(Wa,{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:g,children:e.jsx(co,{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:y,title:f?"Copy link":"Share & earn leads",children:f?e.jsx(Md,{className:"h-4 w-4"}):e.jsx(Cn,{className:"h-4 w-4 text-amber-500"})})]})]}),e.jsx(g7t,{open:d,onOpenChange:u,listingId:s.id,listingSlug:s.slug||null,listingTitle:s.property_address||`${s.city}, ${s.state}`}),e.jsxs(De,{className:"p-4 space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("p",{className:"text-xl font-bold text-primary",children:h(s.price)}),s.open_to_referrals&&e.jsxs(We,{variant:"outline",className:"text-xs",children:[e.jsx(Yn,{className:"h-3 w-3 mr-1"}),"Referrals"]})]}),e.jsxs("div",{children:[s.property_address&&e.jsx("p",{className:"font-medium truncate",children:s.property_address}),e.jsxs("p",{className:"text-sm text-muted-foreground flex items-center gap-1",children:[e.jsx(ii,{className:"h-3 w-3"}),s.city,", ",s.state,s.neighborhood&&` • ${s.neighborhood}`]})]}),e.jsxs("div",{className:"flex items-center gap-4 text-sm text-muted-foreground",children:[s.bedrooms&&e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(A_,{className:"h-4 w-4"}),s.bedrooms," bd"]}),s.bathrooms&&e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Wx,{className:"h-4 w-4"}),s.bathrooms," ba"]}),s.square_footage&&e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(L_,{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(We,{variant:"secondary",className:"text-xs",children:ajn[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(da,{className:"h-3 w-3"}),s.view_count]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Md,{className:"h-3 w-3"}),s.share_count]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(co,{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:b=>{b.stopPropagation(),a()},children:[e.jsx(j9,{className:"h-4 w-4"}),"Music Video"]}),n&&e.jsxs(B,{variant:"outline",size:"sm",className:"flex-1",onClick:b=>{b.stopPropagation(),n()},children:[e.jsx(xp,{className:"h-4 w-4 mr-2"}),"Edit"]}),r&&e.jsx(B,{variant:"destructive",size:"sm",onClick:b=>{b.stopPropagation(),r()},children:e.jsx(qn,{className:"h-4 w-4"})})]})]})]})}const UWe="lu_listing_selection_v1",B5e=24,$5e=new Set;function x7t(){try{return JSON.parse(sessionStorage.getItem(UWe)||"{}")}catch{return{}}}function UPe(s){try{sessionStorage.setItem(UWe,JSON.stringify(s))}catch{}$5e.forEach(t=>t())}let QS=x7t();function ojn(){QS=x7t(),$5e.forEach(s=>s())}typeof window<"u"&&window.addEventListener("storage",s=>{s.key===UWe&&ojn()});const nA={getSnapshot:()=>QS,subscribe(s){return $5e.add(s),()=>$5e.delete(s)},toggle(s){const t={...QS};if(t[s.mlsNumber])delete t[s.mlsNumber];else{if(Object.keys(t).length>=B5e)return!1;t[s.mlsNumber]=s}return QS=t,UPe(t),!0},remove(s){const t={...QS};delete t[s],QS=t,UPe(t)},clear(){QS={},UPe({})},has(s){return!!QS[s]},all(){return Object.values(QS)}};function y7t(){const s=N.useSyncExternalStore(nA.subscribe,nA.getSnapshot,nA.getSnapshot);return{selected:Object.values(s),selectedIds:new Set(Object.keys(s)),count:Object.keys(s).length,has:t=>!!s[t],toggle:nA.toggle,remove:nA.remove,clear:nA.clear}}const ljn=new Set(["office_exclusive","coming_soon","pre_market"]);function cjn(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=ljn.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 Cne(s){const{has:t}=y7t(),n=`lx-${s.listing.id}`,r=t(n);return e.jsxs("div",{className:"relative",children:[e.jsx(ijn,{...s}),e.jsx("button",{type:"button",onClick:a=>{a.stopPropagation(),nA.toggle(cjn(s.listing))||ie.error(`You can select up to ${B5e} 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(pa,{className:"h-4 w-4"}):e.jsx(mn,{className:"h-4 w-4"})})]})}function djn({open:s,onOpenChange:t,listings:n}){const{user:r}=Ls(),{leadSite:a}=Qx(),[i,l]=N.useState("grid"),[o,c]=N.useState(""),[d,u]=N.useState(""),[h,m]=N.useState(""),[f,g]=N.useState(new Set),[y,x]=N.useState(!1),[_,b]=N.useState(!1),{data:k}=OCe(),[A,T]=N.useState(!1);N.useEffect(()=>{!s||!(r!=null&&r.id)||H.from("gmail_integrations").select("gmail_email").eq("user_id",r.id).maybeSingle().then(({data:X})=>b(!!(X!=null&&X.gmail_email)))},[s,r==null?void 0:r.id]),N.useEffect(()=>{if(s){if(!o){const X=Array.from(new Set(n.map(ne=>ne.city).filter(Boolean))),te=X.length===1?` in ${X[0]}`:"";c(n.length===1?`New listing for you${te}`:`${n.length} hand-picked listings${te}`)}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:P=[],isLoading:I}=mt({queryKey:["send-listings-contacts",r==null?void 0:r.id],queryFn:async()=>{const{data:X}=await H.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 X||[]},enabled:!!(r!=null&&r.id)&&s}),{data:M}=mt({queryKey:["send-listings-suggestions",n.map(X=>X.mlsNumber).join(",")],queryFn:async()=>{const{data:X,error:te}=await H.functions.invoke("listing-email-suggestions",{body:{listings:n.map(ne=>({mlsNumber:ne.mlsNumber,city:ne.city,state:ne.state,price:ne.price,bedrooms:ne.bedrooms,bathrooms:ne.bathrooms}))}});if(te)throw te;return X},enabled:s&&n.length>0}),L=(M==null?void 0:M.suggestions)||[],z=N.useMemo(()=>{const X=h.trim().toLowerCase();return X?P.filter(te=>`${te.first_name??""} ${te.last_name??""} ${te.email} ${te.city??""}`.toLowerCase().includes(X)):P},[P,h]),$=X=>{g(te=>{const ne=new Set(te);return ne.has(X)?ne.delete(X):ne.add(X),ne})},V=()=>{g(X=>{const te=new Set(X);return L.forEach(ne=>te.add(ne.contact_id)),te})},W=n.length>0&&n.every(X=>X.mlsNumber.startsWith("lx-")),G=async()=>{if(!W&&!(a!=null&&a.id)){ie.error("You need an active lead site to send listings.");return}if(!o.trim())return ie.error("Subject is required");if(f.size===0)return ie.error("Pick at least one recipient");if(!_&&k&&!k.hasVerifiedSes){T(!0);return}const X=P.filter(te=>f.has(te.id)).map(te=>({contact_id:te.id,email:te.email,first_name:te.first_name,last_name:te.last_name}));x(!0);try{const{data:te,error:ne}=await H.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(me=>({mlsNumber:me.mlsNumber,address:me.address,city:me.city,state:me.state,zip:me.zip,price:me.price,bedrooms:me.bedrooms,bathrooms:me.bathrooms,sqft:me.sqft,status:me.status,photos:(me.photos||[]).slice(0,1),description:me.description||"",external_url:me.externalUrl||null,is_private:me.is_private===!0})),recipients:X}});if(ne)throw ne;if(!(te!=null&&te.success))throw new Error((te==null?void 0:te.error)||"Send failed");ie.success(`Sent ${te.sent}/${X.length} via ${_?"Gmail":"Amazon SES"}${te.failed?` · ${te.failed} failed`:""}`),nA.clear(),g(new Set),t(!1)}catch(te){ie.error((te==null?void 0:te.message)||"Failed to send")}finally{x(!1)}};return e.jsxs(Bs,{open:s,onOpenChange:t,children:[e.jsxs(Fs,{className:"max-w-5xl max-h-[92vh] overflow-hidden p-0 flex flex-col",children:[e.jsxs(qs,{className:"px-6 pt-6 pb-2",children:[e.jsxs($s,{className:"flex items-center gap-2",children:[e.jsx(mn,{className:"h-5 w-5 text-primary"}),"Email ",n.length," ",n.length===1?"Listing":"Listings"]}),e.jsx(Ar,{children:W?"Send your Listing Exchange properties. Recipients land on listings.relevelup.com and clicks track back to the contact.":"Drive traffic to your site. Recipients land on your lead site and clicks show up on Mission Control."})]}),e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-0 flex-1 overflow-hidden",children:[e.jsxs("div",{className:"overflow-y-auto px-6 pb-4 space-y-4 border-r",children:[e.jsxs("div",{children:[e.jsx(re,{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(X=>{var te;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:((te=X.photos)==null?void 0:te[0])&&e.jsx("img",{src:X.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:["$",(X.price/1e3).toFixed(0),"k"]}),e.jsxs("div",{className:"text-[10px] text-muted-foreground truncate",children:[X.city,", ",X.state]})]})]},X.mlsNumber)})})]}),e.jsxs("div",{children:[e.jsx(re,{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(G0,{className:"h-4 w-4 mb-1.5"}),e.jsx("div",{className:"text-sm font-medium",children:"Magazine grid"}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"Clean card stack"})]}),e.jsxs("button",{type:"button",onClick:()=>l("hero"),className:`rounded-lg border p-3 text-left transition ${i==="hero"?"border-primary bg-primary/5":"hover:bg-muted/50"}`,children:[e.jsx(pc,{className:"h-4 w-4 mb-1.5"}),e.jsx("div",{className:"text-sm font-medium",children:"Hero + list"}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"First listing gets spotlight"})]})]})]}),e.jsxs("div",{children:[e.jsx(re,{htmlFor:"subject",children:"Subject"}),e.jsx(we,{id:"subject",value:o,onChange:X=>c(X.target.value),placeholder:"Subject line",className:"mt-1"})]}),e.jsxs("div",{children:[e.jsx(re,{htmlFor:"intro",children:"Personal message"}),e.jsx(Ws,{id:"intro",value:d,onChange:X=>u(X.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:_?"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:[L.length>0&&e.jsxs(_e,{className:"p-3 bg-amber-50/50 border-amber-200",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Cn,{className:"h-4 w-4 text-amber-600"}),e.jsxs("div",{className:"text-sm font-medium",children:[L.length," smart ",L.length===1?"match":"matches"]})]}),e.jsx(B,{size:"sm",variant:"outline",onClick:V,children:"Add all"})]}),e.jsx(lo,{className:"max-h-32 mt-2",children:e.jsx("div",{className:"space-y-1",children:L.slice(0,12).map(X=>{const te=f.has(X.contact_id);return e.jsxs("label",{className:"flex items-start gap-2 text-xs py-1 cursor-pointer",children:[e.jsx(Bi,{checked:te,onCheckedChange:()=>$(X.contact_id),className:"mt-0.5"}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"font-medium truncate",children:[X.first_name," ",X.last_name??""," ",e.jsxs("span",{className:"text-muted-foreground font-normal",children:["· ",X.email]})]}),e.jsx("div",{className:"text-muted-foreground truncate",children:X.reason})]})]},X.contact_id)})})})]}),e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsxs(re,{className:"text-xs uppercase tracking-wide text-muted-foreground",children:["All contacts (",z.length,")"]}),f.size>0&&e.jsxs(We,{variant:"secondary",children:[f.size," selected"]})]}),e.jsx(we,{placeholder:"Search contacts…",value:h,onChange:X=>m(X.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(lo,{className:"h-full",children:I?e.jsx("div",{className:"p-4 text-sm text-muted-foreground",children:"Loading…"}):z.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:z.map(X=>{const te=f.has(X.id);return e.jsxs("label",{className:"flex items-center gap-2 px-3 py-2 cursor-pointer hover:bg-muted/40",children:[e.jsx(Bi,{checked:te,onCheckedChange:()=>$(X.id)}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"text-sm font-medium truncate",children:[X.first_name," ",X.last_name??""]}),e.jsxs("div",{className:"text-xs text-muted-foreground truncate",children:[X.email,X.city&&e.jsxs(e.Fragment,{children:[" · ",X.city]})]})]})]},X.id)})})})})}),e.jsxs("div",{className:"px-6 py-2 text-xs text-muted-foreground border-t flex items-center justify-between",children:[e.jsxs("span",{children:[e.jsx("strong",{className:"text-foreground",children:f.size})," recipients"]}),f.size>0&&e.jsxs(B,{variant:"ghost",size:"sm",className:"h-7 text-xs",onClick:()=>g(new Set),children:[e.jsx(hr,{className:"h-3 w-3 mr-1"}),"Clear"]})]})]})]}),e.jsxs(Cr,{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:G,disabled:y||f.size===0,children:y?e.jsxs(e.Fragment,{children:[e.jsx(us,{className:"h-4 w-4 mr-2 animate-spin"}),"Sending…"]}):e.jsxs(e.Fragment,{children:[e.jsx(Rr,{className:"h-4 w-4 mr-2"}),"Send to ",f.size," ",f.size===1?"contact":"contacts"]})})]})]}),e.jsx(FCe,{open:A,onOpenChange:T,hasPending:!!(k!=null&&k.hasPendingSes),pendingEmails:k==null?void 0:k.pendingEmails})]})}function ujn(){const{selected:s,count:t,remove:n,clear:r}=y7t(),[a,i]=N.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>=B5e?"Max reached":`Pick up to ${B5e}`})]})]}),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(hr,{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(qn,{className:"h-4 w-4"})," Clear"]}),e.jsxs(B,{size:"sm",className:"gap-1.5",onClick:()=>i(!0),children:[e.jsx(Rr,{className:"h-4 w-4"}),"Email these ",t===1?"listing":"listings"]})]})]})}),e.jsx(djn,{open:a,onOpenChange:i,listings:s})]})}const hjn=[{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"}],mjn=[{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 pjn({filters:s,onFiltersChange:t,onClose:n}){const r=()=>{t({sortBy:"newest"})};return e.jsxs(_e,{children:[e.jsxs(zt,{className:"flex flex-row items-center justify-between pb-3",children:[e.jsx(qt,{className:"text-lg",children:"Filters"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(B,{variant:"ghost",size:"sm",onClick:r,children:"Clear All"}),e.jsx(B,{variant:"ghost",size:"icon",onClick:n,children:e.jsx(hr,{className:"h-4 w-4"})})]})]}),e.jsxs(De,{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(re,{children:"Status"}),e.jsxs(Ns,{value:s.status||"all",onValueChange:a=>t({...s,status:a==="all"?void 0:a}),children:[e.jsx(ws,{children:e.jsx(ks,{placeholder:"All statuses"})}),e.jsxs(js,{children:[e.jsx(nt,{value:"all",children:"All Statuses"}),hjn.map(a=>e.jsx(nt,{value:a.value,children:a.label},a.value))]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{children:"Property Type"}),e.jsxs(Ns,{value:s.propertyType||"all",onValueChange:a=>t({...s,propertyType:a==="all"?void 0:a}),children:[e.jsx(ws,{children:e.jsx(ks,{placeholder:"All types"})}),e.jsxs(js,{children:[e.jsx(nt,{value:"all",children:"All Types"}),mjn.map(a=>e.jsx(nt,{value:a.value,children:a.label},a.value))]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{children:"Min Price"}),e.jsx(we,{type:"number",placeholder:"No minimum",value:s.minPrice||"",onChange:a=>t({...s,minPrice:a.target.value?Number(a.target.value):void 0})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{children:"Max Price"}),e.jsx(we,{type:"number",placeholder:"No maximum",value:s.maxPrice||"",onChange:a=>t({...s,maxPrice:a.target.value?Number(a.target.value):void 0})})]})]}),e.jsxs("div",{className:"flex items-center justify-between mt-4 pt-4 border-t",children:[e.jsxs("div",{children:[e.jsx(re,{children:"Open to Referrals Only"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Show only listings accepting buyer referrals"})]}),e.jsx(zn,{checked:s.openToReferrals||!1,onCheckedChange:a=>t({...s,openToReferrals:a||void 0})})]})]})]})}function fjn({leaderboard:s}){const t=r=>{switch(r){case 0:return e.jsx(gl,{className:"h-5 w-5 text-amber-500"});case 1:return e.jsx(i3,{className:"h-5 w-5 text-gray-400"});case 2:return e.jsx(ku,{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(We,{variant:l===0?"default":"secondary",children:[i.count," ",a]})]},i.agentId))});return e.jsxs("div",{className:"space-y-6",children:[e.jsxs(_e,{children:[e.jsx(zt,{children:e.jsxs(qt,{className:"flex items-center gap-2",children:[e.jsx(gl,{className:"h-5 w-5 text-amber-500"}),"Community Badges"]})}),e.jsx(De,{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(Md,{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(_a,{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(i3,{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(gl,{className:"h-6 w-6 text-amber-500"})}),e.jsx("p",{className:"font-medium text-sm",children:"Community MVP"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Top performer"})]})]})})]}),e.jsxs(_e,{children:[e.jsx(zt,{children:e.jsx(qt,{children:"Community Leaderboard"})}),e.jsx(De,{children:e.jsxs(ya,{defaultValue:"sharers",children:[e.jsxs(va,{className:"w-full",children:[e.jsxs(ls,{value:"sharers",className:"flex-1",children:[e.jsx(Md,{className:"h-4 w-4 mr-2"}),"Top Sharers"]}),e.jsxs(ls,{value:"listers",className:"flex-1",children:[e.jsx(_a,{className:"h-4 w-4 mr-2"}),"Top Contributors"]})]}),e.jsx(_s,{value:"sharers",className:"mt-4",children:n(s==null?void 0:s.topSharers,"shares")}),e.jsx(_s,{value:"listers",className:"mt-4",children:n(s==null?void 0:s.topListers,"listings")})]})})]})]})}const jft={coming_soon:"#F59E0B",office_exclusive:"#6366F1",pre_market:"#06B6D4",active:"#10B981",price_improvement:"#8B5CF6",under_contract:"#3B82F6",sold:"#A855F7"},Nft={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 gjn(s){return s>=1e6?`$${(s/1e6).toFixed(1)}M`:`$${(s/1e3).toFixed(0)}K`}function xjn({listings:s,isLoading:t}){const n=tr(),r=N.useRef(null),a=N.useRef(null),i=N.useRef([]),{isAdmin:l}=Ls(),[o,c]=N.useState(""),[d,u]=N.useState(!0),[h,m]=N.useState(!1),f=s.filter(y=>y.latitude!=null&&y.longitude!=null),g=s.filter(y=>(y.latitude==null||y.longitude==null)&&(y.property_address||y.city));return N.useEffect(()=>{(async()=>{u(!0);try{const{data:x}=await H.from("settings").select("value").eq("key","mapbox_public_token").maybeSingle();x!=null&&x.value&&c(x.value)}catch(x){console.error("Error fetching mapbox token:",x)}u(!1)})()},[]),N.useEffect(()=>{if(!o||g.length===0||h)return;(async()=>{var x;m(!0);for(const _ of g){const b=[_.property_address,_.city,_.state].filter(Boolean).join(", ");if(b)try{const A=await(await fetch(`https://api.mapbox.com/geocoding/v5/mapbox.places/${encodeURIComponent(b)}.json?access_token=${o}&limit=1`)).json();if((x=A.features)!=null&&x[0]){const[T,P]=A.features[0].center;await H.from("listings").update({latitude:P,longitude:T}).eq("id",_.id),_.latitude=P,_.longitude=T}}catch(k){console.error("Geocode error:",k)}}m(!1)})()},[o,s]),N.useEffect(()=>{if(!r.current||!o||a.current)return;Rc.accessToken=o;const y=s.filter(b=>b.latitude!=null&&b.longitude!=null);let x=[-98.5795,39.8283],_=4;if(y.length>0){const b=y.reduce((A,T)=>A+T.longitude,0)/y.length,k=y.reduce((A,T)=>A+T.latitude,0)/y.length;x=[b,k],_=y.length===1?12:10}return a.current=new Rc.Map({container:r.current,style:"mapbox://styles/mapbox/light-v11",zoom:_,center:x}),a.current.addControl(new Rc.NavigationControl,"top-right"),()=>{var b;(b=a.current)==null||b.remove(),a.current=null}},[o]),N.useEffect(()=>{if(!a.current||!o)return;i.current.forEach(x=>x.remove()),i.current=[];const y=s.filter(x=>x.latitude!=null&&x.longitude!=null);if(y.forEach(x=>{var P,I,M;const _=jft[x.status]||"#10B981",b=((P=x.photos)==null?void 0:P.find(L=>L.is_primary))||((I=x.photos)==null?void 0:I[0]),k=document.createElement("div");k.className="cursor-pointer",k.innerHTML=`
`;const A=new Rc.Popup({offset:25,closeButton:!0,maxWidth:"280px"}).setHTML(`
${b!=null&&b.photo_url?``:""}
${gjn(x.price)}
${x.property_address||""}
${x.city}, ${x.state}
${Nft[x.status]||x.status} ${x.bedrooms?`${x.bedrooms} bed`:""} ${x.bathrooms?`${x.bathrooms} bath`:""}
${(M=x.agent)!=null&&M.name?`
Listed by ${x.agent.name}
`:""}
Click to view details →
`),T=new Rc.Marker(k).setLngLat([x.longitude,x.latitude]).setPopup(A).addTo(a.current);i.current.push(T)}),y.length>1){const x=new Rc.LngLatBounds;y.forEach(_=>x.extend([_.longitude,_.latitude])),a.current.fitBounds(x,{padding:60,maxZoom:13})}else y.length===1&&a.current.flyTo({center:[y[0].longitude,y[0].latitude],zoom:12})},[s,o,h]),N.useEffect(()=>(window.__navigateToListing__=y=>{n(`/mission-control/listings/${y}`)},()=>{delete window.__navigateToListing__}),[n]),d||t?e.jsx(_e,{children:e.jsx(De,{className:"flex items-center justify-center h-[60vh]",children:e.jsx("div",{className:"animate-spin rounded-full h-8 w-8 border-b-2 border-primary"})})}):o?s.length===0?e.jsx(_e,{children:e.jsxs(De,{className:"flex flex-col items-center justify-center h-[60vh] text-center gap-3",children:[e.jsx(ii,{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(jft).map(([y,x])=>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:x}}),e.jsx("span",{className:"text-xs",children:Nft[y]})]},y)),e.jsxs("span",{className:"text-muted-foreground ml-auto text-xs",children:[f.length," of ",s.length," mapped",h&&" · Geocoding..."]})]}),e.jsx("div",{ref:r,className:"w-full h-[60vh] rounded-lg shadow-lg border"})]}):e.jsx(_e,{children:e.jsxs(De,{className:"flex flex-col items-center justify-center h-[60vh] text-center gap-3",children:[e.jsx(Uo,{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 mze="homereel_mv_prefill",pze="homereel_mv_badge_default";function v7t(s){try{sessionStorage.setItem(mze,JSON.stringify(s)),s.badge&&s.badge.type!=="none"&&sessionStorage.setItem(pze,JSON.stringify(s.badge))}catch{}}function CFn(){try{const s=sessionStorage.getItem(mze);return s?(sessionStorage.removeItem(mze),JSON.parse(s)):null}catch{return null}}function AFn(){try{const s=sessionStorage.getItem(pze);return s?(sessionStorage.removeItem(pze),JSON.parse(s)):null}catch{return null}}function b7t(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 yjn(){var L,z,$,V,W,G,X,te;const s=tr(),{brokerageId:t}=Ls(),{data:n,isLoading:r}=E4t(),[a,i]=N.useState("feed"),[l,o]=N.useState(!1),[c,d]=N.useState(""),[u,h]=N.useState({sortBy:"newest"}),{data:m,isLoading:f}=M4t({...u,city:c||u.city}),{data:g,isLoading:y}=qjs(),{data:x,isLoading:_}=L4t(),{data:b,isLoading:k}=Wjs(),{data:A,isLoading:T}=Zjs(),{data:P}=Yjs(),I=P4t(),M=async ne=>{if(confirm("Are you sure you want to delete this listing? This action cannot be undone."))try{await I.mutateAsync(ne),ie.success("Listing deleted successfully")}catch{ie.error("Failed to delete listing")}};return r?e.jsx(Qs,{title:"Listing Exchange",description:"Community-powered listing collaboration",children:e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsx("div",{className:"animate-spin h-8 w-8 border-4 border-primary border-t-transparent rounded-full"})})}):n?e.jsxs(Qs,{title:"Listing Exchange",description:"Community-powered listing collaboration",children:[e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center justify-between gap-4",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("h1",{className:"text-2xl font-bold",children:"Listing Exchange"}),e.jsx("span",{className:"text-[10px] font-semibold uppercase tracking-wide px-1.5 py-0.5 rounded border border-amber-500 text-amber-600 dark:text-amber-400 bg-amber-500/10",children:"Beta"})]}),e.jsxs(B,{onClick:()=>s("/mission-control/listings/new"),children:[e.jsx(nn,{className:"h-4 w-4 mr-2"}),"Add Listing"]})]}),e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4",children:[e.jsx(_e,{children:e.jsxs(De,{className:"p-4 flex items-center gap-3",children:[e.jsx("div",{className:"p-2 bg-primary/10 rounded-lg",children:e.jsx(_a,{className:"h-5 w-5 text-primary"})}),e.jsxs("div",{children:[e.jsx("p",{className:"text-2xl font-bold",children:(m==null?void 0:m.length)||0}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Active Listings"})]})]})}),e.jsx(_e,{children:e.jsxs(De,{className:"p-4 flex items-center gap-3",children:[e.jsx("div",{className:"p-2 bg-pink-500/10 rounded-lg",children:e.jsx(co,{className:"h-5 w-5 text-pink-500"})}),e.jsxs("div",{children:[e.jsx("p",{className:"text-2xl font-bold",children:(g==null?void 0:g.length)||0}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Saved"})]})]})}),e.jsx(_e,{children:e.jsxs(De,{className:"p-4 flex items-center gap-3",children:[e.jsx("div",{className:"p-2 bg-emerald-500/10 rounded-lg",children:e.jsx(iD,{className:"h-5 w-5 text-emerald-500"})}),e.jsxs("div",{children:[e.jsx("p",{className:"text-2xl font-bold",children:(x==null?void 0:x.length)||0}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"My Listings"})]})]})}),e.jsx(_e,{children:e.jsxs(De,{className:"p-4 flex items-center gap-3",children:[e.jsx("div",{className:"p-2 bg-sky-500/10 rounded-lg",children:e.jsx(Yn,{className:"h-5 w-5 text-sky-500"})}),e.jsxs("div",{children:[e.jsx("p",{className:"text-2xl font-bold",children:(((L=b==null?void 0:b.sent)==null?void 0:L.length)||0)+(((z=b==null?void 0:b.received)==null?void 0:z.length)||0)}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Referrals"})]})]})})]}),e.jsxs(ya,{value:a,onValueChange:i,children:[e.jsxs(va,{className:"w-full justify-start overflow-x-auto",children:[e.jsx(ls,{value:"feed",children:"Community Feed"}),t&&e.jsx(ls,{value:"brokerage",children:"Brokerage"}),e.jsx(ls,{value:"my-listings",children:"My Listings"}),e.jsx(ls,{value:"saved",children:"Saved"}),e.jsx(ls,{value:"referrals",children:"Referrals"}),e.jsx(ls,{value:"map",children:"Map"}),e.jsx(ls,{value:"leaderboard",children:"Leaderboard"})]}),e.jsxs(_s,{value:"feed",className:"space-y-4",children:[e.jsxs("div",{className:"flex flex-col sm:flex-row gap-3",children:[e.jsxs("div",{className:"relative flex-1",children:[e.jsx(Gr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(we,{placeholder:"Search by city or neighborhood...",value:c,onChange:ne=>d(ne.target.value),className:"pl-9"})]}),e.jsxs(Ns,{value:u.sortBy,onValueChange:ne=>h({...u,sortBy:ne}),children:[e.jsx(ws,{className:"w-[180px]",children:e.jsx(ks,{placeholder:"Sort by"})}),e.jsxs(js,{children:[e.jsx(nt,{value:"newest",children:"Newest First"}),e.jsx(nt,{value:"updated",children:"Recently Updated"}),e.jsx(nt,{value:"price_asc",children:"Price: Low to High"}),e.jsx(nt,{value:"price_desc",children:"Price: High to Low"})]})]}),e.jsxs(B,{variant:"outline",onClick:()=>o(!l),children:[e.jsx(cj,{className:"h-4 w-4 mr-2"}),"Filters"]})]}),l&&e.jsx(pjn,{filters:u,onFiltersChange:h,onClose:()=>o(!1)}),f?e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4",children:[...Array(6)].map((ne,me)=>e.jsxs(_e,{children:[e.jsx(xn,{className:"h-48 w-full"}),e.jsxs(De,{className:"p-4 space-y-2",children:[e.jsx(xn,{className:"h-5 w-3/4"}),e.jsx(xn,{className:"h-4 w-1/2"}),e.jsx(xn,{className:"h-4 w-1/4"})]})]},me))}):(m==null?void 0:m.length)===0?e.jsx(_e,{children:e.jsxs(De,{className:"py-12 text-center",children:[e.jsx(_a,{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(nn,{className:"h-4 w-4 mr-2"}),"Add Listing"]})]})}):e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4",children:m==null?void 0:m.map(ne=>e.jsx(Cne,{listing:ne,onClick:()=>s(`/mission-control/listings/${ne.id}`)},ne.id))})]}),e.jsx(_s,{value:"my-listings",className:"space-y-4",children:_?e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4",children:[...Array(3)].map((ne,me)=>e.jsxs(_e,{children:[e.jsx(xn,{className:"h-48 w-full"}),e.jsxs(De,{className:"p-4 space-y-2",children:[e.jsx(xn,{className:"h-5 w-3/4"}),e.jsx(xn,{className:"h-4 w-1/2"})]})]},me))}):(x==null?void 0:x.length)===0?e.jsx(_e,{children:e.jsxs(De,{className:"py-12 text-center",children:[e.jsx(iD,{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(nn,{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:x==null?void 0:x.map(ne=>e.jsx(Cne,{listing:ne,showActions:!0,onClick:()=>s(`/mission-control/listings/${ne.id}`),onEdit:()=>s(`/mission-control/listings/${ne.id}/edit`),onDelete:()=>M(ne.id),onCreateMusicVideo:()=>{const me=(ne.photos??[]).slice().sort((ue,ce)=>(ce.is_primary?1:0)-(ue.is_primary?1:0)||(ue.sort_order??0)-(ce.sort_order??0)).map(ue=>ue.photo_url).filter(Boolean);if(me.length===0){ie.error("Add photos to this listing first.");return}v7t({photos:me,details:{address:ne.property_address||`${ne.city??""} ${ne.state??""}`.trim(),beds:ne.bedrooms?String(ne.bedrooms):"",baths:ne.bathrooms?String(ne.bathrooms):"",sqft:ne.square_footage?String(ne.square_footage):"",price:ne.price?String(ne.price):"",highlights:ne.description||""},sourceLabel:"My Listings",badge:b7t(ne.status,ne.price)}),s("/admin/beta/homereel?tab=music-video")}},ne.id))})}),e.jsx(_s,{value:"saved",className:"space-y-4",children:y?e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4",children:[...Array(3)].map((ne,me)=>e.jsxs(_e,{children:[e.jsx(xn,{className:"h-48 w-full"}),e.jsxs(De,{className:"p-4 space-y-2",children:[e.jsx(xn,{className:"h-5 w-3/4"}),e.jsx(xn,{className:"h-4 w-1/2"})]})]},me))}):(g==null?void 0:g.length)===0?e.jsx(_e,{children:e.jsxs(De,{className:"py-12 text-center",children:[e.jsx(co,{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:g==null?void 0:g.map(ne=>e.jsx(Cne,{listing:ne.listing,onClick:()=>s(`/mission-control/listings/${ne.listing.id}`)},ne.id))})}),e.jsx(_s,{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(Md,{className:"h-4 w-4"}),"Referrals Sent (",(($=b==null?void 0:b.sent)==null?void 0:$.length)||0,")"]}),((V=b==null?void 0:b.sent)==null?void 0:V.length)===0?e.jsx(_e,{children:e.jsx(De,{className:"py-8 text-center text-muted-foreground",children:"No referrals sent yet"})}):e.jsx("div",{className:"space-y-3",children:(W=b==null?void 0:b.sent)==null?void 0:W.map(ne=>{var me,ue;return e.jsx(_e,{children:e.jsx(De,{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:ne.buyer_name}),e.jsx("p",{className:"text-sm text-muted-foreground",children:((me=ne.listing)==null?void 0:me.property_address)||((ue=ne.listing)==null?void 0:ue.city)})]}),e.jsx(We,{variant:ne.status==="closed"?"default":"secondary",children:ne.status.replace("_"," ")})]})})},ne.id)})})]}),e.jsxs("div",{children:[e.jsxs("h3",{className:"font-semibold mb-3 flex items-center gap-2",children:[e.jsx(Yn,{className:"h-4 w-4"}),"Referrals Received (",((G=b==null?void 0:b.received)==null?void 0:G.length)||0,")"]}),((X=b==null?void 0:b.received)==null?void 0:X.length)===0?e.jsx(_e,{children:e.jsx(De,{className:"py-8 text-center text-muted-foreground",children:"No referrals received yet"})}):e.jsx("div",{className:"space-y-3",children:(te=b==null?void 0:b.received)==null?void 0:te.map(ne=>{var me;return e.jsx(_e,{children:e.jsxs(De,{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:ne.buyer_name}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:["From: ",(me=ne.sender)==null?void 0:me.name]})]}),e.jsx(We,{variant:ne.status==="closed"?"default":"secondary",children:ne.status.replace("_"," ")})]}),e.jsx(B,{size:"sm",variant:"outline",className:"w-full mt-2",onClick:()=>s(`/mission-control/listings/${ne.listing_id}`),children:"View Listing"})]})},ne.id)})})]})]})}),t&&e.jsx(_s,{value:"brokerage",className:"space-y-4",children:T?e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4",children:[...Array(3)].map((ne,me)=>e.jsxs(_e,{children:[e.jsx(xn,{className:"h-48 w-full"}),e.jsxs(De,{className:"p-4 space-y-2",children:[e.jsx(xn,{className:"h-5 w-3/4"}),e.jsx(xn,{className:"h-4 w-1/2"})]})]},me))}):(A==null?void 0:A.length)===0?e.jsx(_e,{children:e.jsxs(De,{className:"py-12 text-center",children:[e.jsx(iD,{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(nn,{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:A==null?void 0:A.map(ne=>e.jsx(Cne,{listing:ne,onClick:()=>s(`/mission-control/listings/${ne.id}`)},ne.id))})}),e.jsx(_s,{value:"map",children:e.jsx(xjn,{listings:m||[],isLoading:f})}),e.jsx(_s,{value:"leaderboard",children:e.jsx(fjn,{leaderboard:P})})]})]}),e.jsx(ujn,{})]}):e.jsx(Qs,{title:"Listing Exchange",description:"Community-powered listing collaboration",children:e.jsx(_e,{children:e.jsxs(De,{className:"py-12 text-center",children:[e.jsx(_a,{className:"h-12 w-12 mx-auto text-muted-foreground mb-4"}),e.jsx("h2",{className:"text-xl font-semibold mb-2",children:"Coming Soon"}),e.jsx("p",{className:"text-muted-foreground",children:"Listing Exchange is currently in development. Check back soon!"})]})})})}function _7t(s){return mt({queryKey:["listing-documents",s],queryFn:async()=>{const{data:t,error:n}=await H.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 vjn(){const{user:s}=Ls(),t=as();return _t({mutationFn:async({listingId:n,file:r})=>{if(!(s!=null&&s.id))throw new Error("Not authenticated");const a=r.name.split(".").pop(),i=`${s.id}/${n}/${crypto.randomUUID()}.${a}`,{error:l}=await H.storage.from("listing-documents").upload(i,r,{contentType:r.type||void 0});if(l)throw l;const{data:o,error:c}=await H.from("listing_documents").insert({listing_id:n,owner_user_id:s.id,file_name:r.name,file_size:r.size,file_type:r.type||null,storage_path:i}).select().single();if(c)throw c;return o},onSuccess:(n,r)=>{t.invalidateQueries({queryKey:["listing-documents",r.listingId]})}})}function bjn(){const s=as();return _t({mutationFn:async({id:t,storage_path:n,listingId:r})=>{await H.storage.from("listing-documents").remove([n]);const{error:a}=await H.from("listing_documents").delete().eq("id",t);if(a)throw a;return r},onSuccess:t=>{s.invalidateQueries({queryKey:["listing-documents",t]})}})}function _jn(){const s=as();return _t({mutationFn:async({id:t,visible:n,listingId:r})=>{const{error:a}=await H.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 w7t(s){const{data:t,error:n}=await H.storage.from("listing-documents").createSignedUrl(s,3600);if(n)throw n;return t.signedUrl}const wjn=s=>s<1024?`${s} B`:s<1024*1024?`${(s/1024).toFixed(0)} KB`:`${(s/(1024*1024)).toFixed(1)} MB`;function jjn({listingId:s,ownerOnly:t=!1}){const{data:n=[]}=_7t(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 w7t(i);window.open(l,"_blank")}catch{ie.error("Failed to open document")}};return e.jsxs(_e,{children:[e.jsx(zt,{children:e.jsxs(qt,{className:"text-lg flex items-center gap-2",children:[e.jsx(Wr,{className:"h-5 w-5"}),"Documents & Disclosures (",r.length,")"]})}),e.jsx(De,{children:e.jsx("div",{className:"space-y-2",children:r.map(i=>e.jsxs("button",{onClick:()=>a(i.storage_path),className:"w-full flex items-center gap-3 p-3 rounded-lg border hover:bg-muted transition-colors text-left group",children:[e.jsx("div",{className:"p-2 rounded-md bg-primary/10 flex-shrink-0",children:e.jsx(Wr,{className:"h-4 w-4 text-primary"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("div",{className:"text-sm font-medium truncate",children:i.file_name}),e.jsx("div",{className:"text-xs text-muted-foreground",children:wjn(i.file_size)})]}),e.jsx(oi,{className:"h-4 w-4 text-muted-foreground group-hover:text-primary"})]},i.id))})})]})}const Njn=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)}`},kft=s=>new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:0}).format(s),V6="#D4AF37",Sft="#0F172A",Cft=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}),Aft=(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)},wG=(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()}…`},kjn=(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},Cjn=s=>s instanceof DOMException||s instanceof Error?s.name:null;function j7t({listingId:s,open:t,onOpenChange:n}){var T,P;const{data:r}=mqe(s||""),[a,i]=N.useState(null),[l,o]=N.useState(!1),[c,d]=N.useState(null),[u,h]=N.useState(null),m=((r==null?void 0:r.photos)||[]).slice().sort((I,M)=>I.is_primary&&!M.is_primary?-1:!I.is_primary&&M.is_primary?1:(I.sort_order??0)-(M.sort_order??0));N.useEffect(()=>{var M;if(!t)return;const I=((M=m[0])==null?void 0:M.photo_url)||null;h(L=>L||I)},[t,r==null?void 0:r.id,m.length]),N.useEffect(()=>{let I=!1;if(!(!t||!(r!=null&&r.agent_id)))return(async()=>{var $,V,W,G;const{data:M}=await H.from("profiles").select("name, phone, phone_e164, avatar_url, brokerage:brokerages!profiles_brokerage_id_fkey(name)").eq("id",r.agent_id).maybeSingle();if(I)return;const L=M,z=(($=L==null?void 0:L.brokerage)==null?void 0:$.name)||((W=(V=r.agent)==null?void 0:V.brokerage)==null?void 0:W.name)||null;i({name:(L==null?void 0:L.name)||((G=r.agent)==null?void 0:G.name)||"Agent",phone:(L==null?void 0:L.phone)||(L==null?void 0:L.phone_e164)||null,avatar_url:(L==null?void 0:L.avatar_url)||null,brokerage:z})})(),()=>{I=!0}},[t,r==null?void 0:r.agent_id]),N.useEffect(()=>{if(!t){d(null),h(null);return}if(!r||!a)return;const I=setTimeout(()=>{f()},350);return()=>clearTimeout(I)},[t,r==null?void 0:r.id,a==null?void 0:a.name,u]);const f=async()=>{if(!(!r||!a)){o(!0);try{const I=document.createElement("canvas");I.width=1080,I.height=1080;const M=I.getContext("2d");if(!M)throw new Error("Canvas unavailable");if(M.fillStyle=Sft,M.fillRect(0,0,1080,1080),b){const G=await Cft(b);Aft(M,G,0,0,1080,1080)}const L=M.createLinearGradient(0,0,0,1080);L.addColorStop(0,"rgba(15,23,42,0.58)"),L.addColorStop(.34,"rgba(15,23,42,0.16)"),L.addColorStop(.62,"rgba(15,23,42,0.48)"),L.addColorStop(1,"rgba(15,23,42,0.98)"),M.fillStyle=L,M.fillRect(0,0,1080,1080),M.fillStyle=V6,M.fillRect(56,62,72,2),M.font="600 22px Arial, sans-serif",Sjn(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 z=kjn(M,r.property_address||`${r.city||""}, ${r.state||""}`.trim(),952,2);let $=z.length>1?590:654;z.forEach(G=>{M.fillText(G,64,$),$+=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(wG(M,V.toUpperCase(),952),64,$+8),M.fillStyle=V6,M.font="700 56px Arial, sans-serif",M.fillText(kft(r.price),64,$+58),A.length>0&&(M.fillStyle="rgba(248,250,252,0.86)",M.font="600 22px Arial, sans-serif",M.fillText(wG(M,A.join(" · "),430),360,$+78));const W=M.createLinearGradient(0,880,0,1080);if(W.addColorStop(0,"rgba(15,23,42,0.96)"),W.addColorStop(1,"#0B1322"),M.fillStyle=W,M.fillRect(0,880,1080,200),M.fillStyle=V6,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=V6,M.stroke(),M.clip(),a.avatar_url)try{const G=await Cft(a.avatar_url);Aft(M,G,64,920,120,120)}catch{M.fillStyle=V6,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=V6,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(wG(M,a.name,k?430:820),212,970),a.brokerage&&(M.fillStyle=V6,M.font="600 20px Arial, sans-serif",M.fillText(wG(M,a.brokerage.toUpperCase(),k?430:820),212,1008)),k&&(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(k,1016,1008)),d(I.toDataURL("image/png"))}catch(I){console.error("Generate graphic error",I),ie.error("Could not generate graphic")}finally{o(!1)}}},g=async I=>(await fetch(I)).blob(),y=async()=>{if(!c)return;const I=document.createElement("a");I.href=c,I.download=`just-listed-${(r==null?void 0:r.slug)||(r==null?void 0:r.id)||"graphic"}.png`,I.click(),ie.success("Downloaded!")},x=async()=>{if(c)try{const I=await g(c);await navigator.clipboard.write([new ClipboardItem({"image/png":I})]),ie.success("Copied to clipboard")}catch{ie.error("Copy not supported in this browser")}},_=async()=>{if(c)try{const I=await g(c),M=new File([I],"just-listed.png",{type:"image/png"});navigator.canShare&&navigator.canShare({files:[M]})?await navigator.share({files:[M],title:"Just Listed"}):y()}catch(I){Cjn(I)!=="AbortError"&&ie.error("Share failed")}},b=u||((T=m[0])==null?void 0:T.photo_url)||null,k=Njn(a==null?void 0:a.phone),A=[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(Bs,{open:t,onOpenChange:n,children:e.jsx(Fs,{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(qs,{className:"px-5 pt-5 pb-3 shrink-0",children:[e.jsxs($s,{className:"flex items-center gap-2 pr-8",children:[e.jsx(Cn,{className:"h-5 w-5 text-amber-500 shrink-0"}),e.jsx("span",{className:"truncate",children:"Your Just Listed Graphic"})]}),e.jsx(Ar,{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:Sft},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?kft(r.price):""}),A.length>0&&e.jsx("span",{className:"truncate text-[8px] font-semibold uppercase tracking-[0.14em] text-white/80",children:A.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"}):(P=a==null?void 0:a.name)==null?void 0:P.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})]}),k&&e.jsx("div",{className:"ml-2 shrink-0 text-[9px] font-semibold text-white",children:k})]}),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(us,{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(I=>{const M=u===I.photo_url;return e.jsx("button",{type:"button",onClick:()=>h(I.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:I.photo_url,alt:"",className:"w-full h-full object-cover"})},I.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 f(),disabled:l||!r||!a,children:"Regenerate"}),e.jsxs(B,{variant:"outline",size:"sm",onClick:x,disabled:!c,className:"gap-1.5",children:[e.jsx(Pa,{className:"h-3.5 w-3.5"})," Copy"]}),e.jsxs(B,{variant:"outline",size:"sm",onClick:_,disabled:!c,className:"gap-1.5",children:[e.jsx(Md,{className:"h-3.5 w-3.5"})," Share"]}),e.jsxs(B,{size:"sm",onClick:y,disabled:!c,className:"gap-1.5",children:[e.jsx(oi,{className:"h-3.5 w-3.5"})," Download"]})]})]})})})}function Ajn(s){return new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:0}).format(s)}const Tjn={single_family:"Single Family Home",condo:"Condo",townhouse:"Townhouse",land:"Land",multi_family:"Multi-Family",luxury:"Luxury Home",commercial:"Commercial",other:"Property"};function Ejn({open:s,onOpenChange:t,listing:n}){const{user:r}=Ls(),{data:a=[],isLoading:i}=Wy(),{data:l=[]}=K_(),[o,c]=N.useState(""),[d,u]=N.useState("all"),[h,m]=N.useState(new Set),[f,g]=N.useState(!1),[y,x]=N.useState(null);N.useEffect(()=>{s||(c(""),u("all"),m(new Set),g(!1))},[s]),N.useEffect(()=>{!s||!r||(async()=>{const{data:M}=await H.from("gmail_integrations").select("gmail_email").eq("user_id",r.id).maybeSingle();x((M==null?void 0:M.gmail_email)||null)})()},[s,r]);const _=N.useMemo(()=>a.filter(M=>M.email),[a]),b=N.useMemo(()=>{let M=_;if(d!=="all"&&(M=M.filter(L=>{var z;return(z=L.tags)==null?void 0:z.some($=>$.relationship_type_id===d)})),o.trim()){const L=o.toLowerCase();M=M.filter(z=>`${z.first_name||""} ${z.last_name||""}`.toLowerCase().includes(L)||(z.email||"").toLowerCase().includes(L))}return M},[_,o,d]),k=()=>{h.size===b.length?m(new Set):m(new Set(b.map(M=>M.id)))},A=M=>{const L=new Set(h);L.has(M)?L.delete(M):L.add(M),m(L)},T=N.useMemo(()=>_.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})),[_,h]),{defaultSubject:P,defaultBody:I}=N.useMemo(()=>{var ae,he,xe,ve;const M=n.property_address||`${n.city}, ${n.state}`,L=Ajn(n.price),z=Tjn[n.property_type]||"home",$=n.bedrooms?`${n.bedrooms} bed`:"",V=n.bathrooms?`${n.bathrooms} bath`:"",W=n.square_footage?`${n.square_footage.toLocaleString()} sqft`:"",G=[$,V,W].filter(Boolean).join(" • "),X=`https://listings.relevelup.com/${n.slug||n.id}`,te=((he=(ae=n.photos)==null?void 0:ae.find(ge=>ge.is_primary))==null?void 0:he.photo_url)||((ve=(xe=n.photos)==null?void 0:xe[0])==null?void 0:ve.photo_url)||"",me={active:"Just Listed",coming_soon:"Coming Soon",office_exclusive:"Office Exclusive",pre_market:"Pre-Market",price_improvement:"Price Improvement",under_contract:"Under Contract",sold:"Sold"}[n.status]||"New Listing",ue=`${me}: ${M} — ${L}`,ce=`

Hi {{first_name}},

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

${te?` ${M} `:""}
${me}

${L}

${M}

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

${G?`

${G} • ${z}

`:""} View Photos & Details →

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

Talk soon,

`;return{defaultSubject:ue,defaultBody:ce}},[n]);return f?e.jsx(Y_,{open:f,onOpenChange:M=>{g(M),M||t(!1)},bulkContacts:T,defaultSubject:P,defaultBody:I,gmailEmail:y}):e.jsx(Bs,{open:s,onOpenChange:t,children:e.jsxs(Fs,{className:"sm:max-w-[640px] max-h-[90vh] flex flex-col",children:[e.jsxs(qs,{children:[e.jsxs($s,{className:"flex items-center gap-2",children:[e.jsx(Cn,{className:"h-5 w-5 text-amber-500"}),"Email this listing to your sphere"]}),e.jsx(Ar,{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(Gr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(we,{placeholder:"Search contacts...",value:o,onChange:M=>c(M.target.value),className:"pl-9"})]}),e.jsxs(Ns,{value:d,onValueChange:u,children:[e.jsx(ws,{className:"sm:w-[180px]",children:e.jsx(ks,{placeholder:"Filter by tag"})}),e.jsxs(js,{children:[e.jsx(nt,{value:"all",children:"All contacts"}),l.map(M=>e.jsx(nt,{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:k,className:"flex items-center gap-2 text-primary hover:underline",children:[e.jsx(Bi,{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(We,{variant:"secondary",className:"gap-1",children:[e.jsx(Yn,{className:"h-3 w-3"}),h.size," selected"]})]}),e.jsx(lo,{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(us,{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:_.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(Bi,{checked:h.has(M.id),onCheckedChange:()=>A(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(L=>{var z;return e.jsx(We,{variant:"outline",className:"text-[10px] px-1.5 py-0",children:(z=L.relationship_type)==null?void 0:z.name},L.id)})})]},M.id))})}),e.jsx(Wl,{}),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:()=>g(!0),disabled:h.size===0,className:"gap-2",children:[e.jsx(mn,{className:"h-4 w-4"}),"Compose Email (",h.size,")"]})]})]})]})})}function Jw(s){const t=s.expected_commission;if(!t)return null;if((s.commission_calc_method||"standard")==="referral_first"){let a=t;s.referral_fee_pct&&(a-=t*(s.referral_fee_pct/100));let i=a;return s.brokerage_split_pct&&(i-=a*(s.brokerage_split_pct/100)),s.team_split_pct&&(i-=t*(s.team_split_pct/100)),s.franchise_fee_pct&&(i-=t*(s.franchise_fee_pct/100)),s.transaction_fee&&(i-=s.transaction_fee),Math.max(0,i)}let r=t;return s.brokerage_split_pct&&(r-=t*(s.brokerage_split_pct/100)),s.team_split_pct&&(r-=t*(s.team_split_pct/100)),s.franchise_fee_pct&&(r-=t*(s.franchise_fee_pct/100)),s.referral_fee_pct&&(r-=t*(s.referral_fee_pct/100)),s.transaction_fee&&(r-=s.transaction_fee),Math.max(0,r)}function PJ(){const s=Ya();return mt({queryKey:["deal-pipeline-stages",s],queryFn:async()=>{if(!s)return[];const{data:t,error:n}=await H.from("deal_pipeline_stages").select("*").eq("owner_user_id",s).order("sort_order",{ascending:!0});if(n)throw n;return t},enabled:!!s})}function N7t(){const s=Ya(),t=as();return _t({mutationFn:async()=>{if(!s)throw new Error("Not authenticated");const{error:n}=await H.rpc("initialize_deal_pipeline_stages",{p_user_id:s});if(n)throw n},onSuccess:()=>{t.invalidateQueries({queryKey:["deal-pipeline-stages"]})}})}function SAe(){const s=Ya();return mt({queryKey:["deal-pipeline-deals",s],queryFn:async()=>{if(!s)return[];const{data:t,error:n}=await H.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 k7t(){const s=Ya(),t=as();return _t({mutationFn:async n=>{if(!s)throw new Error("Not authenticated");const{data:r,error:a}=await H.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 H.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 S7t(){const s=as();return _t({mutationFn:async({id:t,...n})=>{const{data:r,error:a}=await H.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 Mjn(){const s=as();return _t({mutationFn:async({dealId:t,stageId:n,stageName:r})=>{const{data:a,error:i}=await H.from("deal_pipeline").update({stage_id:n}).eq("id",t).select().single();if(i)throw i;return await H.from("deal_activities").insert({deal_id:t,activity_type:"stage_change",title:`Moved to ${r}`,metadata:{new_stage_id:n,new_stage_name:r}}),a},onSuccess:()=>{s.invalidateQueries({queryKey:["deal-pipeline-deals"]}),s.invalidateQueries({queryKey:["deal-activities"]})}})}function Ljn(){const s=as();return _t({mutationFn:async t=>{const{error:n}=await H.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 Pjn(s){return mt({queryKey:["deal-activities",s],queryFn:async()=>{const{data:t,error:n}=await H.from("deal_activities").select("*").eq("deal_id",s).order("created_at",{ascending:!1});if(n)throw n;return t},enabled:!!s})}function Ijn(){const s=as();return _t({mutationFn:async t=>{const{data:n,error:r}=await H.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 Djn(s){return mt({queryKey:["deal-checklist",s],queryFn:async()=>{const{data:t,error:n}=await H.from("deal_checklist_items").select("*").eq("deal_id",s).order("sort_order",{ascending:!0});if(n)throw n;return t},enabled:!!s})}function Rjn(){const s=as();return _t({mutationFn:async({id:t,is_completed:n,deal_id:r})=>{const{data:a,error:i}=await H.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 Ojn(){const s=as();return _t({mutationFn:async t=>{const{data:n,error:r}=await H.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 Fjn(){const s=Ya();return mt({queryKey:["deal-pipeline-stats",s],queryFn:async()=>{if(!s)return null;const{data:t,error:n}=await H.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),0),expectedNetToAgent:r.reduce((o,c)=>o+(Jw(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)*d},0),weightedNet:r.reduce((o,c)=>{const d=(c.probability??50)/100;return o+(Jw(c)||0)*d},0),ytdWonDeals:l.length,ytdWonGCI:l.reduce((o,c)=>o+(c.expected_commission||0),0),ytdWonNet:l.reduce((o,c)=>o+(Jw(c)||0),0),projectedAnnualNet:l.reduce((o,c)=>o+(Jw(c)||0),0)+r.reduce((o,c)=>{const d=(c.probability??50)/100;return o+(Jw(c)||0)*d},0)}},enabled:!!s})}function zjn(s){const t=Ya();return mt({queryKey:["deal-by-listing",s,t],queryFn:async()=>{if(!t||!s)return null;const{data:n,error:r}=await H.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 Bjn(){const s=as();return _t({mutationFn:async({dealId:t,listingId:n})=>{const{data:r,error:a}=await H.from("deal_pipeline").update({listing_id:n}).eq("id",t).select().single();if(a)throw a;return await H.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 $jn(){const s=as();return _t({mutationFn:async({dealId:t,listingId:n})=>{const{data:r,error:a}=await H.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 Ujn({listing:s}){const t=tr(),[n,r]=N.useState(""),[a,i]=N.useState(!1),{data:l,isLoading:o}=zjn(s.id),{data:c,isLoading:d}=PJ(),{data:u,isLoading:h}=SAe(),m=N7t(),f=Bjn(),g=$jn(),y=k7t(),x=(u==null?void 0:u.filter(T=>!T.listing_id))||[],_=T=>{if(!(c!=null&&c.length))return null;switch(T){case"coming_soon":case"active":case"price_improvement":return c.find(P=>P.name==="Active");case"under_contract":return c.find(P=>P.name==="Under Contract");case"sold":return c.find(P=>P.is_won_stage);default:return c.find(P=>P.name==="Active")}},b=async()=>{i(!0);try{c!=null&&c.length||await m.mutateAsync();const T=_(s.status);await y.mutateAsync({deal_name:s.property_address?`${s.property_address}, ${s.city}`:`${s.city}, ${s.state}`,deal_type:"seller",stage_id:(T==null?void 0:T.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}),ie.success("Deal created and linked to listing!")}catch(T){console.error("Failed to create deal:",T),ie.error("Failed to create deal")}finally{i(!1)}},k=async()=>{if(!n){ie.error("Please select a deal");return}try{await f.mutateAsync({dealId:n,listingId:s.id}),ie.success("Listing linked to deal!"),r("")}catch{ie.error("Failed to link listing")}},A=async()=>{if(l)try{await g.mutateAsync({dealId:l.id,listingId:s.id}),ie.success("Listing unlinked from deal")}catch{ie.error("Failed to unlink listing")}};return o||d?e.jsxs(_e,{children:[e.jsx(zt,{children:e.jsxs(qt,{className:"flex items-center gap-2 text-base",children:[e.jsx(r3,{className:"h-4 w-4"}),"Deal Pipeline"]})}),e.jsx(De,{children:e.jsx("div",{className:"flex items-center justify-center py-4",children:e.jsx(us,{className:"h-5 w-5 animate-spin text-muted-foreground"})})})]}):l?e.jsxs(_e,{className:"border-primary/20 bg-primary/5",children:[e.jsx(zt,{className:"pb-2",children:e.jsxs(qt,{className:"flex items-center gap-2 text-base",children:[e.jsx(cd,{className:"h-4 w-4 text-primary"}),"Linked to Pipeline"]})}),e.jsxs(De,{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(We,{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(vi,{className:"h-3 w-3 ml-1"})]}),e.jsx(B,{variant:"ghost",size:"sm",onClick:A,disabled:g.isPending,children:g.isPending?e.jsx(us,{className:"h-4 w-4 animate-spin"}):e.jsx(kD,{className:"h-4 w-4"})})]})]})]}):e.jsxs(_e,{children:[e.jsx(zt,{className:"pb-2",children:e.jsxs(qt,{className:"flex items-center gap-2 text-base",children:[e.jsx(r3,{className:"h-4 w-4"}),"Deal Pipeline"]})}),e.jsxs(De,{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(us,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(nn,{className:"h-4 w-4 mr-2"}),"Create New Deal"]}),x.length>0&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"relative",children:[e.jsx("div",{className:"absolute inset-0 flex items-center",children:e.jsx("span",{className:"w-full border-t"})}),e.jsx("div",{className:"relative flex justify-center text-xs uppercase",children:e.jsx("span",{className:"bg-card px-2 text-muted-foreground",children:"or"})})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(Ns,{value:n,onValueChange:r,children:[e.jsx(ws,{className:"flex-1 text-sm",children:e.jsx(ks,{placeholder:"Link to existing deal..."})}),e.jsx(js,{children:x.map(T=>e.jsx(nt,{value:T.id,children:T.deal_name},T.id))})]}),e.jsx(B,{variant:"secondary",size:"icon",onClick:k,disabled:!n||f.isPending,children:f.isPending?e.jsx(us,{className:"h-4 w-4 animate-spin"}):e.jsx(cd,{className:"h-4 w-4"})})]})]})]})]})}const qjn={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"},Vjn={active:"Active",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"};function Hjn(){var ne,me,ue,ce,ae,he,xe,ve,ge;const{listingId:s}=uo(),t=tr(),{user:n}=Ls(),{data:r,isLoading:a}=mqe(s||""),{data:i}=D4t(s||""),{data:l}=Hjs(s||""),o=I4t(),c=Vjs(),d=Gjs(),u=P4t(),h=Kjs(),[m,f]=N.useState(!1),[g,y]=N.useState(!1),[x,_]=N.useState(!1),[b,k]=N.useState(!1),[A,T]=N.useState(!1),[P,I]=N.useState(null),[M,L]=N.useState({buyerName:"",buyerType:"",notes:""}),z=(n==null?void 0:n.id)===(r==null?void 0:r.agent_id),$=be=>new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:0}).format(be),V=async be=>{const Se=`https://listings.relevelup.com/${(r==null?void 0:r.slug)||(r==null?void 0:r.id)}`,Ie=`Check out this listing: ${(r==null?void 0:r.property_address)||(r==null?void 0:r.city)}`;d.mutate({listingId:r.id,shareType:be});try{switch(be){case"facebook":window.open(`https://www.facebook.com/sharer/sharer.php?u=${encodeURIComponent(Se)}`,"_blank");break;case"copy":await navigator.clipboard.writeText(Se),ie.success("Link copied to clipboard!");break;case"text":window.open(`sms:?body=${encodeURIComponent(`${Ie} ${Se}`)}`);break;case"email":window.open(`mailto:?subject=${encodeURIComponent(Ie)}&body=${encodeURIComponent(`Check out this listing: ${Se}`)}`);break}}catch(Me){console.error("Share error:",Me),ie.error("Failed to share")}},W=async()=>{try{await u.mutateAsync(r.id),ie.success("Listing deleted"),t("/mission-control/listings")}catch{ie.error("Failed to delete listing")}},G=async()=>{if(!M.buyerName.trim()){ie.error("Please enter buyer name");return}try{await h.mutateAsync({listingId:r.id,listingAgentId:r.agent_id,buyerName:M.buyerName,buyerType:M.buyerType||void 0,notes:M.notes||void 0}),ie.success("Referral sent successfully!"),y(!1),L({buyerName:"",buyerType:"",notes:""})}catch{ie.error("Failed to send referral")}},X=be=>{var Ge,Ce;const Se=(r==null?void 0:r.property_address)||`${r==null?void 0:r.city}, ${r==null?void 0:r.state}`,Ie=$((r==null?void 0:r.price)||0),Me=r!=null&&r.bedrooms?`${r.bedrooms}BD`:"",Re=r!=null&&r.bathrooms?`${r.bathrooms}BA`:"",Be=r!=null&&r.square_footage?`${r.square_footage.toLocaleString()}SF`:"",Ne=[Me,Re,Be].filter(Boolean).join(" | ");switch(be){case"just_listed":return`🏡 JUST LISTED! ${Se} ${Ie} ${Ne} ${(r==null?void 0:r.description)||"Schedule your showing today!"} #JustListed #RealEstate #HomeForSale #${(Ge=r==null?void 0:r.city)==null?void 0:Ge.replace(/\s/g,"")}`;case"price_improvement":return`📣 PRICE IMPROVEMENT! ${Se} Now ${Ie}! ${Ne} Don't miss this opportunity! #PriceReduced #RealEstate #HomeForSale`;case"teaser":return`Looking for a ${Tft[(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! ${Ne} DM me for details! 📩 #ComingSoon #RealEstate #${(Ce=r==null?void 0:r.city)==null?void 0:Ce.replace(/\s/g,"")}`;default:return""}};if(a)return e.jsx(Qs,{title:"Listing",description:"",children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(xn,{className:"h-10 w-32"}),e.jsx(xn,{className:"h-[400px] w-full"}),e.jsxs("div",{className:"grid md:grid-cols-3 gap-6",children:[e.jsx(xn,{className:"h-48"}),e.jsx(xn,{className:"h-48"}),e.jsx(xn,{className:"h-48"})]})]})});if(!r)return e.jsx(Qs,{title:"Listing Not Found",description:"",children:e.jsx(_e,{children:e.jsxs(De,{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 te=((ne=r.photos)==null?void 0:ne.find(be=>be.is_primary))||((me=r.photos)==null?void 0:me[0]);return e.jsxs(Qs,{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:()=>te&&I(te.photo_url),children:te?e.jsx("img",{src:te.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:(ue=r.photos)==null?void 0:ue.slice(1,5).map((be,Se)=>e.jsx("div",{className:"aspect-square rounded-lg overflow-hidden bg-muted cursor-pointer",onClick:()=>I(be.photo_url),children:e.jsx("img",{src:be.photo_url,alt:`Photo ${Se+2}`,className:"w-full h-full object-cover"})},be.id))})]}),e.jsxs("div",{className:"grid md:grid-cols-3 gap-6",children:[e.jsxs("div",{className:"md:col-span-2 space-y-6",children:[e.jsx(_e,{children:e.jsxs(De,{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(We,{className:`${qjn[r.status]} text-white border-0`,children:Vjn[r.status]}),r.is_featured&&e.jsxs(We,{variant:"outline",className:"border-amber-500 text-amber-500",children:[e.jsx(Wa,{className:"h-3 w-3 mr-1 fill-amber-500"}),"Featured"]}),r.open_to_referrals&&e.jsxs(We,{variant:"outline",children:[e.jsx(Yn,{className:"h-3 w-3 mr-1"}),"Open to Referrals"]})]}),e.jsx("h1",{className:"text-3xl font-bold text-primary mb-2",children:$(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(ii,{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(co,{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(d5,{className:"h-4 w-4"}):e.jsx(yg,{className:"h-4 w-4"})}),!z&&e.jsxs(B,{variant:"outline",className:"border-amber-500 text-amber-600 hover:bg-amber-50",onClick:()=>_(!0),children:[e.jsx(Cn,{className:"h-4 w-4 mr-2"}),"Share & Earn Leads"]}),e.jsxs(qd,{children:[e.jsx(Vd,{asChild:!0,children:e.jsxs(B,{variant:"outline",children:[e.jsx(Md,{className:"h-4 w-4 mr-2"}),"Share"]})}),e.jsxs(Ld,{children:[e.jsxs(ba,{onClick:()=>V("copy"),children:[e.jsx(Pa,{className:"h-4 w-4 mr-2"}),"Copy Link"]}),e.jsxs(ba,{onClick:()=>V("facebook"),children:[e.jsx(Kf,{className:"h-4 w-4 mr-2"}),"Facebook"]}),e.jsxs(ba,{onClick:()=>V("text"),children:[e.jsx(xo,{className:"h-4 w-4 mr-2"}),"Text"]}),e.jsxs(ba,{onClick:()=>V("email"),children:[e.jsx(mn,{className:"h-4 w-4 mr-2"}),"Email"]})]})]}),z&&e.jsxs(e.Fragment,{children:[e.jsxs(B,{variant:"outline",onClick:()=>{const be=(r.photos??[]).slice().sort((Se,Ie)=>(Ie.is_primary?1:0)-(Se.is_primary?1:0)||(Se.sort_order??0)-(Ie.sort_order??0)).map(Se=>Se.photo_url).filter(Boolean);if(be.length===0){ie.error("Add photos to this listing first.");return}v7t({photos:be,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:b7t(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(j9,{className:"h-4 w-4"}),"Create Music Video"]}),e.jsxs(B,{variant:"outline",onClick:()=>T(!0),className:"gap-2 border-amber-500/60 text-amber-600 hover:bg-amber-50",children:[e.jsx(Cn,{className:"h-4 w-4"}),"Just Listed Graphic"]}),e.jsxs(B,{variant:"outline",onClick:()=>k(!0),className:"gap-2",children:[e.jsx(mn,{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(Cn,{className:"h-4 w-4"}),"Customize Public Page"]}),e.jsxs(B,{variant:"outline",onClick:()=>t(`/mission-control/listings/${r.id}/edit`),children:[e.jsx(xp,{className:"h-4 w-4 mr-2"}),"Edit"]}),e.jsx(B,{variant:"destructive",size:"icon",onClick:()=>f(!0),children:e.jsx(qn,{className:"h-4 w-4"})})]})]})]}),e.jsxs("div",{className:"grid grid-cols-2 sm:grid-cols-4 gap-4 py-4 border-y",children:[r.bedrooms&&e.jsxs("div",{className:"text-center",children:[e.jsx(A_,{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(Wx,{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(L_,{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(ta,{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(We,{variant:"secondary",children:[e.jsx(Ti,{className:"h-3 w-3 mr-1"}),Tft[r.property_type]]}),r.lot_size&&e.jsxs(We,{variant:"secondary",children:["Lot: ",r.lot_size]}),r.has_hoa&&e.jsx(We,{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.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(Tr,{className:"h-4 w-4 mr-2"}),"View on MLS"]})})]}),e.jsxs("div",{className:"flex items-center gap-4 pt-4 mt-4 border-t text-sm text-muted-foreground",children:[e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(da,{className:"h-4 w-4"}),r.view_count," views"]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Md,{className:"h-4 w-4"}),r.share_count," shares"]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(co,{className:"h-4 w-4"}),r.save_count," saves"]})]})]})}),r.allow_sharing&&e.jsxs(_e,{children:[e.jsx(zt,{children:e.jsx(qt,{className:"text-lg",children:"Share Content"})}),e.jsx(De,{className:"space-y-4",children:["just_listed","price_improvement","teaser"].map(be=>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:[be.replace("_"," ")," Caption"]}),e.jsx(B,{size:"sm",variant:"ghost",onClick:()=>{navigator.clipboard.writeText(X(be)),ie.success("Caption copied!")},children:e.jsx(Pa,{className:"h-3 w-3"})})]}),e.jsx("p",{className:"text-xs text-muted-foreground whitespace-pre-wrap",children:X(be)})]},be))})]}),e.jsx(jjn,{listingId:r.id,ownerOnly:z})]}),e.jsxs("div",{className:"space-y-6",children:[e.jsxs(_e,{children:[e.jsx(zt,{children:e.jsx(qt,{className:"text-lg",children:"Listing Agent"})}),e.jsxs(De,{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:((ae=(ce=r.agent)==null?void 0:ce.name)==null?void 0:ae.charAt(0))||"?"})}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:((he=r.agent)==null?void 0:he.name)||"Unknown"}),((ve=(xe=r.agent)==null?void 0:xe.brokerage)==null?void 0:ve.name)&&e.jsx("p",{className:"text-sm text-muted-foreground",children:r.agent.brokerage.name})]})]}),!z&&e.jsx("div",{className:"space-y-2",children:((ge=r.agent)==null?void 0:ge.email)&&e.jsx(B,{variant:"outline",className:"w-full",asChild:!0,children:e.jsxs("a",{href:`mailto:${r.agent.email}`,children:[e.jsx(mn,{className:"h-4 w-4 mr-2"}),"Email Agent"]})})})]})]}),z&&e.jsx(Ujn,{listing:r}),!z&&r.open_to_referrals&&e.jsxs(_e,{children:[e.jsx(zt,{children:e.jsxs(qt,{className:"text-lg flex items-center gap-2",children:[e.jsx(Yn,{className:"h-5 w-5"}),"Send a Buyer"]})}),e.jsxs(De,{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(Bs,{open:!!P,onOpenChange:()=>I(null),children:e.jsx(Fs,{className:"max-w-4xl",children:e.jsx("img",{src:P||"",alt:"Full size",className:"w-full h-auto"})})}),e.jsx(Bs,{open:m,onOpenChange:f,children:e.jsxs(Fs,{children:[e.jsxs(qs,{children:[e.jsx($s,{children:"Delete Listing"}),e.jsx(Ar,{children:"Are you sure you want to delete this listing? This action cannot be undone."})]}),e.jsxs(Cr,{children:[e.jsx(B,{variant:"outline",onClick:()=>f(!1),children:"Cancel"}),e.jsx(B,{variant:"destructive",onClick:W,disabled:u.isPending,children:u.isPending?"Deleting...":"Delete"})]})]})}),e.jsx(Bs,{open:g,onOpenChange:y,children:e.jsxs(Fs,{children:[e.jsxs(qs,{children:[e.jsx($s,{children:"Send Buyer Referral"}),e.jsx(Ar,{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(re,{children:"Buyer Name *"}),e.jsx(we,{value:M.buyerName,onChange:be=>L({...M,buyerName:be.target.value}),placeholder:"Enter buyer's name"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{children:"Buyer Type"}),e.jsxs(Ns,{value:M.buyerType,onValueChange:be=>L({...M,buyerType:be}),children:[e.jsx(ws,{children:e.jsx(ks,{placeholder:"Select type"})}),e.jsxs(js,{children:[e.jsx(nt,{value:"first_time",children:"First-Time Buyer"}),e.jsx(nt,{value:"investor",children:"Investor"}),e.jsx(nt,{value:"relocating",children:"Relocating"}),e.jsx(nt,{value:"upgrade",children:"Upgrading"}),e.jsx(nt,{value:"downsize",children:"Downsizing"})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{children:"Notes"}),e.jsx(Ws,{value:M.notes,onChange:be=>L({...M,notes:be.target.value}),placeholder:"Any additional information..."})]})]}),e.jsxs(Cr,{children:[e.jsx(B,{variant:"outline",onClick:()=>y(!1),children:"Cancel"}),e.jsx(B,{onClick:G,disabled:h.isPending,children:h.isPending?"Sending...":"Send Referral"})]})]})}),e.jsx(g7t,{open:x,onOpenChange:_,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(Ejn,{open:b,onOpenChange:k,listing:r}),e.jsx(j7t,{listingId:(r==null?void 0:r.id)||null,open:A,onOpenChange:T})]})}function Gjn({onImport:s}){const[t,n]=N.useState(""),[r,a]=N.useState([]),[i,l]=N.useState(!1),[o,c]=N.useState(!1),[d,u]=N.useState(null),h=N.useRef(),m=N.useRef(null);N.useEffect(()=>{const b=k=>{m.current&&!m.current.contains(k.target)&&c(!1)};return document.addEventListener("mousedown",b),()=>document.removeEventListener("mousedown",b)},[]);const f=async b=>{if(b.trim().length<3){a([]),c(!1);return}l(!0);try{const{data:k,error:A}=await H.functions.invoke("mls-listing-search",{body:{query:b}});if(A)throw A;a((k==null?void 0:k.listings)||[]),c(!0)}catch(k){console.error("MLS search error:",k),a([])}finally{l(!1)}},g=b=>{n(b),h.current&&clearTimeout(h.current),h.current=setTimeout(()=>f(b),400)},y=b=>{u(b.mlsNumber),s(b),c(!1),n(`${b.address}, ${b.city}`),ie.success(`Imported: ${b.address}`,{description:"Property details and photos have been auto-filled."}),u(null)},x=b=>b?`$${b.toLocaleString()}`:"",_=b=>{const k=(b||"").toLowerCase();return k.includes("single")||k.includes("detached")?"Single Family":k.includes("condo")?"Condo":k.includes("town")?"Townhouse":k.includes("land")||k.includes("lot")?"Land":k.includes("multi")?"Multi-Family":k.includes("commercial")?"Commercial":b||"Other"};return e.jsxs(_e,{className:"border-primary/30 bg-primary/5",children:[e.jsxs(zt,{className:"pb-3",children:[e.jsxs(qt,{className:"text-base flex items-center gap-2",children:[e.jsx(oi,{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(De,{children:e.jsxs("div",{ref:m,className:"relative",children:[e.jsxs("div",{className:"relative",children:[e.jsx(Gr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(we,{value:t,onChange:b=>g(b.target.value),onFocus:()=>r.length>0&&c(!0),placeholder:"Start typing a property address...",className:"pl-9 pr-9"}),i&&e.jsx(us,{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(hr,{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(ii,{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:x(b.price)}),b.bedrooms>0&&e.jsxs("span",{className:"flex items-center gap-0.5",children:[e.jsx(A_,{className:"h-3 w-3"})," ",b.bedrooms]}),b.bathrooms>0&&e.jsxs("span",{className:"flex items-center gap-0.5",children:[e.jsx(Wx,{className:"h-3 w-3"})," ",b.bathrooms]}),b.sqft>0&&e.jsxs("span",{className:"flex items-center gap-0.5",children:[e.jsx(l3,{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(We,{variant:"outline",className:"text-[10px]",children:_(b.propertyType)}),b.photos.length>0&&e.jsxs("span",{className:"text-[10px] text-muted-foreground",children:[b.photos.length," photos"]})]})]},b.mlsNumber))})]})})]})}function Wjn({photo:s,onRemove:t,onSetPrimary:n}){const{attributes:r,listeners:a,setNodeRef:i,transform:l,transition:o,isDragging:c}=V3e({id:s.id}),d={transform:fE.Transform.toString(l),transition:o};return e.jsxs("div",{ref:i,style:d,className:Ot("relative aspect-square rounded-lg overflow-hidden bg-muted group",c&&"opacity-50 ring-2 ring-primary z-50"),children:[e.jsx("img",{src:s.photo_url,alt:"",className:"w-full h-full object-cover"}),e.jsx("button",{type:"button",...r,...a,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(Mp,{className:"h-3.5 w-3.5"})}),e.jsx("button",{type:"button",onClick:()=>t(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(hr,{className:"h-3 w-3"})}),s.is_primary?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(Wa,{className:"h-2.5 w-2.5 fill-current"})," Primary"]}):e.jsx("button",{type:"button",onClick:()=>n(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 Kjn({photos:s,uploading:t,onUpload:n,onRemove:r,onReorder:a,onSetPrimary:i}){const l=D3e(QB(kU,{activationConstraint:{distance:5}})),o=[...s].sort((d,u)=>(d.sort_order??0)-(u.sort_order??0)),c=d=>{const{active:u,over:h}=d;if(!h||u.id===h.id)return;const m=o.findIndex(_=>_.id===u.id),f=o.findIndex(_=>_.id===h.id),g=[...o],[y]=g.splice(m,1);g.splice(f,0,y);const x=g.map((_,b)=>({..._,sort_order:b}));a(x)};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($3e,{sensors:l,collisionDetection:R3e,onDragEnd:c,children:e.jsx(q3e,{items:o.map(d=>d.id),strategy:rJ,children:e.jsxs("div",{className:"grid grid-cols-3 sm:grid-cols-4 gap-4",children:[o.map(d=>e.jsx(Wjn,{photo:d,onRemove:r,onSetPrimary:i},d.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(us,{className:"h-8 w-8 animate-spin"}):e.jsxs(e.Fragment,{children:[e.jsx(ni,{className:"h-8 w-8"}),e.jsx("span",{className:"text-xs",children:"Upload"})]}),e.jsx("input",{type:"file",accept:"image/*",multiple:!0,className:"hidden",onChange:d=>n(d.target.files),disabled:t})]})]})})})]})}function Yjn({selectedVideoId:s,onVideoSelect:t,listingId:n}){const r=tr(),{user:a}=Ls(),[i,l]=N.useState(!1),[o,c]=N.useState([]),[d,u]=N.useState(!1),[h,m]=N.useState(null),[f,g]=N.useState({});N.useEffect(()=>{s&&a?y():m(null)},[s,a]);const y=async()=>{if(!s)return;const{data:L,error:z}=await H.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();!z&&L&&(m(L),x(L))},x=async L=>{try{const{data:z,error:$}=await H.functions.invoke("bunny-upload",{body:{action:"asset-urls",videoId:L.bunny_video_id,isAgentVideo:!0}});!$&&(z!=null&&z.thumbnailUrl)&&g(V=>({...V,[L.id]:{thumbnailUrl:z.thumbnailUrl}}))}catch(z){console.warn("Failed to get signed URL",z)}},_=async()=>{if(a){u(!0);try{const{data:L,error:z}=await H.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(z)throw z;c(L||[]),L!=null&&L.length&&b(L)}catch(L){console.error("Error fetching videos:",L),ie.error("Failed to load videos")}finally{u(!1)}}},b=async L=>{var z;try{const $=L.map(te=>te.bunny_video_id),{data:V,error:W}=await H.functions.invoke("bunny-upload",{body:{action:"bulk-asset-urls",videoIds:$,isAgentVideo:!0}});if(W)throw W;const G=(V==null?void 0:V.assets)||{},X={};for(const te of L)(z=G[te.bunny_video_id])!=null&&z.thumbnailUrl&&(X[te.id]={thumbnailUrl:G[te.bunny_video_id].thumbnailUrl});g(te=>({...te,...X}))}catch($){console.warn("Failed to bulk-fetch signed URLs",$)}},k=()=>{l(!0),_()},A=L=>{t(L.id),m(L),l(!1),ie.success("Video selected")},T=()=>{t(null),m(null)},P=()=>{const L=n?`/mission-control/listings/${n}/edit`:"/mission-control/listings/new";r(`/mission-control/video?returnUrl=${encodeURIComponent(L)}`)},I=L=>{if(!L)return"0:00";const z=Math.floor(L/60),$=L%60;return`${z}:${$.toString().padStart(2,"0")}`},M=L=>{var z;return((z=f[L.id])==null?void 0:z.thumbnailUrl)||L.thumbnail_url};return e.jsxs("div",{className:"space-y-3",children:[h?e.jsx(_e,{className:"overflow-hidden",children:e.jsx(De,{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(na,{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(dd,{className:"h-6 w-6 text-white fill-white"})}),h.duration_seconds&&e.jsx("div",{className:"absolute bottom-1 right-1 bg-black/70 text-white text-[10px] px-1.5 py-0.5 rounded",children:I(h.duration_seconds)})]}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"font-medium text-sm truncate",children:h.title||"Untitled Video"}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:"Property Video Tour"})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(B,{type:"button",variant:"outline",size:"sm",onClick:k,children:"Change"}),e.jsx(B,{type:"button",variant:"ghost",size:"sm",onClick:T,className:"text-destructive hover:text-destructive",children:e.jsx(hr,{className:"h-4 w-4"})})]})]})})}):e.jsx(_e,{className:"border-dashed",children:e.jsx(De,{className:"p-6",children:e.jsxs("div",{className:"text-center",children:[e.jsx(na,{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:k,className:"gap-2",children:[e.jsx(rb,{className:"h-4 w-4"}),"Select from Library"]}),e.jsxs(B,{type:"button",variant:"outline",onClick:P,className:"gap-2",children:[e.jsx($0,{className:"h-4 w-4"}),"Record New Video"]})]})]})})}),e.jsx(Bs,{open:i,onOpenChange:l,children:e.jsxs(Fs,{className:"max-w-2xl max-h-[80vh] overflow-hidden flex flex-col",children:[e.jsx(qs,{children:e.jsxs($s,{className:"flex items-center gap-2",children:[e.jsx(rb,{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(us,{className:"h-8 w-8 animate-spin text-muted-foreground"})}):o.length===0?e.jsxs("div",{className:"text-center py-12",children:[e.jsx(na,{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:P,className:"gap-2",children:[e.jsx($0,{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(L=>e.jsxs("button",{type:"button",onClick:()=>A(L),className:`group relative rounded-lg overflow-hidden border-2 transition-all text-left ${s===L.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(L)?e.jsx("img",{src:M(L),alt:L.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(na,{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(dd,{className:"h-8 w-8 text-white opacity-0 group-hover:opacity-100 transition-opacity"})}),L.duration_seconds&&e.jsx("div",{className:"absolute bottom-1 right-1 bg-black/70 text-white text-[10px] px-1.5 py-0.5 rounded",children:I(L.duration_seconds)})]}),e.jsx("div",{className:"p-2 bg-card",children:e.jsx("p",{className:"text-xs font-medium truncate",children:L.title||"Untitled Video"})})]},L.id))})}),e.jsxs("div",{className:"flex justify-between items-center pt-4 border-t",children:[e.jsxs(B,{type:"button",variant:"ghost",onClick:P,className:"gap-2",children:[e.jsx($0,{className:"h-4 w-4"}),"Record New Video"]}),e.jsx(B,{type:"button",variant:"outline",onClick:()=>l(!1),children:"Cancel"})]})]})})]})}const Zjn=s=>s<1024?`${s} B`:s<1024*1024?`${(s/1024).toFixed(0)} KB`:`${(s/(1024*1024)).toFixed(1)} MB`;function Xjn({listingId:s}){const t=N.useRef(null),{data:n=[],isLoading:r}=_7t(s),a=vjn(),i=bjn(),l=_jn(),o=async d=>{if(!(!d||d.length===0)){for(const u of Array.from(d)){if(u.size>25*1024*1024){ie.error(`${u.name} exceeds 25MB limit`);continue}try{await a.mutateAsync({listingId:s,file:u})}catch(h){ie.error(`Failed to upload ${u.name}: ${h.message}`)}}t.current&&(t.current.value=""),ie.success("Documents uploaded")}},c=async d=>{try{const u=await w7t(d);window.open(u,"_blank")}catch{ie.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(us,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(ni,{className:"h-4 w-4 mr-2"}),"Upload PDFs (disclosures, etc.)"]}),r?e.jsx("p",{className:"text-sm text-muted-foreground",children:"Loading..."}):n.length===0?e.jsx("p",{className:"text-sm text-muted-foreground text-center py-4",children:"No documents yet. Upload PDFs that other agents can download from your listing."}):e.jsx("div",{className:"space-y-2",children:n.map(d=>e.jsxs(_e,{className:"p-3 flex items-center gap-3",children:[e.jsx("div",{className:"p-2 rounded-md bg-primary/10",children:e.jsx(Wr,{className:"h-4 w-4 text-primary"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("div",{className:"text-sm font-medium truncate",children:d.file_name}),e.jsx("div",{className:"text-xs text-muted-foreground",children:Zjn(d.file_size)})]}),e.jsxs("div",{className:"flex items-center gap-1 text-xs text-muted-foreground",children:[d.visible_on_exchange?e.jsx(da,{className:"h-3 w-3"}):e.jsx(V0,{className:"h-3 w-3"}),e.jsx("span",{className:"hidden sm:inline",children:d.visible_on_exchange?"Visible":"Hidden"}),e.jsx(zn,{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(oi,{className:"h-4 w-4"})}),e.jsx(B,{type:"button",variant:"ghost",size:"icon",onClick:()=>{confirm(`Delete ${d.file_name}?`)&&i.mutate({id:d.id,storage_path:d.storage_path,listingId:s})},children:e.jsx(hr,{className:"h-4 w-4 text-destructive"})})]},d.id))})]})}const Qjn=[{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"}],Jjn=[{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 e2n({id:s,url:t,index:n,onRemove:r}){const{attributes:a,listeners:i,setNodeRef:l,transform:o,transition:c,isDragging:d}=V3e({id:s}),u={transform:fE.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(Mp,{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(hr,{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(Wa,{className:"h-2.5 w-2.5 fill-current"})," Primary"]})]})}function t2n({photoUrls:s,pendingPhotos:t,onRemove:n,onReorder:r,uploading:a,onUpload:i}){const l=D3e(QB(kU,{activationConstraint:{distance:5}})),o=s.map((d,u)=>`pending-${u}`),c=d=>{const{active:u,over:h}=d;if(!h||u.id===h.id)return;const m=o.indexOf(u.id),f=o.indexOf(h.id),g=[...s],y=[...t],[x]=g.splice(m,1),[_]=y.splice(m,1);g.splice(f,0,x),y.splice(f,0,_),r(g,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($3e,{sensors:l,collisionDetection:R3e,onDragEnd:c,children:e.jsx(q3e,{items:o,strategy:rJ,children:e.jsxs("div",{className:"grid grid-cols-3 sm:grid-cols-4 gap-4",children:[s.map((d,u)=>e.jsx(e2n,{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(us,{className:"h-8 w-8 animate-spin"}):e.jsxs(e.Fragment,{children:[e.jsx(ni,{className:"h-8 w-8"}),e.jsx("span",{className:"text-xs",children:"Upload"})]}),e.jsx("input",{type:"file",accept:"image/*",multiple:!0,className:"hidden",onChange:d=>i(d.target.files),disabled:a})]})]})})}),t.length>0&&e.jsxs("p",{className:"text-sm text-muted-foreground mt-4",children:[t.length," photo",t.length!==1?"s":""," will be uploaded when you save."]})]})}function Eft(){const{listingId:s}=uo(),[t]=$c(),n=t.get("brokerage"),r=tr(),{user:a}=Ls(),{hasLeadSite:i}=Qx(),l=!!s&&s!=="new",o=!!n&&!l,[c,d]=N.useState([]),[u,h]=N.useState({open:!1,listingId:null,nextPath:"/mission-control/listings"}),{data:m,isLoading:f}=mqe(l?s:""),g=Rjs(),y=Ojs(),x=Fjs(),_=zjs(),b=Bjs(),k=$js(),A=Ujs(),{data:T=[]}=mt({queryKey:["brokerage-agents",n],queryFn:async()=>{if(!n)return[];const{data:xe,error:ve}=await H.from("profiles").select("id, name, email").eq("brokerage_id",n).order("name");if(ve)throw ve;return xe||[]},enabled:o}),[P,I]=N.useState(""),[M,L]=N.useState(!1),[z,$]=N.useState([]),[V,W]=N.useState([]),[G,X]=N.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,allow_sharing:!0,open_to_referrals:!0,open_to_social_promotion:!0,share_with_brokerage:!1,is_public:!0});N.useEffect(()=>{var xe,ve,ge,be,Se;m&&l&&X({property_address:m.property_address||"",city:m.city||"",state:m.state||"",neighborhood:m.neighborhood||"",price:((xe=m.price)==null?void 0:xe.toString())||"",property_type:m.property_type,status:m.status,bedrooms:((ve=m.bedrooms)==null?void 0:ve.toString())||"",bathrooms:((ge=m.bathrooms)==null?void 0:ge.toString())||"",square_footage:((be=m.square_footage)==null?void 0:be.toString())||"",lot_size:m.lot_size||"",year_built:((Se=m.year_built)==null?void 0:Se.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,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})},[m,l]);const te=xe=>{var Se,Ie;const ve={"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"},ge=(xe.propertyType||"").toLowerCase(),be=((Se=Object.entries(ve).find(([Me])=>ge.includes(Me)))==null?void 0:Se[1])||"other";X(Me=>({...Me,property_address:xe.address||Me.property_address,city:xe.city||Me.city,state:xe.state||Me.state,price:xe.price?String(xe.price):Me.price,property_type:be,bedrooms:xe.bedrooms?String(xe.bedrooms):Me.bedrooms,bathrooms:xe.bathrooms?String(xe.bathrooms):Me.bathrooms,square_footage:xe.sqft?String(xe.sqft):Me.square_footage,lot_size:xe.lotSize?String(xe.lotSize):Me.lot_size,year_built:xe.yearBuilt?String(xe.yearBuilt):Me.year_built,description:xe.description||Me.description})),((Ie=xe.photos)==null?void 0:Ie.length)>0&&(d(xe.photos),V.forEach(Me=>URL.revokeObjectURL(Me)),$([]),W([]))},ne=xe=>{if(!xe)return;const ve=Array.from(xe);$(be=>[...be,...ve]);const ge=ve.map(be=>URL.createObjectURL(be));W(be=>[...be,...ge])},me=xe=>{URL.revokeObjectURL(V[xe]),$(ve=>ve.filter((ge,be)=>be!==xe)),W(ve=>ve.filter((ge,be)=>be!==xe))},ue=async xe=>{var ve;if(!(!xe||!m)){L(!0);try{for(const ge of Array.from(xe)){const be=ge.name.split(".").pop(),Se=`${a==null?void 0:a.id}/${m.id}/${Date.now()}.${be}`,{error:Ie}=await H.storage.from("listing-photos").upload(Se,ge);if(Ie)throw Ie;const{data:{publicUrl:Me}}=H.storage.from("listing-photos").getPublicUrl(Se);await _.mutateAsync({listingId:m.id,photoUrl:Me,isPrimary:!((ve=m.photos)!=null&&ve.length)})}ie.success("Photos uploaded!")}catch(ge){console.error("Upload error:",ge),ie.error("Failed to upload photos")}finally{L(!1)}}},ce=async xe=>{for(let ve=0;ve{if(m)try{await b.mutateAsync({photoId:xe,listingId:m.id}),ie.success("Photo removed")}catch{ie.error("Failed to remove photo")}},he=async xe=>{if(xe.preventDefault(),!G.city.trim()||!G.state.trim()||!G.price){ie.error("Please fill in required fields (City, State, Price)");return}if(o&&!P){ie.error("Please select an agent to assign this listing to");return}try{const ve={property_address:G.property_address||null,city:G.city,state:G.state,neighborhood:G.neighborhood||null,price:Number(G.price),property_type:G.property_type,status:G.status,bedrooms:G.bedrooms?Number(G.bedrooms):null,bathrooms:G.bathrooms?Number(G.bathrooms):null,square_footage:G.square_footage?Number(G.square_footage):null,lot_size:G.lot_size||null,year_built:G.year_built?Number(G.year_built):null,has_hoa:G.has_hoa,description:G.description||null,agent_notes:G.agent_notes||null,agent_notes_public:G.agent_notes_public,mls_link:G.mls_link||null,video_link:G.video_link||null,video_id:G.video_id||null,allow_sharing:G.allow_sharing,open_to_referrals:G.open_to_referrals,open_to_social_promotion:G.open_to_social_promotion,share_with_brokerage:G.share_with_brokerage,is_public:G.is_public};if(l)await x.mutateAsync({id:s,...ve}),ie.success("Listing updated!"),r(`/mission-control/listings/${s}`);else{L(!0);let ge;if(o&&P?ge=await y.mutateAsync({agentId:P,...ve}):ge=await g.mutateAsync(ve),z.length>0)try{await ce(ge.id),V.forEach(Se=>URL.revokeObjectURL(Se)),$([]),W([])}catch(Se){console.error("Photo upload error:",Se),ie.error("Listing created but some photos failed to upload")}if(c.length>0)try{for(let Se=0;Ser(o?"/my-brokerage":"/mission-control/listings"),children:[e.jsx(ka,{className:"h-4 w-4 mr-2"}),o?"Back to Brokerage":"Back to Listings"]}),e.jsxs("div",{className:"grid md:grid-cols-3 gap-6",children:[e.jsxs("div",{className:"md:col-span-2 space-y-6",children:[o&&e.jsxs(_e,{children:[e.jsx(zt,{children:e.jsx(qt,{children:"Assign to Agent *"})}),e.jsxs(De,{children:[e.jsxs(Ns,{value:P,onValueChange:I,children:[e.jsx(ws,{children:e.jsx(ks,{placeholder:"Select an agent..."})}),e.jsx(js,{children:T.map(xe=>e.jsx(nt,{value:xe.id,children:xe.name||xe.email},xe.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(Gjn,{onImport:te}),c.length>0&&e.jsxs(_e,{className:"border-primary/30 bg-primary/5",children:[e.jsxs(zt,{className:"pb-3",children:[e.jsxs(qt,{className:"text-base flex items-center gap-2",children:[e.jsx(oi,{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(De,{children:[e.jsxs("div",{className:"grid grid-cols-4 sm:grid-cols-6 gap-2",children:[c.slice(0,12).map((xe,ve)=>e.jsx("div",{className:"aspect-square rounded overflow-hidden bg-muted",children:e.jsx("img",{src:xe,alt:"",className:"w-full h-full object-cover"})},ve)),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(hr,{className:"h-3 w-3 mr-1"})," Clear MLS photos"]})]})]}),e.jsxs(_e,{children:[e.jsx(zt,{children:e.jsx(qt,{children:"Property Details"})}),e.jsx(De,{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(re,{children:"Property Address"}),e.jsx(we,{value:G.property_address,onChange:xe=>X({...G,property_address:xe.target.value}),placeholder:"123 Main St"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{children:"City *"}),e.jsx(we,{value:G.city,onChange:xe=>X({...G,city:xe.target.value}),placeholder:"City",required:!0})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{children:"State *"}),e.jsx(we,{value:G.state,onChange:xe=>X({...G,state:xe.target.value}),placeholder:"State",required:!0})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{children:"Neighborhood"}),e.jsx(we,{value:G.neighborhood,onChange:xe=>X({...G,neighborhood:xe.target.value}),placeholder:"Neighborhood"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{children:"Price *"}),e.jsx(we,{type:"number",value:G.price,onChange:xe=>X({...G,price:xe.target.value}),placeholder:"500000",required:!0})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{children:"Property Type"}),e.jsxs(Ns,{value:G.property_type,onValueChange:xe=>X({...G,property_type:xe}),children:[e.jsx(ws,{children:e.jsx(ks,{})}),e.jsx(js,{children:Jjn.map(xe=>e.jsx(nt,{value:xe.value,children:xe.label},xe.value))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{children:"Status"}),e.jsxs(Ns,{value:G.status,onValueChange:xe=>X({...G,status:xe}),children:[e.jsx(ws,{children:e.jsx(ks,{})}),e.jsx(js,{children:Qjn.map(xe=>e.jsx(nt,{value:xe.value,children:xe.label},xe.value))})]})]})]})})]}),e.jsxs(_e,{children:[e.jsx(zt,{children:e.jsx(qt,{children:"Property Specs (Optional)"})}),e.jsx(De,{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(re,{children:"Bedrooms"}),e.jsx(we,{type:"number",value:G.bedrooms,onChange:xe=>X({...G,bedrooms:xe.target.value}),placeholder:"3"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{children:"Bathrooms"}),e.jsx(we,{type:"number",step:"0.5",value:G.bathrooms,onChange:xe=>X({...G,bathrooms:xe.target.value}),placeholder:"2"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{children:"Sq Ft"}),e.jsx(we,{type:"number",value:G.square_footage,onChange:xe=>X({...G,square_footage:xe.target.value}),placeholder:"2000"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{children:"Lot Size"}),e.jsx(we,{value:G.lot_size,onChange:xe=>X({...G,lot_size:xe.target.value}),placeholder:"0.25 acres"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{children:"Year Built"}),e.jsx(we,{type:"number",value:G.year_built,onChange:xe=>X({...G,year_built:xe.target.value}),placeholder:"2005"})]}),e.jsxs("div",{className:"flex items-center gap-2 pt-6",children:[e.jsx(zn,{checked:G.has_hoa,onCheckedChange:xe=>X({...G,has_hoa:xe})}),e.jsx(re,{children:"Has HOA"})]})]})})]}),e.jsxs(_e,{children:[e.jsx(zt,{children:e.jsx(qt,{children:"Description & Links"})}),e.jsxs(De,{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{children:"Description"}),e.jsx(Ws,{value:G.description,onChange:xe=>X({...G,description:xe.target.value}),placeholder:"Tell the story of this property...",rows:4})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{children:"Agent Notes"}),e.jsx(Ws,{value:G.agent_notes,onChange:xe=>X({...G,agent_notes:xe.target.value}),placeholder:"Notes for other agents...",rows:2}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(zn,{checked:G.agent_notes_public,onCheckedChange:xe=>X({...G,agent_notes_public:xe})}),e.jsx(re,{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(re,{children:"MLS Link"}),e.jsx(we,{value:G.mls_link,onChange:xe=>X({...G,mls_link:xe.target.value}),placeholder:"https://..."})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{children:"Video Link"}),e.jsx(we,{value:G.video_link,onChange:xe=>X({...G,video_link:xe.target.value}),placeholder:"YouTube or Vimeo URL"})]})]})]})]}),e.jsxs(_e,{children:[e.jsx(zt,{children:e.jsxs(qt,{className:"flex items-center gap-2",children:[e.jsx(na,{className:"h-5 w-5"}),"Property Video"]})}),e.jsx(De,{children:e.jsx(Yjn,{selectedVideoId:G.video_id,onVideoSelect:xe=>X({...G,video_id:xe}),listingId:l?s:void 0})})]}),e.jsxs(_e,{children:[e.jsx(zt,{children:e.jsx(qt,{children:"Photos"})}),e.jsx(De,{children:l&&(m!=null&&m.photos)?e.jsx(Kjn,{photos:m.photos,uploading:M,onUpload:xe=>ue(xe),onRemove:xe=>ae(xe),onReorder:xe=>{k.mutate({photos:xe.map(ve=>({id:ve.id,sort_order:ve.sort_order,is_primary:ve.is_primary}))})},onSetPrimary:xe=>{m&&A.mutate({photoId:xe,listingId:m.id})}}):e.jsx(t2n,{photoUrls:V,onRemove:me,onReorder:(xe,ve)=>{W(xe),$(ve)},pendingPhotos:z,uploading:M,onUpload:ne})})]}),e.jsxs(_e,{children:[e.jsx(zt,{children:e.jsxs(qt,{className:"flex items-center gap-2",children:[e.jsx(oi,{className:"h-5 w-5"}),"Documents & Disclosures"]})}),e.jsx(De,{children:l&&s?e.jsx(Xjn,{listingId:s}):e.jsx("p",{className:"text-sm text-muted-foreground",children:"Save the listing first, then you can upload PDFs (disclosures, floor plans, HOA docs, etc.) for other agents to download."})})]})]}),e.jsxs("div",{className:"space-y-6",children:[e.jsxs(_e,{children:[e.jsx(zt,{children:e.jsx(qt,{children:"Sharing & Collaboration"})}),e.jsxs(De,{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(re,{children:"Allow Sharing"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Other agents can share this listing"})]}),e.jsx(zn,{checked:G.allow_sharing,onCheckedChange:xe=>X({...G,allow_sharing:xe})})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(re,{children:"Open to Referrals"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Accept buyer referrals"})]}),e.jsx(zn,{checked:G.open_to_referrals,onCheckedChange:xe=>X({...G,open_to_referrals:xe})})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(re,{children:"Social Promotion"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Can be promoted on social media"})]}),e.jsx(zn,{checked:G.open_to_social_promotion,onCheckedChange:xe=>X({...G,open_to_social_promotion:xe})})]}),e.jsxs("div",{className:"flex items-center justify-between pt-2 border-t",children:[e.jsxs("div",{children:[e.jsx(re,{children:"Share with Brokerage"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Visible to agents in your brokerage"})]}),e.jsx(zn,{checked:G.share_with_brokerage,onCheckedChange:xe=>X({...G,share_with_brokerage:xe})})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(re,{children:"Make Public"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Publish on listings.relevelup.com to get leads"})]}),e.jsx(zn,{checked:G.is_public,onCheckedChange:xe=>X({...G,is_public:xe})})]})]})]}),e.jsx(B,{type:"submit",className:"w-full",size:"lg",disabled:g.isPending||x.isPending,children:g.isPending||x.isPending?e.jsxs(e.Fragment,{children:[e.jsx(us,{className:"h-4 w-4 mr-2 animate-spin"}),"Saving..."]}):l?"Update Listing":"Create Listing"})]})]})]}),e.jsx(j7t,{listingId:u.listingId,open:u.open,onOpenChange:xe=>{if(!xe){const{nextPath:ve}=u;h({open:!1,listingId:null,nextPath:ve}),r(ve)}}})]})}const fze=[{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"}],C7t=[{type:"extra_video",label:"Extra Video / Reel",icon:na,desc:"Add a YouTube, Vimeo, or MP4 embed",accent:"from-rose-500/20 to-rose-500/5"},{type:"tour_3d",label:"3D Tour",icon:zG,desc:"Matterport, iGuide, or Kuula embed",accent:"from-indigo-500/20 to-indigo-500/5"},{type:"floor_plans",label:"Floor Plans",icon:pc,desc:"Upload floor plan images",accent:"from-sky-500/20 to-sky-500/5"},{type:"testimonial",label:"Testimonial",icon:Q2,desc:"A quote from a past client",accent:"from-amber-500/20 to-amber-500/5"},{type:"countdown",label:"Offer Countdown",icon:Xr,desc:'"Offers due Friday 5pm"',accent:"from-emerald-500/20 to-emerald-500/5"},{type:"custom_cta",label:"Custom CTA Button",icon:gc,desc:"Link to a brochure or booking page",accent:"from-violet-500/20 to-violet-500/5"}],s2n=["#0f172a","#406E71","#c9a84c","#b91c1c","#0d7a5f","#4f46e5","#e85d3a","#111827"],qPe={sections:Object.fromEntries(fze.map(s=>[s.key,!0])),hero_style:"photo",accent_color:null,custom_note:"",addons:[]},n2n=()=>Math.random().toString(36).slice(2,10);function r2n(){const{listingId:s}=uo(),t=tr(),{user:n}=Ls(),r=as(),[a,i]=N.useState("desktop"),[l,o]=N.useState(qPe),[c,d]=N.useState(!1),[u,h]=N.useState(0),{data:m,isLoading:f}=mt({queryKey:["listing-customize",s],queryFn:async()=>{const{data:z,error:$}=await H.from("listings").select("id, agent_id, slug, property_address, city, state, price, page_config, page_theme").eq("id",s).single();if($)throw $;return z},enabled:!!s});N.useEffect(()=>{var z,$;m!=null&&m.page_config&&o({...qPe,...m.page_config||{},sections:{...qPe.sections,...((z=m.page_config)==null?void 0:z.sections)||{}},addons:(($=m.page_config)==null?void 0:$.addons)||[]})},[m==null?void 0:m.id]);const g=!!n&&!!m&&n.id===m.agent_id,y=N.useMemo(()=>m?`/public/listing/${m.slug||m.id}?preview=1&t=${u}`:"",[m,u]),x=N.useMemo(()=>m?`https://listings.relevelup.com/${m.slug||m.id}`:"",[m]),_=_t({mutationFn:async()=>{const{error:z}=await H.from("listings").update({page_config:l}).eq("id",s);if(z)throw z},onSuccess:()=>{ie.success("Saved. Your public page is live."),d(!1),r.invalidateQueries({queryKey:["listing-customize",s]}),r.invalidateQueries({queryKey:["public-listing"]}),h(z=>z+1)},onError:z=>ie.error(`Save failed: ${z.message||"Try again"}`)}),b=z=>{o($=>({...$,...z})),d(!0)},k=(z,$)=>b({sections:{...l.sections||{},[z]:$}}),A=z=>b({addons:[...l.addons||[],{id:n2n(),type:z,data:{}}]}),T=(z,$)=>b({addons:(l.addons||[]).map(V=>V.id===z?{...V,data:{...V.data,...$}}:V)}),P=z=>b({addons:(l.addons||[]).filter($=>$.id!==z)}),I=(z,$)=>{const V=[...l.addons||[]],W=V.findIndex(X=>X.id===z);if(W<0)return;const G=W+$;G<0||G>=V.length||([V[W],V[G]]=[V[G],V[W]],b({addons:V}))};if(f)return e.jsx(Qs,{title:"",description:"",children:e.jsx("div",{className:"p-8 text-sm text-muted-foreground",children:"Loading…"})});if(!m)return e.jsx(Qs,{title:"",description:"",children:e.jsx("div",{className:"p-8",children:"Listing not found."})});if(!g)return e.jsx(Qs,{title:"",description:"",children:e.jsxs("div",{className:"p-8",children:[e.jsx("p",{children:"You can only customize your own listing pages."}),e.jsx(B,{className:"mt-3",onClick:()=>t(`/mission-control/listings/${m.id}`),children:"Back"})]})});const M=(l.addons||[]).length,L=Object.values(l.sections||{}).filter(Boolean).length;return e.jsxs(Qs,{title:"",description:"",children:[e.jsxs("div",{className:"sticky top-0 z-30 -mx-4 sm:-mx-6 px-4 sm:px-6 py-3 bg-background/85 backdrop-blur border-b flex items-center gap-3",children:[e.jsxs(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(hj,{className:"h-3.5 w-3.5"})," Desktop"]}),e.jsxs("button",{onClick:()=>i("mobile"),className:`h-8 px-2.5 rounded-md text-xs flex items-center gap-1.5 ${a==="mobile"?"bg-background shadow-sm":"text-muted-foreground"}`,children:[e.jsx($y,{className:"h-3.5 w-3.5"})," Mobile"]})]}),e.jsxs(B,{variant:"outline",size:"sm",onClick:()=>h(z=>z+1),children:[e.jsx(oo,{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:x,target:"_blank",rel:"noopener noreferrer",children:[e.jsx(Tr,{className:"h-3.5 w-3.5 mr-1.5"})," Open live"]})}),e.jsx(B,{size:"sm",onClick:()=>_.mutate(),disabled:!c||_.isPending,children:_.isPending?"Saving…":e.jsxs(e.Fragment,{children:[e.jsx(Kl,{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(lo,{className:"lg:h-[calc(100vh-140px)] pr-2",children:e.jsxs("div",{className:"space-y-6 pb-16",children:[e.jsx(hH,{icon:e.jsx(Cn,{className:"h-4 w-4"}),title:"Hero",desc:"What visitors see first",children:e.jsxs("div",{children:[e.jsx(re,{className:"text-xs",children:"Hero style"}),e.jsx("div",{className:"mt-2 grid grid-cols-3 gap-2",children:["photo","video","slideshow"].map(z=>e.jsx("button",{onClick:()=>b({hero_style:z}),className:`text-xs rounded-lg border py-3 capitalize transition ${l.hero_style===z?"border-primary bg-primary/5 text-primary font-medium":"border-border hover:bg-muted"}`,children:z},z))})]})}),e.jsx(hH,{icon:e.jsx(zc,{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"}),s2n.map(z=>e.jsx("button",{onClick:()=>b({accent_color:z}),className:`h-9 w-9 rounded-full border-2 transition ${l.accent_color===z?"ring-2 ring-offset-2 ring-primary border-white":"border-white/20"}`,style:{background:z},"aria-label":z},z))]})}),e.jsx(hH,{icon:e.jsx(Zg,{className:"h-4 w-4"}),title:"Personal note",desc:"Shows in a beautiful callout on the public page",children:e.jsx(Ws,{value:l.custom_note||"",onChange:z=>b({custom_note:z.target.value}),placeholder:"Why we love this home… (optional)",rows:3})}),e.jsx(hH,{icon:e.jsx(c4,{className:"h-4 w-4"}),title:"Page sections",desc:"Toggle any default section on or off",rightLabel:`${L} of ${fze.length} on`,children:e.jsx("div",{className:"divide-y rounded-xl border",children:fze.map(z=>{var V;const $=((V=l.sections)==null?void 0:V[z.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:z.label}),e.jsx("p",{className:"text-xs text-muted-foreground truncate",children:z.hint})]}),e.jsx(zn,{checked:$,onCheckedChange:W=>k(z.key,W)})]},z.key)})})}),e.jsxs(hH,{icon:e.jsx(nn,{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:C7t.map(z=>e.jsxs("button",{onClick:()=>A(z.type),className:`group text-left rounded-xl border p-3 hover:shadow-md transition bg-gradient-to-br ${z.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(z.icon,{className:"h-3.5 w-3.5"})}),e.jsx("span",{className:"text-sm font-medium",children:z.label})]}),e.jsx("p",{className:"text-[11px] text-muted-foreground leading-snug",children:z.desc})]},z.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((z,$)=>e.jsx(a2n,{addon:z,onChange:V=>T(z.id,V),onRemove:()=>P(z.id),onMoveUp:$>0?()=>I(z.id,-1):void 0,onMoveDown:$I(z.id,1):void 0},z.id))]})]}),e.jsx("div",{className:"lg:hidden",children:e.jsx(B,{className:"w-full",onClick:()=>_.mutate(),disabled:!c||_.isPending,children:_.isPending?"Saving…":e.jsxs(e.Fragment,{children:[e.jsx(Kl,{className:"h-4 w-4 mr-1.5"})," Save & Publish"]})})})]})}),e.jsx("div",{className:"lg:h-[calc(100vh-140px)]",children:e.jsxs(_e,{className:"h-full overflow-hidden bg-neutral-100 p-4 lg:p-6 border rounded-2xl",children:[e.jsxs("div",{className:"flex items-center justify-between mb-3",children:[e.jsxs("div",{className:"flex items-center gap-2 text-xs text-muted-foreground",children:[e.jsx(da,{className:"h-3.5 w-3.5"}),"Live preview",c&&e.jsx(We,{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(pa,{className:"h-3 w-3"})," In sync"]})]}),e.jsxs("div",{className:"lg:hidden inline-flex rounded-lg border bg-background p-0.5",children:[e.jsx("button",{onClick:()=>i("desktop"),className:`h-7 px-2 rounded ${a==="desktop"?"bg-muted":""}`,children:e.jsx(hj,{className:"h-3.5 w-3.5"})}),e.jsx("button",{onClick:()=>i("mobile"),className:`h-7 px-2 rounded ${a==="mobile"?"bg-muted":""}`,children:e.jsx($y,{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 hH({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 a2n({addon:s,onChange:t,onRemove:n,onMoveUp:r,onMoveDown:a}){const i=C7t.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(Mp,{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(Mp,{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(qn,{className:"h-3.5 w-3.5"})})]})]}),s.type==="extra_video"&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{className:"text-xs",children:"Video URL"}),e.jsx(we,{placeholder:"https://youtu.be/…",value:s.data.url||"",onChange:o=>t({url:o.target.value})}),e.jsx(re,{className:"text-xs",children:"Title (optional)"}),e.jsx(we,{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(re,{className:"text-xs",children:"3D tour embed URL"}),e.jsx(we,{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(re,{className:"text-xs",children:"Floor plan image URLs (one per line)"}),e.jsx(Ws,{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(re,{className:"text-xs",children:"Quote"}),e.jsx(Ws,{rows:3,placeholder:`"Best home-buying experience we've ever had."`,value:s.data.quote||"",onChange:o=>t({quote:o.target.value})}),e.jsx(re,{className:"text-xs",children:"Attribution"}),e.jsx(we,{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(re,{className:"text-xs",children:"Headline"}),e.jsx(we,{placeholder:"Offers due",value:s.data.headline||"",onChange:o=>t({headline:o.target.value})}),e.jsx(re,{className:"text-xs",children:"Deadline (date & time)"}),e.jsx(we,{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(re,{className:"text-xs",children:"Button label"}),e.jsx(we,{placeholder:"Download brochure",value:s.data.label||"",onChange:o=>t({label:o.target.value})}),e.jsx(re,{className:"text-xs",children:"Link URL"}),e.jsx(we,{placeholder:"https://…",value:s.data.url||"",onChange:o=>t({url:o.target.value})})]})]})}const A7t="teleprompter_settings",VPe={scrollSpeed:30,fontSize:24,lineHeight:1.6,opacity:.85,position:"top",isMirrored:!1};function i2n(){try{const s=localStorage.getItem(A7t);return s?{...VPe,...JSON.parse(s)}:VPe}catch{return VPe}}function o2n(s){try{localStorage.setItem(A7t,JSON.stringify(s))}catch{}}function qWe({text:s,isVisible:t,onToggleVisibility:n,isRecording:r=!1,startCountdown:a=!1,onCountdownComplete:i,className:l}){const o=N.useRef(null),c=N.useRef(null),d=N.useRef(0),u=N.useRef(0),[h,m]=N.useState(i2n),{scrollSpeed:f,fontSize:g,lineHeight:y,opacity:x,position:_,isMirrored:b}=h,k=N.useCallback((V,W)=>{m(G=>{const X={...G,[V]:W};return o2n(X),X})},[]),[A,T]=N.useState(!1),[P,I]=N.useState(null),M=N.useCallback(V=>{if(!o.current)return;d.current===0&&(d.current=V);const W=V-d.current;d.current=V,u.current+=f*W/1e3;const G=Math.floor(u.current);G>0&&(o.current.scrollTop+=G,u.current-=G);const{scrollTop:X,scrollHeight:te,clientHeight:ne}=o.current;if(X+ne>=te){T(!1);return}c.current=requestAnimationFrame(M)},[f]);N.useEffect(()=>(A?(d.current=0,u.current=0,c.current=requestAnimationFrame(M)):c.current&&cancelAnimationFrame(c.current),()=>{c.current&&cancelAnimationFrame(c.current)}),[A,M]),N.useEffect(()=>{if(r&&t)if(o.current&&(o.current.scrollTop=0),a){I(3);let V=3;const W=setInterval(()=>{V-=1,V<=0?(clearInterval(W),I(null),i==null||i(),T(!0)):I(V)},1e3);return()=>clearInterval(W)}else setTimeout(()=>T(!0),100);else r||(T(!1),I(null))},[r,t,a,i]);const L=N.useCallback(()=>{o.current&&(o.current.scrollTop=0),T(!1)},[]),z=N.useCallback(()=>{T(V=>!V)},[]);if(!t)return e.jsx("div",{className:Ot("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(da,{className:"h-4 w-4 mr-2"}),"Show Script"]})});const $={top:"top-0 pt-16",center:"top-1/2 -translate-y-1/2",bottom:"bottom-0 pb-24"};return e.jsxs("div",{className:Ot("absolute inset-0 pointer-events-none",l),children:[P!==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:P},P),e.jsx("p",{className:"text-white/80 text-lg font-medium drop-shadow-md",children:"Get ready…"})]})}),e.jsx("div",{className:Ot("absolute left-0 right-0 h-[60%] overflow-hidden pointer-events-auto",$[_],P!==null&&"opacity-30"),style:{opacity:P!==null?.3:x},children:e.jsxs("div",{ref:o,className:Ot("mx-auto max-w-2xl px-6 overflow-y-auto scrollbar-hide h-full",b&&"scale-x-[-1]"),style:{maskImage:"linear-gradient(to bottom, transparent, black 10%, black 90%, transparent)",WebkitMaskImage:"linear-gradient(to bottom, transparent, black 10%, black 90%, transparent)"},children:[e.jsx("div",{className:"h-full",style:{minHeight:"100%"}}),e.jsx("p",{className:"text-white text-center font-medium drop-shadow-lg",style:{fontSize:`${g}px`,lineHeight: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(rc,{children:[e.jsx(ac,{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(sc,{className:"h-4 w-4"})})}),e.jsx(Zl,{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(re,{className:"text-xs",children:"Scroll Speed"}),e.jsx("span",{className:"text-xs text-muted-foreground",children:f})]}),e.jsx(qf,{value:[f],onValueChange:([V])=>k("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(re,{className:"text-xs",children:"Font Size"}),e.jsxs("span",{className:"text-xs text-muted-foreground",children:[g,"px"]})]}),e.jsx(qf,{value:[g],onValueChange:([V])=>k("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(re,{className:"text-xs",children:"Line Spacing"}),e.jsx("span",{className:"text-xs text-muted-foreground",children:y.toFixed(1)})]}),e.jsx(qf,{value:[y*10],onValueChange:([V])=>k("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(re,{className:"text-xs",children:"Opacity"}),e.jsxs("span",{className:"text-xs text-muted-foreground",children:[Math.round(x*100),"%"]})]}),e.jsx(qf,{value:[x*100],onValueChange:([V])=>k("opacity",V/100),min:30,max:100,step:5})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{className:"text-xs",children:"Position"}),e.jsxs("div",{className:"flex gap-1",children:[e.jsx(B,{variant:_==="top"?"default":"outline",size:"sm",onClick:()=>k("position","top"),children:e.jsx(zy,{className:"h-4 w-4"})}),e.jsx(B,{variant:_==="center"?"default":"outline",size:"sm",onClick:()=>k("position","center"),children:e.jsx(X2,{className:"h-4 w-4"})}),e.jsx(B,{variant:_==="bottom"?"default":"outline",size:"sm",onClick:()=>k("position","bottom"),children:e.jsx(Xo,{className:"h-4 w-4"})})]})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(re,{className:"text-xs",children:"Mirror Mode"}),e.jsx(zn,{checked:b,onCheckedChange:V=>k("isMirrored",V)})]})]})})]}),e.jsx(B,{variant:"secondary",size:"icon",onClick:z,className:"h-9 w-9 bg-black/50 hover:bg-black/70 text-white border-0",children:A?e.jsx(K0,{className:"h-4 w-4"}):e.jsx(dd,{className:"h-4 w-4"})}),e.jsx(B,{variant:"secondary",size:"icon",onClick:L,className:"h-9 w-9 bg-black/50 hover:bg-black/70 text-white border-0",children:e.jsx(hf,{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(V0,{className:"h-4 w-4 mr-2"}),"Hide"]})]})]})}function l2n({onSelectScript:s,onCreateNew:t,selectedScriptId:n,className:r}){const{toast:a}=Ci(),[i,l]=N.useState(""),[o,c]=N.useState(null),[d,u]=N.useState("levelup"),{data:h,isLoading:m}=Xmn(),{data:f,isLoading:g}=Qmn(),{data:y,isLoading:x}=Jmn(),_=epn(),b=N.useMemo(()=>f?f.filter(I=>{const M=!i||I.title.toLowerCase().includes(i.toLowerCase())||I.script_text.toLowerCase().includes(i.toLowerCase())||I.tags.some(z=>z.toLowerCase().includes(i.toLowerCase())),L=!o||I.category_id===o;return M&&L}):[],[f,i,o]),k=N.useMemo(()=>y?y.filter(I=>!i||I.title.toLowerCase().includes(i.toLowerCase())||I.script_text.toLowerCase().includes(i.toLowerCase())):[],[y,i]),A=I=>{s({title:I.title,text:I.script_text})},T=async I=>{try{await _.mutateAsync(I),a({title:"Script saved to My Scripts"})}catch{a({title:"Failed to save script",variant:"destructive"})}},P=m||g||x;return e.jsxs("div",{className:Ot("flex flex-col h-full",r),children:[e.jsx("div",{className:"p-4 border-b",children:e.jsxs("div",{className:"relative",children:[e.jsx(Gr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(we,{placeholder:"Search scripts...",value:i,onChange:I=>l(I.target.value),className:"pl-9"})]})}),e.jsxs(ya,{value:d,onValueChange:I=>u(I),className:"flex-1 flex flex-col",children:[e.jsxs(va,{className:"mx-4 mt-4 grid grid-cols-2",children:[e.jsxs(ls,{value:"levelup",children:[e.jsx(Wr,{className:"h-4 w-4 mr-2"}),"LevelUp Scripts"]}),e.jsxs(ls,{value:"my-scripts",children:[e.jsx(Hv,{className:"h-4 w-4 mr-2"}),"My Scripts"]})]}),e.jsxs(_s,{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(We,{variant:o?"outline":"default",className:"cursor-pointer",onClick:()=>c(null),children:"All"}),h==null?void 0:h.map(I=>e.jsx(We,{variant:o===I.id?"default":"outline",className:"cursor-pointer",onClick:()=>c(I.id),children:I.name},I.id))]}),e.jsx(lo,{className:"flex-1 max-h-[50vh]",children:P?e.jsx("div",{className:"flex items-center justify-center py-8",children:e.jsx(us,{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(Wr,{className:"h-12 w-12 mx-auto mb-2 opacity-50"}),e.jsx("p",{children:"No scripts found"})]}):e.jsx("div",{className:"space-y-2",children:b.map(I=>e.jsxs(_e,{className:Ot("cursor-pointer hover:bg-accent/50 transition-colors",n===I.id&&"ring-2 ring-primary"),onClick:()=>A(I),children:[e.jsx(zt,{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(qt,{className:"text-sm font-medium truncate",children:I.title}),I.category&&e.jsx(We,{variant:"secondary",className:"mt-1 text-xs",children:I.category.name})]}),e.jsxs("div",{className:"flex items-center gap-1 ml-2",children:[e.jsx(B,{variant:"ghost",size:"icon",className:"h-8 w-8",onClick:M=>{M.stopPropagation(),T(I)},children:e.jsx(Hv,{className:"h-4 w-4"})}),e.jsx(Qa,{className:"h-4 w-4 text-muted-foreground"})]})]})}),e.jsx(De,{className:"p-3 pt-0",children:e.jsx("p",{className:"text-xs text-muted-foreground line-clamp-2",children:I.script_text})})]},I.id))})})]}),e.jsxs(_s,{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(nn,{className:"h-4 w-4 mr-2"}),"Create New Script"]}),e.jsx(lo,{className:"flex-1 max-h-[50vh]",children:x?e.jsx("div",{className:"flex items-center justify-center py-8",children:e.jsx(us,{className:"h-6 w-6 animate-spin text-muted-foreground"})}):k.length===0?e.jsxs("div",{className:"text-center py-8 text-muted-foreground",children:[e.jsx(Hv,{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:k.map(I=>e.jsxs(_e,{className:Ot("cursor-pointer hover:bg-accent/50 transition-colors",n===I.id&&"ring-2 ring-primary"),onClick:()=>A(I),children:[e.jsx(zt,{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(qt,{className:"text-sm font-medium truncate",children:I.title}),e.jsx("div",{className:"flex items-center gap-2 mt-1",children:I.is_custom?e.jsx(We,{variant:"outline",className:"text-xs",children:"Custom"}):e.jsx(We,{variant:"secondary",className:"text-xs",children:"Saved"})})]}),e.jsx(Qa,{className:"h-4 w-4 text-muted-foreground ml-2"})]})}),e.jsx(De,{className:"p-3 pt-0",children:e.jsx("p",{className:"text-xs text-muted-foreground line-clamp-2",children:I.script_text})})]},I.id))})})]})]})]})}function c2n({selectedTemplate:s,onSelect:t,contactName:n,saving:r=!1}){const[a,i]=N.useState(()=>{const o=q9(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(re,{className:"text-sm font-medium",children:"Share Page Template"}),r&&e.jsx(us,{className:"h-3 w-3 animate-spin text-muted-foreground"})]}),e.jsx("div",{className:"space-y-3",children:Bws.map(o=>{const c=$ws(o.id),d=a.has(o.id),u=c.some(h=>h.id===s);return e.jsxs(Kv,{open:d,onOpenChange:()=>l(o.id),children:[e.jsxs(Yv,{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(Xo,{className:Ot("h-4 w-4 text-muted-foreground transition-transform",d&&"rotate-180")})]}),e.jsx(Zv,{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:Ot("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(pa,{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: "',q9(s).headerText(n),'"']})]})}function T7t({open:s,onOpenChange:t,video:n,contactName:r,onTemplateUpdated:a}){const[i,l]=N.useState(n.page_template||"default"),[o,c]=N.useState(!1),[d,u]=N.useState(!1),[h,m]=N.useState(n.page_template||"default"),[f,g]=N.useState([]),[y,x]=N.useState(n.contact_id&&r?{id:n.contact_id,name:r,email:null}:null),[_,b]=N.useState(!1),[k,A]=N.useState(!1),T=n.share_token?`https://video.relevelup.com/${n.share_token}`:"";N.useEffect(()=>{s&&f.length===0&&P()},[s]);const P=async()=>{A(!0);try{const{data:X,error:te}=await H.from("innercircle_contacts").select("id, first_name, last_name, email").order("first_name",{ascending:!0}).limit(500);if(te)throw te;const ne=(X||[]).map(me=>({id:me.id,name:[me.first_name,me.last_name].filter(Boolean).join(" ")||"Unnamed",email:me.email||null}));g(ne)}catch(X){console.error("Failed to fetch contacts:",X)}finally{A(!1)}},I=async X=>{x(X),b(!1),c(!0);try{const{error:te}=await H.from("agent_videos").update({contact_id:(X==null?void 0:X.id)||null,recipient_name:(X==null?void 0:X.name)||null}).eq("id",n.id);if(te)throw te;ie.success(X?`Assigned to ${X.name}`:"Contact removed"),a==null||a()}catch(te){console.error("Failed to update contact:",te),ie.error("Failed to update contact")}finally{c(!1)}},M=async X=>{l(X),c(!0);try{const{error:te}=await H.from("agent_videos").update({page_template:X}).eq("id",n.id);if(te)throw te;m(X),ie.success("Template saved!"),a==null||a()}catch(te){console.error("Failed to save template:",te),ie.error("Failed to save template"),l(h)}finally{c(!1)}},L=(y==null?void 0:y.name)||null,z=()=>{const X=n.title||"Video Message",te=n.share_token?`https://video.relevelup.com/thumb/${n.share_token}`:n.thumbnail_url||"";return``},$=async()=>{if(!n.thumbnail_url){ie.error("Video thumbnail not available yet");return}const X=z(),te=`Watch: ${n.title||"Video Message"} ${T}`;try{const ne=new Blob([X],{type:"text/html"}),me=new Blob([te],{type:"text/plain"}),ue=new ClipboardItem({"text/html":ne,"text/plain":me});await navigator.clipboard.write([ue]),ie.success("Copied! Paste into Gmail - the thumbnail will appear after sending.")}catch{await navigator.clipboard.writeText(te+` `+X),ie.success("Copied! Paste into your email.")}},V=async()=>{await navigator.clipboard.writeText(T),u(!0),ie.success("Share link copied!"),setTimeout(()=>u(!1),2e3)},W=()=>{const te=q9(i).headerText(L),ne=i==="default"?`Check out this video: ${T}`:`${te} Check out this special video: ${T}`;window.open(`sms:?body=${encodeURIComponent(ne)}`,"_self")},G=()=>{const X=q9(i),te=X.headerText(L),ne=i==="default"?n.title||"Video Message":te,me=`${X.subText} Watch the video: ${T}`,ue=y!=null&&y.email?encodeURIComponent(y.email):"";window.open(`mailto:${ue}?subject=${encodeURIComponent(ne)}&body=${encodeURIComponent(me)}`,"_self")};return e.jsx(Bs,{open:s,onOpenChange:t,children:e.jsxs(Fs,{className:"max-w-lg max-h-[90vh] overflow-y-auto",children:[e.jsxs(qs,{children:[e.jsxs($s,{className:"flex items-center gap-2",children:[e.jsx(gc,{className:"h-5 w-5"}),"Share Video"]}),e.jsx(Ar,{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(re,{className:"text-sm font-medium",children:"Personalize for Contact (Optional)"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(rc,{open:_,onOpenChange:b,children:[e.jsx(ac,{asChild:!0,children:e.jsxs(B,{variant:"outline",role:"combobox","aria-expanded":_,className:"flex-1 justify-between",disabled:o,children:[y?e.jsxs("span",{className:"flex items-center gap-2",children:[e.jsx(Ro,{className:"h-4 w-4 text-muted-foreground"}),y.name]}):e.jsx("span",{className:"text-muted-foreground",children:"Select a contact..."}),e.jsx(sb,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]})}),e.jsx(Zl,{className:"w-[300px] p-0",align:"start",children:e.jsxs(db,{children:[e.jsx(ub,{placeholder:"Search contacts..."}),e.jsxs(hb,{children:[e.jsx(mb,{children:k?"Loading...":"No contacts found."}),e.jsx(pb,{children:f.map(X=>e.jsxs(Ry,{value:X.name,onSelect:()=>I(X),children:[e.jsx(pa,{className:Ot("mr-2 h-4 w-4",(y==null?void 0:y.id)===X.id?"opacity-100":"opacity-0")}),X.name]},X.id))})]})]})})]}),y&&e.jsx(B,{variant:"ghost",size:"icon",onClick:()=>I(null),disabled:o,className:"shrink-0",children:e.jsx(hr,{className:"h-4 w-4"})})]}),y&&i!=="default"&&e.jsxs("p",{className:"text-xs text-muted-foreground",children:['Page will show: "',q9(i).headerText(y.name),'"']})]}),e.jsx(c2n,{selectedTemplate:i,onSelect:M,contactName:L,saving:o}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{children:"Share Link"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(we,{value:T,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(pa,{className:"h-4 w-4"}),"Copied"]}):e.jsxs(e.Fragment,{children:[e.jsx(Pa,{className:"h-4 w-4"}),"Copy"]})})]})]}),n.thumbnail_url&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{children:"Share for Email"}),e.jsxs(B,{variant:"outline",className:"w-full gap-2",onClick:$,children:[e.jsx(pc,{className:"h-4 w-4"}),"Copy with Thumbnail (for Gmail)"]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Paste into Gmail to embed a clickable video thumbnail"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{children:"Quick Share"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(B,{variant:"outline",className:"flex-1 gap-2",onClick:W,children:[e.jsx(xo,{className:"h-4 w-4"}),"Text"]}),e.jsxs(B,{variant:"outline",className:"flex-1 gap-2",onClick:G,children:[e.jsx(mn,{className:"h-4 w-4"}),"Email"]})]})]})]}),e.jsx(Cr,{children:e.jsx(B,{variant:"outline",onClick:()=>t(!1),children:"Done"})})]})})}function d2n(){var $e;const s=tr(),[t]=$c(),{toast:n}=Ci(),r=t.get("contact_id"),a=t.get("task_id"),{canRecord:i,remainingMb:l,usagePercent:o,isNearLimit:c,storage:d}=dIt(),{data:u}=Wy(),h=G3(),m=apn(),[f,g]=N.useState("record"),[y,x]=N.useState(""),[_,b]=N.useState(!1),[k,A]=N.useState(!1),[T,P]=N.useState(!1),[I,M]=N.useState(null),[L,z]=N.useState(0),[$,V]=N.useState(0),[W,G]=N.useState(null),[X,te]=N.useState(null),[ne,me]=N.useState(r||""),[ue,ce]=N.useState(""),[ae,he]=N.useState(""),[xe,ve]=N.useState(null),[ge,be]=N.useState(null),[Se,Ie]=N.useState(null),[Me,Re]=N.useState(!1),Be=N.useCallback(async(Ye,Je)=>{M(Ye),g("uploading");try{const{videoId:Ke,uploadUrl:st}=await sO(ue||"Quick Video Touch");G(Ke);const{apiKey:rt}=await nO(Ke),Ze=new XMLHttpRequest;Ze.upload.onprogress=Yt=>{Yt.lengthComputable&&z(Yt.loaded/Yt.total*100)},await new Promise((Yt,Kt)=>{Ze.onload=()=>{Ze.status>=200&&Ze.status<300?Yt():Kt(new Error(`Upload failed: ${Ze.status}`))},Ze.onerror=()=>Kt(new Error("Upload failed")),Ze.open("PUT",st),Ze.setRequestHeader("AccessKey",rt),Ze.send(Ye)}),g("processing");let ht=0;const Bt=Date.now(),Ct=90*1e3;for(;ht<4;){if(await new Promise(Kt=>setTimeout(Kt,3e3)),Date.now()-Bt>Ct){const Kt=Ye.size/1048576,Xs=`https://iframe.mediadelivery.net/play/${Ke}/${Ke}`;await h.mutateAsync({bunny_video_id:Ke,playback_url:Xs,file_size_mb:Kt,title:ue||"Quick Video Touch",notes:ae||void 0,contact_id:ne&&ne!=="none"?ne: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 Yt=await F5(Ke);if(ht=Yt.status,V(Yt.encodeProgress||0),ht===4)te({playbackUrl:Yt.directPlayUrl,thumbnailUrl:Yt.thumbnailUrl,previewUrl:Yt.previewUrl||null,duration:Yt.length||Je,fileSizeMb:(Yt.storageSize||Ye.size)/(1024*1024)});else if(ht===5||ht===6)throw new Error("Video processing failed")}g("details")}catch(Ke){console.error("Upload error:",Ke),n({title:"Upload failed",description:"Please try recording again.",variant:"destructive"}),g("record")}},[ue,n]),Ne=async()=>{if(!(!W||!X))try{const Ye=ne&&ne!=="none"?ne:null,Je=await h.mutateAsync({bunny_video_id:W,contact_id:Ye,playback_url:X.playbackUrl,thumbnail_url:X.thumbnailUrl,preview_url:X.previewUrl,duration_seconds:X.duration,file_size_mb:X.fileSizeMb,title:ue||"Quick Video Touch",notes:ae,task_id:a||null,status:"ready"});ve(Je.id),be(Je.share_token||null),Ye&&await m.mutateAsync({contactId:Ye,videoId:Je.id,notes:ae}),n({title:"Video saved successfully!"}),g("share")}catch(Ye){console.error("Save video error:",Ye),n({title:"Failed to save video",description:(Ye==null?void 0:Ye.message)||"Please try again.",variant:"destructive"})}},Ge=(Ye,Je)=>{navigator.clipboard.writeText(Je),Ie(Ye),setTimeout(()=>Ie(null),2e3),n({title:"Copied to clipboard!"})},Ce=()=>ge?`https://video.relevelup.com/${ge}`:(X==null?void 0:X.playbackUrl)||"",Fe=()=>{const Ye=u==null?void 0:u.find(Ze=>Ze.id===ne),Je=Ye?`${Ye.first_name}`:"",Ke=(Ye==null?void 0:Ye.phone)||"",st=(Ye==null?void 0:Ye.email)||"",rt=Ce();return{text:`Hey${Je?` ${Je}`:""}! I recorded a quick video for you: ${rt}`,link:rt,contactPhone:Ke,contactEmail:st}},Ae=()=>{const{text:Ye,contactPhone:Je}=Fe(),Ke=Je?`sms:${Je}?body=${encodeURIComponent(Ye)}`:`sms:?body=${encodeURIComponent(Ye)}`;window.open(Ke,"_self")},Xe=()=>{const{link:Ye,contactEmail:Je}=Fe(),Ke="Check out this video",st=`I recorded a quick video for you: ${Ye}`,rt=Je?`mailto:${Je}?subject=${encodeURIComponent(Ke)}&body=${encodeURIComponent(st)}`:`mailto:?subject=${encodeURIComponent(Ke)}&body=${encodeURIComponent(st)}`;window.open(rt,"_self")};return i?e.jsx(Qs,{title:"QuickVid",children:e.jsxs("div",{className:"max-w-4xl mx-auto space-y-6",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsx(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(Wr,{className:"h-4 w-4"}),"Video Library"]}),c&&e.jsxs("div",{className:"text-right",children:[e.jsxs("p",{className:"text-sm text-warning",children:["Storage: ",o.toFixed(0),"% used"]}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[l.toFixed(0)," MB remaining"]})]})]})]}),f==="record"&&e.jsxs("div",{className:"grid gap-6 lg:grid-cols-3",children:[e.jsxs("div",{className:"lg:col-span-2",children:[e.jsx(oO,{maxDurationSeconds:600,onRecordingComplete:Be,onRecordingStateChange:P,className:"w-full",teleprompterContent:_&&y&&e.jsx(qWe,{text:y,isVisible:_,onToggleVisibility:()=>b(!1),isRecording:T,startCountdown:!1})}),!_&&y&&e.jsxs(B,{variant:"outline",className:"mt-4",onClick:()=>b(!0),children:[e.jsx(Wr,{className:"h-4 w-4 mr-2"}),"Show Teleprompter"]})]}),e.jsxs(_e,{className:"lg:col-span-1",children:[e.jsx(zt,{className:"pb-2",children:e.jsx(qt,{className:"text-lg",children:"Teleprompter Script"})}),e.jsxs(De,{className:"space-y-4",children:[e.jsx(Ws,{placeholder:"Type or paste your script here...",value:y,onChange:Ye=>x(Ye.target.value),rows:6}),e.jsxs(l1,{open:k,onOpenChange:A,children:[e.jsx(PQ,{asChild:!0,children:e.jsxs(B,{variant:"outline",className:"w-full",children:[e.jsx(Wr,{className:"h-4 w-4 mr-2"}),"Browse Scripts"]})}),e.jsxs(Gy,{side:"right",className:"w-[400px] sm:w-[540px] p-0",children:[e.jsx(gb,{className:"p-4 border-b",children:e.jsx(xb,{children:"Select a Script"})}),e.jsx(l2n,{onSelectScript:Ye=>{x(Ye.text),A(!1),b(!0)},className:"h-[calc(100vh-80px)]"})]})]}),y&&e.jsx(B,{className:"w-full",onClick:()=>b(!0),children:"Use Script"})]})]})]}),f==="uploading"&&e.jsx(_e,{className:"max-w-md mx-auto",children:e.jsxs(De,{className:"pt-6 text-center",children:[e.jsx(ni,{className:"h-12 w-12 mx-auto mb-4 text-primary animate-pulse"}),e.jsx("h2",{className:"text-lg font-semibold mb-2",children:"Uploading Video..."}),e.jsx(ro,{value:L,className:"mb-2"}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:[L.toFixed(0),"%"]})]})}),f==="processing"&&e.jsx(_e,{className:"max-w-md mx-auto",children:e.jsxs(De,{className:"pt-6 text-center space-y-4",children:[e.jsx(us,{className:"h-12 w-12 mx-auto mb-4 text-primary animate-spin"}),e.jsx("h2",{className:"text-lg font-semibold mb-2",children:"Processing Video..."}),e.jsx(ro,{value:$,className:"mb-2"}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:[$.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.`})]})}),f==="details"&&e.jsxs(_e,{className:"max-w-lg mx-auto",children:[e.jsx(zt,{children:e.jsx(qt,{children:"Video Details"})}),e.jsxs(De,{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(re,{children:"Title"}),e.jsx(we,{value:ue,onChange:Ye=>ce(Ye.target.value),placeholder:"Quick Video Touch"})]}),e.jsxs("div",{children:[e.jsx(re,{children:"Attach to Contact (Optional)"}),e.jsxs(Ns,{value:ne,onValueChange:me,children:[e.jsx(ws,{children:e.jsx(ks,{placeholder:"No contact - use anywhere"})}),e.jsxs(js,{children:[e.jsx(nt,{value:"none",children:e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground",children:[e.jsx(gc,{className:"h-4 w-4"}),"No contact - use anywhere"]})}),u==null?void 0:u.map(Ye=>e.jsx(nt,{value:Ye.id,children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ro,{className:"h-4 w-4"}),Ye.first_name," ",Ye.last_name]})},Ye.id))]})]})]}),e.jsxs("div",{children:[e.jsx(re,{children:"Notes"}),e.jsx(Ws,{value:ae,onChange:Ye=>he(Ye.target.value),placeholder:"Add notes about this video...",rows:3})]}),e.jsxs(B,{className:"w-full",onClick:Ne,disabled:h.isPending,children:[h.isPending&&e.jsx(us,{className:"h-4 w-4 mr-2 animate-spin"}),"Save Video"]})]})]}),f==="share"&&e.jsxs(_e,{className:"max-w-lg mx-auto",children:[e.jsx(zt,{children:e.jsxs(qt,{className:"flex items-center gap-2",children:[e.jsx(pa,{className:"h-5 w-5 text-green-500"}),"Video Saved!"]})}),e.jsxs(De,{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:Ae,children:[e.jsx(xo,{className:"h-4 w-4 mr-2"}),"Text Contact Video"]}),e.jsxs(B,{variant:"outline",className:"justify-start",onClick:Xe,children:[e.jsx(mn,{className:"h-4 w-4 mr-2"}),"Email Contact Video"]}),e.jsxs(B,{variant:"outline",className:"justify-start",onClick:()=>Ge("link",Fe().link),children:[e.jsx(gc,{className:"h-4 w-4 mr-2"}),"Copy Video Link",Se==="link"&&e.jsx(pa,{className:"h-4 w-4 ml-auto text-green-500"})]}),e.jsxs(B,{variant:"outline",className:"justify-start",onClick:()=>Re(!0),children:[e.jsx(zc,{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:()=>{g("record"),M(null),G(null),te(null)},children:"Record Another"})]})]})]}),xe&&ge&&e.jsx(T7t,{open:Me,onOpenChange:Re,video:{id:xe,share_token:ge,title:ue||null,contact_id:ne||null,thumbnail_url:(X==null?void 0:X.thumbnailUrl)||null},contactName:(($e=u==null?void 0:u.find(Ye=>Ye.id===ne))==null?void 0:$e.first_name)||null})]})}):e.jsx(Qs,{title:"QuickVid",children:e.jsxs("div",{className:"max-w-2xl mx-auto text-center py-12",children:[e.jsx(xd,{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 u2n({open:s,onOpenChange:t,video:n,gmailEmail:r,signedThumbnailUrl:a,onSendComplete:i}){const[l,o]=N.useState([]),[c,d]=N.useState(null),[u,h]=N.useState(!1),[m,f]=N.useState(!1),[g,y]=N.useState(""),[x,_]=N.useState(""),[b,k]=N.useState(""),[A,T]=N.useState(!1),P=rIt(),I=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||"",L=n.title||"Video Message";N.useEffect(()=>{s&&l.length===0&&z()},[s]),N.useEffect(()=>{if(s&&(_(`I recorded a video for you — ${L}`),k("Hey! I recorded a quick video just for you. Click below to watch it:"),d(null),y(""),n.contact_id)){const te=l.find(ne=>ne.id===n.contact_id);te&&(d(te),y(te.email||""))}},[s,n.contact_id,l]);const z=async()=>{f(!0);try{const{data:te,error:ne}=await H.from("innercircle_contacts").select("id, first_name, last_name, email").order("first_name",{ascending:!0}).limit(500);if(ne)throw ne;o(te||[])}catch{console.error("Failed to fetch contacts")}finally{f(!1)}},$=te=>{d(te),h(!1),y(te.email||""),k(`Hey ${te.first_name}! I recorded a quick video just for you. Click below to watch it:`),_(`I recorded a video for you — ${L}`)},V=()=>{d(null),y(""),k("Hey! I recorded a quick video just for you. Click below to watch it:")},W=te=>`${te.first_name} ${te.last_name||""}`.trim(),G=te=>{const ne=b.split(/\n\n+/).map(ce=>`

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

`).join(""),me=te?iIt(te):I,ue=te?``:"";return`
${ne}

▶ Watch Video

${ue}
`},X=async()=>{var te;if(!g){ie.error("Please enter a recipient email");return}if(!I){ie.error("Video does not have a share link");return}T(!0);try{let ne;try{const he=c?W(c):g.split("@")[0];ne=(await P.mutateAsync({video_id:n.id,recipient_email:g,recipient_name:he,contact_id:(c==null?void 0:c.id)||null,sent_via:"gmail"})).share_token}catch(he){console.warn("Failed to create tracking record, sending without tracking:",he)}const me=G(ne),{data:ue,error:ce}=await H.functions.invoke("gmail-send",{body:{to:g,subject:x,body:me,contactId:(c==null?void 0:c.id)||null}});let ae=null;if(ce&&((te=ce.context)!=null&&te.json))try{ae=await ce.context.json()}catch{}if((ae==null?void 0:ae.error)==="insufficient_scope"||(ue==null?void 0:ue.error)==="insufficient_scope"){ie.error((ae==null?void 0:ae.message)||"Gmail is missing send permission. Please disconnect and reconnect Gmail, allowing 'Send email on your behalf'.",{duration:1e4});return}if(ce)throw new Error((ae==null?void 0:ae.message)||ce.message);if(!(ue!=null&&ue.success))throw new Error((ue==null?void 0:ue.error)||"Failed to send");ie.success("Video email sent!"),t(!1),i==null||i()}catch(ne){console.error("Gmail send error:",ne),ie.error("Failed to send: "+(ne instanceof Error?ne.message:"Unknown error"))}finally{T(!1)}};return e.jsx(Bs,{open:s,onOpenChange:t,children:e.jsxs(Fs,{className:"sm:max-w-[560px] max-h-[90vh] overflow-y-auto",children:[e.jsxs(qs,{children:[e.jsxs($s,{className:"flex items-center gap-2",children:[e.jsx(mn,{className:"h-5 w-5 text-red-500"}),"Send Video via Gmail"]}),r&&e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Sending from ",e.jsx("span",{className:"font-medium",children:r})]})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(re,{children:"Send to Contact"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(rc,{open:u,onOpenChange:h,children:[e.jsx(ac,{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",children:[e.jsx(Ro,{className:"h-4 w-4 text-muted-foreground"}),W(c),c.email&&e.jsxs("span",{className:"text-muted-foreground text-xs",children:["(",c.email,")"]})]}):e.jsx("span",{className:"text-muted-foreground",children:"Select a contact..."}),e.jsx(sb,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]})}),e.jsx(Zl,{className:"w-[350px] p-0",align:"start",children:e.jsxs(db,{children:[e.jsx(ub,{placeholder:"Search contacts..."}),e.jsxs(hb,{children:[e.jsx(mb,{children:m?"Loading...":"No contacts found."}),e.jsx(pb,{children:l.filter(te=>te.email).map(te=>e.jsxs(Ry,{value:`${te.first_name} ${te.last_name||""} ${te.email||""}`,onSelect:()=>$(te),children:[e.jsx(pa,{className:Ot("mr-2 h-4 w-4",(c==null?void 0:c.id)===te.id?"opacity-100":"opacity-0")}),e.jsxs("div",{children:[e.jsx("div",{className:"font-medium",children:W(te)}),e.jsx("div",{className:"text-xs text-muted-foreground",children:te.email})]})]},te.id))})]})]})})]}),c&&e.jsx(B,{variant:"ghost",size:"icon",onClick:V,className:"shrink-0",children:e.jsx(hr,{className:"h-4 w-4"})})]})]}),!c&&e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(re,{htmlFor:"video-to",children:"Or type email address"}),e.jsx(we,{id:"video-to",value:g,onChange:te=>y(te.target.value),placeholder:"recipient@example.com",type:"email"})]}),e.jsx(Wl,{}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(re,{htmlFor:"video-subject",children:"Subject"}),e.jsx(we,{id:"video-subject",value:x,onChange:te=>_(te.target.value)})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(re,{htmlFor:"video-message",children:"Personal Message"}),e.jsx(Ws,{id:"video-message",value:b,onChange:te=>k(te.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(re,{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:L,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(dd,{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(dd,{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:A,children:"Cancel"}),e.jsxs(B,{onClick:X,disabled:A||!g||!x,className:"gap-2",children:[A?e.jsx(us,{className:"h-4 w-4 animate-spin"}):e.jsx(Rr,{className:"h-4 w-4"}),A?"Sending...":"Send Video Email"]})]})]})]})})}const h2n=()=>{const{user:s}=Ls();return mt({queryKey:["team-videos",s==null?void 0:s.id],queryFn:async()=>{const{data:t,error:n}=await H.rpc("get_team_videos",{_user_id:s.id});if(n)throw n;return t||[]},enabled:!!s})};function m2n({recipient:s}){return s.watched_at?e.jsxs(We,{className:"bg-emerald-100 text-emerald-800 text-[10px]",children:[e.jsx(dd,{className:"h-2.5 w-2.5 mr-0.5"}),"Watched"]}):s.clicked_at?e.jsxs(We,{className:"bg-blue-100 text-blue-800 text-[10px]",children:[e.jsx(Qg,{className:"h-2.5 w-2.5 mr-0.5"}),"Clicked"]}):s.opened_at?e.jsxs(We,{className:"bg-amber-100 text-amber-800 text-[10px]",children:[e.jsx(da,{className:"h-2.5 w-2.5 mr-0.5"}),"Opened"]}):e.jsxs(We,{variant:"outline",className:"text-[10px]",children:[e.jsx(Rr,{className:"h-2.5 w-2.5 mr-0.5"}),"Sent"]})}function p2n({open:s,onOpenChange:t,videoId:n,videoTitle:r}){const{data:a=[],isLoading:i}=Imn(n);return e.jsx(Bs,{open:s,onOpenChange:t,children:e.jsxs(Fs,{className:"max-w-2xl max-h-[80vh]",children:[e.jsx(qs,{children:e.jsxs($s,{className:"flex items-center gap-2",children:[e.jsx(fl,{className:"h-5 w-5"}),"Send Analytics: ",r]})}),i?e.jsx("div",{className:"space-y-2",children:[...Array(3)].map((l,o)=>e.jsx(xn,{className:"h-12 w-full"},o))}):a.length===0?e.jsx("p",{className:"text-sm text-muted-foreground text-center py-8",children:"No recipients tracked for this video yet."}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"grid grid-cols-3 gap-3 mb-4",children:[e.jsxs("div",{className:"text-center p-2 rounded-lg bg-muted/50",children:[e.jsx("div",{className:"text-lg font-bold",children:a.length}),e.jsx("div",{className:"text-[10px] text-muted-foreground",children:"Sent"})]}),e.jsxs("div",{className:"text-center p-2 rounded-lg bg-amber-50",children:[e.jsx("div",{className:"text-lg font-bold text-amber-700",children:a.filter(l=>l.opened_at).length}),e.jsx("div",{className:"text-[10px] text-muted-foreground",children:"Opened"})]}),e.jsxs("div",{className:"text-center p-2 rounded-lg bg-blue-50",children:[e.jsx("div",{className:"text-lg font-bold text-blue-700",children:a.filter(l=>l.clicked_at).length}),e.jsx("div",{className:"text-[10px] text-muted-foreground",children:"Clicked"})]})]}),e.jsx(lo,{className:"h-[400px]",children:e.jsxs(Oa,{children:[e.jsx(Fa,{children:e.jsxs(un,{children:[e.jsx(Mt,{children:"Recipient"}),e.jsx(Mt,{children:"Status"}),e.jsx(Mt,{children:"Sent"}),e.jsx(Mt,{children:"Last Activity"})]})}),e.jsx(za,{children:a.map(l=>e.jsxs(un,{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(m2n,{recipient:l})}),e.jsx(gt,{className:"text-xs text-muted-foreground",children:Js(new Date(l.sent_at),"MMM d, h:mm a")}),e.jsx(gt,{className:"text-xs text-muted-foreground",children:l.last_activity_at?nc(new Date(l.last_activity_at),{addSuffix:!0}):"—"})]},l.id))})]})})]})]})})}function f2n(){const{data:s,isLoading:t}=Dmn(),{data:n=[],isLoading:r}=Rmn(),[a,i]=N.useState(null),l=t||r,o=n.reduce((c,d)=>{const u=d.agent_videos,h=(u==null?void 0:u.id)||d.video_id;return c[h]||(c[h]={videoId:h,title:(u==null?void 0:u.title)||"Untitled",thumbnailUrl:u==null?void 0:u.thumbnail_url,recipients:[]}),c[h].recipients.push(d),c},{});return l?e.jsx("div",{className:"space-y-4",children:e.jsx("div",{className:"grid gap-4 md:grid-cols-4",children:[...Array(4)].map((c,d)=>e.jsxs(_e,{children:[e.jsx(zt,{className:"pb-2",children:e.jsx(xn,{className:"h-4 w-20"})}),e.jsx(De,{children:e.jsx(xn,{className:"h-8 w-16"})})]},d))})}):e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"grid gap-3 grid-cols-3",children:[e.jsxs(_e,{children:[e.jsxs(zt,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(qt,{className:"text-sm font-medium",children:"Total Sent"}),e.jsx(Rr,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsx(De,{children:e.jsx("div",{className:"text-2xl font-bold",children:(s==null?void 0:s.totalSent)||0})})]}),e.jsxs(_e,{children:[e.jsxs(zt,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(qt,{className:"text-sm font-medium",children:"Open Rate"}),e.jsx(da,{className:"h-4 w-4 text-amber-500"})]}),e.jsxs(De,{children:[e.jsxs("div",{className:"text-2xl font-bold",children:[(s==null?void 0:s.openRate)||0,"%"]}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[(s==null?void 0:s.totalOpened)||0," opened"]})]})]}),e.jsxs(_e,{children:[e.jsxs(zt,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(qt,{className:"text-sm font-medium",children:"Click Rate"}),e.jsx(Qg,{className:"h-4 w-4 text-blue-500"})]}),e.jsxs(De,{children:[e.jsxs("div",{className:"text-2xl font-bold",children:[(s==null?void 0:s.clickRate)||0,"%"]}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[(s==null?void 0:s.totalClicked)||0," clicked"]})]})]})]}),e.jsxs(_e,{children:[e.jsxs(zt,{children:[e.jsx(qt,{className:"text-sm font-medium",children:"Send History by Video"}),e.jsx(_r,{children:"Click a video to see individual recipient tracking"})]}),e.jsx(De,{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(na,{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(Rr,{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(da,{className:"h-3 w-3"})," ",d]}),e.jsxs("span",{className:"text-xs text-blue-600 flex items-center gap-1",children:[e.jsx(Qg,{className:"h-3 w-3"})," ",u]})]})]}),e.jsx(ml,{className:"h-4 w-4 text-muted-foreground"})]},c.videoId)})})})]}),e.jsx(p2n,{open:!!a,onOpenChange:c=>!c&&i(null),videoId:(a==null?void 0:a.id)||null,videoTitle:(a==null?void 0:a.title)||""})]})}function g2n({previewSrc:s,thumbnailSrc:t,alt:n,isHovered:r}){const[a,i]=N.useState(!1),[l,o]=N.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(na,{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 x2n({video:s,previewSrc:t,thumbnailSrc:n,onOpen:r,onDelete:a,onRename:i,onNavigateToContact:l,onGetEmbedCode:o,onCopyEmailHtml:c,onEmbedToCrm:d,onShareWithTemplate:u,onSendViaGmail:h,isGmailConnected:m,getContactName:f,getShareUrl:g,copyToClipboard:y,formatDuration:x}){const[_,b]=N.useState(!1);return e.jsxs(_e,{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(g2n,{previewSrc:t,thumbnailSrc:n,alt:s.title||"Video preview",isHovered:_}),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(dd,{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:x(s.duration_seconds)}),s.status!=="ready"&&e.jsx(We,{variant:s.status==="processing"?"secondary":"destructive",className:"absolute top-2 left-2",children:s.status})]}),e.jsx(De,{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(Ro,{className:"h-3 w-3"}),e.jsx("span",{className:"truncate",children:f(s.contact_id)})]}),e.jsxs("div",{className:"flex items-center gap-4 text-xs text-muted-foreground mt-0.5",children:[e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(Xr,{className:"h-3 w-3"}),e.jsx("span",{children:Js(new Date(s.created_at),"MMM d, yyyy")})]}),(s.view_count??0)>0&&e.jsxs("div",{className:"flex items-center gap-1 text-primary",children:[e.jsx(da,{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:k=>{k.stopPropagation(),h==null||h()},children:[e.jsx(mn,{className:"h-3 w-3"}),"Send via Gmail"]}),e.jsx("h3",{className:"font-medium truncate",children:s.title||"Untitled Video"}),e.jsxs("div",{className:"flex items-center gap-2 text-xs text-muted-foreground mt-1",children:[e.jsx(Ro,{className:"h-3 w-3"}),e.jsx("span",{className:"truncate",children:f(s.contact_id)})]}),e.jsxs("div",{className:"flex items-center gap-4 text-xs text-muted-foreground mt-0.5",children:[e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(Xr,{className:"h-3 w-3"}),e.jsx("span",{children:Js(new Date(s.created_at),"MMM d, yyyy")})]}),(s.view_count??0)>0&&e.jsxs("div",{className:"flex items-center gap-1 text-primary",children:[e.jsx(da,{className:"h-3 w-3"}),e.jsxs("span",{children:[s.view_count," ",s.view_count===1?"view":"views"]})]})]})]}),e.jsxs(qd,{children:[e.jsx(Vd,{asChild:!0,children:e.jsx(B,{variant:"ghost",size:"icon",className:"h-8 w-8",onClick:k=>k.stopPropagation(),children:e.jsx(Ev,{className:"h-4 w-4"})})}),e.jsxs(Ld,{align:"end",className:"bg-popover",children:[e.jsxs(ba,{onClick:k=>{k.stopPropagation(),r()},children:[e.jsx(da,{className:"h-4 w-4 mr-2"}),"Watch"]}),e.jsx(s1,{}),e.jsxs(ba,{onClick:k=>{k.stopPropagation(),u()},children:[e.jsx(zc,{className:"h-4 w-4 mr-2"}),"Share with Template"]}),e.jsxs(ba,{onClick:k=>{k.stopPropagation(),y(g(s),"Share link")},children:[e.jsx(gc,{className:"h-4 w-4 mr-2"}),"Copy Share Link"]}),e.jsxs(ba,{onClick:k=>{k.stopPropagation(),o()},children:[e.jsx(cD,{className:"h-4 w-4 mr-2"}),"Get Embed Code"]}),e.jsxs(ba,{onClick:k=>{k.stopPropagation(),c()},children:[e.jsx(mn,{className:"h-4 w-4 mr-2"}),"Copy HTML for Email"]}),e.jsxs(ba,{onClick:k=>{k.stopPropagation(),d()},children:[e.jsx(Tr,{className:"h-4 w-4 mr-2"}),"Embed to CRM"]}),m&&s.share_token&&e.jsxs(ba,{onClick:k=>{k.stopPropagation(),h==null||h()},children:[e.jsx(Rr,{className:"h-4 w-4 mr-2"}),"Send via Gmail"]}),e.jsxs(ba,{onClick:k=>{k.stopPropagation(),i()},children:[e.jsx(Ja,{className:"h-4 w-4 mr-2"}),"Rename"]}),e.jsx(s1,{}),s.contact_id&&e.jsxs(ba,{onClick:k=>{k.stopPropagation(),l()},children:[e.jsx(Ro,{className:"h-4 w-4 mr-2"}),"View Contact"]}),e.jsxs(ba,{onClick:k=>{k.stopPropagation(),a()},className:"text-destructive",children:[e.jsx(qn,{className:"h-4 w-4 mr-2"}),"Delete"]})]})]})]})})]})}function y2n(){var Xs,zs;const s=tr(),{data:t,isLoading:n,refetch:r}=tpn(),{data:a}=VCe(),{data:i}=Wy(),l=rpn(),o=npn(),{isGmailConnected:c,gmailEmail:d}=_f(),{data:u}=Cj(),{data:h=[],isLoading:m}=h2n(),[f,g]=N.useState("my"),[y,x]=N.useState(""),[_,b]=N.useState(null),[k,A]=N.useState(!1),[T,P]=N.useState(!1),[I,M]=N.useState(!1),[L,z]=N.useState(!1),[$,V]=N.useState(!1),[W,G]=N.useState(""),[X,te]=N.useState(!1),[ne,me]=N.useState(!1),[ue,ce]=N.useState(!1),[ae,he]=N.useState(!1),[xe,ve]=N.useState(""),[ge,be]=N.useState({}),Se=Vt=>{if(!Vt)return"Unassigned";const At=i==null?void 0:i.find(Os=>Os.id===Vt);return At?`${At.first_name} ${At.last_name||""}`.trim():"Unknown"},Ie=Vt=>{if(!Vt)return"0:00";const At=Math.floor(Vt/60),Os=Vt%60;return`${At}:${Os.toString().padStart(2,"0")}`},[Me,Re]=N.useState("all"),Be=t==null?void 0:t.filter(Vt=>{const At=Vt.category||"general";if(Me==="general"&&At!=="general"||Me==="open_house"&&At!=="open_house")return!1;if(!y)return!0;const Os=Se(Vt.contact_id).toLowerCase(),Nt=(Vt.title||"").toLowerCase(),ms=(Vt.notes||"").toLowerCase();return Os.includes(y.toLowerCase())||Nt.includes(y.toLowerCase())||ms.includes(y.toLowerCase())}),Ne=(t==null?void 0:t.filter(Vt=>(Vt.category||"general")==="open_house").length)||0,Ge=(t==null?void 0:t.filter(Vt=>(Vt.category||"general")==="general").length)||0,Ce=(t||[]).filter(Vt=>Vt.status==="processing"&&Vt.bunny_video_id).map(Vt=>Vt.id).join(",");N.useEffect(()=>{(async()=>{if(!(t!=null&&t.length))return;const At=t.filter(Nt=>Nt.status==="processing"&&Nt.bunny_video_id);if(!At.length)return;let Os=!1;for(const Nt of At)try{const{data:ms,error:Ys}=await H.functions.invoke("bunny-upload",{body:{action:"status",videoId:Nt.bunny_video_id,isAgentVideo:!0}});if(Ys||!ms)continue;ms.status===4&&(await H.from("agent_videos").update({status:"ready",playback_url:ms.directPlayUrl,thumbnail_url:ms.thumbnailUrl,preview_url:ms.previewUrl,duration_seconds:ms.length||Nt.duration_seconds,updated_at:new Date().toISOString()}).eq("id",Nt.id),Os=!0)}catch(ms){console.warn("Reconcile check failed for video",Nt.id,ms)}Os&&r()})()},[Ce,r]),N.useEffect(()=>{(async()=>{if(!(t!=null&&t.length))return;const At=t.filter(It=>(It==null?void 0:It.bunny_video_id)&&!ge[It.id]);if(!At.length)return;const Os=At.map(It=>It.bunny_video_id),{data:Nt,error:ms}=await H.functions.invoke("bunny-upload",{body:{action:"bulk-asset-urls",videoIds:Os,isAgentVideo:!0}});if(ms)throw ms;const Ys=(Nt==null?void 0:Nt.assets)||{};be(It=>{const Ds={...It};for(const As of At)Ys[As.bunny_video_id]&&(Ds[As.id]={previewUrl:Ys[As.bunny_video_id].previewUrl,thumbnailUrl:Ys[As.bunny_video_id].thumbnailUrl});return Ds})})().catch(At=>console.warn("Failed to load signed Bunny asset URLs",At))},[t,ge]);const Fe=(a==null?void 0:a.total_storage_mb)||0,Ae=(a==null?void 0:a.max_storage_mb)||1024,Xe=Fe/Ae*100,$e=Xe>=80,Ye=Xe>=100,Je=async(Vt,At)=>{await navigator.clipboard.writeText(Vt),ie.success(`${At} copied to clipboard`)},Ke=Vt=>Vt.share_token?`https://video.relevelup.com/${Vt.share_token}`:Vt.playback_url||"",st=Vt=>{const At=Ke(Vt),Os=i==null?void 0:i.find(As=>As.id===Vt.contact_id),Nt=Se(Vt.contact_id),ms=Nt!=="Unassigned"?Nt.split(" ")[0]:"",Ys=(Os==null?void 0:Os.phone)||"",It=`Hey${ms?` ${ms}`:""}! I recorded a quick video message for you. Check it out: ${At}`,Ds=Ys?`sms:${Ys}?body=${encodeURIComponent(It)}`:`sms:?body=${encodeURIComponent(It)}`;window.open(Ds,"_self")},rt=Vt=>{const At=i==null?void 0:i.find(Ds=>Ds.id===Vt.contact_id),Os=(At==null?void 0:At.email)||"",Nt=Ke(Vt),ms="Check out this video",Ys=`I recorded a quick video for you: ${Nt}`,It=Os?`mailto:${Os}?subject=${encodeURIComponent(ms)}&body=${encodeURIComponent(Ys)}`:`mailto:?subject=${encodeURIComponent(ms)}&body=${encodeURIComponent(Ys)}`;window.open(It,"_self")},Ze=Vt=>{var ms;const At=Ke(Vt),Os=Vt.title||"Video Message",Nt=Vt.share_token?`https://video.relevelup.com/thumb/${Vt.share_token}`:((ms=ge[Vt.id])==null?void 0:ms.thumbnailUrl)||Vt.thumbnail_url||"";return``},ht=async Vt=>{if(!Vt.thumbnail_url&&!Vt.share_token){ie.error("Video thumbnail not available yet");return}const At=Ze(Vt),Os=Ke(Vt),Nt=`Watch: ${Vt.title||"Video Message"} ${Os}`;try{const ms=new Blob([At],{type:"text/html"}),Ys=new Blob([Nt],{type:"text/plain"}),It=new ClipboardItem({"text/html":ms,"text/plain":Ys});await navigator.clipboard.write([It]),ie.success("Copied! Paste into Gmail - the thumbnail will appear after sending.")}catch{await navigator.clipboard.writeText(Nt+` `+At),ie.success("Copied! Paste into your email.")}},Bt=async Vt=>{try{ie.loading("Preparing download...",{id:"download"});const{data:At,error:Os}=await H.functions.invoke("bunny-upload",{body:{action:"download-url",videoId:Vt.bunny_video_id,isAgentVideo:!0}});if(Os||!(At!=null&&At.downloadUrl))throw new Error((Os==null?void 0:Os.message)||"Failed to get download URL");const ms=`${((Vt.title||"video").toString().trim()||"video").replace(/[\\/:*?"<>|]+/g,"-")}.mp4`,Ys=await fetch(At.downloadUrl);if(!Ys.ok)throw new Error("Failed to fetch video file");const It=await Ys.blob(),Ds=URL.createObjectURL(It),As=document.createElement("a");As.href=Ds,As.download=ms,As.rel="noreferrer",document.body.appendChild(As),As.click(),As.remove(),URL.revokeObjectURL(Ds),ie.success("Download started",{id:"download"})}catch(At){console.error("Download error:",At),ie.error("Could not force download (your browser may block it).",{id:"download"})}},Ct=async Vt=>{b(Vt),te(!0),G(""),V(!0);try{const{data:At,error:Os}=await H.functions.invoke("bunny-upload",{body:{action:"crm-embed",videoId:Vt.bunny_video_id,title:Vt.title,isAgentVideo:!0,shareToken:Vt.share_token}});if(Os||!(At!=null&&At.html))throw new Error("Failed to generate CRM embed code");G(At.html)}catch(At){console.error("CRM embed error:",At),ie.error("Failed to generate CRM embed code"),V(!1)}finally{te(!1)}},Yt=Vt=>{b(Vt),A(!0)},Kt=async()=>{if(_)try{await l.mutateAsync({id:_.id,bunnyVideoId:_.bunny_video_id,hardDelete:!0}),P(!1),b(null),ie.success("Video deleted successfully")}catch{ie.error("Failed to delete video")}};return e.jsx(Qs,{title:"Video Library",description:"Manage your video touches",children:e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex flex-col sm:flex-row items-start sm:items-center justify-between gap-4",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl font-bold",children:"Video Library"}),e.jsx("p",{className:"text-muted-foreground",children:"Manage and share your video touches"})]}),e.jsxs("div",{className:"flex bg-muted rounded-lg p-1 gap-0.5 ml-2",children:[e.jsx("button",{onClick:()=>g("my"),className:`px-3 py-1.5 rounded-md text-sm font-medium transition-colors ${f==="my"?"bg-background text-foreground shadow-sm":"text-muted-foreground hover:text-foreground"}`,children:"My Videos"}),u&&((Xs=u.team)==null?void 0:Xs.shared_videos_enabled)&&e.jsxs("button",{onClick:()=>g("team"),className:`px-3 py-1.5 rounded-md text-sm font-medium transition-colors flex items-center gap-1.5 ${f==="team"?"bg-background text-foreground shadow-sm":"text-muted-foreground hover:text-foreground"}`,children:[e.jsx(Yn,{className:"h-3.5 w-3.5"}),"Team"]}),e.jsxs("button",{onClick:()=>g("analytics"),className:`px-3 py-1.5 rounded-md text-sm font-medium transition-colors flex items-center gap-1.5 ${f==="analytics"?"bg-background text-foreground shadow-sm":"text-muted-foreground hover:text-foreground"}`,children:[e.jsx(fl,{className:"h-3.5 w-3.5"}),"Analytics"]})]})]}),f==="my"&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(B,{variant:"outline",onClick:()=>M(!0),children:[e.jsx(ni,{className:"h-4 w-4 mr-2"}),"Upload Video"]}),e.jsxs(B,{onClick:()=>s("/mission-control/video/record"),children:[e.jsx(nn,{className:"h-4 w-4 mr-2"}),"Record New Video"]})]})]}),f==="team"?e.jsx(v2n,{videos:h,isLoading:m,searchTerm:y,setSearchTerm:x}):f==="analytics"?e.jsx(f2n,{}):e.jsxs(e.Fragment,{children:[e.jsx(_e,{className:$e?"border-amber-500":Ye?"border-destructive":"",children:e.jsxs(De,{className:"py-4",children:[e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsx(QG,{className:`h-5 w-5 ${Ye?"text-destructive":$e?"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 / ",Ae>=1024?`${(Ae/1024).toFixed(0)} GB`:`${Ae} MB`]})]}),e.jsx(ro,{value:Math.min(Xe,100),className:`h-2 ${Ye?"[&>div]:bg-destructive":$e?"[&>div]:bg-amber-500":""}`})]}),$e&&!Ye&&e.jsxs(We,{variant:"outline",className:"border-amber-500 text-amber-600",children:[e.jsx(Uo,{className:"h-3 w-3 mr-1"}),"Near Limit"]}),Ye&&e.jsxs(We,{variant:"destructive",children:[e.jsx(Uo,{className:"h-3 w-3 mr-1"}),"At Limit"]})]}),Ye&&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:Ge},{id:"open_house",label:"Open House Tours",count:Ne}].map(Vt=>e.jsxs("button",{onClick:()=>Re(Vt.id),className:`px-3 py-1.5 rounded-md text-sm font-medium transition-colors ${Me===Vt.id?"bg-background text-foreground shadow-sm":"text-muted-foreground hover:text-foreground"}`,children:[Vt.label," ",e.jsx("span",{className:"ml-1 text-xs text-muted-foreground",children:Vt.count})]},Vt.id))}),e.jsxs("div",{className:"relative",children:[e.jsx(Gr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(we,{placeholder:"Search videos by contact, title, or notes...",value:y,onChange:Vt=>x(Vt.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"})}):(Be==null?void 0:Be.length)===0?e.jsx(_e,{children:e.jsxs(De,{className:"py-12 text-center",children:[e.jsx(na,{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(nn,{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:Be==null?void 0:Be.map(Vt=>{var At,Os;return e.jsx(x2n,{video:Vt,previewSrc:(At=ge[Vt.id])==null?void 0:At.previewUrl,thumbnailSrc:(Os=ge[Vt.id])==null?void 0:Os.thumbnailUrl,onOpen:()=>Yt(Vt),onDelete:()=>{b(Vt),P(!0)},onRename:()=>{b(Vt),ve(Vt.title||""),he(!0)},onNavigateToContact:()=>s(`/mission-control/contacts/${Vt.contact_id}`),onGetEmbedCode:()=>{b(Vt),z(!0)},onCopyEmailHtml:()=>ht(Vt),onEmbedToCrm:()=>Ct(Vt),onShareWithTemplate:()=>{b(Vt),me(!0)},onSendViaGmail:()=>{b(Vt),ce(!0)},isGmailConnected:c,getContactName:Se,getShareUrl:Ke,copyToClipboard:Je,formatDuration:Ie},Vt.id)})}),e.jsx(Bs,{open:k,onOpenChange:A,children:e.jsxs(Fs,{className:"max-w-2xl",children:[e.jsxs(qs,{children:[e.jsx($s,{children:(_==null?void 0:_.title)||"Video Preview"}),e.jsx(Ar,{children:(_==null?void 0:_.contact_id)&&e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Ro,{className:"h-3 w-3"}),Se(_.contact_id)]})})]}),_&&e.jsxs("div",{className:"space-y-4",children:[_.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(us,{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:()=>{A(!1),r()},children:[e.jsx(oo,{className:"h-4 w-4 mr-2"}),"Refresh Library"]})]}):e.jsx("div",{className:"relative w-full",style:{paddingBottom:"56.25%"},children:_.playback_url?(()=>{let Vt=_.playback_url;return Vt.includes("iframe.mediadelivery.net/play/")&&(Vt=Vt.replace("/play/","/embed/"),Vt+=(Vt.includes("?")?"&":"?")+"autoplay=false&responsive=true"),Vt.includes("iframe.mediadelivery.net")?e.jsx("iframe",{src:Vt,title:_.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:_.playback_url,controls:!0,playsInline:!0,preload:"metadata",poster:_.thumbnail_url||void 0,className:"absolute top-0 left-0 w-full h-full rounded-lg object-cover",onError:()=>ie.error("Video preview failed to load")},_.playback_url)})():e.jsxs("div",{className:"absolute inset-0 flex items-center justify-center bg-muted rounded-lg",children:[e.jsx(na,{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:()=>st(_),children:[e.jsx(xo,{className:"h-4 w-4 mr-2"}),"Text Contact Video"]}),!c&&e.jsxs(B,{variant:"outline",onClick:()=>rt(_),children:[e.jsx(mn,{className:"h-4 w-4 mr-2"}),"Email Contact Video"]}),e.jsxs(B,{variant:"outline",onClick:()=>Je(Ke(_),"Share link"),children:[e.jsx(Pa,{className:"h-4 w-4 mr-2"}),"Copy Share Link"]}),e.jsxs(B,{variant:"outline",onClick:()=>ht(_),children:[e.jsx(mn,{className:"h-4 w-4 mr-2"}),"Copy HTML for Email"]}),e.jsxs(B,{variant:"outline",onClick:()=>Bt(_),children:[e.jsx(oi,{className:"h-4 w-4 mr-2"}),"Download Video"]}),e.jsxs(B,{variant:"outline",onClick:()=>{A(!1),Ct(_)},children:[e.jsx(Tr,{className:"h-4 w-4 mr-2"}),"Embed to CRM"]}),e.jsxs(B,{variant:"outline",onClick:()=>{A(!1),me(!0)},children:[e.jsx(zc,{className:"h-4 w-4 mr-2"}),"Send with Page Template"]}),c&&(_==null?void 0:_.share_token)&&e.jsxs(B,{variant:"outline",onClick:()=>{A(!1),ce(!0)},children:[e.jsx(Rr,{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:()=>{A(!1),P(!0)},children:[e.jsx(qn,{className:"h-4 w-4 mr-2"}),"Delete Video"]})})]})]})}),e.jsx(Bs,{open:T,onOpenChange:P,children:e.jsxs(Fs,{children:[e.jsxs(qs,{children:[e.jsx($s,{children:"Delete Video"}),e.jsx(Ar,{children:"Are you sure you want to delete this video? This action cannot be undone."})]}),e.jsxs(Cr,{children:[e.jsx(B,{variant:"outline",onClick:()=>P(!1),children:"Cancel"}),e.jsx(B,{variant:"destructive",onClick:Kt,disabled:l.isPending,children:l.isPending?"Deleting...":"Delete"})]})]})}),e.jsx(uIt,{open:I,onOpenChange:M}),e.jsx(Bs,{open:L,onOpenChange:z,children:e.jsxs(Fs,{className:"sm:max-w-lg",children:[e.jsxs(qs,{children:[e.jsx($s,{children:"Embed Video"}),e.jsx(Ar,{children:"Copy this code to embed the video on your website."})]}),_&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{children:"Embed Code"}),e.jsx(Ws,{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 Vt=``;Je(Vt,"Embed code")},children:[e.jsx(Pa,{className:"h-4 w-4 mr-2"}),"Copy Embed Code"]})}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Paste this code into your website's HTML where you want the video to appear. The video will automatically resize to fit its container."})]})]})}),_&&e.jsx(T7t,{open:ne,onOpenChange:me,video:_,contactName:Se(_.contact_id)}),_&&e.jsx(u2n,{open:ue,onOpenChange:ce,video:_,gmailEmail:d,signedThumbnailUrl:(zs=ge[_.id])==null?void 0:zs.thumbnailUrl}),e.jsx(Bs,{open:ae,onOpenChange:he,children:e.jsxs(Fs,{className:"max-w-sm",children:[e.jsxs(qs,{children:[e.jsx($s,{children:"Rename Video"}),e.jsx(Ar,{children:"Enter a new title for this video."})]}),e.jsx(we,{value:xe,onChange:Vt=>ve(Vt.target.value),placeholder:"Video title",autoFocus:!0,onKeyDown:Vt=>{Vt.key==="Enter"&&xe.trim()&&o.mutate({id:_.id,title:xe.trim()},{onSuccess:()=>{ie.success("Video renamed"),he(!1)}})}}),e.jsxs(Cr,{children:[e.jsx(B,{variant:"outline",onClick:()=>he(!1),children:"Cancel"}),e.jsx(B,{disabled:!xe.trim()||o.isPending,onClick:()=>{o.mutate({id:_.id,title:xe.trim()},{onSuccess:()=>{ie.success("Video renamed"),he(!1)}})},children:o.isPending?"Saving...":"Save"})]})]})}),e.jsx(Bs,{open:$,onOpenChange:V,children:e.jsxs(Fs,{className:"sm:max-w-lg",children:[e.jsxs(qs,{children:[e.jsxs($s,{className:"flex items-center gap-2",children:[e.jsx(Tr,{className:"h-5 w-5"}),"Embed to CRM"]}),e.jsx(Ar,{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."})]}),X?e.jsx("div",{className:"flex items-center justify-center py-8",children:e.jsx(us,{className:"h-8 w-8 animate-spin text-muted-foreground"})}):W?e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{children:"CRM Email HTML"}),e.jsx(Ws,{readOnly:!0,rows:12,value:W,className:"font-mono text-xs"})]}),e.jsxs(B,{className:"w-full",onClick:()=>{Je(W,"CRM embed code")},children:[e.jsx(Pa,{className:"h-4 w-4 mr-2"}),"Copy CRM Embed Code"]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Paste this into your CRM's email HTML editor. The recipient will see the video thumbnail and can click to watch. Works with Follow Up Boss, KvCORE, BoomTown, Sierra, and more."})]}):null]})})]})]})})}function v2n({videos:s,isLoading:t,searchTerm:n,setSearchTerm:r}){const a=N.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=N.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(Gr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(we,{placeholder:"Search team videos by title, owner, or recipient...",value:n,onChange:o=>r(o.target.value),className:"pl-10"})]}),t?e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsx("div",{className:"animate-spin h-8 w-8 border-4 border-primary border-t-transparent rounded-full"})}):a.length===0?e.jsx(_e,{children:e.jsxs(De,{className:"py-12 text-center",children:[e.jsx(Yn,{className:"h-12 w-12 mx-auto text-muted-foreground mb-4"}),e.jsx("h3",{className:"font-semibold mb-2",children:"No team videos"}),e.jsx("p",{className:"text-muted-foreground",children:s.length===0?"Your teammates haven't recorded any videos yet.":"No videos match your search."})]})}):e.jsx("div",{className:"space-y-6",children:i.map(([o,c])=>e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(Ua,{className:"h-7 w-7",children:[e.jsx(Gi,{src:c.avatar||""}),e.jsx(qa,{children:(c.name||"?").charAt(0).toUpperCase()})]}),e.jsx("h3",{className:"font-semibold text-sm",children:c.name}),e.jsx(We,{variant:"secondary",className:"text-xs",children:c.videos.length})]}),e.jsx("div",{className:"grid gap-4 sm:grid-cols-2 lg:grid-cols-3",children:c.videos.map(d=>e.jsxs(_e,{className:"overflow-hidden",children:[e.jsxs("div",{className:"relative aspect-video bg-muted flex items-center justify-center",children:[d.thumbnail_url?e.jsx("img",{src:d.thumbnail_url,alt:d.title||"Video",className:"w-full h-full object-cover",referrerPolicy:"no-referrer",onError:u=>{u.target.style.display="none"}}):e.jsx(na,{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(De,{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(Ro,{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(da,{className:"h-3 w-3"}),d.view_count]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Xr,{className:"h-3 w-3"}),Js(new Date(d.created_at),"MMM d")]})]})]})]},d.id))})]},o))})]})}const b2n=()=>{const{user:s}=Ls();return mt({queryKey:["team-deals",s==null?void 0:s.id],queryFn:async()=>{const{data:t,error:n}=await H.rpc("get_team_deals",{_user_id:s.id});if(n)throw n;return t||[]},enabled:!!s})},Mft=["#8B5CF6","#EC4899","#F59E0B","#10B981","#3B82F6","#EF4444","#06B6D4","#F97316"];function _2n({open:s,onOpenChange:t}){const{data:n,isLoading:r}=b2n(),[a,i]=N.useState(""),[l,o]=N.useState("all"),c=N.useMemo(()=>{if(!n)return new Map;const g=new Map;let y=0;return n.forEach(x=>{g.has(x.owner_user_id)||(g.set(x.owner_user_id,{name:x.owner_name||"Unknown",avatar:x.owner_avatar_url,color:Mft[y%Mft.length]}),y++)}),g},[n]),d=N.useMemo(()=>Array.from(c.entries()).map(([g,y])=>({id:g,...y})),[c]),u=N.useMemo(()=>{if(!n)return[];let g=n;if(l!=="all"&&(g=g.filter(y=>y.owner_user_id===l)),a.trim()){const y=a.toLowerCase();g=g.filter(x=>{var _,b,k,A;return x.deal_name.toLowerCase().includes(y)||((_=x.contact_name)==null?void 0:_.toLowerCase().includes(y))||((b=x.property_address)==null?void 0:b.toLowerCase().includes(y))||((k=x.city)==null?void 0:k.toLowerCase().includes(y))||((A=x.owner_name)==null?void 0:A.toLowerCase().includes(y))})}return g},[n,a,l]),h=N.useMemo(()=>{const g=new Map;return u.forEach(y=>{const x=y.stage_name||"Unknown";g.has(x)||g.set(x,{name:x,color:y.stage_color,icon:y.stage_icon,deals:[],totalValue:0});const _=g.get(x);_.deals.push(y),_.totalValue+=y.sale_price||0}),Array.from(g.values())},[u]),m=g=>g>=1e6?`$${(g/1e6).toFixed(1)}M`:g>=1e3?`$${(g/1e3).toFixed(0)}K`:`$${g.toFixed(0)}`,f=g=>g?new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:0}).format(g):null;return e.jsx(Bs,{open:s,onOpenChange:t,children:e.jsxs(Fs,{className:"max-w-[95vw] w-full max-h-[90vh] flex flex-col",children:[e.jsx(qs,{children:e.jsxs($s,{className:"flex items-center gap-2",children:[e.jsx(Yn,{className:"h-5 w-5"}),"Team Pipeline"]})}),e.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[e.jsxs("div",{className:"relative flex-1 max-w-xs",children:[e.jsx(Gr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(we,{placeholder:"Search deals...",value:a,onChange:g=>i(g.target.value),className:"pl-9"})]}),e.jsxs(Ns,{value:l,onValueChange:o,children:[e.jsx(ws,{className:"w-[180px]",children:e.jsx(ks,{placeholder:"All Members"})}),e.jsxs(js,{children:[e.jsx(nt,{value:"all",children:"All Members"}),d.map(g=>e.jsx(nt,{value:g.id,children:e.jsxs("span",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"h-2 w-2 rounded-full inline-block",style:{backgroundColor:g.color}}),g.name]})},g.id))]})]}),e.jsxs("div",{className:"hidden md:flex items-center gap-3 ml-auto text-xs text-muted-foreground",children:[d.slice(0,6).map(g=>e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx("span",{className:"h-2 w-2 rounded-full",style:{backgroundColor:g.color}}),g.name.split(" ")[0]]},g.id)),d.length>6&&e.jsxs("span",{children:["+",d.length-6," more"]})]})]}),e.jsx("div",{className:"flex-1 overflow-hidden mt-2",children:r?e.jsx("div",{className:"flex gap-4 h-full",children:[1,2,3,4].map(g=>e.jsxs("div",{className:"min-w-[260px] flex-1",children:[e.jsx(xn,{className:"h-12 w-full mb-2 rounded-lg"}),e.jsx(xn,{className:"h-24 w-full mb-2 rounded-lg"}),e.jsx(xn,{className:"h-24 w-full rounded-lg"})]},g))}):h.length===0?e.jsx("div",{className:"flex items-center justify-center h-full text-muted-foreground",children:e.jsxs("div",{className:"text-center",children:[e.jsx(Yn,{className:"h-10 w-10 mx-auto mb-3 opacity-50"}),e.jsx("p",{className:"font-medium",children:"No team deals found"}),e.jsx("p",{className:"text-sm",children:"Team members' deals will appear here."})]})}):e.jsx("div",{className:"flex gap-3 h-full overflow-x-auto pb-2",children:h.map(g=>{const y=g.icon&&zSe[g.icon]||bg;return e.jsxs("div",{className:"flex flex-col h-full min-w-[260px] max-w-[300px] flex-1 bg-muted/30 rounded-xl border border-border/50",children:[e.jsxs("div",{className:"p-3 border-b border-border/50 shrink-0",style:{borderTopColor:g.color||"hsl(var(--border))",borderTopWidth:3},children:[e.jsxs("div",{className:"flex items-center justify-between mb-1",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"w-6 h-6 rounded-md flex items-center justify-center",style:{backgroundColor:g.color?`${g.color}20`:void 0},children:e.jsx(y,{className:"h-3.5 w-3.5",style:{color:g.color||void 0}})}),e.jsx("h3",{className:"font-semibold text-sm",children:g.name})]}),e.jsx(We,{variant:"secondary",className:"text-xs px-2",children:g.deals.length})]}),g.totalValue>0&&e.jsx("p",{className:"text-xs text-muted-foreground ml-8",children:m(g.totalValue)})]}),e.jsx(lo,{className:"flex-1 p-2",children:e.jsx("div",{className:"space-y-2",children:g.deals.map(x=>{const _=c.get(x.owner_user_id);return e.jsx(w2n,{deal:x,ownerColor:(_==null?void 0:_.color)||"#888",ownerName:(_==null?void 0:_.name)||"Unknown",ownerAvatar:(_==null?void 0:_.avatar)||null,formatPrice:f},x.id)})})})]},g.name)})})}),e.jsxs("p",{className:"text-xs text-muted-foreground text-center pt-2 border-t shrink-0",children:[u.length," deal",u.length!==1?"s":""," across ",h.length," stage",h.length!==1?"s":""," from ",d.length," member",d.length!==1?"s":""]})]})})}function w2n({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(Ua,{className:"h-4 w-4",children:[e.jsx(Gi,{src:r||""}),e.jsx(qa,{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(We,{variant:"outline",className:Ot("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(_a,{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(Ed,{className:"h-3 w-3 text-emerald-500 shrink-0"}),e.jsx("span",{className:"font-semibold text-foreground",children:a(s.sale_price)})]})]})}function j2n({members:s,enabledMembers:t,onToggleMember:n,isOpen:r,onToggleOpen:a}){const i=t.size;return e.jsxs("div",{className:Ot("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(Yn,{className:"h-4 w-4 shrink-0 text-primary"}),r&&e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"text-xs font-semibold flex-1 text-left",children:"Team"}),i>0&&e.jsx("span",{className:"text-[10px] bg-primary text-primary-foreground rounded-full px-1.5 py-0.5",children:i}),e.jsx(Fc,{className:"h-3 w-3 text-muted-foreground"})]}),!r&&i>0&&e.jsx("span",{className:"absolute -top-1 -right-1 text-[9px] bg-primary text-primary-foreground rounded-full w-4 h-4 flex items-center justify-center",children:i})]})}),r?e.jsxs(lo,{className:"flex-1 p-2",children:[e.jsx("div",{className:"space-y-1",children:s.map(l=>{const o=t.has(l.id);return e.jsxs("button",{onClick:()=>n(l.id),className:Ot("w-full flex items-center gap-2 px-2 py-2 rounded-lg text-left transition-colors",o?"bg-primary/10 hover:bg-primary/15":"hover:bg-muted/50"),children:[e.jsxs("div",{className:"relative",children:[e.jsxs(Ua,{className:"h-7 w-7",children:[e.jsx(Gi,{src:l.avatar_url||""}),e.jsx(qa,{className:"text-[10px] font-semibold text-white",style:{backgroundColor:l.color},children:l.name.charAt(0).toUpperCase()})]}),o&&e.jsx("div",{className:"absolute -bottom-0.5 -right-0.5 w-3 h-3 rounded-full border-2 border-background",style:{backgroundColor:l.color}})]}),e.jsx("span",{className:Ot("text-xs truncate flex-1",o?"font-medium text-foreground":"text-muted-foreground"),children:l.name}),e.jsx(zn,{checked:o,onCheckedChange:()=>n(l.id),className:"scale-75",onClick:c=>c.stopPropagation()})]},l.id)})}),s.length===0&&e.jsx("p",{className:"text-xs text-muted-foreground text-center py-4",children:"No team members"})]}):e.jsxs("div",{className:"flex-1 flex flex-col items-center pt-2 gap-2",children:[s.slice(0,5).map(l=>{const o=t.has(l.id);return e.jsx("button",{onClick:()=>n(l.id),className:"relative",title:l.name,children:e.jsxs(Ua,{className:Ot("h-7 w-7 transition-all",o?"ring-2 ring-offset-1 ring-offset-background":"opacity-50"),style:o?{"--tw-ring-color":l.color}:{},children:[e.jsx(Gi,{src:l.avatar_url||""}),e.jsx(qa,{className:"text-[10px] font-semibold text-white",style:{backgroundColor:l.color},children:l.name.charAt(0).toUpperCase()})]})},l.id)}),s.length>5&&e.jsxs("span",{className:"text-[10px] text-muted-foreground",children:["+",s.length-5]})]})]})}const Lft=["#8B5CF6","#EC4899","#F59E0B","#10B981","#3B82F6","#EF4444","#06B6D4","#F97316"];function N2n(){const s=Ya(),{data:t}=Cj(),n=(t==null?void 0:t.role)==="team_leader",r=t==null?void 0:t.teamId,a=mt({queryKey:["team-pipeline-members",r,s],queryFn:async()=>{const{data:i,error:l}=await H.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 H.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:Lft[h%Lft.length]}))},enabled:!!r&&!!s&&n,staleTime:5*60*1e3});return{isTeamLeader:n,teamMembers:a.data||[],isLoadingMembers:a.isLoading}}function k2n(s){return mt({queryKey:["team-member-deals",s],queryFn:async()=>{if(s.length===0)return[];const{data:t,error:n}=await H.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 S2n(){const s=Ya();return mt({queryKey:["all-deal-tags-map",s],queryFn:async()=>{if(!s)return{tags:[],byDeal:{},unique:[]};const{data:t,error:n}=await H.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 E7t({stages:s,currentStageId:t,onStageSelect:n,disabled:r}){const[a,i]=N.useState(!1),l=s.find(c=>c.id===t),o=c=>{c.id!==t&&n(c.id,c.name),i(!1)};return e.jsxs(qd,{open:a,onOpenChange:i,children:[e.jsx(Vd,{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(Qa,{className:"h-3 w-3 shrink-0"})]})}),e.jsx(Ld,{align:"end",className:"w-48 z-50 bg-popover",onClick:c=>c.stopPropagation(),children:s.map(c=>{const d=c.icon&&zSe[c.icon]||bg,u=c.id===t;return e.jsxs(ba,{onClick:()=>o(c),className:Ot("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(pa,{className:"h-4 w-4 text-primary"})]},c.id)})})]})}const C2n={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"}},A2n={low:{color:"bg-slate-100 text-slate-600",dot:"bg-slate-400"},medium:{color:"bg-amber-100 text-amber-700",dot:"bg-amber-500"},high:{color:"bg-orange-100 text-orange-700",dot:"bg-orange-500"},urgent:{color:"bg-red-100 text-red-700",dot:"bg-red-500"}};function M7t({deal:s,onClick:t,isDragging:n,stages:r,onStageChange:a,showStagePicker:i=!1,isWonStage:l=!1,ownerInfo:o=null}){var b,k;const c=qU(),d=C2n[s.deal_type],u=A2n[s.priority],h=N.useMemo(()=>s.target_close_date?wj(Tc(s.target_close_date),new Date):null,[s.target_close_date]),m=h!==null&&h<0,f=h!==null&&h<=7&&h>=0,g=N.useMemo(()=>{var P;if(s.deal_type!=="seller"&&s.deal_type!=="dual")return null;const A=((P=s.listing)==null?void 0:P.created_at)||s.listing_date;if(!A)return null;const T=s.contract_date?Tc(s.contract_date):new Date;return wj(T,Tc(A))},[s]),y=l&&!s.scorecard_transaction_id,x=!!s.scorecard_transaction_id,_=A=>A?new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:0}).format(A):null;return e.jsx(_e,{className:Ot("cursor-pointer transition-all duration-200 hover:shadow-md hover:border-primary/30 group overflow-hidden",n&&"opacity-50 rotate-2 shadow-xl",m&&"border-red-200 bg-red-50/30",y&&"border-amber-300 bg-amber-50/30 dark:bg-amber-950/20"),onClick:t,style:o?{borderLeftWidth:4,borderLeftColor:o.color}:void 0,children:e.jsxs(De,{className:"p-3 space-y-2.5",children:[o&&e.jsxs("div",{className:"flex items-center gap-1.5 -mt-0.5 mb-1",children:[e.jsxs(Ua,{className:"h-4 w-4",children:[e.jsx(Gi,{src:o.avatar_url||""}),e.jsx(qa,{className:"text-[8px] font-semibold text-white",style:{backgroundColor:o.color},children:o.name.charAt(0).toUpperCase()})]}),e.jsx("span",{className:"text-[10px] font-medium",style:{color:o.color},children:o.name})]}),e.jsxs("div",{className:"flex items-start justify-between gap-2",children:[e.jsx("div",{className:"flex-1 min-w-0",children:e.jsx("h4",{className:"font-medium text-sm leading-tight line-clamp-2 group-hover:text-primary transition-colors",children:s.deal_name})}),e.jsx(We,{variant:"outline",className:Ot("text-[10px] px-1.5 py-0 shrink-0",d.color),children:d.label})]}),s.contact&&e.jsxs("div",{className:"flex items-center gap-2 text-xs text-muted-foreground",children:[e.jsx(Ua,{className:"h-5 w-5",children:e.jsxs(qa,{className:"text-[10px] bg-primary/10 text-primary",children:[(b=s.contact.first_name)==null?void 0:b[0],(k=s.contact.last_name)==null?void 0:k[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(cd,{className:"h-3 w-3 text-primary shrink-0"}),e.jsx("span",{className:"text-primary truncate",children:"Linked to Listing Exchange"})]}),y&&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(gl,{className:"h-3 w-3 shrink-0"}),e.jsx("span",{className:"truncate font-medium",children:"Add to Scorecard"})]}),x&&l&&e.jsxs("div",{className:"flex items-center gap-1.5 text-xs text-green-600 dark:text-green-400",children:[e.jsx(Hr,{className:"h-3 w-3 shrink-0"}),e.jsx("span",{className:"truncate",children:"Synced to Scorecard"})]}),g!==null&&e.jsxs("div",{className:"flex items-center gap-1.5 text-xs",children:[e.jsx(df,{className:"h-3 w-3 text-muted-foreground shrink-0"}),e.jsxs("span",{className:Ot("font-medium",g>90?"text-red-600":g>60?"text-amber-600":"text-muted-foreground"),children:[g," 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(_a,{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(Ed,{className:"h-3 w-3 text-emerald-500 shrink-0"}),e.jsx("span",{className:"font-semibold text-foreground",children:_(s.expected_price)}),s.expected_commission&&e.jsxs("span",{className:"text-muted-foreground",children:["• ",_(s.expected_commission)," GCI"]}),(()=>{const A=Jw(s);return A!==null&&A!==s.expected_commission?e.jsxs("span",{className:"text-teal-600 dark:text-teal-400",children:["• ",_(A)," Net"]}):null})()]}),e.jsxs("div",{className:"flex items-center justify-between pt-1 border-t border-border/50",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("div",{className:Ot("flex items-center gap-1 px-1.5 py-0.5 rounded text-[10px]",u.color),children:[e.jsx("div",{className:Ot("w-1.5 h-1.5 rounded-full",u.dot)}),e.jsx("span",{className:"capitalize",children:s.priority})]}),e.jsxs("span",{className:"text-[10px] text-muted-foreground",children:[s.probability,"%"]})]}),i&&c&&r&&a?e.jsx(E7t,{stages:r,currentStageId:s.stage_id||"",onStageSelect:(A,T)=>a(s.id,A,T)}):s.target_close_date?e.jsxs("div",{className:Ot("flex items-center gap-1 text-[10px]",m&&"text-red-600",f&&!m&&"text-amber-600",!m&&!f&&"text-muted-foreground"),children:[m?e.jsx(Uo,{className:"h-3 w-3"}):e.jsx(ta,{className:"h-3 w-3"}),e.jsx("span",{children:m?`${Math.abs(h)}d overdue`:f?`${h}d left`:Js(Tc(s.target_close_date),"MMM d")})]}):null]})]})})}function T2n({stage:s,deals:t,onDealClick:n,onAddDeal:r,onDragStart:a,onDragOver:i,onDrop:l,isDragOver:o,isWonStage:c=!1,getOwnerInfo:d}){const u=N.useRef(null),h=t.reduce((x,_)=>x+(_.expected_price||0),0),m=t.reduce((x,_)=>x+(_.expected_commission||0),0),f=t.reduce((x,_)=>x+(Jw(_)||0),0),g=x=>x>=1e6?`$${(x/1e6).toFixed(1)}M`:x>=1e3?`$${(x/1e3).toFixed(0)}K`:`$${x.toFixed(0)}`,y=s.icon&&zSe[s.icon]||bg;return e.jsxs("div",{ref:u,className:Ot("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:x=>i(x,s.id),onDrop:x=>l(x,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(y,{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.jsx(We,{variant:"secondary",className:"text-xs font-medium px-2",children:t.length})]}),h>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:g(h)}),e.jsx("span",{children:"•"}),e.jsxs("span",{children:[g(m)," GCI"]}),f>0&&f!==m&&e.jsxs(e.Fragment,{children:[e.jsx("span",{children:"•"}),e.jsxs("span",{className:"text-teal-600 dark:text-teal-400",children:[g(f)," Net"]})]})]})]}),e.jsx(lo,{className:"flex-1 p-2",children:e.jsxs("div",{className:"space-y-2",children:[t.map(x=>e.jsx("div",{draggable:!0,onDragStart:_=>{_.dataTransfer.effectAllowed="move",a(x.id,s.id)},children:e.jsx(M7t,{deal:x,onClick:()=>n(x),isWonStage:c,ownerInfo:(d==null?void 0:d(x))||null})},x.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(nn,{className:"h-4 w-4 mr-2"}),"Add Deal"]})})]})}function E2n({stats:s,isLoading:t}){const n=a=>a>=1e6?`$${(a/1e6).toFixed(1)}M`:a>=1e3?`$${(a/1e3).toFixed(0)}K`:`$${a.toLocaleString()}`,r=[{label:"Active Deals",value:(s==null?void 0:s.activeDeals)||0,icon:iu,color:"text-blue-500",bgColor:"bg-blue-500/10"},{label:"Weighted GCI",value:n((s==null?void 0:s.weightedGCI)||0),icon:xW,color:"text-indigo-500",bgColor:"bg-indigo-500/10",tooltip:"GCI adjusted by each deal's win probability"},{label:"Weighted Net",value:n((s==null?void 0:s.weightedNet)||0),icon:I9,color:"text-teal-500",bgColor:"bg-teal-500/10",tooltip:"Net to Agent adjusted by each deal's win probability"},{label:"YTD Closed Net",value:n((s==null?void 0:s.ytdWonNet)||0),icon:kT,color:"text-green-500",bgColor:"bg-green-500/10",subtitle:`${(s==null?void 0:s.ytdWonDeals)||0} deals`,tooltip:"Net commission from deals closed this year"},{label:"Projected Annual",value:n((s==null?void 0:s.projectedAnnualNet)||0),icon:ml,color:"text-amber-500",bgColor:"bg-amber-500/10",tooltip:"YTD Closed Net + Weighted Active Net"}];return t?e.jsx("div",{className:"grid grid-cols-2 md:grid-cols-5 gap-3",children:[1,2,3,4,5].map(a=>e.jsx(_e,{className:"animate-pulse",children:e.jsx(De,{className:"p-4",children:e.jsx("div",{className:"h-10 bg-muted rounded"})})},a))}):e.jsx(fN,{children:e.jsx("div",{className:"grid grid-cols-2 md:grid-cols-5 gap-3",children:r.map(a=>{const i=e.jsx(_e,{className:"border-border/50 hover:shadow-sm transition-shadow",children:e.jsx(De,{className:"p-4",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:Ot("p-2 rounded-lg",a.bgColor),children:e.jsx(a.icon,{className:Ot("h-5 w-5",a.color)})}),e.jsxs("div",{children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:a.label}),e.jsx("p",{className:"text-xl font-bold",children:a.value}),"subtitle"in a&&a.subtitle&&e.jsx("p",{className:"text-[10px] text-muted-foreground",children:a.subtitle})]})]})})},a.label);return"tooltip"in a&&a.tooltip?e.jsxs(wu,{children:[e.jsx(ju,{asChild:!0,children:i}),e.jsx(nu,{children:e.jsx("p",{children:a.tooltip})})]},a.label):i})})})}function M2n({formData:s,onChange:t,isEditing:n}){const{isAdmin:r}=Ls(),[a,i]=N.useState(s.portal_enabled);if(!r)return e.jsxs("div",{className:"border rounded-lg p-4 opacity-60",children:[e.jsx("div",{className:"flex items-center justify-between",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Cn,{className:"h-4 w-4 text-primary"}),e.jsx("h4",{className:"font-medium text-sm",children:"Client Portal"}),e.jsx(We,{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(Kv,{open:a,onOpenChange:i,children:e.jsxs("div",{className:"border rounded-lg",children:[e.jsxs(Yv,{className:"w-full p-4 flex items-center justify-between hover:bg-muted/50 transition-colors rounded-t-lg",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Cn,{className:"h-4 w-4 text-primary"}),e.jsx("h4",{className:"font-medium text-sm",children:"Client Portal"}),s.portal_enabled&&e.jsx(We,{className:"text-xs bg-emerald-500/10 text-emerald-600 border-emerald-200",variant:"outline",children:"Enabled"})]}),e.jsx(Xo,{className:Ot("h-4 w-4 text-muted-foreground transition-transform",a&&"rotate-180")})]}),e.jsx(Zv,{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(re,{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(zn,{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(re,{className:"text-sm font-medium",children:"Portal Visibility"}),e.jsxs(K1,{value:s.visibility,onValueChange:o=>l({visibility:o}),className:"grid grid-cols-2 gap-3",children:[e.jsxs("label",{className:Ot("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(Ju,{value:"private"}),e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(Au,{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:Ot("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(Ju,{value:"public"}),e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(au,{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(Bi,{id:"require_onboarding",checked:s.require_onboarding,onCheckedChange:o=>l({require_onboarding:!!o}),className:"mt-0.5"}),e.jsxs("div",{children:[e.jsx(re,{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(Bi,{id:"allow_spouse",checked:s.allow_spouse,onCheckedChange:o=>l({allow_spouse:!!o})}),e.jsx(re,{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(re,{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(re,{className:"text-xs text-muted-foreground",children:"Client Full Name"}),e.jsx(we,{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(re,{className:"text-xs text-muted-foreground",children:"Email"}),e.jsx(we,{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(re,{className:"text-xs text-muted-foreground",children:"Phone"}),e.jsx(we,{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(re,{className:"text-xs text-muted-foreground",children:"Preferred Invite Method"}),e.jsxs(Ns,{value:s.invite_method,onValueChange:o=>l({invite_method:o}),children:[e.jsx(ws,{children:e.jsx(ks,{})}),e.jsxs(js,{children:[e.jsx(nt,{value:"email",children:"Email"}),e.jsxs(nt,{value:"sms",disabled:!s.client_phone,children:["SMS ",!s.client_phone&&"(add phone first)"]})]})]})]})]})]})]})]})})]})})}const L2n=[{value:"buyer",label:"Buyer"},{value:"seller",label:"Seller"},{value:"dual",label:"Dual Agency"},{value:"referral",label:"Referral"},{value:"lease",label:"Lease"}],P2n=[{value:"low",label:"Low"},{value:"medium",label:"Medium"},{value:"high",label:"High"},{value:"urgent",label:"Urgent"}];function I2n({open:s,onOpenChange:t,deal:n,defaultStageId:r}){const{data:a}=PJ(),{data:i}=Wy(),{data:l}=L4t(),o=e3e(),c=k7t(),d=S7t(),u=mGe(),[h,m]=N.useState({portal_enabled:!1,visibility:"private",require_onboarding:!0,allow_spouse:!1,client_name:"",client_email:"",client_phone:"",invite_method:"email"}),[f,g]=N.useState(""),[y,x]=N.useState(!1),[_,b]=N.useState(!1),[k,A]=N.useState({first_name:"",last_name:"",email:"",phone:""}),T=(l==null?void 0:l.filter(W=>((n==null?void 0:n.listing_id)===W.id,!0)))||[],[P,I]=N.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:"",commission_calc_method:"standard",target_close_date:void 0,contract_date:void 0,listing_date:void 0,priority:"medium",probability:"50",notes:""});N.useEffect(()=>{var W,G,X,te,ne,me,ue,ce;s&&(n?(I({deal_name:n.deal_name,deal_type:n.deal_type,stage_id:n.stage_id||"",contact_id:n.contact_id||"",listing_id:n.listing_id||"",property_address:n.property_address||"",city:n.city||"",state:n.state||"",zip_code:n.zip_code||"",expected_price:((W=n.expected_price)==null?void 0:W.toString())||"",commission_percentage:((G=n.commission_percentage)==null?void 0:G.toString())||"3",brokerage_split_pct:((X=n.brokerage_split_pct)==null?void 0:X.toString())||"",team_split_pct:((te=n.team_split_pct)==null?void 0:te.toString())||"",referral_fee_pct:((ne=n.referral_fee_pct)==null?void 0:ne.toString())||"",franchise_fee_pct:((me=n.franchise_fee_pct)==null?void 0:me.toString())||"",transaction_fee:((ue=n.transaction_fee)==null?void 0:ue.toString())||"",commission_calc_method:n.commission_calc_method||"standard",target_close_date:n.target_close_date?Tc(n.target_close_date):void 0,contract_date:n.contract_date?Tc(n.contract_date):void 0,listing_date:n.listing_date?Tc(n.listing_date):void 0,priority:n.priority,probability:n.probability.toString(),notes:n.notes||""}),n.contact&&g(`${n.contact.first_name} ${n.contact.last_name}`)):(I({deal_name:"",deal_type:"buyer",stage_id:r||((ce=a==null?void 0:a[0])==null?void 0:ce.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:"",commission_calc_method:"standard",target_close_date:void 0,contract_date:void 0,listing_date:void 0,priority:"medium",probability:"50",notes:""}),g(""),m({portal_enabled:!1,visibility:"private",require_onboarding:!0,allow_spouse:!1,client_name:"",client_email:"",client_phone:"",invite_method:"email"})))},[s,n,r,a]);const M=i==null?void 0:i.filter(W=>{var he,xe,ve,ge,be;const G=f.toLowerCase().trim();if(!G)return!0;const X=((he=W.first_name)==null?void 0:he.toLowerCase())||"",te=((xe=W.last_name)==null?void 0:xe.toLowerCase())||"",ne=((ve=W.email)==null?void 0:ve.toLowerCase())||"",me=((be=(ge=W.phone)==null?void 0:ge.toLowerCase)==null?void 0:be.call(ge))||"",ue=`${X} ${te}`.trim(),ce=`${te} ${X}`.trim();if(ue.includes(G)||ce.includes(G)||X.includes(G)||te.includes(G)||ne.includes(G)||me.includes(G))return!0;const ae=G.split(/\s+/).filter(Boolean);return ae.length>1?ae.every(Se=>X.includes(Se)||te.includes(Se)||ne.includes(Se)||me.includes(Se)):!1}).slice(0,8),L=()=>{const W=parseFloat(P.expected_price)||0,G=parseFloat(P.commission_percentage)||0;return W*(G/100)},z=()=>{const W=L();if(!W)return null;const G=parseFloat(P.brokerage_split_pct)||0,X=parseFloat(P.team_split_pct)||0,te=parseFloat(P.referral_fee_pct)||0,ne=parseFloat(P.franchise_fee_pct)||0,me=parseFloat(P.transaction_fee)||0;if(P.commission_calc_method==="referral_first"){let ce=W;te&&(ce-=W*te/100);let ae=ce;return G&&(ae-=ce*G/100),X&&(ae-=W*X/100),ne&&(ae-=W*ne/100),me&&(ae-=me),Math.max(0,ae)}let ue=W;return G&&(ue=ue*((100-G)/100)),X&&(ue=ue*((100-X)/100)),te&&(ue=ue-W*te/100),ne&&(ue=ue-W*ne/100),me&&(ue=ue-me),Math.max(0,ue)},$=async W=>{var G,X,te;if(W.preventDefault(),!P.deal_name.trim()){ie.error("Please enter a deal name");return}try{const ne={deal_name:P.deal_name,deal_type:P.deal_type,stage_id:P.stage_id||null,contact_id:P.contact_id||null,listing_id:P.listing_id||null,property_address:P.property_address||null,city:P.city||null,state:P.state||null,zip_code:P.zip_code||null,expected_price:P.expected_price?parseFloat(P.expected_price):null,expected_commission:L()||null,commission_percentage:P.commission_percentage?parseFloat(P.commission_percentage):3,brokerage_split_pct:P.brokerage_split_pct?parseFloat(P.brokerage_split_pct):null,team_split_pct:P.team_split_pct?parseFloat(P.team_split_pct):null,referral_fee_pct:P.referral_fee_pct?parseFloat(P.referral_fee_pct):null,franchise_fee_pct:P.franchise_fee_pct?parseFloat(P.franchise_fee_pct):null,transaction_fee:P.transaction_fee?parseFloat(P.transaction_fee):null,commission_calc_method:P.commission_calc_method,target_close_date:((G=P.target_close_date)==null?void 0:G.toISOString().split("T")[0])||null,contract_date:((X=P.contract_date)==null?void 0:X.toISOString().split("T")[0])||null,listing_date:((te=P.listing_date)==null?void 0:te.toISOString().split("T")[0])||null,priority:P.priority,probability:parseInt(P.probability)||50,notes:P.notes||null};if(n)await d.mutateAsync({id:n.id,...ne}),ie.success("Deal updated successfully");else{const me=await c.mutateAsync(ne);if(ie.success("Deal created successfully"),h.portal_enabled&&(me!=null&&me.id))try{await u.mutateAsync({deal_id:me.id,visibility:h.visibility,require_onboarding:h.require_onboarding,allow_spouse:h.allow_spouse,client_name:h.client_name||null,client_email:h.client_email||null,client_phone:h.client_phone||null,invite_method:h.invite_method}),ie.success("Client portal created!")}catch{ie.error("Deal created, but portal setup failed")}}t(!1)}catch{ie.error("Failed to save deal")}},V=c.isPending||d.isPending;return e.jsx(Bs,{open:s,onOpenChange:t,children:e.jsxs(Fs,{className:"max-w-2xl max-h-[90vh] overflow-y-auto",children:[e.jsxs(qs,{children:[e.jsx($s,{children:n?"Edit Deal":"Add New Deal"}),e.jsx(Ar,{children:n?"Update the deal details below.":"Enter the details for your new deal."})]}),e.jsxs("form",{onSubmit:$,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(re,{htmlFor:"deal_name",children:"Deal Name *"}),e.jsx(we,{id:"deal_name",value:P.deal_name,onChange:W=>I(G=>({...G,deal_name:W.target.value})),placeholder:"e.g., Smith Family - 123 Main St"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{children:"Deal Type"}),e.jsxs(Ns,{value:P.deal_type,onValueChange:W=>I(G=>({...G,deal_type:W})),children:[e.jsx(ws,{children:e.jsx(ks,{})}),e.jsx(js,{children:L2n.map(W=>e.jsx(nt,{value:W.value,children:W.label},W.value))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{children:"Stage"}),e.jsxs(Ns,{value:P.stage_id||"none",onValueChange:W=>I(G=>({...G,stage_id:W==="none"?"":W})),children:[e.jsx(ws,{children:e.jsx(ks,{placeholder:"Select stage"})}),e.jsxs(js,{children:[e.jsx(nt,{value:"none",children:"No Stage"}),a==null?void 0:a.map(W=>e.jsx(nt,{value:W.id,children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"w-2 h-2 rounded-full",style:{backgroundColor:W.color}}),W.name]})},W.id))]})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{children:"Link to Contact"}),e.jsxs("div",{className:"relative",children:[e.jsx(Gr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(we,{value:f,onChange:W=>{g(W.target.value),x(!0),b(!1),W.target.value||I(G=>({...G,contact_id:""}))},onFocus:()=>x(!0),placeholder:"Search contacts...",className:"pl-9"}),y&&f&&e.jsxs("div",{className:"absolute z-10 w-full mt-1 bg-background border rounded-lg shadow-lg max-h-60 overflow-y-auto",children:[M&&M.length>0?M.map(W=>e.jsxs("button",{type:"button",className:"w-full px-3 py-2 text-left hover:bg-muted flex items-center gap-2",onClick:()=>{I(G=>({...G,contact_id:W.id})),g(`${W.first_name} ${W.last_name}`),x(!1)},children:[e.jsx(Ro,{className:"h-4 w-4 text-muted-foreground"}),e.jsxs("span",{children:[W.first_name," ",W.last_name]}),W.email&&e.jsx("span",{className:"text-xs text-muted-foreground ml-auto",children:W.email})]},W.id)):e.jsx("div",{className:"px-3 py-2 text-sm text-muted-foreground",children:"No contacts found"}),e.jsxs("button",{type:"button",className:"w-full px-3 py-2 text-left hover:bg-muted flex items-center gap-2 border-t text-primary font-medium",onClick:()=>{const W=f.trim().split(/\s+/);A({first_name:W[0]||"",last_name:W.slice(1).join(" ")||"",email:"",phone:""}),b(!0),x(!1)},children:[e.jsx(Yl,{className:"h-4 w-4"}),e.jsxs("span",{children:['Create new contact "',f.trim(),'"']})]})]})]}),_&&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(Yl,{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:()=>b(!1),children:"Cancel"})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[e.jsx(we,{placeholder:"First name *",value:k.first_name,onChange:W=>A(G=>({...G,first_name:W.target.value})),className:"h-8 text-sm"}),e.jsx(we,{placeholder:"Last name",value:k.last_name,onChange:W=>A(G=>({...G,last_name:W.target.value})),className:"h-8 text-sm"}),e.jsx(we,{placeholder:"Email",type:"email",value:k.email,onChange:W=>A(G=>({...G,email:W.target.value})),className:"h-8 text-sm"}),e.jsx(we,{placeholder:"Phone",type:"tel",value:k.phone,onChange:W=>A(G=>({...G,phone:W.target.value})),className:"h-8 text-sm"})]}),e.jsx(B,{type:"button",size:"sm",className:"w-full h-8",disabled:!k.first_name.trim()||o.isPending,onClick:async()=>{try{const W=await o.mutateAsync({first_name:k.first_name.trim(),last_name:k.last_name.trim()||null,email:k.email.trim()||null,phone:k.phone.trim()||null});W&&(I(G=>({...G,contact_id:W.id})),g(`${W.first_name} ${W.last_name||""}`.trim()),b(!1))}catch{}},children:o.isPending?e.jsxs(e.Fragment,{children:[e.jsx(us,{className:"h-3.5 w-3.5 mr-1 animate-spin"})," Creating..."]}):e.jsxs(e.Fragment,{children:[e.jsx(Yl,{className:"h-3.5 w-3.5 mr-1"})," Add & Link Contact"]})})]})]}),T.length>0&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs(re,{className:"flex items-center gap-2",children:[e.jsx(cd,{className:"h-4 w-4"}),"Link to Listing Exchange"]}),e.jsxs(Ns,{value:P.listing_id||"none",onValueChange:W=>{const G=W==="none"?"":W,X=T.find(te=>te.id===G);I(X?te=>{var ne;return{...te,listing_id:G,deal_type:"seller",property_address:X.property_address||te.property_address,city:X.city||te.city,state:X.state||te.state,expected_price:((ne=X.price)==null?void 0:ne.toString())||te.expected_price}}:te=>({...te,listing_id:G}))},children:[e.jsx(ws,{children:e.jsx(ks,{placeholder:"Select a listing to sync status..."})}),e.jsxs(js,{children:[e.jsx(nt,{value:"none",children:"None"}),T.map(W=>e.jsx(nt,{value:W.id,children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{children:W.property_address||`${W.city}, ${W.state}`}),e.jsxs("span",{className:"text-xs text-muted-foreground",children:["$",(W.price/1e3).toFixed(0),"K"]})]})},W.id))]})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Status changes will sync automatically between the deal and listing."})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsx("h4",{className:"font-medium text-sm",children:"Property Details"}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{className:"col-span-2 space-y-2",children:[e.jsx(re,{htmlFor:"property_address",children:"Address"}),e.jsx(we,{id:"property_address",value:P.property_address,onChange:W=>I(G=>({...G,property_address:W.target.value})),placeholder:"123 Main Street"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{htmlFor:"city",children:"City"}),e.jsx(we,{id:"city",value:P.city,onChange:W=>I(G=>({...G,city:W.target.value}))})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{htmlFor:"state",children:"State"}),e.jsx(we,{id:"state",value:P.state,onChange:W=>I(G=>({...G,state:W.target.value})),maxLength:2,placeholder:"TX"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{htmlFor:"zip_code",children:"ZIP"}),e.jsx(we,{id:"zip_code",value:P.zip_code,onChange:W=>I(G=>({...G,zip_code:W.target.value}))})]})]})]})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsx("h4",{className:"font-medium text-sm",children:"Financial Details"}),e.jsxs("div",{className:"grid grid-cols-3 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{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(we,{id:"expected_price",type:"number",value:P.expected_price,onChange:W=>I(G=>({...G,expected_price:W.target.value})),className:"pl-7",placeholder:"500000"})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{htmlFor:"commission_percentage",children:"Commission %"}),e.jsxs("div",{className:"relative",children:[e.jsx(we,{id:"commission_percentage",type:"number",step:"0.1",value:P.commission_percentage,onChange:W=>I(G=>({...G,commission_percentage:W.target.value})),className:"pr-7"}),e.jsx("span",{className:"absolute right-3 top-1/2 -translate-y-1/2 text-muted-foreground",children:"%"})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{children:"Expected GCI"}),e.jsx(we,{value:L()?`$${L().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(re,{className:"text-xs whitespace-nowrap",children:"Calculation Method:"}),e.jsxs(Ns,{value:P.commission_calc_method,onValueChange:W=>I(G=>({...G,commission_calc_method:W})),children:[e.jsx(ws,{className:"h-7 text-xs",children:e.jsx(ks,{})}),e.jsxs(js,{children:[e.jsx(nt,{value:"standard",children:"Standard (all splits on GCI)"}),e.jsx(nt,{value:"referral_first",children:"Referral First (brokerage split after referral)"})]})]})]}),P.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(re,{className:"text-xs",children:"Brokerage Split"}),e.jsxs("div",{className:"relative",children:[e.jsx(we,{type:"number",step:"1",min:"0",max:"100",value:P.brokerage_split_pct,onChange:W=>I(G=>({...G,brokerage_split_pct:W.target.value})),className:"pr-7 h-8 text-sm",placeholder:"30"}),e.jsx("span",{className:"absolute right-3 top-1/2 -translate-y-1/2 text-muted-foreground text-xs",children:"%"})]}),e.jsx("p",{className:"text-[10px] text-muted-foreground",children:"% that goes to brokerage"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(re,{className:"text-xs",children:"Team Split"}),e.jsxs("div",{className:"relative",children:[e.jsx(we,{type:"number",step:"1",min:"0",max:"100",value:P.team_split_pct,onChange:W=>I(G=>({...G,team_split_pct:W.target.value})),className:"pr-7 h-8 text-sm",placeholder:"0"}),e.jsx("span",{className:"absolute right-3 top-1/2 -translate-y-1/2 text-muted-foreground text-xs",children:"%"})]}),e.jsx("p",{className:"text-[10px] text-muted-foreground",children:"% that goes to team lead"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(re,{className:"text-xs",children:"Referral Fee"}),e.jsxs("div",{className:"relative",children:[e.jsx(we,{type:"number",step:"1",min:"0",max:"100",value:P.referral_fee_pct,onChange:W=>I(G=>({...G,referral_fee_pct:W.target.value})),className:"pr-7 h-8 text-sm",placeholder:"0"}),e.jsx("span",{className:"absolute right-3 top-1/2 -translate-y-1/2 text-muted-foreground text-xs",children:"%"})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(re,{className:"text-xs",children:"Franchise Fee"}),e.jsxs("div",{className:"relative",children:[e.jsx(we,{type:"number",step:"1",min:"0",max:"100",value:P.franchise_fee_pct,onChange:W=>I(G=>({...G,franchise_fee_pct:W.target.value})),className:"pr-7 h-8 text-sm",placeholder:"0"}),e.jsx("span",{className:"absolute right-3 top-1/2 -translate-y-1/2 text-muted-foreground text-xs",children:"%"})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(re,{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(we,{type:"number",step:"1",min:"0",value:P.transaction_fee,onChange:W=>I(G=>({...G,transaction_fee:W.target.value})),className:"pl-7 h-8 text-sm",placeholder:"500"})]}),e.jsx("p",{className:"text-[10px] text-muted-foreground",children:"Flat fee deducted"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(re,{className:"text-xs",children:"Net to Agent"}),e.jsx(we,{value:z()?`$${Math.round(z()).toLocaleString()}`:"-",disabled:!0,className:"bg-muted h-8 text-sm font-semibold"})]})]})]})]})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsx("h4",{className:"font-medium text-sm",children:"Dates & Status"}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{children:"Target Close Date"}),e.jsxs(rc,{children:[e.jsx(ac,{asChild:!0,children:e.jsxs(B,{variant:"outline",className:Ot("w-full justify-start text-left font-normal",!P.target_close_date&&"text-muted-foreground"),children:[e.jsx(ta,{className:"mr-2 h-4 w-4"}),P.target_close_date?Js(P.target_close_date,"PPP"):"Pick a date"]})}),e.jsx(Zl,{className:"w-auto p-0",align:"start",children:e.jsx(Xv,{mode:"single",selected:P.target_close_date,onSelect:W=>I(G=>({...G,target_close_date:W})),initialFocus:!0,className:"pointer-events-auto"})})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{children:"Contract Date"}),e.jsxs(rc,{children:[e.jsx(ac,{asChild:!0,children:e.jsxs(B,{variant:"outline",className:Ot("w-full justify-start text-left font-normal",!P.contract_date&&"text-muted-foreground"),children:[e.jsx(ta,{className:"mr-2 h-4 w-4"}),P.contract_date?Js(P.contract_date,"PPP"):"Pick a date"]})}),e.jsx(Zl,{className:"w-auto p-0",align:"start",children:e.jsx(Xv,{mode:"single",selected:P.contract_date,onSelect:W=>I(G=>({...G,contract_date:W})),initialFocus:!0,className:"pointer-events-auto"})})]})]}),(P.deal_type==="seller"||P.deal_type==="dual")&&!P.listing_id&&e.jsxs("div",{className:"space-y-2 col-span-2",children:[e.jsx(re,{children:"Listing Date (for Days on Market)"}),e.jsxs(rc,{children:[e.jsx(ac,{asChild:!0,children:e.jsxs(B,{variant:"outline",className:Ot("w-full justify-start text-left font-normal",!P.listing_date&&"text-muted-foreground"),children:[e.jsx(ta,{className:"mr-2 h-4 w-4"}),P.listing_date?Js(P.listing_date,"PPP"):"Pick a date"]})}),e.jsx(Zl,{className:"w-auto p-0",align:"start",children:e.jsx(Xv,{mode:"single",selected:P.listing_date,onSelect:W=>I(G=>({...G,listing_date:W})),initialFocus:!0,className:"pointer-events-auto"})})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Used to calculate Days on Market. Auto-filled for linked listings."})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{children:"Priority"}),e.jsxs(Ns,{value:P.priority,onValueChange:W=>I(G=>({...G,priority:W})),children:[e.jsx(ws,{children:e.jsx(ks,{})}),e.jsx(js,{children:P2n.map(W=>e.jsx(nt,{value:W.value,children:W.label},W.value))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{children:"Win Probability"}),e.jsxs("div",{className:"relative",children:[e.jsx(we,{type:"number",min:"0",max:"100",value:P.probability,onChange:W=>I(G=>({...G,probability:W.target.value})),className:"pr-7"}),e.jsx("span",{className:"absolute right-3 top-1/2 -translate-y-1/2 text-muted-foreground",children:"%"})]})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{htmlFor:"notes",children:"Notes"}),e.jsx(Ws,{id:"notes",value:P.notes,onChange:W=>I(G=>({...G,notes:W.target.value})),placeholder:"Add any additional notes about this deal...",rows:3})]}),!n&&e.jsx(M2n,{formData:h,onChange:m}),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:V,children:[V&&e.jsx(us,{className:"h-4 w-4 mr-2 animate-spin"}),n?"Update Deal":"Create Deal"]})]})]})]})})}function D2n({dealId:s}){const t=Ya(),n=as(),[r,a]=N.useState(""),[i,l]=N.useState(!1),{data:o=[]}=mt({queryKey:["deal-tags",s],queryFn:async()=>{const{data:g,error:y}=await H.from("deal_tags").select("*").eq("deal_id",s).order("created_at");if(y)throw y;return g},enabled:!!s}),{data:c=[]}=mt({queryKey:["all-deal-tags",t],queryFn:async()=>{if(!t)return[];const{data:g,error:y}=await H.from("deal_tags").select("tag").eq("owner_user_id",t);if(y)throw y;return[...new Set(g.map(_=>_.tag))].sort()},enabled:!!t}),d=_t({mutationFn:async g=>{if(!t)throw new Error("Not authenticated");const{error:y}=await H.from("deal_tags").insert({deal_id:s,owner_user_id:t,tag:g.trim()});if(y)throw y},onSuccess:()=>{n.invalidateQueries({queryKey:["deal-tags",s]}),n.invalidateQueries({queryKey:["all-deal-tags"]}),a("")}}),u=_t({mutationFn:async g=>{const{error:y}=await H.from("deal_tags").delete().eq("id",g);if(y)throw y},onSuccess:()=>{n.invalidateQueries({queryKey:["deal-tags",s]})}}),h=()=>{const g=r.trim();g&&(o.some(y=>y.tag.toLowerCase()===g.toLowerCase())||d.mutate(g))},m=o.map(g=>g.tag.toLowerCase()),f=c.filter(g=>g.toLowerCase().includes(r.toLowerCase())&&!m.includes(g.toLowerCase())).slice(0,5);return e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex flex-wrap gap-1.5",children:[o.map(g=>e.jsxs(We,{variant:"secondary",className:"gap-1 text-xs",children:[g.tag,e.jsx("button",{type:"button",onClick:()=>u.mutate(g.id),className:"ml-0.5 hover:text-destructive",children:e.jsx(hr,{className:"h-3 w-3"})})]},g.id)),!i&&e.jsxs("button",{type:"button",onClick:()=>l(!0),className:"flex items-center gap-1 text-xs text-muted-foreground hover:text-foreground px-2 py-0.5 rounded border border-dashed border-border hover:border-primary transition-colors",children:[e.jsx(nn,{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(we,{value:r,onChange:g=>a(g.target.value),onKeyDown:g=>{g.key==="Enter"&&(g.preventDefault(),h()),g.key==="Escape"&&(l(!1),a(""))},placeholder:"Type tag name...",className:"h-8 text-xs flex-1",autoFocus:!0}),e.jsx("button",{type:"button",onClick:h,disabled:!r.trim()||d.isPending,className:"h-8 px-3 rounded-md bg-primary text-primary-foreground text-xs font-medium disabled:opacity-50 shrink-0",children:"Add"}),e.jsx("button",{type:"button",onClick:()=>{l(!1),a("")},className:"h-8 px-2 rounded-md bg-muted text-muted-foreground text-xs shrink-0",children:"Cancel"})]}),r&&f.length>0&&e.jsx("div",{className:"absolute z-20 w-full mt-1 bg-background border rounded shadow-lg max-h-32 overflow-y-auto",children:f.map(g=>e.jsx("button",{type:"button",className:"w-full px-3 py-2 text-left text-xs hover:bg-muted active:bg-muted",onClick:y=>{y.preventDefault(),d.mutate(g)},children:g},g))})]})]})}function R2n(s){return mt({queryKey:["deal-files",s],queryFn:async()=>{const{data:t,error:n}=await H.from("deal_files").select("*").eq("deal_id",s).order("created_at",{ascending:!1});if(n)throw n;return t},enabled:!!s})}function O2n(){const s=Ya(),t=as();return _t({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 H.storage.from("deal-files").upload(i,r);if(l)throw l;const{data:o,error:c}=await H.from("deal_files").insert({deal_id:n,owner_user_id:s,file_name:r.name,file_size:r.size,file_type:r.type||null,storage_path:i}).select().single();if(c)throw c;return o},onSuccess:(n,r)=>{t.invalidateQueries({queryKey:["deal-files",r.dealId]})}})}function F2n(){const s=as();return _t({mutationFn:async({fileId:t,storagePath:n,dealId:r})=>{await H.storage.from("deal-files").remove([n]);const{error:a}=await H.from("deal_files").delete().eq("id",t);if(a)throw a;return r},onSuccess:t=>{s.invalidateQueries({queryKey:["deal-files",t]})}})}function z2n(){const s=as();return _t({mutationFn:async({fileId:t,visible:n,dealId:r})=>{const{error:a}=await H.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 B2n(s){const{data:t,error:n}=await H.storage.from("deal-files").createSignedUrl(s,3600);if(n)throw n;return t.signedUrl}const Pft={text:"Short Text",textarea:"Long Text",dropdown:"Dropdown",toggle:"Yes / No"};function L7t({open:s,onOpenChange:t}){const{data:n,isLoading:r}=Jpn(),a=efn(),i=tfn(),l=sfn(),[o,c]=N.useState(!1),[d,u]=N.useState({question_text:"",field_type:"text",options:[],is_required:!1}),[h,m]=N.useState(""),f=async()=>{if(d.question_text.trim())try{await a.mutateAsync({question_text:d.question_text.trim(),field_type:d.field_type,options:d.field_type==="dropdown"?d.options:[],is_required:d.is_required,sort_order:((n==null?void 0:n.length)||0)+1}),u({question_text:"",field_type:"text",options:[],is_required:!1}),m(""),c(!1),ie.success("Question added")}catch{ie.error("Failed to add question")}},g=async b=>{try{await l.mutateAsync(b),ie.success("Question removed")}catch{ie.error("Failed to remove question")}},y=async(b,k)=>{try{await i.mutateAsync({id:b,is_required:k})}catch{ie.error("Failed to update question")}},x=()=>{h.trim()&&(u(b=>({...b,options:[...b.options,h.trim()]})),m(""))},_=b=>{u(k=>({...k,options:k.options.filter((A,T)=>T!==b)}))};return e.jsx(Bs,{open:s,onOpenChange:t,children:e.jsxs(Fs,{className:"max-w-md max-h-[85vh] flex flex-col",children:[e.jsxs(qs,{children:[e.jsx($s,{children:"Custom Intake Questions"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"These questions appear on all your portal onboarding forms."})]}),e.jsx(lo,{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(us,{className:"h-5 w-5 animate-spin text-muted-foreground"})}),n==null?void 0:n.map(b=>{var k;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(Mp,{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(We,{variant:"secondary",className:"text-xs",children:Pft[b.field_type]||b.field_type}),b.is_required&&e.jsx(We,{variant:"outline",className:"text-xs",children:"Required"})]}),b.field_type==="dropdown"&&((k=b.options)==null?void 0:k.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(zn,{checked:b.is_required,onCheckedChange:A=>y(b.id,A),className:"scale-75"}),e.jsx(B,{variant:"ghost",size:"icon",className:"h-7 w-7 text-muted-foreground hover:text-destructive",onClick:()=>g(b.id),children:e.jsx(qn,{className:"h-3.5 w-3.5"})})]})]})},b.id)}),!r&&(n==null?void 0:n.length)===0&&!o&&e.jsxs("div",{className:"text-center py-8 border border-dashed rounded-lg",children:[e.jsx("p",{className:"text-sm text-muted-foreground mb-2",children:"No custom questions yet"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Add questions that clients will answer during onboarding."})]}),o&&e.jsxs("div",{className:"border-2 border-primary/20 rounded-lg p-4 space-y-3 bg-primary/5",children:[e.jsxs("div",{children:[e.jsx(re,{className:"text-sm font-medium",children:"Question"}),e.jsx(we,{value:d.question_text,onChange:b=>u(k=>({...k,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(re,{className:"text-sm font-medium",children:"Answer Type"}),e.jsx("div",{className:"flex flex-wrap gap-1.5 mt-1.5",children:Object.entries(Pft).map(([b,k])=>e.jsx("button",{type:"button",onClick:()=>u(A=>({...A,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:k},b))})]}),d.field_type==="dropdown"&&e.jsxs("div",{children:[e.jsx(re,{className:"text-sm font-medium",children:"Options"}),e.jsxs("div",{className:"space-y-1.5 mt-1.5",children:[d.options.map((b,k)=>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:()=>_(k),className:"text-muted-foreground hover:text-destructive",children:e.jsx(hr,{className:"h-3.5 w-3.5"})})]},k)),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(we,{value:h,onChange:b=>m(b.target.value),onKeyDown:b=>b.key==="Enter"&&(b.preventDefault(),x()),placeholder:"Add option...",className:"h-8 text-sm"}),e.jsx(B,{variant:"outline",size:"sm",onClick:x,disabled:!h.trim(),className:"h-8",children:e.jsx(nn,{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(zn,{checked:d.is_required,onCheckedChange:b=>u(k=>({...k,is_required:b}))}),e.jsx(re,{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:f,disabled:!d.question_text.trim()||a.isPending,className:"flex-1",children:[a.isPending?e.jsx(us,{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(nn,{className:"h-4 w-4 mr-1"})," Add Question"]}),e.jsx(B,{variant:"ghost",size:"sm",onClick:()=>t(!1),children:"Done"})]})]})})}function $2n({override:s,onChange:t}){const n=Ya(),{data:r}=hSt(),[a,i]=N.useState(null),l=d=>t({...s,...d}),o=async(d,u)=>{if(n){if(d.size>5*1024*1024){ie.error("Image must be under 5MB");return}i(u);try{const h=await mSt(n,d,`${u}`);l(u==="logo"?{logo_url:h}:{cover_photo_url:h})}catch(h){ie.error(`Upload failed: ${h.message||h}`)}finally{i(null)}}},c=Object.values(s||{}).some(d=>d!=null&&d!=="");return e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-start gap-2 p-3 rounded-md bg-primary/5 border border-primary/10",children:[e.jsx(Cn,{className:"h-4 w-4 text-primary shrink-0 mt-0.5"}),e.jsxs("div",{className:"text-xs text-muted-foreground",children:["These settings ",e.jsx("span",{className:"font-medium text-foreground",children:"override your global Portal Branding"})," for this deal only. Leave any field empty to use your global default."]})]}),e.jsx(Ift,{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(Ift,{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(Dft,{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(Dft,{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(re,{className:"text-sm font-medium",children:"Tagline"}),e.jsx(we,{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(qn,{className:"h-3 w-3 mr-1"}),"Clear all overrides"]})]})}function Ift({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(re,{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:Ot("rounded-lg border-2 border-dashed flex items-center justify-center overflow-hidden bg-muted/30 shrink-0",c?"border-primary":"border-input",l==="square"?"h-16 w-16":"h-16 w-32"),children:o?e.jsx("img",{src:o,alt:s,className:"h-full w-full object-cover"}):e.jsx(pc,{className:"h-5 w-5 text-muted-foreground/40"})}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs("label",{className:"cursor-pointer",children:[e.jsx("input",{type:"file",accept:"image/*",className:"hidden",onChange:d=>{var h;const u=(h=d.target.files)==null?void 0:h[0];u&&a(u),d.target.value=""}}),e.jsxs("span",{className:"inline-flex items-center gap-1.5 h-9 px-3 rounded-md border border-input bg-background hover:bg-accent text-sm font-medium",children:[r?e.jsx(us,{className:"h-3.5 w-3.5 animate-spin"}):e.jsx(ni,{className:"h-3.5 w-3.5"}),t?"Replace":"Override"]})]}),t&&e.jsx(B,{variant:"ghost",size:"sm",onClick:i,className:"text-muted-foreground hover:text-destructive",children:e.jsx(qn,{className:"h-3.5 w-3.5"})})]})]})]})}function Dft({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(re,{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:Ot("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(we,{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(qn,{className:"h-3 w-3"})})]})]})}function U2n({portalId:s,agentUserId:t}){const n=as(),{data:r,isLoading:a}=mt({queryKey:["portal-vendor-manage",s,t],queryFn:async()=>{const{data:h}=await H.from("profiles").select("brokerage_id").eq("id",t).maybeSingle(),m=h==null?void 0:h.brokerage_id,f=H.from("vendors").select("*").eq("is_active",!0),g=m?f.or(`and(owner_type.eq.agent,owner_user_id.eq.${t}),and(owner_type.eq.brokerage,owner_brokerage_id.eq.${m})`):f.eq("owner_type","agent").eq("owner_user_id",t),[{data:y,error:x},{data:_},{data:b}]=await Promise.all([g.order("sort_order",{ascending:!0}).order("name",{ascending:!0}),H.from("agent_vendor_selections").select("vendor_id, is_visible").eq("agent_user_id",t),H.from("portal_vendor_overrides").select("vendor_id, is_visible").eq("portal_id",s)]);if(x)throw x;const k=new Map;(_||[]).forEach(T=>k.set(T.vendor_id,T.is_visible));const A=new Map;return(b||[]).forEach(T=>A.set(T.vendor_id,T.is_visible)),{vendors:y||[],selMap:k,overrideMap:A}}}),i=_t({mutationFn:async({vendorId:h,isVisible:m})=>{const{data:f}=await H.from("portal_vendor_overrides").select("id").eq("portal_id",s).eq("vendor_id",h).maybeSingle();if(f){const{error:g}=await H.from("portal_vendor_overrides").update({is_visible:m}).eq("id",f.id);if(g)throw g}else{const{error:g}=await H.from("portal_vendor_overrides").insert({portal_id:s,vendor_id:h,is_visible:m});if(g)throw g}},onSuccess:()=>{n.invalidateQueries({queryKey:["portal-vendor-manage",s,t]}),n.invalidateQueries({queryKey:["portal-vendors",s]})},onError:h=>ie.error(h.message)});if(a)return e.jsx("div",{className:"flex items-center justify-center py-8",children:e.jsx(us,{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(Y2,{className:"w-10 h-10 text-muted-foreground mx-auto mb-3"}),e.jsx("h3",{className:"font-semibold",children:"No vendors in your library yet"}),e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:"Add vendors in the Vendors tab of Client Portals, then toggle them here per portal."})]});const d=h=>{const m=c.get(h.id);if(m!==void 0)return m;if(h.is_required)return!0;const f=o.get(h.id);return f===void 0?!0:f!==!1},u=h=>{var m;return((m=mU.find(f=>f.value===h))==null?void 0:m.label)||h};return e.jsxs("div",{className:"space-y-3",children:[e.jsxs("p",{className:"text-sm text-muted-foreground",children:["Choose which vendors from your library appear in ",e.jsx("em",{children:"this specific portal"}),". Changes here only affect this deal — your global vendor library and other portals are unaffected."]}),e.jsx(lo,{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(We,{variant:"outline",className:"text-[10px] shrink-0",children:u(h.category)}),h.owner_type==="brokerage"&&e.jsx(We,{variant:"secondary",className:"text-[10px] shrink-0",children:"Brokerage"}),h.is_required&&e.jsx(We,{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(zn,{checked:m,disabled:h.is_required||i.isPending,onCheckedChange:f=>i.mutate({vendorId:h.id,isVisible:f})})]},h.id)})})})]})}function q2n({portalId:s,ownerId:t,clientEmail:n,linkedPortalId:r,onLink:a}){const[i,l]=N.useState(""),[o,c]=N.useState(!1),{data:d,isLoading:u}=mt({queryKey:["all-owner-portals",t],queryFn:async()=>{const{data:g,error:y}=await H.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 g},enabled:o||!!r}),h=N.useMemo(()=>!r||!d?null:d.find(g=>g.id===r),[r,d]),m=N.useMemo(()=>!d||!n?[]:d.filter(g=>{var y;return((y=g.client_email)==null?void 0:y.toLowerCase())===n.toLowerCase()&&g.id!==s}),[d,n,s]),f=N.useMemo(()=>{if(!d||!i.trim())return[];const g=i.toLowerCase();return d.filter(y=>{var _,b,k,A;const x=y.deal_pipeline;return((_=y.client_name)==null?void 0:_.toLowerCase().includes(g))||((b=y.client_email)==null?void 0:b.toLowerCase().includes(g))||((k=x==null?void 0:x.deal_name)==null?void 0:k.toLowerCase().includes(g))||((A=x==null?void 0:x.property_address)==null?void 0:A.toLowerCase().includes(g))})},[d,i]);if(r){const g=h==null?void 0:h.deal_pipeline;return e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{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(cd,{className:"h-4 w-4 text-primary shrink-0"}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-sm font-medium truncate",children:(h==null?void 0:h.client_name)||(g==null?void 0:g.deal_name)||"Linked Portal"}),e.jsxs("p",{className:"text-xs text-muted-foreground truncate",children:[(g==null?void 0:g.deal_type)==="listing"?"🏠 Listing":"🔑 Purchase"," · ",(g==null?void 0:g.property_address)||"No address"]})]}),e.jsxs(B,{variant:"ghost",size:"sm",className:"text-xs text-destructive hover:text-destructive shrink-0",onClick:()=>a(null),children:[e.jsx(kD,{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(re,{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(cd,{className:"h-3 w-3 mr-1"}),o?"Cancel":"Link"]})]}),!o&&m.length>0&&e.jsxs("div",{className:"space-y-1.5",children:[e.jsx("p",{className:"text-[11px] text-muted-foreground font-medium",children:"✨ Suggested match (same client email)"}),m.map(g=>{const y=g.deal_pipeline;return e.jsxs("button",{onClick:()=>a(g.id),className:"w-full flex items-center gap-2 bg-amber-50 border border-amber-200 rounded-lg p-2.5 hover:bg-amber-100 transition-colors text-left",children:[e.jsx(We,{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)||g.client_name}),e.jsx("p",{className:"text-[11px] text-muted-foreground truncate",children:y==null?void 0:y.property_address})]}),e.jsx(cd,{className:"h-3.5 w-3.5 text-amber-600 shrink-0"})]},g.id)})]}),o&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"relative",children:[e.jsx(Gr,{className:"absolute left-2.5 top-1/2 -translate-y-1/2 h-3.5 w-3.5 text-muted-foreground"}),e.jsx(we,{value:i,onChange:g=>l(g.target.value),placeholder:"Search by name, email, or address...",className:"pl-8 h-8 text-xs",autoFocus:!0})]}),u&&e.jsx("div",{className:"flex items-center justify-center py-4",children:e.jsx(us,{className:"h-4 w-4 animate-spin text-muted-foreground"})}),f.length>0&&e.jsx("div",{className:"space-y-1 max-h-[200px] overflow-y-auto",children:f.map(g=>{const y=g.deal_pipeline;return e.jsxs("button",{onClick:()=>{a(g.id),c(!1),l("")},className:"w-full flex items-center gap-2 border rounded-lg p-2 hover:bg-muted/50 transition-colors text-left",children:[e.jsx(We,{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)||g.client_name}),e.jsx("p",{className:"text-[11px] text-muted-foreground truncate",children:g.client_email})]})]},g.id)})}),i&&f.length===0&&!u&&e.jsx("p",{className:"text-xs text-muted-foreground text-center py-3",children:"No portals found"})]})]})}function VWe({contactId:s,onVideoReady:t}){const[n,r]=N.useState(!1),[a,i]=N.useState("record"),[l,o]=N.useState(0),[c,d]=N.useState(0),u=G3(),h=()=>{i("record"),o(0),d(0)},m=g=>{!g&&(a==="uploading"||a==="processing")||(r(g),g||h())},f=N.useCallback(async(g,y)=>{i("uploading");try{const x="Card Video",{videoId:_,libraryId:b}=await sO(x),{uploadUrl:k,apiKey:A}=await nO(_),T=new XMLHttpRequest;T.upload.onprogress=V=>{V.lengthComputable&&o(V.loaded/V.total*100)},await new Promise((V,W)=>{T.onload=()=>T.status>=200&&T.status<300?V():W(new Error("Upload failed")),T.onerror=()=>W(new Error("Upload failed")),T.open("PUT",k),T.setRequestHeader("AccessKey",A),T.send(g)}),i("processing");let P=0;const I=Date.now(),M=9e4,L=`https://iframe.mediadelivery.net/embed/${b}/${_}`;for(;P<4;){if(await new Promise(W=>setTimeout(W,3e3)),Date.now()-I>M){const W=g.size/1048576;await u.mutateAsync({bunny_video_id:_,playback_url:`https://iframe.mediadelivery.net/play/${b}/${_}`,file_size_mb:W,title:x,contact_id:s||void 0,status:"processing",touch_type:"video"}),t(L),ie.success("Video saved — still encoding. It will be ready shortly."),i("done"),setTimeout(()=>{r(!1),h()},1500);return}const V=await F5(_);if(P=V.status,d(V.encodeProgress||0),P===5||P===6)throw new Error("Video processing failed")}const z=await F5(_),$=(z.storageSize||g.size)/(1024*1024);await u.mutateAsync({bunny_video_id:_,contact_id:s||void 0,playback_url:z.directPlayUrl||L,thumbnail_url:z.thumbnailUrl,preview_url:z.previewUrl||null,duration_seconds:z.length||y,file_size_mb:$,title:x,status:"ready",touch_type:"video"}),t(L),ie.success("Video recorded & added to your library!"),i("done"),setTimeout(()=>{r(!1),h()},1500)}catch(x){console.error("Recording upload error:",x),ie.error("Failed to process video. Please try again."),i("record")}},[s,t,u]);return e.jsxs(Bs,{open:n,onOpenChange:m,children:[e.jsx(Ao,{asChild:!0,children:e.jsxs(B,{variant:"outline",size:"sm",className:"gap-1.5 w-full",children:[e.jsx(na,{className:"h-3.5 w-3.5"}),"Record Video"]})}),e.jsxs(Fs,{className:"sm:max-w-2xl max-h-[90vh] overflow-y-auto",children:[e.jsx(qs,{children:e.jsx($s,{children:"Record a Video for Your Card"})}),a==="record"&&e.jsx(oO,{maxDurationSeconds:600,onRecordingComplete:f,onError:g=>ie.error(g)}),a==="uploading"&&e.jsxs("div",{className:"flex flex-col items-center gap-4 py-12",children:[e.jsx(us,{className:"h-10 w-10 animate-spin text-primary"}),e.jsx("p",{className:"text-sm font-medium",children:"Uploading video..."}),e.jsx(ro,{value:l,className:"w-64"}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[Math.round(l),"%"]})]}),a==="processing"&&e.jsxs("div",{className:"flex flex-col items-center gap-4 py-12",children:[e.jsx(us,{className:"h-10 w-10 animate-spin text-primary"}),e.jsx("p",{className:"text-sm font-medium",children:"Processing video..."}),e.jsx(ro,{value:c,className:"w-64"}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[Math.round(c),"%"]})]}),a==="done"&&e.jsxs("div",{className:"flex flex-col items-center gap-3 py-12",children:[e.jsx(Po,{className:"h-12 w-12 text-emerald-500"}),e.jsx("p",{className:"text-sm font-medium",children:"Video attached to your card!"})]})]})]})}const V2n=s=>`portal-settings-draft:${s}`;function HWe({open:s,onOpenChange:t,portal:n,dealOwnerId:r}){const a=VU(),[i,l]=N.useState(!1),o=N.useMemo(()=>V2n(n.id),[n.id]),[c,d]=N.useState(!1),[u,h]=N.useState(n.next_step_text||""),[m,f]=N.useState(n.next_step_video_url||""),[g,y]=N.useState(n.inspection_date||""),[x,_]=N.useState(n.appraisal_date||""),[b,k]=N.useState(n.welcome_message||""),[A,T]=N.useState(n.review_url||""),[P,I]=N.useState(n.show_post_close_tips),[M,L]=N.useState(n.notify_client),[z,$]=N.useState(n.require_onboarding),[V,W]=N.useState(n.allow_spouse),[G,X]=N.useState(n.visibility),[te,ne]=N.useState(n.stage_mapping||[]),[me,ue]=N.useState(null),[ce,ae]=N.useState(n.linked_portal_id||null),[he,xe]=N.useState(n.referral_enabled??!0),[ve,ge]=N.useState(n.referral_reward_text||""),[be,Se]=N.useState(n.referral_cta_headline||""),[Ie,Me]=N.useState(n.homeowner_hub_video_url||""),[Re,Be]=N.useState(n.branding_override||{}),Ne=()=>{h(n.next_step_text||""),f(n.next_step_video_url||""),y(n.inspection_date||""),_(n.appraisal_date||""),k(n.welcome_message||""),T(n.review_url||""),I(n.show_post_close_tips),L(n.notify_client),$(n.require_onboarding),W(n.allow_spouse),X(n.visibility),ne(n.stage_mapping||[]),ae(n.linked_portal_id||null),xe(n.referral_enabled??!0),ge(n.referral_reward_text||""),Se(n.referral_cta_headline||""),Me(n.homeowner_hub_video_url||""),Be(n.branding_override||{})};N.useEffect(()=>{d(!1);const Ye=localStorage.getItem(o);if(Ye)try{const Je=JSON.parse(Ye);h(Je.nextStepText||""),f(Je.nextStepVideo||""),y(Je.inspectionDate||""),_(Je.appraisalDate||""),k(Je.welcomeMessage||""),T(Je.reviewUrl||""),I(!!Je.showPostClose),L(!!Je.notifyClient),$(!!Je.requireOnboarding),W(!!Je.allowSpouse),X(Je.visibility||n.visibility),ne(Je.stageMapping||[]),ae(Je.linkedPortalId??null),xe(Je.referralEnabled??!0),ge(Je.referralRewardText||""),Se(Je.referralCtaHeadline||""),Me(Je.homeownerHubVideoUrl||""),Be(Je.brandingOverride||{}),d(!0);return}catch{localStorage.removeItem(o)}Ne(),d(!0)},[o,n]),N.useEffect(()=>{if(!c)return;const Ye={nextStepText:u,nextStepVideo:m,inspectionDate:g,appraisalDate:x,welcomeMessage:b,reviewUrl:A,showPostClose:P,notifyClient:M,requireOnboarding:z,allowSpouse:V,visibility:G,stageMapping:te,linkedPortalId:ce,referralEnabled:he,referralRewardText:ve,referralCtaHeadline:be,homeownerHubVideoUrl:Ie,brandingOverride:Re};u!==(n.next_step_text||"")||m!==(n.next_step_video_url||"")||g!==(n.inspection_date||"")||x!==(n.appraisal_date||"")||b!==(n.welcome_message||"")||A!==(n.review_url||"")||P!==n.show_post_close_tips||M!==n.notify_client||z!==n.require_onboarding||V!==n.allow_spouse||G!==n.visibility||JSON.stringify(te)!==JSON.stringify(n.stage_mapping||[])||ce!==(n.linked_portal_id||null)||he!==(n.referral_enabled??!0)||ve!==(n.referral_reward_text||"")||be!==(n.referral_cta_headline||"")||Ie!==(n.homeowner_hub_video_url||"")||JSON.stringify(Re)!==JSON.stringify(n.branding_override||{})?localStorage.setItem(o,JSON.stringify(Ye)):localStorage.removeItem(o)},[u,m,g,x,b,A,P,M,z,V,G,te,ce,he,ve,be,Ie,Re,o,c,n]);const Ge=()=>{localStorage.removeItem(o),Ne()},Ce=async()=>{try{await a.mutateAsync({id:n.id,next_step_text:u||null,next_step_video_url:m||null,inspection_date:g||null,appraisal_date:x||null,welcome_message:b||null,review_url:A||null,show_post_close_tips:P,notify_client:M,require_onboarding:z,allow_spouse:V,visibility:G,stage_mapping:te.length>0?te:null,linked_portal_id:ce,referral_enabled:he,referral_reward_text:ve||null,referral_cta_headline:be||null,homeowner_hub_video_url:Ie||null,branding_override:Object.values(Re).some(Je=>Je!=null&&Je!=="")?Re:null});const Ye=n.linked_portal_id;ce&&ce!==Ye&&await H.from("client_portals").update({linked_portal_id:n.id}).eq("id",ce),!ce&&Ye&&await H.from("client_portals").update({linked_portal_id:null}).eq("id",Ye),localStorage.removeItem(o),ie.success("Portal settings saved"),t(!1)}catch{ie.error("Failed to save settings")}},Fe=()=>{ne([...te,{label:""}])},Ae=Ye=>{ne(te.filter((Je,Ke)=>Ke!==Ye)),me===Ye&&ue(null)},Xe=(Ye,Je,Ke)=>{const st=[...te];st[Ye]={...st[Ye],[Je]:Ke},ne(st)},$e=()=>{const Je=q4e(null).map(Ke=>({label:Ke.label,description:Ke.description,stageId:void 0}));ne(Je)};return e.jsxs(e.Fragment,{children:[e.jsx(Bs,{open:s,onOpenChange:t,children:e.jsxs(Fs,{className:"max-w-lg max-h-[85vh] flex flex-col",children:[e.jsx(qs,{children:e.jsx($s,{children:"Portal Settings"})}),e.jsxs(ya,{defaultValue:"general",className:"flex-1 overflow-hidden flex flex-col",children:[e.jsxs(va,{className:"grid grid-cols-5 shrink-0",children:[e.jsx(ls,{value:"general",children:"General"}),e.jsx(ls,{value:"timeline",children:"Timeline"}),e.jsx(ls,{value:"content",children:"Content"}),e.jsx(ls,{value:"vendors",children:"Vendors"}),e.jsx(ls,{value:"branding",children:"Branding"})]}),e.jsxs("div",{className:"flex-1 overflow-y-auto mt-4 min-h-0",children:[e.jsxs(_s,{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(re,{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(Ye=>e.jsx("button",{onClick:()=>X(Ye),className:`px-3 py-1.5 rounded-full text-xs font-medium border transition-colors ${G===Ye?"bg-primary text-primary-foreground border-primary":"bg-background text-muted-foreground border-input hover:border-primary/50"}`,children:Ye.charAt(0).toUpperCase()+Ye.slice(1)},Ye))})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(re,{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(zn,{checked:z,onCheckedChange:$})]}),z&&e.jsxs("div",{className:"flex items-center justify-between pl-4 border-l-2 border-primary/20",children:[e.jsxs("div",{children:[e.jsx(re,{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(re,{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(zn,{checked:V,onCheckedChange:W})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(re,{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(zn,{checked:P,onCheckedChange:I})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(re,{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(zn,{checked:M,onCheckedChange:L})]}),e.jsx("div",{className:"border-t pt-4",children:e.jsx(q2n,{portalId:n.id,ownerId:r,clientEmail:n.client_email,linkedPortalId:ce,onLink:ae})}),e.jsx("div",{children:e.jsx(we,{type:"date",value:g,onChange:Ye=>y(Ye.target.value),className:"mt-1"})}),e.jsxs("div",{children:[e.jsx(re,{className:"text-sm font-medium",children:"Appraisal Date"}),e.jsx(we,{type:"date",value:x,onChange:Ye=>_(Ye.target.value),className:"mt-1"})]})]}),e.jsx(_s,{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(re,{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:$e,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.'}),te.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:$e,children:"Customize journey labels"})]}),e.jsx("div",{className:"space-y-2 mt-2",children:te.map((Ye,Je)=>e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Mp,{className:"h-4 w-4 text-muted-foreground/50 flex-shrink-0"}),e.jsx(we,{value:Ye.label,onChange:Ke=>Xe(Je,"label",Ke.target.value),placeholder:`Stage ${Je+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:()=>ue(me===Je?null:Je),children:me===Je?"Less":"More"}),e.jsx(B,{variant:"ghost",size:"icon",className:"h-9 w-9 text-muted-foreground hover:text-destructive",onClick:()=>Ae(Je),children:e.jsx(qn,{className:"h-3.5 w-3.5"})})]}),me===Je&&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(re,{className:"text-xs text-muted-foreground",children:"Description"}),e.jsx("textarea",{value:Ye.description||"",onChange:Ke=>Xe(Je,"description",Ke.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(re,{className:"text-xs text-muted-foreground",children:"Video"}),Ye.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:Ye.video_url.length>40?Ye.video_url.slice(0,40)+"...":Ye.video_url}),e.jsx(B,{variant:"ghost",size:"sm",className:"h-7 text-xs text-destructive hover:text-destructive",onClick:()=>Xe(Je,"video_url",""),children:"Remove"})]}):e.jsxs("div",{className:"mt-1 flex items-center gap-1.5",children:[e.jsx(VWe,{onVideoReady:Ke=>Xe(Je,"video_url",Ke)}),e.jsx(tO,{userId:r,onSelect:Ke=>Xe(Je,"video_url",Ke),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 Ke=prompt("Paste a YouTube or Loom URL:");Ke&&Xe(Je,"video_url",Ke)},children:[e.jsx(gc,{className:"h-3 w-3"}),"Paste URL"]})]})]})]})]},Je))}),te.length>0&&e.jsxs(B,{variant:"outline",size:"sm",onClick:Fe,className:"mt-2 text-xs w-full",children:[e.jsx(nn,{className:"h-3 w-3 mr-1"})," Add Stage"]})]})}),e.jsxs(_s,{value:"content",className:"space-y-4 mt-0 px-1",children:[e.jsxs("div",{children:[e.jsx(re,{className:"text-sm font-medium",children:"Welcome Message"}),e.jsx("textarea",{value:b,onChange:Ye=>k(Ye.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(re,{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:Ye=>h(Ye.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(re,{className:"text-sm font-medium",children:"Next Step Video (optional)"}),e.jsx(we,{value:m,onChange:Ye=>f(Ye.target.value),className:"mt-1",placeholder:"YouTube or Loom URL"})]}),e.jsxs("div",{children:[e.jsx(re,{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(we,{value:A,onChange:Ye=>T(Ye.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(re,{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(re,{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(zn,{checked:he,onCheckedChange:xe})]}),he&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{children:[e.jsx(re,{className:"text-sm font-medium",children:"Headline"}),e.jsx(we,{value:be,onChange:Ye=>Se(Ye.target.value),className:"mt-1",placeholder:"Know someone buying or selling?"})]}),e.jsxs("div",{children:[e.jsx(re,{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(we,{value:ve,onChange:Ye=>ge(Ye.target.value),className:"mt-1",placeholder:"$250 gift card • Donation to your charity • Closing gift"})]}),e.jsxs("div",{children:[e.jsx(re,{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(we,{value:Ie,onChange:Ye=>Me(Ye.target.value),className:"mt-1",placeholder:"YouTube, Loom, or direct video URL"})]})]})]})]}),e.jsx(_s,{value:"vendors",className:"space-y-4 mt-0 px-1",children:e.jsx(U2n,{portalId:n.id,agentUserId:r})}),e.jsx(_s,{value:"branding",className:"space-y-4 mt-0 px-1",children:e.jsx($2n,{override:Re,onChange:Be})})]})]}),e.jsxs("div",{className:"flex justify-between gap-2 pt-4 border-t shrink-0",children:[e.jsx(B,{variant:"ghost",onClick:Ge,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:Ce,disabled:a.isPending,children:[a.isPending?e.jsx(us,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(Kl,{className:"h-4 w-4 mr-2"}),"Save Settings"]})]})]})]})}),e.jsx(L7t,{open:i,onOpenChange:l})]})}const H2n=s=>`portal-update-draft:${s}`;function GWe({open:s,onOpenChange:t,portalId:n,portalSlug:r,notifyClient:a}){const i=N.useMemo(()=>H2n(n),[n]),[l,o]=N.useState(""),[c,d]=N.useState(""),[u,h]=N.useState(""),[m,f]=N.useState(!1),[g,y]=N.useState(a??!1),[x,_]=N.useState(!1),b=jIt();N.useEffect(()=>{_(!1);const T=localStorage.getItem(i);if(T)try{const P=JSON.parse(T);o(P.title||""),d(P.content||""),h(P.videoUrl||""),f(!!P.isStageChange),y(typeof P.sendNotification=="boolean"?P.sendNotification:a??!1),_(!0);return}catch{localStorage.removeItem(i)}o(""),d(""),h(""),f(!1),y(a??!1),_(!0)},[i,a]),N.useEffect(()=>{if(!x)return;const T={title:l,content:c,videoUrl:u,isStageChange:m,sendNotification:g};l.trim()||c.trim()||u.trim()||m||g!==(a??!1)?localStorage.setItem(i,JSON.stringify(T)):localStorage.removeItem(i)},[l,c,u,m,g,x,i,a]);const k=()=>{localStorage.removeItem(i),o(""),d(""),h(""),f(!1),y(a??!1)},A=async()=>{if(l.trim())try{if(await b.mutateAsync({portal_id:n,title:l.trim(),content:c.trim()||void 0,video_url:u.trim()||void 0,is_stage_change:m}),g&&r)try{const T=j5(r);await H.functions.invoke("send-portal-notification",{body:{portal_id:n,update_title:l.trim(),update_content:c.trim()||null,portal_url:T}}),ie.success("Update posted & client notified")}catch(T){console.error("Notification failed:",T),ie.success("Update posted (notification failed to send)")}else ie.success("Update posted to portal");k(),t(!1)}catch{ie.error("Failed to post update")}};return e.jsx(Bs,{open:s,onOpenChange:t,children:e.jsxs(Fs,{className:"max-w-md",children:[e.jsx(qs,{children:e.jsx($s,{children:"Post Portal Update"})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(re,{className:"text-sm font-medium",children:"Title *"}),e.jsx(we,{value:l,onChange:T=>o(T.target.value),className:"mt-1",placeholder:"Inspection cleared!"})]}),e.jsxs("div",{children:[e.jsx(re,{className:"text-sm font-medium",children:"Message"}),e.jsx("textarea",{value:c,onChange:T=>d(T.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(re,{className:"text-sm font-medium",children:"Video URL (optional)"}),e.jsxs("div",{className:"relative mt-1",children:[e.jsx(we,{value:u,onChange:T=>h(T.target.value),className:"pl-9",placeholder:"YouTube or Loom link"}),e.jsx(na,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"})]})]}),e.jsxs("div",{className:"flex items-center gap-3 flex-wrap",children:[e.jsx("button",{type:"button",onClick:()=>f(!m),className:`px-3 py-1.5 rounded-full text-xs font-medium border transition-colors ${m?"bg-emerald-500/10 text-emerald-700 border-emerald-200":"bg-background text-muted-foreground border-input"}`,children:"📊 Stage Change"}),e.jsxs("button",{type:"button",onClick:()=>y(!g),className:`px-3 py-1.5 rounded-full text-xs font-medium border transition-colors flex items-center gap-1.5 ${g?"bg-blue-500/10 text-blue-700 border-blue-200":"bg-background text-muted-foreground border-input"}`,children:[g?e.jsx(yg,{className:"h-3 w-3"}):e.jsx(d5,{className:"h-3 w-3"}),g?"Notify Client":"No Notification"]})]})]}),e.jsxs("div",{className:"flex justify-between gap-2 pt-2",children:[e.jsx(B,{variant:"ghost",onClick:k,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:A,disabled:!l.trim()||b.isPending,children:[b.isPending?e.jsx(us,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(Rr,{className:"h-4 w-4 mr-2"}),"Post Update"]})]})]})]})})}function WWe({open:s,onOpenChange:t,portal:n,dealName:r}){const a=VU(),{isGmailConnected:i,gmailEmail:l}=_f(),[o,c]=N.useState(n.client_name||""),[d,u]=N.useState(n.client_email||""),[h,m]=N.useState(!1),[f,g]=N.useState(!1),y=j5(n.slug),x=o.split(" ")[0]||"there",_=`Your Transaction Portal – ${r}`,b=`Hi ${x}, 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!`,k=()=>{navigator.clipboard.writeText(y),g(!0),setTimeout(()=>g(!1),2e3),ie.success("Portal link copied!")},A=async()=>{if(!d.trim()){ie.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:P}=await H.functions.invoke("gmail-send",{body:{to:d,subject:_,body:b.replace(/\n/g,"
")}});if(P){let I="";try{const M=P==null?void 0:P.context;if(M&&typeof M.json=="function"){const L=await M.json();I=(L==null?void 0:L.message)||(L==null?void 0:L.error)||""}}catch{}throw new Error(I||P.message||"Failed to send invite")}ie.success(`Invite sent to ${d}`),t(!1)}catch(P){ie.error(P.message||"Failed to send invite")}finally{m(!1)}},T=()=>{const P=encodeURIComponent(_),I=encodeURIComponent(b);window.open(`mailto:${d}?subject=${P}&body=${I}`,"_blank"),a.mutateAsync({id:n.id,client_name:o||null,client_email:d||null,invite_sent_at:new Date().toISOString(),invite_method:"email"}).catch(()=>{})};return e.jsx(Bs,{open:s,onOpenChange:t,children:e.jsxs(Fs,{className:"max-w-md",children:[e.jsx(qs,{children:e.jsx($s,{children:"Invite Client to Portal"})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(re,{className:"text-sm font-medium",children:"Client Name"}),e.jsx(we,{value:o,onChange:P=>c(P.target.value),className:"mt-1",placeholder:"John Doe"})]}),e.jsxs("div",{children:[e.jsx(re,{className:"text-sm font-medium",children:"Client Email"}),e.jsx(we,{type:"email",value:d,onChange:P=>u(P.target.value),className:"mt-1",placeholder:"john@example.com"})]}),e.jsxs("div",{children:[e.jsx(re,{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:k,className:"shrink-0",children:f?e.jsx(pa,{className:"h-4 w-4 text-emerald-600"}):e.jsx(Pa,{className:"h-4 w-4"})})]})]}),e.jsxs("div",{className:"space-y-2 pt-2 border-t",children:[i?e.jsxs(B,{onClick:A,disabled:h||!d.trim(),className:"w-full",children:[h?e.jsx(us,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(mn,{className:"h-4 w-4 mr-2"}),"Send via Gmail (",l,")"]}):e.jsxs(B,{onClick:T,disabled:!d.trim(),className:"w-full",variant:"outline",children:[e.jsx(Tr,{className:"h-4 w-4 mr-2"}),"Open in Email App"]}),e.jsxs(B,{variant:"ghost",onClick:k,className:"w-full text-muted-foreground",children:[e.jsx(Pa,{className:"h-4 w-4 mr-2"}),"Just Copy Link"]})]})]})]})})}function G2n({deal:s}){const{isAdmin:t,user:n}=Ls(),{data:r,isLoading:a}=Xpn(s.id),i=mGe(),l=VU(),[o,c]=N.useState(!1),[d,u]=N.useState(!1),[h,m]=N.useState(!1),[f,g]=N.useState(!1),y=`portal-management-ui:${s.id}`;if(N.useEffect(()=>{const P=sessionStorage.getItem(y);if(P)try{const I=JSON.parse(P);u(!!I.settingsOpen),m(!!I.composerOpen),g(!!I.inviteOpen)}catch{sessionStorage.removeItem(y)}},[y]),N.useEffect(()=>{d||h||f?sessionStorage.setItem(y,JSON.stringify({settingsOpen:d,composerOpen:h,inviteOpen:f})):sessionStorage.removeItem(y)},[d,h,f,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(Cn,{className:"h-4 w-4 text-primary"}),e.jsx("span",{className:"font-medium text-sm",children:"Client Portal"}),e.jsx(us,{className:"h-3 w-3 animate-spin ml-auto"})]})});const x=async()=>{var P,I;c(!0);try{await i.mutateAsync({deal_id:s.id,visibility:"private",require_onboarding:!0,client_name:s.contact?`${s.contact.first_name} ${s.contact.last_name}`:void 0,client_email:((P=s.contact)==null?void 0:P.email)||void 0,client_phone:((I=s.contact)==null?void 0:I.phone)||void 0}),ie.success("Client portal enabled!")}catch{ie.error("Failed to create portal")}finally{c(!1)}},_=async P=>{if(r)try{await l.mutateAsync({id:r.id,is_enabled:P}),ie.success(P?"Portal enabled":"Portal disabled")}catch{ie.error("Failed to update portal")}},b=()=>{if(!r)return;const P=j5(r.slug);navigator.clipboard.writeText(P),ie.success("Portal link copied!")},k=()=>{if(!r)return;const P=j5(r.slug);window.open(P,"_blank")};if(!r)return e.jsxs("div",{className:"border rounded-lg p-4 border-dashed",children:[e.jsx("div",{className:"flex items-center justify-between mb-3",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Cn,{className:"h-4 w-4 text-primary"}),e.jsx("span",{className:"font-medium text-sm",children:"Client Portal"})]})}),e.jsx("p",{className:"text-xs text-muted-foreground mb-3",children:"Create a beautiful portal so your client can track their deal progress in real-time."}),e.jsxs(B,{onClick:x,disabled:o,size:"sm",className:"w-full",children:[o?e.jsx(us,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(Cn,{className:"h-4 w-4 mr-2"}),"Enable Client Portal"]})]});const A=j5(r.slug),T=(n==null?void 0:n.id)||"";return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"border rounded-lg p-4",children:[e.jsxs("div",{className:"flex items-center justify-between mb-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Cn,{className:"h-4 w-4 text-primary"}),e.jsx("span",{className:"font-medium text-sm",children:"Client Portal"}),e.jsx(We,{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(zn,{checked:r.is_enabled,onCheckedChange:_})]}),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(We,{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:A})}),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(Pa,{className:"h-3 w-3 mr-1 shrink-0"}),e.jsx("span",{className:"truncate",children:"Copy"})]}),e.jsxs(B,{variant:"outline",size:"sm",onClick:k,className:"text-xs w-full min-w-0 px-2",children:[e.jsx(Tr,{className:"h-3 w-3 mr-1 shrink-0"}),e.jsx("span",{className:"truncate",children:"Preview"})]}),e.jsxs(B,{variant:"outline",size:"sm",onClick:()=>g(!0),className:"text-xs w-full min-w-0 px-2",children:[e.jsx(Rr,{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(Qk,{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(sc,{className:"h-3 w-3 mr-1 shrink-0"}),e.jsx("span",{className:"truncate",children:"Settings"})]})]}),e.jsxs(cr,{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(Io,{className:"h-3 w-3"}),"View incoming referrals"]})]}),e.jsx(HWe,{open:d,onOpenChange:u,portal:r,dealOwnerId:T}),e.jsx(GWe,{open:h,onOpenChange:m,portalId:r.id,portalSlug:r.slug,notifyClient:r.notify_client}),e.jsx(WWe,{open:f,onOpenChange:g,portal:r,dealName:s.deal_name})]})}const W2n=["Client","Co-Buyer","Co-Seller","Spouse","Lender","Title Company","Inspector","Appraiser","Attorney","Contractor","Other"];function K2n(s){return mt({queryKey:["deal-contacts",s],queryFn:async()=>{const{data:t,error:n}=await H.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 Y2n(){const s=as();return _t({mutationFn:async({dealId:t,contactId:n,role:r})=>{const{data:a,error:i}=await H.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]}),ie.success("Contact linked to deal")},onError:t=>{var n;(n=t.message)!=null&&n.includes("duplicate")?ie.error("This contact is already linked to this deal"):ie.error("Failed to link contact")}})}function Z2n(){const s=as();return _t({mutationFn:async({id:t,dealId:n})=>{const{error:r}=await H.from("deal_contacts").delete().eq("id",t);if(r)throw r},onSuccess:(t,n)=>{s.invalidateQueries({queryKey:["deal-contacts",n.dealId]}),ie.success("Contact removed from deal")},onError:()=>{ie.error("Failed to remove contact")}})}function X2n({dealId:s,primaryContactId:t}){const n=tr(),{data:r,isLoading:a}=K2n(s),{data:i}=Wy(),l=Y2n(),o=Z2n(),[c,d]=N.useState(!1),[u,h]=N.useState(""),[m,f]=N.useState("Client"),g=new Set((r==null?void 0:r.map(k=>k.contact_id))||[]);t&&g.add(t);const y=i==null?void 0:i.filter(k=>{var T,P,I;if(g.has(k.id))return!1;if(!u.trim())return!0;const A=u.toLowerCase();return((T=k.first_name)==null?void 0:T.toLowerCase().includes(A))||((P=k.last_name)==null?void 0:P.toLowerCase().includes(A))||((I=k.email)==null?void 0:I.toLowerCase().includes(A))}).slice(0,8),x=k=>{l.mutate({dealId:s,contactId:k,role:m}),d(!1),h("")},_=k=>{o.mutate({id:k,dealId:s})},b={Client:"bg-primary/10 text-primary","Co-Buyer":"bg-blue-500/10 text-blue-600","Co-Seller":"bg-emerald-500/10 text-emerald-600",Spouse:"bg-pink-500/10 text-pink-600",Lender:"bg-amber-500/10 text-amber-600","Title Company":"bg-purple-500/10 text-purple-600",Inspector:"bg-orange-500/10 text-orange-600",Appraiser:"bg-cyan-500/10 text-cyan-600",Attorney:"bg-slate-500/10 text-slate-600",Contractor:"bg-lime-500/10 text-lime-600",Other:"bg-muted text-muted-foreground"};return!(r!=null&&r.length)&&!c?e.jsxs("div",{className:"space-y-2",children:[e.jsx("div",{className:"flex items-center justify-between",children:e.jsxs("h4",{className:"text-sm font-medium flex items-center gap-2",children:[e.jsx(Yn,{className:"h-4 w-4"}),"Additional Contacts"]})}),e.jsxs(rc,{open:c,onOpenChange:d,children:[e.jsx(ac,{asChild:!0,children:e.jsxs(B,{variant:"outline",size:"sm",className:"w-full text-muted-foreground",children:[e.jsx(nn,{className:"h-3.5 w-3.5 mr-1"}),"Link a contact (lender, spouse, vendor...)"]})}),e.jsx(Zl,{className:"w-80 p-3",align:"start",children:e.jsx(Rft,{search:u,setSearch:h,selectedRole:m,setSelectedRole:f,filteredContacts:y,onAdd:x})})]})]}):e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("h4",{className:"text-sm font-medium flex items-center gap-2",children:[e.jsx(Yn,{className:"h-4 w-4"}),"Linked Contacts",r&&r.length>0&&e.jsx(We,{variant:"secondary",className:"text-[10px] px-1.5",children:r.length})]}),e.jsxs(rc,{open:c,onOpenChange:d,children:[e.jsx(ac,{asChild:!0,children:e.jsx(B,{variant:"ghost",size:"sm",className:"h-7 px-2",children:e.jsx(nn,{className:"h-3.5 w-3.5"})})}),e.jsx(Zl,{className:"w-80 p-3",align:"end",children:e.jsx(Rft,{search:u,setSearch:h,selectedRole:m,setSelectedRole:f,filteredContacts:y,onAdd:x})})]})]}),e.jsx("div",{className:"space-y-1.5",children:r==null?void 0:r.map(k=>{var A,T,P,I,M,L,z,$;return e.jsxs("div",{className:"flex items-center gap-2 p-2 rounded-md bg-muted/40 group",children:[e.jsx(Ua,{className:"h-7 w-7",children:e.jsxs(qa,{className:"text-[10px] bg-primary/10 text-primary",children:[(T=(A=k.contact)==null?void 0:A.first_name)==null?void 0:T[0],(I=(P=k.contact)==null?void 0:P.last_name)==null?void 0:I[0]]})}),e.jsx("div",{className:"flex-1 min-w-0",children:e.jsxs("button",{onClick:()=>n(`/mission-control/contacts/${k.contact_id}`),className:"text-sm font-medium hover:underline text-primary truncate block",children:[(M=k.contact)==null?void 0:M.first_name," ",(L=k.contact)==null?void 0:L.last_name]})}),e.jsx(We,{variant:"outline",className:`text-[10px] px-1.5 py-0 shrink-0 ${b[k.role]||b.Other}`,children:k.role}),e.jsxs("div",{className:"flex gap-0.5 opacity-0 group-hover:opacity-100 transition-opacity",children:[((z=k.contact)==null?void 0:z.phone)&&e.jsx(B,{variant:"ghost",size:"icon",className:"h-6 w-6",asChild:!0,children:e.jsx("a",{href:`tel:${k.contact.phone}`,children:e.jsx(ga,{className:"h-3 w-3"})})}),(($=k.contact)==null?void 0:$.email)&&e.jsx(B,{variant:"ghost",size:"icon",className:"h-6 w-6",asChild:!0,children:e.jsx("a",{href:`mailto:${k.contact.email}`,children:e.jsx(mn,{className:"h-3 w-3"})})}),e.jsx(B,{variant:"ghost",size:"icon",className:"h-6 w-6 text-destructive",onClick:()=>_(k.id),children:e.jsx(qn,{className:"h-3 w-3"})})]})]},k.id)})})]})}function Rft({search:s,setSearch:t,selectedRole:n,setSelectedRole:r,filteredContacts:a,onAdd:i}){return e.jsxs("div",{className:"space-y-3",children:[e.jsxs(Ns,{value:n,onValueChange:r,children:[e.jsx(ws,{className:"h-8 text-sm",children:e.jsx(ks,{placeholder:"Role"})}),e.jsx(js,{children:W2n.map(l=>e.jsx(nt,{value:l,children:l},l))})]}),e.jsxs("div",{className:"relative",children:[e.jsx(Gr,{className:"absolute left-2 top-2.5 h-3.5 w-3.5 text-muted-foreground"}),e.jsx(we,{value:s,onChange:l=>t(l.target.value),placeholder:"Search contacts...",className:"pl-7 h-8 text-sm",autoFocus:!0})]}),e.jsx(lo,{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 jG=[{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"}],Q2n=[{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 J2n(){const s=as();return _t({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 H.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 eNn(){const s=as();return _t({mutationFn:async({dealId:t,completed:n})=>{const{error:r}=await H.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 tNn(){return mt({queryKey:["tc-playbooks"],queryFn:async()=>{const{data:s,error:t}=await H.from("tc_playbooks").select("*").eq("is_active",!0).order("sort_order");if(t)throw t;const{data:n,error:r}=await H.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 sNn(){const s=Ya(),t=as();return _t({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([H.from("deal_pipeline").select("*").eq("id",r).single(),H.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 H.from("deal_tasks").select("title").eq("deal_id",r),d=new Set((c||[]).map(g=>String(g.title).toLowerCase())),u=a,h=(g,y)=>{const x=g==="stage_entry"?null:u[g],_=x?new Date(`${x}T12:00:00`):new Date;return _.setDate(_.getDate()+(y||0)),_.toISOString().split("T")[0]},m=l.filter(g=>!d.has(String(g.title).toLowerCase())).map((g,y)=>({owner_user_id:s,deal_id:r,contact_id:u.contact_id,stage_id:u.stage_id,title:g.title,description:g.description,priority:g.priority,status:"todo",due_date:h(g.due_anchor,g.due_offset_days),sort_order:y}));if(m.length===0)return 0;const{error:f}=await H.from("deal_tasks").insert(m);if(f)throw f;return m.length},onSuccess:()=>{t.invalidateQueries({queryKey:["deal-tasks"]}),t.invalidateQueries({queryKey:["tc-dashboard"]})}})}function nNn(){const s=Ya(),t=as();return _t({mutationFn:async({playbookId:n,stageId:r})=>{if(!s)throw new Error("Not authenticated");const[{data:a},{data:i,error:l}]=await Promise.all([H.from("tc_playbooks").select("deal_type").eq("id",n).single(),H.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 H.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 H.from("deal_task_templates").insert(d);if(u)throw u;return d.length},onSuccess:()=>{t.invalidateQueries({queryKey:["deal-task-templates"]})}})}function rNn(){const s=Ya();return mt({queryKey:["tc-dashboard",s],queryFn:async()=>{if(!s)return[];const{data:t,error:n}=await H.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 H.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 KWe(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 vk(s){const t=KWe(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 aNn(s){return s===null?"none":s<0?"overdue":s===0?"today":s<=3?"soon":"upcoming"}const iNn={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 oNn(s){const t=KWe(s);return t?t.toLocaleDateString("en-US",{month:"short",day:"numeric"}):null}function Oft(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 lNn({deal:s,compact:t=!1}){const n=J2n(),r=eNn(),[a,i]=N.useState(!1),[l,o]=N.useState({}),c=Array.isArray(s==null?void 0:s.completed_key_dates)?s.completed_key_dates:[],[d,u]=N.useState(c),h=c.join(","),m=N.useRef(h);N.useEffect(()=>{m.current!==h&&(m.current=h,u(c))},[h]);const f=d,g=()=>{const L={};jG.forEach(z=>{L[z.key]=(s==null?void 0:s[z.key])??""}),o(L),i(!0)},y=async()=>{try{await n.mutateAsync({dealId:s.id,dates:l}),ie.success("Transaction dates updated"),i(!1)}catch(L){ie.error((L==null?void 0:L.message)||"Could not save dates")}},x=async(L,z)=>{const $=f;u(L);try{await r.mutateAsync({dealId:s.id,completed:L}),ie.success(z)}catch(V){u($),ie.error((V==null?void 0:V.message)||"Could not update milestone")}},_=N.useMemo(()=>jG.map(L=>{const z=(s==null?void 0:s[L.key])??null,$=vk(z),V=f.includes(L.key),W=z?V?"done":aNn($):"none";return{...L,value:z,days:$,isDone:V,state:W}}),[s,f.join(",")]),b=_.filter(L=>L.value).length,k=_.filter(L=>L.state==="done").length,A=vk(s==null?void 0:s.target_close_date),T=_.filter(L=>L.value&&!L.isDone&&L.days!==null&&L.days>=0).sort((L,z)=>(L.days??0)-(z.days??0))[0],P=_.filter(L=>L.state==="overdue"),I=()=>{const L=Array.from(new Set([...f,...P.map(z=>z.key)]));x(L,"Past milestones marked complete")},M=(L,z)=>{const $=z?f.filter(V=>V!==L):[...f,L];x($,z?"Marked as not complete":"Milestone completed")};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(df,{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:A!==null?A>=0?`${A} day${A===1?"":"s"} to closing · ${k}/${b} milestones done`:`Closing was ${Math.abs(A)} day${Math.abs(A)===1?"":"s"} ago`:`${b} of ${jG.length} key dates set`})]})]}),e.jsxs(rc,{open:a,onOpenChange:L=>L?g():i(!1),children:[e.jsx(ac,{asChild:!0,children:e.jsxs(B,{variant:"outline",size:"sm",className:"shrink-0 gap-1.5",children:[e.jsx(Ja,{className:"h-3.5 w-3.5"}),t?"":"Edit dates"]})}),e.jsxs(Zl,{className:"w-80 p-4 max-h-[70vh] overflow-y-auto",align:"end",children:[e.jsx("p",{className:"text-sm font-semibold mb-3",children:"Key transaction dates"}),e.jsx("div",{className:"space-y-3",children:jG.map(L=>e.jsxs("div",{className:"space-y-1",children:[e.jsx(re,{htmlFor:`kd-${L.key}`,className:"text-xs text-muted-foreground",children:L.label}),e.jsx(we,{id:`kd-${L.key}`,type:"date",value:l[L.key]??"",onChange:z=>o($=>({...$,[L.key]:z.target.value})),className:"h-9"})]},L.key))}),e.jsxs("div",{className:"flex justify-end gap-2 mt-4",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(us,{className:"h-3.5 w-3.5 mr-1 animate-spin"}):e.jsx(pa,{className:"h-3.5 w-3.5 mr-1"}),"Save"]})]})]})]})]}),e.jsxs("div",{className:"p-3",children:[e.jsx("div",{className:"grid grid-cols-3 sm:grid-cols-3 gap-2",children:_.map(L=>{const z=!!L.value;return e.jsxs(wu,{children:[e.jsx(ju,{asChild:!0,children:e.jsxs("button",{type:"button",disabled:!z||r.isPending,onClick:()=>z&&M(L.key,L.isDone),className:Ot("relative text-left rounded-lg border px-2.5 py-2 transition-colors w-full",iNn[L.state],z&&"hover:brightness-105 cursor-pointer"),children:[e.jsx("p",{className:"text-[10px] uppercase tracking-wide opacity-70 truncate pr-4",children:L.short}),e.jsx("p",{className:"text-sm font-semibold leading-tight truncate",children:oNn(L.value)??"—"}),L.value&&e.jsx("p",{className:"text-[10px] opacity-80 truncate",children:Oft(L.state,L.days)}),z&&e.jsx("span",{className:Ot("absolute top-1.5 right-1.5 h-4 w-4 rounded-full border flex items-center justify-center",L.isDone?"bg-emerald-500 border-emerald-500 text-white":"border-current opacity-40"),children:L.isDone&&e.jsx(pa,{className:"h-2.5 w-2.5"})})]})}),e.jsx(nu,{side:"top",children:L.value?L.isDone?`${L.label} completed — click to reopen`:`Click to mark ${L.label} complete`:`${L.label} — not set`})]},L.key)})}),(P.length>0||T||k>0)&&e.jsxs("div",{className:"mt-3 flex flex-wrap items-center gap-2 text-xs",children:[k>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(oD,{className:"h-3 w-3"}),k," completed"]}),P.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(xd,{className:"h-3 w-3"}),P.length," awaiting confirmation"]}),T&&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: ",T.label," · ",Oft(T.state,T.days)]}),P.length>0&&e.jsxs("button",{type:"button",onClick:I,disabled:r.isPending,className:"ml-auto inline-flex items-center gap-1 rounded-full border px-2.5 py-1 font-medium hover:bg-muted transition-colors",children:[e.jsx(oD,{className:"h-3 w-3"}),"Mark past dates complete"]})]}),P.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 cNn={Home:_a,FileSignature:WC,Handshake:Y2,CalendarClock:df,Sparkles:Cn,ClipboardCheck:e3},dNn={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 uNn(s,t){var a;const n=((a=Q2n.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 P7t({open:s,onOpenChange:t,dealId:n,dealName:r}){const{data:a,isLoading:i}=tNn(),{data:l}=PJ(),o=sNn(),c=nNn(),[d,u]=N.useState(null),[h,m]=N.useState({}),f=x=>{if(h[x.id])return h[x.id];const _=l==null?void 0:l.find(b=>{var k,A;return((k=b.name)==null?void 0:k.toLowerCase())===((A=x.target_stage_name)==null?void 0:A.toLowerCase())});return(_==null?void 0:_.id)??""},g=async x=>{if(n){u(x.id);try{const _=await o.mutateAsync({playbookId:x.id,dealId:n});ie.success(_>0?`Added ${_} task${_===1?"":"s"} to this deal`:"All tasks already exist on this deal"),_>0&&t(!1)}catch(_){ie.error((_==null?void 0:_.message)||"Could not apply playbook")}finally{u(null)}}},y=async x=>{const _=f(x);if(!_){ie.error("Pick which stage this playbook should trigger on");return}u(`install-${x.id}`);try{const b=await c.mutateAsync({playbookId:x.id,stageId:_});ie.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){ie.error((b==null?void 0:b.message)||"Could not automate playbook")}finally{u(null)}};return e.jsx(Bs,{open:s,onOpenChange:t,children:e.jsxs(Fs,{className:"sm:max-w-2xl max-h-[85vh] flex flex-col p-0",children:[e.jsx(qs,{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(Ep,{className:"h-4.5 w-4.5 text-primary"})}),e.jsxs("div",{children:[e.jsx($s,{children:"Transaction Playbooks"}),e.jsx(Ar,{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(lo,{className:"flex-1",children:e.jsx("div",{className:"p-6 pt-4",children:i?e.jsx("div",{className:"flex justify-center py-12",children:e.jsx(us,{className:"h-6 w-6 animate-spin text-muted-foreground"})}):e.jsx(qR,{type:"single",collapsible:!0,className:"space-y-3",children:(a||[]).map(x=>{const _=cNn[x.icon||"ClipboardCheck"]||e3,b=x.accent_color||"hsl(var(--primary))";return e.jsxs($E,{value:x.id,className:"border rounded-xl px-0 overflow-hidden bg-card",children:[e.jsx(UE,{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(_,{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:x.name}),e.jsxs(We,{variant:"secondary",className:"text-[10px]",children:[x.tasks.length," steps"]}),x.deal_type&&e.jsx(We,{variant:"outline",className:"text-[10px] capitalize",children:x.deal_type})]}),e.jsx("p",{className:"text-xs text-muted-foreground mt-0.5 line-clamp-1",children:x.description})]})]})}),e.jsxs(qE,{className:"px-4 pb-4",children:[e.jsx("div",{className:"space-y-1.5 mb-4",children:x.tasks.map((k,A)=>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:A+1}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("p",{className:"text-sm font-medium leading-tight",children:k.title}),k.description&&e.jsx("p",{className:"text-xs text-muted-foreground mt-0.5",children:k.description}),e.jsx("p",{className:"text-[11px] text-muted-foreground mt-1",children:uNn(k.due_anchor,k.due_offset_days)})]}),e.jsx("span",{className:Ot("text-[10px] px-1.5 py-0.5 rounded-full shrink-0 capitalize",dNn[k.priority]),children:k.priority})]},k.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:()=>g(x),disabled:d===x.id,children:[d===x.id?e.jsx(us,{className:"h-3.5 w-3.5 animate-spin"}):e.jsx(ff,{className:"h-3.5 w-3.5"}),"Add to this deal"]}),e.jsxs("div",{className:"flex gap-2 flex-1",children:[e.jsxs(Ns,{value:f(x),onValueChange:k=>m(A=>({...A,[x.id]:k})),children:[e.jsx(ws,{className:"h-9 text-xs flex-1",children:e.jsx(ks,{placeholder:"Trigger stage"})}),e.jsx(js,{children:(l||[]).map(k=>e.jsx(nt,{value:k.id,children:k.name},k.id))})]}),e.jsxs(B,{size:"sm",variant:"outline",className:"gap-1.5 shrink-0",onClick:()=>y(x),disabled:d===`install-${x.id}`,children:[d===`install-${x.id}`?e.jsx(us,{className:"h-3.5 w-3.5 animate-spin"}):e.jsx(S9,{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(Hr,{className:"h-3 w-3"}),"Automating adds these steps to every future deal that reaches that stage."]})]})]},x.id)})})})})]})})}const hNn={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"}},mNn={note:xo,call:ga,email:mn,meeting:ta,stage_change:Tr,task_completed:Hr,document:_a,system:Xr};function pNn({deal:s,open:t,onOpenChange:n,onEdit:r,onAddToScorecard:a,isWonStage:i}){var Re,Be;const l=tr(),{data:o,isLoading:c}=Pjn((s==null?void 0:s.id)||""),{data:d,isLoading:u}=Djn((s==null?void 0:s.id)||""),h=Ijn(),m=Ojn(),f=Rjn(),g=Ljn(),{data:y,isLoading:x}=R2n((s==null?void 0:s.id)||""),_=O2n(),b=F2n(),k=z2n(),A=N.useRef(null),[T,P]=N.useState(""),[I,M]=N.useState(""),[L,z]=N.useState(!1),[$,V]=N.useState(!1),[W,G]=N.useState(!1);if(!s)return null;const X=hNn[s.deal_type],te=(()=>{var Ce;if(s.deal_type!=="seller"&&s.deal_type!=="dual")return null;const Ne=((Ce=s.listing)==null?void 0:Ce.created_at)||s.listing_date;if(!Ne)return null;const Ge=s.contract_date?Tc(s.contract_date):new Date;return wj(Ge,Tc(Ne))})(),ne=Ne=>Ne?new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:0}).format(Ne):"-",me=async()=>{if(T.trim())try{await h.mutateAsync({deal_id:s.id,activity_type:"note",title:"Note added",description:T}),P(""),ie.success("Note added")}catch{ie.error("Failed to add note")}},ue=async()=>{if(I.trim())try{await m.mutateAsync({deal_id:s.id,title:I,sort_order:((d==null?void 0:d.length)||0)+1}),M(""),ie.success("Task added")}catch{ie.error("Failed to add task")}},ce=async(Ne,Ge)=>{try{await f.mutateAsync({id:Ne,is_completed:Ge,deal_id:s.id})}catch{ie.error("Failed to update task")}},ae=async()=>{try{await g.mutateAsync(s.id),ie.success("Deal deleted"),n(!1)}catch{ie.error("Failed to delete deal")}},he=(d==null?void 0:d.filter(Ne=>Ne.is_completed).length)||0,xe=(d==null?void 0:d.length)||0,ve=(y==null?void 0:y.length)||0,ge=Ne=>Ne<1024?`${Ne} B`:Ne<1024*1024?`${(Ne/1024).toFixed(1)} KB`:`${(Ne/(1024*1024)).toFixed(1)} MB`,be=Ne=>Ne?Ne.startsWith("image/")?pc:Ne.includes("pdf")?Wr:u9:u9,Se=async Ne=>{const Ge=Ne.target.files;if(!(!Ge||!s)){G(!0);try{for(const Ce of Array.from(Ge)){if(Ce.size>20*1024*1024){ie.error(`${Ce.name} exceeds 20MB limit`);continue}await _.mutateAsync({dealId:s.id,file:Ce})}ie.success("File(s) uploaded")}catch{ie.error("Failed to upload file")}finally{G(!1),A.current&&(A.current.value="")}}},Ie=async(Ne,Ge)=>{if(s)try{await b.mutateAsync({fileId:Ne,storagePath:Ge,dealId:s.id}),ie.success("File deleted")}catch{ie.error("Failed to delete file")}},Me=async(Ne,Ge)=>{try{const Ce=await B2n(Ne),Fe=document.createElement("a");Fe.href=Ce,Fe.download=Ge,Fe.target="_blank",document.body.appendChild(Fe),Fe.click(),document.body.removeChild(Fe)}catch{ie.error("Failed to download file")}};return e.jsxs(e.Fragment,{children:[e.jsx(l1,{open:t,onOpenChange:n,children:e.jsxs(Gy,{className:"w-full sm:max-w-xl p-0 flex flex-col",children:[e.jsx(gb,{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(We,{variant:"outline",className:Ot("text-xs",X.color),children:X.label}),e.jsxs(We,{variant:"secondary",className:"text-xs capitalize",children:[s.priority," priority"]})]}),e.jsx(xb,{className:"text-xl",children:s.deal_name}),e.jsx("div",{className:"mt-2",children:e.jsx(D2n,{dealId:s.id})})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(B,{variant:"outline",size:"icon",onClick:()=>r(s),children:e.jsx(xp,{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(qn,{className:"h-4 w-4"})})]})]})}),e.jsx(lo,{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(Ua,{className:"h-10 w-10",children:e.jsxs(qa,{className:"bg-primary/10 text-primary",children:[(Re=s.contact.first_name)==null?void 0:Re[0],(Be=s.contact.last_name)==null?void 0:Be[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(ga,{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(mn,{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(Tr,{className:"h-4 w-4"})})]})]}),e.jsx(X2n,{dealId:s.id,primaryContactId:s.contact_id}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[(s.property_address||s.city)&&e.jsxs("div",{className:"col-span-2 flex items-start gap-2 text-sm",children:[e.jsx(_a,{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:ne(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:ne(s.expected_commission)})]}),(s.brokerage_split_pct||s.team_split_pct||s.referral_fee_pct||s.franchise_fee_pct||s.transaction_fee)&&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?` (${ne(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:ne(s.transaction_fee)})]}),s.net_commission!=null&&e.jsx(e.Fragment,{children: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:ne(s.net_commission)})]})})})]}),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(gl,{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(Hr,{className:"h-4 w-4 text-green-600"}),e.jsx("span",{children:"Synced to Scorecard"})]}),te!==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:Ot("text-lg font-bold",te>90?"text-red-600":te>60?"text-amber-600":"text-foreground"),children:[te," ",s.contract_date?"(final)":"days"]})]}),s.target_close_date&&e.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[e.jsx(ta,{className:"h-4 w-4 text-muted-foreground"}),e.jsxs("span",{children:["Close: ",Js(Tc(s.target_close_date),"MMM d, yyyy")]})]}),e.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[e.jsx(Ed,{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(lNn,{deal:s}),e.jsx(G2n,{deal:s}),e.jsxs(ya,{defaultValue:"tasks",className:"w-full",children:[e.jsxs(va,{className:"w-full grid grid-cols-3",children:[e.jsxs(ls,{value:"tasks",className:"gap-1",children:[e.jsx(Hr,{className:"h-4 w-4"}),"Tasks ",xe>0&&`(${he}/${xe})`]}),e.jsxs(ls,{value:"files",className:"gap-1",children:[e.jsx(LT,{className:"h-4 w-4"}),"Files ",ve>0&&`(${ve})`]}),e.jsxs(ls,{value:"activity",className:"gap-1",children:[e.jsx(Xr,{className:"h-4 w-4"}),"Activity"]})]}),e.jsxs(_s,{value:"tasks",className:"mt-4 space-y-3",children:[e.jsxs("div",{className:"flex gap-2",children:[e.jsx(we,{placeholder:"Add a new task...",value:I,onChange:Ne=>M(Ne.target.value),onKeyDown:Ne=>Ne.key==="Enter"&&ue()}),e.jsx(B,{onClick:ue,disabled:!I.trim(),children:e.jsx(nn,{className:"h-4 w-4"})}),e.jsxs(B,{variant:"outline",className:"gap-1.5 shrink-0",onClick:()=>z(!0),children:[e.jsx(Ep,{className:"h-4 w-4"}),"Playbooks"]})]}),e.jsxs("div",{className:"space-y-2",children:[d==null?void 0:d.map(Ne=>e.jsxs("div",{className:Ot("flex items-center gap-3 p-3 rounded-lg border transition-colors",Ne.is_completed?"bg-muted/50 border-border":"bg-background"),children:[e.jsx(Bi,{checked:Ne.is_completed,onCheckedChange:Ge=>ce(Ne.id,!!Ge)}),e.jsx("span",{className:Ot("flex-1 text-sm",Ne.is_completed&&"line-through text-muted-foreground"),children:Ne.title}),Ne.due_date&&e.jsx("span",{className:"text-xs text-muted-foreground",children:Js(new Date(Ne.due_date),"MMM d")})]},Ne.id)),(d==null?void 0:d.length)===0&&e.jsx("p",{className:"text-center text-muted-foreground text-sm py-4",children:"No tasks yet. Add one above!"})]})]}),e.jsxs(_s,{value:"files",className:"mt-4 space-y-3",children:[e.jsx("input",{type:"file",ref:A,className:"hidden",multiple:!0,onChange:Se,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 Ne;return(Ne=A.current)==null?void 0:Ne.click()},disabled:W,children:[W?e.jsx(us,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(ni,{className:"h-4 w-4 mr-2"}),W?"Uploading...":"Upload Files"]}),e.jsxs("div",{className:"space-y-2",children:[y==null?void 0:y.map(Ne=>{const Ge=be(Ne.file_type);return e.jsxs("div",{className:"flex items-center gap-3 p-3 rounded-lg border bg-background",children:[e.jsx("div",{className:"w-8 h-8 rounded bg-muted flex items-center justify-center shrink-0",children:e.jsx(Ge,{className:"h-4 w-4 text-muted-foreground"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-sm font-medium truncate",children:Ne.file_name}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[ge(Ne.file_size)," · ",Js(new Date(Ne.created_at),"MMM d, yyyy")]})]}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(fN,{children:e.jsxs(wu,{children:[e.jsx(ju,{asChild:!0,children:e.jsx(B,{variant:"ghost",size:"icon",className:`h-8 w-8 transition-colors ${Ne.visible_on_portal?"text-primary bg-primary/10 hover:bg-primary/20":"text-muted-foreground/40 hover:text-muted-foreground"}`,onClick:()=>k.mutate({fileId:Ne.id,visible:!Ne.visible_on_portal,dealId:s.id}),children:Ne.visible_on_portal?e.jsx(da,{className:"h-4 w-4"}):e.jsx(V0,{className:"h-4 w-4"})})}),e.jsx(nu,{side:"top",children:Ne.visible_on_portal?"Visible on client portal":"Hidden from client portal"})]})}),e.jsx(B,{variant:"ghost",size:"icon",className:"h-8 w-8",onClick:()=>Me(Ne.storage_path,Ne.file_name),children:e.jsx(oi,{className:"h-4 w-4"})}),e.jsx(B,{variant:"ghost",size:"icon",className:"h-8 w-8 text-destructive hover:text-destructive",onClick:()=>Ie(Ne.id,Ne.storage_path),children:e.jsx(hr,{className:"h-4 w-4"})})]})]},Ne.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(_s,{value:"activity",className:"mt-4 space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(Ws,{placeholder:"Add a note...",value:T,onChange:Ne=>P(Ne.target.value),rows:2}),e.jsxs(B,{onClick:me,disabled:!T.trim(),size:"sm",className:"w-full",children:[e.jsx(Rr,{className:"h-4 w-4 mr-2"}),"Add Note"]})]}),e.jsxs("div",{className:"space-y-3",children:[o==null?void 0:o.map(Ne=>{const Ge=mNn[Ne.activity_type]||Xr;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(Ge,{className:"h-4 w-4 text-muted-foreground"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-sm font-medium",children:Ne.title}),Ne.description&&e.jsx("p",{className:"text-sm text-muted-foreground mt-0.5",children:Ne.description}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:nc(new Date(Ne.created_at),{addSuffix:!0})})]})]},Ne.id)}),(o==null?void 0:o.length)===0&&e.jsx("p",{className:"text-center text-muted-foreground text-sm py-4",children:"No activity yet"})]})]})]})]})})]})}),e.jsx(P7t,{open:L,onOpenChange:z,dealId:s==null?void 0:s.id,dealName:s==null?void 0:s.deal_name}),e.jsx(Fl,{open:$,onOpenChange:V,children:e.jsxs(kl,{children:[e.jsxs(Sl,{children:[e.jsx(Al,{children:"Delete Deal?"}),e.jsxs(Tl,{children:['This will permanently delete "',s.deal_name,'" and all associated data. This action cannot be undone.']})]}),e.jsxs(Cl,{children:[e.jsx(El,{children:"Cancel"}),e.jsx(wl,{onClick:ae,className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:"Delete"})]})]})})]})}function fNn({open:s,onOpenChange:t,deal:n,onComplete:r}){const a=t3e(),i=S7t(),{data:l}=$R(),{data:o}=K_(),[c,d]=N.useState({property_address:"",city:"",state:"",zip:"",transaction_type:"buyer",close_date:Js(new Date,"yyyy-MM-dd"),sale_price:0,commission_amount:0,lead_source_id:"",client_type_id:"",notes:""});N.useEffect(()=>{if(n&&s){const m=n.deal_type==="seller"?"seller":"buyer",f=n.expected_price||0,g=n.commission_percentage||3,y=n.expected_commission||f*g/100;d({property_address:n.property_address||n.deal_name||"",city:n.city||"",state:n.state||"",zip:n.zip_code||"",transaction_type:m,close_date:n.actual_close_date||n.target_close_date||Js(new Date,"yyyy-MM-dd"),sale_price:f,commission_amount:y,lead_source_id:"",client_type_id:"",notes:n.notes||""})}},[n,s]);const u=async m=>{if(m.preventDefault(),!!n)try{const f=await a.mutateAsync({property_address:c.property_address,city:c.city||null,state:c.state||null,zip:c.zip||null,transaction_type:c.transaction_type,close_date:c.close_date,sale_price:c.sale_price,commission_amount:c.commission_amount||null,brokerage_split_pct:n.brokerage_split_pct||null,team_split_pct:n.team_split_pct||null,franchise_fee_pct:n.franchise_fee_pct||null,referral_fee_pct:n.referral_fee_pct||null,transaction_fee:n.transaction_fee||null,lead_source_id:c.lead_source_id||null,client_type_id:c.client_type_id||null,contact_id:n.contact_id||null,notes:c.notes||null,is_win:!0});await i.mutateAsync({id:n.id,scorecard_transaction_id:f.id,actual_close_date:c.close_date}),ie.success("Deal added to Scorecard! 🎉"),t(!1),r==null||r()}catch(f){console.error("Error syncing to scorecard:",f),ie.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(Bs,{open:s,onOpenChange:t,children:e.jsxs(Fs,{className:"sm:max-w-[550px] max-h-[90vh] overflow-y-auto",children:[e.jsxs(qs,{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(gl,{className:"h-6 w-6 text-green-600 dark:text-green-400"})}),e.jsx($s,{className:"text-center text-xl",children:"Congratulations on Closing! 🎉"}),e.jsx(Ar,{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(re,{htmlFor:"property_address",className:"flex items-center gap-2",children:[e.jsx(_a,{className:"h-4 w-4 text-muted-foreground"}),"Property Address *"]}),e.jsx(we,{id:"property_address",value:c.property_address,onChange:m=>d(f=>({...f,property_address:m.target.value})),placeholder:"123 Main St",required:!0})]}),e.jsxs("div",{className:"grid grid-cols-3 gap-3",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{htmlFor:"city",children:"City"}),e.jsx(we,{id:"city",value:c.city,onChange:m=>d(f=>({...f,city:m.target.value})),placeholder:"City"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{htmlFor:"state",children:"State"}),e.jsx(we,{id:"state",value:c.state,onChange:m=>d(f=>({...f,state:m.target.value})),placeholder:"TX",maxLength:2})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{htmlFor:"zip",children:"Zip"}),e.jsx(we,{id:"zip",value:c.zip,onChange:m=>d(f=>({...f,zip:m.target.value})),placeholder:"75001"})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{children:"Transaction Type *"}),e.jsxs(Ns,{value:c.transaction_type,onValueChange:m=>d(f=>({...f,transaction_type:m})),children:[e.jsx(ws,{children:e.jsx(ks,{})}),e.jsxs(js,{children:[e.jsx(nt,{value:"buyer",children:"Buyer"}),e.jsx(nt,{value:"seller",children:"Seller"})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs(re,{htmlFor:"close_date",className:"flex items-center gap-2",children:[e.jsx(ta,{className:"h-4 w-4 text-muted-foreground"}),"Close Date *"]}),e.jsx(we,{id:"close_date",type:"date",value:c.close_date,onChange:m=>d(f=>({...f,close_date:m.target.value})),required:!0})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsxs(re,{htmlFor:"sale_price",className:"flex items-center gap-2",children:[e.jsx(Ed,{className:"h-4 w-4 text-muted-foreground"}),"Sale Price *"]}),e.jsx(we,{id:"sale_price",type:"number",value:c.sale_price||"",onChange:m=>d(f=>({...f,sale_price:Number(m.target.value)})),placeholder:"450000",required:!0,min:0}),c.sale_price>0&&e.jsx("p",{className:"text-xs text-muted-foreground",children:h(c.sale_price)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs(re,{htmlFor:"commission_amount",className:"flex items-center gap-2",children:[e.jsx(IT,{className:"h-4 w-4 text-muted-foreground"}),"GCI (Commission)"]}),e.jsx(we,{id:"commission_amount",type:"number",value:c.commission_amount||"",onChange:m=>d(f=>({...f,commission_amount:Number(m.target.value)})),placeholder:"13500",min:0}),c.commission_amount>0&&e.jsx("p",{className:"text-xs text-muted-foreground",children:h(c.commission_amount)})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{children:"Lead Source"}),e.jsxs(Ns,{value:c.lead_source_id,onValueChange:m=>d(f=>({...f,lead_source_id:m})),children:[e.jsx(ws,{children:e.jsx(ks,{placeholder:"Select source"})}),e.jsx(js,{children:l==null?void 0:l.map(m=>e.jsx(nt,{value:m.id,children:m.name},m.id))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{children:"Client Type"}),e.jsxs(Ns,{value:c.client_type_id,onValueChange:m=>d(f=>({...f,client_type_id:m})),children:[e.jsx(ws,{children:e.jsx(ks,{placeholder:"Select type"})}),e.jsx(js,{children:o==null?void 0:o.map(m=>e.jsx(nt,{value:m.id,children:m.name},m.id))})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{htmlFor:"notes",children:"Notes"}),e.jsx(Ws,{id:"notes",value:c.notes,onChange:m=>d(f=>({...f,notes:m.target.value})),placeholder:"Any additional notes about this transaction...",rows:2})]}),e.jsxs(Cr,{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(vi,{className:"ml-2 h-4 w-4"})]})})]})]})]})})}const gNn={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"}},Fft={urgent:0,high:1,medium:2,low:3};function xNn({deals:s,stages:t,onDealClick:n,onStageChange:r}){const[a,i]=N.useState("target_close_date"),[l,o]=N.useState("asc"),c=f=>{a===f?o(g=>g==="asc"?"desc":"asc"):(i(f),o("asc"))},d=N.useMemo(()=>[...s].sort((f,g)=>{var x,_;let y=0;switch(a){case"deal_name":y=f.deal_name.localeCompare(g.deal_name);break;case"stage":{const b=((x=t.find(A=>A.id===f.stage_id))==null?void 0:x.sort_order)||0,k=((_=t.find(A=>A.id===g.stage_id))==null?void 0:_.sort_order)||0;y=b-k;break}case"expected_price":y=(f.expected_price||0)-(g.expected_price||0);break;case"expected_commission":y=(f.expected_commission||0)-(g.expected_commission||0);break;case"target_close_date":{const b=f.target_close_date?Tc(f.target_close_date).getTime():1/0,k=g.target_close_date?Tc(g.target_close_date).getTime():1/0;y=b-k;break}case"priority":y=Fft[f.priority]-Fft[g.priority];break}return l==="asc"?y:-y}),[s,t,a,l]),u=f=>f?new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:0}).format(f):"—",h=f=>f?t.find(g=>g.id===f):null,m=({field:f,children:g})=>e.jsxs(B,{variant:"ghost",size:"sm",className:"h-8 -ml-3 font-medium",onClick:()=>c(f),children:[g,a===f?l==="asc"?e.jsx(Om,{className:"ml-2 h-4 w-4"}):e.jsx(Wf,{className:"ml-2 h-4 w-4"}):e.jsx(mg,{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(Oa,{children:[e.jsx(Fa,{children:e.jsxs(un,{className:"bg-muted/50",children:[e.jsx(Mt,{className:"w-[250px]",children:e.jsx(m,{field:"deal_name",children:"Deal Name"})}),e.jsx(Mt,{className:"w-[150px]",children:e.jsx(m,{field:"stage",children:"Stage"})}),e.jsx(Mt,{className:"w-[100px]",children:"Type"}),e.jsx(Mt,{className:"w-[120px]",children:e.jsx(m,{field:"expected_price",children:"Price"})}),e.jsx(Mt,{className:"w-[120px]",children:e.jsx(m,{field:"expected_commission",children:"GCI"})}),e.jsx(Mt,{className:"w-[130px]",children:e.jsx(m,{field:"target_close_date",children:"Close Date"})}),e.jsx(Mt,{className:"w-[100px]",children:e.jsx(m,{field:"priority",children:"Priority"})})]})}),e.jsx(za,{children:d.map(f=>{h(f.stage_id);const g=gNn[f.deal_type],y=f.target_close_date?wj(Tc(f.target_close_date),new Date):null,x=y!==null&&y<0,_=y!==null&&y<=7&&y>=0;return e.jsxs(un,{className:Ot("cursor-pointer hover:bg-muted/50 transition-colors",x&&"bg-red-50/50"),onClick:()=>n(f),children:[e.jsx(gt,{className:"font-medium",children:e.jsxs("div",{children:[e.jsx("p",{className:"truncate max-w-[230px]",children:f.deal_name}),f.contact&&e.jsxs("p",{className:"text-xs text-muted-foreground truncate",children:[f.contact.first_name," ",f.contact.last_name]})]})}),e.jsx(gt,{onClick:b=>b.stopPropagation(),children:e.jsx(E7t,{stages:t,currentStageId:f.stage_id||"",onStageSelect:(b,k)=>r(f.id,b,k)})}),e.jsx(gt,{children:e.jsx(We,{variant:"outline",className:Ot("text-xs",g.color),children:g.label})}),e.jsx(gt,{children:e.jsx("span",{className:"font-medium",children:u(f.expected_price)})}),e.jsx(gt,{children:e.jsx("span",{className:"text-emerald-600",children:u(f.expected_commission)})}),e.jsx(gt,{children:f.target_close_date?e.jsxs("div",{className:Ot("flex items-center gap-1 text-sm",x&&"text-red-600",_&&!x&&"text-amber-600"),children:[x&&e.jsx(Uo,{className:"h-3.5 w-3.5"}),e.jsx("span",{children:Js(Tc(f.target_close_date),"MMM d, yyyy")})]}):e.jsx("span",{className:"text-muted-foreground",children:"—"})}),e.jsx(gt,{children:e.jsx(We,{variant:"outline",className:Ot("text-xs capitalize",f.priority==="urgent"&&"border-red-200 bg-red-50 text-red-700",f.priority==="high"&&"border-orange-200 bg-orange-50 text-orange-700",f.priority==="medium"&&"border-amber-200 bg-amber-50 text-amber-700",f.priority==="low"&&"border-slate-200 bg-slate-50 text-slate-600"),children:f.priority})})]},f.id)})})]})})}function yNn(){const s=Ya();return mt({queryKey:["deal-tasks",s],queryFn:async()=>{if(!s)return[];const{data:t,error:n}=await H.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 vNn(s){const t=Ya();return mt({queryKey:["deal-tasks","deal",s,t],queryFn:async()=>{if(!t||!s)return[];const{data:n,error:r}=await H.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 bNn(){const s=Ya(),t=as();return _t({mutationFn:async n=>{if(!s)throw new Error("Not authenticated");const{data:r,error:a}=await H.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 _Nn(){const s=as();return _t({mutationFn:async({id:t,...n})=>{const{data:r,error:a}=await H.from("deal_tasks").update(n).eq("id",t).select().single();if(a)throw a;return r},onSuccess:()=>{s.invalidateQueries({queryKey:["deal-tasks"]})}})}function wNn(){const s=as();return _t({mutationFn:async t=>{const{error:n}=await H.from("deal_tasks").delete().eq("id",t);if(n)throw n},onSuccess:()=>{s.invalidateQueries({queryKey:["deal-tasks"]})}})}function CAe(){const s=as();return _t({mutationFn:async({id:t,status:n})=>{const{data:r,error:a}=await H.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 jNn(){const s=as();return _t({mutationFn:async t=>{if(t.length===0)return;const{error:n}=await H.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 NNn(s){const t=Ya();return mt({queryKey:["deal-task-templates",t,s],queryFn:async()=>{if(!t)return[];let n=H.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 kNn(){const s=Ya(),t=as();return _t({mutationFn:async n=>{if(!s)throw new Error("Not authenticated");const{data:r,error:a}=await H.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 SNn(){const s=as();return _t({mutationFn:async t=>{const{error:n}=await H.from("deal_task_templates").delete().eq("id",t);if(n)throw n},onSuccess:()=>{s.invalidateQueries({queryKey:["deal-task-templates"]})}})}function CNn(){const s=Ya(),t=as();return _t({mutationFn:async({dealId:n,stageId:r})=>{if(!s)throw new Error("Not authenticated");const{data:a,error:i}=await H.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 H.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 H.from("deal_tasks").insert(c).select();if(u)throw u;return d},onSuccess:()=>{t.invalidateQueries({queryKey:["deal-tasks"]})}})}const ANn={urgent:"🔴",high:"🟠",medium:"🟡",low:"🟢"};function TNn({open:s,onOpenChange:t,dealId:n,dealName:r,fromStageName:a,toStageName:i,toStageId:l,onConfirm:o}){const{data:c,isLoading:d}=vNn(s?n:void 0),u=jNn(),h=CNn(),[m,f]=N.useState(new Set),[g,y]=N.useState(!1),x=(c||[]).filter(A=>A.status!=="done");N.useEffect(()=>{x.length>0&&f(new Set(x.map(A=>A.id)))},[c]);const _=A=>{f(T=>{const P=new Set(T);return P.has(A)?P.delete(A):P.add(A),P})},b=async()=>{y(!0);try{const A=Array.from(m);A.length>0&&await u.mutateAsync(A),await o(),await h.mutateAsync({dealId:n,stageId:l}),t(!1)}catch(A){console.error("Stage move failed:",A),ie.error((A==null?void 0:A.message)||"Failed to move deal. Please try again.")}finally{y(!1)}},k=async()=>{y(!0);try{await o(),await h.mutateAsync({dealId:n,stageId:l}),t(!1)}catch(A){console.error("Stage move (skip) failed:",A),ie.error((A==null?void 0:A.message)||"Failed to move deal. Please try again.")}finally{y(!1)}};return e.jsx(Bs,{open:s,onOpenChange:t,children:e.jsxs(Fs,{className:"sm:max-w-[480px]",children:[e.jsxs(qs,{children:[e.jsx($s,{children:"Move Deal"}),e.jsxs(Ar,{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(We,{variant:"outline",className:"text-sm",children:a}),e.jsx(vi,{className:"h-4 w-4 text-muted-foreground"}),e.jsx(We,{className:"text-sm bg-primary",children:i})]}),d?e.jsx("div",{className:"flex justify-center py-8",children:e.jsx(us,{className:"h-6 w-6 animate-spin text-muted-foreground"})}):x.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:x.length})," incomplete task",x.length!==1?"s":"",". Select which to mark as done:"]}),e.jsx(lo,{className:"max-h-[250px]",children:e.jsx("div",{className:"space-y-1",children:x.map(A=>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(Bi,{checked:m.has(A.id),onCheckedChange:()=>_(A.id)}),e.jsxs("span",{className:"text-sm flex-1",children:[ANn[A.priority]," ",A.title]}),A.stage&&e.jsx("span",{className:"text-[10px] px-1.5 py-0.5 rounded-full",style:{backgroundColor:A.stage.color+"20",color:A.stage.color},children:A.stage.name})]},A.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===x.length?f(new Set):f(new Set(x.map(A=>A.id)))},children:m.size===x.length?"Deselect All":"Select All"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(B,{variant:"outline",size:"sm",onClick:k,disabled:g,children:"Skip"}),e.jsxs(B,{size:"sm",onClick:b,disabled:g,children:[g&&e.jsx(us,{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(Hr,{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:g,children:[g&&e.jsx(us,{className:"h-4 w-4 mr-1 animate-spin"}),"Move to ",i]})]})]})]})})}const ENn=[{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"}],MNn=[{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 I7t({open:s,onOpenChange:t}){const n=Ya(),{data:r,isLoading:a}=hSt(),i=Zvs(),[l,o]=N.useState({logo_url:null,cover_photo_url:null,brand_color:null,accent_color:null,tagline:null,welcome_message:null,portal_theme:"noir"}),[c,d]=N.useState(null);N.useEffect(()=>{s&&o({logo_url:(r==null?void 0:r.logo_url)??null,cover_photo_url:(r==null?void 0:r.cover_photo_url)??null,brand_color:(r==null?void 0:r.brand_color)??null,accent_color:(r==null?void 0:r.accent_color)??null,tagline:(r==null?void 0:r.tagline)??null,welcome_message:(r==null?void 0:r.welcome_message)??null,portal_theme:(r==null?void 0:r.portal_theme)??"noir"})},[s,r]);const u=f=>o(g=>({...g,...f})),h=async(f,g)=>{if(n){if(f.size>5*1024*1024){ie.error("Image must be under 5MB");return}d(g);try{const y=await mSt(n,f,g);u(g==="logo"?{logo_url:y}:{cover_photo_url:y})}catch(y){ie.error(`Upload failed: ${y.message||y}`)}finally{d(null)}}},m=async()=>{try{await i.mutateAsync(l),ie.success("Portal branding saved"),t(!1)}catch{ie.error("Failed to save branding")}};return e.jsx(Bs,{open:s,onOpenChange:t,children:e.jsxs(Fs,{className:"max-w-lg max-h-[90vh] flex flex-col",children:[e.jsxs(qs,{children:[e.jsxs($s,{className:"flex items-center gap-2",children:[e.jsx(zc,{className:"h-5 w-5 text-primary"}),"Portal Branding"]}),e.jsx(Ar,{children:"Customize how your client portals look. These defaults apply to every portal — you can override them per deal."})]}),e.jsx(lo,{className:"flex-1 pr-3 -mr-3",children:a?e.jsx("div",{className:"py-12 flex justify-center",children:e.jsx(us,{className:"h-5 w-5 animate-spin text-muted-foreground"})}):e.jsxs("div",{className:"space-y-6 py-2",children:[e.jsx(LNn,{draft:l}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{children:[e.jsx(re,{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:MNn.map(f=>{const g=(l.portal_theme??"noir")===f.id;return e.jsxs("button",{type:"button",onClick:()=>u({portal_theme:f.id}),className:Ot("rounded-xl border-2 p-3 text-left transition-all",g?"border-primary ring-2 ring-primary/20":"border-input hover:border-primary/40"),children:[e.jsx("div",{className:"rounded-lg overflow-hidden mb-2",style:{background:f.bg},children:e.jsxs("div",{className:"p-3 space-y-1.5",children:[e.jsx("div",{className:"h-1.5 w-10 rounded-full",style:{background:f.accent}}),e.jsx("div",{className:"h-2.5 w-20 rounded",style:{background:f.ink,opacity:.85}}),e.jsx("div",{className:"h-6 rounded-md",style:{background:f.surface,border:`1px solid ${f.accent}44`}})]})}),e.jsx("div",{className:"text-sm font-medium text-foreground",children:f.name}),e.jsx("div",{className:"text-[11px] text-muted-foreground leading-snug",children:f.description})]},f.id)})})]}),e.jsx(zft,{label:"Logo",hint:"Shown above your name on the portal. PNG with transparent background works best.",value:l.logo_url,uploading:c==="logo",onUpload:f=>h(f,"logo"),onClear:()=>u({logo_url:null}),aspect:"square"}),e.jsx(zft,{label:"Cover Photo",hint:"Hero background at the top of the portal. Wide landscape works best.",value:l.cover_photo_url,uploading:c==="cover",onUpload:f=>h(f,"cover"),onClear:()=>u({cover_photo_url:null}),aspect:"cover"}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{children:[e.jsx(re,{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:ENn.map(f=>{const g=l.brand_color===f.brand&&l.accent_color===f.accent;return e.jsxs("button",{type:"button",onClick:()=>u({brand_color:f.brand,accent_color:f.accent}),className:Ot("group relative rounded-lg border-2 p-2 text-left transition-all",g?"border-primary ring-2 ring-primary/20":"border-input hover:border-primary/40"),children:[e.jsxs("div",{className:"flex h-6 rounded-md overflow-hidden",children:[e.jsx("div",{className:"flex-1",style:{background:f.brand}}),e.jsx("div",{className:"flex-1",style:{background:f.accent}})]}),e.jsx("div",{className:"text-[11px] mt-1.5 font-medium text-foreground",children:f.name})]},f.name)})}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsx(Bft,{label:"Brand",value:l.brand_color,onChange:f=>u({brand_color:f})}),e.jsx(Bft,{label:"Accent",value:l.accent_color,onChange:f=>u({accent_color:f})})]})]}),e.jsxs("div",{children:[e.jsx(re,{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(we,{value:l.tagline||"",onChange:f=>u({tagline:f.target.value}),placeholder:"Your trusted real estate advisor",maxLength:80})]}),e.jsxs("div",{children:[e.jsx(re,{className:"text-sm font-medium",children:"Default Welcome Message"}),e.jsx("p",{className:"text-xs text-muted-foreground mb-1",children:"Shown on the portal hero. Per-deal welcome messages override this."}),e.jsx("textarea",{value:l.welcome_message||"",onChange:f=>u({welcome_message:f.target.value}),placeholder:"Welcome! Here's everything you need for your transaction.",className:"w-full rounded-md border border-input bg-background px-3 py-2 text-sm min-h-[70px] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring",maxLength:300})]})]})}),e.jsxs("div",{className:"flex justify-end gap-2 pt-4 border-t shrink-0",children:[e.jsx(B,{variant:"outline",onClick:()=>t(!1),children:"Cancel"}),e.jsxs(B,{onClick:m,disabled:i.isPending,children:[i.isPending?e.jsx(us,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(Kl,{className:"h-4 w-4 mr-2"}),"Save Branding"]})]})]})})}function LNn({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 zft({label:s,hint:t,value:n,uploading:r,onUpload:a,onClear:i,aspect:l}){return e.jsxs("div",{children:[e.jsx(re,{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:Ot("rounded-lg border-2 border-dashed border-input flex items-center justify-center overflow-hidden bg-muted/30 shrink-0",l==="square"?"h-16 w-16":"h-16 w-32"),children:n?e.jsx("img",{src:n,alt:s,className:"h-full w-full object-cover"}):e.jsx(pc,{className:"h-5 w-5 text-muted-foreground/40"})}),e.jsxs("div",{className:"flex-1 flex gap-2",children:[e.jsxs("label",{className:"cursor-pointer",children:[e.jsx("input",{type:"file",accept:"image/*",className:"hidden",onChange:o=>{var d;const c=(d=o.target.files)==null?void 0:d[0];c&&a(c),o.target.value=""}}),e.jsxs("span",{className:"inline-flex items-center gap-1.5 h-9 px-3 rounded-md border border-input bg-background hover:bg-accent text-sm font-medium",children:[r?e.jsx(us,{className:"h-3.5 w-3.5 animate-spin"}):e.jsx(ni,{className:"h-3.5 w-3.5"}),n?"Replace":"Upload"]})]}),n&&e.jsx(B,{variant:"ghost",size:"sm",onClick:i,className:"text-muted-foreground hover:text-destructive",children:e.jsx(qn,{className:"h-3.5 w-3.5"})})]})]})]})}function Bft({label:s,value:t,onChange:n}){const r=t||"#000000";return e.jsxs("div",{children:[e.jsx(re,{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(we,{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 PNn(){const s=Ya();return mt({queryKey:["all-client-portals",s],queryFn:async()=>{if(!s)return[];const{data:t,error:n}=await H.from("client_portals").select("*").eq("owner_user_id",s);if(n)throw n;return t||[]},enabled:!!s})}function INn({dealId:s,dealName:t,contactName:n,portal:r,onSettingsOpen:a,onComposerOpen:i,onInviteOpen:l,onDeleteConfirm:o}){const c=mGe(),d=VU(),u=bIt(),h=_It(),[m,f]=N.useState(!1),g=!!(r!=null&&r.archived_at),y=async()=>{f(!0);try{await c.mutateAsync({deal_id:s,visibility:"private",require_onboarding:!0}),ie.success("Portal enabled!")}catch{ie.error("Failed to create portal")}finally{f(!1)}},x=async T=>{if(r)try{await d.mutateAsync({id:r.id,is_enabled:T}),ie.success(T?"Portal enabled":"Portal disabled")}catch{ie.error("Failed to update portal")}},_=()=>{r&&(navigator.clipboard.writeText(j5(r.slug)),ie.success("Link copied!"))},b=()=>{r&&window.open(j5(r.slug),"_blank")},k=async()=>{if(r)try{await u.mutateAsync(r.id),ie.success("Portal archived")}catch{ie.error("Failed to archive portal")}},A=async()=>{if(r)try{await h.mutateAsync(r.id),ie.success("Portal restored")}catch{ie.error("Failed to restore portal")}};return r?g?e.jsxs("div",{className:"flex items-center gap-4 p-4 border rounded-lg opacity-60 bg-muted/30",children:[e.jsxs(cr,{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(We,{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:A,className:"text-xs gap-1",children:[e.jsx(a9,{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(qn,{className:"h-3.5 w-3.5"}),"Delete"]})]})]}):e.jsxs("div",{className:"flex items-center gap-4 p-4 border rounded-lg hover:border-primary/40 hover:bg-muted/30 transition-colors group",children:[e.jsxs(cr,{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(We,{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(Qa,{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:_,title:"Copy link",children:e.jsx(Pa,{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(Tr,{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(Rr,{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(Qk,{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(sc,{className:"h-3.5 w-3.5"})}),e.jsxs(qd,{children:[e.jsx(Vd,{asChild:!0,children:e.jsx(B,{variant:"ghost",size:"icon",className:"h-8 w-8",children:e.jsx(Iy,{className:"h-3.5 w-3.5"})})}),e.jsx(Ld,{align:"end",children:e.jsxs(ba,{onClick:k,children:[e.jsx(xg,{className:"h-4 w-4 mr-2"}),"Archive Portal"]})})]}),e.jsx(zn,{checked:r.is_enabled,onCheckedChange:x,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(us,{className:"h-3 w-3 animate-spin mr-1"}):e.jsx(Cn,{className:"h-3 w-3 mr-1"}),"Enable Portal"]})]})}function D7t(){const{data:s,isLoading:t}=SAe(),{data:n,isLoading:r}=PNn(),[a,i]=N.useState(""),[l,o]=N.useState("all"),c=wIt(),[d,u]=N.useState(null),[h,m]=N.useState(null),[f,g]=N.useState(null),[y,x]=N.useState(null),[_,b]=N.useState(!1),k=Ya(),A=t||r,T=new Map;n==null||n.forEach(V=>T.set(V.deal_id,V));const I=[...(s||[]).filter(V=>{var ne,me,ue,ce,ae;const W=T.get(V.id),G=a.toLowerCase(),X=!G||V.deal_name.toLowerCase().includes(G)||((me=(ne=V.contact)==null?void 0:ne.first_name)==null?void 0:me.toLowerCase().includes(G))||((ce=(ue=V.contact)==null?void 0:ue.last_name)==null?void 0:ce.toLowerCase().includes(G))||((ae=W==null?void 0:W.client_name)==null?void 0:ae.toLowerCase().includes(G));let te=!0;return l==="active"?te=!!(W!=null&&W.is_enabled)&&!(W!=null&&W.archived_at):l==="disabled"?te=!!W&&!W.is_enabled&&!W.archived_at:l==="archived"?te=!!(W!=null&&W.archived_at):l==="none"?te=!W:l==="all"&&(te=!(W!=null&&W.archived_at)||!W),X&&te})].sort((V,W)=>{const G=T.get(V.id),X=T.get(W.id);if(G!=null&&G.archived_at&&!(X!=null&&X.archived_at))return 1;if(!(G!=null&&G.archived_at)&&(X!=null&&X.archived_at)||G&&!X)return-1;if(!G&&X)return 1;if(G&&X){if(G.is_enabled&&!X.is_enabled)return-1;if(!G.is_enabled&&X.is_enabled)return 1}return 0}),M=(n==null?void 0:n.filter(V=>!V.archived_at).length)||0,L=(n==null?void 0:n.filter(V=>V.is_enabled&&!V.archived_at).length)||0,z=(n==null?void 0:n.filter(V=>V.archived_at).length)||0,$=async()=>{if(y)try{await c.mutateAsync({id:y.id,dealId:y.deal_id}),ie.success("Portal permanently deleted"),x(null)}catch{ie.error("Failed to delete portal")}};return A?e.jsx("div",{className:"flex items-center justify-center py-16",children:e.jsx(us,{className:"h-6 w-6 animate-spin text-muted-foreground"})}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between gap-4",children:[e.jsxs("div",{className:"flex items-center gap-4 text-sm",children:[e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(Cn,{className:"h-4 w-4 text-primary"}),e.jsxs("span",{className:"font-medium",children:[M," Portals"]})]}),e.jsxs("span",{className:"text-muted-foreground",children:[L," active · ",M-L," disabled",z>0&&` · ${z} archived`]})]}),e.jsxs(B,{variant:"outline",size:"sm",onClick:()=>b(!0),className:"gap-1.5",children:[e.jsx(zc,{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(Gr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(we,{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(hr,{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(lo,{className:"h-[calc(100vh-22rem)]",children:e.jsxs("div",{className:"space-y-2 pb-4",children:[I.map(V=>{const W=T.get(V.id)||null,G=V.contact?`${V.contact.first_name||""} ${V.contact.last_name||""}`.trim():"";return e.jsx(INn,{dealId:V.id,dealName:V.deal_name,contactName:G,portal:W,onSettingsOpen:u,onComposerOpen:X=>m(X),onInviteOpen:(X,te)=>g({portal:X,dealName:te}),onDeleteConfirm:x},V.id)}),I.length===0&&e.jsxs("div",{className:"text-center py-12",children:[e.jsx("div",{className:"w-12 h-12 mx-auto mb-3 bg-muted rounded-full flex items-center justify-center",children:e.jsx(Cn,{className:"h-5 w-5 text-muted-foreground"})}),e.jsx("p",{className:"text-sm font-medium",children:"No matching deals"}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:"Try adjusting your search or filters"})]})]})})]}),d&&e.jsx(HWe,{open:!!d,onOpenChange:V=>!V&&u(null),portal:d,dealOwnerId:k||""}),h&&e.jsx(GWe,{open:!!h,onOpenChange:V=>!V&&m(null),portalId:h.id,portalSlug:h.slug,notifyClient:h.notify_client}),f&&e.jsx(WWe,{open:!!f,onOpenChange:V=>!V&&g(null),portal:f.portal,dealName:f.dealName}),e.jsx(I7t,{open:_,onOpenChange:b}),e.jsx(Fl,{open:!!y,onOpenChange:V=>!V&&x(null),children:e.jsxs(kl,{children:[e.jsxs(Sl,{children:[e.jsx(Al,{children:"Permanently delete this portal?"}),e.jsx(Tl,{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(Cl,{children:[e.jsx(El,{children:"Cancel"}),e.jsx(wl,{onClick:$,className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:"Delete Permanently"})]})]})})]})}class DNn extends N.Component{constructor(t){super(t),this.state={hasError:!1,error:null}}static getDerivedStateFromError(t){return{hasError:!0,error:t}}componentDidCatch(t,n){console.error("DealPipeline error:",t,n)}render(){return this.state.hasError?e.jsx(Qs,{children:e.jsxs("div",{className:"flex flex-col items-center justify-center h-[60vh] gap-4 text-center px-4",children:[e.jsx("div",{className:"w-16 h-16 bg-destructive/10 rounded-full flex items-center justify-center",children:e.jsx("span",{className:"text-2xl",children:"⚠️"})}),e.jsx("h2",{className:"text-xl font-semibold",children:"Something went wrong"}),e.jsx("p",{className:"text-muted-foreground max-w-md",children:"There was an error in the deal pipeline. Click below to try again."}),e.jsxs("div",{className:"flex gap-3",children:[e.jsx("button",{onClick:()=>this.setState({hasError:!1,error:null}),className:"px-4 py-2 bg-primary text-primary-foreground rounded-md text-sm font-medium hover:bg-primary/90",children:"Try Again"}),e.jsx("button",{onClick:()=>window.location.reload(),className:"px-4 py-2 border border-border rounded-md text-sm font-medium hover:bg-muted",children:"Refresh Page"})]})]})}):this.props.children}}const mH="deal-pipeline-detail-sheet";function RNn(){var As;const s=qU(),{data:t,isLoading:n}=PJ(),{data:r,isLoading:a,refetch:i}=SAe(),{data:l,isLoading:o}=Fjn(),c=N7t(),d=Mjn(),[u,h]=N.useState("board"),[m,f]=N.useState(!1),[g,y]=N.useState(!1),[x,_]=N.useState(null),[b,k]=N.useState(null),[A,T]=N.useState(null),[P,I]=N.useState(null),[M,L]=N.useState(!1),[z,$]=N.useState(null),[V,W]=N.useState(""),[G,X]=N.useState("all"),[te,ne]=N.useState("all"),[me,ue]=N.useState("all"),{data:ce}=S2n(),[ae,he]=N.useState(!1),[xe,ve]=N.useState(!1),[ge,be]=N.useState(new Set),Se=N.useRef(!1),[Ie,Me]=N.useState(null),{data:Re}=Cj(),{isTeamLeader:Be,teamMembers:Ne}=N2n(),Ge=N.useMemo(()=>Array.from(ge),[ge]),{data:Ce}=k2n(Ge),Fe=N.useMemo(()=>{const Hs=new Map;return Ne.forEach(Rs=>Hs.set(Rs.id,{name:Rs.name,avatar_url:Rs.avatar_url,color:Rs.color})),Hs},[Ne]),Ae=N.useCallback(Hs=>Hs.owner_user_id&&Fe.get(Hs.owner_user_id)||null,[Fe]),Xe=N.useCallback(Hs=>{be(Rs=>{const en=new Set(Rs);return en.has(Hs)?en.delete(Hs):en.add(Hs),en})},[]);N.useEffect(()=>{!n&&t&&t.length===0&&c.mutate()},[n,t]);const[$e,Ye]=$c(),Je=N.useRef(!1);N.useEffect(()=>{const Hs=$e.get("deal");if(Hs&&r&&r.length>0&&!Je.current){const Rs=r.find(en=>en.id===Hs);Rs&&(Je.current=!0,_(Rs),y(!0),$e.delete("deal"),Ye($e,{replace:!0}))}},[r,$e]);const Ke=N.useMemo(()=>{if(!Ce||!t)return[];const Hs=new Map(t.map(Rs=>[Rs.name,Rs.id]));return Ce.map(Rs=>{const en=Rs._stage_name&&Hs.get(Rs._stage_name)||null;return{...Rs,stage_id:en||Rs.stage_id}})},[Ce,t]),st=N.useMemo(()=>[...r||[],...Ke],[r,Ke]);N.useEffect(()=>{if(Se.current||st.length===0)return;Se.current=!0;const Hs=sessionStorage.getItem(mH);if(Hs)try{const Rs=JSON.parse(Hs);if(!Rs.open||!Rs.dealId)return;const en=st.find(Rn=>Rn.id===Rs.dealId);en&&(_(en),y(!0))}catch{sessionStorage.removeItem(mH)}},[st]),N.useEffect(()=>{g&&(x!=null&&x.id)?sessionStorage.setItem(mH,JSON.stringify({dealId:x.id,open:!0})):sessionStorage.removeItem(mH)},[g,x==null?void 0:x.id]);const rt=(ce==null?void 0:ce.byDeal)||{},Ze=(ce==null?void 0:ce.unique)||[],ht=st.filter(Hs=>{var sn,ki,ia,vr,Nr,rn;const Rs=V.toLowerCase(),en=rt[Hs.id]||[],Rn=!Rs||Hs.deal_name.toLowerCase().includes(Rs)||((ki=(sn=Hs.contact)==null?void 0:sn.first_name)==null?void 0:ki.toLowerCase().includes(Rs))||((vr=(ia=Hs.contact)==null?void 0:ia.last_name)==null?void 0:vr.toLowerCase().includes(Rs))||((Nr=Hs.property_address)==null?void 0:Nr.toLowerCase().includes(Rs))||((rn=Hs.city)==null?void 0:rn.toLowerCase().includes(Rs))||en.some(Zn=>Zn.toLowerCase().includes(Rs)),Bn=G==="all"||Hs.deal_type===G,Dn=te==="all"||en.includes(te),Jn=Hs.actual_close_date||Hs.target_close_date||Hs.contract_date||Hs.created_at,ua=Jn?String(Jn).slice(0,4):null;return Rn&&Bn&&Dn&&(me==="all"||ua===me)}),Bt=N.useMemo(()=>{const Hs=new Set;return Hs.add(String(new Date().getFullYear())),st.forEach(Rs=>{const en=Rs.actual_close_date||Rs.target_close_date||Rs.contract_date||Rs.created_at;en&&Hs.add(String(en).slice(0,4))}),Array.from(Hs).sort((Rs,en)=>Number(en)-Number(Rs))},[st]),Ct=N.useMemo(()=>{if(!t)return l||null;const Hs=new Set(t.filter(Jn=>Jn.is_won_stage).map(Jn=>Jn.id)),Rs=new Set(t.filter(Jn=>Jn.is_lost_stage).map(Jn=>Jn.id)),en=st.filter(Jn=>Jn.stage_id&&!Hs.has(Jn.stage_id)&&!Rs.has(Jn.stage_id)),Rn=st.filter(Jn=>Jn.stage_id&&Hs.has(Jn.stage_id)),Bn=new Date().getFullYear(),Dn=Rn.filter(Jn=>Jn.actual_close_date?new Date(Jn.actual_close_date).getFullYear()===Bn:!0);return{totalDeals:st.length,activeDeals:en.length,wonDeals:Rn.length,pipelineValue:en.reduce((Jn,ua)=>Jn+(ua.expected_price||0),0),expectedCommission:en.reduce((Jn,ua)=>Jn+(ua.expected_commission||0),0),expectedNetToAgent:en.reduce((Jn,ua)=>Jn+(Jw(ua)||0),0),wonValue:Rn.reduce((Jn,ua)=>Jn+(ua.expected_price||0),0),weightedGCI:en.reduce((Jn,ua)=>Jn+(ua.expected_commission||0)*((ua.probability??50)/100),0),weightedNet:en.reduce((Jn,ua)=>Jn+(Jw(ua)||0)*((ua.probability??50)/100),0),ytdWonDeals:Dn.length,ytdWonGCI:Dn.reduce((Jn,ua)=>Jn+(ua.expected_commission||0),0),ytdWonNet:Dn.reduce((Jn,ua)=>Jn+(Jw(ua)||0),0),projectedAnnualNet:Dn.reduce((Jn,ua)=>Jn+(Jw(ua)||0),0)+en.reduce((Jn,ua)=>Jn+(Jw(ua)||0)*((ua.probability??50)/100),0)}},[st,t,l]),Yt=Hs=>{_(Hs),y(!0)},Kt=Hs=>{k(Hs||null),_(null),f(!0)},Xs=Hs=>{_(Hs),y(!1),f(!0)},zs=Hs=>{y(Hs),Hs||sessionStorage.removeItem(mH)},Vt=(Hs,Rs)=>{T(Hs)},At=(Hs,Rs)=>{Hs.preventDefault(),Hs.dataTransfer.dropEffect="move",I(Rs)},Os=async(Hs,Rs)=>{if(Hs.preventDefault(),I(null),!A)return;const en=r==null?void 0:r.find(Dn=>Dn.id===A),Rn=t==null?void 0:t.find(Dn=>Dn.id===Rs),Bn=t==null?void 0:t.find(Dn=>Dn.id===(en==null?void 0:en.stage_id));if(!en||!Rn||en.stage_id===Rs){T(null);return}Me({dealId:A,dealName:en.deal_name,fromStageName:(Bn==null?void 0:Bn.name)||"Unknown",toStageName:Rn.name,toStageId:Rs,isWonStage:Rn.is_won_stage,deal:en}),T(null)},Nt=async()=>{if(!Ie)return;const{dealId:Hs,toStageId:Rs,toStageName:en,isWonStage:Rn,deal:Bn}=Ie;if(await d.mutateAsync({dealId:Hs,stageId:Rs,stageName:en}),ie.success(`Moved to ${en}`),Rn&&!Bn.scorecard_transaction_id){const Dn={...Bn,stage_id:Rs};$(Dn),L(!0)}},ms=N.useCallback(async(Hs,Rs,en)=>{const Rn=r==null?void 0:r.find(Jn=>Jn.id===Hs),Bn=t==null?void 0:t.find(Jn=>Jn.id===Rs),Dn=t==null?void 0:t.find(Jn=>Jn.id===(Rn==null?void 0:Rn.stage_id));!Rn||!Bn||Rn.stage_id===Rs||Me({dealId:Hs,dealName:Rn.deal_name,fromStageName:(Dn==null?void 0:Dn.name)||"Unknown",toStageName:en,toStageId:Rs,isWonStage:Bn.is_won_stage,deal:Rn})},[r,t]),Ys=Hs=>ht.filter(Rs=>Rs.stage_id===Hs),It=n||a,Ds=s?"list":u;return e.jsxs(Qs,{children:[e.jsxs("div",{className:"flex flex-col h-[calc(100vh-4rem)]",children:[e.jsxs("div",{className:"shrink-0 p-4 md:p-6 pb-0 space-y-4",children:[e.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:"Deal Pipeline"}),e.jsx("p",{className:"text-muted-foreground text-sm",children:"Track and manage your active deals"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(B,{variant:"outline",size:"icon",onClick:()=>i(),className:"shrink-0",children:e.jsx(oo,{className:"h-4 w-4"})}),!s&&e.jsx(fN,{children:e.jsxs("div",{className:"flex bg-muted rounded-lg p-1 gap-0.5",children:[e.jsxs(wu,{children:[e.jsx(ju,{asChild:!0,children:e.jsxs(B,{variant:u==="board"?"secondary":"ghost",size:"sm",onClick:()=>h("board"),className:"px-3 gap-1.5",children:[e.jsx(G0,{className:"h-4 w-4"}),e.jsx("span",{className:"hidden sm:inline text-xs",children:"Board"})]})}),e.jsx(nu,{children:"Kanban board view"})]}),e.jsxs(wu,{children:[e.jsx(ju,{asChild:!0,children:e.jsxs(B,{variant:u==="list"?"secondary":"ghost",size:"sm",onClick:()=>h("list"),className:"px-3 gap-1.5",children:[e.jsx(Kx,{className:"h-4 w-4"}),e.jsx("span",{className:"hidden sm:inline text-xs",children:"List"})]})}),e.jsx(nu,{children:"Grouped list view"})]}),e.jsxs(wu,{children:[e.jsx(ju,{asChild:!0,children:e.jsxs(B,{variant:u==="table"?"secondary":"ghost",size:"sm",onClick:()=>h("table"),className:"px-3 gap-1.5",children:[e.jsx(T9,{className:"h-4 w-4"}),e.jsx("span",{className:"hidden sm:inline text-xs",children:"Table"})]})}),e.jsx(nu,{children:"Sortable table view"})]}),e.jsxs(wu,{children:[e.jsx(ju,{asChild:!0,children:e.jsxs(B,{variant:u==="portals"?"secondary":"ghost",size:"sm",onClick:()=>h("portals"),className:"px-3 gap-1.5",children:[e.jsx(Cn,{className:"h-4 w-4"}),e.jsx("span",{className:"hidden sm:inline text-xs",children:"Portals"})]})}),e.jsx(nu,{children:"Client portal management"})]})]})}),Re&&!Be&&e.jsxs(B,{variant:"outline",onClick:()=>he(!0),children:[e.jsx(Yn,{className:"h-4 w-4 mr-2"}),"Team"]}),e.jsxs(B,{onClick:()=>Kt(),children:[e.jsx(nn,{className:"h-4 w-4 mr-2"}),"Add Deal"]})]})]}),Ds!=="portals"&&e.jsx(E2n,{stats:Ct,isLoading:o}),Ds!=="portals"&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("div",{className:"relative flex-1 max-w-sm",children:[e.jsx(Gr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(we,{placeholder:"Search deals, contacts, addresses, tags...",value:V,onChange:Hs=>W(Hs.target.value),className:"pl-9 pr-8"}),V&&e.jsx("button",{onClick:()=>W(""),className:"absolute right-2 top-1/2 -translate-y-1/2 text-muted-foreground hover:text-foreground",children:e.jsx(hr,{className:"h-4 w-4"})})]}),e.jsxs(Ns,{value:G,onValueChange:X,children:[e.jsx(ws,{className:"w-[140px]",children:e.jsx(ks,{placeholder:"All Types"})}),e.jsxs(js,{children:[e.jsx(nt,{value:"all",children:"All Types"}),e.jsx(nt,{value:"buyer",children:"Buyer"}),e.jsx(nt,{value:"seller",children:"Seller"}),e.jsx(nt,{value:"dual",children:"Dual"}),e.jsx(nt,{value:"referral",children:"Referral"}),e.jsx(nt,{value:"lease",children:"Lease"})]})]}),e.jsxs(Ns,{value:me,onValueChange:ue,children:[e.jsx(ws,{className:"w-[120px]",children:e.jsx(ks,{placeholder:"Year"})}),e.jsxs(js,{children:[e.jsx(nt,{value:"all",children:"All Years"}),Bt.map(Hs=>e.jsx(nt,{value:Hs,children:Hs},Hs))]})]}),e.jsxs(Ns,{value:te,onValueChange:ne,children:[e.jsxs(ws,{className:"w-[160px]",children:[e.jsx(pf,{className:"h-3.5 w-3.5 mr-1.5 text-muted-foreground"}),e.jsx(ks,{placeholder:"All Tags"})]}),e.jsxs(js,{className:"max-h-[300px]",children:[e.jsx(nt,{value:"all",children:"All Tags"}),Ze.length===0&&e.jsx("div",{className:"px-2 py-1.5 text-xs text-muted-foreground",children:"No tags yet"}),Ze.map(Hs=>e.jsx(nt,{value:Hs,children:Hs},Hs))]})]}),te!=="all"&&e.jsxs(We,{variant:"secondary",className:"gap-1",children:[e.jsx(pf,{className:"h-3 w-3"}),te,e.jsx("button",{onClick:()=>ne("all"),className:"ml-1 hover:text-foreground","aria-label":"Clear tag filter",children:e.jsx(hr,{className:"h-3 w-3"})})]}),(V||G!=="all"||te!=="all"||me!=="all")&&e.jsxs("span",{className:"text-xs text-muted-foreground whitespace-nowrap",children:[ht.length," of ",(r==null?void 0:r.length)||0," deals"]})]})]}),e.jsxs("div",{className:"flex-1 min-h-0 flex",children:[Be&&!s&&Ne.length>0&&e.jsx(j2n,{members:Ne,enabledMembers:ge,onToggleMember:Xe,isOpen:xe,onToggleOpen:()=>ve(Hs=>!Hs)}),e.jsx("div",{className:"flex-1 min-w-0 min-h-0 p-4 md:p-6 pt-4",children:It?e.jsx("div",{className:"flex gap-4 h-full",children:[1,2,3,4].map(Hs=>e.jsx("div",{className:"min-w-[280px] max-w-[320px] flex-shrink-0",children:e.jsx(xn,{className:"h-full rounded-xl"})},Hs))}):Ds==="board"?e.jsxs(lo,{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(Hs=>e.jsx(T2n,{stage:Hs,deals:Ys(Hs.id),onDealClick:Yt,onAddDeal:Kt,onDragStart:Vt,onDragOver:At,onDrop:Os,isDragOver:P===Hs.id,isWonStage:Hs.is_won_stage,getOwnerInfo:Ae},Hs.id))}),e.jsx(DQ,{orientation:"horizontal"})]}):Ds==="table"?e.jsx(lo,{className:"h-full",children:e.jsx(xNn,{deals:ht,stages:t||[],onDealClick:Yt,onStageChange:ms})}):Ds==="portals"?e.jsx(D7t,{}):e.jsx(lo,{className:"h-full",children:e.jsxs("div",{className:"space-y-6",children:[t==null?void 0:t.map(Hs=>{const Rs=Ys(Hs.id);return Rs.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:Hs.color}}),e.jsx("h3",{className:"font-semibold",children:Hs.name}),e.jsxs("span",{className:"text-muted-foreground text-sm",children:["(",Rs.length,")"]})]}),e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-3",children:Rs.map(en=>e.jsx(M7t,{deal:en,onClick:()=>Yt(en),stages:t,onStageChange:ms,showStagePicker:!0,isWonStage:Hs.is_won_stage,ownerInfo:Ae(en)},en.id))})]},Hs.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(G0,{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:()=>Kt(),children:[e.jsx(nn,{className:"h-4 w-4 mr-2"}),"Add Your First Deal"]})]}),((r==null?void 0:r.length)||0)>0&&ht.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(Gr,{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:()=>{W(""),X("all"),ne("all"),ue("all")},children:"Clear Filters"})]})]})})})]})]}),e.jsx(I2n,{open:m,onOpenChange:f,deal:x,defaultStageId:b}),e.jsx(pNn,{deal:x,open:g,onOpenChange:zs,onEdit:Xs,isWonStage:x?(As=t==null?void 0:t.find(Hs=>Hs.id===x.stage_id))==null?void 0:As.is_won_stage:!1,onAddToScorecard:Hs=>{$(Hs),L(!0),y(!1)}}),e.jsx(fNn,{open:M,onOpenChange:L,deal:z,onComplete:()=>{i(),$(null)}}),Ie&&e.jsx(TNn,{open:!!Ie,onOpenChange:Hs=>{Hs||Me(null)},dealId:Ie.dealId,dealName:Ie.dealName,fromStageName:Ie.fromStageName,toStageName:Ie.toStageName,toStageId:Ie.toStageId,onConfirm:Nt}),e.jsx(_2n,{open:ae,onOpenChange:he})]})}function ONn(){return e.jsx(DNn,{children:e.jsx(RNn,{})})}function R7t({open:s,onOpenChange:t,editTask:n,defaultDealId:r,defaultStageId:a}){var W;const i=bNn(),l=_Nn(),{data:o}=SAe(),c=Ya(),{data:d}=mt({queryKey:["contacts-for-tasks",c],queryFn:async()=>{if(!c)return[];const{data:G,error:X}=await H.from("innercircle_contacts").select("id, first_name, last_name").eq("owner_user_id",c).order("first_name").limit(500);if(X)throw X;return G},enabled:!!c&&s}),[u,h]=N.useState(""),[m,f]=N.useState(""),[g,y]=N.useState("none"),[x,_]=N.useState("none"),[b,k]=N.useState("medium"),[A,T]=N.useState("todo"),[P,I]=N.useState(),[M,L]=N.useState(!1),[z,$]=N.useState(!1);N.useEffect(()=>{n?(h(n.title),f(n.description||""),y(n.deal_id||"none"),_(n.contact_id||"none"),k(n.priority),T(n.status),I(n.due_date?jp(n.due_date):void 0)):(h(""),f(""),y(r||"none"),_("none"),k("medium"),T("todo"),I(void 0))},[n,s,r]);const V=async()=>{if(!u.trim()){ie.error("Task title is required");return}try{const G={title:u.trim(),description:m.trim()||null,deal_id:g==="none"?null:g,contact_id:x==="none"?null:x,stage_id:a||null,priority:b,status:A,due_date:P?Js(P,"yyyy-MM-dd"):null};n?(await l.mutateAsync({id:n.id,...G}),ie.success("Task updated")):(await i.mutateAsync(G),ie.success("Task created")),t(!1)}catch{ie.error("Failed to save task")}};return e.jsx(Bs,{open:s,onOpenChange:t,children:e.jsxs(Fs,{className:"sm:max-w-[480px]",children:[e.jsx(qs,{children:e.jsx($s,{children:n?"Edit Task":"New Task"})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(re,{children:"Title *"}),e.jsx(we,{value:u,onChange:G=>h(G.target.value),placeholder:"e.g., Send inspection report"})]}),e.jsxs("div",{children:[e.jsx(re,{children:"Description"}),e.jsx(Ws,{value:m,onChange:G=>f(G.target.value),placeholder:"Optional details...",rows:2})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(re,{children:"Priority"}),e.jsxs(Ns,{value:b,onValueChange:G=>k(G),children:[e.jsx(ws,{children:e.jsx(ks,{})}),e.jsxs(js,{children:[e.jsx(nt,{value:"low",children:"🟢 Low"}),e.jsx(nt,{value:"medium",children:"🟡 Medium"}),e.jsx(nt,{value:"high",children:"🟠 High"}),e.jsx(nt,{value:"urgent",children:"🔴 Urgent"})]})]})]}),e.jsxs("div",{children:[e.jsx(re,{children:"Status"}),e.jsxs(Ns,{value:A,onValueChange:G=>T(G),children:[e.jsx(ws,{children:e.jsx(ks,{})}),e.jsxs(js,{children:[e.jsx(nt,{value:"todo",children:"To Do"}),e.jsx(nt,{value:"in_progress",children:"In Progress"}),e.jsx(nt,{value:"done",children:"Done"})]})]})]})]}),e.jsxs("div",{children:[e.jsx(re,{children:"Due Date"}),e.jsxs(rc,{children:[e.jsx(ac,{asChild:!0,children:e.jsxs(B,{variant:"outline",className:Ot("w-full justify-start text-left font-normal",!P&&"text-muted-foreground"),children:[e.jsx(ta,{className:"mr-2 h-4 w-4"}),P?Js(P,"PPP"):"Pick a date"]})}),e.jsx(Zl,{className:"w-auto p-0",align:"start",children:e.jsx(Xv,{mode:"single",selected:P,onSelect:I,initialFocus:!0,className:"p-3 pointer-events-auto"})})]})]}),e.jsxs("div",{children:[e.jsx(re,{children:"Link to Deal"}),e.jsxs(rc,{open:M,onOpenChange:L,children:[e.jsx(ac,{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(Ti,{className:"h-3.5 w-3.5 text-muted-foreground shrink-0"}),g!=="none"?((W=o==null?void 0:o.find(G=>G.id===g))==null?void 0:W.deal_name)||"Select deal":"No Deal"]}),e.jsx(sb,{className:"h-4 w-4 shrink-0 opacity-50"})]})}),e.jsx(Zl,{className:"w-[--radix-popover-trigger-width] p-0",align:"start",children:e.jsxs(db,{children:[e.jsx(ub,{placeholder:"Search deals..."}),e.jsxs(hb,{children:[e.jsx(mb,{children:"No deals found."}),e.jsxs(pb,{children:[e.jsxs(Ry,{value:"no-deal",onSelect:()=>{y("none"),L(!1)},children:[e.jsx(pa,{className:Ot("mr-2 h-4 w-4",g==="none"?"opacity-100":"opacity-0")}),"No Deal"]}),o==null?void 0:o.map(G=>e.jsxs(Ry,{value:G.deal_name,onSelect:()=>{y(G.id),L(!1)},children:[e.jsx(pa,{className:Ot("mr-2 h-4 w-4",g===G.id?"opacity-100":"opacity-0")}),G.deal_name]},G.id))]})]})]})})]})]}),e.jsxs("div",{children:[e.jsx(re,{children:"Link to Contact"}),e.jsxs(rc,{open:z,onOpenChange:$,children:[e.jsx(ac,{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(Ro,{className:"h-3.5 w-3.5 text-muted-foreground shrink-0"}),x!=="none"?(()=>{const G=d==null?void 0:d.find(X=>X.id===x);return G?`${G.first_name} ${G.last_name}`:"Select contact"})():"No Contact"]}),e.jsx(sb,{className:"h-4 w-4 shrink-0 opacity-50"})]})}),e.jsx(Zl,{className:"w-[--radix-popover-trigger-width] p-0",align:"start",children:e.jsxs(db,{children:[e.jsx(ub,{placeholder:"Search contacts..."}),e.jsxs(hb,{children:[e.jsx(mb,{children:"No contacts found."}),e.jsxs(pb,{children:[e.jsxs(Ry,{value:"no-contact",onSelect:()=>{_("none"),$(!1)},children:[e.jsx(pa,{className:Ot("mr-2 h-4 w-4",x==="none"?"opacity-100":"opacity-0")}),"No Contact"]}),d==null?void 0:d.map(G=>e.jsxs(Ry,{value:`${G.first_name} ${G.last_name}`,onSelect:()=>{_(G.id),$(!1)},children:[e.jsx(pa,{className:Ot("mr-2 h-4 w-4",x===G.id?"opacity-100":"opacity-0")}),G.first_name," ",G.last_name]},G.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 FNn={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 zNn({tasks:s}){const t=CAe(),n=wNn(),r=tr(),[a,i]=N.useState(null),l=async u=>{const h=u.status==="done"?"todo":"done";try{await t.mutateAsync({id:u.id,status:h})}catch{ie.error("Failed to update task")}},o=async u=>{try{await n.mutateAsync(u),ie.success("Task deleted")}catch{ie.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(Hr,{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($ft,{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(Ti,{className:"h-3.5 w-3.5 text-muted-foreground"}),e.jsx("h3",{className:"font-medium text-sm",children:h.dealName}),e.jsxs(We,{variant:"secondary",className:"ml-auto text-xs",children:[h.tasks.filter(m=>m.status==="done").length,"/",h.tasks.length]}),e.jsx(Qa,{className:"h-3.5 w-3.5 text-muted-foreground"})]}),h.tasks.map(m=>e.jsx($ft,{task:m,onToggle:l,onDelete:o,onEdit:i,onNavigateDeal:f=>r(`/mission-control/pipeline?deal=${f}`)},m.id))]},u)),a&&e.jsx(R7t,{open:!!a,onOpenChange:()=>i(null),editTask:a})]})}function $ft({task:s,onToggle:t,onDelete:n,onEdit:r,onNavigateDeal:a}){const i=s.status==="done",l=!i&&s.due_date&&x5(jp(s.due_date))&&!O0(jp(s.due_date)),o=!i&&s.due_date&&O0(jp(s.due_date)),c=FNn[s.priority];return e.jsxs("div",{className:Ot("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(Hr,{className:"h-5 w-5 text-emerald-500"}):e.jsx(bg,{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:Ot("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(Ro,{className:"h-2.5 w-2.5"}),s.contact.first_name," ",s.contact.last_name]})]})]}),e.jsxs(We,{variant:"outline",className:Ot("text-[10px] shrink-0",c.color),children:[c.dot," ",c.label]}),s.due_date&&e.jsxs("span",{className:Ot("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(Xr,{className:"h-3 w-3"}),Js(jp(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(xp,{className:"h-3.5 w-3.5 text-muted-foreground"})}),e.jsx("button",{onClick:()=>n(s.id),className:"p-1 hover:bg-destructive/10 rounded",children:e.jsx(qn,{className:"h-3.5 w-3.5 text-destructive"})})]})]})}const BNn=[{status:"todo",label:"To Do",icon:bg,color:"border-t-slate-400"},{status:"in_progress",label:"In Progress",icon:wp,color:"border-t-blue-500"},{status:"done",label:"Done",icon:Hr,color:"border-t-emerald-500"}],$Nn={urgent:"🔴",high:"🟠",medium:"🟡",low:"🟢"};function UNn({tasks:s}){const t=CAe(),n=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{ie.error("Failed to move task")}};return e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-4",children:BNn.map(i=>e.jsxs("div",{className:Ot("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(We,{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(qNn,{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 qNn({task:s,onDragStart:t}){const n=s.status==="done",r=!n&&s.due_date&&x5(jp(s.due_date))&&!O0(jp(s.due_date)),a=!n&&s.due_date&&O0(jp(s.due_date));return e.jsx("div",{draggable:!0,onDragStart:i=>t(i,s.id),className:Ot("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:$Nn[s.priority]}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:Ot("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(Ti,{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(Ro,{className:"h-2.5 w-2.5"}),s.contact.first_name," ",s.contact.last_name]})]}),s.due_date&&e.jsxs("div",{className:Ot("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(Xr,{className:"h-2.5 w-2.5"}),r?"Overdue — ":a?"Due today — ":"",Js(jp(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 Uft={urgent:"🔴",high:"🟠",medium:"🟡",low:"🟢"};function VNn({tasks:s}){const[t,n]=N.useState(new Date),r=CAe(),a=am(t),i=m_(t),l=lx(a),o=FB(i),c=UDe({start:l,end:o}),d=N.useMemo(()=>{const m=new Map;return s.forEach(f=>{if(!f.due_date)return;const g=f.due_date,y=m.get(g)||[];y.push(f),m.set(g,y)}),m},[s]),u=N.useMemo(()=>s.filter(m=>!m.due_date),[s]),h=async m=>{const f=m.status==="done"?"todo":"done";try{await r.mutateAsync({id:m.id,status:f})}catch{ie.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(TI(t,1)),children:e.jsx(Fc,{className:"h-4 w-4"})}),e.jsx("h3",{className:"font-semibold",children:Js(t,"MMMM yyyy")}),e.jsx(B,{variant:"ghost",size:"icon",onClick:()=>n(J0(t,1)),children:e.jsx(Qa,{className:"h-4 w-4"})})]}),e.jsx("div",{className:"grid grid-cols-7 text-center",children:["Sun","Mon","Tue","Wed","Thu","Fri","Sat"].map(m=>e.jsx("div",{className:"text-xs font-medium text-muted-foreground py-2",children:m},m))}),e.jsx("div",{className:"grid grid-cols-7 border-l border-t",children:c.map(m=>{const f=Js(m,"yyyy-MM-dd"),g=d.get(f)||[],y=MQ(m,t),x=O0(m);return e.jsxs("div",{className:Ot("border-r border-b min-h-[100px] p-1",!y&&"bg-muted/30",x&&"bg-primary/5"),children:[e.jsx("div",{className:Ot("text-xs font-medium mb-1 text-right px-1",!y&&"text-muted-foreground/40",x&&"text-primary font-bold"),children:Js(m,"d")}),e.jsxs("div",{className:"space-y-0.5",children:[g.slice(0,3).map(_=>e.jsxs("button",{onClick:()=>h(_),className:Ot("w-full text-left text-[10px] px-1 py-0.5 rounded truncate flex items-center gap-0.5 hover:bg-muted transition-colors",_.status==="done"?"text-muted-foreground line-through":"text-foreground"),children:[_.status==="done"?e.jsx(Hr,{className:"h-2.5 w-2.5 text-emerald-500 shrink-0"}):e.jsx(bg,{className:"h-2.5 w-2.5 shrink-0"}),e.jsxs("span",{className:"truncate",children:[Uft[_.priority]," ",_.title]})]},_.id)),g.length>3&&e.jsxs("p",{className:"text-[9px] text-muted-foreground text-center",children:["+",g.length-3," more"]})]})]},f)})}),u.length>0&&e.jsxs("div",{className:"border rounded-lg p-3",children:[e.jsxs("h4",{className:"text-sm font-medium text-muted-foreground mb-2",children:["No Due Date (",u.length,")"]}),e.jsx("div",{className:"space-y-1",children:u.map(m=>e.jsxs("button",{onClick:()=>h(m),className:Ot("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(Hr,{className:"h-3.5 w-3.5 text-emerald-500 shrink-0"}):e.jsx(bg,{className:"h-3.5 w-3.5 shrink-0"}),e.jsxs("span",{className:"truncate",children:[Uft[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 HNn={urgent:"🔴",high:"🟠",medium:"🟡",low:"🟢"};function GNn({open:s,onOpenChange:t,stages:n}){var _;const[r,a]=N.useState(((_=n[0])==null?void 0:_.id)||""),{data:i,isLoading:l}=NNn(r||void 0),o=kNn(),c=SNn(),[d,u]=N.useState(""),[h,m]=N.useState("medium"),[f,g]=N.useState(""),y=async()=>{if(!(!d.trim()||!r))try{await o.mutateAsync({stage_id:r,title:d.trim(),priority:h,default_due_offset_days:f?parseInt(f):null,sort_order:((i==null?void 0:i.length)||0)+1}),u(""),g(""),ie.success("Template added")}catch{ie.error("Failed to add template")}},x=async b=>{try{await c.mutateAsync(b),ie.success("Template deleted")}catch{ie.error("Failed to delete template")}};return e.jsx(Bs,{open:s,onOpenChange:t,children:e.jsxs(Fs,{className:"sm:max-w-[560px]",children:[e.jsx(qs,{children:e.jsxs($s,{className:"flex items-center gap-2",children:[e.jsx(WG,{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(re,{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:Ot("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(lo,{className:"max-h-[250px]",children:e.jsxs("div",{className:"space-y-1.5",children:[i==null?void 0:i.map((b,k)=>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:HNn[b.priority]}),e.jsx("span",{className:"text-sm flex-1 truncate",children:b.title}),b.default_due_offset_days&&e.jsxs(We,{variant:"outline",className:"text-[10px]",children:["+",b.default_due_offset_days,"d"]}),e.jsx("button",{onClick:()=>x(b.id),className:"opacity-0 group-hover:opacity-100 p-1 hover:bg-destructive/10 rounded transition-opacity",children:e.jsx(qn,{className:"h-3.5 w-3.5 text-destructive"})})]},b.id)),(i==null?void 0:i.length)===0&&r&&e.jsx("p",{className:"text-sm text-muted-foreground text-center py-6",children:"No templates for this stage yet"})]})}),r&&e.jsxs("div",{className:"space-y-3 border-t pt-3",children:[e.jsx(re,{className:"text-xs text-muted-foreground",children:"Add Template Task"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(we,{placeholder:"Task title...",value:d,onChange:b=>u(b.target.value),className:"flex-1",onKeyDown:b=>b.key==="Enter"&&y()}),e.jsxs(Ns,{value:h,onValueChange:b=>m(b),children:[e.jsx(ws,{className:"w-[100px]",children:e.jsx(ks,{})}),e.jsxs(js,{children:[e.jsx(nt,{value:"low",children:"🟢 Low"}),e.jsx(nt,{value:"medium",children:"🟡 Med"}),e.jsx(nt,{value:"high",children:"🟠 High"}),e.jsx(nt,{value:"urgent",children:"🔴 Urgent"})]})]})]}),e.jsxs("div",{className:"flex gap-2 items-end",children:[e.jsxs("div",{className:"flex-1",children:[e.jsx(re,{className:"text-xs",children:"Due offset (days from entering stage)"}),e.jsx(we,{type:"number",placeholder:"e.g., 7",value:f,onChange:b=>g(b.target.value)})]}),e.jsxs(B,{onClick:y,disabled:!d.trim()||o.isPending,children:[e.jsx(nn,{className:"h-4 w-4 mr-1"}),"Add"]})]})]})]})})}function WNn(){const{data:s,isLoading:t}=yNn(),{data:n}=PJ(),[r,a]=N.useState("list"),[i,l]=N.useState(""),[o,c]=N.useState("active"),[d,u]=N.useState("all"),[h,m]=N.useState("all"),[f,g]=N.useState(!1),[y,x]=N.useState(!1),_=N.useMemo(()=>{if(!s)return[];const A=new Map;return s.forEach(T=>{T.deal&&A.set(T.deal.id,T.deal.deal_name)}),Array.from(A,([T,P])=>({id:T,name:P}))},[s]),b=N.useMemo(()=>s?s.filter(A=>{var z,$,V,W;const T=i.toLowerCase(),P=!T||A.title.toLowerCase().includes(T)||(($=(z=A.deal)==null?void 0:z.deal_name)==null?void 0:$.toLowerCase().includes(T))||`${((V=A.contact)==null?void 0:V.first_name)||""} ${((W=A.contact)==null?void 0:W.last_name)||""}`.toLowerCase().includes(T),I=o==="all"||o==="active"&&A.status!=="done"||o==="todo"&&A.status==="todo"||o==="in_progress"&&A.status==="in_progress"||o==="done"&&A.status==="done"||o==="overdue"&&A.status!=="done"&&A.due_date&&x5(jp(A.due_date))&&!O0(jp(A.due_date)),M=d==="all"||A.priority===d,L=h==="all"||h==="no_deal"&&!A.deal_id||A.deal_id===h;return P&&I&&M&&L}):[],[s,i,o,d,h]),k=N.useMemo(()=>{if(!s)return{total:0,overdue:0,dueToday:0,dueThisWeek:0,completed:0};const A=s.filter(T=>T.status!=="done");return{total:A.length,overdue:A.filter(T=>T.due_date&&x5(jp(T.due_date))&&!O0(jp(T.due_date))).length,dueToday:A.filter(T=>T.due_date&&O0(jp(T.due_date))).length,dueThisWeek:A.filter(T=>T.due_date&&Zcs(jp(T.due_date))).length,completed:s.filter(T=>T.status==="done").length}},[s]);return e.jsx(Qs,{children:e.jsxs("div",{className:"space-y-6 p-4 md:p-6 max-w-[1600px] mx-auto",children:[e.jsxs("div",{className:"flex flex-col md:flex-row md:items-center justify-between gap-4",children:[e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl font-bold tracking-tight",children:"Tasks"}),e.jsx("p",{className:"text-muted-foreground text-sm",children:"Manage tasks across deals and contacts"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(B,{variant:"outline",size:"sm",onClick:()=>x(!0),children:[e.jsx(cj,{className:"h-4 w-4 mr-1"}),"Templates"]}),e.jsxs(B,{size:"sm",onClick:()=>g(!0),children:[e.jsx(nn,{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(Kx,{className:"h-3.5 w-3.5"}),"Active"]}),e.jsx("p",{className:"text-xl font-bold mt-1",children:k.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(xd,{className:"h-3.5 w-3.5"}),"Overdue"]}),e.jsx("p",{className:"text-xl font-bold mt-1 text-destructive",children:k.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(Xr,{className:"h-3.5 w-3.5"}),"Due Today"]}),e.jsx("p",{className:"text-xl font-bold mt-1",children:k.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(ld,{className:"h-3.5 w-3.5"}),"This Week"]}),e.jsx("p",{className:"text-xl font-bold mt-1",children:k.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(Hr,{className:"h-3.5 w-3.5"}),"Completed"]}),e.jsx("p",{className:"text-xl font-bold mt-1",children:k.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(Gr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(we,{placeholder:"Search tasks...",value:i,onChange:A=>l(A.target.value),className:"pl-9"})]}),e.jsxs(Ns,{value:d,onValueChange:u,children:[e.jsx(ws,{className:"w-[130px]",children:e.jsx(ks,{placeholder:"Priority"})}),e.jsxs(js,{children:[e.jsx(nt,{value:"all",children:"All Priorities"}),e.jsx(nt,{value:"urgent",children:"🔴 Urgent"}),e.jsx(nt,{value:"high",children:"🟠 High"}),e.jsx(nt,{value:"medium",children:"🟡 Medium"}),e.jsx(nt,{value:"low",children:"🟢 Low"})]})]}),e.jsxs(Ns,{value:h,onValueChange:m,children:[e.jsx(ws,{className:"w-[160px]",children:e.jsx(ks,{placeholder:"Deal"})}),e.jsxs(js,{children:[e.jsx(nt,{value:"all",children:"All Deals"}),e.jsx(nt,{value:"no_deal",children:"No Deal"}),_.map(A=>e.jsx(nt,{value:A.id,children:A.name},A.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(Kx,{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(r3,{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(ld,{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(zNn,{tasks:b}),r==="kanban"&&e.jsx(UNn,{tasks:b}),r==="calendar"&&e.jsx(VNn,{tasks:b})]}),e.jsx(R7t,{open:f,onOpenChange:g}),e.jsx(GNn,{open:y,onOpenChange:x,stages:n||[]})]})})}function KNn(s){const t=KWe(s);return t?t.toLocaleDateString("en-US",{weekday:"short",month:"short",day:"numeric"}):""}function YNn({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 Ane({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:Ot("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 ZNn(){const s=tr(),{data:t,isLoading:n}=rNn(),r=CAe(),[a,i]=N.useState(""),[l,o]=N.useState(!1),[c,d]=N.useState("all"),u=N.useMemo(()=>{let b=t||[];c==="contract"&&(b=b.filter(A=>!!A.contract_date));const k=a.trim().toLowerCase();return k&&(b=b.filter(A=>{var T,P,I,M;return((T=A.deal_name)==null?void 0:T.toLowerCase().includes(k))||((P=A.property_address)==null?void 0:P.toLowerCase().includes(k))||`${((I=A.contact)==null?void 0:I.first_name)??""} ${((M=A.contact)==null?void 0:M.last_name)??""}`.toLowerCase().includes(k)})),b},[t,a,c]),h=N.useMemo(()=>{const b=[];return(u||[]).forEach(k=>{jG.forEach(A=>{const T=k[A.key],P=vk(T);T&&P!==null&&P<=30&&b.push({id:`${k.id}-${A.key}`,kind:"date",label:A.label,dealId:k.id,dealName:k.deal_name,date:T,days:P})}),k.tasks.filter(A=>A.status!=="done"&&A.due_date).forEach(A=>{const T=vk(A.due_date);T!==null&&T<=30&&b.push({id:A.id,kind:"task",label:A.title,dealId:k.id,dealName:k.deal_name,date:A.due_date,days:T,priority:A.priority})})}),b.sort((k,A)=>k.days-A.days)},[u]),m=N.useMemo(()=>({overdue:h.filter(b=>b.days<0),today:h.filter(b=>b.days===0),week:h.filter(b=>b.days>0&&b.days<=7),later:h.filter(b=>b.days>7)}),[h]),f=N.useMemo(()=>{const b=t||[],k=b.filter(P=>{const I=vk(P.target_close_date);return I!==null&&I>=0&&I<=7}).length,A=b.reduce((P,I)=>P+I.tasks.filter(M=>{const L=vk(M.due_date);return M.status!=="done"&&L!==null&&L<0}).length,0),T=b.reduce((P,I)=>P+(Number(I.expected_price)||0),0);return{active:b.length,closingSoon:k,overdueTasks:A,volume:T}},[t]),g=b=>b.tasks.length===0?0:b.tasks.filter(k=>k.status==="done").length/b.tasks.length*100,y=b=>s(`/mission-control/pipeline?deal=${b}`),x=async b=>{try{await r.mutateAsync({id:b,status:"done"}),ie.success("Task completed")}catch{ie.error("Could not update task")}},_=({title:b,items:k,tone:A})=>{if(k.length===0)return null;const T=A==="danger"?"bg-destructive":A==="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:Ot("h-1.5 w-1.5 rounded-full",T)}),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:["(",k.length,")"]})]}),k.slice(0,12).map(P=>e.jsxs("div",{className:Ot("group flex items-center gap-3 rounded-lg border px-3 py-2 transition-colors hover:bg-muted/50",A==="danger"&&"border-destructive/30 bg-destructive/5"),children:[P.kind==="task"?e.jsx(Bi,{className:"shrink-0",onCheckedChange:()=>x(P.id),"aria-label":`Complete ${P.label}`}):e.jsx(df,{className:"h-4 w-4 text-muted-foreground shrink-0"}),e.jsxs("button",{type:"button",onClick:()=>y(P.dealId),className:"flex-1 min-w-0 text-left",children:[e.jsx("p",{className:"text-sm font-medium leading-tight truncate",children:P.label}),e.jsxs("p",{className:"text-xs text-muted-foreground truncate",children:[P.dealName," · ",KNn(P.date)]})]}),e.jsx("span",{className:Ot("text-[11px] font-semibold shrink-0 tabular-nums",P.days<0?"text-destructive":P.days<=3?"text-amber-600":"text-muted-foreground"),children:P.days<0?`${Math.abs(P.days)}d late`:P.days===0?"Today":`${P.days}d`})]},P.id))]})};return e.jsxs(Qs,{children:[e.jsxs("div",{className:"p-4 sm:p-6 space-y-6 max-w-[1400px] mx-auto",children:[e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl font-bold tracking-tight",children:"Transaction Coordinator"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Every deadline, every checklist, one screen. Nothing slips."})]}),e.jsxs(B,{onClick:()=>o(!0),className:"gap-2 shrink-0",children:[e.jsx(Ep,{className:"h-4 w-4"}),"Playbooks"]})]}),e.jsxs("div",{className:"grid grid-cols-2 lg:grid-cols-4 gap-3",children:[e.jsx(Ane,{icon:lj,label:"Active transactions",value:f.active}),e.jsx(Ane,{icon:Cu,label:"Closing within 7 days",value:f.closingSoon,tone:"warn"}),e.jsx(Ane,{icon:xd,label:"Overdue tasks",value:f.overdueTasks,tone:f.overdueTasks>0?"danger":"good"}),e.jsx(Ane,{icon:ml,label:"Pipeline volume",value:f.volume>=1e6?`$${(f.volume/1e6).toFixed(1)}M`:`$${Math.round(f.volume/1e3)}K`,tone:"good"})]}),e.jsxs("div",{className:"flex flex-col sm:flex-row gap-2",children:[e.jsxs("div",{className:"relative flex-1",children:[e.jsx(Gr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(we,{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(us,{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(df,{className:"h-4 w-4 text-primary"}),e.jsx("h2",{className:"text-sm font-semibold",children:"Deadline Radar"}),e.jsx(We,{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(Hr,{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(_,{title:"Overdue",items:m.overdue,tone:"danger"}),e.jsx(_,{title:"Today",items:m.today,tone:"warn"}),e.jsx(_,{title:"This week",items:m.week,tone:"warn"}),e.jsx(_,{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(_a,{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 k=g(b),A=vk(b.target_close_date),T=b.tasks.filter(M=>M.status!=="done"),P=T.filter(M=>{const L=vk(M.due_date);return L!==null&&L<0}),I=T.filter(M=>M.due_date).sort((M,L)=>(vk(M.due_date)??0)-(vk(L.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(YNn,{value:k}),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(Qa,{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(We,{variant:"outline",className:"text-[10px] capitalize",children:b.deal_type}),A!==null&&e.jsx(We,{variant:"secondary",className:Ot("text-[10px]",A<0&&"bg-destructive/10 text-destructive",A>=0&&A<=7&&"bg-amber-500/10 text-amber-700 dark:text-amber-400"),children:A<0?`Closing ${Math.abs(A)}d overdue`:`Closes in ${A}d`}),P.length>0&&e.jsxs(We,{className:"text-[10px] bg-destructive/10 text-destructive hover:bg-destructive/10",children:[P.length," overdue"]})]}),e.jsxs("div",{className:"mt-3",children:[e.jsx(ro,{value:k,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"]}),I&&e.jsxs("p",{className:"text-[11px] text-muted-foreground truncate max-w-[55%]",children:["Next: ",I.title]})]})]}),b.tasks.length===0&&e.jsx("p",{className:"text-[11px] text-muted-foreground mt-2 italic",children:"No checklist yet — open the deal and apply a playbook."})]})]})},b.id)})})]})]}),e.jsx(P7t,{open:l,onOpenChange:o})]})}function O7t(){const s=Ya();return mt({queryKey:["portal-referrals",s],queryFn:async()=>{if(!s)return[];const{data:t,error:n}=await H.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 XNn(){const s=as();return _t({mutationFn:async({id:t,...n})=>{const{data:r,error:a}=await H.from("portal_referrals").update(n).eq("id",t).select().single();if(a)throw a;return r},onSuccess:()=>{s.invalidateQueries({queryKey:["portal-referrals"]})}})}function QNn(){const s=as();return _t({mutationFn:async t=>{const{error:n}=await H.from("portal_referrals").delete().eq("id",t);if(n)throw n},onSuccess:()=>{s.invalidateQueries({queryKey:["portal-referrals"]})}})}const JNn=s=>new Intl.DateTimeFormat("en-US",{timeZone:"America/New_York",month:"short",day:"numeric",year:"numeric"}).format(new Date(s)),HPe=[{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"}],ekn={buying:"Buying",selling:"Selling",both:"Buying & Selling",unsure:"Not sure yet"};function F7t(){const{data:s=[],isLoading:t}=O7t(),n=XNn(),r=QNn(),[a,i]=N.useState("all"),[l,o]=N.useState({}),c=N.useMemo(()=>a==="all"?s:s.filter(f=>f.status===a),[s,a]),d=N.useMemo(()=>({total:s.length,new:s.filter(f=>f.status==="new").length,converted:s.filter(f=>f.status==="converted").length}),[s]),u=(f,g)=>{n.mutate({id:f.id,status:g}),ie.success("Status updated")},h=f=>{const g=l[f.id];n.mutate({id:f.id,agent_notes:g}),o(y=>{const{[f.id]:x,..._}=y;return _}),ie.success("Notes saved")},m=f=>{confirm(`Delete referral for ${f.friend_name}?`)&&r.mutate(f.id)};return e.jsxs("div",{className:"container max-w-5xl py-6 px-4",children:[e.jsx(ic,{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(Io,{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"},...HPe.map(f=>({v:f.value,l:f.label}))].map(f=>e.jsx("button",{onClick:()=>i(f.v),className:`px-3 py-1.5 rounded-full text-xs font-medium border transition-colors ${a===f.v?"bg-primary text-primary-foreground border-primary":"bg-background text-muted-foreground border-input hover:border-primary/50"}`,children:f.l},f.v))}),t?e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsx(us,{className:"h-6 w-6 animate-spin text-muted-foreground"})}):c.length===0?e.jsx(_e,{children:e.jsxs(De,{className:"py-12 text-center",children:[e.jsx(Io,{className:"h-10 w-10 text-muted-foreground/40 mx-auto mb-3"}),e.jsx("p",{className:"text-sm font-medium",children:"No referrals yet"}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:"Once your closed clients refer friends from their portal, they'll show up here."})]})}):e.jsx("div",{className:"space-y-3",children:c.map(f=>{var _,b;const g=HPe.find(k=>k.value===f.status),y=(_=f.client_portals)==null?void 0:_.slug,x=f.referrer_name||((b=f.client_portals)==null?void 0:b.client_name)||"Anonymous client";return e.jsxs(_e,{children:[e.jsx(zt,{className:"pb-3",children:e.jsxs("div",{className:"flex items-start justify-between flex-wrap gap-2",children:[e.jsxs("div",{children:[e.jsx(qt,{className:"text-lg",children:f.friend_name}),e.jsxs("p",{className:"text-xs text-muted-foreground mt-1 flex items-center gap-1.5",children:[e.jsx(ta,{className:"h-3 w-3"}),"Referred by ",e.jsx("span",{className:"font-medium text-foreground",children:x})," ·"," ",JNn(f.created_at)]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(We,{variant:"outline",className:g==null?void 0:g.className,children:(g==null?void 0:g.label)||f.status}),e.jsxs(Ns,{value:f.status,onValueChange:k=>u(f,k),children:[e.jsx(ws,{className:"h-8 w-[130px] text-xs",children:e.jsx(ks,{})}),e.jsx(js,{children:HPe.map(k=>e.jsx(nt,{value:k.value,className:"text-xs",children:k.label},k.value))})]})]})]})}),e.jsxs(De,{className:"space-y-3",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[f.friend_interest&&e.jsx(We,{variant:"secondary",className:"text-xs",children:ekn[f.friend_interest]||f.friend_interest}),f.friend_email&&e.jsxs("a",{href:`mailto:${f.friend_email}`,className:"inline-flex items-center gap-1 text-xs text-primary hover:underline",children:[e.jsx(mn,{className:"h-3 w-3"}),f.friend_email]}),f.friend_phone&&e.jsxs(e.Fragment,{children:[e.jsxs("a",{href:`tel:${f.friend_phone}`,className:"inline-flex items-center gap-1 text-xs text-primary hover:underline",children:[e.jsx(ga,{className:"h-3 w-3"}),f.friend_phone]}),e.jsxs("a",{href:`sms:${f.friend_phone}`,className:"inline-flex items-center gap-1 text-xs text-primary hover:underline",children:[e.jsx(Ud,{className:"h-3 w-3"}),"Text"]})]})]}),f.friend_message&&e.jsxs("div",{className:"bg-muted/50 rounded-md p-3 text-sm",children:[e.jsx("p",{className:"text-[11px] uppercase tracking-wide text-muted-foreground mb-1",children:"Note from referrer"}),e.jsxs("p",{className:"italic text-foreground",children:['"',f.friend_message,'"']})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-[11px] uppercase tracking-wide text-muted-foreground mb-1",children:"Your notes"}),l[f.id]!==void 0?e.jsxs("div",{className:"space-y-2",children:[e.jsx(Ws,{value:l[f.id],onChange:k=>o(A=>({...A,[f.id]:k.target.value})),rows:3,className:"text-sm"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(B,{size:"sm",onClick:()=>h(f),children:"Save"}),e.jsx(B,{size:"sm",variant:"ghost",onClick:()=>o(k=>{const{[f.id]:A,...T}=k;return T}),children:"Cancel"})]})]}):e.jsx("button",{onClick:()=>o(k=>({...k,[f.id]:f.agent_notes||""})),className:"text-sm text-left w-full p-2 rounded border border-dashed border-input hover:border-primary/50 hover:bg-muted/30 transition-colors",children:f.agent_notes||e.jsx("span",{className:"text-muted-foreground italic",children:"Click to add notes..."})})]}),e.jsxs("div",{className:"flex items-center justify-between border-t pt-3",children:[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(Tr,{className:"h-3 w-3"}),"View source portal"]}),e.jsx(B,{variant:"ghost",size:"sm",onClick:()=>m(f),className:"text-destructive hover:text-destructive ml-auto h-8",children:e.jsx(qn,{className:"h-3.5 w-3.5"})})]})]})]},f.id)})})]})}function z7t({vendor:s,onEdit:t,onDelete:n,onToggleVisible:r,isVisible:a,showOwnerBadge:i,clickCount:l}){var c;const o=((c=mU.find(d=>d.value===s.category))==null?void 0:c.label)||s.category;return e.jsxs(_e,{className:"p-4 flex flex-col gap-3",children:[e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx("div",{className:"w-12 h-12 rounded-lg bg-muted flex items-center justify-center overflow-hidden shrink-0",children:s.logo_url?e.jsx("img",{src:s.logo_url,alt:s.name,className:"w-full h-full object-cover"}):e.jsx("span",{className:"text-lg font-semibold text-muted-foreground",children:s.name.charAt(0).toUpperCase()})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-1.5 flex-wrap",children:[e.jsx("h3",{className:"font-semibold truncate",children:s.name}),s.is_required&&e.jsx(Au,{className:"w-3.5 h-3.5 text-amber-600","aria-label":"Required"}),s.is_featured&&e.jsx(Wa,{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(We,{variant:"secondary",className:"text-[10px]",children:o}),i==="brokerage"&&e.jsx(We,{variant:"outline",className:"text-[10px]",children:"Brokerage"}),i==="agent"&&e.jsx(We,{variant:"outline",className:"text-[10px]",children:"Personal"}),!s.is_active&&e.jsx(We,{variant:"destructive",className:"text-[10px]",children:"Inactive"}),typeof l=="number"&&l>0&&e.jsxs(We,{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(ga,{className:"w-3 h-3"}),s.phone]}),s.email&&e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(mn,{className:"w-3 h-3"}),e.jsx("span",{className:"truncate",children:s.email})]}),s.website&&e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(au,{className:"w-3 h-3"}),e.jsx("span",{className:"truncate",children:s.website})]}),s.booking_url&&e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(ta,{className:"w-3 h-3"}),e.jsx("span",{className:"truncate",children:"Booking link"})]}),s.address&&e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(ii,{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(da,{className:"w-3.5 h-3.5 mr-1.5"}):e.jsx(V0,{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(xp,{className:"w-3.5 h-3.5"})}),n&&e.jsx(B,{size:"sm",variant:"ghost",onClick:n,className:"text-destructive",children:e.jsx(qn,{className:"w-3.5 h-3.5"})})]})]})}function B7t({open:s,onOpenChange:t,vendor:n,ownerType:r,brokerageId:a,agentUserId:i,showBrokerageOnlyFields:l}){const o=Fvs(),[c,d]=N.useState({}),[u,h]=N.useState(!1),m=N.useRef(null),f=async x=>{if(!x.type.startsWith("image/")){ie.error("Please select an image");return}if(x.size>5*1024*1024){ie.error("Image must be under 5MB");return}h(!0);try{const _=x.name.split(".").pop()||"png",b=`${r}/${a||i||"misc"}/${Date.now()}.${_}`,{error:k}=await H.storage.from("vendor-logos").upload(b,x,{upsert:!0,contentType:x.type});if(k)throw k;const{data:A}=H.storage.from("vendor-logos").getPublicUrl(b);d(T=>({...T,logo_url:A.publicUrl})),ie.success("Logo uploaded")}catch(_){ie.error(_.message||"Upload failed")}finally{h(!1)}};N.useEffect(()=>{s&&d(n||{owner_type:r,owner_brokerage_id:r==="brokerage"&&a||null,owner_user_id:r==="agent"&&i||null,category:"other",action_type:"call",is_active:!0,is_featured:!1,is_required:!1})},[s,n,r,a,i]);const g=(x,_)=>d(b=>({...b,[x]:_})),y=async()=>{var x;if(!((x=c.name)!=null&&x.trim())){ie.error("Name is required");return}try{await o.mutateAsync(c),ie.success(n?"Vendor updated":"Vendor added"),t(!1)}catch(_){ie.error(_.message||"Failed to save vendor")}};return e.jsx(Bs,{open:s,onOpenChange:t,children:e.jsxs(Fs,{className:"max-w-2xl max-h-[90vh] overflow-y-auto",children:[e.jsx(qs,{children:e.jsx($s,{children:n?"Edit Vendor":"Add Vendor"})}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[e.jsxs("div",{className:"md:col-span-2",children:[e.jsx(re,{children:"Contact Name *"}),e.jsx(we,{value:c.name||"",onChange:x=>g("name",x.target.value),placeholder:"Bob Smith"})]}),e.jsxs("div",{children:[e.jsx(re,{children:"Company"}),e.jsx(we,{value:c.company||"",onChange:x=>g("company",x.target.value),placeholder:"Smith Inspections"})]}),e.jsxs("div",{children:[e.jsx(re,{children:"Category"}),e.jsxs(Ns,{value:c.category,onValueChange:x=>g("category",x),children:[e.jsx(ws,{children:e.jsx(ks,{})}),e.jsx(js,{children:mU.map(x=>e.jsx(nt,{value:x.value,children:x.label},x.value))})]})]}),e.jsxs("div",{children:[e.jsx(re,{children:"Phone"}),e.jsx(we,{value:c.phone||"",onChange:x=>g("phone",x.target.value),placeholder:"(555) 123-4567"})]}),e.jsxs("div",{children:[e.jsx(re,{children:"Email"}),e.jsx(we,{type:"email",value:c.email||"",onChange:x=>g("email",x.target.value),placeholder:"bob@smithinsp.com"})]}),e.jsxs("div",{children:[e.jsx(re,{children:"Website"}),e.jsx(we,{value:c.website||"",onChange:x=>g("website",x.target.value),placeholder:"https://..."})]}),e.jsxs("div",{children:[e.jsx(re,{children:"Logo"}),e.jsx("input",{ref:m,type:"file",accept:"image/*",className:"hidden",onChange:x=>{var b;const _=(b=x.target.files)==null?void 0:b[0];_&&f(_),x.target.value=""}}),e.jsxs("div",{className:"flex items-center gap-3 mt-1",children:[c.logo_url?e.jsxs("div",{className:"relative",children:[e.jsx("img",{src:c.logo_url,alt:"Vendor logo",className:"h-14 w-14 rounded-md object-cover border"}),e.jsx("button",{type:"button",onClick:()=>g("logo_url",""),className:"absolute -top-2 -right-2 bg-background border rounded-full p-0.5 shadow","aria-label":"Remove logo",children:e.jsx(hr,{className:"h-3 w-3"})})]}):e.jsx("div",{className:"h-14 w-14 rounded-md border border-dashed flex items-center justify-center text-muted-foreground",children:e.jsx(ni,{className:"h-5 w-5"})}),e.jsxs(B,{type:"button",variant:"outline",size:"sm",onClick:()=>{var x;return(x=m.current)==null?void 0:x.click()},disabled:u,children:[u?e.jsx(us,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(ni,{className:"h-4 w-4 mr-2"}),c.logo_url?"Replace":"Upload Logo"]})]})]}),e.jsxs("div",{className:"md:col-span-2",children:[e.jsx(re,{children:"Address"}),e.jsx(we,{value:c.address||"",onChange:x=>g("address",x.target.value)})]}),e.jsxs("div",{className:"md:col-span-2",children:[e.jsx(re,{children:"Description"}),e.jsx(Ws,{rows:3,value:c.description||"",onChange:x=>g("description",x.target.value),placeholder:"Why your clients should use this vendor..."})]}),e.jsxs("div",{children:[e.jsx(re,{children:"Primary Action"}),e.jsxs(Ns,{value:c.action_type,onValueChange:x=>g("action_type",x),children:[e.jsx(ws,{children:e.jsx(ks,{})}),e.jsx(js,{children:Dvs.map(x=>e.jsx(nt,{value:x.value,children:x.label},x.value))})]})]}),e.jsxs("div",{children:[e.jsx(re,{children:"Booking URL (Calendly etc.)"}),e.jsx(we,{value:c.booking_url||"",onChange:x=>g("booking_url",x.target.value),placeholder:"https://calendly.com/..."})]}),e.jsxs("div",{className:"md:col-span-2",children:[e.jsx(re,{children:"Compliance Disclosure (optional)"}),e.jsx(Ws,{rows:2,value:c.disclosure_text||"",onChange:x=>g("disclosure_text",x.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(re,{className:"font-medium",children:"Active"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Show this vendor in client portals"})]}),e.jsx(zn,{checked:!!c.is_active,onCheckedChange:x=>g("is_active",x)})]}),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(re,{className:"font-medium",children:"Featured"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Highlight in agent library"})]}),e.jsx(zn,{checked:!!c.is_featured,onCheckedChange:x=>g("is_featured",x)})]}),e.jsxs("div",{className:"flex items-center justify-between border rounded-lg p-3",children:[e.jsxs("div",{children:[e.jsx(re,{className:"font-medium",children:"Required"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Agents cannot hide"})]}),e.jsx(zn,{checked:!!c.is_required,onCheckedChange:x=>g("is_required",x)})]})]})]}),e.jsxs(Cr,{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 $7t({embedded:s=!1}={}){const t=Ya(),{brokerageId:n}=Ls(),{data:r,isLoading:a}=Ovs(),{data:i={}}=lSt("agent",t),l=iSt(),o=zvs(),[c,d]=N.useState(null),[u,h]=N.useState(!1),[m,f]=N.useState(""),[g,y]=N.useState("all"),x=(r==null?void 0:r.vendors)||[],_=(r==null?void 0:r.selections)||[],b=N.useMemo(()=>{const z=new Map;return _.forEach($=>z.set($.vendor_id,$.is_visible)),z},[_]),k=N.useMemo(()=>x.filter(z=>!(g!=="all"&&z.category!==g||m&&!`${z.name} ${z.company||""}`.toLowerCase().includes(m.toLowerCase()))),[x,m,g]),A=k.filter(z=>z.owner_type==="agent"),T=k.filter(z=>z.owner_type==="brokerage"),P=async z=>{if(confirm("Delete this vendor?"))try{await l.mutateAsync(z),ie.success("Vendor deleted")}catch($){ie.error($.message)}},I=async(z,$)=>{try{await o.mutateAsync({vendorId:z,isVisible:$})}catch(V){ie.error(V.message)}},M=z=>z.is_required?!0:b.get(z.id)??z.owner_type==="agent",L=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(vg,{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(nn,{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(Gr,{className:"w-4 h-4 absolute left-3 top-1/2 -translate-y-1/2 text-muted-foreground"}),e.jsx(we,{className:"pl-9",placeholder:"Search vendors...",value:m,onChange:z=>f(z.target.value)})]}),e.jsxs("select",{value:g,onChange:z=>y(z.target.value),className:"border rounded-md px-3 py-2 text-sm bg-background",children:[e.jsx("option",{value:"all",children:"All categories"}),mU.map(z=>e.jsx("option",{value:z.value,children:z.label},z.value))]})]}),a?e.jsx("div",{className:"text-center text-muted-foreground py-12",children:"Loading vendors..."}):e.jsxs(ya,{defaultValue:n?"all":"personal",children:[e.jsxs(va,{children:[e.jsxs(ls,{value:"all",children:["All (",k.length,")"]}),n&&e.jsxs(ls,{value:"brokerage",children:["From Brokerage (",T.length,")"]}),e.jsxs(ls,{value:"personal",children:["My Personal (",A.length,")"]})]}),e.jsx(_s,{value:"all",className:"mt-4",children:e.jsx(GPe,{vendors:k,isVisibleInPortals:M,onToggle:I,onEdit:z=>{d(z),h(!0)},onDelete:P,userId:t,clicks:i})}),n&&e.jsx(_s,{value:"brokerage",className:"mt-4",children:T.length===0?e.jsx(qft,{icon:e.jsx(Cn,{className:"w-12 h-12"}),title:"No brokerage vendors yet",desc:"Your brokerage hasn't added any vendors. Ask your manager to set them up."}):e.jsx(GPe,{vendors:T,isVisibleInPortals:M,onToggle:I,userId:t,clicks:i})}),e.jsx(_s,{value:"personal",className:"mt-4",children:A.length===0?e.jsx(qft,{icon:e.jsx(vg,{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(nn,{className:"w-4 h-4 mr-2"})," Add Your First Vendor"]})}):e.jsx(GPe,{vendors:A,isVisibleInPortals:M,onToggle:I,onEdit:z=>{d(z),h(!0)},onDelete:P,userId:t,clicks:i})})]}),e.jsx(B7t,{open:u,onOpenChange:h,vendor:c,ownerType:"agent",agentUserId:t})]});return s?L:e.jsx(Qs,{children:L})}function GPe({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(z7t,{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 qft({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 tkn(){const{brokerageId:s,isBrokerageManager:t,isAdmin:n,loading:r}=Ls(),{data:a=[],isLoading:i}=Rvs(s),{data:l={}}=lSt("brokerage",s),o=iSt(),[c,d]=N.useState(null),[u,h]=N.useState(!1),[m,f]=N.useState(""),[g,y]=N.useState("all");if(r)return e.jsx(Qs,{children:e.jsx("div",{className:"p-8",children:"Loading..."})});if(!t&&!n)return e.jsx(Qs,{children:e.jsx("div",{className:"p-8 text-center",children:e.jsx("h2",{className:"text-xl font-semibold",children:"Brokerage managers only"})})});const x=a.filter(b=>!(g!=="all"&&b.category!==g||m&&!`${b.name} ${b.company||""}`.toLowerCase().includes(m.toLowerCase()))),_=async b=>{if(confirm("Delete this vendor? This will remove it from all agent libraries."))try{await o.mutateAsync(b),ie.success("Vendor deleted")}catch(k){ie.error(k.message)}};return e.jsx(Qs,{children:e.jsxs("div",{className:"max-w-6xl mx-auto p-4 md:p-8 space-y-6",children:[e.jsxs("div",{className:"flex items-start justify-between flex-wrap gap-4",children:[e.jsxs("div",{children:[e.jsxs("h1",{className:"text-2xl font-bold flex items-center gap-2",children:[e.jsx(Ti,{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(nn,{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(Gr,{className:"w-4 h-4 absolute left-3 top-1/2 -translate-y-1/2 text-muted-foreground"}),e.jsx(we,{className:"pl-9",placeholder:"Search vendors...",value:m,onChange:b=>f(b.target.value)})]}),e.jsxs("select",{value:g,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"}),mU.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..."}):x.length===0?e.jsxs("div",{className:"text-center py-16 border-2 border-dashed rounded-xl",children:[e.jsx(Ti,{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(nn,{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:x.map(b=>e.jsx(z7t,{vendor:b,onEdit:()=>{d(b),h(!0)},onDelete:()=>_(b.id),clickCount:l[b.id]},b.id))}),e.jsx(B7t,{open:u,onOpenChange:h,vendor:c,ownerType:"brokerage",brokerageId:s,showBrokerageOnlyFields:!0})]})})}const skn=[{value:"overview",label:"Portals",icon:G0},{value:"vendors",label:"Vendors",icon:Y2},{value:"referrals",label:"Referrals",icon:Io},{value:"branding",label:"Branding",icon:zc},{value:"questions",label:"Onboarding",icon:zm}];function nkn(){const[s,t]=$c(),n=s.get("tab")||"overview",[r,a]=N.useState(n),[i,l]=N.useState(!1),[o,c]=N.useState(!1);return N.useEffect(()=>{t(d=>{const u=new URLSearchParams(d);return u.set("tab",r),u},{replace:!0})},[r,t]),e.jsxs(Qs,{children:[e.jsx(ic,{children:e.jsx("title",{children:"Client Portals"})}),e.jsxs("div",{className:"max-w-6xl mx-auto p-4 md:p-8 space-y-6",children:[e.jsx("div",{className:"flex items-start justify-between flex-wrap gap-4",children:e.jsxs("div",{children:[e.jsxs("h1",{className:"text-2xl font-bold flex items-center gap-2",children:[e.jsx(Cn,{className:"w-6 h-6 text-primary"}),"Client Portals"]}),e.jsx("p",{className:"text-sm text-muted-foreground mt-1 max-w-2xl",children:"Your central hub for everything client-facing — manage active portals, curate trusted vendors, tune branding, and inbox referrals from happy clients."})]})}),e.jsx("div",{className:"border rounded-xl p-5 bg-card",children:e.jsxs("div",{className:"flex items-start gap-4",children:[e.jsx("div",{className:"rounded-lg bg-primary/10 p-3",children:e.jsx(DW,{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(cr,{to:"/mission-control/pipeline",children:"Open Deal Pipeline"})})]})}),e.jsxs(ya,{value:r,onValueChange:a,className:"w-full",children:[e.jsx(va,{className:"w-full justify-start overflow-x-auto h-auto flex-wrap",children:skn.map(d=>e.jsxs(ls,{value:d.value,className:"gap-2",children:[e.jsx(d.icon,{className:"w-4 h-4"}),d.label]},d.value))}),e.jsx(_s,{value:"overview",className:"mt-6",children:e.jsx(D7t,{})}),e.jsx(_s,{value:"vendors",className:"mt-6",children:e.jsx(rkn,{})}),e.jsx(_s,{value:"referrals",className:"mt-6",children:e.jsx(akn,{})}),e.jsx(_s,{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(zc,{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(sc,{className:"w-4 h-4 mr-2"}),"Edit Branding Defaults"]})]})]})})}),e.jsx(_s,{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(zm,{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(sc,{className:"w-4 h-4 mr-2"}),"Manage Questions"]})]})]})})})]})]}),e.jsx(I7t,{open:i,onOpenChange:l}),e.jsx(L7t,{open:o,onOpenChange:c})]})}function rkn(){return e.jsx($7t,{embedded:!0})}function akn(){return e.jsx(F7t,{})}const RF=s=>new Intl.DateTimeFormat("en-US",{timeZone:"America/New_York",month:"short",day:"numeric",year:"numeric"}).format(new Date(s));function ikn(s){return mt({queryKey:["client-portal-by-id",s],queryFn:async()=>{if(!s)return null;const{data:t,error:n}=await H.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 H.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 H.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 okn(){const{portalId:s}=uo(),t=tr(),n=Ya(),{data:r,isLoading:a}=ikn(s),{data:i=[]}=Qpn(s),{data:l=[]}=O7t(),o=VU(),c=bIt(),d=_It(),u=wIt(),[h,m]=N.useState(!1),[f,g]=N.useState(!1),[y,x]=N.useState(!1),[_,b]=N.useState(!1),k=(r==null?void 0:r.portal)??null,A=(r==null?void 0:r.deal)??null,T=N.useMemo(()=>k?l.filter(te=>te.portal_id===k.id):[],[l,k==null?void 0:k.id]);if(a)return e.jsx(Qs,{children:e.jsx("div",{className:"flex items-center justify-center py-24",children:e.jsx(us,{className:"h-6 w-6 animate-spin text-muted-foreground"})})});if(!k)return e.jsx(Qs,{children:e.jsxs("div",{className:"max-w-3xl mx-auto p-8 text-center",children:[e.jsx("h1",{className:"text-xl font-semibold mb-2",children:"Portal not found"}),e.jsx("p",{className:"text-sm text-muted-foreground mb-4",children:"This portal may have been deleted or you don't have access to it."}),e.jsx(B,{asChild:!0,variant:"outline",children:e.jsxs(cr,{to:"/mission-control/client-portals",children:[e.jsx(ka,{className:"w-4 h-4 mr-2"}),"Back to Portals"]})})]})});const P=j5(k.slug),I=(A==null?void 0:A.deal_name)||"Untitled deal",M=A==null?void 0:A.contact,L=M?`${M.first_name||""} ${M.last_name||""}`.trim():"",z=!!k.archived_at,$=()=>{navigator.clipboard.writeText(P),ie.success("Portal link copied!")},V=async te=>{try{await o.mutateAsync({id:k.id,is_enabled:te}),ie.success(te?"Portal enabled":"Portal disabled")}catch{ie.error("Failed to update")}},W=async()=>{try{await c.mutateAsync(k.id),ie.success("Portal archived")}catch{ie.error("Failed to archive")}},G=async()=>{try{await d.mutateAsync(k.id),ie.success("Portal restored")}catch{ie.error("Failed to restore")}},X=async()=>{try{await u.mutateAsync({id:k.id,dealId:k.deal_id}),ie.success("Portal deleted"),t("/mission-control/client-portals")}catch{ie.error("Failed to delete")}};return e.jsxs(Qs,{children:[e.jsx(ic,{children:e.jsxs("title",{children:[I," — Client Portal"]})}),e.jsxs("div",{className:"max-w-6xl mx-auto p-4 md:p-8 space-y-6",children:[e.jsx("div",{children:e.jsx(B,{asChild:!0,variant:"ghost",size:"sm",className:"-ml-2 text-muted-foreground",children:e.jsxs(cr,{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(Cn,{className:"w-5 h-5 text-primary"}),e.jsx("h1",{className:"text-2xl font-bold truncate",children:I}),e.jsx(We,{variant:"outline",className:z?"bg-muted text-muted-foreground":k.is_enabled?"bg-emerald-500/10 text-emerald-700 border-emerald-200":"bg-muted text-muted-foreground",children:z?"Archived":k.is_enabled?"Active":"Disabled"}),e.jsx(We,{variant:"outline",className:"capitalize text-xs",children:k.visibility})]}),e.jsxs("p",{className:"text-sm text-muted-foreground flex items-center gap-2 flex-wrap",children:[e.jsx(Ro,{className:"w-3.5 h-3.5"}),k.client_name||L||"No client name set",(M==null?void 0:M.email)&&e.jsxs(e.Fragment,{children:["· ",e.jsx(mn,{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(ga,{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:P})})]}),!z&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-xs text-muted-foreground",children:"Live"}),e.jsx(zn,{checked:k.is_enabled,onCheckedChange:V})]})]}),e.jsxs("div",{className:"mt-5 flex items-center gap-2 flex-wrap",children:[e.jsxs(B,{onClick:$,variant:"outline",size:"sm",children:[e.jsx(Pa,{className:"w-4 h-4 mr-1.5"})," Copy Link"]}),e.jsxs(B,{onClick:()=>window.open(P,"_blank"),variant:"outline",size:"sm",children:[e.jsx(Tr,{className:"w-4 h-4 mr-1.5"})," Preview"]}),e.jsxs(B,{onClick:()=>x(!0),size:"sm",children:[e.jsx(Rr,{className:"w-4 h-4 mr-1.5"})," Invite Client"]}),e.jsxs(B,{onClick:()=>g(!0),variant:"outline",size:"sm",children:[e.jsx(Qk,{className:"w-4 h-4 mr-1.5"})," Post Update"]}),e.jsxs(B,{onClick:()=>m(!0),variant:"outline",size:"sm",children:[e.jsx(sc,{className:"w-4 h-4 mr-1.5"})," Settings"]}),e.jsxs("div",{className:"ml-auto flex items-center gap-2",children:[z?e.jsxs(B,{onClick:G,variant:"outline",size:"sm",children:[e.jsx(a9,{className:"w-4 h-4 mr-1.5"})," Restore"]}):e.jsxs(B,{onClick:W,variant:"ghost",size:"sm",children:[e.jsx(xg,{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(qn,{className:"w-4 h-4"})})]})]})]}),e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-3",children:[e.jsx(Tne,{icon:Qk,label:"Updates Posted",value:i.length}),e.jsx(Tne,{icon:Io,label:"Referrals",value:T.length}),e.jsx(Tne,{icon:ta,label:"Inspection",value:k.inspection_date?RF(k.inspection_date):"—"}),e.jsx(Tne,{icon:ta,label:"Appraisal",value:k.appraisal_date?RF(k.appraisal_date):"—"})]}),e.jsxs(ya,{defaultValue:"updates",className:"w-full",children:[e.jsxs(va,{children:[e.jsxs(ls,{value:"updates",children:["Updates (",i.length,")"]}),e.jsxs(ls,{value:"referrals",children:["Referrals (",T.length,")"]}),e.jsx(ls,{value:"branding",children:"Branding"}),e.jsx(ls,{value:"details",children:"Details"})]}),e.jsx(_s,{value:"updates",className:"mt-4",children:e.jsx(_e,{children:e.jsxs(De,{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:()=>g(!0),children:[e.jsx(Qk,{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(Qk,{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(te=>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:te.title}),te.is_stage_change&&e.jsx(We,{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:RF(te.created_at)}),te.content&&e.jsx("p",{className:"text-sm text-muted-foreground mt-2 whitespace-pre-wrap",children:te.content}),te.video_url&&e.jsxs("a",{href:te.video_url,target:"_blank",rel:"noreferrer",className:"inline-flex items-center gap-1 text-xs text-primary hover:underline mt-2",children:[e.jsx(na,{className:"w-3 h-3"})," View video"]})]})})},te.id))})]})})}),e.jsx(_s,{value:"referrals",className:"mt-4",children:e.jsx(_e,{children:e.jsxs(De,{className:"p-4",children:[e.jsx("h3",{className:"font-semibold mb-4",children:"Referrals from this Portal"}),T.length===0?e.jsxs("div",{className:"text-center py-12 border-2 border-dashed rounded-lg",children:[e.jsx(Io,{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:T.map(te=>e.jsx(cr,{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:te.friend_name}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[te.friend_email||te.friend_phone||"No contact info"," · ",RF(te.created_at)]})]}),e.jsx(We,{variant:"outline",className:"text-xs capitalize",children:te.status})]})},te.id))})]})})}),e.jsx(_s,{value:"branding",className:"mt-4",children:e.jsx(_e,{children:e.jsx(De,{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(zc,{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(sc,{className:"w-4 h-4 mr-2"}),"Edit Branding (in Settings)"]})]})]})})})}),e.jsx(_s,{value:"details",className:"mt-4",children:e.jsx(_e,{children:e.jsxs(De,{className:"p-6 space-y-4",children:[e.jsx(CC,{label:"Visibility",value:k.visibility}),e.jsx(CC,{label:"Onboarding Required",value:k.require_onboarding?"Yes":"No"}),e.jsx(CC,{label:"Allow Spouse",value:k.allow_spouse?"Yes":"No"}),e.jsx(CC,{label:"Notify Client on Updates",value:k.notify_client?"Yes":"No"}),e.jsx(CC,{label:"Show Post-Close Tips",value:k.show_post_close_tips?"Yes":"No"}),e.jsx(CC,{label:"Slug",value:k.slug,mono:!0}),e.jsx(CC,{label:"Created",value:RF(k.created_at)}),e.jsx(CC,{label:"Last Updated",value:RF(k.updated_at)}),e.jsx("div",{className:"pt-2",children:e.jsxs(B,{variant:"outline",onClick:()=>m(!0),children:[e.jsx(sc,{className:"w-4 h-4 mr-2"})," Edit All Settings"]})})]})})})]})]}),e.jsx(HWe,{open:h,onOpenChange:m,portal:k,dealOwnerId:n||""}),e.jsx(GWe,{open:f,onOpenChange:g,portalId:k.id,portalSlug:k.slug,notifyClient:k.notify_client}),e.jsx(WWe,{open:y,onOpenChange:x,portal:k,dealName:I}),e.jsx(Fl,{open:_,onOpenChange:b,children:e.jsxs(kl,{children:[e.jsxs(Sl,{children:[e.jsx(Al,{children:"Permanently delete this portal?"}),e.jsx(Tl,{children:"This removes the portal and all its updates. The client will lose access. This action cannot be undone."})]}),e.jsxs(Cl,{children:[e.jsx(El,{children:"Cancel"}),e.jsx(wl,{onClick:X,className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:"Delete Permanently"})]})]})})]})}function Tne({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 CC({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 gze=[{value:"video_intro",label:"Video Intro",icon:na,description:"Add an intro video"},{value:"testimonials",label:"Testimonials",icon:f5,description:"Client testimonials carousel"},{value:"specialties",label:"Specialties",icon:pf,description:"Tags for your specialties"},{value:"custom_links",label:"Custom Links",icon:cd,description:"Custom CTA buttons"},{value:"social_media",label:"Social Media",icon:Md,description:"Links to your social profiles"}],lkn=["First-Time Buyers","Luxury Homes","Investment Properties","Relocation","New Construction","Condos & Townhomes","Waterfront","Commercial","Land & Lots","Senior Living","Military/VA","Short Sales & Foreclosures"],ckn={video_intro:{video_url:""},testimonials:{testimonials:[{name:"",quote:"",role:""}]},specialties:{tags:[]},custom_links:{links:[{label:"",url:""}]},social_media:{platforms:[]}};function U7t({cardId:s}){const{data:t,isLoading:n}=Fis(s),r=zis(),a=Bis(),i=$is(),[l,o]=N.useState(!1),[c,d]=N.useState(""),[u,h]=N.useState(null);if(n)return e.jsxs("div",{className:"space-y-3",children:[e.jsx(xn,{className:"h-16 w-full"}),e.jsx(xn,{className:"h-16 w-full"})]});const m=()=>{c&&r.mutate({card_id:s,block_type:c,sort_order:(t==null?void 0:t.length)||0,config:ckn[c]||{}},{onSuccess:()=>{o(!1),d("")}})},f=b=>{a.mutate({id:b.id,is_visible:!b.is_visible})},g=(b,k)=>{if(!t)return;const A=t.findIndex(I=>I.id===b.id),T=k==="up"?A-1:A+1;if(T<0||T>=t.length)return;const P=t[T];a.mutate({id:b.id,sort_order:P.sort_order}),a.mutate({id:P.id,sort_order:b.sort_order})},y=b=>{confirm("Remove this block from this card?")&&i.mutate(b.id)},x=(b,k)=>{a.mutate({id:b.id,config:k},{onSuccess:()=>h(null)})},_=b=>gze.find(k=>k.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(nn,{className:"h-4 w-4 mr-1"})," Add Block"]})]}):e.jsxs(e.Fragment,{children:[t.map((b,k)=>{const A=_(b.block_type),T=(A==null?void 0:A.icon)||pf;return e.jsx(_e,{className:b.is_visible?"":"opacity-50",children:e.jsx(De,{className:"p-3",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Mp,{className:"h-4 w-4 text-muted-foreground flex-shrink-0"}),e.jsx(T,{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:(A==null?void 0:A.label)||b.block_type}),e.jsx("p",{className:"text-xs text-muted-foreground truncate",children:dkn(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:()=>g(b,"up"),disabled:k===0,children:e.jsx(Om,{className:"h-3 w-3"})}),e.jsx(B,{variant:"ghost",size:"icon",className:"h-7 w-7",onClick:()=>g(b,"down"),disabled:k===t.length-1,children:e.jsx(Wf,{className:"h-3 w-3"})}),e.jsx(B,{variant:"ghost",size:"icon",className:"h-7 w-7",onClick:()=>f(b),children:b.is_visible?e.jsx(da,{className:"h-3 w-3"}):e.jsx(V0,{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(qn,{className:"h-3 w-3"})})]})]})})},b.id)}),e.jsxs(B,{variant:"outline",size:"sm",className:"w-full",onClick:()=>o(!0),children:[e.jsx(nn,{className:"h-4 w-4 mr-1"})," Add Block"]})]}),e.jsx(Bs,{open:l,onOpenChange:o,children:e.jsxs(Fs,{children:[e.jsx(qs,{children:e.jsx($s,{children:"Add Block"})}),e.jsx("div",{className:"grid gap-3",children:gze.map(b=>{const k=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(k,{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(Cr,{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(ukn,{block:u,onSave:b=>x(u,b),onClose:()=>h(null)})]})}function dkn(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 ukn({block:s,onSave:t,onClose:n}){const[r,a]=N.useState(s.config),i=gze.find(l=>l.value===s.block_type);return e.jsx(Bs,{open:!0,onOpenChange:n,children:e.jsxs(Fs,{className:"max-w-lg max-h-[80vh] overflow-y-auto",children:[e.jsx(qs,{children:e.jsxs($s,{children:["Edit ",i==null?void 0:i.label]})}),s.block_type==="video_intro"&&e.jsx(hkn,{config:r,onChange:a,cardId:s.card_id}),s.block_type==="testimonials"&&e.jsx(mkn,{config:r,onChange:a}),s.block_type==="specialties"&&e.jsx(pkn,{config:r,onChange:a}),s.block_type==="custom_links"&&e.jsx(fkn,{config:r,onChange:a}),s.block_type==="social_media"&&e.jsx(gkn,{config:r,onChange:a}),e.jsxs(Cr,{children:[e.jsx(B,{variant:"outline",onClick:n,children:"Cancel"}),e.jsx(B,{onClick:()=>t(r),children:"Save"})]})]})})}function hkn({config:s,onChange:t,cardId:n}){var f,g;const[r,a]=N.useState(""),[i,l]=N.useState((f=s.video_url)!=null&&f.includes("youtube")||(g=s.video_url)!=null&&g.includes("youtu.be")?"youtube":"library"),{data:o}=mt({queryKey:["card-owner",n],queryFn:async()=>{const{data:y}=await H.from("agent_cards").select("user_id").eq("id",n).single();return y==null?void 0:y.user_id},enabled:!!n}),{data:c,isLoading:d}=mt({queryKey:["agent-videos-library",o],queryFn:async()=>{const{data:y,error:x}=await H.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(x)throw x;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 k;const x=(k=y.playback_url)==null?void 0:k.match(/\/(?:play|embed)\/(\d+)\//),b=`https://iframe.mediadelivery.net/embed/${x?x[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(ya,{value:i,onValueChange:l,children:[e.jsxs(va,{className:"w-full",children:[e.jsx(ls,{value:"library",className:"flex-1",children:"Video Library"}),e.jsx(ls,{value:"youtube",className:"flex-1",children:"YouTube URL"})]}),e.jsxs(_s,{value:"library",className:"space-y-3 mt-3",children:[e.jsxs("div",{className:"relative",children:[e.jsx(Gr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(we,{placeholder:"Search videos...",value:r,onChange:y=>a(y.target.value),className:"pl-9"})]}),e.jsx(lo,{className:"h-[240px]",children:d?e.jsxs("div",{className:"space-y-2",children:[e.jsx(xn,{className:"h-14 w-full"}),e.jsx(xn,{className:"h-14 w-full"})]}):u.length===0?e.jsx("p",{className:"text-sm text-muted-foreground text-center py-8",children:(c==null?void 0:c.length)===0?"No videos in library yet":"No matching videos"}):e.jsx("div",{className:"space-y-1.5 pr-3",children:u.map(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:x=>{var _;x.currentTarget.style.display="none",(_=x.currentTarget.nextElementSibling)==null||_.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(na,{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(pa,{className:"h-4 w-4 text-primary flex-shrink-0"})]},y.id))})})]}),e.jsx(_s,{value:"youtube",className:"space-y-3 mt-3",children:e.jsxs("div",{children:[e.jsx(re,{children:"YouTube URL"}),e.jsx(we,{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 mkn({config:s,onChange:t}){const n=s.testimonials||[],r=(l,o,c)=>{const d=[...n];d[l]={...d[l],[o]:c},t({...s,testimonials:d})},a=()=>t({...s,testimonials:[...n,{name:"",quote:"",role:""}]}),i=l=>t({...s,testimonials:n.filter((o,c)=>c!==l)});return e.jsxs("div",{className:"space-y-4",children:[n.map((l,o)=>e.jsx(_e,{children:e.jsxs(De,{className:"p-3 space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs(re,{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(qn,{className:"h-3 w-3"})})]}),e.jsx(we,{placeholder:"Client name",value:l.name,onChange:c=>r(o,"name",c.target.value)}),e.jsx(we,{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(nn,{className:"h-4 w-4 mr-1"})," Add Testimonial"]})]})}function pkn({config:s,onChange:t}){const n=s.tags||[],[r,a]=N.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(re,{className:"text-sm mb-2 block",children:"Preset Specialties"}),e.jsx("div",{className:"flex flex-wrap gap-2",children:lkn.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(re,{className:"text-sm mb-2 block",children:"Custom Tag"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(we,{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(re,{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 fkn({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(we,{placeholder:"Button label",value:l.label,onChange:c=>r(o,"label",c.target.value)}),e.jsx(we,{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(qn,{className:"h-3 w-3"})})]},o)),e.jsxs(B,{variant:"outline",size:"sm",onClick:a,className:"w-full",children:[e.jsx(nn,{className:"h-4 w-4 mr-1"})," Add Link"]})]})}const Vft=[{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 gkn({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=Vft.filter(c=>!n.find(d=>d.platform===c.value)),o=c=>{const d=BDe[c],u=Vft.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(we,{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(qn,{className:"h-3.5 w-3.5"})})]},d)})}),l.length>0&&e.jsxs("div",{children:[e.jsx(re,{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=BDe[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."})]})}var xkn=Object.defineProperty,U5e=Object.getOwnPropertySymbols,q7t=Object.prototype.hasOwnProperty,V7t=Object.prototype.propertyIsEnumerable,Hft=(s,t,n)=>t in s?xkn(s,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):s[t]=n,xze=(s,t)=>{for(var n in t||(t={}))q7t.call(t,n)&&Hft(s,n,t[n]);if(U5e)for(var n of U5e(t))V7t.call(t,n)&&Hft(s,n,t[n]);return s},yze=(s,t)=>{var n={};for(var r in s)q7t.call(s,r)&&t.indexOf(r)<0&&(n[r]=s[r]);if(s!=null&&U5e)for(var r of U5e(s))t.indexOf(r)<0&&V7t.call(s,r)&&(n[r]=s[r]);return n};/** * @license QR Code generator library (TypeScript) * Copyright (c) Project Nayuki. * SPDX-License-Identifier: MIT */var ER;(s=>{const t=class Dc{constructor(c,d,u,h){if(this.version=c,this.errorCorrectionLevel=d,this.modules=[],this.isFunction=[],cDc.MAX_VERSION)throw new RangeError("Version value out of range");if(h<-1||h>7)throw new RangeError("Mask value out of range");this.size=c*4+17;let m=[];for(let g=0;g7)throw new RangeError("Invalid value");let g,y;for(g=u;;g++){const k=Dc.getNumDataCodewords(g,d)*8,A=l.getTotalBits(c,g);if(A<=k){y=A;break}if(g>=h)throw new RangeError("Data too long")}for(const k of[Dc.Ecc.MEDIUM,Dc.Ecc.QUARTILE,Dc.Ecc.HIGH])f&&y<=Dc.getNumDataCodewords(g,k)*8&&(d=k);let x=[];for(const k of c){n(k.mode.modeBits,4,x),n(k.numChars,k.mode.numCharCountBits(g),x);for(const A of k.getData())x.push(A)}a(x.length==y);const _=Dc.getNumDataCodewords(g,d)*8;a(x.length<=_),n(0,Math.min(4,_-x.length),x),n(0,(8-x.length%8)%8,x),a(x.length%8==0);for(let k=236;x.length<_;k^=253)n(k,8,x);let b=[];for(;b.length*8b[A>>>3]|=k<<7-(A&7)),new Dc(g,d,b,m)}getModule(c,d){return 0<=c&&c>>9)*1335;const h=(d<<10|u)^21522;a(h>>>15==0);for(let m=0;m<=5;m++)this.setFunctionModule(8,m,r(h,m));this.setFunctionModule(8,7,r(h,6)),this.setFunctionModule(8,8,r(h,7)),this.setFunctionModule(7,8,r(h,8));for(let m=9;m<15;m++)this.setFunctionModule(14-m,8,r(h,m));for(let m=0;m<8;m++)this.setFunctionModule(this.size-1-m,8,r(h,m));for(let m=8;m<15;m++)this.setFunctionModule(8,this.size-15+m,r(h,m));this.setFunctionModule(8,this.size-8,!0)}drawVersion(){if(this.version<7)return;let c=this.version;for(let u=0;u<12;u++)c=c<<1^(c>>>11)*7973;const d=this.version<<12|c;a(d>>>18==0);for(let u=0;u<18;u++){const h=r(d,u),m=this.size-11+u%3,f=Math.floor(u/3);this.setFunctionModule(m,f,h),this.setFunctionModule(f,m,h)}}drawFinderPattern(c,d){for(let u=-4;u<=4;u++)for(let h=-4;h<=4;h++){const m=Math.max(Math.abs(h),Math.abs(u)),f=c+h,g=d+u;0<=f&&f{(k!=y-m||T>=g)&&b.push(A[k])});return a(b.length==f),b}drawCodewords(c){if(c.length!=Math.floor(Dc.getNumRawDataModules(this.version)/8))throw new RangeError("Invalid argument");let d=0;for(let u=this.size-1;u>=1;u-=2){u==6&&(u=5);for(let h=0;h>>3],7-(d&7)),d++)}}a(d==c.length*8)}applyMask(c){if(c<0||c>7)throw new RangeError("Mask value out of range");for(let d=0;d5&&c++):(this.finderPenaltyAddHistory(g,y),f||(c+=this.finderPenaltyCountPatterns(y)*Dc.PENALTY_N3),f=this.modules[m][x],g=1);c+=this.finderPenaltyTerminateAndCount(f,g,y)*Dc.PENALTY_N3}for(let m=0;m5&&c++):(this.finderPenaltyAddHistory(g,y),f||(c+=this.finderPenaltyCountPatterns(y)*Dc.PENALTY_N3),f=this.modules[x][m],g=1);c+=this.finderPenaltyTerminateAndCount(f,g,y)*Dc.PENALTY_N3}for(let m=0;mf+(g?1:0),d);const u=this.size*this.size,h=Math.ceil(Math.abs(d*20-u*10)/u)-1;return a(0<=h&&h<=9),c+=h*Dc.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.lengthDc.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(Dc.getNumRawDataModules(c)/8)-Dc.ECC_CODEWORDS_PER_BLOCK[d.ordinal][c]*Dc.NUM_ERROR_CORRECTION_BLOCKS[d.ordinal][c]}static reedSolomonComputeDivisor(c){if(c<1||c>255)throw new RangeError("Degree out of range");let d=[];for(let h=0;h0);for(const h of c){const m=h^u.shift();u.push(0),d.forEach((f,g)=>u[g]^=Dc.reedSolomonMultiply(f,m))}return u}static reedSolomonMultiply(c,d){if(c>>>8||d>>>8)throw new RangeError("Byte out of range");let u=0;for(let h=7;h>=0;h--)u=u<<1^(u>>>7)*285,u^=(d>>>h&1)*c;return a(u>>>8==0),u}finderPenaltyCountPatterns(c){const d=c[1];a(d<=this.size*3);const u=d>0&&c[2]==d&&c[3]==d*3&&c[4]==d&&c[5]==d;return(u&&c[0]>=d*4&&c[6]>=d?1:0)+(u&&c[6]>=d*4&&c[0]>=d?1:0)}finderPenaltyTerminateAndCount(c,d,u){return c&&(this.finderPenaltyAddHistory(d,u),d=0),d+=this.size,this.finderPenaltyAddHistory(d,u),this.finderPenaltyCountPatterns(u)}finderPenaltyAddHistory(c,d){d[0]==0&&(c+=this.size),d.pop(),d.unshift(c)}};t.MIN_VERSION=1,t.MAX_VERSION=40,t.PENALTY_N1=3,t.PENALTY_N2=3,t.PENALTY_N3=40,t.PENALTY_N4=10,t.ECC_CODEWORDS_PER_BLOCK=[[-1,7,10,15,20,26,18,20,24,30,18,20,24,26,30,22,24,28,30,28,28,28,28,30,30,26,28,30,30,30,30,30,30,30,30,30,30,30,30,30,30],[-1,10,16,26,18,24,16,18,22,22,26,30,22,22,24,24,28,28,26,26,26,26,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28],[-1,13,22,18,26,18,24,18,22,20,24,28,26,24,20,30,24,28,28,26,30,28,30,30,30,30,28,30,30,30,30,30,30,30,30,30,30,30,30,30,30],[-1,17,28,22,16,22,28,26,26,24,28,24,28,22,24,24,30,28,28,26,28,30,24,30,30,30,30,30,30,30,30,30,30,30,30,30,30,30,30,30,30]],t.NUM_ERROR_CORRECTION_BLOCKS=[[-1,1,1,1,1,1,2,2,2,2,4,4,4,4,4,6,6,6,6,7,8,8,9,9,10,12,12,12,13,14,15,16,17,18,19,19,20,21,22,24,25],[-1,1,1,1,2,2,4,4,4,5,5,5,8,9,9,10,10,11,13,14,16,17,17,18,20,21,23,25,26,28,29,31,33,35,37,38,40,43,45,47,49],[-1,1,1,2,2,4,4,6,6,8,8,8,10,12,16,12,17,16,18,21,20,23,23,25,27,29,34,34,35,38,40,43,45,48,51,53,56,59,62,65,68],[-1,1,1,2,4,4,4,5,6,8,8,11,11,16,16,18,16,19,21,25,25,25,34,30,32,35,37,40,42,45,48,51,54,57,60,63,66,70,74,77,81]],s.QrCode=t;function n(o,c,d){if(c<0||c>31||o>>>c)throw new RangeError("Value out of range");for(let u=c-1;u>=0;u--)d.push(o>>>u&1)}function r(o,c){return(o>>>c&1)!=0}function a(o){if(!o)throw new Error("Assertion error")}const i=class Qp{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 Qp(Qp.Mode.BYTE,c.length,d)}static makeNumeric(c){if(!Qp.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={}))})(ER||(ER={}));(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={}))})(ER||(ER={}));var W7=ER;/** * @license qrcode.react * Copyright (c) Paul O'Shannessy * SPDX-License-Identifier: ISC */var ykn={L:W7.QrCode.Ecc.LOW,M:W7.QrCode.Ecc.MEDIUM,Q:W7.QrCode.Ecc.QUARTILE,H:W7.QrCode.Ecc.HIGH},H7t=128,G7t="L",W7t="#FFFFFF",K7t="#000000",Y7t=!1,Z7t=1,vkn=4,bkn=0,_kn=.1;function X7t(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 Q7t(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 wkn(s,t,n,r){if(r==null)return null;const a=s.length+n*2,i=Math.floor(t*_kn),l=a/t,o=(r.width||i)*l,c=(r.height||i)*l,d=r.x==null?s.length/2-o/2:r.x*l,u=r.y==null?s.length/2-c/2:r.y*l,h=r.opacity==null?1:r.opacity;let m=null;if(r.excavate){let g=Math.floor(d),y=Math.floor(u),x=Math.ceil(o+d-g),_=Math.ceil(c+u-y);m={x:g,y,w:x,h:_}}const f=r.crossOrigin;return{x:d,y:u,h:c,w:o,excavation:m,opacity:h,crossOrigin:f}}function jkn(s,t){return t!=null?Math.max(Math.floor(t),0):s?vkn:bkn}function J7t({value:s,level:t,minVersion:n,includeMargin:r,marginSize:a,imageSettings:i,size:l,boostLevel:o}){let c=Rt.useMemo(()=>{const g=(Array.isArray(s)?s:[s]).reduce((y,x)=>(y.push(...W7.QrSegment.makeSegments(x)),y),[]);return W7.QrCode.encodeSegments(g,ykn[t],n,void 0,void 0,o)},[s,t,n,o]);const{cells:d,margin:u,numCells:h,calculatedImageSettings:m}=Rt.useMemo(()=>{let f=c.getModules();const g=jkn(r,a),y=f.length+g*2,x=wkn(f,l,g,i);return{cells:f,margin:g,numCells:y,calculatedImageSettings:x}},[c,l,i,r,a]);return{qrcode:c,margin:u,cells:d,numCells:h,calculatedImageSettings:m}}var Nkn=function(){try{new Path2D().addPath(new Path2D)}catch{return!1}return!0}(),kkn=Rt.forwardRef(function(t,n){const r=t,{value:a,size:i=H7t,level:l=G7t,bgColor:o=W7t,fgColor:c=K7t,includeMargin:d=Y7t,minVersion:u=Z7t,boostLevel:h,marginSize:m,imageSettings:f}=r,y=yze(r,["value","size","level","bgColor","fgColor","includeMargin","minVersion","boostLevel","marginSize","imageSettings"]),{style:x}=y,_=yze(y,["style"]),b=f==null?void 0:f.src,k=Rt.useRef(null),A=Rt.useRef(null),T=Rt.useCallback(G=>{k.current=G,typeof n=="function"?n(G):n&&(n.current=G)},[n]),[P,I]=Rt.useState(!1),{margin:M,cells:L,numCells:z,calculatedImageSettings:$}=J7t({value:a,level:l,minVersion:u,boostLevel:h,includeMargin:d,marginSize:m,imageSettings:f,size:i});Rt.useEffect(()=>{if(k.current!=null){const G=k.current,X=G.getContext("2d");if(!X)return;let te=L;const ne=A.current,me=$!=null&&ne!==null&&ne.complete&&ne.naturalHeight!==0&&ne.naturalWidth!==0;me&&$.excavation!=null&&(te=Q7t(L,$.excavation));const ue=window.devicePixelRatio||1;G.height=G.width=i*ue;const ce=i/z*ue;X.scale(ce,ce),X.fillStyle=o,X.fillRect(0,0,z,z),X.fillStyle=c,Nkn?X.fill(new Path2D(X7t(te,M))):L.forEach(function(ae,he){ae.forEach(function(xe,ve){xe&&X.fillRect(ve+M,he+M,1,1)})}),$&&(X.globalAlpha=$.opacity),me&&X.drawImage(ne,$.x+M,$.y+M,$.w,$.h)}}),Rt.useEffect(()=>{I(!1)},[b]);const V=xze({height:i,width:i},x);let W=null;return b!=null&&(W=Rt.createElement("img",{src:b,key:b,style:{display:"none"},onLoad:()=>{I(!0)},ref:A,crossOrigin:$==null?void 0:$.crossOrigin})),Rt.createElement(Rt.Fragment,null,Rt.createElement("canvas",xze({style:V,height:i,width:i,ref:T,role:"img"},_)),W)});kkn.displayName="QRCodeCanvas";var IJ=Rt.forwardRef(function(t,n){const r=t,{value:a,size:i=H7t,level:l=G7t,bgColor:o=W7t,fgColor:c=K7t,includeMargin:d=Y7t,minVersion:u=Z7t,boostLevel:h,title:m,marginSize:f,imageSettings:g}=r,y=yze(r,["value","size","level","bgColor","fgColor","includeMargin","minVersion","boostLevel","title","marginSize","imageSettings"]),{margin:x,cells:_,numCells:b,calculatedImageSettings:k}=J7t({value:a,level:l,minVersion:u,boostLevel:h,includeMargin:d,marginSize:f,imageSettings:g,size:i});let A=_,T=null;g!=null&&k!=null&&(k.excavation!=null&&(A=Q7t(_,k.excavation)),T=Rt.createElement("image",{href:g.src,height:k.h,width:k.w,x:k.x+x,y:k.y+x,preserveAspectRatio:"none",opacity:k.opacity,crossOrigin:k.crossOrigin}));const P=X7t(A,x);return Rt.createElement("svg",xze({height:i,width:i,viewBox:`0 0 ${b} ${b}`,ref:n,role:"img"},y),!!m&&Rt.createElement("title",null,m),Rt.createElement("path",{fill:o,d:`M0,0 h${b}v${b}H0z`,shapeRendering:"crispEdges"}),Rt.createElement("path",{fill:c,d:P,shapeRendering:"crispEdges"}),T)});IJ.displayName="QRCodeSVG";function Skn({slug:s,agentName:t}){const n=N.useRef(null),r=`https://cards.relevelup.com/${s}`,a=N.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(),ie.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(re,{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(IJ,{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(oi,{className:"h-3.5 w-3.5"}),"Download PNG"]})]})]})]})}function WPe(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 Ckn(){const{user:s}=Ls(),{data:t,isLoading:n}=Dis(s==null?void 0:s.id),r=qU(),[a,i]=N.useState(null),l=N.useMemo(()=>a||(t?WPe(t):null),[a,t]);if(n)return e.jsx(Qs,{children:e.jsxs("div",{className:"max-w-2xl mx-auto p-4 space-y-4",children:[e.jsx(xn,{className:"h-8 w-48"}),e.jsx(xn,{className:"h-32 w-full"}),e.jsx(xn,{className:"h-32 w-full"})]})});if(!t)return e.jsx(Qs,{children:e.jsx(Tkn,{userId:s==null?void 0:s.id})});const o=l||WPe(t),c=d=>{i(u=>{const h=u||WPe(t);return typeof d=="function"?d(h):d})};return e.jsx(Qs,{children:e.jsxs("div",{className:"flex gap-6 items-start",children:[e.jsxs("div",{className:`${r?"w-full":"flex-1 min-w-0"} max-w-2xl p-4 space-y-6 animate-fade-in`,children:[e.jsx(Ekn,{card:t}),e.jsx(Ikn,{card:t,form:o,setForm:c})]}),!r&&e.jsx("div",{className:"w-[400px] shrink-0","aria-hidden":"true"}),!r&&e.jsx("div",{className:"fixed right-8 top-[5.5rem] w-[400px] z-30",style:{height:"calc(100vh - 6.5rem)"},children:e.jsxs("div",{className:"rounded-xl border bg-muted/30 overflow-hidden h-full flex flex-col",children:[e.jsxs("div",{className:"flex items-center gap-2 px-4 py-2.5 border-b bg-card shrink-0",children:[e.jsx(hj,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{className:"text-sm font-medium",children:"Live Preview"})]}),e.jsx("div",{className:"flex-1 overflow-y-auto",children:e.jsx(Akn,{card:t,form:o})})]})})]})})}function Akn({card:s,form:t}){const{data:n}=mt({queryKey:["card-preview-profile",s.user_id],queryFn:async()=>{const{data:a}=await H.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 H.storage.from("avatars").list(`${s.user_id}`);if(l&&l.length>0){const{data:o}=H.storage.from("avatars").getPublicUrl(`${s.user_id}/${l[0].name}`);i=`${o.publicUrl}?t=${Date.now()}`}}return{...a,avatar_url:i}}}),r=N.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(W$e,{card:r})})}function Tkn({userId:s}){var c;const[t,n]=N.useState(""),r=H2t(),{data:a}=mt({queryKey:["my-profile-for-card",s],queryFn:async()=>{if(!s)return null;const{data:d}=await H.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){ie.error("Please enter a URL slug for your card");return}r.mutate({user_id:s,slug:d,is_published:!0},{onSuccess:()=>ie.success("Your digital card has been created!")})},o=[{icon:au,title:"Shareable Link",desc:"One link that works everywhere"},{icon:ff,title:"Lead Capture",desc:"Collect leads automatically"},{icon:mf,title:"Always Up-to-Date",desc:"Edit anytime, changes are instant"},{icon:zc,title:"Fully Customizable",desc:"Themes, colors, and content blocks"}];return e.jsxs("div",{className:"max-w-2xl mx-auto p-4 animate-fade-in",children:[e.jsxs("div",{className:"relative overflow-hidden rounded-2xl bg-gradient-to-br from-primary/90 via-primary to-primary/80 p-8 md:p-12 mb-8 text-primary-foreground",children:[e.jsx("div",{className:"absolute inset-0 bg-[radial-gradient(circle_at_30%_20%,rgba(255,255,255,0.15),transparent_50%)]"}),e.jsx("div",{className:"absolute inset-0 bg-[radial-gradient(circle_at_80%_80%,rgba(0,0,0,0.1),transparent_50%)]"}),e.jsxs("div",{className:"relative z-10",children:[e.jsxs("div",{className:"inline-flex items-center gap-2 px-3 py-1 rounded-full bg-white/20 backdrop-blur-sm text-sm font-medium mb-4",children:[e.jsx(Cn,{className:"h-3.5 w-3.5"}),"New Feature"]}),e.jsx("h1",{className:"text-3xl md:text-4xl font-bold mb-3 tracking-tight",children:"Your Digital Business Card"}),e.jsx("p",{className:"text-primary-foreground/80 text-lg max-w-md leading-relaxed",children:"Ditch the paper. Share a beautiful, interactive card that captures leads and makes a lasting impression."})]})]}),e.jsx("div",{className:"grid grid-cols-2 gap-3 mb-8",children:o.map(d=>e.jsxs("div",{className:"flex items-start gap-3 p-4 rounded-xl border bg-card hover:shadow-md transition-shadow",children:[e.jsx("div",{className:"mt-0.5 p-2 rounded-lg bg-primary/10 shrink-0",children:e.jsx(d.icon,{className:"h-4 w-4 text-primary"})}),e.jsxs("div",{children:[e.jsx("p",{className:"font-semibold text-sm",children:d.title}),e.jsx("p",{className:"text-xs text-muted-foreground",children:d.desc})]})]},d.title))}),e.jsxs(_e,{className:"shadow-lg border-2",children:[e.jsxs(zt,{className:"text-center pb-2",children:[e.jsx(qt,{className:"text-xl",children:"Set Up Your Card"}),e.jsx(_r,{children:"Choose a URL slug — this is the link you'll share with clients"})]}),e.jsxs(De,{className:"p-6 pt-2 space-y-5",children:[e.jsxs("div",{children:[e.jsx(re,{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(we,{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(Cn,{className:"h-4 w-4 mr-2"}),r.isPending?"Creating...":"Create My Card"]})]})]})]})}function Ekn({card:s}){const n=`https://cards.relevelup.com/${s.slug}`,r=()=>{navigator.clipboard.writeText(n),ie.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(We,{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(au,{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(Pa,{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(Tr,{className:"h-3.5 w-3.5"})," Preview"]})})]})]})})}function Mkn({userId:s}){const t=as(),n=N.useRef(null),[r,a]=N.useState(!1),[i,l]=N.useState(""),{data:o,isLoading:c}=mt({queryKey:["card-editor-profile",s],queryFn:async()=>{const{data:$}=await H.from("profiles").select("name, email, phone, avatar_url").eq("id",s).single();let V=($==null?void 0:$.avatar_url)||null;if(!V){const{data:W}=await H.storage.from("avatars").list(`${s}`);if(W&&W.length>0){const{data:G}=H.storage.from("avatars").getPublicUrl(`${s}/${W[0].name}`);V=`${G.publicUrl}?t=${Date.now()}`,await H.from("profiles").update({avatar_url:V}).eq("id",s)}}return{...$,avatar_url:V}}}),[d,u]=N.useState(null),[h,m]=N.useState(null),[f,g]=N.useState(null),[y,x]=N.useState(!1),_=d??(o==null?void 0:o.name)??"",b=h??(o==null?void 0:o.phone)??"",k=f??(o==null?void 0:o.email)??"",A=o==null?void 0:o.avatar_url,T=((o==null?void 0:o.name)||"A").split(" ").map($=>$[0]).join("").toUpperCase().slice(0,2),P=!(o!=null&&o.avatar_url)||!(o!=null&&o.phone),I=_t({mutationFn:async $=>{const{error:V}=await H.from("profiles").update($).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"]}),ie.success("Profile updated!")},onError:()=>ie.error("Failed to update profile")}),M=()=>{const $={};if(d!==null&&d!==(o==null?void 0:o.name)&&($.name=d),h!==null&&h!==(o==null?void 0:o.phone)&&($.phone=h||null),f!==null&&f!==(o==null?void 0:o.email)&&($.email=f),Object.keys($).length===0){ie.info("No changes to save");return}I.mutate($)},L=$=>{var G;const V=(G=$.target.files)==null?void 0:G[0];if(!V)return;if(!V.type.startsWith("image/")){ie.error("Please select an image file");return}const W=new FileReader;W.onloadend=()=>{l(W.result),a(!0)},W.readAsDataURL(V),$.target.value=""},z=async $=>{x(!0);try{const{data:V}=await H.storage.from("avatars").list(`${s}`);V&&V.length>0&&await H.storage.from("avatars").remove(V.map(ne=>`${s}/${ne.name}`));const W=`${s}/avatar.jpg`,{error:G}=await H.storage.from("avatars").upload(W,$,{upsert:!0,contentType:"image/jpeg"});if(G)throw G;const{data:X}=H.storage.from("avatars").getPublicUrl(W),te=X.publicUrl+"?t="+Date.now();await H.from("profiles").update({avatar_url:te}).eq("id",s),t.invalidateQueries({queryKey:["card-editor-profile",s]}),t.invalidateQueries({queryKey:["card-preview-profile",s]}),t.invalidateQueries({queryKey:["agent-card-user"]}),ie.success("Photo updated!")}catch{ie.error("Failed to upload photo")}finally{x(!1)}};return c?e.jsx(xn,{className:"h-32 w-full rounded-xl"}):e.jsxs(e.Fragment,{children:[e.jsx(_e,{className:P?"border-amber-300 dark:border-amber-700":"",children:e.jsxs(De,{className:"p-5 space-y-4",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[e.jsx(re,{className:"text-sm font-semibold",children:"Profile Info"}),P&&e.jsxs("span",{className:"inline-flex items-center gap-1 text-xs text-amber-600 dark:text-amber-400 font-medium",children:[e.jsx(Uo,{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 $;return($=n.current)==null?void 0:$.click()},children:[e.jsxs(Ua,{className:"h-16 w-16 ring-2 ring-muted",children:[e.jsx(Gi,{src:A||void 0,alt:_}),e.jsx(qa,{className:"text-lg font-semibold bg-primary/10 text-primary",children:T})]}),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($0,{className:"h-5 w-5 text-white"})}),e.jsx("input",{ref:n,type:"file",accept:"image/*",className:"hidden",onChange:L})]}),e.jsxs("div",{className:"flex-1 space-y-0.5",children:[e.jsx("p",{className:"text-sm font-medium",children:y?"Uploading...":A?"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(re,{className:"text-xs font-medium text-muted-foreground",children:"Full Name"}),e.jsx(we,{value:_,onChange:$=>u($.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(re,{className:"text-xs font-medium text-muted-foreground",children:"Phone Number"}),e.jsx(we,{value:b,onChange:$=>m($.target.value),placeholder:"(555) 123-4567",className:"h-10",type:"tel"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(re,{className:"text-xs font-medium text-muted-foreground",children:"Email"}),e.jsx(we,{value:k,onChange:$=>g($.target.value),placeholder:"you@example.com",className:"h-10",type:"email"})]})]})]}),e.jsx(B,{variant:"outline",size:"sm",onClick:M,disabled:I.isPending,className:"w-full",children:I.isPending?"Saving...":"Update Profile Info"})]})}),e.jsx(aVe,{open:r,onClose:()=>a(!1),imageSrc:i,onCropComplete:z,aspectRatio:1})]})}function Lkn({form:s,setForm:t,userId:n}){const[r,a]=N.useState(null),[i,l]=N.useState(s.brokerage_logo_url?"logo":"name"),[o,c]=N.useState(s.team_logo_url?"logo":"name"),d=f=>{l(f),t(f==="name"?g=>({...g,brokerage_logo_url:""}):g=>({...g,brokerage_display_name:""}))},u=f=>{c(f),t(f==="name"?g=>({...g,team_logo_url:""}):g=>({...g,team_name:""}))},h=async(f,g)=>{var x;const y=(x=f.target.files)==null?void 0:x[0];if(y){if(!y.type.startsWith("image/")){ie.error("Please select an image file");return}a(g);try{const _=y.name.split(".").pop()||"png",k=`${n}/${g==="brokerage_logo_url"?"brokerage-logo":"team-logo"}.${_}`,{error:A}=await H.storage.from("card-logos").upload(k,y,{upsert:!0});if(A)throw A;const{data:T}=H.storage.from("card-logos").getPublicUrl(k),P=T.publicUrl+"?t="+Date.now();t(g==="brokerage_logo_url"?I=>({...I,[g]:P,brokerage_display_name:""}):I=>({...I,[g]:P,team_name:""})),ie.success("Logo uploaded!")}catch{ie.error("Failed to upload logo")}finally{a(null),f.target.value=""}}},m=f=>{t(g=>({...g,[f]:""}))};return e.jsx(_e,{children:e.jsxs(De,{className:"p-5 space-y-5",children:[e.jsxs("div",{children:[e.jsx(re,{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(re,{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(re,{className:"text-xs font-medium text-muted-foreground",children:"Brokerage Name"}),e.jsx(we,{value:s.brokerage_display_name,onChange:f=>t(g=>({...g,brokerage_display_name:f.target.value})),placeholder:"e.g. Keller Williams Realty",className:"h-10"})]}):e.jsxs("div",{className:"space-y-3",children:[e.jsx(re,{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($0,{className:"h-3.5 w-3.5"}),r==="brokerage_logo_url"?"Uploading...":s.brokerage_logo_url?"Change":"Upload Logo"]}),e.jsx("input",{type:"file",accept:"image/*",className:"hidden",onChange:f=>h(f,"brokerage_logo_url"),disabled:r!==null})]})]}),s.brokerage_logo_url&&e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(re,{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(qf,{value:[s.brokerage_logo_size||56],onValueChange:([f])=>t(g=>({...g,brokerage_logo_size:f})),min:24,max:120,step:4})]})]})]}),e.jsxs("div",{className:"space-y-3 p-3 rounded-lg bg-muted/30 border",children:[e.jsx(re,{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(re,{className:"text-xs font-medium text-muted-foreground",children:"Team Name"}),e.jsx(we,{value:s.team_name,onChange:f=>t(g=>({...g,team_name:f.target.value})),placeholder:"e.g. The Smith Group",className:"h-10"})]}):e.jsxs("div",{className:"space-y-3",children:[e.jsx(re,{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($0,{className:"h-3.5 w-3.5"}),r==="team_logo_url"?"Uploading...":s.team_logo_url?"Change":"Upload Logo"]}),e.jsx("input",{type:"file",accept:"image/*",className:"hidden",onChange:f=>h(f,"team_logo_url"),disabled:r!==null})]})]}),s.team_logo_url&&e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(re,{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(qf,{value:[s.team_logo_size||56],onValueChange:([f])=>t(g=>({...g,team_logo_size:f})),min:24,max:120,step:4})]})]})]})]})})}function Pkn({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(re,{className:"text-sm font-semibold flex items-center gap-1.5",children:[e.jsx(zc,{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(we,{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 Ikn({card:s,form:t,setForm:n}){var y;const r=G2t(),a=as(),{data:i}=W2t(s.id),[l,o]=N.useState(s.slug),[c,d]=N.useState(!1),[u,h]=N.useState("idle"),m=N.useRef(JSON.stringify(t)),f=N.useRef(null);N.useEffect(()=>{const x=JSON.stringify(t);if(x!==m.current)return f.current&&clearTimeout(f.current),f.current=setTimeout(()=>{h("saving"),r.mutate({id:s.id,...t,is_published:!0,title:t.title||null,positioning_statement:t.positioning_statement||null,bio:t.bio||null,review_snippet:t.review_snippet||null,review_source_url:t.review_source_url||null,booking_url:t.booking_url||null,custom_cta_label:t.custom_cta_label||null,brokerage_display_name:t.brokerage_display_name||null,brokerage_logo_url:t.brokerage_logo_url||null,brokerage_logo_size:t.brokerage_logo_size,team_name:t.team_name||null,team_logo_url:t.team_logo_url||null,team_logo_size:t.team_logo_size,bold_theme_colors:t.bold_theme_colors||null,display_email:t.display_email||null},{onSuccess:()=>{m.current=x,h("saved"),setTimeout(()=>h("idle"),2e3)},onError:()=>h("idle")})},1500),()=>{f.current&&clearTimeout(f.current)}},[t]);const g=async()=>{const x=l.trim().toLowerCase().replace(/[^a-z0-9-]/g,"-").replace(/-+/g,"-").replace(/(^-|-$)/g,"");if(!x){ie.error("Please enter a valid URL");return}if(x===s.slug){ie.info("No changes to save");return}d(!0);try{const{data:_}=await H.from("agent_cards").select("id").eq("slug",x).neq("id",s.id).maybeSingle();if(_){ie.error("This URL is already taken. Try another one.");return}const{error:b}=await H.from("agent_cards").update({slug:x}).eq("id",s.id);if(b)throw b;o(x),a.invalidateQueries({queryKey:["agent-card"]}),ie.success("Card address updated!")}catch{ie.error("Failed to update card address")}finally{d(!1)}};return e.jsxs("div",{className:"space-y-4",children:[e.jsxs(ya,{defaultValue:"content",children:[e.jsxs(va,{className:"w-full h-11 p-1",children:[e.jsxs(ls,{value:"content",className:"flex-1 gap-1.5 data-[state=active]:shadow-sm",children:[e.jsx(U0,{className:"h-3.5 w-3.5 hidden sm:inline"}),"Content"]}),e.jsxs(ls,{value:"sections",className:"flex-1 gap-1.5 data-[state=active]:shadow-sm",children:[e.jsx(da,{className:"h-3.5 w-3.5 hidden sm:inline"}),"Sections"]}),e.jsxs(ls,{value:"blocks",className:"flex-1 gap-1.5 data-[state=active]:shadow-sm",children:[e.jsx(ff,{className:"h-3.5 w-3.5 hidden sm:inline"}),"Blocks"]}),e.jsxs(ls,{value:"qrcode",className:"flex-1 gap-1.5 data-[state=active]:shadow-sm",children:[e.jsx(M_,{className:"h-3.5 w-3.5 hidden sm:inline"}),"QR Code"]}),e.jsxs(ls,{value:"analytics",className:"flex-1 gap-1.5 data-[state=active]:shadow-sm",children:[e.jsx(ru,{className:"h-3.5 w-3.5 hidden sm:inline"}),"Analytics"]})]}),e.jsxs(_s,{value:"content",className:"mt-4 space-y-4",children:[e.jsx(Mkn,{userId:s.user_id}),e.jsx(Lkn,{form:t,setForm:n,userId:s.user_id}),e.jsx(_e,{children:e.jsxs(De,{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(re,{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(zn,{checked:t.is_published,onCheckedChange:x=>n(_=>({..._,is_published:x}))})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(re,{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(we,{value:l,onChange:x=>o(x.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:g,disabled:c||l===s.slug,className:"shrink-0",children:c?"Saving...":"Update"})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"This is your unique card URL. Only letters, numbers, and dashes allowed."})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(re,{className:"text-sm font-medium",children:"Card Email (Override)"}),e.jsx(we,{value:t.display_email,onChange:x=>n(_=>({..._,display_email:x.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(re,{className:"text-sm font-medium",children:"Theme"}),e.jsxs(Ns,{value:t.theme,onValueChange:x=>n(_=>({..._,theme:x})),children:[e.jsx(ws,{className:"h-11",children:e.jsx(ks,{})}),e.jsxs(js,{children:[e.jsx(nt,{value:"standard",children:"✨ Standard — Modern & Clean"}),e.jsx(nt,{value:"luxury",children:"🌙 Luxury — Dark & Gold"}),e.jsx(nt,{value:"bold",children:"🔥 Bold — Vibrant & Punchy"}),e.jsx(nt,{value:"classic",children:"📋 Classic — Professional"})]})]})]}),t.theme==="bold"&&e.jsx(Pkn,{form:t,setForm:n}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(re,{className:"text-sm font-medium",children:"Title / Tagline"}),e.jsx(we,{value:t.title,onChange:x=>n(_=>({..._,title:x.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(re,{className:"text-sm font-medium",children:"Positioning Statement"}),e.jsx(we,{value:t.positioning_statement,onChange:x=>n(_=>({..._,positioning_statement:x.target.value})),placeholder:"Your home journey, handled with care.",className:"h-11"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(re,{className:"text-sm font-medium",children:"Bio"}),e.jsx(Ws,{value:t.bio,onChange:x=>n(_=>({..._,bio:x.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(re,{className:"text-sm font-medium",children:"Review Snippet"}),e.jsx(we,{value:t.review_snippet,onChange:x=>n(_=>({..._,review_snippet:x.target.value})),placeholder:"Best agent we've ever worked with...",className:"h-11"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(re,{className:"text-sm font-medium",children:"Review Source URL"}),e.jsx(we,{value:t.review_source_url,onChange:x=>n(_=>({..._,review_source_url:x.target.value})),placeholder:"https://g.page/your-business/review",className:"h-11"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(re,{className:"text-sm font-medium",children:"Booking URL"}),e.jsx(we,{value:t.booking_url,onChange:x=>n(_=>({..._,booking_url:x.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(re,{className:"text-sm font-medium",children:"Custom CTA Label"}),e.jsx(we,{value:t.custom_cta_label,onChange:x=>n(_=>({..._,custom_cta_label:x.target.value})),placeholder:"Book a Call",className:"h-11"})]})]})})]}),e.jsx(_s,{value:"sections",className:"mt-4",children:e.jsx(_e,{children:e.jsx(De,{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:x,label:_,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(re,{className:"text-sm font-medium",children:_}),e.jsx("p",{className:"text-xs text-muted-foreground",children:b})]}),e.jsx(zn,{checked:t[x],onCheckedChange:k=>n(A=>({...A,[x]:k}))})]},x))})})}),e.jsx(_s,{value:"blocks",className:"mt-4",children:e.jsx(U7t,{cardId:s.id})}),e.jsx(_s,{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:da,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:ru,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:Yl,color:"text-emerald-600 bg-emerald-100 dark:text-emerald-400 dark:bg-emerald-900/30"}].map(x=>e.jsx(_e,{className:"overflow-hidden",children:e.jsxs(De,{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 ${x.color}`,children:e.jsx(x.icon,{className:"h-3.5 w-3.5"})}),e.jsx("span",{className:"text-xs font-medium text-muted-foreground",children:x.label})]}),e.jsx("div",{className:"text-2xl font-bold",children:x.value})]})},x.label))}),i&&i.leads.length>0&&e.jsxs(_e,{children:[e.jsx(zt,{className:"pb-3",children:e.jsx(qt,{className:"text-base",children:"Recent Leads"})}),e.jsx(De,{className:"pt-0 space-y-2",children:i.leads.slice(0,5).map(x=>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:x.name}),x.phone&&e.jsx("span",{className:"text-muted-foreground ml-2",children:x.phone})]}),x.intent&&e.jsx(We,{variant:"secondary",className:"text-xs",children:x.intent})]},x.id))})]}),(!i||i.leads.length===0)&&e.jsx(_e,{children:e.jsxs(De,{className:"p-8 text-center",children:[e.jsx(ru,{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(_s,{value:"qrcode",className:"mt-4 space-y-4",children:e.jsx(_e,{children:e.jsx(De,{className:"p-6",children:e.jsx(Skn,{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 Dkn(){const s=as(),[t,n]=N.useState(""),[r,a]=N.useState(!1),[i,l]=N.useState(!1),[o,c]=N.useState(null),[d,u]=N.useState(!1),[h,m]=N.useState(!1),[f,g]=N.useState(null),[y,x]=N.useState(null),[_,b]=N.useState(0),[k,A]=N.useState(""),[T,P]=N.useState(!1),{data:I,isLoading:M}=mt({queryKey:["boldtrail-status"],queryFn:async()=>{const{data:ue,error:ce}=await H.functions.invoke("boldtrail-sync",{body:{action:"status"}});if(ce)throw ce;return ue}}),L=_t({mutationFn:async ue=>{const{data:ce,error:ae}=await H.functions.invoke("boldtrail-sync",{body:{action:"save_token",api_token:ue}});if(ae)throw ae;if(ce!=null&&ce.error)throw new Error(ce.error);return ce},onSuccess:()=>{s.invalidateQueries({queryKey:["boldtrail-status"]}),n(""),ie.success("BoldTrail connected successfully!")},onError:ue=>{ie.error(ue.message||"Failed to connect BoldTrail")}}),z=_t({mutationFn:async()=>{const{data:ue,error:ce}=await H.functions.invoke("boldtrail-sync",{body:{action:"disconnect"}});if(ce)throw ce;return ue},onSuccess:()=>{s.invalidateQueries({queryKey:["boldtrail-status"]}),ie.success("BoldTrail disconnected")},onError:()=>ie.error("Failed to disconnect")}),$=_t({mutationFn:async ue=>{const{data:ce,error:ae}=await H.functions.invoke("boldtrail-sync",{body:{action:"save_direction",sync_direction:ue}});if(ae)throw ae;if(ce!=null&&ce.error)throw new Error(ce.error);return ce},onSuccess:()=>{s.invalidateQueries({queryKey:["boldtrail-status"]}),ie.success("Sync direction saved")},onError:ue=>{ie.error(ue.message||"Failed to save sync direction")}}),V=_t({mutationFn:async()=>{const{data:ue,error:ce}=await H.functions.invoke("boldtrail-sync",{body:{action:"detect_owner"}});if(ce)throw ce;if(ue!=null&&ue.error)throw new Error(ue.error);return ue},onSuccess:ue=>{if(s.invalidateQueries({queryKey:["boldtrail-status"]}),ue.kvcore_user_id){const ce=ue.detected_name||ue.detected_email||`ID ${ue.kvcore_user_id}`;ie.success(`Detected your BoldTrail account: ${ce}`)}else if(ue.candidates&&ue.candidates.length>0){const ce=ue.candidates.slice(0,5).map(ae=>`${ae.id} (${ae.count} contacts)`).join(", ");ie.warning(`Couldn't auto-detect your ID. Owner IDs found in your contacts: ${ce}. Pick yours and enter it below.`,{duration:12e3}),P(!0)}else ie.warning("Couldn't auto-detect your BoldTrail user ID. Please find it in BoldTrail (My Profile URL) and enter it manually."),P(!0)},onError:ue=>ie.error(ue.message||"Detection failed")}),W=_t({mutationFn:async ue=>{const{data:ce,error:ae}=await H.functions.invoke("boldtrail-sync",{body:{action:"save_owner_settings",...ue}});if(ae)throw ae;if(ce!=null&&ce.error)throw new Error(ce.error);return ce},onSuccess:()=>{s.invalidateQueries({queryKey:["boldtrail-status"]}),ie.success("Settings saved"),P(!1)},onError:ue=>ie.error(ue.message||"Failed to save settings")}),G=_t({mutationFn:async()=>{const{data:ue,error:ce}=await H.functions.invoke("boldtrail-sync",{body:{action:"sync_preview"}});if(ce)throw ce;if(ue!=null&&ue.error)throw new Error(ue.error);return ue},onSuccess:ue=>{g(null),c(ue),a(!0)},onError:ue=>{ie.error(ue.message||"Failed to generate sync preview")}}),X=_t({mutationFn:async()=>{x("Initializing sync..."),b(5);const{data:ue,error:ce}=await H.functions.invoke("boldtrail-sync",{body:{action:"sync",phase:"init",sync_direction:me}});if(ce)throw ce;if(ue!=null&&ue.error)throw new Error(ue.error);const ae=ue;let he=ae.sync_log_id,xe=ae.next_phase,ve=ae.next_offset,ge=ae.push_total||0,be=ae.pull_total||0,Se=0,Ie=0;for(;xe!=="finalize";){const Be=ge+be;xe==="fetch_bt"?x("Fetching BoldTrail contacts..."):xe==="analyze"?(x("Analyzing contacts..."),b(15)):xe==="push"?(x(`Pushing contacts to BoldTrail... (${Se}/${ge})`),b(Be>0?Se/Be*100:0)):xe==="pull"&&(x(`Pulling contacts from BoldTrail... (${Ie}/${be})`),b(Be>0?(ge+Ie)/Be*100:0));const{data:Ne,error:Ge}=await H.functions.invoke("boldtrail-sync",{body:{action:"sync",phase:xe,offset:ve,sync_log_id:he,sync_direction:me}});if(Ge)throw Ge;if(Ne!=null&&Ne.error)throw new Error(Ne.error);const Ce=Ne;Se+=Ce.chunk_pushed||0,Ie+=Ce.chunk_pulled||0,Ce.push_total!==void 0&&(ge=Ce.push_total||0),Ce.pull_total!==void 0&&(be=Ce.pull_total||0),Ce.progress&&x(Ce.progress),xe==="pull"&&be>0?b(Math.min(95,Ie/be*100)):xe==="push"&&ge>0&&b(Math.min(95,Se/ge*100)),xe=Ce.next_phase,ve=Ce.next_offset}x("Finalizing sync..."),b(95);const{data:Me,error:Re}=await H.functions.invoke("boldtrail-sync",{body:{action:"sync",phase:"finalize",sync_log_id:he,sync_direction:me}});if(Re)throw Re;return b(100),Me},onSuccess:ue=>{x(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"]}),ie.success(`Sync complete! Pushed ${ue.contacts_pushed||0}, pulled ${ue.contacts_pulled||0}, skipped ${ue.contacts_skipped||0} duplicates.`)},onError:ue=>{x(null),b(0),ie.error(ue.message||"Sync failed")}}),te=I==null?void 0:I.connected,ne=(I==null?void 0:I.sync_direction)||"bidirectional",me=f??ne;return e.jsxs(e.Fragment,{children:[e.jsxs(_e,{children:[e.jsx(zt,{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(mg,{className:"h-5 w-5 text-emerald-600"})}),e.jsxs("div",{children:[e.jsxs(qt,{className:"text-lg flex items-center gap-2",children:["BoldTrail",te&&e.jsx(We,{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(wp,{className:"h-3.5 w-3.5"}),"Learn More"]})]}),e.jsx(_r,{children:"Sync contacts bidirectionally between Agent OS and your BoldTrail (kvCORE) CRM."})]})]})}),e.jsx(De,{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(Po,{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(Po,{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(Po,{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"})]}),te?e.jsxs("div",{className:"space-y-3 mt-4",children:[e.jsx("div",{className:"rounded-lg border p-3 space-y-2",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("p",{className:"font-medium text-sm",children:"BoldTrail Connected"}),(I==null?void 0:I.last_sync_at)&&e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Last sync: ",new Date(I.last_sync_at).toLocaleString(),I.last_sync_status&&e.jsx(We,{variant:I.last_sync_status==="success"?"default":"secondary",className:"ml-2 text-[10px]",children:I.last_sync_status})]}),(I==null?void 0:I.boldtrail_contact_count)!=null&&e.jsxs("p",{className:"text-xs text-muted-foreground",children:[I.boldtrail_contact_count," contacts in BoldTrail"]}),(I==null?void 0:I.last_sync_message)&&e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:I.last_sync_message})]}),e.jsxs(Fl,{children:[e.jsx(Gf,{asChild:!0,children:e.jsx(B,{variant:"ghost",size:"icon",className:"text-destructive hover:text-destructive",children:e.jsx(qn,{className:"h-4 w-4"})})}),e.jsxs(kl,{children:[e.jsxs(Sl,{children:[e.jsx(Al,{children:"Disconnect BoldTrail?"}),e.jsx(Tl,{children:"This will remove your API token. Previously synced contacts will remain in both systems."})]}),e.jsxs(Cl,{children:[e.jsx(El,{children:"Cancel"}),e.jsx(wl,{onClick:()=>z.mutate(),className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:"Disconnect"})]})]})]})]})}),e.jsxs("div",{className:"rounded-lg border p-3 space-y-3",children:[e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsx(tN,{className:"h-4 w-4 mt-0.5 text-emerald-600 shrink-0"}),e.jsxs("div",{className:"flex-1 space-y-1",children:[e.jsx("p",{className:"text-sm font-medium",children:"Only sync contacts I own in BoldTrail"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"If your token has access to the whole brokerage's contacts, turn this on to sync just the contacts assigned to you."})]}),e.jsx(zn,{checked:!!(I!=null&&I.sync_only_owned),onCheckedChange:ue=>W.mutate({sync_only_owned:ue}),disabled:W.isPending})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(re,{className:"text-xs",children:"Your BoldTrail Agent ID"}),T?e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(we,{type:"number",placeholder:"e.g. 12345",value:k,onChange:ue=>A(ue.target.value),className:"h-8 text-sm"}),e.jsx(B,{size:"sm",onClick:()=>{const ue=k.trim()===""?null:Number(k);W.mutate({kvcore_user_id:ue})},disabled:W.isPending,children:"Save"}),e.jsx(B,{size:"sm",variant:"ghost",onClick:()=>P(!1),children:"Cancel"})]}):e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsx("span",{className:"text-sm font-mono",children:(I==null?void 0:I.kvcore_user_id)??e.jsx("span",{className:"text-muted-foreground",children:"Not set"})}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(B,{size:"sm",variant:"outline",onClick:()=>V.mutate(),disabled:V.isPending,children:[V.isPending?e.jsx(oo,{className:"h-3 w-3 mr-1 animate-spin"}):null,"Auto-detect"]}),e.jsx(B,{size:"sm",variant:"ghost",onClick:()=>{var ue;A(((ue=I==null?void 0:I.kvcore_user_id)==null?void 0:ue.toString())??""),P(!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(a7e,{value:ne,onChange:ue=>$.mutate(ue)})}),e.jsx("div",{className:"flex gap-2",children:e.jsxs(B,{onClick:()=>G.mutate(),disabled:G.isPending||X.isPending,variant:"outline",className:"gap-2",children:[G.isPending?e.jsx(oo,{className:"h-4 w-4 animate-spin"}):e.jsx(da,{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(we,{type:"password",placeholder:"Paste your BoldTrail API token",value:t,onChange:ue=>n(ue.target.value),className:"flex-1"}),e.jsxs(B,{onClick:()=>L.mutate(t),disabled:!t||t.length<10||L.isPending,children:[L.isPending?e.jsx(oo,{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(Bs,{open:r,onOpenChange:ue=>{X.isPending||a(ue)},children:e.jsxs(Fs,{className:"sm:max-w-lg",children:[e.jsxs(qs,{children:[e.jsxs($s,{className:"flex items-center gap-2",children:[e.jsx(mg,{className:"h-5 w-5 text-emerald-600"}),"Sync Preview"]}),e.jsx(Ar,{children:"Review what will happen when you sync your contacts."})]}),o&&(()=>{const ue=me==="pull_only"?0:o.to_push,ce=me==="push_only"?0:o.to_pull;return e.jsxs("div",{className:"space-y-4",children:[e.jsx(a7e,{value:me,onChange:g,size:"sm"}),o.owner_filter_active&&e.jsxs("div",{className:"rounded-md border border-emerald-200 bg-emerald-50 p-2 text-xs text-emerald-900 flex items-start gap-2",children:[e.jsx(tN,{className:"h-3.5 w-3.5 mt-0.5 shrink-0"}),e.jsxs("span",{children:["Owner filter is on. Only contacts assigned to your BoldTrail account",o.kvcore_user_id?` (ID ${o.kvcore_user_id})`:""," will be synced.",o.boldtrail_total_brokerage!=null&&e.jsxs(e.Fragment,{children:[" Brokerage total: ",e.jsx("strong",{children:o.boldtrail_total_brokerage.toLocaleString()}),"."]})]})]}),e.jsxs("div",{className:"grid grid-cols-3 gap-3",children:[e.jsxs("div",{className:`rounded-lg border p-3 text-center ${me==="pull_only"?"opacity-40":""}`,children:[e.jsx("p",{className:"text-2xl font-bold text-emerald-600",children:ue}),e.jsxs("p",{className:"text-xs text-muted-foreground flex items-center justify-center gap-1",children:[e.jsx(Om,{className:"h-3 w-3"})," Push to BoldTrail"]})]}),e.jsxs("div",{className:`rounded-lg border p-3 text-center ${me==="push_only"?"opacity-40":""}`,children:[e.jsx("p",{className:"text-2xl font-bold text-blue-600",children:ce}),e.jsxs("p",{className:"text-xs text-muted-foreground flex items-center justify-center gap-1",children:[e.jsx(Wf,{className:"h-3 w-3"})," Pull to Agent OS"]})]}),e.jsxs("div",{className:"rounded-lg border p-3 text-center",children:[e.jsx("p",{className:"text-2xl font-bold text-muted-foreground",children:o.already_synced}),e.jsxs("p",{className:"text-xs text-muted-foreground flex items-center justify-center gap-1",children:[e.jsx(Yn,{className:"h-3 w-3"})," Already synced"]})]})]}),e.jsxs("div",{className:"text-xs text-muted-foreground text-center",children:["Agent OS: ",o.agent_os_total," contacts · BoldTrail: ",o.boldtrail_total," contacts"]}),X.isPending&&e.jsxs("div",{className:"space-y-2 py-2",children:[e.jsx(ro,{value:_||10,className:"h-2"}),e.jsx("p",{className:"text-xs text-muted-foreground text-center",children:y||"Sync in progress..."})]}),ue>0&&e.jsxs(Kv,{open:d,onOpenChange:u,children:[e.jsx(Yv,{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(Om,{className:"h-3 w-3 text-emerald-600"}),ue," contacts to push to BoldTrail"]}),e.jsx(Xo,{className:`h-3 w-3 transition-transform ${d?"rotate-180":""}`})]})}),e.jsx(Zv,{children:e.jsxs("div",{className:"rounded border divide-y max-h-40 overflow-y-auto",children:[o.push_preview.map((ae,he)=>e.jsxs("div",{className:"px-3 py-1.5 text-xs flex justify-between",children:[e.jsx("span",{className:"font-medium",children:ae.name||"No name"}),e.jsx("span",{className:"text-muted-foreground",children:ae.email})]},he)),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"]})]})})]}),ce>0&&e.jsxs(Kv,{open:h,onOpenChange:m,children:[e.jsx(Yv,{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(Wf,{className:"h-3 w-3 text-blue-600"}),ce," contacts to pull from BoldTrail"]}),e.jsx(Xo,{className:`h-3 w-3 transition-transform ${h?"rotate-180":""}`})]})}),e.jsx(Zv,{children:e.jsxs("div",{className:"rounded border divide-y max-h-40 overflow-y-auto",children:[o.pull_preview.map((ae,he)=>e.jsxs("div",{className:"px-3 py-1.5 text-xs flex justify-between",children:[e.jsx("span",{className:"font-medium",children:ae.name||"No name"}),e.jsx("span",{className:"text-muted-foreground",children:ae.email})]},he)),o.to_pull>20&&e.jsxs("div",{className:"px-3 py-1.5 text-xs text-muted-foreground text-center",children:["...and ",o.to_pull-20," more"]})]})})]}),ue===0&&ce===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:X.isPending,children:"Cancel"}),e.jsxs(B,{onClick:()=>X.mutate(),disabled:X.isPending||ue===0&&ce===0,className:"gap-2",children:[X.isPending?e.jsx(oo,{className:"h-4 w-4 animate-spin"}):e.jsx(mg,{className:"h-4 w-4"}),X.isPending?"Syncing...":"Sync Now"]})]})]})})()]})}),e.jsx(Bs,{open:i,onOpenChange:l,children:e.jsxs(Fs,{className:"sm:max-w-2xl p-0 overflow-hidden",children:[e.jsx(qs,{className:"p-6 pb-0",children:e.jsxs($s,{className:"flex items-center gap-2",children:[e.jsx(mg,{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"})})]})})]})}function Rkn(){const s=as(),[t,n]=N.useState(""),[r,a]=N.useState(!1),[i,l]=N.useState(0),[o,c]=N.useState(null),{data:d,isLoading:u}=mt({queryKey:["fub-status"],queryFn:async()=>{const{data:y,error:x}=await H.functions.invoke("followupboss-sync",{body:{action:"status"}});if(x)throw x;return y}}),h=_t({mutationFn:async y=>{const{data:x,error:_}=await H.functions.invoke("followupboss-sync",{body:{action:"save_token",api_key:y}});if(_)throw _;if(x!=null&&x.error)throw new Error(x.error);return x},onSuccess:()=>{ie.success("Connected to Follow Up Boss"),n(""),s.invalidateQueries({queryKey:["fub-status"]})},onError:y=>ie.error(y.message)}),m=_t({mutationFn:async()=>{const{error:y}=await H.functions.invoke("followupboss-sync",{body:{action:"disconnect"}});if(y)throw y},onSuccess:()=>{ie.success("Disconnected"),s.invalidateQueries({queryKey:["fub-status"]})}}),f=_t({mutationFn:async y=>{const{error:x}=await H.functions.invoke("followupboss-sync",{body:{action:"set_direction",sync_direction:y}});if(x)throw x},onSuccess:()=>s.invalidateQueries({queryKey:["fub-status"]})}),g=async()=>{a(!0),l(0),c("Pulling from FUB…");let y=0,x=0,_=0,b=0;try{for(;;){const{data:P,error:I}=await H.functions.invoke("followupboss-sync",{body:{action:"sync",offset:y}});if(I)throw I;if(P!=null&&P.error)throw new Error(P.error);x+=P.chunk_created||0,_+=P.chunk_updated||0,b+=P.chunk_skipped||0,y=P.next_offset;const M=P.total?Math.min(100,Math.round(y/P.total*100)):100;if(l(M),c(`Pulling · ${y} / ${P.total||"?"}`),P.done)break;await new Promise(L=>setTimeout(L,400))}let k=0,A=0;if((d==null?void 0:d.sync_direction)==="bidirectional"){let P=0;for(l(0),c("Pushing to FUB…");;){const{data:I,error:M}=await H.functions.invoke("followupboss-sync",{body:{action:"push",offset:P}});if(M)throw M;if(I!=null&&I.error)throw new Error(I.error);k+=I.chunk_pushed||0,A+=I.chunk_failed||0,P=I.next_offset;const L=I.total?Math.min(100,Math.round(P/I.total*100)):100;if(l(L),c(`Pushing · ${P} / ${I.total||"?"}`),I.done)break;await new Promise(z=>setTimeout(z,400))}}const T=k||A?` · pushed ${k}${A?`, ${A} failed`:""}`:"";ie.success(`Sync complete · ${x} new, ${_} updated${b?`, ${b} skipped`:""}${T}`),s.invalidateQueries({queryKey:["fub-status"]})}catch(k){ie.error(k.message||"Sync failed")}finally{a(!1),setTimeout(()=>{l(0),c(null)},2500)}};return e.jsxs(_e,{children:[e.jsx(zt,{children:e.jsx("div",{className:"flex items-start justify-between gap-3",children:e.jsxs("div",{children:[e.jsxs(qt,{className:"flex items-center gap-2",children:[e.jsx(o3,{className:"h-5 w-5 text-primary"}),"Follow Up Boss",(d==null?void 0:d.connected)&&e.jsxs(We,{variant:"default",className:"ml-1",children:[e.jsx(Po,{className:"h-3 w-3 mr-1"})," Connected"]})]}),e.jsx(_r,{children:"Sync your Follow Up Boss contacts into Agent OS."})]})})}),e.jsx(De,{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(zn,{checked:d.sync_direction==="bidirectional",onCheckedChange:y=>f.mutate(y?"bidirectional":"pull_only"),disabled:r||f.isPending})]}),o&&e.jsxs("div",{className:"space-y-1",children:[e.jsx(ro,{value:i}),e.jsx("p",{className:"text-xs text-muted-foreground",children:o})]}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsxs(B,{onClick:g,disabled:r,children:[e.jsx(oo,{className:`h-4 w-4 mr-2 ${r?"animate-spin":""}`}),r?"Syncing…":"Sync Now"]}),e.jsxs(Fl,{children:[e.jsx(Gf,{asChild:!0,children:e.jsxs(B,{variant:"outline",disabled:r,children:[e.jsx(qn,{className:"h-4 w-4 mr-2"})," Disconnect"]})}),e.jsxs(kl,{children:[e.jsxs(Sl,{children:[e.jsx(Al,{children:"Disconnect Follow Up Boss?"}),e.jsx(Tl,{children:"Your API key will be removed. Synced contacts stay in Agent OS."})]}),e.jsxs(Cl,{children:[e.jsx(El,{children:"Cancel"}),e.jsx(wl,{onClick:()=>m.mutate(),children:"Disconnect"})]})]})]})]})]}):e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{children:[e.jsx(re,{htmlFor:"fub-key",children:"Follow Up Boss API Key"}),e.jsx(we,{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(Tr,{className:"h-3 w-3"})]})]})]}),e.jsx(B,{onClick:()=>h.mutate(t),disabled:!t.trim()||h.isPending,children:h.isPending?"Connecting…":"Connect"})]})})]})}function Okn(){var G;const s=as(),[t,n]=N.useState(""),[r,a]=N.useState(""),[i,l]=N.useState(!1),[o,c]=N.useState(0),[d,u]=N.useState(null),[h,m]=N.useState(!1),[f,g]=N.useState(null),[y,x]=N.useState(!1),[_,b]=N.useState(new Set),{data:k,isLoading:A}=mt({queryKey:["cloze-status"],queryFn:async()=>{const{data:X,error:te}=await H.functions.invoke("cloze-sync",{body:{action:"status"}});if(te)throw te;return X}}),T=_t({mutationFn:async()=>{const{data:X,error:te}=await H.functions.invoke("cloze-sync",{body:{action:"save_token",api_key:t.trim(),account_email:r.trim()}});if(te)throw te;if(X!=null&&X.error)throw new Error(X.error);return X},onSuccess:()=>{ie.success("Connected to Cloze"),n(""),a(""),s.invalidateQueries({queryKey:["cloze-status"]})},onError:X=>ie.error(X.message)}),P=_t({mutationFn:async()=>{const{error:X}=await H.functions.invoke("cloze-sync",{body:{action:"disconnect"}});if(X)throw X},onSuccess:()=>{ie.success("Cloze disconnected"),s.invalidateQueries({queryKey:["cloze-status"]})}}),I=_t({mutationFn:async X=>{const{error:te}=await H.functions.invoke("cloze-sync",{body:{action:"set_direction",sync_direction:X}});if(te)throw te},onSuccess:()=>s.invalidateQueries({queryKey:["cloze-status"]})}),M=_t({mutationFn:async X=>{const{error:te}=await H.functions.invoke("cloze-sync",{body:{action:"set_scope",...X}});if(te)throw te},onSuccess:()=>s.invalidateQueries({queryKey:["cloze-status"]})}),L=async()=>{x(!0);try{const{data:X,error:te}=await H.functions.invoke("cloze-sync",{body:{action:"list_segments"}});if(te)throw te;if(X!=null&&X.error)throw new Error(X.error);g(X.segments||[]),b(new Set((k==null?void 0:k.selected_segments)||[])),m(!0)}catch(X){ie.error(X.message||"Failed to load segments")}finally{x(!1)}},z=async()=>{const X=Array.from(_);await M.mutateAsync({sync_scope:"segments",selected_segments:X}),ie.success(`Saved · ${X.length} segment(s) selected`),m(!1)},$=async()=>{const X=(k==null?void 0:k.sync_direction)||"pull_only";l(!0),c(0);try{if(X==="pull_only"||X==="bidirectional"){u("Pulling from Cloze…");let te=0,ne=0,me=0;for(;;){const{data:ue,error:ce}=await H.functions.invoke("cloze-sync",{body:{action:"sync",offset:te}});if(ce)throw ce;if(ue!=null&&ue.error)throw new Error(ue.error);if(ne+=ue.chunk_created||0,me+=ue.chunk_updated||0,te=ue.next_offset,u(`Pulling · ${ne+me} contacts processed`),c(ue.done?100:Math.min(95,(ne+me)%200/2)),ue.done)break;await new Promise(ae=>setTimeout(ae,300))}ie.success(`Pulled · ${ne} new, ${me} updated`)}if(X==="push_only"||X==="bidirectional"){c(0),u("Pushing to Cloze…");let te=0,ne=0,me=0;for(;;){const{data:ue,error:ce}=await H.functions.invoke("cloze-sync",{body:{action:"push",offset:te}});if(ce)throw ce;if(ue!=null&&ue.error)throw new Error(ue.error);ne+=ue.chunk_pushed||0,me+=ue.chunk_failed||0,te=ue.next_offset;const ae=ue.total?Math.min(100,Math.round(te/ue.total*100)):100;if(c(ae),u(`Pushing · ${te} / ${ue.total||"?"}`),ue.done)break;await new Promise(he=>setTimeout(he,300))}ie.success(`Pushed · ${ne}${me?`, ${me} failed`:""}`)}s.invalidateQueries({queryKey:["cloze-status"]})}catch(te){ie.error(te.message||"Sync failed")}finally{l(!1),setTimeout(()=>{c(0),u(null)},2e3)}},V=(k==null?void 0:k.sync_scope)||"all",W=((G=k==null?void 0:k.selected_segments)==null?void 0:G.length)||0;return e.jsxs(_e,{children:[e.jsx(zt,{children:e.jsx("div",{className:"flex items-start justify-between gap-3",children:e.jsxs("div",{children:[e.jsxs(qt,{className:"flex items-center gap-2",children:[e.jsx(o3,{className:"h-5 w-5 text-primary"}),"Cloze",(k==null?void 0:k.connected)&&e.jsxs(We,{variant:"default",className:"ml-1",children:[e.jsx(Po,{className:"h-3 w-3 mr-1"})," Connected"]})]}),e.jsx(_r,{children:"Sync contacts between Cloze and Agent OS using your personal Cloze API key."})]})})}),e.jsx(De,{className:"space-y-4",children:A?e.jsx("p",{className:"text-sm text-muted-foreground",children:"Loading…"}):k!=null&&k.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:k.account_email})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-muted-foreground",children:"Last sync"}),e.jsx("p",{className:"font-medium",children:k.last_sync_at?new Date(k.last_sync_at).toLocaleString():"Never"})]})]}),k.last_sync_status==="error"&&e.jsx("p",{className:"text-sm text-destructive",children:k.last_sync_message}),e.jsx("div",{className:"rounded-lg border px-3 py-2 space-y-2",children:e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium",children:"Sync direction"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Choose which way contacts should flow."})]}),e.jsxs(Ns,{value:k.sync_direction||"pull_only",onValueChange:X=>I.mutate(X),disabled:i||I.isPending,children:[e.jsx(ws,{className:"w-[180px]",children:e.jsx(ks,{})}),e.jsxs(js,{children:[e.jsx(nt,{value:"pull_only",children:"Pull from Cloze"}),e.jsx(nt,{value:"push_only",children:"Push to Cloze"}),e.jsx(nt,{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.":`${W} segment${W===1?"":"s"} selected.`})]}),e.jsxs(Ns,{value:V,onValueChange:X=>{X==="all"?M.mutate({sync_scope:"all",selected_segments:[]}):(M.mutate({sync_scope:"segments",selected_segments:k.selected_segments||[]}),L())},disabled:i||M.isPending,children:[e.jsx(ws,{className:"w-[180px]",children:e.jsx(ks,{})}),e.jsxs(js,{children:[e.jsx(nt,{value:"all",children:"All contacts"}),e.jsx(nt,{value:"segments",children:"Selected segments"})]})]})]}),V==="segments"&&e.jsxs("div",{children:[e.jsxs(B,{variant:"outline",size:"sm",onClick:L,disabled:y,children:[e.jsx(NW,{className:"h-4 w-4 mr-2"}),y?"Loading segments…":"Choose segments"]}),h&&f&&e.jsxs("div",{className:"mt-3 space-y-2",children:[e.jsxs("div",{className:"max-h-96 overflow-y-auto rounded-md border divide-y",children:[f.length===0&&e.jsx("p",{className:"text-sm text-muted-foreground p-3",children:"No segments found in your Cloze account."}),f.map(X=>{const te=_.has(X.id);return e.jsxs("label",{className:"flex items-center gap-3 p-2 cursor-pointer hover:bg-muted/50",children:[e.jsx(Bi,{checked:te,onCheckedChange:ne=>{const me=new Set(_);ne?me.add(X.id):me.delete(X.id),b(me)}}),e.jsx("span",{className:"flex-1 text-sm",children:X.name}),X.count!=null&&e.jsx(We,{variant:"secondary",className:"text-xs",children:X.count})]},X.id)})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(B,{size:"sm",onClick:z,disabled:M.isPending,children:["Save selection (",_.size,")"]}),e.jsx(B,{size:"sm",variant:"ghost",onClick:()=>m(!1),children:"Cancel"})]})]})]})]}),d&&e.jsxs("div",{className:"space-y-1",children:[e.jsx(ro,{value:o}),e.jsx("p",{className:"text-xs text-muted-foreground",children:d})]}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsxs(Fl,{children:[e.jsx(Gf,{asChild:!0,children:e.jsxs(B,{disabled:i,children:[e.jsx(oo,{className:`h-4 w-4 mr-2 ${i?"animate-spin":""}`}),i?"Syncing…":"Sync Now"]})}),e.jsxs(kl,{children:[e.jsxs(Sl,{children:[e.jsx(Al,{children:"Preview sync"}),e.jsx(Tl,{asChild:!0,children:e.jsx(Fkn,{segments:f})})]}),e.jsxs(Cl,{children:[e.jsx(El,{children:"Cancel"}),e.jsx(wl,{onClick:$,children:"Start Sync"})]})]})]}),e.jsxs(Fl,{children:[e.jsx(Gf,{asChild:!0,children:e.jsxs(B,{variant:"outline",disabled:i,children:[e.jsx(qn,{className:"h-4 w-4 mr-2"})," Disconnect"]})}),e.jsxs(kl,{children:[e.jsxs(Sl,{children:[e.jsx(Al,{children:"Disconnect Cloze?"}),e.jsx(Tl,{children:"Your API key will be removed. Contacts already synced will remain."})]}),e.jsxs(Cl,{children:[e.jsx(El,{children:"Cancel"}),e.jsx(wl,{onClick:()=>P.mutate(),children:"Disconnect"})]})]})]})]})]}):e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{children:[e.jsx(re,{htmlFor:"cloze-email",children:"Cloze Account Email"}),e.jsx(we,{id:"cloze-email",type:"email",placeholder:"you@example.com",value:r,onChange:X=>a(X.target.value)})]}),e.jsxs("div",{children:[e.jsx(re,{htmlFor:"cloze-key",children:"Cloze API Key"}),e.jsx(we,{id:"cloze-key",type:"password",placeholder:"Your personal Cloze API key",value:t,onChange:X=>n(X.target.value)}),e.jsxs("p",{className:"text-xs text-muted-foreground mt-1 flex items-center gap-1",children:["Generate one in Cloze → Settings → API Keys.",e.jsxs("a",{href:"https://app.cloze.com/app/#/settings/apikeys",target:"_blank",rel:"noreferrer",className:"inline-flex items-center gap-0.5 text-primary hover:underline",children:["Open ",e.jsx(Tr,{className:"h-3 w-3"})]})]})]}),e.jsx(B,{onClick:()=>T.mutate(),disabled:!t.trim()||!r.trim()||T.isPending,children:T.isPending?"Connecting…":"Connect Cloze"})]})})]})}function Fkn({segments:s}){var h;const[t,n]=N.useState(!0),[r,a]=N.useState(null),[i,l]=N.useState(null);if(N.useEffect(()=>{(async()=>{try{const{data:m,error:f}=await H.functions.invoke("cloze-sync",{body:{action:"preview"}});if(f)throw f;if(m!=null&&m.error)throw new Error(m.error);a(m)}catch(m){l(m.message||"Could not load preview")}finally{n(!1)}})()},[]),t)return e.jsx("span",{className:"text-sm",children:"Calculating…"});if(i)return e.jsx("span",{className:"text-sm text-destructive",children:i});const o=new Map((s||[]).map(m=>[m.id,m.name])),c=r.total_incoming??0,d=r.already_synced??0,u=Math.max(0,c-d);return e.jsxs("div",{className:"space-y-3 text-sm text-foreground",children:[e.jsxs("div",{className:"rounded-md border p-3 space-y-1",children:[e.jsxs("div",{className:"flex justify-between",children:[e.jsxs("span",{children:["Contacts in Cloze (",r.scope==="segments"?"selected segments":"all",")"]}),e.jsx("strong",{children:c.toLocaleString()})]}),e.jsxs("div",{className:"flex justify-between text-muted-foreground",children:[e.jsx("span",{children:"Already linked to Cloze in your CRM"}),e.jsx("span",{children:d.toLocaleString()})]}),e.jsxs("div",{className:"flex justify-between",children:[e.jsx("span",{children:"Estimated new contacts"}),e.jsxs("strong",{children:["~",u.toLocaleString()]})]})]}),r.scope==="segments"&&((h=r.segment_counts)==null?void 0:h.length)>0&&e.jsx("div",{className:"rounded-md border p-3 space-y-1 max-h-40 overflow-auto",children:r.segment_counts.map(m=>e.jsxs("div",{className:"flex justify-between text-xs",children:[e.jsx("span",{children:o.get(m.id)||m.id}),e.jsx("span",{className:"text-muted-foreground",children:m.total})]},m.id))}),e.jsx("p",{className:"text-xs text-muted-foreground",children:r.note})]})}function zkn(){const s=as(),[t,n]=N.useState(""),[r,a]=N.useState(!1),[i,l]=N.useState(0),[o,c]=N.useState(null),{data:d,isLoading:u}=mt({queryKey:["boomtown-status"],queryFn:async()=>{const{data:y,error:x}=await H.functions.invoke("boomtown-sync",{body:{action:"status"}});if(x)throw x;return y}}),h=_t({mutationFn:async y=>{const{data:x,error:_}=await H.functions.invoke("boomtown-sync",{body:{action:"save_token",api_key:y}});if(_)throw _;if(x!=null&&x.error)throw new Error(x.error);return x},onSuccess:()=>{ie.success("Connected to Boomtown"),n(""),s.invalidateQueries({queryKey:["boomtown-status"]})},onError:y=>ie.error(y.message)}),m=_t({mutationFn:async()=>{const{error:y}=await H.functions.invoke("boomtown-sync",{body:{action:"disconnect"}});if(y)throw y},onSuccess:()=>{ie.success("Disconnected"),s.invalidateQueries({queryKey:["boomtown-status"]})}}),f=_t({mutationFn:async y=>{const{error:x}=await H.functions.invoke("boomtown-sync",{body:{action:"set_direction",sync_direction:y}});if(x)throw x},onSuccess:()=>s.invalidateQueries({queryKey:["boomtown-status"]})}),g=async()=>{a(!0),l(0),c("Pulling from Boomtown…");let y=0,x=0,_=0,b=0;try{for(;;){const{data:P,error:I}=await H.functions.invoke("boomtown-sync",{body:{action:"sync",offset:y}});if(I)throw I;if(P!=null&&P.error)throw new Error(P.error);x+=P.chunk_created||0,_+=P.chunk_updated||0,b+=P.chunk_skipped||0,y=P.next_offset;const M=P.total?Math.min(100,Math.round(y/P.total*100)):100;if(l(M),c(`Pulling · ${y} / ${P.total||"?"}`),P.done)break;await new Promise(L=>setTimeout(L,400))}let k=0,A=0;if((d==null?void 0:d.sync_direction)==="bidirectional"){let P=0;for(l(0),c("Pushing to Boomtown…");;){const{data:I,error:M}=await H.functions.invoke("boomtown-sync",{body:{action:"push",offset:P}});if(M)throw M;if(I!=null&&I.error)throw new Error(I.error);k+=I.chunk_pushed||0,A+=I.chunk_failed||0,P=I.next_offset;const L=I.total?Math.min(100,Math.round(P/I.total*100)):100;if(l(L),c(`Pushing · ${P} / ${I.total||"?"}`),I.done)break;await new Promise(z=>setTimeout(z,400))}}const T=k||A?` · pushed ${k}${A?`, ${A} failed`:""}`:"";ie.success(`Sync complete · ${x} new, ${_} updated${b?`, ${b} skipped`:""}${T}`),s.invalidateQueries({queryKey:["boomtown-status"]})}catch(k){ie.error(k.message||"Sync failed")}finally{a(!1),setTimeout(()=>{l(0),c(null)},2500)}};return e.jsxs(_e,{children:[e.jsx(zt,{children:e.jsx("div",{className:"flex items-start justify-between gap-3",children:e.jsxs("div",{children:[e.jsxs(qt,{className:"flex items-center gap-2",children:[e.jsx(o3,{className:"h-5 w-5 text-primary"}),"Boomtown",(d==null?void 0:d.connected)&&e.jsxs(We,{variant:"default",className:"ml-1",children:[e.jsx(Po,{className:"h-3 w-3 mr-1"})," Connected"]})]}),e.jsx(_r,{children:"Sync your Boomtown contacts into Agent OS."})]})})}),e.jsx(De,{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(zn,{checked:d.sync_direction==="bidirectional",onCheckedChange:y=>f.mutate(y?"bidirectional":"pull_only"),disabled:r||f.isPending})]}),o&&e.jsxs("div",{className:"space-y-1",children:[e.jsx(ro,{value:i}),e.jsx("p",{className:"text-xs text-muted-foreground",children:o})]}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsxs(B,{onClick:g,disabled:r,children:[e.jsx(oo,{className:`h-4 w-4 mr-2 ${r?"animate-spin":""}`}),r?"Syncing…":"Sync Now"]}),e.jsxs(Fl,{children:[e.jsx(Gf,{asChild:!0,children:e.jsxs(B,{variant:"outline",disabled:r,children:[e.jsx(qn,{className:"h-4 w-4 mr-2"})," Disconnect"]})}),e.jsxs(kl,{children:[e.jsxs(Sl,{children:[e.jsx(Al,{children:"Disconnect Boomtown?"}),e.jsx(Tl,{children:"Your API key will be removed. Synced contacts stay in Agent OS."})]}),e.jsxs(Cl,{children:[e.jsx(El,{children:"Cancel"}),e.jsx(wl,{onClick:()=>m.mutate(),children:"Disconnect"})]})]})]})]})]}):e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{children:[e.jsx(re,{htmlFor:"boomtown-key",children:"Boomtown API Key"}),e.jsx(we,{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(Tr,{className:"h-3 w-3"})]})]}),e.jsx(B,{onClick:()=>h.mutate(t),disabled:!t.trim()||h.isPending,children:h.isPending?"Connecting…":"Connect"})]})})]})}function e9t(){const s=tr(),[t,n]=N.useState(""),[r,a]=N.useState(""),[i,l]=N.useState("Test from ReLevelUp"),[o,c]=N.useState(!1),{data:d,isLoading:u}=mt({queryKey:["ses-config"],queryFn:async()=>{const f=await bZ();return(await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/ses-send-campaign",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${f}`},body:JSON.stringify({action:"check_config"})})).json()}}),h=async()=>{if(!t||!r){ie.error("Please fill in From and To email addresses");return}c(!0);try{const f=await bZ(),y=await(await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/ses-send-campaign",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${f}`},body:JSON.stringify({action:"test_send",to:t,from_email:r,subject:i,body_html:"

Test Email

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

If you received this, SES is configured correctly! 🎉

"})})).json();y.success?ie.success(`Test email sent! Message ID: ${y.messageId}`):ie.error(y.error||"Failed to send test email")}catch(f){ie.error(f.message||"Failed to send test email")}finally{c(!1)}},m=(d==null?void 0:d.configured)===!0;return e.jsxs(_e,{children:[e.jsx(zt,{children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"h-10 w-10 rounded-lg bg-orange-500/10 flex items-center justify-center",children:e.jsx(mn,{className:"h-5 w-5 text-orange-600"})}),e.jsxs("div",{children:[e.jsx(qt,{className:"text-lg",children:"Amazon SES — Mass Email"}),e.jsx(_r,{children:"Send bulk email campaigns via Amazon SES"})]})]}),e.jsx(We,{variant:m?"default":"secondary",children:u?"Checking...":m?e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Po,{className:"h-3 w-3"})," Connected"]}):e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Uo,{className:"h-3 w-3"})," Not Configured"]})})]})}),m&&e.jsxs(De,{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(re,{className:"text-xs",children:"From Email"}),e.jsx(we,{placeholder:"notifications@mail.relevelup.com",value:r,onChange:f=>a(f.target.value),className:"text-sm"})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(re,{className:"text-xs",children:"To Email"}),e.jsx(we,{placeholder:"your@email.com",value:t,onChange:f=>n(f.target.value),className:"text-sm"})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(re,{className:"text-xs",children:"Subject"}),e.jsx(we,{value:i,onChange:f=>l(f.target.value),className:"text-sm"})]})]}),e.jsxs(B,{onClick:h,disabled:o,size:"sm",children:[o?e.jsx(us,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(Rr,{className:"h-4 w-4 mr-2"}),"Send Test"]})]}),e.jsxs(B,{onClick:()=>s("/admin/email-campaigns"),className:"w-full",children:[e.jsx(um,{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(De,{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 KPe(s){const t=await bZ(),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 Bkn({status:s}){return s==="verified"?e.jsxs(We,{className:"bg-green-500/10 text-green-700 hover:bg-green-500/20 border-green-500/20",children:[e.jsx(Hr,{className:"h-3 w-3 mr-1"})," Verified"]}):s==="pending"?e.jsxs(We,{variant:"secondary",children:[e.jsx(Xr,{className:"h-3 w-3 mr-1"})," Pending — check inbox"]}):s==="failed"||s==="temporary_failure"?e.jsxs(We,{variant:"destructive",children:[e.jsx(Uo,{className:"h-3 w-3 mr-1"})," Failed"]}):e.jsxs(We,{variant:"outline",children:[e.jsx(Uo,{className:"h-3 w-3 mr-1"})," Not started"]})}function t9t({brokerageId:s,onVerifiedSelect:t}){const n=as(),[r,a]=N.useState(""),[i,l]=N.useState(""),[o,c]=N.useState(!1),[d,u]=N.useState(null),[h,m]=N.useState(null),{data:f,isLoading:g}=mt({queryKey:["brokerage-verified-senders",s],queryFn:async()=>{const{data:b,error:k}=await H.from("brokerage_verified_senders").select("*").eq("brokerage_id",s).order("created_at",{ascending:!1});if(k)throw k;return b||[]}}),y=_t({mutationFn:async()=>KPe({action:"request_verification",brokerage_id:s,email:r,display_name:i||void 0}),onSuccess:()=>{n.invalidateQueries({queryKey:["brokerage-verified-senders",s]}),ie.success("Verification email sent",{description:`Check ${r} and click the AWS verification link.`}),a(""),l(""),c(!1)},onError:b=>ie.error(b.message)}),x=async b=>{var k,A;u(b.id);try{const T=await KPe({action:"check_status",sender_id:b.id});n.invalidateQueries({queryKey:["brokerage-verified-senders",s]}),((k=T.sender)==null?void 0:k.status)==="verified"?ie.success(`${b.email} is verified! 🎉`):ie.info(`Status: ${((A=T.sender)==null?void 0:A.status)||"unknown"}`)}catch(T){ie.error(T.message)}finally{u(null)}},_=_t({mutationFn:async b=>KPe({action:"delete",sender_id:b}),onSuccess:()=>{n.invalidateQueries({queryKey:["brokerage-verified-senders",s]}),ie.success("Sender removed"),m(null)},onError:b=>ie.error(b.message)});return e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium mb-1",children:"Verified Sender Addresses"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Verify any email address (yours or your brokerage's) so recruiting emails can be sent from that address. Anyone managing this brokerage can use these senders."})]}),g?e.jsx("div",{className:"text-xs text-muted-foreground py-3",children:"Loading…"}):f&&f.length>0?e.jsx("div",{className:"space-y-2",children:f.map(b=>e.jsxs("div",{className:"flex items-center justify-between gap-3 p-3 rounded-lg border bg-card",children:[e.jsxs("div",{className:"flex items-center gap-3 min-w-0 flex-1",children:[e.jsx("div",{className:"h-9 w-9 rounded-full bg-muted flex items-center justify-center shrink-0",children:e.jsx(mn,{className:"h-4 w-4 text-muted-foreground"})}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsx("span",{className:"text-sm font-medium truncate",children:b.email}),e.jsx(Bkn,{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:()=>x(b),disabled:d===b.id,title:"Refresh status from AWS",children:d===b.id?e.jsx(us,{className:"h-4 w-4 animate-spin"}):e.jsx(oo,{className:"h-4 w-4"})}),e.jsx(B,{size:"sm",variant:"ghost",onClick:()=>m(b),className:"text-destructive hover:text-destructive",children:e.jsx(qn,{className:"h-4 w-4"})})]})]},b.id))}):e.jsx("div",{className:"text-xs text-muted-foreground py-2 italic",children:"No verified senders yet. Add one below."}),o?e.jsxs("div",{className:"rounded-lg border p-4 space-y-3 bg-muted/30",children:[e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-3",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(re,{className:"text-xs",children:"Email Address *"}),e.jsx(we,{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(re,{className:"text-xs",children:"Display Name (optional)"}),e.jsx(we,{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(us,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(mn,{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(nn,{className:"h-4 w-4 mr-1"})," Add Sender Address"]}),e.jsx(Fl,{open:!!h,onOpenChange:b=>!b&&m(null),children:e.jsxs(kl,{children:[e.jsxs(Sl,{children:[e.jsx(Al,{children:"Remove this sender?"}),e.jsxs(Tl,{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(Cl,{children:[e.jsx(El,{children:"Cancel"}),e.jsx(wl,{onClick:()=>h&&_.mutate(h.id),className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:"Remove"})]})]})})]})}async function YPe(s){const t=await bZ(),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 $kn({status:s}){return s==="verified"?e.jsxs(We,{className:"bg-green-500/10 text-green-700 hover:bg-green-500/20 border-green-500/20",children:[e.jsx(Hr,{className:"h-3 w-3 mr-1"})," Verified"]}):s==="pending"?e.jsxs(We,{variant:"secondary",children:[e.jsx(Xr,{className:"h-3 w-3 mr-1"})," Pending — check inbox"]}):s==="failed"||s==="temporary_failure"?e.jsxs(We,{variant:"destructive",children:[e.jsx(Uo,{className:"h-3 w-3 mr-1"})," Failed"]}):e.jsxs(We,{variant:"outline",children:[e.jsx(Uo,{className:"h-3 w-3 mr-1"})," Not started"]})}function Ukn({userId:s,onVerifiedSelect:t}){const n=as(),[r,a]=N.useState(""),[i,l]=N.useState(""),[o,c]=N.useState(!1),[d,u]=N.useState(null),[h,m]=N.useState(null),{data:f,isLoading:g}=mt({queryKey:["user-verified-senders",s],queryFn:async()=>{const{data:b,error:k}=await H.from("user_verified_senders").select("*").eq("user_id",s).order("created_at",{ascending:!1});if(k)throw k;return b||[]}}),y=_t({mutationFn:async()=>YPe({action:"request_verification",scope:"user",email:r,display_name:i||void 0}),onSuccess:()=>{n.invalidateQueries({queryKey:["user-verified-senders",s]}),ie.success("Verification email sent",{description:`Check ${r} and click the AWS verification link.`}),a(""),l(""),c(!1)},onError:b=>ie.error(b.message)}),x=async b=>{var k,A;u(b.id);try{const T=await YPe({action:"check_status",sender_id:b.id});n.invalidateQueries({queryKey:["user-verified-senders",s]}),((k=T.sender)==null?void 0:k.status)==="verified"?ie.success(`${b.email} is verified! 🎉`):ie.info(`Status: ${((A=T.sender)==null?void 0:A.status)||"unknown"}`)}catch(T){ie.error(T.message)}finally{u(null)}},_=_t({mutationFn:async b=>YPe({action:"delete",sender_id:b}),onSuccess:()=>{n.invalidateQueries({queryKey:["user-verified-senders",s]}),ie.success("Sender removed"),m(null)},onError:b=>ie.error(b.message)});return e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium mb-1",children:"Your Verified Sender Addresses"}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Verify your email address with Amazon so mass emails can be sent ",e.jsx("em",{children:"from"})," you. Add an address, then click the verification link Amazon sends to that inbox."]})]}),g?e.jsx("div",{className:"text-xs text-muted-foreground py-3",children:"Loading…"}):f&&f.length>0?e.jsx("div",{className:"space-y-2",children:f.map(b=>e.jsxs("div",{className:"flex items-center justify-between gap-3 p-3 rounded-lg border bg-card",children:[e.jsxs("div",{className:"flex items-center gap-3 min-w-0 flex-1",children:[e.jsx("div",{className:"h-9 w-9 rounded-full bg-muted flex items-center justify-center shrink-0",children:e.jsx(mn,{className:"h-4 w-4 text-muted-foreground"})}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsx("span",{className:"text-sm font-medium truncate",children:b.email}),e.jsx($kn,{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:()=>x(b),disabled:d===b.id,title:"Refresh status from AWS",children:d===b.id?e.jsx(us,{className:"h-4 w-4 animate-spin"}):e.jsx(oo,{className:"h-4 w-4"})}),e.jsx(B,{size:"sm",variant:"ghost",onClick:()=>m(b),className:"text-destructive hover:text-destructive",children:e.jsx(qn,{className:"h-4 w-4"})})]})]},b.id))}):e.jsx("div",{className:"text-xs text-muted-foreground py-2 italic",children:"No verified senders yet. Add one below."}),o?e.jsxs("div",{className:"rounded-lg border p-4 space-y-3 bg-muted/30",children:[e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-3",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(re,{className:"text-xs",children:"Email Address *"}),e.jsx(we,{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(re,{className:"text-xs",children:"Display Name (optional)"}),e.jsx(we,{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(us,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(mn,{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(nn,{className:"h-4 w-4 mr-1"})," Add Sender Address"]}),e.jsx(Fl,{open:!!h,onOpenChange:b=>!b&&m(null),children:e.jsxs(kl,{children:[e.jsxs(Sl,{children:[e.jsx(Al,{children:"Remove this sender?"}),e.jsxs(Tl,{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(Cl,{children:[e.jsx(El,{children:"Cancel"}),e.jsx(wl,{onClick:()=>h&&_.mutate(h.id),className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:"Remove"})]})]})})]})}function qkn(){var A,T,P,I,M;const{user:s,isBrokerageManager:t,isAdmin:n,managedBrokerages:r,selectedBrokerageId:a}=Ls(),i=a||((A=r==null?void 0:r[0])==null?void 0:A.id)||null,l=(t||n)&&!!i,o=as(),[c,d]=N.useState(!1),[u,h]=N.useState(""),[m,f]=N.useState(""),{data:g}=mt({queryKey:["mass-email-settings",s==null?void 0:s.id],enabled:!!s,queryFn:async()=>{const{data:L,error:z}=await H.from("mass_email_settings").select("*").eq("user_id",s.id).maybeSingle();if(z)throw z;return L}}),{data:y}=mt({queryKey:["agent-profile-email",s==null?void 0:s.id],enabled:!!s,queryFn:async()=>{const{data:L,error:z}=await H.from("profiles").select("email, name").eq("id",s.id).single();if(z)throw z;return L}}),x=((T=g==null?void 0:g.reply_to_email)==null?void 0:T.trim())||((P=y==null?void 0:y.email)==null?void 0:P.trim())||"",_=((I=g==null?void 0:g.display_name)==null?void 0:I.trim())||((M=y==null?void 0:y.name)==null?void 0:M.trim())||"";N.useEffect(()=>{c||(h(x),f(_))},[c,x,_]);const b=_t({mutationFn:async()=>{if(!s||!u.trim())throw new Error("Please enter a reply-to email");const L={reply_to_email:u.trim(),display_name:m.trim()||null,updated_at:new Date().toISOString()};if(g){const{error:z}=await H.from("mass_email_settings").update(L).eq("user_id",s.id);if(z)throw z}else{const{error:z}=await H.from("mass_email_settings").insert({user_id:s.id,...L});if(z)throw z}},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]}),ie.success("Reply-to email saved!"),d(!1)},onError:L=>ie.error(L.message)}),k=!!x;return e.jsxs(_e,{children:[e.jsx(zt,{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(Rr,{className:"h-5 w-5 text-orange-600"})}),e.jsxs("div",{children:[e.jsxs(qt,{className:"text-lg flex items-center gap-2",children:["Mass Email",k?e.jsxs(We,{variant:"default",className:"text-xs bg-green-600",children:[e.jsx(Po,{className:"h-3 w-3 mr-1"})," Set Up"]}):e.jsx(We,{variant:"secondary",className:"text-xs",children:"Setup Required"})]}),e.jsx(_r,{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(De,{className:"space-y-3",children:[k&&!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:_||"No display name"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:x})]}),e.jsxs(B,{variant:"ghost",size:"sm",onClick:()=>d(!0),children:[e.jsx(Ja,{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(re,{className:"text-xs",children:"Display Name"}),e.jsx(we,{placeholder:"e.g. 🏡 Karen Hall",value:m,onChange:L=>f(L.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(re,{className:"text-xs",children:"Reply-To Email *"}),e.jsx(we,{type:"email",placeholder:"your@email.com",value:u,onChange:L=>h(L.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(Kl,{className:"h-4 w-4 mr-1"})," Save"]}),c&&e.jsxs(B,{size:"sm",variant:"outline",onClick:()=>{d(!1),h(x),f(_)},children:[e.jsx(hr,{className:"h-4 w-4 mr-1"})," Cancel"]})]})]}),s&&e.jsxs(e.Fragment,{children:[e.jsx(Wl,{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(Wv,{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(Ukn,{userId:s.id,onVerifiedSelect:L=>{h(L),d(!0)}})]})]}),l&&e.jsxs(e.Fragment,{children:[e.jsx(Wl,{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(Wv,{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(t9t,{brokerageId:i})]})]})]})]})}function Vkn({authUserId:s,actingAsUserId:t}){const n=s??null,r=t??null,a=!!r&&!!n&&r!==n,i=a?r:n;return{scopeUserId:i,isDelegated:a,canViewConnections:!!i&&!a,canManageConnections:!!i&&!a}}function Hkn(){const s=tr(),{isAdmin:t,user:n}=Ls(),{actingAsAgent:r,effectiveUserId:a}=n4e(),i=as(),[l,o]=N.useState(!1),[c,d]=N.useState(!1),[u,h]=N.useState(!1),{scopeUserId:m,isDelegated:f}=Vkn({authUserId:n==null?void 0:n.id,actingAsUserId:(r==null?void 0:r.id)??a}),{data:g,isLoading:y}=mt({queryKey:["gmail-integration",m],enabled:!!m&&!f,queryFn:async()=>{const{data:z,error:$}=await H.from("gmail_integrations").select("*").eq("user_id",m).maybeSingle();if($)throw $;return z}}),{data:x}=mt({queryKey:["social-accounts",m],enabled:!!m&&!f,queryFn:async()=>{const{data:z,error:$}=await H.from("social_accounts").select("*").eq("user_id",m).order("created_at",{ascending:!1});if($)throw $;return z}}),_=async()=>{if(f){ie.error("Account connections must be made by the agent from their own login.");return}o(!0);try{const{data:z,error:$}=await H.functions.invoke("gmail-oauth",{body:{action:"get_auth_url"}});if($)throw $;if(z!=null&&z.authUrl)window.location.href=z.authUrl;else throw new Error("Failed to get authorization URL")}catch(z){console.error("Gmail OAuth error:",z),ie.error("Failed to start Gmail connection"),o(!1)}},b=async z=>{if(f){ie.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:$,error:V}=await H.functions.invoke("meta-oauth",{body:{action:"get_auth_url",callbackPath:"/social-connections/callback",authMode:z}});if(V)throw V;if($!=null&&$.authUrl)window.location.href=$.authUrl;else throw new Error("Failed to get authorization URL")}catch($){console.error("Meta OAuth error:",$),ie.error("Failed to start connection. Make sure Meta App credentials are configured."),d(!1)}},k=async()=>{if(f){ie.error("Account connections must be made by the agent from their own login.");return}h(!0);try{const{data:z,error:$}=await H.functions.invoke("linkedin-oauth",{body:{action:"get_auth_url",callbackPath:"/social-connections/linkedin-callback"}});if($)throw $;if(z!=null&&z.authUrl)window.location.href=z.authUrl;else throw new Error("Failed to get LinkedIn authorization URL")}catch(z){console.error("LinkedIn OAuth error:",z),ie.error("Failed to start LinkedIn connection. Please try again."),h(!1)}},A=_t({mutationFn:async z=>{const{error:$}=await H.from("gmail_integrations").delete().eq("id",z).eq("user_id",m);if($)throw $},onSuccess:()=>{i.invalidateQueries({queryKey:["gmail-integration",m]}),ie.success("Gmail disconnected")},onError:()=>{ie.error("Failed to disconnect Gmail")}}),T=_t({mutationFn:async z=>{const{error:$}=await H.from("social_accounts").delete().eq("id",z).eq("user_id",m);if($)throw $},onSuccess:()=>{i.invalidateQueries({queryKey:["social-accounts",m]}),ie.success("Account disconnected")},onError:()=>{ie.error("Failed to disconnect account")}}),P=!f&&!!(g!=null&&g.is_active),I=(x==null?void 0:x.filter(z=>z.platform==="facebook"))||[],M=(x==null?void 0:x.filter(z=>z.platform==="instagram"))||[],L=(x==null?void 0:x.filter(z=>z.platform==="linkedin"))||[];return e.jsx(Qs,{children:e.jsxs("div",{className:"max-w-3xl mx-auto space-y-6 animate-fade-in",children:[e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl font-bold tracking-tight",children:"Integrations"}),e.jsx("p",{className:"text-muted-foreground",children:"Connect third-party services to supercharge your Agent OS workflow."})]}),f&&e.jsx(_e,{className:"border-amber-500/40 bg-amber-500/5",children:e.jsxs(zt,{className:"flex flex-row items-start gap-3 space-y-0",children:[e.jsx(Au,{className:"h-5 w-5 text-amber-600 mt-0.5"}),e.jsxs("div",{children:[e.jsx(qt,{className:"text-base",children:"Connected accounts are hidden"}),e.jsxs(_r,{children:["You're working on behalf of ",r==null?void 0:r.name,". Email and social account connections are private to each agent and can only be viewed or changed from their own login."]})]})]})}),e.jsxs(_e,{children:[e.jsx(zt,{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(NT,{className:"h-5 w-5 text-primary"})}),e.jsxs("div",{children:[e.jsx(qt,{className:"text-lg",children:"ChatGPT"}),e.jsx(_r,{children:"Connect ChatGPT to LevelUp so it can use LevelUp tools on your behalf."})]})]})}),e.jsx(De,{children:e.jsxs(B,{variant:"outline",onClick:()=>s("/connect-chatgpt"),children:["View connection instructions ",e.jsx(vi,{className:"h-4 w-4 ml-1"})]})})]}),e.jsxs(_e,{children:[e.jsx(zt,{children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"h-10 w-10 rounded-lg bg-destructive/10 flex items-center justify-center",children:e.jsx(mn,{className:"h-5 w-5 text-destructive"})}),e.jsxs("div",{children:[e.jsxs(qt,{className:"text-lg flex items-center gap-2",children:["Gmail",P&&e.jsx(We,{variant:"default",className:"text-xs bg-green-600",children:"Connected"})]}),e.jsx(_r,{children:"Send emails directly from your contact pages and auto-log them as touchpoints."})]})]})}),e.jsx(De,{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(Po,{className:"h-4 w-4 mt-0.5 text-green-500 shrink-0"}),e.jsx("span",{children:"Send personalized emails from your Gmail account"})]}),e.jsxs("div",{className:"flex items-start gap-2 text-sm text-muted-foreground",children:[e.jsx(Po,{className:"h-4 w-4 mt-0.5 text-green-500 shrink-0"}),e.jsx("span",{children:"Automatically log emails as activity touchpoints"})]}),e.jsxs("div",{className:"flex items-start gap-2 text-sm text-muted-foreground",children:[e.jsx(Po,{className:"h-4 w-4 mt-0.5 text-green-500 shrink-0"}),e.jsx("span",{children:"Quick compose from any contact detail page"})]}),P?e.jsxs("div",{className:"flex items-center justify-between mt-4 p-3 rounded-lg border",children:[e.jsxs("div",{children:[e.jsx("p",{className:"font-medium text-sm",children:g.gmail_email}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Connected Gmail account"})]}),e.jsxs(Fl,{children:[e.jsx(Gf,{asChild:!0,children:e.jsx(B,{variant:"ghost",size:"icon",className:"text-destructive hover:text-destructive",children:e.jsx(qn,{className:"h-4 w-4"})})}),e.jsxs(kl,{children:[e.jsxs(Sl,{children:[e.jsx(Al,{children:"Disconnect Gmail?"}),e.jsx(Tl,{children:"This will remove your Gmail connection. You'll need to reconnect to send emails."})]}),e.jsxs(Cl,{children:[e.jsx(El,{children:"Cancel"}),e.jsx(wl,{onClick:()=>A.mutate(g.id),className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:"Disconnect"})]})]})]})]}):e.jsxs(B,{className:"mt-4",onClick:_,disabled:l||y,children:[l?e.jsx(oo,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(mn,{className:"h-4 w-4 mr-2"}),"Connect Gmail",e.jsx(vi,{className:"h-4 w-4 ml-2"})]})]})})]}),e.jsxs(_e,{children:[e.jsx(zt,{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(Kf,{className:"h-5 w-5 text-blue-600"})}),e.jsxs("div",{children:[e.jsxs(qt,{className:"text-lg flex items-center gap-2",children:["Facebook",I.length>0&&e.jsx(We,{variant:"default",className:"text-xs bg-green-600",children:"Connected"})]}),e.jsx(_r,{children:"Connect Facebook Pages to post content and reach your audience."})]})]})}),e.jsxs(De,{className:"space-y-3",children:[I.length>0&&e.jsx("div",{className:"space-y-2",children:I.map(z=>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(Ua,{className:"h-8 w-8",children:[e.jsx(Gi,{src:z.profile_picture_url||""}),e.jsx(qa,{children:e.jsx(Kf,{className:"h-4 w-4"})})]}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium text-sm",children:z.page_name||z.platform_username||"Facebook Page"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Connected Facebook Page"})]})]}),e.jsxs(Fl,{children:[e.jsx(Gf,{asChild:!0,children:e.jsx(B,{variant:"ghost",size:"icon",className:"text-destructive hover:text-destructive",children:e.jsx(qn,{className:"h-4 w-4"})})}),e.jsxs(kl,{children:[e.jsxs(Sl,{children:[e.jsx(Al,{children:"Disconnect Facebook?"}),e.jsx(Tl,{children:"This will remove the connection. You'll need to reconnect to post content."})]}),e.jsxs(Cl,{children:[e.jsx(El,{children:"Cancel"}),e.jsx(wl,{onClick:()=>T.mutate(z.id),className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:"Disconnect"})]})]})]})]},z.id))}),e.jsxs(B,{onClick:()=>b("facebook"),disabled:c,variant:"outline",className:"gap-2",children:[c?e.jsx(oo,{className:"h-4 w-4 animate-spin"}):e.jsx(nn,{className:"h-4 w-4"}),"Connect Facebook Page"]})]})]}),e.jsxs(_e,{children:[e.jsx(zt,{children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"h-10 w-10 rounded-lg bg-pink-500/10 flex items-center justify-center",children:e.jsx(dm,{className:"h-5 w-5 text-pink-600"})}),e.jsxs("div",{children:[e.jsxs(qt,{className:"text-lg flex items-center gap-2",children:["Instagram",M.length>0&&e.jsx(We,{variant:"default",className:"text-xs bg-green-600",children:"Connected"})]}),e.jsx(_r,{children:"Connect an Instagram Business or Creator account to schedule and publish posts. Personal accounts are not supported by Meta's API."})]})]})}),e.jsxs(De,{className:"space-y-3",children:[M.length>0&&e.jsx("div",{className:"space-y-2",children:M.map(z=>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(Ua,{className:"h-8 w-8",children:[e.jsx(Gi,{src:z.profile_picture_url||""}),e.jsx(qa,{children:e.jsx(dm,{className:"h-4 w-4"})})]}),e.jsxs("div",{children:[e.jsxs("p",{className:"font-medium text-sm",children:["@",z.platform_username||"Instagram Account"]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Connected Instagram account"})]})]}),e.jsxs(Fl,{children:[e.jsx(Gf,{asChild:!0,children:e.jsx(B,{variant:"ghost",size:"icon",className:"text-destructive hover:text-destructive",children:e.jsx(qn,{className:"h-4 w-4"})})}),e.jsxs(kl,{children:[e.jsxs(Sl,{children:[e.jsx(Al,{children:"Disconnect Instagram?"}),e.jsx(Tl,{children:"This will remove the connection. You'll need to reconnect to post content."})]}),e.jsxs(Cl,{children:[e.jsx(El,{children:"Cancel"}),e.jsx(wl,{onClick:()=>T.mutate(z.id),className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:"Disconnect"})]})]})]})]},z.id))}),e.jsxs(B,{onClick:()=>b("instagram"),disabled:c,variant:"outline",className:"gap-2",children:[c?e.jsx(oo,{className:"h-4 w-4 animate-spin"}):e.jsx(nn,{className:"h-4 w-4"}),"Connect Instagram Professional"]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Uses Instagram's professional login for Business or Creator accounts. Personal accounts cannot post via Meta's API — convert your account in the Instagram app (Profile → Menu → Settings → Account type → Switch to Professional)."})]})]}),e.jsxs(_e,{children:[e.jsx(zt,{children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"h-10 w-10 rounded-lg bg-blue-700/10 flex items-center justify-center",children:e.jsx(W0,{className:"h-5 w-5 text-blue-700"})}),e.jsxs("div",{children:[e.jsxs(qt,{className:"text-lg flex items-center gap-2",children:["LinkedIn",L.length>0&&e.jsx(We,{variant:"default",className:"text-xs bg-green-600",children:"Connected"})]}),e.jsx(_r,{children:"Connect your LinkedIn profile to share content and grow your professional network."})]})]})}),e.jsxs(De,{className:"space-y-3",children:[L.length>0&&e.jsx("div",{className:"space-y-2",children:L.map(z=>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(Ua,{className:"h-8 w-8",children:[e.jsx(Gi,{src:z.profile_picture_url||""}),e.jsx(qa,{children:e.jsx(W0,{className:"h-4 w-4"})})]}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium text-sm",children:z.platform_username||"LinkedIn Account"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Connected LinkedIn profile"})]})]}),e.jsxs(Fl,{children:[e.jsx(Gf,{asChild:!0,children:e.jsx(B,{variant:"ghost",size:"icon",className:"text-destructive hover:text-destructive",children:e.jsx(qn,{className:"h-4 w-4"})})}),e.jsxs(kl,{children:[e.jsxs(Sl,{children:[e.jsx(Al,{children:"Disconnect LinkedIn?"}),e.jsx(Tl,{children:"This will remove your LinkedIn connection. You'll need to reconnect to post content."})]}),e.jsxs(Cl,{children:[e.jsx(El,{children:"Cancel"}),e.jsx(wl,{onClick:()=>T.mutate(z.id),className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:"Disconnect"})]})]})]})]},z.id))}),e.jsxs(B,{onClick:k,disabled:u,variant:"outline",className:"gap-2",children:[u?e.jsx(oo,{className:"h-4 w-4 animate-spin"}):e.jsx(nn,{className:"h-4 w-4"}),"Connect LinkedIn"]})]})]}),e.jsx(Dkn,{}),e.jsx(Rkn,{}),e.jsx(Okn,{}),e.jsx(zkn,{}),e.jsx(qkn,{}),t&&e.jsx(e9t,{})]})})}const Gkn="https://chromewebstore.google.com/detail/levelup-companion/lppakdeaencigddecnkcifdcemlfpkkk";function Wkn(){const[s,t]=N.useState(null),[n,r]=N.useState(!1),[a,i]=N.useState(0),[l,o]=N.useState(!1),c="/levelup-extension.zip",d="https://tile-portal.lovable.app/levelup-extension.zip",u=window.location.hostname.startsWith("id-preview--"),h=async x=>{const _=new Uint8Array(await x.slice(0,4).arrayBuffer());return _[0]===80&&_[1]===75&&_[2]===3&&_[3]===4||_[0]===80&&_[1]===75&&_[2]===5&&_[3]===6||_[0]===80&&_[1]===75&&_[2]===7&&_[3]===8},m=x=>{const _=document.createElement("a");_.href=x,_.download="levelup-extension.zip",_.rel="noopener noreferrer",_.target="_blank",document.body.appendChild(_),_.click(),_.remove()},f=async()=>{o(!0);try{if(u){m(`${d}?v=${Date.now()}`);return}const x=await fetch(`${c}?v=${Date.now()}`,{cache:"no-store"});if(!x.ok)throw new Error(`Download failed (${x.status})`);const _=await x.blob();if(!await h(_)){m(`${d}?v=${Date.now()}`);return}const b=new Blob([_],{type:"application/zip"}),k=URL.createObjectURL(b),A=document.createElement("a");A.href=k,A.download="levelup-extension.zip",document.body.appendChild(A),A.click(),A.remove(),setTimeout(()=>URL.revokeObjectURL(k),1e3)}catch(x){ie.error(x.message||"Download failed")}finally{o(!1)}},g=async()=>{r(!0);try{await H.auth.refreshSession();const{data:x}=await H.auth.getSession();if(!x.session){ie.error("Your session has expired. Please sign in again.");return}const{data:_,error:b}=await H.functions.invoke("extension-pair-start",{headers:{Authorization:`Bearer ${x.session.access_token}`}});if(b)throw b;t(_.code),i(_.expires_in||300);const k=setInterval(()=>{i(A=>A<=1?(clearInterval(k),t(null),0):A-1)},1e3)}catch(x){console.error("generateCode error",x),ie.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),ie.success("Copied"))};return e.jsx(Qs,{title:"Browser Extension",children:e.jsxs("div",{className:"container max-w-3xl mx-auto py-8 px-4 space-y-6",children:[e.jsxs(ic,{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(lD,{className:"w-6 h-6"})}),e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl font-bold",children:"Browser Extension"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Add contacts and import listings from anywhere on the web."})]})]})}),e.jsxs(_e,{className:"p-6 space-y-4 border-2 border-primary/20",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"w-6 h-6 rounded-full bg-primary text-primary-foreground flex items-center justify-center text-xs font-bold",children:"1"}),e.jsx("h2",{className:"text-lg font-semibold",children:"Install from the Chrome Web Store"})]}),e.jsxs("ul",{className:"text-sm text-muted-foreground space-y-1 list-disc list-inside",children:[e.jsx("li",{children:"Quick-add contacts from any webpage with one click or right-click"}),e.jsx("li",{children:"Import listings from Zillow, Realtor.com, and Redfin as drafts"}),e.jsx("li",{children:'"Add to LevelUp" button on Gmail threads and LinkedIn profiles'}),e.jsx("li",{children:"Toolbar launcher with shortcuts to Dashboard, ReelFlow, Card Studio, and more"})]}),e.jsxs(B,{size:"lg",className:"w-full",onClick:()=>window.open(Gkn,"_blank","noopener,noreferrer"),children:[e.jsx(lD,{className:"w-4 h-4 mr-2"}),"Add to Chrome",e.jsx(Tr,{className:"w-3.5 h-3.5 ml-2 opacity-70"})]}),e.jsx("p",{className:"text-xs text-center text-muted-foreground",children:"Works in Chrome, Edge, Brave, and Arc. Free to install."})]}),e.jsxs(_e,{className:"p-6 space-y-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"w-6 h-6 rounded-full bg-primary text-primary-foreground flex items-center justify-center text-xs font-bold",children:"2"}),e.jsx("h2",{className:"text-lg font-semibold",children:"Pair the extension"})]}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Generate a one-time pairing code, then enter it inside the extension popup."}),s?e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"bg-muted rounded-xl p-6 text-center",children:[e.jsx("div",{className:"text-4xl font-mono font-bold tracking-[0.4em] text-primary",children:s}),e.jsxs("p",{className:"text-xs text-muted-foreground mt-3",children:["Expires in ",Math.floor(a/60),":",String(a%60).padStart(2,"0")]})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(B,{onClick:y,variant:"outline",className:"flex-1",children:[e.jsx(Pa,{className:"w-4 h-4 mr-2"})," Copy"]}),e.jsxs(B,{onClick:g,variant:"outline",className:"flex-1",children:[e.jsx(oo,{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(pa,{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:g,disabled:n,size:"lg",className:"w-full",children:n?e.jsxs(e.Fragment,{children:[e.jsx(oo,{className:"w-4 h-4 mr-2 animate-spin"}),"Generating…"]}):"Generate pairing code"})]}),e.jsxs(_e,{className:"p-6 space-y-4 bg-muted/30 border-dashed",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ku,{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:f,disabled:l,children:"Download the extension ZIP"})}),e.jsx("li",{children:"Unzip the downloaded file"}),e.jsxs("li",{children:["Open"," ",e.jsx("code",{className:"px-1.5 py-0.5 rounded bg-muted text-foreground",children:"chrome://extensions"})," ","in Chrome, Edge, Brave, or Arc"]}),e.jsxs("li",{children:["Turn on ",e.jsx("b",{className:"text-foreground",children:"Developer mode"})," (top-right toggle)"]}),e.jsxs("li",{children:["Click ",e.jsx("b",{className:"text-foreground",children:"Load unpacked"})," and pick the unzipped folder"]}),e.jsx("li",{children:"Pin the LevelUp icon to your toolbar"})]})]})]})})}function Kkn(){const[s]=$c(),t=tr(),[n,r]=N.useState("loading"),[a,i]=N.useState("Connecting your Gmail account...");return N.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"),ie.error("Connection failed: "+(d||c));return}if(!o){r("error"),i("No authorization code received"),ie.error("No authorization code received");return}try{const{data:h,error:m}=await H.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!"),ie.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"),ie.error("Failed to connect: "+(h instanceof Error?h.message:"Unknown error"))}})()},[s]),e.jsx("div",{className:"min-h-screen flex items-center justify-center bg-background p-4",children:e.jsxs(_e,{className:"w-full max-w-md",children:[e.jsxs(zt,{className:"text-center",children:[n==="loading"&&e.jsx(us,{className:"h-12 w-12 animate-spin mx-auto text-primary"}),n==="success"&&e.jsx(Po,{className:"h-12 w-12 mx-auto text-green-500"}),n==="error"&&e.jsx(Nu,{className:"h-12 w-12 mx-auto text-destructive"}),e.jsxs(qt,{className:"mt-4",children:[n==="loading"&&"Connecting...",n==="success"&&"Connected!",n==="error"&&"Connection Failed"]}),e.jsx(_r,{children:a})]}),e.jsx(De,{className:"flex justify-center",children:n!=="loading"&&e.jsx(B,{onClick:()=>t("/mission-control/integrations"),children:n==="success"?"Back to Integrations":"Try Again"})})]})})}function Ykn(){const s=tr();return N.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 Zkn(){const[s]=$c(),t=tr(),[n,r]=N.useState("loading"),[a,i]=N.useState("Processing your connection...");return N.useEffect(()=>{(async()=>{var h;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"),ie.error("Connection failed: "+(d||c));return}if(!o){r("error"),i("No authorization code received"),ie.error("No authorization code received");return}try{const{data:m,error:f}=await H.functions.invoke("meta-oauth",{body:{action:"exchange_code",code:o,state:u,callbackPath:"/mission-control/integrations/meta/callback"}});if(m&&m.success===!1)throw new Error(m.error||"Failed to connect accounts");if(f){let g=f.message||"Failed to connect accounts";try{const y=f.context;if(y&&typeof y.json=="function"){const x=await y.json();x!=null&&x.error&&(g=x.error)}}catch{}throw new Error(g)}if(m!=null&&m.success)r("success"),i(`Successfully connected ${((h=m.accounts)==null?void 0:h.length)||0} account(s)!`),ie.success("Social accounts connected successfully!");else throw new Error((m==null?void 0:m.error)||"Unknown error")}catch(m){console.error("OAuth callback error:",m),r("error"),i(m instanceof Error?m.message:"Failed to connect accounts"),ie.error("Failed to connect: "+(m instanceof Error?m.message:"Unknown error"))}})()},[s]),e.jsx("div",{className:"min-h-screen flex items-center justify-center bg-background p-4",children:e.jsxs(_e,{className:"w-full max-w-md",children:[e.jsxs(zt,{className:"text-center",children:[n==="loading"&&e.jsx(us,{className:"h-12 w-12 animate-spin mx-auto text-primary"}),n==="success"&&e.jsx(Po,{className:"h-12 w-12 mx-auto text-green-500"}),n==="error"&&e.jsx(Nu,{className:"h-12 w-12 mx-auto text-destructive"}),e.jsxs(qt,{className:"mt-4",children:[n==="loading"&&"Connecting...",n==="success"&&"Connected!",n==="error"&&"Connection Failed"]}),e.jsx(_r,{children:a})]}),e.jsx(De,{className:"flex justify-center",children:n!=="loading"&&e.jsx(B,{onClick:()=>t("/mission-control/integrations"),children:n==="success"?"View Integrations":"Try Again"})})]})})}const s9t=new Date().getFullYear(),Xkn=Array.from({length:5},(s,t)=>s9t-t);function Qkn(){const[s,t]=N.useState(s9t),n=tr(),{data:r,isLoading:a}=l2s();return a?e.jsx(Qs,{title:"Scorecard Admin",children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(xn,{className:"h-8 w-64"}),e.jsx("div",{className:"grid grid-cols-4 gap-4",children:[1,2,3,4].map(i=>e.jsx(xn,{className:"h-24"},i))}),e.jsx(xn,{className:"h-96"})]})}):e.jsx(Qs,{title:"Scorecard Admin",children:e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4",children:[e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl font-bold text-foreground",children:"Scorecard Admin"}),e.jsx("p",{className:"text-muted-foreground",children:"View agent performance and scorecards"})]}),e.jsxs(Ns,{value:String(s),onValueChange:i=>t(Number(i)),children:[e.jsx(ws,{className:"w-[120px]",children:e.jsx(ks,{})}),e.jsx(js,{children:Xkn.map(i=>e.jsx(nt,{value:String(i),children:i},i))})]})]}),e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4",children:[e.jsx(_e,{children:e.jsxs(De,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[e.jsx(Yn,{className:"h-4 w-4"}),e.jsx("span",{className:"text-xs font-medium",children:"Agents Tracking"})]}),e.jsx("p",{className:"text-2xl font-bold",children:(r==null?void 0:r.length)||0})]})}),e.jsx(_e,{children:e.jsxs(De,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[e.jsx(fl,{className:"h-4 w-4"}),e.jsx("span",{className:"text-xs font-medium",children:"Total Agents"})]}),e.jsx("p",{className:"text-2xl font-bold",children:(r==null?void 0:r.length)||0}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"with transactions"})]})})]}),e.jsxs(_e,{children:[e.jsxs(zt,{children:[e.jsx(qt,{children:"Agents with Scorecards"}),e.jsx(_r,{children:"Click to view individual agent scorecards"})]}),e.jsx(De,{children:!r||r.length===0?e.jsxs("div",{className:"text-center py-8 text-muted-foreground",children:[e.jsx(fl,{className:"h-12 w-12 mx-auto mb-4 opacity-50"}),e.jsx("p",{children:"No agents have added transactions yet"})]}):e.jsxs(Oa,{children:[e.jsx(Fa,{children:e.jsxs(un,{children:[e.jsx(Mt,{children:"Agent"}),e.jsx(Mt,{children:"Email"}),e.jsx(Mt,{className:"text-right",children:"Actions"})]})}),e.jsx(za,{children:r.map(i=>e.jsxs(un,{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(da,{className:"h-4 w-4 mr-2"}),"View Scorecard"]})})]},i.id))})]})})]})]})})}const n9t=new Date().getFullYear(),Jkn=Array.from({length:10},(s,t)=>n9t-t);function Gft(){var y;const{userId:s}=uo(),t=tr(),r=Id().pathname.startsWith("/mission-control"),[a,i]=N.useState(n9t),{data:l,isLoading:o}=mt({queryKey:["agent-profile",s],queryFn:async()=>{const{data:x,error:_}=await H.from("profiles").select("id, name, email").eq("id",s).single();if(_)throw _;return x},enabled:!!s}),{data:c,isLoading:d}=fqe(a,s),{yearStats:u,lifetimeStats:h,isLoading:m,showCommission:f}=U4t(a,s),{data:g}=$4t(a,s);return o?e.jsx(Qs,{title:"Agent Scorecard",children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(xn,{className:"h-8 w-64"}),e.jsx("div",{className:"grid grid-cols-4 gap-4",children:[1,2,3,4].map(x=>e.jsx(xn,{className:"h-24"},x))})]})}):e.jsx(Qs,{title:`${l==null?void 0:l.name}'s Scorecard`,children:e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4",children:[e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsx(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(Ns,{value:String(a),onValueChange:x=>i(Number(x)),children:[e.jsx(ws,{className:"w-[120px]",children:e.jsx(ks,{})}),e.jsx(js,{children:Jkn.map(x=>e.jsx(nt,{value:String(x),children:x},x))})]})]}),e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 lg:grid-cols-5 gap-4",children:[e.jsx(_e,{children:e.jsxs(De,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[e.jsx(_a,{className:"h-4 w-4"}),e.jsx("span",{className:"text-xs font-medium",children:"Transactions"})]}),e.jsx("p",{className:"text-2xl font-bold",children:u.totalTransactions}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[h.totalTransactions," lifetime"]})]})}),e.jsx(_e,{children:e.jsxs(De,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[e.jsx(Yn,{className:"h-4 w-4"}),e.jsx("span",{className:"text-xs font-medium",children:"Buyer/Seller"})]}),e.jsxs("p",{className:"text-2xl font-bold",children:[u.buyerCount,"/",u.sellerCount]})]})}),e.jsx(_e,{children:e.jsxs(De,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[e.jsx(Ed,{className:"h-4 w-4"}),e.jsx("span",{className:"text-xs font-medium",children:"Volume"})]}),e.jsx("p",{className:"text-2xl font-bold",children:_u(u.totalVolume,!0)})]})}),e.jsx(_e,{children:e.jsxs(De,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[e.jsx(ml,{className:"h-4 w-4"}),e.jsx("span",{className:"text-xs font-medium",children:"Avg Price"})]}),e.jsx("p",{className:"text-2xl font-bold",children:_u(u.averagePrice,!0)})]})}),e.jsx(_e,{children:e.jsxs(De,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[e.jsx(ku,{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)||"-"})]})})]}),g&&e.jsx(d7t,{goals:g,stats:u,year:a,showCommission:f}),e.jsxs(ya,{defaultValue:"transactions",className:"space-y-4",children:[e.jsxs(va,{children:[e.jsx(ls,{value:"transactions",children:"Transactions"}),e.jsx(ls,{value:"charts",children:"Charts"}),e.jsxs(ls,{value:"map",children:[e.jsx(ii,{className:"h-4 w-4 mr-1"}),"Map"]})]}),e.jsx(_s,{value:"transactions",children:e.jsx(zWe,{transactions:c||[],showCommission:f,isLoading:d})}),e.jsx(_s,{value:"charts",children:e.jsx(BWe,{stats:u,year:a})}),e.jsx(_s,{value:"map",children:e.jsx($We,{transactions:c||[],isLoading:d})})]})]})})}function e5n(){const s=as(),[t,n]=N.useState(""),[r,a]=N.useState("all"),[i,l]=N.useState(null);_St();const{data:o,refetch:c}=mt({queryKey:["listing-exchange-flag"],queryFn:async()=>{const{data:L}=await H.from("feature_flags").select("enabled").eq("key","listing_exchange_enabled").single();return(L==null?void 0:L.enabled)??!1}}),{data:d,isLoading:u}=mt({queryKey:["admin-listings"],queryFn:async()=>{const{data:L,error:z}=await H.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(z)throw z;return L}}),{data:h}=mt({queryKey:["admin-listing-stats"],queryFn:async()=>{const{data:L}=await H.from("listings").select("id, is_approved, status"),{data:z}=await H.from("listing_shares").select("id"),{data:$}=await H.from("listing_views").select("id"),{count:V}=await H.from("listing_leads").select("id",{count:"exact",head:!0}),W=new Date(Date.now()-7*24*60*60*1e3).toISOString(),{count:G}=await H.from("listing_leads").select("id",{count:"exact",head:!0}).gte("created_at",W);return{total:(L==null?void 0:L.length)||0,pending:(L==null?void 0:L.filter(X=>!X.is_approved).length)||0,active:(L==null?void 0:L.filter(X=>X.status==="active").length)||0,totalShares:(z==null?void 0:z.length)||0,totalViews:($==null?void 0:$.length)||0,totalLeads:V||0,leadsLast7:G||0}}}),{data:m}=mt({queryKey:["admin-listing-lead-counts"],queryFn:async()=>{const L={};let z=0;const $=1e3;for(;;){const{data:V,error:W}=await H.from("listing_leads").select("listing_id").range(z,z+$-1);if(W)throw W;if(!V||V.length===0)break;for(const G of V)G.listing_id&&(L[G.listing_id]=(L[G.listing_id]||0)+1);if(V.length<$)break;z+=$}return L}}),{data:f,isLoading:g}=mt({queryKey:["admin-listing-leads",i==null?void 0:i.listingId],enabled:!!i,queryFn:async()=>{const{data:L,error:z}=await H.from("listing_leads").select("*").eq("listing_id",i.listingId).order("created_at",{ascending:!1});if(z)throw z;return L}}),y=async(L,z,$="submit_url")=>{try{const{data:{session:V}}=await H.auth.getSession();if(!V)return;const{data:W,error:G}=await H.functions.invoke("google-indexing",{body:{action:$,listing_id:L,listing_slug:z}});if(G)throw G;if((W==null?void 0:W.configured)===!1)return;W!=null&&W.success&&ie.success("Submitted to Google for indexing")}catch(V){console.error("Google indexing submission failed:",V)}},x=_t({mutationFn:async()=>{const{data:{session:L}}=await H.auth.getSession();if(!L)throw new Error("Not authenticated");const{data:z,error:$}=await H.functions.invoke("google-indexing",{body:{action:"submit_all"}});if($)throw $;return z},onSuccess:L=>{if((L==null?void 0:L.configured)===!1){ie.error("Google Indexing API not configured. Add the GOOGLE_INDEXING_SERVICE_ACCOUNT secret.");return}ie.success(`Submitted ${(L==null?void 0:L.succeeded)||0} URLs to Google (${(L==null?void 0:L.failed)||0} failed)`)},onError:L=>{ie.error("Failed to submit to Google"),console.error(L)}}),_=_t({mutationFn:async({id:L,approved:z,slug:$})=>{const{error:V}=await H.from("listings").update({is_approved:z}).eq("id",L);if(V)throw V;return{id:L,approved:z,slug:$}},onSuccess:L=>{s.invalidateQueries({queryKey:["admin-listings"]}),s.invalidateQueries({queryKey:["admin-listing-stats"]}),ie.success(L.approved?"Listing approved":"Listing unapproved"),L.approved?y(L.id,L.slug||null,"submit_url"):y(L.id,L.slug||null,"remove_url")}}),b=_t({mutationFn:async({id:L,featured:z})=>{const{error:$}=await H.from("listings").update({is_featured:z}).eq("id",L);if($)throw $},onSuccess:(L,{featured:z})=>{s.invalidateQueries({queryKey:["admin-listings"]}),ie.success(z?"Listing featured":"Listing unfeatured")}}),k=_t({mutationFn:async L=>{const{error:z}=await H.from("listings").delete().eq("id",L);if(z)throw z},onSuccess:()=>{s.invalidateQueries({queryKey:["admin-listings"]}),s.invalidateQueries({queryKey:["admin-listing-stats"]}),ie.success("Listing deleted")}}),A=_t({mutationFn:async L=>{const{error:z}=await H.from("feature_flags").update({enabled:L}).eq("key","listing_exchange_enabled");if(z)throw z},onSuccess:()=>{c(),ie.success("Feature flag updated")}}),T=o??!1,P=d==null?void 0:d.filter(L=>{var V,W,G,X;const z=((V=L.city)==null?void 0:V.toLowerCase().includes(t.toLowerCase()))||((G=(W=L.agent)==null?void 0:W.name)==null?void 0:G.toLowerCase().includes(t.toLowerCase()))||((X=L.property_address)==null?void 0:X.toLowerCase().includes(t.toLowerCase())),$=r==="all"||r==="pending"&&!L.is_approved||r==="approved"&&L.is_approved;return z&&$}),I=L=>new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:0}).format(L),M=L=>{const z={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 z[L]||z.active};return e.jsxs(Qs,{title:"Listing Exchange Admin",children:[e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center justify-between gap-4",children:[e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl font-bold",children:"Listing Exchange"}),e.jsx("p",{className:"text-muted-foreground",children:"Manage community listings"})]}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs(B,{variant:"outline",size:"sm",onClick:()=>x.mutate(),disabled:x.isPending,className:"gap-2",children:[x.isPending?e.jsx(us,{className:"h-4 w-4 animate-spin"}):e.jsx(au,{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(zn,{checked:T,onCheckedChange:L=>A.mutate(L)})]})]}),e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-6 gap-4",children:[e.jsx(_e,{children:e.jsxs(De,{className:"p-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ti,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{className:"text-sm text-muted-foreground",children:"Total Listings"})]}),e.jsx("p",{className:"text-2xl font-bold mt-1",children:(h==null?void 0:h.total)||0})]})}),e.jsx(_e,{children:e.jsxs(De,{className:"p-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ml,{className:"h-4 w-4 text-green-500"}),e.jsx("span",{className:"text-sm text-muted-foreground",children:"Active"})]}),e.jsx("p",{className:"text-2xl font-bold mt-1",children:(h==null?void 0:h.active)||0})]})}),e.jsx(_e,{children:e.jsxs(De,{className:"p-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Yn,{className:"h-4 w-4 text-amber-500"}),e.jsx("span",{className:"text-sm text-muted-foreground",children:"Pending Review"})]}),e.jsx("p",{className:"text-2xl font-bold mt-1",children:(h==null?void 0:h.pending)||0})]})}),e.jsx(_e,{children:e.jsxs(De,{className:"p-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(da,{className:"h-4 w-4 text-blue-500"}),e.jsx("span",{className:"text-sm text-muted-foreground",children:"Total Views"})]}),e.jsx("p",{className:"text-2xl font-bold mt-1",children:(h==null?void 0:h.totalViews)||0})]})}),e.jsx(_e,{children:e.jsxs(De,{className:"p-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Md,{className:"h-4 w-4 text-purple-500"}),e.jsx("span",{className:"text-sm text-muted-foreground",children:"Total Shares"})]}),e.jsx("p",{className:"text-2xl font-bold mt-1",children:(h==null?void 0:h.totalShares)||0})]})}),e.jsx(_e,{children:e.jsxs(De,{className:"p-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Yl,{className:"h-4 w-4 text-teal-600"}),e.jsx("span",{className:"text-sm text-muted-foreground",children:"Leads"})]}),e.jsx("p",{className:"text-2xl font-bold mt-1",children:(h==null?void 0:h.totalLeads)||0}),e.jsxs("p",{className:"text-xs text-muted-foreground mt-0.5",children:[(h==null?void 0:h.leadsLast7)||0," in last 7 days"]})]})})]}),e.jsx(_e,{children:e.jsx(De,{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(Gr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(we,{placeholder:"Search by city, address, or agent...",value:t,onChange:L=>n(L.target.value),className:"pl-9"})]}),e.jsx(ya,{value:r,onValueChange:L=>a(L),children:e.jsxs(va,{children:[e.jsx(ls,{value:"all",children:"All"}),e.jsx(ls,{value:"pending",children:"Pending"}),e.jsx(ls,{value:"approved",children:"Approved"})]})})]})})}),e.jsxs(_e,{children:[e.jsx(zt,{children:e.jsxs(qt,{children:["Listings (",(P==null?void 0:P.length)||0,")"]})}),e.jsx(De,{children:e.jsx("div",{className:"overflow-x-auto",children:e.jsxs(Oa,{children:[e.jsx(Fa,{children:e.jsxs(un,{children:[e.jsx(Mt,{children:"Property"}),e.jsx(Mt,{children:"Agent"}),e.jsx(Mt,{children:"Price"}),e.jsx(Mt,{children:"Status"}),e.jsx(Mt,{className:"text-center",children:"Approved"}),e.jsx(Mt,{className:"text-center",children:"Featured"}),e.jsx(Mt,{children:"Views"}),e.jsx(Mt,{children:"Shares"}),e.jsx(Mt,{children:"Leads"}),e.jsx(Mt,{children:"Date"}),e.jsx(Mt,{})]})}),e.jsx(za,{children:u?e.jsx(un,{children:e.jsx(gt,{colSpan:11,className:"text-center py-8 text-muted-foreground",children:"Loading..."})}):(P==null?void 0:P.length)===0?e.jsx(un,{children:e.jsx(gt,{colSpan:11,className:"text-center py-8 text-muted-foreground",children:"No listings found"})}):P==null?void 0:P.map(L=>{var z,$,V,W,G;return e.jsxs(un,{children:[e.jsx(gt,{children:e.jsxs("div",{className:"flex items-center gap-3",children:[($=(z=L.photos)==null?void 0:z[0])!=null&&$.photo_url?e.jsx("img",{src:L.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(Ti,{className:"h-5 w-5 text-muted-foreground"})}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium text-sm",children:L.property_address||`${L.city}, ${L.state}`}),e.jsx("p",{className:"text-xs text-muted-foreground",children:(V=L.property_type)==null?void 0:V.replace("_"," ")})]})]})}),e.jsx(gt,{children:e.jsx("p",{className:"text-sm",children:((W=L.agent)==null?void 0:W.name)||"Unknown"})}),e.jsx(gt,{className:"font-medium",children:I(L.price)}),e.jsx(gt,{children:e.jsx(We,{variant:"outline",className:M(L.status),children:(G=L.status)==null?void 0:G.replace("_"," ")})}),e.jsx(gt,{className:"text-center",children:e.jsx(zn,{checked:L.is_approved??!1,onCheckedChange:X=>_.mutate({id:L.id,approved:X,slug:L.slug})})}),e.jsx(gt,{className:"text-center",children:e.jsx(zn,{checked:L.is_featured??!1,onCheckedChange:X=>b.mutate({id:L.id,featured:X})})}),e.jsx(gt,{children:L.view_count||0}),e.jsx(gt,{children:L.share_count||0}),e.jsx(gt,{children:((m==null?void 0:m[L.id])??0)>0?e.jsx(B,{variant:"link",size:"sm",className:"px-0 h-auto font-semibold text-teal-600",onClick:()=>l({listingId:L.id,label:L.property_address||`${L.city}, ${L.state}`}),children:m==null?void 0:m[L.id]}):e.jsx("span",{className:"text-muted-foreground",children:"0"})}),e.jsx(gt,{className:"text-sm text-muted-foreground",children:Js(new Date(L.created_at),"MMM d, yyyy")}),e.jsx(gt,{children:e.jsxs(qd,{children:[e.jsx(Vd,{asChild:!0,children:e.jsx(B,{variant:"ghost",size:"icon",children:e.jsx(Iy,{className:"h-4 w-4"})})}),e.jsxs(Ld,{align:"end",children:[e.jsxs(ba,{onClick:()=>window.open(`/mission-control/listings/${L.id}`,"_blank"),children:[e.jsx(da,{className:"h-4 w-4 mr-2"}),"View Listing"]}),e.jsxs(ba,{onClick:()=>b.mutate({id:L.id,featured:!L.is_featured}),children:[e.jsx(Wa,{className:"h-4 w-4 mr-2"}),L.is_featured?"Unfeature":"Feature"]}),e.jsxs(ba,{className:"text-destructive",onClick:()=>{confirm("Are you sure you want to delete this listing?")&&k.mutate(L.id)},children:[e.jsx(hr,{className:"h-4 w-4 mr-2"}),"Delete"]})]})]})})]},L.id)})})]})})})]})]}),e.jsx(Bs,{open:!!i,onOpenChange:L=>!L&&l(null),children:e.jsxs(Fs,{className:"max-w-3xl max-h-[80vh] overflow-y-auto",children:[e.jsxs(qs,{children:[e.jsx($s,{children:"Leads from listing"}),e.jsx(Ar,{children:i==null?void 0:i.label})]}),g?e.jsxs("div",{className:"py-8 text-center text-muted-foreground",children:[e.jsx(us,{className:"h-5 w-5 animate-spin inline mr-2"}),"Loading leads..."]}):!f||f.length===0?e.jsx("div",{className:"py-8 text-center text-muted-foreground",children:"No leads yet."}):e.jsxs(Oa,{children:[e.jsx(Fa,{children:e.jsxs(un,{children:[e.jsx(Mt,{children:"Name"}),e.jsx(Mt,{children:"Email"}),e.jsx(Mt,{children:"Phone"}),e.jsx(Mt,{children:"Type"}),e.jsx(Mt,{children:"Captured"})]})}),e.jsx(za,{children:f.map(L=>{var z;return e.jsxs(un,{children:[e.jsx(gt,{className:"font-medium",children:[L.first_name,L.last_name].filter(Boolean).join(" ")||"—"}),e.jsx(gt,{children:L.email}),e.jsx(gt,{children:L.phone||"—"}),e.jsx(gt,{children:e.jsx(We,{variant:"outline",children:(z=L.lead_type)==null?void 0:z.replace("_"," ")})}),e.jsx(gt,{className:"text-sm text-muted-foreground",children:Js(new Date(L.created_at),"MMM d, yyyy h:mm a")})]},L.id)})})]})]})})]})}function t5n(s){return s?new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:0}).format(s):"—"}function s5n(){const[s,t]=N.useState(""),[n,r]=N.useState("all"),[a,i]=N.useState("all"),{data:l,isLoading:o}=mt({queryKey:["admin-all-listing-leads"],queryFn:async()=>{const h=[];let m=0;const f=1e3;for(;;){const{data:g,error:y}=await H.from("listing_leads").select(` id, listing_id, agent_id, referred_by_agent_id, first_name, last_name, email, phone, lead_type, showing_mode, preferred_date, preferred_time, message, created_at, listing:listings!listing_leads_listing_id_fkey(id, slug, property_address, city, state, price), agent:profiles!listing_leads_agent_id_fkey(id, name, email), referrer:profiles!listing_leads_referred_by_agent_id_fkey(id, name, email) `).order("created_at",{ascending:!1}).range(m,m+f-1);if(y)throw y;if(!g||g.length===0||(h.push(...g),g.length{if(!l)return[];const h=n==="all"?0:Date.now()-parseInt(n)*24*60*60*1e3,m=s.trim().toLowerCase();return l.filter(f=>{var y,x,_,b,k,A;return h&&new Date(f.created_at).getTime(){const h=c.length,m=c.filter(y=>y.lead_type==="showing_request").length,f=new Set(c.map(y=>y.agent_id)).size,g=new Set(c.map(y=>y.listing_id)).size;return{total:h,showings:m,uniqueAgents:f,uniqueListings:g}},[c]),u=()=>{const m=[["Date","Name","Email","Phone","Type","Showing Date","Property","City","Price","Assigned Agent","Agent Email","Referred By","Message"],...c.map(x=>{var _,b,k,A,T,P;return[Js(new Date(x.created_at),"yyyy-MM-dd HH:mm"),`${x.first_name||""} ${x.last_name||""}`.trim(),x.email,x.phone||"",x.lead_type,x.preferred_date?`${x.preferred_date} ${x.preferred_time||""}`:"",((_=x.listing)==null?void 0:_.property_address)||"",((b=x.listing)==null?void 0:b.city)||"",(k=x.listing)!=null&&k.price?String(x.listing.price):"",((A=x.agent)==null?void 0:A.name)||"",((T=x.agent)==null?void 0:T.email)||"",((P=x.referrer)==null?void 0:P.name)||"",(x.message||"").replace(/[\r\n]+/g," ")]})].map(x=>x.map(_=>`"${String(_).replace(/"/g,'""')}"`).join(",")).join(` `),f=new Blob([m],{type:"text/csv"}),g=URL.createObjectURL(f),y=document.createElement("a");y.href=g,y.download=`listing-leads-${Js(new Date,"yyyy-MM-dd")}.csv`,y.click(),URL.revokeObjectURL(g)};return e.jsx(Qs,{title:"Listing Leads",children:e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center justify-between gap-4",children:[e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl font-bold",children:"Listing Leads"}),e.jsx("p",{className:"text-muted-foreground",children:"All leads submitted through the public listings site"})]}),e.jsxs(B,{variant:"outline",onClick:u,disabled:!c.length,className:"gap-2",children:[e.jsx(oi,{className:"h-4 w-4"}),"Export CSV"]})]}),e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4",children:[e.jsx(_e,{children:e.jsxs(De,{className:"p-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Yl,{className:"h-4 w-4 text-teal-600"}),e.jsx("span",{className:"text-sm text-muted-foreground",children:"Total Leads"})]}),e.jsx("p",{className:"text-2xl font-bold mt-1",children:d.total})]})}),e.jsx(_e,{children:e.jsxs(De,{className:"p-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ta,{className:"h-4 w-4 text-purple-600"}),e.jsx("span",{className:"text-sm text-muted-foreground",children:"Showing Requests"})]}),e.jsx("p",{className:"text-2xl font-bold mt-1",children:d.showings})]})}),e.jsx(_e,{children:e.jsxs(De,{className:"p-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(_a,{className:"h-4 w-4 text-blue-600"}),e.jsx("span",{className:"text-sm text-muted-foreground",children:"Properties"})]}),e.jsx("p",{className:"text-2xl font-bold mt-1",children:d.uniqueListings})]})}),e.jsx(_e,{children:e.jsxs(De,{className:"p-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Yl,{className:"h-4 w-4 text-amber-600"}),e.jsx("span",{className:"text-sm text-muted-foreground",children:"Agents w/ Leads"})]}),e.jsx("p",{className:"text-2xl font-bold mt-1",children:d.uniqueAgents})]})})]}),e.jsx(_e,{children:e.jsx(De,{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(Gr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(we,{placeholder:"Search name, email, property, agent...",value:s,onChange:h=>t(h.target.value),className:"pl-9"})]}),e.jsxs(Ns,{value:a,onValueChange:h=>i(h),children:[e.jsx(ws,{className:"w-full sm:w-48",children:e.jsx(ks,{})}),e.jsxs(js,{children:[e.jsx(nt,{value:"all",children:"All Types"}),e.jsx(nt,{value:"info_request",children:"Info Request"}),e.jsx(nt,{value:"showing_request",children:"Showing Request"})]})]}),e.jsxs(Ns,{value:n,onValueChange:h=>r(h),children:[e.jsx(ws,{className:"w-full sm:w-40",children:e.jsx(ks,{})}),e.jsxs(js,{children:[e.jsx(nt,{value:"all",children:"All Time"}),e.jsx(nt,{value:"7",children:"Last 7 days"}),e.jsx(nt,{value:"30",children:"Last 30 days"}),e.jsx(nt,{value:"90",children:"Last 90 days"})]})]})]})})}),e.jsxs(_e,{children:[e.jsx(zt,{children:e.jsxs(qt,{children:["Leads (",c.length,")"]})}),e.jsx(De,{children:e.jsx("div",{className:"overflow-x-auto",children:e.jsxs(Oa,{children:[e.jsx(Fa,{children:e.jsxs(un,{children:[e.jsx(Mt,{children:"Date"}),e.jsx(Mt,{children:"Lead"}),e.jsx(Mt,{children:"Contact"}),e.jsx(Mt,{children:"Property"}),e.jsx(Mt,{children:"Type"}),e.jsx(Mt,{children:"Assigned To"}),e.jsx(Mt,{children:"Referred By"}),e.jsx(Mt,{children:"Message"})]})}),e.jsx(za,{children:o?e.jsx(un,{children:e.jsx(gt,{colSpan:8,className:"text-center py-8 text-muted-foreground",children:"Loading..."})}):c.length===0?e.jsx(un,{children:e.jsx(gt,{colSpan:8,className:"text-center py-8 text-muted-foreground",children:"No leads found"})}):c.map(h=>{var m,f;return e.jsxs(un,{children:[e.jsxs(gt,{className:"whitespace-nowrap text-sm",children:[Js(new Date(h.created_at),"MMM d, yyyy"),e.jsx("div",{className:"text-xs text-muted-foreground",children:Js(new Date(h.created_at),"h:mm a")})]}),e.jsx(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(mn,{className:"h-3 w-3"}),h.email]}),h.phone&&e.jsxs("a",{href:`tel:${h.phone}`,className:"flex items-center gap-1 text-muted-foreground hover:underline",children:[e.jsx(ga,{className:"h-3 w-3"}),h.phone]})]})}),e.jsx(gt,{children:h.listing?e.jsxs(cr,{to:`/public/listing/${h.listing.slug||h.listing.id}`,target:"_blank",className:"group",children:[e.jsxs("div",{className:"font-medium text-sm group-hover:underline flex items-center gap-1",children:[h.listing.property_address||"Untitled",e.jsx(Tr,{className:"h-3 w-3 opacity-60"})]}),e.jsxs("div",{className:"text-xs text-muted-foreground",children:[[h.listing.city,h.listing.state].filter(Boolean).join(", ")," · ",t5n(h.listing.price)]})]}):e.jsx("span",{className:"text-muted-foreground text-sm",children:"—"})}),e.jsxs(gt,{children:[e.jsx(We,{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)||"—"}),((f=h.agent)==null?void 0:f.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(xo,{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 OF={new_listing_alerts:{label:"New Listing Alerts",icon:yg,color:"bg-amber-100 text-amber-800"},exit_intent:{label:"Exit Intent",icon:xD,color:"bg-rose-100 text-rose-800"},saved_listing:{label:"Saved Home",icon:co,color:"bg-pink-100 text-pink-800"},saved_search:{label:"Saved Search",icon:Gr,color:"bg-blue-100 text-blue-800"},buyer_guide:{label:"Buyer's Guide",icon:Ep,color:"bg-emerald-100 text-emerald-800"}},Wft=[{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 Kft(s){return new Date(s).toLocaleString("en-US",{timeZone:"America/New_York",month:"short",day:"numeric",year:"numeric",hour:"numeric",minute:"2-digit"})}function n5n(){const[s,t]=N.useState([]),[n,r]=N.useState(!0),[a,i]=N.useState("30d"),[l,o]=N.useState("all"),[c,d]=N.useState("");N.useEffect(()=>{let f=!1;return(async()=>{r(!0);let g=H.from("public_site_leads").select("*").order("created_at",{ascending:!1}).limit(2e3);const y=Wft.find(b=>b.key===a);if(y&&y.days>0){const b=new Date(Date.now()-y.days*864e5).toISOString();g=g.gte("created_at",b)}const{data:x,error:_}=await g;f||(_?(console.error(_),t([])):t(x||[]),r(!1))})(),()=>{f=!0}},[a]);const u=N.useMemo(()=>s.filter(f=>{if(l!=="all"&&f.lead_type!==l)return!1;if(c){const g=c.toLowerCase();if(![f.email,f.first_name,f.last_name,f.phone,f.source_page,f.referrer].filter(Boolean).join(" ").toLowerCase().includes(g))return!1}return!0}),[s,l,c]),h=N.useMemo(()=>{const f=u.length,g=new Set(u.map(x=>x.email.toLowerCase())).size,y={};return u.forEach(x=>{y[x.lead_type]=(y[x.lead_type]||0)+1}),{total:f,uniqueEmails:g,byType:y}},[u]),m=()=>{const g=[["Date (ET)","Type","Email","First","Last","Phone","Listing ID","Source Page","Referrer","Criteria"].join(",")];u.forEach(b=>{var A;const k=[Kft(b.created_at),((A=OF[b.lead_type])==null?void 0:A.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(T=>`"${String(T).replace(/"/g,'""')}"`);g.push(k.join(","))});const y=new Blob([g.join(` `)],{type:"text/csv"}),x=URL.createObjectURL(y),_=document.createElement("a");_.href=x,_.download=`public-site-leads-${new Date().toISOString().slice(0,10)}.csv`,_.click(),URL.revokeObjectURL(x)};return e.jsxs("div",{className:"min-h-screen bg-slate-50",children:[e.jsx(ic,{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(cr,{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(oi,{className:"h-4 w-4 mr-1"})," Export CSV"]})]})}),e.jsxs("div",{className:"max-w-7xl mx-auto px-6 py-6 space-y-6",children:[e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-5 gap-3",children:[e.jsx(_e,{children:e.jsxs(De,{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(OF).map(f=>{const g=OF[f],y=g.icon;return e.jsx(_e,{children:e.jsxs(De,{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"}),g.label]}),e.jsx("div",{className:"text-2xl font-bold mt-1",children:h.byType[f]||0})]})},f)})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsxs(Ns,{value:a,onValueChange:f=>i(f),children:[e.jsx(ws,{className:"w-[160px] bg-white",children:e.jsx(ks,{})}),e.jsx(js,{children:Wft.map(f=>e.jsx(nt,{value:f.key,children:f.label},f.key))})]}),e.jsxs(Ns,{value:l,onValueChange:o,children:[e.jsx(ws,{className:"w-[200px] bg-white",children:e.jsx(ks,{})}),e.jsxs(js,{children:[e.jsx(nt,{value:"all",children:"All lead types"}),Object.keys(OF).map(f=>e.jsx(nt,{value:f,children:OF[f].label},f))]})]}),e.jsxs("div",{className:"relative flex-1 min-w-[200px] max-w-md",children:[e.jsx(Gr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-slate-400"}),e.jsx(we,{placeholder:"Search name, email, phone…",value:c,onChange:f=>d(f.target.value),className:"pl-9 bg-white"})]}),e.jsxs("div",{className:"ml-auto text-sm text-slate-500",children:[u.length," ",u.length===1?"lead":"leads"]})]}),e.jsx(_e,{children:e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("table",{className:"w-full text-sm",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"border-b bg-slate-50 text-left text-xs uppercase tracking-wide text-slate-500",children:[e.jsx("th",{className:"px-4 py-3",children:"Date"}),e.jsx("th",{className:"px-4 py-3",children:"Type"}),e.jsx("th",{className:"px-4 py-3",children:"Contact"}),e.jsx("th",{className:"px-4 py-3",children:"Phone"}),e.jsx("th",{className:"px-4 py-3",children:"Details"}),e.jsx("th",{className:"px-4 py-3",children:"Source"})]})}),e.jsx("tbody",{children:n?e.jsx("tr",{children:e.jsx("td",{colSpan:6,className:"px-4 py-12 text-center text-slate-500",children:"Loading…"})}):u.length===0?e.jsx("tr",{children:e.jsx("td",{colSpan:6,className:"px-4 py-12 text-center text-slate-500",children:"No leads yet in this range."})}):u.map(f=>{const g=OF[f.lead_type],y=g==null?void 0:g.icon,x=[f.first_name,f.last_name].filter(Boolean).join(" ")||"—";return e.jsxs("tr",{className:"border-b hover:bg-slate-50/60",children:[e.jsx("td",{className:"px-4 py-3 whitespace-nowrap text-slate-600 text-xs",children:Kft(f.created_at)}),e.jsx("td",{className:"px-4 py-3 whitespace-nowrap",children:e.jsxs(We,{className:`${(g==null?void 0:g.color)||""} font-normal`,variant:"secondary",children:[y?e.jsx(y,{className:"h-3 w-3 mr-1"}):null,(g==null?void 0:g.label)||f.lead_type]})}),e.jsxs("td",{className:"px-4 py-3",children:[e.jsx("div",{className:"font-medium text-slate-900",children:x}),e.jsxs("a",{href:`mailto:${f.email}`,className:"text-xs text-blue-600 hover:underline inline-flex items-center gap-1",children:[e.jsx(mn,{className:"h-3 w-3"}),f.email]})]}),e.jsx("td",{className:"px-4 py-3 whitespace-nowrap",children:f.phone?e.jsxs("a",{href:`tel:${f.phone}`,className:"text-xs text-blue-600 hover:underline inline-flex items-center gap-1",children:[e.jsx(ga,{className:"h-3 w-3"}),f.phone]}):e.jsx("span",{className:"text-slate-400 text-xs",children:"—"})}),e.jsxs("td",{className:"px-4 py-3 text-xs text-slate-600 max-w-xs",children:[f.listing_id&&e.jsxs("div",{className:"mb-0.5",children:["Listing: ",e.jsxs("span",{className:"font-mono text-[10px]",children:[f.listing_id.slice(0,8),"…"]})]}),f.criteria&&Object.keys(f.criteria).length>0&&e.jsx("div",{className:"text-slate-500 line-clamp-2",children:Object.entries(f.criteria).map(([_,b])=>`${_}: ${b}`).join(" · ")})]}),e.jsxs("td",{className:"px-4 py-3 text-xs text-slate-500 max-w-xs truncate",children:[f.source_page&&e.jsxs("div",{className:"inline-flex items-center gap-1",children:[e.jsx(Tr,{className:"h-3 w-3"}),e.jsx("span",{className:"truncate",children:f.source_page})]}),f.referrer&&e.jsxs("div",{className:"text-slate-400 truncate",children:["from ",f.referrer]})]})]},f.id)})})]})})})]})]})}const r5n=()=>{var h,m;const[s,t]=N.useState(""),[n,r]=N.useState(null),{data:a,isLoading:i}=mt({queryKey:["membership-reviews"],queryFn:async()=>{const{data:f,error:g}=await H.from("membership_reviews").select("*").order("created_at",{ascending:!1});if(g)throw g;const y=(f==null?void 0:f.map(b=>b.user_id))||[],{data:x}=await H.from("profiles").select("id, name, email").in("id",y);return f==null?void 0:f.map(b=>({...b,profiles:(x==null?void 0:x.find(k=>k.id===b.user_id))||null}))}}),l=a==null?void 0:a.filter(f=>{var y,x,_,b,k;const g=s.toLowerCase();return((x=(y=f.profiles)==null?void 0:y.name)==null?void 0:x.toLowerCase().includes(g))||((b=(_=f.profiles)==null?void 0:_.email)==null?void 0:b.toLowerCase().includes(g))||((k=f.review_text)==null?void 0:k.toLowerCase().includes(g))}),o=a!=null&&a.length?(a.reduce((f,g)=>f+g.rating,0)/a.length).toFixed(1):"0.0",c=a==null?void 0:a.reduce((f,g)=>(f[g.rating]=(f[g.rating]||0)+1,f),{}),d=(a==null?void 0:a.filter(f=>f.posted_to_google).length)||0,u=f=>e.jsx("div",{className:"flex gap-0.5",children:[1,2,3,4,5].map(g=>e.jsx(Wa,{className:Ot("h-4 w-4",f>=g?"fill-yellow-400 text-yellow-400":"text-muted-foreground")},g))});return e.jsx(Qs,{children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(Uh,{title:"Membership Reviews",description:"View and manage feedback from LevelUp members"}),e.jsxs("div",{className:"grid gap-4 md:grid-cols-4",children:[e.jsx(_e,{children:e.jsxs(zt,{className:"pb-2",children:[e.jsx(_r,{children:"Total Reviews"}),e.jsx(qt,{className:"text-3xl",children:(a==null?void 0:a.length)||0})]})}),e.jsx(_e,{children:e.jsxs(zt,{className:"pb-2",children:[e.jsx(_r,{children:"Average Rating"}),e.jsxs(qt,{className:"flex items-center gap-2 text-3xl",children:[o,e.jsx(Wa,{className:"h-6 w-6 fill-yellow-400 text-yellow-400"})]})]})}),e.jsx(_e,{children:e.jsxs(zt,{className:"pb-2",children:[e.jsx(_r,{children:"5-Star Reviews"}),e.jsx(qt,{className:"text-3xl",children:(c==null?void 0:c[5])||0})]})}),e.jsx(_e,{children:e.jsxs(zt,{className:"pb-2",children:[e.jsx(_r,{children:"Posted to Google"}),e.jsxs(qt,{className:"flex items-center gap-2 text-3xl",children:[d,e.jsx(Tr,{className:"h-5 w-5 text-muted-foreground"})]})]})})]}),e.jsxs("div",{className:"relative max-w-sm",children:[e.jsx(Gr,{className:"absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground"}),e.jsx(we,{placeholder:"Search by name, email, or review...",value:s,onChange:f=>t(f.target.value),className:"pl-9"})]}),e.jsx(_e,{children:e.jsx(De,{className:"p-0",children:e.jsxs(Oa,{children:[e.jsx(Fa,{children:e.jsxs(un,{children:[e.jsx(Mt,{children:"Member"}),e.jsx(Mt,{children:"Rating"}),e.jsx(Mt,{className:"hidden md:table-cell",children:"Review"}),e.jsx(Mt,{children:"Google"}),e.jsx(Mt,{children:"Date"})]})}),e.jsx(za,{children:i?e.jsx(un,{children:e.jsx(gt,{colSpan:5,className:"text-center py-8",children:"Loading reviews..."})}):(l==null?void 0:l.length)===0?e.jsx(un,{children:e.jsx(gt,{colSpan:5,className:"text-center py-8 text-muted-foreground",children:"No reviews found"})}):l==null?void 0:l.map(f=>{var g,y;return e.jsxs(un,{className:"cursor-pointer hover:bg-muted/50",onClick:()=>r(f),children:[e.jsx(gt,{children:e.jsxs("div",{children:[e.jsx("div",{className:"font-medium",children:((g=f.profiles)==null?void 0:g.name)||"Unknown"}),e.jsx("div",{className:"text-sm text-muted-foreground",children:(y=f.profiles)==null?void 0:y.email})]})}),e.jsx(gt,{children:u(f.rating)}),e.jsx(gt,{className:"hidden md:table-cell max-w-xs",children:e.jsx("p",{className:"truncate text-sm text-muted-foreground",children:f.review_text||"-"})}),e.jsx(gt,{children:f.posted_to_google?e.jsx(We,{variant:"secondary",className:"bg-green-100 text-green-800",children:"Posted"}):e.jsx(We,{variant:"outline",children:"No"})}),e.jsx(gt,{className:"text-sm text-muted-foreground",children:Js(new Date(f.created_at),"MMM d, yyyy")})]},f.id)})})]})})}),e.jsx(Bs,{open:!!n,onOpenChange:()=>r(null),children:e.jsxs(Fs,{className:"max-w-lg",children:[e.jsx(qs,{children:e.jsx($s,{children:"Review Details"})}),n&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-start gap-4 p-4 bg-muted/50 rounded-lg",children:[e.jsxs("div",{className:"flex-1",children:[e.jsx("h3",{className:"font-semibold text-lg",children:((h=n.profiles)==null?void 0:h.name)||"Unknown Member"}),((m=n.profiles)==null?void 0:m.email)&&e.jsxs("a",{href:`mailto:${n.profiles.email}`,className:"flex items-center gap-1 text-sm text-muted-foreground hover:text-primary",children:[e.jsx(mn,{className:"h-3 w-3"}),n.profiles.email]})]}),e.jsxs("div",{className:"text-right",children:[u(n.rating),e.jsxs("p",{className:"text-xs text-muted-foreground mt-1",children:[n.rating," out of 5 stars"]})]})]}),e.jsxs("div",{children:[e.jsx("h4",{className:"text-sm font-medium mb-2",children:"Review"}),e.jsx("p",{className:"text-sm text-muted-foreground whitespace-pre-wrap",children:n.review_text||"No written review provided."})]}),e.jsxs("div",{className:"flex items-center justify-between pt-4 border-t",children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[e.jsx(ta,{className:"h-4 w-4"}),Js(new Date(n.created_at),"MMMM d, yyyy 'at' h:mm a")]}),n.posted_to_google?e.jsxs(We,{variant:"secondary",className:"bg-green-100 text-green-800",children:[e.jsx(Tr,{className:"h-3 w-3 mr-1"}),"Posted to Google"]}):e.jsx(We,{variant:"outline",children:"Not posted to Google"})]})]})]})})]})})},Yft={agent_card:"Agent Card",listing:"Listing",lead_site:"Lead Site",guest_book:"Guest Book",landing_page:"Landing Page",connect_page:"Connect Page",booking:"Booking"},a5n={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 i5n(){const[s,t]=N.useState(""),[n,r]=N.useState("all"),[a,i]=N.useState("all"),[l,o]=N.useState("7"),{data:c,isLoading:d}=mt({queryKey:["lead-notification-log",l],queryFn:async()=>{const m=new Date(Date.now()-Number(l)*864e5).toISOString(),{data:f,error:g}=await H.from("lead_notification_log").select("*").gte("created_at",m).order("created_at",{ascending:!1}).limit(2e3);if(g)throw g;return f||[]}}),u=N.useMemo(()=>{const m=s.trim().toLowerCase();return(c||[]).filter(f=>n!=="all"&&f.source!==n||a!=="all"&&f.status!==a?!1:m?[f.agent_name,f.agent_email,f.lead_name,f.lead_email,f.lead_phone,f.subject].some(g=>(g||"").toLowerCase().includes(m)):!0)},[c,s,n,a]),h=N.useMemo(()=>{const m=u.length,f=u.filter(x=>x.status==="sent"||x.status==="backfilled").length,g=u.filter(x=>x.status==="failed").length,y=new Set(u.map(x=>x.agent_user_id).filter(Boolean)).size;return{total:m,sent:f,failed:g,agents:y}},[u]);return e.jsx(Qs,{children:e.jsxs("div",{className:"container mx-auto py-6 space-y-6",children:[e.jsx(Uh,{title:"Lead Notifications",description:"Every new-lead notification sent to agents — agent cards, listings, lead sites, guest book sign-ins, landing pages, connect pages, and bookings."}),e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4",children:[e.jsx(_e,{children:e.jsxs(De,{className:"p-4",children:[e.jsx("div",{className:"text-sm text-muted-foreground",children:"Total"}),e.jsx("div",{className:"text-2xl font-bold",children:h.total})]})}),e.jsx(_e,{children:e.jsxs(De,{className:"p-4",children:[e.jsx("div",{className:"text-sm text-muted-foreground",children:"Sent"}),e.jsx("div",{className:"text-2xl font-bold text-green-600",children:h.sent})]})}),e.jsx(_e,{children:e.jsxs(De,{className:"p-4",children:[e.jsx("div",{className:"text-sm text-muted-foreground",children:"Failed"}),e.jsx("div",{className:"text-2xl font-bold text-red-600",children:h.failed})]})}),e.jsx(_e,{children:e.jsxs(De,{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(Gr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(we,{placeholder:"Search agent or lead name, email, phone…",value:s,onChange:m=>t(m.target.value),className:"pl-9"})]}),e.jsxs(Ns,{value:n,onValueChange:r,children:[e.jsx(ws,{className:"w-full md:w-48",children:e.jsx(ks,{placeholder:"Source"})}),e.jsxs(js,{children:[e.jsx(nt,{value:"all",children:"All Sources"}),Object.entries(Yft).map(([m,f])=>e.jsx(nt,{value:m,children:f},m))]})]}),e.jsxs(Ns,{value:a,onValueChange:i,children:[e.jsx(ws,{className:"w-full md:w-40",children:e.jsx(ks,{placeholder:"Status"})}),e.jsxs(js,{children:[e.jsx(nt,{value:"all",children:"All Statuses"}),e.jsx(nt,{value:"sent",children:"Sent"}),e.jsx(nt,{value:"backfilled",children:"Backfilled"}),e.jsx(nt,{value:"failed",children:"Failed"})]})]}),e.jsxs(Ns,{value:l,onValueChange:o,children:[e.jsx(ws,{className:"w-full md:w-36",children:e.jsx(ks,{})}),e.jsxs(js,{children:[e.jsx(nt,{value:"1",children:"Last 24h"}),e.jsx(nt,{value:"7",children:"Last 7 days"}),e.jsx(nt,{value:"14",children:"Last 14 days"}),e.jsx(nt,{value:"30",children:"Last 30 days"})]})]})]}),e.jsx(_e,{children:e.jsx(De,{className:"p-0",children:e.jsxs(Oa,{children:[e.jsx(Fa,{children:e.jsxs(un,{children:[e.jsx(Mt,{children:"When"}),e.jsx(Mt,{children:"Source"}),e.jsx(Mt,{children:"Agent"}),e.jsx(Mt,{children:"Lead"}),e.jsx(Mt,{children:"Status"})]})}),e.jsx(za,{children:d?e.jsx(un,{children:e.jsx(gt,{colSpan:5,className:"text-center py-8 text-muted-foreground",children:"Loading…"})}):u.length===0?e.jsx(un,{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(un,{children:[e.jsx(gt,{className:"whitespace-nowrap text-sm",children:Js(new Date(m.created_at),"MMM d, yyyy h:mm a")}),e.jsx(gt,{children:e.jsx(We,{variant:"secondary",children:Yft[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(mn,{className:"h-3 w-3"}),m.lead_email]}),m.lead_phone&&e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(ga,{className:"h-3 w-3"}),m.lead_phone]})]})]}),e.jsxs(gt,{children:[e.jsx(We,{className:a5n[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 o5n=[{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"}],l5n=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 c5n(){const s=as(),{user:t}=Ls(),[n,r]=N.useState(!1),[a,i]=N.useState(!1),[l,o]=N.useState(!1),{data:c,isLoading:d}=mt({queryKey:["weekly-digest-settings"],queryFn:async()=>{const{data:M,error:L}=await H.from("weekly_digest_settings").select("*").single();if(L)throw L;return M}}),{data:u,isLoading:h}=mt({queryKey:["weekly-digest-logs"],queryFn:async()=>{const{data:M,error:L}=await H.from("weekly_digest_logs").select("*").order("sent_at",{ascending:!1}).limit(100);if(L)throw L;return M}}),{data:m}=mt({queryKey:["digest-subscriber-count"],queryFn:async()=>{const{count:M,error:L}=await H.from("profiles").select("id",{count:"exact",head:!0}).eq("digest_opt_out",!1).not("email","is",null);if(L)throw L;return M||0}}),{data:f,refetch:g}=mt({queryKey:["digest-queue-status"],queryFn:async()=>{const M=new Date;M.setUTCHours(0,0,0,0);const[L,z,$,V]=await Promise.all([H.from("weekly_digest_send_queue").select("id",{count:"exact",head:!0}).eq("status","pending").gte("created_at",M.toISOString()),H.from("weekly_digest_send_queue").select("id",{count:"exact",head:!0}).eq("status","processing").gte("created_at",M.toISOString()),H.from("weekly_digest_send_queue").select("id",{count:"exact",head:!0}).eq("status","sent").gte("created_at",M.toISOString()),H.from("weekly_digest_send_queue").select("id",{count:"exact",head:!0}).eq("status","failed").gte("created_at",M.toISOString())]);return{pending:L.count||0,processing:z.count||0,sent:$.count||0,failed:V.count||0,total:(L.count||0)+(z.count||0)+($.count||0)+(V.count||0)}},refetchInterval:5e3});N.useEffect(()=>{if(f&&(f.pending>0||f.processing>0)){const M=setInterval(()=>{g(),s.invalidateQueries({queryKey:["weekly-digest-logs"]}),s.invalidateQueries({queryKey:["digest-today-failed-count"]}),s.invalidateQueries({queryKey:["digest-today-missing-count"]})},5e3);return()=>clearInterval(M)}},[f,g,s]);const{data:y=0}=mt({queryKey:["digest-today-failed-count"],queryFn:async()=>{const M=new Date;M.setUTCHours(0,0,0,0);const{count:L,error:z}=await H.from("weekly_digest_logs").select("id",{count:"exact",head:!0}).eq("delivery_status","failed").gte("sent_at",M.toISOString());if(z)throw z;return L||0}}),x=_t({mutationFn:async M=>{const{error:L}=await H.from("weekly_digest_settings").update(M).eq("id",c==null?void 0:c.id);if(L)throw L},onSuccess:()=>{s.invalidateQueries({queryKey:["weekly-digest-settings"]}),ie.success("Settings updated")},onError:M=>{ie.error("Failed to update settings: "+M.message)}}),_=async()=>{r(!0);try{const{data:M,error:L}=await H.functions.invoke("send-weekly-digest",{body:{manual:!0}});if(L)throw L;M.queued?ie.success(`${M.queued.toLocaleString()} emails queued! They'll be sent automatically (~80/minute).`):M.sent!==void 0&&ie.success(`Digest sent! ${M.sent} emails delivered, ${M.failed} failed`),g(),s.invalidateQueries({queryKey:["weekly-digest-logs"]})}catch(M){ie.error("Failed to send digest: "+M.message)}finally{r(!1)}},b=async()=>{var M,L,z,$,V,W;if(!(t!=null&&t.email)){ie.error("No email found for your account");return}i(!0);try{const{data:G,error:X}=await H.functions.invoke("send-weekly-digest",{body:{preview:!0,previewEmail:t.email}});if(X)throw X;const te=G==null?void 0:G.resendId,ne=G==null?void 0:G.resendDetails,me=ne==null?void 0:ne.status,ue=((M=ne==null?void 0:ne.body)==null?void 0:M.status)||((z=(L=ne==null?void 0:ne.body)==null?void 0:L.data)==null?void 0:z.status),ce=((V=($=ne==null?void 0:ne.body)==null?void 0:$.error)==null?void 0:V.message)||((W=ne==null?void 0:ne.body)==null?void 0:W.message);ie.success(te?`Preview accepted by email provider (id: ${te})${me?`, status check: ${me}`:""}${ue?`, provider: ${ue}`:""}${ce?` (${ce})`:""}. Check spam/promotions—delivery can take a few minutes.`:"Preview accepted by email provider. Check spam/promotions—delivery can take a few minutes.")}catch(G){ie.error("Failed to send preview: "+G.message)}finally{i(!1)}},k=async()=>{o(!0);try{const{data:M,error:L}=await H.functions.invoke("send-weekly-digest",{body:{retryFailed:!0}});if(L)throw L;M.queued===0||M.sent===0&&M.failed===0&&!M.queued?ie.info("No failed emails to retry"):M.queued?ie.success(`${M.queued} emails queued for retry!`):ie.success(`Retry complete! ${M.sent} emails delivered, ${M.failed} failed`),g(),s.invalidateQueries({queryKey:["weekly-digest-logs"]}),s.invalidateQueries({queryKey:["digest-today-failed-count"]}),s.invalidateQueries({queryKey:["digest-today-missing-count"]})}catch(M){ie.error("Failed to retry: "+M.message)}finally{o(!1)}},A=f!=null&&f.total?Math.round((f.sent+f.failed)/f.total*100):0,T=((f==null?void 0:f.pending)||0)>0||((f==null?void 0:f.processing)||0)>0,{data:P}=mt({queryKey:["digest-delivery-stats"],queryFn:async()=>{var W,G;const M=new Date;M.setUTCHours(0,0,0,0);const[L,z,$,V]=await Promise.all([H.from("weekly_digest_logs").select("id",{count:"exact",head:!0}).eq("delivery_status","sent").gte("sent_at",M.toISOString()),H.from("weekly_digest_logs").select("id",{count:"exact",head:!0}).eq("delivery_status","failed").gte("sent_at",M.toISOString()),H.from("weekly_digest_logs").select("id",{count:"exact",head:!0}).eq("has_agent_os_activity",!0).gte("sent_at",M.toISOString()),H.from("weekly_digest_logs").select("sent_at").order("sent_at",{ascending:!1}).limit(1)]);return{totalSent:L.count||0,totalFailed:z.count||0,agentOsEngaged:$.count||0,lastSent:((G=(W=V.data)==null?void 0:W[0])==null?void 0:G.sent_at)||null}},refetchInterval:T?5e3:!1}),I={totalSent:(P==null?void 0:P.totalSent)||0,totalFailed:(P==null?void 0:P.totalFailed)||0,lastSent:P==null?void 0:P.lastSent,agentOsEngaged:(P==null?void 0:P.agentOsEngaged)||0};return d?e.jsx(Qs,{title:"Weekly Digest",description:"Manage automated weekly email digests",children:e.jsxs("div",{className:"animate-pulse space-y-4",children:[e.jsx("div",{className:"h-32 bg-muted rounded-lg"}),e.jsx("div",{className:"h-64 bg-muted rounded-lg"})]})}):e.jsx(Qs,{title:"Weekly Digest",description:"Configure and manage automated weekly email digests for members",children:e.jsxs(ya,{defaultValue:"settings",className:"space-y-6",children:[e.jsxs(va,{children:[e.jsxs(ls,{value:"settings",className:"flex items-center gap-2",children:[e.jsx(sc,{className:"h-4 w-4"}),"Settings"]}),e.jsxs(ls,{value:"stats",className:"flex items-center gap-2",children:[e.jsx(fl,{className:"h-4 w-4"}),"Delivery Stats"]})]}),e.jsxs(_s,{value:"settings",className:"space-y-6",children:[T&&f&&e.jsx(_e,{className:"border-primary/50 bg-primary/5",children:e.jsxs(De,{className:"pt-6",children:[e.jsxs("div",{className:"flex items-center gap-4 mb-4",children:[e.jsx(us,{className:"h-5 w-5 animate-spin text-primary"}),e.jsxs("div",{className:"flex-1",children:[e.jsx("p",{className:"font-medium",children:"Sending emails..."}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:[f.sent.toLocaleString()," sent, ",f.pending.toLocaleString()," pending",f.failed>0&&`, ${f.failed} failed`]})]}),e.jsxs("span",{className:"text-sm font-medium",children:[A,"%"]})]}),e.jsx(ro,{value:A,className:"h-2"}),e.jsxs("p",{className:"text-xs text-muted-foreground mt-2",children:["Processing ~80 emails per minute. Estimated time remaining: ~",Math.ceil(f.pending/80)," min"]})]})}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-4 gap-4",children:[e.jsx(_e,{children:e.jsx(De,{className:"pt-6",children:e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsx("div",{className:"p-3 rounded-full bg-primary/10",children:e.jsx(Yn,{className:"h-5 w-5 text-primary"})}),e.jsxs("div",{children:[e.jsx("p",{className:"text-2xl font-bold",children:m}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Subscribers"})]})]})})}),e.jsx(_e,{children:e.jsx(De,{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(Hr,{className:"h-5 w-5 text-emerald-500"})}),e.jsxs("div",{children:[e.jsx("p",{className:"text-2xl font-bold",children:I.totalSent}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Delivered"})]})]})})}),e.jsx(_e,{children:e.jsx(De,{className:"pt-6",children:e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsx("div",{className:"p-3 rounded-full bg-destructive/10",children:e.jsx(Nu,{className:"h-5 w-5 text-destructive"})}),e.jsxs("div",{children:[e.jsx("p",{className:"text-2xl font-bold",children:I.totalFailed}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Failed"})]})]})})}),e.jsx(_e,{children:e.jsx(De,{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(Xr,{className:"h-5 w-5 text-primary"})}),e.jsxs("div",{children:[e.jsx("p",{className:"text-2xl font-bold",children:I.lastSent?Js(new Date(I.lastSent),"MMM d"):"Never"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Last Sent"})]})]})})})]}),e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-6",children:[e.jsxs(_e,{children:[e.jsxs(zt,{children:[e.jsxs(qt,{className:"flex items-center gap-2",children:[e.jsx(Xr,{className:"h-5 w-5"}),"Schedule"]}),e.jsx(_r,{children:"Configure when the digest is sent"})]}),e.jsxs(De,{className:"space-y-6",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(re,{children:"Enable Weekly Digest"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Send automated weekly emails to members"})]}),e.jsx(zn,{checked:c==null?void 0:c.is_enabled,onCheckedChange:M=>x.mutate({is_enabled:M})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{children:"Cron Frequency"}),e.jsxs(Ns,{value:(c==null?void 0:c.cron_frequency)||"daily",onValueChange:M=>x.mutate({cron_frequency:M}),children:[e.jsx(ws,{children:e.jsx(ks,{})}),e.jsxs(js,{children:[e.jsx(nt,{value:"daily",children:"Daily (runs once at selected time)"}),e.jsx(nt,{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(re,{children:"Day of Week"}),e.jsxs(Ns,{value:String(c==null?void 0:c.send_day),onValueChange:M=>x.mutate({send_day:parseInt(M)}),children:[e.jsx(ws,{children:e.jsx(ks,{})}),e.jsx(js,{children:o5n.map(M=>e.jsx(nt,{value:M.value,children:M.label},M.value))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{children:"Time (UTC)"}),e.jsxs(Ns,{value:String(c==null?void 0:c.send_hour),onValueChange:M=>x.mutate({send_hour:parseInt(M)}),disabled:(c==null?void 0:c.cron_frequency)==="daily",children:[e.jsx(ws,{children:e.jsx(ks,{})}),e.jsx(js,{children:l5n.map(M=>e.jsx(nt,{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(da,{className:"h-4 w-4 mr-2"}),a?"Sending...":"Send Preview to Me"]}),e.jsxs(B,{onClick:_,disabled:n,className:"flex-1",children:[e.jsx(Rr,{className:"h-4 w-4 mr-2"}),n?"Sending...":"Send to All"]})]}),y>0&&e.jsxs(B,{onClick:k,disabled:l,variant:"outline",className:"w-full",children:[e.jsx(oo,{className:`h-4 w-4 mr-2 ${l?"animate-spin":""}`}),l?"Retrying...":`Retry ${y} Failed`]})]})]})]}),e.jsxs(_e,{children:[e.jsxs(zt,{children:[e.jsxs(qt,{className:"flex items-center gap-2",children:[e.jsx(Wr,{className:"h-5 w-5"}),"Content Sections"]}),e.jsx(_r,{children:"Choose what to include in the digest"})]}),e.jsxs(De,{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Wr,{className:"h-4 w-4 text-muted-foreground"}),e.jsx(re,{children:"New Resources"})]}),e.jsx(zn,{checked:c==null?void 0:c.include_new_resources,onCheckedChange:M=>x.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(Yn,{className:"h-4 w-4 text-muted-foreground"}),e.jsx(re,{children:"Community Highlights"})]}),e.jsx(zn,{checked:c==null?void 0:c.include_community_posts,onCheckedChange:M=>x.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(fl,{className:"h-4 w-4 text-muted-foreground"}),e.jsx(re,{children:"Agent OS Stats"})]}),e.jsx(zn,{checked:c==null?void 0:c.include_agent_os_stats,onCheckedChange:M=>x.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(ta,{className:"h-4 w-4 text-muted-foreground"}),e.jsx(re,{children:"Upcoming Events"})]}),e.jsx(zn,{checked:c==null?void 0:c.include_upcoming_events,onCheckedChange:M=>x.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(iu,{className:"h-4 w-4 text-muted-foreground"}),e.jsx(re,{children:"Goals Progress"})]}),e.jsx(zn,{checked:c==null?void 0:c.include_goals_progress,onCheckedChange:M=>x.mutate({include_goals_progress:M})})]})]})]})]}),e.jsxs(_e,{children:[e.jsxs(zt,{children:[e.jsx(qt,{children:"Custom Introduction"}),e.jsx(_r,{children:"Personalize the intro message (optional)"})]}),e.jsx(De,{children:e.jsx(Ws,{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=>x.mutate({custom_intro_text:M.target.value||null}),rows:3})})]})]}),e.jsx(_s,{value:"stats",children:e.jsxs(_e,{children:[e.jsxs(zt,{children:[e.jsxs(qt,{className:"flex items-center gap-2",children:[e.jsx(mn,{className:"h-5 w-5"}),"Delivery History"]}),e.jsx(_r,{children:"Recent digest emails sent to members"})]}),e.jsx(De,{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(Oa,{children:[e.jsx(Fa,{children:e.jsxs(un,{children:[e.jsx(Mt,{children:"Email"}),e.jsx(Mt,{children:"Sent At"}),e.jsx(Mt,{children:"Status"}),e.jsx(Mt,{children:"Resources"}),e.jsx(Mt,{children:"Agent OS"})]})}),e.jsx(za,{children:u.map(M=>e.jsxs(un,{children:[e.jsx(gt,{className:"font-medium",children:M.email_sent_to}),e.jsx(gt,{children:Js(new Date(M.sent_at),"MMM d, yyyy h:mm a")}),e.jsx(gt,{children:e.jsx(We,{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(We,{variant:"secondary",children:"Active"}):e.jsx(We,{variant:"outline",children:"Not Started"})})]},M.id))})]}):e.jsxs("div",{className:"text-center py-8 text-muted-foreground",children:[e.jsx(mn,{className:"h-12 w-12 mx-auto mb-4 opacity-50"}),e.jsx("p",{children:"No digests sent yet"}),e.jsx("p",{className:"text-sm",children:"Send your first digest to see delivery stats"})]})})]})})]})})}const d5n={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 u5n(){var he,xe,ve;const s=as(),[t,n]=N.useState(""),[r,a]=N.useState(null),[i,l]=N.useState(!1),[o,c]=N.useState(!1),[d,u]=N.useState(""),[h,m]=N.useState(""),[f,g]=N.useState(!0),[y,x]=N.useState(!1),[_,b]=N.useState(""),[k,A]=N.useState(null),{data:T,isLoading:P}=mt({queryKey:["admin-agent-points"],queryFn:async()=>{const{data:ge,error:be}=await H.from("agent_attendance_stats").select("*").order("total_points",{ascending:!1});if(be)throw be;const Se=(ge==null?void 0:ge.map(Re=>Re.user_id))||[],{data:Ie}=await H.from("profiles").select("id, name, email").in("id",Se),Me=new Map((Ie==null?void 0:Ie.map(Re=>[Re.id,{name:Re.name,email:Re.email}]))||[]);return ge==null?void 0:ge.map(Re=>({...Re,profile:Me.get(Re.user_id)||null}))}}),{data:I}=mt({queryKey:["all-profiles-for-points",T],queryFn:async()=>{const be=[];let Se=0;for(;;){const{data:Ie,error:Me}=await H.from("profiles").select("id, name, email").order("name").range(Se,Se+1e3-1);if(Me)throw Me;if(be.push(...Ie),!Ie||Ie.length<1e3)break;Se+=1e3}return be}}),L=((I==null?void 0:I.filter(ge=>!(T!=null&&T.some(be=>be.user_id===ge.id))))||[]).filter(ge=>{var Se,Ie;if(!_)return!0;const be=_.toLowerCase();return((Se=ge.name)==null?void 0:Se.toLowerCase().includes(be))||((Ie=ge.email)==null?void 0:Ie.toLowerCase().includes(be))}),{data:z,isLoading:$}=mt({queryKey:["agent-point-history",r==null?void 0:r.user_id],queryFn:async()=>{if(!(r!=null&&r.user_id))return[];const{data:ge,error:be}=await H.from("agent_points").select("*").eq("user_id",r.user_id).order("created_at",{ascending:!1});if(be)throw be;return ge},enabled:!!(r!=null&&r.user_id)&&o}),{data:V}=mt({queryKey:["agent-badges",r==null?void 0:r.user_id],queryFn:async()=>{if(!(r!=null&&r.user_id))return[];const{data:ge,error:be}=await H.from("agent_badges").select("*").eq("user_id",r.user_id).order("earned_at",{ascending:!1});if(be)throw be;return ge},enabled:!!(r!=null&&r.user_id)}),W=_t({mutationFn:async({userId:ge,points:be,reason:Se})=>{const{error:Ie}=await H.from("agent_points").insert({user_id:ge,points:be,reason:Se});if(Ie)throw Ie;const{data:Me}=await H.from("agent_attendance_stats").select("total_points, spendable_points").eq("user_id",ge).maybeSingle(),Re=((Me==null?void 0:Me.total_points)||0)+be,Be=((Me==null?void 0:Me.spendable_points)||0)+be,{error:Ne}=await H.from("agent_attendance_stats").upsert({user_id:ge,total_points:Math.max(0,Re),spendable_points:Math.max(0,Be),updated_at:new Date().toISOString()},{onConflict:"user_id"});if(Ne)throw Ne},onSuccess:()=>{s.invalidateQueries({queryKey:["admin-agent-points"]}),s.invalidateQueries({queryKey:["agent-point-history"]}),l(!1),u(""),m(""),ie.success(f?"Points awarded successfully!":"Points deducted successfully!")},onError:ge=>{console.error("Error modifying points:",ge),ie.error("Failed to modify points")}}),G=()=>{if(!r||!d||!h){ie.error("Please fill in all fields");return}const ge=parseInt(d);if(isNaN(ge)||ge<=0){ie.error("Please enter a valid positive number");return}W.mutate({userId:r.user_id,points:f?ge:-ge,reason:h})},X=()=>{if(!k||!d||!h){ie.error("Please fill in all fields");return}const ge=parseInt(d);if(isNaN(ge)||ge<=0){ie.error("Please enter a valid positive number");return}W.mutate({userId:k.id,points:ge,reason:h},{onSuccess:()=>{x(!1),A(null),b("")}})},te=(ge,be)=>{a(ge),g(be),l(!0)},ne=ge=>{a(ge),c(!0)},me=T==null?void 0:T.filter(ge=>{var Me,Re,Be,Ne;const be=((Re=(Me=ge.profile)==null?void 0:Me.name)==null?void 0:Re.toLowerCase())||"",Se=((Ne=(Be=ge.profile)==null?void 0:Be.email)==null?void 0:Ne.toLowerCase())||"",Ie=t.toLowerCase();return be.includes(Ie)||Se.includes(Ie)}),ue=(T==null?void 0:T.reduce((ge,be)=>ge+be.total_points,0))||0,ce=(T==null?void 0:T.length)||0,ae=ce>0?Math.round(ue/ce):0;return P?e.jsx(Qs,{title:"Agent Points",children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(xn,{className:"h-8 w-64"}),e.jsx("div",{className:"grid grid-cols-3 gap-4",children:[1,2,3].map(ge=>e.jsx(xn,{className:"h-24"},ge))}),e.jsx(xn,{className:"h-96"})]})}):e.jsx(Qs,{title:"Agent Points",children:e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl font-bold text-foreground",children:"Agent Points Management"}),e.jsx("p",{className:"text-muted-foreground",children:"Track, view, and manage agent gamification points"})]}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-4",children:[e.jsx(_e,{children:e.jsxs(De,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[e.jsx(Yn,{className:"h-4 w-4"}),e.jsx("span",{className:"text-xs font-medium",children:"Total Agents"})]}),e.jsx("p",{className:"text-2xl font-bold",children:ce}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"with points tracked"})]})}),e.jsx(_e,{children:e.jsxs(De,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[e.jsx(gl,{className:"h-4 w-4"}),e.jsx("span",{className:"text-xs font-medium",children:"Total Points"})]}),e.jsx("p",{className:"text-2xl font-bold",children:ue.toLocaleString()}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"awarded across all agents"})]})}),e.jsx(_e,{children:e.jsxs(De,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[e.jsx(ml,{className:"h-4 w-4"}),e.jsx("span",{className:"text-xs font-medium",children:"Average Points"})]}),e.jsx("p",{className:"text-2xl font-bold",children:ae}),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(Gr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(we,{placeholder:"Search agents...",value:t,onChange:ge=>n(ge.target.value),className:"pl-10"})]}),e.jsxs(B,{onClick:()=>x(!0),children:[e.jsx(nn,{className:"h-4 w-4 mr-2"}),"Award Points to New Agent"]})]}),e.jsxs(_e,{children:[e.jsxs(zt,{children:[e.jsx(qt,{children:"Agent Leaderboard"}),e.jsx(_r,{children:"All agents with their points, events, and streaks"})]}),e.jsx(De,{children:!me||me.length===0?e.jsxs("div",{className:"text-center py-8 text-muted-foreground",children:[e.jsx(gl,{className:"h-12 w-12 mx-auto mb-4 opacity-50"}),e.jsx("p",{children:"No agents with points yet"})]}):e.jsxs(Oa,{children:[e.jsx(Fa,{children:e.jsxs(un,{children:[e.jsx(Mt,{className:"w-12",children:"#"}),e.jsx(Mt,{children:"Agent"}),e.jsx(Mt,{className:"text-center",children:"Total Points"}),e.jsx(Mt,{className:"text-center",children:"Spendable"}),e.jsx(Mt,{className:"text-center",children:"Events"}),e.jsx(Mt,{className:"text-center",children:"Streak"}),e.jsx(Mt,{className:"text-right",children:"Actions"})]})}),e.jsx(za,{children:me.map((ge,be)=>{var Se,Ie,Me,Re;return e.jsxs(un,{children:[e.jsx(gt,{className:"font-medium",children:be<3?e.jsx("div",{className:`w-6 h-6 rounded-full flex items-center justify-center ${be===0?"bg-yellow-100 text-yellow-700":be===1?"bg-gray-100 text-gray-600":"bg-amber-100 text-amber-700"}`,children:be+1}):e.jsx("span",{className:"text-muted-foreground",children:be+1})}),e.jsx(gt,{children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(Ua,{className:"h-8 w-8",children:e.jsx(qa,{children:((Ie=(Se=ge.profile)==null?void 0:Se.name)==null?void 0:Ie.charAt(0))||"?"})}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:((Me=ge.profile)==null?void 0:Me.name)||"Unknown"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:(Re=ge.profile)==null?void 0:Re.email})]})]})}),e.jsx(gt,{className:"text-center",children:e.jsxs(We,{variant:"secondary",className:"font-bold",children:[e.jsx(Wa,{className:"h-3 w-3 mr-1"}),ge.total_points]})}),e.jsx(gt,{className:"text-center",children:e.jsxs(We,{variant:"outline",className:"font-bold text-primary",children:[e.jsx(Io,{className:"h-3 w-3 mr-1"}),ge.spendable_points||0]})}),e.jsx(gt,{className:"text-center",children:e.jsxs("div",{className:"flex items-center justify-center gap-1",children:[e.jsx(ta,{className:"h-3 w-3 text-muted-foreground"}),ge.total_events_attended]})}),e.jsx(gt,{className:"text-center",children:e.jsxs("div",{className:"flex items-center justify-center gap-1",children:[e.jsx(Cu,{className:"h-3 w-3 text-orange-500"}),ge.current_streak]})}),e.jsx(gt,{className:"text-right",children:e.jsxs("div",{className:"flex items-center justify-end gap-1",children:[e.jsx(B,{variant:"ghost",size:"sm",onClick:()=>te(ge,!0),title:"Award points",children:e.jsx(nn,{className:"h-4 w-4 text-green-600"})}),e.jsx(B,{variant:"ghost",size:"sm",onClick:()=>te(ge,!1),title:"Deduct points",children:e.jsx(X2,{className:"h-4 w-4 text-red-600"})}),e.jsx(B,{variant:"ghost",size:"sm",onClick:()=>ne(ge),title:"View history",children:e.jsx(fD,{className:"h-4 w-4"})})]})})]},ge.user_id)})})]})})]}),e.jsx(Bs,{open:i,onOpenChange:l,children:e.jsxs(Fs,{children:[e.jsxs(qs,{children:[e.jsx($s,{children:f?"Award Points":"Deduct Points"}),e.jsxs(Ar,{children:[f?"Award":"Deduct"," points ",f?"to":"from"," ",((he=r==null?void 0:r.profile)==null?void 0:he.name)||"this agent"]})]}),e.jsxs("div",{className:"space-y-4 py-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{htmlFor:"points",children:"Points Amount"}),e.jsx(we,{id:"points",type:"number",min:"1",placeholder:"Enter points...",value:d,onChange:ge=>u(ge.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{htmlFor:"reason",children:"Reason"}),e.jsx(Ws,{id:"reason",placeholder:"Enter reason for this adjustment...",value:h,onChange:ge=>m(ge.target.value)})]})]}),e.jsxs(Cr,{children:[e.jsx(B,{variant:"outline",onClick:()=>l(!1),children:"Cancel"}),e.jsx(B,{onClick:G,disabled:W.isPending,className:f?"bg-green-600 hover:bg-green-700":"bg-red-600 hover:bg-red-700",children:W.isPending?"Saving...":f?"Award Points":"Deduct Points"})]})]})}),e.jsx(Bs,{open:o,onOpenChange:c,children:e.jsxs(Fs,{className:"max-w-2xl",children:[e.jsxs(qs,{children:[e.jsxs($s,{children:["Point History: ",(xe=r==null?void 0:r.profile)==null?void 0:xe.name]}),e.jsx(Ar,{children:"View all point transactions and badges for this agent"})]}),e.jsxs(ya,{defaultValue:"history",className:"w-full",children:[e.jsxs(va,{className:"grid w-full grid-cols-2",children:[e.jsx(ls,{value:"history",children:"Point History"}),e.jsx(ls,{value:"badges",children:"Badges"})]}),e.jsx(_s,{value:"history",className:"mt-4",children:$?e.jsx("div",{className:"space-y-2",children:[1,2,3].map(ge=>e.jsx(xn,{className:"h-12"},ge))}):!z||z.length===0?e.jsxs("div",{className:"text-center py-8 text-muted-foreground",children:[e.jsx(fD,{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:z.map(ge=>e.jsxs("div",{className:"flex items-center justify-between p-3 border rounded-lg",children:[e.jsxs("div",{className:"flex-1",children:[e.jsx("p",{className:"font-medium",children:ge.reason}),e.jsx("p",{className:"text-xs text-muted-foreground",children:Js(new Date(ge.created_at),"MMM d, yyyy h:mm a")})]}),e.jsxs(We,{variant:ge.points>=0?"default":"destructive",className:ge.points>=0?"bg-green-100 text-green-800":"",children:[ge.points>=0?"+":"",ge.points]})]},ge.id))})}),e.jsx(_s,{value:"badges",className:"mt-4",children:!V||V.length===0?e.jsxs("div",{className:"text-center py-8 text-muted-foreground",children:[e.jsx(ku,{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(ge=>e.jsxs("div",{className:`p-3 rounded-lg ${d5n[ge.badge_type]||"bg-gray-100"}`,children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ku,{className:"h-5 w-5"}),e.jsx("span",{className:"font-medium",children:ge.badge_name})]}),ge.badge_description&&e.jsx("p",{className:"text-xs mt-1 opacity-80",children:ge.badge_description}),e.jsxs("p",{className:"text-xs mt-1 opacity-60",children:["Earned ",Js(new Date(ge.earned_at),"MMM d, yyyy")]})]},ge.id))})})]})]})}),e.jsx(Bs,{open:y,onOpenChange:ge=>{x(ge),ge||(A(null),b(""),u(""),m(""))},children:e.jsxs(Fs,{className:"max-w-md",children:[e.jsxs(qs,{children:[e.jsx($s,{children:"Award Points to New Agent"}),e.jsx(Ar,{children:"Select an agent who doesn't have points yet and award them points"})]}),e.jsx("div",{className:"space-y-4 py-4",children:k?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex items-center gap-3 p-3 bg-muted/50 rounded-lg",children:[e.jsx(Ua,{className:"h-10 w-10",children:e.jsx(qa,{children:((ve=k.name)==null?void 0:ve.charAt(0))||"?"})}),e.jsxs("div",{className:"flex-1",children:[e.jsx("p",{className:"font-medium",children:k.name||"Unknown"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:k.email})]}),e.jsx(B,{variant:"ghost",size:"sm",onClick:()=>A(null),children:"Change"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{htmlFor:"new-points",children:"Points Amount"}),e.jsx(we,{id:"new-points",type:"number",min:"1",placeholder:"Enter points...",value:d,onChange:ge=>u(ge.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{htmlFor:"new-reason",children:"Reason"}),e.jsx(Ws,{id:"new-reason",placeholder:"Enter reason for awarding points...",value:h,onChange:ge=>m(ge.target.value)})]})]}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{children:"Search Agent"}),e.jsxs("div",{className:"relative",children:[e.jsx(Gr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(we,{placeholder:"Search by name or email...",value:_,onChange:ge=>b(ge.target.value),className:"pl-10"})]})]}),e.jsx("div",{className:"max-h-60 overflow-y-auto border rounded-lg",children:L.length===0?e.jsxs("div",{className:"text-center py-4 text-muted-foreground",children:[e.jsx(Yn,{className:"h-6 w-6 mx-auto mb-2 opacity-50"}),e.jsx("p",{className:"text-sm",children:_?"No matching agents found":"All agents already have points"})]}):L.slice(0,20).map(ge=>{var be;return e.jsxs("button",{onClick:()=>A(ge),className:"w-full flex items-center gap-3 p-3 hover:bg-muted/50 transition-colors border-b last:border-b-0 text-left",children:[e.jsx(Ua,{className:"h-8 w-8",children:e.jsx(qa,{children:((be=ge.name)==null?void 0:be.charAt(0))||"?"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"font-medium truncate",children:ge.name||"Unknown"}),e.jsx("p",{className:"text-xs text-muted-foreground truncate",children:ge.email})]})]},ge.id)})})]})}),e.jsxs(Cr,{children:[e.jsx(B,{variant:"outline",onClick:()=>x(!1),children:"Cancel"}),k&&e.jsxs(B,{onClick:X,disabled:W.isPending,className:"bg-green-600 hover:bg-green-700",children:[e.jsx(nn,{className:"h-4 w-4 mr-2"}),"Award Points"]})]})]})})]})})}function h5n(){const{data:s,isLoading:t}=Iis(),[n,r]=N.useState(null),[a,i]=N.useState(!1),[l,o]=N.useState(""),[c,d]=N.useState("all"),[u,h]=N.useState("newest"),[m,f]=N.useState("table"),g=N.useMemo(()=>(s==null?void 0:s.map(k=>k.user_id))||[],[s]),y=N.useMemo(()=>(s==null?void 0:s.map(k=>k.id))||[],[s]),{data:x}=mt({queryKey:["card-profiles-lookup",g],queryFn:async()=>{if(g.length===0)return{};const{data:k}=await H.from("profiles").select("id, name, email").in("id",g),A={};return k==null||k.forEach(T=>{A[T.id]={name:T.name||"",email:T.email||""}}),A},enabled:g.length>0}),{data:_}=mt({queryKey:["card-stats-all",y],queryFn:async()=>{if(y.length===0)return{};const k={};y.forEach(P=>{k[P]={views:0,leads:0}});const{data:A}=await H.from("agent_card_interactions").select("card_id").in("card_id",y).eq("interaction_type","card_view");A==null||A.forEach(P=>{k[P.card_id]&&k[P.card_id].views++});const{data:T}=await H.from("agent_card_leads").select("card_id").in("card_id",y);return T==null||T.forEach(P=>{k[P.card_id]&&k[P.card_id].leads++}),k},enabled:y.length>0}),b=N.useMemo(()=>{if(!s)return[];let k=[...s];if(c==="live"?k=k.filter(A=>A.is_published):c==="draft"&&(k=k.filter(A=>!A.is_published)),l.trim()){const A=l.toLowerCase();k=k.filter(T=>{var I,M;const P=x==null?void 0:x[T.user_id];return T.slug.toLowerCase().includes(A)||((I=P==null?void 0:P.name)==null?void 0:I.toLowerCase().includes(A))||((M=P==null?void 0:P.email)==null?void 0:M.toLowerCase().includes(A))})}return u==="newest"?k.sort((A,T)=>new Date(T.created_at).getTime()-new Date(A.created_at).getTime()):u==="oldest"?k.sort((A,T)=>new Date(A.created_at).getTime()-new Date(T.created_at).getTime()):u==="name"?k.sort((A,T)=>{var P,I;return(((P=x==null?void 0:x[A.user_id])==null?void 0:P.name)||"").localeCompare(((I=x==null?void 0:x[T.user_id])==null?void 0:I.name)||"")}):u==="slug"?k.sort((A,T)=>A.slug.localeCompare(T.slug)):u==="views_desc"?k.sort((A,T)=>{var P,I;return(((P=_==null?void 0:_[T.id])==null?void 0:P.views)||0)-(((I=_==null?void 0:_[A.id])==null?void 0:I.views)||0)}):u==="views_asc"?k.sort((A,T)=>{var P,I;return(((P=_==null?void 0:_[A.id])==null?void 0:P.views)||0)-(((I=_==null?void 0:_[T.id])==null?void 0:I.views)||0)}):u==="leads_desc"?k.sort((A,T)=>{var P,I;return(((P=_==null?void 0:_[T.id])==null?void 0:P.leads)||0)-(((I=_==null?void 0:_[A.id])==null?void 0:I.leads)||0)}):u==="leads_asc"&&k.sort((A,T)=>{var P,I;return(((P=_==null?void 0:_[A.id])==null?void 0:P.leads)||0)-(((I=_==null?void 0:_[T.id])==null?void 0:I.leads)||0)}),k},[s,c,l,u,x]);return e.jsxs(Qs,{title:"Digital Agent Cards",children:[e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl font-bold",children:"Digital Agent Cards"}),e.jsx("p",{className:"text-muted-foreground",children:"Create and manage agent digital business cards"})]}),e.jsxs(B,{onClick:()=>i(!0),children:[e.jsx(nn,{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(Gr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(we,{placeholder:"Search by name, email, or slug...",value:l,onChange:k=>o(k.target.value),className:"pl-9"})]}),e.jsxs(Ns,{value:c,onValueChange:d,children:[e.jsx(ws,{className:"w-full sm:w-36",children:e.jsx(ks,{placeholder:"Status"})}),e.jsxs(js,{children:[e.jsx(nt,{value:"all",children:"All Status"}),e.jsx(nt,{value:"live",children:"Live"}),e.jsx(nt,{value:"draft",children:"Draft"})]})]}),e.jsxs(Ns,{value:u,onValueChange:h,children:[e.jsx(ws,{className:"w-full sm:w-44",children:e.jsx(ks,{placeholder:"Sort by"})}),e.jsxs(js,{children:[e.jsx(nt,{value:"newest",children:"Newest First"}),e.jsx(nt,{value:"oldest",children:"Oldest First"}),e.jsx(nt,{value:"name",children:"Name A–Z"}),e.jsx(nt,{value:"slug",children:"Slug A–Z"}),e.jsx(nt,{value:"views_desc",children:"Most Views"}),e.jsx(nt,{value:"views_asc",children:"Fewest Views"}),e.jsx(nt,{value:"leads_desc",children:"Most Leads"}),e.jsx(nt,{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:()=>f("table"),className:"rounded-r-none",children:e.jsx(T9,{className:"h-4 w-4"})}),e.jsx(B,{variant:m==="grid"?"default":"ghost",size:"sm",onClick:()=>f("grid"),className:"rounded-l-none",children:e.jsx(G0,{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(k=>e.jsx(xn,{className:"h-48"},k))}):b.length>0?m==="table"?e.jsx(m5n,{cards:b,cardProfiles:x,cardStats:_,onEdit:r,sortBy:u,setSortBy:h}):e.jsx("div",{className:"grid gap-4 md:grid-cols-2 lg:grid-cols-3",children:b.map(k=>e.jsx(p5n,{card:k,onEdit:()=>r(k),stats:_==null?void 0:_[k.id]},k.id))}):s&&s.length>0?e.jsx(_e,{children:e.jsxs(De,{className:"flex flex-col items-center justify-center py-12",children:[e.jsx(Gr,{className:"h-12 w-12 text-muted-foreground mb-4"}),e.jsx("h3",{className:"text-lg font-semibold mb-1",children:"No matching cards"}),e.jsx("p",{className:"text-muted-foreground text-sm",children:"Try adjusting your search or filters"})]})}):e.jsx(_e,{children:e.jsxs(De,{className:"flex flex-col items-center justify-center py-12",children:[e.jsx(Yn,{className:"h-12 w-12 text-muted-foreground mb-4"}),e.jsx("h3",{className:"text-lg font-semibold mb-1",children:"No cards yet"}),e.jsx("p",{className:"text-muted-foreground text-sm mb-4",children:"Create your first digital agent card"}),e.jsxs(B,{onClick:()=>i(!0),children:[e.jsx(nn,{className:"h-4 w-4 mr-2"}),"Create Card"]})]})})]}),e.jsx(f5n,{open:a,onOpenChange:i}),n&&e.jsx(g5n,{card:n,open:!!n,onOpenChange:k=>!k&&r(null)})]})}function m5n({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(Wf,{className:"h-3 w-3"}):a===`${c}_asc`?e.jsx(Om,{className:"h-3 w-3"}):e.jsx(mg,{className:"h-3 w-3 opacity-40"});return e.jsx(_e,{children:e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("table",{className:"w-full text-sm",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"border-b bg-muted/50",children:[e.jsx("th",{className:"text-left p-3 font-medium",children:e.jsxs("button",{onClick:()=>{i(a==="name"?"newest":"name")},className:"flex items-center gap-1 hover:text-foreground text-muted-foreground",children:["Agent ",a==="name"&&e.jsx(Om,{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(We,{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(Ja,{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),ie.success("Link copied!")},children:e.jsx(Pa,{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(Tr,{className:"h-3.5 w-3.5"})})})]})})]},c.id)})})]})})})}function p5n({card:s,onEdit:t,stats:n}){const[r,a]=N.useState(null);N.useEffect(()=>{(async()=>{const{data:c}=await H.from("profiles").select("name").eq("id",s.user_id).single();let d=null;try{const{data:u}=await H.storage.from("avatars").list(`${s.user_id}`);if(u&&u.length>0){const{data:h}=H.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),ie.success("Link copied!")};return e.jsx(_e,{children:e.jsxs(De,{className:"p-4",children:[e.jsxs("div",{className:"flex items-start gap-3 mb-3",children:[e.jsxs(Ua,{className:"h-10 w-10",children:[e.jsx(Gi,{src:(r==null?void 0:r.avatar_url)||void 0}),e.jsx(qa,{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(We,{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(da,{className:"h-3.5 w-3.5"}),(n==null?void 0:n.views)??0," views"]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Yn,{className:"h-3.5 w-3.5"}),(n==null?void 0:n.leads)??0," leads"]})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(B,{variant:"outline",size:"sm",onClick:t,className:"flex-1",children:[e.jsx(Ja,{className:"h-3 w-3 mr-1"}),"Edit"]}),e.jsx(B,{variant:"outline",size:"sm",onClick:l,children:e.jsx(Pa,{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(Tr,{className:"h-3 w-3"})})})]})]})})}function f5n({open:s,onOpenChange:t}){const[n,r]=N.useState(""),[a,i]=N.useState(""),[l,o]=N.useState(""),[c,d]=N.useState(!1),u=H2t(),h=l.trim(),{data:m}=mt({queryKey:["profiles-search-for-cards",h],queryFn:async()=>{let b=H.from("profiles").select("id, name, email").order("name").limit(50);h.length>=2&&(b=b.or(`name.ilike.%${h}%,email.ilike.%${h}%`));const{data:k}=await b;return k||[]},enabled:s}),[f,g]=N.useState(null),y=(m==null?void 0:m.find(b=>b.id===n))||f,x=()=>{if(!n||!a.trim()){ie.error("Select an agent and enter a slug");return}u.mutate({user_id:n,slug:a.trim().toLowerCase().replace(/[^a-z0-9-]/g,"-"),is_published:!0},{onSuccess:()=>{t(!1),r(""),i(""),o("")}})},_=b=>{var A;r(b),d(!1);const k=m==null?void 0:m.find(T=>T.id===b);k&&(g(k),i(((A=k.name)==null?void 0:A.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/(^-|-$)/g,""))||""))};return e.jsx(Bs,{open:s,onOpenChange:t,children:e.jsxs(Fs,{children:[e.jsxs(qs,{children:[e.jsx($s,{children:"Create Agent Card"}),e.jsx(Ar,{children:"Select an agent and set their card URL slug."})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(re,{children:"Agent"}),e.jsxs(rc,{open:c,onOpenChange:d,children:[e.jsx(ac,{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(sb,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]})}),e.jsx(Zl,{className:"w-[--radix-popover-trigger-width] p-0",align:"start",children:e.jsxs(db,{shouldFilter:!1,children:[e.jsx(ub,{placeholder:"Search by name or email...",value:l,onValueChange:o}),e.jsxs(hb,{children:[e.jsx(mb,{children:"No agents found."}),e.jsx(pb,{children:(m||[]).map(b=>e.jsxs(Ry,{value:b.id,onSelect:_,children:[e.jsx(pa,{className:Ot("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(re,{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(we,{value:a,onChange:b=>i(b.target.value),placeholder:"john-doe"})]})]}),e.jsx(B,{onClick:x,disabled:u.isPending,className:"w-full",children:u.isPending?"Creating...":"Create Card"})]})]})})}function g5n({card:s,open:t,onOpenChange:n}){const r=G2t(),{data:a}=W2t(s.id),i=as(),[l,o]=N.useState(null),[c,d]=N.useState(!1),[u,h]=N.useState(!1),[m,f]=N.useState(""),[g,y]=N.useState(s.slug),[x,_]=N.useState(!1),[b,k]=N.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});N.useEffect(()=>{t&&(async()=>{try{const{data:z}=await H.storage.from("avatars").list(`${s.user_id}`);if(z&&z.length>0){const{data:$}=H.storage.from("avatars").getPublicUrl(`${s.user_id}/${z[0].name}`);o(`${$.publicUrl}?t=${Date.now()}`)}}catch{}})()},[s.user_id,t]);const A=L=>{var V;const z=(V=L.target.files)==null?void 0:V[0];if(!z)return;if(!z.type.startsWith("image/")){ie.error("Please select an image file");return}if(z.size>5*1024*1024){ie.error("Image must be under 5MB");return}const $=new FileReader;$.onloadend=()=>{f($.result),h(!0)},$.readAsDataURL(z),L.target.value=""},T=async L=>{d(!0);try{const{data:z}=await H.storage.from("avatars").list(`${s.user_id}`);z&&z.length>0&&await H.storage.from("avatars").remove(z.map(X=>`${s.user_id}/${X.name}`));const $=`${s.user_id}/avatar.jpg`,{error:V}=await H.storage.from("avatars").upload($,L,{upsert:!0,contentType:"image/jpeg"});if(V)throw V;const{data:W}=H.storage.from("avatars").getPublicUrl($),G=`${W.publicUrl}?t=${Date.now()}`;o(G),await H.from("profiles").update({avatar_url:G}).eq("id",s.user_id),i.invalidateQueries({queryKey:["agent-card-public"]}),ie.success("Photo updated!")}catch(z){ie.error(z.message||"Upload failed")}finally{d(!1)}},P=async()=>{const L=g.trim().toLowerCase().replace(/[^a-z0-9-]/g,"-").replace(/-+/g,"-").replace(/(^-|-$)/g,"");if(!L){ie.error("Please enter a valid URL");return}if(L===s.slug){ie.info("No changes to save");return}_(!0);try{const{data:z}=await H.from("agent_cards").select("id").eq("slug",L).neq("id",s.id).maybeSingle();if(z){ie.error("This URL is already taken. Try another one.");return}const{error:$}=await H.from("agent_cards").update({slug:L}).eq("id",s.id);if($)throw $;y(L),i.invalidateQueries({queryKey:["agent-cards-admin"]}),ie.success("Card address updated!")}catch{ie.error("Failed to update card address")}finally{_(!1)}},I=async(L,z)=>{var V;const $=(V=L.target.files)==null?void 0:V[0];if($){if(!$.type.startsWith("image/")){ie.error("Please select an image file");return}try{const W=$.name.split(".").pop()||"png",G=z==="brokerage_logo_url"?"brokerage-logo":"team-logo",X=`${s.user_id}/${G}.${W}`,{error:te}=await H.storage.from("card-logos").upload(X,$,{upsert:!0});if(te)throw te;const{data:ne}=H.storage.from("card-logos").getPublicUrl(X),me=ne.publicUrl+"?t="+Date.now();k(z==="brokerage_logo_url"?ue=>({...ue,[z]:me,brokerage_display_name:""}):ue=>({...ue,[z]:me,team_name:""})),ie.success("Logo uploaded!")}catch{ie.error("Failed to upload logo")}finally{L.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(Bs,{open:t,onOpenChange:n,children:e.jsxs(Fs,{className:"max-w-2xl max-h-[85vh] overflow-y-auto",children:[e.jsxs(qs,{children:[e.jsx($s,{children:"Edit Agent Card"}),e.jsxs(Ar,{children:["/card/",s.slug]})]}),e.jsxs(ya,{defaultValue:"content",children:[e.jsxs(va,{className:"w-full",children:[e.jsx(ls,{value:"content",className:"flex-1",children:"Content"}),e.jsx(ls,{value:"sections",className:"flex-1",children:"Sections"}),e.jsx(ls,{value:"blocks",className:"flex-1",children:"Blocks"}),e.jsx(ls,{value:"analytics",className:"flex-1",children:"Analytics"})]}),e.jsxs(_s,{value:"content",className:"space-y-4 mt-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(re,{children:"Published"}),e.jsx(zn,{checked:b.is_published,onCheckedChange:L=>k(z=>({...z,is_published:L}))})]}),e.jsxs("div",{children:[e.jsx(re,{children:"Agent Photo"}),e.jsxs("div",{className:"flex items-center gap-4 mt-1",children:[e.jsxs(Ua,{className:"h-16 w-16",children:[e.jsx(Gi,{src:l||void 0}),e.jsx(qa,{children:"?"})]}),e.jsxs("label",{className:"cursor-pointer",children:[e.jsx("input",{type:"file",accept:"image/*",className:"hidden",onChange:A,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(us,{className:"h-3 w-3 mr-1 animate-spin"}),"Uploading..."]}):e.jsxs(e.Fragment,{children:[e.jsx(ni,{className:"h-3 w-3 mr-1"}),"Change Photo"]})})})]})]})]}),e.jsxs("div",{children:[e.jsx(re,{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(we,{value:g,onChange:L=>y(L.target.value.toLowerCase().replace(/[^a-z0-9-]/g,"-")),placeholder:"agent-name",className:"rounded-l-none"})]}),e.jsx(B,{variant:"outline",size:"sm",onClick:P,disabled:x||g===s.slug,className:"shrink-0",children:x?"Saving...":"Update"})]})]}),e.jsxs("div",{children:[e.jsx(re,{children:"Theme"}),e.jsxs(Ns,{value:b.theme,onValueChange:L=>k(z=>({...z,theme:L})),children:[e.jsx(ws,{children:e.jsx(ks,{})}),e.jsxs(js,{children:[e.jsx(nt,{value:"standard",children:"✨ Standard (Modern Clean)"}),e.jsx(nt,{value:"luxury",children:"🌙 Luxury (Dark & Gold)"}),e.jsx(nt,{value:"bold",children:"🔥 Bold (Vibrant & Punchy)"}),e.jsx(nt,{value:"classic",children:"📋 Classic (Professional)"})]})]})]}),e.jsxs("div",{children:[e.jsx(re,{children:"Title / Tagline"}),e.jsx(we,{value:b.title,onChange:L=>k(z=>({...z,title:L.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(re,{children:"Positioning Statement"}),e.jsx(we,{value:b.positioning_statement,onChange:L=>k(z=>({...z,positioning_statement:L.target.value})),placeholder:"Your home journey, handled with care."})]}),e.jsxs("div",{children:[e.jsx(re,{children:"Bio"}),e.jsx(Ws,{value:b.bio,onChange:L=>k(z=>({...z,bio:L.target.value})),placeholder:"Short about me...",rows:3})]}),e.jsxs("div",{children:[e.jsx(re,{children:"Review Snippet"}),e.jsx(we,{value:b.review_snippet,onChange:L=>k(z=>({...z,review_snippet:L.target.value})),placeholder:"Best agent we've ever worked with..."})]}),e.jsxs("div",{children:[e.jsx(re,{children:"Review Source URL"}),e.jsx(we,{value:b.review_source_url,onChange:L=>k(z=>({...z,review_source_url:L.target.value})),placeholder:"https://g.page/your-business/review"})]}),e.jsxs("div",{children:[e.jsx(re,{children:"Booking URL (optional — if empty, shows lead form)"}),e.jsx(we,{value:b.booking_url,onChange:L=>k(z=>({...z,booking_url:L.target.value})),placeholder:"https://calendly.com/your-link"})]}),e.jsxs("div",{children:[e.jsx(re,{children:"Custom CTA Label (optional)"}),e.jsx(we,{value:b.custom_cta_label,onChange:L=>k(z=>({...z,custom_cta_label:L.target.value})),placeholder:"Book a Call"})]}),e.jsxs("div",{children:[e.jsx(re,{children:"Custom CTA URL (optional)"}),e.jsx(we,{value:b.custom_cta_url,onChange:L=>k(z=>({...z,custom_cta_url:L.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(re,{className:"text-xs font-semibold uppercase tracking-wider text-muted-foreground",children:"Brokerage Branding"}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(we,{value:b.brokerage_display_name,onChange:L=>k(z=>({...z,brokerage_display_name:L.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:()=>k(L=>({...L,brokerage_logo_url:""})),className:"absolute -top-1.5 -right-1.5 h-5 w-5 rounded-full bg-destructive text-destructive-foreground text-xs flex items-center justify-center opacity-0 group-hover:opacity-100 transition-opacity",children:"×"})]}),e.jsxs("label",{className:"cursor-pointer",children:[e.jsxs("span",{className:"inline-flex items-center gap-1.5 px-3 py-1.5 rounded-md border text-xs font-medium hover:bg-muted transition-colors",children:[e.jsx(ni,{className:"h-3.5 w-3.5"}),b.brokerage_logo_url?"Change Logo":"Upload Logo"]}),e.jsx("input",{type:"file",accept:"image/*",className:"hidden",onChange:L=>I(L,"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(re,{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(qf,{value:[b.brokerage_logo_size||56],onValueChange:([L])=>k(z=>({...z,brokerage_logo_size:L})),min:24,max:120,step:4})]})]})]}),e.jsxs("div",{className:"space-y-3 p-3 rounded-lg bg-muted/30 border",children:[e.jsx(re,{className:"text-xs font-semibold uppercase tracking-wider text-muted-foreground",children:"Team Branding"}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(we,{value:b.team_name,onChange:L=>k(z=>({...z,team_name:L.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:()=>k(L=>({...L,team_logo_url:""})),className:"absolute -top-1.5 -right-1.5 h-5 w-5 rounded-full bg-destructive text-destructive-foreground text-xs flex items-center justify-center opacity-0 group-hover:opacity-100 transition-opacity",children:"×"})]}),e.jsxs("label",{className:"cursor-pointer",children:[e.jsxs("span",{className:"inline-flex items-center gap-1.5 px-3 py-1.5 rounded-md border text-xs font-medium hover:bg-muted transition-colors",children:[e.jsx(ni,{className:"h-3.5 w-3.5"}),b.team_logo_url?"Change Logo":"Upload Logo"]}),e.jsx("input",{type:"file",accept:"image/*",className:"hidden",onChange:L=>I(L,"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(re,{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(qf,{value:[b.team_logo_size||56],onValueChange:([L])=>k(z=>({...z,team_logo_size:L})),min:24,max:120,step:4})]})]})]})]}),e.jsx(_s,{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:L,label:z,hint:$})=>e.jsxs("div",{className:"flex items-center justify-between py-2",children:[e.jsxs("div",{children:[e.jsx(re,{children:z}),$&&e.jsxs("p",{className:"text-xs text-muted-foreground mt-0.5",children:[$," ",L==="show_photo"&&e.jsx("a",{href:"/profile",target:"_blank",rel:"noopener noreferrer",className:"text-primary underline hover:no-underline",children:"Update Profile"})]})]}),e.jsx(zn,{checked:b[L],onCheckedChange:V=>k(W=>({...W,[L]:V}))})]},L))}),e.jsx(_s,{value:"blocks",className:"mt-4",children:e.jsx(U7t,{cardId:s.id})}),e.jsx(_s,{value:"analytics",className:"mt-4",children:a?e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"grid grid-cols-3 gap-4",children:[e.jsx(_e,{children:e.jsxs(De,{className:"p-4 text-center",children:[e.jsx("div",{className:"text-2xl font-bold",children:a.views}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"Views"})]})}),e.jsx(_e,{children:e.jsxs(De,{className:"p-4 text-center",children:[e.jsx("div",{className:"text-2xl font-bold",children:a.clicks}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"Clicks"})]})}),e.jsx(_e,{children:e.jsxs(De,{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(L=>e.jsxs("div",{className:"text-sm p-2 bg-muted/50 rounded-lg",children:[e.jsx("span",{className:"font-medium",children:L.name}),L.phone&&e.jsxs("span",{className:"text-muted-foreground",children:[" · ",L.phone]}),L.intent&&e.jsx(We,{variant:"secondary",className:"ml-2 text-xs",children:L.intent})]},L.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(aVe,{open:u,onClose:()=>h(!1),imageSrc:m,onCropComplete:T,aspectRatio:1})]})}const cz={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"},YWe={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 ZWe(s=!0){return mt({queryKey:["marketplace-categories",s],queryFn:async()=>{let t=H.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 x5n(){const s=as();return _t({mutationFn:async t=>{const{data:n,error:r}=await H.from("marketplace_categories").insert([t]).select().single();if(r)throw r;return n},onSuccess:()=>{s.invalidateQueries({queryKey:["marketplace-categories"]}),ie.success("Category created successfully")},onError:t=>{ie.error("Failed to create category: "+t.message)}})}function y5n(){const s=as();return _t({mutationFn:async({id:t,...n})=>{const{data:r,error:a}=await H.from("marketplace_categories").update(n).eq("id",t).select().single();if(a)throw a;return r},onSuccess:()=>{s.invalidateQueries({queryKey:["marketplace-categories"]}),ie.success("Category updated successfully")},onError:t=>{ie.error("Failed to update category: "+t.message)}})}function v5n(){const s=as();return _t({mutationFn:async t=>{const{error:n}=await H.from("marketplace_categories").delete().eq("id",t);if(n)throw n},onSuccess:()=>{s.invalidateQueries({queryKey:["marketplace-categories"]}),ie.success("Category deleted successfully")},onError:t=>{ie.error("Failed to delete category: "+t.message)}})}function r9t(s,t=!0){return mt({queryKey:["marketplace-products",s,t],queryFn:async()=>{let n=H.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 b5n(s){return mt({queryKey:["marketplace-product",s],queryFn:async()=>{const{data:t,error:n}=await H.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 _5n(){const s=as();return _t({mutationFn:async t=>{const{data:n,error:r}=await H.from("marketplace_products").insert([t]).select().single();if(r)throw r;return n},onSuccess:()=>{s.invalidateQueries({queryKey:["marketplace-products"]}),ie.success("Product created successfully")},onError:t=>{ie.error("Failed to create product: "+t.message)}})}function w5n(){const s=as();return _t({mutationFn:async({id:t,...n})=>{const{data:r,error:a}=await H.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]}),ie.success("Product updated successfully")},onError:t=>{ie.error("Failed to update product: "+t.message)}})}function j5n(){const s=as();return _t({mutationFn:async t=>{const{error:n}=await H.from("marketplace_products").delete().eq("id",t);if(n)throw n},onSuccess:()=>{s.invalidateQueries({queryKey:["marketplace-products"]}),ie.success("Product deleted successfully")},onError:t=>{ie.error("Failed to delete product: "+t.message)}})}function N5n(){const s=as();return _t({mutationFn:async t=>{const{data:n,error:r}=await H.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 k5n(){const s=as();return _t({mutationFn:async({id:t,productId:n})=>{const{error:r}=await H.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]}),ie.success("Image deleted successfully")},onError:t=>{ie.error("Failed to delete image: "+t.message)}})}function S5n(){const s=as();return _t({mutationFn:async({imageId:t,productId:n})=>{const{error:r}=await H.from("marketplace_product_images").update({is_primary:!1}).eq("product_id",n);if(r)throw r;const{error:a}=await H.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]}),ie.success("Primary image updated")},onError:t=>{ie.error("Failed to set primary image: "+t.message)}})}function C5n(){const s=as();return _t({mutationFn:async t=>{const{data:n,error:r}=await H.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]}),ie.success("Variant added successfully")}})}function A5n(){const s=as();return _t({mutationFn:async({id:t,productId:n})=>{const{error:r}=await H.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]}),ie.success("Variant deleted successfully")}})}function T5n(){const s=as();return _t({mutationFn:async({productId:t,videoUrl:n})=>{await H.from("marketplace_product_videos").delete().eq("product_id",t);const{data:r,error:a}=await H.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]}),ie.success("Video updated successfully")}})}function E5n(s){const{isAdmin:t}=Ls();return mt({queryKey:["marketplace-orders",s,t],queryFn:async()=>{let n=H.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 H.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 M5n(){const{user:s}=Ls();return mt({queryKey:["my-marketplace-orders",s==null?void 0:s.id],queryFn:async()=>{const{data:t,error:n}=await H.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 L5n(s){return mt({queryKey:["marketplace-order",s],queryFn:async()=>{const{data:t,error:n}=await H.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 P5n(){const s=as(),{user:t}=Ls();return _t({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 H.from("marketplace_orders").update(c).eq("id",n);if(d)throw d;const{error:u}=await H.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 H.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"]}),ie.success("Order status updated")},onError:n=>{ie.error("Failed to update order: "+n.message)}})}function I5n(){const s=as();return _t({mutationFn:async({itemId:t,proofUrl:n,proofNotes:r,orderId:a})=>{const{error:i}=await H.from("marketplace_order_items").update({proof_url:n,proof_notes:r,proof_status:"pending"}).eq("id",t);if(i)throw i;await H.from("marketplace_orders").update({status:"awaiting_proof_approval"}).eq("id",a);try{await H.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"]}),ie.success("Proof uploaded & customer notified")}})}function D5n(){const s=as();return _t({mutationFn:async({itemId:t,orderId:n})=>{const{error:r}=await H.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"]}),ie.success("Proof approved")}})}function R5n(){const s=as();return _t({mutationFn:async({itemId:t,orderId:n,reason:r})=>{const{error:a}=await H.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"]}),ie.success("Proof rejected - please upload a new proof")}})}function O5n(){const{data:s,isLoading:t}=ZWe(!1),n=x5n(),r=y5n(),a=v5n(),[i,l]=N.useState(!1),[o,c]=N.useState(null),[d,u]=N.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)},f=async y=>{y.preventDefault(),o?await r.mutateAsync({id:o.id,...d}):await n.mutateAsync(d),l(!1),h()},g=async y=>{confirm("Are you sure you want to delete this category?")&&await a.mutateAsync(y)};return t?e.jsxs(_e,{children:[e.jsx(zt,{children:e.jsx(xn,{className:"h-8 w-48"})}),e.jsx(De,{children:e.jsx("div",{className:"space-y-4",children:[1,2,3].map(y=>e.jsx(xn,{className:"h-12 w-full"},y))})})]}):e.jsxs(_e,{children:[e.jsxs(zt,{className:"flex flex-row items-center justify-between",children:[e.jsx(qt,{children:"Categories"}),e.jsxs(Bs,{open:i,onOpenChange:y=>{l(y),y||h()},children:[e.jsx(Ao,{asChild:!0,children:e.jsxs(B,{children:[e.jsx(nn,{className:"h-4 w-4 mr-2"}),"Add Category"]})}),e.jsxs(Fs,{children:[e.jsx(qs,{children:e.jsx($s,{children:o?"Edit Category":"Add Category"})}),e.jsxs("form",{onSubmit:f,className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{htmlFor:"name",children:"Name"}),e.jsx(we,{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(re,{htmlFor:"description",children:"Description"}),e.jsx(Ws,{id:"description",value:d.description,onChange:y=>u({...d,description:y.target.value})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{htmlFor:"image_url",children:"Image URL"}),e.jsx(we,{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(re,{htmlFor:"sort_order",children:"Sort Order"}),e.jsx(we,{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(zn,{id:"is_active",checked:d.is_active,onCheckedChange:y=>u({...d,is_active:y})}),e.jsx(re,{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(De,{children:s&&s.length>0?e.jsxs(Oa,{children:[e.jsx(Fa,{children:e.jsxs(un,{children:[e.jsx(Mt,{children:"Name"}),e.jsx(Mt,{children:"Description"}),e.jsx(Mt,{children:"Sort Order"}),e.jsx(Mt,{children:"Status"}),e.jsx(Mt,{className:"text-right",children:"Actions"})]})}),e.jsx(za,{children:s.map(y=>e.jsxs(un,{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(Ja,{className:"h-4 w-4"})}),e.jsx(B,{variant:"ghost",size:"icon",onClick:()=>g(y.id),disabled:a.isPending,children:e.jsx(qn,{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 F5n(){var ae,he;const{data:s,isLoading:t}=r9t(void 0,!1),{data:n}=ZWe(!1),r=_5n(),a=w5n(),i=j5n(),l=N5n(),o=k5n(),c=S5n(),d=C5n(),u=A5n(),h=T5n(),[m,f]=N.useState(!1),[g,y]=N.useState(!1),[x,_]=N.useState(!1),[b,k]=N.useState(null),[A,T]=N.useState(null),[P,I]=N.useState(!1),[M,L]=N.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}),[z,$]=N.useState({name:"",price_adjustment:0}),[V,W]=N.useState(""),G=()=>{L({name:"",description:"",base_price:0,shipping_fee:0,category_id:"",allow_artwork_upload:!1,requires_proof_approval:!1,is_active:!0,sort_order:0}),k(null)},X=xe=>{k(xe),L({name:xe.name,description:xe.description||"",base_price:Number(xe.base_price),shipping_fee:Number(xe.shipping_fee),category_id:xe.category_id||"",allow_artwork_upload:xe.allow_artwork_upload,requires_proof_approval:xe.requires_proof_approval,is_active:xe.is_active,sort_order:xe.sort_order}),f(!0)},te=async xe=>{xe.preventDefault();const ve={...M,category_id:M.category_id||null};b?await a.mutateAsync({id:b.id,...ve}):await r.mutateAsync(ve),f(!1),G()},ne=async xe=>{confirm("Are you sure you want to delete this product?")&&await i.mutateAsync(xe)},me=async xe=>{if(!A||!xe.target.files||xe.target.files.length===0)return;I(!0);const ve=xe.target.files[0],ge=ve.name.split(".").pop(),be=`products/${A.id}/${Date.now()}.${ge}`;try{const{error:Se}=await H.storage.from("marketplace").upload(be,ve);if(Se)throw Se;const{data:{publicUrl:Ie}}=H.storage.from("marketplace").getPublicUrl(be);await l.mutateAsync({product_id:A.id,image_url:Ie,is_primary:!A.images||A.images.length===0}),ie.success("Image uploaded successfully")}catch(Se){ie.error("Failed to upload image: "+Se.message)}finally{I(!1)}},ue=async xe=>{xe.preventDefault(),A&&(await d.mutateAsync({product_id:A.id,name:z.name,price_adjustment:z.price_adjustment}),$({name:"",price_adjustment:0}))},ce=async()=>{!A||!V||(await h.mutateAsync({productId:A.id,videoUrl:V}),W(""))};return t?e.jsxs(_e,{children:[e.jsx(zt,{children:e.jsx(xn,{className:"h-8 w-48"})}),e.jsx(De,{children:e.jsx("div",{className:"grid gap-4 md:grid-cols-2 lg:grid-cols-3",children:[1,2,3].map(xe=>e.jsx(xn,{className:"h-64 w-full"},xe))})})]}):e.jsxs(e.Fragment,{children:[e.jsxs(_e,{children:[e.jsxs(zt,{className:"flex flex-row items-center justify-between",children:[e.jsx(qt,{children:"Products"}),e.jsxs(Bs,{open:m,onOpenChange:xe=>{f(xe),xe||G()},children:[e.jsx(Ao,{asChild:!0,children:e.jsxs(B,{children:[e.jsx(nn,{className:"h-4 w-4 mr-2"}),"Add Product"]})}),e.jsxs(Fs,{className:"max-w-2xl max-h-[90vh] overflow-y-auto",children:[e.jsx(qs,{children:e.jsx($s,{children:b?"Edit Product":"Add Product"})}),e.jsxs("form",{onSubmit:te,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(re,{htmlFor:"name",children:"Product Name"}),e.jsx(we,{id:"name",value:M.name,onChange:xe=>L({...M,name:xe.target.value}),required:!0})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{htmlFor:"category",children:"Category"}),e.jsxs(Ns,{value:M.category_id,onValueChange:xe=>L({...M,category_id:xe}),children:[e.jsx(ws,{children:e.jsx(ks,{placeholder:"Select category"})}),e.jsx(js,{children:n==null?void 0:n.map(xe=>e.jsx(nt,{value:xe.id,children:xe.name},xe.id))})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{htmlFor:"description",children:"Description"}),e.jsx(Ws,{id:"description",value:M.description,onChange:xe=>L({...M,description:xe.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(re,{htmlFor:"base_price",children:"Base Price ($)"}),e.jsx(we,{id:"base_price",type:"number",step:"0.01",min:"0",value:M.base_price,onChange:xe=>L({...M,base_price:parseFloat(xe.target.value)||0}),required:!0})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{htmlFor:"shipping_fee",children:"Shipping Fee ($)"}),e.jsx(we,{id:"shipping_fee",type:"number",step:"0.01",min:"0",value:M.shipping_fee,onChange:xe=>L({...M,shipping_fee:parseFloat(xe.target.value)||0})})]})]}),e.jsx("div",{className:"grid grid-cols-2 gap-4",children:e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{htmlFor:"sort_order",children:"Sort Order"}),e.jsx(we,{id:"sort_order",type:"number",value:M.sort_order,onChange:xe=>L({...M,sort_order:parseInt(xe.target.value)||0})})]})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(zn,{id:"allow_artwork_upload",checked:M.allow_artwork_upload,onCheckedChange:xe=>L({...M,allow_artwork_upload:xe})}),e.jsx(re,{htmlFor:"allow_artwork_upload",children:"Allow customer to upload artwork"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(zn,{id:"requires_proof_approval",checked:M.requires_proof_approval,onCheckedChange:xe=>L({...M,requires_proof_approval:xe})}),e.jsx(re,{htmlFor:"requires_proof_approval",children:"Requires proof approval"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(zn,{id:"is_active",checked:M.is_active,onCheckedChange:xe=>L({...M,is_active:xe})}),e.jsx(re,{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(De,{children:s&&s.length>0?e.jsx("div",{className:"grid gap-4 md:grid-cols-2 lg:grid-cols-3",children:s.map(xe=>{var ve,ge;return e.jsxs(_e,{className:"overflow-hidden",children:[e.jsxs("div",{className:"aspect-video bg-muted relative",children:[xe.images&&xe.images.length>0?e.jsx("img",{src:((ve=xe.images.find(be=>be.is_primary))==null?void 0:ve.image_url)||xe.images[0].image_url,alt:xe.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"}),!xe.is_active&&e.jsx(We,{variant:"secondary",className:"absolute top-2 right-2",children:"Inactive"})]}),e.jsxs(De,{className:"p-4",children:[e.jsx("h3",{className:"font-semibold mb-1",children:xe.name}),e.jsx("p",{className:"text-sm text-muted-foreground mb-2",children:((ge=xe.category)==null?void 0:ge.name)||"No category"}),e.jsxs("div",{className:"flex items-center justify-between mb-3",children:[e.jsxs("span",{className:"font-bold",children:["$",Number(xe.base_price).toFixed(2)]}),Number(xe.shipping_fee)>0&&e.jsxs("span",{className:"text-sm text-muted-foreground",children:["+$",Number(xe.shipping_fee).toFixed(2)," shipping"]})]}),e.jsxs("div",{className:"flex flex-wrap gap-1 mb-3",children:[xe.allow_artwork_upload&&e.jsx(We,{variant:"outline",className:"text-xs",children:"Artwork Upload"}),xe.requires_proof_approval&&e.jsx(We,{variant:"outline",className:"text-xs",children:"Proof Required"}),xe.variants&&xe.variants.length>0&&e.jsxs(We,{variant:"outline",className:"text-xs",children:[xe.variants.length," Variants"]})]}),e.jsxs("div",{className:"flex gap-2 flex-wrap",children:[e.jsxs(B,{variant:"outline",size:"sm",onClick:()=>X(xe),children:[e.jsx(Ja,{className:"h-3 w-3 mr-1"}),"Edit"]}),e.jsxs(B,{variant:"outline",size:"sm",onClick:()=>{T(xe),y(!0)},children:[e.jsx(Gv,{className:"h-3 w-3 mr-1"}),"Images"]}),e.jsxs(B,{variant:"outline",size:"sm",onClick:()=>{T(xe),_(!0)},children:[e.jsx(pf,{className:"h-3 w-3 mr-1"}),"Variants"]}),e.jsx(B,{variant:"ghost",size:"sm",onClick:()=>ne(xe.id),children:e.jsx(qn,{className:"h-3 w-3 text-destructive"})})]})]})]},xe.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(Bs,{open:g,onOpenChange:y,children:e.jsxs(Fs,{className:"max-w-2xl",children:[e.jsx(qs,{children:e.jsxs($s,{children:["Manage Images - ",A==null?void 0:A.name]})}),e.jsxs("div",{className:"space-y-4",children:[e.jsx("div",{className:"grid grid-cols-3 gap-4",children:(ae=A==null?void 0:A.images)==null?void 0:ae.map(xe=>e.jsxs("div",{className:"relative group",children:[e.jsx("img",{src:xe.image_url,alt:"",className:"w-full aspect-square object-cover rounded-lg"}),xe.is_primary&&e.jsx(We,{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:[!xe.is_primary&&e.jsx(B,{variant:"secondary",size:"icon",onClick:async()=>{var ve;await c.mutateAsync({imageId:xe.id,productId:A.id}),T({...A,images:(ve=A.images)==null?void 0:ve.map(ge=>({...ge,is_primary:ge.id===xe.id}))})},disabled:c.isPending,title:"Set as primary",children:e.jsx(Wa,{className:"h-4 w-4"})}),e.jsx(B,{variant:"destructive",size:"icon",onClick:async()=>{var ge;await o.mutateAsync({id:xe.id,productId:A.id});const ve=s==null?void 0:s.find(be=>be.id===A.id);ve&&T({...ve,images:(ge=ve.images)==null?void 0:ge.filter(be=>be.id!==xe.id)})},disabled:o.isPending,children:e.jsx(qn,{className:"h-4 w-4"})})]})]},xe.id))}),e.jsxs("div",{className:"border-2 border-dashed rounded-lg p-6 text-center",children:[e.jsx("input",{type:"file",accept:"image/*",onChange:me,className:"hidden",id:"image-upload",disabled:P}),e.jsxs("label",{htmlFor:"image-upload",className:"cursor-pointer",children:[e.jsx(Gv,{className:"h-8 w-8 mx-auto mb-2 text-muted-foreground"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:P?"Uploading...":"Click to upload an image"})]})]}),e.jsxs("div",{className:"border-t pt-4 mt-4",children:[e.jsx(re,{children:"Product Video (optional)"}),e.jsxs("div",{className:"flex gap-2 mt-2",children:[e.jsx(we,{placeholder:"Enter video URL (YouTube, Vimeo, etc.)",value:V,onChange:xe=>W(xe.target.value)}),e.jsxs(B,{onClick:ce,disabled:!V,children:[e.jsx(na,{className:"h-4 w-4 mr-2"}),"Set Video"]})]}),(A==null?void 0:A.video)&&e.jsxs("p",{className:"text-sm text-muted-foreground mt-2",children:["Current video: ",A.video.video_url]})]})]})]})}),e.jsx(Bs,{open:x,onOpenChange:_,children:e.jsxs(Fs,{children:[e.jsx(qs,{children:e.jsxs($s,{children:["Manage Variants - ",A==null?void 0:A.name]})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("form",{onSubmit:ue,className:"flex gap-2",children:[e.jsx(we,{placeholder:"Variant name (e.g., 500 count)",value:z.name,onChange:xe=>$({...z,name:xe.target.value}),required:!0}),e.jsx(we,{type:"number",step:"0.01",placeholder:"Price adj.",value:z.price_adjustment,onChange:xe=>$({...z,price_adjustment:parseFloat(xe.target.value)||0}),className:"w-32"}),e.jsx(B,{type:"submit",children:"Add"})]}),e.jsxs("div",{className:"space-y-2",children:[(he=A==null?void 0:A.variants)==null?void 0:he.map(xe=>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:xe.name}),e.jsxs("span",{className:"text-sm text-muted-foreground ml-2",children:[Number(xe.price_adjustment)>=0?"+":"","$",Number(xe.price_adjustment).toFixed(2)]})]}),e.jsx(B,{variant:"ghost",size:"icon",onClick:()=>u.mutateAsync({id:xe.id,productId:A.id}),children:e.jsx(qn,{className:"h-4 w-4 text-destructive"})})]},xe.id)),(!(A!=null&&A.variants)||A.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 z5n=["pending_payment","order_submitted","awaiting_proof_approval","proof_approved","processing","in_production","shipped","completed","cancelled","refunded"];function B5n(){var y,x,_;const{data:s,isLoading:t}=E5n(),n=P5n(),r=I5n(),[a,i]=N.useState(null),[l,o]=N.useState(!1),[c,d]=N.useState({status:"",notes:"",trackingNumber:"",trackingUrl:""}),[u,h]=N.useState(!1),m=b=>{i(b),d({status:b.status,notes:"",trackingNumber:b.tracking_number||"",trackingUrl:b.tracking_url||""}),o(!0)},f=async()=>{a&&(await n.mutateAsync({orderId:a.id,status:c.status,notes:c.notes,trackingNumber:c.trackingNumber,trackingUrl:c.trackingUrl,previousStatus:a.status}),o(!1))},g=async(b,k)=>{if(!a||!b.target.files||b.target.files.length===0)return;h(!0);const A=b.target.files[0],T=A.name.split(".").pop(),P=`proofs/${a.id}/${k}/${Date.now()}.${T}`;try{const{error:I}=await H.storage.from("marketplace").upload(P,A);if(I)throw I;const{data:{publicUrl:M}}=H.storage.from("marketplace").getPublicUrl(P);await r.mutateAsync({itemId:k,proofUrl:M,orderId:a.id}),ie.success("Proof uploaded successfully")}catch(I){ie.error("Failed to upload proof: "+I.message)}finally{h(!1)}};return t?e.jsxs(_e,{children:[e.jsx(zt,{children:e.jsx(xn,{className:"h-8 w-48"})}),e.jsx(De,{children:e.jsx("div",{className:"space-y-4",children:[1,2,3].map(b=>e.jsx(xn,{className:"h-16 w-full"},b))})})]}):e.jsxs(e.Fragment,{children:[e.jsxs(_e,{children:[e.jsx(zt,{children:e.jsx(qt,{children:"Orders"})}),e.jsx(De,{children:s&&s.length>0?e.jsxs(Oa,{children:[e.jsx(Fa,{children:e.jsxs(un,{children:[e.jsx(Mt,{children:"Order #"}),e.jsx(Mt,{children:"Customer"}),e.jsx(Mt,{children:"Date"}),e.jsx(Mt,{children:"Total"}),e.jsx(Mt,{children:"Status"}),e.jsx(Mt,{className:"text-right",children:"Actions"})]})}),e.jsx(za,{children:s.map(b=>{var k,A;return e.jsxs(un,{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:((k=b.user)==null?void 0:k.name)||"Unknown"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:(A=b.user)==null?void 0:A.email})]})}),e.jsx(gt,{children:Js(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(We,{className:YWe[b.status],children:cz[b.status]})}),e.jsx(gt,{className:"text-right",children:e.jsxs(B,{variant:"ghost",size:"sm",onClick:()=>m(b),children:[e.jsx(da,{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(Bs,{open:l,onOpenChange:o,children:e.jsxs(Fs,{className:"max-w-3xl max-h-[90vh] overflow-y-auto",children:[e.jsx(qs,{children:e.jsxs($s,{children:["Order ",a==null?void 0:a.order_number]})}),a&&e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx("h4",{className:"font-medium mb-2",children:"Customer"}),e.jsx("p",{children:(y=a.user)==null?void 0:y.name}),e.jsx("p",{className:"text-sm text-muted-foreground",children:(x=a.user)==null?void 0:x.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:(_=a.items)==null?void 0:_.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(We,{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:k=>g(k,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(ni,{className:"h-4 w-4 mr-1"}),u?"Uploading...":"Upload Proof"]})})})]})]})})]},b.id))})]}),e.jsxs("div",{className:"border-t pt-4",children:[e.jsxs("div",{className:"flex justify-between text-sm",children:[e.jsx("span",{children:"Subtotal"}),e.jsxs("span",{children:["$",Number(a.subtotal).toFixed(2)]})]}),e.jsxs("div",{className:"flex justify-between text-sm",children:[e.jsx("span",{children:"Shipping"}),e.jsxs("span",{children:["$",Number(a.shipping_total).toFixed(2)]})]}),e.jsxs("div",{className:"flex justify-between font-bold text-lg mt-2",children:[e.jsx("span",{children:"Total"}),e.jsxs("span",{children:["$",Number(a.total).toFixed(2)]})]})]}),e.jsxs("div",{className:"border-t pt-4",children:[e.jsx("h4",{className:"font-medium mb-3",children:"Update Order Status"}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{children:"Status"}),e.jsxs(Ns,{value:c.status,onValueChange:b=>d({...c,status:b}),children:[e.jsx(ws,{children:e.jsx(ks,{})}),e.jsx(js,{children:z5n.map(b=>e.jsx(nt,{value:b,children:cz[b]},b))})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{children:"Tracking Number"}),e.jsx(we,{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(re,{children:"Tracking URL"}),e.jsx(we,{value:c.trackingUrl,onChange:b=>d({...c,trackingUrl:b.target.value}),placeholder:"https://..."})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{children:"Notes (optional)"}),e.jsx(Ws,{value:c.notes,onChange:b=>d({...c,notes:b.target.value}),placeholder:"Add a note about this status change..."})]}),e.jsxs(B,{onClick:f,disabled:n.isPending,className:"w-full",children:[e.jsx(Ku,{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(We,{variant:"outline",children:cz[b.status]}),b.notes&&e.jsx("p",{className:"text-muted-foreground mt-1",children:b.notes})]}),e.jsx("span",{className:"text-muted-foreground",children:Js(new Date(b.created_at),"MMM d, h:mm a")})]},b.id))})]})]})]})})]})}function $5n(){const[s,t]=N.useState("products"),n=tr();return e.jsx(Qs,{title:"Marketplace Management",children:e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl font-bold",children:"Marketplace Management"}),e.jsx("p",{className:"text-muted-foreground",children:"Manage products, categories, and orders"})]}),e.jsxs(B,{variant:"outline",onClick:()=>n("/marketplace"),children:[e.jsx(Tr,{className:"h-4 w-4 mr-2"}),"View Store"]})]}),e.jsxs(ya,{value:s,onValueChange:t,children:[e.jsxs(va,{className:"grid w-full grid-cols-3",children:[e.jsxs(ls,{value:"products",className:"flex items-center gap-2",children:[e.jsx(Ku,{className:"h-4 w-4"}),"Products"]}),e.jsxs(ls,{value:"categories",className:"flex items-center gap-2",children:[e.jsx(H0,{className:"h-4 w-4"}),"Categories"]}),e.jsxs(ls,{value:"orders",className:"flex items-center gap-2",children:[e.jsx(W1,{className:"h-4 w-4"}),"Orders"]})]}),e.jsx(_s,{value:"products",children:e.jsx(F5n,{})}),e.jsx(_s,{value:"categories",children:e.jsx(O5n,{})}),e.jsx(_s,{value:"orders",children:e.jsx(B5n,{})})]})]})})}function a9t(){return mt({queryKey:["reward-categories"],queryFn:async()=>{const{data:s,error:t}=await H.from("reward_store_categories").select("*").order("sort_order",{ascending:!0});if(t)throw t;return s}})}function U5n(s){return mt({queryKey:["reward-items",s],queryFn:async()=>{let t=H.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 q5n(s){return mt({queryKey:["active-reward-items",s],queryFn:async()=>{let t=H.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 V5n(s){return mt({queryKey:["user-purchases",s],queryFn:async()=>{if(!s)return[];const{data:t,error:n}=await H.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 H5n(){return mt({queryKey:["all-reward-purchases"],queryFn:async()=>{const{data:s,error:t}=await H.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 H.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 G5n(s){return mt({queryKey:["spendable-points",s],queryFn:async()=>{if(!s)return 0;const{data:t,error:n}=await H.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 W5n(){const s=as();return _t({mutationFn:async t=>{const{data:n,error:r}=await H.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 K5n(){const s=as();return _t({mutationFn:async t=>{const{data:n,error:r}=await H.from("reward_store_categories").insert([t]).select().single();if(r)throw r;return n},onSuccess:()=>{s.invalidateQueries({queryKey:["reward-categories"]})}})}function Y5n(){const s=as();return _t({mutationFn:async({id:t,...n})=>{const{data:r,error:a}=await H.from("reward_store_categories").update(n).eq("id",t).select().single();if(a)throw a;return r},onSuccess:()=>{s.invalidateQueries({queryKey:["reward-categories"]})}})}function Z5n(){const s=as();return _t({mutationFn:async t=>{const{error:n}=await H.from("reward_store_categories").delete().eq("id",t);if(n)throw n},onSuccess:()=>{s.invalidateQueries({queryKey:["reward-categories"]})}})}function X5n(){const s=as();return _t({mutationFn:async t=>{const{data:n,error:r}=await H.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 Q5n(){const s=as();return _t({mutationFn:async({id:t,...n})=>{const{data:r,error:a}=await H.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 J5n(){const s=as();return _t({mutationFn:async t=>{const{error:n}=await H.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 eSn(s){const t=s.match(/\/storage\/v1\/object\/public\/([^/]+)\/(.+)$/);return t?{bucket:t[1],path:t[2]}:null}async function ZPe(s,t){const n=eSn(s);if(n)try{const{data:r,error:a}=await H.storage.from(n.bucket).download(n.path);if(a){console.error("Error downloading file:",a),ie.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),ie.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),ie.error("Failed to download file")}}function i9t(){return mt({queryKey:["point-reward-settings"],queryFn:async()=>{const{data:s,error:t}=await H.from("point_reward_settings").select("*").order("action_name");if(t)throw t;return s}})}function tSn(){const s=as();return _t({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 H.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 sSn(){const{user:s}=Ls(),[t,n]=N.useState("items"),[r,a]=N.useState(!1),[i,l]=N.useState(null),[o,c]=N.useState(""),[d,u]=N.useState(""),[h,m]=N.useState(""),[f,g]=N.useState(null),[y,x]=N.useState(!1),[_,b]=N.useState(null),[k,A]=N.useState(""),[T,P]=N.useState(""),[I,M]=N.useState(null),[L,z]=N.useState(""),[$,V]=N.useState("file"),[W,G]=N.useState(""),[X,te]=N.useState(""),[ne,me]=N.useState(""),[ue,ce]=N.useState(!0),[ae,he]=N.useState(null),[xe,ve]=N.useState(!1),[ge,be]=N.useState(!1),Se=N.useRef(null),Ie=N.useRef(null),{data:Me,isLoading:Re}=a9t(),{data:Be,isLoading:Ne}=U5n(),{data:Ge,isLoading:Ce}=H5n(),{data:Fe,isLoading:Ae}=i9t(),Xe=K5n(),$e=Y5n(),Ye=Z5n(),Je=X5n(),Ke=Q5n(),st=J5n(),rt=tSn(),[Ze,ht]=N.useState({}),Bt=Nt=>{Nt?(l(Nt),c(Nt.name),u(Nt.description||""),m(Nt.icon||"")):(l(null),c(""),u(""),m("")),a(!0)},Ct=async()=>{if(!o.trim()){ie.error("Please enter a category name");return}try{i?(await $e.mutateAsync({id:i.id,name:o,description:d||null,icon:h||null}),ie.success("Category updated successfully")):(await Xe.mutateAsync({name:o,description:d||null,icon:h||null,sort_order:((Me==null?void 0:Me.length)||0)+1}),ie.success("Category created successfully")),a(!1)}catch(Nt){console.error("Error saving category:",Nt),ie.error("Failed to save category")}},Yt=async()=>{if(f)try{await Ye.mutateAsync(f),ie.success("Category deleted successfully"),g(null)}catch(Nt){console.error("Error deleting category:",Nt),ie.error("Failed to delete category")}},Kt=Nt=>{var ms;Nt?(b(Nt),A(Nt.name),P(Nt.description||""),M(Nt.category_id),z(Nt.points_cost.toString()),V(Nt.item_type),G(Nt.file_url||""),te(Nt.preview_image_url||""),me(((ms=Nt.max_quantity)==null?void 0:ms.toString())||""),ce(Nt.is_active)):(b(null),A(""),P(""),M(null),z(""),V("file"),G(""),te(""),me(""),ce(!0)),x(!0)},Xs=async(Nt,ms)=>{ms==="file"?ve(!0):be(!0);try{const Ys=Nt.name.split(".").pop(),It=`${Date.now()}-${Math.random().toString(36).substring(7)}.${Ys}`,Ds=`${ms==="file"?"items":"previews"}/${It}`,{error:As}=await H.storage.from("reward-store").upload(Ds,Nt);if(As)throw As;const{data:{publicUrl:Hs}}=H.storage.from("reward-store").getPublicUrl(Ds);ms==="file"?G(Hs):te(Hs),ie.success("File uploaded successfully")}catch(Ys){console.error("Error uploading file:",Ys),ie.error("Failed to upload file")}finally{ms==="file"?ve(!1):be(!1)}},zs=async()=>{if(!k.trim()){ie.error("Please enter an item name");return}if(!L||parseInt(L)<0){ie.error("Please enter a valid points cost");return}try{const Nt={name:k,description:T||null,category_id:I,points_cost:parseInt(L),item_type:$,file_url:W||null,preview_image_url:X||null,max_quantity:ne?parseInt(ne):null,current_quantity:ne?parseInt(ne):null,is_active:ue,created_by:s==null?void 0:s.id};_?(await Ke.mutateAsync({id:_.id,...Nt,current_quantity:_.max_quantity!==(ne?parseInt(ne):null)?ne?parseInt(ne):null:_.current_quantity}),ie.success("Item updated successfully")):(await Je.mutateAsync(Nt),ie.success("Item created successfully")),x(!1)}catch(Nt){console.error("Error saving item:",Nt),ie.error("Failed to save item")}},Vt=async()=>{if(ae)try{await st.mutateAsync(ae),ie.success("Item deleted successfully"),he(null)}catch(Nt){console.error("Error deleting item:",Nt),ie.error("Failed to delete item")}},At=async(Nt,ms)=>{const Ys=Ze[Nt];if(Ys===void 0||Ys===ms.toString())return;const It=parseInt(Ys);if(isNaN(It)||It<0){ie.error("Please enter a valid positive number");return}try{await rt.mutateAsync({id:Nt,points:It}),ie.success("Points updated successfully"),ht(Ds=>{const As={...Ds};return delete As[Nt],As})}catch(Ds){console.error("Error updating points:",Ds),ie.error("Failed to update points")}};return Re||Ne||Ce||Ae?e.jsx(Qs,{title:"Reward Store",children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(xn,{className:"h-8 w-64"}),e.jsx(xn,{className:"h-96"})]})}):e.jsxs(Qs,{title:"Reward Store",children:[e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl font-bold text-foreground",children:"Reward Store Management"}),e.jsx("p",{className:"text-muted-foreground",children:"Manage store items that agents can purchase with their points"})]}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-4",children:[e.jsx(_e,{children:e.jsxs(De,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[e.jsx(Ku,{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:(Be==null?void 0:Be.length)||0}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[(Be==null?void 0:Be.filter(Nt=>Nt.is_active).length)||0," active"]})]})}),e.jsx(_e,{children:e.jsxs(De,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[e.jsx(H0,{className:"h-4 w-4"}),e.jsx("span",{className:"text-xs font-medium",children:"Categories"})]}),e.jsx("p",{className:"text-2xl font-bold",children:(Me==null?void 0:Me.length)||0})]})}),e.jsx(_e,{children:e.jsxs(De,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[e.jsx(Wa,{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:[Be&&Be.length>0?Math.round(Be.reduce((Nt,ms)=>Nt+ms.points_cost,0)/Be.length):0," pts"]})]})})]}),e.jsxs(ya,{value:t,onValueChange:n,children:[e.jsxs(va,{children:[e.jsx(ls,{value:"items",children:"Items"}),e.jsx(ls,{value:"categories",children:"Categories"}),e.jsx(ls,{value:"purchases",children:"Purchases"}),e.jsx(ls,{value:"point-settings",children:"Point Settings"})]}),e.jsx(_s,{value:"items",className:"mt-4",children:e.jsxs(_e,{children:[e.jsxs(zt,{className:"flex flex-row items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(qt,{children:"Store Items"}),e.jsx(_r,{children:"Manage rewards that agents can purchase"})]}),e.jsxs(B,{onClick:()=>Kt(),children:[e.jsx(nn,{className:"h-4 w-4 mr-2"}),"Add Item"]})]}),e.jsx(De,{children:!Be||Be.length===0?e.jsxs("div",{className:"text-center py-8 text-muted-foreground",children:[e.jsx(Io,{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(Oa,{children:[e.jsx(Fa,{children:e.jsxs(un,{children:[e.jsx(Mt,{children:"Item"}),e.jsx(Mt,{children:"Category"}),e.jsx(Mt,{className:"text-center",children:"Cost"}),e.jsx(Mt,{className:"text-center",children:"Type"}),e.jsx(Mt,{className:"text-center",children:"Quantity"}),e.jsx(Mt,{className:"text-center",children:"Status"}),e.jsx(Mt,{className:"text-right",children:"Actions"})]})}),e.jsx(za,{children:Be.map(Nt=>e.jsxs(un,{children:[e.jsx(gt,{children:e.jsxs("div",{className:"flex items-center gap-3",children:[Nt.preview_image_url?e.jsx("img",{src:Nt.preview_image_url,alt:Nt.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(Io,{className:"h-5 w-5 text-muted-foreground"})}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:Nt.name}),e.jsx("p",{className:"text-xs text-muted-foreground line-clamp-1",children:Nt.description||"No description"})]})]})}),e.jsx(gt,{children:Nt.category?e.jsx(We,{variant:"outline",children:Nt.category.name}):e.jsx("span",{className:"text-muted-foreground",children:"—"})}),e.jsx(gt,{className:"text-center",children:e.jsxs(We,{variant:"secondary",className:"font-bold",children:[e.jsx(Wa,{className:"h-3 w-3 mr-1"}),Nt.points_cost]})}),e.jsx(gt,{className:"text-center",children:e.jsxs("div",{className:"flex items-center justify-center gap-1",children:[Nt.item_type==="file"?e.jsx(Wr,{className:"h-4 w-4 text-muted-foreground"}):e.jsx(gc,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{className:"text-xs capitalize",children:Nt.item_type})]})}),e.jsx(gt,{className:"text-center",children:Nt.max_quantity!==null?e.jsxs("span",{className:Nt.current_quantity===0?"text-red-500":"",children:[Nt.current_quantity,"/",Nt.max_quantity]}):e.jsx("span",{className:"text-muted-foreground",children:"Unlimited"})}),e.jsx(gt,{className:"text-center",children:e.jsx(We,{variant:Nt.is_active?"default":"secondary",children:Nt.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:()=>Kt(Nt),children:e.jsx(Ja,{className:"h-4 w-4"})}),e.jsx(B,{variant:"ghost",size:"sm",onClick:()=>he(Nt.id),children:e.jsx(qn,{className:"h-4 w-4 text-destructive"})})]})})]},Nt.id))})]})})]})}),e.jsx(_s,{value:"categories",className:"mt-4",children:e.jsxs(_e,{children:[e.jsxs(zt,{className:"flex flex-row items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(qt,{children:"Categories"}),e.jsx(_r,{children:"Organize your store items into categories"})]}),e.jsxs(B,{onClick:()=>Bt(),children:[e.jsx(nn,{className:"h-4 w-4 mr-2"}),"Add Category"]})]}),e.jsx(De,{children:!Me||Me.length===0?e.jsxs("div",{className:"text-center py-8 text-muted-foreground",children:[e.jsx(H0,{className:"h-12 w-12 mx-auto mb-4 opacity-50"}),e.jsx("p",{children:"No categories yet. Add your first category!"})]}):e.jsxs(Oa,{children:[e.jsx(Fa,{children:e.jsxs(un,{children:[e.jsx(Mt,{children:"Name"}),e.jsx(Mt,{children:"Description"}),e.jsx(Mt,{className:"text-center",children:"Items"}),e.jsx(Mt,{className:"text-right",children:"Actions"})]})}),e.jsx(za,{children:Me.map(Nt=>e.jsxs(un,{children:[e.jsxs(gt,{className:"font-medium",children:[Nt.icon&&e.jsx("span",{className:"mr-2",children:Nt.icon}),Nt.name]}),e.jsx(gt,{className:"text-muted-foreground",children:Nt.description||"—"}),e.jsx(gt,{className:"text-center",children:(Be==null?void 0:Be.filter(ms=>ms.category_id===Nt.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:()=>Bt(Nt),children:e.jsx(Ja,{className:"h-4 w-4"})}),e.jsx(B,{variant:"ghost",size:"sm",onClick:()=>g(Nt.id),children:e.jsx(qn,{className:"h-4 w-4 text-destructive"})})]})})]},Nt.id))})]})})]})}),e.jsx(_s,{value:"purchases",className:"mt-4",children:e.jsxs(_e,{children:[e.jsxs(zt,{children:[e.jsxs(qt,{className:"flex items-center gap-2",children:[e.jsx(W1,{className:"h-5 w-5"}),"Purchase History"]}),e.jsx(_r,{children:"View all reward redemptions by agents"})]}),e.jsx(De,{children:!Ge||Ge.length===0?e.jsxs("div",{className:"text-center py-8 text-muted-foreground",children:[e.jsx(W1,{className:"h-12 w-12 mx-auto mb-4 opacity-50"}),e.jsx("p",{children:"No purchases yet."})]}):e.jsxs(Oa,{children:[e.jsx(Fa,{children:e.jsxs(un,{children:[e.jsx(Mt,{children:"Date"}),e.jsx(Mt,{children:"Agent"}),e.jsx(Mt,{children:"Item"}),e.jsx(Mt,{className:"text-center",children:"Points Spent"})]})}),e.jsx(za,{children:Ge.map(Nt=>{var ms,Ys,It,Ds;return e.jsxs(un,{children:[e.jsx(gt,{className:"text-muted-foreground",children:Js(new Date(Nt.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(Ro,{className:"h-4 w-4 text-muted-foreground"})}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:((ms=Nt.user)==null?void 0:ms.name)||"Unknown"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:((Ys=Nt.user)==null?void 0:Ys.email)||"—"})]})]})}),e.jsx(gt,{children:e.jsxs("div",{className:"flex items-center gap-2",children:[(It=Nt.item)!=null&&It.preview_image_url?e.jsx("img",{src:Nt.item.preview_image_url,alt:Nt.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(Io,{className:"h-4 w-4 text-muted-foreground"})}),e.jsx("span",{children:((Ds=Nt.item)==null?void 0:Ds.name)||"Deleted item"})]})}),e.jsx(gt,{className:"text-center",children:e.jsxs(We,{variant:"secondary",className:"font-bold",children:[e.jsx(Wa,{className:"h-3 w-3 mr-1"}),Nt.points_spent]})})]},Nt.id)})})]})})]})})]})]}),e.jsx(Bs,{open:r,onOpenChange:a,children:e.jsxs(Fs,{children:[e.jsxs(qs,{children:[e.jsx($s,{children:i?"Edit Category":"Add Category"}),e.jsx(Ar,{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(re,{htmlFor:"categoryName",children:"Name"}),e.jsx(we,{id:"categoryName",value:o,onChange:Nt=>c(Nt.target.value),placeholder:"e.g., Templates, Resources"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{htmlFor:"categoryDescription",children:"Description"}),e.jsx(Ws,{id:"categoryDescription",value:d,onChange:Nt=>u(Nt.target.value),placeholder:"Optional description..."})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{htmlFor:"categoryIcon",children:"Icon (emoji)"}),e.jsx(we,{id:"categoryIcon",value:h,onChange:Nt=>m(Nt.target.value),placeholder:"e.g., 📄, 🎁"})]})]}),e.jsxs(Cr,{children:[e.jsx(B,{variant:"outline",onClick:()=>a(!1),children:"Cancel"}),e.jsx(B,{onClick:Ct,disabled:Xe.isPending||$e.isPending,children:Xe.isPending||$e.isPending?"Saving...":"Save"})]})]})}),e.jsx(Bs,{open:y,onOpenChange:x,children:e.jsxs(Fs,{className:"max-w-lg max-h-[90vh] overflow-y-auto",children:[e.jsxs(qs,{children:[e.jsx($s,{children:_?"Edit Item":"Add Item"}),e.jsx(Ar,{children:_?"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(re,{htmlFor:"itemName",children:"Name *"}),e.jsx(we,{id:"itemName",value:k,onChange:Nt=>A(Nt.target.value),placeholder:"e.g., Premium Template Pack"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{htmlFor:"itemDescription",children:"Description"}),e.jsx(Ws,{id:"itemDescription",value:T,onChange:Nt=>P(Nt.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(re,{htmlFor:"itemCategory",children:"Category"}),e.jsxs(Ns,{value:I||"none",onValueChange:Nt=>M(Nt==="none"?null:Nt),children:[e.jsx(ws,{children:e.jsx(ks,{placeholder:"Select category"})}),e.jsxs(js,{children:[e.jsx(nt,{value:"none",children:"No category"}),Me==null?void 0:Me.map(Nt=>e.jsxs(nt,{value:Nt.id,children:[Nt.icon&&`${Nt.icon} `,Nt.name]},Nt.id))]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{htmlFor:"itemPointsCost",children:"Points Cost *"}),e.jsx(we,{id:"itemPointsCost",type:"number",min:"0",value:L,onChange:Nt=>z(Nt.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(re,{htmlFor:"itemType",children:"Type"}),e.jsxs(Ns,{value:$,onValueChange:V,children:[e.jsx(ws,{children:e.jsx(ks,{})}),e.jsxs(js,{children:[e.jsx(nt,{value:"file",children:"File Download"}),e.jsx(nt,{value:"link",children:"External Link"})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{htmlFor:"itemMaxQuantity",children:"Max Quantity"}),e.jsx(we,{id:"itemMaxQuantity",type:"number",min:"1",value:ne,onChange:Nt=>me(Nt.target.value),placeholder:"Leave empty for unlimited"})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{children:"File / Link URL"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(we,{value:W,onChange:Nt=>G(Nt.target.value),placeholder:$==="file"?"Upload a file or paste URL":"Paste external link"}),$==="file"&&e.jsxs(e.Fragment,{children:[e.jsx(B,{type:"button",variant:"outline",size:"icon",onClick:()=>{var Nt;return(Nt=Se.current)==null?void 0:Nt.click()},disabled:xe,children:e.jsx(ni,{className:"h-4 w-4"})}),e.jsx("input",{ref:Se,type:"file",className:"hidden",onChange:Nt=>{var Ys;const ms=(Ys=Nt.target.files)==null?void 0:Ys[0];ms&&Xs(ms,"file")}})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{children:"Preview Image"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(we,{value:X,onChange:Nt=>te(Nt.target.value),placeholder:"Upload an image or paste URL"}),e.jsx(B,{type:"button",variant:"outline",size:"icon",onClick:()=>{var Nt;return(Nt=Ie.current)==null?void 0:Nt.click()},disabled:ge,children:e.jsx(pc,{className:"h-4 w-4"})}),e.jsx("input",{ref:Ie,type:"file",accept:"image/*",className:"hidden",onChange:Nt=>{var Ys;const ms=(Ys=Nt.target.files)==null?void 0:Ys[0];ms&&Xs(ms,"preview")}})]}),X&&e.jsx("img",{src:X,alt:"Preview",className:"mt-2 h-24 rounded object-cover"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(zn,{id:"itemIsActive",checked:ue,onCheckedChange:ce}),e.jsx(re,{htmlFor:"itemIsActive",children:"Active (visible to agents)"})]})]}),e.jsxs(Cr,{children:[e.jsx(B,{variant:"outline",onClick:()=>x(!1),children:"Cancel"}),e.jsx(B,{onClick:zs,disabled:Je.isPending||Ke.isPending,children:Je.isPending||Ke.isPending?"Saving...":"Save"})]})]})}),e.jsx(Fl,{open:!!f,onOpenChange:()=>g(null),children:e.jsxs(kl,{children:[e.jsxs(Sl,{children:[e.jsx(Al,{children:"Delete Category"}),e.jsx(Tl,{children:"Are you sure you want to delete this category? Items in this category will become uncategorized."})]}),e.jsxs(Cl,{children:[e.jsx(El,{children:"Cancel"}),e.jsx(wl,{onClick:Yt,className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:"Delete"})]})]})}),e.jsx(Fl,{open:!!ae,onOpenChange:()=>he(null),children:e.jsxs(kl,{children:[e.jsxs(Sl,{children:[e.jsx(Al,{children:"Delete Item"}),e.jsx(Tl,{children:"Are you sure you want to delete this item? This action cannot be undone."})]}),e.jsxs(Cl,{children:[e.jsx(El,{children:"Cancel"}),e.jsx(wl,{onClick:Vt,className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:"Delete"})]})]})}),t==="point-settings"&&e.jsxs(_e,{className:"mt-4",children:[e.jsx(zt,{children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(sc,{className:"h-5 w-5"}),e.jsxs("div",{children:[e.jsx(qt,{children:"Point Reward Settings"}),e.jsx(_r,{children:"Configure how many points agents earn for various actions. Adjust these values to run double-points promotions."})]})]})}),e.jsx(De,{children:!Fe||Fe.length===0?e.jsxs("div",{className:"text-center py-8 text-muted-foreground",children:[e.jsx(sc,{className:"h-12 w-12 mx-auto mb-4 opacity-50"}),e.jsx("p",{children:"No point settings configured."})]}):e.jsxs(Oa,{children:[e.jsx(Fa,{children:e.jsxs(un,{children:[e.jsx(Mt,{children:"Action"}),e.jsx(Mt,{children:"Description"}),e.jsx(Mt,{className:"text-center w-32",children:"Points"}),e.jsx(Mt,{className:"text-right w-24",children:"Save"})]})}),e.jsx(za,{children:Fe.map(Nt=>e.jsxs(un,{children:[e.jsx(gt,{children:e.jsx("p",{className:"font-medium",children:Nt.action_name})}),e.jsx(gt,{children:e.jsx("p",{className:"text-sm text-muted-foreground",children:Nt.description})}),e.jsx(gt,{className:"text-center",children:e.jsx(we,{type:"number",min:"0",className:"w-20 mx-auto text-center",value:Ze[Nt.id]??Nt.points.toString(),onChange:ms=>ht(Ys=>({...Ys,[Nt.id]:ms.target.value}))})}),e.jsx(gt,{className:"text-right",children:e.jsx(B,{size:"sm",variant:"outline",disabled:Ze[Nt.id]===void 0||Ze[Nt.id]===Nt.points.toString()||rt.isPending,onClick:()=>At(Nt.id,Nt.points),children:e.jsx(Kl,{className:"h-4 w-4"})})})]},Nt.id))})]})})]})]})}const Zft=()=>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"})]}),Xft=[{value:"template",label:"Templates"},{value:"brand",label:"Brand Assets"},{value:"listing",label:"Listing Assets"},{value:"social",label:"Social Media"},{value:"general",label:"General"}];function nSn(){const s=as(),[t,n]=N.useState(!1),[r,a]=N.useState(!1),[i,l]=N.useState(!1),[o,c]=N.useState({brokerage_id:"",folder_id:"",folder_name:"",folder_type:"template",description:""}),{data:d,isLoading:u}=mt({queryKey:["canva-integration"],queryFn:async()=>{const{data:b,error:k}=await H.from("canva_integration").select("*").eq("is_active",!0).maybeSingle();if(k)throw k;return b}}),{data:h}=mt({queryKey:["brokerages-list"],queryFn:async()=>{const{data:b,error:k}=await H.from("brokerages").select("id, name").order("name");if(k)throw k;return b}}),{data:m}=mt({queryKey:["canva-brokerage-folders"],queryFn:async()=>{const{data:b,error:k}=await H.from("canva_brokerage_folders").select("*, brokerages(name)").order("sort_order");if(k)throw k;return b}}),f=async()=>{var b;n(!0);try{const{data:k}=await H.auth.getSession(),A=(b=k==null?void 0:k.session)==null?void 0:b.access_token;if(!A)throw new Error("Not authenticated");const I=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/canva-oauth",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${A}`,apikey:"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6InJlbHplamlzd25vdGlramd2amh6Iiwicm9sZSI6ImFub24iLCJpYXQiOjE3NjE5NTAzNDQsImV4cCI6MjA3NzUyNjM0NH0.dzIkIr_oFSbFE3oWS0ktIr83iKHHkZxt40Gc7SpC_mM"},body:JSON.stringify({action:"get_auth_url"})}),M=await I.json();if(!I.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 L=window.open(M.authUrl,"canva-oauth","width=600,height=700,scrollbars=yes,resizable=yes");if(!L){ie.error("Popup was blocked. Please allow popups for this site and try again."),n(!1);return}const z=V=>{var W,G;V.origin===window.location.origin&&(((W=V.data)==null?void 0:W.type)==="canva-oauth-success"?(window.removeEventListener("message",z),ie.success("Canva connected successfully!"),s.invalidateQueries({queryKey:["canva-integration"]}),n(!1)):((G=V.data)==null?void 0:G.type)==="canva-oauth-error"&&(window.removeEventListener("message",z),ie.error("Canva connection failed: "+(V.data.error||"Unknown error")),n(!1)))};window.addEventListener("message",z);const $=setInterval(()=>{L.closed&&(clearInterval($),window.removeEventListener("message",z),s.invalidateQueries({queryKey:["canva-integration"]}),n(!1))},500)}else throw new Error("Failed to get authorization URL")}catch(k){console.error("Canva connect error:",k);const A=(k==null?void 0:k.message)||"";A.includes("CANVA_CLIENT_ID")?ie.error("Canva app credentials not configured yet."):ie.error(A||"Failed to start Canva connection"),n(!1)}},g=_t({mutationFn:async b=>{var L;const{data:k}=await H.auth.getSession(),A=(L=k==null?void 0:k.session)==null?void 0:L.access_token;if(!A)throw new Error("Not authenticated");const I=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/canva-oauth",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${A}`,apikey:"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6InJlbHplamlzd25vdGlramd2amh6Iiwicm9sZSI6ImFub24iLCJpYXQiOjE3NjE5NTAzNDQsImV4cCI6MjA3NzUyNjM0NH0.dzIkIr_oFSbFE3oWS0ktIr83iKHHkZxt40Gc7SpC_mM"},body:JSON.stringify({action:"disconnect",integrationId:b})}),M=await I.json();if(!I.ok||M!=null&&M.error)throw new Error((M==null?void 0:M.error)||"Failed to disconnect")},onSuccess:()=>{s.invalidateQueries({queryKey:["canva-integration"]}),ie.success("Canva disconnected")},onError:b=>{ie.error(b.message||"Failed to disconnect Canva")}}),y=_t({mutationFn:async b=>{const{error:k}=await H.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(k)throw k},onSuccess:()=>{s.invalidateQueries({queryKey:["canva-brokerage-folders"]}),ie.success("Folder added"),l(!1),c({brokerage_id:"",folder_id:"",folder_name:"",folder_type:"template",description:""})},onError:()=>ie.error("Failed to add folder")}),x=_t({mutationFn:async b=>{const{error:k}=await H.from("canva_brokerage_folders").delete().eq("id",b);if(k)throw k},onSuccess:()=>{s.invalidateQueries({queryKey:["canva-brokerage-folders"]}),ie.success("Folder removed")},onError:()=>ie.error("Failed to remove folder")}),_=!!d;return e.jsxs(e.Fragment,{children:[e.jsxs(_e,{children:[e.jsx(zt,{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(Zft,{})}),e.jsxs("div",{children:[e.jsxs(qt,{className:"text-lg flex items-center gap-2",children:["Canva Connect",_&&e.jsx(We,{variant:"default",className:"text-xs",children:"Connected"}),e.jsx(We,{variant:"outline",className:"text-xs",children:"Admin Only"})]}),e.jsx(_r,{children:"Auto-share brokerage asset folders with agents when they connect their Canva accounts."})]})]})})}),e.jsx(De,{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(Po,{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(Po,{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(Po,{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"})]}),_?e.jsxs("div",{className:"space-y-3 mt-4",children:[e.jsxs("div",{className:"flex items-center justify-between p-3 rounded-lg border",children:[e.jsxs("div",{children:[e.jsx("p",{className:"font-medium text-sm",children:d.canva_team_id?`Team: ${d.canva_team_id}`:"Canva Account"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:d.expires_at?`Token expires ${new Date(d.expires_at).toLocaleDateString()}`:"Platform integration active"})]}),e.jsxs(Fl,{children:[e.jsx(Gf,{asChild:!0,children:e.jsx(B,{variant:"ghost",size:"icon",className:"text-destructive hover:text-destructive",children:e.jsx(qn,{className:"h-4 w-4"})})}),e.jsxs(kl,{children:[e.jsxs(Sl,{children:[e.jsx(Al,{children:"Disconnect Canva?"}),e.jsx(Tl,{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(Cl,{children:[e.jsx(El,{children:"Cancel"}),e.jsx(wl,{onClick:()=>g.mutate(d.id),className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:"Disconnect"})]})]})]})]}),e.jsxs("div",{className:"border rounded-lg overflow-hidden",children:[e.jsxs("button",{onClick:()=>a(!r),className:"w-full flex items-center justify-between p-3 text-sm font-medium hover:bg-muted transition-colors",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(H0,{className:"h-4 w-4 text-primary"}),"Brokerage Folder Mappings",m&&m.length>0&&e.jsx(We,{variant:"secondary",className:"text-xs",children:m.length})]}),r?e.jsx(zy,{className:"h-4 w-4"}):e.jsx(Xo,{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 k,A;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(We,{variant:"outline",className:"text-xs shrink-0",children:((k=Xft.find(T=>T.value===b.folder_type))==null?void 0:k.label)||b.folder_type})]}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[(A=b.brokerages)==null?void 0:A.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:()=>x.mutate(b.id),children:e.jsx(hr,{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(nn,{className:"h-3.5 w-3.5"}),"Add Folder Mapping"]})]})]})]}):e.jsxs(B,{className:"mt-4",onClick:f,disabled:t||u,children:[t?e.jsx(oo,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx("div",{className:"mr-2",children:e.jsx(Zft,{})}),"Connect Canva",e.jsx(vi,{className:"h-4 w-4 ml-2"})]})]})})]}),e.jsx(Bs,{open:i,onOpenChange:l,children:e.jsxs(Fs,{children:[e.jsx(qs,{children:e.jsx($s,{children:"Add Brokerage Folder Mapping"})}),e.jsxs("div",{className:"space-y-4 py-2",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(re,{children:"Brokerage"}),e.jsxs(Ns,{value:o.brokerage_id,onValueChange:b=>c(k=>({...k,brokerage_id:b})),children:[e.jsx(ws,{children:e.jsx(ks,{placeholder:"Select a brokerage…"})}),e.jsx(js,{children:h==null?void 0:h.map(b=>e.jsx(nt,{value:b.id,children:b.name},b.id))})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(re,{children:"Canva Folder ID"}),e.jsx(we,{placeholder:"e.g. FABCdef123456",value:o.folder_id,onChange:b=>c(k=>({...k,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(re,{children:"Folder Display Name"}),e.jsx(we,{placeholder:"e.g. Brand Templates 2024",value:o.folder_name,onChange:b=>c(k=>({...k,folder_name:b.target.value}))})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(re,{children:"Folder Type"}),e.jsxs(Ns,{value:o.folder_type,onValueChange:b=>c(k=>({...k,folder_type:b})),children:[e.jsx(ws,{children:e.jsx(ks,{})}),e.jsx(js,{children:Xft.map(b=>e.jsx(nt,{value:b.value,children:b.label},b.value))})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs(re,{children:["Description ",e.jsx("span",{className:"text-muted-foreground",children:"(optional)"})]}),e.jsx(we,{placeholder:"What's in this folder?",value:o.description,onChange:b=>c(k=>({...k,description:b.target.value}))})]})]}),e.jsxs(Cr,{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(oo,{className:"h-4 w-4 mr-2 animate-spin"}):null,"Add Folder"]})]})]})})]})}function rSn(){const s=tr();return e.jsx(Qs,{children:e.jsxs("div",{className:"space-y-6 p-4 md:p-8",children:[e.jsx(Uh,{title:"Integrations",description:"Manage platform-level service connections"}),e.jsxs(_e,{className:"p-6 flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsx("div",{className:"p-3 rounded-lg bg-primary/10",children:e.jsx(Md,{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(vi,{className:"h-4 w-4 ml-1"})]})]}),e.jsx(nSn,{}),e.jsx(e9t,{})]})})}const Qft=s=>{const t="h-4 w-4";return s==="facebook"?e.jsx(Kf,{className:t}):s==="instagram"?e.jsx(dm,{className:t}):s==="linkedin"?e.jsx(W0,{className:t}):s==="google"?e.jsx(mn,{className:t}):null},aSn=s=>s?new Intl.DateTimeFormat("en-US",{timeZone:"America/New_York",year:"numeric",month:"short",day:"numeric"}).format(new Date(s)):"—";function iSn(){const[s,t]=N.useState([]),[n,r]=N.useState(!0),[a,i]=N.useState(""),[l,o]=N.useState("all");N.useEffect(()=>{(async()=>{r(!0);const{data:m,error:f}=await H.rpc("admin_get_social_connections");if(f){ie.error(f.message),r(!1);return}t(m||[]),r(!1)})()},[]);const c=N.useMemo(()=>{const m=a.trim().toLowerCase();return s.filter(f=>l!=="all"&&f.platform!==l?!1:m?(f.user_name||"").toLowerCase().includes(m)||(f.user_email||"").toLowerCase().includes(m)||(f.page_name||"").toLowerCase().includes(m)||(f.platform_username||"").toLowerCase().includes(m):!0)},[s,a,l]),d=N.useMemo(()=>{const m=new Map;return s.forEach(f=>{const g=m.get(f.user_id)||{name:f.user_name,email:f.user_email,platforms:new Set,count:0};g.platforms.add(f.platform),g.count+=1,m.set(f.user_id,g)}),Array.from(m.entries()).map(([f,g])=>({user_id:f,...g}))},[s]),u=N.useMemo(()=>{const m=new Map;return s.forEach(f=>m.set(f.platform,(m.get(f.platform)||0)+1)),{uniqueUsers:d.length,totalConnections:s.length,byPlatform:Array.from(m.entries())}},[s,d]),h=m=>m&&new Date(m).getTime()e.jsxs(_e,{className:"p-4",children:[e.jsxs("div",{className:"text-sm text-muted-foreground capitalize flex items-center gap-2",children:[Qft(m)," ",m]}),e.jsx("div",{className:"text-2xl font-bold",children:f})]},m))]}),e.jsxs("div",{className:"flex flex-col md:flex-row gap-3",children:[e.jsx(we,{placeholder:"Search by user, email, page, or handle…",value:a,onChange:m=>i(m.target.value),className:"md:max-w-md"}),e.jsxs(Ns,{value:l,onValueChange:o,children:[e.jsx(ws,{className:"md:w-48",children:e.jsx(ks,{placeholder:"All platforms"})}),e.jsxs(js,{children:[e.jsx(nt,{value:"all",children:"All platforms"}),e.jsx(nt,{value:"facebook",children:"Facebook"}),e.jsx(nt,{value:"instagram",children:"Instagram"}),e.jsx(nt,{value:"linkedin",children:"LinkedIn"}),e.jsx(nt,{value:"google",children:"Google"})]})]})]}),e.jsx(_e,{children:n?e.jsx("div",{className:"flex items-center justify-center p-12",children:e.jsx(us,{className:"h-6 w-6 animate-spin text-muted-foreground"})}):e.jsxs(Oa,{children:[e.jsx(Fa,{children:e.jsxs(un,{children:[e.jsx(Mt,{children:"User"}),e.jsx(Mt,{children:"Platform"}),e.jsx(Mt,{children:"Page / Account"}),e.jsx(Mt,{children:"Status"}),e.jsx(Mt,{children:"Connected"})]})}),e.jsx(za,{children:c.length===0?e.jsx(un,{children:e.jsx(gt,{colSpan:5,className:"text-center text-muted-foreground py-8",children:"No connections found."})}):c.map(m=>{const f=h(m.token_expires_at);return e.jsxs(un,{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:[Qft(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?f?e.jsxs(We,{variant:"destructive",className:"gap-1",children:[e.jsx(Uo,{className:"h-3 w-3"})," Expired"]}):e.jsx(We,{children:"Active"}):e.jsx(We,{variant:"secondary",children:"Inactive"})}),e.jsx(gt,{className:"text-sm text-muted-foreground",children:aSn(m.created_at)})]},m.id)})})]})})]})})}const oSn={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 pH(s,t=18,n=10){return s.length<=t+n+3?s:`${s.slice(0,t)}…${s.slice(-n)}`}function lSn(){var $,V,W,G,X;const s=as(),[t,n]=N.useState("Test Push"),[r,a]=N.useState("Testing web push notification"),[i,l]=N.useState("/community"),[o,c]=N.useState(!1),[d,u]=N.useState(!1),[h,m]=N.useState({isSupported:typeof window<"u"&&"serviceWorker"in navigator&&"PushManager"in window}),[f,g]=N.useState(null),[y,x]=N.useState(null),{data:_,isLoading:b}=mt({queryKey:["push-notification-settings"],queryFn:async()=>{const{data:te,error:ne}=await H.from("push_notification_settings").select("*").order("setting_key");if(ne)throw ne;return te}}),{data:k,isLoading:A}=mt({queryKey:["push-subscription-stats"],queryFn:async()=>{const{count:te,error:ne}=await H.from("push_subscriptions").select("*",{count:"exact",head:!0});if(ne)throw ne;return{totalSubscriptions:te||0}}}),T=_t({mutationFn:async({settingKey:te,isEnabled:ne})=>{const{error:me}=await H.from("push_notification_settings").update({is_enabled:ne}).eq("setting_key",te);if(me)throw me},onSuccess:()=>{s.invalidateQueries({queryKey:["push-notification-settings"]}),ie.success("Notification setting updated")},onError:te=>{ie.error("Failed to update setting: "+te.message)}}),P=N.useMemo(()=>{var te,ne;return h.isSupported?`perm=${h.permission??"unknown"} · controller=${h.controllerPresent?"yes":"no"} · sw=${((te=h.serviceWorker)==null?void 0:te.activeState)??"unknown"} · sub=${(ne=h.subscription)!=null&&ne.endpoint?"yes":"no"}`:"Push not supported in this browser."},[h]);N.useEffect(()=>{let te=!0;const ne=async()=>{var ae,he,xe,ve,ge,be,Se;const ue="serviceWorker"in navigator&&"PushManager"in window,ce={isSupported:ue,permission:typeof Notification<"u"?Notification.permission:void 0,controllerPresent:!!((ae=navigator.serviceWorker)!=null&&ae.controller)};if(!ue){te&&m(ce);return}try{const{data:Ie,error:Me}=await H.functions.invoke("get-vapid-public-key",{body:{}});if(Me)throw Me;ce.vapidPublicKey=Ie==null?void 0:Ie.vapidPublicKey;const Be=(await navigator.serviceWorker.getRegistrations()).find(Ne=>{var Ce,Fe,Ae;return(((Ce=Ne.active)==null?void 0:Ce.scriptURL)||((Fe=Ne.waiting)==null?void 0:Fe.scriptURL)||((Ae=Ne.installing)==null?void 0:Ae.scriptURL)||"").includes("/sw.js")});if(Be){ce.pushWorkerScriptUrl=((he=Be.active)==null?void 0:he.scriptURL)||((xe=Be.waiting)==null?void 0:xe.scriptURL)||((ve=Be.installing)==null?void 0:ve.scriptURL),ce.serviceWorker={scope:Be.scope,activeState:(ge=Be.active)==null?void 0:ge.state};const Ne=await Be.pushManager.getSubscription();if(Ne){const Ge=Ne.toJSON();ce.subscription={endpoint:Ge.endpoint,p256dh:(be=Ge.keys)==null?void 0:be.p256dh,auth:(Se=Ge.keys)==null?void 0:Se.auth}}}}catch(Ie){ce.error=(Ie==null?void 0:Ie.message)||String(Ie)}te&&m(ce)};ne();const me=window.setInterval(ne,4e3);return()=>{te=!1,window.clearInterval(me)}},[]);const I=async()=>{if(typeof Notification>"u"){ie.error("Notifications API not available in this browser.");return}try{if(Notification.permission!=="granted"&&await Notification.requestPermission()!=="granted"){ie.error("Notification permission not granted.");return}new Notification("Local notification test",{body:"If you see this, OS/browser notifications can display."}),ie.success("Triggered a local notification (not push).")}catch(te){ie.error(`Local notification failed: ${(te==null?void 0:te.message)||String(te)}`)}},M=async()=>{c(!0),g(null);try{const{data:te,error:ne}=await H.functions.invoke("send-push-notification",{body:{title:t,body:r,url:i}});if(ne)throw ne;g({sent:te==null?void 0:te.sent,failed:te==null?void 0:te.failed,expiredCleaned:te==null?void 0:te.expiredCleaned,vapidPublicKey:te==null?void 0:te.vapidPublicKey}),(te==null?void 0:te.sent)>0?ie.success(`Test notification sent to ${te.sent} subscriber(s)`):(te==null?void 0:te.failed)>0?ie.warning(`Notification failed for ${te.failed} subscriber(s). ${te.expired||0} expired subscriptions cleaned up.`):ie.info("No active subscriptions to send to")}catch(te){console.error("Error sending test notification:",te),g({error:(te==null?void 0:te.message)||String(te)}),ie.error("Failed to send test notification: "+(te.message||"Unknown error"))}finally{c(!1)}},L=async()=>{u(!0),x(null);try{const{data:te,error:ne}=await H.functions.invoke("generate-vapid-keys",{body:{}});if(ne)throw ne;const me=te==null?void 0:te.publicKey,ue=te==null?void 0:te.privateKey;if(!me||!ue)throw new Error("generate-vapid-keys did not return keys");x({publicKey:me,privateKey:ue}),ie.success("Generated new VAPID keys. Update backend secrets, then clear + re-subscribe.")}catch(te){console.error("Error generating VAPID keys:",te),ie.error("Failed to generate VAPID keys: "+((te==null?void 0:te.message)||"Unknown error"))}finally{u(!1)}},z=_t({mutationFn:async()=>{const{error:te}=await H.from("push_subscriptions").delete().neq("id","00000000-0000-0000-0000-000000000000");if(te)throw te},onSuccess:()=>{ie.success("All subscriptions cleared. Users will need to re-enable notifications."),s.invalidateQueries({queryKey:["push-subscription-stats"]})},onError:te=>{ie.error("Failed to clear subscriptions: "+te.message)}});return e.jsx(Qs,{title:"Notification Settings",children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(Uh,{title:"Notification Settings",description:"Manage push notifications and test the notification system"}),e.jsxs(_e,{children:[e.jsxs(zt,{children:[e.jsxs(qt,{className:"flex items-center gap-2",children:[e.jsx(Yn,{className:"h-5 w-5"}),"Push Notification Subscribers"]}),e.jsx(_r,{children:"Current active push notification subscriptions"})]}),e.jsx(De,{children:e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsx("div",{className:"text-4xl font-bold",children:A?"...":(k==null?void 0:k.totalSubscriptions)||0}),e.jsx("div",{className:"text-sm text-muted-foreground",children:"active subscriptions"})]})})]}),e.jsxs(_e,{children:[e.jsxs(zt,{children:[e.jsxs(qt,{className:"flex items-center gap-2",children:[e.jsx(sc,{className:"h-5 w-5"}),"Notification Types"]}),e.jsx(_r,{children:"Control which types of push notifications are sent to users"})]}),e.jsx(De,{children:b?e.jsx("div",{className:"text-sm text-muted-foreground",children:"Loading settings..."}):e.jsx("div",{className:"space-y-4",children:_==null?void 0:_.map(te=>{const ne=oSn[te.setting_key]||{label:te.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:ne.icon}),e.jsxs("div",{children:[e.jsx("div",{className:"font-medium",children:ne.label}),e.jsx("div",{className:"text-sm text-muted-foreground",children:te.description})]})]}),e.jsx(zn,{checked:te.is_enabled,onCheckedChange:me=>T.mutate({settingKey:te.setting_key,isEnabled:me}),disabled:T.isPending})]},te.id)})})})]}),e.jsxs(_e,{children:[e.jsxs(zt,{children:[e.jsxs(qt,{className:"flex items-center gap-2",children:[e.jsx(yg,{className:"h-5 w-5"}),"Send Test Notification"]}),e.jsx(_r,{children:"Send a test push notification to all subscribed users"})]}),e.jsxs(De,{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:P}),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?pH(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: ",($=h.serviceWorker)!=null&&$.scope?pH(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: ",(W=h.subscription)!=null&&W.endpoint?pH(h.subscription.endpoint,40,12):"none"]}),e.jsxs("div",{children:["p256dh: ",(G=h.subscription)!=null&&G.p256dh?pH(h.subscription.p256dh,22,10):"none"]}),e.jsxs("div",{children:["auth: ",(X=h.subscription)!=null&&X.auth?pH(h.subscription.auth,22,10):"none"]})]})]})]}),e.jsxs("div",{className:"mt-3 flex flex-wrap gap-2",children:[e.jsx(B,{variant:"outline",onClick:I,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(re,{htmlFor:"test-title",children:"Notification Title"}),e.jsx(we,{id:"test-title",value:t,onChange:te=>n(te.target.value),placeholder:"Enter notification title"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{htmlFor:"test-body",children:"Notification Body"}),e.jsx(Ws,{id:"test-body",value:r,onChange:te=>a(te.target.value),placeholder:"Enter notification message",rows:3})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{htmlFor:"test-url",children:"Click URL (optional)"}),e.jsx(we,{id:"test-url",value:i,onChange:te=>l(te.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(Rr,{className:"h-4 w-4 mr-2"}),o?"Sending...":"Send Test Notification"]}),f&&e.jsxs("div",{className:"rounded-md border bg-muted/30 p-3 text-sm",children:[e.jsx("div",{className:"font-medium",children:"Last send debug"}),f.error?e.jsxs("div",{className:"mt-1 text-destructive",children:["Error: ",f.error]}):e.jsxs("div",{className:"mt-1 space-y-1 text-muted-foreground",children:[e.jsxs("div",{children:["Result: ",f.sent??0," sent, ",f.failed??0," failed, ",f.expiredCleaned??0," expired cleaned"]}),f.vapidPublicKey?e.jsxs("div",{className:"break-all",children:["Backend VAPID public key: ",e.jsx("span",{className:"font-mono",children:f.vapidPublicKey})]}):e.jsx("div",{children:"Backend VAPID public key: (not returned)"})]})]})]})]}),e.jsxs(_e,{children:[e.jsxs(zt,{children:[e.jsxs(qt,{className:"flex items-center gap-2 text-destructive",children:[e.jsx(qn,{className:"h-5 w-5"}),"Subscription Maintenance"]}),e.jsx(_r,{children:"Clear all push subscriptions if VAPID keys were changed or subscriptions are invalid"})]}),e.jsxs(De,{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:()=>z.mutate(),disabled:z.isPending,children:[e.jsx(qn,{className:"h-4 w-4 mr-2"}),z.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:L,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 cSn(){const{toast:s}=Ci(),[t,n]=N.useState([]),[r,a]=N.useState({totalPresentations:0,totalViews:0,totalLeads:0,totalCtaClicks:0,agentsUsing:0}),[i,l]=N.useState(!0),{sortKey:o,sortDirection:c,handleSort:d,sortData:u}=JQ("presentation_count","desc"),h=u(t,{name:g=>{var y;return((y=g.name)==null?void 0:y.toLowerCase())||""},presentations:g=>g.presentation_count,views:g=>g.total_views,leads:g=>g.total_leads,cta_clicks:g=>g.total_cta_clicks,conversion:g=>g.total_views>0?g.total_leads/g.total_views*100:0});N.useEffect(()=>{m()},[]);const m=async()=>{try{l(!0);const{data:g,error:y}=await H.rpc("get_admin_presentation_stats");if(y)throw y;if(!g||g.length===0){l(!1);return}const x=g.map(T=>T.owner_user_id),{data:_,error:b}=await H.from("profiles").select("id, name, email, avatar_url").in("id",x);if(b)throw b;const k=new Map((_==null?void 0:_.map(T=>[T.id,T]))||[]),A=g.map(T=>{const P=k.get(T.owner_user_id);return{owner_user_id:T.owner_user_id,name:(P==null?void 0:P.name)||"Unknown",email:(P==null?void 0:P.email)||"",avatar_url:(P==null?void 0:P.avatar_url)||null,presentation_count:Number(T.presentation_count),total_views:Number(T.total_views),total_leads:Number(T.total_leads),total_cta_clicks:Number(T.total_cta_clicks)}});n(A),n(A),a({totalPresentations:A.reduce((T,P)=>T+P.presentation_count,0),totalViews:A.reduce((T,P)=>T+P.total_views,0),totalLeads:A.reduce((T,P)=>T+P.total_leads,0),totalCtaClicks:A.reduce((T,P)=>T+P.total_cta_clicks,0),agentsUsing:A.length})}catch(g){console.error("Error loading presentation stats:",g),s({title:"Error",description:"Failed to load presentation analytics",variant:"destructive"})}finally{l(!1)}},f=[{label:"Agents Using",value:r.agentsUsing,icon:Yn,color:"text-blue-600"},{label:"Total Presentations",value:r.totalPresentations,icon:ab,color:"text-violet-600"},{label:"Total Views",value:r.totalViews,icon:da,color:"text-emerald-600"},{label:"Total Leads",value:r.totalLeads,icon:Yl,color:"text-amber-600"},{label:"CTA Clicks",value:r.totalCtaClicks,icon:ru,color:"text-rose-600"}];return e.jsx(Qs,{title:"Presentation Analytics",children:e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl font-bold text-foreground",children:"Presentation Analytics"}),e.jsx("p",{className:"text-muted-foreground mt-1",children:"Track Smart Presentations usage and engagement across all agents"})]}),e.jsx("div",{className:"grid grid-cols-2 md:grid-cols-3 lg:grid-cols-5 gap-4",children:f.map(g=>e.jsxs(_e,{children:[e.jsxs(zt,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(qt,{className:"text-sm font-medium",children:g.label}),e.jsx(g.icon,{className:`h-4 w-4 ${g.color}`})]}),e.jsx(De,{children:i?e.jsx(xn,{className:"h-8 w-16"}):e.jsx("div",{className:"text-2xl font-bold",children:g.value.toLocaleString()})})]},g.label))}),e.jsxs(_e,{children:[e.jsx(zt,{children:e.jsxs(qt,{className:"flex items-center gap-2",children:[e.jsx(ml,{className:"h-5 w-5"}),"Agent Breakdown"]})}),e.jsx(De,{children:i?e.jsx("div",{className:"space-y-3",children:[...Array(5)].map((g,y)=>e.jsx(xn,{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(Oa,{children:[e.jsx(Fa,{children:e.jsxs(un,{children:[e.jsx(Hu,{sortKey:"name",currentSortKey:o,currentDirection:c,onSort:d,children:"Agent"}),e.jsx(Hu,{sortKey:"presentations",currentSortKey:o,currentDirection:c,onSort:d,className:"text-center",children:"Presentations"}),e.jsx(Hu,{sortKey:"views",currentSortKey:o,currentDirection:c,onSort:d,className:"text-center",children:"Views"}),e.jsx(Hu,{sortKey:"leads",currentSortKey:o,currentDirection:c,onSort:d,className:"text-center",children:"Leads"}),e.jsx(Hu,{sortKey:"cta_clicks",currentSortKey:o,currentDirection:c,onSort:d,className:"text-center",children:"CTA Clicks"}),e.jsx(Hu,{sortKey:"conversion",currentSortKey:o,currentDirection:c,onSort:d,className:"text-center",children:"Conversion"})]})}),e.jsx(za,{children:h.map(g=>{var x,_;const y=g.total_views>0?(g.total_leads/g.total_views*100).toFixed(1):"0.0";return e.jsxs(un,{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:g.avatar_url?e.jsx("img",{src:g.avatar_url,alt:"",className:"h-full w-full object-cover"}):e.jsx("span",{className:"text-xs font-medium text-muted-foreground",children:((_=(x=g.name)==null?void 0:x.charAt(0))==null?void 0:_.toUpperCase())||"?"})}),e.jsxs("div",{children:[e.jsx("div",{className:"font-medium text-sm",children:g.name}),e.jsx("div",{className:"text-xs text-muted-foreground",children:g.email})]})]})}),e.jsx(gt,{className:"text-center font-medium",children:g.presentation_count}),e.jsx(gt,{className:"text-center",children:g.total_views.toLocaleString()}),e.jsx(gt,{className:"text-center",children:g.total_leads>0?e.jsx(We,{variant:"secondary",children:g.total_leads}):e.jsx("span",{className:"text-muted-foreground",children:"0"})}),e.jsx(gt,{className:"text-center",children:g.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,"%"]})})]},g.owner_user_id)})})]})})]})]})})}const XPe=s=>s?new Intl.DateTimeFormat("en-US",{timeZone:"America/New_York",month:"short",day:"numeric",year:"numeric"}).format(new Date(s)):"—",dSn=s=>s==null?"—":`$${Number(s).toLocaleString("en-US",{maximumFractionDigits:0})}`;function uSn(){const{toast:s}=Ci(),[t,n]=N.useState(!0),[r,a]=N.useState([]),[i,l]=N.useState({}),[o,c]=N.useState("");N.useEffect(()=>{(async()=>{try{n(!0);const x=[],_=1e3;for(let A=0;;A+=_){const{data:T,error:P}=await H.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(A,A+_-1);if(P)throw P;if(x.push(...T??[]),!T||T.length<_)break}a(x);const b=Array.from(new Set(x.map(A=>A.owner_user_id))),k={};for(let A=0;A{k[P.id]={name:P.name??"Unknown",email:P.email??""}})}l(k)}catch(x){console.error(x),s({title:"Error",description:"Failed to load presentation data",variant:"destructive"})}finally{n(!1)}})()},[s]);const d=N.useMemo(()=>{const y=Date.now(),x=y-7*24*60*60*1e3,_=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()>=x).length,thisMonth:r.filter(b=>new Date(b.created_at).getTime()>=_).length}},[r]),u=N.useMemo(()=>{const y=new Map;return r.forEach(x=>{const _=i[x.owner_user_id],b=y.get(x.owner_user_id)??{user_id:x.owner_user_id,name:(_==null?void 0:_.name)??"Unknown",email:(_==null?void 0:_.email)??"",total:0,generated:0,last_activity:x.updated_at};b.total+=1,x.last_generated_at&&(b.generated+=1),new Date(x.updated_at)>new Date(b.last_activity)&&(b.last_activity=x.updated_at),y.set(x.owner_user_id,b)}),Array.from(y.values()).sort((x,_)=>_.total-x.total)},[r,i]),h=o.trim().toLowerCase(),m=h?u.filter(y=>y.name.toLowerCase().includes(h)||y.email.toLowerCase().includes(h)):u,f=h?r.filter(y=>{const x=i[y.owner_user_id];return(y.title??"").toLowerCase().includes(h)||(y.property_address_line1??"").toLowerCase().includes(h)||(y.city??"").toLowerCase().includes(h)||((x==null?void 0:x.name)??"").toLowerCase().includes(h)||((x==null?void 0:x.email)??"").toLowerCase().includes(h)}):r,g=[{label:"Total presentations",value:d.total,icon:Wr,sub:"All time"},{label:"Agents using it",value:d.agents,icon:Yn,sub:"Created at least one"},{label:"PDFs generated",value:d.generated,icon:Cn,sub:"Rendered at least once"},{label:"Created last 30 days",value:d.thisMonth,icon:df,sub:`${d.thisWeek} in last 7 days`}];return e.jsx(Qs,{title:"Listing Presentation Studio",children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(Uh,{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(xn,{className:"h-28 w-full"},y))}):e.jsx("div",{className:"grid gap-4 md:grid-cols-2 lg:grid-cols-4",children:g.map(y=>e.jsxs(_e,{children:[e.jsxs(zt,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(qt,{className:"text-sm font-medium",children:y.label}),e.jsx(y.icon,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(De,{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(Gr,{className:"absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground"}),e.jsx(we,{className:"pl-9",placeholder:"Search agents, addresses, titles...",value:o,onChange:y=>c(y.target.value)})]}),e.jsxs(ya,{defaultValue:"agents",className:"space-y-4",children:[e.jsxs(va,{children:[e.jsxs(ls,{value:"agents",children:["By agent (",m.length,")"]}),e.jsxs(ls,{value:"all",children:["All presentations (",f.length,")"]})]}),e.jsx(_s,{value:"agents",children:e.jsx(_e,{children:e.jsx(De,{className:"p-0",children:e.jsxs(Oa,{children:[e.jsx(Fa,{children:e.jsxs(un,{children:[e.jsx(Mt,{children:"Agent"}),e.jsx(Mt,{className:"text-right",children:"Presentations"}),e.jsx(Mt,{className:"text-right",children:"Generated"}),e.jsx(Mt,{children:"Last activity"})]})}),e.jsxs(za,{children:[m.map(y=>e.jsxs(un,{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:XPe(y.last_activity)})]},y.user_id)),!t&&m.length===0&&e.jsx(un,{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(_s,{value:"all",children:e.jsx(_e,{children:e.jsx(De,{className:"p-0",children:e.jsxs(Oa,{children:[e.jsx(Fa,{children:e.jsxs(un,{children:[e.jsx(Mt,{children:"Presentation"}),e.jsx(Mt,{children:"Agent"}),e.jsx(Mt,{children:"Property"}),e.jsx(Mt,{children:"Price"}),e.jsx(Mt,{children:"Status"}),e.jsx(Mt,{children:"Created"}),e.jsx(Mt,{children:"Last generated"})]})}),e.jsxs(za,{children:[f.slice(0,300).map(y=>{var x,_;return e.jsxs(un,{children:[e.jsx(gt,{className:"font-medium",children:y.title||"Untitled"}),e.jsxs(gt,{children:[e.jsx("div",{children:((x=i[y.owner_user_id])==null?void 0:x.name)??"Unknown"}),e.jsx("div",{className:"text-xs text-muted-foreground",children:((_=i[y.owner_user_id])==null?void 0:_.email)??""})]}),e.jsx(gt,{className:"text-sm",children:[y.property_address_line1,y.city,y.state].filter(Boolean).join(", ")||"—"}),e.jsx(gt,{children:dSn(y.list_price)}),e.jsx(gt,{children:e.jsx(We,{variant:y.last_generated_at?"default":"secondary",children:y.last_generated_at?"Generated":y.status||"Draft"})}),e.jsx(gt,{children:XPe(y.created_at)}),e.jsx(gt,{children:XPe(y.last_generated_at)})]},y.id)}),!t&&f.length===0&&e.jsx(un,{children:e.jsx(gt,{colSpan:7,className:"py-10 text-center text-muted-foreground",children:"No presentations found."})})]})]})})})})]})]})})}function hSn(){const{toast:s}=Ci(),[t,n]=N.useState([]),[r,a]=N.useState({totalOpenHouses:0,totalVisitors:0,totalLeads:0,activeOpenHouses:0,agentsUsing:0}),[i,l]=N.useState(!0);N.useEffect(()=>{o()},[]);const o=async()=>{try{l(!0);const{data:d,error:u}=await H.rpc("get_admin_guest_book_stats");if(u)throw u;if(!d||d.length===0){l(!1);return}const h=d.map(x=>x.agent_id),{data:m,error:f}=await H.from("profiles").select("id, name, email, avatar_url").in("id",h);if(f)throw f;const g=new Map((m==null?void 0:m.map(x=>[x.id,x]))||[]),y=d.map(x=>{const _=g.get(x.agent_id);return{agent_id:x.agent_id,name:(_==null?void 0:_.name)||"Unknown",email:(_==null?void 0:_.email)||"",avatar_url:(_==null?void 0:_.avatar_url)||null,open_house_count:Number(x.open_house_count),total_visitors:Number(x.total_visitors),total_leads:Number(x.total_leads),active_count:Number(x.active_count)}});y.sort((x,_)=>_.total_visitors-x.total_visitors),n(y),a({totalOpenHouses:y.reduce((x,_)=>x+_.open_house_count,0),totalVisitors:y.reduce((x,_)=>x+_.total_visitors,0),totalLeads:y.reduce((x,_)=>x+_.total_leads,0),activeOpenHouses:y.reduce((x,_)=>x+_.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:Yn,color:"text-blue-600"},{label:"Total Open Houses",value:r.totalOpenHouses,icon:_a,color:"text-violet-600"},{label:"Active Now",value:r.activeOpenHouses,icon:Po,color:"text-emerald-600"},{label:"Total Visitors",value:r.totalVisitors,icon:da,color:"text-amber-600"},{label:"Leads Created",value:r.totalLeads,icon:Yl,color:"text-rose-600"}];return e.jsx(Qs,{title:"Guest Book Analytics",children:e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl font-bold text-foreground",children:"Guest Book Analytics"}),e.jsx("p",{className:"text-muted-foreground mt-1",children:"Track open house sign-in usage and lead generation across all agents"})]}),e.jsx("div",{className:"grid grid-cols-2 md:grid-cols-3 lg:grid-cols-5 gap-4",children:c.map(d=>e.jsxs(_e,{children:[e.jsxs(zt,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(qt,{className:"text-sm font-medium",children:d.label}),e.jsx(d.icon,{className:`h-4 w-4 ${d.color}`})]}),e.jsx(De,{children:i?e.jsx(xn,{className:"h-8 w-16"}):e.jsx("div",{className:"text-2xl font-bold",children:d.value.toLocaleString()})})]},d.label))}),e.jsxs(_e,{children:[e.jsx(zt,{children:e.jsxs(qt,{className:"flex items-center gap-2",children:[e.jsx(ml,{className:"h-5 w-5"}),"Agent Breakdown"]})}),e.jsx(De,{children:i?e.jsx("div",{className:"space-y-3",children:[...Array(5)].map((d,u)=>e.jsx(xn,{className:"h-12 w-full"},u))}):t.length===0?e.jsx("p",{className:"text-muted-foreground text-center py-8",children:"No open houses created yet."}):e.jsxs(Oa,{children:[e.jsx(Fa,{children:e.jsxs(un,{children:[e.jsx(Mt,{children:"Agent"}),e.jsx(Mt,{className:"text-center",children:"Open Houses"}),e.jsx(Mt,{className:"text-center",children:"Active"}),e.jsx(Mt,{className:"text-center",children:"Visitors"}),e.jsx(Mt,{className:"text-center",children:"Leads"}),e.jsx(Mt,{className:"text-center",children:"Conversion"})]})}),e.jsx(za,{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(un,{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(We,{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(We,{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 mSn(){const[s]=$c(),t=tr(),[n,r]=N.useState("loading"),[a,i]=N.useState("Processing connection...");return N.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"),ie.error("Failed to connect: "+(d||c));return}if(!o){r("error"),i("No authorization code received"),ie.error("Failed to connect: No authorization code");return}try{const{data:h,error:m}=await H.functions.invoke("meta-oauth",{body:{action:"exchange_code",code:o,state:u}});if(h&&h.success===!1)throw new Error(h.error||"Failed to connect accounts");if(m){let f=m.message||"Failed to connect accounts";try{const g=m.context;if(g&&typeof g.json=="function"){const y=await g.json();y!=null&&y.error&&(f=y.error)}}catch{}throw new Error(f)}if(h!=null&&h.success)r("success"),i(h.message||"Accounts connected successfully!"),ie.success(h.message||"Social accounts connected!");else throw new Error((h==null?void 0:h.error)||"Failed to connect accounts")}catch(h){console.error("Callback error:",h),r("error"),i(h.message||"Failed to complete connection"),ie.error(h.message||"Failed to connect accounts")}})()},[s]),e.jsx("div",{className:"flex min-h-screen items-center justify-center bg-background p-4",children:e.jsxs(_e,{className:"w-full max-w-md",children:[e.jsxs(zt,{className:"text-center",children:[e.jsxs("div",{className:"mx-auto mb-4",children:[n==="loading"&&e.jsx(us,{className:"h-12 w-12 animate-spin text-primary"}),n==="success"&&e.jsx(Po,{className:"h-12 w-12 text-green-500"}),n==="error"&&e.jsx(Nu,{className:"h-12 w-12 text-destructive"})]}),e.jsxs(qt,{children:[n==="loading"&&"Connecting...",n==="success"&&"Connected!",n==="error"&&"Connection Failed"]}),e.jsx(_r,{children:a})]}),e.jsx(De,{className:"flex justify-center",children:e.jsx(B,{onClick:()=>t("/admin/integrations"),children:n==="success"?"View Integrations":"Back to Integrations"})})]})})}function pSn(){const s=as(),[t,n]=N.useState(""),[r,a]=N.useState(""),[i,l]=N.useState([]),o=N.useRef(null),{data:c,isLoading:d}=mt({queryKey:["prospect-emails"],queryFn:async()=>{const{data:b,error:k}=await H.from("prospect_emails").select("*").order("sent_at",{ascending:!1});if(k)throw k;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=_t({mutationFn:async b=>{const{data:k,error:A}=await H.functions.invoke("send-prospect-email",{body:{emails:b}});if(A)throw A;return k},onSuccess:b=>{s.invalidateQueries({queryKey:["prospect-emails"]}),ie.success(`${b.sent} email${b.sent>1?"s":""} sent successfully!`),n(""),a(""),l([])},onError:b=>{ie.error("Failed to send: "+b.message)}}),f=_t({mutationFn:async()=>{var T,P;const{data:{user:b}}=await H.auth.getUser();if(!(b!=null&&b.email))throw new Error("Could not get your email");const{data:k,error:A}=await H.functions.invoke("send-prospect-email",{body:{emails:[{email:b.email,first_name:(P=(T=b.user_metadata)==null?void 0:T.name)==null?void 0:P.split(" ")[0]}],test_mode:!0}});if(A)throw A;return k},onSuccess:()=>{ie.success("Test email sent to your inbox!")},onError:b=>{ie.error("Failed to send test: "+b.message)}}),g=_t({mutationFn:async()=>{const{data:b,error:k}=await H.functions.invoke("send-prospect-email",{body:{mode:"live_leads"}});if(k)throw k;return b},onSuccess:b=>{s.invalidateQueries({queryKey:["prospect-emails"]}),ie.success(`${b.sent} live lead invite${b.sent===1?"":"s"} sent!`)},onError:b=>{ie.error("Failed to send live lead invites: "+b.message)}}),y=()=>{if(!t.trim()){ie.error("Please enter an email address");return}if(c==null?void 0:c.find(k=>k.email.toLowerCase()===t.trim().toLowerCase())){ie.error("This email has already been prospected");return}m.mutate([{email:t.trim(),first_name:r.trim()||void 0}])},x=b=>{var T;const k=(T=b.target.files)==null?void 0:T[0];if(!k)return;const A=new FileReader;A.onload=P=>{var $,V;const M=(($=P.target)==null?void 0:$.result).split(` `).filter(W=>W.trim()),L=[],z=(V=M[0])!=null&&V.toLowerCase().includes("email")?1:0;for(let W=z;Wne.trim().replace(/"/g,"")),X=G[0],te=G[1];X&&X.includes("@")&&L.push({email:X,first_name:te||void 0})}l(L),ie.success(`${L.length} entries loaded from CSV`)},A.readAsText(k),o.current&&(o.current.value="")},_=()=>{if(i.length===0){ie.error("No entries to send");return}const b=new Set((c==null?void 0:c.map(A=>A.email.toLowerCase()))||[]),k=i.filter(A=>!b.has(A.email.toLowerCase()));if(k.length===0){ie.error("All emails have already been prospected");return}k.length0&&e.jsxs(_e,{className:"border-red-200/50 bg-red-500/[0.02]",children:[e.jsxs(zt,{children:[e.jsxs(qt,{className:"flex items-center gap-2",children:[e.jsx(Y0,{className:"h-5 w-5 text-red-600"}),"Live Event Leads",e.jsx(We,{variant:"secondary",className:"ml-2",children:h.liveLeads})]}),e.jsx(_r,{children:"These agents registered on a LevelUp Live page but haven't received a free trial invite yet."})]}),e.jsx(De,{children:e.jsxs(B,{onClick:()=>g.mutate(),disabled:g.isPending,className:"gap-2",children:[g.isPending?e.jsx(us,{className:"h-4 w-4 animate-spin"}):e.jsx(Rr,{className:"h-4 w-4"}),"Send free trial invite to all live leads"]})})]}),e.jsxs(_e,{children:[e.jsxs(zt,{children:[e.jsxs(qt,{className:"flex items-center gap-2",children:[e.jsx(iu,{className:"h-5 w-5"}),"Send Prospect Email"]}),e.jsxs(_r,{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:()=>f.mutate(),disabled:f.isPending,className:"gap-2 ml-4 shrink-0",children:[f.isPending?e.jsx(us,{className:"h-3 w-3 animate-spin"}):e.jsx(mn,{className:"h-3 w-3"}),"Send Test to Me"]})]})]}),e.jsx(De,{children:e.jsxs(ya,{defaultValue:"single",children:[e.jsxs(va,{className:"mb-4",children:[e.jsxs(ls,{value:"single",children:[e.jsx(Rr,{className:"h-4 w-4 mr-2"}),"Single Send"]}),e.jsxs(ls,{value:"bulk",children:[e.jsx(ni,{className:"h-4 w-4 mr-2"}),"Bulk CSV"]})]}),e.jsx(_s,{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(re,{htmlFor:"prospect-email",className:"sr-only",children:"Email"}),e.jsx(we,{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(re,{htmlFor:"prospect-name",className:"sr-only",children:"First Name"}),e.jsx(we,{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(us,{className:"h-4 w-4 animate-spin"}):e.jsx(Rr,{className:"h-4 w-4"}),"Send Invite"]})]})}),e.jsx(_s,{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:x,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(Wr,{className:"h-4 w-4"}),"Upload CSV"]}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Format: email, first_name (one per line)"})]}),i.length>0&&e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs(We,{variant:"secondary",className:"gap-1",children:[e.jsx(Yn,{className:"h-3 w-3"}),i.length," entries ready"]}),e.jsxs(B,{variant:"ghost",size:"sm",onClick:()=>l([]),children:[e.jsx(hr,{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,k)=>e.jsxs("div",{className:"text-muted-foreground",children:[b.email,b.first_name?` — ${b.first_name}`:""]},k)),i.length>20&&e.jsxs("div",{className:"text-muted-foreground/60",children:["...and ",i.length-20," more"]})]}),e.jsxs(B,{onClick:_,disabled:m.isPending,className:"gap-2",children:[m.isPending?e.jsx(us,{className:"h-4 w-4 animate-spin"}):e.jsx(Rr,{className:"h-4 w-4"}),"Send ",i.length," Invites"]})]})]})})]})})]}),e.jsxs(_e,{children:[e.jsxs(zt,{children:[e.jsxs(qt,{className:"flex items-center gap-2",children:[e.jsx(mn,{className:"h-5 w-5"}),"Prospect Log"]}),e.jsx(_r,{children:"Track all sent invitations and their conversion status"})]}),e.jsx(De,{children:d?e.jsx("div",{className:"space-y-3",children:[...Array(5)].map((b,k)=>e.jsx(xn,{className:"h-12 w-full"},k))}):c&&c.length>0?e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("table",{className:"w-full",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"border-b",children:[e.jsx("th",{className:"text-left py-3 px-4 text-sm font-medium text-muted-foreground",children:"Email"}),e.jsx("th",{className:"text-left py-3 px-4 text-sm font-medium text-muted-foreground",children:"Name"}),e.jsx("th",{className:"text-left py-3 px-4 text-sm font-medium text-muted-foreground",children:"Sent"}),e.jsx("th",{className:"text-left py-3 px-4 text-sm font-medium text-muted-foreground",children:"Status"}),e.jsx("th",{className:"text-left py-3 px-4 text-sm font-medium text-muted-foreground",children:"Converted"})]})}),e.jsx("tbody",{children:c.map(b=>e.jsxs("tr",{className:"border-b last:border-0 hover:bg-muted/30",children:[e.jsx("td",{className:"py-3 px-4 text-sm font-medium text-foreground",children:b.email}),e.jsx("td",{className:"py-3 px-4 text-sm text-muted-foreground",children:b.first_name||"—"}),e.jsx("td",{className:"py-3 px-4 text-sm text-muted-foreground",children:Js(new Date(b.sent_at),"MMM d, yyyy")}),e.jsx("td",{className:"py-3 px-4",children:b.status==="converted"?e.jsxs(We,{className:"bg-green-500/10 text-green-700 hover:bg-green-500/20 border-0",children:[e.jsx(Hr,{className:"h-3 w-3 mr-1"}),"Converted"]}):b.status==="live_lead"?e.jsxs(We,{className:"bg-red-500/10 text-red-700 hover:bg-red-500/20 border-0 gap-1",children:[e.jsx(Y0,{className:"h-3 w-3"}),"Live lead"]}):e.jsxs(We,{variant:"secondary",className:"gap-1",children:[e.jsx(Xr,{className:"h-3 w-3"}),"Sent"]})}),e.jsx("td",{className:"py-3 px-4 text-sm text-muted-foreground",children:b.converted_at?Js(new Date(b.converted_at),"MMM d, yyyy"):"—"})]},b.id))})]})}):e.jsxs("div",{className:"text-center py-12",children:[e.jsx(iu,{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 DJ(s){const t=as(),{toast:n}=Ci(),r=mt({queryKey:["recruit-stages",s],queryFn:async()=>{if(!s)return[];const{data:c,error:d}=await H.from("recruit_pipeline_stages").select("*").eq("brokerage_id",s).order("sort_order");if(d)throw d;return c},enabled:!!s}),a=mt({queryKey:["recruit-prospects",s],queryFn:async()=>{if(!s)return[];const c=1e3;let d=[],u=0,h=!0;for(;h;){const{data:m,error:f}=await H.from("recruit_prospects").select("*").eq("brokerage_id",s).order("created_at",{ascending:!1}).range(u,u+c-1);if(f)throw f;d=d.concat(m),h=m.length===c,u+=c}return d},enabled:!!s}),i=_t({mutationFn:async c=>{const{data:{user:d}}=await H.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 H.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=_t({mutationFn:async({id:c,...d})=>{const{data:u,error:h}=await H.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=_t({mutationFn:async c=>{const{error:d}=await H.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 fSn(s){const t=as(),{toast:n}=Ci(),r=mt({queryKey:["recruit-activities",s],queryFn:async()=>{if(!s)return[];const{data:i,error:l}=await H.from("recruit_activities").select("*").eq("prospect_id",s).order("created_at",{ascending:!1});if(l)throw l;return i},enabled:!!s}),a=_t({mutationFn:async i=>{const{data:{user:l}}=await H.auth.getUser();if(!l)throw new Error("Not authenticated");const{data:o,error:c}=await H.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 Jft=(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 o9t({open:s,onOpenChange:t,stages:n,defaultStageId:r,onSubmit:a,isSubmitting:i}){const[l,o]=N.useState(Jft(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(Jft(r,n)),t(!1)};return e.jsx(Bs,{open:s,onOpenChange:t,children:e.jsxs(Fs,{className:"max-w-2xl max-h-[90vh] overflow-y-auto",children:[e.jsx(qs,{children:e.jsx($s,{children:"Add Recruit Prospect"})}),e.jsxs("form",{onSubmit:d,className:"space-y-4",children:[e.jsxs(ya,{defaultValue:"basic",className:"w-full",children:[e.jsxs(va,{className:"grid w-full grid-cols-4",children:[e.jsx(ls,{value:"basic",children:"Basic Info"}),e.jsx(ls,{value:"production",children:"Production"}),e.jsx(ls,{value:"social",children:"Social & Web"}),e.jsx(ls,{value:"personal",children:"Personal"})]}),e.jsxs(_s,{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(re,{children:"First Name *"}),e.jsx(we,{required:!0,value:l.first_name,onChange:c("first_name")})]}),e.jsxs("div",{children:[e.jsx(re,{children:"Last Name"}),e.jsx(we,{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(re,{children:"Email"}),e.jsx(we,{type:"email",value:l.email,onChange:c("email")})]}),e.jsxs("div",{children:[e.jsx(re,{children:"Phone"}),e.jsx(we,{value:l.phone,onChange:c("phone")})]})]}),e.jsxs("div",{children:[e.jsx(re,{children:"Current Brokerage"}),e.jsx(we,{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(re,{children:"License #"}),e.jsx(we,{value:l.license_number,onChange:c("license_number")})]}),e.jsxs("div",{children:[e.jsx(re,{children:"Experience (years)"}),e.jsx(we,{type:"number",min:"0",value:l.experience_years,onChange:c("experience_years")})]})]}),e.jsxs("div",{children:[e.jsx(re,{children:"Address"}),e.jsx(we,{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(re,{children:"City"}),e.jsx(we,{value:l.city,onChange:c("city")})]}),e.jsxs("div",{children:[e.jsx(re,{children:"State"}),e.jsx(we,{value:l.state,onChange:c("state")})]}),e.jsxs("div",{children:[e.jsx(re,{children:"Zip"}),e.jsx(we,{value:l.zip_code,onChange:c("zip_code")})]})]}),e.jsxs("div",{children:[e.jsx(re,{children:"Pipeline Stage"}),e.jsxs(Ns,{value:l.stage_id,onValueChange:u=>o(h=>({...h,stage_id:u})),children:[e.jsx(ws,{children:e.jsx(ks,{})}),e.jsx(js,{children:n.map(u=>e.jsx(nt,{value:u.id,children:u.name},u.id))})]})]}),e.jsxs("div",{children:[e.jsx(re,{children:"Referred By"}),e.jsx(we,{placeholder:"Who referred this prospect?",value:l.referred_by,onChange:c("referred_by")})]})]}),e.jsxs(_s,{value:"production",className:"space-y-4 mt-4",children:[e.jsxs("div",{children:[e.jsx(re,{children:"Annual Production Volume"}),e.jsx(we,{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(re,{children:"Last Year Volume"}),e.jsx(we,{placeholder:"e.g. $8.2M",value:l.last_year_volume,onChange:c("last_year_volume")})]}),e.jsxs("div",{children:[e.jsx(re,{children:"Last Year Transactions"}),e.jsx(we,{type:"number",min:"0",placeholder:"e.g. 24",value:l.last_year_transactions,onChange:c("last_year_transactions")})]})]}),e.jsxs("div",{children:[e.jsx(re,{children:"Avg Sale Price"}),e.jsx(we,{placeholder:"e.g. $350K",value:l.avg_sale_price,onChange:c("avg_sale_price")})]}),e.jsxs("div",{children:[e.jsx(re,{children:"Specialties / Niche"}),e.jsx(we,{placeholder:"e.g. Luxury, First-time buyers, Investment",value:l.specialties,onChange:c("specialties")})]})]}),e.jsxs(_s,{value:"social",className:"space-y-4 mt-4",children:[e.jsxs("div",{children:[e.jsx(re,{children:"LinkedIn URL"}),e.jsx(we,{type:"url",placeholder:"https://linkedin.com/in/...",value:l.linkedin_url,onChange:c("linkedin_url")})]}),e.jsxs("div",{children:[e.jsx(re,{children:"Website URL"}),e.jsx(we,{type:"url",placeholder:"https://...",value:l.website_url,onChange:c("website_url")})]}),e.jsxs("div",{children:[e.jsx(re,{children:"Instagram Handle"}),e.jsx(we,{placeholder:"@handle",value:l.instagram_handle,onChange:c("instagram_handle")})]}),e.jsxs("div",{children:[e.jsx(re,{children:"Facebook URL"}),e.jsx(we,{type:"url",placeholder:"https://facebook.com/...",value:l.facebook_url,onChange:c("facebook_url")})]})]}),e.jsxs(_s,{value:"personal",className:"space-y-4 mt-4",children:[e.jsxs("div",{children:[e.jsx(re,{children:"Birthday"}),e.jsx(we,{type:"date",value:l.birthday,onChange:c("birthday")})]}),e.jsxs("div",{children:[e.jsx(re,{children:"Spouse / Partner Name"}),e.jsx(we,{value:l.spouse_name,onChange:c("spouse_name")})]}),e.jsxs("div",{children:[e.jsx(re,{children:"Interests / Hobbies"}),e.jsx(we,{placeholder:"Golf, travel, community events...",value:l.interests,onChange:c("interests")})]})]})]}),e.jsxs("div",{children:[e.jsx(re,{children:"Notes"}),e.jsx(Ws,{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 AAe(){const{user:s}=Ls();return mt({queryKey:["recruit-email-senders",s==null?void 0:s.id],enabled:!!s,staleTime:6e4,queryFn:async()=>{const[t,n]=await Promise.all([H.from("user_verified_senders").select("email, display_name, status").eq("user_id",s.id).eq("status","verified").limit(1).maybeSingle(),H.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 XWe({value:s,onChange:t}){const{data:n,isLoading:r}=AAe();return e.jsxs("div",{children:[e.jsx(re,{className:"text-xs",children:"Send from"}),e.jsxs(Ns,{value:s,onValueChange:a=>t(a),disabled:r,children:[e.jsx(ws,{className:"mt-1",children:e.jsx(ks,{})}),e.jsxs(js,{children:[e.jsx(nt,{value:"default",children:e.jsxs("span",{className:"flex items-center gap-2",children:[e.jsx(Ti,{className:"h-3.5 w-3.5"})," Brokerage default sender"]})}),e.jsx(nt,{value:"mass_email",disabled:!(n!=null&&n.massEmail),children:e.jsxs("span",{className:"flex items-center gap-2",children:[e.jsx(n3,{className:"h-3.5 w-3.5"}),"Mass Email",n!=null&&n.massEmail?` (${n.massEmail.email})`:" — not configured"]})}),e.jsx(nt,{value:"gmail",disabled:!(n!=null&&n.gmail),children:e.jsxs("span",{className:"flex items-center gap-2",children:[e.jsx(mn,{className:"h-3.5 w-3.5"}),"Gmail",n!=null&&n.gmail?` (${n.gmail.email})`:" — not connected"]})})]})]}),e.jsx("p",{className:"text-[11px] text-muted-foreground mt-1",children:"Mass Email and Gmail use your own verified sender. Configure them under Integrations."})]})}function l9t({open:s,onOpenChange:t,recruitVideoId:n,brokerageId:r,prospectName:a,prospectEmail:i,videoTitle:l,defaultMessage:o}){const c=(a||"").split(" ")[0]||"there",[d,u]=N.useState(""),[h,m]=N.useState(""),[f,g]=N.useState("default"),[y,x]=N.useState(!1),_=as(),{data:b}=AAe();N.useEffect(()=>{s&&(u(`${c}, I made you a quick video 🎥`),m(o||""),g(b!=null&&b.massEmail?"mass_email":b!=null&&b.gmail?"gmail":"default"))},[s,c,o,b==null?void 0:b.massEmail,b==null?void 0:b.gmail]);const k=async()=>{var A,T;if(!i){ie.error("This prospect has no email address on file.");return}x(!0);try{const{data:P,error:I}=await H.functions.invoke("send-recruit-video-email",{body:{recruit_video_ids:[n],brokerage_id:r,subject_override:d.trim()||void 0,message_override:h.trim()||void 0,send_via:f}});if(I)throw I;if(((P==null?void 0:P.sent)??0)>0)ie.success(`Email sent to ${i}`),_.invalidateQueries({queryKey:["recruit-videos"]}),_.invalidateQueries({queryKey:["recruit-videos-prospect"]}),t(!1);else{const L=((T=(A=P==null?void 0:P.results)==null?void 0:A[0])==null?void 0:T.error)||"Failed to send";ie.error(L)}}catch(P){ie.error((P==null?void 0:P.message)||"Failed to send email")}finally{x(!1)}};return e.jsx(Bs,{open:s,onOpenChange:t,children:e.jsxs(Fs,{className:"max-w-lg",children:[e.jsx(qs,{children:e.jsxs($s,{className:"flex items-center gap-2",children:[e.jsx(mn,{className:"h-5 w-5"})," Email video to ",a]})}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{children:[e.jsx(re,{className:"text-xs",children:"To"}),e.jsx(we,{value:i||"— no email on file —",disabled:!0,className:"mt-1"})]}),e.jsx(XWe,{value:f,onChange:g}),e.jsxs("div",{children:[e.jsx(re,{className:"text-xs",children:"Subject"}),e.jsx(we,{value:d,onChange:A=>u(A.target.value),className:"mt-1"})]}),e.jsxs("div",{children:[e.jsx(re,{className:"text-xs",children:"Personal message (optional)"}),e.jsx(Ws,{value:h,onChange:A=>m(A.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(Cr,{children:[e.jsx(B,{variant:"ghost",onClick:()=>t(!1),disabled:y,children:"Cancel"}),e.jsxs(B,{onClick:k,disabled:y||!i,children:[y?e.jsx(us,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(Rr,{className:"h-4 w-4 mr-2"}),"Send Email"]})]})]})})}function r5(s){return s?s.share_token?`https://video.relevelup.com/thumb/${s.share_token}`:s.thumbnail_url||s.preview_url||null:null}const vze=[{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 gSn(s){return mt({queryKey:["recruit-videos",s],queryFn:async()=>{if(!s)return[];const{data:t,error:n}=await H.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 xSn(s){return mt({queryKey:["recruit-videos-prospect",s],queryFn:async()=>{if(!s)return[];const{data:t,error:n}=await H.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 c9t(){const s=as(),{toast:t}=Ci();return _t({mutationFn:async n=>{const{data:{user:r}}=await H.auth.getUser();if(!r)throw new Error("Not authenticated");const{data:a,error:i}=await H.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 d9t(){const s=as();return _t({mutationFn:async({id:t,sent_via:n})=>{const{error:r}=await H.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 u9t(s){return mt({queryKey:["recruit-video-scripts",s],queryFn:async()=>{if(!s)return[];const{data:t,error:n}=await H.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 ySn(){const s=as(),{toast:t}=Ci();return _t({mutationFn:async n=>{const{data:{user:r}}=await H.auth.getUser();if(!r)throw new Error("Not authenticated");const{data:a,error:i}=await H.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 vSn(){const s=as();return _t({mutationFn:async t=>{const{error:n}=await H.from("recruit_video_scripts").delete().eq("id",t);if(n)throw n},onSuccess:()=>{s.invalidateQueries({queryKey:["recruit-video-scripts"]})}})}function bSn({prospectId:s,prospectName:t,prospectEmail:n,brokerageId:r}){var X;const{data:a=[],isLoading:i}=xSn(s),{data:l=[]}=u9t(r),o=c9t(),c=G3();d9t();const[d,u]=N.useState("idle"),[h,m]=N.useState(0),[f,g]=N.useState(0),[y,x]=N.useState(""),[_,b]=N.useState(""),[k,A]=N.useState(!1),[T,P]=N.useState(null),[I,M]=N.useState(null),[L,z]=N.useState(null),$=((X=l.find(te=>te.id===y))==null?void 0:X.script_text)||"",V=()=>{u("idle"),m(0),g(0),x(""),b("")},W=N.useCallback(async(te,ne)=>{u("uploading");try{const me=`Recruiting: ${t}`,{videoId:ue,libraryId:ce}=await sO(me),{uploadUrl:ae,apiKey:he}=await nO(ue),xe=new XMLHttpRequest;xe.upload.onprogress=Be=>{Be.lengthComputable&&m(Be.loaded/Be.total*100)},await new Promise((Be,Ne)=>{xe.onload=()=>xe.status>=200&&xe.status<300?Be():Ne(new Error("Upload failed")),xe.onerror=()=>Ne(new Error("Upload failed")),xe.open("PUT",ae),xe.setRequestHeader("AccessKey",he),xe.send(te)}),u("processing");let ve=0;const ge=Date.now(),be=9e4,Se=`https://iframe.mediadelivery.net/embed/${ce}/${ue}`;for(;ve<4&&(await new Promise(Ne=>setTimeout(Ne,3e3)),!(Date.now()-ge>be));){const Be=await F5(ue);if(ve=Be.status,g(Be.encodeProgress||0),ve===5||ve===6)throw new Error("Video processing failed")}const Ie=await F5(ue),Me=(Ie.storageSize||te.size)/(1024*1024),Re=await c.mutateAsync({bunny_video_id:ue,playback_url:Ie.directPlayUrl||Se,thumbnail_url:Ie.thumbnailUrl,preview_url:Ie.previewUrl||null,duration_seconds:Ie.length||ne,file_size_mb:Me,title:me,status:ve>=4?"ready":"processing",touch_type:"recruiting"});await o.mutateAsync({prospect_id:s,video_id:Re.id,brokerage_id:r,message:_||void 0}),u("done"),ie.success("Video recorded and linked to prospect!"),setTimeout(()=>{A(!1),V()},1500)}catch(me){ie.error(me.message||"Failed to upload video"),u("record")}},[s,t,r,_,c,o]),G=te=>{te&&(navigator.clipboard.writeText(`${window.location.origin}/recruit-video/${te}`),ie.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(na,{className:"h-4 w-4"})," Video Outreach"]}),e.jsxs(Bs,{open:k,onOpenChange:te=>{!te&&(d==="uploading"||d==="processing")||(A(te),te||V())},children:[e.jsx(Ao,{asChild:!0,children:e.jsxs(B,{size:"sm",variant:"outline",onClick:()=>u("script"),children:[e.jsx(nn,{className:"h-3.5 w-3.5 mr-1"})," Record Video"]})}),e.jsxs(Fs,{className:"max-w-2xl",children:[e.jsx(qs,{children:e.jsxs($s,{children:["Record Video for ",t]})}),d==="script"&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(re,{className:"text-xs",children:"Choose a Script (optional)"}),e.jsxs(Ns,{value:y,onValueChange:x,children:[e.jsx(ws,{className:"mt-1",children:e.jsx(ks,{placeholder:"No script — speak freely"})}),e.jsxs(js,{children:[e.jsx(nt,{value:"none",children:"No script"}),l.map(te=>{var ne;return e.jsx(nt,{value:te.id,children:e.jsxs("span",{className:"flex items-center gap-2",children:[te.title,e.jsx(We,{variant:"outline",className:"text-[9px] ml-1",children:(ne=vze.find(me=>me.value===te.category))==null?void 0:ne.label})]})},te.id)})]})]}),$&&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:$})]}),e.jsxs("div",{children:[e.jsx(re,{className:"text-xs",children:"Personal Message (shown on landing page)"}),e.jsx(Ws,{value:_,onChange:te=>b(te.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(na,{className:"h-4 w-4 mr-2"})," Start Recording"]})]}),d==="record"&&e.jsx(oO,{maxDurationSeconds:600,onRecordingComplete:W,teleprompterContent:$||void 0}),d==="uploading"&&e.jsxs("div",{className:"py-8 space-y-4 text-center",children:[e.jsx("p",{className:"font-medium",children:"Uploading video…"}),e.jsx(ro,{value:h,className:"mx-auto max-w-sm"}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:[Math.round(h),"%"]})]}),d==="processing"&&e.jsxs("div",{className:"py-8 space-y-4 text-center",children:[e.jsx("p",{className:"font-medium",children:"Processing video…"}),e.jsx(ro,{value:f,className:"mx-auto max-w-sm"}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:[Math.round(f),"%"]})]}),d==="done"&&e.jsxs("div",{className:"py-8 text-center",children:[e.jsx("div",{className:"h-12 w-12 rounded-full bg-emerald-100 flex items-center justify-center mx-auto mb-3",children:e.jsx(dd,{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(te=>{var ne;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:r5(te.video)?e.jsx("img",{src:r5(te.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(na,{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:((ne=te.video)==null?void 0:ne.title)||"Untitled"}),e.jsxs("div",{className:"flex items-center gap-2 mt-0.5",children:[te.view_count>0?e.jsxs(We,{variant:"secondary",className:"text-[9px] h-4",children:[e.jsx(da,{className:"h-2.5 w-2.5 mr-0.5"}),te.view_count]}):te.sent_at?e.jsxs(We,{variant:"outline",className:"text-[9px] h-4",children:[e.jsx(Rr,{className:"h-2.5 w-2.5 mr-0.5"}),"Sent"]}):e.jsxs(We,{variant:"outline",className:"text-[9px] h-4",children:[e.jsx(Xr,{className:"h-2.5 w-2.5 mr-0.5"}),"Draft"]}),e.jsx("span",{className:"text-[10px] text-muted-foreground",children:Js(new Date(te.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:()=>G(te.share_token),title:"Copy link",children:e.jsx(Pa,{className:"h-3 w-3"})}),e.jsxs(B,{variant:te.sent_at?"ghost":"default",size:"sm",className:"h-7 gap-1",disabled:!n,onClick:()=>{var me;P(te.id),M(((me=te.video)==null?void 0:me.title)||null),z(te.message||null)},title:n?"Email video to prospect":"No email on file",children:[e.jsx(mn,{className:"h-3 w-3"}),e.jsx("span",{className:"text-[10px]",children:te.sent_at?"Resend":"Email"})]})]})]},te.id)})}),T&&e.jsx(l9t,{open:!!T,onOpenChange:te=>{te||P(null)},recruitVideoId:T,brokerageId:r,prospectName:t,prospectEmail:n,videoTitle:I,defaultMessage:L})]})}function _Sn({brokerageId:s,onSelect:t}){const{data:n=[],isLoading:r}=mt({queryKey:["recruit-email-templates",s??"global-only"],queryFn:async()=>{let i=H.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(qd,{children:[e.jsx(Vd,{asChild:!0,children:e.jsxs(B,{variant:"outline",size:"sm",className:"gap-2",type:"button",children:[e.jsx(Wr,{className:"h-4 w-4"}),"Use Template",e.jsx(Xo,{className:"h-3.5 w-3.5 opacity-60"})]})}),e.jsx(Ld,{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(us,{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(s1,{}),e.jsx(cE,{className:"text-[11px] uppercase tracking-wide text-muted-foreground",children:i}),l.map(c=>e.jsxs(ba,{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(We,{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 wSn({open:s,onOpenChange:t,prospectId:n,brokerageId:r,prospectName:a,prospectEmail:i}){const{user:l}=Ls(),o=(a||"").split(" ")[0]||"there",[c,d]=N.useState(""),[u,h]=N.useState(""),[m,f]=N.useState("default"),[g,y]=N.useState(!1),[x,_]=N.useState(null),[b,k]=N.useState(!1),A=as(),{data:T}=AAe();N.useEffect(()=>{if(s){d(`Hi ${o}`),h("");const $=T!=null&&T.massEmail?"mass_email":T!=null&&T.gmail?"gmail":"default";f($),_(null),k(!1)}},[s,o,T==null?void 0:T.massEmail,T==null?void 0:T.gmail]);const{data:P=[],isLoading:I}=mt({queryKey:["prospect-email-video-library",l==null?void 0:l.id],queryFn:async()=>{const{data:$,error:V}=await H.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 $??[]},enabled:s&&!!(l!=null&&l.id)}),M=P.find($=>$.id===x)||null,L=async()=>{var $,V;if(!i){ie.error("This prospect has no email address on file.");return}if(!c.trim()||!u.trim()){ie.error("Subject and message are required.");return}y(!0);try{if(x){const{data:W}=await H.from("recruit_videos").select("id").eq("prospect_id",n).eq("video_id",x).maybeSingle();let G=W==null?void 0:W.id;if(!G){const{data:me,error:ue}=await H.from("recruit_videos").insert({prospect_id:n,video_id:x,brokerage_id:r,message:u.trim(),created_by:l.id}).select("id").single();if(ue)throw ue;G=me.id}const{data:X,error:te}=await H.functions.invoke("send-recruit-video-email",{body:{recruit_video_ids:[G],brokerage_id:r,subject_override:c.trim(),message_override:u.trim(),send_via:m}});if(te)throw te;if(((X==null?void 0:X.sent)??0)>0)ie.success(`Email sent to ${i}`),A.invalidateQueries({queryKey:["recruit-videos"]}),A.invalidateQueries({queryKey:["recruit-videos-prospect",n]}),A.invalidateQueries({queryKey:["recruit-activities",n]}),A.invalidateQueries({queryKey:["recruit-sent-emails"]}),t(!1);else{const me=((V=($=X==null?void 0:X.results)==null?void 0:$[0])==null?void 0:V.error)||"Failed to send";ie.error(me)}}else{const{data:W,error:G}=await H.functions.invoke("send-recruit-prospect-email",{body:{prospect_id:n,brokerage_id:r,subject:c.trim(),message:u.trim(),send_via:m}});if(G)throw G;W!=null&&W.success?(ie.success(`Email sent to ${i}`),A.invalidateQueries({queryKey:["recruit-activities",n]}),A.invalidateQueries({queryKey:["recruit-sent-emails"]}),t(!1)):ie.error((W==null?void 0:W.error)||"Failed to send")}}catch(W){ie.error((W==null?void 0:W.message)||"Failed to send email")}finally{y(!1)}},z=$=>{const V=W=>W.replace(/\[First Name\]/gi,o);d(V($.subject)),h(V($.body)),ie.success(`Loaded "${$.title}"`)};return e.jsx(Bs,{open:s,onOpenChange:t,children:e.jsxs(Fs,{className:"max-w-lg max-h-[90vh] overflow-y-auto",children:[e.jsx(qs,{children:e.jsxs($s,{className:"flex items-center gap-2",children:[e.jsx(mn,{className:"h-5 w-5"})," Email ",a]})}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{children:[e.jsx(re,{className:"text-xs",children:"To"}),e.jsx(we,{value:i||"— no email on file —",disabled:!0,className:"mt-1"})]}),e.jsx(XWe,{value:m,onChange:f}),e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsx(re,{className:"text-xs",children:"Subject"}),e.jsx(_Sn,{brokerageId:r,onSelect:z})]}),e.jsx(we,{value:c,onChange:$=>d($.target.value)}),e.jsxs("div",{children:[e.jsx(re,{className:"text-xs",children:"Message"}),e.jsx(Ws,{value:u,onChange:$=>h($.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(re,{className:"text-xs flex items-center gap-1.5",children:[e.jsx(na,{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:()=>{_(null),k(!1)},children:[e.jsx(hr,{className:"h-3 w-3 mr-1"})," Remove"]}):e.jsx(B,{type:"button",variant:"outline",size:"sm",className:"h-7 text-xs",onClick:()=>k($=>!$),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:r5(M)?e.jsx("img",{src:r5(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(na,{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:I?e.jsx("div",{className:"flex items-center justify-center py-4",children:e.jsx(us,{className:"h-4 w-4 animate-spin text-muted-foreground"})}):P.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."}):P.map($=>e.jsxs("button",{type:"button",onClick:()=>{_($.id),k(!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:r5($)?e.jsx("img",{src:r5($),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(na,{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:$.title||"Untitled video"}),$.duration_seconds&&e.jsxs("p",{className:"text-[10px] text-muted-foreground",children:[Math.floor($.duration_seconds/60),":",String(Math.floor($.duration_seconds%60)).padStart(2,"0")]})]})]},$.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(Cr,{children:[e.jsx(B,{variant:"ghost",onClick:()=>t(!1),disabled:g,children:"Cancel"}),e.jsxs(B,{onClick:L,disabled:g||!i,children:[g?e.jsx(us,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(Rr,{className:"h-4 w-4 mr-2"}),"Send Email"]})]})]})})}function jSn(s){return mt({queryKey:["recruit-campaign-sends",s],queryFn:async()=>{if(!s)return[];const{data:t,error:n}=await H.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 egt=[{value:"call",label:"Phone Call",icon:ga},{value:"email",label:"Email",icon:mn},{value:"text",label:"Text Message",icon:xo},{value:"meeting",label:"Meeting",icon:ta},{value:"note",label:"Note",icon:Wr},{value:"campaign_email",label:"Campaign Email",icon:Rr}];function Kb({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 Ene({label:s,url:t,icon:n}){return t?e.jsxs("a",{href:t.startsWith("http")?t:`https://${t}`,target:"_blank",rel:"noopener noreferrer",className:"flex items-center gap-2 text-sm text-primary hover:underline",children:[e.jsx(n,{className:"h-3.5 w-3.5"})," ",s," ",e.jsx(Tr,{className:"h-3 w-3 opacity-50"})]}):null}function em({label:s,value:t,onChange:n,type:r="text",placeholder:a}){return e.jsxs("div",{children:[e.jsx(re,{className:"text-xs",children:s}),e.jsx(we,{type:r,value:t,onChange:i=>n(i.target.value),placeholder:a,className:"mt-1 h-8 text-sm"})]})}function h9t({prospect:s,stages:t,brokerageId:n,open:r,onOpenChange:a,onUpdate:i,onDelete:l}){const{activities:o,addActivity:c}=fSn((s==null?void 0:s.id)||null),{data:d=[]}=jSn((s==null?void 0:s.id)||null),[u,h]=N.useState({type:"note",title:"",description:""}),[m,f]=N.useState(!1),[g,y]=N.useState(!1),[x,_]=N.useState({}),[b,k]=N.useState(!1);if(!s)return null;const A=()=>{var G,X;_({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:((G=s.experience_years)==null?void 0:G.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:((X=s.last_year_transactions)==null?void 0:X.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)},T=()=>{const G={id:s.id};for(const[X,te]of Object.entries(x))X==="experience_years"||X==="last_year_transactions"?G[X]=te?parseInt(te):null:G[X]=te||null;i(G),y(!1)},P=()=>y(!1),I=G=>X=>_(te=>({...te,[G]:X})),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:""}),f(!1))},L=t.find(G=>G.id===s.stage_id),z=s.address||s.city||s.state,$=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,W=s.birthday||s.spouse_name||s.interests||s.referred_by;return e.jsxs(l1,{open:r,onOpenChange:G=>{G||y(!1),a(G)},children:[e.jsx(Gy,{className:"w-full sm:max-w-lg p-0",children:e.jsx(lo,{className:"h-full",children:e.jsxs("div",{className:"p-6 space-y-5",children:[e.jsx(gb,{children:e.jsxs("div",{className:"flex items-start justify-between",children:[e.jsxs("div",{children:[e.jsxs(xb,{className:"text-xl",children:[s.first_name," ",s.last_name]}),L&&e.jsx(We,{variant:"outline",style:{borderColor:L.color,color:L.color},className:"mt-1",children:L.name})]}),e.jsxs("div",{className:"flex items-center gap-1",children:[g?e.jsxs(e.Fragment,{children:[e.jsx(B,{variant:"ghost",size:"icon",onClick:P,children:e.jsx(hr,{className:"h-4 w-4"})}),e.jsx(B,{variant:"default",size:"icon",onClick:T,children:e.jsx(Kl,{className:"h-4 w-4"})})]}):e.jsx(B,{variant:"ghost",size:"icon",onClick:A,title:"Edit prospect",children:e.jsx(Ja,{className:"h-4 w-4"})}),e.jsxs(Fl,{children:[e.jsx(Gf,{asChild:!0,children:e.jsx(B,{variant:"ghost",size:"icon",className:"text-destructive hover:text-destructive",children:e.jsx(qn,{className:"h-4 w-4"})})}),e.jsxs(kl,{children:[e.jsxs(Sl,{children:[e.jsx(Al,{children:"Delete prospect?"}),e.jsx(Tl,{children:"This will permanently remove this prospect and all their activity history."})]}),e.jsxs(Cl,{children:[e.jsx(El,{children:"Cancel"}),e.jsx(wl,{onClick:()=>{l(s.id),a(!1)},children:"Delete"})]})]})]})]})]})}),!g&&e.jsxs("div",{className:"space-y-2 text-sm",children:[s.email&&e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground min-w-0",children:[e.jsx(mn,{className:"h-3.5 w-3.5 flex-shrink-0"}),e.jsx("span",{className:"truncate",children:s.email})]}),e.jsxs(B,{size:"sm",variant:"outline",className:"h-7 gap-1.5 flex-shrink-0",onClick:()=>k(!0),children:[e.jsx(mn,{className:"h-3 w-3"})," Email"]})]}),s.phone&&e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground",children:[e.jsx(ga,{className:"h-3.5 w-3.5"})," ",s.phone]}),z&&e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground",children:[e.jsx(ii,{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(re,{className:"text-xs text-muted-foreground",children:"Move to Stage"}),e.jsxs(Ns,{value:s.stage_id||"",onValueChange:G=>i({id:s.id,stage_id:G}),children:[e.jsx(ws,{className:"mt-1",children:e.jsx(ks,{})}),e.jsx(js,{children:t.map(G=>e.jsx(nt,{value:G.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:G.color}}),G.name]})},G.id))})]})]}),e.jsxs(ya,{defaultValue:"details",className:"w-full",children:[e.jsxs(va,{className:"grid w-full grid-cols-4 h-8 text-xs",children:[e.jsx(ls,{value:"details",className:"text-xs",children:"Details"}),e.jsx(ls,{value:"production",className:"text-xs",children:"Production"}),e.jsx(ls,{value:"social",className:"text-xs",children:"Social"}),e.jsx(ls,{value:"personal",className:"text-xs",children:"Personal"})]}),g?e.jsxs(e.Fragment,{children:[e.jsxs(_s,{value:"details",className:"mt-3 space-y-3",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsx(em,{label:"First Name",value:x.first_name,onChange:I("first_name")}),e.jsx(em,{label:"Last Name",value:x.last_name,onChange:I("last_name")})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsx(em,{label:"Email",value:x.email,onChange:I("email"),type:"email"}),e.jsx(em,{label:"Phone",value:x.phone,onChange:I("phone")})]}),e.jsx(em,{label:"Current Brokerage",value:x.current_brokerage,onChange:I("current_brokerage")}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsx(em,{label:"License #",value:x.license_number,onChange:I("license_number")}),e.jsx(em,{label:"Experience (years)",value:x.experience_years,onChange:I("experience_years"),type:"number"})]}),e.jsx(em,{label:"Address",value:x.address,onChange:I("address"),placeholder:"Street address"}),e.jsxs("div",{className:"grid grid-cols-3 gap-3",children:[e.jsx(em,{label:"City",value:x.city,onChange:I("city")}),e.jsx(em,{label:"State",value:x.state,onChange:I("state")}),e.jsx(em,{label:"Zip",value:x.zip_code,onChange:I("zip_code")})]}),e.jsx(em,{label:"Source",value:x.source,onChange:I("source")}),e.jsx(em,{label:"Referred By",value:x.referred_by,onChange:I("referred_by")}),e.jsxs("div",{children:[e.jsx(re,{className:"text-xs",children:"Notes"}),e.jsx(Ws,{value:x.notes,onChange:G=>_(X=>({...X,notes:G.target.value})),rows:3,className:"mt-1 text-sm"})]})]}),e.jsxs(_s,{value:"production",className:"mt-3 space-y-3",children:[e.jsx(em,{label:"Annual Production",value:x.annual_production,onChange:I("annual_production"),placeholder:"e.g. $5M"}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsx(em,{label:"Last Year Volume",value:x.last_year_volume,onChange:I("last_year_volume"),placeholder:"e.g. $8.2M"}),e.jsx(em,{label:"Last Year Transactions",value:x.last_year_transactions,onChange:I("last_year_transactions"),type:"number",placeholder:"e.g. 24"})]}),e.jsx(em,{label:"Avg Sale Price",value:x.avg_sale_price,onChange:I("avg_sale_price"),placeholder:"e.g. $350K"}),e.jsx(em,{label:"Specialties / Niche",value:x.specialties,onChange:I("specialties"),placeholder:"e.g. Luxury, Investment"})]}),e.jsxs(_s,{value:"social",className:"mt-3 space-y-3",children:[e.jsx(em,{label:"LinkedIn URL",value:x.linkedin_url,onChange:I("linkedin_url"),type:"url",placeholder:"https://linkedin.com/in/..."}),e.jsx(em,{label:"Website URL",value:x.website_url,onChange:I("website_url"),type:"url",placeholder:"https://..."}),e.jsx(em,{label:"Instagram Handle",value:x.instagram_handle,onChange:I("instagram_handle"),placeholder:"@handle"}),e.jsx(em,{label:"Facebook URL",value:x.facebook_url,onChange:I("facebook_url"),type:"url",placeholder:"https://facebook.com/..."})]}),e.jsxs(_s,{value:"personal",className:"mt-3 space-y-3",children:[e.jsx(em,{label:"Birthday",value:x.birthday,onChange:I("birthday"),type:"date"}),e.jsx(em,{label:"Spouse / Partner",value:x.spouse_name,onChange:I("spouse_name")}),e.jsx(em,{label:"Interests / Hobbies",value:x.interests,onChange:I("interests"),placeholder:"Golf, travel, community events..."})]})]}):e.jsxs(e.Fragment,{children:[e.jsxs(_s,{value:"details",className:"mt-3",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsx(Kb,{label:"Current Brokerage",value:s.current_brokerage}),e.jsx(Kb,{label:"License #",value:s.license_number}),e.jsx(Kb,{label:"Experience",value:s.experience_years!=null?`${s.experience_years} years`:null}),e.jsx(Kb,{label:"Referred By",value:s.referred_by}),e.jsx(Kb,{label:"Source",value:s.source})]}),s.notes&&e.jsxs("div",{className:"mt-3",children:[e.jsx(re,{className:"text-xs text-muted-foreground",children:"Notes"}),e.jsx("p",{className:"text-sm mt-1 whitespace-pre-wrap",children:s.notes})]})]}),e.jsx(_s,{value:"production",className:"mt-3",children:$?e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsx(Kb,{label:"Annual Production",value:s.annual_production}),e.jsx(Kb,{label:"Last Year Volume",value:s.last_year_volume}),e.jsx(Kb,{label:"Last Year Transactions",value:s.last_year_transactions}),e.jsx(Kb,{label:"Avg Sale Price",value:s.avg_sale_price}),e.jsx(Kb,{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(_s,{value:"social",className:"mt-3",children:V?e.jsxs("div",{className:"space-y-2",children:[e.jsx(Ene,{label:"LinkedIn",url:s.linkedin_url,icon:W0}),e.jsx(Ene,{label:"Website",url:s.website_url,icon:au}),s.instagram_handle&&e.jsx(Ene,{label:s.instagram_handle,url:`https://instagram.com/${s.instagram_handle.replace("@","")}`,icon:dm}),e.jsx(Ene,{label:"Facebook",url:s.facebook_url,icon:Kf})]}):e.jsx("p",{className:"text-sm text-muted-foreground text-center py-4",children:"No social profiles added yet"})}),e.jsx(_s,{value:"personal",className:"mt-3",children:W?e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsx(Kb,{label:"Birthday",value:s.birthday?Js(new Date(s.birthday+"T00:00:00"),"MMMM d, yyyy"):null,icon:Io}),e.jsx(Kb,{label:"Spouse / Partner",value:s.spouse_name,icon:co}),e.jsx("div",{className:"col-span-2",children:e.jsx(Kb,{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(bSn,{prospectId:s.id,prospectName:`${s.first_name} ${s.last_name||""}`,prospectEmail:s.email,brokerageId:n}),e.jsx(Wl,{}),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:()=>f(!m),children:[e.jsx(nn,{className:"h-3.5 w-3.5 mr-1"})," Log Activity"]})]}),m&&e.jsxs("div",{className:"border rounded-lg p-3 mb-4 space-y-3 bg-muted/30",children:[e.jsxs(Ns,{value:u.type,onValueChange:G=>h(X=>({...X,type:G})),children:[e.jsx(ws,{children:e.jsx(ks,{})}),e.jsx(js,{children:egt.map(G=>e.jsx(nt,{value:G.value,children:G.label},G.value))})]}),e.jsx(we,{placeholder:"Subject / Title",value:u.title,onChange:G=>h(X=>({...X,title:G.target.value}))}),e.jsx(Ws,{placeholder:"Details (optional)",value:u.description,onChange:G=>h(X=>({...X,description:G.target.value})),rows:2}),e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx(B,{size:"sm",variant:"ghost",onClick:()=>f(!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 G=[...o.map(X=>({type:"manual",data:X,date:X.created_at})),...d.map(X=>({type:"campaign_email",data:X,date:X.sent_at||X.created_at}))].sort((X,te)=>new Date(te.date).getTime()-new Date(X.date).getTime());return G.length===0?e.jsx("p",{className:"text-sm text-muted-foreground text-center py-4",children:"No activity logged yet"}):G.map(X=>{if(X.type==="manual"){const ne=X.data,me=egt.find(ce=>ce.value===ne.activity_type),ue=(me==null?void 0:me.icon)||Wr;return e.jsxs("div",{className:"flex gap-3 text-sm",children:[e.jsx("div",{className:"mt-0.5",children:e.jsx("div",{className:"h-7 w-7 rounded-full bg-muted flex items-center justify-center",children:e.jsx(ue,{className:"h-3.5 w-3.5 text-muted-foreground"})})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"font-medium",children:ne.title}),ne.description&&e.jsx("p",{className:"text-muted-foreground text-xs mt-0.5",children:ne.description}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:Js(new Date(ne.created_at),"MMM d, yyyy h:mm a")})]})]},`activity-${ne.id}`)}const te=X.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(Rr,{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 #",te.email_number]}),e.jsx("p",{className:"text-muted-foreground text-xs mt-0.5",children:te.subject}),e.jsxs("div",{className:"flex flex-wrap items-center gap-1.5 mt-1.5",children:[te.status==="failed"?e.jsx(We,{variant:"destructive",className:"text-[10px] px-1.5 py-0 h-4",children:"Failed"}):e.jsxs(We,{variant:"outline",className:"text-[10px] px-1.5 py-0 h-4 border-green-500 text-green-600",children:[e.jsx(Rr,{className:"h-2.5 w-2.5 mr-0.5"})," Sent"]}),te.opened_at?e.jsxs(We,{variant:"outline",className:"text-[10px] px-1.5 py-0 h-4 border-blue-500 text-blue-600",children:[e.jsx(da,{className:"h-2.5 w-2.5 mr-0.5"})," Opened ",Js(new Date(te.opened_at),"MMM d, h:mm a")]}):te.status!=="failed"?e.jsx(We,{variant:"outline",className:"text-[10px] px-1.5 py-0 h-4 text-muted-foreground",children:"Not opened"}):null,te.clicked_at&&e.jsxs(We,{variant:"outline",className:"text-[10px] px-1.5 py-0 h-4 border-purple-500 text-purple-600",children:[e.jsx(Qg,{className:"h-2.5 w-2.5 mr-0.5"})," Clicked ",Js(new Date(te.clicked_at),"MMM d, h:mm a")]})]}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:Js(new Date(te.sent_at||te.created_at),"MMM d, yyyy h:mm a")})]})]},`send-${te.id}`)})})()})]})]})})}),e.jsx(wSn,{open:b,onOpenChange:k,prospectId:s.id,brokerageId:s.brokerage_id,prospectName:`${s.first_name} ${s.last_name??""}`.trim(),prospectEmail:s.email})]})}const NSn=["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 m9t({open:s,onOpenChange:t,brokerageId:n,stages:r}){var z;const{toast:a}=Ci(),i=as(),l=N.useRef(null),[o,c]=N.useState([]),[d,u]=N.useState([]),[h,m]=N.useState({}),[f,g]=N.useState(((z=r[0])==null?void 0:z.id)||""),[y,x]=N.useState(!1),[_,b]=N.useState("upload"),[k,A]=N.useState(0),T=()=>{c([]),u([]),m({}),b("upload"),A(0)},P=$=>{var G;const V=(G=$.target.files)==null?void 0:G[0];if(!V)return;const W=new FileReader;W.onload=X=>{var he;const ne=((he=X.target)==null?void 0:he.result).split(/\r?\n/).filter(xe=>xe.trim());if(ne.length<2){a({title:"Invalid CSV",description:"File must have a header row and at least one data row",variant:"destructive"});return}const me=I(ne[0]);u(me);const ue={},ce=new Set;me.forEach((xe,ve)=>{const ge=xe.toLowerCase().replace(/[^a-z0-9]/g,"");let be=null;/^firstname$/.test(ge)||ge==="first"?be="first_name":/^lastname$/.test(ge)||ge==="last"?be="last_name":/^email$/.test(ge)||ge==="emailaddress"?be="email":/^mobile$|^phone$|^cellphone$|^mobilephone$/.test(ge)?be="phone":/officename|currentbrokerage|brokerage|company/.test(ge)?be="current_brokerage":/membernumber|licensenumber|license/.test(ge)?be="license_number":/experienceyears|yearsexperience/.test(ge)?be="experience_years":/^totalvolume$|annualproduction/.test(ge)?be="annual_production":/^address$/.test(ge)?be="address":/^city$/.test(ge)?be="city":/^state$/.test(ge)?be="state":/^postalcode$|^zip$|^zipcode$/.test(ge)?be="zip_code":/listsidevolume|lastyearvolume/.test(ge)?be="last_year_volume":/^totalcount$|lastyeartransactions/.test(ge)?be="last_year_transactions":/avgsaleprice|averageprice/.test(ge)?be="avg_sale_price":/linkedin/.test(ge)?be="linkedin_url":/website/.test(ge)?be="website_url":/specialt/.test(ge)?be="specialties":/referr/.test(ge)?be="referred_by":/^notes$|^note$/.test(ge)&&(be="notes"),be&&!ce.has(be)&&(ue[String(ve)]=be,ce.add(be))}),m(ue);const ae=ne.slice(1).map(xe=>{const ve=I(xe),ge={};return me.forEach((be,Se)=>{ge[String(Se)]=ve[Se]||""}),ge});c(ae),b("map")},W.readAsText(V)},I=$=>{const V=[];let W="",G=!1;for(const X of $)X==='"'?G=!G:X===","&&!G?(V.push(W.trim()),W=""):W+=X;return V.push(W.trim()),V},M=async()=>{x(!0);try{const{data:{user:$}}=await H.auth.getUser();if(!$)throw new Error("Not authenticated");const V=o.map(G=>{const X={brokerage_id:n,created_by:$.id,stage_id:f,source:"csv_import",first_name:"Unknown"},te=X;return Object.entries(h).forEach(([ne,me])=>{var ce;const ue=(ce=G[ne])==null?void 0:ce.trim();ue&&(me==="experience_years"||me==="last_year_transactions"?te[me]=parseInt(ue.replace(/[^0-9.-]/g,""))||null:me==="annual_production"||me==="last_year_volume"||me==="avg_sale_price"?te[me]=ue.replace(/[^0-9.$,.-]/g,""):te[me]=ue)}),X});let W=0;for(let G=0;G{const $=`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([$],{type:"text/csv"}),W=URL.createObjectURL(V),G=document.createElement("a");G.href=W,G.download="recruit-prospects-template.csv",G.click(),URL.revokeObjectURL(W)};return e.jsx(Bs,{open:s,onOpenChange:$=>{$||T(),t($)},children:e.jsxs(Fs,{className:"max-w-2xl max-h-[90vh] overflow-y-auto",children:[e.jsx(qs,{children:e.jsx($s,{children:"Import Prospects from CSV"})}),_==="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(m5,{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:P}),e.jsxs(B,{onClick:()=>{var $;return($=l.current)==null?void 0:$.click()},children:[e.jsx(ni,{className:"h-4 w-4 mr-2"})," Choose File"]})]}),e.jsx(B,{variant:"link",className:"text-xs",onClick:L,children:"Download CSV template"})]}),_==="map"&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("p",{className:"text-sm text-muted-foreground",children:[o.length," rows found"]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-sm",children:"Import to stage:"}),e.jsxs(Ns,{value:f,onValueChange:g,children:[e.jsx(ws,{className:"w-[180px]",children:e.jsx(ks,{})}),e.jsx(js,{children:r.map($=>e.jsx(nt,{value:$.id,children:$.name},$.id))})]})]})]}),e.jsx("div",{className:"border rounded-lg overflow-hidden",children:e.jsxs(Oa,{children:[e.jsx(Fa,{children:e.jsxs(un,{children:[e.jsx(Mt,{className:"w-[140px]",children:"CSV Column"}),e.jsx(Mt,{className:"w-[160px]",children:"Map To"}),e.jsx(Mt,{children:"Preview"})]})}),e.jsx(za,{children:d.map(($,V)=>{var W;return e.jsxs(un,{children:[e.jsx(gt,{className:"font-medium text-xs",children:$}),e.jsx(gt,{children:e.jsxs(Ns,{value:h[String(V)]||"skip",onValueChange:G=>m(X=>({...X,[String(V)]:G==="skip"?"":G})),children:[e.jsx(ws,{className:"h-8 text-xs",children:e.jsx(ks,{})}),e.jsxs(js,{children:[e.jsx(nt,{value:"skip",children:"— Skip —"}),NSn.map(G=>e.jsx(nt,{value:G,children:G.replace(/_/g," ")},G))]})]})}),e.jsx(gt,{className:"text-xs text-muted-foreground truncate max-w-[200px]",children:((W=o[0])==null?void 0:W[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(Uo,{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:()=>{T()},children:"Back"}),e.jsx(B,{onClick:M,disabled:y||!Object.values(h).includes("first_name"),children:y?"Importing...":`Import ${o.length} Prospects`})]})]}),_==="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(pa,{className:"h-6 w-6 text-green-600"})}),e.jsxs("p",{className:"font-semibold",children:[k," prospects imported successfully!"]}),e.jsx(B,{onClick:()=>{T(),t(!1)},children:"Close"})]})]})})}function p9t({brokerageId:s}){const{stages:t,prospects:n,isLoading:r,addProspect:a,updateProspect:i,deleteProspect:l}=DJ(s),[o,c]=N.useState(!1),[d,u]=N.useState(),[h,m]=N.useState(null),[f,g]=N.useState(!1),[y,x]=N.useState(!1),[_,b]=N.useState(null);if(r)return e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})});const k=L=>n.filter(z=>z.stage_id===L),A=(L,z)=>{b(z),L.dataTransfer.effectAllowed="move"},T=L=>{L.preventDefault(),L.dataTransfer.dropEffect="move"},P=(L,z)=>{L.preventDefault(),_&&(i.mutate({id:_,stage_id:z}),b(null))},I=L=>{u(L),c(!0)},M=L=>{m(L),g(!0)};return e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("div",{children:e.jsxs("p",{className:"text-sm text-muted-foreground",children:[n.length," prospect",n.length!==1?"s":""]})}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(B,{variant:"outline",onClick:()=>x(!0),children:[e.jsx(ni,{className:"h-4 w-4 mr-2"})," Import CSV"]}),e.jsxs(B,{onClick:()=>{u(void 0),c(!0)},children:[e.jsx(nn,{className:"h-4 w-4 mr-2"})," Add Prospect"]})]})]}),e.jsxs(lo,{className:"w-full",children:[e.jsx("div",{className:"flex gap-4 pb-4",style:{minWidth:t.length*300},children:t.map(L=>{const z=k(L.id);return e.jsxs("div",{className:"w-[280px] flex-shrink-0 flex flex-col",onDragOver:T,onDrop:$=>P($,L.id),children:[e.jsxs("div",{className:"flex items-center justify-between mb-3 px-1",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"h-3 w-3 rounded-full",style:{backgroundColor:L.color}}),e.jsx("h3",{className:"font-semibold text-sm",children:L.name}),e.jsx(We,{variant:"secondary",className:"text-xs h-5 px-1.5",children:z.length})]}),e.jsx(B,{variant:"ghost",size:"icon",className:"h-6 w-6",onClick:()=>I(L.id),children:e.jsx(nn,{className:"h-3.5 w-3.5"})})]}),e.jsx("div",{className:"space-y-2 min-h-[200px] bg-muted/30 rounded-lg p-2",children:z.map($=>e.jsx(_e,{className:"p-3 cursor-pointer hover:shadow-md transition-shadow border-l-4 group",style:{borderLeftColor:L.color},draggable:!0,onDragStart:V=>A(V,$.id),onClick:()=>M($),children:e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsx(Mp,{className:"h-4 w-4 text-muted-foreground/40 mt-0.5 opacity-0 group-hover:opacity-100 transition-opacity cursor-grab"}),e.jsxs("div",{className:"flex-1 min-w-0 space-y-1.5",children:[e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(Ro,{className:"h-3.5 w-3.5 text-muted-foreground"}),e.jsxs("span",{className:"font-medium text-sm truncate",children:[$.first_name," ",$.last_name]})]}),$.current_brokerage&&e.jsxs("div",{className:"flex items-center gap-1.5 text-xs text-muted-foreground",children:[e.jsx(Ti,{className:"h-3 w-3"}),e.jsx("span",{className:"truncate",children:$.current_brokerage})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[$.email&&e.jsx(mn,{className:"h-3 w-3 text-muted-foreground"}),$.phone&&e.jsx(ga,{className:"h-3 w-3 text-muted-foreground"}),$.experience_years!=null&&e.jsxs(We,{variant:"secondary",className:"text-[10px] h-4 px-1",children:[$.experience_years,"yr"]})]})]})]})},$.id))})]},L.id)})}),e.jsx(DQ,{orientation:"horizontal"})]}),e.jsx(o9t,{open:o,onOpenChange:c,stages:t,defaultStageId:d,onSubmit:L=>a.mutate(L),isSubmitting:a.isPending}),e.jsx(h9t,{prospect:h,stages:t,brokerageId:s,open:f,onOpenChange:g,onUpdate:L=>{i.mutate(L),m(z=>z?{...z,...L}:null)},onDelete:L=>l.mutate(L)}),e.jsx(m9t,{open:y,onOpenChange:x,brokerageId:s,stages:t})]})}function q5e({brokerageId:s}){const{stages:t,prospects:n,isLoading:r,addProspect:a,updateProspect:i,deleteProspect:l}=DJ(s),{user:o}=Ls(),c=as(),[d,u]=N.useState(!1),[h,m]=N.useState(null),[f,g]=N.useState(!1),[y,x]=N.useState(!1),[_,b]=N.useState(""),[k,A]=N.useState("all"),[T,P]=N.useState("all"),[I,M]=N.useState("all"),[L,z]=N.useState(null),[$,V]=N.useState("asc"),[W,G]=N.useState(new Set),[X,te]=N.useState(!1),[ne,me]=N.useState(""),ue=N.useMemo(()=>{const Ne=new Set;return n.forEach(Ge=>{Ge.current_brokerage&&Ne.add(Ge.current_brokerage)}),Array.from(Ne).sort()},[n]),{data:ce=[]}=mt({queryKey:["recruit-campaigns-list",s],queryFn:async()=>{const{data:Ne,error:Ge}=await H.from("recruit_campaigns").select("id, name, warmth_level").or(`brokerage_id.is.null,brokerage_id.eq.${s}`).order("name");if(Ge)throw Ge;return Ne}}),{data:ae=[]}=mt({queryKey:["recruit-campaign-assignments-lookup",s],queryFn:async()=>{let Ge=[],Ce=0;for(;;){const{data:Fe,error:Ae}=await H.from("recruit_campaign_assignments").select("prospect_id, campaign_id, status").eq("brokerage_id",s).range(Ce,Ce+1e3-1);if(Ae)throw Ae;if(Ge=Ge.concat(Fe??[]),!Fe||Fe.length<1e3)break;Ce+=1e3}return Ge}}),he=N.useMemo(()=>{const Ne=new Map;return ae.forEach(Ge=>{Ne.has(Ge.prospect_id)||Ne.set(Ge.prospect_id,new Set),Ne.get(Ge.prospect_id).add(Ge.campaign_id)}),Ne},[ae]),xe=Ne=>{L===Ne?V(Ge=>Ge==="asc"?"desc":"asc"):(z(Ne),V("asc"))},ve=({column:Ne})=>L!==Ne?e.jsx(mg,{className:"h-3.5 w-3.5 ml-1 text-muted-foreground/50"}):$==="asc"?e.jsx(Om,{className:"h-3.5 w-3.5 ml-1 text-primary"}):e.jsx(Wf,{className:"h-3.5 w-3.5 ml-1 text-primary"}),ge=Ne=>t.find(Ge=>Ge.id===Ne),be=N.useMemo(()=>{let Ne=n.filter(Ge=>{var $e,Ye,Je;const Ce=!_||`${Ge.first_name} ${Ge.last_name}`.toLowerCase().includes(_.toLowerCase())||(($e=Ge.email)==null?void 0:$e.toLowerCase().includes(_.toLowerCase()))||((Ye=Ge.current_brokerage)==null?void 0:Ye.toLowerCase().includes(_.toLowerCase())),Fe=k==="all"||Ge.stage_id===k,Ae=T==="all"||Ge.current_brokerage===T;let Xe=!0;return I==="in_campaign"?Xe=he.has(Ge.id):I==="not_in_campaign"?Xe=!he.has(Ge.id):I!=="all"&&(Xe=((Je=he.get(Ge.id))==null?void 0:Je.has(I))??!1),Ce&&Fe&&Ae&&Xe});return L&&(Ne=[...Ne].sort((Ge,Ce)=>{var $e,Ye;let Fe=null,Ae=null;switch(L){case"name":Fe=`${Ge.first_name} ${Ge.last_name||""}`.toLowerCase(),Ae=`${Ce.first_name} ${Ce.last_name||""}`.toLowerCase();break;case"stage":Fe=(($e=ge(Ge.stage_id))==null?void 0:$e.sort_order)??999,Ae=((Ye=ge(Ce.stage_id))==null?void 0:Ye.sort_order)??999;break;case"brokerage":Fe=(Ge.current_brokerage||"").toLowerCase(),Ae=(Ce.current_brokerage||"").toLowerCase();break;case"experience":Fe=Ge.experience_years??-1,Ae=Ce.experience_years??-1;break;case"production":Fe=(Ge.annual_production||"").toLowerCase(),Ae=(Ce.annual_production||"").toLowerCase();break;case"source":Fe=(Ge.source||"").toLowerCase(),Ae=(Ce.source||"").toLowerCase();break;default:return 0}if(Fe===Ae)return 0;if(Fe==null)return 1;if(Ae==null)return-1;const Xe=Fe0&&be.every(Ne=>W.has(Ne.id)),Ie=be.some(Ne=>W.has(Ne.id)),Me=()=>{G(Se?new Set:new Set(be.map(Ne=>Ne.id)))},Re=Ne=>{G(Ge=>{const Ce=new Set(Ge);return Ce.has(Ne)?Ce.delete(Ne):Ce.add(Ne),Ce})},Be=_t({mutationFn:async()=>{if(!ne||!(o!=null&&o.id))throw new Error("Select a campaign");const Ne=new Set(ae.filter(Fe=>Fe.campaign_id===ne).map(Fe=>Fe.prospect_id)),Ge=Array.from(W).filter(Fe=>!Ne.has(Fe)).map(Fe=>({prospect_id:Fe,campaign_id:ne,brokerage_id:s,assigned_by:o.id,status:"active",current_email_number:0}));if(Ge.length===0)throw new Error("All selected prospects are already in this campaign");const{error:Ce}=await H.from("recruit_campaign_assignments").insert(Ge);if(Ce)throw Ce;return Ge.length},onSuccess:Ne=>{ie.success(`${Ne} prospect(s) added to campaign`),te(!1),G(new Set),me(""),c.invalidateQueries({queryKey:["recruit-campaign-assignments-lookup"]})},onError:Ne=>ie.error(Ne.message)});return r?e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})}):e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between gap-4 flex-wrap",children:[e.jsxs("div",{className:"relative flex-1 max-w-sm min-w-[200px]",children:[e.jsx(Gr,{className:"absolute left-2.5 top-2.5 h-4 w-4 text-muted-foreground"}),e.jsx(we,{placeholder:"Search prospects...",value:_,onChange:Ne=>b(Ne.target.value),className:"pl-8"})]}),e.jsxs("div",{className:"flex gap-2",children:[W.size>0&&e.jsxs(B,{variant:"secondary",onClick:()=>te(!0),className:"gap-1.5",children:[e.jsx(Rr,{className:"h-4 w-4"})," Add ",W.size," to Campaign"]}),e.jsxs(B,{variant:"outline",onClick:()=>x(!0),children:[e.jsx(ni,{className:"h-4 w-4 mr-2"})," Import CSV"]}),e.jsxs(B,{onClick:()=>u(!0),children:[e.jsx(nn,{className:"h-4 w-4 mr-2"})," Add Prospect"]})]})]}),e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsx(cj,{className:"h-4 w-4 text-muted-foreground"}),e.jsxs(Ns,{value:k,onValueChange:A,children:[e.jsx(ws,{className:"w-[160px] h-8 text-xs",children:e.jsx(ks,{placeholder:"All stages"})}),e.jsxs(js,{children:[e.jsx(nt,{value:"all",children:"All stages"}),t.map(Ne=>e.jsx(nt,{value:Ne.id,children:Ne.name},Ne.id))]})]}),e.jsxs(Ns,{value:T,onValueChange:P,children:[e.jsxs(ws,{className:"w-[200px] h-8 text-xs",children:[e.jsx(Ti,{className:"h-3.5 w-3.5 mr-1.5"}),e.jsx(ks,{placeholder:"All brokerages"})]}),e.jsxs(js,{children:[e.jsx(nt,{value:"all",children:"All brokerages"}),ue.map(Ne=>e.jsx(nt,{value:Ne,children:Ne},Ne))]})]}),e.jsxs(Ns,{value:I,onValueChange:M,children:[e.jsxs(ws,{className:"w-[200px] h-8 text-xs",children:[e.jsx(mn,{className:"h-3.5 w-3.5 mr-1.5"}),e.jsx(ks,{placeholder:"Campaign status"})]}),e.jsxs(js,{children:[e.jsx(nt,{value:"all",children:"All contacts"}),e.jsx(nt,{value:"in_campaign",children:"In any campaign"}),e.jsx(nt,{value:"not_in_campaign",children:"Not in any campaign"}),ce.map(Ne=>e.jsxs(nt,{value:Ne.id,children:["In: ",Ne.name]},Ne.id))]})]}),(k!=="all"||T!=="all"||I!=="all")&&e.jsx(B,{variant:"ghost",size:"sm",className:"h-8 text-xs text-muted-foreground",onClick:()=>{A("all"),P("all"),M("all")},children:"Clear filters"})]}),e.jsx("div",{className:"rounded-md border",children:e.jsxs(Oa,{children:[e.jsx(Fa,{children:e.jsxs(un,{children:[e.jsx(Mt,{className:"w-[40px]",children:e.jsx(Bi,{checked:Se,onCheckedChange:Me,"aria-label":"Select all",...Ie&&!Se?{"data-state":"indeterminate"}:{}})}),e.jsx(Mt,{className:"cursor-pointer select-none",onClick:()=>xe("name"),children:e.jsxs("span",{className:"inline-flex items-center",children:["Name ",e.jsx(ve,{column:"name"})]})}),e.jsx(Mt,{className:"cursor-pointer select-none",onClick:()=>xe("stage"),children:e.jsxs("span",{className:"inline-flex items-center",children:["Stage ",e.jsx(ve,{column:"stage"})]})}),e.jsx(Mt,{className:"hidden md:table-cell cursor-pointer select-none",onClick:()=>xe("brokerage"),children:e.jsxs("span",{className:"inline-flex items-center",children:["Brokerage ",e.jsx(ve,{column:"brokerage"})]})}),e.jsx(Mt,{className:"hidden md:table-cell",children:"Contact"}),e.jsx(Mt,{className:"hidden lg:table-cell cursor-pointer select-none",onClick:()=>xe("experience"),children:e.jsxs("span",{className:"inline-flex items-center",children:["Experience ",e.jsx(ve,{column:"experience"})]})}),e.jsx(Mt,{className:"hidden lg:table-cell cursor-pointer select-none",onClick:()=>xe("production"),children:e.jsxs("span",{className:"inline-flex items-center",children:["Production ",e.jsx(ve,{column:"production"})]})}),e.jsx(Mt,{className:"hidden lg:table-cell",children:"Campaigns"}),e.jsx(Mt,{className:"w-[50px]"})]})}),e.jsx(za,{children:be.length===0?e.jsx(un,{children:e.jsx(gt,{colSpan:9,className:"text-center text-muted-foreground py-8",children:"No prospects found"})}):be.map(Ne=>{const Ge=ge(Ne.stage_id),Ce=he.get(Ne.id),Fe=(Ce==null?void 0:Ce.size)??0;return e.jsxs(un,{className:"cursor-pointer",onClick:()=>{m(Ne),g(!0)},children:[e.jsx(gt,{onClick:Ae=>Ae.stopPropagation(),children:e.jsx(Bi,{checked:W.has(Ne.id),onCheckedChange:()=>Re(Ne.id),"aria-label":`Select ${Ne.first_name}`})}),e.jsxs(gt,{className:"font-medium",children:[Ne.first_name," ",Ne.last_name]}),e.jsx(gt,{children:Ge?e.jsxs(We,{variant:"outline",className:"text-xs gap-1 whitespace-nowrap",style:{borderColor:Ge.color,color:Ge.color,backgroundColor:`${Ge.color}10`},children:[e.jsx("span",{className:"h-1.5 w-1.5 rounded-full inline-block",style:{backgroundColor:Ge.color}}),Ge.name]}):e.jsx("span",{className:"text-muted-foreground text-xs",children:"—"})}),e.jsx(gt,{className:"hidden md:table-cell",children:Ne.current_brokerage?e.jsxs("div",{className:"flex items-center gap-1.5 text-sm",children:[e.jsx(Ti,{className:"h-3.5 w-3.5 text-muted-foreground"}),e.jsx("span",{className:"truncate max-w-[150px]",children:Ne.current_brokerage})]}):e.jsx("span",{className:"text-muted-foreground",children:"—"})}),e.jsx(gt,{className:"hidden md:table-cell",children:e.jsxs("div",{className:"flex items-center gap-2",children:[Ne.email&&e.jsx(mn,{className:"h-3.5 w-3.5 text-muted-foreground"}),Ne.phone&&e.jsx(ga,{className:"h-3.5 w-3.5 text-muted-foreground"}),!Ne.email&&!Ne.phone&&e.jsx("span",{className:"text-muted-foreground",children:"—"})]})}),e.jsx(gt,{className:"hidden lg:table-cell",children:Ne.experience_years!=null?`${Ne.experience_years} yr`:"—"}),e.jsx(gt,{className:"hidden lg:table-cell",children:Ne.annual_production||"—"}),e.jsx(gt,{className:"hidden lg:table-cell",children:Fe>0?e.jsxs(We,{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:Ae=>{Ae.stopPropagation(),l.mutate(Ne.id)},children:e.jsx(qn,{className:"h-3.5 w-3.5"})})})]},Ne.id)})})]})}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[W.size>0&&e.jsxs("span",{className:"font-medium text-foreground",children:[W.size," selected · "]}),be.length," of ",n.length," prospects"]}),e.jsx(Bs,{open:X,onOpenChange:te,children:e.jsxs(Fs,{className:"sm:max-w-md",children:[e.jsx(qs,{children:e.jsx($s,{children:"Add to Campaign"})}),e.jsxs("div",{className:"space-y-4 py-2",children:[e.jsxs("p",{className:"text-sm text-muted-foreground",children:["Add ",e.jsx("span",{className:"font-medium text-foreground",children:W.size})," selected prospect(s) to a recruiting campaign drip."]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{children:"Campaign"}),e.jsxs(Ns,{value:ne,onValueChange:me,children:[e.jsx(ws,{children:e.jsx(ks,{placeholder:"Select a campaign..."})}),e.jsx(js,{children:ce.map(Ne=>e.jsxs(nt,{value:Ne.id,children:[Ne.name," ",e.jsxs("span",{className:"text-muted-foreground ml-1",children:["(",Ne.warmth_level,")"]})]},Ne.id))})]})]})]}),e.jsxs(Cr,{children:[e.jsx(B,{variant:"outline",onClick:()=>te(!1),children:"Cancel"}),e.jsx(B,{onClick:()=>Be.mutate(),disabled:!ne||Be.isPending,children:Be.isPending?"Adding...":"Add to Campaign"})]})]})}),e.jsx(o9t,{open:d,onOpenChange:u,stages:t,onSubmit:Ne=>a.mutate(Ne),isSubmitting:a.isPending}),e.jsx(h9t,{prospect:h,stages:t,brokerageId:s,open:f,onOpenChange:g,onUpdate:Ne=>{i.mutate(Ne),m(Ge=>Ge?{...Ge,...Ne}:null)},onDelete:Ne=>l.mutate(Ne)}),e.jsx(m9t,{open:y,onOpenChange:x,brokerageId:s,stages:t})]})}function f9t({brokerageId:s}){const{stages:t,prospects:n,isLoading:r}=DJ(s),a=N.useMemo(()=>{if(!t.length||!n.length)return null;const i=n.length,l=t.find(_=>_.name==="Signed"),o=t.find(_=>_.name==="Onboarded"),c=n.filter(_=>_.stage_id===(l==null?void 0:l.id)||_.stage_id===(o==null?void 0:o.id)).length,d=i>0?(c/i*100).toFixed(1):"0",u=new Date,h=i>0?Math.round(n.reduce((_,b)=>_+wj(u,new Date(b.created_at)),0)/i):0,m=t.map(_=>({..._,count:n.filter(b=>b.stage_id===_.id).length})),f={};n.forEach(_=>{const b=_.source||"unknown";f[b]=(f[b]||0)+1});const g=Object.entries(f).sort((_,b)=>b[1]-_[1]),y=new Date;y.setDate(y.getDate()-30);const x=n.filter(_=>new Date(_.created_at)>=y).length;return{total:i,signed:c,conversionRate:d,avgDays:h,byStage:m,bySrc:g,recentCount:x}},[t,n]);return r?e.jsx("div",{className:"flex justify-center py-8",children:e.jsx("div",{className:"h-6 w-6 animate-spin rounded-full border-4 border-primary border-t-transparent"})}):a?e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4",children:[e.jsx(_e,{children:e.jsx(De,{className:"pt-6",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"h-10 w-10 rounded-lg bg-blue-500/10 flex items-center justify-center",children:e.jsx(Yn,{className:"h-5 w-5 text-blue-600"})}),e.jsxs("div",{children:[e.jsx("p",{className:"text-2xl font-bold",children:a.total}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Total Prospects"})]})]})})}),e.jsx(_e,{children:e.jsx(De,{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(ml,{className:"h-5 w-5 text-green-600"})}),e.jsxs("div",{children:[e.jsxs("p",{className:"text-2xl font-bold",children:[a.conversionRate,"%"]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Conversion Rate"})]})]})})}),e.jsx(_e,{children:e.jsx(De,{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(Xr,{className:"h-5 w-5 text-amber-600"})}),e.jsxs("div",{children:[e.jsxs("p",{className:"text-2xl font-bold",children:[a.avgDays,"d"]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Avg Days in Pipeline"})]})]})})}),e.jsx(_e,{children:e.jsx(De,{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(iu,{className:"h-5 w-5 text-violet-600"})}),e.jsxs("div",{children:[e.jsx("p",{className:"text-2xl font-bold",children:a.recentCount}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Added (30 days)"})]})]})})})]}),e.jsxs("div",{className:"grid md:grid-cols-2 gap-6",children:[e.jsxs(_e,{children:[e.jsx(zt,{children:e.jsx(qt,{className:"text-base",children:"Pipeline Breakdown"})}),e.jsx(De,{className:"space-y-3",children:a.byStage.map(i=>{const l=a.total>0?i.count/a.total*100:0;return e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:"flex items-center justify-between text-sm",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"h-2.5 w-2.5 rounded-full",style:{backgroundColor:i.color}}),e.jsx("span",{children:i.name})]}),e.jsx("span",{className:"font-medium",children:i.count})]}),e.jsx("div",{className:"h-2 bg-muted rounded-full overflow-hidden",children:e.jsx("div",{className:"h-full rounded-full transition-all",style:{width:`${l}%`,backgroundColor:i.color}})})]},i.id)})})]}),e.jsxs(_e,{children:[e.jsx(zt,{children:e.jsx(qt,{className:"text-base",children:"Lead Sources"})}),e.jsxs(De,{className:"space-y-3",children:[a.bySrc.map(([i,l])=>e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(We,{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 kSn=["Outreach","Follow-up","Interview","Offer","Referral","Other"];function g9t({brokerageId:s}){const{toast:t}=Ci(),{user:n}=Ls(),r=as(),[a,i]=N.useState(null),[l,o]=N.useState(null),[c,d]=N.useState(!1),[u,h]=N.useState(null),{data:m=[],isLoading:f}=mt({queryKey:["recruit-email-templates-manage",s],queryFn:async()=>{const{data:A,error:T}=await H.from("recruit_email_templates").select("*").or(`brokerage_id.is.null,brokerage_id.eq.${s}`).order("sort_order");if(T)throw T;return A}}),g=_t({mutationFn:async A=>{if(A.id){const{error:T}=await H.from("recruit_email_templates").update({category:A.category,title:A.title,subject:A.subject,body:A.body}).eq("id",A.id);if(T)throw T}else{const{error:T}=await H.from("recruit_email_templates").insert({brokerage_id:s,category:A.category||"Outreach",title:A.title,subject:A.subject,body:A.body,created_by:n==null?void 0:n.id,sort_order:100});if(T)throw T}},onSuccess:()=>{r.invalidateQueries({queryKey:["recruit-email-templates-manage",s]}),r.invalidateQueries({queryKey:["recruit-email-templates"]}),t({title:"Template saved"}),d(!1),h(null)},onError:A=>t({title:"Save failed",description:A.message,variant:"destructive"})}),y=_t({mutationFn:async A=>{const{error:T}=await H.from("recruit_email_templates").delete().eq("id",A);if(T)throw T},onSuccess:()=>{r.invalidateQueries({queryKey:["recruit-email-templates-manage",s]}),r.invalidateQueries({queryKey:["recruit-email-templates"]}),t({title:"Template deleted"})},onError:A=>t({title:"Delete failed",description:A.message,variant:"destructive"})}),x=(A,T)=>{navigator.clipboard.writeText(A),i(T),t({title:"Copied to clipboard!"}),setTimeout(()=>i(null),2e3)},_=()=>{h({category:"Outreach",title:"",subject:"",body:""}),d(!0)},b=A=>{h(A),d(!0)},k=Array.from(new Set(m.map(A=>A.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:_,size:"sm",className:"gap-1.5",children:[e.jsx(nn,{className:"h-4 w-4"})," New Template"]})]}),f?e.jsx("div",{className:"flex items-center justify-center py-8",children:e.jsx(us,{className:"h-5 w-5 animate-spin text-muted-foreground"})}):k.map(A=>e.jsxs("div",{className:"space-y-3",children:[e.jsxs("h3",{className:"font-semibold text-sm flex items-center gap-2",children:[e.jsx(mn,{className:"h-4 w-4"})," ",A]}),m.filter(T=>T.category===A).map(T=>{const P=T.brokerage_id!==null;return e.jsxs(_e,{className:`transition-all ${l===T.id?"ring-2 ring-primary/20":"hover:shadow-sm"}`,children:[e.jsx(zt,{className:"pb-2 cursor-pointer",onClick:()=>o(l===T.id?null:T.id),children:e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsxs(qt,{className:"text-sm flex items-center gap-2",children:[e.jsx("span",{className:"truncate",children:T.title}),!P&&e.jsx(We,{variant:"secondary",className:"text-[10px] shrink-0",children:"Built-in"}),P&&e.jsx(We,{className:"text-[10px] shrink-0",children:"Custom"})]}),e.jsxs("p",{className:"text-xs text-muted-foreground mt-0.5 truncate",children:["Subject: ",T.subject]})]}),e.jsx(We,{variant:"outline",className:"text-[10px] shrink-0",children:T.category})]})}),l===T.id&&e.jsxs(De,{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:T.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:T.body})]}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsxs(B,{size:"sm",variant:"outline",onClick:()=>x(T.subject,T.id+"-s"),children:[a===T.id+"-s"?e.jsx(pa,{className:"h-3.5 w-3.5 mr-1"}):e.jsx(Pa,{className:"h-3.5 w-3.5 mr-1"}),"Copy Subject"]}),e.jsxs(B,{size:"sm",variant:"outline",onClick:()=>x(T.body,T.id+"-b"),children:[a===T.id+"-b"?e.jsx(pa,{className:"h-3.5 w-3.5 mr-1"}):e.jsx(Pa,{className:"h-3.5 w-3.5 mr-1"}),"Copy Body"]}),P&&e.jsxs(e.Fragment,{children:[e.jsxs(B,{size:"sm",variant:"outline",onClick:()=>b(T),children:[e.jsx(Ja,{className:"h-3.5 w-3.5 mr-1"})," Edit"]}),e.jsxs(B,{size:"sm",variant:"outline",className:"text-destructive hover:text-destructive",onClick:()=>{confirm("Delete this template?")&&y.mutate(T.id)},children:[e.jsx(qn,{className:"h-3.5 w-3.5 mr-1"})," Delete"]})]})]})]})]},T.id)})]},A)),e.jsx(Bs,{open:c,onOpenChange:d,children:e.jsxs(Fs,{className:"max-w-2xl",children:[e.jsx(qs,{children:e.jsx($s,{children:u!=null&&u.id?"Edit Template":"New Template"})}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(re,{className:"text-xs",children:"Title"}),e.jsx(we,{value:(u==null?void 0:u.title)||"",onChange:A=>h(T=>({...T,title:A.target.value})),className:"mt-1"})]}),e.jsxs("div",{children:[e.jsx(re,{className:"text-xs",children:"Category"}),e.jsx("select",{value:(u==null?void 0:u.category)||"Outreach",onChange:A=>h(T=>({...T,category:A.target.value})),className:"mt-1 flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-sm",children:kSn.map(A=>e.jsx("option",{value:A,children:A},A))})]})]}),e.jsxs("div",{children:[e.jsx(re,{className:"text-xs",children:"Subject"}),e.jsx(we,{value:(u==null?void 0:u.subject)||"",onChange:A=>h(T=>({...T,subject:A.target.value})),className:"mt-1"})]}),e.jsxs("div",{children:[e.jsx(re,{className:"text-xs",children:"Body"}),e.jsx(Ws,{value:(u==null?void 0:u.body)||"",onChange:A=>h(T=>({...T,body:A.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(Cr,{children:[e.jsx(B,{variant:"ghost",onClick:()=>d(!1),children:"Cancel"}),e.jsxs(B,{onClick:()=>g.mutate(u||{}),disabled:g.isPending||!(u!=null&&u.title)||!(u!=null&&u.subject)||!(u!=null&&u.body),children:[g.isPending&&e.jsx(us,{className:"h-4 w-4 mr-2 animate-spin"}),"Save Template"]})]})]})})]})}const tgt={call:ga,email:mn,text:xo,meeting:ta,note:Wr};function x9t({brokerageId:s}){const{data:t,isLoading:n}=mt({queryKey:["recruit-activity-report",s],queryFn:async()=>{const{data:r,error:a}=await H.from("recruit_prospects").select("id, created_by").eq("brokerage_id",s);if(a)throw a;const i=(r==null?void 0:r.map(f=>f.id))||[];if(i.length===0)return{recruiters:[],recentActivities:[]};const{data:l,error:o}=await H.from("recruit_activities").select("*").in("prospect_id",i).order("created_at",{ascending:!1});if(o)throw o;const c=[...new Set([...r.map(f=>f.created_by),...(l||[]).map(f=>f.created_by)])],{data:d}=await H.from("profiles").select("id, name, email").in("id",c),u=Object.fromEntries((d||[]).map(f=>[f.id,f])),h=zW(new Date,30);return{recruiters:c.map(f=>{var b,k;const g=(l||[]).filter(A=>A.created_by===f),y=g.filter(A=>new Date(A.created_at)>=h),x={};y.forEach(A=>{x[A.activity_type]=(x[A.activity_type]||0)+1});const _=r.filter(A=>A.created_by===f).length;return{id:f,name:((b=u[f])==null?void 0:b.name)||"Unknown",email:((k=u[f])==null?void 0:k.email)||"",totalActivities:g.length,recentActivities:y.length,byType:x,prospectsCreated:_}}).sort((f,g)=>g.recentActivities-f.recentActivities),recentActivities:(l||[]).slice(0,20)}},enabled:!!s});return n?e.jsx("div",{className:"flex justify-center py-8",children:e.jsx("div",{className:"h-6 w-6 animate-spin rounded-full border-4 border-primary border-t-transparent"})}):t!=null&&t.recruiters.length?e.jsxs("div",{className:"space-y-6",children:[e.jsxs(_e,{children:[e.jsx(zt,{children:e.jsx(qt,{className:"text-base",children:"Recruiter Leaderboard (Last 30 Days)"})}),e.jsx(De,{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(Ro,{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=tgt[i]||Wr;return e.jsxs(We,{variant:"outline",className:"text-[10px] gap-1",children:[e.jsx(o,{className:"h-2.5 w-2.5"})," ",l," ",i,l!==1?"s":""]},i)})})]}),e.jsxs("div",{className:"text-right",children:[e.jsx("p",{className:"text-lg font-bold",children:r.recentActivities}),e.jsx("p",{className:"text-[10px] text-muted-foreground",children:"activities"})]}),e.jsxs("div",{className:"text-right",children:[e.jsx("p",{className:"text-lg font-bold",children:r.prospectsCreated}),e.jsx("p",{className:"text-[10px] text-muted-foreground",children:"prospects"})]})]},r.id))})]}),e.jsxs(_e,{children:[e.jsx(zt,{children:e.jsx(qt,{className:"text-base",children:"Recent Activity"})}),e.jsx(De,{className:"space-y-3",children:t.recentActivities.map(r=>{const a=tgt[r.activity_type]||Wr;return e.jsxs("div",{className:"flex items-start gap-3 text-sm",children:[e.jsx("div",{className:"h-7 w-7 rounded-full bg-muted flex items-center justify-center flex-shrink-0 mt-0.5",children:e.jsx(a,{className:"h-3.5 w-3.5 text-muted-foreground"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"font-medium",children:r.title}),r.description&&e.jsx("p",{className:"text-xs text-muted-foreground truncate",children:r.description}),e.jsx("p",{className:"text-xs text-muted-foreground mt-0.5",children:Js(new Date(r.created_at),"MMM d, h:mm a")})]})]},r.id)})})]})]}):e.jsx("p",{className:"text-sm text-muted-foreground text-center py-8",children:"No recruiter activity yet."})}function y9t({brokerageId:s}){const{toast:t}=Ci(),n=as(),[r,a]=N.useState(!1),[i,l]=N.useState({first_name:"",last_name:"",email:"",phone:"",current_brokerage:"",notes:""}),{data:o=[],isLoading:c}=mt({queryKey:["recruit-referrals",s],queryFn:async()=>{const{data:x,error:_}=await H.from("recruit_referrals").select("*").eq("brokerage_id",s).order("created_at",{ascending:!1});if(_)throw _;return x}}),d=[...new Set(o.map(x=>x.referred_by))],{data:u=[]}=mt({queryKey:["referral-profiles",d],queryFn:async()=>{if(!d.length)return[];const{data:x}=await H.from("profiles").select("id, name, email").in("id",d);return x||[]},enabled:d.length>0}),h=Object.fromEntries(u.map(x=>[x.id,x])),m=_t({mutationFn:async x=>{const{data:{user:_}}=await H.auth.getUser();if(!_)throw new Error("Not authenticated");const{error:b}=await H.from("recruit_referrals").insert({brokerage_id:s,referred_by:_.id,referee_first_name:x.first_name,referee_last_name:x.last_name||null,referee_email:x.email||null,referee_phone:x.phone||null,referee_current_brokerage:x.current_brokerage||null,notes:x.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:x=>t({title:"Error",description:x.message,variant:"destructive"})}),f=_t({mutationFn:async({id:x,status:_,incentive_status:b})=>{const k={updated_at:new Date().toISOString()};_&&(k.status=_),b&&(k.incentive_status=b);const{error:A}=await H.from("recruit_referrals").update(k).eq("id",x);if(A)throw A},onSuccess:()=>n.invalidateQueries({queryKey:["recruit-referrals",s]})}),g=x=>x==="approved"||x==="signed"?e.jsx(pa,{className:"h-3 w-3"}):x==="rejected"?e.jsx(Nu,{className:"h-3 w-3"}):e.jsx(Xr,{className:"h-3 w-3"}),y=x=>x==="approved"||x==="signed"||x==="paid"?"bg-green-500/10 text-green-600 border-green-200":x==="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(nn,{className:"h-4 w-4 mr-2"})," Submit Referral"]})]}),o.length===0?e.jsxs(_e,{className:"py-12 text-center",children:[e.jsx(Yl,{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(x=>{var _;return e.jsx(_e,{className:"p-4",children:e.jsxs("div",{className:"flex items-start justify-between gap-4",children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[e.jsxs("span",{className:"font-medium",children:[x.referee_first_name," ",x.referee_last_name]}),e.jsxs(We,{variant:"outline",className:y(x.status),children:[g(x.status)," ",x.status]}),x.incentive_status&&e.jsxs(We,{variant:"outline",className:y(x.incentive_status),children:[e.jsx(Io,{className:"h-3 w-3 mr-1"})," ",x.incentive_status]})]}),e.jsxs("div",{className:"text-xs text-muted-foreground space-y-0.5",children:[x.referee_email&&e.jsx("p",{children:x.referee_email}),x.referee_phone&&e.jsx("p",{children:x.referee_phone}),x.referee_current_brokerage&&e.jsxs("p",{children:["Currently at: ",x.referee_current_brokerage]}),e.jsxs("p",{children:["Referred by: ",((_=h[x.referred_by])==null?void 0:_.name)||"Unknown"," • ",Js(new Date(x.created_at),"MMM d, yyyy")]})]}),x.notes&&e.jsx("p",{className:"text-xs text-muted-foreground mt-1 italic",children:x.notes})]}),e.jsxs("div",{className:"flex gap-1",children:[e.jsxs(Ns,{value:x.status,onValueChange:b=>f.mutate({id:x.id,status:b}),children:[e.jsx(ws,{className:"h-7 text-xs w-[110px]",children:e.jsx(ks,{})}),e.jsxs(js,{children:[e.jsx(nt,{value:"pending",children:"Pending"}),e.jsx(nt,{value:"contacted",children:"Contacted"}),e.jsx(nt,{value:"approved",children:"Approved"}),e.jsx(nt,{value:"signed",children:"Signed"}),e.jsx(nt,{value:"rejected",children:"Rejected"})]})]}),e.jsxs(Ns,{value:x.incentive_status||"pending",onValueChange:b=>f.mutate({id:x.id,incentive_status:b}),children:[e.jsx(ws,{className:"h-7 text-xs w-[100px]",children:e.jsx(ks,{})}),e.jsxs(js,{children:[e.jsx(nt,{value:"pending",children:"Unpaid"}),e.jsx(nt,{value:"paid",children:"Paid"}),e.jsx(nt,{value:"n/a",children:"N/A"})]})]})]})]})},x.id)})}),e.jsx(Bs,{open:r,onOpenChange:a,children:e.jsxs(Fs,{children:[e.jsx(qs,{children:e.jsx($s,{children:"Submit a Recruit Referral"})}),e.jsxs("form",{onSubmit:x=>{x.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(re,{children:"First Name *"}),e.jsx(we,{required:!0,value:i.first_name,onChange:x=>l(_=>({..._,first_name:x.target.value}))})]}),e.jsxs("div",{children:[e.jsx(re,{children:"Last Name"}),e.jsx(we,{value:i.last_name,onChange:x=>l(_=>({..._,last_name:x.target.value}))})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(re,{children:"Email"}),e.jsx(we,{type:"email",value:i.email,onChange:x=>l(_=>({..._,email:x.target.value}))})]}),e.jsxs("div",{children:[e.jsx(re,{children:"Phone"}),e.jsx(we,{value:i.phone,onChange:x=>l(_=>({..._,phone:x.target.value}))})]})]}),e.jsxs("div",{children:[e.jsx(re,{children:"Current Brokerage"}),e.jsx(we,{value:i.current_brokerage,onChange:x=>l(_=>({..._,current_brokerage:x.target.value}))})]}),e.jsxs("div",{children:[e.jsx(re,{children:"Notes"}),e.jsx(Ws,{value:i.notes,onChange:x=>l(_=>({..._,notes:x.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 v9t({brokerageId:s}){const{toast:t}=Ci(),n=as(),[r,a]=N.useState(!1),{data:i}=mt({queryKey:["brokerage-recruit-form",s],queryFn:async()=>{const{data:m,error:f}=await H.from("brokerages").select("id, name, recruit_form_slug, recruit_form_enabled").eq("id",s).single();if(f)throw f;return m}}),{data:l=[]}=mt({queryKey:["recruit-interest-submissions",s],queryFn:async()=>{const{data:m,error:f}=await H.from("recruit_interest_submissions").select("*").eq("brokerage_id",s).order("created_at",{ascending:!1});if(f)throw f;return m}}),o=_t({mutationFn:async m=>{const{error:f}=await H.from("brokerages").update({recruit_form_enabled:m}).eq("id",s);if(f)throw f},onSuccess:()=>{n.invalidateQueries({queryKey:["brokerage-recruit-form",s]}),t({title:i!=null&&i.recruit_form_enabled?"Form disabled":"Form enabled"})}}),c=_t({mutationFn:async({id:m,status:f})=>{const{error:g}=await H.from("recruit_interest_submissions").update({status:f}).eq("id",m);if(g)throw g},onSuccess:()=>n.invalidateQueries({queryKey:["recruit-interest-submissions",s]})}),d=`https://bestbrokerage.relevelup.com/join-brokerage/${(i==null?void 0:i.recruit_form_slug)||""}`,u=()=>{navigator.clipboard.writeText(d),a(!0),t({title:"Link copied!"}),setTimeout(()=>a(!1),2e3)},h=m=>m==="contacted"||m==="converted"?"bg-green-500/10 text-green-600":m==="dismissed"?"bg-red-500/10 text-red-600":"bg-blue-500/10 text-blue-600";return e.jsxs("div",{className:"space-y-6",children:[e.jsxs(_e,{children:[e.jsx(zt,{children:e.jsx(qt,{className:"text-base",children:"Public Interest Form"})}),e.jsxs(De,{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(re,{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(zn,{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(pa,{className:"h-3.5 w-3.5"}):e.jsx(Pa,{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(Tr,{className:"h-3.5 w-3.5"})})})]})]})]}),e.jsxs(_e,{children:[e.jsx(zt,{children:e.jsxs(qt,{className:"text-base",children:["Interest Submissions (",l.length,")"]})}),e.jsx(De,{children:l.length===0?e.jsxs("div",{className:"text-center py-8",children:[e.jsx(Yl,{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(We,{variant:"outline",className:h(m.status),children:m.status})]}),e.jsxs("div",{className:"flex flex-wrap gap-3 text-xs text-muted-foreground",children:[m.email&&e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(mn,{className:"h-3 w-3"}),m.email]}),m.phone&&e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(ga,{className:"h-3 w-3"}),m.phone]}),m.current_brokerage&&e.jsxs("span",{children:["From: ",m.current_brokerage]}),m.experience_years&&e.jsxs("span",{children:[m.experience_years,"yr exp"]})]}),m.why_interested&&e.jsxs("p",{className:"text-xs text-muted-foreground mt-1 italic",children:['"',m.why_interested,'"']}),e.jsx("p",{className:"text-[10px] text-muted-foreground mt-1",children:Js(new Date(m.created_at),"MMM d, yyyy h:mm a")})]}),e.jsxs(Ns,{value:m.status,onValueChange:f=>c.mutate({id:m.id,status:f}),children:[e.jsx(ws,{className:"h-7 text-xs w-[110px]",children:e.jsx(ks,{})}),e.jsxs(js,{children:[e.jsx(nt,{value:"new",children:"New"}),e.jsx(nt,{value:"contacted",children:"Contacted"}),e.jsx(nt,{value:"converted",children:"Converted"}),e.jsx(nt,{value:"dismissed",children:"Dismissed"})]})]})]},m.id))})})]})]})}function b9t({brokerageId:s}){const{toast:t}=Ci(),n=as(),[r,a]=N.useState(!1),[i,l]=N.useState({prospect_id:"",title:"",description:"",due_date:Js(Ad(new Date,1),"yyyy-MM-dd'T'HH:mm")}),[o,c]=N.useState("pending"),{data:d=[]}=mt({queryKey:["recruit-prospects-list",s],queryFn:async()=>{const{data:T,error:P}=await H.from("recruit_prospects").select("id, first_name, last_name").eq("brokerage_id",s).order("first_name");if(P)throw P;return T}}),{data:u=[],isLoading:h}=mt({queryKey:["recruit-follow-ups",s],queryFn:async()=>{const T=d.map(M=>M.id);if(!T.length)return[];const{data:P,error:I}=await H.from("recruit_follow_ups").select("*").in("prospect_id",T).order("due_date");if(I)throw I;return P},enabled:d.length>0}),m=Object.fromEntries(d.map(T=>[T.id,T])),f=_t({mutationFn:async T=>{const{data:{user:P}}=await H.auth.getUser();if(!P)throw new Error("Not authenticated");const{error:I}=await H.from("recruit_follow_ups").insert({prospect_id:T.prospect_id,assigned_to:P.id,title:T.title,description:T.description||null,due_date:new Date(T.due_date).toISOString()});if(I)throw I},onSuccess:()=>{n.invalidateQueries({queryKey:["recruit-follow-ups",s]}),t({title:"Follow-up scheduled"}),l({prospect_id:"",title:"",description:"",due_date:Js(Ad(new Date,1),"yyyy-MM-dd'T'HH:mm")}),a(!1)},onError:T=>t({title:"Error",description:T.message,variant:"destructive"})}),g=_t({mutationFn:async({id:T,completed:P})=>{const{error:I}=await H.from("recruit_follow_ups").update({completed_at:P?new Date().toISOString():null}).eq("id",T);if(I)throw I},onSuccess:()=>n.invalidateQueries({queryKey:["recruit-follow-ups",s]})}),y=u.filter(T=>o==="pending"?!T.completed_at:o==="completed"?!!T.completed_at:!0),x=y.filter(T=>!T.completed_at&&x5(new Date(T.due_date))&&!O0(new Date(T.due_date))),_=y.filter(T=>!T.completed_at&&O0(new Date(T.due_date))),b=y.filter(T=>!T.completed_at&&!x5(new Date(T.due_date))&&!O0(new Date(T.due_date))),k=y.filter(T=>!!T.completed_at),A=T=>{const P=m[T.prospect_id],I=!T.completed_at&&x5(new Date(T.due_date))&&!O0(new Date(T.due_date));return e.jsxs("div",{className:"flex items-start gap-3 p-3 border rounded-lg",children:[e.jsx(Bi,{checked:!!T.completed_at,onCheckedChange:M=>g.mutate({id:T.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 ${T.completed_at?"line-through text-muted-foreground":""}`,children:T.title}),T.description&&e.jsx("p",{className:"text-xs text-muted-foreground",children:T.description}),e.jsxs("div",{className:"flex items-center gap-2 mt-1 text-xs text-muted-foreground",children:[P&&e.jsxs(We,{variant:"secondary",className:"text-[10px]",children:[P.first_name," ",P.last_name]}),e.jsxs("span",{className:`flex items-center gap-1 ${I?"text-destructive font-medium":""}`,children:[I?e.jsx(Uo,{className:"h-3 w-3"}):e.jsx(ta,{className:"h-3 w-3"}),Js(new Date(T.due_date),"MMM d, h:mm a")]}),T.is_automated&&e.jsx(We,{variant:"outline",className:"text-[10px]",children:"Auto"})]})]})]},T.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(T=>e.jsxs(B,{size:"sm",variant:o===T?"default":"outline",onClick:()=>c(T),className:"capitalize text-xs",children:[T," ",T==="pending"&&x.length+_.length+b.length>0&&`(${x.length+_.length+b.length})`]},T))}),e.jsxs(B,{size:"sm",onClick:()=>a(!0),children:[e.jsx(nn,{className:"h-4 w-4 mr-1"})," Add Follow-up"]})]}),o!=="completed"&&x.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(Uo,{className:"h-3.5 w-3.5"})," Overdue (",x.length,")"]}),x.map(A)]}),o!=="completed"&&_.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(Xr,{className:"h-3.5 w-3.5"})," Today (",_.length,")"]}),_.map(A)]}),o!=="completed"&&b.length>0&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs("h3",{className:"text-xs font-semibold text-muted-foreground flex items-center gap-1",children:[e.jsx(ta,{className:"h-3.5 w-3.5"})," Upcoming (",b.length,")"]}),b.map(A)]}),o!=="pending"&&k.length>0&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs("h3",{className:"text-xs font-semibold text-muted-foreground flex items-center gap-1",children:[e.jsx(pa,{className:"h-3.5 w-3.5"})," Completed (",k.length,")"]}),k.map(A)]}),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(Bs,{open:r,onOpenChange:a,children:e.jsxs(Fs,{children:[e.jsx(qs,{children:e.jsx($s,{children:"Schedule Follow-up"})}),e.jsxs("form",{onSubmit:T=>{T.preventDefault(),f.mutate(i)},className:"space-y-3",children:[e.jsxs("div",{children:[e.jsx(re,{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:T=>l(P=>({...P,prospect_id:T.target.value})),children:[e.jsx("option",{value:"",children:"Select prospect..."}),d.map(T=>e.jsxs("option",{value:T.id,children:[T.first_name," ",T.last_name]},T.id))]})]}),e.jsxs("div",{children:[e.jsx(re,{children:"Task *"}),e.jsx(we,{required:!0,value:i.title,onChange:T=>l(P=>({...P,title:T.target.value})),placeholder:"e.g. Follow-up call"})]}),e.jsxs("div",{children:[e.jsx(re,{children:"Details"}),e.jsx(Ws,{value:i.description,onChange:T=>l(P=>({...P,description:T.target.value})),rows:2})]}),e.jsxs("div",{children:[e.jsx(re,{children:"Due Date *"}),e.jsx(we,{type:"datetime-local",required:!0,value:i.due_date,onChange:T=>l(P=>({...P,due_date:T.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:f.isPending,children:"Schedule"})]})]})]})})]})}const SSn=[{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 _9t({brokerageId:s}){const{toast:t}=Ci(),n=as(),[r,a]=N.useState(null),{data:i,isLoading:l}=mt({queryKey:["recruit-landing-settings",s],queryFn:async()=>{const{data:x,error:_}=await H.from("recruit_landing_page_settings").select("*").eq("brokerage_id",s).maybeSingle();if(_)throw _;return x}}),[o,c]=N.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:SSn,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});N.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=_t({mutationFn:async()=>{const x={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:_}=await H.from("recruit_landing_page_settings").update(x).eq("id",o.id);if(_)throw _}else{const{error:_}=await H.from("recruit_landing_page_settings").insert(x);if(_)throw _}},onSuccess:()=>{n.invalidateQueries({queryKey:["recruit-landing-settings",s]}),t({title:"Landing page saved!"})},onError:x=>t({title:"Error",description:x.message,variant:"destructive"})}),u=async(x,_)=>{const b=x.name.split(".").pop(),k=`${s}/${_}-${Date.now()}.${b}`,{error:A}=await H.storage.from("recruit-landing").upload(k,x);if(A)throw A;const{data:{publicUrl:T}}=H.storage.from("recruit-landing").getPublicUrl(k);return T},h=async(x,_)=>{var k;const b=(k=x.target.files)==null?void 0:k[0];if(b){a(_);try{const A=await u(b,_);c(T=>({...T,[_]:A})),t({title:"Image uploaded!"})}catch(A){t({title:"Upload failed",description:A.message,variant:"destructive"})}finally{a(null)}}},m=async x=>{var b;const _=(b=x.target.files)==null?void 0:b[0];if(_){a("gallery");try{const k=await u(_,"gallery");c(A=>({...A,gallery_images:[...A.gallery_images,k]})),t({title:"Gallery image added!"})}catch(k){t({title:"Upload failed",description:k.message,variant:"destructive"})}finally{a(null)}}},f=async(x,_)=>{var k;const b=(k=x.target.files)==null?void 0:k[0];if(b){a(`testimonial-${_}`);try{const A=await u(b,`testimonial-${_}`);c(T=>{const P=[...T.testimonials];return P[_]={...P[_],photo_url:A},{...T,testimonials:P}})}catch(A){t({title:"Upload failed",description:A.message,variant:"destructive"})}finally{a(null)}}},{data:g}=mt({queryKey:["brokerage-slug-for-landing",s],queryFn:async()=>{const{data:x,error:_}=await H.from("brokerages").select("recruit_form_slug, recruit_form_enabled").eq("id",s).single();if(_)throw _;return x}}),y=`https://bestbrokerage.relevelup.com/join-brokerage/${(g==null?void 0:g.recruit_form_slug)||""}`;return l?e.jsx("div",{className:"flex justify-center py-12",children:e.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})}):e.jsxs("div",{className:"space-y-6",children:[(g==null?void 0:g.recruit_form_enabled)&&e.jsxs("div",{className:"flex items-center gap-2 p-3 bg-muted/50 rounded-lg border",children:[e.jsx("span",{className:"text-sm text-muted-foreground",children:"Live page:"}),e.jsx("code",{className:"text-xs flex-1 truncate",children:y}),e.jsx(B,{size:"sm",variant:"outline",asChild:!0,children:e.jsxs("a",{href:y,target:"_blank",rel:"noopener noreferrer",children:[e.jsx(Tr,{className:"h-3.5 w-3.5 mr-1"})," Preview"]})})]}),e.jsxs(_e,{children:[e.jsx(zt,{children:e.jsx(qt,{className:"text-base",children:"Branding"})}),e.jsx(De,{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(re,{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(ni,{className:"h-3.5 w-3.5 mr-1"}),r==="logo_url"?"Uploading...":"Upload Logo"]})}),e.jsx("input",{type:"file",accept:"image/*",className:"hidden",onChange:x=>h(x,"logo_url")})]})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(re,{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:x=>c(_=>({..._,primary_color:x.target.value})),className:"h-9 w-12 rounded border cursor-pointer"}),e.jsx(we,{value:o.primary_color,onChange:x=>c(_=>({..._,primary_color:x.target.value})),className:"font-mono text-xs"})]})]}),e.jsxs("div",{children:[e.jsx(re,{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:x=>c(_=>({..._,accent_color:x.target.value})),className:"h-9 w-12 rounded border cursor-pointer"}),e.jsx(we,{value:o.accent_color,onChange:x=>c(_=>({..._,accent_color:x.target.value})),className:"font-mono text-xs"})]})]})]})]})})]}),e.jsxs(_e,{children:[e.jsx(zt,{children:e.jsx(qt,{className:"text-base",children:"Hero Section"})}),e.jsxs(De,{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(re,{children:"Headline"}),e.jsx(we,{value:o.hero_headline,onChange:x=>c(_=>({..._,hero_headline:x.target.value})),placeholder:"Join Our Team"})]}),e.jsxs("div",{children:[e.jsx(re,{children:"Subtext"}),e.jsx(Ws,{value:o.hero_subtext,onChange:x=>c(_=>({..._,hero_subtext:x.target.value})),rows:2,placeholder:"Take your career to the next level..."})]}),e.jsxs("div",{children:[e.jsx(re,{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(ni,{className:"h-3.5 w-3.5 mr-1"}),r==="hero_image_url"?"Uploading...":"Upload Image"]})}),e.jsx("input",{type:"file",accept:"image/*",className:"hidden",onChange:x=>h(x,"hero_image_url")})]}),o.hero_image_url&&e.jsx(B,{variant:"ghost",size:"sm",onClick:()=>c(x=>({...x,hero_image_url:null})),children:e.jsx(qn,{className:"h-3.5 w-3.5"})})]})]})]})]}),e.jsxs(_e,{children:[e.jsxs(zt,{className:"flex flex-row items-center justify-between",children:[e.jsx(qt,{className:"text-base",children:"Benefits / Why Join Us"}),e.jsxs(B,{size:"sm",variant:"outline",onClick:()=>c(x=>({...x,benefits:[...x.benefits,{title:"",description:"",icon:"✨"}]})),children:[e.jsx(nn,{className:"h-3.5 w-3.5 mr-1"})," Add"]})]}),e.jsxs(De,{className:"space-y-3",children:[o.benefits.map((x,_)=>e.jsxs("div",{className:"flex items-start gap-3 p-3 border rounded-lg",children:[e.jsx(Mp,{className:"h-4 w-4 mt-2 text-muted-foreground"}),e.jsx(we,{value:x.icon,onChange:b=>{const k=[...o.benefits];k[_]={...x,icon:b.target.value},c(A=>({...A,benefits:k}))},className:"w-14 text-center"}),e.jsxs("div",{className:"flex-1 space-y-2",children:[e.jsx(we,{value:x.title,onChange:b=>{const k=[...o.benefits];k[_]={...x,title:b.target.value},c(A=>({...A,benefits:k}))},placeholder:"Benefit title"}),e.jsx(we,{value:x.description,onChange:b=>{const k=[...o.benefits];k[_]={...x,description:b.target.value},c(A=>({...A,benefits:k}))},placeholder:"Short description"})]}),e.jsx(B,{variant:"ghost",size:"sm",onClick:()=>c(b=>({...b,benefits:b.benefits.filter((k,A)=>A!==_)})),children:e.jsx(qn,{className:"h-3.5 w-3.5 text-destructive"})})]},_)),o.benefits.length===0&&e.jsx("p",{className:"text-sm text-muted-foreground text-center py-4",children:"No benefits added yet"})]})]}),e.jsxs(_e,{children:[e.jsxs(zt,{className:"flex flex-row items-center justify-between",children:[e.jsx(qt,{className:"text-base",children:"Testimonials"}),e.jsxs(B,{size:"sm",variant:"outline",onClick:()=>c(x=>({...x,testimonials:[...x.testimonials,{name:"",role:"",quote:""}]})),children:[e.jsx(nn,{className:"h-3.5 w-3.5 mr-1"})," Add"]})]}),e.jsxs(De,{className:"space-y-3",children:[o.testimonials.map((x,_)=>{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:[x.photo_url?e.jsx("img",{src:x.photo_url,alt:x.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=x.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-${_}`?"...":"Photo"}),e.jsx("input",{type:"file",accept:"image/*",className:"hidden",onChange:k=>f(k,_)})]})]}),e.jsxs("div",{className:"flex-1 space-y-2",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[e.jsx(we,{value:x.name,onChange:k=>{const A=[...o.testimonials];A[_]={...x,name:k.target.value},c(T=>({...T,testimonials:A}))},placeholder:"Name"}),e.jsx(we,{value:x.role,onChange:k=>{const A=[...o.testimonials];A[_]={...x,role:k.target.value},c(T=>({...T,testimonials:A}))},placeholder:"Role / Title"})]}),e.jsx(Ws,{value:x.quote,onChange:k=>{const A=[...o.testimonials];A[_]={...x,quote:k.target.value},c(T=>({...T,testimonials:A}))},placeholder:"What they say about working here...",rows:2})]}),e.jsx(B,{variant:"ghost",size:"sm",onClick:()=>c(k=>({...k,testimonials:k.testimonials.filter((A,T)=>T!==_)})),children:e.jsx(qn,{className:"h-3.5 w-3.5 text-destructive"})})]},_)}),o.testimonials.length===0&&e.jsx("p",{className:"text-sm text-muted-foreground text-center py-4",children:"No testimonials added yet"})]})]}),e.jsxs(_e,{children:[e.jsxs(zt,{className:"flex flex-row items-center justify-between",children:[e.jsx(qt,{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(pc,{className:"h-3.5 w-3.5 mr-1"}),r==="gallery"?"Uploading...":"Add Photo"]})}),e.jsx("input",{type:"file",accept:"image/*",className:"hidden",onChange:m})]})]}),e.jsx(De,{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((x,_)=>e.jsxs("div",{className:"relative group",children:[e.jsx("img",{src:x,alt:`Gallery ${_+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((k,A)=>A!==_)})),children:e.jsx(qn,{className:"h-3 w-3"})})]},_))}):e.jsx("p",{className:"text-sm text-muted-foreground text-center py-4",children:"No gallery images added yet"})})]}),e.jsxs(_e,{children:[e.jsx(zt,{children:e.jsxs(qt,{className:"text-base flex items-center gap-2",children:[e.jsx(Cn,{className:"h-4 w-4 text-primary"})," Form Style & Trust"]})}),e.jsxs(De,{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(re,{children:"Application Form Style"}),e.jsxs(Ns,{value:o.form_style,onValueChange:x=>c(_=>({..._,form_style:x})),children:[e.jsx(ws,{className:"mt-1.5",children:e.jsx(ks,{})}),e.jsxs(js,{children:[e.jsx(nt,{value:"classic",children:"Classic — single-page form (all fields visible)"}),e.jsx(nt,{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(Au,{className:"h-4 w-4 mt-0.5 text-primary"}),e.jsxs("div",{children:[e.jsx(re,{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(zn,{checked:o.confidential_messaging,onCheckedChange:x=>c(_=>({..._,confidential_messaging:x}))})]})]})]}),e.jsxs(_e,{children:[e.jsxs(zt,{className:"flex flex-row items-center justify-between",children:[e.jsxs(qt,{className:"text-base flex items-center gap-2",children:[e.jsx(u5,{className:"h-4 w-4 text-primary"})," Split & Income Calculator"]}),e.jsx(zn,{checked:o.calculator_enabled,onCheckedChange:x=>c(_=>({..._,calculator_enabled:x}))})]}),o.calculator_enabled&&e.jsxs(De,{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(re,{className:"text-xs",children:"Calculator Headline"}),e.jsx(we,{value:o.calculator_config.headline||"",onChange:x=>c(_=>({..._,calculator_config:{..._.calculator_config,headline:x.target.value}})),placeholder:"See What You Could Earn With Us"})]}),e.jsxs("div",{children:[e.jsx(re,{className:"text-xs",children:"Subtext"}),e.jsx(we,{value:o.calculator_config.subtext||"",onChange:x=>c(_=>({..._,calculator_config:{..._.calculator_config,subtext:x.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(re,{className:"text-xs",children:"Pre-Cap Split % (agent keeps)"}),e.jsx(we,{type:"number",value:o.calculator_config.commission_split_pct??80,onChange:x=>c(_=>({..._,calculator_config:{..._.calculator_config,commission_split_pct:parseFloat(x.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(re,{className:"text-xs",children:"Cap Amount ($)"}),e.jsx(we,{type:"number",value:o.calculator_config.cap_amount??16e3,onChange:x=>c(_=>({..._,calculator_config:{..._.calculator_config,cap_amount:parseFloat(x.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(re,{className:"text-xs",children:"Post-Cap Split % (agent keeps)"}),e.jsx(we,{type:"number",value:o.calculator_config.post_cap_split_pct??100,onChange:x=>c(_=>({..._,calculator_config:{..._.calculator_config,post_cap_split_pct:parseFloat(x.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(re,{className:"text-xs",children:"Monthly Fee ($)"}),e.jsx(we,{type:"number",value:o.calculator_config.monthly_fee??99,onChange:x=>c(_=>({..._,calculator_config:{..._.calculator_config,monthly_fee:parseFloat(x.target.value)||0}}))})]}),e.jsxs("div",{children:[e.jsx(re,{className:"text-xs",children:"Per-Transaction Fee ($)"}),e.jsx(we,{type:"number",value:o.calculator_config.transaction_fee??0,onChange:x=>c(_=>({..._,calculator_config:{..._.calculator_config,transaction_fee:parseFloat(x.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(re,{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(zn,{checked:o.calculator_config.show_email_capture!==!1,onCheckedChange:x=>c(_=>({..._,calculator_config:{..._.calculator_config,show_email_capture:x}}))})]})]})]}),e.jsxs(_e,{children:[e.jsxs(zt,{className:"flex flex-row items-center justify-between",children:[e.jsxs(qt,{className:"text-base flex items-center gap-2",children:[e.jsx(uD,{className:"h-4 w-4 text-primary"})," Lead Magnet (Gated PDF)"]}),e.jsx(zn,{checked:o.lead_magnet_enabled,onCheckedChange:x=>c(_=>({..._,lead_magnet_enabled:x}))})]}),o.lead_magnet_enabled&&e.jsxs(De,{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(re,{className:"text-xs",children:"Title"}),e.jsx(we,{value:o.lead_magnet_config.title||"",onChange:x=>c(_=>({..._,lead_magnet_config:{..._.lead_magnet_config,title:x.target.value}})),placeholder:"Get the Full Comp Plan PDF"})]}),e.jsxs("div",{children:[e.jsx(re,{className:"text-xs",children:"Description"}),e.jsx(Ws,{rows:2,value:o.lead_magnet_config.description||"",onChange:x=>c(_=>({..._,lead_magnet_config:{..._.lead_magnet_config,description:x.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(re,{className:"text-xs",children:"Button Text"}),e.jsx(we,{value:o.lead_magnet_config.button_text||"",onChange:x=>c(_=>({..._,lead_magnet_config:{..._.lead_magnet_config,button_text:x.target.value}})),placeholder:"Email Me the PDF"})]}),e.jsxs("div",{children:[e.jsx(re,{className:"text-xs",children:"PDF / File URL"}),e.jsxs("div",{className:"flex items-center gap-2 mt-1",children:[e.jsx(we,{value:o.lead_magnet_config.pdf_url||"",onChange:x=>c(_=>({..._,lead_magnet_config:{..._.lead_magnet_config,pdf_url:x.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(ni,{className:"h-3.5 w-3.5 mr-1"}),r==="lead_magnet_pdf"?"...":"Upload"]})}),e.jsx("input",{type:"file",accept:"application/pdf,.pdf,.doc,.docx",className:"hidden",onChange:async x=>{var b;const _=(b=x.target.files)==null?void 0:b[0];if(_){a("lead_magnet_pdf");try{const k=await u(_,"lead-magnet");c(A=>({...A,lead_magnet_config:{...A.lead_magnet_config,pdf_url:k}})),t({title:"PDF uploaded!"})}catch(k){t({title:"Upload failed",description:k.message,variant:"destructive"})}finally{a(null)}}}})]})]})]})]})]})]}),e.jsx(CSn,{brokerageId:s}),e.jsx("div",{className:"flex justify-end",children:e.jsxs(B,{onClick:()=>d.mutate(),disabled:d.isPending,size:"lg",children:[e.jsx(Kl,{className:"h-4 w-4 mr-2"}),d.isPending?"Saving...":"Save Landing Page"]})})]})}function CSn({brokerageId:s}){const{data:t=[]}=mt({queryKey:["lead-magnet-downloads",s],queryFn:async()=>{const{data:n,error:r}=await H.from("recruit_lead_magnet_downloads").select("*").eq("brokerage_id",s).order("created_at",{ascending:!1}).limit(100);if(r)throw r;return n}});return t.length===0?null:e.jsxs(_e,{children:[e.jsx(zt,{children:e.jsxs(qt,{className:"text-base flex items-center gap-2",children:[e.jsx(oi,{className:"h-4 w-4 text-primary"})," Lead Magnet Downloads (",t.length,")"]})}),e.jsx(De,{children:e.jsx("div",{className:"space-y-2 max-h-80 overflow-y-auto",children:t.map(n=>e.jsx("div",{className:"flex items-center justify-between gap-3 p-2.5 border rounded-lg text-sm",children:e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"font-medium truncate",children:[n.first_name||"—"," · ",n.email]}),e.jsxs("div",{className:"text-[11px] text-muted-foreground",children:[Js(new Date(n.created_at),"MMM d, yyyy h:mm a")," · via ",n.source]})]})},n.id))})})]})}function w9t({brokerageId:s,trigger:t,initialProspectId:n,open:r,onOpenChange:a}){const[i,l]=N.useState(!1),o=r??i,c=a??l,[d,u]=N.useState("pick-recipients"),[h,m]=N.useState(new Set(n?[n]:[])),[f,g]=N.useState("all"),[y,x]=N.useState(""),[_,b]=N.useState(null),[k,A]=N.useState(""),[T,P]=N.useState(0),[I,M]=N.useState(0),[L,z]=N.useState(""),[$,V]=N.useState(""),{data:W}=AAe(),[G,X]=N.useState("default");N.useEffect(()=>{X(W!=null&&W.massEmail?"mass_email":W!=null&&W.gmail?"gmail":"default")},[W==null?void 0:W.massEmail,W==null?void 0:W.gmail]);const[te,ne]=N.useState(null),{prospects:me,stages:ue}=DJ(s),ce=c9t(),ae=G3(),{data:he=[]}=mt({queryKey:["brokerage-recruit-video-pool",s],queryFn:async()=>{const{data:Ne,error:Ge}=await H.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(Ge)throw Ge;return Ne??[]},enabled:o&&d==="pick-video"}),xe=N.useCallback(()=>{u("pick-recipients"),m(new Set(n?[n]:[])),g("all"),x(""),b(null),A(""),P(0),M(0),z(""),V(""),X("default"),ne(null)},[n]),ve=Ne=>{!Ne&&(d==="uploading"||d==="processing"||d==="sending")||(c(Ne),Ne||setTimeout(xe,200))},ge=N.useMemo(()=>me.filter(Ne=>{if(!Ne.email||f!=="all"&&Ne.stage_id!==f)return!1;if(y){const Ge=y.toLowerCase();if(!`${Ne.first_name} ${Ne.last_name??""}`.toLowerCase().includes(Ge)&&!Ne.email.toLowerCase().includes(Ge))return!1}return!0}),[me,f,y]),be=Ne=>{m(Ge=>{const Ce=new Set(Ge);return Ce.has(Ne)?Ce.delete(Ne):Ce.add(Ne),Ce})},Se=()=>{h.size===ge.length?m(new Set):m(new Set(ge.map(Ne=>Ne.id)))},Ie=N.useCallback(async(Ne,Ge)=>{u("uploading");try{const Ce=`Recruiting blast (${h.size} recipients)`,{videoId:Fe,libraryId:Ae}=await sO(Ce),{uploadUrl:Xe,apiKey:$e}=await nO(Fe),Ye=new XMLHttpRequest;Ye.upload.onprogress=Ct=>{Ct.lengthComputable&&P(Ct.loaded/Ct.total*100)},await new Promise((Ct,Yt)=>{Ye.onload=()=>Ye.status>=200&&Ye.status<300?Ct():Yt(new Error("Upload failed")),Ye.onerror=()=>Yt(new Error("Upload failed")),Ye.open("PUT",Xe),Ye.setRequestHeader("AccessKey",$e),Ye.send(Ne)}),u("processing");const Je=`https://iframe.mediadelivery.net/embed/${Ae}/${Fe}`;let Ke=0;const st=Date.now(),rt=9e4;for(;Ke<4&&(await new Promise(Yt=>setTimeout(Yt,3e3)),!(Date.now()-st>rt));){const Ct=await F5(Fe);if(Ke=Ct.status,M(Ct.encodeProgress||0),Ke===5||Ke===6)throw new Error("Video processing failed")}const Ze=await F5(Fe),ht=(Ze.storageSize||Ne.size)/(1024*1024),Bt=await ae.mutateAsync({bunny_video_id:Fe,playback_url:Ze.directPlayUrl||Je,thumbnail_url:Ze.thumbnailUrl,preview_url:Ze.previewUrl||null,duration_seconds:Ze.length||Ge,file_size_mb:ht,title:Ce,status:Ke>=4?"ready":"processing",touch_type:"recruiting"});b(Bt.id),A(Ce),u("compose")}catch(Ce){ie.error((Ce==null?void 0:Ce.message)||"Failed to upload video"),u("pick-video")}},[h.size,ae]),Me=N.useCallback(async()=>{if(!(!_||h.size===0)){u("sending");try{const Ne=[];for(const Fe of h){const Ae=await ce.mutateAsync({prospect_id:Fe,video_id:_,brokerage_id:s,message:$||void 0});Ne.push(Ae.id)}const{data:Ge,error:Ce}=await H.functions.invoke("send-recruit-video-email",{body:{recruit_video_ids:Ne,brokerage_id:s,subject_override:L||void 0,message_override:$||void 0,send_via:G}});if(Ce)throw new Error(Ce.message);ne({sent:(Ge==null?void 0:Ge.sent)??0,total:(Ge==null?void 0:Ge.total)??Ne.length}),u("done"),ie.success(`Sent ${(Ge==null?void 0:Ge.sent)??0} of ${(Ge==null?void 0:Ge.total)??Ne.length} videos`)}catch(Ne){ie.error((Ne==null?void 0:Ne.message)||"Failed to send"),u("compose")}}},[_,h,s,$,L,G,ce]),Re=h.size,Be=me.filter(Ne=>!Ne.email).length;return e.jsxs(Bs,{open:o,onOpenChange:ve,children:[t&&e.jsx(Ao,{asChild:!0,children:t}),e.jsxs(Fs,{className:"max-w-3xl max-h-[90vh] overflow-hidden flex flex-col",children:[e.jsx(qs,{children:e.jsxs($s,{className:"flex items-center gap-2",children:[e.jsx(na,{className:"h-5 w-5 text-primary"}),"Send Recruiting Video",Re>0&&e.jsxs(We,{variant:"secondary",className:"ml-2",children:[e.jsx(Yn,{className:"h-3 w-3 mr-1"}),Re," ",Re===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(Gr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(we,{placeholder:"Search prospects...",value:y,onChange:Ne=>x(Ne.target.value),className:"pl-9"})]}),e.jsxs(Ns,{value:f,onValueChange:g,children:[e.jsx(ws,{className:"w-48",children:e.jsx(ks,{})}),e.jsxs(js,{children:[e.jsx(nt,{value:"all",children:"All stages"}),ue.map(Ne=>e.jsx(nt,{value:Ne.id,children:Ne.name},Ne.id))]})]})]}),e.jsxs("div",{className:"flex items-center justify-between text-xs text-muted-foreground",children:[e.jsxs("button",{onClick:Se,className:"hover:underline",children:[h.size===ge.length&&ge.length>0?"Deselect all":"Select all"," ","(",ge.length,")"]}),Be>0&&e.jsxs("span",{children:[Be," prospect(s) hidden — no email on file"]})]}),e.jsx(lo,{className:"flex-1 border rounded-md",children:ge.length===0?e.jsx("div",{className:"p-8 text-center text-sm text-muted-foreground",children:"No prospects match. Make sure prospects have email addresses."}):e.jsx("div",{className:"divide-y",children:ge.map(Ne=>{const Ge=h.has(Ne.id),Ce=ue.find(Fe=>Fe.id===Ne.stage_id);return e.jsxs("label",{className:"flex items-center gap-3 p-3 hover:bg-muted/30 cursor-pointer",children:[e.jsx(Bi,{checked:Ge,onCheckedChange:()=>be(Ne.id)}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("p",{className:"font-medium text-sm truncate",children:[Ne.first_name," ",Ne.last_name]}),Ce&&e.jsx(We,{variant:"outline",className:"text-[10px]",style:{borderColor:Ce.color,color:Ce.color},children:Ce.name})]}),e.jsxs("p",{className:"text-xs text-muted-foreground truncate",children:[Ne.email," ",Ne.current_brokerage&&`· ${Ne.current_brokerage}`]})]})]},Ne.id)})})}),e.jsxs(Cr,{children:[e.jsx(B,{variant:"outline",onClick:()=>ve(!1),children:"Cancel"}),e.jsx(B,{disabled:Re===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(ya,{defaultValue:"record",className:"flex-1 flex flex-col overflow-hidden",children:[e.jsxs(va,{className:"self-start",children:[e.jsxs(ls,{value:"record",children:[e.jsx(nn,{className:"h-3.5 w-3.5 mr-1"}),"Record New"]}),e.jsxs(ls,{value:"library",children:[e.jsx(rb,{className:"h-3.5 w-3.5 mr-1"}),"Use Existing"]})]}),e.jsx(_s,{value:"record",className:"flex-1 overflow-auto",children:e.jsxs("div",{className:"text-center py-8 space-y-4",children:[e.jsx(Rh,{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 ",Re," ",Re===1?"recipient":"recipients"," — each gets their own tracked link."]})]}),e.jsxs(B,{onClick:()=>u("record"),children:[e.jsx(na,{className:"h-4 w-4 mr-2"}),"Start Recording"]})]})}),e.jsx(_s,{value:"library",className:"flex-1 overflow-auto",children:he.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:he.map(Ne=>e.jsxs("button",{onClick:()=>{b(Ne.id),A(Ne.title||"Untitled"),u("compose")},className:"text-left group rounded-md border overflow-hidden hover:border-primary transition-colors",children:[e.jsx("div",{className:"aspect-video bg-muted relative",children:r5(Ne)?e.jsx("img",{src:r5(Ne),alt:"",className:"w-full h-full object-cover",referrerPolicy:"no-referrer"}):e.jsx("div",{className:"w-full h-full flex items-center justify-center",children:e.jsx(na,{className:"h-8 w-8 text-muted-foreground"})})}),e.jsx("div",{className:"p-2",children:e.jsx("p",{className:"text-xs font-medium truncate",children:Ne.title||"Untitled"})})]},Ne.id))})})]}),e.jsx(Cr,{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(oO,{maxDurationSeconds:600,onRecordingComplete:Ie}),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(us,{className:"h-8 w-8 animate-spin mx-auto text-primary"}),e.jsx("p",{className:"font-medium",children:d==="uploading"?"Uploading video…":"Processing video…"}),e.jsx(ro,{value:d==="uploading"?T:I,className:"mx-auto max-w-sm"}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:[Math.round(d==="uploading"?T:I),"%"]})]}),d==="compose"&&e.jsxs("div",{className:"flex-1 overflow-auto space-y-4",children:[e.jsxs("div",{className:"rounded-md border p-3 bg-muted/30 flex items-center gap-3",children:[e.jsx(Hr,{className:"h-4 w-4 text-primary"}),e.jsxs("div",{className:"flex-1 text-sm",children:[e.jsx("span",{className:"font-medium",children:k})," selected · sending to ",e.jsx("strong",{children:Re})," recipient",Re===1?"":"s"]})]}),e.jsxs("div",{children:[e.jsx(re,{className:"text-xs",children:"Subject (optional override)"}),e.jsx(we,{value:L,onChange:Ne=>z(Ne.target.value),placeholder:"[First Name], I made you a quick video 🎥",className:"mt-1"}),e.jsx("p",{className:"text-[11px] text-muted-foreground mt-1",children:"Leave blank to use the default personalized subject."})]}),e.jsxs("div",{children:[e.jsx(re,{className:"text-xs",children:"Personal message shown in the email & on the landing page"}),e.jsx(Ws,{value:$,onChange:Ne=>V(Ne.target.value),placeholder:"Hey there — wanted to share a quick thought on what we're building here...",rows:5,className:"mt-1"})]}),e.jsx(XWe,{value:G,onChange:X}),e.jsxs(Cr,{children:[e.jsx(B,{variant:"outline",onClick:()=>u("pick-video"),children:"Back"}),e.jsxs(B,{onClick:Me,disabled:!_||Re===0,children:[e.jsx(Rr,{className:"h-4 w-4 mr-2"})," Send to ",Re," ",Re===1?"prospect":"prospects"]})]})]}),d==="sending"&&e.jsxs("div",{className:"py-12 text-center space-y-3",children:[e.jsx(us,{className:"h-8 w-8 animate-spin mx-auto text-primary"}),e.jsxs("p",{className:"font-medium",children:["Sending to ",Re," recipient",Re===1?"":"s","…"]}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Each prospect gets their own tracked share link."})]}),d==="done"&&te&&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 ${te.sent===te.total?"bg-primary/10":"bg-muted"}`,children:te.sent===te.total?e.jsx(Hr,{className:"h-8 w-8 text-primary"}):e.jsx(Uo,{className:"h-8 w-8 text-muted-foreground"})}),e.jsxs("div",{children:[e.jsxs("p",{className:"font-semibold text-lg",children:[te.sent," of ",te.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:()=>ve(!1),children:"Done"})]})]})]})}function ASn(s){if(!s)return"—";const t=Math.floor(s/60),n=s%60;return t>0?`${t}m ${n}s`:`${n}s`}function TSn({video:s}){return s.cta_clicked_at?e.jsx(We,{className:"bg-emerald-500/10 text-emerald-600 border-emerald-200",children:"CTA Clicked"}):s.view_count>0?e.jsxs(We,{className:"bg-blue-500/10 text-blue-600 border-blue-200",children:[e.jsx(da,{className:"h-3 w-3 mr-1"}),s.view_count," views"]}):s.sent_at?e.jsxs(We,{variant:"secondary",children:[e.jsx(Rr,{className:"h-3 w-3 mr-1"}),"Sent"]}):e.jsxs(We,{variant:"outline",children:[e.jsx(Xr,{className:"h-3 w-3 mr-1"}),"Draft"]})}function j9t({brokerageId:s}){var k,A,T,P;const{data:t=[],isLoading:n}=gSn(s),{data:r=[]}=u9t(s),a=ySn(),i=vSn(),l=d9t(),[o,c]=N.useState(""),[d,u]=N.useState(!1),[h,m]=N.useState({title:"",script_text:"",category:"general"}),[f,g]=N.useState(null),y=t.filter(I=>{var L,z,$,V;return o?`${((L=I.prospect)==null?void 0:L.first_name)||""} ${((z=I.prospect)==null?void 0:z.last_name)||""}`.toLowerCase().includes(o.toLowerCase())||((V=($=I.video)==null?void 0:$.title)==null?void 0:V.toLowerCase().includes(o.toLowerCase())):!0}),x={total:t.length,sent:t.filter(I=>I.sent_at).length,viewed:t.filter(I=>I.view_count>0).length,ctaClicked:t.filter(I=>I.cta_clicked_at).length},_=N.useCallback(I=>{if(!I)return;const M=`${window.location.origin}/recruit-video/${I}`;navigator.clipboard.writeText(M),ie.success("Share link copied")},[]);N.useCallback((I,M)=>{l.mutate({id:I,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:x.total,icon:na,color:"text-primary"},{label:"Sent",value:x.sent,icon:Rr,color:"text-blue-500"},{label:"Viewed",value:x.viewed,icon:da,color:"text-amber-500"},{label:"CTA Clicked",value:x.ctaClicked,icon:Hr,color:"text-emerald-500"}].map(I=>e.jsx(_e,{children:e.jsxs(De,{className:"p-4 flex items-center gap-3",children:[e.jsx("div",{className:`h-10 w-10 rounded-lg bg-muted flex items-center justify-center ${I.color}`,children:e.jsx(I.icon,{className:"h-5 w-5"})}),e.jsxs("div",{children:[e.jsx("p",{className:"text-2xl font-bold",children:I.value}),e.jsx("p",{className:"text-xs text-muted-foreground",children:I.label})]})]})},I.label))}),e.jsxs(ya,{defaultValue:"videos",className:"space-y-4",children:[e.jsxs(va,{children:[e.jsxs(ls,{value:"videos",children:[e.jsx(na,{className:"h-4 w-4 mr-1.5"}),"All Videos"]}),e.jsxs(ls,{value:"scripts",children:[e.jsx(Wr,{className:"h-4 w-4 mr-1.5"}),"Script Library"]}),e.jsxs(ls,{value:"analytics",children:[e.jsx(fl,{className:"h-4 w-4 mr-1.5"}),"Engagement"]})]}),e.jsx(_s,{value:"videos",children:e.jsxs(_e,{children:[e.jsx(zt,{className:"pb-3",children:e.jsxs("div",{className:"flex items-center justify-between gap-2 flex-wrap",children:[e.jsx(qt,{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(Gr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(we,{placeholder:"Search by name or title...",value:o,onChange:I=>c(I.target.value),className:"pl-9"})]}),e.jsx(w9t,{brokerageId:s,trigger:e.jsxs(B,{size:"sm",className:"gap-1.5",children:[e.jsx(mn,{className:"h-4 w-4"})," Send Video Email"]})})]})]})}),e.jsx(De,{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(na,{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(I=>{var M,L,z,$,V,W,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:[r5(I.video)?e.jsx("img",{src:r5(I.video),alt:"",className:"h-full w-full object-cover",referrerPolicy:"no-referrer"}):e.jsx("div",{className:"h-full w-full flex items-center justify-center",children:e.jsx(na,{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:ASn(((M=I.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:[(L=I.prospect)==null?void 0:L.first_name," ",(z=I.prospect)==null?void 0:z.last_name]}),e.jsx(TSn,{video:I})]}),e.jsx("p",{className:"text-sm text-muted-foreground truncate",children:(($=I.video)==null?void 0:$.title)||"Untitled video"}),e.jsxs("p",{className:"text-xs text-muted-foreground mt-0.5",children:[Js(new Date(I.created_at),"MMM d, yyyy"),((V=I.prospect)==null?void 0:V.current_brokerage)&&` · ${I.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:()=>_(I.share_token),title:"Copy share link",children:e.jsx(Pa,{className:"h-4 w-4"})}),e.jsxs(B,{variant:I.sent_at?"ghost":"default",size:"sm",className:"h-8 gap-1.5",onClick:()=>g(I),disabled:!((W=I.prospect)!=null&&W.email),title:(G=I.prospect)!=null&&G.email?"Email this video to the prospect":"Prospect has no email",children:[e.jsx(mn,{className:"h-4 w-4"}),I.sent_at?"Resend":"Email"]}),I.share_token&&e.jsx(B,{variant:"ghost",size:"icon",className:"h-8 w-8",onClick:()=>window.open(`/recruit-video/${I.share_token}`,"_blank"),title:"Preview landing page",children:e.jsx(Tr,{className:"h-4 w-4"})})]})]},I.id)})})})]})}),e.jsx(_s,{value:"scripts",children:e.jsxs(_e,{children:[e.jsx(zt,{className:"pb-3",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(qt,{className:"text-lg",children:"Recruiting Scripts"}),e.jsxs(Bs,{open:d,onOpenChange:u,children:[e.jsx(Ao,{asChild:!0,children:e.jsxs(B,{size:"sm",children:[e.jsx(nn,{className:"h-4 w-4 mr-1.5"}),"New Script"]})}),e.jsxs(Fs,{children:[e.jsx(qs,{children:e.jsx($s,{children:"Create Recruiting Script"})}),e.jsxs("div",{className:"space-y-4 mt-2",children:[e.jsxs("div",{children:[e.jsx(re,{children:"Title"}),e.jsx(we,{value:h.title,onChange:I=>m(M=>({...M,title:I.target.value})),placeholder:"e.g., Why Switch to Our Brokerage"})]}),e.jsxs("div",{children:[e.jsx(re,{children:"Category"}),e.jsxs(Ns,{value:h.category,onValueChange:I=>m(M=>({...M,category:I})),children:[e.jsx(ws,{children:e.jsx(ks,{})}),e.jsx(js,{children:vze.map(I=>e.jsx(nt,{value:I.value,children:I.label},I.value))})]})]}),e.jsxs("div",{children:[e.jsx(re,{children:"Script"}),e.jsx(Ws,{value:h.script_text,onChange:I=>m(M=>({...M,script_text:I.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(De,{children:r.length===0?e.jsxs("div",{className:"text-center py-12 text-muted-foreground",children:[e.jsx(Wr,{className:"h-12 w-12 mx-auto mb-4 opacity-50"}),e.jsx("p",{className:"font-medium",children:"No scripts yet"}),e.jsx("p",{className:"text-sm mt-1",children:"Create teleprompter scripts for common recruiting conversations"})]}):e.jsx("div",{className:"grid gap-3 md:grid-cols-2",children:r.map(I=>{var L;const M=((L=vze.find(z=>z.value===I.category))==null?void 0:L.label)||I.category;return e.jsx(_e,{className:"relative group",children:e.jsxs(De,{className:"p-4",children:[e.jsxs("div",{className:"flex items-start justify-between",children:[e.jsxs("div",{children:[e.jsx(We,{variant:"outline",className:"text-[10px] mb-2",children:M}),e.jsx("h4",{className:"font-medium text-sm",children:I.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(I.id),children:e.jsx(qn,{className:"h-3.5 w-3.5"})})]}),e.jsx("p",{className:"text-xs text-muted-foreground mt-2 line-clamp-3",children:I.script_text}),I.is_global&&e.jsx(We,{variant:"secondary",className:"mt-2 text-[10px]",children:"Template"})]})},I.id)})})})]})}),e.jsx(_s,{value:"analytics",children:e.jsxs(_e,{children:[e.jsx(zt,{children:e.jsx(qt,{className:"text-lg",children:"Engagement Funnel"})}),e.jsxs(De,{children:[e.jsx("div",{className:"space-y-4",children:[{label:"Videos Created",count:x.total,pct:100,color:"bg-primary"},{label:"Sent to Prospects",count:x.sent,pct:x.total?Math.round(x.sent/x.total*100):0,color:"bg-blue-500"},{label:"Viewed by Prospect",count:x.viewed,pct:x.sent?Math.round(x.viewed/x.sent*100):0,color:"bg-amber-500"},{label:"CTA Clicked",count:x.ctaClicked,pct:x.viewed?Math.round(x.ctaClicked/x.viewed*100):0,color:"bg-emerald-500"}].map(I=>e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs("div",{className:"flex justify-between text-sm",children:[e.jsx("span",{children:I.label}),e.jsxs("span",{className:"font-medium",children:[I.count," (",I.pct,"%)"]})]}),e.jsx("div",{className:"h-3 bg-muted rounded-full overflow-hidden",children:e.jsx("div",{className:`h-full ${I.color} rounded-full transition-all`,style:{width:`${I.pct}%`}})})]},I.label))}),t.filter(I=>I.view_count>0).length>0&&e.jsxs("div",{className:"mt-8",children:[e.jsx("h4",{className:"font-medium text-sm mb-3",children:"Most Engaged Prospects"}),e.jsx("div",{className:"space-y-2",children:t.filter(I=>I.view_count>0).sort((I,M)=>M.view_count-I.view_count).slice(0,5).map(I=>{var M,L;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=I.prospect)==null?void 0:M.first_name," ",(L=I.prospect)==null?void 0:L.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(da,{className:"h-3.5 w-3.5"})," ",I.view_count]}),I.cta_clicked_at&&e.jsx(Hr,{className:"h-4 w-4 text-emerald-500"})]})]},I.id)})})]})]})]})})]}),f&&e.jsx(l9t,{open:!!f,onOpenChange:I=>{I||g(null)},recruitVideoId:f.id,brokerageId:s,prospectName:`${((k=f.prospect)==null?void 0:k.first_name)||""} ${((A=f.prospect)==null?void 0:A.last_name)||""}`.trim(),prospectEmail:(T=f.prospect)==null?void 0:T.email,videoTitle:(P=f.video)==null?void 0:P.title,defaultMessage:f.message})]})}function N9t({brokerageId:s}){const{toast:t}=Ci(),n=as(),{stages:r,prospects:a}=DJ(s),[i,l]=N.useState(!1),[o,c]=N.useState({title:"",target_count:"10",target_stage_id:"",period_start:Js(new Date,"yyyy-MM-dd"),period_end:Js(new Date(new Date().getFullYear(),new Date().getMonth()+3,0),"yyyy-MM-dd")}),{data:d=[],isLoading:u}=mt({queryKey:["recruit-goals",s],queryFn:async()=>{const{data:g,error:y}=await H.from("recruit_goals").select("*").eq("brokerage_id",s).order("period_end",{ascending:!1});if(y)throw y;return g}}),h=_t({mutationFn:async g=>{const{data:{user:y}}=await H.auth.getUser();if(!y)throw new Error("Not authenticated");const{error:x}=await H.from("recruit_goals").insert({brokerage_id:s,title:g.title,target_count:parseInt(g.target_count),target_stage_id:g.target_stage_id||null,period_start:g.period_start,period_end:g.period_end,created_by:y.id});if(x)throw x},onSuccess:()=>{n.invalidateQueries({queryKey:["recruit-goals",s]}),t({title:"Goal created"}),l(!1)},onError:g=>t({title:"Error",description:g.message,variant:"destructive"})}),m=_t({mutationFn:async g=>{const{error:y}=await H.from("recruit_goals").delete().eq("id",g);if(y)throw y},onSuccess:()=>{n.invalidateQueries({queryKey:["recruit-goals",s]}),t({title:"Goal removed"})}}),f=g=>{const y=r.find(_=>_.id===g.target_stage_id);return{count:a.filter(_=>M2(new Date(_.created_at),{start:new Date(g.period_start),end:new Date(g.period_end)})?g.target_stage_id?_.stage_id===g.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(nn,{className:"h-4 w-4 mr-1"})," New Goal"]})]}),d.length===0?e.jsxs(_e,{className:"py-12 text-center",children:[e.jsx(iu,{className:"h-10 w-10 mx-auto text-muted-foreground mb-3"}),e.jsx("p",{className:"text-muted-foreground",children:"No goals set. Create a recruiting target to track progress."})]}):e.jsx("div",{className:"grid md:grid-cols-2 gap-4",children:d.map(g=>{const{count:y,stage:x}=f(g),_=Math.min(100,y/g.target_count*100),b=M2(new Date,{start:new Date(g.period_start),end:new Date(g.period_end)});return e.jsxs(_e,{className:b?"":"opacity-60",children:[e.jsx(zt,{className:"pb-2",children:e.jsxs("div",{className:"flex items-start justify-between",children:[e.jsxs("div",{children:[e.jsx(qt,{className:"text-sm",children:g.title}),e.jsxs("p",{className:"text-xs text-muted-foreground mt-0.5",children:[Js(new Date(g.period_start),"MMM d")," – ",Js(new Date(g.period_end),"MMM d, yyyy")]})]}),e.jsxs("div",{className:"flex items-center gap-1",children:[b?e.jsx(We,{className:"text-[10px]",children:"Active"}):e.jsx(We,{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(g.id),children:e.jsx(qn,{className:"h-3.5 w-3.5"})})]})]})}),e.jsxs(De,{className:"space-y-2",children:[x&&e.jsxs(We,{variant:"outline",className:"text-[10px]",style:{borderColor:x.color,color:x.color},children:["Stage: ",x.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:["/ ",g.target_count]})]}),e.jsx(ro,{value:_,className:"h-2"}),e.jsxs("p",{className:"text-xs text-muted-foreground text-right",children:[_.toFixed(0),"% complete"]})]})]},g.id)})}),e.jsx(Bs,{open:i,onOpenChange:l,children:e.jsxs(Fs,{children:[e.jsx(qs,{children:e.jsx($s,{children:"Create Recruiting Goal"})}),e.jsxs("form",{onSubmit:g=>{g.preventDefault(),h.mutate(o)},className:"space-y-3",children:[e.jsxs("div",{children:[e.jsx(re,{children:"Goal Title *"}),e.jsx(we,{required:!0,value:o.title,onChange:g=>c(y=>({...y,title:g.target.value})),placeholder:"e.g. Q2 Recruiting Target"})]}),e.jsxs("div",{children:[e.jsx(re,{children:"Target Count *"}),e.jsx(we,{type:"number",min:"1",required:!0,value:o.target_count,onChange:g=>c(y=>({...y,target_count:g.target.value}))})]}),e.jsxs("div",{children:[e.jsx(re,{children:"Target Stage (optional)"}),e.jsxs("select",{className:"w-full rounded-md border border-input bg-background px-3 py-2 text-sm",value:o.target_stage_id,onChange:g=>c(y=>({...y,target_stage_id:g.target.value})),children:[e.jsx("option",{value:"",children:"All stages (total prospects)"}),r.map(g=>e.jsx("option",{value:g.id,children:g.name},g.id))]}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:"Count prospects that reach this stage"})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(re,{children:"Start Date"}),e.jsx(we,{type:"date",required:!0,value:o.period_start,onChange:g=>c(y=>({...y,period_start:g.target.value}))})]}),e.jsxs("div",{children:[e.jsx(re,{children:"End Date"}),e.jsx(we,{type:"date",required:!0,value:o.period_end,onChange:g=>c(y=>({...y,period_end:g.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 ESn={first_name:"Sarah",brokerage_name:"ABC Realty",city:"Austin",sender_name:"Jeremy"};function k9t({email:s,mergeValues:t=ESn,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(Bs,{open:!0,onOpenChange:()=>r(),children:e.jsxs(Fs,{className:"max-w-2xl max-h-[85vh] overflow-y-auto p-0",children:[e.jsxs(qs,{className:"px-6 pt-6 pb-4 border-b",children:[e.jsxs($s,{className:"text-base",children:["Email #",s.email_number," — ",s.title]}),e.jsxs("div",{className:"flex items-center gap-3 mt-2",children:[e.jsxs(We,{variant:"outline",className:"text-xs gap-1",children:[e.jsx(Xr,{className:"h-3 w-3"}),s.email_number===1?"Sent immediately":`Day ${s.delay_days}`]}),i.length>1&&e.jsxs(We,{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 QWe({brokerageId:s}){const t=as(),{user:n}=Ls(),[r,a]=N.useState(""),[i,l]=N.useState(!1),[o,c]=N.useState({brokerage_id:s,sender_name:"LevelUp",sender_email:"recruiting@relevelup.com",reply_to_email:"",merge_fields:{city:"",broker_name:""}}),{data:d}=mt({queryKey:["brokerage-recruit-settings",s],queryFn:async()=>{const{data:g,error:y}=await H.from("brokerage_recruit_settings").select("*").eq("brokerage_id",s).maybeSingle();if(y)throw y;return g}}),{data:u}=mt({queryKey:["brokerage-detail",s],queryFn:async()=>{const{data:g,error:y}=await H.from("brokerages").select("name, city, state").eq("id",s).single();if(y)throw y;return g}});N.useEffect(()=>{d?c({...d,merge_fields:d.merge_fields||{city:"",broker_name:""}}):u&&c(g=>({...g,merge_fields:{...g.merge_fields,brokerage_name:u.name,city:u.city||""}}))},[d,u]),N.useEffect(()=>{n!=null&&n.id&&H.from("profiles").select("recruit_cta_url").eq("id",n.id).single().then(({data:g})=>a((g==null?void 0:g.recruit_cta_url)||""))},[n==null?void 0:n.id]);const h=async()=>{if(!(n!=null&&n.id))return;l(!0);const{error:g}=await H.from("profiles").update({recruit_cta_url:r.trim()||null}).eq("id",n.id);l(!1),g?ie.error(g.message):ie.success("Scheduling link saved!")},m=_t({mutationFn:async()=>{const g={brokerage_id:s,sender_name:o.sender_name,sender_email:o.sender_email,reply_to_email:o.reply_to_email||null,merge_fields:o.merge_fields,updated_at:new Date().toISOString()};if(d!=null&&d.id){const{error:y}=await H.from("brokerage_recruit_settings").update(g).eq("id",d.id);if(y)throw y}else{const{error:y}=await H.from("brokerage_recruit_settings").insert(g);if(y)throw y}},onSuccess:()=>{t.invalidateQueries({queryKey:["brokerage-recruit-settings",s]}),ie.success("Recruiting email settings saved!")},onError:g=>ie.error(g.message)}),f=(g,y)=>{c(x=>({...x,merge_fields:{...x.merge_fields,[g]: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(ta,{className:"h-4 w-4 text-primary"}),e.jsx("p",{className:"text-sm font-medium",children:"Your Scheduling Link"})]}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:["This URL powers the ",e.jsx("strong",{children:'"Schedule a Conversation"'})," button on every recruiting video page you send. Paste your Calendly, HubSpot Meetings, Google Calendar booking link, etc."]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(we,{value:r,onChange:g=>a(g.target.value),placeholder:"https://calendly.com/your-name/intro"}),e.jsxs(B,{onClick:h,disabled:i,size:"sm",children:[e.jsx(Kl,{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(re,{className:"text-xs",children:"Sender Display Name"}),e.jsx(we,{value:o.sender_name,onChange:g=>c({...o,sender_name:g.target.value}),placeholder:"e.g. Jeremy at LevelUp"})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(re,{className:"text-xs",children:"Sender Email Address"}),e.jsx(we,{value:o.sender_email,onChange:g=>c({...o,sender_email:g.target.value}),placeholder:"recruiting@relevelup.com"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Must be a verified SES identity. Verify your own address below to send from it."})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(re,{className:"text-xs",children:"Reply-To Email (optional)"}),e.jsx(we,{value:o.reply_to_email,onChange:g=>c({...o,reply_to_email:g.target.value}),placeholder:"jeremy@relevelup.com"})]})]}),e.jsxs("div",{className:"border-t pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[e.jsx(Wv,{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(t9t,{brokerageId:s,onVerifiedSelect:g=>{c(y=>({...y,sender_email:g})),ie.success(`Sender set to ${g}`)}})]}),e.jsxs("div",{className:"border-t pt-4",children:[e.jsx("p",{className:"text-sm font-medium mb-3",children:"Default Merge Fields"}),e.jsx("p",{className:"text-xs text-muted-foreground mb-3",children:"These values will auto-fill in campaign emails for this brokerage."}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(re,{className:"text-xs",children:"{{brokerage_name}}"}),e.jsx(we,{value:o.merge_fields.brokerage_name||"",onChange:g=>f("brokerage_name",g.target.value),placeholder:(u==null?void 0:u.name)||"Brokerage Name"})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(re,{className:"text-xs",children:"{{city}}"}),e.jsx(we,{value:o.merge_fields.city||"",onChange:g=>f("city",g.target.value),placeholder:"e.g. Austin"})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(re,{className:"text-xs",children:"{{sender_name}}"}),e.jsx(we,{value:o.merge_fields.sender_name||"",onChange:g=>f("sender_name",g.target.value),placeholder:"e.g. Jeremy"})]})]})]}),e.jsxs(B,{onClick:()=>m.mutate(),disabled:m.isPending,className:"w-full",children:[e.jsx(Kl,{className:"h-4 w-4 mr-1"})," Save Settings"]})]})}const MSn=uN.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",$m(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()}}}),sgt=[{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 _0({onClick:s,active:t,disabled:n,icon:r,tooltip:a}){return e.jsxs(wu,{children:[e.jsx(ju,{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(nu,{side:"bottom",className:"text-xs",children:a})]})}function LSn({content:s,onChange:t}){const n=qqe({extensions:[Hqe.configure({heading:{levels:[1,2,3]}}),MSn,tVe.configure({openOnClick:!1,HTMLAttributes:{class:"text-primary underline cursor-pointer"}}),sVe.configure({types:["heading","paragraph"]}),nVe,KPt],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())}});N.useEffect(()=>{n&&s!==n.getHTML()&&n.commands.setContent(s)},[s,n]);const r=N.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=N.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(_0,{onClick:()=>n.chain().focus().toggleBold().run(),active:n.isActive("bold"),icon:jT,tooltip:"Bold"}),e.jsx(_0,{onClick:()=>n.chain().focus().toggleItalic().run(),active:n.isActive("italic"),icon:AT,tooltip:"Italic"}),e.jsx(_0,{onClick:()=>n.chain().focus().toggleUnderline().run(),active:n.isActive("underline"),icon:L9,tooltip:"Underline"}),e.jsx(_0,{onClick:()=>n.chain().focus().toggleStrike().run(),active:n.isActive("strike"),icon:jW,tooltip:"Strikethrough"}),e.jsx(Wl,{orientation:"vertical",className:"mx-1 h-6"}),e.jsx(_0,{onClick:()=>n.chain().focus().toggleHeading({level:1}).run(),active:n.isActive("heading",{level:1}),icon:h9,tooltip:"Heading 1"}),e.jsx(_0,{onClick:()=>n.chain().focus().toggleHeading({level:2}).run(),active:n.isActive("heading",{level:2}),icon:m9,tooltip:"Heading 2"}),e.jsx(_0,{onClick:()=>n.chain().focus().toggleHeading({level:3}).run(),active:n.isActive("heading",{level:3}),icon:JG,tooltip:"Heading 3"}),e.jsx(Wl,{orientation:"vertical",className:"mx-1 h-6"}),e.jsx(_0,{onClick:()=>n.chain().focus().toggleBulletList().run(),active:n.isActive("bulletList"),icon:Kx,tooltip:"Bullet List"}),e.jsx(_0,{onClick:()=>n.chain().focus().toggleOrderedList().run(),active:n.isActive("orderedList"),icon:dj,tooltip:"Numbered List"}),e.jsx(_0,{onClick:()=>n.chain().focus().toggleBlockquote().run(),active:n.isActive("blockquote"),icon:Q2,tooltip:"Blockquote"}),e.jsx(_0,{onClick:()=>n.chain().focus().setHorizontalRule().run(),icon:X2,tooltip:"Divider"}),e.jsx(Wl,{orientation:"vertical",className:"mx-1 h-6"}),e.jsx(_0,{onClick:()=>n.chain().focus().setTextAlign("left").run(),active:n.isActive({textAlign:"left"}),icon:nD,tooltip:"Align Left"}),e.jsx(_0,{onClick:()=>n.chain().focus().setTextAlign("center").run(),active:n.isActive({textAlign:"center"}),icon:sD,tooltip:"Align Center"}),e.jsx(_0,{onClick:()=>n.chain().focus().setTextAlign("right").run(),active:n.isActive({textAlign:"right"}),icon:rD,tooltip:"Align Right"}),e.jsx(Wl,{orientation:"vertical",className:"mx-1 h-6"}),e.jsx(_0,{onClick:r,active:n.isActive("link"),icon:gc,tooltip:"Insert Link"}),e.jsx(Wl,{orientation:"vertical",className:"mx-1 h-6"}),e.jsx(_0,{onClick:()=>n.chain().focus().undo().run(),disabled:!n.can().undo(),icon:BT,tooltip:"Undo"}),e.jsx(_0,{onClick:()=>n.chain().focus().redo().run(),disabled:!n.can().redo(),icon:RT,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(qd,{children:[e.jsx(Vd,{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(P9,{className:"h-3.5 w-3.5"}),"Merge Tags"]})}),e.jsx(Ld,{align:"end",className:"w-56",children:sgt.map(i=>e.jsxs(ba,{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($qe,{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:"}),sgt.map(i=>e.jsx(We,{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 PSn({open:s,onClose:t,campaignName:n,stat:r}){return e.jsx(Bs,{open:s,onOpenChange:a=>!a&&t(),children:e.jsxs(Fs,{className:"max-w-3xl max-h-[85vh] overflow-y-auto",children:[e.jsxs(qs,{children:[e.jsxs($s,{className:"flex items-center gap-2",children:[e.jsx(ml,{className:"h-5 w-5 text-primary"}),n," — Engagement Stats"]}),e.jsx(Ar,{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(Rr,{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(Mne,{icon:mn,color:"text-blue-500",label:"Total Sent",value:r.sent.toLocaleString()}),e.jsx(Mne,{icon:da,color:"text-amber-500",label:"Opens",value:`${r.opened.toLocaleString()}`,sub:`${r.openRate.toFixed(1)}% open rate`}),e.jsx(Mne,{icon:ru,color:"text-green-500",label:"Clicks",value:`${r.clicked.toLocaleString()}`,sub:`${r.clickRate.toFixed(1)}% click rate`}),e.jsx(Mne,{icon:xd,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(Xr,{className:"h-3 w-3"})," Last sent: ",Js(new Date(r.lastSentAt),"MMM d, yyyy h:mm a")]}),e.jsxs("div",{children:[e.jsx("h4",{className:"text-sm font-semibold mb-2 mt-4",children:"Per-Email Performance"}),e.jsx("div",{className:"space-y-2",children:r.byEmail.map(a=>{const i=a.sent_count>0?a.opened_count/a.sent_count*100:0,l=a.sent_count>0?a.clicked_count/a.sent_count*100:0;return e.jsx(_e,{className:"overflow-hidden",children:e.jsxs(De,{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(We,{variant:"outline",className:"text-[10px] gap-1",children:[e.jsx(mn,{className:"h-2.5 w-2.5"})," ",a.sent_count.toLocaleString()," sent"]}),e.jsxs(We,{variant:"outline",className:"text-[10px] gap-1 border-amber-500/30 text-amber-600",children:[e.jsx(da,{className:"h-2.5 w-2.5"})," ",a.opened_count.toLocaleString()," (",i.toFixed(1),"%)"]}),e.jsxs(We,{variant:"outline",className:"text-[10px] gap-1 border-green-500/30 text-green-600",children:[e.jsx(ru,{className:"h-2.5 w-2.5"})," ",a.clicked_count.toLocaleString()," (",l.toFixed(1),"%)"]}),a.failed_count>0&&e.jsxs(We,{variant:"outline",className:"text-[10px] gap-1 border-destructive/30 text-destructive",children:[e.jsx(xd,{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 Mne({icon:s,color:t,label:n,value:r,sub:a}){return e.jsx(_e,{children:e.jsx(De,{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 S9t(s){return mt({queryKey:["recruit-campaign-stats",s],enabled:!!s,staleTime:6e4,queryFn:async()=>{const{data:t,error:n}=await H.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 ngt={cold:{icon:nj,color:"text-blue-500",bg:"bg-blue-50 dark:bg-blue-950/30",label:"Cold — Curiosity"},warm:{icon:J2,color:"text-amber-500",bg:"bg-amber-50 dark:bg-amber-950/30",label:"Warm — Growth"},hot:{icon:Cu,color:"text-red-500",bg:"bg-red-50 dark:bg-red-950/30",label:"Hot — Private Invite"}};function C9t({brokerageId:s}){var Se,Ie,Me,Re;const{user:t}=Ls(),n=as(),[r,a]=N.useState(null),[i,l]=N.useState(null),[o,c]=N.useState(null),[d,u]=N.useState(!1),[h,m]=N.useState(!1),[f,g]=N.useState("editor"),[y,x]=N.useState(null),[_,b]=N.useState(null),{data:k={}}=S9t(s),[A,T]=N.useState({name:"",description:"",theme:"",goal:"",primary_cta:"Learn more",warmth_level:"warm",sender_name:"",sender_email:"",reply_to_email:""}),{data:P}=mt({queryKey:["brokerage-detail",s],queryFn:async()=>{const{data:Be,error:Ne}=await H.from("brokerages").select("name, city, state").eq("id",s).single();if(Ne)throw Ne;return Be}}),{data:I}=mt({queryKey:["brokerage-recruit-settings",s],queryFn:async()=>{const{data:Be,error:Ne}=await H.from("brokerage_recruit_settings").select("*").eq("brokerage_id",s).maybeSingle();if(Ne)throw Ne;return Be}}),M={first_name:"Sarah",brokerage_name:((Se=I==null?void 0:I.merge_fields)==null?void 0:Se.brokerage_name)||(P==null?void 0:P.name)||"Your Brokerage",city:((Ie=I==null?void 0:I.merge_fields)==null?void 0:Ie.city)||(P==null?void 0:P.city)||"Your City",sender_name:((Me=I==null?void 0:I.merge_fields)==null?void 0:Me.sender_name)||(I==null?void 0:I.sender_name)||"Your Name"},L=Be=>Be.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:z=[],isLoading:$}=mt({queryKey:["recruit-campaigns",s],queryFn:async()=>{const{data:Be,error:Ne}=await H.from("recruit_campaigns").select("*").or(`brokerage_id.is.null,brokerage_id.eq.${s}`).order("sort_order");if(Ne)throw Ne;return Be}}),{data:V={}}=mt({queryKey:["recruit-campaign-emails",s],enabled:z.length>0,queryFn:async()=>{const Be=z.map(Fe=>Fe.id),{data:Ne,error:Ge}=await H.from("recruit_campaign_emails").select("*").in("campaign_id",Be).order("email_number");if(Ge)throw Ge;const Ce={};return Ne.forEach(Fe=>{Ce[Fe.campaign_id]||(Ce[Fe.campaign_id]=[]),Ce[Fe.campaign_id].push(Fe)}),Ce}}),W=Object.values(V).flat().map(Be=>Be.id),{data:G=[]}=mt({queryKey:["recruit-subject-overrides",s],enabled:W.length>0,queryFn:async()=>{const{data:Be,error:Ne}=await H.from("recruit_brokerage_subject_overrides").select("*").eq("brokerage_id",s);if(Ne)throw Ne;return Be}}),X={};G.forEach(Be=>{X[Be.campaign_email_id]=Be.selected_subject_index});const te=_t({mutationFn:async({campaignEmailId:Be,selectedIndex:Ne})=>{const{error:Ge}=await H.from("recruit_brokerage_subject_overrides").upsert({brokerage_id:s,campaign_email_id:Be,selected_subject_index:Ne,updated_at:new Date().toISOString()},{onConflict:"brokerage_id,campaign_email_id"});if(Ge)throw Ge},onSuccess:()=>{n.invalidateQueries({queryKey:["recruit-subject-overrides",s]}),ie.success("Subject line updated for your brokerage")},onError:Be=>ie.error(Be.message)}),ne=_t({mutationFn:async Be=>{const{error:Ne}=await H.from("recruit_campaign_emails").update({title:Be.title,subject_line:Be.subject_line,subject_line_options:Be.subject_line_options,body_html:Be.body_html,body_text:Be.body_text,delay_days:Be.delay_days,updated_at:new Date().toISOString()}).eq("id",Be.id);if(Ne)throw Ne},onSuccess:()=>{n.invalidateQueries({queryKey:["recruit-campaign-emails"]}),ie.success("Email template saved!"),l(null)},onError:Be=>ie.error(Be.message)}),me=_t({mutationFn:async()=>{const Be=A.name.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/(^-|-$)/g,""),{data:Ne,error:Ge}=await H.from("recruit_campaigns").insert({name:A.name,slug:Be,description:A.description||null,theme:A.theme||null,goal:A.goal||null,primary_cta:A.primary_cta||"Learn more",warmth_level:A.warmth_level,brokerage_id:s,created_by:t==null?void 0:t.id,sender_name:A.sender_name||null,sender_email:A.sender_email||null,reply_to_email:A.reply_to_email||null,is_active:!0,sort_order:z.length+1}).select().single();if(Ge)throw Ge;const Ce=[{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 H.from("recruit_campaign_emails").insert(Ce.map(Ae=>({campaign_id:Ne.id,...Ae,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 Ne},onSuccess:()=>{n.invalidateQueries({queryKey:["recruit-campaigns"]}),n.invalidateQueries({queryKey:["recruit-campaign-emails"]}),ie.success("Campaign created with 4 starter emails!"),m(!1),T({name:"",description:"",theme:"",goal:"",primary_cta:"Learn more",warmth_level:"warm",sender_name:"",sender_email:"",reply_to_email:""})},onError:Be=>ie.error(Be.message)}),ue=_t({mutationFn:async Be=>{const{error:Ne}=await H.from("recruit_campaigns").update({name:Be.name,description:Be.description,theme:Be.theme,goal:Be.goal,primary_cta:Be.primary_cta,warmth_level:Be.warmth_level,sender_name:Be.sender_name,sender_email:Be.sender_email,reply_to_email:Be.reply_to_email,updated_at:new Date().toISOString()}).eq("id",Be.id);if(Ne)throw Ne},onSuccess:()=>{n.invalidateQueries({queryKey:["recruit-campaigns"]}),ie.success("Campaign settings saved!"),x(null)},onError:Be=>ie.error(Be.message)}),ce=_t({mutationFn:async Be=>{var Xe,$e;const{data:Ne}=await H.from("recruit_campaign_emails").select("email_number, delay_days").eq("campaign_id",Be).order("email_number",{ascending:!1}).limit(1),Ge=((Xe=Ne==null?void 0:Ne[0])==null?void 0:Xe.email_number)??0,Ce=(($e=Ne==null?void 0:Ne[0])==null?void 0:$e.delay_days)??0,Fe=Ge+1,{error:Ae}=await H.from("recruit_campaign_emails").insert({campaign_id:Be,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:Ce+7,is_active:!0});if(Ae)throw Ae},onSuccess:()=>{n.invalidateQueries({queryKey:["recruit-campaign-emails"]}),ie.success("Email added to campaign!")},onError:Be=>ie.error(Be.message)}),ae=_t({mutationFn:async Be=>{const{error:Ne}=await H.from("recruit_campaigns").delete().eq("id",Be);if(Ne)throw Ne},onSuccess:()=>{n.invalidateQueries({queryKey:["recruit-campaigns"]}),n.invalidateQueries({queryKey:["recruit-campaign-emails"]}),ie.success("Campaign deleted")},onError:Be=>ie.error(Be.message)}),he=_t({mutationFn:async Be=>{const{error:Ne}=await H.from("recruit_campaign_emails").delete().eq("id",Be);if(Ne)throw Ne},onSuccess:()=>{n.invalidateQueries({queryKey:["recruit-campaign-emails"]}),ie.success("Email removed from campaign")},onError:Be=>ie.error(Be.message)}),xe=_t({mutationFn:async({emailId:Be,delay_days:Ne})=>{const{error:Ge}=await H.from("recruit_campaign_emails").update({delay_days:Ne,updated_at:new Date().toISOString()}).eq("id",Be);if(Ge)throw Ge},onSuccess:()=>{n.invalidateQueries({queryKey:["recruit-campaign-emails"]}),ie.success("Send delay updated")},onError:Be=>ie.error(Be.message)});if($)return e.jsx("div",{className:"flex justify-center py-12",children:e.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})});const ve=z.filter(Be=>!Be.brokerage_id),ge=z.filter(Be=>Be.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(sc,{className:"h-4 w-4"})," Default Settings"]}),e.jsxs(B,{size:"sm",onClick:()=>m(!0),className:"gap-1.5",children:[e.jsx(nn,{className:"h-4 w-4"})," New Campaign"]})]})]}),e.jsx(_e,{className:"border-primary/20 bg-primary/5",children:e.jsx(De,{className:"py-3",children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx(Cn,{className:"h-5 w-5 text-primary mt-0.5 shrink-0"}),e.jsxs("div",{className:"text-sm",children:[e.jsx("p",{className:"font-semibold",children:"Per-Campaign Email Settings"}),e.jsxs("p",{className:"text-muted-foreground",children:["Each campaign can override the default sender name, email, and reply-to. Click the ",e.jsx(sc,{className:"inline h-3.5 w-3.5"})," icon on any campaign to customize."]})]})]})})}),ge.length>0&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs("h3",{className:"text-sm font-semibold text-muted-foreground uppercase tracking-wider flex items-center gap-2",children:[e.jsx(nW,{className:"h-4 w-4"})," Your Custom Campaigns"]}),e.jsx("div",{className:"space-y-3",children:ge.map(Be=>be(Be,!0))})]}),ve.length>0&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs("h3",{className:"text-sm font-semibold text-muted-foreground uppercase tracking-wider flex items-center gap-2",children:[e.jsx(Cn,{className:"h-4 w-4"})," System Campaigns"]}),e.jsx("div",{className:"space-y-3",children:ve.map(Be=>be(Be,!1))})]}),z.length===0&&e.jsx(_e,{children:e.jsxs(De,{className:"py-12 text-center text-muted-foreground",children:[e.jsx(mn,{className:"h-12 w-12 mx-auto mb-4 opacity-50"}),e.jsx("p",{children:"No campaigns yet. Create your first campaign to start automated outreach."}),e.jsxs(B,{className:"mt-4",onClick:()=>m(!0),children:[e.jsx(nn,{className:"h-4 w-4 mr-1"})," Create Campaign"]})]})}),e.jsx(PSn,{open:!!_,onClose:()=>b(null),campaignName:(_==null?void 0:_.name)||"",stat:_&&k[_.id]||null}),o&&e.jsx(k9t,{email:o,mergeValues:M,selectedSubjectIndex:X[o.id],onClose:()=>c(null)}),e.jsx(Bs,{open:!!i,onOpenChange:Be=>!Be&&l(null),children:e.jsxs(Fs,{className:"max-w-4xl max-h-[90vh] overflow-y-auto p-0",children:[e.jsxs(qs,{className:"px-6 pt-6 pb-4 border-b",children:[e.jsxs($s,{className:"flex items-center gap-2",children:[e.jsx(CT,{className:"h-5 w-5 text-primary"}),"Edit Email #",i==null?void 0:i.email_number]}),e.jsx(Ar,{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(re,{className:"text-xs font-medium text-muted-foreground uppercase tracking-wider",children:"Email Title"}),e.jsx(we,{value:i.title,onChange:Be=>l({...i,title:Be.target.value}),className:"h-9"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(re,{className:"text-xs font-medium text-muted-foreground uppercase tracking-wider",children:"Delay (days after previous)"}),e.jsx(we,{type:"number",min:0,max:90,value:i.delay_days,onChange:Be=>l({...i,delay_days:parseInt(Be.target.value)||7}),className:"h-9"})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(re,{className:"text-xs font-medium text-muted-foreground uppercase tracking-wider",children:"Subject Line"}),e.jsx(we,{value:i.subject_line,onChange:Be=>l({...i,subject_line:Be.target.value}),placeholder:"e.g. Hey {{first_name}}, quick question...",className:"h-9"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs(re,{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(Ws,{value:((Re=i.subject_line_options)==null?void 0:Re.join(` `))||"",onChange:Be=>l({...i,subject_line_options:Be.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(re,{className:"text-xs font-medium text-muted-foreground uppercase tracking-wider",children:"Email Body"}),e.jsx(ya,{value:f,onValueChange:Be=>g(Be),children:e.jsxs(va,{className:"h-7",children:[e.jsx(ls,{value:"editor",className:"text-xs px-3 h-6",children:"Editor"}),e.jsx(ls,{value:"preview",className:"text-xs px-3 h-6",children:"Preview"})]})})]}),f==="editor"?e.jsx(LSn,{content:i.body_html,onChange:Be=>l({...i,body_html:Be})}):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:L(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:L(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:()=>ne.mutate(i),disabled:ne.isPending,className:"gap-1.5",children:[e.jsx(Kl,{className:"h-3.5 w-3.5"})," Save Changes"]})]})]})]})]})}),e.jsx(Bs,{open:h,onOpenChange:m,children:e.jsxs(Fs,{className:"max-w-lg",children:[e.jsxs(qs,{children:[e.jsxs($s,{className:"flex items-center gap-2",children:[e.jsx(nn,{className:"h-5 w-5 text-primary"})," Create Custom Campaign"]}),e.jsx(Ar,{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(re,{className:"text-xs font-medium",children:"Campaign Name *"}),e.jsx(we,{value:A.name,onChange:Be=>T({...A,name:Be.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(re,{className:"text-xs font-medium",children:"Warmth Level"}),e.jsxs(Ns,{value:A.warmth_level,onValueChange:Be=>T({...A,warmth_level:Be}),children:[e.jsx(ws,{children:e.jsx(ks,{})}),e.jsxs(js,{children:[e.jsx(nt,{value:"cold",children:"❄️ Cold — Curiosity"}),e.jsx(nt,{value:"warm",children:"☀️ Warm — Growth"}),e.jsx(nt,{value:"hot",children:"🔥 Hot — Private Invite"})]})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(re,{className:"text-xs font-medium",children:"Primary CTA"}),e.jsx(we,{value:A.primary_cta,onChange:Be=>T({...A,primary_cta:Be.target.value}),placeholder:"Learn more"})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(re,{className:"text-xs font-medium",children:"Description"}),e.jsx(Ws,{value:A.description,onChange:Be=>T({...A,description:Be.target.value}),placeholder:"What is this campaign about?",rows:2})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(re,{className:"text-xs font-medium",children:"Goal"}),e.jsx(we,{value:A.goal,onChange:Be=>T({...A,goal:Be.target.value}),placeholder:"e.g. Convert warm leads to meetings"})]}),e.jsxs(Kv,{children:[e.jsx(Yv,{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(mn,{className:"h-3.5 w-3.5"})," Email Settings Override"]}),e.jsx(Xo,{className:"h-3.5 w-3.5"})]})}),e.jsxs(Zv,{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(re,{className:"text-xs",children:"Sender Name"}),e.jsx(we,{value:A.sender_name,onChange:Be=>T({...A,sender_name:Be.target.value}),placeholder:"e.g. Jeremy at LevelUp"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(re,{className:"text-xs",children:"Sender Email"}),e.jsx(we,{value:A.sender_email,onChange:Be=>T({...A,sender_email:Be.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(re,{className:"text-xs",children:"Reply-To Email"}),e.jsx(we,{value:A.reply_to_email,onChange:Be=>T({...A,reply_to_email:Be.target.value}),placeholder:"e.g. jeremy@mybrokerage.com"})]})]})]}),e.jsxs(B,{className:"w-full",disabled:!A.name.trim()||me.isPending,onClick:()=>me.mutate(),children:[e.jsx(nn,{className:"h-4 w-4 mr-1"})," Create Campaign"]})]})]})}),e.jsx(Bs,{open:!!y,onOpenChange:Be=>!Be&&x(null),children:e.jsxs(Fs,{className:"max-w-lg",children:[e.jsxs(qs,{children:[e.jsxs($s,{className:"flex items-center gap-2",children:[e.jsx(sc,{className:"h-5 w-5 text-primary"})," Campaign Email Settings"]}),e.jsx(Ar,{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(re,{className:"text-xs font-medium",children:"Campaign Name"}),e.jsx(we,{value:y.name,onChange:Be=>x({...y,name:Be.target.value})})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(re,{className:"text-xs font-medium",children:"Warmth Level"}),e.jsxs(Ns,{value:y.warmth_level,onValueChange:Be=>x({...y,warmth_level:Be}),children:[e.jsx(ws,{children:e.jsx(ks,{})}),e.jsxs(js,{children:[e.jsx(nt,{value:"cold",children:"❄️ Cold"}),e.jsx(nt,{value:"warm",children:"☀️ Warm"}),e.jsx(nt,{value:"hot",children:"🔥 Hot"})]})]})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(re,{className:"text-xs font-medium",children:"Goal"}),e.jsx(we,{value:y.goal||"",onChange:Be=>x({...y,goal:Be.target.value})})]}),e.jsxs("div",{className:"border-t pt-4 space-y-3",children:[e.jsxs("p",{className:"text-sm font-semibold flex items-center gap-1.5",children:[e.jsx(mn,{className:"h-4 w-4 text-primary"})," Email Sender Override"]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(re,{className:"text-xs",children:"Sender Name"}),e.jsx(we,{value:y.sender_name||"",onChange:Be=>x({...y,sender_name:Be.target.value}),placeholder:"Uses brokerage default"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(re,{className:"text-xs",children:"Sender Email"}),e.jsx(we,{value:y.sender_email||"",onChange:Be=>x({...y,sender_email:Be.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(re,{className:"text-xs",children:"Reply-To Email"}),e.jsx(we,{value:y.reply_to_email||"",onChange:Be=>x({...y,reply_to_email:Be.target.value}),placeholder:"Uses brokerage default"})]})]}),e.jsxs(B,{className:"w-full",onClick:()=>ue.mutate(y),disabled:ue.isPending,children:[e.jsx(Kl,{className:"h-4 w-4 mr-1"})," Save Campaign Settings"]})]})]})}),e.jsx(Bs,{open:d,onOpenChange:u,children:e.jsxs(Fs,{className:"max-w-lg",children:[e.jsxs(qs,{children:[e.jsx($s,{children:"Default Recruiting Email Settings"}),e.jsx(Ar,{children:"These defaults apply to campaigns without their own overrides."})]}),e.jsx(QWe,{brokerageId:s})]})})]});function be(Be,Ne){const Ge=ngt[Be.warmth_level]||ngt.cold,Ce=Ge.icon,Fe=V[Be.id]||[],Ae=r===Be.id,Xe=!!(Be.sender_name||Be.sender_email||Be.reply_to_email),$e=k[Be.id];return e.jsxs(_e,{className:"overflow-hidden transition-shadow hover:shadow-md",children:[e.jsx(zt,{className:"cursor-pointer hover:bg-muted/40 transition-colors py-4",onClick:()=>a(Ae?null:Be.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 ${Ge.bg} flex items-center justify-center`,children:e.jsx(Ce,{className:`h-5 w-5 ${Ge.color}`})}),e.jsxs("div",{children:[e.jsxs(qt,{className:"text-base flex items-center gap-2",children:[Be.name,e.jsx(We,{variant:Be.is_active?"default":"secondary",className:"text-[10px] px-1.5",children:Be.is_active?"Active":"Draft"}),Ne&&e.jsx(We,{variant:"outline",className:"text-[10px] px-1.5",children:"Custom"}),Xe&&e.jsxs(We,{variant:"outline",className:"text-[10px] px-1.5 border-primary/30 text-primary",children:[e.jsx(mn,{className:"h-2.5 w-2.5 mr-0.5"})," Custom Sender"]})]}),e.jsx(_r,{className:"text-xs mt-0.5",children:Be.theme||Be.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:Ye=>{Ye.stopPropagation(),x({...Be})},children:e.jsx(sc,{className:"h-4 w-4 text-muted-foreground"})}),Ne&&e.jsx(B,{variant:"ghost",size:"sm",className:"h-8 w-8 p-0 text-destructive hover:text-destructive hover:bg-destructive/10",onClick:Ye=>{Ye.stopPropagation(),confirm("Delete this campaign and all its emails? This cannot be undone.")&&ae.mutate(Be.id)},children:e.jsx(qn,{className:"h-4 w-4"})}),$e&&$e.sent>0&&e.jsxs("div",{className:"hidden md:flex items-center gap-1.5",children:[e.jsxs(We,{variant:"outline",className:"text-[10px] gap-1 font-medium",title:"Total emails sent",children:[e.jsx(mn,{className:"h-2.5 w-2.5"})," ",$e.sent.toLocaleString()]}),e.jsxs(We,{variant:"outline",className:"text-[10px] gap-1 border-amber-500/30 text-amber-600 font-medium",title:`${$e.openRate.toFixed(1)}% open rate`,children:[e.jsx(da,{className:"h-2.5 w-2.5"})," ",$e.opened.toLocaleString()," (",$e.openRate.toFixed(0),"%)"]}),e.jsxs(We,{variant:"outline",className:"text-[10px] gap-1 border-green-500/30 text-green-600 font-medium",title:`${$e.clickRate.toFixed(1)}% click rate`,children:[e.jsx(ru,{className:"h-2.5 w-2.5"})," ",$e.clicked.toLocaleString()," (",$e.clickRate.toFixed(1),"%)"]})]}),e.jsxs(B,{variant:"outline",size:"sm",className:"h-7 px-2 gap-1 text-xs",onClick:Ye=>{Ye.stopPropagation(),b(Be)},title:"View detailed engagement stats",children:[e.jsx(fl,{className:"h-3.5 w-3.5"})," Stats"]}),e.jsxs("div",{className:"flex items-center gap-1 text-xs text-muted-foreground",children:[e.jsx(mn,{className:"h-3.5 w-3.5"}),e.jsxs("span",{children:[Fe.length," emails"]})]}),e.jsx("div",{className:"h-7 w-7 rounded-md flex items-center justify-center",children:Ae?e.jsx(zy,{className:"h-4 w-4 text-muted-foreground"}):e.jsx(Xo,{className:"h-4 w-4 text-muted-foreground"})})]})]})}),Ae&&e.jsxs(De,{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:Be.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:Be.primary_cta||"—"})]})]}),Xe&&e.jsxs("div",{className:"p-3 rounded-lg bg-primary/5 border border-primary/10 text-sm",children:[e.jsxs("p",{className:"text-xs font-semibold text-primary mb-1 flex items-center gap-1",children:[e.jsx(mn,{className:"h-3 w-3"})," Campaign Sender Override"]}),e.jsxs("div",{className:"grid grid-cols-3 gap-2 text-xs text-muted-foreground",children:[Be.sender_name&&e.jsxs("p",{children:[e.jsx("span",{className:"font-medium",children:"Name:"})," ",Be.sender_name]}),Be.sender_email&&e.jsxs("p",{children:[e.jsx("span",{className:"font-medium",children:"Email:"})," ",Be.sender_email]}),Be.reply_to_email&&e.jsxs("p",{children:[e.jsx("span",{className:"font-medium",children:"Reply-To:"})," ",Be.reply_to_email]})]})]}),e.jsx("div",{className:"relative",children:Fe.map((Ye,Je)=>{var Ke,st;return e.jsxs("div",{className:"relative flex gap-4 pb-4 last:pb-0",children:[Jert.stopPropagation(),onBlur:rt=>{const Ze=parseInt(rt.target.value)||0;Ze!==Ye.delay_days&&xe.mutate({emailId:Ye.id,delay_days:Ze})},onKeyDown:rt=>{rt.key==="Enter"&&rt.target.blur()}}),"days"]})]}):e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Xr,{className:"h-3 w-3"}),Ye.email_number===1?"Sent immediately":`Day ${Ye.delay_days}`]}),e.jsx("span",{className:"text-border",children:"•"}),e.jsxs("span",{className:"truncate",children:["Subject: ",L(((Ke=Ye.subject_line_options)==null?void 0:Ke.length)>0&&Ye.subject_line_options[X[Ye.id]??0]||Ye.subject_line)]})]}),((st=Ye.subject_line_options)==null?void 0:st.length)>1&&e.jsx("div",{className:"mt-2",children:e.jsxs(Ns,{value:String(X[Ye.id]??0),onValueChange:rt=>te.mutate({campaignEmailId:Ye.id,selectedIndex:parseInt(rt)}),children:[e.jsx(ws,{className:"h-7 text-xs w-full max-w-sm",children:e.jsx(ks,{placeholder:"Choose subject line"})}),e.jsx(js,{children:Ye.subject_line_options.map((rt,Ze)=>e.jsxs(nt,{value:String(Ze),className:"text-xs",children:[e.jsxs("span",{className:"font-medium mr-1.5",children:[Ze===0?"Primary":`Alt ${Ze}`,":"]}),L(rt)]},Ze))})]})})]}),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(Ye),children:e.jsx(da,{className:"h-4 w-4"})}),e.jsx(B,{variant:"ghost",size:"sm",className:"h-8 w-8 p-0",onClick:()=>{l({...Ye}),g("editor")},children:e.jsx(Ja,{className:"h-4 w-4"})}),Ne&&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:()=>{confirm("Delete this email from the sequence?")&&he.mutate(Ye.id)},children:e.jsx(qn,{className:"h-4 w-4"})})]})]})})]},Ye.id)})}),Ne&&e.jsxs(B,{variant:"outline",size:"sm",className:"w-full gap-1.5",onClick:()=>ce.mutate(Be.id),disabled:ce.isPending,children:[e.jsx(nn,{className:"h-3.5 w-3.5"})," Add Email to Sequence"]})]})]},Be.id)}}const rgt={active:{icon:dd,color:"bg-green-500/10 text-green-600",label:"Active"},paused:{icon:K0,color:"bg-amber-500/10 text-amber-600",label:"Paused"},completed:{icon:Po,color:"bg-blue-500/10 text-blue-600",label:"Completed"},cancelled:{icon:Nu,color:"bg-red-500/10 text-red-600",label:"Cancelled"}},agt={sent:{icon:mn,color:"text-blue-500"},opened:{icon:da,color:"text-amber-500"},clicked:{icon:ru,color:"text-green-500"},failed:{icon:xd,color:"text-destructive"}};function A9t({brokerageId:s}){var Re,Be,Ne,Ge,Ce;const{user:t}=Ls(),n=as(),[r,a]=N.useState(!1),[i,l]=N.useState(""),[o,c]=N.useState(new Set),[d,u]=N.useState("assignments"),[h,m]=N.useState(null),[f,g]=N.useState(""),[y,x]=N.useState("all"),[_,b]=N.useState("all"),[k,A]=N.useState(!1),{data:T}=OCe(),{data:P={}}=mt({queryKey:["recruit-campaign-emails-for-preview",s],queryFn:async()=>{const{data:Fe,error:Ae}=await H.from("recruit_campaign_emails").select("*").order("email_number");if(Ae)throw Ae;const Xe={};return(Fe??[]).forEach($e=>{Xe[$e.campaign_id]||(Xe[$e.campaign_id]=[]),Xe[$e.campaign_id].push($e)}),Xe}}),{data:I}=mt({queryKey:["brokerage-detail",s],queryFn:async()=>{const{data:Fe,error:Ae}=await H.from("brokerages").select("name, city, state").eq("id",s).single();if(Ae)throw Ae;return Fe}}),{data:M}=mt({queryKey:["brokerage-recruit-settings",s],queryFn:async()=>{const{data:Fe,error:Ae}=await H.from("brokerage_recruit_settings").select("*").eq("brokerage_id",s).maybeSingle();if(Ae)throw Ae;return Fe}}),{data:L=[]}=mt({queryKey:["recruit-subject-overrides",s],queryFn:async()=>{const{data:Fe,error:Ae}=await H.from("recruit_brokerage_subject_overrides").select("*").eq("brokerage_id",s);if(Ae)throw Ae;return Fe}}),z={};L.forEach(Fe=>{z[Fe.campaign_email_id]=Fe.selected_subject_index});const $={first_name:((Re=h==null?void 0:h.prospect)==null?void 0:Re.first_name)||"Sarah",brokerage_name:((Be=M==null?void 0:M.merge_fields)==null?void 0:Be.brokerage_name)||(I==null?void 0:I.name)||"Your Brokerage",city:((Ne=M==null?void 0:M.merge_fields)==null?void 0:Ne.city)||(I==null?void 0:I.city)||"Your City",sender_name:((Ge=M==null?void 0:M.merge_fields)==null?void 0:Ge.sender_name)||(M==null?void 0:M.sender_name)||"Your Name"},V=Fe=>{const Ae=P[Fe.campaign_id]||[],Xe=Fe.current_email_number+1;return Ae.find($e=>$e.email_number===Xe)||null},{data:W=[],isLoading:G}=mt({queryKey:["recruit-campaign-assignments",s],queryFn:async()=>{let Ae=[],Xe=0;for(;;){const{data:$e,error:Ye}=await H.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(Xe,Xe+1e3-1);if(Ye)throw Ye;if(Ae=Ae.concat($e??[]),!$e||$e.length<1e3)break;Xe+=1e3}return Ae}}),{data:X=[]}=mt({queryKey:["recruit-campaign-sends",s],queryFn:async()=>{const{data:Fe,error:Ae}=await H.from("recruit_campaign_sends").select(` *, prospect:recruit_prospects(first_name, last_name, email), campaign_email:recruit_campaign_emails(title, campaign_id) `).eq("brokerage_id",s).neq("status","failed").order("sent_at",{ascending:!1}).limit(500);if(Ae)throw Ae;return Fe}}),{data:te=[]}=mt({queryKey:["recruit-campaigns"],queryFn:async()=>{const{data:Fe,error:Ae}=await H.from("recruit_campaigns").select("id, name, warmth_level").eq("is_active",!0).order("sort_order");if(Ae)throw Ae;return Fe}}),{data:ne=[]}=mt({queryKey:["recruit-prospects-for-assign",s],queryFn:async()=>{let Ae=[],Xe=0;for(;;){const{data:$e,error:Ye}=await H.from("recruit_prospects").select("id, first_name, last_name, email").eq("brokerage_id",s).order("first_name").range(Xe,Xe+1e3-1);if(Ye)throw Ye;if(Ae=Ae.concat($e??[]),!$e||$e.length<1e3)break;Xe+=1e3}return Ae}}),me=new Set(W.map(Fe=>`${Fe.prospect_id}-${Fe.campaign_id}`)),ue=_t({mutationFn:async()=>{if(!i||o.size===0)throw new Error("Select a campaign and at least one prospect");const Fe=new Date,Ae=Array.from(o).filter($e=>!me.has(`${$e}-${i}`)).map($e=>({prospect_id:$e,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(Ae.length===0)throw new Error("All selected prospects are already assigned to this campaign");const{error:Xe}=await H.from("recruit_campaign_assignments").insert(Ae);if(Xe)throw Xe},onSuccess:()=>{n.invalidateQueries({queryKey:["recruit-campaign-assignments",s]}),ie.success(`Campaign assigned to ${o.size} prospect(s)!`),a(!1),l(""),c(new Set)},onError:Fe=>ie.error(Fe.message)}),ce=_t({mutationFn:async({id:Fe,newStatus:Ae})=>{const{error:Xe}=await H.from("recruit_campaign_assignments").update({status:Ae,updated_at:new Date().toISOString()}).eq("id",Fe);if(Xe)throw Xe},onSuccess:()=>{n.invalidateQueries({queryKey:["recruit-campaign-assignments",s]}),ie.success("Assignment updated")}}),ae=_t({mutationFn:async()=>{const{data:Fe,error:Ae}=await H.functions.invoke("ses-recruit-drip",{body:{action:"process_drips"}});if(Ae)throw Ae;return Fe},onSuccess:Fe=>{n.invalidateQueries({queryKey:["recruit-campaign-assignments",s]}),n.invalidateQueries({queryKey:["recruit-campaign-sends",s]}),ie.success(`Wave sent! ${Fe.sent} emails delivered, ${Fe.skipped} skipped, ${Fe.failed} failed`)},onError:Fe=>ie.error(`Send failed: ${Fe.message}`)}),he=W.filter(Fe=>Fe.status==="active").length;W.filter(Fe=>Fe.status==="completed").length;const xe=W.filter(Fe=>Fe.status==="active"&&Fe.next_send_at&&new Date(Fe.next_send_at)<=new Date).length,{data:ve={}}=S9t(s),ge=W.reduce((Fe,Ae)=>Fe+Math.max(0,Ae.current_email_number||0),0),be=Object.values(ve).reduce((Fe,Ae)=>Fe+Ae.opened,0),Se=Object.values(ve).reduce((Fe,Ae)=>Fe+Ae.clicked,0);Object.values(ve).reduce((Fe,Ae)=>Fe+Ae.failed,0);const Ie=ge>0?Math.round(be/ge*100):0,Me=ge>0?Se/ge*100:0;return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"text-xl font-bold",children:"Campaign Assignments"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Assign recruiting campaigns to prospects — emails auto-send weekly via SES"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[xe>0&&e.jsxs(B,{variant:"outline",onClick:()=>{ae.mutate()},disabled:ae.isPending,className:"border-amber-500/50 text-amber-600 hover:bg-amber-500/10",children:[e.jsx(ff,{className:"h-4 w-4 mr-1"}),ae.isPending?"Sending...":`Send Next Wave (${xe})`]}),e.jsxs(B,{onClick:()=>a(!0),children:[e.jsx(Rr,{className:"h-4 w-4 mr-1"})," Assign Campaign"]})]})]}),e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-5 gap-3",children:[e.jsx(_e,{children:e.jsxs(De,{className:"pt-3 pb-2 flex items-center gap-3",children:[e.jsx(Yn,{className:"h-7 w-7 text-primary"}),e.jsxs("div",{children:[e.jsx("p",{className:"text-xl font-bold",children:W.length}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Assigned"})]})]})}),e.jsx(_e,{children:e.jsxs(De,{className:"pt-3 pb-2 flex items-center gap-3",children:[e.jsx(dd,{className:"h-7 w-7 text-green-500"}),e.jsxs("div",{children:[e.jsx("p",{className:"text-xl font-bold",children:he}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Active"})]})]})}),e.jsx(_e,{children:e.jsxs(De,{className:"pt-3 pb-2 flex items-center gap-3",children:[e.jsx(mn,{className:"h-7 w-7 text-blue-500"}),e.jsxs("div",{children:[e.jsx("p",{className:"text-xl font-bold",children:ge.toLocaleString()}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Emails Sent"})]})]})}),e.jsx(_e,{children:e.jsxs(De,{className:"pt-3 pb-2 flex items-center gap-3",children:[e.jsx(da,{className:"h-7 w-7 text-amber-500"}),e.jsxs("div",{children:[e.jsxs("p",{className:"text-xl font-bold",children:[Ie,"%"]}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Open Rate (",be.toLocaleString(),")"]})]})]})}),e.jsx(_e,{children:e.jsxs(De,{className:"pt-3 pb-2 flex items-center gap-3",children:[e.jsx(ru,{className:"h-7 w-7 text-green-500"}),e.jsxs("div",{children:[e.jsxs("p",{className:"text-xl font-bold",children:[Me.toFixed(1),"%"]}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Click Rate (",Se.toLocaleString(),")"]})]})]})})]}),e.jsxs(ya,{value:d,onValueChange:u,children:[e.jsxs(va,{children:[e.jsxs(ls,{value:"assignments",children:["Active Drips (",he,")"]}),e.jsxs(ls,{value:"history",children:["Send History (",ge.toLocaleString(),")"]})]}),e.jsx(_s,{value:"assignments",className:"mt-4",children:G?e.jsx("div",{className:"flex justify-center py-8",children:e.jsx("div",{className:"h-6 w-6 animate-spin rounded-full border-2 border-primary border-t-transparent"})}):W.length===0?e.jsx(_e,{children:e.jsxs(De,{className:"py-12 text-center text-muted-foreground",children:[e.jsx(Rr,{className:"h-12 w-12 mx-auto mb-4 opacity-50"}),e.jsx("p",{className:"font-medium",children:"No campaigns assigned yet"}),e.jsx("p",{className:"text-sm",children:"Assign a recruiting campaign to your prospects to start automated outreach"})]})}):e.jsx("div",{className:"space-y-2",children:W.map(Fe=>{var Ke,st,rt,Ze;const Ae=rgt[Fe.status]||rgt.active,Xe=Ae.icon,Ye=(P[Fe.campaign_id]||[]).length||4,Je=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(We,{className:`text-xs ${Ae.color} border-0`,children:[e.jsx(Xe,{className:"h-3 w-3 mr-1"}),Ae.label]}),e.jsxs("div",{className:"min-w-0",children:[e.jsxs("p",{className:"font-medium text-sm",children:[(Ke=Fe.prospect)==null?void 0:Ke.first_name," ",(st=Fe.prospect)==null?void 0:st.last_name,e.jsx("span",{className:"text-muted-foreground font-normal ml-2",children:(rt=Fe.prospect)==null?void 0:rt.email})]}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[(Ze=Fe.campaign)==null?void 0:Ze.name," · Email ",Fe.current_email_number,"/",Ye,Fe.next_send_at&&Fe.status==="active"&&e.jsxs(e.Fragment,{children:[" ","· ",e.jsx(Xr,{className:"h-3 w-3 inline"})," Next: ",Js(new Date(Fe.next_send_at),"MMM d, h:mm a"),new Date(Fe.next_send_at)<=new Date&&e.jsx(We,{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:[Je&&e.jsx(B,{variant:"ghost",size:"sm",title:"Preview next email",onClick:()=>m(Fe),children:e.jsx(da,{className:"h-3.5 w-3.5"})}),Fe.status==="active"&&e.jsx(B,{variant:"ghost",size:"sm",onClick:()=>ce.mutate({id:Fe.id,newStatus:"paused"}),children:e.jsx(K0,{className:"h-3.5 w-3.5"})}),Fe.status==="paused"&&e.jsx(B,{variant:"ghost",size:"sm",onClick:()=>ce.mutate({id:Fe.id,newStatus:"active"}),children:e.jsx(dd,{className:"h-3.5 w-3.5"})}),(Fe.status==="active"||Fe.status==="paused")&&e.jsx(B,{variant:"ghost",size:"sm",className:"text-destructive",onClick:()=>ce.mutate({id:Fe.id,newStatus:"cancelled"}),children:e.jsx(Nu,{className:"h-3.5 w-3.5"})})]})]},Fe.id)})})}),e.jsxs(_s,{value:"history",className:"mt-4 space-y-3",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx("span",{className:"text-xs text-muted-foreground",children:"Filter:"}),e.jsxs(Ns,{value:y,onValueChange:x,children:[e.jsx(ws,{className:"w-[220px] h-8 text-xs",children:e.jsx(ks,{placeholder:"All campaigns"})}),e.jsxs(js,{children:[e.jsx(nt,{value:"all",children:"All campaigns"}),te.map(Fe=>e.jsx(nt,{value:Fe.id,children:Fe.name},Fe.id))]})]}),e.jsxs(Ns,{value:_,onValueChange:b,children:[e.jsx(ws,{className:"w-[160px] h-8 text-xs",children:e.jsx(ks,{placeholder:"All statuses"})}),e.jsxs(js,{children:[e.jsx(nt,{value:"all",children:"All statuses"}),e.jsx(nt,{value:"sent",children:"Sent (no engagement)"}),e.jsx(nt,{value:"opened",children:"Opened"}),e.jsx(nt,{value:"clicked",children:"Clicked"})]})]}),(y!=="all"||_!=="all")&&e.jsx(B,{variant:"ghost",size:"sm",className:"h-8 text-xs",onClick:()=>{x("all"),b("all")},children:"Clear"})]}),(()=>{var Ae;const Fe=X.filter(Xe=>{var $e;return!(y!=="all"&&(($e=Xe.campaign_email)==null?void 0:$e.campaign_id)!==y||_==="opened"&&!Xe.opened_at||_==="clicked"&&!Xe.clicked_at||_==="sent"&&(Xe.opened_at||Xe.clicked_at))});return Fe.length===0?e.jsx(_e,{children:e.jsxs(De,{className:"py-12 text-center text-muted-foreground",children:[e.jsx(mn,{className:"h-12 w-12 mx-auto mb-4 opacity-50"}),e.jsx("p",{className:"font-medium",children:X.length===0?"No emails sent yet":"No emails match these filters"}),e.jsx("p",{className:"text-sm",children:X.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 ",X.length," recent sends",y!=="all"&&` · ${(Ae=te.find(Xe=>Xe.id===y))==null?void 0:Ae.name}`]}),e.jsx("div",{className:"space-y-1",children:Fe.map(Xe=>{var Ke,st,rt;const $e=agt[Xe.status]||agt.sent,Ye=$e.icon,Je=(Ke=te.find(Ze=>{var ht;return Ze.id===((ht=Xe.campaign_email)==null?void 0:ht.campaign_id)}))==null?void 0:Ke.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(Ye,{className:`h-4 w-4 flex-shrink-0 ${$e.color}`}),e.jsxs("div",{className:"min-w-0",children:[e.jsxs("p",{className:"font-medium text-sm truncate",children:[(st=Xe.prospect)==null?void 0:st.first_name," ",(rt=Xe.prospect)==null?void 0:rt.last_name,e.jsxs("span",{className:"text-muted-foreground font-normal ml-2",children:["Email #",Xe.email_number]}),Je&&e.jsx(We,{variant:"outline",className:"ml-2 text-[10px] px-1.5 py-0 font-normal",children:Je})]}),e.jsx("p",{className:"text-xs text-muted-foreground truncate",children:Xe.subject})]})]}),e.jsxs("div",{className:"flex items-center gap-2 text-xs text-muted-foreground flex-shrink-0",children:[Xe.opened_at&&e.jsxs("span",{className:"flex items-center gap-1 text-amber-500",children:[e.jsx(da,{className:"h-3 w-3"})," ",Js(new Date(Xe.opened_at),"MMM d")]}),Xe.clicked_at&&e.jsxs("span",{className:"flex items-center gap-1 text-green-500",children:[e.jsx(ru,{className:"h-3 w-3"})," ",Js(new Date(Xe.clicked_at),"MMM d")]}),e.jsx("span",{children:Js(new Date(Xe.sent_at),"MMM d, h:mm a")})]})]},Xe.id)})})]})})()]})]}),e.jsx(Bs,{open:r,onOpenChange:Fe=>{a(Fe),Fe||(g(""),c(new Set),l(""))},children:e.jsxs(Fs,{className:"max-w-lg max-h-[85vh] flex flex-col p-0",children:[e.jsxs(qs,{className:"px-6 pt-6 pb-4",children:[e.jsx($s,{children:"Assign Campaign to Prospects"}),e.jsx(Ar,{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(re,{className:"text-sm font-medium",children:"1. Select Campaign"}),e.jsxs(Ns,{value:i,onValueChange:l,children:[e.jsx(ws,{children:e.jsx(ks,{placeholder:"Choose a campaign..."})}),e.jsx(js,{children:te.map(Fe=>e.jsx(nt,{value:Fe.id,children:Fe.name},Fe.id))})]})]}),i&&(()=>{const Fe=f.toLowerCase(),Ae=ne.filter(Ye=>`${Ye.first_name} ${Ye.last_name}`.toLowerCase().includes(Fe)||Ye.email.toLowerCase().includes(Fe)),Xe=Ae.filter(Ye=>!me.has(`${Ye.id}-${i}`)),$e=Xe.length>0&&Xe.every(Ye=>o.has(Ye.id));return e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(re,{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(Gr,{className:"absolute left-2.5 top-2.5 h-4 w-4 text-muted-foreground"}),e.jsx(we,{placeholder:"Search by name or email...",value:f,onChange:Ye=>g(Ye.target.value),className:"pl-9 h-9"})]}),e.jsxs(B,{variant:"outline",size:"sm",className:"h-9 whitespace-nowrap",onClick:()=>{if($e){const Ye=new Set(o);Xe.forEach(Je=>Ye.delete(Je.id)),c(Ye)}else{const Ye=new Set(o);Xe.forEach(Je=>Ye.add(Je.id)),c(Ye)}},children:[e.jsx(oD,{className:"h-3.5 w-3.5 mr-1"}),$e?"Deselect All":`Select All (${Xe.length})`]})]}),e.jsx("div",{className:"border rounded-lg max-h-60 overflow-y-auto divide-y",children:Ae.length===0?e.jsx("p",{className:"text-sm text-muted-foreground text-center py-4",children:f?"No prospects match your search":"No prospects found for this brokerage"}):Ae.map(Ye=>{const Je=me.has(`${Ye.id}-${i}`);return e.jsxs("label",{className:`flex items-center gap-3 p-2.5 hover:bg-muted/50 cursor-pointer ${Je?"opacity-40":""}`,children:[e.jsx(Bi,{checked:o.has(Ye.id),disabled:Je,onCheckedChange:Ke=>{const st=new Set(o);Ke?st.add(Ye.id):st.delete(Ye.id),c(st)}}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("p",{className:"text-sm font-medium truncate",children:[Ye.first_name," ",Ye.last_name]}),e.jsx("p",{className:"text-xs text-muted-foreground truncate",children:Ye.email})]}),Je&&e.jsx(We,{variant:"outline",className:"text-[10px] shrink-0",children:"Already assigned"})]},Ye.id)})}),Ae.length>0&&e.jsxs("p",{className:"text-[11px] text-muted-foreground",children:["Showing ",Ae.length," of ",ne.length," prospects",Xe.length0&&e.jsx(_e,{className:"bg-primary/5 border-primary/20",children:e.jsxs(De,{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:(Ce=te.find(Fe=>Fe.id===i))==null?void 0:Ce.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(Cr,{className:"px-6 py-4 border-t",children:[e.jsx(B,{variant:"outline",onClick:()=>a(!1),children:"Cancel"}),e.jsxs(B,{onClick:()=>{ue.mutate()},disabled:ue.isPending||!i||o.size===0,children:[e.jsx(Rr,{className:"h-4 w-4 mr-1"}),ue.isPending?"Assigning...":`Assign & Start (${o.size})`]})]})]})}),h&&(()=>{const Fe=V(h);return Fe?e.jsx(k9t,{email:Fe,mergeValues:$,selectedSubjectIndex:z[Fe.id],onClose:()=>m(null)}):null})(),e.jsx(FCe,{open:k,onOpenChange:A,hasPending:T==null?void 0:T.hasPendingSes,pendingEmails:T==null?void 0:T.pendingEmails})]})}function T9t({brokerageId:s}){const t=as(),[n,r]=N.useState([]),[a,i]=N.useState([]),[l,o]=N.useState(!1),c=N.useRef(!1),{data:d,isLoading:u}=mt({queryKey:["recruit-stages-editor",s],queryFn:async()=>{const{data:x,error:_}=await H.from("recruit_pipeline_stages").select("*").eq("brokerage_id",s).order("sort_order");if(_)throw _;return x},enabled:!!s});N.useEffect(()=>{if(d){if(c.current){c.current=!1;return}r(d.map(x=>({id:x.id,name:x.name,color:x.color,sort_order:x.sort_order}))),i([]),o(!1)}},[d]);const h=_t({mutationFn:async()=>{for(const b of a){const{error:k}=await H.from("recruit_pipeline_stages").delete().eq("id",b);if(k)throw k}const x=n.filter(b=>b.id&&!b.isNew),_=n.filter(b=>!b.id||b.isNew);for(const b of x){const{error:k}=await H.from("recruit_pipeline_stages").update({name:b.name,color:b.color,sort_order:b.sort_order}).eq("id",b.id);if(k)throw k}if(_.length>0){const{error:b}=await H.from("recruit_pipeline_stages").insert(_.map(k=>({brokerage_id:s,name:k.name,color:k.color,sort_order:k.sort_order})));if(b)throw b}},onSuccess:()=>{i([]),t.invalidateQueries({queryKey:["recruit-stages-editor",s]}),t.invalidateQueries({queryKey:["recruit-stages",s]}),ie.success("Pipeline stages saved!"),o(!1)},onError:x=>ie.error(x.message)}),m=(x,_,b)=>{r(k=>k.map((A,T)=>T===x?{...A,[_]:b}:A)),o(!0)},f=()=>{const x=n.length>0?Math.max(...n.map(_=>_.sort_order)):0;r(_=>[..._,{name:"",color:"#6366f1",sort_order:x+1,isNew:!0}]),o(!0)},g=x=>{const _=n[x];_.id&&!_.isNew&&i(b=>[...b,_.id]),r(b=>b.filter((k,A)=>A!==x)),o(!0)},y=(x,_)=>{const b=x+_;if(b<0||b>=n.length)return;const k=[...n];[k[x],k[b]]=[k[b],k[x]],k.forEach((A,T)=>A.sort_order=T+1),r(k),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((x,_)=>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(_,-1),disabled:_===0,className:"text-muted-foreground hover:text-foreground disabled:opacity-30 text-xs",children:"▲"}),e.jsx("button",{type:"button",onClick:()=>y(_,1),disabled:_===n.length-1,className:"text-muted-foreground hover:text-foreground disabled:opacity-30 text-xs",children:"▼"})]}),e.jsx(Mp,{className:"h-4 w-4 text-muted-foreground/50 shrink-0"}),e.jsx("input",{type:"color",value:x.color,onChange:b=>m(_,"color",b.target.value),className:"h-8 w-8 rounded cursor-pointer border-0 p-0 shrink-0"}),e.jsx(we,{value:x.name,onChange:b=>m(_,"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:_+1}),e.jsx(B,{variant:"ghost",size:"icon",onClick:()=>g(_),className:"text-destructive hover:text-destructive shrink-0 h-8 w-8",children:e.jsx(qn,{className:"h-4 w-4"})})]},x.id||`new-${_}`))}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(B,{variant:"outline",size:"sm",onClick:f,className:"gap-1",children:[e.jsx(nn,{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(Kl,{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 ISn({brokerageId:s}){const{data:t=[],isLoading:n}=mt({queryKey:["recruit-unsubscribed",s],queryFn:async()=>{const{data:r,error:a}=await H.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(jD,{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(We,{variant:"secondary",className:"text-base px-3 py-1",children:[t.length," total"]})]}),t.length===0?e.jsx(_e,{children:e.jsxs(De,{className:"py-12 text-center text-muted-foreground",children:[e.jsx(jD,{className:"h-10 w-10 mx-auto mb-3 opacity-40"}),e.jsx("p",{className:"text-sm",children:"No prospects have unsubscribed. Nice work!"})]})}):e.jsx("div",{className:"grid gap-3",children:t.map(r=>e.jsxs(_e,{className:"hover:shadow-sm transition-shadow",children:[e.jsx(zt,{className:"pb-3",children:e.jsxs("div",{className:"flex items-start justify-between gap-3",children:[e.jsxs("div",{children:[e.jsxs(qt,{className:"text-base",children:[r.first_name," ",r.last_name]}),e.jsxs("div",{className:"flex items-center gap-3 text-xs text-muted-foreground mt-1",children:[e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(mn,{className:"h-3 w-3"}),r.email]}),r.current_brokerage&&e.jsxs("span",{children:["· ",r.current_brokerage]})]})]}),e.jsxs("div",{className:"flex items-center gap-1.5 text-xs text-muted-foreground whitespace-nowrap",children:[e.jsx(ta,{className:"h-3 w-3"}),r.unsubscribed_at&&Js(new Date(r.unsubscribed_at),"MMM d, yyyy")]})]})}),r.unsubscribe_reason&&e.jsx(De,{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 DSn(){var o;const[s,t]=N.useState(""),[n,r]=N.useState("board"),{data:a=[],isLoading:i}=mt({queryKey:["all-brokerages"],queryFn:async()=>{const{data:c,error:d}=await H.from("brokerages").select("id, name").order("name");if(d)throw d;return c}}),l=s||((o=a[0])==null?void 0:o.id)||"";return i?e.jsx(Qs,{title:"Recruiting",description:"Agent Recruiting Pipeline",children:e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})})}):e.jsx(Qs,{title:"Recruiting",description:"Agent Recruiting Pipeline",children:e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3 flex-wrap",children:[a.length>1?e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("span",{className:"text-sm text-muted-foreground",children:"Brokerage:"}),e.jsxs(Ns,{value:l,onValueChange:t,children:[e.jsxs(ws,{className:"w-[280px]",children:[e.jsx(Ti,{className:"mr-2 h-4 w-4"}),e.jsx(ks,{placeholder:"Select brokerage"})]}),e.jsx(js,{children:a.map(c=>e.jsx(nt,{value:c.id,children:c.name},c.id))})]})]}):e.jsx("div",{}),l&&e.jsx(w9t,{brokerageId:l,trigger:e.jsxs(B,{size:"sm",className:"gap-1.5",children:[e.jsx(na,{className:"h-4 w-4"})," Record & Send Video"]})})]}),l?e.jsxs(ya,{defaultValue:"pipeline",className:"space-y-4",children:[e.jsxs(va,{className:"flex-wrap h-auto gap-1",children:[e.jsx(ls,{value:"pipeline",children:"Pipeline"}),e.jsxs(ls,{value:"contacts",children:[e.jsx(Yn,{className:"h-3.5 w-3.5 mr-1"}),"Contacts"]}),e.jsxs(ls,{value:"video-outreach",children:[e.jsx(na,{className:"h-3.5 w-3.5 mr-1"}),"Video Outreach"]}),e.jsx(ls,{value:"follow-ups",children:"Follow-ups"}),e.jsx(ls,{value:"referrals",children:"Referrals"}),e.jsx(ls,{value:"interest",children:"Interest Form"}),e.jsx(ls,{value:"landing-page",children:"Landing Page"}),e.jsx(ls,{value:"goals",children:"Goals"}),e.jsx(ls,{value:"metrics",children:"Metrics"}),e.jsx(ls,{value:"templates",children:"Email Templates"}),e.jsxs(ls,{value:"campaigns",children:[e.jsx(mn,{className:"h-3.5 w-3.5 mr-1"}),"Campaigns"]}),e.jsxs(ls,{value:"drip-assignments",children:[e.jsx(Rr,{className:"h-3.5 w-3.5 mr-1"}),"Drip Assignments"]}),e.jsx(ls,{value:"activity",children:"Recruiter Activity"}),e.jsxs(ls,{value:"email-settings",children:[e.jsx(sc,{className:"h-3.5 w-3.5 mr-1"}),"Email Settings"]}),e.jsxs(ls,{value:"pipeline-stages",children:[e.jsx(OT,{className:"h-3.5 w-3.5 mr-1"}),"Pipeline Stages"]}),e.jsxs(ls,{value:"unsubscribed",children:[e.jsx(jD,{className:"h-3.5 w-3.5 mr-1"}),"Unsubscribed"]})]}),e.jsxs(_s,{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(G0,{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(E9,{className:"h-3.5 w-3.5"})," Table"]})]})}),n==="board"?e.jsx(p9t,{brokerageId:l}):e.jsx(q5e,{brokerageId:l})]}),e.jsx(_s,{value:"contacts",children:e.jsx(q5e,{brokerageId:l})}),e.jsx(_s,{value:"video-outreach",children:e.jsx(j9t,{brokerageId:l})}),e.jsx(_s,{value:"follow-ups",children:e.jsx(b9t,{brokerageId:l})}),e.jsx(_s,{value:"referrals",children:e.jsx(y9t,{brokerageId:l})}),e.jsx(_s,{value:"interest",children:e.jsx(v9t,{brokerageId:l})}),e.jsx(_s,{value:"landing-page",children:e.jsx(_9t,{brokerageId:l})}),e.jsx(_s,{value:"goals",children:e.jsx(N9t,{brokerageId:l})}),e.jsx(_s,{value:"metrics",children:e.jsx(f9t,{brokerageId:l})}),e.jsx(_s,{value:"templates",children:e.jsx(g9t,{brokerageId:l})}),e.jsx(_s,{value:"campaigns",children:e.jsx(C9t,{brokerageId:l})}),e.jsx(_s,{value:"drip-assignments",children:e.jsx(A9t,{brokerageId:l})}),e.jsx(_s,{value:"activity",children:e.jsx(x9t,{brokerageId:l})}),e.jsx(_s,{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(QWe,{brokerageId:l})]})}),e.jsx(_s,{value:"pipeline-stages",children:e.jsx("div",{className:"max-w-2xl",children:e.jsx(T9t,{brokerageId:l})})}),e.jsx(_s,{value:"unsubscribed",children:e.jsx(ISn,{brokerageId:l})})]}):e.jsxs("div",{className:"text-center py-12 text-muted-foreground",children:[e.jsx(Ti,{className:"h-12 w-12 mx-auto mb-4 opacity-50"}),e.jsx("p",{children:"No brokerages found. Create a brokerage first."})]})]})})}function RSn({brokerageId:s}){const[t,n]=N.useState(""),[r,a]=N.useState("all"),{data:i,isLoading:l}=mt({queryKey:["recruit-sent-emails",s],queryFn:async()=>{var x;const{data:d,error:u}=await H.from("recruit_prospects").select("id, first_name, last_name, email").eq("brokerage_id",s);if(u)throw u;const h=new Map((d||[]).map(_=>[_.id,_]));if(Array.from(h.keys()).length===0)return[];const{data:f}=await H.from("recruit_videos").select("id, prospect_id, share_token, sent_at, sent_via, view_count, first_viewed_at, cta_clicked_at, video:agent_videos(title)").eq("brokerage_id",s).not("sent_at","is",null).order("sent_at",{ascending:!1}),{data:g}=await H.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 _ of f||[]){const b=h.get(_.prospect_id);b&&y.push({id:`v-${_.id}`,kind:"video",prospect_id:_.prospect_id,prospect_name:`${b.first_name||""} ${b.last_name||""}`.trim()||"—",prospect_email:b.email,subject:(x=_.video)!=null&&x.title?`Video: ${_.video.title}`:"Recruiting Video",status:_.cta_clicked_at?"clicked":_.first_viewed_at?"viewed":"sent",sent_at:_.sent_at,opened_at:_.first_viewed_at,clicked_at:_.cta_clicked_at,view_count:_.view_count,share_token:_.share_token})}for(const _ of g||[]){if(!_.sent_at)continue;const b=h.get(_.prospect_id);b&&y.push({id:`c-${_.id}`,kind:"campaign",prospect_id:_.prospect_id,prospect_name:`${b.first_name||""} ${b.last_name||""}`.trim()||"—",prospect_email:b.email,subject:_.subject||`Email #${_.email_number}`,status:_.status||"sent",sent_at:_.sent_at,opened_at:_.opened_at,clicked_at:_.clicked_at,error:_.error_message})}return y.sort((_,b)=>new Date(b.sent_at).getTime()-new Date(_.sent_at).getTime()),y}}),o=N.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=N.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:Rr,color:"text-primary"},{label:"Video Emails",value:o.videos,icon:na,color:"text-blue-500"},{label:"Campaign Emails",value:o.campaigns,icon:mn,color:"text-violet-500"},{label:"Opened / Viewed",value:o.opened,icon:da,color:"text-amber-500"},{label:"Clicked",value:o.clicked,icon:ru,color:"text-emerald-500"}].map(d=>e.jsx(_e,{children:e.jsxs(De,{className:"p-3 flex items-center gap-2.5",children:[e.jsx("div",{className:`h-9 w-9 rounded-lg bg-muted flex items-center justify-center ${d.color}`,children:e.jsx(d.icon,{className:"h-4 w-4"})}),e.jsxs("div",{children:[e.jsx("p",{className:"text-xl font-bold leading-tight",children:d.value}),e.jsx("p",{className:"text-[11px] text-muted-foreground",children:d.label})]})]})},d.label))}),e.jsxs(_e,{children:[e.jsx(zt,{className:"pb-3",children:e.jsxs("div",{className:"flex items-center justify-between gap-2 flex-wrap",children:[e.jsx(qt,{className:"text-lg",children:"Sent Emails"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ya,{value:r,onValueChange:d=>a(d),children:e.jsxs(va,{className:"h-8",children:[e.jsx(ls,{value:"all",className:"text-xs h-7",children:"All"}),e.jsx(ls,{value:"video",className:"text-xs h-7",children:"Video"}),e.jsx(ls,{value:"campaign",className:"text-xs h-7",children:"Campaign"})]})}),e.jsxs("div",{className:"relative w-56",children:[e.jsx(Gr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(we,{placeholder:"Search recruit, subject...",value:t,onChange:d=>n(d.target.value),className:"pl-9 h-9"})]})]})]})}),e.jsx(De,{children:l?e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})}):c.length===0?e.jsxs("div",{className:"text-center py-12 text-muted-foreground",children:[e.jsx(mn,{className:"h-12 w-12 mx-auto mb-4 opacity-50"}),e.jsx("p",{className:"font-medium",children:"No emails sent yet"}),e.jsx("p",{className:"text-sm mt-1",children:"Emails sent from Video Outreach or Drip Campaigns will appear here."})]}):e.jsx("div",{className:"rounded-lg border overflow-hidden",children:e.jsxs("table",{className:"w-full text-sm",children:[e.jsx("thead",{className:"bg-muted/40 text-xs text-muted-foreground",children:e.jsxs("tr",{children:[e.jsx("th",{className:"text-left font-medium px-3 py-2",children:"Type"}),e.jsx("th",{className:"text-left font-medium px-3 py-2",children:"Recruit"}),e.jsx("th",{className:"text-left font-medium px-3 py-2",children:"Subject"}),e.jsx("th",{className:"text-left font-medium px-3 py-2",children:"Status"}),e.jsx("th",{className:"text-left font-medium px-3 py-2",children:"Sent"}),e.jsx("th",{className:"text-right font-medium px-3 py-2",children:"Engagement"})]})}),e.jsx("tbody",{children:c.map(d=>e.jsxs("tr",{className:"border-t hover:bg-muted/30 transition-colors",children:[e.jsx("td",{className:"px-3 py-2",children:d.kind==="video"?e.jsxs(We,{variant:"outline",className:"gap-1",children:[e.jsx(na,{className:"h-3 w-3"}),"Video"]}):e.jsxs(We,{variant:"outline",className:"gap-1",children:[e.jsx(mn,{className:"h-3 w-3"}),"Campaign"]})}),e.jsxs("td",{className:"px-3 py-2",children:[e.jsx("div",{className:"font-medium",children:d.prospect_name}),d.prospect_email&&e.jsx("div",{className:"text-xs text-muted-foreground",children:d.prospect_email})]}),e.jsx("td",{className:"px-3 py-2 max-w-xs truncate",children:d.subject}),e.jsxs("td",{className:"px-3 py-2",children:[d.status==="failed"||d.status==="bounced"?e.jsxs(We,{variant:"destructive",className:"gap-1",children:[e.jsx(Uo,{className:"h-3 w-3"}),d.status]}):d.clicked_at?e.jsxs(We,{className:"bg-emerald-500/15 text-emerald-700 border-emerald-200 gap-1",children:[e.jsx(ru,{className:"h-3 w-3"}),"Clicked"]}):d.opened_at?e.jsxs(We,{className:"bg-blue-500/15 text-blue-700 border-blue-200 gap-1",children:[e.jsx(da,{className:"h-3 w-3"}),"Opened"]}):e.jsxs(We,{variant:"secondary",className:"gap-1",children:[e.jsx(Rr,{className:"h-3 w-3"}),"Sent"]}),d.error&&e.jsx("p",{className:"text-[10px] text-destructive mt-0.5 max-w-[200px] truncate",title:d.error,children:d.error})]}),e.jsxs("td",{className:"px-3 py-2 text-xs text-muted-foreground whitespace-nowrap",children:[Js(new Date(d.sent_at),"MMM d, yyyy"),e.jsx("div",{className:"text-[10px]",children:Js(new Date(d.sent_at),"h:mm a")})]}),e.jsx("td",{className:"px-3 py-2 text-right",children:e.jsxs("div",{className:"flex items-center gap-2 justify-end text-xs text-muted-foreground",children:[d.kind==="video"&&d.view_count!=null&&e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(da,{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(Tr,{className:"h-3.5 w-3.5"})})]})})]},d.id))})]})})})]})]})}function OSn(){var l;const{managedBrokerages:s,selectedBrokerageId:t,setSelectedBrokerageId:n}=Ls(),[r,a]=N.useState("board"),i=t||((l=s[0])==null?void 0:l.id)||"";return s.length===0?e.jsx(Qs,{title:"Recruiting",description:"Agent Recruiting Pipeline",children:e.jsxs("div",{className:"text-center py-12 text-muted-foreground",children:[e.jsx(Ti,{className:"h-12 w-12 mx-auto mb-4 opacity-50"}),e.jsx("p",{children:"No brokerages assigned to you. Contact an admin for access."})]})}):e.jsx(Qs,{title:"Recruiting",description:"Agent Recruiting Pipeline",children:e.jsxs("div",{className:"space-y-6",children:[s.length>1&&e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("span",{className:"text-sm text-muted-foreground",children:"Brokerage:"}),e.jsxs(Ns,{value:i,onValueChange:n,children:[e.jsxs(ws,{className:"w-[280px]",children:[e.jsx(Ti,{className:"mr-2 h-4 w-4"}),e.jsx(ks,{placeholder:"Select brokerage"})]}),e.jsx(js,{children:s.map(o=>e.jsx(nt,{value:o.id,children:o.name},o.id))})]})]}),i?e.jsxs(ya,{defaultValue:"pipeline",className:"space-y-4",children:[e.jsxs(va,{className:"flex-wrap h-auto gap-1",children:[e.jsx(ls,{value:"pipeline",children:"Pipeline"}),e.jsxs(ls,{value:"contacts",children:[e.jsx(Yn,{className:"h-3.5 w-3.5 mr-1"}),"Contacts"]}),e.jsxs(ls,{value:"video-outreach",children:[e.jsx(na,{className:"h-3.5 w-3.5 mr-1"}),"Video Outreach"]}),e.jsx(ls,{value:"follow-ups",children:"Follow-ups"}),e.jsx(ls,{value:"referrals",children:"Referrals"}),e.jsx(ls,{value:"interest",children:"Interest Form"}),e.jsx(ls,{value:"landing-page",children:"Landing Page"}),e.jsx(ls,{value:"goals",children:"Goals"}),e.jsx(ls,{value:"metrics",children:"Metrics"}),e.jsx(ls,{value:"templates",children:"Email Templates"}),e.jsxs(ls,{value:"campaigns",children:[e.jsx(mn,{className:"h-3.5 w-3.5 mr-1"}),"Campaigns"]}),e.jsxs(ls,{value:"drip-assignments",children:[e.jsx(Rr,{className:"h-3.5 w-3.5 mr-1"}),"Drip Assignments"]}),e.jsxs(ls,{value:"sent-emails",children:[e.jsx(n3,{className:"h-3.5 w-3.5 mr-1"}),"Sent Emails"]}),e.jsx(ls,{value:"activity",children:"Recruiter Activity"}),e.jsxs(ls,{value:"email-settings",children:[e.jsx(sc,{className:"h-3.5 w-3.5 mr-1"}),"Email Settings"]}),e.jsxs(ls,{value:"pipeline-stages",children:[e.jsx(OT,{className:"h-3.5 w-3.5 mr-1"}),"Pipeline Stages"]})]}),e.jsxs(_s,{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:r==="board"?"default":"ghost",size:"sm",className:"h-7 px-2.5 gap-1.5",onClick:()=>a("board"),children:[e.jsx(G0,{className:"h-3.5 w-3.5"})," Board"]}),e.jsxs(B,{variant:r==="table"?"default":"ghost",size:"sm",className:"h-7 px-2.5 gap-1.5",onClick:()=>a("table"),children:[e.jsx(E9,{className:"h-3.5 w-3.5"})," Table"]})]})}),r==="board"?e.jsx(p9t,{brokerageId:i}):e.jsx(q5e,{brokerageId:i})]}),e.jsx(_s,{value:"contacts",children:e.jsx(q5e,{brokerageId:i})}),e.jsx(_s,{value:"video-outreach",children:e.jsx(j9t,{brokerageId:i})}),e.jsx(_s,{value:"follow-ups",children:e.jsx(b9t,{brokerageId:i})}),e.jsx(_s,{value:"referrals",children:e.jsx(y9t,{brokerageId:i})}),e.jsx(_s,{value:"interest",children:e.jsx(v9t,{brokerageId:i})}),e.jsx(_s,{value:"landing-page",children:e.jsx(_9t,{brokerageId:i})}),e.jsx(_s,{value:"goals",children:e.jsx(N9t,{brokerageId:i})}),e.jsx(_s,{value:"metrics",children:e.jsx(f9t,{brokerageId:i})}),e.jsx(_s,{value:"templates",children:e.jsx(g9t,{brokerageId:i})}),e.jsx(_s,{value:"campaigns",children:e.jsx(C9t,{brokerageId:i})}),e.jsx(_s,{value:"drip-assignments",children:e.jsx(A9t,{brokerageId:i})}),e.jsx(_s,{value:"sent-emails",children:e.jsx(RSn,{brokerageId:i})}),e.jsx(_s,{value:"activity",children:e.jsx(x9t,{brokerageId:i})}),e.jsx(_s,{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(QWe,{brokerageId:i})]})}),e.jsx(_s,{value:"pipeline-stages",children:e.jsx("div",{className:"max-w-2xl",children:e.jsx(T9t,{brokerageId:i})})})]}):e.jsxs("div",{className:"text-center py-12 text-muted-foreground",children:[e.jsx(Ti,{className:"h-12 w-12 mx-auto mb-4 opacity-50"}),e.jsx("p",{children:"No brokerages found."})]})]})})}function FSn(){const[s,t]=N.useState(""),{data:n,isLoading:r}=mt({queryKey:["admin-brokerage-content-activity"],queryFn:async()=>{const{data:o}=await H.from("brokerages").select("id, name");if(!o)return[];const{data:c}=await H.from("brokerage_content").select("id, brokerage_id, content_type, created_at"),{data:d}=await H.from("brokerage_content_categories").select("id, brokerage_id"),u=c||[],h=d||[],m=o.map(f=>{const g=u.filter(_=>_.brokerage_id===f.id),y=h.filter(_=>_.brokerage_id===f.id),x=g.length>0?g.reduce((_,b)=>b.created_at>_?b.created_at:_,g[0].created_at):null;return{brokerage_id:f.id,brokerage_name:f.name,total_items:g.length,videos:g.filter(_=>_.content_type==="video").length,pdfs:g.filter(_=>_.content_type==="pdf").length,links:g.filter(_=>_.content_type==="link"||_.content_type==="canva_link").length,events:g.filter(_=>_.content_type==="event").length,graphics:g.filter(_=>_.content_type==="graphic").length,latest_item_date:x,categories:y.length}});return m.sort((f,g)=>g.total_items-f.total_items),m}}),a=(n||[]).filter(o=>o.brokerage_name.toLowerCase().includes(s.toLowerCase())),i=a.reduce((o,c)=>o+c.total_items,0),l=a.filter(o=>o.total_items>0).length;return e.jsx(Qs,{title:"Brokerage Content Activity",children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(Uh,{title:"Brokerage Content Activity",description:"See which brokerages are creating custom content for their agents"}),e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-3 gap-4",children:[e.jsxs(_e,{children:[e.jsx(zt,{className:"pb-2",children:e.jsx(qt,{className:"text-sm font-medium text-muted-foreground",children:"Active Brokerages"})}),e.jsxs(De,{children:[e.jsx("p",{className:"text-2xl font-bold",children:l}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"with content uploaded"})]})]}),e.jsxs(_e,{children:[e.jsx(zt,{className:"pb-2",children:e.jsx(qt,{className:"text-sm font-medium text-muted-foreground",children:"Total Content Items"})}),e.jsxs(De,{children:[e.jsx("p",{className:"text-2xl font-bold",children:i}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"across all brokerages"})]})]}),e.jsxs(_e,{children:[e.jsx(zt,{className:"pb-2",children:e.jsx(qt,{className:"text-sm font-medium text-muted-foreground",children:"Total Brokerages"})}),e.jsxs(De,{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(Gr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(we,{placeholder:"Search brokerages...",value:s,onChange:o=>t(o.target.value),className:"pl-9"})]}),e.jsx(_e,{children:e.jsx(De,{className:"p-0",children:e.jsxs(Oa,{children:[e.jsx(Fa,{children:e.jsxs(un,{children:[e.jsx(Mt,{children:"Brokerage"}),e.jsx(Mt,{className:"text-center",children:"Total"}),e.jsx(Mt,{className:"text-center",children:e.jsxs("div",{className:"flex items-center justify-center gap-1",children:[e.jsx(na,{className:"h-3 w-3"})," Videos"]})}),e.jsx(Mt,{className:"text-center",children:e.jsxs("div",{className:"flex items-center justify-center gap-1",children:[e.jsx(Wr,{className:"h-3 w-3"})," PDFs"]})}),e.jsx(Mt,{className:"text-center",children:e.jsxs("div",{className:"flex items-center justify-center gap-1",children:[e.jsx(cd,{className:"h-3 w-3"})," Links"]})}),e.jsx(Mt,{className:"text-center",children:e.jsxs("div",{className:"flex items-center justify-center gap-1",children:[e.jsx(ld,{className:"h-3 w-3"})," Events"]})}),e.jsx(Mt,{className:"text-center",children:e.jsxs("div",{className:"flex items-center justify-center gap-1",children:[e.jsx(pc,{className:"h-3 w-3"})," Graphics"]})}),e.jsx(Mt,{className:"text-center",children:"Categories"}),e.jsx(Mt,{children:"Last Upload"})]})}),e.jsx(za,{children:r?e.jsx(un,{children:e.jsx(gt,{colSpan:9,className:"text-center py-8 text-muted-foreground",children:"Loading..."})}):a.length===0?e.jsx(un,{children:e.jsx(gt,{colSpan:9,className:"text-center py-8 text-muted-foreground",children:"No brokerages found"})}):a.map(o=>e.jsxs(un,{className:o.total_items===0?"opacity-50":"",children:[e.jsx(gt,{children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ti,{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(We,{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:Js(new Date(o.latest_item_date),"MMM d, yyyy")}):e.jsx("span",{className:"text-muted-foreground",children:"–"})})]},o.brokerage_id))})]})})})]})})}const zSn=[{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:"📉"}],igt=[{value:"instagram-square",label:"Instagram Post",dimensions:"1080×1080",icon:e.jsx(dm,{className:"h-4 w-4"})},{value:"instagram-story",label:"Instagram Story",dimensions:"1080×1920",icon:e.jsx(dm,{className:"h-4 w-4"})},{value:"facebook-post",label:"Facebook Post",dimensions:"1200×630",icon:e.jsx(Kf,{className:"h-4 w-4"})}],BSn=[{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:"📰"}],ogt=s=>new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:0}).format(s),lgt={"luxury-dark":PVe,"modern-clean":IVe,"bold-colorful":DVe,editorial:RVe};function $Sn(){const[s,t]=N.useState(""),[n,r]=N.useState("address"),[a,i]=N.useState(!1),[l,o]=N.useState([]),[c,d]=N.useState(null),[u,h]=N.useState(0),[m,f]=N.useState("just-listed"),[g,y]=N.useState(["instagram-square"]),[x,_]=N.useState("luxury-dark"),[b,k]=N.useState(!1),[A,T]=N.useState(""),[P,I]=N.useState(""),[M,L]=N.useState(""),[z,$]=N.useState(!1),[V,W]=N.useState(!1),[G,X]=N.useState([]),[te,ne]=N.useState("search"),me=N.useRef({});N.useEffect(()=>{(async()=>{const{data:{user:Ie}}=await H.auth.getUser();if(!Ie)return;const{data:Me}=await H.from("profiles").select("name, avatar_url, brokerages(name)").eq("id",Ie.id).single();if(Me){T(Me.name||""),L(Me.avatar_url||"");const Re=Me.brokerages;I((Re==null?void 0:Re.name)||"")}})()},[]);const ue=async()=>{var Se;if(s.trim()){i(!0),o([]);try{const{data:Ie,error:Me}=await H.functions.invoke("repliers-mls-search",{body:{searchType:n,query:s.trim()}});if(Me)throw Me;if(Ie.error)throw new Error(Ie.error);o(Ie.listings||[]),((Se=Ie.listings)==null?void 0:Se.length)===0&&ie.info("No listings found. Try a different search.")}catch(Ie){ie.error(Ie.message||"Search failed")}finally{i(!1)}}},ce=Se=>{var Ie;d(Se),h(0),ne("customize"),Se.soldDate||(Ie=Se.status)!=null&&Ie.toLowerCase().includes("sold")?f("just-sold"):f("just-listed")},ae=Se=>{y(Ie=>Ie.includes(Se)?Ie.filter(Me=>Me!==Se):[...Ie,Se])},he=N.useCallback(async()=>{if(!(!c||g.length===0)){$(!0),X([]),ne("generate");try{await new Promise(Ie=>setTimeout(Ie,500));const Se=[];for(const Ie of g){const Me=`${x}-${Ie}`,Re=me.current[Me];if(!Re)continue;const Be=cT[Ie],Ne=await LVe(Re,{width:Be.width,height:Be.height,pixelRatio:1,cacheBust:!0,style:{transform:"none",transformOrigin:"top left"}});Se.push({format:Ie,imageUrl:Ne})}X(Se),ie.success(`Generated ${Se.length} social post${Se.length>1?"s":""}!`)}catch(Se){ie.error(Se.message||"Generation failed")}finally{$(!1)}}},[c,g,x,u,b,A,P,M,m]),xe=async()=>{if(!(!c||g.length===0)){$(!0),X([]),ne("generate");try{const Se={...c,photos:c.photos.length>0?[c.photos[u]]:[]},Ie=[];for(const Me of g){const{data:Re,error:Be}=await H.functions.invoke("generate-listing-social-post",{body:{listing:Se,postType:m,format:Me,branding:b?{enabled:!0,agentName:A,brokerage:P}:{enabled:!1}}});if(Be)throw Be;if(Re.error)throw new Error(Re.error);Ie.push({format:Me,imageUrl:Re.imageUrl})}X(Ie),ie.success(`Generated ${Ie.length} AI post${Ie.length>1?"s":""}!`)}catch(Se){ie.error(Se.message||"AI generation failed")}finally{$(!1)}}},ve=()=>V?xe():he(),ge=(Se,Ie)=>{var Re;const Me=document.createElement("a");Me.href=Se,Me.download=`${((Re=c==null?void 0:c.address)==null?void 0:Re.replace(/\s+/g,"-"))||"listing"}-${m}-${Ie}.png`,document.body.appendChild(Me),Me.click(),document.body.removeChild(Me)},be=c?{listing:c,postType:m,format:"instagram-square",branding:b?{enabled:!0,agentName:A,brokerage:P,agentPhotoUrl:M||void 0}:{enabled:!1},selectedPhotoIndex:u}:null;return e.jsx(Qs,{children:e.jsxs("div",{className:"space-y-6 p-4 md:p-8",children:[e.jsx(Uh,{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:()=>ne("search"),className:`flex items-center gap-1.5 px-3 py-1.5 rounded-full transition-colors ${te==="search"?"bg-primary text-primary-foreground":"bg-muted text-muted-foreground hover:text-foreground"}`,children:[e.jsx(Gr,{className:"h-3.5 w-3.5"})," 1. Find Listing"]}),e.jsx(Qa,{className:"h-4 w-4 text-muted-foreground"}),e.jsxs("button",{onClick:()=>c&&ne("customize"),disabled:!c,className:`flex items-center gap-1.5 px-3 py-1.5 rounded-full transition-colors ${te==="customize"?"bg-primary text-primary-foreground":c?"bg-muted text-muted-foreground hover:text-foreground":"bg-muted text-muted-foreground/50 cursor-not-allowed"}`,children:[e.jsx(Cn,{className:"h-3.5 w-3.5"})," 2. Customize"]}),e.jsx(Qa,{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 ${te==="generate"?"bg-primary text-primary-foreground":"bg-muted text-muted-foreground/50"}`,children:[e.jsx(pc,{className:"h-3.5 w-3.5"})," 3. Generate"]})]}),te==="search"&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs(_e,{children:[e.jsxs(zt,{children:[e.jsxs(qt,{className:"flex items-center gap-2",children:[e.jsx(Gr,{className:"h-5 w-5 text-primary"})," Search MLS Listings ",e.jsx(R4t,{})]}),e.jsx(_r,{children:"Find a listing by MLS number or property address using Repliers.io"})]}),e.jsxs(De,{className:"space-y-4",children:[e.jsx(ya,{value:n,onValueChange:Se=>r(Se),children:e.jsxs(va,{children:[e.jsxs(ls,{value:"address",children:[e.jsx(ii,{className:"h-4 w-4 mr-1.5"})," Address"]}),e.jsxs(ls,{value:"mls",children:[e.jsx(pf,{className:"h-4 w-4 mr-1.5"})," MLS #"]})]})}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(we,{value:s,onChange:Se=>t(Se.target.value),placeholder:n==="mls"?"Enter MLS number...":"Enter property address...",className:"flex-1",onKeyDown:Se=>Se.key==="Enter"&&ue()}),e.jsxs(B,{onClick:ue,disabled:a||!s.trim(),children:[a?e.jsx(us,{className:"h-4 w-4 animate-spin"}):e.jsx(Gr,{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((Se,Ie)=>{var Me;return e.jsx(_e,{className:"cursor-pointer hover:border-primary/50 hover:shadow-md transition-all group",onClick:()=>ce(Se),children:e.jsx(De,{className:"p-0",children:e.jsxs("div",{className:"flex",children:[e.jsx("div",{className:"w-32 h-28 flex-shrink-0 bg-muted rounded-l-lg overflow-hidden",children:(Me=Se.photos)!=null&&Me[0]?e.jsx("img",{src:Se.photos[0],alt:Se.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(_a,{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:ogt(Se.price)}),e.jsx("p",{className:"text-sm text-muted-foreground truncate",children:Se.address}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[Se.city,", ",Se.state," ",Se.zip]}),e.jsxs("div",{className:"flex items-center gap-3 mt-1.5 text-xs text-muted-foreground",children:[Se.bedrooms>0&&e.jsxs("span",{className:"flex items-center gap-0.5",children:[e.jsx(J4,{className:"h-3 w-3"})," ",Se.bedrooms]}),Se.bathrooms>0&&e.jsxs("span",{className:"flex items-center gap-0.5",children:[e.jsx(Wx,{className:"h-3 w-3"})," ",Se.bathrooms]}),Se.sqft>0&&e.jsxs("span",{className:"flex items-center gap-0.5",children:[e.jsx(vD,{className:"h-3 w-3"})," ",Se.sqft.toLocaleString()]})]}),e.jsxs("div",{className:"flex items-center gap-2 mt-1",children:[e.jsx(We,{variant:"outline",className:"text-[10px]",children:Se.mlsNumber}),e.jsx(We,{variant:"outline",className:"text-[10px]",children:Se.status})]})]})]})})},Se.mlsNumber||Ie)})})]})]}),te==="customize"&&c&&e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-3 gap-6",children:[e.jsxs(_e,{className:"lg:col-span-1",children:[e.jsx(zt,{className:"pb-3",children:e.jsx(qt,{className:"text-base",children:"Selected Listing"})}),e.jsxs(De,{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(Se=>Math.max(0,Se-1)),disabled:u===0,children:e.jsx(Fc,{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(Se=>Math.min(c.photos.length-1,Se+1)),disabled:u===c.photos.length-1,children:e.jsx(Qa,{className:"h-4 w-4"})})]})]}),e.jsxs("div",{children:[e.jsx("p",{className:"font-bold text-lg",children:ogt(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:()=>{ne("search"),d(null)},children:[e.jsx(hf,{className:"h-3.5 w-3.5 mr-1.5"})," Choose Different Listing"]})]})]}),e.jsxs(_e,{className:"lg:col-span-2",children:[e.jsxs(zt,{children:[e.jsxs(qt,{className:"flex items-center gap-2",children:[e.jsx(Cn,{className:"h-5 w-5 text-primary"})," Customize Your Post"]}),e.jsx(_r,{children:"Choose template, post type, format, and branding"})]}),e.jsxs(De,{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(zc,{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(zn,{checked:V,onCheckedChange:W}),V&&e.jsx(Zg,{className:"h-4 w-4 text-purple-500"})]})]}),!V&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs(re,{className:"text-sm font-medium flex items-center gap-2",children:[e.jsx(zc,{className:"h-4 w-4"})," Template Style"]}),e.jsx("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-2",children:BSn.map(Se=>e.jsxs("button",{onClick:()=>_(Se.value),className:`flex flex-col items-center gap-1 px-3 py-3 rounded-lg border-2 transition-all text-center ${x===Se.value?"border-primary bg-primary/5":"border-border hover:border-primary/30"}`,children:[e.jsx("span",{className:"text-2xl",children:Se.preview}),e.jsx("span",{className:"text-sm font-medium",children:Se.label}),e.jsx("span",{className:"text-[10px] text-muted-foreground leading-tight",children:Se.description})]},Se.value))})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{className:"text-sm font-medium",children:"Post Type"}),e.jsx("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-2",children:zSn.map(Se=>e.jsxs("button",{onClick:()=>f(Se.value),className:`flex items-center gap-2 px-3 py-2.5 rounded-lg border-2 transition-all text-sm font-medium ${m===Se.value?"border-primary bg-primary/5":"border-border hover:border-primary/30"}`,children:[e.jsx("span",{className:"text-lg",children:Se.icon})," ",Se.label]},Se.value))})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{className:"text-sm font-medium",children:"Output Formats"}),e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-2",children:igt.map(Se=>e.jsxs("button",{onClick:()=>ae(Se.value),className:`flex items-center gap-2 px-3 py-2.5 rounded-lg border-2 transition-all text-sm ${g.includes(Se.value)?"border-primary bg-primary/5":"border-border hover:border-primary/30"}`,children:[Se.icon,e.jsxs("div",{className:"text-left",children:[e.jsx("p",{className:"font-medium",children:Se.label}),e.jsx("p",{className:"text-[10px] text-muted-foreground",children:Se.dimensions})]})]},Se.value))})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs(re,{className:"text-sm font-medium flex items-center gap-2",children:[e.jsx(Ro,{className:"h-4 w-4"})," Agent Branding"]}),e.jsx(zn,{checked:b,onCheckedChange:k})]}),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(re,{className:"text-xs text-muted-foreground",children:"Agent Name"}),e.jsx(we,{value:A,onChange:Se=>T(Se.target.value),placeholder:"Jane Smith"})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(re,{className:"text-xs text-muted-foreground",children:"Brokerage (optional)"}),e.jsx(we,{value:P,onChange:Se=>I(Se.target.value),placeholder:"XYZ Realty"})]})]})]})]}),!V&&be&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{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*(cT[g[0]||"instagram-square"].height/cT[g[0]||"instagram-square"].width)},children:(()=>{const Se=lgt[x],Ie=g[0]||"instagram-square";return e.jsx(Se,{...be,format:Ie})})()})})]}),e.jsx(B,{onClick:ve,disabled:g.length===0||z,size:"lg",className:"w-full gap-2",children:z?e.jsxs(e.Fragment,{children:[e.jsx(us,{className:"h-5 w-5 animate-spin"})," Generating ",g.length," post",g.length>1?"s":"","..."]}):e.jsxs(e.Fragment,{children:[V?e.jsx(Zg,{className:"h-5 w-5"}):e.jsx(Cn,{className:"h-5 w-5"}),"Generate ",g.length," Social Post",g.length>1?"s":"",V&&e.jsx(We,{variant:"outline",className:"ml-2 text-[10px]",children:"Uses Credits"})]})})]})]})]}),te==="generate"&&e.jsxs("div",{className:"space-y-4",children:[z&&e.jsx(_e,{children:e.jsxs(De,{className:"flex flex-col items-center justify-center py-16",children:[e.jsx(us,{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"})]})}),G.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:()=>ne("customize"),children:[e.jsx(hf,{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:G.map((Se,Ie)=>{const Me=igt.find(Re=>Re.value===Se.format);return e.jsxs(_e,{className:"overflow-hidden",children:[e.jsx("div",{className:"bg-muted/30 p-1",children:e.jsx("img",{src:Se.imageUrl,alt:`${Se.format} social post`,className:"w-full rounded"})}),e.jsxs(De,{className:"p-3 space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-1.5",children:[Me==null?void 0:Me.icon,e.jsx("span",{className:"text-sm font-medium",children:Me==null?void 0:Me.label})]}),e.jsx(We,{variant:"outline",className:"text-[10px]",children:Me==null?void 0:Me.dimensions})]}),e.jsxs(B,{size:"sm",className:"w-full gap-1.5",onClick:()=>ge(Se.imageUrl,Se.format),children:[e.jsx(oi,{className:"h-3.5 w-3.5"})," Download"]})]})]},Ie)})})]})]}),te==="generate"&&!V&&c&&be&&e.jsx("div",{style:{position:"absolute",left:"-9999px",top:0},"aria-hidden":!0,children:g.map(Se=>{const Ie=lgt[x],Me=cT[Se];return e.jsx("div",{style:{width:Me.width,height:Me.height},children:e.jsx(Ie,{ref:Re=>{me.current[`${x}-${Se}`]=Re},...be,format:Se})},`${x}-${Se}`)})})]})})}function USn(){return mt({queryKey:["lms-courses-admin"],queryFn:async()=>{const{data:s,error:t}=await H.from("lms_courses").select("*, modules:lms_modules(count), access:lms_course_access(*)").order("sort_order");if(t)throw t;return s}})}function qSn(s){return mt({queryKey:["lms-course-admin",s],queryFn:async()=>{if(!s)return null;const{data:t,error:n}=await H.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 VSn(){const s=as();return _t({mutationFn:async t=>{const{data:n,error:r}=await H.from("lms_courses").insert(t).select().single();if(r)throw r;return n},onSuccess:()=>s.invalidateQueries({queryKey:["lms-courses"]})})}function E9t(){const s=as();return _t({mutationFn:async({id:t,...n})=>{const{data:r,error:a}=await H.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 HSn(){const s=as();return _t({mutationFn:async t=>{const{error:n}=await H.from("lms_courses").delete().eq("id",t);if(n)throw n},onSuccess:()=>s.invalidateQueries({queryKey:["lms-courses"]})})}function GSn(){const s=as();return _t({mutationFn:async t=>{const{data:n,error:r}=await H.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 WSn(){const s=as();return _t({mutationFn:async({id:t,...n})=>{const{data:r,error:a}=await H.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 KSn(){const s=as();return _t({mutationFn:async t=>{const{error:n}=await H.from("lms_modules").delete().eq("id",t);if(n)throw n},onSuccess:()=>{s.invalidateQueries({queryKey:["lms-course"]}),s.invalidateQueries({queryKey:["lms-course-admin"]})}})}function YSn(){const s=as();return _t({mutationFn:async t=>{const{data:n,error:r}=await H.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 ZSn(){const s=as();return _t({mutationFn:async t=>{const{error:n}=await H.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 XSn(){const s=as();return _t({mutationFn:async({courseId:t,accessRules:n})=>{const{error:r}=await H.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 H.from("lms_course_access").insert(a);if(i)throw i}},onSuccess:()=>{s.invalidateQueries({queryKey:["lms-courses"]}),s.invalidateQueries({queryKey:["lms-course"]})}})}function QSn(){return mt({queryKey:["lms-courses-agent"],queryFn:async()=>{const{data:s,error:t}=await H.from("lms_courses").select("*, modules:lms_modules(id)").eq("is_published",!0).order("sort_order");if(t)throw t;return s}})}function JSn(s){return mt({queryKey:["lms-course-agent",s],queryFn:async()=>{if(!s)return null;const{data:t,error:n}=await H.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 M9t(s){return mt({queryKey:["lms-progress",s],queryFn:async()=>{if(!s)return[];const{data:t,error:n}=await H.from("lms_progress").select("*").eq("course_id",s);if(n)throw n;return t},enabled:!!s})}function e4n(){const s=as();return _t({mutationFn:async({courseId:t,moduleId:n,userId:r})=>{const{data:a,error:i}=await H.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 t4n(){const{user:s}=Ls(),t=tr(),{data:n,isLoading:r}=USn(),a=VSn(),i=E9t(),l=HSn(),[o,c]=N.useState(!1),[d,u]=N.useState(""),[h,m]=N.useState(""),[f,g]=N.useState(!0),y=async()=>{if(!(!d.trim()||!s))try{const b=await a.mutateAsync({title:d.trim(),description:h.trim()||void 0,is_sequential:f,created_by:s.id});ie.success("Course created"),c(!1),u(""),m(""),g(!0),t(`/admin/lms/${b.id}`)}catch{ie.error("Failed to create course")}},x=async b=>{try{await i.mutateAsync({id:b.id,is_published:!b.is_published}),ie.success(b.is_published?"Course unpublished":"Course published")}catch{ie.error("Failed to update course")}},_=async b=>{if(confirm("Delete this course and all its modules? This cannot be undone."))try{await l.mutateAsync(b),ie.success("Course deleted")}catch{ie.error("Failed to delete")}};return e.jsxs(Qs,{title:"LevelUp U - Admin",children:[e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsxs("h1",{className:"text-2xl font-bold text-foreground flex items-center gap-2",children:[e.jsx(Oh,{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(fl,{className:"h-4 w-4 mr-2"}),"Analytics"]}),e.jsxs(B,{onClick:()=>c(!0),children:[e.jsx(nn,{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(_e,{className:"animate-pulse",children:e.jsxs(zt,{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 P,I;const k=((I=(P=b.modules)==null?void 0:P[0])==null?void 0:I.count)??0,A=b.access||[],T=A.length===0?"No access set":A.some(M=>M.access_type==="all")?"All agents":`${A.length} rule(s)`;return e.jsxs(_e,{className:"group hover:shadow-md transition-all hover:border-primary/50 cursor-pointer",onClick:()=>t(`/admin/lms/${b.id}`),children:[e.jsx(zt,{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(qt,{className:"text-base truncate",children:b.title}),b.description&&e.jsx(_r,{className:"mt-1 line-clamp-2",children:b.description})]}),e.jsx(We,{variant:b.is_published?"default":"secondary",className:"ml-2 shrink-0",children:b.is_published?"Published":"Draft"})]})}),e.jsxs(De,{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(Ep,{className:"h-3.5 w-3.5"}),k," module",k!==1?"s":""]}),e.jsxs("span",{className:"flex items-center gap-1",children:[b.is_sequential?e.jsx(dj,{className:"h-3.5 w-3.5"}):e.jsx(ND,{className:"h-3.5 w-3.5"}),b.is_sequential?"Sequential":"Free order"]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Yn,{className:"h-3.5 w-3.5"}),T]})]}),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(),x(b)},children:[b.is_published?e.jsx(V0,{className:"h-3.5 w-3.5 mr-1"}):e.jsx(da,{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(),_(b.id)},children:e.jsx(qn,{className:"h-3.5 w-3.5"})}),e.jsx("div",{className:"flex-1"}),e.jsx(vi,{className:"h-4 w-4 text-muted-foreground"})]})]})]},b.id)})}):e.jsx(_e,{className:"border-dashed",children:e.jsxs(De,{className:"flex flex-col items-center justify-center py-16 text-center",children:[e.jsx(Ep,{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(nn,{className:"h-4 w-4 mr-2"}),"Create Course"]})]})})]}),e.jsx(Bs,{open:o,onOpenChange:c,children:e.jsxs(Fs,{children:[e.jsxs(qs,{children:[e.jsx($s,{children:"Create New Course"}),e.jsx(Ar,{children:"Set up a new training course for your agents"})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(re,{children:"Course Title"}),e.jsx(we,{value:d,onChange:b=>u(b.target.value),placeholder:"e.g. LevelUp Onboarding"})]}),e.jsxs("div",{children:[e.jsx(re,{children:"Description"}),e.jsx(Ws,{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(zn,{checked:f,onCheckedChange:g})]})]}),e.jsxs(Cr,{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 s4n(){const{courseId:s}=uo(),t=tr(),{data:n,isLoading:r}=qSn(s),a=E9t(),i=GSn(),l=WSn(),o=KSn(),c=YSn(),d=ZSn(),u=XSn(),{data:h}=mt({queryKey:["all-brokerages"],queryFn:async()=>{const{data:st}=await H.from("brokerages").select("id, name").order("name");return st||[]}}),[m,f]=N.useState(null),[g,y]=N.useState(!1),[x,_]=N.useState({title:"",description:"",video_url:"",text_content:"",duration_minutes:""}),[b,k]=N.useState(null),[A,T]=N.useState({title:"",resource_type:"link",url:""}),[P,I]=N.useState(new Set),[M,L]=N.useState(null),[z,$]=N.useState(0),[V,W]=N.useState(!1),G=N.useRef(null),X=N.useRef(null),[te,ne]=N.useState(!1),[me,ue]=N.useState(""),[ce,ae]=N.useState(""),[he,xe]=N.useState(""),[ve,ge]=N.useState(!1);if(r)return e.jsx(Qs,{title:"Loading...",children:e.jsx("div",{className:"flex items-center justify-center py-20",children:e.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})})});if(!n)return e.jsx(Qs,{title:"Course Not Found",children:e.jsxs("div",{className:"text-center py-20",children:[e.jsx("p",{className:"text-muted-foreground",children:"Course not found"}),e.jsxs(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 be=n.modules||[],Se=n.access||[],Ie=Se.some(st=>st.access_type==="all"),Me=Se.filter(st=>st.access_type==="brokerage").map(st=>st.brokerage_id),Re=(h||[]).filter(st=>st.name.toLowerCase().includes(me.toLowerCase())),Be=st=>{const rt=new Set(P);rt.has(st)?rt.delete(st):rt.add(st),I(rt)},Ne=async()=>{if(!M)return null;W(!0),$(0);try{const{data:st,error:rt}=await H.functions.invoke("bunny-upload",{body:{action:"create",title:M.name}});if(rt)throw new Error(rt.message);const{videoId:Ze,libraryId:ht}=st,{data:Bt,error:Ct}=await H.functions.invoke("bunny-upload",{body:{action:"upload-url",videoId:Ze,libraryId:ht}});if(Ct)throw new Error(Ct.message);const Yt=new XMLHttpRequest;return await new Promise((Kt,Xs)=>{Yt.upload.onprogress=zs=>{zs.lengthComputable&&$(Math.round(zs.loaded/zs.total*100))},Yt.onload=()=>Yt.status>=200&&Yt.status<300?Kt():Xs(new Error(`Upload failed: ${Yt.status}`)),Yt.onerror=()=>Xs(new Error("Upload failed")),Yt.open("PUT",Bt.uploadUrl),Yt.setRequestHeader("AccessKey",Bt.apiKey),Yt.send(M)}),`https://iframe.mediadelivery.net/embed/${ht}/${Ze}`}catch(st){return console.error("Bunny upload error:",st),ie.error("Video upload failed"),null}finally{W(!1),$(0)}},Ge=async()=>{if(x.title.trim())try{let st=x.video_url.trim()||void 0;if(M){const rt=await Ne();if(!rt)return;st=rt}await i.mutateAsync({course_id:n.id,title:x.title.trim(),description:x.description.trim()||void 0,video_url:st,text_content:x.text_content.trim()||void 0,duration_minutes:x.duration_minutes?parseInt(x.duration_minutes):void 0,sort_order:be.length}),ie.success("Module added"),y(!1),_({title:"",description:"",video_url:"",text_content:"",duration_minutes:""}),L(null)}catch{ie.error("Failed to add module")}},Ce=async()=>{if(m)try{let st=x.video_url.trim()||null;if(M){const rt=await Ne();if(!rt)return;st=rt}await l.mutateAsync({id:m.id,title:x.title.trim(),description:x.description.trim()||null,video_url:st,text_content:x.text_content.trim()||null,duration_minutes:x.duration_minutes?parseInt(x.duration_minutes):null}),ie.success("Module updated"),f(null),L(null)}catch{ie.error("Failed to update")}},Fe=async st=>{if(confirm("Delete this module?"))try{await o.mutateAsync(st),ie.success("Module deleted")}catch{ie.error("Failed to delete")}},Ae=async st=>{if(A.title.trim())try{await c.mutateAsync({module_id:st,title:A.title.trim(),resource_type:A.resource_type,url:A.url.trim()||void 0}),ie.success("Resource added"),k(null),T({title:"",resource_type:"link",url:""})}catch{ie.error("Failed to add resource")}},Xe=async()=>{try{await u.mutateAsync({courseId:n.id,accessRules:[{access_type:"all"}]}),ie.success("Access updated: All brokerages / all agents")}catch{ie.error("Failed to update access")}},$e=async st=>{const rt=Se.filter(Ct=>Ct.access_type==="brokerage").map(Ct=>Ct.brokerage_id),Ze=rt.includes(st);let ht;Ze?ht=rt.filter(Ct=>Ct!==st):ht=[...rt,st];const Bt=ht.map(Ct=>({access_type:"brokerage",brokerage_id:Ct}));try{await u.mutateAsync({courseId:n.id,accessRules:Bt}),ie.success(Ze?"Brokerage removed":"Brokerage added")}catch{ie.error("Failed to update access")}},Ye=async()=>{try{await u.mutateAsync({courseId:n.id,accessRules:[]}),ie.success("Access cleared")}catch{ie.error("Failed")}},Je=async(st,rt)=>{const Ze=rt==="up"?st-1:st+1;if(!(Ze<0||Ze>=be.length))try{await Promise.all([l.mutateAsync({id:be[st].id,sort_order:Ze}),l.mutateAsync({id:be[Ze].id,sort_order:st})])}catch{ie.error("Failed to reorder")}},Ke=async()=>{try{await a.mutateAsync({id:n.id,title:ce,description:he||null}),ie.success("Course updated"),ge(!1)}catch{ie.error("Failed to update")}};return e.jsxs(Qs,{title:n.title,children:[e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex items-start justify-between gap-4",children:[e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx(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(We,{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(dj,{className:"h-3.5 w-3.5"}):e.jsx(ND,{className:"h-3.5 w-3.5"}),n.is_sequential?"Sequential":"Free order"]}),e.jsxs("span",{children:[be.length," module",be.length!==1?"s":""]})]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(B,{variant:"outline",size:"sm",onClick:()=>{ae(n.title),xe(n.description||""),ge(!0)},children:[e.jsx(Ja,{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(()=>ie.success(n.is_published?"Unpublished":"Published")),children:[n.is_published?e.jsx(V0,{className:"h-3.5 w-3.5 mr-1"}):e.jsx(da,{className:"h-3.5 w-3.5 mr-1"}),n.is_published?"Unpublish":"Publish"]})]})]}),e.jsxs(ya,{defaultValue:"modules",className:"w-full",children:[e.jsxs(va,{children:[e.jsx(ls,{value:"modules",children:"Modules"}),e.jsx(ls,{value:"access",children:"Access & Permissions"}),e.jsx(ls,{value:"settings",children:"Settings"})]}),e.jsxs(_s,{value:"modules",className:"mt-6 space-y-4",children:[be.map((st,rt)=>e.jsxs(_e,{className:"overflow-hidden",children:[e.jsxs("div",{className:"flex items-center gap-3 p-4 cursor-pointer hover:bg-muted/50 transition-colors",onClick:()=>Be(st.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:Ze=>{Ze.stopPropagation(),Je(rt,"up")},disabled:rt===0,className:"hover:text-foreground disabled:opacity-30",children:e.jsx(zy,{className:"h-3.5 w-3.5"})}),e.jsx("button",{onClick:Ze=>{Ze.stopPropagation(),Je(rt,"down")},disabled:rt===be.length-1,className:"hover:text-foreground disabled:opacity-30",children:e.jsx(Xo,{className:"h-3.5 w-3.5"})})]})}),e.jsx(We,{variant:"outline",className:"shrink-0 font-mono text-xs",children:rt+1}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"font-medium text-sm truncate",children:st.title}),e.jsxs("div",{className:"flex items-center gap-2 text-xs text-muted-foreground mt-0.5",children:[st.video_url&&e.jsxs("span",{className:"flex items-center gap-0.5",children:[e.jsx(na,{className:"h-3 w-3"})," Video"]}),st.text_content&&e.jsxs("span",{className:"flex items-center gap-0.5",children:[e.jsx(Wr,{className:"h-3 w-3"})," Text"]}),st.duration_minutes&&e.jsxs("span",{children:[st.duration_minutes," min"]}),st.resources&&st.resources.length>0&&e.jsxs("span",{className:"flex items-center gap-0.5",children:[e.jsx(cd,{className:"h-3 w-3"})," ",st.resources.length," resource(s)"]})]})]}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(B,{size:"sm",variant:"ghost",onClick:Ze=>{var ht;Ze.stopPropagation(),f(st),_({title:st.title,description:st.description||"",video_url:st.video_url||"",text_content:st.text_content||"",duration_minutes:((ht=st.duration_minutes)==null?void 0:ht.toString())||""})},children:e.jsx(Ja,{className:"h-3.5 w-3.5"})}),e.jsx(B,{size:"sm",variant:"ghost",className:"text-destructive",onClick:Ze=>{Ze.stopPropagation(),Fe(st.id)},children:e.jsx(qn,{className:"h-3.5 w-3.5"})})]})]}),P.has(st.id)&&e.jsxs("div",{className:"border-t bg-muted/30 p-4 space-y-3",children:[st.description&&e.jsx("p",{className:"text-sm text-muted-foreground",children:st.description}),st.video_url&&e.jsxs("div",{className:"text-xs",children:[e.jsx("span",{className:"text-muted-foreground",children:"Video: "}),e.jsx("a",{href:st.video_url,target:"_blank",rel:"noreferrer",className:"text-primary hover:underline break-all",children:st.video_url})]}),st.text_content&&e.jsx("div",{className:"text-sm bg-background rounded-md p-3 border max-h-40 overflow-auto whitespace-pre-wrap",children:st.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:()=>{k(st.id),T({title:"",resource_type:"link",url:""})},children:[e.jsx(nn,{className:"h-3 w-3 mr-1"})," Add Resource"]})]}),st.resources&&st.resources.length>0?e.jsx("div",{className:"space-y-1",children:st.resources.map(Ze=>e.jsxs("div",{className:"flex items-center gap-2 text-sm bg-background rounded p-2 border",children:[e.jsx(We,{variant:"outline",className:"text-[10px]",children:Ze.resource_type}),e.jsx("span",{className:"flex-1 truncate",children:Ze.title}),Ze.url&&e.jsx("a",{href:Ze.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(Ze.id),children:e.jsx(hr,{className:"h-3 w-3"})})]},Ze.id))}):e.jsx("p",{className:"text-xs text-muted-foreground",children:"No resources yet"})]})]})]},st.id)),e.jsxs(B,{variant:"outline",className:"w-full border-dashed",onClick:()=>{y(!0),_({title:"",description:"",video_url:"",text_content:"",duration_minutes:""})},children:[e.jsx(nn,{className:"h-4 w-4 mr-2"})," Add Module"]})]}),e.jsx(_s,{value:"access",className:"mt-6 space-y-4",children:e.jsxs(_e,{children:[e.jsx(zt,{children:e.jsx(qt,{className:"text-base",children:"Who can access this course?"})}),e.jsxs(De,{className:"space-y-5",children:[e.jsxs("div",{className:Ot("flex items-center gap-3 p-4 rounded-xl border-2 cursor-pointer transition-all",Ie?"border-primary bg-primary/5":"border-muted hover:border-muted-foreground/30"),onClick:Xe,children:[e.jsx("div",{className:Ot("h-10 w-10 rounded-full flex items-center justify-center shrink-0",Ie?"bg-primary/15 text-primary":"bg-muted text-muted-foreground"),children:e.jsx(au,{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(zn,{checked:Ie,onCheckedChange:Xe})]}),!Ie&&e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-semibold",children:"Select Brokerages"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:Me.length===0?"No brokerages selected — agents won't see this course":`${Me.length} brokerage${Me.length!==1?"s":""} selected`})]}),Me.length>0&&e.jsx(B,{size:"sm",variant:"ghost",className:"text-xs text-muted-foreground",onClick:Ye,children:"Clear all"})]}),e.jsx(we,{placeholder:"Search brokerages...",value:me,onChange:st=>ue(st.target.value),className:"h-9"}),e.jsx("div",{className:"border rounded-lg divide-y max-h-[360px] overflow-auto",children:Re.length===0?e.jsx("div",{className:"p-4 text-center text-sm text-muted-foreground",children:"No brokerages found"}):Re.map(st=>{const rt=Me.includes(st.id);return e.jsxs("div",{className:Ot("flex items-center gap-3 px-3 py-2.5 cursor-pointer transition-colors",rt?"bg-primary/5":"hover:bg-muted/50"),onClick:()=>$e(st.id),children:[e.jsx("div",{className:Ot("h-5 w-5 rounded border-2 flex items-center justify-center shrink-0 transition-colors",rt?"bg-primary border-primary":"border-muted-foreground/30"),children:rt&&e.jsx("svg",{className:"h-3 w-3 text-primary-foreground",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",strokeWidth:3,children:e.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M5 13l4 4L19 7"})})}),e.jsx(Ti,{className:"h-4 w-4 text-muted-foreground shrink-0"}),e.jsx("span",{className:"text-sm flex-1 truncate",children:st.name}),rt&&e.jsx(We,{variant:"secondary",className:"text-[10px] shrink-0",children:"Active"})]},st.id)})})]})]})]})}),e.jsxs(_s,{value:"settings",className:"mt-6 space-y-4",children:[e.jsxs(_e,{children:[e.jsx(zt,{children:e.jsx(qt,{className:"text-base",children:"Course Thumbnail"})}),e.jsx(De,{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(()=>ie.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(hr,{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(Gv,{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:X,type:"file",accept:"image/*",className:"hidden",onChange:async st=>{var Ze;const rt=(Ze=st.target.files)==null?void 0:Ze[0];if(!(!rt||!n)){ne(!0);try{const ht=rt.name.split(".").pop(),Bt=`${n.id}/thumbnail.${ht}`,{error:Ct}=await H.storage.from("lms-thumbnails").upload(Bt,rt,{upsert:!0});if(Ct)throw Ct;const{data:Yt}=H.storage.from("lms-thumbnails").getPublicUrl(Bt),Kt=`${Yt.publicUrl}?t=${Date.now()}`;await a.mutateAsync({id:n.id,thumbnail_url:Kt}),ie.success("Thumbnail uploaded")}catch{ie.error("Failed to upload thumbnail")}finally{ne(!1),X.current&&(X.current.value="")}}}}),e.jsxs(B,{variant:"outline",size:"sm",disabled:te,onClick:()=>{var st;return(st=X.current)==null?void 0:st.click()},children:[te?e.jsx(us,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(ni,{className:"h-4 w-4 mr-2"}),te?"Uploading...":"Upload Thumbnail"]})]})]})})]}),e.jsxs(_e,{children:[e.jsx(zt,{children:e.jsx(qt,{className:"text-base",children:"Course Settings"})}),e.jsxs(De,{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(zn,{checked:n.is_sequential,onCheckedChange:st=>a.mutateAsync({id:n.id,is_sequential:st}).then(()=>ie.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(zn,{checked:n.is_published,onCheckedChange:st=>a.mutateAsync({id:n.id,is_published:st}).then(()=>ie.success("Updated"))})]})]})]})]})]})]}),e.jsx(Bs,{open:g||!!m,onOpenChange:st=>{st||(y(!1),f(null))},children:e.jsxs(Fs,{className:"max-w-lg",children:[e.jsxs(qs,{children:[e.jsx($s,{children:m?"Edit Module":"Add Module"}),e.jsx(Ar,{children:"Configure the module content"})]}),e.jsxs("div",{className:"space-y-4 max-h-[60vh] overflow-auto",children:[e.jsxs("div",{children:[e.jsx(re,{children:"Title"}),e.jsx(we,{value:x.title,onChange:st=>_(rt=>({...rt,title:st.target.value})),placeholder:"Module title"})]}),e.jsxs("div",{children:[e.jsx(re,{children:"Description"}),e.jsx(Ws,{value:x.description,onChange:st=>_(rt=>({...rt,description:st.target.value})),placeholder:"Brief description",rows:2})]}),e.jsxs("div",{children:[e.jsx(re,{children:"Video"}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:Ot("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 st;return(st=G.current)==null?void 0:st.click()},children:[e.jsx("input",{ref:G,type:"file",accept:"video/*",className:"hidden",onChange:st=>{var Ze;const rt=(Ze=st.target.files)==null?void 0:Ze[0];rt&&(L(rt),_(ht=>({...ht,video_url:""})))}}),M?e.jsxs("div",{className:"flex items-center justify-center gap-2 text-sm",children:[e.jsx(na,{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:st=>{st.stopPropagation(),L(null)},children:e.jsx(hr,{className:"h-3 w-3"})})]}):e.jsxs("div",{className:"flex flex-col items-center gap-1 text-muted-foreground",children:[e.jsx(ni,{className:"h-5 w-5"}),e.jsx("span",{className:"text-xs",children:"Click to upload a video file"})]})]}),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(us,{className:"h-3.5 w-3.5 animate-spin"}),e.jsxs("span",{children:["Uploading to Bunny.net... ",z,"%"]})]}),e.jsx(ro,{value:z,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(we,{value:x.video_url,onChange:st=>_(rt=>({...rt,video_url:st.target.value})),placeholder:"YouTube, Vimeo, or Bunny.net URL"})]})]})]}),e.jsxs("div",{children:[e.jsx(re,{children:"Text Content"}),e.jsx(Ws,{value:x.text_content,onChange:st=>_(rt=>({...rt,text_content:st.target.value})),placeholder:"Additional text content, instructions, notes...",rows:4})]}),e.jsxs("div",{children:[e.jsx(re,{children:"Duration (minutes)"}),e.jsx(we,{type:"number",value:x.duration_minutes,onChange:st=>_(rt=>({...rt,duration_minutes:st.target.value})),placeholder:"e.g. 15"})]})]}),e.jsxs(Cr,{children:[e.jsx(B,{variant:"outline",onClick:()=>{y(!1),f(null),L(null)},children:"Cancel"}),e.jsxs(B,{onClick:m?Ce:Ge,disabled:!x.title.trim()||V,children:[V?e.jsx(us,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(Kl,{className:"h-4 w-4 mr-2"}),V?"Uploading...":m?"Save Changes":"Add Module"]})]})]})}),e.jsx(Bs,{open:!!b,onOpenChange:st=>{st||k(null)},children:e.jsxs(Fs,{children:[e.jsxs(qs,{children:[e.jsx($s,{children:"Add Resource"}),e.jsx(Ar,{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(re,{children:"Title"}),e.jsx(we,{value:A.title,onChange:st=>T(rt=>({...rt,title:st.target.value})),placeholder:"Resource title"})]}),e.jsxs("div",{children:[e.jsx(re,{children:"Type"}),e.jsxs(Ns,{value:A.resource_type,onValueChange:st=>T(rt=>({...rt,resource_type:st})),children:[e.jsx(ws,{children:e.jsx(ks,{})}),e.jsxs(js,{children:[e.jsx(nt,{value:"link",children:"Link"}),e.jsx(nt,{value:"pdf",children:"PDF"}),e.jsx(nt,{value:"template",children:"Template"}),e.jsx(nt,{value:"worksheet",children:"Worksheet"})]})]})]}),e.jsxs("div",{children:[e.jsx(re,{children:"URL"}),e.jsx(we,{value:A.url,onChange:st=>T(rt=>({...rt,url:st.target.value})),placeholder:"https://..."})]})]}),e.jsxs(Cr,{children:[e.jsx(B,{variant:"outline",onClick:()=>k(null),children:"Cancel"}),e.jsx(B,{onClick:()=>b&&Ae(b),disabled:!A.title.trim(),children:"Add Resource"})]})]})}),e.jsx(Bs,{open:ve,onOpenChange:ge,children:e.jsxs(Fs,{children:[e.jsxs(qs,{children:[e.jsx($s,{children:"Edit Course"}),e.jsx(Ar,{children:"Update the course title and description"})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(re,{children:"Title"}),e.jsx(we,{value:ce,onChange:st=>ae(st.target.value)})]}),e.jsxs("div",{children:[e.jsx(re,{children:"Description"}),e.jsx(Ws,{value:he,onChange:st=>xe(st.target.value),rows:3})]})]}),e.jsxs(Cr,{children:[e.jsx(B,{variant:"outline",onClick:()=>ge(!1),children:"Cancel"}),e.jsx(B,{onClick:Ke,disabled:!ce.trim(),children:"Save"})]})]})})]})}function n4n(){return mt({queryKey:["lms-stats-overview"],queryFn:async()=>{const{data:s,error:t}=await H.rpc("get_lms_stats");if(t)throw t;return s}})}function r4n(){return mt({queryKey:["lms-stats-courses"],queryFn:async()=>{const{data:s,error:t}=await H.rpc("get_lms_course_stats");if(t)throw t;return s||[]}})}function a4n(s){return mt({queryKey:["lms-stats-agents",s],queryFn:async()=>{if(!s)return[];const{data:t,error:n}=await H.rpc("get_lms_agent_progress",{p_course_id:s});if(n)throw n;return t||[]},enabled:!!s})}function i4n(){const s=tr(),{data:t,isLoading:n}=n4n(),{data:r,isLoading:a}=r4n(),[i,l]=N.useState(null),{data:o,isLoading:c}=a4n(i),[d,u]=N.useState(""),h=r==null?void 0:r.find(g=>g.course_id===i),m=o==null?void 0:o.filter(g=>{var y,x;return!d||((y=g.agent_name)==null?void 0:y.toLowerCase().includes(d.toLowerCase()))||((x=g.email)==null?void 0:x.toLowerCase().includes(d.toLowerCase()))}),f=[{label:"Total Courses",value:(t==null?void 0:t.total_courses)??0,icon:Ep,color:"text-primary"},{label:"Published",value:(t==null?void 0:t.published_courses)??0,icon:Hr,color:"text-emerald-500"},{label:"Enrolled Agents",value:(t==null?void 0:t.total_enrollments)??0,icon:Yn,color:"text-blue-500"},{label:"Modules Completed",value:(t==null?void 0:t.total_completions)??0,icon:gl,color:"text-amber-500"},{label:"Active (30d)",value:(t==null?void 0:t.active_learners)??0,icon:ml,color:"text-violet-500"},{label:"Total Modules",value:(t==null?void 0:t.total_modules)??0,icon:fl,color:"text-rose-500"}];return e.jsx(Qs,{title:"LevelUp U - Stats",children:e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(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(Oh,{className:"h-7 w-7 text-primary"}),"LevelUp U — Analytics"]}),e.jsx("p",{className:"text-muted-foreground text-sm mt-0.5",children:"Track enrollment, progress, and completion across all courses"})]})]}),e.jsx("div",{className:"grid grid-cols-2 md:grid-cols-3 xl:grid-cols-6 gap-3",children:f.map(g=>e.jsx(_e,{className:Ot("transition-all",n&&"animate-pulse"),children:e.jsxs(De,{className:"p-4",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[e.jsx(g.icon,{className:Ot("h-4 w-4",g.color)}),e.jsx("span",{className:"text-xs font-medium text-muted-foreground",children:g.label})]}),e.jsx("p",{className:"text-2xl font-bold text-foreground",children:n?"—":g.value})]})},g.label))}),e.jsxs("div",{className:"grid grid-cols-1 xl:grid-cols-5 gap-6",children:[e.jsxs("div",{className:"xl:col-span-2 space-y-3",children:[e.jsxs("h2",{className:"text-lg font-semibold text-foreground flex items-center gap-2",children:[e.jsx(fl,{className:"h-5 w-5 text-primary"}),"Course Breakdown"]}),a?e.jsx("div",{className:"space-y-3",children:[1,2,3].map(g=>e.jsx(_e,{className:"animate-pulse",children:e.jsx(De,{className:"p-4",children:e.jsx("div",{className:"h-16 bg-muted rounded"})})},g))}):r!=null&&r.length?e.jsx("div",{className:"space-y-2",children:r.map(g=>{const y=i===g.course_id;return e.jsx(_e,{className:Ot("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:g.course_id),children:e.jsxs(De,{className:"p-4",children:[e.jsxs("div",{className:"flex items-start justify-between mb-3",children:[e.jsx("div",{className:"flex-1 min-w-0",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("p",{className:"font-semibold text-sm text-foreground truncate",children:g.course_title}),e.jsx(We,{variant:g.is_published?"default":"secondary",className:"shrink-0 text-[10px] px-1.5 py-0",children:g.is_published?"Live":"Draft"})]})}),e.jsx(Qa,{className:Ot("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:g.enrolled_agents}),e.jsx("p",{className:"text-[10px] text-muted-foreground uppercase tracking-wide",children:"Enrolled"})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-lg font-bold text-foreground",children:g.total_completions}),e.jsx("p",{className:"text-[10px] text-muted-foreground uppercase tracking-wide",children:"Completed"})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-lg font-bold text-foreground",children:g.total_modules}),e.jsx("p",{className:"text-[10px] text-muted-foreground uppercase tracking-wide",children:"Modules"})]})]}),e.jsxs("div",{className:"mt-3",children:[e.jsxs("div",{className:"flex items-center justify-between text-xs mb-1",children:[e.jsx("span",{className:"text-muted-foreground",children:"Avg. Completion"}),e.jsxs("span",{className:"font-semibold text-foreground",children:[g.avg_completion_pct,"%"]})]}),e.jsx(ro,{value:g.avg_completion_pct,className:"h-2"})]})]})},g.course_id)})}):e.jsx(_e,{className:"border-dashed",children:e.jsx(De,{className:"py-10 text-center",children:e.jsx("p",{className:"text-muted-foreground text-sm",children:"No courses created yet"})})})]}),e.jsxs("div",{className:"xl:col-span-3 space-y-3",children:[e.jsxs("h2",{className:"text-lg font-semibold text-foreground flex items-center gap-2",children:[e.jsx(tN,{className:"h-5 w-5 text-primary"}),h?`Agent Progress — ${h.course_title}`:"Agent Progress"]}),i?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"relative",children:[e.jsx(Gr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(we,{value:d,onChange:g=>u(g.target.value),placeholder:"Search agents...",className:"pl-9"})]}),c?e.jsx("div",{className:"space-y-2",children:[1,2,3,4].map(g=>e.jsx(_e,{className:"animate-pulse",children:e.jsx(De,{className:"p-4",children:e.jsx("div",{className:"h-12 bg-muted rounded"})})},g))}):m!=null&&m.length?e.jsx("div",{className:"space-y-2 max-h-[600px] overflow-y-auto pr-1",children:m.map((g,y)=>{const x=g.completion_pct>=100;return e.jsx(_e,{className:Ot("transition-all",x&&"border-emerald-200 bg-emerald-50/30 dark:border-emerald-900/40 dark:bg-emerald-950/10"),children:e.jsx(De,{className:"p-4",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:Ot("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(Ua,{className:"h-9 w-9 shrink-0",children:[e.jsx(Gi,{src:g.avatar_url||void 0}),e.jsx(qa,{className:"text-xs bg-primary/10 text-primary",children:(g.agent_name||g.email||"?").charAt(0).toUpperCase()})]}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("p",{className:"text-sm font-medium text-foreground truncate",children:g.agent_name||g.email}),x&&e.jsxs(We,{variant:"default",className:"text-[10px] px-1.5 py-0 bg-emerald-500 hover:bg-emerald-600 shrink-0",children:[e.jsx(Hr,{className:"h-3 w-3 mr-0.5"})," Complete"]})]}),e.jsxs("div",{className:"flex items-center gap-3 text-[11px] text-muted-foreground mt-0.5",children:[e.jsxs("span",{children:[g.modules_completed,"/",g.total_modules," modules"]}),g.last_activity&&e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Xr,{className:"h-3 w-3"}),Js(new Date(g.last_activity),"MMM d, yyyy")]})]})]}),e.jsxs("div",{className:"text-right shrink-0 w-20",children:[e.jsxs("p",{className:Ot("text-sm font-bold",x?"text-emerald-600 dark:text-emerald-400":"text-foreground"),children:[g.completion_pct,"%"]}),e.jsx(ro,{value:g.completion_pct,className:"h-1.5 mt-1"})]})]})})},g.user_id)})}):e.jsx(_e,{className:"border-dashed",children:e.jsx(De,{className:"py-10 text-center",children:e.jsx("p",{className:"text-muted-foreground text-sm",children:d?"No agents match your search":"No agents have started this course yet"})})})]}):e.jsx(_e,{className:"border-dashed",children:e.jsxs(De,{className:"py-16 text-center",children:[e.jsx(Yn,{className:"h-10 w-10 text-muted-foreground/40 mx-auto mb-3"}),e.jsx("p",{className:"text-muted-foreground text-sm",children:"Select a course to view agent progress"})]})})]})]})]})})}function o4n(){const{user:s}=Ls(),t=tr(),{data:n,isLoading:r}=QSn();return e.jsx(Qs,{title:"LevelUp U",children:e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"relative overflow-hidden rounded-2xl bg-gradient-to-br from-primary/10 via-primary/5 to-background border p-8",children:[e.jsx("div",{className:"relative z-10",children:e.jsxs("div",{className:"flex items-center gap-3 mb-2",children:[e.jsx("div",{className:"h-12 w-12 rounded-xl bg-primary/15 flex items-center justify-center",children:e.jsx(Oh,{className:"h-6 w-6 text-primary"})}),e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl font-bold text-foreground",children:"LevelUp U"}),e.jsx("p",{className:"text-muted-foreground text-sm",children:"Your training & development hub"})]})]})}),e.jsx("div",{className:"absolute top-0 right-0 w-64 h-64 bg-primary/5 rounded-full -translate-y-1/2 translate-x-1/2"})]}),r?e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4",children:[1,2,3].map(a=>e.jsx(_e,{className:"animate-pulse",children:e.jsxs(De,{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(l4n,{course:a,userId:s==null?void 0:s.id,onClick:()=>t(`/levelup-u/${a.id}`)},a.id))}):e.jsx(_e,{className:"border-dashed",children:e.jsxs(De,{className:"flex flex-col items-center justify-center py-16 text-center",children:[e.jsx(Ep,{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 l4n({course:s,userId:t,onClick:n}){var o;const r=((o=s.modules)==null?void 0:o.length)??0,{data:a}=M9t(s.id),i=(a==null?void 0:a.filter(c=>c.completed).length)??0,l=r>0?Math.round(i/r*100):0;return e.jsxs(_e,{className:"group cursor-pointer hover:shadow-lg transition-all hover:border-primary/50 overflow-hidden",onClick:n,children:[s.thumbnail_url?e.jsx("div",{className:"aspect-video bg-muted overflow-hidden",children:e.jsx("img",{src:s.thumbnail_url,alt:s.title,className:"w-full h-full object-cover group-hover:scale-105 transition-transform duration-300"})}):e.jsx("div",{className:"aspect-video bg-gradient-to-br from-primary/15 via-primary/5 to-muted flex items-center justify-center",children:e.jsx(Oh,{className:"h-10 w-10 text-primary/40"})}),e.jsxs(De,{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(Ep,{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(dj,{className:"h-3.5 w-3.5"}):e.jsx(ND,{className:"h-3.5 w-3.5"}),s.is_sequential?"In order":"Any order"]})]}),r>0&&e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs("div",{className:"flex items-center justify-between text-xs",children:[e.jsxs("span",{className:"text-muted-foreground",children:[i," of ",r," completed"]}),e.jsxs("span",{className:"font-medium text-foreground",children:[l,"%"]})]}),e.jsx(ro,{value:l,className:"h-1.5"})]}),e.jsx("div",{className:"flex items-center justify-end",children:e.jsxs("span",{className:"text-xs text-primary font-medium flex items-center gap-1 opacity-0 group-hover:opacity-100 transition-opacity",children:[l===100?"Review":l>0?"Continue":"Start"," Course",e.jsx(Qa,{className:"h-3.5 w-3.5"})]})})]})]})}function c4n(){const{courseId:s}=uo(),t=tr(),{user:n}=Ls(),{data:r,isLoading:a}=JSn(s),{data:i}=M9t(s),l=e4n(),[o,c]=N.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;N.useEffect(()=>{if(d.length>0&&!o){const b=d.find(k=>!u.has(k.id));c((b==null?void 0:b.id)||d[0].id)}},[d,o,u]);const f=d.find(b=>b.id===o),g=d.findIndex(b=>b.id===o),y=(b,k)=>{if(!(r!=null&&r.is_sequential)||k===0)return!1;for(let A=0;A{if(!(!f||!n||!s))try{await l.mutateAsync({courseId:s,moduleId:f.id,userId:n.id}),ie.success("Module completed! 🎉"),g{const k=b.match(/(?:youtube\.com\/(?:watch\?v=|embed\/)|youtu\.be\/)([a-zA-Z0-9_-]{11})/);if(k)return`https://www.youtube.com/embed/${k[1]}`;const A=b.match(/vimeo\.com\/(\d+)/);if(A)return`https://player.vimeo.com/video/${A[1]}`;const T=b.match(/(?:iframe\.mediadelivery\.net|video\.bunnycdn\.com)\/(?:play|embed)\/(\d+)\/([a-f0-9-]+)/);return T?`https://iframe.mediadelivery.net/embed/${T[1]}/${T[2]}?responsive=true`:b};return a?e.jsx(Qs,{title:"Loading...",children:e.jsx("div",{className:"flex items-center justify-center py-20",children:e.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})})}):r?e.jsx(Qs,{title:r.title,children:e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(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(ro,{value:m,className:"h-2"})})]}),e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-[320px_1fr] gap-4 items-start",children:[e.jsx(_e,{className:"lg:sticky lg:top-4",children:e.jsxs(De,{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(lo,{className:"max-h-[calc(100vh-280px)]",children:e.jsx("div",{className:"p-1",children:d.map((b,k)=>{const A=y(b,k),T=u.has(b.id),P=b.id===o;return e.jsxs("button",{disabled:A,onClick:()=>!A&&c(b.id),className:Ot("w-full flex items-center gap-3 p-3 rounded-lg text-left transition-all text-sm",P?"bg-primary/10 text-primary":"hover:bg-muted/50",A&&"opacity-50 cursor-not-allowed"),children:[e.jsx("div",{className:"shrink-0",children:A?e.jsx(Au,{className:"h-4 w-4 text-muted-foreground"}):T?e.jsx(Hr,{className:"h-4 w-4 text-green-500"}):e.jsx(bg,{className:"h-4 w-4 text-muted-foreground"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("p",{className:Ot("font-medium truncate",P&&"text-primary"),children:[k+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(Xr,{className:"h-3 w-3"})," ",b.duration_minutes," min"]})]})]},b.id)})})})]})}),e.jsx("div",{className:"space-y-4",children:f?e.jsxs(e.Fragment,{children:[f.video_url&&e.jsx(_e,{className:"overflow-hidden",children:e.jsx("div",{className:"aspect-video bg-black",children:e.jsx("iframe",{src:_(f.video_url),className:"w-full h-full",allow:"accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture",allowFullScreen:!0})})}),e.jsx(_e,{children:e.jsxs(De,{className:"p-6 space-y-4",children:[e.jsxs("div",{className:"flex items-start justify-between gap-4",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"text-lg font-semibold",children:f.title}),f.description&&e.jsx("p",{className:"text-muted-foreground mt-1",children:f.description})]}),u.has(f.id)?e.jsxs(We,{className:"bg-green-500/15 text-green-600 border-green-500/30 shrink-0",children:[e.jsx(Hr,{className:"h-3.5 w-3.5 mr-1"})," Completed"]}):e.jsxs(B,{size:"sm",onClick:x,disabled:l.isPending,children:[e.jsx(Hr,{className:"h-4 w-4 mr-1"}),"Mark Complete"]})]}),f.text_content&&e.jsx("div",{className:"prose prose-sm max-w-none text-foreground border-t pt-4 whitespace-pre-wrap",children:f.text_content}),f.resources&&f.resources.length>0&&e.jsxs("div",{className:"border-t pt-4",children:[e.jsx("p",{className:"text-sm font-medium mb-2",children:"Resources"}),e.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-2",children:f.resources.map(b=>e.jsxs("a",{href:b.url||b.file_url||"#",target:"_blank",rel:"noreferrer",className:"flex items-center gap-2 p-3 rounded-lg border hover:bg-muted/50 transition-colors text-sm",children:[b.resource_type==="pdf"?e.jsx(Wr,{className:"h-4 w-4 text-red-500 shrink-0"}):b.resource_type==="template"?e.jsx(Oh,{className:"h-4 w-4 text-purple-500 shrink-0"}):e.jsx(cd,{className:"h-4 w-4 text-blue-500 shrink-0"}),e.jsx("span",{className:"flex-1 truncate",children:b.title}),e.jsx(Tr,{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:g===0,onClick:()=>g>0&&c(d[g-1].id),children:[e.jsx(ka,{className:"h-3.5 w-3.5 mr-1"})," Previous"]}),gc(d[g+1].id),children:["Next ",e.jsx(Qa,{className:"h-3.5 w-3.5 ml-1"})]}):m===100&&e.jsx(We,{className:"bg-green-500/15 text-green-600 border-green-500/30 text-sm px-3 py-1.5",children:"🎉 Course Complete!"})]})]})})]}):e.jsx(_e,{children:e.jsx(De,{className:"flex items-center justify-center py-16 text-muted-foreground",children:"Select a module to begin"})})})]})]})}):e.jsx(Qs,{title:"Not Found",children:e.jsxs("div",{className:"text-center py-20",children:[e.jsx("p",{className:"text-muted-foreground",children:"Course not found"}),e.jsxs(B,{variant:"outline",className:"mt-4",onClick:()=>t("/levelup-u"),children:[e.jsx(ka,{className:"h-4 w-4 mr-2"})," Back"]})]})})}function d4n({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(vi,{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 H_({children:s,className:t="",delay:n=0,direction:r="up"}){const a=N.useRef(null),i=Cvs(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 u4n({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(H_,{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(H_,{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 h4n({images:s,primaryColor:t,accentColor:n}){const[r,a]=N.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(H_,{children:e.jsxs("div",{className:"text-center mb-16",children:[e.jsxs("div",{className:"inline-flex items-center gap-2 px-4 py-2 rounded-full bg-white border border-gray-200 mb-6",children:[e.jsx(Yn,{className:"h-4 w-4",style:{color:t}}),e.jsx("span",{className:"text-sm font-medium text-gray-600",children:"Life at Our Brokerage"})]}),e.jsx("h2",{className:"text-3xl md:text-5xl font-bold tracking-tight",style:{color:n},children:"Our Team & Culture"})]})}),e.jsx("div",{className:"grid grid-cols-2 md:grid-cols-3 gap-3 md:gap-4",children:s.map((i,l)=>e.jsx(H_,{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(hr,{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 m4n({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(H_,{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(H_,{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(Q2,{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 p4n({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(H_,{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(H_,{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(re,{className:"text-gray-700 text-sm font-medium",children:"First Name *"}),e.jsx(we,{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(re,{className:"text-gray-700 text-sm font-medium",children:"Last Name"}),e.jsx(we,{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(re,{className:"text-gray-700 text-sm font-medium",children:"Email *"}),e.jsx(we,{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(re,{className:"text-gray-700 text-sm font-medium",children:"Phone"}),e.jsx(we,{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(re,{className:"text-gray-700 text-sm font-medium",children:"Current Brokerage"}),e.jsx(we,{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(re,{className:"text-gray-700 text-sm font-medium",children:"License #"}),e.jsx(we,{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(re,{className:"text-gray-700 text-sm font-medium",children:"Years Experience"}),e.jsx(we,{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(re,{className:"text-gray-700 text-sm font-medium",children:"Annual Production"}),e.jsx(we,{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(re,{className:"text-gray-700 text-sm font-medium",children:"Why are you interested?"}),e.jsx(Ws,{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(vi,{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(mf,{className:"h-3.5 w-3.5"}),e.jsx("span",{children:"Your information is confidential and will not be shared."})]})]})})]})]})}function f4n({form:s,setForm:t,onSubmit:n,isPending:r,primaryColor:a,accentColor:i,showConfidentialBadges:l=!0}){const[o,c]=N.useState(1),[d,u]=N.useState(""),h=3,m=!!s.first_name&&!!s.email,f=g=>{u(g),t(y=>({...y,why_interested:g})),setTimeout(()=>c(2),200)};return e.jsxs("section",{id:"apply",className:"py-24 md:py-32 px-6 relative overflow-hidden",children:[e.jsx("div",{className:"absolute inset-0 top-0 h-1/2",style:{background:`linear-gradient(160deg, ${i}, ${a})`}}),e.jsx("div",{className:"absolute inset-0 top-1/2 bg-gray-50"}),e.jsxs("div",{className:"relative z-10 max-w-xl mx-auto",children:[e.jsx(H_,{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(Au,{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(H_,{delay:.15,children:e.jsxs("div",{className:"bg-white rounded-3xl shadow-2xl p-8 md:p-10",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-7",children:[[1,2,3].map(g=>e.jsx("div",{className:"h-1 flex-1 rounded-full transition-colors duration-500",style:{backgroundColor:g<=o?a:"#e5e7eb"}},g)),e.jsxs("span",{className:"text-xs text-gray-400 ml-2",children:[o,"/",h]})]}),e.jsxs($4e,{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(g=>e.jsxs("button",{type:"button",onClick:()=>f(g.val),className:"w-full flex items-center gap-3 p-4 rounded-xl border-2 border-gray-100 hover:border-gray-300 transition-all text-left group",children:[e.jsx("span",{className:"text-2xl",children:g.icon}),e.jsx("span",{className:"font-medium text-gray-700 group-hover:text-gray-900 flex-1",children:g.label}),e.jsx(vi,{className:"h-4 w-4 text-gray-300 group-hover:text-gray-500 group-hover:translate-x-1 transition-all"})]},g.val))]},"step1"),o===2&&e.jsxs(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(re,{className:"text-gray-700 text-sm font-medium",children:"First Name *"}),e.jsx(we,{required:!0,value:s.first_name,onChange:g=>t(y=>({...y,first_name:g.target.value})),className:"h-11",placeholder:"John"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(re,{className:"text-gray-700 text-sm font-medium",children:"Last Name"}),e.jsx(we,{value:s.last_name,onChange:g=>t(y=>({...y,last_name:g.target.value})),className:"h-11",placeholder:"Smith"})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(re,{className:"text-gray-700 text-sm font-medium",children:"Email *"}),e.jsx(we,{type:"email",required:!0,value:s.email,onChange:g=>t(y=>({...y,email:g.target.value})),className:"h-11",placeholder:"john@email.com"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(re,{className:"text-gray-700 text-sm font-medium",children:"Phone (preferred)"}),e.jsx(we,{value:s.phone,onChange:g=>t(y=>({...y,phone:g.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(vi,{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(re,{className:"text-gray-700 text-sm font-medium",children:"Current Brokerage"}),e.jsx(we,{value:s.current_brokerage,onChange:g=>t(y=>({...y,current_brokerage:g.target.value})),className:"h-11",placeholder:"(stays private)"})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(re,{className:"text-gray-700 text-sm font-medium",children:"Years Experience"}),e.jsx(we,{type:"number",min:"0",value:s.experience_years,onChange:g=>t(y=>({...y,experience_years:g.target.value})),className:"h-11"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(re,{className:"text-gray-700 text-sm font-medium",children:"Annual Production"}),e.jsx(we,{value:s.annual_production,onChange:g=>t(y=>({...y,annual_production:g.target.value})),className:"h-11",placeholder:"e.g. $5M"})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(re,{className:"text-gray-700 text-sm font-medium",children:"Anything else?"}),e.jsx(Ws,{value:s.why_interested,onChange:g=>t(y=>({...y,why_interested:g.target.value})),rows:2,className:"resize-none",placeholder:"Optional message..."})]}),e.jsxs("div",{className:"flex gap-2 pt-2",children:[e.jsxs(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(pa,{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(mf,{className:"h-3 w-3"})," Confidential"]}),e.jsxs("div",{className:"flex items-center gap-1 justify-center",children:[e.jsx(xo,{className:"h-3 w-3"})," Text first"]}),e.jsxs("div",{className:"flex items-center gap-1 justify-center",children:[e.jsx(ga,{className:"h-3 w-3"})," No spam"]})]})]})})]})]})}function g4n({config:s,primaryColor:t,accentColor:n,brokerageId:r,brokerageName:a}){const{toast:i}=Ci(),[l,o]=N.useState("250000"),[c,d]=N.useState("12"),[u,h]=N.useState("70"),[m,f]=N.useState("150"),[g,y]=N.useState(""),[x,_]=N.useState(!1),[b,k]=N.useState(!1),A=s.commission_split_pct??80,T=s.cap_amount??16e3,P=s.post_cap_split_pct??100,I=s.monthly_fee??99,M=s.transaction_fee??0,L=N.useMemo(()=>{const V=parseFloat(l)||0,W=Math.max(0,parseInt(c,10)||0),G=parseFloat(u)||0,X=parseFloat(m)||0,te=V*(G/100)-X*12-M*W,ne=1-A/100,me=ne>0?T/ne:V,ue=Math.min(V,me),ce=Math.max(0,V-me),ae=ue*ne+ce*(1-P/100),he=V-ae-I*12-M*W,xe=he-te;return{currentNet:te,newNet:he,diff:xe}},[l,c,u,m,A,T,P,I,M]),z=V=>new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:0}).format(V),$=async V=>{if(V.preventDefault(),!!g){k(!0);try{const{error:W}=await H.from("recruit_lead_magnet_downloads").insert({brokerage_id:r,email:g,source:"calculator"});if(W)throw W;const{error:G}=await H.functions.invoke("send-calculator-breakdown",{body:{brokerage_id:r,brokerage_name:a,email:g,inputs:{gci:parseFloat(l)||0,transactions:parseInt(c,10)||0,current_split_pct:parseFloat(u)||0,current_monthly_fee:parseFloat(m)||0},plan:{commission_split_pct:A,cap_amount:T,post_cap_split_pct:P,monthly_fee:I,transaction_fee:M},result:L,primary_color:t,accent_color:n}});G&&console.error("Breakdown email failed:",G),_(!0),i({title:"Sent!",description:"Check your email for the full breakdown."})}catch(W){i({title:"Error",description:W.message,variant:"destructive"})}finally{k(!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(H_,{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(Au,{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(H_,{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(u5,{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(re,{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(we,{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(re,{className:"text-gray-600 text-sm",children:"Transactions per Year"}),e.jsx(we,{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(re,{className:"text-gray-600 text-sm",children:"Your Current Commission Split (%)"}),e.jsx(we,{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(re,{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(we,{type:"number",value:m,onChange:V=>f(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(ml,{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:z(L.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:z(L.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:L.diff>=0?"You could earn":"Difference"}),e.jsxs("p",{className:"text-4xl font-bold mb-1",children:[L.diff>=0?"+":"",z(L.diff)]}),e.jsx("p",{className:"text-white/70 text-xs",children:L.diff>=0?"more per year":"per year"})]},L.diff),s.show_email_capture&&!x&&e.jsxs("form",{onSubmit:$,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(we,{type:"email",required:!0,value:g,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"})]})]}),x&&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(pa,{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 x4n({config:s,primaryColor:t,accentColor:n,brokerageId:r}){const{toast:a}=Ci(),[i,l]=N.useState(""),[o,c]=N.useState(""),[d,u]=N.useState(!1),[h,m]=N.useState(!1),f=async g=>{g.preventDefault(),m(!0);try{const{error:y}=await H.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(H_,{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(uD,{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(Au,{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(pa,{className:"h-5 w-5 shrink-0"}),e.jsxs("span",{children:["Sent! ",s.pdf_url?"Your download should open in a new tab.":"Check your email shortly."]})]}):e.jsxs("form",{onSubmit:f,className:"space-y-3",children:[e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-3",children:[e.jsx(we,{value:o,onChange:g=>c(g.target.value),placeholder:"First name (optional)",className:"h-11"}),e.jsx(we,{type:"email",required:!0,value:i,onChange:g=>l(g.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(uD,{className:"h-4 w-4 mr-2"}),h?"Sending...":s.button_text||"Email Me the PDF"]})]})]})]})})})})})}function y4n(){const{slug:s}=uo(),{toast:t}=Ci(),[n,r]=N.useState(!1),[a,i]=N.useState({first_name:"",last_name:"",email:"",phone:"",current_brokerage:"",experience_years:"",annual_production:"",license_number:"",why_interested:""});N.useEffect(()=>{document.body.classList.add("recruit-landing-page");const L=()=>{['[id*="lc_text_widget"]','[class*="lc-text-widget"]','[class*="lc_text_widget"]','[id*="chat-widget"]','[class*="chat-widget"]','iframe[src*="leadconnector"]','iframe[src*="msgsndr"]',"[data-chat-widget]",'div[id^="hubspot"]',".widget-visible"].forEach(W=>document.querySelectorAll(W).forEach(G=>G.style.display="none"))};L();const z=[setTimeout(L,500),setTimeout(L,1500),setTimeout(L,3e3)],$=new MutationObserver(L);return $.observe(document.body,{childList:!0,subtree:!0}),()=>{document.body.classList.remove("recruit-landing-page"),z.forEach(clearTimeout),$.disconnect()}},[]);const{data:l,isLoading:o,error:c}=mt({queryKey:["recruit-form-brokerage",s],queryFn:async()=>{const{data:L,error:z}=await H.from("brokerages").select("id, name, recruit_form_enabled").eq("recruit_form_slug",s).single();if(z)throw z;return L},enabled:!!s}),{data:d}=mt({queryKey:["recruit-landing-public",l==null?void 0:l.id],queryFn:async()=>{const{data:L,error:z}=await H.from("recruit_landing_page_settings").select("*").eq("brokerage_id",l.id).single();if(z&&z.code!=="PGRST116")throw z;return L},enabled:!!(l!=null&&l.id)}),u=_t({mutationFn:async()=>{const L={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:z}=await H.from("recruit_interest_submissions").insert(L);if(z)throw z;H.functions.invoke("recruit-lead-notify",{body:{lead:L,brokerage_id:l.id}}).catch($=>console.error("Lead notification error:",$))},onSuccess:()=>r(!0),onError:L=>t({title:"Error",description:L.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(Ti,{className:"h-10 w-10 mx-auto text-gray-300 mb-4"}),e.jsx("p",{className:"text-gray-400 text-lg",children:"This page is not available."})]})});const h=d,m=(h==null?void 0:h.primary_color)||"#406E71",f=(h==null?void 0:h.accent_color)||"#2a4c64",g=(h==null?void 0:h.benefits)||[],y=(h==null?void 0:h.testimonials)||[],x=(h==null?void 0:h.gallery_images)||[],_=(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.",k=(h==null?void 0:h.calculator_enabled)===!0,A=(h==null?void 0:h.calculator_config)||{},T=(h==null?void 0:h.lead_magnet_enabled)===!0,P=(h==null?void 0:h.lead_magnet_config)||{},I=(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}, ${f})`},children:e.jsx(pa,{className:"h-10 w-10 text-white"})}),e.jsx("h2",{className:"text-3xl font-bold mb-3 tracking-tight",style:{color:f},children:"Thank You!"}),e.jsxs("p",{className:"text-gray-500 text-lg leading-relaxed mb-8",children:["Your interest in joining ",e.jsx("span",{className:"font-semibold",style:{color:f},children:l.name})," has been received. A member of our recruitment team will be in touch shortly."]}),e.jsx("div",{className:"w-16 h-1 mx-auto rounded-full",style:{backgroundColor:m}})]})}):e.jsxs("div",{className:"min-h-screen bg-white",style:{"--recruit-primary":m,"--recruit-accent":f},children:[e.jsx("nav",{className:"fixed top-0 left-0 right-0 z-40 bg-white/80 backdrop-blur-lg border-b border-gray-100/50",children:e.jsxs("div",{className:"max-w-6xl mx-auto px-6 h-14 flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[(h==null?void 0:h.logo_url)&&e.jsx("img",{src:h.logo_url,alt:l.name,className:"h-8 w-auto"}),e.jsx("span",{className:"font-semibold text-sm tracking-tight",style:{color:f},children:l.name})]}),e.jsxs("a",{href:"#apply",className:"inline-flex items-center gap-2 px-5 py-2 rounded-full text-sm font-semibold text-white transition-all duration-300 hover:shadow-md hover:scale-105",style:{background:`linear-gradient(135deg, ${m}, ${f})`},children:["Apply Now ",e.jsx(vi,{className:"h-3.5 w-3.5"})]})]})}),e.jsx(d4n,{headline:_,subtext:b,primaryColor:m,accentColor:f,heroImageUrl:h==null?void 0:h.hero_image_url,logoUrl:h==null?void 0:h.logo_url,brokerageName:l.name}),e.jsx(u4n,{benefits:g,accentColor:f,primaryColor:m}),e.jsx(h4n,{images:x,primaryColor:m,accentColor:f}),e.jsx(m4n,{testimonials:y,primaryColor:m,accentColor:f}),k&&e.jsx(g4n,{config:A,primaryColor:m,accentColor:f,brokerageId:l.id,brokerageName:l.name}),T&&e.jsx(x4n,{config:P,primaryColor:m,accentColor:f,brokerageId:l.id}),I==="multi_step"?e.jsx(f4n,{form:a,setForm:i,onSubmit:()=>u.mutate(),isPending:u.isPending,primaryColor:m,accentColor:f,showConfidentialBadges:M}):e.jsx(p4n,{form:a,setForm:i,onSubmit:()=>u.mutate(),isPending:u.isPending,primaryColor:m,accentColor:f}),e.jsx("footer",{className:"py-10 text-center bg-white border-t border-gray-100",children:e.jsxs("p",{className:"text-sm text-gray-400",children:["© ",new Date().getFullYear()," ",l.name,". All rights reserved."]})})]})}function v4n(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 b4n(){var m,f,g,y;const{shareToken:s}=uo(),t=N.useRef(!1),{data:n,isLoading:r,error:a}=mt({queryKey:["public-recruit-video",s],queryFn:async()=>{var T;if(!s)throw new Error("No token");const{data:x,error:_}=await H.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(_)throw _;const{data:b}=await H.from("profiles").select("name, avatar_url, title, recruit_cta_url").eq("id",(T=x.video)==null?void 0:T.owner_user_id).single(),{data:k}=await H.from("brokerages").select("name").eq("id",x.brokerage_id).single(),{data:A}=await H.from("recruit_landing_page_settings").select("logo_url, primary_color, accent_color, hero_headline").eq("brokerage_id",x.brokerage_id).maybeSingle();return{rv:x,profile:b,brokerage:k,settings:A}},enabled:!!s});if(N.useEffect(()=>{var x;!((x=n==null?void 0:n.rv)!=null&&x.id)||t.current||(t.current=!0,H.rpc("log_recruit_video_view",{p_recruit_video_id:n.rv.id,p_user_agent:navigator.userAgent,p_referrer:document.referrer||null}).then(()=>{}))},[(m=n==null?void 0:n.rv)==null?void 0:m.id]),r)return e.jsx("div",{className:"min-h-screen flex items-center justify-center bg-background",children:e.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})});if(a||!n)return e.jsx("div",{className:"min-h-screen flex items-center justify-center bg-background",children:e.jsx("p",{className:"text-muted-foreground",children:"This video is no longer available."})});const{rv:i,profile:l,brokerage:o,settings:c}=n,d=(c==null?void 0:c.primary_color)||"#3b82f6",u=((f=i.prospect)==null?void 0:f.first_name)||"there",h=(g=i.video)!=null&&g.playback_url?v4n(i.video.playback_url):null;return e.jsxs(e.Fragment,{children:[e.jsx(ic,{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:()=>{H.from("recruit_videos").update({cta_clicked_at:new Date().toISOString()}).eq("id",i.id).then(()=>{})},children:e.jsxs("a",{href:l.recruit_cta_url,target:"_blank",rel:"noopener noreferrer",children:[e.jsx(ta,{className:"h-5 w-5 mr-2"})," Schedule a Conversation"]})})})]}),e.jsx("footer",{className:"text-center py-6 text-xs text-muted-foreground",children:"Powered by LevelUp"})]})]})}const _4n="relzejiswnotikjgvjhz",cgt=`https://${_4n}.supabase.co/functions/v1/recruit-unsubscribe`;function w4n(){const[s]=$c(),t=s.get("token")||"",[n,r]=N.useState(!0),[a,i]=N.useState(!1),[l,o]=N.useState(!1),[c,d]=N.useState(""),[u,h]=N.useState({});N.useEffect(()=>{document.body.classList.add("recruit-unsubscribe-page");const f=()=>{['[id*="lc_text_widget"]','[class*="lc-text-widget"]','[class*="lc_text_widget"]','[id*="chat-widget"]','[class*="chat-widget"]','iframe[src*="leadconnector"]','iframe[src*="msgsndr"]',"[data-chat-widget]",'div[id^="hubspot"]',".widget-visible"].forEach(_=>document.querySelectorAll(_).forEach(b=>b.style.display="none"))};f();const g=[setTimeout(f,500),setTimeout(f,1500),setTimeout(f,3e3)],y=new MutationObserver(f);return y.observe(document.body,{childList:!0,subtree:!0}),()=>{document.body.classList.remove("recruit-unsubscribe-page"),g.forEach(clearTimeout),y.disconnect()}},[]),N.useEffect(()=>{if(!t){h({error:"Missing unsubscribe token in link."}),r(!1);return}fetch(`${cgt}?token=${encodeURIComponent(t)}`).then(async f=>{const g=await f.json();if(!f.ok)throw new Error(g.error||"Lookup failed");h(g),g.already_unsubscribed&&o(!0)}).catch(f=>h({error:f.message||"Could not load status"})).finally(()=>r(!1))},[t]);const m=async()=>{i(!0);try{const f=await fetch(cgt,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({token:t,reason:c.trim()||null})}),g=await f.json();if(!f.ok)throw new Error(g.error||"Failed");o(!0)}catch(f){h({...u,error:f.message||"Could not unsubscribe"})}finally{i(!1)}};return e.jsx("div",{className:"min-h-screen bg-gradient-to-br from-slate-50 via-white to-slate-100 flex items-center justify-center p-6",children:e.jsx("div",{className:"w-full max-w-lg bg-white rounded-2xl shadow-xl border border-slate-200 p-8 sm:p-10",children:n?e.jsxs("div",{className:"flex flex-col items-center justify-center py-12 gap-3 text-slate-500",children:[e.jsx(us,{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(Uo,{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(Hr,{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(Wv,{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(Wv,{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(re,{htmlFor:"reason",className:"text-xs text-slate-500",children:"Optional — what's the main reason? (helps us improve)"}),e.jsx(Ws,{id:"reason",value:c,onChange:f=>d(f.target.value),placeholder:"e.g. Not currently looking, too many emails, already moved…",rows:3,className:"resize-none"})]}),e.jsx(B,{onClick:m,disabled:a,className:"w-full h-11",variant:"default",children:a?e.jsxs(e.Fragment,{children:[e.jsx(us,{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 j4n="relzejiswnotikjgvjhz",dgt=`https://${j4n}.supabase.co/functions/v1/event-invite-unsubscribe`;function N4n(){const[s]=$c(),t=s.get("token")||"",[n,r]=N.useState(!0),[a,i]=N.useState(!1),[l,o]=N.useState(!1),[c,d]=N.useState({});N.useEffect(()=>(document.body.classList.add("event-invite-unsubscribe-page"),()=>{document.body.classList.remove("event-invite-unsubscribe-page")}),[]),N.useEffect(()=>{if(!t){d({error:"Missing unsubscribe token in link."}),r(!1);return}fetch(`${dgt}?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(dgt,{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(us,{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(Uo,{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(Hr,{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(Wv,{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(UG,{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(us,{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 k4n(){const s=tr(),t=as(),{isAdmin:n}=Ls(),[r,a]=N.useState(!1),[i,l]=N.useState(null),[o,c]=N.useState(null),{data:d,isLoading:u}=mt({queryKey:["my-social-accounts"],queryFn:async()=>{const{data:{user:T},error:P}=await H.auth.getUser();if(P)throw P;if(!T)return[];const{data:I,error:M}=await H.from("social_accounts").select("*").eq("user_id",T.id).order("created_at",{ascending:!1});if(M)throw M;return I}}),h=_t({mutationFn:async T=>{const{data:{user:P},error:I}=await H.auth.getUser();if(I)throw I;if(!P)throw new Error("Not authenticated");const{error:M}=await H.from("social_accounts").delete().eq("id",T).eq("user_id",P.id);if(M)throw M},onSuccess:()=>{t.invalidateQueries({queryKey:["my-social-accounts"]}),t.invalidateQueries({queryKey:["social-accounts-for-post"]}),ie.success("Account disconnected successfully")},onError:()=>{ie.error("Failed to disconnect account")}}),m=async T=>{a(!0),sessionStorage.setItem("social-connect-return-to",window.location.pathname);try{const{data:P,error:I}=await H.functions.invoke("meta-oauth",{body:{action:"get_auth_url",callbackPath:"/social-connections/callback",authMode:T}});if(I)throw I;if(P!=null&&P.authUrl)window.location.href=P.authUrl;else throw new Error("Failed to get authorization URL")}catch(P){console.error("Meta OAuth error:",P),ie.error("Failed to start connection. Please try again."),a(!1)}},f=async()=>{a(!0);try{const{data:T,error:P}=await H.functions.invoke("linkedin-oauth",{body:{action:"get_auth_url",callbackPath:"/social-connections/linkedin-callback"}});if(P)throw P;if(T!=null&&T.authUrl)window.location.href=T.authUrl;else throw new Error("Failed to get LinkedIn authorization URL")}catch(T){console.error("LinkedIn OAuth error:",T),ie.error("Failed to start LinkedIn connection. Please try again."),a(!1)}},g=async()=>{a(!0);try{const{data:T,error:P}=await H.functions.invoke("google-business-oauth",{body:{action:"get_auth_url"}});if(P)throw P;if(T!=null&&T.authUrl)window.location.href=T.authUrl;else throw new Error("Failed to get Google authorization URL")}catch(T){console.error("Google OAuth error:",T),ie.error("Failed to start Google connection. Please try again."),a(!1)}},y=(d==null?void 0:d.filter(T=>T.platform==="facebook"))||[],x=(d==null?void 0:d.filter(T=>T.platform==="instagram"))||[],_=(d==null?void 0:d.filter(T=>T.platform==="linkedin"))||[],b=(d==null?void 0:d.filter(T=>T.platform==="google_business"))||[],k=((d==null?void 0:d.length)||0)>0,A=async(T,P)=>{l(T),c(null);try{const{data:I,error:M}=await H.functions.invoke("meta-api-test",{body:{testType:"all",accountId:T}});if(M)throw M;c(I.results||[]),ie.success(I.summary||"API tests completed")}catch(I){console.error("Meta API test error:",I),ie.error("Failed to run API tests")}finally{l(null)}};return e.jsx(Qs,{title:"Social Connections",children:e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"relative overflow-hidden rounded-2xl bg-gradient-to-br from-pink-500 via-purple-500 to-blue-500 p-6 md:p-8 text-white",children:[e.jsx("div",{className:"absolute inset-0 bg-[url('data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iNjAiIGhlaWdodD0iNjAiIHZpZXdCb3g9IjAgMCA2MCA2MCIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj48ZyBmaWxsPSJub25lIiBmaWxsLXJ1bGU9ImV2ZW5vZGQiPjxnIGZpbGw9IiNmZmYiIGZpbGwtb3BhY2l0eT0iMC4xIj48cGF0aCBkPSJNMzYgMzRjMC0yIDItNCAyLTRzMiAyIDIgNC0yIDQtMiA0LTItMi0yLTR6Ii8+PC9nPjwvZz48L3N2Zz4=')] opacity-30"}),e.jsxs("div",{className:"relative",children:[e.jsx("div",{className:"flex items-center gap-2 mb-3",children:e.jsxs(We,{variant:"secondary",className:"bg-white/20 text-white border-0 backdrop-blur-sm",children:[e.jsx(Cn,{className:"h-3 w-3 mr-1"}),"Post directly from Social Swag"]})}),e.jsx("h1",{className:"text-2xl md:text-3xl font-bold mb-2",children:"Connect Your Social Accounts"}),e.jsx("p",{className:"text-white/90 max-w-xl",children:"Link your Facebook Pages and Instagram Business accounts to post content directly from Social Swag with one click."})]})]}),e.jsxs(B,{variant:"ghost",onClick:()=>s("/social-swag-2"),className:"gap-2",children:[e.jsx(ka,{className:"h-4 w-4"}),"Back to Social Swag"]}),k&&e.jsx(_e,{className:"border-green-200 bg-green-50 dark:bg-green-950/20 dark:border-green-900",children:e.jsxs(De,{className:"flex items-center gap-4 p-4",children:[e.jsx("div",{className:"rounded-full bg-green-500 p-2",children:e.jsx(Po,{className:"h-5 w-5 text-white"})}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium text-green-800 dark:text-green-200",children:"You're all set!"}),e.jsx("p",{className:"text-sm text-green-600 dark:text-green-400",children:"You can now post directly to your connected accounts from Social Swag."})]})]})}),e.jsxs("div",{className:"grid gap-6 md:grid-cols-2 lg:grid-cols-3",children:[e.jsxs(_e,{children:[e.jsx(zt,{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(Kf,{className:"h-6 w-6 text-blue-600"})}),e.jsxs("div",{children:[e.jsx(qt,{className:"text-lg",children:"Facebook"}),e.jsx(_r,{children:"Connect your Facebook Pages"})]})]})}),e.jsxs(De,{className:"space-y-4",children:[u?e.jsx("div",{className:"flex items-center justify-center py-8",children:e.jsx(oo,{className:"h-6 w-6 animate-spin text-muted-foreground"})}):y.length>0?e.jsx("div",{className:"space-y-3",children:y.map(T=>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(Ua,{className:"h-10 w-10",children:[e.jsx(Gi,{src:T.profile_picture_url||""}),e.jsx(qa,{children:e.jsx(Kf,{className:"h-5 w-5"})})]}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:T.page_name||T.platform_username||"Facebook Page"}),e.jsx(We,{variant:T.is_active?"default":"secondary",className:"text-xs",children:T.is_active?"Connected":"Inactive"})]})]}),e.jsxs(Fl,{children:[e.jsx(Gf,{asChild:!0,children:e.jsx(B,{variant:"ghost",size:"icon",className:"text-destructive hover:text-destructive",children:e.jsx(qn,{className:"h-4 w-4"})})}),e.jsxs(kl,{children:[e.jsxs(Sl,{children:[e.jsx(Al,{children:"Disconnect Facebook?"}),e.jsx(Tl,{children:"This will remove the connection. You'll need to reconnect to post content."})]}),e.jsxs(Cl,{children:[e.jsx(El,{children:"Cancel"}),e.jsx(wl,{onClick:()=>h.mutate(T.id),className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:"Disconnect"})]})]})]})]},T.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:y.length>0?"outline":"default",children:[r?e.jsx(oo,{className:"h-4 w-4 animate-spin"}):e.jsx(nn,{className:"h-4 w-4"}),y.length>0?"Connect Another Page":"Connect Facebook Page"]})]})]}),e.jsxs(_e,{children:[e.jsx(zt,{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(dm,{className:"h-6 w-6 text-pink-600"})}),e.jsxs("div",{children:[e.jsx(qt,{className:"text-lg",children:"Instagram"}),e.jsx(_r,{children:"Connect Instagram Business accounts"})]})]})}),e.jsxs(De,{className:"space-y-4",children:[u?e.jsx("div",{className:"flex items-center justify-center py-8",children:e.jsx(oo,{className:"h-6 w-6 animate-spin text-muted-foreground"})}):x.length>0?e.jsx("div",{className:"space-y-3",children:x.map(T=>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(Ua,{className:"h-10 w-10",children:[e.jsx(Gi,{src:T.profile_picture_url||""}),e.jsx(qa,{children:e.jsx(dm,{className:"h-5 w-5"})})]}),e.jsxs("div",{children:[e.jsxs("p",{className:"font-medium",children:["@",T.platform_username||"Instagram Account"]}),e.jsx(We,{variant:T.is_active?"default":"secondary",className:"text-xs",children:T.is_active?"Connected":"Inactive"})]})]}),e.jsxs(Fl,{children:[e.jsx(Gf,{asChild:!0,children:e.jsx(B,{variant:"ghost",size:"icon",className:"text-destructive hover:text-destructive",children:e.jsx(qn,{className:"h-4 w-4"})})}),e.jsxs(kl,{children:[e.jsxs(Sl,{children:[e.jsx(Al,{children:"Disconnect Instagram?"}),e.jsx(Tl,{children:"This will remove the connection. You'll need to reconnect to post content."})]}),e.jsxs(Cl,{children:[e.jsx(El,{children:"Cancel"}),e.jsx(wl,{onClick:()=>h.mutate(T.id),className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:"Disconnect"})]})]})]})]},T.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:x.length>0?"outline":"default",children:[r?e.jsx(oo,{className:"h-4 w-4 animate-spin"}):e.jsx(nn,{className:"h-4 w-4"}),x.length>0?"Connect Another Account":"Connect Instagram Professional"]}),e.jsx("p",{className:"text-xs text-muted-foreground text-center",children:"Use Instagram login for Business or Creator accounts; Facebook Page login is only needed if you want to connect Pages."})]})]}),e.jsxs(_e,{children:[e.jsx(zt,{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(W0,{className:"h-6 w-6 text-blue-700"})}),e.jsxs("div",{children:[e.jsx(qt,{className:"text-lg",children:"LinkedIn"}),e.jsx(_r,{children:"Connect your LinkedIn profile"})]})]})}),e.jsxs(De,{className:"space-y-4",children:[u?e.jsx("div",{className:"flex items-center justify-center py-8",children:e.jsx(oo,{className:"h-6 w-6 animate-spin text-muted-foreground"})}):_.length>0?e.jsx("div",{className:"space-y-3",children:_.map(T=>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(Ua,{className:"h-10 w-10",children:[e.jsx(Gi,{src:T.profile_picture_url||""}),e.jsx(qa,{children:e.jsx(W0,{className:"h-5 w-5"})})]}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:T.platform_username||"LinkedIn Account"}),e.jsx(We,{variant:T.is_active?"default":"secondary",className:"text-xs",children:T.is_active?"Connected":"Inactive"})]})]}),e.jsxs(Fl,{children:[e.jsx(Gf,{asChild:!0,children:e.jsx(B,{variant:"ghost",size:"icon",className:"text-destructive hover:text-destructive",children:e.jsx(qn,{className:"h-4 w-4"})})}),e.jsxs(kl,{children:[e.jsxs(Sl,{children:[e.jsx(Al,{children:"Disconnect LinkedIn?"}),e.jsx(Tl,{children:"This will remove the connection. You'll need to reconnect to post content."})]}),e.jsxs(Cl,{children:[e.jsx(El,{children:"Cancel"}),e.jsx(wl,{onClick:()=>h.mutate(T.id),className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:"Disconnect"})]})]})]})]},T.id))}):e.jsx("p",{className:"text-sm text-muted-foreground py-4 text-center",children:"No LinkedIn account connected yet"}),e.jsxs(B,{onClick:f,disabled:r,className:"w-full gap-2",variant:_.length>0?"outline":"default",children:[r?e.jsx(oo,{className:"h-4 w-4 animate-spin"}):e.jsx(nn,{className:"h-4 w-4"}),_.length>0?"Reconnect LinkedIn":"Connect LinkedIn"]}),e.jsx("p",{className:"text-xs text-muted-foreground text-center",children:"Share content directly to your LinkedIn profile"})]})]}),e.jsxs(_e,{className:`relative overflow-hidden ${n?"":"opacity-75"}`,children:[!n&&e.jsx("div",{className:"absolute top-3 right-3 z-10",children:e.jsx(We,{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(We,{variant:"secondary",className:"bg-green-100 text-green-800 dark:bg-green-900/30 dark:text-green-400",children:"Admin Testing"})}),e.jsx(zt,{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(ii,{className:"h-6 w-6 text-red-600"})}),e.jsxs("div",{children:[e.jsx(qt,{className:"text-lg",children:"Google Business"}),e.jsx(_r,{children:"Connect your Google Business Profile"})]})]})}),e.jsxs(De,{className:"space-y-4",children:[u?e.jsx("div",{className:"flex items-center justify-center py-8",children:e.jsx(oo,{className:"h-6 w-6 animate-spin text-muted-foreground"})}):b.length>0?e.jsx("div",{className:"space-y-3",children:b.map(T=>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(Ua,{className:"h-10 w-10",children:[e.jsx(Gi,{src:T.profile_picture_url||""}),e.jsx(qa,{children:e.jsx(ii,{className:"h-5 w-5"})})]}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:T.page_name||T.platform_username||"Google Business"}),e.jsx(We,{variant:T.is_active?"default":"secondary",className:"text-xs",children:T.is_active?"Connected":"Inactive"})]})]}),e.jsxs(Fl,{children:[e.jsx(Gf,{asChild:!0,children:e.jsx(B,{variant:"ghost",size:"icon",className:"text-destructive hover:text-destructive",children:e.jsx(qn,{className:"h-4 w-4"})})}),e.jsxs(kl,{children:[e.jsxs(Sl,{children:[e.jsx(Al,{children:"Disconnect Google Business?"}),e.jsx(Tl,{children:"This will remove the connection. You'll need to reconnect to post content."})]}),e.jsxs(Cl,{children:[e.jsx(El,{children:"Cancel"}),e.jsx(wl,{onClick:()=>h.mutate(T.id),className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:"Disconnect"})]})]})]})]},T.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?g:void 0,disabled:!n||r,className:"w-full gap-2",variant:b.length>0?"outline":"default",children:[r?e.jsx(oo,{className:"h-4 w-4 animate-spin"}):e.jsx(nn,{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||x.length>0)&&e.jsxs(_e,{className:"border-amber-200 bg-amber-50 dark:bg-amber-950/20 dark:border-amber-900",children:[e.jsx(zt,{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(ST,{className:"h-6 w-6 text-amber-600"})}),e.jsxs("div",{children:[e.jsx(qt,{className:"text-lg",children:"Meta API Testing (Admin Only)"}),e.jsx(_r,{children:"Run API tests to trigger all required permissions for Meta App Review"})]})]})}),e.jsxs(De,{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(T=>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(Kf,{className:"h-5 w-5 text-blue-600"}),e.jsx("span",{className:"font-medium",children:T.page_name||"Facebook Page"})]}),e.jsx(B,{size:"sm",variant:"outline",onClick:()=>A(T.id),disabled:i===T.id,children:i===T.id?e.jsxs(e.Fragment,{children:[e.jsx(us,{className:"h-4 w-4 mr-2 animate-spin"}),"Testing..."]}):e.jsxs(e.Fragment,{children:[e.jsx(ST,{className:"h-4 w-4 mr-2"}),"Run Tests"]})})]},`test-fb-${T.id}`)),x.map(T=>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(dm,{className:"h-5 w-5 text-pink-600"}),e.jsxs("span",{className:"font-medium",children:["@",T.platform_username||"Instagram"]})]}),e.jsx(B,{size:"sm",variant:"outline",onClick:()=>A(T.id),disabled:i===T.id,children:i===T.id?e.jsxs(e.Fragment,{children:[e.jsx(us,{className:"h-4 w-4 mr-2 animate-spin"}),"Testing..."]}):e.jsxs(e.Fragment,{children:[e.jsx(ST,{className:"h-4 w-4 mr-2"}),"Run Tests"]})})]},`test-ig-${T.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((T,P)=>e.jsxs("div",{className:"flex items-start gap-2 text-sm",children:[T.status==="success"?e.jsx(Hr,{className:"h-4 w-4 text-green-600 mt-0.5 shrink-0"}):T.status==="pending"?e.jsx(us,{className:"h-4 w-4 text-amber-600 mt-0.5 shrink-0"}):e.jsx(Nu,{className:"h-4 w-4 text-red-600 mt-0.5 shrink-0"}),e.jsxs("div",{children:[e.jsx("span",{className:"font-mono text-xs bg-muted px-1 rounded",children:T.test}),e.jsx("span",{className:"ml-2 text-muted-foreground",children:T.details})]})]},P))})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Note: Facebook posts are auto-deleted. Instagram posts will remain and should be manually deleted. Allow up to 24 hours for Meta to register the API calls."})]})]}),e.jsxs(_e,{children:[e.jsx(zt,{children:e.jsx(qt,{className:"text-lg",children:"How it works"})}),e.jsx(De,{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 S4n(){const[s]=$c(),t=tr(),[n,r]=N.useState("loading"),[a,i]=N.useState("Processing your connection..."),l=(()=>{const o=sessionStorage.getItem("social-connect-return-to");return o&&o.startsWith("/")&&!o.startsWith("/admin")?o:"/social-connections"})();return N.useEffect(()=>{(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"),i(u||"Authorization was denied"),ie.error("Connection failed: "+(u||d));return}if(!c){r("error"),i("No authorization code received"),ie.error("No authorization code received");return}try{const{data:f,error:g}=await H.functions.invoke("meta-oauth",{body:{action:"exchange_code",code:c,state:h,callbackPath:"/social-connections/callback"}});if(g)throw g;if(f!=null&&f.success)r("success"),i(`Successfully connected ${((m=f.accounts)==null?void 0:m.length)||0} account(s)!`),ie.success("Social accounts connected successfully!");else throw new Error((f==null?void 0:f.error)||"Unknown error")}catch(f){console.error("OAuth callback error:",f),r("error"),i(f instanceof Error?f.message:"Failed to connect accounts"),ie.error("Failed to connect: "+(f instanceof Error?f.message:"Unknown error"))}})()},[s]),e.jsx("div",{className:"min-h-screen flex items-center justify-center bg-background p-4",children:e.jsxs(_e,{className:"w-full max-w-md",children:[e.jsxs(zt,{className:"text-center",children:[n==="loading"&&e.jsx(us,{className:"h-12 w-12 animate-spin mx-auto text-primary"}),n==="success"&&e.jsx(Po,{className:"h-12 w-12 mx-auto text-green-500"}),n==="error"&&e.jsx(Nu,{className:"h-12 w-12 mx-auto text-destructive"}),e.jsxs(qt,{className:"mt-4",children:[n==="loading"&&"Connecting...",n==="success"&&"Connected!",n==="error"&&"Connection Failed"]}),e.jsx(_r,{children:a})]}),e.jsx(De,{className:"flex justify-center",children:n!=="loading"&&e.jsx(B,{onClick:()=>t(l),children:n==="success"?"View Connected Accounts":"Try Again"})})]})})}function C4n(){const[s]=$c(),t=tr(),[n,r]=N.useState("loading"),[a,i]=N.useState("Connecting your Google Business Profile...");return N.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"),ie.error("Connection failed: "+(d||c));return}if(!o){r("error"),i("No authorization code received"),ie.error("No authorization code received");return}try{const{data:h,error:m}=await H.functions.invoke("google-business-oauth",{body:{action:"exchange_code",code:o,state:u}});if(m)throw m;if(h!=null&&h.success)r("success"),i(h.message||"Successfully connected Google Business Profile!"),ie.success("Google Business Profile connected!");else throw new Error((h==null?void 0:h.error)||"Unknown error")}catch(h){console.error("Google OAuth callback error:",h),r("error"),i(h instanceof Error?h.message:"Failed to connect Google Business Profile"),ie.error("Failed to connect: "+(h instanceof Error?h.message:"Unknown error"))}})()},[s]),e.jsx("div",{className:"min-h-screen flex items-center justify-center bg-background p-4",children:e.jsxs(_e,{className:"w-full max-w-md",children:[e.jsxs(zt,{className:"text-center",children:[n==="loading"&&e.jsx(us,{className:"h-12 w-12 animate-spin mx-auto text-primary"}),n==="success"&&e.jsx(Po,{className:"h-12 w-12 mx-auto text-green-500"}),n==="error"&&e.jsx(Nu,{className:"h-12 w-12 mx-auto text-destructive"}),e.jsxs(qt,{className:"mt-4",children:[n==="loading"&&"Connecting...",n==="success"&&"Connected!",n==="error"&&"Connection Failed"]}),e.jsx(_r,{children:a})]}),e.jsx(De,{className:"flex justify-center",children:n!=="loading"&&e.jsx(B,{onClick:()=>t("/social-connections"),children:n==="success"?"View Connected Accounts":"Try Again"})})]})})}function A4n(){const[s]=$c(),t=tr(),[n,r]=N.useState("loading"),[a,i]=N.useState("Connecting your LinkedIn account...");return N.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"),ie.error(u||"Failed to connect LinkedIn");return}if(!o){r("error"),i("No authorization code received"),ie.error("No authorization code received");return}try{const{data:m,error:f}=await H.functions.invoke("linkedin-oauth",{body:{action:"exchange_code",code:o,state:c,callbackPath:"/social-connections/linkedin-callback"}});if(f)throw f;if(m!=null&&m.success)r("success"),i(`Successfully connected ${((h=m.accounts)==null?void 0:h.length)||1} LinkedIn account`),ie.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"),ie.error("Failed to connect LinkedIn")}})()},[s]),e.jsx("div",{className:"min-h-screen flex items-center justify-center p-4 bg-background",children:e.jsxs(_e,{className:"w-full max-w-md",children:[e.jsxs(zt,{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(us,{className:"h-8 w-8 animate-spin text-blue-600"}),n==="success"&&e.jsx(Po,{className:"h-8 w-8 text-green-600"}),n==="error"&&e.jsx(Nu,{className:"h-8 w-8 text-red-600"})]}),e.jsxs(qt,{className:"flex items-center justify-center gap-2",children:[e.jsx(W0,{className:"h-5 w-5 text-blue-600"}),n==="loading"&&"Connecting...",n==="success"&&"Connected!",n==="error"&&"Connection Failed"]}),e.jsx(_r,{children:a})]}),e.jsx(De,{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 T4n(){const s=tr(),[t,n]=N.useState(null),{data:r,isLoading:a}=r9t(t||void 0,!0),{data:i,isLoading:l}=ZWe(!0),{cartItems:o}=J4e(),c=o.reduce((u,h)=>u+h.quantity,0),d=u=>{s(`/marketplace/${u.id}`)};return a||l?e.jsx(Qs,{title:"Marketplace",children:e.jsxs("div",{className:"space-y-6",children:[e.jsx("div",{className:"flex gap-2 overflow-x-auto pb-2",children:[1,2,3].map(u=>e.jsx(xn,{className:"h-10 w-24 flex-shrink-0"},u))}),e.jsx("div",{className:"grid gap-4 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4",children:[1,2,3,4].map(u=>e.jsx(xn,{className:"h-72 w-full"},u))})]})}):e.jsx(Qs,{title:"Marketplace",children:e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("h1",{className:"text-5xl font-bold text-foreground",children:"Marketplace"}),e.jsx("p",{className:"text-muted-foreground mt-1",children:"Shop exclusive products for LevelUp members"})]}),e.jsxs(B,{variant:"outline",onClick:()=>s("/marketplace/cart"),className:"relative",children:[e.jsx(W1,{className:"h-4 w-4 mr-2"}),"Cart",c>0&&e.jsx(We,{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(_e,{className:"overflow-hidden cursor-pointer hover:shadow-lg transition-shadow",onClick:()=>d(u),children:[e.jsxs("div",{className:"aspect-square bg-muted relative",children:[u.images&&u.images.length>0?e.jsx("img",{src:((h=u.images.find(m=>m.is_primary))==null?void 0:h.image_url)||u.images[0].image_url,alt:u.name,className:"w-full h-full object-cover"}):e.jsx("div",{className:"flex items-center justify-center h-full",children:e.jsx(Ku,{className:"h-12 w-12 text-muted-foreground"})}),u.category&&e.jsx(We,{className:"absolute top-2 left-2",variant:"secondary",children:u.category.name})]}),e.jsxs(De,{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(Ku,{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 L9t=N.forwardRef(({...s},t)=>e.jsx("nav",{ref:t,"aria-label":"breadcrumb",...s}));L9t.displayName="Breadcrumb";const P9t=N.forwardRef(({className:s,...t},n)=>e.jsx("ol",{ref:n,className:Ot("flex flex-wrap items-center gap-1.5 break-words text-sm text-muted-foreground sm:gap-2.5",s),...t}));P9t.displayName="BreadcrumbList";const Bje=N.forwardRef(({className:s,...t},n)=>e.jsx("li",{ref:n,className:Ot("inline-flex items-center gap-1.5",s),...t}));Bje.displayName="BreadcrumbItem";const bze=N.forwardRef(({asChild:s,className:t,...n},r)=>{const a=s?JBe:"a";return e.jsx(a,{ref:r,className:Ot("transition-colors hover:text-foreground",t),...n})});bze.displayName="BreadcrumbLink";const I9t=N.forwardRef(({className:s,...t},n)=>e.jsx("span",{ref:n,role:"link","aria-disabled":"true","aria-current":"page",className:Ot("font-normal text-foreground",s),...t}));I9t.displayName="BreadcrumbPage";const _ze=({children:s,className:t,...n})=>e.jsx("li",{role:"presentation","aria-hidden":"true",className:Ot("[&>svg]:size-3.5",t),...n,children:s??e.jsx(Qa,{})});_ze.displayName="BreadcrumbSeparator";function E4n(){var W,G;const{productId:s}=uo(),t=tr(),{data:n,isLoading:r}=b5n(s||""),{addToCart:a,cartItems:i}=J4e(),[l,o]=N.useState(null),[c,d]=N.useState(1),[u,h]=N.useState(0),[m,f]=N.useState(null),[g,y]=N.useState(!1),[x,_]=N.useState(!1),b=(W=n==null?void 0:n.variants)==null?void 0:W.find(X=>X.id===l),k=((G=n==null?void 0:n.variants)==null?void 0:G.filter(X=>X.is_active))||[],A=Number((n==null?void 0:n.base_price)||0),T=b?Number(b.price_adjustment):0,P=A+T,I=Number((n==null?void 0:n.shipping_fee)||0),M=i.reduce((X,te)=>X+te.quantity,0),L=async X=>{if(!X.target.files||X.target.files.length===0)return;y(!0);const te=X.target.files[0],ne=te.name.split(".").pop(),me=`artwork/${Date.now()}-${Math.random().toString(36).substring(7)}.${ne}`;try{const{error:ue}=await H.storage.from("marketplace").upload(me,te);if(ue)throw ue;const{data:{publicUrl:ce}}=H.storage.from("marketplace").getPublicUrl(me);f(ce),ie.success("Artwork uploaded successfully")}catch(ue){ie.error("Failed to upload artwork: "+ue.message)}finally{y(!1)}},z=()=>{if(n){if(k.length>0&&!l){ie.error("Please select an option");return}a(n,b||void 0,c,m||void 0),_(!0),ie.success("Added to cart!"),setTimeout(()=>_(!1),2e3)}},$=()=>{n!=null&&n.images&&h(X=>(X+1)%n.images.length)},V=()=>{n!=null&&n.images&&h(X=>(X-1+n.images.length)%n.images.length)};return r?e.jsx(Qs,{title:"Product",children:e.jsxs("div",{className:"grid gap-8 lg:grid-cols-2",children:[e.jsx(xn,{className:"aspect-square w-full"}),e.jsxs("div",{className:"space-y-4",children:[e.jsx(xn,{className:"h-8 w-3/4"}),e.jsx(xn,{className:"h-6 w-1/4"}),e.jsx(xn,{className:"h-24 w-full"}),e.jsx(xn,{className:"h-12 w-full"})]})]})}):n?e.jsxs(Qs,{title:n.name,children:[e.jsx(L9t,{className:"mb-6",children:e.jsxs(P9t,{children:[e.jsx(Bje,{children:e.jsx(bze,{asChild:!0,children:e.jsx(cr,{to:"/marketplace",children:"Marketplace"})})}),n.category&&e.jsxs(e.Fragment,{children:[e.jsx(_ze,{}),e.jsx(Bje,{children:e.jsx(bze,{asChild:!0,children:e.jsx(cr,{to:`/marketplace?category=${n.category.id}`,children:n.category.name})})})]}),e.jsx(_ze,{}),e.jsx(Bje,{children:e.jsx(I9t,{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(Fc,{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:$,children:e.jsx(Qa,{className:"h-6 w-6"})})]})]}):e.jsx("div",{className:"flex items-center justify-center h-full",children:e.jsx(Ku,{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((X,te)=>e.jsx("button",{onClick:()=>h(te),className:`w-16 h-16 flex-shrink-0 rounded-md overflow-hidden border-2 ${te===u?"border-primary":"border-transparent"}`,children:e.jsx("img",{src:X.image_url,alt:"",className:"w-full h-full object-cover"})},X.id))}),n.video&&e.jsx(_e,{children:e.jsxs(De,{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(We,{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:["$",P.toFixed(2)]}),I>0&&e.jsxs("span",{className:"text-muted-foreground",children:["+ $",I.toFixed(2)," shipping"]})]})]}),n.description&&e.jsx("div",{className:"prose prose-sm max-w-none",children:e.jsx("p",{className:"text-muted-foreground whitespace-pre-wrap",children:n.description})}),k.length>0&&e.jsxs("div",{className:"space-y-3",children:[e.jsx(re,{children:"Select Option"}),e.jsx("div",{className:"flex flex-wrap gap-2",children:k.map(X=>e.jsxs(B,{variant:l===X.id?"default":"outline",onClick:()=>o(X.id),children:[X.name,Number(X.price_adjustment)!==0&&e.jsxs("span",{className:"ml-1 opacity-70",children:["(",Number(X.price_adjustment)>0?"+":"","$",Number(X.price_adjustment).toFixed(2),")"]})]},X.id))})]}),n.allow_artwork_upload&&e.jsxs("div",{className:"space-y-3",children:[e.jsx(re,{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:()=>f(null),children:"×"})]}):e.jsxs("div",{className:"border-2 border-dashed rounded-lg p-6",children:[e.jsx("input",{type:"file",accept:"image/*,.pdf,.ai,.eps",onChange:L,className:"hidden",id:"artwork-upload",disabled:g}),e.jsxs("label",{htmlFor:"artwork-upload",className:"flex flex-col items-center cursor-pointer",children:[e.jsx(ni,{className:"h-8 w-8 text-muted-foreground mb-2"}),e.jsx("span",{className:"text-sm text-muted-foreground",children:g?"Uploading...":"Click to upload artwork"}),e.jsx("span",{className:"text-xs text-muted-foreground mt-1",children:"Supported: JPG, PNG, PDF, AI, EPS"})]})]})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsx(re,{children:"Quantity"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(B,{variant:"outline",size:"icon",onClick:()=>d(X=>Math.max(1,X-1)),children:"-"}),e.jsx(we,{type:"number",value:c,onChange:X=>d(Math.max(1,parseInt(X.target.value)||1)),className:"w-20 text-center",min:"1"}),e.jsx(B,{variant:"outline",size:"icon",onClick:()=>d(X=>X+1),children:"+"})]})]}),e.jsxs("div",{className:"flex gap-4",children:[e.jsx(B,{size:"lg",className:"flex-1",onClick:z,disabled:x,children:x?e.jsxs(e.Fragment,{children:[e.jsx(pa,{className:"h-5 w-5 mr-2"}),"Added!"]}):e.jsxs(e.Fragment,{children:[e.jsx(W1,{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(W1,{className:"h-5 w-5"}),M>0&&e.jsx(We,{className:"absolute -top-2 -right-2 h-5 w-5 flex items-center justify-center p-0 text-xs",children:M})]})]}),n.requires_proof_approval&&e.jsx("p",{className:"text-sm text-muted-foreground bg-muted p-3 rounded-lg",children:"📋 This product requires proof approval before production. You'll receive a proof to review after your order is placed."})]})]})]}):e.jsx(Qs,{title:"Product Not Found",children:e.jsxs("div",{className:"text-center py-12",children:[e.jsx(Ku,{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 M4n(){const s=tr(),{cartItems:t,removeFromCart:n,updateQuantity:r,getItemPrice:a,getSubtotal:i,getShippingTotal:l,getTotal:o,clearCart:c}=J4e(),[d,u]=N.useState(!1),[h,m]=N.useState(""),f=async()=>{if(t.length===0){ie.error("Your cart is empty");return}u(!0);try{const{data:g,error:y}=await H.functions.invoke("marketplace-checkout",{body:{items:t.map(x=>{var _;return{product_id:x.product.id,variant_id:((_=x.variant)==null?void 0:_.id)||null,quantity:x.quantity,artwork_url:x.artworkUrl||null}}),notes:h.trim()||null}});if(y)throw y;if(g!=null&&g.url)c(),window.open(g.url,"_blank");else throw new Error("No checkout URL received")}catch(g){ie.error("Checkout failed: "+g.message)}finally{u(!1)}};return t.length===0?e.jsx(Qs,{title:"Shopping Cart",children:e.jsxs("div",{className:"text-center py-12",children:[e.jsx(g5,{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(Qs,{title:"Shopping Cart",children:e.jsxs("div",{className:"grid gap-8 lg:grid-cols-3",children:[e.jsxs("div",{className:"lg:col-span-2 space-y-4",children:[t.map(g=>{var y,x;return e.jsx(_e,{children:e.jsx(De,{className:"p-4",children:e.jsxs("div",{className:"flex gap-4",children:[e.jsx("div",{className:"w-24 h-24 flex-shrink-0 bg-muted rounded-lg overflow-hidden",children:g.product.images&&g.product.images.length>0?e.jsx("img",{src:((y=g.product.images.find(_=>_.is_primary))==null?void 0:y.image_url)||g.product.images[0].image_url,alt:g.product.name,className:"w-full h-full object-cover"}):e.jsx("div",{className:"flex items-center justify-center h-full",children:e.jsx(g5,{className:"h-8 w-8 text-muted-foreground"})})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("h3",{className:"font-semibold line-clamp-1",children:g.product.name}),g.variant&&e.jsx("p",{className:"text-sm text-muted-foreground",children:g.variant.name}),e.jsxs("p",{className:"font-medium mt-1",children:["$",a(g).toFixed(2),Number(g.product.shipping_fee)>0&&e.jsxs("span",{className:"text-sm text-muted-foreground ml-2",children:["+ $",Number(g.product.shipping_fee).toFixed(2)," shipping"]})]}),g.artworkUrl&&e.jsx("div",{className:"mt-2",children:e.jsx("span",{className:"text-xs text-muted-foreground",children:"Artwork uploaded ✓"})})]}),e.jsxs("div",{className:"flex flex-col items-end gap-2",children:[e.jsx(B,{variant:"ghost",size:"icon",className:"h-8 w-8",onClick:()=>{var _;return n(g.product.id,(_=g.variant)==null?void 0:_.id)},children:e.jsx(qn,{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 _;return r(g.product.id,(_=g.variant)==null?void 0:_.id,g.quantity-1)},disabled:g.quantity<=1,children:e.jsx(X2,{className:"h-3 w-3"})}),e.jsx(we,{type:"number",value:g.quantity,onChange:_=>{var b;return r(g.product.id,(b=g.variant)==null?void 0:b.id,parseInt(_.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 _;return r(g.product.id,(_=g.variant)==null?void 0:_.id,g.quantity+1)},children:e.jsx(nn,{className:"h-3 w-3"})})]})]})]})})},`${g.product.id}-${((x=g.variant)==null?void 0:x.id)||"base"}`)}),e.jsx(B,{variant:"ghost",className:"text-destructive",onClick:c,children:"Clear Cart"})]}),e.jsx("div",{children:e.jsxs(_e,{className:"sticky top-4",children:[e.jsx(zt,{children:e.jsx(qt,{children:"Order Summary"})}),e.jsxs(De,{className:"space-y-4",children:[e.jsxs("div",{className:"flex justify-between text-sm",children:[e.jsxs("span",{children:["Subtotal (",t.reduce((g,y)=>g+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(Wl,{}),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(Wl,{}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{htmlFor:"orderNotes",children:"Order Notes (Optional)"}),e.jsx(Ws,{id:"orderNotes",placeholder:"Add any special instructions, design notes, or comments for your order...",value:h,onChange:g=>m(g.target.value),rows:3,className:"resize-none"})]}),e.jsx(B,{className:"w-full",size:"lg",onClick:f,disabled:d,children:d?e.jsxs(e.Fragment,{children:[e.jsx(us,{className:"h-5 w-5 mr-2 animate-spin"}),"Processing..."]}):e.jsxs(e.Fragment,{children:["Checkout",e.jsx(vi,{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 L4n(){const s=tr(),{data:t,isLoading:n}=M5n();return n?e.jsx(Qs,{title:"My Orders",children:e.jsx("div",{className:"space-y-4",children:[1,2,3].map(r=>e.jsx(xn,{className:"h-32 w-full"},r))})}):!t||t.length===0?e.jsx(Qs,{title:"My Orders",children:e.jsxs("div",{className:"text-center py-12",children:[e.jsx(Ku,{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(Qs,{title:"My Orders",children:e.jsx("div",{className:"space-y-4",children:t.map(r=>{var a,i,l;return e.jsx(_e,{className:"cursor-pointer hover:shadow-md transition-shadow",onClick:()=>s(`/marketplace/orders/${r.id}`),children:e.jsxs(De,{className:"p-4",children:[e.jsxs("div",{className:"flex items-center justify-between mb-3",children:[e.jsxs("div",{children:[e.jsx("span",{className:"font-semibold",children:r.order_number}),e.jsx("span",{className:"text-muted-foreground text-sm ml-2",children:Js(new Date(r.created_at),"MMM d, yyyy")})]}),e.jsx(We,{className:YWe[r.status],children:cz[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(Tr,{className:"h-4 w-4 mr-1"}),"Track"]}),e.jsx(Qa,{className:"h-5 w-5 text-muted-foreground"})]})]})]})},r.id)})})})}const ugt=["order_submitted","awaiting_proof_approval","proof_approved","processing","in_production","shipped","completed"];function P4n({currentStatus:s,statusHistory:t}){const n=ugt.indexOf(s);return e.jsx("div",{className:"space-y-3",children:ugt.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(Hr,{className:"h-4 w-4"}):o?e.jsx(Xr,{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:cz[r]}),i&&e.jsxs("p",{className:"text-xs text-muted-foreground",children:[Js(new Date(i.created_at),"MMM d, yyyy h:mm a"),i.notes&&` — ${i.notes}`]})]})]},r)})})}function I4n(){var _;const{orderId:s}=uo(),t=tr(),{data:n,isLoading:r,refetch:a}=L5n(s||""),i=D5n(),l=R5n(),[o,c]=N.useState(!1),[d,u]=N.useState(null),[h,m]=N.useState(""),[f,g]=N.useState(null),y=async b=>{g(b);try{await i.mutateAsync({orderId:s,itemId:b}),ie.success("Proof approved!"),a()}catch{ie.error("Failed to approve proof")}finally{g(null)}},x=async()=>{if(d){g(d);try{await l.mutateAsync({orderId:s,itemId:d,reason:h}),ie.success("Revision requested"),c(!1),m(""),u(null),a()}catch{ie.error("Failed to request revision")}finally{g(null)}}};return r?e.jsx(Qs,{title:"Order Details",children:e.jsxs("div",{className:"grid gap-6 lg:grid-cols-3",children:[e.jsxs("div",{className:"lg:col-span-2 space-y-6",children:[e.jsx(xn,{className:"h-64 w-full"}),e.jsx(xn,{className:"h-48 w-full"})]}),e.jsx(xn,{className:"h-96 w-full"})]})}):n?e.jsxs(Qs,{title:`Order ${n.order_number}`,children:[e.jsxs("div",{className:"grid gap-6 lg:grid-cols-3",children:[e.jsxs("div",{className:"lg:col-span-2 space-y-6",children:[e.jsxs(_e,{children:[e.jsxs(zt,{className:"flex flex-row items-center justify-between",children:[e.jsx(qt,{children:"Order Status"}),e.jsx(We,{className:YWe[n.status],children:cz[n.status]})]}),e.jsx(De,{children:e.jsx(P4n,{currentStatus:n.status,statusHistory:n.status_history})})]}),e.jsxs(_e,{children:[e.jsx(zt,{children:e.jsx(qt,{children:"Items"})}),e.jsx(De,{className:"space-y-4",children:(_=n.items)==null?void 0:_.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(t3,{className:"h-4 w-4"}),"View Artwork",e.jsx(Tr,{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(t3,{className:"h-4 w-4"}),"View Proof",e.jsx(Tr,{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:f===b.id,children:[f===b.id?e.jsx(us,{className:"h-4 w-4 mr-1 animate-spin"}):e.jsx(ax,{className:"h-4 w-4 mr-1"}),"Approve"]}),e.jsxs(B,{size:"sm",variant:"outline",onClick:()=>{u(b.id),c(!0)},disabled:f===b.id,children:[e.jsx(SW,{className:"h-4 w-4 mr-1"}),"Request Changes"]})]}),b.proof_status==="approved"&&e.jsxs(We,{className:"bg-green-100 text-green-800",children:[e.jsx(Hr,{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(We,{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(_e,{children:[e.jsx(zt,{children:e.jsxs(qt,{className:"flex items-center gap-2",children:[e.jsx(AW,{className:"h-5 w-5"}),"Shipping"]})}),e.jsxs(De,{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(Tr,{className:"h-3 w-3 ml-1"})]})]})]})]})]}),e.jsx("div",{children:e.jsxs(_e,{className:"sticky top-4",children:[e.jsx(zt,{children:e.jsx(qt,{children:"Order Summary"})}),e.jsxs(De,{className:"space-y-4",children:[e.jsxs("div",{className:"text-sm text-muted-foreground",children:["Placed on ",Js(new Date(n.created_at),"MMMM d, yyyy")]}),e.jsx(Wl,{}),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(Wl,{}),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(Wl,{}),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(Bs,{open:o,onOpenChange:c,children:e.jsxs(Fs,{children:[e.jsxs(qs,{children:[e.jsx($s,{children:"Request Changes"}),e.jsx(Ar,{children:"Please describe what changes you'd like made to the proof."})]}),e.jsx(Ws,{placeholder:"Describe the changes needed...",value:h,onChange:b=>m(b.target.value),rows:4}),e.jsxs(Cr,{children:[e.jsx(B,{variant:"outline",onClick:()=>c(!1),children:"Cancel"}),e.jsxs(B,{onClick:x,disabled:!h.trim()||f!==null,children:[f?e.jsx(us,{className:"h-4 w-4 mr-2 animate-spin"}):null,"Submit Request"]})]})]})})]}):e.jsx(Qs,{title:"Order Not Found",children:e.jsxs("div",{className:"text-center py-12",children:[e.jsx(Ku,{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 D4n(){const s=tr(),[t]=$c();return t.get("session_id"),N.useEffect(()=>{localStorage.removeItem("marketplace-cart")},[]),e.jsx(Qs,{title:"Order Confirmed",children:e.jsx("div",{className:"max-w-lg mx-auto text-center py-8",children:e.jsx(_e,{children:e.jsxs(De,{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(Hr,{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(Ku,{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(vi,{className:"h-4 w-4 ml-2"})]}),e.jsx(B,{variant:"outline",className:"flex-1",onClick:()=>s("/marketplace"),children:"Continue Shopping"})]})]})})})})}function R4n(){const{user:s}=Ls(),[t,n]=N.useState("store"),[r,a]=N.useState(null),[i,l]=N.useState(null),[o,c]=N.useState(!1),[d,u]=N.useState(5),[h,m]=N.useState(""),[f,g]=N.useState(!1),[y,x]=N.useState(!1),[_,b]=N.useState(""),[k,A]=N.useState(null),[T,P]=N.useState(!1),{hasSubmittedReview:I,submitReview:M,markPostedToGoogle:L}=c4t(),{data:z}=i9t(),{data:$,isLoading:V}=a9t(),{data:W,isLoading:G}=q5n(r),{data:X,isLoading:te}=V5n(s==null?void 0:s.id),{data:ne=0}=G5n(s==null?void 0:s.id),me=W5n(),ue=new Set((X==null?void 0:X.map(be=>be.item_id))||[]),ce=async()=>{if(i)try{const be=await me.mutateAsync(i.id);i.item_type==="reelflow_credits"?ie.success(`🎬 ${i.max_quantity} ReelFlow credits added to your balance!`):ie.success(`Successfully purchased "${i.name}"!`),l(null)}catch(be){ie.error(be.message||"Failed to purchase item")}},ae=async()=>{if(!h.trim()){ie.error("Please write a review");return}g(!0);const be=await M(d,h);g(!1),be.success?(ie.success("Thank you for your review! You earned 25 points!"),b(h),x(!0),m(""),u(5)):ie.error(be.error||"Failed to submit review")},he=()=>{navigator.clipboard.writeText(_),ie.success("Review copied to clipboard!")},xe=()=>{L(),window.open("https://g.page/r/CT8bqTBTm7nJEBM/review","_blank")},ve=()=>{x(!1),c(!1),b("")};return V||G||te?e.jsx(Qs,{title:"Reward Store",children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(xn,{className:"h-24 w-full"}),e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4",children:[1,2,3,4,5,6].map(be=>e.jsx(xn,{className:"h-64"},be))})]})}):e.jsxs(Qs,{title:"Reward Store",children:[e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{children:[e.jsx("h1",{className:"text-5xl font-bold text-foreground",children:"Reward Store"}),e.jsx("p",{className:"text-muted-foreground mt-1",children:"Redeem your points for exclusive rewards"})]}),e.jsx(_e,{className:"bg-gradient-to-r from-primary/10 to-primary/5 border-primary/20",children:e.jsx(De,{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(Wa,{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:ne.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(gl,{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(Cu,{className:"h-4 w-4 text-orange-500"}),e.jsx("span",{children:"Streak bonuses add extra points!"})]})]})]})})}),e.jsx(Kv,{open:T,onOpenChange:P,children:e.jsxs(_e,{className:"border-primary/20",children:[e.jsx(Yv,{asChild:!0,children:e.jsx(zt,{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(gl,{className:"h-5 w-5 text-primary"})}),e.jsxs("div",{children:[e.jsx(qt,{className:"text-base",children:"How to Earn Points"}),e.jsx(_r,{children:"See all the ways you can earn spendable points"})]})]}),T?e.jsx(zy,{className:"h-5 w-5 text-muted-foreground"}):e.jsx(Xo,{className:"h-5 w-5 text-muted-foreground"})]})})}),e.jsx(Zv,{children:e.jsx(De,{className:"pt-0",children:e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-3",children:[z==null?void 0:z.filter(be=>be.is_active).map(be=>{const Se=Ie=>{switch(Ie){case"event_attendance":return e.jsx(ta,{className:"h-5 w-5"});case"leave_review":return e.jsx(Wa,{className:"h-5 w-5"});case"add_listing":return e.jsx(_a,{className:"h-5 w-5"});case"first_contact":return e.jsx(Yn,{className:"h-5 w-5"});case"first_video":return e.jsx(na,{className:"h-5 w-5"});case"first_community_post":return e.jsx(xo,{className:"h-5 w-5"});default:return e.jsx(Io,{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:Se(be.action_key)}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"font-medium text-sm",children:be.action_name}),be.description&&e.jsx("p",{className:"text-xs text-muted-foreground truncate",children:be.description})]}),e.jsxs(We,{variant:"secondary",className:"font-bold shrink-0",children:["+",be.points]})]},be.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(Cu,{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(We,{variant:"outline",className:"font-bold shrink-0 border-orange-500/50 text-orange-600",children:"+Bonus"})]})]})})})]})}),!I&&e.jsx(_e,{className:"bg-gradient-to-r from-yellow-500/10 to-orange-500/10 border-yellow-500/20",children:e.jsx(De,{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(xo,{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(Wa,{className:"h-4 w-4 mr-2"}),"Leave Review"]})]})})}),e.jsxs(ya,{value:t,onValueChange:n,children:[e.jsxs(va,{children:[e.jsxs(ls,{value:"store",className:"flex items-center gap-2",children:[e.jsx(g5,{className:"h-4 w-4"}),"Store"]}),e.jsxs(ls,{value:"my-rewards",className:"flex items-center gap-2",children:[e.jsx(Ku,{className:"h-4 w-4"}),"My Rewards",X&&X.length>0&&e.jsx(We,{variant:"secondary",className:"ml-1",children:X.length})]})]}),e.jsxs(_s,{value:"store",className:"mt-6",children:[$&&$.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"}),$.map(be=>e.jsxs(B,{variant:r===be.id?"default":"outline",size:"sm",onClick:()=>a(be.id),children:[be.icon&&`${be.icon} `,be.name]},be.id))]}),!W||W.length===0?e.jsx(_e,{children:e.jsx(De,{className:"py-12",children:e.jsxs("div",{className:"text-center text-muted-foreground",children:[e.jsx(Io,{className:"h-12 w-12 mx-auto mb-4 opacity-50"}),e.jsx("p",{className:"font-medium",children:"No items available"}),e.jsx("p",{className:"text-sm",children:"Check back later for new rewards!"})]})})}):e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4",children:W.map(be=>{const Se=be.item_type==="reelflow_credits",Ie=!Se&&ue.has(be.id),Me=!Se&&be.max_quantity!==null&&be.current_quantity===0,Re=ne>=be.points_cost;return e.jsxs(_e,{className:`overflow-hidden transition-all cursor-pointer hover:shadow-lg ${Ie?"ring-2 ring-green-500/50 bg-green-500/5":""}`,onClick:()=>A(be),children:[be.preview_image_url?e.jsxs("div",{className:"aspect-video relative overflow-hidden bg-muted",children:[e.jsx("img",{src:be.preview_image_url,alt:be.name,className:"w-full h-full object-cover"}),Ie&&e.jsx("div",{className:"absolute top-2 right-2",children:e.jsxs(We,{className:"bg-green-500 text-white",children:[e.jsx(Hr,{className:"h-3 w-3 mr-1"}),"Owned"]})}),Me&&!Ie&&e.jsx("div",{className:"absolute inset-0 bg-black/50 flex items-center justify-center",children:e.jsx(We,{variant:"destructive",children:"Sold Out"})})]}):e.jsxs("div",{className:"aspect-video bg-muted flex items-center justify-center relative",children:[e.jsx(Io,{className:"h-12 w-12 text-muted-foreground/50"}),Ie&&e.jsx("div",{className:"absolute top-2 right-2",children:e.jsxs(We,{className:"bg-green-500 text-white",children:[e.jsx(Hr,{className:"h-3 w-3 mr-1"}),"Owned"]})})]}),e.jsxs(zt,{className:"pb-2",children:[e.jsxs("div",{className:"flex items-start justify-between",children:[e.jsx(qt,{className:"text-lg",children:be.name}),e.jsxs(We,{variant:"secondary",className:"font-bold shrink-0",children:[e.jsx(Wa,{className:"h-3 w-3 mr-1"}),be.points_cost]})]}),be.category&&e.jsxs(We,{variant:"outline",className:"w-fit",children:[be.category.icon&&`${be.category.icon} `,be.category.name]})]}),e.jsxs(De,{children:[e.jsx(_r,{className:"mb-4 line-clamp-2",children:be.description||"No description available"}),be.max_quantity!==null&&!Ie&&!Se&&e.jsxs("p",{className:"text-xs text-muted-foreground mb-3",children:[be.current_quantity," of ",be.max_quantity," remaining"]}),Se&&e.jsxs("p",{className:"text-xs text-violet-600 font-medium mb-3",children:["🎬 Grants ",be.max_quantity," ReelFlow credits per purchase"]}),Ie?e.jsx(B,{className:"w-full",onClick:Be=>{Be.stopPropagation(),be.file_url&&ZPe(be.file_url,be.name)},disabled:!be.file_url,children:be.item_type==="file"?e.jsxs(e.Fragment,{children:[e.jsx(oi,{className:"h-4 w-4 mr-2"}),"Download"]}):e.jsxs(e.Fragment,{children:[e.jsx(Tr,{className:"h-4 w-4 mr-2"}),"Access"]})}):e.jsx(B,{className:"w-full",onClick:Be=>{Be.stopPropagation(),l(be)},disabled:Me||!Re,children:Me?"Sold Out":Re?e.jsxs(e.Fragment,{children:[e.jsx(g5,{className:"h-4 w-4 mr-2"}),"Purchase"]}):`Need ${be.points_cost-ne} more pts`})]})]},be.id)})})]}),e.jsx(_s,{value:"my-rewards",className:"mt-6",children:!X||X.length===0?e.jsx(_e,{children:e.jsx(De,{className:"py-12",children:e.jsxs("div",{className:"text-center text-muted-foreground",children:[e.jsx(Ku,{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:X.map(be=>{var Se,Ie,Me,Re,Be,Ne,Ge;return e.jsxs(_e,{className:"overflow-hidden",children:[(Se=be.item)!=null&&Se.preview_image_url?e.jsx("div",{className:"aspect-video relative overflow-hidden bg-muted",children:e.jsx("img",{src:be.item.preview_image_url,alt:((Ie=be.item)==null?void 0:Ie.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(Io,{className:"h-12 w-12 text-muted-foreground/50"})}),e.jsxs(zt,{className:"pb-2",children:[e.jsx(qt,{className:"text-lg",children:((Me=be.item)==null?void 0:Me.name)||"Unknown Item"}),e.jsxs(_r,{className:"text-xs",children:["Purchased for ",be.points_spent," points • ",new Date(be.purchased_at).toLocaleDateString()]})]}),e.jsx(De,{children:((Re=be.item)==null?void 0:Re.item_type)==="reelflow_credits"?e.jsxs(B,{className:"w-full",variant:"outline",disabled:!0,children:[e.jsx(Hr,{className:"h-4 w-4 mr-2 text-green-500"}),(Be=be.item)==null?void 0:Be.max_quantity," Credits Applied"]}):e.jsx(B,{className:"w-full",onClick:()=>{var Ce,Fe;(Ce=be.item)!=null&&Ce.file_url&&ZPe(be.item.file_url,(Fe=be.item)==null?void 0:Fe.name)},disabled:!((Ne=be.item)!=null&&Ne.file_url),children:((Ge=be.item)==null?void 0:Ge.item_type)==="file"?e.jsxs(e.Fragment,{children:[e.jsx(oi,{className:"h-4 w-4 mr-2"}),"Download"]}):e.jsxs(e.Fragment,{children:[e.jsx(Tr,{className:"h-4 w-4 mr-2"}),"Access"]})})})]},be.id)})})})]})]}),e.jsx(Fl,{open:!!i,onOpenChange:()=>l(null),children:e.jsxs(kl,{children:[e.jsxs(Sl,{children:[e.jsx(Al,{children:"Confirm Purchase"}),e.jsxs(Tl,{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:[ne," points"]}),". After this purchase, you'll have"," ",e.jsxs("strong",{children:[ne-((i==null?void 0:i.points_cost)||0)," points"]})," remaining."]})]}),e.jsxs(Cl,{children:[e.jsx(El,{children:"Cancel"}),e.jsx(wl,{onClick:ce,disabled:me.isPending,children:me.isPending?"Purchasing...":"Confirm Purchase"})]})]})}),e.jsx(Bs,{open:o,onOpenChange:be=>{!be&&y?ve():c(be)},children:e.jsx(Fs,{children:y?e.jsxs(e.Fragment,{children:[e.jsxs(qs,{children:[e.jsxs($s,{className:"flex items-center gap-2",children:[e.jsx(Hr,{className:"h-5 w-5 text-green-500"}),"Thank You for Your Review!"]}),e.jsx(Ar,{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:['"',_,'"']})]}),e.jsxs(B,{variant:"outline",className:"w-full",onClick:he,children:[e.jsx(Pa,{className:"h-4 w-4 mr-2"}),"Copy Review to Clipboard"]})]}),e.jsxs(Cr,{className:"flex-col sm:flex-row gap-2",children:[e.jsx(B,{variant:"outline",onClick:ve,children:"Maybe Later"}),e.jsxs(B,{onClick:xe,className:"bg-blue-600 hover:bg-blue-700",children:[e.jsx(Tr,{className:"h-4 w-4 mr-2"}),"Leave Google Review"]})]})]}):e.jsxs(e.Fragment,{children:[e.jsxs(qs,{children:[e.jsx($s,{children:"Leave a Review"}),e.jsx(Ar,{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(be=>e.jsx("button",{type:"button",onClick:()=>u(be),className:"focus:outline-none",children:e.jsx(Wa,{className:`h-8 w-8 transition-colors ${d>=be?"fill-yellow-400 text-yellow-400":"text-muted-foreground hover:text-yellow-400"}`})},be))})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-sm font-medium mb-2 block",children:"Your Review"}),e.jsx(Ws,{placeholder:"What do you love about LevelUp? How has it helped your business?",value:h,onChange:be=>m(be.target.value),rows:4})]})]}),e.jsxs(Cr,{children:[e.jsx(B,{variant:"outline",onClick:()=>c(!1),children:"Cancel"}),e.jsx(B,{onClick:ae,disabled:f,className:"bg-yellow-600 hover:bg-yellow-700",children:f?"Submitting...":"Submit & Earn 25 Points"})]})]})})}),e.jsx(Bs,{open:!!k,onOpenChange:()=>A(null),children:e.jsxs(Fs,{className:"max-w-lg",children:[e.jsxs(qs,{children:[e.jsxs($s,{className:"flex items-center gap-2",children:[k==null?void 0:k.name,e.jsxs(We,{variant:"secondary",className:"font-bold",children:[e.jsx(Wa,{className:"h-3 w-3 mr-1"}),k==null?void 0:k.points_cost]})]}),(k==null?void 0:k.category)&&e.jsxs(We,{variant:"outline",className:"w-fit",children:[k.category.icon&&`${k.category.icon} `,k.category.name]})]}),(k==null?void 0:k.preview_image_url)&&e.jsx("div",{className:"aspect-video relative overflow-hidden bg-muted rounded-lg",children:e.jsx("img",{src:k.preview_image_url,alt:k.name,className:"w-full h-full object-cover"})}),e.jsxs("div",{className:"space-y-4",children:[e.jsx("p",{className:"text-muted-foreground",children:(k==null?void 0:k.description)||"No description available"}),(k==null?void 0:k.item_type)==="reelflow_credits"&&e.jsxs("p",{className:"text-sm text-violet-600 font-medium",children:["🎬 Grants ",k==null?void 0:k.max_quantity," ReelFlow credits per purchase"]}),(k==null?void 0:k.item_type)!=="reelflow_credits"&&(k==null?void 0:k.max_quantity)!==null&&!ue.has((k==null?void 0:k.id)||"")&&e.jsxs("p",{className:"text-sm text-muted-foreground",children:[k==null?void 0:k.current_quantity," of ",k==null?void 0:k.max_quantity," remaining"]})]}),e.jsx(Cr,{children:k&&k.item_type!=="reelflow_credits"&&ue.has(k.id)?e.jsx(B,{className:"w-full",onClick:()=>{k.file_url&&ZPe(k.file_url,k.name)},disabled:!k.file_url,children:k.item_type==="file"?e.jsxs(e.Fragment,{children:[e.jsx(oi,{className:"h-4 w-4 mr-2"}),"Download"]}):e.jsxs(e.Fragment,{children:[e.jsx(Tr,{className:"h-4 w-4 mr-2"}),"Access"]})}):k&&e.jsx(B,{className:"w-full",onClick:()=>{A(null),l(k)},disabled:k.item_type!=="reelflow_credits"&&k.max_quantity!==null&&k.current_quantity===0||ne{s&&te()},[s==null?void 0:s.id]);const te=async()=>{if(!s)return;o(!0),_(!1),y(!0);const{data:Be}=await H.from("point_reward_settings").select("action_key, points").in("action_key",["referral_signup","referral_paid"]);Be==null||Be.forEach(Fe=>{Fe.action_key==="referral_signup"&&h(Fe.points),Fe.action_key==="referral_paid"&&f(Fe.points)});const{data:Ne}=await H.from("profiles").select("name").eq("id",s.id).maybeSingle();Ne!=null&&Ne.name&&k(Ne.name);let{data:Ge}=await H.from("agent_referral_codes").select("code").eq("user_id",s.id).maybeSingle();if(!Ge){const{data:Fe}=await H.rpc("generate_agent_referral_code",{_user_id:s.id}),Ae=Fe||`agent${s.id.slice(0,6)}`,{data:Xe,error:$e}=await H.from("agent_referral_codes").insert({user_id:s.id,code:Ae}).select("code").maybeSingle();!$e&&Xe&&(Ge=Xe)}i((Ge==null?void 0:Ge.code)??null);const{data:Ce}=await H.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(Ce&&Ce.length>0){const Fe=Ce.map($e=>$e.referred_user_id),{data:Ae}=await H.from("profiles").select("id, name, email").in("id",Fe),Xe=new Map((Ae==null?void 0:Ae.map($e=>[$e.id,$e]))??[]);d(Ce.map($e=>({...$e,referred_profile:Xe.get($e.referred_user_id)??null})))}else d([]);o(!1)},ne=N.useMemo(()=>a?`${O4n}/trial?ref=${a}`:"",[a]),me=c.length,ue=c.filter(Be=>Be.status==="qualified").length,ce=c.filter(Be=>Be.signup_points_awarded).length*u+c.filter(Be=>Be.paid_points_awarded).length*m,ae=async()=>{ne&&(await navigator.clipboard.writeText(ne),ie.success("Referral link copied!"))},he=()=>{const Be=encodeURIComponent("Join me on LevelUp"),Ne=encodeURIComponent(`Hi — I've been using LevelUp to grow my real estate business and thought you'd love it too. Sign up using my link and we'll both get a head start: ${ne} Let me know if you have any questions!`);window.location.href=`mailto:?subject=${Be}&body=${Ne}`},xe=()=>{const Be=encodeURIComponent(`Hey! I think you'd love LevelUp for your business — sign up with my link: ${ne}`);window.location.href=`sms:?&body=${Be}`},ve=async()=>{if(navigator.share&&ne)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:ne})}catch{}else ae()},ge=Be=>/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(Be.trim()),be=Be=>{const Ne=(Be??P).trim().replace(/,$/,"");if(!Ne)return;const Ge=Ne.split(/[\s,;]+/).filter(Boolean),Ce=[...M];let Fe=0;for(const Ae of Ge){if(!ge(Ae)){ie.error(`Invalid email: ${Ae}`);continue}Ce.includes(Ae)||(Ce.push(Ae),Fe++)}L(Ce),Fe>0&&I("")},Se=Be=>L(M.filter(Ne=>Ne!==Be)),Ie=()=>{W(`${b?b.split(" ")[0]+" invited you to":"Join me on"} LevelUp`),$("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."),T(!0)},Me=Be=>{const Ne=Be.replace(/&/g,"&").replace(//g,">").replace(/\n/g,"
"),Ge=b||"A fellow agent",Ce="https://relzejiswnotikjgvjhz.supabase.co/storage/v1/object/public/email-assets/levelup-logo-email.png",Fe=ne;return`
LevelUp
You're Invited

${Ge} thinks you'd love LevelUp 🎉

${Ne}

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

Or copy & paste this link:
${Fe}

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

`.trim()},Re=async()=>{if(M.length===0&&(P.trim()&&be(),M.length===0)){ie.error("Add at least one recipient");return}if(!V.trim()){ie.error("Subject is required");return}X(!0);const Be=Me(z);let Ne=0,Ge=0;for(const Ce of M)try{const{data:Fe,error:Ae}=await H.functions.invoke("gmail-send",{body:{to:Ce,subject:V,body:Be,source:"referral_invite"}});if(Ae||Fe!=null&&Fe.error)throw new Error((Ae==null?void 0:Ae.message)||(Fe==null?void 0:Fe.error));Ne++}catch(Fe){console.error("Gmail send failed for",Ce,Fe),Ge++}X(!1),Ne>0?(ie.success(`Invite sent to ${Ne} ${Ne===1?"person":"people"}`+(Ge>0?` (${Ge} failed)`:"")),L([]),I(""),T(!1)):ie.error("Failed to send invites")};return!x&&!g?e.jsx(Qs,{title:"Refer & Earn",children:e.jsxs("div",{className:"container max-w-3xl mx-auto p-4 md:p-8",children:[e.jsx(ic,{children:e.jsx("title",{children:"Refer & Earn | LevelUp"})}),e.jsxs(_e,{className:"border-2 border-dashed",children:[e.jsxs(zt,{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(Au,{className:"h-6 w-6 text-muted-foreground"})}),e.jsx(qt,{children:"Refer & Earn is for active members"}),e.jsx(_r,{children:"Activate your subscription to unlock your personal referral link and start earning points."})]}),e.jsx(De,{className:"flex justify-center",children:e.jsx(B,{onClick:()=>t("/subscription"),children:"View Subscription"})})]})]})}):e.jsxs(Qs,{title:"Refer & Earn",children:[e.jsxs("div",{className:"container max-w-5xl mx-auto p-4 md:p-8 space-y-6",children:[e.jsxs(ic,{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(Io,{className:"h-7 w-7 text-primary"}),e.jsx("h1",{className:"text-3xl font-bold tracking-tight",children:"Refer & Earn"})]}),e.jsxs("p",{className:"text-muted-foreground",children:["Share LevelUp with peers, mentees, or fellow agents. Earn"," ",e.jsxs("span",{className:"font-semibold text-foreground",children:[u," points"]})," when they sign up and"," ",e.jsxs("span",{className:"font-semibold text-foreground",children:[m," more"]})," when they activate a paid plan."]})]}),e.jsxs("div",{className:"grid gap-3 md:grid-cols-3",children:[e.jsx(_e,{children:e.jsxs(De,{className:"p-4 flex items-center gap-3",children:[e.jsx(Yn,{className:"h-5 w-5 text-muted-foreground"}),e.jsxs("div",{children:[e.jsx("div",{className:"text-2xl font-bold",children:me}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"Friends signed up"})]})]})}),e.jsx(_e,{children:e.jsxs(De,{className:"p-4 flex items-center gap-3",children:[e.jsx(Hr,{className:"h-5 w-5 text-emerald-600"}),e.jsxs("div",{children:[e.jsx("div",{className:"text-2xl font-bold",children:ue}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"Activated paid plan"})]})]})}),e.jsx(_e,{children:e.jsxs(De,{className:"p-4 flex items-center gap-3",children:[e.jsx(gl,{className:"h-5 w-5 text-amber-500"}),e.jsxs("div",{children:[e.jsx("div",{className:"text-2xl font-bold",children:ce.toLocaleString()}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"Points earned"})]})]})})]}),e.jsxs(_e,{children:[e.jsxs(zt,{children:[e.jsxs(qt,{className:"flex items-center gap-2",children:[e.jsx(Cn,{className:"h-5 w-5 text-primary"}),"Your referral link"]}),e.jsx(_r,{children:"Anyone who signs up through this link is credited to you."})]}),e.jsxs(De,{className:"space-y-4",children:[e.jsxs("div",{className:"flex flex-col sm:flex-row gap-2",children:[e.jsx(we,{readOnly:!0,value:l?"Loading…":ne,className:"font-mono text-sm",onFocus:Be=>Be.currentTarget.select()}),e.jsxs(B,{onClick:ae,disabled:!ne,children:[e.jsx(Pa,{className:"h-4 w-4 mr-2"}),"Copy link"]})]}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[n&&e.jsxs(B,{size:"sm",onClick:Ie,disabled:!ne,className:"bg-primary hover:bg-primary/90",children:[e.jsx(Rr,{className:"h-4 w-4 mr-2"})," Send via Gmail"]}),e.jsxs(B,{variant:"outline",size:"sm",onClick:he,disabled:!ne,children:[e.jsx(mn,{className:"h-4 w-4 mr-2"})," Email"]}),e.jsxs(B,{variant:"outline",size:"sm",onClick:xe,disabled:!ne,children:[e.jsx(xo,{className:"h-4 w-4 mr-2"})," Text"]}),e.jsxs(B,{variant:"outline",size:"sm",onClick:ve,disabled:!ne,children:[e.jsx(Md,{className:"h-4 w-4 mr-2"})," More…"]})]}),!n&&e.jsxs("div",{className:"text-xs text-muted-foreground",children:["💡 ",e.jsx("button",{onClick:()=>t("/integrations"),className:"underline hover:text-foreground",children:"Connect Gmail"})," to send branded invite emails directly from your inbox."]}),a&&e.jsxs("div",{className:"text-xs text-muted-foreground",children:["Your code: ",e.jsx("span",{className:"font-mono font-semibold text-foreground",children:a})]})]})]}),e.jsxs(_e,{children:[e.jsxs(zt,{children:[e.jsx(qt,{children:"Your Referrals"}),e.jsx(_r,{children:"Track who joined and when they upgrade."})]}),e.jsx(De,{children:l?e.jsx("p",{className:"text-sm text-muted-foreground py-6 text-center",children:"Loading…"}):c.length===0?e.jsxs("div",{className:"text-center py-10 space-y-2",children:[e.jsx(Yn,{className:"h-10 w-10 mx-auto text-muted-foreground/50"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"No referrals yet. Share your link to get started!"})]}):e.jsx("div",{className:"divide-y",children:c.map(Be=>{var Ce,Fe;const Ne=((Ce=Be.referred_profile)==null?void 0:Ce.name)||((Fe=Be.referred_profile)==null?void 0:Fe.email)||"New agent",Ge=new Intl.DateTimeFormat("en-US",{timeZone:"America/New_York",month:"short",day:"numeric",year:"numeric"}).format(new Date(Be.signed_up_at));return e.jsxs("div",{className:"py-3 flex items-center justify-between gap-3",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"font-medium truncate",children:Ne}),e.jsxs("div",{className:"text-xs text-muted-foreground",children:["Joined ",Ge]})]}),Be.status==="qualified"?e.jsxs(We,{className:"bg-emerald-100 text-emerald-700 border-emerald-200 hover:bg-emerald-100",children:[e.jsx(Hr,{className:"h-3 w-3 mr-1"})," Paid · +",u+m," pts"]}):e.jsxs(We,{variant:"secondary",children:[e.jsx(Xr,{className:"h-3 w-3 mr-1"})," Signed up · +",u," pts"]})]},Be.id)})})})]}),e.jsx(_e,{className:"bg-muted/30",children:e.jsxs(De,{className:"p-6",children:[e.jsxs("h3",{className:"font-semibold mb-3 flex items-center gap-2",children:[e.jsx(Cn,{className:"h-4 w-4 text-primary"})," How it works"]}),e.jsxs("ol",{className:"text-sm text-muted-foreground space-y-2 list-decimal list-inside",children:[e.jsx("li",{children:"Share your unique link with peers, mentees, or other agents."}),e.jsxs("li",{children:["They sign up — you instantly earn ",e.jsxs("strong",{className:"text-foreground",children:[u," points"]}),"."]}),e.jsxs("li",{children:["When they activate a paid plan, you earn another ",e.jsxs("strong",{className:"text-foreground",children:[m," points"]}),"."]}),e.jsxs("li",{children:["Redeem points in the ",e.jsx("a",{href:"/reward-store",className:"text-primary underline",children:"Reward Store"}),"."]})]})]})}),e.jsx(Wl,{className:"opacity-0"})]}),e.jsx(Bs,{open:A,onOpenChange:T,children:e.jsxs(Fs,{className:"sm:max-w-2xl max-h-[90vh] overflow-y-auto",children:[e.jsxs(qs,{children:[e.jsxs($s,{className:"flex items-center gap-2",children:[e.jsx(Rr,{className:"h-5 w-5 text-primary"})," Send referral invites via Gmail"]}),e.jsxs(Ar,{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(re,{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(Be=>e.jsxs(We,{variant:"secondary",className:"gap-1 pr-1",children:[Be,e.jsx("button",{type:"button",onClick:()=>Se(Be),className:"hover:bg-muted-foreground/20 rounded-full p-0.5","aria-label":`Remove ${Be}`,children:e.jsx(hr,{className:"h-3 w-3"})})]},Be)),e.jsx("input",{type:"email",value:P,onChange:Be=>I(Be.target.value),onKeyDown:Be=>{Be.key==="Enter"||Be.key===","||Be.key===" "?(Be.preventDefault(),be()):Be.key==="Backspace"&&!P&&M.length>0&&L(M.slice(0,-1))},onBlur:()=>P.trim()&&be(),onPaste:Be=>{const Ne=Be.clipboardData.getData("text");/[\s,;]/.test(Ne)&&(Be.preventDefault(),be(Ne))},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(re,{htmlFor:"email-subject",children:"Subject"}),e.jsx(we,{id:"email-subject",value:V,onChange:Be=>W(Be.target.value),placeholder:"Subject line"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{htmlFor:"personal-note",children:"Your personal note"}),e.jsx(Ws,{id:"personal-note",value:z,onChange:Be=>$(Be.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(re,{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:Me(z),className:"w-full h-[420px] bg-white"})]})]})]}),e.jsxs(Cr,{children:[e.jsx(B,{variant:"outline",onClick:()=>T(!1),disabled:G,children:"Cancel"}),e.jsxs(B,{onClick:Re,disabled:G,children:[e.jsx(Rr,{className:"h-4 w-4 mr-2"}),G?"Sending…":`Send${M.length>0?` to ${M.length}`:""}`]})]})]})})]})}const D9t=()=>{const{user:s}=Ls(),t=as(),n=mt({queryKey:["smart-presentations",s==null?void 0:s.id],queryFn:async()=>{const{data:d,error:u}=await H.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=mt({queryKey:["smart-presentation-templates",s==null?void 0:s.id],queryFn:async()=>{const{data:d,error:u}=await H.from("smart_presentation_templates").select("*").eq("is_active",!0).order("created_at",{ascending:!0});if(u)throw u;return d||[]},enabled:!!s}),a=_t({mutationFn:async d=>{const{data:u,error:h}=await H.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=_t({mutationFn:async({id:d,...u})=>{const{data:h,error:m}=await H.from("smart_presentations").update(u).eq("id",d).select().single();if(m)throw m;return h},onSuccess:()=>{t.invalidateQueries({queryKey:["smart-presentations"]})}}),l=_t({mutationFn:async d=>{const{data:u,error:h}=await H.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"]}),ie.success("Presentation published!")}}),o=_t({mutationFn:async d=>{const{error:u}=await H.from("smart_presentations").update({status:"archived"}).eq("id",d);if(u)throw u},onSuccess:()=>{t.invalidateQueries({queryKey:["smart-presentations"]}),ie.success("Presentation archived")}}),c=_t({mutationFn:async d=>{const{error:u}=await H.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"]}),ie.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}},z4n=()=>{const s=tr(),{presentations:t,isLoading:n,archivePresentation:r,saveAsTemplate:a}=D9t(),i=o=>o.status==="draft"?e.jsx(We,{variant:"outline",className:"text-xs",children:"Draft"}):o.view_count>1?e.jsx(We,{className:"text-xs bg-emerald-100 text-emerald-700 border-emerald-200",children:"Revisited"}):o.view_count===1?e.jsx(We,{className:"text-xs bg-blue-100 text-blue-700 border-blue-200",children:"Opened"}):e.jsx(We,{variant:"secondary",className:"text-xs",children:"Not Opened"}),l=o=>{const c=`https://presentations.relevelup.com/${o}`;navigator.clipboard.writeText(c),ie.success("Link copied!")};return e.jsx(Qs,{title:"Smart Presentations",children:e.jsxs("div",{className:"max-w-5xl mx-auto space-y-6",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("div",{className:"flex items-center gap-2",children:e.jsx("h1",{className:"text-2xl font-serif font-bold text-foreground",children:"Smart Presentations"})}),e.jsx("p",{className:"text-muted-foreground mt-1",children:"Create personalized, video-first presentations for your clients"})]}),e.jsxs(B,{onClick:()=>s("/mission-control/presentations/new"),className:"gap-2",children:[e.jsx(nn,{className:"h-4 w-4"}),"Create Presentation"]})]}),n?e.jsx("div",{className:"space-y-3",children:[1,2,3].map(o=>e.jsx(xn,{className:"h-20 w-full rounded-lg"},o))}):t.length===0?e.jsx(_e,{children:e.jsxs(De,{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(ab,{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(nn,{className:"h-4 w-4"}),"Create Your First Presentation"]})]})}):e.jsx("div",{className:"space-y-3",children:t.map(o=>e.jsx(_e,{className:"hover:shadow-sm transition-shadow",children:e.jsx(De,{className:"p-4",children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx("div",{className:"w-10 h-10 rounded-lg bg-primary/10 flex items-center justify-center shrink-0",children:e.jsx(Wr,{className:"h-5 w-5 text-primary"})}),e.jsx("div",{className:"min-w-0 flex-1",children:e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-start sm:justify-between gap-2",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsx("h3",{className:"font-semibold truncate",children:o.title}),i(o)]}),e.jsxs("div",{className:"flex items-center gap-x-3 gap-y-0.5 flex-wrap text-sm text-muted-foreground mt-0.5",children:[o.client_name&&e.jsx("span",{children:o.client_name}),e.jsxs("span",{children:["Created ",Js(new Date(o.created_at),"MMM d, yyyy")]}),o.view_count>0&&e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(da,{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(Pa,{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(qd,{children:[e.jsx(Vd,{asChild:!0,children:e.jsx(B,{variant:"ghost",size:"icon",className:"h-8 w-8",children:e.jsx(Ev,{className:"h-4 w-4"})})}),e.jsxs(Ld,{align:"end",children:[o.status==="published"&&o.share_token&&e.jsxs(ba,{onClick:()=>window.open(`https://presentations.relevelup.com/${o.share_token}`,"_blank"),children:[e.jsx(Tr,{className:"h-4 w-4 mr-2"}),"Preview Link"]}),e.jsxs(ba,{onClick:()=>a.mutate(o),children:[e.jsx(Wr,{className:"h-4 w-4 mr-2"}),"Save as Template"]}),e.jsxs(ba,{onClick:()=>r.mutate(o.id),className:"text-destructive",children:[e.jsx(xg,{className:"h-4 w-4 mr-2"}),"Archive"]})]})]})]})]})})]})})},o.id))})]})})},hgt={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."}]},B4n=[{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 $4n(s){const t=hgt[s];if(t)return t;const n=s.toLowerCase();for(const[r,a]of Object.entries(hgt))if(n.includes(r.toLowerCase())||r.toLowerCase().includes(n))return a;return B4n}function U4n({sectionTitle:s,contactId:t,onVideoReady:n}){const[r,a]=N.useState(!1),[i,l]=N.useState("script"),[o,c]=N.useState(0),[d,u]=N.useState(0),{canRecord:h}=dIt(),m=G3(),[f,g]=N.useState(""),[y,x]=N.useState(!1),[_,b]=N.useState(!0),[k,A]=N.useState(!1),[T,P]=N.useState(null),I=$4n(s),M=()=>{l("script"),c(0),u(0),g(""),x(!1),b(!0),A(!1),P(null)},L=G=>{!G&&(i==="uploading"||i==="processing")||(a(G),G||M())},z=G=>{P(G),g(I[G].text),x(!1)},$=()=>{l("record"),b(f.trim().length>0)},V=()=>{g(""),b(!1),l("record")},W=N.useCallback(async(G,X)=>{l("uploading");try{const te=s||"Presentation Video",{videoId:ne,uploadUrl:me,libraryId:ue}=await sO(te),{apiKey:ce}=await nO(ne),ae=new XMLHttpRequest;ae.upload.onprogress=be=>{be.lengthComputable&&c(be.loaded/be.total*100)},await new Promise((be,Se)=>{ae.onload=()=>ae.status>=200&&ae.status<300?be():Se(new Error("Upload failed")),ae.onerror=()=>Se(new Error("Upload failed")),ae.open("PUT",me),ae.setRequestHeader("AccessKey",ce),ae.send(G)}),l("processing");let he=0;const xe=Date.now(),ve=9e4;let ge=null;for(;he<4;){if(await new Promise(Se=>setTimeout(Se,3e3)),Date.now()-xe>ve){const Se=G.size/1048576,Ie=`https://iframe.mediadelivery.net/embed/${ue}/${ne}?responsive=true`;await m.mutateAsync({bunny_video_id:ne,playback_url:Ie,file_size_mb:Se,title:te,contact_id:t||void 0,status:"processing",touch_type:"presentation"}),n(Ie),ie.success("Video saved — still encoding. It will be ready shortly."),l("done"),setTimeout(()=>a(!1),1500);return}const be=await F5(ne);if(he=be.status,u(be.encodeProgress||0),he===4)ge={playbackUrl:be.directPlayUrl,thumbnailUrl:be.thumbnailUrl,previewUrl:be.previewUrl||null,duration:be.length||X,fileSizeMb:(be.storageSize||G.size)/(1024*1024)};else if(he===5||he===6)throw new Error("Video processing failed")}if(!ge)throw new Error("No video data");await m.mutateAsync({bunny_video_id:ne,contact_id:t||void 0,playback_url:ge.playbackUrl,thumbnail_url:ge.thumbnailUrl,preview_url:ge.previewUrl,duration_seconds:ge.duration,file_size_mb:ge.fileSizeMb,title:te,status:"ready",touch_type:"presentation"}),n(ge.playbackUrl),ie.success("Video recorded, saved to library & attached!"),l("done"),setTimeout(()=>a(!1),1500)}catch(te){console.error("Recording upload error:",te),ie.error("Failed to process video. Please try again."),l("record")}},[s,t,n,m]);return e.jsxs(Bs,{open:r,onOpenChange:L,children:[e.jsx(Ao,{asChild:!0,children:e.jsxs(B,{variant:"outline",size:"sm",className:"gap-1.5 shrink-0",title:"Record a video",children:[e.jsx(na,{className:"h-3.5 w-3.5"}),"Record"]})}),e.jsxs(Fs,{className:"max-w-2xl max-h-[90vh] overflow-y-auto !top-[5%] !translate-y-0 sm:!top-[5%] sm:!translate-y-0",children:[e.jsx(qs,{children:e.jsxs($s,{children:[i==="script"&&`Prepare your script for "${s}"`,i==="record"&&`Record video for "${s}"`,i==="uploading"&&"Uploading...",i==="processing"&&"Processing...",i==="done"&&"Done!"]})}),i==="script"&&e.jsxs("div",{className:"space-y-4",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Choose a starter script below, edit it to make it yours, or skip and speak freely."}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("p",{className:"text-xs font-medium text-muted-foreground uppercase tracking-wide",children:"Starter Scripts"}),e.jsx("div",{className:"grid gap-2",children:I.map((G,X)=>e.jsxs("button",{onClick:()=>z(X),className:Ot("text-left p-3 rounded-lg border transition-all hover:bg-accent/50",T===X?"border-primary bg-primary/5 ring-1 ring-primary":"border-border"),children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[e.jsx(Wr,{className:"h-3.5 w-3.5 text-primary shrink-0"}),e.jsx("span",{className:"text-sm font-medium",children:G.label})]}),e.jsx("p",{className:"text-xs text-muted-foreground line-clamp-2 ml-5.5",children:G.text})]},X))})]}),f&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("p",{className:"text-xs font-medium text-muted-foreground uppercase tracking-wide",children:"Your Script"}),!y&&e.jsxs(B,{variant:"ghost",size:"sm",onClick:()=>x(!0),className:"h-7 text-xs gap-1",children:[e.jsx(Ja,{className:"h-3 w-3"}),"Edit"]})]}),y?e.jsx(Ws,{value:f,onChange:G=>g(G.target.value),rows:5,placeholder:"Type your script here...",className:"text-sm"}):e.jsx("div",{className:"p-3 rounded-lg bg-muted/50 text-sm text-foreground leading-relaxed",children:f})]}),!f&&e.jsxs("div",{className:"space-y-2",children:[e.jsx("p",{className:"text-xs font-medium text-muted-foreground uppercase tracking-wide",children:"Or Write Your Own"}),e.jsx(Ws,{value:f,onChange:G=>{g(G.target.value),P(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:$,disabled:!1,children:f.trim()?"Continue with Script":"Continue Without Script"})]})]}),!h&&i==="record"?e.jsxs("div",{className:"flex flex-col items-center gap-3 py-8 text-center",children:[e.jsx(xd,{className:"h-10 w-10 text-destructive"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"You've reached your video storage limit. Delete some videos to free up space."})]}):i==="record"?e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"Record up to 5 minutes. Saved to your library & auto-attached."}),f.trim()&&e.jsxs(B,{variant:"ghost",size:"sm",onClick:()=>b(!_),className:"h-7 text-xs gap-1",children:[_?e.jsx(V0,{className:"h-3 w-3"}):e.jsx(da,{className:"h-3 w-3"}),_?"Hide Script":"Show Script"]})]}),e.jsx(oO,{maxDurationSeconds:600,onRecordingComplete:W,onRecordingStateChange:A,onError:G=>ie.error(G),teleprompterContent:f.trim()?e.jsx(qWe,{text:f,isVisible:_,onToggleVisibility:()=>b(!_),isRecording:k,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(us,{className:"h-10 w-10 animate-spin text-primary"}),e.jsxs("div",{className:"w-full max-w-xs space-y-2",children:[e.jsx(ro,{value:o,className:"h-2"}),e.jsxs("p",{className:"text-sm text-muted-foreground text-center",children:["Uploading... ",Math.round(o),"%"]})]})]}):i==="processing"?e.jsxs("div",{className:"flex flex-col items-center gap-4 py-12",children:[e.jsx(us,{className:"h-10 w-10 animate-spin text-primary"}),e.jsxs("div",{className:"w-full max-w-xs space-y-2",children:[e.jsx(ro,{value:d,className:"h-2"}),e.jsxs("p",{className:"text-sm text-muted-foreground text-center",children:["Processing... ",Math.round(d),"%"]}),e.jsx("p",{className:"text-xs text-muted-foreground text-center",children:"This usually takes less than a minute"})]})]}):i==="done"?e.jsxs("div",{className:"flex flex-col items-center gap-3 py-12",children:[e.jsx(Po,{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 q4n({sectionTitle:s,contactId:t,onVideoReady:n}){const[r,a]=N.useState(!1),[i,l]=N.useState(null),[o,c]=N.useState("idle"),[d,u]=N.useState(0),h=N.useRef(null),m=G3(),{data:f}=VCe(),g=(f==null?void 0:f.total_storage_mb)||0,x=((f==null?void 0:f.max_storage_mb)||1024)-g,_=()=>{l(null),c("idle"),u(0)},b=I=>{!I&&o!=="idle"&&o!=="done"||(a(I),I||_())},k=I=>{var z;const M=(z=I.target.files)==null?void 0:z[0];if(!M)return;if(!M.type.startsWith("video/")){ie.error("Please select a video file");return}const L=M.size/(1024*1024);if(L>500){ie.error("Video file must be less than 500MB");return}if(L>x){ie.error(`Not enough storage. You have ${x.toFixed(1)} MB remaining.`);return}l(M)},A=N.useCallback(async()=>{if(i){c("creating"),u(0);try{const I=s||i.name,{data:M,error:L}=await H.functions.invoke("bunny-upload",{body:{action:"create",title:I,isAgentVideo:!0}});if(L)throw new Error(L.message);const{videoId:z,libraryId:$}=M;c("uploading");const{data:V,error:W}=await H.functions.invoke("bunny-upload",{body:{action:"upload-url",videoId:z,isAgentVideo:!0}});if(W)throw new Error(W.message);await new Promise((te,ne)=>{const me=new XMLHttpRequest;me.upload.addEventListener("progress",ue=>{ue.lengthComputable&&u(Math.round(ue.loaded/ue.total*100))}),me.addEventListener("load",()=>me.status>=200&&me.status<300?te():ne(new Error(`Upload failed (${me.status})`))),me.addEventListener("error",()=>ne(new Error("Upload failed"))),me.open("PUT",V.uploadUrl),me.setRequestHeader("AccessKey",V.apiKey),me.send(i)}),c("processing");const G=i.size/(1024*1024),X=`https://iframe.mediadelivery.net/embed/${$}/${z}`;await m.mutateAsync({bunny_video_id:z,playback_url:X,file_size_mb:G,title:I,contact_id:t||void 0,status:"processing",touch_type:"presentation"}),n(X),c("done"),ie.success("Video uploaded & attached to section!"),setTimeout(()=>a(!1),1200)}catch(I){console.error("Upload error:",I),ie.error(I instanceof Error?I.message:"Failed to upload video"),c("idle")}}},[i,s,t,n,m]),T=()=>{switch(o){case"creating":return"Preparing upload...";case"uploading":return`Uploading... ${d}%`;case"processing":return"Saving video...";case"done":return"Done!";default:return""}},P=o!=="idle"&&o!=="done";return e.jsxs(Bs,{open:r,onOpenChange:b,children:[e.jsx(Ao,{asChild:!0,children:e.jsxs(B,{variant:"outline",size:"sm",className:"gap-1.5 shrink-0",title:"Upload a video file",children:[e.jsx(ni,{className:"h-3.5 w-3.5"}),"Upload"]})}),e.jsxs(Fs,{className:"sm:max-w-md",children:[e.jsx(qs,{children:e.jsxs($s,{children:['Upload Video for "',s,'"']})}),e.jsxs("div",{className:"space-y-4 py-2",children:[i?e.jsxs("div",{className:"flex items-center gap-3 p-3 bg-muted rounded-lg",children:[e.jsx(na,{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"]})]}),!P&&e.jsx(B,{variant:"ghost",size:"icon",className:"h-8 w-8",onClick:()=>l(null),children:e.jsx(hr,{className:"h-4 w-4"})})]}):e.jsxs("div",{className:"border-2 border-dashed border-muted-foreground/25 rounded-lg p-8 text-center cursor-pointer hover:border-primary/50 transition-colors",onClick:()=>{var I;return(I=h.current)==null?void 0:I.click()},children:[e.jsx(ni,{className:"h-8 w-8 mx-auto text-muted-foreground mb-2"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Click to select a video file"}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:"MP4, MOV, WebM (max 500MB)"})]}),e.jsx("input",{ref:h,type:"file",accept:"video/*",className:"hidden",onChange:k,disabled:P}),P&&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(us,{className:"h-4 w-4 animate-spin"}),e.jsx("span",{children:T()})]}),e.jsx(ro,{value:o==="uploading"?d:o==="processing"?100:10})]})]}),e.jsxs(Cr,{children:[e.jsx(B,{variant:"outline",onClick:()=>b(!1),disabled:P,children:"Cancel"}),e.jsx(B,{onClick:A,disabled:!i||P,children:P?e.jsxs(e.Fragment,{children:[e.jsx(us,{className:"h-4 w-4 mr-2 animate-spin"}),"Uploading..."]}):e.jsxs(e.Fragment,{children:[e.jsx(ni,{className:"h-4 w-4 mr-2"}),"Upload & Attach"]})})]})]})]})}const mgt=[{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"}],pgt=()=>{const s=tr(),{id:t}=uo(),{user:n}=Ls(),{templates:r,templatesLoading:a,createPresentation:i,updatePresentation:l,publishPresentation:o}=D9t(),{isGmailConnected:c,gmailEmail:d}=_f(),[u,h]=N.useState(!1),[m,f]=N.useState("client"),[g,y]=N.useState(!1),[x,_]=N.useState(""),[b,k]=N.useState([]),[A,T]=N.useState(!1),[P,I]=N.useState(null),[M,L]=N.useState(!1),[z,$]=N.useState(""),[V,W]=N.useState(""),[G,X]=N.useState(""),[te,ne]=N.useState("buyer"),[me,ue]=N.useState(""),[ce,ae]=N.useState(null),[he,xe]=N.useState(""),[ve,ge]=N.useState([]),[be,Se]=N.useState("schedule_call"),[Ie,Me]=N.useState("Schedule a Call"),[Re,Be]=N.useState(""),[Ne,Ge]=N.useState(""),[Ce,Fe]=N.useState(null),[Ae,Xe]=N.useState(t||null),[$e,Ye]=N.useState(null),[Je,Ke]=N.useState(!1),st=async(Nt,ms)=>{if(!n)return;const Ys=5*1024*1024;if(Nt.size>Ys){ie.error("Image must be under 5MB");return}if(!Nt.type.startsWith("image/")){ie.error("Please upload an image file");return}Fe(ms);try{const It=Nt.name.split(".").pop()||"jpg",Ds=`${n.id}/${Date.now()}.${It}`,{error:As}=await H.storage.from("listing-photos").upload(Ds,Nt);if(As)throw As;const{data:{publicUrl:Hs}}=H.storage.from("listing-photos").getPublicUrl(Ds);Yt(ms,{image_url:Hs}),ie.success("Image uploaded")}catch{ie.error("Failed to upload image")}finally{Fe(null)}};N.useEffect(()=>{t&&rt(t)},[t]);const rt=async Nt=>{const{data:ms,error:Ys}=await H.from("smart_presentations").select("*").eq("id",Nt).single();if(Ys||!ms)return;const It=ms;if(y(!0),xe(It.title),$(It.client_name||""),ue(It.property_address||""),ge(It.sections||[]),Se(It.cta_type||"schedule_call"),Me(It.cta_label||"Schedule a Call"),Be(It.cta_url||""),Ge(It.heading||""),Ye(It.share_token),Ke(It.status==="published"),Xe(It.id),f("builder"),It.contact_id){const{data:Ds}=await H.from("innercircle_contacts").select("id, first_name, last_name, email, phone").eq("id",It.contact_id).maybeSingle();Ds&&(I(Ds),W(Ds.email||""),X(Ds.phone||""))}};N.useEffect(()=>{if(!n||x.length<1){k([]);return}const Nt=setTimeout(async()=>{T(!0);const{data:ms}=await H.from("innercircle_contacts").select("id, first_name, last_name, email, phone, lead_source").eq("owner_user_id",n.id).or(`first_name.ilike.%${x}%,last_name.ilike.%${x}%,email.ilike.%${x}%`).limit(10);k(ms||[]),T(!1)},300);return()=>clearTimeout(Nt)},[x,n]);const Ze=Nt=>{I(Nt),$(`${Nt.first_name} ${Nt.last_name||""}`.trim()),W(Nt.email||""),X(Nt.phone||""),L(!1)},ht=async()=>{if(!z.trim()){ie.error("Client name is required");return}const Nt=z.trim().split(" "),ms=Nt[0],Ys=Nt.slice(1).join(" ")||null,{data:It,error:Ds}=await H.from("innercircle_contacts").insert({owner_user_id:n.id,first_name:ms,last_name:Ys,email:V||null,phone:G||null,lead_source:"Smart Presentation"}).select().single();if(Ds){ie.error("Failed to create client");return}I(It),ie.success("Client created & saved to Agent OS"),f("template")},Bt=Nt=>{ae(Nt);const ms=(Nt.sections||[]).map(Ys=>({...Ys,is_visible:!0,video_url:"",text:""}));if(ge(ms),xe(Nt.name+(z?` for ${z}`:"")),Nt.cta_config){const Ys=Nt.cta_config;Se(Ys.type||"schedule_call"),Me(Ys.label||"Schedule a Call")}f("builder")},Ct=()=>{ge([{title:"Welcome",description:"A personal welcome",type:"video",icon:"👋",is_visible:!0}]),xe(z?`Presentation for ${z}`:"New Presentation"),f("builder")},Yt=(Nt,ms)=>{ge(Ys=>Ys.map((It,Ds)=>Ds===Nt?{...It,...ms}:It))},Kt=Nt=>{Yt(Nt,{is_visible:!ve[Nt].is_visible})},Xs=()=>{ge(Nt=>[...Nt,{title:"New Section",description:"",type:"video",icon:"📝",is_visible:!0}])},zs=Nt=>{ge(ms=>ms.filter((Ys,It)=>It!==Nt))},Vt=async()=>{if(!he.trim()){ie.error("Title is required");return}try{if(Ae){const Nt=await l.mutateAsync({id:Ae,title:he,sections:ve,client_name:z,property_address:me||null,cta_type:be,cta_label:Ie,cta_url:Re||null,heading:Ne||null});ie.success("Saved")}else{const Nt=await i.mutateAsync({title:he,contact_id:(P==null?void 0:P.id)||void 0,client_name:z,property_address:me||void 0,template_id:(ce==null?void 0:ce.id)||void 0,sections:ve,cta_type:be,cta_label:Ie,cta_url:Re||void 0,heading:Ne||void 0});Xe(Nt.id),Ye(Nt.share_token),ie.success("Presentation created!")}}catch(Nt){console.error("Failed to save presentation:",Nt);const ms=(Nt==null?void 0:Nt.message)||(Nt==null?void 0:Nt.toString())||"Unknown error";ie.error(`Failed to save: ${ms}`)}},At=async()=>{try{await Vt();const Nt=Ae;if(Nt){const ms=await o.mutateAsync(Nt);Ye(ms.share_token),Ke(!0),f("share")}}catch(Nt){console.error("Failed to publish presentation:",Nt),ie.error(`Failed to publish: ${(Nt==null?void 0:Nt.message)||"Unknown error"}`)}},Os=$e?`https://presentations.relevelup.com/${$e}`:"";return e.jsx(Qs,{title:"Smart Presentations",children:e.jsxs("div",{className:"max-w-4xl mx-auto space-y-6",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(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:g?"Edit Presentation":"Create Smart Presentation"}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:[m==="client"&&"Who is this presentation for?",m==="template"&&"Choose a starting template",m==="builder"&&"Customize your presentation",m==="share"&&"Share with your client"]})]})]}),!g&&e.jsx("div",{className:"flex items-center gap-2",children:["client","template","builder","share"].map((Nt,ms)=>e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:Ot("w-8 h-8 rounded-full flex items-center justify-center text-sm font-medium transition-colors",m===Nt?"bg-primary text-primary-foreground":ms<["client","template","builder","share"].indexOf(m)?"bg-emerald-100 text-emerald-700":"bg-muted text-muted-foreground"),children:ms<["client","template","builder","share"].indexOf(m)?e.jsx(pa,{className:"h-4 w-4"}):ms+1}),e.jsx("span",{className:"text-sm font-medium capitalize hidden sm:inline",children:Nt}),ms<3&&e.jsx("div",{className:"w-8 h-px bg-border"})]},Nt))}),m==="client"&&e.jsxs("div",{className:"space-y-6",children:[e.jsxs("button",{onClick:()=>{I(null),$(""),W(""),X(""),L(!1),f("template")},className:"w-full group flex items-center justify-between gap-4 rounded-xl border border-dashed border-primary/30 bg-primary/5 hover:bg-primary/10 transition-all p-4",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"h-10 w-10 rounded-full bg-primary/10 flex items-center justify-center shrink-0",children:e.jsx(Rr,{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(vi,{className:"h-4 w-4 text-muted-foreground group-hover:text-primary transition-colors shrink-0"})]}),e.jsxs("div",{className:"grid gap-6 md:grid-cols-2",children:[e.jsxs(_e,{children:[e.jsx(zt,{className:"pb-3",children:e.jsxs(qt,{className:"text-base flex items-center gap-2",children:[e.jsx(Gr,{className:"h-4 w-4 text-muted-foreground"}),"Select Existing Client"]})}),e.jsxs(De,{className:"space-y-3",children:[e.jsxs("div",{className:"relative",children:[e.jsx(Gr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(we,{placeholder:"Search by name or email...",value:x,onChange:Nt=>_(Nt.target.value),className:"pl-10"})]}),e.jsxs("div",{className:"space-y-2 max-h-56 overflow-y-auto",children:[A&&e.jsx(xn,{className:"h-12 w-full"}),b.map(Nt=>e.jsxs("button",{onClick:()=>Ze(Nt),className:Ot("w-full text-left p-3 rounded-lg border transition-colors",(P==null?void 0:P.id)===Nt.id?"border-primary bg-primary/5":"border-border hover:border-primary/50"),children:[e.jsxs("p",{className:"font-medium text-sm",children:[Nt.first_name," ",Nt.last_name]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:Nt.email||Nt.phone||"No contact info"})]},Nt.id)),!x&&e.jsx("p",{className:"text-sm text-muted-foreground text-center py-6",children:"Start typing to search your contacts"}),x&&b.length===0&&!A&&e.jsx("p",{className:"text-sm text-muted-foreground text-center py-6",children:"No clients found"})]}),P&&e.jsxs(B,{onClick:()=>f("template"),className:"w-full gap-2",children:["Continue with ",P.first_name,e.jsx(vi,{className:"h-4 w-4"})]})]})]}),e.jsxs(_e,{children:[e.jsx(zt,{className:"pb-3",children:e.jsxs(qt,{className:"text-base flex items-center gap-2",children:[e.jsx(Yl,{className:"h-4 w-4 text-muted-foreground"}),"Add New Client"]})}),e.jsxs(De,{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(re,{className:"text-xs",children:"Name *"}),e.jsx(we,{value:z,onChange:Nt=>{$(Nt.target.value),L(!0),I(null)},placeholder:"Sarah & Mike Johnson"})]}),e.jsxs("div",{children:[e.jsx(re,{className:"text-xs",children:"Email"}),e.jsx(we,{value:V,onChange:Nt=>W(Nt.target.value),placeholder:"Optional",type:"email"})]}),e.jsxs("div",{children:[e.jsx(re,{className:"text-xs",children:"Phone"}),e.jsx(we,{value:G,onChange:Nt=>X(Nt.target.value),placeholder:"Optional"})]}),e.jsxs("div",{children:[e.jsx(re,{className:"text-xs",children:"Client Type"}),e.jsxs(Ns,{value:te,onValueChange:ne,children:[e.jsx(ws,{children:e.jsx(ks,{})}),e.jsxs(js,{children:[e.jsx(nt,{value:"buyer",children:"Buyer"}),e.jsx(nt,{value:"seller",children:"Seller"}),e.jsx(nt,{value:"recruit",children:"Recruit"}),e.jsx(nt,{value:"other",children:"Other"})]})]})]}),e.jsxs("div",{children:[e.jsx(re,{className:"text-xs",children:"Property Address"}),e.jsx(we,{value:me,onChange:Nt=>ue(Nt.target.value),placeholder:"Optional"})]})]}),M&&z&&e.jsxs(B,{onClick:ht,className:"w-full gap-2",children:["Create Client & Continue",e.jsx(vi,{className:"h-4 w-4"})]})]})]})]})]}),m==="template"&&e.jsxs("div",{className:"space-y-6",children:[e.jsxs(ya,{defaultValue:"system",children:[e.jsxs(va,{children:[e.jsx(ls,{value:"mine",children:"My Core Templates"}),e.jsx(ls,{value:"system",children:"LevelUp Smart Templates"}),e.jsx(ls,{value:"blank",children:"+ Start Blank"})]}),e.jsx(_s,{value:"mine",className:"mt-4",children:a?e.jsx("div",{className:"grid grid-cols-2 gap-4",children:[1,2].map(Nt=>e.jsx(xn,{className:"h-32"},Nt))}):e.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-4",children:r.filter(Nt=>!Nt.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(Nt=>!Nt.is_system).map(Nt=>e.jsx(fgt,{template:Nt,onSelect:Bt},Nt.id))})}),e.jsx(_s,{value:"system",className:"mt-4",children:e.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-4",children:r.filter(Nt=>Nt.is_system).map(Nt=>e.jsx(fgt,{template:Nt,onSelect:Bt},Nt.id))})}),e.jsx(_s,{value:"blank",className:"mt-4",children:e.jsx(_e,{children:e.jsxs(De,{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:Ct,children:"Start from Scratch"})]})})})]}),e.jsxs(B,{variant:"outline",onClick:()=>f("client"),className:"gap-2",children:[e.jsx(ka,{className:"h-4 w-4"}),"Back"]})]}),m==="builder"&&e.jsxs("div",{className:"space-y-6",children:[e.jsx(_e,{children:e.jsxs(De,{className:"pt-6 space-y-4",children:[e.jsxs("div",{children:[e.jsx(re,{children:"Presentation Title"}),e.jsx(we,{value:he,onChange:Nt=>xe(Nt.target.value)})]}),e.jsxs("div",{children:[e.jsx(re,{children:"Page Heading"}),e.jsx(we,{value:Ne,onChange:Nt=>Ge(Nt.target.value),placeholder:z?`Welcome, ${z}!`:"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(re,{children:"Client Name"}),e.jsx(we,{value:z,onChange:Nt=>$(Nt.target.value)})]}),e.jsxs("div",{children:[e.jsx(re,{children:"Property Address"}),e.jsx(we,{value:me,onChange:Nt=>ue(Nt.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:Xs,children:"+ Add Section"})]}),e.jsx("div",{className:"space-y-3",children:ve.map((Nt,ms)=>e.jsx(_e,{className:Ot(!Nt.is_visible&&"opacity-50"),children:e.jsx(De,{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(Mp,{className:"h-4 w-4 text-muted-foreground cursor-grab"}),e.jsx("span",{className:"text-lg",children:Nt.icon})]}),e.jsxs("div",{className:"flex-1 space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(we,{value:Nt.title,onChange:Ys=>Yt(ms,{title:Ys.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:()=>Kt(ms),children:Nt.is_visible?e.jsx(da,{className:"h-4 w-4"}):e.jsx(V0,{className:"h-4 w-4"})}),e.jsx(B,{variant:"ghost",size:"icon",onClick:()=>zs(ms),className:"text-destructive hover:text-destructive",children:e.jsx(qn,{className:"h-4 w-4"})})]})]}),e.jsx(we,{value:Nt.description||"",onChange:Ys=>Yt(ms,{description:Ys.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(re,{className:"text-xs",children:"Video URL"}),e.jsx(we,{value:Nt.video_url||"",onChange:Ys=>Yt(ms,{video_url:Ys.target.value}),placeholder:"Paste a YouTube or video URL...",className:"text-sm"})]}),e.jsx(U4n,{sectionTitle:Nt.title,contactId:P==null?void 0:P.id,onVideoReady:Ys=>Yt(ms,{video_url:Ys})}),e.jsx(q4n,{sectionTitle:Nt.title,contactId:P==null?void 0:P.id,onVideoReady:Ys=>Yt(ms,{video_url:Ys})}),e.jsx(tO,{userId:n==null?void 0:n.id,onSelect:Ys=>Yt(ms,{video_url:Ys})})]}),e.jsxs("div",{children:[e.jsx(re,{className:"text-xs",children:"Image (optional — shown if no video is set)"}),Nt.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:Nt.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:()=>Yt(ms,{image_url:""}),children:e.jsx(hr,{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:[Ce===ms?e.jsx(us,{className:"h-4 w-4 animate-spin text-muted-foreground"}):e.jsx(Gv,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{className:"text-sm text-muted-foreground",children:Ce===ms?"Uploading...":"Click to upload an image"}),e.jsx("input",{type:"file",accept:"image/*",className:"hidden",disabled:Ce===ms,onChange:Ys=>{var Ds;const It=(Ds=Ys.target.files)==null?void 0:Ds[0];It&&st(It,ms),Ys.target.value=""}})]})]}),e.jsxs("div",{children:[e.jsx(re,{className:"text-xs",children:"Text (optional)"}),e.jsx(yN,{content:Nt.text||"",onChange:Ys=>Yt(ms,{text:Ys}),placeholder:"Add supporting text...",minHeight:"80px",compact:!0})]})]})]})})},ms))})]}),e.jsxs(_e,{children:[e.jsx(zt,{children:e.jsx(qt,{className:"text-base",children:"Call to Action"})}),e.jsxs(De,{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(re,{children:"CTA Type"}),e.jsxs(Ns,{value:be,onValueChange:Nt=>{Se(Nt);const ms=mgt.find(Ys=>Ys.value===Nt);ms&&Me(ms.label)},children:[e.jsx(ws,{children:e.jsx(ks,{})}),e.jsx(js,{children:mgt.map(Nt=>e.jsx(nt,{value:Nt.value,children:Nt.label},Nt.value))})]})]}),e.jsxs("div",{children:[e.jsx(re,{children:"Button Label"}),e.jsx(we,{value:Ie,onChange:Nt=>Me(Nt.target.value)})]}),e.jsxs("div",{children:[e.jsxs(re,{children:["Link URL ",e.jsx("span",{className:"text-muted-foreground",children:"(optional — leave blank to show a lead capture form instead)"})]}),e.jsx(we,{value:Re,onChange:Nt=>Be(Nt.target.value),placeholder:"https://calendly.com/..."}),!Re&&e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:"Without a URL, clients will see a contact form — their info gets added to your contacts and you'll receive an email notification."})]})]})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[!g&&e.jsxs(B,{variant:"outline",onClick:()=>f("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:Vt,disabled:i.isPending||l.isPending,children:"Save Draft"}),e.jsxs(B,{onClick:At,disabled:o.isPending,className:"gap-2",children:[e.jsx(Rr,{className:"h-4 w-4"}),Je?"Update & Reshare":"Publish & Share"]})]})]})]}),m==="share"&&$e&&e.jsxs("div",{className:"space-y-6",children:[e.jsx(_e,{children:e.jsxs(De,{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(pa,{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 ",z||"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(we,{value:Os,readOnly:!0,className:"text-center font-mono text-sm"}),e.jsx(B,{onClick:()=>{navigator.clipboard.writeText(Os),ie.success("Link copied!")},children:e.jsx(Pa,{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 Nt=`Hi ${z||""}! I put together something for you — check it out: ${Os}`;navigator.clipboard.writeText(Nt),ie.success("Message copied!")},children:[e.jsx(xo,{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(he)}&body=${encodeURIComponent(`Hi ${(P==null?void 0:P.first_name)||(z==null?void 0:z.split(" ")[0])||""}, I put together a personalized presentation for you: ${Os} Looking forward to connecting!`)}`)},children:[e.jsx(mn,{className:"h-4 w-4"}),"Send Email"]})]}),c&&e.jsx(Y_,{open:u,onOpenChange:h,contact:P?{id:P.id,first_name:P.first_name,last_name:P.last_name,email:V||P.email||""}:V?{id:"",first_name:(z==null?void 0:z.split(" ")[0])||"",last_name:(z==null?void 0:z.split(" ").slice(1).join(" "))||"",email:V}:void 0,defaultSubject:he,defaultBody:`Hi ${(P==null?void 0:P.first_name)||(z==null?void 0:z.split(" ")[0])||""}, I put together a personalized presentation for you: ${Os} Looking forward to connecting!`,gmailEmail:d})]})}),e.jsxs("div",{className:"flex justify-between",children:[e.jsxs(B,{variant:"outline",onClick:()=>f("builder"),children:[e.jsx(ka,{className:"h-4 w-4 mr-2"}),"Edit Presentation"]}),e.jsx(B,{onClick:()=>s("/mission-control/presentations"),children:"Done"})]})]})]})})},fgt=({template:s,onSelect:t})=>e.jsx(_e,{className:"hover:shadow-sm transition-shadow",children:e.jsxs(De,{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(We,{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"})]})}),V4n=()=>{var y;const{shareToken:s}=uo(),[t,n]=N.useState(null),[r,a]=N.useState(!0),[i,l]=N.useState(0),[o,c]=N.useState(!1);N.useEffect(()=>(document.body.classList.add("presentation-page"),()=>{document.body.classList.remove("presentation-page")}),[]),N.useEffect(()=>{s&&d()},[s]);const d=async()=>{const{data:x,error:_}=await H.from("smart_presentations").select("*").eq("share_token",s).eq("status","published").single();if(_||!x){c(!0),a(!1);return}const{data:b}=await H.from("profiles").select("name, email, phone, avatar_url, title, brokerage_id").eq("id",x.owner_user_id).single();let k;if(b!=null&&b.brokerage_id){const{data:T}=await H.from("brokerages").select("name").eq("id",b.brokerage_id).single();k=(T==null?void 0:T.name)||void 0}let A=null;if(x.contact_id){const{data:T}=await H.from("innercircle_contacts").select("first_name, last_name, email, phone").eq("id",x.contact_id).single();A=T}n({...x,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:k,contact_name:A?[A.first_name,A.last_name].filter(Boolean).join(" "):void 0,contact_email:(A==null?void 0:A.email)||void 0,contact_phone:(A==null?void 0:A.phone)||void 0}),a(!1);try{await H.rpc("log_presentation_view",{p_presentation_id:x.id,p_section_index:0,p_cta_clicked:!1,p_ip_hash:null,p_user_agent:navigator.userAgent,p_referrer:document.referrer||null})}catch{}},u=async()=>{if(t){try{await H.rpc("log_presentation_view",{p_presentation_id:t.id,p_section_index:null,p_cta_clicked:!0,p_ip_hash:null,p_user_agent:navigator.userAgent,p_referrer:null})}catch{}t.cta_url&&window.open(t.cta_url,"_blank")}};if(r)return e.jsx("div",{className:"min-h-screen bg-white flex items-center justify-center",children:e.jsxs("div",{className:"space-y-4 w-full max-w-2xl px-4",children:[e.jsx(xn,{className:"h-12 w-3/4 mx-auto"}),e.jsx(xn,{className:"h-64 w-full"}),e.jsx(xn,{className:"h-8 w-1/2 mx-auto"})]})});if(o||!t)return e.jsx("div",{className:"min-h-screen bg-white flex items-center justify-center",children:e.jsxs("div",{className:"text-center",children:[e.jsx("h1",{className:"text-2xl font-bold mb-2",children:"Presentation Not Found"}),e.jsx("p",{className:"text-gray-500",children:"This presentation may have been removed or is no longer available."})]})});const h=t.sections.filter(x=>x.is_visible!==!1),m=h[i],f=x=>{const _=x.match(/(?:youtube\.com\/watch\?v=|youtu\.be\/)([a-zA-Z0-9_-]+)/);if(_)return`https://www.youtube.com/embed/${_[1]}?rel=0`;if(x.includes("iframe.mediadelivery.net/play/")){const A=x.replace("/play/","/embed/"),T=A.includes("?")?"&":"?";return`${A}${T}responsive=true`}if(x.includes("iframe.mediadelivery.net")){if(x.match(/\/embed\/(\d+)\/([a-f0-9-]+)/)){const T=x.includes("?")?"&":"?";return`${x}${T}responsive=true`}return""}const b=x.match(/loom\.com\/share\/([a-zA-Z0-9]+)/);if(b)return`https://www.loom.com/embed/${b[1]}`;const k=x.match(/video\.bunnycdn\.com\/play\/(\d+)\/([a-f0-9-]+)/);return k?`https://iframe.mediadelivery.net/embed/${k[1]}/${k[2]}?responsive=true`:x},g=!!((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&&f(m.video_url)?e.jsx("div",{className:"relative w-full rounded-xl overflow-hidden shadow-lg bg-gray-900",style:{paddingTop:"56.25%"},children:e.jsx("iframe",{src:f(m.video_url),className:"absolute inset-0 w-full h-full border-0",allow:"accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture",allowFullScreen:!0,loading:"lazy"})}):m!=null&&m.image_url?e.jsx("div",{className:"rounded-xl overflow-hidden shadow-lg",children:e.jsx("img",{src:m.image_url,alt:m.title,className:"w-full h-auto object-cover",loading:"lazy"})}):e.jsxs("div",{className:"aspect-video bg-gradient-to-br from-blue-50 to-slate-100 rounded-xl flex flex-col items-center justify-center shadow-lg",children:[e.jsx("span",{className:"text-5xl mb-3",children:m==null?void 0:m.icon}),e.jsx("h3",{className:"text-xl font-semibold text-gray-800",children:m==null?void 0:m.title}),e.jsx("p",{className:"text-gray-500 mt-1 text-sm",children:m==null?void 0:m.description})]}),(m==null?void 0:m.text)&&e.jsx("div",{className:"mt-4 p-4 bg-white rounded-lg border text-gray-700 text-sm leading-relaxed prose prose-sm max-w-none",dangerouslySetInnerHTML:{__html:m.text}})]}),e.jsx("div",{className:"md:col-span-2 space-y-3",children:h.map((x,_)=>e.jsx("button",{onClick:()=>l(_),className:Ot("w-full text-left p-4 rounded-xl border transition-all",i===_?"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(_+1).padStart(2,"0"),"."]}),e.jsxs("div",{children:[e.jsx("span",{className:"mr-2",children:x.icon}),e.jsx("span",{className:"font-semibold text-gray-900",children:x.title}),e.jsx("p",{className:"text-xs text-gray-500 mt-0.5",children:x.description})]})]})},_))})]}),e.jsxs("div",{className:"mt-12 max-w-md mx-auto bg-white rounded-2xl border border-gray-200 shadow-sm p-6 text-center",children:[t.owner_avatar&&e.jsx("img",{src:t.owner_avatar,alt:t.owner_name||"Agent",className:"h-20 w-20 rounded-full object-cover mx-auto mb-3 border-2 border-gray-100"}),e.jsx("h3",{className:"text-lg font-bold text-gray-900",children:t.owner_name}),t.owner_title&&e.jsx("p",{className:"text-sm text-gray-500",children:t.owner_title}),t.brokerage_name&&e.jsx("p",{className:"text-sm text-gray-500",children:t.brokerage_name}),e.jsxs("div",{className:"mt-3 flex flex-col items-center gap-1 text-sm text-gray-600",children:[t.owner_phone&&e.jsx("a",{href:`tel:${t.owner_phone}`,className:"hover:text-blue-600 transition-colors",children:t.owner_phone}),t.owner_email&&e.jsx("a",{href:`mailto:${t.owner_email}`,className:"hover:text-blue-600 transition-colors",children:t.owner_email})]})]}),t.cta_label&&e.jsxs("div",{className:"text-center mt-8 py-8",children:[e.jsx("h2",{className:"text-2xl font-bold text-gray-900 mb-4",children:"Ready to Get Started?"}),g?e.jsxs(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(Tr,{className:"h-5 w-5 ml-2"})]}):e.jsx("div",{className:"max-w-md mx-auto bg-white rounded-2xl border border-gray-200 shadow-sm p-6",children:e.jsx(K2t,{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"})]})},QPe="__none__";function H4n({value:s,onChange:t}){const{data:n=[],isLoading:r}=pJ(),a=uGe(),[i,l]=N.useState(!1),o=N.useMemo(()=>n.filter(h=>!h.is_starter),[n]),c=N.useMemo(()=>n.find(h=>h.is_starter&&/open house/i.test(h.name||"")),[n]),d=N.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),xa({title:"Open House Follow-Up added",description:"The 6-email sequence is now in your library and selected here."})}catch(h){xa({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(re,{className:"text-sm font-medium flex items-center gap-2",children:[e.jsx(FT,{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(We,{variant:"outline",className:"text-[10px] border-emerald-300 bg-emerald-500/10 text-emerald-700",children:"On"})]}),e.jsxs(Ns,{value:s??QPe,onValueChange:h=>t(h===QPe?null:h),disabled:r,children:[e.jsx(ws,{children:e.jsx(ks,{placeholder:"No follow-up campaign"})}),e.jsxs(js,{children:[e.jsx(nt,{value:QPe,children:"No follow-up campaign"}),o.map(h=>e.jsxs(nt,{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(us,{className:"h-3.5 w-3.5 animate-spin"}):e.jsx(Cn,{className:"h-3.5 w-3.5 text-primary"}),'Add the "Open House Follow-Up" starter (6 emails)']}),o.length===0&&!c&&e.jsx("p",{className:"text-xs text-muted-foreground",children:"Create a campaign in Smart Drips first, then choose it here."})]})}function G4n({openHouseId:s,enableSurvey:t,onToggleSurvey:n}){const{data:r,isLoading:a}=gos(s),i=bos(),l=_os(),o=wos(),c=jos(),[d,u]=N.useState(""),[h,m]=N.useState("rating"),f=async _=>{n(_),_&&(!r||r.length===0)&&await c.mutateAsync(s)},g=async()=>{if(!d.trim())return;const _=(r==null?void 0:r.reduce((b,k)=>Math.max(b,k.sort_order),0))??0;await i.mutateAsync({open_house_id:s,question_type:h,question_text:d.trim(),sort_order:_+1}),u("")},y=async _=>{await l.mutateAsync({id:_.id,open_house_id:s,is_active:!_.is_active})},x=async _=>{await o.mutateAsync({id:_.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(re,{className:"text-sm font-medium flex items-center gap-2",children:[e.jsx(lj,{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(zn,{checked:t,onCheckedChange:f})]}),t&&e.jsx("div",{className:"space-y-3 pt-2 border-t border-border",children:a?e.jsx("div",{className:"flex items-center justify-center py-4",children:e.jsx(us,{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(_=>e.jsxs("div",{className:"flex items-center gap-2 p-2 rounded-lg border border-border bg-muted/20",children:[e.jsx(Mp,{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:_.question_text}),e.jsx("p",{className:"text-xs text-muted-foreground capitalize",children:_.question_type.replace("_"," ")})]}),e.jsx(zn,{checked:_.is_active,onCheckedChange:()=>y(_),className:"scale-75"}),e.jsx(B,{variant:"ghost",size:"icon",className:"h-7 w-7 shrink-0 text-muted-foreground hover:text-destructive",onClick:()=>x(_),children:e.jsx(qn,{className:"h-3.5 w-3.5"})})]},_.id))}),e.jsxs("div",{className:"flex items-end gap-2",children:[e.jsxs("div",{className:"flex-1",children:[e.jsx(re,{className:"text-xs text-muted-foreground",children:"Add Question"}),e.jsx(we,{value:d,onChange:_=>u(_.target.value),placeholder:"e.g. How did you hear about this listing?",className:"mt-1 h-9 text-sm",onKeyDown:_=>_.key==="Enter"&&g()})]}),e.jsxs(Ns,{value:h,onValueChange:m,children:[e.jsx(ws,{className:"w-28 h-9 text-xs",children:e.jsx(ks,{})}),e.jsxs(js,{children:[e.jsx(nt,{value:"rating",children:"Rating"}),e.jsx(nt,{value:"open_text",children:"Text"})]})]}),e.jsx(B,{size:"sm",variant:"outline",onClick:g,disabled:!d.trim()||i.isPending,className:"h-9",children:e.jsx(nn,{className:"h-3.5 w-3.5"})})]})]})})]})}function W4n({openHouseId:s}){const{user:t}=Ls(),{data:n=[],isLoading:r}=Cos(s),a=Tos(),[i,l]=N.useState(""),[o,c]=N.useState(!1),d=async()=>{const u=i.trim();if(u){c(!0);try{await a.mutateAsync({open_house_id:s,name:u,sort_order:n.length}),l("")}finally{c(!1)}}};return e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(re,{className:"text-sm font-medium",children:"Rooms"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Add rooms and upload photos or videos. Visitors swipe through them on mobile and tab through them on desktop."})]}),r?e.jsxs("div",{className:"py-6 text-center text-sm text-muted-foreground",children:[e.jsx(us,{className:"h-4 w-4 animate-spin inline"})," Loading…"]}):n.length===0?e.jsx("p",{className:"text-xs text-muted-foreground italic",children:"No rooms yet — add your first below."}):e.jsx("div",{className:"space-y-3",children:n.map((u,h)=>e.jsx(K4n,{room:u,index:h,total:n.length,userId:(t==null?void 0:t.id)||"",openHouseId:s},u.id))}),e.jsxs("div",{className:"flex gap-2 pt-2",children:[e.jsx(we,{value:i,onChange:u=>l(u.target.value),placeholder:"e.g. Kitchen, Primary Bedroom, Backyard…",onKeyDown:u=>{u.key==="Enter"&&(u.preventDefault(),d())}}),e.jsx(B,{onClick:d,disabled:!i.trim()||o,size:"sm",children:o?e.jsx(us,{className:"h-4 w-4 animate-spin"}):e.jsxs(e.Fragment,{children:[e.jsx(nn,{className:"h-4 w-4 mr-1"})," Add"]})})]})]})}function K4n({room:s,index:t,total:n,userId:r,openHouseId:a}){const i=Eos(),l=Mos(),o=Los(),c=Pos(),d=N.useRef(null),[u,h]=N.useState(!0),[m,f]=N.useState(s.name),[g,y]=N.useState(s.description||""),[x,_]=N.useState(!1),b=N.useMemo(()=>s.media.filter(L=>L.kind==="video"&&L.agent_video_id).map(L=>L.agent_video_id),[s.media]),{data:k={}}=mt({queryKey:["room-video-statuses",s.id,b.join(",")],enabled:b.length>0,queryFn:async()=>{const{data:L,error:z}=await H.from("agent_videos").select("id, status, bunny_video_id, thumbnail_url, preview_url").in("id",b);if(z)throw z;const $=L||[],V=$.filter(G=>G.status==="processing"&&G.bunny_video_id);await Promise.all(V.map(async G=>{try{const{data:X}=await H.functions.invoke("bunny-upload",{body:{action:"status",videoId:G.bunny_video_id,isAgentVideo:!0}});X&&X.status===4&&(await H.from("agent_videos").update({status:"ready",playback_url:X.directPlayUrl,thumbnail_url:X.thumbnailUrl,preview_url:X.previewUrl,duration_seconds:X.length||void 0,updated_at:new Date().toISOString()}).eq("id",G.id),G.status="ready",G.thumbnail_url=X.thumbnailUrl,G.preview_url=X.previewUrl)}catch{}}));const W={};return $.forEach(G=>{W[G.id]={status:G.status,thumbnail_url:G.thumbnail_url,preview_url:G.preview_url}}),W},refetchInterval:L=>{const z=L.state.data;return z?Object.values(z).some($=>$.status!=="ready"&&$.status!=="failed")?5e3:!1:5e3}}),A=()=>{m.trim()&&m!==s.name&&i.mutate({id:s.id,open_house_id:a,name:m.trim()})},T=()=>{g!==(s.description||"")&&i.mutate({id:s.id,open_house_id:a,description:g.trim()||null})},P=()=>{confirm(`Delete "${s.name}" and all its media?`)&&l.mutate({id:s.id,open_house_id:a})},I=L=>{i.mutate({id:s.id,open_house_id:a,sort_order:t+L})},M=async L=>{const z=Array.from(L.target.files||[]);if(!(!z.length||!r)){_(!0);try{for(const $ of z){const V=$.type.startsWith("video/"),W=V?500*1024*1024:15*1024*1024;if($.size>W){xa({title:`${$.name} is too large`,description:V?"Videos must be under 500MB":"Photos must be under 15MB",variant:"destructive"});continue}if(V){try{const me=`${s.name} – ${$.name.replace(/\.[^/.]+$/,"")}`,{data:ue,error:ce}=await H.functions.invoke("bunny-upload",{body:{action:"create",title:me,isAgentVideo:!0}});if(ce||!ue)throw new Error((ce==null?void 0:ce.message)||"Could not start upload");const{videoId:ae,libraryId:he}=ue,{data:xe,error:ve}=await H.functions.invoke("bunny-upload",{body:{action:"upload-url",videoId:ae,isAgentVideo:!0}});if(ve||!xe)throw new Error((ve==null?void 0:ve.message)||"Could not get upload URL");await new Promise((Me,Re)=>{const Be=new XMLHttpRequest;Be.addEventListener("load",()=>{Be.status>=200&&Be.status<300?Me():Re(new Error(`Upload failed (${Be.status})`))}),Be.addEventListener("error",()=>Re(new Error("Upload failed"))),Be.open("PUT",xe.uploadUrl),Be.setRequestHeader("AccessKey",xe.apiKey),Be.send($)});const ge=`https://iframe.mediadelivery.net/embed/${he}/${ae}`,be=$.size/(1024*1024),{data:Se,error:Ie}=await H.from("agent_videos").insert({owner_user_id:r,bunny_video_id:ae,playback_url:ge,file_size_mb:be,title:me,status:"processing",touch_type:"open_house_tour",category:"open_house",page_template:"default"}).select().single();if(Ie)throw Ie;await o.mutateAsync({open_house_id:a,room_id:s.id,kind:"video",url:ge,sort_order:s.media.length,agent_video_id:Se.id}),xa({title:"Video uploaded",description:"Processing in the background — it’ll appear in your Video Library too."})}catch(me){xa({title:"Video upload failed",description:(me==null?void 0:me.message)||"Try again",variant:"destructive"})}continue}const G=$.name.split(".").pop()||"jpg",X=`${r}/${a}/rooms/${s.id}-${Date.now()}-${Math.random().toString(36).slice(2,7)}.${G}`,{error:te}=await H.storage.from("open-house-tour-media").upload(X,$,{upsert:!1,contentType:$.type});if(te){xa({title:"Upload failed",description:te.message,variant:"destructive"});continue}const{data:ne}=H.storage.from("open-house-tour-media").getPublicUrl(X);await o.mutateAsync({open_house_id:a,room_id:s.id,kind:"photo",url:ne.publicUrl,sort_order:s.media.length})}}finally{_(!1),d.current&&(d.current.value="")}}};return e.jsxs("div",{className:"rounded-lg border border-border bg-card",children:[e.jsxs("div",{className:"flex items-center gap-2 px-3 py-2 border-b border-border",children:[e.jsx(Mp,{className:"h-4 w-4 text-muted-foreground"}),e.jsxs("button",{onClick:()=>h(L=>!L),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(zy,{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(Xo,{className:"h-4 w-4"})}),e.jsx(B,{size:"icon",variant:"ghost",className:"h-7 w-7 text-destructive",onClick:P,children:e.jsx(qn,{className:"h-4 w-4"})})]}),u&&e.jsxs("div",{className:"p-3 space-y-3",children:[e.jsx(we,{value:m,onChange:L=>f(L.target.value),onBlur:A,placeholder:"Room name",className:"h-9"}),e.jsx(Ws,{value:g,onChange:L=>y(L.target.value),onBlur:T,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(L=>{const z=L.agent_video_id?k[L.agent_video_id]:void 0,$=z==null?void 0:z.status,V=L.kind==="video"&&$&&$!=="ready"&&$!=="failed",W=L.kind==="video"&&$==="failed",G=(z==null?void 0:z.thumbnail_url)||(z==null?void 0:z.preview_url);return e.jsxs("div",{className:"relative aspect-square rounded-md overflow-hidden bg-muted group",children:[L.kind==="video"?e.jsxs(e.Fragment,{children:[G?e.jsx("img",{src:G,alt:"",className:"w-full h-full object-cover"}):/iframe\.mediadelivery\.net\/embed\//.test(L.url)?e.jsx("div",{className:"w-full h-full bg-slate-800"}):e.jsx("video",{src:L.url,className:"w-full h-full object-cover"}),!V&&!W&&e.jsx("div",{className:"absolute inset-0 flex items-center justify-center bg-black/30 pointer-events-none",children:e.jsx(na,{className:"h-6 w-6 text-white"})}),V&&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(us,{className:"h-5 w-5 animate-spin"}),e.jsx("span",{className:"text-[10px] font-medium uppercase tracking-wide",children:"Processing"})]}),W&&e.jsx("div",{className:"absolute inset-0 flex items-center justify-center bg-destructive/80 text-white text-[10px] font-medium uppercase tracking-wide pointer-events-none px-2 text-center",children:"Failed"})]}):e.jsx("img",{src:L.url,alt:"",className:"w-full h-full object-cover"}),e.jsx("button",{onClick:()=>c.mutate({id:L.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(hr,{className:"h-3.5 w-3.5"})})]},L.id)})}),e.jsx("input",{ref:d,type:"file",accept:"image/*,video/*",multiple:!0,onChange:M,className:"hidden"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(B,{variant:"outline",size:"sm",onClick:()=>{var L;return(L=d.current)==null?void 0:L.click()},disabled:x,className:"flex-1",children:x?e.jsx(us,{className:"h-4 w-4 animate-spin"}):e.jsxs(e.Fragment,{children:[e.jsx(ni,{className:"h-4 w-4 mr-2"})," Upload"]})}),e.jsx(tO,{userId:r,triggerLabel:"From Video Library",triggerClassName:"gap-1.5 flex-1 justify-center",onSelect:()=>{},onSelectVideo:async L=>{try{await o.mutateAsync({open_house_id:a,room_id:s.id,kind:"video",url:L.playback_url||"",sort_order:s.media.length,agent_video_id:L.id}),xa({title:"Video added to room"})}catch(z){xa({title:"Failed to add video",description:z==null?void 0:z.message,variant:"destructive"})}}})]})]})]})}function Y4n({open:s,onOpenChange:t,openHouse:n}){const r=Z2t(),{user:a}=Ls(),i=N.useRef(null),l=N.useRef(null),o=N.useRef(null),c=n.kind==="virtual",[d,u]=N.useState(n.auto_forward_to_card??!1),[h,m]=N.useState(n.disclosure_pdf_url??""),[f,g]=N.useState(n.enable_survey??!1),[y,x]=N.useState(n.ask_visitor_intent??!0),[_,b]=N.useState(n.ask_visitor_address??!1),[k,A]=N.useState(n.photo_url??""),[T,P]=N.useState(!1),[I,M]=N.useState(!1),[L,z]=N.useState(!1),[$,V]=N.useState(n.hero_video_url??""),[W,G]=N.useState(!1),[X,te]=N.useState(n.price!=null?String(n.price):""),[ne,me]=N.useState(n.beds!=null?String(n.beds):""),[ue,ce]=N.useState(n.baths!=null?String(n.baths):""),[ae,he]=N.useState(n.sqft!=null?String(n.sqft):""),[xe,ve]=N.useState(n.enable_question??!0),[ge,be]=N.useState(n.enable_showing??!0),[Se,Ie]=N.useState(n.enable_disclosures??!0),[Me,Re]=N.useState(n.enable_offer??!0),[Be,Ne]=N.useState(n.brand_color_override??""),[Ge,Ce]=N.useState(n.property_description??""),[Fe,Ae]=N.useState(n.drip_campaign_id??null),Xe=async rt=>{var Kt;const Ze=(Kt=rt.target.files)==null?void 0:Kt[0];if(!Ze||!a)return;if(Ze.size>200*1024*1024){xa({title:"Video must be under 200MB",variant:"destructive"});return}if(!Ze.type.startsWith("video/")){xa({title:"Please upload a video file",variant:"destructive"});return}G(!0);const ht=Ze.name.split(".").pop()||"mp4",Bt=`${a.id}/${n.id}/hero-${Date.now()}.${ht}`,{error:Ct}=await H.storage.from("open-house-tour-media").upload(Bt,Ze,{upsert:!0,contentType:Ze.type});if(Ct){xa({title:"Upload failed",description:Ct.message,variant:"destructive"}),G(!1);return}const{data:Yt}=H.storage.from("open-house-tour-media").getPublicUrl(Bt);V(Yt.publicUrl),G(!1),xa({title:"Video uploaded!"})},$e=async rt=>{var Kt;const Ze=(Kt=rt.target.files)==null?void 0:Kt[0];if(!Ze||!a)return;if(Ze.size>10*1024*1024){xa({title:"Image must be under 10MB",variant:"destructive"});return}if(!Ze.type.startsWith("image/")){xa({title:"Please upload an image file",variant:"destructive"});return}M(!0);const ht=Ze.name.split(".").pop()||"jpg",Bt=`${a.id}/${n.id}-${Date.now()}.${ht}`,{error:Ct}=await H.storage.from("open-house-photos").upload(Bt,Ze,{upsert:!0});if(Ct){xa({title:"Upload failed",description:Ct.message,variant:"destructive"}),M(!1);return}const{data:Yt}=H.storage.from("open-house-photos").getPublicUrl(Bt);A(Yt.publicUrl),M(!1),xa({title:"Photo updated!"})},Ye=()=>{A(""),l.current&&(l.current.value="")},Je=async rt=>{var Yt;const Ze=(Yt=rt.target.files)==null?void 0:Yt[0];if(!Ze||!a)return;if(Ze.size>20*1024*1024){xa({title:"File must be under 20MB",variant:"destructive"});return}if(Ze.type!=="application/pdf"){xa({title:"Only PDF files are accepted",variant:"destructive"});return}P(!0);const ht=`${a.id}/disclosures/${n.id}-${Date.now()}.pdf`,{error:Bt}=await H.storage.from("open-house-photos").upload(ht,Ze,{upsert:!0});if(Bt){xa({title:"Upload failed",description:Bt.message,variant:"destructive"}),P(!1);return}const{data:Ct}=H.storage.from("open-house-photos").getPublicUrl(ht);m(Ct.publicUrl),P(!1),xa({title:"PDF uploaded!"})},Ke=()=>{m(""),i.current&&(i.current.value="")},st=async()=>{z(!0);try{const rt={id:n.id,auto_forward_to_card:d,disclosure_pdf_url:h||null,enable_survey:f,ask_visitor_intent:y,ask_visitor_address:_,photo_url:k||null,drip_campaign_id:Fe};c&&(rt.hero_video_url=$||null,rt.price=X.trim()?Number(X):null,rt.beds=ne.trim()?parseInt(ne,10):null,rt.baths=ue.trim()?Number(ue):null,rt.sqft=ae.trim()?parseInt(ae,10):null,rt.enable_question=xe,rt.enable_showing=ge,rt.enable_disclosures=Se,rt.enable_offer=Me,rt.brand_color_override=Be.trim()||null,rt.property_description=Ge.trim()||null),await r.mutateAsync(rt),xa({title:"Settings saved!"}),t(!1)}catch{xa({title:"Failed to save",variant:"destructive"})}finally{z(!1)}};return e.jsx(Bs,{open:s,onOpenChange:t,children:e.jsxs(Fs,{className:"sm:max-w-md max-h-[85vh] overflow-y-auto",children:[e.jsxs(qs,{children:[e.jsx($s,{children:c?"Virtual Open House Settings":"Guest Book Settings"}),e.jsx(Ar,{className:"truncate",children:n.property_address})]}),e.jsxs("div",{className:"space-y-6 pt-2",children:[c&&e.jsxs(e.Fragment,{children:[n.tour_mode==="single_video"?e.jsxs("div",{className:"space-y-2",children:[e.jsxs(re,{className:"text-sm font-medium flex items-center gap-2",children:[e.jsx(na,{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:Xe,className:"hidden"}),$?e.jsxs("div",{className:"relative rounded-lg overflow-hidden border border-border bg-black",children:[e.jsx("video",{src:$,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 rt;return(rt=o.current)==null?void 0:rt.click()},disabled:W,children:W?e.jsx(us,{className:"h-3.5 w-3.5 animate-spin"}):e.jsxs(e.Fragment,{children:[e.jsx(ni,{className:"h-3.5 w-3.5 mr-1"}),"Replace"]})}),e.jsx(B,{variant:"secondary",size:"icon",className:"h-8 w-8",onClick:()=>V(""),children:e.jsx(hr,{className:"h-4 w-4"})})]})]}):e.jsx("button",{type:"button",onClick:()=>{var rt;return(rt=o.current)==null?void 0:rt.click()},disabled:W,className:"w-full h-32 rounded-xl border-2 border-dashed border-muted-foreground/25 hover:border-muted-foreground/50 flex flex-col items-center justify-center gap-2 text-muted-foreground hover:text-foreground transition-colors",children:W?e.jsx(us,{className:"h-5 w-5 animate-spin"}):e.jsxs(e.Fragment,{children:[e.jsx(na,{className:"h-5 w-5"}),e.jsx("span",{className:"text-xs",children:"Upload tour video (max 200MB)"})]})})]}):e.jsx(W4n,{openHouseId:n.id}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{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(re,{className:"text-xs text-muted-foreground",children:"Price (USD)"}),e.jsx(we,{type:"number",value:X,onChange:rt=>te(rt.target.value),placeholder:"650000",className:"mt-1"})]}),e.jsxs("div",{children:[e.jsx(re,{className:"text-xs text-muted-foreground",children:"Sq Ft"}),e.jsx(we,{type:"number",value:ae,onChange:rt=>he(rt.target.value),placeholder:"2200",className:"mt-1"})]}),e.jsxs("div",{children:[e.jsx(re,{className:"text-xs text-muted-foreground",children:"Beds"}),e.jsx(we,{type:"number",value:ne,onChange:rt=>me(rt.target.value),placeholder:"3",className:"mt-1"})]}),e.jsxs("div",{children:[e.jsx(re,{className:"text-xs text-muted-foreground",children:"Baths"}),e.jsx(we,{type:"number",step:"0.5",value:ue,onChange:rt=>ce(rt.target.value),placeholder:"2.5",className:"mt-1"})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{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(Ws,{value:Ge,onChange:rt=>Ce(rt.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(re,{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(zn,{checked:xe,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(zn,{checked:ge,onCheckedChange:be})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"text-sm",children:"Request seller disclosures"}),e.jsx(zn,{checked:Se,onCheckedChange:Ie})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"text-sm",children:"Make an offer / express interest"}),e.jsx(zn,{checked:Me,onCheckedChange:Re})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{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:Be||"#0f172a",onChange:rt=>Ne(rt.target.value),className:"h-10 w-14 rounded-md border border-input cursor-pointer bg-transparent"}),e.jsx(we,{value:Be,onChange:rt=>Ne(rt.target.value),placeholder:"#0f172a",className:"flex-1 font-mono text-sm"}),Be&&e.jsx(B,{variant:"ghost",size:"sm",onClick:()=>Ne(""),children:"Reset"})]}),e.jsx("div",{className:"flex flex-wrap gap-1.5 pt-1",children:["#0f172a","#406E71","#2a4c64","#7c2d12","#1e3a8a","#581c87","#9f1239","#065f46"].map(rt=>e.jsx("button",{type:"button",onClick:()=>Ne(rt),className:"w-6 h-6 rounded-full border border-border hover:scale-110 transition-transform",style:{backgroundColor:rt},"aria-label":rt},rt))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{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:$e,className:"hidden"}),k?e.jsxs("div",{className:"relative rounded-lg overflow-hidden border border-border",children:[e.jsx("img",{src:k,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 rt;return(rt=l.current)==null?void 0:rt.click()},disabled:I,children:[I?e.jsx(us,{className:"h-3.5 w-3.5 animate-spin"}):e.jsx(ni,{className:"h-3.5 w-3.5 mr-1"}),I?"":"Replace"]}),e.jsx(B,{variant:"secondary",size:"icon",className:"h-8 w-8",onClick:Ye,children:e.jsx(hr,{className:"h-4 w-4"})})]})]}):e.jsx("button",{type:"button",onClick:()=>{var rt;return(rt=l.current)==null?void 0:rt.click()},disabled:I,className:"w-full h-32 rounded-xl border-2 border-dashed border-muted-foreground/25 hover:border-muted-foreground/50 flex flex-col items-center justify-center gap-2 text-muted-foreground hover:text-foreground transition-colors",children:I?e.jsx(us,{className:"h-5 w-5 animate-spin"}):e.jsxs(e.Fragment,{children:[e.jsx(pc,{className:"h-5 w-5"}),e.jsx("span",{className:"text-xs",children:"Upload property photo (max 10MB)"})]})})]}),e.jsx(H4n,{value:Fe,onChange:Ae}),e.jsx("div",{className:"space-y-2",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"space-y-0.5",children:[e.jsx(re,{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(zn,{checked:d,onCheckedChange:u})]})}),!d&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{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:Je,className:"hidden"}),h?e.jsxs("div",{className:"flex items-center gap-3 p-3 rounded-lg border border-border bg-muted/30",children:[e.jsx(Wr,{className:"h-5 w-5 text-primary shrink-0"}),e.jsx("span",{className:"text-sm truncate flex-1",children:"Disclosure PDF uploaded"}),e.jsx(B,{variant:"ghost",size:"icon",className:"h-7 w-7 shrink-0",onClick:Ke,children:e.jsx(hr,{className:"h-4 w-4"})})]}):e.jsx("button",{type:"button",onClick:()=>{var rt;return(rt=i.current)==null?void 0:rt.click()},disabled:T,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:T?e.jsx(us,{className:"h-5 w-5 animate-spin"}):e.jsxs(e.Fragment,{children:[e.jsx(ni,{className:"h-5 w-5"}),e.jsx("span",{className:"text-xs",children:"Upload PDF (max 20MB)"})]})})]}),e.jsx("div",{className:"space-y-2",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"space-y-0.5",children:[e.jsx(re,{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(zn,{checked:y,onCheckedChange:x})]})}),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(re,{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(zn,{checked:_,onCheckedChange:b})]})}),e.jsx(G4n,{openHouseId:n.id,enableSurvey:f,onToggleSurvey:g}),e.jsx(B,{onClick:st,disabled:L,className:"w-full",children:L?"Saving...":"Save Settings"})]})]})})}const R9t={5:"Excellent",4:"Good",3:"Neutral",2:"Bad",1:"Very Bad"};function Z4n({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:R9t[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 X4n({openHouseId:s}){const{data:t,isLoading:n}=vos(s),{data:r}=Y2t(s),a=N.useMemo(()=>{const h={};return r==null||r.forEach(m=>{h[m.id]=m}),h},[r]);if(n||!t)return null;const{questions:i,responses:l}=t;if(i.length===0)return null;const o=i.filter(h=>h.question_type==="rating"),c=i.filter(h=>h.question_type!=="rating"),d=[...new Set(l.map(h=>h.visitor_id))],u=d.length;return u===0?e.jsxs(_e,{children:[e.jsx(zt,{className:"pb-3",children:e.jsxs(qt,{className:"text-base flex items-center gap-2",children:[e.jsx(lj,{className:"h-4 w-4"}),"Survey Results"]})}),e.jsx(De,{children:e.jsx("p",{className:"text-sm text-muted-foreground",children:"No survey responses yet."})})]}):e.jsxs(_e,{children:[e.jsx(zt,{className:"pb-3",children:e.jsxs(qt,{className:"text-base flex items-center gap-2",children:[e.jsx(lj,{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(De,{children:e.jsxs(ya,{defaultValue:"summary",children:[e.jsxs(va,{className:"mb-4",children:[e.jsxs(ls,{value:"summary",className:"text-xs gap-1",children:[e.jsx(fl,{className:"h-3.5 w-3.5"})," Summary"]}),e.jsxs(ls,{value:"individual",className:"text-xs gap-1",children:[e.jsx(Ro,{className:"h-3.5 w-3.5"})," Per Visitor"]})]}),e.jsxs(_s,{value:"summary",className:"space-y-6",children:[o.map(h=>e.jsx(Z4n,{question:h,responses:l},h.id)),c.map(h=>{const m=l.filter(f=>f.question_id===h.id&&f.text_value);return m.length===0?null:e.jsxs("div",{className:"space-y-2",children:[e.jsx("span",{className:"text-sm font-medium",children:h.question_text}),e.jsx("div",{className:"space-y-1.5 max-h-40 overflow-y-auto",children:m.map(f=>{const g=a[f.visitor_id];return e.jsxs("div",{className:"text-sm p-2 bg-muted/30 rounded-lg",children:[e.jsxs("span",{className:"text-muted-foreground text-xs",children:[g?`${g.first_name} ${g.last_name||""}`.trim():"Visitor",":"]}),e.jsx("p",{className:"mt-0.5",children:f.text_value})]},f.id)})})]},h.id)})]}),e.jsx(_s,{value:"individual",className:"space-y-4",children:d.map(h=>{const m=a[h],f=l.filter(g=>g.visitor_id===h);return e.jsxs("div",{className:"p-3 rounded-lg border border-border space-y-2",children:[e.jsxs("p",{className:"text-sm font-medium",children:[m?`${m.first_name} ${m.last_name||""}`.trim():"Unknown Visitor",(m==null?void 0:m.email)&&e.jsx("span",{className:"text-xs text-muted-foreground ml-2",children:m.email})]}),e.jsx("div",{className:"space-y-1",children:f.map(g=>{const y=i.find(x=>x.id===g.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:g.rating_value!=null?R9t[g.rating_value]||g.rating_value:g.text_value})]},g.id):null})})]},h)})})]})})]})}const Q4n={question:{label:"Question",icon:xo,color:"text-sky-700 dark:text-sky-300",bg:"bg-sky-100 dark:bg-sky-950"},showing:{label:"Showing",icon:ta,color:"text-orange-700 dark:text-orange-300",bg:"bg-orange-100 dark:bg-orange-950"},disclosure:{label:"Disclosures",icon:Wr,color:"text-indigo-700 dark:text-indigo-300",bg:"bg-indigo-100 dark:bg-indigo-950"},offer:{label:"Hot Lead",icon:Ed,color:"text-emerald-700 dark:text-emerald-300",bg:"bg-emerald-100 dark:bg-emerald-950"}},ggt={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 J4n({openHouseId:s}){const{data:t=[],isLoading:n}=Ios(s),r=Dos(),[a,i]=N.useState(null),[l,o]=N.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(n3,{className:"h-4 w-4"}),"Virtual Open House Leads",e.jsx(We,{variant:"secondary",className:"ml-1",children:d.all}),d.new>0&&e.jsxs(We,{className:"bg-emerald-600 hover:bg-emerald-600",children:[d.new," new"]})]}),e.jsx("div",{className:"flex items-center gap-1 flex-wrap",children:[["all","All",d.all],["new","New",d.new],["offer","Hot",d.offer],["showing","Showings",d.showing],["question","Questions",d.question],["disclosure","Docs",d.disclosure]].map(([h,m,f])=>e.jsxs("button",{onClick:()=>o(h),className:`text-xs px-2.5 py-1 rounded-full transition-colors ${l===h?"bg-foreground text-background":"bg-background hover:bg-muted text-muted-foreground"}`,children:[m," ",e.jsx("span",{className:"opacity-60",children:f})]},h))})]}),c.length===0?e.jsx("div",{className:"px-4 py-10 text-center text-sm text-muted-foreground",children:t.length===0?"No leads yet. Share your virtual open house link to start capturing leads.":"No leads match this filter."}):e.jsx("ul",{className:"divide-y",children:c.map(h=>{const m=Q4n[h.action_type],f=m.icon,g=h.payload||{},y=a===h.id,x=h.status==="contacted",_=h.status==="archived";return e.jsxs("li",{className:`transition-colors ${_?"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(f,{className:`h-4 w-4 ${m.color}`})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsx("span",{className:"font-semibold text-sm truncate",children:g.visitor_name||"Visitor"}),e.jsx(We,{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"}),x&&e.jsxs("span",{className:"text-[10px] font-bold text-muted-foreground uppercase tracking-wide flex items-center gap-1",children:[e.jsx(Hr,{className:"h-3 w-3"}),"Contacted"]})]}),g.message&&e.jsxs("p",{className:"text-sm text-muted-foreground line-clamp-1 mt-0.5 italic",children:['"',g.message,'"']}),e.jsxs("div",{className:"flex items-center gap-3 text-[11px] text-muted-foreground mt-1",children:[e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Xr,{className:"h-3 w-3"}),Js(new Date(h.created_at),"MMM d, h:mm a")]}),g.email&&e.jsxs("span",{className:"flex items-center gap-1 truncate",children:[e.jsx(mn,{className:"h-3 w-3"}),g.email]}),g.phone&&e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(ga,{className:"h-3 w-3"}),g.phone]})]})]}),y?e.jsx(Xo,{className:"h-4 w-4 mt-1 text-muted-foreground"}):e.jsx(Qa,{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:[g.message&&e.jsxs("div",{className:"bg-muted/40 rounded-md p-3 text-sm border-l-2 border-foreground/30",children:['"',g.message,'"']}),Object.keys(ggt).some(b=>g[b]!=null&&g[b]!==""&&!(Array.isArray(g[b])&&g[b].length===0))&&e.jsx("div",{className:"grid grid-cols-2 gap-x-4 gap-y-1.5 text-sm",children:Object.entries(ggt).map(([b,k])=>{const A=g[b];return A==null||A===""||Array.isArray(A)&&A.length===0?null:e.jsxs("div",{children:[e.jsx("div",{className:"text-[11px] text-muted-foreground uppercase tracking-wide",children:k}),e.jsx("div",{className:"font-medium",children:Array.isArray(A)?A.join(", "):String(A)})]},b)})}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2 pt-1",children:[g.email&&e.jsx("a",{href:`mailto:${g.email}?subject=${encodeURIComponent("Re: your open house inquiry")}`,children:e.jsxs(B,{size:"sm",variant:"default",className:"gap-1.5",children:[e.jsx(mn,{className:"h-3.5 w-3.5"}),"Reply"]})}),g.phone&&e.jsx("a",{href:`tel:${String(g.phone).replace(/[^0-9+]/g,"")}`,children:e.jsxs(B,{size:"sm",variant:"outline",className:"gap-1.5",children:[e.jsx(ga,{className:"h-3.5 w-3.5"}),"Call"]})}),!x&&e.jsxs(B,{size:"sm",variant:"outline",className:"gap-1.5",onClick:()=>u(h.id,"contacted"),children:[e.jsx(Hr,{className:"h-3.5 w-3.5"}),"Mark contacted"]}),_?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(xg,{className:"h-3.5 w-3.5"}),"Archive"]})]})]})]},h.id)})})]})}function e3n({open:s,onOpenChange:t,openHouse:n}){const{isGmailConnected:r,gmailEmail:a}=_f(),i=Ya(),[l,o]=N.useState([]),[c,d]=N.useState([]),[u,h]=N.useState(!1),[m,f]=N.useState(!1),[g,y]=N.useState(""),[x,_]=N.useState(""),[b,k]=N.useState(""),[A,T]=N.useState(!1),[P,I]=N.useState(!1),[M,L]=N.useState(!1),z=`https://guestbook.relevelup.com/${n.slug}`;N.useEffect(()=>{s&&(_(`Take a virtual tour of ${n.property_address}`),k(`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.`),d([]),y(""),T(r),l.length===0&&$())},[s,n.id,r]);const $=async()=>{if(i){f(!0);try{const{data:ue,error:ce}=await H.from("innercircle_contacts").select("id, first_name, last_name, email").eq("owner_user_id",i).not("email","is",null).neq("email","").order("first_name",{ascending:!0}).limit(1e3);if(ce)throw ce;o(ue||[])}catch{ie.error("Failed to load contacts")}finally{f(!1)}}},V=ue=>`${ue.first_name} ${ue.last_name||""}`.trim(),W=ue=>{d(ce=>ce.find(ae=>ae.id===ue.id)?ce.filter(ae=>ae.id!==ue.id):[...ce,ue])},G=()=>{const ue=g.trim();if(!ue)return;if(!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(ue)){ie.error("Invalid email");return}d(ae=>[...ae,{id:`manual-${ue}`,first_name:ue.split("@")[0],last_name:null,email:ue}]),y("")},X=N.useMemo(()=>c.filter(ue=>!!ue.email).map(ue=>({email:ue.email,name:V(ue)})),[c]),te=ue=>{const ce=ue?`Hi ${ue},`:"Hi there,",ae=b.split(/\n\n+/).map(he=>`

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

`).join("");return`

${ce}

${ae}

▶ Start Virtual Tour

Or copy this link: ${z}

`},ne=async()=>{var ue;if(X.length===0){ie.error("Add at least one recipient");return}I(!0);try{if(A&&r){let ce=0;for(const ae of X){const{data:he,error:xe}=await H.functions.invoke("gmail-send",{body:{to:ae.email,subject:x,body:te((ue=ae.name)==null?void 0:ue.split(" ")[0])}});!xe&&(he!=null&&he.success)?ce+=1:console.warn("gmail-send error",xe,he)}if(ce===0)throw new Error("Gmail send failed");ie.success(`Sent to ${ce} of ${X.length} via Gmail`)}else{const{data:ce,error:ae}=await H.functions.invoke("send-virtual-tour-invite",{body:{openHouseId:n.id,recipients:X,subject:x,personalMessage:b}});if(ae)throw ae;if(!(ce!=null&&ce.success))throw new Error((ce==null?void 0:ce.error)||"Send failed");ie.success(`Sent to ${ce.sent} of ${ce.total} recipient${ce.total===1?"":"s"}`)}t(!1)}catch(ce){ie.error((ce==null?void 0:ce.message)||"Failed to send")}finally{I(!1)}},me=async()=>{await navigator.clipboard.writeText(z),L(!0),setTimeout(()=>L(!1),1500)};return e.jsx(Bs,{open:s,onOpenChange:t,children:e.jsxs(Fs,{className:"sm:max-w-[560px] w-[calc(100vw-2rem)] max-h-[90vh] overflow-y-auto overflow-x-hidden",children:[e.jsxs(qs,{className:"min-w-0",children:[e.jsxs($s,{className:"flex items-center gap-2",children:[e.jsx(mn,{className:"h-5 w-5 text-primary"}),"Share Virtual Tour"]}),e.jsx(Ar,{className:"truncate",children:n.property_address})]}),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(gc,{className:"h-4 w-4 text-muted-foreground shrink-0"}),e.jsx("code",{className:"flex-1 min-w-0 text-xs truncate",children:z}),e.jsxs(B,{variant:"ghost",size:"sm",onClick:me,className:"shrink-0 h-7 gap-1",children:[M?e.jsx(pa,{className:"h-3.5 w-3.5 text-emerald-600"}):e.jsx(Pa,{className:"h-3.5 w-3.5"}),M?"Copied":"Copy"]})]}),r&&e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(B,{type:"button",variant:A?"default":"outline",size:"sm",onClick:()=>T(!0),className:"gap-1.5",children:[e.jsx(mn,{className:"h-3.5 w-3.5"}),"Send from Gmail"]}),e.jsx(B,{type:"button",variant:A?"outline":"default",size:"sm",onClick:()=>T(!1),className:"gap-1.5",children:"Send from LevelUp"})]}),A&&a&&e.jsxs("p",{className:"text-xs text-muted-foreground -mt-2",children:["Sending as ",e.jsx("span",{className:"font-medium",children:a})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs(re,{className:"flex items-center gap-1.5",children:[e.jsx(Yn,{className:"h-3.5 w-3.5"}),"Recipients"]}),e.jsxs(rc,{open:u,onOpenChange:h,modal:!0,children:[e.jsx(ac,{asChild:!0,children:e.jsxs(B,{variant:"outline",role:"combobox",className:"w-full justify-between",children:[e.jsx("span",{className:"text-muted-foreground",children:c.length?`${c.length} selected`:"Select contacts..."}),e.jsx(sb,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]})}),e.jsx(Zl,{className:"w-[440px] max-w-[calc(100vw-2rem)] p-0",align:"start",children:e.jsxs(db,{children:[e.jsx(ub,{placeholder:"Search contacts..."}),e.jsxs(hb,{className:"max-h-[300px] overflow-y-auto",children:[e.jsx(mb,{children:m?"Loading...":"No contacts found."}),e.jsx(pb,{children:l.map(ue=>{const ce=!!c.find(xe=>xe.id===ue.id),ae=V(ue).slice(0,80),he=(ue.email||"").slice(0,80);return e.jsxs(Ry,{value:`${ae} ${he}`,onSelect:()=>W(ue),className:"py-2",children:[e.jsx(pa,{className:Ot("mr-2 h-4 w-4 shrink-0",ce?"opacity-100":"opacity-0")}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("div",{className:"font-medium text-sm truncate",children:ae||"(no name)"}),e.jsx("div",{className:"text-xs text-muted-foreground truncate",children:he})]})]},ue.id)})})]})]})})]}),c.length>0&&e.jsx("div",{className:"flex flex-wrap gap-1.5 pt-1",children:c.map(ue=>e.jsxs(We,{variant:"secondary",className:"gap-1 pl-2 pr-1 py-0.5",children:[e.jsx("span",{className:"text-xs",children:V(ue)}),e.jsx("button",{onClick:()=>W(ue),className:"hover:bg-muted-foreground/20 rounded p-0.5",children:e.jsx(hr,{className:"h-3 w-3"})})]},ue.id))}),e.jsxs("div",{className:"flex gap-2 pt-2",children:[e.jsx(we,{value:g,onChange:ue=>y(ue.target.value),placeholder:"Or type an email...",type:"email",onKeyDown:ue=>{ue.key==="Enter"&&(ue.preventDefault(),G())}}),e.jsx(B,{type:"button",variant:"outline",size:"sm",onClick:G,children:"Add"})]})]}),e.jsx(Wl,{}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(re,{htmlFor:"vt-subject",children:"Subject"}),e.jsx(we,{id:"vt-subject",value:x,onChange:ue=>_(ue.target.value)})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(re,{htmlFor:"vt-message",children:"Personal Message"}),e.jsx(Ws,{id:"vt-message",value:b,onChange:ue=>k(ue.target.value),rows:4,className:"resize-y"})]}),e.jsxs("div",{className:"flex justify-end gap-2 pt-2",children:[e.jsx(B,{variant:"outline",onClick:()=>t(!1),disabled:P,children:"Cancel"}),e.jsxs(B,{onClick:ne,disabled:P||X.length===0||!x.trim(),className:"gap-2",children:[P?e.jsx(us,{className:"h-4 w-4 animate-spin"}):e.jsx(Rr,{className:"h-4 w-4"}),P?"Sending...":`Send${X.length?` to ${X.length}`:""}`]})]})]})]})})}const wze="guestbook.relevelup.com";function t3n(){const{data:s,isLoading:t}=hos(),n=mos(),r=Z2t(),a=pos(),[i,l]=N.useState(!1),[o,c]=N.useState(null),{user:d}=Ls(),u=Ya(),[h,m]=N.useState(null),[f,g]=N.useState(null),[y,x]=N.useState(!1),_=N.useRef(null),[b,k]=N.useState({property_address:"",city:"",state:"",zip:"",event_date:Js(new Date,"yyyy-MM-dd"),start_time:"10:00",end_time:"14:00",agent_greeting:"Welcome! Please sign in below.",event_type:"property",kind:"physical",tour_mode:"rooms"}),A=M=>{var z;const L=(z=M.target.files)==null?void 0:z[0];if(L){if(L.size>5*1024*1024){xa({title:"Photo must be under 5MB",variant:"destructive"});return}m(L),g(URL.createObjectURL(L))}},T=()=>{m(null),g(null),_.current&&(_.current.value="")},P=async()=>{if(!b.property_address){xa({title:b.event_type==="community"?"Event name is required":"Address is required",variant:"destructive"});return}let M;if(h&&d){x(!0);const z=h.name.split(".").pop(),$=`${u}/${Date.now()}.${z}`,{error:V}=await H.storage.from("open-house-photos").upload($,h,{upsert:!0});if(V){xa({title:"Photo upload failed",description:V.message,variant:"destructive"}),x(!1);return}const{data:W}=H.storage.from("open-house-photos").getPublicUrl($);M=W.publicUrl,x(!1)}const L=b.kind==="virtual"?{...b,start_time:void 0,end_time:void 0,photo_url:M}:{...b,photo_url:M};await n.mutateAsync(L),l(!1),k({property_address:"",city:"",state:"",zip:"",event_date:Js(new Date,"yyyy-MM-dd"),start_time:"10:00",end_time:"14:00",agent_greeting:"Welcome! Please sign in below.",event_type:"property",kind:"physical",tour_mode:"rooms"}),T()},I=M=>{navigator.clipboard.writeText(`https://${wze}/${M}`),xa({title:"Link copied!"})};return e.jsxs(Qs,{title:"Guest Book",children:[e.jsx(ic,{children:e.jsx("title",{children:"Guest Book | LevelUp"})}),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",{children:[e.jsx("h1",{className:"text-2xl font-bold font-serif text-foreground",children:"Guest Book"}),e.jsx("p",{className:"text-muted-foreground text-sm",children:"The modern open house sign-in experience"})]}),e.jsxs(Bs,{open:i,onOpenChange:l,children:[e.jsx(Ao,{asChild:!0,children:e.jsxs(B,{children:[e.jsx(nn,{className:"h-4 w-4 mr-2"}),"New Open House"]})}),e.jsxs(Fs,{className:"sm:max-w-lg max-h-[90vh] flex flex-col",children:[e.jsxs(qs,{children:[e.jsx($s,{children:"Create Open House"}),e.jsx(Ar,{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(re,{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:()=>k(M=>({...M,kind:"physical"})),className:`p-3 rounded-lg border text-left transition-all ${b.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:()=>k(M=>({...M,kind:"virtual",event_type:"property"})),className:`p-3 rounded-lg border text-left transition-all ${b.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"})]})]})]}),b.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:()=>k(M=>({...M,event_type:"property"})),className:`flex-1 px-3 py-2 rounded-md text-sm font-medium transition-colors ${b.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:()=>k(M=>({...M,event_type:"community"})),className:`flex-1 px-3 py-2 rounded-md text-sm font-medium transition-colors ${b.event_type==="community"?"bg-primary text-primary-foreground shadow-sm":"text-muted-foreground hover:text-foreground"}`,children:"Community Event"})]})}),b.kind==="virtual"&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{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:()=>k(M=>({...M,tour_mode:"rooms"})),className:`p-3 rounded-lg border text-left transition-all ${b.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:()=>k(M=>({...M,tour_mode:"single_video"})),className:`p-3 rounded-lg border text-left transition-all ${b.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(re,{children:b.event_type==="community"?"Event Name *":"Property Address *"}),e.jsx(we,{value:b.property_address,onChange:M=>k(L=>({...L,property_address:M.target.value})),placeholder:b.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(re,{children:"City"}),e.jsx(we,{value:b.city,onChange:M=>k(L=>({...L,city:M.target.value})),placeholder:"Austin"})]}),e.jsxs("div",{children:[e.jsx(re,{children:"State"}),e.jsx(we,{value:b.state,onChange:M=>k(L=>({...L,state:M.target.value})),placeholder:"TX",maxLength:2})]}),e.jsxs("div",{children:[e.jsx(re,{children:"ZIP"}),e.jsx(we,{value:b.zip,onChange:M=>k(L=>({...L,zip:M.target.value})),placeholder:"78701"})]})]}),b.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(re,{children:"Date"}),e.jsx(we,{type:"date",value:b.event_date,onChange:M=>k(L=>({...L,event_date:M.target.value}))})]}),e.jsxs("div",{children:[e.jsx(re,{children:"Start Time"}),e.jsx(we,{type:"time",value:b.start_time,onChange:M=>k(L=>({...L,start_time:M.target.value}))})]}),e.jsxs("div",{children:[e.jsx(re,{children:"End Time"}),e.jsx(we,{type:"time",value:b.end_time,onChange:M=>k(L=>({...L,end_time:M.target.value}))})]})]}),e.jsxs("div",{children:[e.jsx(re,{children:"Welcome Message"}),e.jsx(Ws,{value:b.agent_greeting,onChange:M=>k(L=>({...L,agent_greeting:M.target.value})),placeholder:"Welcome! Please sign in below."})]}),e.jsxs("div",{children:[e.jsx(re,{children:b.event_type==="community"?"Event Photo":"Property Photo"}),e.jsx("input",{ref:_,type:"file",accept:"image/*",onChange:A,className:"hidden"}),f?e.jsxs("div",{className:"relative mt-1 rounded-xl overflow-hidden border border-border",children:[e.jsx("img",{src:f,alt:"Property preview",className:"w-full h-40 object-cover"}),e.jsx("button",{type:"button",onClick:T,className:"absolute top-2 right-2 bg-black/60 hover:bg-black/80 text-white rounded-full p-1 transition-colors",children:e.jsx(hr,{className:"h-4 w-4"})})]}):e.jsxs("button",{type:"button",onClick:()=>{var M;return(M=_.current)==null?void 0:M.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(Gv,{className:"h-6 w-6"}),e.jsxs("span",{className:"text-sm",children:["Add a ",b.event_type==="community"?"cover":"property"," photo"]}),e.jsx("span",{className:"text-xs text-muted-foreground",children:"Max 5MB"})]})]}),e.jsx(B,{onClick:P,disabled:n.isPending||y,className:"w-full",children:y?"Uploading photo...":n.isPending?"Creating...":b.kind==="virtual"?"Create Virtual Open House":b.event_type==="community"?"Create Community Event":"Create Open House"})]})]})]})]}),t?e.jsx("div",{className:"grid gap-4",children:[1,2].map(M=>e.jsx(_e,{className:"animate-pulse",children:e.jsxs(zt,{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"})]})},M))}):s!=null&&s.length?e.jsx("div",{className:"space-y-4",children:s.map(M=>e.jsx(s3n,{openHouse:M,isExpanded:o===M.id,onToggle:()=>c(o===M.id?null:M.id),onCopyLink:()=>I(M.slug||""),onToggleActive:()=>r.mutate({id:M.id,is_active:!M.is_active}),onDelete:()=>a.mutate(M.id)},M.id))}):e.jsx(_e,{className:"border-dashed",children:e.jsxs(De,{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(M_,{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(nn,{className:"h-4 w-4 mr-2"}),"Create Your First Open House"]})]})})]})]})}function s3n({openHouse:s,isExpanded:t,onToggle:n,onCopyLink:r,onToggleActive:a,onDelete:i}){const{data:l}=Y2t(t?s.id:void 0),{data:o}=mt({queryKey:["agent-profile-flyer",s.agent_id],queryFn:async()=>{const{data:I,error:M}=await H.from("profiles").select("name, avatar_url, phone, title, brokerages:brokerage_id(name)").eq("id",s.agent_id).single();if(M)throw M;const L=I.brokerages;return{...I,brokerage_name:(L==null?void 0:L.name)||null}},enabled:!!s.agent_id}),[c,d]=N.useState(!1),[u,h]=N.useState(!1),[m,f]=N.useState(!1),[g,y]=N.useState(!1),x=N.useRef(null),_=`https://${wze}/${s.slug}`,b=I=>{if(!I)return"";const[M,L]=I.split(":"),z=parseInt(M),$=z>=12?"PM":"AM";return`${z>12?z-12:z||12}:${L} ${$}`},k=()=>{if(!(l!=null&&l.length))return;const I=["First Name","Last Name","Email","Phone","Address","Intent","Wants Market Updates","Message","Signed In"],M=l.map(W=>[W.first_name,W.last_name||"",W.email||"",W.phone||"",W.visitor_address||"",W.visitor_intent||"",W.wants_market_updates?"Yes":"No",(W.message||"").replace(/"/g,'""'),Js(new Date(W.created_at),"MM/dd/yyyy h:mm a")]),L=[I,...M].map(W=>W.map(G=>`"${G}"`).join(",")).join(` `),z=new Blob([L],{type:"text/csv"}),$=URL.createObjectURL(z),V=document.createElement("a");V.href=$,V.download=`${s.property_address.replace(/[^a-zA-Z0-9]/g,"-")}-visitors.csv`,V.click(),URL.revokeObjectURL($)},A=N.useCallback(()=>{if(!x.current)return;const I=x.current.querySelector("svg");if(!I)return;const M=new XMLSerializer().serializeToString(I),L=document.createElement("canvas");L.width=1024,L.height=1024;const z=L.getContext("2d"),$=new Image;$.onload=()=>{z==null||z.drawImage($,0,0,1024,1024);const V=document.createElement("a");V.download=`${s.property_address.replace(/[^a-zA-Z0-9]/g,"-")}-qr.png`,V.href=L.toDataURL("image/png"),V.click()},$.src="data:image/svg+xml;base64,"+btoa(unescape(encodeURIComponent(M)))},[s.property_address]),T=N.useCallback(()=>{var Ce;if(!x.current)return;const I=x.current.querySelector("svg");if(!I)return;const M=new XMLSerializer().serializeToString(I),L="data:image/svg+xml;base64,"+btoa(unescape(encodeURIComponent(M))),z=Js(new Date(s.event_date+"T00:00:00"),"EEEE, MMMM d, yyyy"),$=s.start_time?`${b(s.start_time)}${s.end_time?" – "+b(s.end_time):""}`:"",V=[s.city,s.state].filter(Boolean).join(", "),W=s.agent_greeting||"Welcome! Please sign in below.",G=!!s.photo_url,X=!!o,te=G||X,ne=G&&X,me=ne?"0.35in 0.75in 0.3in":"0.55in 0.75in 0.45in",ue=ne?"28px":"34px",ce=ne?"0.2in 0.75in":te?"0.3in 0.75in":"0.4in 0.75in",ae=te?"0.15in":"0.3in",he=te?"0.15in":"0.3in",xe=ne?"14px 36px":"22px 44px",ve=ne?"20px":"24px",ge=te?"0.2in":"0.35in",be=ne?"1.8in":"2.4in",Se=te?"0.15in":"0.3in",Ie=ne?"140px":te?"160px":"200px",Me=ne?"16px":"24px",Re=ne?"10px 20px":"16px 28px",Be=ne?"44px":"56px",Ne="0.15in",Ge=window.open("","_blank");Ge&&(Ge.document.write(` Open House – ${s.property_address}
${s.event_type==="community"?"Community Event":"Open House"}
${s.property_address}
${V?`
${V}${s.zip?" "+s.zip:""}
`:""}
Date
${z}
${$?`
Time
${$}
`:""}
${W}
${o?`
${o.avatar_url?`${o.name}`:`
${((Ce=o.name)==null?void 0:Ce.charAt(0))||"A"}
`}
Hosted By
${o.name}
${o.title?`
${o.title}
`:""} ${o.brokerage_name?`
${o.brokerage_name}
`:""} ${o.phone?`
${o.phone}
`:""}
`:""} ${s.photo_url?`Property`:""}
QR Code
Scan to Sign In
Point your phone camera at the QR code
`),Ge.document.close(),setTimeout(()=>{Ge.focus(),Ge.print()},500))},[s,_,o]),P=async()=>{y(!0);try{const{error:I}=await H.functions.invoke("guestbook-email-link",{body:{openHouseId:s.id}});if(I)throw I;xa({title:"Email sent!",description:"Check your inbox for the guest book link."})}catch(I){xa({title:"Failed to send",description:I.message,variant:"destructive"})}finally{y(!1)}};return e.jsxs(_e,{className:`transition-all ${s.is_active?"border-primary/30":"opacity-75"}`,children:[e.jsx(zt,{className:"pb-3",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(qt,{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:[e.jsx(We,{variant:s.is_active?"default":"secondary",className:"shrink-0 text-[11px]",children:s.is_active?"Active":"Inactive"}),s.kind==="virtual"?e.jsxs(We,{variant:"outline",className:"shrink-0 gap-1 text-[11px] bg-purple-50 text-purple-700 dark:bg-purple-900/30 dark:text-purple-300 border-purple-200 dark:border-purple-800",children:[e.jsx(da,{className:"h-3 w-3"}),"Virtual"]}):e.jsxs(We,{variant:"outline",className:"shrink-0 gap-1 text-[11px] bg-emerald-50 text-emerald-700 dark:bg-emerald-900/30 dark:text-emerald-300 border-emerald-200 dark:border-emerald-800",children:[e.jsx(ii,{className:"h-3 w-3"}),"In-Person"]}),s.agent_name&&e.jsxs(We,{variant:"outline",className:"shrink-0 gap-1 text-[11px] bg-blue-50 text-blue-700 dark:bg-blue-900/30 dark:text-blue-300 border-blue-200 dark:border-blue-800",children:[e.jsx(Ro,{className:"h-3 w-3"}),s.agent_name]}),s.event_type==="community"&&e.jsxs(We,{variant:"outline",className:"shrink-0 gap-1 text-[11px]",children:[e.jsx(Ti,{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(zy,{className:"h-4 w-4"}):e.jsx(Xo,{className:"h-4 w-4"})})]}),e.jsxs(_r,{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(ii,{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(Xr,{className:"h-3 w-3"}),"Always on"]}):e.jsxs(e.Fragment,{children:[e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(ta,{className:"h-3 w-3"}),Js(new Date(s.event_date+"T00:00:00"),"MMM d, yyyy")]}),s.start_time&&e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Xr,{className:"h-3 w-3"}),b(s.start_time),s.end_time?` – ${b(s.end_time)}`:""]})]}),e.jsxs("span",{className:"flex items-center gap-1 font-medium",children:[e.jsx(Yn,{className:"h-3 w-3"}),s.visitor_count," signed in"]}),s.qr_scan_count>0&&e.jsxs("span",{className:"flex items-center gap-1 text-muted-foreground",children:[e.jsx(M_,{className:"h-3 w-3"}),s.qr_scan_count," scan",s.qr_scan_count===1?"":"s"]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-2 sm:flex sm:flex-wrap sm:items-center",children:[e.jsxs(B,{variant:"outline",size:"sm",onClick:()=>window.location.href=`/mission-control/guest-book/live/${s.id}`,title:"Go Live",className:"h-9 w-full justify-center gap-1.5 text-xs text-emerald-600 border-emerald-200 hover:bg-emerald-50 dark:text-emerald-400 dark:border-emerald-800 dark:hover:bg-emerald-900/20 sm:h-8 sm:w-auto",children:[e.jsx(Y0,{className:"h-3.5 w-3.5"}),"Live"]}),e.jsxs(B,{variant:"outline",size:"sm",onClick:r,title:"Copy link",className:"h-9 w-full justify-center gap-1.5 text-xs sm:h-8 sm:w-auto",children:[e.jsx(Pa,{className:"h-3.5 w-3.5"}),"Copy"]}),s.kind==="virtual"&&e.jsxs(B,{variant:"outline",size:"sm",onClick:()=>f(!0),title:"Share tour via email",className:"h-9 w-full justify-center gap-1.5 text-xs text-primary border-primary/30 hover:bg-primary/10 sm:h-8 sm:w-auto",children:[e.jsx(Md,{className:"h-3.5 w-3.5"}),"Share"]}),s.kind==="virtual"&&e.jsxs(B,{variant:"outline",size:"sm",onClick:()=>window.open(`/guestbook/${s.slug}?preview=1`,"_blank"),title:"Preview tour as visitor",className:"h-9 w-full justify-center gap-1.5 text-xs text-primary border-primary/30 hover:bg-primary/10 sm:h-8 sm:w-auto",children:[e.jsx(da,{className:"h-3.5 w-3.5"}),"Preview Tour"]}),e.jsxs(B,{variant:"outline",size:"sm",onClick:()=>d(!0),title:"QR Code",className:"h-9 w-full justify-center gap-1.5 text-xs sm:h-8 sm:w-auto",children:[e.jsx(M_,{className:"h-3.5 w-3.5"}),"QR"]}),s.kind!=="virtual"&&e.jsxs(B,{variant:"outline",size:"sm",onClick:()=>window.open(`${_}?kiosk=1`,"_blank"),title:"Launch tablet/kiosk sign-in mode",className:"h-9 w-full justify-center gap-1.5 text-xs text-primary border-primary/30 hover:bg-primary/10 sm:h-8 sm:w-auto",children:[e.jsx(M9,{className:"h-3.5 w-3.5"}),"Tablet"]}),e.jsx(B,{variant:"outline",size:"sm",onClick:()=>h(!0),title:"Settings",className:"h-9 w-full justify-center text-xs sm:h-8 sm:w-auto",children:e.jsx(sc,{className:"h-3.5 w-3.5"})}),e.jsx(B,{variant:"outline",size:"sm",onClick:()=>window.open(_,"_blank"),title:"Preview",className:"h-9 w-full justify-center text-xs sm:h-8 sm:w-auto",children:e.jsx(Tr,{className:"h-3.5 w-3.5"})}),e.jsx(B,{variant:"outline",size:"sm",onClick:a,title:s.is_active?"Deactivate":"Activate",className:"h-9 w-full justify-center text-xs sm:h-8 sm:w-auto",children:s.is_active?e.jsx(V0,{className:"h-3.5 w-3.5"}):e.jsx(da,{className:"h-3.5 w-3.5"})}),e.jsx(B,{variant:"outline",size:"sm",onClick:i,title:"Delete",className:"h-9 w-full justify-center text-xs text-destructive border-destructive/30 hover:bg-destructive/10 sm:h-8 sm:w-auto",children:e.jsx(qn,{className:"h-3.5 w-3.5"})})]})]})}),t&&e.jsxs(De,{className:"pt-0",children:[e.jsx(Wl,{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://",wze,"/",s.slug]})]}),l!=null&&l.length?e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("p",{className:"text-xs font-medium text-muted-foreground",children:[l.length," Visitor",l.length!==1?"s":""]}),e.jsxs(B,{variant:"outline",size:"sm",onClick:k,className:"h-7 text-xs gap-1",children:[e.jsx(oi,{className:"h-3 w-3"}),"Export CSV"]})]}),e.jsx("div",{className:"rounded-lg border overflow-hidden",children:e.jsxs("table",{className:"w-full text-sm",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"bg-muted/30 text-xs text-muted-foreground",children:[e.jsx("th",{className:"text-left p-2 font-medium",children:"Name"}),e.jsx("th",{className:"text-left p-2 font-medium hidden sm:table-cell",children:"Contact"}),e.jsx("th",{className:"text-left p-2 font-medium hidden md:table-cell",children:"Intent"}),e.jsx("th",{className:"text-left p-2 font-medium",children:"Time"})]})}),e.jsx("tbody",{children:l.map(I=>e.jsxs("tr",{className:"border-t border-border/50",children:[e.jsxs("td",{className:"p-2 font-medium",children:[I.first_name,I.last_name?` ${I.last_name}`:""]}),e.jsxs("td",{className:"p-2 text-muted-foreground hidden sm:table-cell",children:[I.email&&e.jsx("div",{className:"truncate max-w-[180px]",children:I.email}),I.phone&&e.jsx("div",{className:"text-xs",children:I.phone}),I.visitor_address&&e.jsx("div",{className:"text-xs truncate max-w-[180px]",children:I.visitor_address})]}),e.jsx("td",{className:"p-2 hidden md:table-cell",children:I.visitor_intent?e.jsx(We,{variant:"outline",className:"text-xs capitalize",children:I.visitor_intent}):I.partial_signin?e.jsx(We,{variant:"outline",className:"text-xs text-amber-600 border-amber-300 dark:text-amber-400 dark:border-amber-700",children:"Didn't finish"}):null}),e.jsx("td",{className:"p-2 text-xs text-muted-foreground",children:Js(new Date(I.created_at),"h:mm a")})]},I.id))})]})})]}):e.jsx("p",{className:"text-sm text-muted-foreground text-center py-6",children:"No visitors yet. Share the link to start collecting sign-ins!"}),s.kind==="virtual"&&e.jsx("div",{className:"mt-4",children:e.jsx(J4n,{openHouseId:s.id})}),s.enable_survey&&e.jsx("div",{className:"mt-4",children:e.jsx(X4n,{openHouseId:s.id})})]}),e.jsx(Bs,{open:c,onOpenChange:d,children:e.jsxs(Fs,{className:"sm:max-w-sm",children:[e.jsxs(qs,{children:[e.jsx($s,{children:"QR Code"}),e.jsx(Ar,{className:"truncate",children:s.property_address})]}),e.jsxs("div",{className:"flex flex-col items-center gap-4 py-4",children:[e.jsx("div",{ref:x,className:"bg-white p-4 rounded-xl",children:e.jsx(IJ,{value:_,size:240,level:"H"})}),e.jsx("p",{className:"text-xs text-muted-foreground text-center break-all",children:_}),e.jsxs("div",{className:"flex gap-2 w-full",children:[e.jsxs(B,{variant:"outline",className:"flex-1",onClick:A,children:[e.jsx(oi,{className:"h-4 w-4 mr-2"}),"Download"]}),e.jsxs(B,{variant:"outline",className:"flex-1",onClick:T,children:[e.jsx(pW,{className:"h-4 w-4 mr-2"}),"Print Flyer"]})]}),e.jsxs(B,{variant:"default",className:"w-full",onClick:P,disabled:g,children:[e.jsx(mn,{className:"h-4 w-4 mr-2"}),g?"Sending...":"Email Link to Me"]})]})]})}),e.jsx(Y4n,{open:u,onOpenChange:h,openHouse:s}),s.kind==="virtual"&&e.jsx(e3n,{open:m,onOpenChange:f,openHouse:{id:s.id,slug:s.slug,property_address:s.property_address,city:s.city,state:s.state}})]})}function n3n(){const{slug:s}=uo();return s?e.jsx(pSt,{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 O9t({photoUrl:s,videoUrl:t,onPhotoChange:n,onVideoChange:r,contactId:a}){const{user:i}=Ls(),l=G3(),o=N.useRef(null),c=N.useRef(null),[d,u]=N.useState(!1),[h,m]=N.useState(!1),[f,g]=N.useState(0),y=async _=>{if(i){u(!0);try{const b=_.name.split(".").pop()||"jpg",k=`${i.id}/card-${Date.now()}.${b}`,{error:A}=await H.storage.from("listing-photos").upload(k,_);if(A)throw A;const{data:{publicUrl:T}}=H.storage.from("listing-photos").getPublicUrl(k);n(T),ie.success("Photo uploaded")}catch(b){ie.error(b.message||"Failed to upload photo")}finally{u(!1)}}},x=async _=>{if(i){if(_.size>500*1024*1024){ie.error("Video must be under 500MB");return}m(!0),g(0);try{const{videoId:b,libraryId:k}=await sO(`Card Video - ${Date.now()}`),{uploadUrl:A,apiKey:T}=await nO(b);await new Promise((M,L)=>{const z=new XMLHttpRequest;z.upload.addEventListener("progress",$=>{$.lengthComputable&&g(Math.round($.loaded/$.total*100))}),z.addEventListener("load",()=>{z.status>=200&&z.status<300?M():L(new Error("Upload failed"))}),z.addEventListener("error",()=>L(new Error("Upload failed"))),z.open("PUT",A),z.setRequestHeader("AccessKey",T),z.send(_)});const P=`https://iframe.mediadelivery.net/embed/${k}/${b}`;r(P);const I=parseFloat((_.size/(1024*1024)).toFixed(2));await l.mutateAsync({bunny_video_id:b,playback_url:`https://iframe.mediadelivery.net/play/${k}/${b}`,file_size_mb:I,title:"Card Video",status:"processing",touch_type:"video",contact_id:a||void 0}),ie.success("Video uploaded & added to your library")}catch(b){ie.error(b.message||"Failed to upload video")}finally{m(!1),g(0)}}};return e.jsxs("div",{className:"space-y-3",children:[e.jsx(re,{children:"Media (optional)"}),e.jsxs(ya,{defaultValue:"photo",className:"w-full",children:[e.jsxs(va,{className:"grid w-full grid-cols-2",children:[e.jsxs(ls,{value:"photo",className:"gap-1.5 text-xs",children:[e.jsx(pc,{className:"h-3.5 w-3.5"}),"Photo"]}),e.jsxs(ls,{value:"video",className:"gap-1.5 text-xs",children:[e.jsx(na,{className:"h-3.5 w-3.5"}),"Video"]})]}),e.jsxs(_s,{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(hr,{className:"h-3.5 w-3.5"})})]}):e.jsx("button",{onClick:()=>{var _;return(_=o.current)==null?void 0:_.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(us,{className:"h-6 w-6 animate-spin"}):e.jsxs(e.Fragment,{children:[e.jsx($0,{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:_=>{var k;const b=(k=_.target.files)==null?void 0:k[0];b&&y(b),_.target.value=""}})]}),e.jsxs(_s,{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(hr,{className:"h-3.5 w-3.5"})})]}):e.jsx("button",{onClick:()=>{var _;return(_=c.current)==null?void 0:_.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(us,{className:"h-6 w-6 animate-spin"}),e.jsxs("span",{className:"text-xs",children:["Uploading... ",f,"%"]}),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:`${f}%`}})})]}):e.jsxs(e.Fragment,{children:[e.jsx(ni,{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(VWe,{contactId:a,onVideoReady:_=>r(_)})}),e.jsx("input",{ref:c,type:"file",accept:"video/*",className:"hidden",onChange:_=>{var k;const b=(k=_.target.files)==null?void 0:k[0];b&&x(b),_.target.value=""}}),e.jsx("p",{className:"text-[10px] text-muted-foreground/60 mt-1.5 text-center",children:"Videos are also saved to your Video Library"})]})]})]})}const r3n=[{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 a3n({onSelect:s}){return e.jsx("div",{className:"grid grid-cols-2 gap-2.5",children:r3n.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 lq={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 xgt({initialOpen:s,initialCardType:t,initialContactId:n,initialRecipientName:r,initialAddress:a,initialDate:i,onOpenChange:l}){const{user:o}=Ls(),c=as(),[d,u]=N.useState(!1),[h,m]=N.useState("type"),[f,g]=N.useState(""),[y,x]=N.useState(null),[_,b]=N.useState(!1),[k,A]=N.useState("home_anniversary"),[T,P]=N.useState(""),[I,M]=N.useState(""),[L,z]=N.useState(""),[$,V]=N.useState(""),[W,G]=N.useState("elegant"),[X,te]=N.useState(null),[ne,me]=N.useState(null),ue=N.useState(!1);!ue[0]&&s&&t&&(ue[1](!0),u(!0),A(t),n&&x(n),r&&P(r),a&&M(a),i&&z(i),m(r?"details":"contact"));const{data:ce}=mt({queryKey:["contacts-for-card",o==null?void 0:o.id,f],queryFn:async()=>{let Be=H.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);f&&(Be=Be.or(`first_name.ilike.%${f}%,last_name.ilike.%${f}%`));const{data:Ne,error:Ge}=await Be;if(Ge)throw Ge;return Ne},enabled:!!(o!=null&&o.id)&&d}),{data:ae}=mt({queryKey:["agent-profile-card",o==null?void 0:o.id],queryFn:async()=>{const{data:Be,error:Ne}=await H.from("profiles").select("name, email, phone, avatar_url, brokerage:brokerages(name)").eq("id",o.id).single();if(Ne)throw Ne;return Be},enabled:!!(o!=null&&o.id)}),he=Be=>{x(Be.id),P(`${Be.first_name}${Be.last_name?" "+Be.last_name:""}`),M([Be.address,Be.city,Be.state].filter(Boolean).join(", "));const Ne=k==="wedding_anniversary"?Be.wedding_anniversary:k==="home_anniversary"?Be.home_anniversary:"";z(Ne||""),m("details")},xe=Be=>{A(Be),m("contact")},ve=async()=>{var Be;if(!(!o||!ae)){b(!0);try{const Ne={owner_user_id:o.id,contact_id:y,card_type:k,template:W,recipient_name:T,property_address:I||null,home_anniversary_date:L||null,custom_message:$||null,property_photo_url:X||null,video_url:ne||null,agent_name:ae.name||"Agent",agent_photo_url:ae.avatar_url,agent_phone:ae.phone,agent_email:ae.email,agent_brokerage:((Be=ae.brokerage)==null?void 0:Be.name)||null},{error:Ge}=await H.from("sendable_cards").insert(Ne);if(Ge)throw Ge;ie.success("Card created! Copy the link to share it."),c.invalidateQueries({queryKey:["sendable-cards"]}),ge()}catch(Ne){ie.error(Ne.message||"Failed to create card")}finally{b(!1)}}},ge=()=>{u(!1),m("type"),A("home_anniversary"),g(""),x(null),P(""),M(""),z(""),V(""),G("elegant"),te(null),me(null)},be={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"},Se=lq[k],Ie=k==="home_anniversary"||k==="wedding_anniversary",Me=k==="wedding_anniversary"?"Wedding Anniversary Date":"Home Anniversary Date",Re=["home_anniversary","just_listed","just_sold"].includes(k);return e.jsxs(Bs,{open:d,onOpenChange:Be=>{Be?u(!0):(ge(),l==null||l(!1))},children:[e.jsx(Ao,{asChild:!0,children:e.jsxs(B,{className:"gap-2",children:[e.jsx(nn,{className:"h-4 w-4"}),"Create Card"]})}),e.jsxs(Fs,{className:"sm:max-w-lg max-h-[90vh] overflow-y-auto",children:[e.jsx(qs,{children:e.jsx($s,{children:h==="type"?"What type of card?":h==="contact"?`${be[k]} — Choose a Contact`:`${be[k]} — Customize`})}),h==="type"&&e.jsx(a3n,{onSelect:xe}),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(Gr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(we,{placeholder:"Search contacts...",value:f,onChange:Be=>g(Be.target.value),className:"pl-9"})]}),e.jsxs("div",{className:"space-y-1 max-h-64 overflow-y-auto",children:[ce==null?void 0:ce.map(Be=>e.jsxs("button",{onClick:()=>he(Be),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(Ro,{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:[Be.first_name," ",Be.last_name]}),Be.address&&e.jsxs("p",{className:"text-xs text-muted-foreground truncate flex items-center gap-1",children:[e.jsx(_a,{className:"h-3 w-3"}),Be.address]})]}),(k==="home_anniversary"&&Be.home_anniversary||k==="wedding_anniversary"&&Be.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"})]},Be.id)),(ce==null?void 0:ce.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(re,{children:"Recipient Name"}),e.jsx(we,{value:T,onChange:Be=>P(Be.target.value),placeholder:"John & Jane Smith"})]}),Re&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{children:"Property Address"}),e.jsx(we,{value:I,onChange:Be=>M(Be.target.value),placeholder:"123 Main St, Austin, TX"})]}),Ie&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{children:Me}),e.jsx(we,{type:"date",value:L,onChange:Be=>z(Be.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{children:"Personal Message (optional)"}),e.jsx(Ws,{value:$,onChange:Be=>V(Be.target.value),placeholder:Se.defaultMessage,rows:3})]}),e.jsx(O9t,{photoUrl:X,videoUrl:ne,onPhotoChange:te,onVideoChange:me,contactId:y}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{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:Be,label:Ne,gradient:Ge})=>e.jsxs("button",{onClick:()=>G(Be),className:`p-2 rounded-lg border-2 transition-all text-center ${W===Be?"border-primary bg-primary/5":"border-border hover:border-primary/30"}`,children:[e.jsx("div",{className:`h-10 rounded-md mb-1.5 ${Ge}`}),e.jsx("span",{className:"text-[10px] font-medium",children:Ne})]},Be))})]}),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:ve,disabled:!T||_,className:"flex-1 gap-2",children:_?"Creating...":"Create Card"})]})]})]})]})}function i3n({open:s,onOpenChange:t}){const n=tr(),r=a=>{t(!1),n(a)};return e.jsx(Bs,{open:s,onOpenChange:t,children:e.jsxs(Fs,{className:"sm:max-w-md",children:[e.jsxs(qs,{children:[e.jsx($s,{children:"Set up an email sender"}),e.jsx(Ar,{children:"To send emails from the platform, connect Gmail or verify a Mass Email (Amazon SES) sender address. Either option lets you send from your own email."})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("button",{onClick:()=>r("/integrations"),className:"w-full flex items-start gap-3 rounded-lg border p-4 text-left hover:bg-muted/50 transition",children:[e.jsx(mn,{className:"h-5 w-5 mt-0.5 text-primary"}),e.jsxs("div",{children:[e.jsx("div",{className:"font-medium",children:"Connect Gmail"}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"Send from your Google account with your full inbox history."})]})]}),e.jsxs("button",{onClick:()=>r("/integrations"),className:"w-full flex items-start gap-3 rounded-lg border p-4 text-left hover:bg-muted/50 transition",children:[e.jsx(n3,{className:"h-5 w-5 mt-0.5 text-primary"}),e.jsxs("div",{children:[e.jsx("div",{className:"font-medium",children:"Verify a Mass Email sender"}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"Send via Amazon SES from any verified email address you own."})]})]}),e.jsx("div",{className:"flex justify-end pt-2",children:e.jsx(B,{variant:"ghost",onClick:()=>t(!1),children:"Not now"})})]})]})})}const o3n={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 l3n({card:s}){const{user:t}=Ls(),{isGmailConnected:n,hasVerifiedSes:r,canSendEmail:a,sendMethod:i}=_f(),l=as(),[o,c]=N.useState(!1),[d,u]=N.useState(!1),[h,m]=N.useState("");N.useEffect(()=>{o&&s.contact_id&&!h&&H.from("innercircle_contacts").select("email").eq("id",s.contact_id).maybeSingle().then(({data:T})=>{T!=null&&T.email&&m(T.email)})},[o,s.contact_id]);const f={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}!`},[g,y]=N.useState(f[s.card_type]||`A Special Card for ${s.recipient_name}!`),[x,_]=N.useState(""),b=`https://cardstudio.relevelup.com/c/${s.share_token}`,k=_t({mutationFn:async()=>{var L;if(!h)throw new Error("Recipient email is required");const T=`
${x?`

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


`:""}

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

${s.property_address?`

${s.property_address}

`:""}
`,{data:P}=await H.auth.getSession(),I=(L=P==null?void 0:P.session)==null?void 0:L.access_token,M=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/gmail-send",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${I}`},body:JSON.stringify({to:h,subject:g,body:T,contactId:s.contact_id||void 0})});if(!M.ok){const z=await M.json();throw new Error(z.error||"Failed to send")}return M.json()},onSuccess:async()=>{await H.from("sendable_cards").update({sent_at:new Date().toISOString(),sent_via:"gmail"}).eq("id",s.id),l.invalidateQueries({queryKey:["sendable-cards"]}),ie.success(`Card sent to ${h}!`),c(!1)},onError:T=>{ie.error(T.message||"Failed to send email")}}),A=i==="mass_email"?"Mass Email":"Gmail";return a?e.jsxs(Bs,{open:o,onOpenChange:c,children:[e.jsx(Ao,{asChild:!0,children:e.jsx(B,{variant:"outline",size:"sm",className:"gap-1 text-xs",children:e.jsx(Rr,{className:"h-3 w-3"})})}),e.jsxs(Fs,{className:"sm:max-w-md",children:[e.jsx(qs,{children:e.jsxs($s,{children:["Send Card via ",A]})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{htmlFor:"gmail-to",children:"To"}),e.jsx(eIt,{value:h,onChange:m,userId:t==null?void 0:t.id,placeholder:"Search contacts or type an email..."}),e.jsx("p",{className:"text-[11px] text-muted-foreground",children:"Pick from your Agent OS contacts, or type any email address."})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{children:"Subject"}),e.jsx(we,{value:g,onChange:T=>y(T.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{children:"Personal Note (optional)"}),e.jsx(Ws,{value:x,onChange:T=>_(T.target.value),placeholder:"Add a warm personal note before the card link...",rows:3})]}),e.jsxs("div",{className:"rounded-lg bg-muted/50 p-3 text-xs text-muted-foreground",children:[i==="mass_email"?e.jsx(e.Fragment,{children:"Sending via your verified Mass Email sender (Gmail isn't connected)."}):e.jsx(e.Fragment,{children:"The email will include a beautiful button linking to your card at:"}),e.jsx("br",{}),e.jsx("span",{className:"font-mono text-foreground",children:b})]}),e.jsx(B,{onClick:()=>k.mutate(),disabled:!h||k.isPending,className:"w-full gap-2",children:k.isPending?e.jsxs(e.Fragment,{children:[e.jsx(us,{className:"h-4 w-4 animate-spin"})," Sending..."]}):e.jsxs(e.Fragment,{children:[e.jsx(Rr,{className:"h-4 w-4"})," Send Card"]})})]})]})]}):e.jsxs(e.Fragment,{children:[e.jsx(B,{variant:"outline",size:"sm",className:"gap-1 text-xs",title:"Set up an email sender to send cards",onClick:()=>u(!0),children:e.jsx(Rr,{className:"h-3 w-3"})}),e.jsx(i3n,{open:d,onOpenChange:u})]})}function c3n({card:s}){const t=as(),[n,r]=N.useState(!1),[a,i]=N.useState(!1),[l,o]=N.useState(s.recipient_name),[c,d]=N.useState(s.property_address||""),[u,h]=N.useState(s.home_anniversary_date||""),[m,f]=N.useState(s.custom_message||""),[g,y]=N.useState(s.template),[x,_]=N.useState(s.property_photo_url),[b,k]=N.useState(s.video_url||null),A=P=>{P&&(o(s.recipient_name),d(s.property_address||""),h(s.home_anniversary_date||""),f(s.custom_message||""),y(s.template),_(s.property_photo_url),k(s.video_url||null)),r(P)},T=async()=>{if(!l.trim()){ie.error("Recipient name is required");return}i(!0);try{const{error:P}=await H.from("sendable_cards").update({recipient_name:l.trim(),property_address:c.trim()||null,home_anniversary_date:u||null,custom_message:m.trim()||null,template:g,property_photo_url:x||null,video_url:b||null}).eq("id",s.id);if(P)throw P;t.invalidateQueries({queryKey:["sendable-cards"]}),ie.success("Card updated"),r(!1)}catch(P){ie.error(P.message||"Failed to update card")}finally{i(!1)}};return e.jsxs(Bs,{open:n,onOpenChange:A,children:[e.jsx(Ao,{asChild:!0,children:e.jsx(B,{variant:"outline",size:"sm",className:"gap-1 text-xs",children:e.jsx(Ja,{className:"h-3 w-3"})})}),e.jsxs(Fs,{className:"sm:max-w-lg max-h-[90vh] overflow-y-auto",children:[e.jsx(qs,{children:e.jsx($s,{children:"Edit Card"})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{children:"Recipient Name"}),e.jsx(we,{value:l,onChange:P=>o(P.target.value),placeholder:"John & Jane Smith"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{children:"Property Address"}),e.jsx(we,{value:c,onChange:P=>d(P.target.value),placeholder:"123 Main St, Austin, TX"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{children:"Home Anniversary Date"}),e.jsx(we,{type:"date",value:u,onChange:P=>h(P.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{children:"Personal Message (optional)"}),e.jsx(Ws,{value:m,onChange:P=>f(P.target.value),placeholder:"Wishing you many more happy years in your beautiful home!",rows:3})]}),e.jsx(O9t,{photoUrl:x,videoUrl:b,onPhotoChange:_,onVideoChange:k,contactId:s.contact_id}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{children:"Template Style"}),e.jsx("div",{className:"grid grid-cols-3 gap-2",children:["elegant","bold","warm"].map(P=>e.jsxs("button",{onClick:()=>y(P),className:`p-3 rounded-lg border-2 transition-all text-center ${g===P?"border-primary bg-primary/5":"border-border hover:border-primary/30"}`,children:[e.jsx("div",{className:`h-12 rounded-md mb-2 ${P==="elegant"?"bg-gradient-to-br from-slate-100 to-slate-200 dark:from-slate-800 dark:to-slate-700":P==="bold"?"bg-gradient-to-br from-violet-500 to-fuchsia-500":"bg-gradient-to-br from-amber-200 to-orange-300"}`}),e.jsx("span",{className:"text-xs font-medium capitalize",children:P})]},P))})]}),e.jsx(B,{onClick:T,disabled:!l.trim()||a,className:"w-full gap-2",children:a?e.jsxs(e.Fragment,{children:[e.jsx(us,{className:"h-4 w-4 animate-spin"})," Saving..."]}):"Save Changes"})]})]})]})}function d3n(){const{user:s}=Ls(),t=as(),[n,r]=N.useState(""),[a,i]=$c(),l=a.get("cardType"),o=a.get("contactId"),c=a.get("name"),d=a.get("address"),u=a.get("date"),h=!!l,{data:m,isLoading:f}=mt({queryKey:["sendable-cards",s==null?void 0:s.id],queryFn:async()=>{const{data:k,error:A}=await H.from("sendable_cards").select("*").eq("owner_user_id",s.id).order("created_at",{ascending:!1});if(A)throw A;return k},enabled:!!(s!=null&&s.id)}),g=_t({mutationFn:async k=>{const{error:A}=await H.from("sendable_cards").delete().eq("id",k);if(A)throw A},onSuccess:()=>{t.invalidateQueries({queryKey:["sendable-cards"]}),ie.success("Card deleted")}}),y=k=>{const A=`https://cardstudio.relevelup.com/c/${k}`;navigator.clipboard.writeText(A),ie.success("Share link copied!")},x=m==null?void 0:m.filter(k=>{var A;return!n||k.recipient_name.toLowerCase().includes(n.toLowerCase())||((A=k.property_address)==null?void 0:A.toLowerCase().includes(n.toLowerCase()))}),_={elegant:"Elegant",bold:"Bold",warm:"Warm"},b={home_anniversary:"Home Anniversary",wedding_anniversary:"Wedding Anniversary",just_listed:"Just Listed",just_sold:"Just Sold",congratulations:"Congratulations",birthday:"Birthday",holiday:"Holiday",thank_you:"Thank You",thinking_of_you:"Thinking of You"};return e.jsx(Qs,{title:"Card Studio",children:e.jsxs("div",{className:"max-w-6xl mx-auto space-y-6",children:[e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center justify-between gap-4",children:[e.jsxs("div",{children:[e.jsx("div",{className:"flex items-center gap-2",children:e.jsx("h1",{className:"text-2xl font-bold text-foreground",children:"Card Studio"})}),e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:"Create & send beautiful branded cards to your clients"})]}),e.jsx(xgt,{initialOpen:h,initialCardType:l,initialContactId:o||void 0,initialRecipientName:c||void 0,initialAddress:d||void 0,initialDate:u||void 0,onOpenChange:()=>i({})})]}),e.jsxs("div",{className:"relative max-w-sm",children:[e.jsx(Gr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(we,{placeholder:"Search cards...",value:n,onChange:k=>r(k.target.value),className:"pl-9"})]}),f?e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4",children:[1,2,3].map(k=>e.jsx(_e,{className:"animate-pulse",children:e.jsxs(De,{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"})]})},k))}):x!=null&&x.length?e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4",children:x.map(k=>e.jsxs(_e,{className:"group overflow-hidden hover:shadow-lg transition-shadow",children:[e.jsxs("div",{className:`aspect-[16/10] flex items-center justify-center relative overflow-hidden ${k.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":k.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:[k.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"})]}),k.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%)]"})]}),k.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:k.card_type==="home_anniversary"?"🏡":k.card_type==="wedding_anniversary"?"💍":k.card_type==="birthday"?"🎂":k.card_type==="just_sold"?"🎉":k.card_type==="just_listed"?"🏠":k.card_type==="thank_you"?"💐":k.card_type==="congratulations"?"🏆":k.card_type==="holiday"?"🎄":k.card_type==="thinking_of_you"?"💭":"✉️"}),e.jsx("p",{className:`text-[10px] uppercase tracking-[0.2em] mb-1 ${k.template==="bold"?"text-white/70":"text-muted-foreground"}`,children:b[k.card_type]||k.card_type}),e.jsx("p",{className:`font-semibold text-base ${k.template==="bold"?"text-white":"text-foreground"}`,children:k.recipient_name}),k.property_address&&e.jsx("p",{className:`text-xs mt-1 ${k.template==="bold"?"text-white/60":"text-muted-foreground"}`,children:k.property_address})]}),e.jsx("div",{className:"absolute top-2 right-2 z-10",children:e.jsx(We,{variant:k.template==="bold"?"outline":"secondary",className:`text-[10px] ${k.template==="bold"?"border-white/30 text-white/80":""}`,children:_[k.template]||k.template})})]}),e.jsxs(De,{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(da,{className:"h-3 w-3"}),k.view_count," views"]}),e.jsx("span",{className:"text-xs text-muted-foreground",children:nc(new Date(k.created_at),{addSuffix:!0})})]}),k.sent_at&&e.jsxs("p",{className:"text-[10px] text-emerald-600 mb-2",children:["Sent ",Js(new Date(k.sent_at),"MMM d, yyyy")," via ",k.sent_via]}),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:()=>y(k.share_token),children:[e.jsx(Pa,{className:"h-3 w-3"}),"Copy Link"]}),e.jsx(c3n,{card:k}),e.jsx(l3n,{card:k}),e.jsx(B,{variant:"outline",size:"sm",className:"gap-1 text-xs",onClick:()=>window.open(`https://cardstudio.relevelup.com/c/${k.share_token}`,"_blank"),children:e.jsx(Tr,{className:"h-3 w-3"})}),e.jsx(B,{variant:"ghost",size:"sm",className:"text-destructive hover:text-destructive gap-1 text-xs",onClick:()=>g.mutate(k.id),children:e.jsx(qn,{className:"h-3 w-3"})})]})]})]},k.id))}):e.jsx(_e,{className:"border-dashed",children:e.jsxs(De,{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(mn,{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(xgt,{initialOpen:h,initialCardType:l,initialContactId:o||void 0,initialRecipientName:c||void 0,initialAddress:d||void 0,initialDate:u||void 0,onOpenChange:()=>i({})})]})})]})})}const Lne=[{id:"mls",label:"MLS Description",tag:"Standard",icon:_a,accent:"from-sky-500 to-cyan-500",desc:"Polished MLS-ready listing",category:"listing"},{id:"luxury",label:"Luxury MLS",tag:"Premium",icon:q0,accent:"from-amber-500 to-orange-500",desc:"Evocative, high-end voice",category:"listing"},{id:"short",label:"Short MLS",tag:"Concise",icon:ff,accent:"from-violet-500 to-fuchsia-500",desc:"Punchy 60–90 words",category:"listing"},{id:"openHouse",label:"Open House",tag:"Promo",icon:h5,accent:"from-emerald-500 to-teal-500",desc:"Friendly invite copy",category:"listing",extras:["openHouse"]},{id:"newConstruction",label:"New Construction",tag:"Build",icon:ZG,accent:"from-rose-500 to-pink-500",desc:"Builder-focused angle",category:"listing",extras:["newConstruction"]},{id:"investment",label:"Investment",tag:"ROI",icon:ml,accent:"from-indigo-500 to-blue-500",desc:"Cap rate & income hooks",category:"listing",extras:["investment"]},{id:"facebookPost",label:"Facebook Post",tag:"Social",icon:Kf,accent:"from-blue-600 to-blue-400",desc:"Engaging FB caption",category:"social"},{id:"instagramPost",label:"Instagram Post",tag:"Social",icon:dm,accent:"from-pink-500 via-fuchsia-500 to-orange-400",desc:"IG caption + hashtags",category:"social"},{id:"linkedinPost",label:"LinkedIn Post",tag:"Social",icon:W0,accent:"from-sky-700 to-sky-500",desc:"Professional tone",category:"social"},{id:"justListed",label:"Just Listed",tag:"Announce",icon:um,accent:"from-emerald-500 to-green-500",desc:"Hit the market announcement",category:"social"},{id:"comingSoon",label:"Coming Soon",tag:"Tease",icon:Xr,accent:"from-amber-500 to-yellow-500",desc:"Build pre-market buzz",category:"social",extras:["comingSoon"]},{id:"priceImprovement",label:"Price Improvement",tag:"Update",icon:eN,accent:"from-orange-500 to-red-500",desc:"New price announcement",category:"social",extras:["priceImprovement"]},{id:"openHousePost",label:"Open House Post",tag:"Event",icon:ld,accent:"from-teal-500 to-emerald-500",desc:"Social invite to OH",category:"social",extras:["openHouse"]},{id:"underContract",label:"Under Contract",tag:"Status",icon:GG,accent:"from-indigo-500 to-purple-500",desc:"Pending celebration",category:"social",extras:["underContract"]},{id:"justSold",label:"Just Sold",tag:"Celebrate",icon:uf,accent:"from-fuchsia-500 to-pink-500",desc:"Sold success post",category:"social",extras:["sold"]},{id:"propertyTourScript",label:"Property Tour",tag:"Script",icon:na,accent:"from-red-500 to-rose-500",desc:"Full walkthrough script",category:"video",extras:["signoff"]},{id:"reelScript",label:"Reel Script",tag:"Short",icon:Rh,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:uj,accent:"from-violet-500 to-purple-500",desc:"5 scroll-stopping hooks",category:"video",extras:["vibe"]},{id:"luxuryWalkthrough",label:"Luxury Walkthrough",tag:"Premium",icon:q0,accent:"from-amber-500 to-yellow-500",desc:"Cinematic, refined tone",category:"video",extras:["signoff"]},{id:"droneScript",label:"Drone Script",tag:"Aerial",icon:hW,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:ii,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:mn,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:x9,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:Yn,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:eN,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:wT,accent:"from-fuchsia-500 to-pink-500",desc:"Sold announcement email",category:"email",extras:["sold","signoff"]},{id:"neighborhoodEmail",label:"Neighborhood Email",tag:"Nurture",icon:ii,accent:"from-sky-500 to-indigo-500",desc:"Area update / market touch",category:"email",extras:["neighborhood","signoff"]}];function u3n(){var Jr,Or,ja,ea,dr,Wi,ho,oa,Ha,$i,Ta;const{user:s}=Ls(),[t,n]=N.useState(""),[r,a]=N.useState(""),[i,l]=N.useState([]),[o,c]=N.useState(""),[d,u]=N.useState([]),[h,m]=N.useState(""),[f,g]=N.useState(""),[y,x]=N.useState(""),[_,b]=N.useState(""),[k,A]=N.useState(""),[T,P]=N.useState(""),[I,M]=N.useState(""),[L,z]=N.useState(null),[$,V]=N.useState(""),[W,G]=N.useState(""),[X,te]=N.useState(""),[ne,me]=N.useState(""),[ue,ce]=N.useState(""),[ae,he]=N.useState(""),[xe,ve]=N.useState(""),[ge,be]=N.useState(""),[Se,Ie]=N.useState(""),[Me,Re]=N.useState(""),[Be,Ne]=N.useState(""),[Ge,Ce]=N.useState(""),[Fe,Ae]=N.useState(""),[Xe,$e]=N.useState(""),[Ye,Je]=N.useState(""),[Ke,st]=N.useState(""),[rt,Ze]=N.useState(""),[ht,Bt]=N.useState(""),[Ct,Yt]=N.useState(""),[Kt,Xs]=N.useState(""),[zs,Vt]=N.useState(""),[At,Os]=N.useState(""),[Nt,ms]=N.useState(""),[Ys,It]=N.useState(""),[Ds,As]=N.useState(""),[Hs,Rs]=N.useState("listing"),[en,Rn]=N.useState("mls"),[Bn,Dn]=N.useState({}),[Jn,ua]=N.useState({}),[Mr,sn]=N.useState(!1),[ki,ia]=N.useState(!1),vr=Wn=>{Rs(Wn);const Ra=Lne.find(mo=>mo.category===Wn);Ra&&Rn(Ra.id)},{data:Nr}=mt({queryKey:["listing-studio-listings",s==null?void 0:s.id],enabled:!!(s!=null&&s.id)&&Mr,queryFn:async()=>{const{data:Wn,error:Ra}=await H.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(Ra)throw Ra;return Wn||[]}}),rn=()=>{const Wn=o.trim();Wn&&(l(Ra=>[...Ra,Wn]),c(""))},Zn=Wn=>l(Ra=>Ra.filter((mo,Ho)=>Ho!==Wn)),sa=Wn=>{var Ra,mo,Ho,No;z(Wn.id),n(Wn.property_address||""),P(Wn.city||""),M(Wn.state||""),b(((Ra=Wn.price)==null?void 0:Ra.toString())||""),m(((mo=Wn.bedrooms)==null?void 0:mo.toString())||""),g(((Ho=Wn.bathrooms)==null?void 0:Ho.toString())||""),x(((No=Wn.square_footage)==null?void 0:No.toString())||""),A(Wn.property_type||""),a(Wn.description||""),sn(!1),ie.success("Listing imported")},xs=async Wn=>{if(!(!Wn.target.files||!(s!=null&&s.id))){ia(!0);try{const Ra=[];for(const mo of Array.from(Wn.target.files).slice(0,10)){const Ho=`${s.id}/${Date.now()}-${mo.name.replace(/[^\w.-]/g,"_")}`,{error:No}=await H.storage.from("listing-photos").upload(Ho,mo,{upsert:!1});if(No){console.error(No);continue}const{data:Go}=H.storage.from("listing-photos").getPublicUrl(Ho);Ra.push(Go.publicUrl)}u(mo=>[...mo,...Ra]),Ra.length&&ie.success(`${Ra.length} photo(s) uploaded`)}catch(Ra){ie.error(Ra.message||"Photo upload failed")}finally{ia(!1)}}},Ve=Lne.find(Wn=>Wn.id===en),it=async Wn=>{var mo,Ho,No;const Ra=Lne.find(Go=>Go.id===Wn);if(!t.trim()&&!r.trim()&&i.length===0){ie.error("Add a property address, MLS remarks, or features first");return}if((mo=Ra.extras)!=null&&mo.includes("openHouse")&&(!$||!W||!X)){ie.error("Add the open house date, start and end time");return}if((Ho=Ra.extras)!=null&&Ho.includes("priceImprovement")&&(!ne||!ue)){ie.error("Add previous and new price");return}if((No=Ra.extras)!=null&&No.includes("sold")&&!ae){ie.error("Add the sold price");return}Rn(Wn),ua(Go=>({...Go,[Wn]:!0}));try{const{data:Go,error:Dd}=await H.functions.invoke("listing-studio-generate",{body:{copyType:Wn,propertyAddress:t,mlsRemarks:r,features:i,photoUrls:d,listingId:L,bedrooms:h?Number(h):null,bathrooms:f?Number(f):null,squareFootage:y?Number(y):null,price:_?Number(_):null,propertyType:k||null,city:T||null,state:I||null,openHouseDate:$||null,openHouseStart:W||null,openHouseEnd:X||null,previousPrice:ne?Number(ne):null,newPrice:ue?Number(ue):null,soldPrice:ae?Number(ae):null,soldDate:xe||null,comingSoonDate:ge||null,builderName:Se||null,yearBuilt:Me?Number(Me):null,warrantyInfo:Be||null,monthlyRent:Ge?Number(Ge):null,capRate:Fe||null,occupancy:Xe||null,daysOnMarket:Ye?Number(Ye):null,offerCount:Ke?Number(Ke):null,originalListPrice:rt?Number(rt):null,soldDaysOnMarket:ht?Number(ht):null,commissionOffered:Ct||null,refreshments:Kt||null,vibe:zs||null,neighborhoodHighlights:At||null,agentName:Nt||null,agentBrokerage:Ys||null,agentContact:Ds||null}});if(Dd)throw Dd;if(Go!=null&&Go.error)throw new Error(Go.error);Dn(Tu=>({...Tu,[Wn]:Go.content}))}catch(Go){ie.error(Go.message||"Generation failed")}finally{ua(Go=>({...Go,[Wn]:!1}))}},ft=Wn=>{navigator.clipboard.writeText(Wn),ie.success("Copied to clipboard")},kt=Ve.icon,Ut=Bn[en]?Bn[en].trim().split(/\s+/).length:0,es=Wn=>e.jsx("div",{className:"grid grid-cols-2 sm:grid-cols-3 gap-3",children:Lne.filter(Ra=>Ra.category===Wn).map(Ra=>{const mo=Ra.icon,Ho=en===Ra.id,No=!!Bn[Ra.id];return e.jsxs("button",{onClick:()=>Rn(Ra.id),className:Ot("relative text-left p-4 rounded-2xl border transition-all overflow-hidden group",Ho?"border-primary shadow-lg shadow-primary/10 bg-card":"border-border/60 hover:border-border bg-card/50 hover:bg-card"),children:[Ho&&e.jsx("div",{className:Ot("absolute inset-0 opacity-[0.07] bg-gradient-to-br",Ra.accent)}),e.jsxs("div",{className:"relative space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("div",{className:Ot("h-9 w-9 rounded-xl grid place-items-center text-white bg-gradient-to-br shadow-sm",Ra.accent),children:e.jsx(mo,{className:"h-4 w-4"})}),No&&e.jsx("div",{className:"h-5 w-5 rounded-full bg-emerald-500/15 text-emerald-600 grid place-items-center",children:e.jsx(pa,{className:"h-3 w-3"})})]}),e.jsxs("div",{children:[e.jsx("div",{className:"font-semibold text-sm",children:Ra.label}),e.jsx("div",{className:"text-xs text-muted-foreground line-clamp-1",children:Ra.desc})]})]})]},Ra.id)})}),Ms=(Jr=Ve.extras)==null?void 0:Jr.includes("openHouse"),bs=(Or=Ve.extras)==null?void 0:Or.includes("priceImprovement"),Zs=(ja=Ve.extras)==null?void 0:ja.includes("sold"),kn=(ea=Ve.extras)==null?void 0:ea.includes("comingSoon"),gn=(dr=Ve.extras)==null?void 0:dr.includes("newConstruction"),xr=(Wi=Ve.extras)==null?void 0:Wi.includes("investment"),Kr=(ho=Ve.extras)==null?void 0:ho.includes("underContract"),ca=(oa=Ve.extras)==null?void 0:oa.includes("brokerOpen"),Er=(Ha=Ve.extras)==null?void 0:Ha.includes("vibe"),qr=($i=Ve.extras)==null?void 0:$i.includes("neighborhood"),Xt=(Ta=Ve.extras)==null?void 0:Ta.includes("signoff"),Gn=Ms||bs||Zs||kn||gn||xr||Kr||ca||Er||qr||Xt;return e.jsx(Qs,{title:"Listing Studio",children:e.jsxs("div",{className:"space-y-8 animate-fade-in",children:[e.jsxs("div",{className:"relative overflow-hidden rounded-3xl border bg-gradient-to-br from-fuchsia-500/10 via-violet-500/5 to-sky-500/10 dark:from-fuchsia-500/20 dark:via-violet-500/10 dark:to-sky-500/20",children:[e.jsx("div",{className:"absolute inset-0 bg-[radial-gradient(circle_at_top_right,_hsl(var(--primary)/0.15),_transparent_60%)]"}),e.jsx("div",{className:"absolute -top-24 -right-24 h-72 w-72 rounded-full bg-fuchsia-500/20 blur-3xl"}),e.jsx("div",{className:"absolute -bottom-24 -left-24 h-72 w-72 rounded-full bg-sky-500/20 blur-3xl"}),e.jsxs("div",{className:"relative px-6 py-8 sm:px-10 sm:py-12 flex flex-col md:flex-row md:items-center gap-6",children:[e.jsxs("div",{className:"flex-1 space-y-3",children:[e.jsxs("div",{className:"inline-flex items-center gap-2 px-3 py-1 rounded-full bg-background/60 backdrop-blur-sm border text-xs font-medium",children:[e.jsx(Cn,{className:"h-3.5 w-3.5 text-fuchsia-500"}),"AI-powered listing & social copy"]}),e.jsx("h1",{className:"text-3xl sm:text-4xl font-bold tracking-tight bg-gradient-to-br from-foreground to-foreground/60 bg-clip-text",children:"Listing Studio"}),e.jsx("p",{className:"text-muted-foreground max-w-xl",children:"Drop in a property, generate magnetic MLS copy, luxury narratives, open-house promos, and ready-to-post social content — all in seconds."})]}),e.jsxs(Bs,{open:Mr,onOpenChange:sn,children:[e.jsx(Ao,{asChild:!0,children:e.jsxs(B,{size:"lg",variant:"secondary",className:"shadow-lg shadow-fuchsia-500/10",children:[e.jsx(Wr,{className:"h-4 w-4 mr-2"}),"Import from Listings"]})}),e.jsxs(Fs,{className:"max-w-2xl max-h-[80vh] overflow-y-auto",children:[e.jsx(qs,{children:e.jsx($s,{children:"Import from Listing Exchange"})}),e.jsxs("div",{className:"space-y-2 mt-2",children:[!(Nr!=null&&Nr.length)&&e.jsx("p",{className:"text-sm text-muted-foreground py-8 text-center",children:"No listings found yet."}),Nr==null?void 0:Nr.map(Wn=>e.jsxs("button",{onClick:()=>sa(Wn),className:"w-full text-left p-4 border rounded-xl hover:border-primary hover:bg-accent/50 transition-all",children:[e.jsx("div",{className:"font-medium",children:Wn.property_address||"Untitled listing"}),e.jsxs("div",{className:"text-sm text-muted-foreground mt-0.5",children:[[Wn.city,Wn.state].filter(Boolean).join(", "),Wn.price?` · $${Number(Wn.price).toLocaleString()}`:"",Wn.bedrooms?` · ${Wn.bedrooms}bd`:"",Wn.bathrooms?` · ${Wn.bathrooms}ba`:""]})]},Wn.id))]})]})]})]})]}),e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-5 gap-6",children:[e.jsx(_e,{className:"lg:col-span-2 border-border/60 shadow-sm",children:e.jsxs(De,{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(_a,{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(re,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Address"}),e.jsx(we,{value:t,onChange:Wn=>n(Wn.target.value),placeholder:"123 Main St"})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"City"}),e.jsx(we,{value:T,onChange:Wn=>P(Wn.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"State"}),e.jsx(we,{value:I,onChange:Wn=>M(Wn.target.value)})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Price"}),e.jsx(we,{type:"number",value:_,onChange:Wn=>b(Wn.target.value),placeholder:"$"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Type"}),e.jsx(we,{value:k,onChange:Wn=>A(Wn.target.value),placeholder:"Single Family"})]})]}),e.jsxs("div",{className:"grid grid-cols-3 gap-3",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Beds"}),e.jsx(we,{type:"number",value:h,onChange:Wn=>m(Wn.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Baths"}),e.jsx(we,{type:"number",step:"0.5",value:f,onChange:Wn=>g(Wn.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Sqft"}),e.jsx(we,{type:"number",value:y,onChange:Wn=>x(Wn.target.value)})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"MLS Remarks / Notes"}),e.jsx(Ws,{value:r,onChange:Wn=>a(Wn.target.value),placeholder:"Paste existing MLS remarks or rough notes...",rows:4,className:"resize-none"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Features"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(we,{value:o,onChange:Wn=>c(Wn.target.value),onKeyDown:Wn=>Wn.key==="Enter"&&(Wn.preventDefault(),rn()),placeholder:"e.g. Quartz countertops"}),e.jsx(B,{type:"button",size:"icon",variant:"secondary",onClick:rn,children:e.jsx(nn,{className:"h-4 w-4"})})]}),i.length>0&&e.jsx("div",{className:"flex flex-wrap gap-1.5 mt-2 animate-fade-in",children:i.map((Wn,Ra)=>e.jsxs(We,{variant:"secondary",className:"pl-3 pr-1 py-1 gap-1",children:[Wn,e.jsx("button",{onClick:()=>Zn(Ra),className:"ml-0.5 p-0.5 hover:bg-background/60 rounded-full",children:e.jsx(hr,{className:"h-3 w-3"})})]},Ra))})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{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(Gv,{className:"h-4 w-4"}),ki?"Uploading…":"Click to upload photos",e.jsx("input",{type:"file",accept:"image/*",multiple:!0,onChange:xs,disabled:ki,className:"hidden"})]}),d.length>0&&e.jsx("div",{className:"grid grid-cols-4 gap-2 mt-2",children:d.map((Wn,Ra)=>e.jsxs("div",{className:"relative aspect-square rounded-lg overflow-hidden group",children:[e.jsx("img",{src:Wn,alt:"",className:"w-full h-full object-cover"}),e.jsx("button",{onClick:()=>u(mo=>mo.filter((Ho,No)=>No!==Ra)),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(hr,{className:"h-3 w-3"})})]},Ra))})]}),Gn&&e.jsxs("div",{className:"space-y-4 p-4 rounded-xl border border-dashed border-primary/40 bg-primary/5 animate-fade-in",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Cn,{className:"h-4 w-4 text-primary"}),e.jsxs("div",{className:"text-sm font-semibold",children:["Extra info for ",Ve.label]})]}),Ms&&e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Date"}),e.jsx(we,{type:"date",value:$,onChange:Wn=>V(Wn.target.value)})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Start"}),e.jsx(we,{type:"time",value:W,onChange:Wn=>G(Wn.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"End"}),e.jsx(we,{type:"time",value:X,onChange:Wn=>te(Wn.target.value)})]})]})]}),bs&&e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Previous Price"}),e.jsx(we,{type:"number",value:ne,onChange:Wn=>me(Wn.target.value),placeholder:"$"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"New Price"}),e.jsx(we,{type:"number",value:ue,onChange:Wn=>ce(Wn.target.value),placeholder:"$"})]})]}),Zs&&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(re,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Sold Price"}),e.jsx(we,{type:"number",value:ae,onChange:Wn=>he(Wn.target.value),placeholder:"$"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Sold Date"}),e.jsx(we,{type:"date",value:xe,onChange:Wn=>ve(Wn.target.value)})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Original List Price (optional)"}),e.jsx(we,{type:"number",value:rt,onChange:Wn=>Ze(Wn.target.value),placeholder:"$"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Days on Market (optional)"}),e.jsx(we,{type:"number",value:ht,onChange:Wn=>Bt(Wn.target.value)})]})]})]}),kn&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Expected Live Date (optional)"}),e.jsx(we,{type:"date",value:ge,onChange:Wn=>be(Wn.target.value)})]}),gn&&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(re,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Builder Name"}),e.jsx(we,{value:Se,onChange:Wn=>Ie(Wn.target.value),placeholder:"ABC Homes"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Year Built"}),e.jsx(we,{type:"number",value:Me,onChange:Wn=>Re(Wn.target.value),placeholder:"2026"})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Warranty / Energy / Smart-home (optional)"}),e.jsx(we,{value:Be,onChange:Wn=>Ne(Wn.target.value),placeholder:"10-yr structural, ENERGY STAR, smart-home pkg"})]})]}),xr&&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(re,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Monthly Rent (optional)"}),e.jsx(we,{type:"number",value:Ge,onChange:Wn=>Ce(Wn.target.value),placeholder:"$"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Cap Rate (optional)"}),e.jsx(we,{value:Fe,onChange:Wn=>Ae(Wn.target.value),placeholder:"6.5%"})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Occupancy"}),e.jsxs("select",{value:Xe,onChange:Wn=>$e(Wn.target.value),className:"w-full h-10 rounded-md border border-input bg-background px-3 text-sm",children:[e.jsx("option",{value:"",children:"Select…"}),e.jsx("option",{value:"Vacant",children:"Vacant"}),e.jsx("option",{value:"Tenant-occupied",children:"Tenant-occupied"}),e.jsx("option",{value:"Owner-occupied",children:"Owner-occupied"}),e.jsx("option",{value:"Short-term rental",children:"Short-term rental"})]})]})]}),Kr&&e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Days on Market (optional)"}),e.jsx(we,{type:"number",value:Ye,onChange:Wn=>Je(Wn.target.value),placeholder:"e.g. 3"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"# of Offers (optional)"}),e.jsx(we,{type:"number",value:Ke,onChange:Wn=>st(Wn.target.value),placeholder:"e.g. 5"})]})]}),ca&&e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Commission / Co-op Offered (optional)"}),e.jsx(we,{value:Ct,onChange:Wn=>Yt(Wn.target.value),placeholder:"2.5% buyer agent commission"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Refreshments / Perks (optional)"}),e.jsx(we,{value:Kt,onChange:Wn=>Xs(Wn.target.value),placeholder:"Lunch + raffle for $100 gift card"})]})]}),Er&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Vibe / Tone"}),e.jsxs("select",{value:zs,onChange:Wn=>Vt(Wn.target.value),className:"w-full h-10 rounded-md border border-input bg-background px-3 text-sm",children:[e.jsx("option",{value:"",children:"Default"}),e.jsx("option",{value:"Energetic",children:"Energetic & fun"}),e.jsx("option",{value:"Luxury",children:"Luxury & cinematic"}),e.jsx("option",{value:"Cozy",children:"Warm & cozy"}),e.jsx("option",{value:"Humorous",children:"Humorous"}),e.jsx("option",{value:"Educational",children:"Educational"}),e.jsx("option",{value:"Bold",children:"Bold & confident"})]})]}),qr&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Nearby Highlights (optional)"}),e.jsx(Ws,{value:At,onChange:Wn=>Os(Wn.target.value),rows:3,placeholder:"Top schools, parks, coffee shops, restaurants, commute, walkability…"})]}),Xt&&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(re,{className:"text-xs font-medium text-muted-foreground",children:"Agent Name"}),e.jsx(we,{value:Nt,onChange:Wn=>ms(Wn.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{className:"text-xs font-medium text-muted-foreground",children:"Brokerage"}),e.jsx(we,{value:Ys,onChange:Wn=>It(Wn.target.value)})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{className:"text-xs font-medium text-muted-foreground",children:"Phone / Email"}),e.jsx(we,{value:Ds,onChange:Wn=>As(Wn.target.value),placeholder:"555-123-4567 or you@brand.com"})]})]})]})]})}),e.jsxs("div",{className:"lg:col-span-3 space-y-6",children:[e.jsx("div",{className:"flex gap-2 p-1 rounded-xl bg-muted/60 border border-border/40 overflow-x-auto",children:[{key:"listing",label:"Listing Copy",icon:Wr},{key:"social",label:"Social Media",icon:dm},{key:"video",label:"Video Scripts",icon:na},{key:"email",label:"Email Marketing",icon:mn}].map(Wn=>{const Ra=Wn.icon,mo=Hs===Wn.key;return e.jsxs("button",{onClick:()=>vr(Wn.key),className:Ot("flex-1 flex items-center justify-center gap-2 px-4 py-2.5 rounded-lg text-sm font-medium transition-all",mo?"bg-card shadow-sm text-foreground border border-border/60":"text-muted-foreground hover:text-foreground hover:bg-background/50"),children:[e.jsx(Ra,{className:"h-4 w-4"}),Wn.label]},Wn.key)})}),es(Hs),e.jsxs(_e,{className:"border-border/60 shadow-sm overflow-hidden",children:[e.jsx("div",{className:Ot("h-1 bg-gradient-to-r",Ve.accent)}),e.jsxs(De,{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:Ot("h-10 w-10 rounded-xl grid place-items-center text-white bg-gradient-to-br",Ve.accent),children:e.jsx(kt,{className:"h-5 w-5"})}),e.jsxs("div",{children:[e.jsxs("div",{className:"font-semibold flex items-center gap-2",children:[Ve.label,e.jsx(We,{variant:"outline",className:"text-[10px] font-normal",children:Ve.tag})]}),e.jsx("div",{className:"text-xs text-muted-foreground",children:Bn[en]?`${Ut} words`:"Ready to generate"})]})]}),e.jsxs("div",{className:"flex gap-2",children:[Bn[en]&&e.jsxs(B,{variant:"outline",size:"sm",onClick:()=>ft(Bn[en]),children:[e.jsx(Pa,{className:"h-4 w-4 mr-2"})," Copy"]}),e.jsx(B,{onClick:()=>it(en),disabled:Jn[en],className:Ot("shadow-lg shadow-primary/10 bg-gradient-to-r text-white border-0 hover:opacity-90",Ve.accent),size:"sm",children:Jn[en]?e.jsxs(e.Fragment,{children:[e.jsx(us,{className:"h-4 w-4 mr-2 animate-spin"})," Generating"]}):Bn[en]?e.jsxs(e.Fragment,{children:[e.jsx(oo,{className:"h-4 w-4 mr-2"})," Regenerate"]}):e.jsxs(e.Fragment,{children:[e.jsx(Zg,{className:"h-4 w-4 mr-2"})," Generate"]})})]})]}),Bn[en]?e.jsx(Ws,{value:Bn[en],onChange:Wn=>Dn(Ra=>({...Ra,[en]:Wn.target.value})),rows:16,className:"resize-none font-serif text-[15px] leading-relaxed bg-muted/30 border-border/60 animate-fade-in"}):e.jsxs("div",{className:"border border-dashed rounded-xl p-12 text-center bg-muted/20",children:[e.jsx("div",{className:Ot("mx-auto h-14 w-14 rounded-2xl grid place-items-center text-white bg-gradient-to-br mb-4",Ve.accent),children:e.jsx(Zg,{className:"h-6 w-6"})}),e.jsxs("div",{className:"font-medium mb-1",children:["Generate a ",Ve.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 fH({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 h3n(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,f=lq[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(fH,{delay:0,x:"15%",y:"20%",size:8}),e.jsx(fH,{delay:1,x:"80%",y:"30%",size:6}),e.jsx(fH,{delay:2,x:"60%",y:"70%",size:10}),e.jsx(fH,{delay:.5,x:"25%",y:"80%",size:7}),e.jsx(fH,{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:f.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:f.title[0]}),f.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:f.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||f.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(ga,{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(mn,{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 JPe({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 gH({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 ygt={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 m3n(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,f=lq[t],g=ygt[t]||ygt.home_anniversary;return e.jsxs("div",{className:`min-h-screen bg-gradient-to-br ${g.bg} flex items-center justify-center p-4 overflow-hidden relative`,children:[e.jsx(JPe,{delay:0,x:"10%",y:"10%",color:g.orbs[0],size:200}),e.jsx(JPe,{delay:1,x:"70%",y:"60%",color:g.orbs[1],size:180}),e.jsx(JPe,{delay:2,x:"50%",y:"20%",color:g.orbs[2],size:150}),e.jsx(gH,{delay:0,x:"20%",y:"25%"}),e.jsx(gH,{delay:.8,x:"75%",y:"15%"}),e.jsx(gH,{delay:1.6,x:"85%",y:"65%"}),e.jsx(gH,{delay:2.4,x:"10%",y:"75%"}),e.jsx(gH,{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:f.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:f.title[0]}),f.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:f.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:f.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(_a,{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||f.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(ga,{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(mn,{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 p3n({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 vgt={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 f3n(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,f=lq[t],g=vgt[t]||vgt.home_anniversary;return e.jsxs("div",{className:`min-h-screen bg-gradient-to-b ${g.bg} flex items-center justify-center p-4 overflow-hidden relative`,children:[f.emojis.map((y,x)=>e.jsx(p3n,{emoji:y,delay:x*1.2,x:`${15+x*14}%`,duration:5+x%3},x)),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 ${g.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:f.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:f.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:f.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:f.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 ${g.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 ${g.accent} mb-1`,initial:{opacity:0,y:10},animate:{opacity:1,y:0},transition:{delay:.9},children:[f.title.join(" ")," ",f.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 ${g.text} mb-1`,children:n}),r&&e.jsxs("p",{className:`text-sm ${g.text} opacity-70 flex items-center justify-center gap-1 mb-5`,children:[e.jsx(ii,{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 ${g.text} leading-relaxed italic`,children:['"',i||f.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 ${g.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 ${g.accent}`,children:l}),u&&e.jsx("p",{className:`text-xs ${g.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 ${g.header} text-xs font-semibold text-white shadow-md`,whileHover:{scale:1.05},whileTap:{scale:.95},children:[e.jsx(ga,{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 ${g.header} text-xs font-semibold text-white shadow-md`,whileHover:{scale:1.05},whileTap:{scale:.95},children:[e.jsx(mn,{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 Pne({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 eIe({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 bgt={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 g3n(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,f=lq[t],g=bgt[t]||bgt.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(Pne,{delay:0,x:"5%",y:"10%",size:300,color:g.mesh[0]}),e.jsx(Pne,{delay:2,x:"60%",y:"50%",size:250,color:g.mesh[1]}),e.jsx(Pne,{delay:4,x:"30%",y:"70%",size:200,color:g.mesh[2]}),e.jsx(Pne,{delay:1,x:"80%",y:"15%",size:180,color:g.mesh[0]}),e.jsx(eIe,{delay:0,x:"15%",y:"20%",size:100}),e.jsx(eIe,{delay:3,x:"70%",y:"60%",size:140}),e.jsx(eIe,{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 ${g.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:f.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] ${g.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:f.title[0]}),f.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:f.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(ii,{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||f.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(ga,{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(mn,{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 tIe({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 Ine({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 _gt={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 x3n(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,f=lq[t],g=_gt[t]||_gt.home_anniversary;return e.jsxs("div",{className:`min-h-screen bg-gradient-to-b ${g.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(tIe,{delay:0,x:"20%",angle:15,color:g.stripe}),e.jsx(tIe,{delay:2,x:"75%",angle:-12,color:g.stripe}),e.jsx(tIe,{delay:4,x:"50%",angle:5,color:g.stripe}),e.jsx(Ine,{delay:0,x:"30%"}),e.jsx(Ine,{delay:1.5,x:"60%"}),e.jsx(Ine,{delay:3,x:"45%"}),e.jsx(Ine,{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 ${g.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:f.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 ${g.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:f.title[0]})}),f.title[1]&&e.jsx("div",{className:"overflow-hidden mb-8",children:e.jsx(Sr.h2,{className:`text-5xl font-black bg-gradient-to-r ${g.accent} bg-clip-text text-transparent`,initial:{y:"100%"},animate:{y:0},transition:{duration:.7,delay:.95,ease:[.16,1,.3,1]},children:f.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(ii,{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||f.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 ${g.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 ${g.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(ga,{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(mn,{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 F9t(){const{shareToken:s}=uo(),{data:t,isLoading:n,error:r}=mt({queryKey:["public-sendable-card",s],queryFn:async()=>{const{data:l,error:o}=await H.from("sendable_cards").select("*").eq("share_token",s).single();if(o)throw o;return l},enabled:!!s});if(N.useEffect(()=>{s&&H.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()-Tc(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(m3n,{...i});case"warm":return e.jsx(f3n,{...i});case"glass":return e.jsx(g3n,{...i});case"cinematic":return e.jsx(x3n,{...i});case"elegant":default:return e.jsx(h3n,{...i})}}function y3n(){const s=Ya();return mt({queryKey:["drip-settings",s],queryFn:async()=>{if(!s)return null;const{data:t,error:n}=await H.from("drip_settings").select("*").eq("user_id",s).maybeSingle();if(n)throw n;return t},enabled:!!s})}function v3n(){const s=Ya(),t=as();return _t({mutationFn:async n=>{if(!s)throw new Error("Not authenticated");const{data:r}=await H.from("drip_settings").select("id").eq("user_id",s).maybeSingle();if(r){const{data:a,error:i}=await H.from("drip_settings").update(n).eq("user_id",s).select().single();if(i)throw i;return a}else{const{data:a,error:i}=await H.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 b3n(){const s=tr(),{isGmailConnected:t,gmailEmail:n}=_f(),{data:r,isLoading:a}=y3n(),i=v3n(),[l,o]=N.useState(!1),[c,d]=N.useState(!0),[u,h]=N.useState(!1);N.useEffect(()=>{r&&(o(r.is_globally_enabled),d(r.append_signature))},[r]);const m=async g=>{if(g&&!t){ie.error("Connect your Gmail account first before enabling Smart Drips");return}o(g);try{await i.mutateAsync({is_globally_enabled:g}),ie.success(g?"Smart Drips enabled globally":"Smart Drips paused globally")}catch{o(!g),ie.error("Failed to update settings")}},f=async g=>{d(g);try{await i.mutateAsync({append_signature:g}),ie.success(g?"Signature will be appended to drip emails":"Signature disabled for drip emails")}catch{d(!g),ie.error("Failed to update settings")}};return e.jsxs(Bs,{open:u,onOpenChange:h,children:[e.jsx(Ao,{asChild:!0,children:e.jsxs(B,{variant:"outline",size:"sm",className:"gap-1.5",children:[e.jsx(sc,{className:"h-3.5 w-3.5"}),"Settings"]})}),e.jsxs(Fs,{className:"sm:max-w-md",children:[e.jsxs(qs,{children:[e.jsxs($s,{className:"flex items-center gap-2",children:[e.jsx(sc,{className:"h-5 w-5 text-primary"}),"Smart Drip Settings"]}),e.jsx(Ar,{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(mn,{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(We,{variant:"outline",className:"gap-1 text-emerald-600 border-emerald-200 bg-emerald-500/10 text-[10px]",children:[e.jsx(Hr,{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(Tr,{className:"h-3 w-3"}),"Connect"]})]}),!t&&e.jsx("p",{className:"text-xs text-muted-foreground",children:"Smart Drips sends emails from your Gmail account. Connect Gmail to get started."})]}),e.jsx(Wl,{}),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(mW,{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(zn,{checked:l,onCheckedChange:m,disabled:a||i.isPending})]}),e.jsx(Wl,{}),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(Ww,{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(zn,{checked:c,onCheckedChange:f,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(Ww,{className:"h-3 w-3 mr-1"}),"Edit your email signature in Profile settings"]})]})]})]})}function _3n(){const s=Ya();return mt({queryKey:["drip-templates",s],queryFn:async()=>{if(!s)return[];const{data:t,error:n}=await H.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 w3n(){const s=Ya();return mt({queryKey:["drip-pipeline-stages",s],queryFn:async()=>{if(!s)return[];const{data:t,error:n}=await H.from("deal_pipeline_stages").select("*").eq("owner_user_id",s).order("sort_order",{ascending:!0});if(n)throw n;return t},enabled:!!s})}function j3n(){const s=Ya(),t=as();return _t({mutationFn:async n=>{if(!s)throw new Error("Not authenticated");const{data:r,error:a}=await H.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 N3n(){const s=as();return _t({mutationFn:async({id:t,...n})=>{const{data:r,error:a}=await H.from("drip_templates").update(n).eq("id",t).select().single();if(a)throw a;return r},onSuccess:()=>{s.invalidateQueries({queryKey:["drip-templates"]})}})}function k3n(){const s=as();return _t({mutationFn:async t=>{const{error:n}=await H.from("drip_templates").delete().eq("id",t);if(n)throw n},onSuccess:()=>{s.invalidateQueries({queryKey:["drip-templates"]})}})}function S3n(){const s=Ya(),t=as();return _t({mutationFn:async({templateId:n,stageId:r})=>{if(!s)throw new Error("Not authenticated");const{data:a,error:i}=await H.from("drip_templates").select("*").eq("id",n).single();if(i)throw i;const{data:l,error:o}=await H.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 C3n=[{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"}];function A3n({open:s,onOpenChange:t,campaignId:n,campaignName:r}){const{data:a,isLoading:i}=Hmn(n||void 0),l=Wmn(),o=cIt(),c=async(h,m)=>{try{await l.mutateAsync({id:h,status:m}),ie.success(`Enrollment ${m}`)}catch{ie.error("Failed to update")}},d=async h=>{if(n)try{const m=await o.mutateAsync({campaignId:n,contactIds:[h]});m.enrolled>0?ie.success("Contact re-enrolled — first email queued"):m.skipped>0?ie.message("Already active in this campaign"):ie.error("Could not re-enroll")}catch{ie.error("Failed to re-enroll")}},u=h=>{const m={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(We,{variant:"outline",className:`text-[10px] capitalize ${m[h]||""}`,children:h})};return e.jsx(Bs,{open:s,onOpenChange:t,children:e.jsxs(Fs,{className:"max-w-2xl max-h-[85vh] flex flex-col p-0 overflow-hidden",children:[e.jsxs("div",{className:"p-5 border-b shrink-0",children:[e.jsxs($s,{className:"flex items-center gap-2",children:[e.jsx(Yn,{className:"h-4 w-4 text-primary"}),"Enrollments — ",r||"Campaign"]}),e.jsx(Ar,{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:"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(h=>e.jsx(xn,{className:"h-14"},h))}):!a||a.length===0?e.jsxs("div",{className:"text-center py-12",children:[e.jsx(Yn,{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",children:"Head to your contacts page and bulk-enroll to start nurturing."})]}):e.jsx("div",{className:"space-y-2",children:a.map(h=>{var m,f,g,y;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:[(m=h.contact)==null?void 0:m.first_name," ",(f=h.contact)==null?void 0:f.last_name]}),u(h.status)]}),e.jsxs("div",{className:"flex items-center gap-3 text-[11px] text-muted-foreground mt-0.5",children:[((g=h.contact)==null?void 0:g.email)&&e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(mn,{className:"h-2.5 w-2.5"})," ",h.contact.email]}),e.jsxs("span",{children:["Step ",h.current_step]}),h.next_send_at&&h.status==="active"&&e.jsxs("span",{children:["Next: ",Js(new Date(h.next_send_at),"MMM d, h:mma")]}),h.exit_reason&&e.jsxs("span",{children:["Exit: ",h.exit_reason]})]})]}),h.status==="active"&&e.jsx(B,{size:"sm",variant:"ghost",onClick:()=>c(h.id,"paused"),title:"Pause",children:e.jsx(K0,{className:"h-3.5 w-3.5"})}),h.status==="paused"&&e.jsx(B,{size:"sm",variant:"ghost",onClick:()=>c(h.id,"active"),title:"Resume",children:e.jsx(dd,{className:"h-3.5 w-3.5"})}),(h.status==="active"||h.status==="paused")&&e.jsx(B,{size:"sm",variant:"ghost",onClick:()=>c(h.id,"exited"),title:"Exit",children:e.jsx(hr,{className:"h-3.5 w-3.5 text-destructive"})}),(h.status==="exited"||h.status==="completed")&&((y=h.contact)==null?void 0:y.id)&&e.jsxs(B,{size:"sm",variant:"outline",className:"h-7 text-[11px] gap-1",onClick:()=>d(h.contact.id),disabled:o.isPending,children:[e.jsx(hf,{className:"h-3 w-3"}),"Re-enroll"]})]},h.id)})})})})]})})}function T3n(){var k;const{data:s,isLoading:t}=pJ(),{hasLeadSite:n}=Qx(),r=uGe(),a=$mn(),i=oIt(),[l,o]=N.useState(null),[c,d]=N.useState(!1),[u,h]=N.useState(null),[m,f]=N.useState(null),g=(s||[]).filter(A=>!A.is_starter),y=(s||[]).filter(A=>A.is_starter).filter(A=>!A.requires_lead_site||n),x=async A=>{try{await r.mutateAsync(A),ie.success("Campaign added to your library — customize and activate it!"),o(null)}catch(T){ie.error(T.message||"Failed to copy campaign")}},_=async A=>{try{await i.mutateAsync({id:A.id,is_active:!A.is_active}),ie.success(A.is_active?"Campaign paused":"Campaign activated")}catch{ie.error("Failed to update")}},b=async A=>{if(confirm("Delete this campaign? Active enrollments will be removed."))try{await a.mutateAsync(A),ie.success("Campaign deleted")}catch{ie.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(A=>e.jsx(xn,{className:"h-44 rounded-xl"},A))}):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(p5,{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(iu,{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(Rr,{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.jsx("p",{className:"text-muted-foreground",children:"You enroll contacts yourself — from this page or the Contacts list."})]})]})]}),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(Yn,{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(nn,{className:"h-3.5 w-3.5 mr-1.5"})," New Campaign"]})]}),g.length===0?e.jsxs("div",{className:"text-center py-10 border border-dashed rounded-xl bg-muted/20",children:[e.jsx(Cn,{className:"h-10 w-10 text-muted-foreground/40 mx-auto mb-3"}),e.jsx("h3",{className:"font-semibold mb-1",children:"No custom campaigns yet"}),e.jsx("p",{className:"text-sm text-muted-foreground mb-4",children:"Build one from scratch or clone a starter from the library below."}),e.jsxs(B,{size:"sm",onClick:()=>{h(null),d(!0)},children:[e.jsx(nn,{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:g.map(A=>e.jsx(E3n,{campaign:A,onPreview:()=>o(A.id),onToggleActive:()=>_(A),onDelete:()=>b(A.id),onEdit:()=>{h(A.id),d(!0)},onViewEnrollments:()=>f(A.id)},A.id))})]}),e.jsxs("section",{children:[e.jsxs("div",{className:"flex items-center justify-between mb-3",children:[e.jsxs("div",{children:[e.jsxs("h2",{className:"text-lg font-semibold flex items-center gap-2",children:[e.jsx(Cn,{className:"h-4 w-4 text-amber-500"}),"Starter Library"]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Premium, ready-to-go campaigns crafted for real estate. One-click copy."})]}),e.jsxs(We,{variant:"outline",className:"text-[10px]",children:[y.length," templates"]})]}),e.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-4",children:y.map(A=>e.jsx(M3n,{campaign:A,onPreview:()=>o(A.id)},A.id))})]}),e.jsx(L3n,{campaignId:l,open:!!l,onOpenChange:A=>!A&&o(null),onClone:x,isCloning:r.isPending,onEdit:A=>{o(null),h(A),d(!0)}}),e.jsx(hIt,{open:c,onOpenChange:d,campaignId:u}),e.jsx(A3n,{open:!!m,onOpenChange:A=>!A&&f(null),campaignId:m,campaignName:(k=g.find(A=>A.id===m))==null?void 0:k.name})]})}function E3n({campaign:s,onPreview:t,onToggleActive:n,onDelete:r,onEdit:a,onViewEnrollments:i}){const o=Gmn(s.id).data??0,c=!s.is_active&&o>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(We,{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(We,{variant:"outline",className:"text-[9px] mt-2",children:qCe[s.category]}),c&&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(xd,{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:[o," contact",o===1?"":"s"," enrolled"]})," but not sending — tap to activate"]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-1.5 mt-3",children:[e.jsxs(B,{size:"sm",variant:"outline",className:"h-7 text-xs",onClick:a,children:[e.jsx(Ja,{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 M3n({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(We,{className:"absolute top-2 right-2 bg-white/90 text-foreground hover:bg-white text-[10px]",children:[e.jsx(Cn,{className:"h-2.5 w-2.5 mr-0.5"})," Starter"]})]}),e.jsxs("div",{className:"p-3.5",children:[e.jsx("h3",{className:"font-semibold text-sm",children:s.name}),e.jsx("p",{className:"text-xs text-muted-foreground line-clamp-2 mt-1 min-h-[2rem]",children:s.description}),e.jsx(We,{variant:"outline",className:"text-[9px] mt-2",children:qCe[s.category]})]})]})}function L3n({campaignId:s,open:t,onOpenChange:n,onClone:r,isCloning:a,onEdit:i}){const{data:l}=pJ(),{data:o}=lIt(s||void 0),[c,d]=N.useState(new Set),u=l==null?void 0:l.find(f=>f.id===s);if(!u)return null;const h=f=>{d(g=>{const y=new Set(g);return y.has(f)?y.delete(f):y.add(f),y})},m=(f,g)=>{if(f.delay_type==="calendar_anchor"){const x=f.anchor_field==="birthday"?"birthday":"home anniversary",_=f.anchor_offset_days||0;return _===0?`On their ${x}`:_<0?`${Math.abs(_)} days before ${x}`:`${_} days after ${x}`}if(g===0&&f.delay_days===0&&f.delay_hours===0)return"Sends immediately";const y=[];return f.delay_days&&y.push(`${f.delay_days}d`),f.delay_hours&&y.push(`${f.delay_hours}h`),g===0?`After ${y.join(" ")}`:`+${y.join(" ")}`};return e.jsx(Bs,{open:t,onOpenChange:n,children:e.jsxs(Fs,{className:"max-w-2xl max-h-[85vh] flex flex-col p-0 overflow-hidden",children:[e.jsx("div",{className:`bg-gradient-to-br ${u.cover_color} p-6 text-white shrink-0`,children:e.jsxs("div",{className:"flex items-start gap-4",children:[e.jsx("span",{className:"text-5xl drop-shadow-sm",children:u.icon}),e.jsxs("div",{className:"flex-1",children:[e.jsx($s,{className:"text-xl font-bold text-white",children:u.name}),e.jsx(Ar,{className:"text-white/90 mt-1",children:u.description}),e.jsxs("div",{className:"flex gap-2 mt-3",children:[e.jsx(We,{className:"bg-white/20 text-white border-white/20 hover:bg-white/20",children:qCe[u.category]}),e.jsxs(We,{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((f,g)=>{const y=c.has(f.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:g+1}),gh(f.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:[f.delay_type==="calendar_anchor"?e.jsx(ta,{className:"h-3 w-3"}):e.jsx(Xr,{className:"h-3 w-3"}),e.jsx("span",{children:m(f,g)}),e.jsx("span",{children:"·"}),e.jsx(mn,{className:"h-3 w-3"}),e.jsx("span",{className:"capitalize",children:f.channel})]}),e.jsx("p",{className:"font-medium text-sm",children:f.subject}),(()=>{const x=f.body||"",_=/<\/?[a-z][\s\S]*>/i.test(x),b=_?x.replace(//gi,"").replace(/<[^>]+>/g," ").replace(/ /g," ").replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/\s+/g," ").trim():x;return y?_?e.jsx("div",{className:"text-xs text-foreground mt-2 prose prose-sm max-w-none [&_a]:text-primary",dangerouslySetInnerHTML:{__html:x}}):e.jsx("p",{className:"text-xs text-muted-foreground mt-2 whitespace-pre-line",children:x}):e.jsx("p",{className:"text-xs text-muted-foreground line-clamp-2 mt-1",children:b})})(),f.body&&f.body.length>160&&e.jsx("span",{className:"text-[10px] text-primary mt-1.5 inline-block",children:y?"Show less":"Show full email"})]})})]},f.id)})]})}),e.jsxs(Cr,{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(Ja,{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(us,{className:"h-3.5 w-3.5 mr-1.5 animate-spin"}):e.jsx(Pa,{className:"h-3.5 w-3.5 mr-1.5"}),"Copy to my campaigns"]})]})]})})}const $je=[{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 P3n(){const s=Ya();return mt({queryKey:["drip-auto-rules",s],queryFn:async()=>{if(!s)return[];const{data:t,error:n}=await H.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 I3n(){const s=Ya(),t=as();return _t({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 H.from("drip_auto_enroll_rules").upsert(r).select().single();if(i)throw i;return a},onSuccess:()=>{t.invalidateQueries({queryKey:["drip-auto-rules"]})}})}function D3n(){const s=as();return _t({mutationFn:async({id:t,is_active:n})=>{const{error:r}=await H.from("drip_auto_enroll_rules").update({is_active:n}).eq("id",t);if(r)throw r},onSuccess:()=>s.invalidateQueries({queryKey:["drip-auto-rules"]})})}function R3n(){const s=as();return _t({mutationFn:async t=>{const{error:n}=await H.from("drip_auto_enroll_rules").delete().eq("id",t);if(n)throw n},onSuccess:()=>s.invalidateQueries({queryKey:["drip-auto-rules"]})})}function O3n(s=25){const t=Ya();return mt({queryKey:["drip-auto-log",t,s],queryFn:async()=>{if(!t)return[];const{data:n,error:r}=await H.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 F3n(){const s=Ya();return mt({queryKey:["life-event-coverage",s],queryFn:async()=>{if(!s)return null;const{data:t,error:n}=await H.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 z3n(){const s=as();return _t({mutationFn:async t=>{const{data:n,error:r}=await H.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 B3n={birthday:Fm,home_anniversary:W2,spouse_birthday:Io,wedding_anniversary:co};function $3n(){var A;const{data:s,isLoading:t}=P3n(),{data:n}=pJ(),{data:r}=F3n(),{data:a}=O3n(10),i=I3n(),l=D3n(),o=R3n(),c=z3n(),d=uGe(),[u,h]=N.useState(null),m=N.useMemo(()=>(n||[]).filter(T=>!T.is_starter),[n]),f={birthday:"Birthday",home_anniversary:"Home Anniversary",spouse_birthday:"Spouse Birthday",wedding_anniversary:"Wedding Anniversary"},g=N.useMemo(()=>{if(!(u!=null&&u.trigger_type))return null;const T=f[u.trigger_type];return!T||m.some(I=>String(I.name||"").toLowerCase().includes(T.toLowerCase()))?null:(n||[]).find(I=>I.is_starter&&String(I.name||"").toLowerCase()===T.toLowerCase())??null},[n,m,u==null?void 0:u.trigger_type]),y=async()=>{if(g)try{const T=await d.mutateAsync(g.id);h(P=>({...P,campaign_id:T.id})),ie.success(`“${g.name}” template added to your campaigns`)}catch(T){ie.error((T==null?void 0:T.message)||"Could not copy the template")}},x=T=>(s||[]).find(P=>P.trigger_type===T),_=async()=>{if(!(u!=null&&u.campaign_id)||!(u!=null&&u.trigger_type)){ie.error("Pick a campaign first");return}try{await i.mutateAsync(u),ie.success("Autopilot rule saved"),h(null)}catch(T){ie.error((T==null?void 0:T.message)||"Could not save rule")}},b=async()=>{try{const T=await c.mutateAsync(void 0);ie.success(T!=null&&T.enrolled?`Enrolled ${T.enrolled} contact${T.enrolled===1?"":"s"} with upcoming life events`:"All caught up — nobody new to enroll right now")}catch(T){ie.error((T==null?void 0:T.message)||"Autopilot run failed")}},k=(s||[]).filter(T=>T.is_active).length;return e.jsxs("div",{className:"space-y-5",children:[e.jsxs("div",{className:"rounded-2xl border bg-gradient-to-br from-primary/10 via-card to-card p-5",children:[e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center justify-between gap-4",children:[e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx("div",{className:"h-11 w-11 rounded-xl bg-primary/15 flex items-center justify-center shrink-0",children:e.jsx(Cn,{className:"h-5 w-5 text-primary"})}),e.jsxs("div",{children:[e.jsx("h2",{className:"text-lg font-bold leading-tight",children:"Life Event Autopilot"}),e.jsx("p",{className:"text-sm text-muted-foreground max-w-xl",children:"Every morning we scan your database for upcoming birthdays and anniversaries and quietly enroll those contacts in the campaign you choose. You never miss a moment again."})]})]}),e.jsxs(B,{variant:"outline",onClick:b,disabled:c.isPending||k===0,className:"gap-2 shrink-0",children:[c.isPending?e.jsx(us,{className:"h-4 w-4 animate-spin"}):e.jsx(oo,{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:$je.map(T=>{const P=r.counts[T.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:[T.emoji," ",T.label]}),e.jsx("p",{className:"text-lg font-bold leading-tight",children:(P==null?void 0:P.total)??0}),e.jsxs("p",{className:"text-[11px] text-muted-foreground",children:[(P==null?void 0:P.upcoming30)??0," in next 30 days"]})]},T.value)})})]}),t?e.jsx("div",{className:"flex justify-center py-10",children:e.jsx(us,{className:"h-5 w-5 animate-spin text-muted-foreground"})}):e.jsx("div",{className:"grid sm:grid-cols-2 gap-3",children:$je.map(T=>{var L;const P=x(T.value),I=B3n[T.value]||Fm,M=r==null?void 0:r.counts[T.value];return e.jsxs("div",{className:Ot("rounded-xl border bg-card p-4 transition-colors",(P==null?void 0:P.is_active)&&"border-primary/40 bg-primary/[0.03]"),children:[e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx("div",{className:Ot("h-10 w-10 rounded-lg flex items-center justify-center shrink-0",P!=null&&P.is_active?"bg-primary/15 text-primary":"bg-muted text-muted-foreground"),children:e.jsx(I,{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:T.label}),(P==null?void 0:P.is_active)&&e.jsx(We,{className:"text-[10px] bg-primary/10 text-primary hover:bg-primary/10",children:"On"})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:P?`${((L=P.campaign)==null?void 0:L.name)??"Campaign"} · starts ${P.lead_days} days before`:T.description}),P&&P.total_enrolled>0&&e.jsxs("p",{className:"text-[11px] text-muted-foreground mt-1",children:[P.total_enrolled," contact",P.total_enrolled===1?"":"s"," enrolled so far"]}),!P&&((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."})]}),P?e.jsx(zn,{checked:P.is_active,onCheckedChange:z=>l.mutate({id:P.id,is_active:z})}):null]}),e.jsxs("div",{className:"flex gap-2 mt-3",children:[e.jsxs(B,{size:"sm",variant:P?"outline":"default",className:"flex-1 gap-1.5",onClick:()=>h(P??{trigger_type:T.value,lead_days:T.value==="birthday"?7:14,require_email:!0,is_active:!0,filter_tags:[],filter_relationship_types:[]}),children:[P?e.jsx(ff,{className:"h-3.5 w-3.5"}):e.jsx(nn,{className:"h-3.5 w-3.5"}),P?"Edit rule":"Turn on autopilot"]}),P&&e.jsx(B,{size:"sm",variant:"ghost",className:"text-muted-foreground hover:text-destructive",onClick:()=>o.mutate(P.id),children:e.jsx(qn,{className:"h-3.5 w-3.5"})})]})]},T.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(T=>{var P,I;return e.jsxs("div",{className:"flex items-center gap-3 px-4 py-2.5",children:[e.jsx(pa,{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:[(P=T.contact)==null?void 0:P.first_name," ",(I=T.contact)==null?void 0:I.last_name]}),e.jsxs("p",{className:"text-xs text-muted-foreground truncate",children:[String(T.trigger_type).replace(/_/g," ")," · ",T.note]})]}),e.jsx("span",{className:"text-[11px] text-muted-foreground shrink-0",children:new Date(T.created_at).toLocaleDateString("en-US",{month:"short",day:"numeric"})})]},T.id)})})]}),e.jsx(Bs,{open:!!u,onOpenChange:T=>!T&&h(null),children:e.jsxs(Fs,{className:"sm:max-w-md",children:[e.jsxs(qs,{children:[e.jsxs($s,{children:[(A=$je.find(T=>T.value===(u==null?void 0:u.trigger_type)))==null?void 0:A.label," autopilot"]}),e.jsx(Ar,{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(re,{children:"Campaign to enroll into"}),e.jsxs(Ns,{value:(u==null?void 0:u.campaign_id)??"",onValueChange:T=>h(P=>({...P,campaign_id:T})),children:[e.jsx(ws,{children:e.jsx(ks,{placeholder:"Select one of your campaigns"})}),e.jsx(js,{children:m.map(T=>e.jsx(nt,{value:T.id,children:T.name},T.id))})]}),g&&e.jsx("div",{className:"rounded-lg border border-primary/25 bg-primary/5 p-3",children:e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsx(Cn,{className:"mt-0.5 h-4 w-4 shrink-0 text-primary"}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("p",{className:"text-sm font-medium leading-tight",children:["Use the LevelUp “",g.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(us,{className:"h-3.5 w-3.5 animate-spin"}):e.jsx(nn,{className:"h-3.5 w-3.5"}),"Use this template"]})]})]})}),m.length===0&&!g&&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(re,{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(qf,{min:0,max:45,step:1,value:[(u==null?void 0:u.lead_days)??14],onValueChange:([T])=>h(P=>({...P,lead_days:T}))}),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(re,{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(zn,{checked:(u==null?void 0:u.require_email)??!0,onCheckedChange:T=>h(P=>({...P,require_email:T}))})]}),e.jsxs("div",{className:"flex items-center justify-between rounded-lg border p-3",children:[e.jsxs("div",{children:[e.jsx(re,{className:"text-sm",children:"Autopilot active"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Runs every morning automatically."})]}),e.jsx(zn,{checked:(u==null?void 0:u.is_active)??!0,onCheckedChange:T=>h(P=>({...P,is_active:T}))})]})]}),e.jsxs(Cr,{children:[e.jsx(B,{variant:"ghost",onClick:()=>h(null),children:"Cancel"}),e.jsxs(B,{onClick:_,disabled:i.isPending||!(u!=null&&u.campaign_id),children:[i.isPending&&e.jsx(us,{className:"h-4 w-4 mr-1.5 animate-spin"}),"Save rule"]})]})]})})]})}function U3n(){const s=Ya(),t=tr(),{isGmailConnected:n,gmailEmail:r,isLoading:a}=_f(),{data:i,isLoading:l}=_3n(),{data:o,isLoading:c}=w3n(),d=j3n(),u=N3n(),h=k3n(),m=S3n(),[f,g]=N.useState(null),[y,x]=N.useState(null),_=(i==null?void 0:i.filter(L=>!L.is_starter&&L.owner_user_id===s))||[],b=(i==null?void 0:i.filter(L=>L.is_starter))||[],k=L=>_.filter(z=>z.stage_id===L),A=async L=>{try{await u.mutateAsync({id:L.id,is_enabled:!L.is_enabled}),ie.success(L.is_enabled?"Drip disabled":"Drip enabled")}catch{ie.error("Failed to update")}},T=async L=>{try{const z=o==null?void 0:o.find($=>$.id===L);await d.mutateAsync({stage_id:L,title:`${(z==null?void 0:z.name)||"Stage"} follow-up`,subject:"",body:"",channel:"email",delay_type:"instant",delay_minutes:0}),g(L),ie.success("Drip template created")}catch{ie.error("Failed to create template")}},P=async L=>{try{await h.mutateAsync(L),ie.success("Template deleted")}catch{ie.error("Failed to delete")}},I=async L=>{if(!o||o.length===0){ie.error("No pipeline stages found");return}const z=o[0].id;try{await m.mutateAsync({templateId:L,stageId:z}),ie.success("Template copied to your drips!")}catch{ie.error("Failed to copy template")}},M=l||c;return e.jsx(Qs,{children:e.jsxs("div",{className:"container max-w-4xl mx-auto py-6 px-4",children:[e.jsxs("div",{className:"flex items-center justify-between mb-6",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ff,{className:"h-5 w-5 text-primary"}),e.jsx("h1",{className:"text-2xl font-bold",children:"Smart Drips"}),e.jsx(We,{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(b3n,{})]}),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(p5,{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(mn,{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(p5,{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(mn,{className:"h-3 w-3 mr-1.5"}),"Connect Gmail"]})]})]})),e.jsxs(ya,{defaultValue:"my-drips",children:[e.jsxs(va,{className:"grid grid-cols-4 w-full max-w-2xl mb-6",children:[e.jsx(ls,{value:"my-drips",children:"Stage Drips"}),e.jsxs(ls,{value:"campaigns",children:["Campaigns",e.jsx(We,{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(ls,{value:"autopilot",children:["Life Events",e.jsx(We,{variant:"outline",className:"ml-1.5 text-[9px] bg-primary/10 text-primary border-primary/20 px-1 py-0",children:"Auto"})]}),e.jsxs(ls,{value:"starters",children:["Stage Starters",b.length>0&&e.jsx(We,{variant:"secondary",className:"ml-1.5 text-[10px] px-1.5 py-0",children:b.length})]})]}),e.jsx(_s,{value:"campaigns",children:e.jsx(T3n,{})}),e.jsx(_s,{value:"autopilot",children:e.jsx($3n,{})}),e.jsx(_s,{value:"my-drips",children:M?e.jsx("div",{className:"space-y-3",children:[1,2,3,4].map(L=>e.jsx(xn,{className:"h-16 w-full rounded-xl"},L))}):!o||o.length===0?e.jsxs("div",{className:"text-center py-12 border border-dashed rounded-xl",children:[e.jsx(ff,{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(L=>!L.is_won_stage&&!L.is_lost_stage).map(L=>{const z=k(L.id),$=f===L.id,V=z.some(W=>W.is_enabled);return e.jsxs("div",{className:"border rounded-xl overflow-hidden",children:[e.jsxs("button",{onClick:()=>g($?null:L.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:L.color||"#94A3B8"}}),e.jsx("span",{className:"font-medium text-sm flex-1",children:L.name}),z.length>0&&e.jsxs(We,{variant:"outline",className:`text-[10px] ${V?"bg-emerald-500/10 text-emerald-600 border-emerald-200":"text-muted-foreground"}`,children:[z.length," drip",z.length!==1?"s":"",V&&" · Active"]}),$?e.jsx(Xo,{className:"h-4 w-4 text-muted-foreground"}):e.jsx(Qa,{className:"h-4 w-4 text-muted-foreground"})]}),$&&e.jsx("div",{className:"border-t bg-muted/10 p-4 space-y-3",children:z.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:()=>T(L.id),disabled:d.isPending,children:[e.jsx(nn,{className:"h-3.5 w-3.5 mr-1.5"}),"Create Drip"]})]}):e.jsxs(e.Fragment,{children:[z.map(W=>e.jsx(wgt,{template:W,isEditing:y===W.id,onToggleEdit:()=>x(y===W.id?null:W.id),onToggleEnabled:()=>A(W),onUpdate:G=>u.mutateAsync({id:W.id,...G}),onDelete:()=>P(W.id),userId:s||""},W.id)),e.jsxs(B,{variant:"ghost",size:"sm",className:"w-full text-xs text-muted-foreground",onClick:()=>T(L.id),children:[e.jsx(nn,{className:"h-3 w-3 mr-1"})," Add another drip"]})]})})]},L.id)}),o.filter(L=>L.is_won_stage||L.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(L=>L.is_won_stage||L.is_lost_stage).map(L=>{const z=k(L.id),$=f===L.id,V=z.some(W=>W.is_enabled);return e.jsxs("div",{className:"border rounded-xl overflow-hidden mb-2",children:[e.jsxs("button",{onClick:()=>g($?null:L.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:L.color||"#94A3B8"}}),e.jsx("span",{className:"font-medium text-sm flex-1",children:L.name}),z.length>0&&e.jsxs(We,{variant:"outline",className:`text-[10px] ${V?"bg-emerald-500/10 text-emerald-600 border-emerald-200":"text-muted-foreground"}`,children:[z.length," drip",z.length!==1?"s":"",V&&" · Active"]}),$?e.jsx(Xo,{className:"h-4 w-4 text-muted-foreground"}):e.jsx(Qa,{className:"h-4 w-4 text-muted-foreground"})]}),$&&e.jsx("div",{className:"border-t bg-muted/10 p-4 space-y-3",children:z.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:()=>T(L.id),disabled:d.isPending,children:[e.jsx(nn,{className:"h-3.5 w-3.5 mr-1.5"})," Create Drip"]})]}):e.jsxs(e.Fragment,{children:[z.map(W=>e.jsx(wgt,{template:W,isEditing:y===W.id,onToggleEdit:()=>x(y===W.id?null:W.id),onToggleEnabled:()=>A(W),onUpdate:G=>u.mutateAsync({id:W.id,...G}),onDelete:()=>P(W.id),userId:s||""},W.id)),e.jsxs(B,{variant:"ghost",size:"sm",className:"w-full text-xs text-muted-foreground",onClick:()=>T(L.id),children:[e.jsx(nn,{className:"h-3 w-3 mr-1"})," Add another drip"]})]})})]},L.id)})]})]})}),e.jsx(_s,{value:"starters",children:b.length===0?e.jsxs("div",{className:"text-center py-12 border border-dashed rounded-xl",children:[e.jsx(Cn,{className:"h-10 w-10 text-muted-foreground/40 mx-auto mb-3"}),e.jsx("h3",{className:"font-semibold text-lg mb-1",children:"No Starter Templates Yet"}),e.jsx("p",{className:"text-sm text-muted-foreground max-w-md mx-auto",children:"Admin-created starter templates will appear here. You'll be able to copy them into your own drips."})]}):e.jsx("div",{className:"space-y-3",children:b.map(L=>e.jsx(q3n,{template:L,onCopy:()=>I(L.id),isCopying:m.isPending},L.id))})})]})]})})}function wgt({template:s,isEditing:t,onToggleEdit:n,onToggleEnabled:r,onUpdate:a,onDelete:i,userId:l}){const[o,c]=N.useState(s.title),[d,u]=N.useState(s.subject),[h,m]=N.useState(s.body),[f,g]=N.useState(s.video_url||""),[y,x]=N.useState(s.channel),[_,b]=N.useState(s.delay_type),[k,A]=N.useState(s.delay_minutes),[T,P]=N.useState(!1),I=async()=>{P(!0);try{await a({title:o,subject:d,body:h,video_url:f||null,channel:y,delay_type:_,delay_minutes:k}),ie.success("Drip saved"),n()}catch{ie.error("Failed to save")}finally{P(!1)}},M=L=>{m(z=>z+L)};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(xo,{className:"h-3 w-3 text-muted-foreground"}):e.jsx(mn,{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(na,{className:"h-3 w-3 text-primary"})]})]}),e.jsx(zn,{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(re,{className:"text-xs font-medium",children:"Title (internal)"}),e.jsx(we,{value:o,onChange:L=>c(L.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(re,{className:"text-xs font-medium",children:"Channel"}),e.jsx("div",{className:"flex gap-1 mt-1",children:["email","sms"].map(L=>e.jsxs("button",{onClick:()=>x(L),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===L?"bg-primary text-primary-foreground border-primary":"bg-background text-muted-foreground border-input hover:border-primary/50"}`,children:[L==="sms"?e.jsx(xo,{className:"h-3 w-3"}):e.jsx(mn,{className:"h-3 w-3"}),L==="sms"?"SMS":"Email"]},L))})]}),e.jsxs("div",{className:"flex-1",children:[e.jsx(re,{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 ${_==="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 ${_==="scheduled"?"bg-primary text-primary-foreground border-primary":"bg-background text-muted-foreground border-input hover:border-primary/50"}`,children:[e.jsx(Xr,{className:"h-3 w-3 mr-1 inline"}),"Delay"]})]})]})]}),_==="scheduled"&&e.jsxs("div",{children:[e.jsx(re,{className:"text-xs font-medium",children:"Delay"}),e.jsxs("div",{className:"flex items-center gap-2 mt-1",children:[e.jsx(we,{type:"number",min:1,value:k>=60?Math.round(k/60):k,onChange:L=>{const z=parseInt(L.target.value)||0;A(k>=60?z*60:z)},className:"h-8 w-20 text-sm"}),e.jsx("div",{className:"flex gap-1",children:[{label:"Minutes",mins:k<60?k:30},{label:"Hours",mins:k>=60?k:60},{label:"Days",mins:k>=1440?k:1440}].map(L=>e.jsx("button",{className:`px-2 py-1 rounded text-xs border transition-colors ${L.label==="Minutes"&&k<60||L.label==="Hours"&&k>=60&&k<1440||L.label==="Days"&&k>=1440?"bg-primary/10 text-primary border-primary/30":"text-muted-foreground border-input"}`,onClick:()=>{L.label==="Minutes"?A(30):L.label==="Hours"?A(60):A(1440)},children:L.label},L.label))})]})]}),y==="email"&&e.jsxs("div",{children:[e.jsx(re,{className:"text-xs font-medium",children:"Subject Line"}),e.jsx(we,{value:d,onChange:L=>u(L.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(re,{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:L=>{L.target.value&&M(L.target.value),L.target.value=""},children:[e.jsx("option",{value:"",children:"Merge variable..."}),C3n.map(L=>e.jsx("option",{value:L.key,children:L.label},L.key))]})]})]}),e.jsx("textarea",{value:h,onChange:L=>m(L.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(re,{className:"text-xs font-medium",children:"Attached Video"}),f?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(na,{className:"h-3 w-3 inline mr-1 text-primary"}),f.length>50?f.slice(0,50)+"...":f]}),e.jsx(B,{variant:"ghost",size:"sm",className:"h-7 text-xs text-destructive",onClick:()=>g(""),children:"Remove"})]}):e.jsxs("div",{className:"mt-1 flex items-center gap-1.5",children:[e.jsx(VWe,{onVideoReady:L=>g(L)}),e.jsx(tO,{userId:l,onSelect:L=>g(L),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 L=prompt("Paste a YouTube or Loom URL:");L&&g(L)},children:[e.jsx(gc,{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(qn,{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:I,disabled:T,children:T?"Saving...":"Save Drip"})]})]})]})]})}function q3n({template:s,onCopy:t,isCopying:n}){const[r,a]=N.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(We,{variant:"secondary",className:"text-[10px] px-1.5 py-0",children:l}),e.jsxs(We,{variant:"outline",className:"text-[10px] gap-1",children:[s.channel==="sms"?e.jsx(xo,{className:"h-3 w-3"}):e.jsx(mn,{className:"h-3 w-3"}),s.channel==="sms"?"SMS":"Email"]}),e.jsxs(We,{variant:"outline",className:"text-[10px] gap-1",children:[e.jsx(Xr,{className:"h-3 w-3"}),s.delay_type==="instant"?"Instant":o.replace("Sends ","")]}),r?e.jsx(Xo,{className:"h-4 w-4 text-muted-foreground ml-1"}):e.jsx(Qa,{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(Xr,{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(Pa,{className:"h-3.5 w-3.5"}),"Use This Template"]})]})]})}const z9t=()=>{const s=Id();return N.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 V3n(){return N.useEffect(()=>(document.body.classList.add("cardstudio-page"),()=>{document.body.classList.remove("cardstudio-page")}),[]),e.jsxs(I2e,{children:[e.jsx(Ss,{path:"/c/:shareToken",element:e.jsx(F9t,{})}),e.jsx(Ss,{path:"*",element:e.jsx(z9t,{})})]})}const sIe={Home:"🏠",Search:"🔍",DollarSign:"💰",Coffee:"☕",Calendar:"📅",Users:"👥",Phone:"📞",Video:"🎥"};function B9t({slugOverride:s}){const t=uo(),n=s||t.slug,[r,a]=N.useState("types"),[i,l]=N.useState(null),[o,c]=N.useState(null),[d,u]=N.useState(null),[h,m]=N.useState(new Date),[f,g]=N.useState({name:"",email:"",phone:"",message:""}),[y,x]=N.useState(!1),{data:_,isLoading:b}=mt({queryKey:["public-booking-settings",n],queryFn:async()=>{const{data:G,error:X}=await H.from("agent_booking_settings").select("*").eq("slug",n).eq("is_active",!0).single();if(X)throw X;return G},enabled:!!n}),{data:k}=mt({queryKey:["public-booking-profile",_==null?void 0:_.user_id],queryFn:async()=>{const{data:G,error:X}=await H.from("profiles").select("name, avatar_url, email, phone, title, bio").eq("id",_.user_id).single();if(X)throw X;return G},enabled:!!(_!=null&&_.user_id)}),{data:A=[]}=mt({queryKey:["public-booking-types",_==null?void 0:_.user_id],queryFn:async()=>{const{data:G,error:X}=await H.from("agent_booking_types").select("id, name, description, duration_minutes, color, icon, qualification_enabled").eq("user_id",_.user_id).eq("is_active",!0).order("sort_order");if(X)throw X;return G},enabled:!!(_!=null&&_.user_id)}),{data:T=[]}=mt({queryKey:["public-availability",_==null?void 0:_.user_id],queryFn:async()=>{const{data:G,error:X}=await H.from("agent_availability_slots").select("day_of_week, start_time, end_time").eq("user_id",_.user_id).eq("is_active",!0);if(X)throw X;return G},enabled:!!(_!=null&&_.user_id)}),{data:P=[]}=mt({queryKey:["public-blocked-dates",_==null?void 0:_.user_id],queryFn:async()=>{const{data:G,error:X}=await H.from("agent_blocked_dates").select("blocked_date").eq("user_id",_.user_id);if(X)throw X;return G.map(te=>te.blocked_date)},enabled:!!(_!=null&&_.user_id)}),{data:I=[]}=mt({queryKey:["public-existing-bookings",_==null?void 0:_.user_id,o],queryFn:async()=>{if(!o)return[];const G=Js(o,"yyyy-MM-dd"),{data:X,error:te}=await H.from("bookings").select("start_time, end_time").eq("agent_user_id",_.user_id).eq("booking_date",G).eq("status","confirmed");if(te)throw te;return X},enabled:!!(_!=null&&_.user_id)&&!!o}),M=N.useMemo(()=>[...new Set(T.map(G=>G.day_of_week))],[T]),L=G=>{const X=ey(new Date),te=Ad(X,(_==null?void 0:_.max_advance_days)||30),ne=Ad(X,0);return rN(G,ne)||pj(G,te)||P.includes(Js(G,"yyyy-MM-dd"))?!1:M.includes(G.getDay())},z=N.useMemo(()=>{if(!o||!i||!_)return[];const G=T.filter(ce=>ce.day_of_week===o.getDay()),X=i.duration_minutes,te=_.buffer_minutes||0,ne=[],me=new Date,ue=(_.min_notice_hours||2)*60*60*1e3;for(const ce of G){const[ae,he]=ce.start_time.split(":").map(Number),[xe,ve]=ce.end_time.split(":").map(Number);let ge=$W(BW(o,ae),he);const be=$W(BW(o,xe),ve);for(;E7(ge,X)<=be;){const Se=Js(ge,"HH:mm"),Ie=Js(E7(ge,X),"HH:mm");ge.getTime()-me.getTime()>=ue&&(I.some(Re=>{const Be=Re.start_time.slice(0,5),Ne=Re.end_time.slice(0,5);return SeBe})||ne.push(Se)),ge=E7(ge,X+te)}}return ne},[o,i,T,_,I]),$=N.useMemo(()=>{const G=h.getFullYear(),X=h.getMonth(),te=new Date(G,X,1),ne=new Date(G,X+1,0),me=te.getDay(),ue=[];for(let ce=0;ce{if(!(!i||!o||!d||!f.name||!_)){x(!0);try{const G=Js(E7($W(BW(new Date,parseInt(d.split(":")[0])),parseInt(d.split(":")[1])),i.duration_minutes),"HH:mm"),{error:X}=await H.from("bookings").insert({agent_user_id:_.user_id,booking_type_id:i.id,booking_date:Js(o,"yyyy-MM-dd"),start_time:d,end_time:G,guest_name:f.name,guest_email:f.email||null,guest_phone:f.phone||null,guest_message:f.message||null});if(X)throw X;H.functions.invoke("booking-notify",{body:{agentUserId:_.user_id,guestName:f.name,guestEmail:f.email||null,guestPhone:f.phone||null,guestMessage:f.message||null,bookingTypeName:i.name,bookingDate:Js(o,"yyyy-MM-dd"),startTime:d,endTime:G,durationMinutes:i.duration_minutes,meetingLink:_.meeting_link||null}}).catch(te=>console.error("Booking notify error:",te)),a("confirmed")}catch(G){ie.error("Failed to book: "+G.message)}finally{x(!1)}}},W=G=>{const[X,te]=G.split(":").map(Number),ne=X>=12?"PM":"AM";return`${X%12||12}:${te.toString().padStart(2,"0")} ${ne}`};return b?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..."})]})}):_?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:[k!=null&&k.avatar_url?e.jsx("img",{src:k.avatar_url,alt:(k==null?void 0:k.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(Ro,{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:(k==null?void 0:k.name)||"Agent"}),(k==null?void 0:k.title)&&e.jsx("p",{className:"text-sm text-slate-500 mt-0.5",children:k.title})]})]})}),e.jsxs("div",{className:"px-6 py-4 flex flex-wrap gap-2",children:[(k==null?void 0:k.phone)&&e.jsxs("a",{href:`tel:${k.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(ga,{className:"h-3.5 w-3.5"}),e.jsx("span",{className:"hidden sm:inline",children:k.phone}),e.jsx("span",{className:"sm:hidden",children:"Call"})]}),(k==null?void 0:k.email)&&e.jsxs("a",{href:`mailto:${k.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(mn,{className:"h-3.5 w-3.5"}),e.jsx("span",{className:"hidden sm:inline",children:k.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:A.map(G=>e.jsx("button",{onClick:()=>{l(G),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:G.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:sIe[G.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:G.name}),G.description&&e.jsx("p",{className:"text-xs text-slate-500 mt-0.5 line-clamp-2",children:G.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(Xr,{className:"h-3 w-3"}),G.duration_minutes,"m"]})]})})},G.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:sIe[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(Xr,{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:Js(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(Fc,{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(Qa,{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(G=>e.jsx("div",{className:"text-[10px] uppercase tracking-wider text-slate-400 font-semibold py-2",children:G},G)),$.map((G,X)=>{if(!G)return e.jsx("div",{},`pad-${X}`);const te=L(G),ne=o&&yd(G,o),me=yd(G,new Date);return e.jsx("button",{disabled:!te,onClick:()=>{c(G),u(null)},className:`h-10 w-10 mx-auto rounded-xl text-sm font-medium transition-all duration-150 ${ne?"bg-[#406E71] text-white shadow-md shadow-[#406E71]/30 scale-105":te?"hover:bg-[#406E71]/10 text-slate-700 hover:text-[#406E71]":"text-slate-200 cursor-not-allowed"} ${me&&!ne?"ring-1 ring-[#406E71]/40":""}`,children:G.getDate()},G.toISOString())})]})]}),o&&e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ld,{className:"h-4 w-4 text-[#406E71]"}),e.jsx("h3",{className:"font-semibold text-sm text-slate-800",children:Js(o,"EEEE, MMMM d")})]}),z.length===0?e.jsxs("div",{className:"text-center py-8 space-y-2",children:[e.jsx(Xr,{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:z.map(G=>{const X=d===G;return e.jsx("button",{onClick:()=>u(G),className:`px-3 py-2.5 rounded-xl text-sm font-medium transition-all duration-150 ${X?"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:W(G)},G)})}),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:sIe[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(ld,{className:"h-3.5 w-3.5 text-[#406E71]"}),Js(o,"EEE, MMM d, yyyy")]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Xr,{className:"h-3.5 w-3.5 text-[#406E71]"}),W(d)," · ",i.duration_minutes," min"]})]})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(re,{className:"text-xs font-semibold text-slate-700",children:"Full Name *"}),e.jsx(we,{value:f.name,onChange:G=>g({...f,name:G.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(re,{className:"text-xs font-semibold text-slate-700",children:"Email"}),e.jsxs("div",{className:"relative",children:[e.jsx(mn,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-slate-400"}),e.jsx(we,{type:"email",value:f.email,onChange:G=>g({...f,email:G.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(re,{className:"text-xs font-semibold text-slate-700",children:"Phone"}),e.jsxs("div",{className:"relative",children:[e.jsx(ga,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-slate-400"}),e.jsx(we,{type:"tel",value:f.phone,onChange:G=>g({...f,phone:G.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(re,{className:"text-xs font-semibold text-slate-700",children:"Message (optional)"}),e.jsx(Ws,{value:f.message,onChange:G=>g({...f,message:G.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:V,disabled:!f.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(Hr,{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 ",(k==null?void 0:k.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&&Js(o,"EEEE, MMMM d, yyyy")}),e.jsxs("p",{className:"text-slate-500",children:[d&&W(d)," · ",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."}),((k==null?void 0:k.phone)||(k==null?void 0:k.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:[(k==null?void 0:k.phone)&&e.jsxs("a",{href:`tel:${k.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(ga,{className:"h-3.5 w-3.5"})," Call"]}),(k==null?void 0:k.email)&&e.jsxs("a",{href:`mailto:${k.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(mn,{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(ld,{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 H3n(){const t=Id().pathname.slice(1).split("/")[0];return N.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(B9t,{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 G3n(){const t=Id().pathname.slice(1);return N.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(j4t,{slugOverride:t})}function W3n(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 K3n={playfair:"'Playfair Display', Georgia, serif",baskerville:"'Libre Baskerville', Georgia, serif",instrument:"'Instrument Serif', Georgia, serif",sans:"'Inter', system-ui, sans-serif"};function Y3n({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=K3n[s.heading_font||"playfair"],u=s.eyebrow||null,h=s.headline_accent||null,m=Array.isArray(s.trust_pills)?s.trust_pills:[],f=t.slice(0,5);return e.jsxs("section",{className:"relative w-full min-h-screen md:min-h-[760px] overflow-hidden",style:{backgroundColor:c},children:[s.hero_image_url?e.jsx("img",{src:s.hero_image_url,alt:"",className:"absolute inset-0 w-full h-full object-cover",loading:"eager"}):e.jsx("div",{className:"absolute inset-0",style:{background:`linear-gradient(135deg, ${c}, #000)`}}),e.jsx("div",{className:"absolute inset-0 bg-gradient-to-r from-black/85 via-black/55 to-black/25"}),e.jsx("div",{className:"absolute inset-0 bg-gradient-to-t from-black/70 via-transparent to-black/20"}),e.jsx("div",{className:"relative z-10 mx-auto w-full max-w-7xl px-6 md:px-10 py-16 md:py-24 min-h-screen md:min-h-[760px] flex items-center",children:e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-5 gap-10 lg:gap-12 w-full items-center",children:[e.jsxs("div",{className:"lg:col-span-3 text-white",children:[s.logo_url&&e.jsx(Z3n,{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(ga,{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(mn,{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:[f.map(g=>e.jsxs("div",{children:[e.jsxs(re,{className:"block text-[11px] font-semibold tracking-wider uppercase text-white/85 mb-1.5",children:[g.label,g.is_required&&e.jsx("span",{className:"ml-1",style:{color:o},children:"*"})]}),e.jsx("div",{className:"[&_input]:bg-white/95 [&_input]:border-0 [&_input]:text-neutral-900 [&_input]:placeholder:text-neutral-400 [&_textarea]:bg-white/95 [&_textarea]:border-0 [&_textarea]:text-neutral-900 [&_textarea]:placeholder:text-neutral-400 [&_button[role=combobox]]:bg-white/95 [&_button[role=combobox]]:border-0 [&_button[role=combobox]]:text-neutral-900",children:l(g,n,r,c)})]},g.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((g,y)=>e.jsxs("span",{className:"flex items-center gap-1.5 text-[11px] md:text-xs text-white/80 font-medium",children:[e.jsx("span",{className:"h-1 w-1 rounded-full",style:{backgroundColor:o}}),g]},y))})]})})]})})]})}function Z3n({src:s}){const[t,n]=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(W3n(a.currentTarget)),onError:()=>n(!0)});return t===!1?e.jsx("span",{className:"inline-flex items-center rounded-md bg-white/90 backdrop-blur px-3 py-2 mb-6 shadow-sm",children:r}):e.jsx("div",{className:"mb-6 inline-block drop-shadow-md",children:r})}function X3n(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 Q3n(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 J3n(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 eCn({startsAt:s,locationName:t,address:n,title:r,accent:a}){const[i,l]=N.useState(Date.now());N.useEffect(()=>{const f=setInterval(()=>l(Date.now()),1e3);return()=>clearInterval(f)},[]);const o=new Date(s).getTime();if(!Number.isFinite(o))return null;const c=X3n(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(f=>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(f.v).padStart(2,"0")}),e.jsx("div",{className:"text-[10px] uppercase tracking-wider text-muted-foreground",children:f.l})]},f.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(Xr,{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(ii,{className:"h-3.5 w-3.5"})," ",h]})]})]}),!d&&e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsxs("a",{href:Q3n(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(ta,{className:"h-4 w-4"})," Add to Google"]}),e.jsxs("a",{href:J3n(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(ta,{className:"h-4 w-4"})," Apple / Outlook"]})]})]})})})}function tCn(){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 $9t({slugOverride:s}){var $;const{slug:t}=uo(),n=s||t,[r,a]=N.useState(!1),[i,l]=N.useState({}),[o,c]=N.useState(0),[d,u]=N.useState(!1),[h,m]=N.useState(""),[f]=N.useState(()=>Date.now()),g=N.useState(()=>tCn())[0],{data:y,isLoading:x}=mt({queryKey:["public-landing-page",n],queryFn:async()=>{const{data:V,error:W}=await H.from("landing_pages").select("*").eq("slug",n).eq("is_published",!0).single();if(W)throw W;return V},enabled:!!n}),{data:_=[]}=mt({queryKey:["public-landing-page-fields",y==null?void 0:y.id],queryFn:async()=>{const{data:V,error:W}=await H.from("landing_page_fields").select("*").eq("page_id",y.id).order("sort_order");if(W)throw W;return V},enabled:!!(y!=null&&y.id)});N.useEffect(()=>{y!=null&&y.id&&H.from("landing_pages").update({view_count:(y.view_count||0)+1}).eq("id",y.id).then(()=>{})},[y==null?void 0:y.id]),N.useEffect(()=>{if(!(y!=null&&y.id))return;const V=new URLSearchParams(window.location.search);H.functions.invoke("landing-page-track",{body:{page_id:y.id,event_type:"view",session_id:g,utm_source:V.get("utm_source"),utm_medium:V.get("utm_medium"),utm_campaign:V.get("utm_campaign"),referrer:document.referrer||null,device:window.matchMedia("(max-width: 768px)").matches?"mobile":"desktop"}}).catch(()=>{})},[y==null?void 0:y.id,g]);const b=_t({mutationFn:async()=>{const V=_.find(ae=>ae.field_type==="text"&&ae.label.toLowerCase().includes("name")),W=_.find(ae=>ae.field_type==="email"),G=_.find(ae=>ae.field_type==="phone"),X=V?String(i[V.label]||""):null,te=W?String(i[W.label]||""):null,ne=G?String(i[G.label]||""):null,me=new URLSearchParams(window.location.search),{data:ue,error:ce}=await H.functions.invoke("landing-page-submit",{body:{page_id:y.id,answers:JSON.parse(JSON.stringify(i)),contact_name:X,contact_email:te,contact_phone:ne,session_id:g,honeypot:h,rendered_at:f,utm_source:me.get("utm_source"),utm_medium:me.get("utm_medium"),utm_campaign:me.get("utm_campaign"),referrer:document.referrer||null}});if(ce)throw ce;return ue},onSuccess:V=>{a(!0),V!=null&&V.redirect_url&&setTimeout(()=>{window.location.href=V.redirect_url},1500)}}),k=V=>{V.preventDefault(),!(_.filter(G=>G.is_required&&!i[G.label]).length>0)&&b.mutate()};if(x)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(!y)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 A=y.primary_color||"#406E71",T=y.accent_color||"#2a4c64",P=y,I=y.page_type==="lead_magnet",M=y.page_type==="just_listed"||y.page_type==="just_sold",L=Array.isArray(P.property_photos)?P.property_photos:[],z=P.lead_magnet_file_url||P.lead_magnet_external_url;if(r)return e.jsx("div",{className:"min-h-screen flex items-center justify-center",style:{background:`linear-gradient(135deg, ${A}, ${T})`},children:e.jsxs("div",{className:"bg-white rounded-2xl shadow-2xl p-8 max-w-md mx-4 text-center",children:[e.jsx(Hr,{className:"h-16 w-16 mx-auto mb-4",style:{color:A}}),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:y.success_message}),I&&z&&e.jsxs("a",{href:z,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:A},children:[e.jsx(oi,{className:"h-5 w-5"}),"Download ",P.lead_magnet_file_name||"Your File"]}),y.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:y.agent_name}),y.agent_phone&&e.jsxs("a",{href:`tel:${y.agent_phone}`,className:"text-sm flex items-center justify-center gap-1 mt-1",style:{color:A},children:[e.jsx(ga,{className:"h-3 w-3"})," ",y.agent_phone]}),y.agent_email&&e.jsxs("a",{href:`mailto:${y.agent_email}`,className:"text-sm flex items-center justify-center gap-1 mt-1",style:{color:A},children:[e.jsx(mn,{className:"h-3 w-3"})," ",y.agent_email]})]})]})});if(M){const V=W=>{const G=parseFloat(W.replace(/[^0-9.]/g,""));return isNaN(G)?W:new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:0}).format(G)};return e.jsxs("div",{className:"min-h-screen bg-gray-50",children:[d&&L.length>0&&e.jsxs("div",{className:"fixed inset-0 z-50 bg-black/95 flex items-center justify-center",onClick:()=>u(!1),children:[e.jsx("button",{onClick:()=>u(!1),className:"absolute top-4 right-4 text-white/80 hover:text-white z-10",children:e.jsx(hr,{className:"h-8 w-8"})}),e.jsx("button",{onClick:W=>{W.stopPropagation(),c(G=>G===0?L.length-1:G-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(Fc,{className:"h-6 w-6"})}),e.jsx("img",{src:L[o],alt:`Property photo ${o+1}`,className:"max-h-[90vh] max-w-[90vw] object-contain rounded-lg",onClick:W=>W.stopPropagation()}),e.jsx("button",{onClick:W=>{W.stopPropagation(),c(G=>G===L.length-1?0:G+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(Qa,{className:"h-6 w-6"})}),e.jsxs("div",{className:"absolute bottom-6 left-1/2 -translate-x-1/2 text-white/70 text-sm",children:[o+1," / ",L.length]})]}),L.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:P.property_status==="just_sold"?"#e74c3c":A},children:P.property_status==="just_sold"?"🎉 Just Sold":"🏡 Just Listed"}),L.length===1?e.jsxs("div",{className:"rounded-2xl overflow-hidden cursor-pointer group",onClick:()=>{c(0),u(!0)},children:[e.jsx("img",{src:L[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($T,{className:"h-4 w-4"})," View"]})]}):L.length===2?e.jsx("div",{className:"grid grid-cols-2 gap-2 rounded-2xl overflow-hidden",children:L.slice(0,2).map((W,G)=>e.jsx("div",{className:"cursor-pointer group relative",onClick:()=>{c(G),u(!0)},children:e.jsx("img",{src:W,alt:`Property ${G+1}`,className:"w-full h-[45vh] object-cover group-hover:scale-105 transition-transform duration-500"})},G))}):e.jsxs("div",{className:"grid grid-cols-4 gap-2 rounded-2xl overflow-hidden",style:{height:"55vh"},children:[e.jsx("div",{className:"col-span-2 row-span-2 cursor-pointer group relative",onClick:()=>{c(0),u(!0)},children:e.jsx("img",{src:L[0],alt:"Property main",className:"w-full h-full object-cover group-hover:scale-105 transition-transform duration-500"})}),L.slice(1,5).map((W,G)=>e.jsxs("div",{className:"cursor-pointer group relative",onClick:()=>{c(G+1),u(!0)},children:[e.jsx("img",{src:W,alt:`Property ${G+2}`,className:"w-full h-full object-cover group-hover:scale-105 transition-transform duration-500"}),G===3&&L.length>5&&e.jsxs("div",{className:"absolute inset-0 bg-black/50 flex items-center justify-center text-white font-bold text-lg",children:["+",L.length-5," more"]})]},G))]}),L.length>2&&e.jsxs("button",{onClick:()=>{c(0),u(!0)},className:"absolute bottom-4 right-8 bg-white shadow-lg hover:shadow-xl text-gray-800 px-4 py-2 rounded-lg text-sm font-medium flex items-center gap-2 transition-shadow",children:[e.jsx($T,{className:"h-4 w-4"})," View all ",L.length," photos"]})]}),L.length===0&&e.jsx("div",{className:"relative py-16 px-4",style:{background:y.hero_image_url?`linear-gradient(rgba(0,0,0,0.55), rgba(0,0,0,0.55)), url(${y.hero_image_url}) center/cover`:`linear-gradient(135deg, ${A}, ${T})`},children:e.jsxs("div",{className:"max-w-2xl mx-auto text-center text-white",children:[y.logo_url&&e.jsx("img",{src:y.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:y.hero_headline}),y.hero_subtext&&e.jsx("p",{className:"mt-3 text-lg opacity-90",children:y.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:[P.property_price&&e.jsx("p",{className:"text-3xl md:text-4xl font-bold mb-2",style:{color:A},children:V(P.property_price)}),P.property_address&&e.jsxs("p",{className:"text-gray-600 flex items-center gap-1.5 mb-5 text-lg",children:[e.jsx(ii,{className:"h-5 w-5 shrink-0"})," ",P.property_address]}),e.jsxs("div",{className:"flex gap-6 mb-5 py-4 border-y border-gray-100",children:[P.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(A_,{className:"h-5 w-5",style:{color:A}})," ",P.property_beds]}),e.jsx("p",{className:"text-xs text-gray-500 mt-0.5",children:"Bedrooms"})]}),P.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(Wx,{className:"h-5 w-5",style:{color:A}})," ",P.property_baths]}),e.jsx("p",{className:"text-xs text-gray-500 mt-0.5",children:"Bathrooms"})]}),P.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(l3,{className:"h-5 w-5",style:{color:A}})," ",Number(P.property_sqft).toLocaleString()]}),e.jsx("p",{className:"text-xs text-gray-500 mt-0.5",children:"Sq Ft"})]})]}),P.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:P.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:A},children:P.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!"}),y.agent_name&&e.jsxs("div",{className:"flex items-center gap-3 mb-5 pb-4 border-b",children:[y.agent_photo_url&&e.jsx("img",{src:y.agent_photo_url,alt:y.agent_name,className:"h-12 w-12 rounded-full object-cover"}),e.jsxs("div",{children:[e.jsx("p",{className:"font-semibold text-sm",children:y.agent_name}),e.jsxs("div",{className:"flex flex-col gap-0.5 text-xs text-gray-500",children:[y.agent_phone&&e.jsxs("a",{href:`tel:${y.agent_phone}`,className:"flex items-center gap-1 hover:underline",children:[e.jsx(ga,{className:"h-3 w-3"})," ",y.agent_phone]}),y.agent_email&&e.jsxs("a",{href:`mailto:${y.agent_email}`,className:"flex items-center gap-1 hover:underline",children:[e.jsx(mn,{className:"h-3 w-3"})," ",y.agent_email]})]})]})]}),e.jsxs("form",{onSubmit:k,className:"space-y-3",children:[_.map(W=>e.jsxs("div",{children:[e.jsxs(re,{className:"text-xs font-medium",children:[W.label,W.is_required&&e.jsx("span",{className:"text-red-500 ml-1",children:"*"})]}),nIe(W,i,l)]},W.id)),e.jsx(B,{type:"submit",className:"w-full text-white",style:{backgroundColor:A},disabled:b.isPending,children:b.isPending?"Submitting...":"Submit"}),b.isError&&e.jsx("p",{className:"text-sm text-red-500 text-center",children:"Something went wrong. Please try again."})]})]})})]})}),e.jsx("div",{className:"text-center py-8 text-xs text-gray-400",children:"Powered by LevelUp"})]})}return y.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:h,onChange:V=>m(V.target.value),style:{position:"absolute",left:"-10000px",top:"auto",width:"1px",height:"1px",overflow:"hidden"}}),e.jsx(Y3n,{page:y,fields:_,answers:i,setAnswers:l,onSubmit:k,isSubmitting:b.isPending,renderField:nIe}),y.page_type==="event_registration"&&(($=y.settings)==null?void 0:$.event_starts_at)&&e.jsx(eCn,{startsAt:y.settings.event_starts_at,locationName:y.settings.event_location_name,address:y.settings.event_address,title:y.hero_headline||y.title,accent:y.accent_color||y.primary_color||"#406E71"}),b.isError&&e.jsx("p",{className:"text-sm text-red-500 text-center py-4",children:"Something went wrong. Please try again."}),e.jsx("div",{className:"text-center py-8 text-xs text-gray-400",children:"Powered by LevelUp"})]}):e.jsxs("div",{className:"min-h-screen bg-gray-50",children:[e.jsx("div",{className:"relative py-16 px-4",style:{background:y.hero_image_url?`linear-gradient(rgba(0,0,0,0.55), rgba(0,0,0,0.55)), url(${y.hero_image_url}) center/cover`:`linear-gradient(135deg, ${A}, ${T})`},children:e.jsxs("div",{className:"max-w-2xl mx-auto text-center text-white",children:[y.logo_url&&e.jsx("img",{src:y.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:y.hero_headline}),y.hero_subtext&&e.jsx("p",{className:"mt-3 text-lg opacity-90",children:y.hero_subtext}),I&&P.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(oi,{className:"h-4 w-4"}),"Free Download: ",P.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!"}),y.agent_name&&e.jsxs("div",{className:"flex items-center gap-3 mb-6 pb-4 border-b",children:[y.agent_photo_url&&e.jsx("img",{src:y.agent_photo_url,alt:y.agent_name,className:"h-12 w-12 rounded-full object-cover"}),e.jsxs("div",{children:[e.jsx("p",{className:"font-semibold",children:y.agent_name}),e.jsxs("div",{className:"flex items-center gap-3 text-sm text-gray-500",children:[y.agent_phone&&e.jsxs("a",{href:`tel:${y.agent_phone}`,className:"flex items-center gap-1 hover:underline",children:[e.jsx(ga,{className:"h-3 w-3"})," ",y.agent_phone]}),y.agent_email&&e.jsxs("a",{href:`mailto:${y.agent_email}`,className:"flex items-center gap-1 hover:underline",children:[e.jsx(mn,{className:"h-3 w-3"})," ",y.agent_email]})]})]})]}),e.jsxs("form",{onSubmit:k,className:"space-y-4",children:[_.map(V=>e.jsxs("div",{children:[e.jsxs(re,{className:"text-sm font-medium",children:[V.label,V.is_required&&e.jsx("span",{className:"text-red-500 ml-1",children:"*"})]}),nIe(V,i,l)]},V.id)),e.jsx(B,{type:"submit",className:"w-full text-white",style:{backgroundColor:A},disabled:b.isPending,children:b.isPending?"Submitting...":I?"Get My Free Download":"Submit"}),b.isError&&e.jsx("p",{className:"text-sm text-red-500 text-center",children:"Something went wrong. Please try again."})]})]})}),e.jsx("div",{className:"text-center py-8 text-xs text-gray-400",children:"Powered by LevelUp"})]})}function nIe(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(we,{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(Ws,{value:String(a),onChange:l=>n(o=>({...o,[s.label]:l.target.value})),placeholder:s.placeholder||"",rows:3,className:"mt-1"});case"select":return e.jsxs(Ns,{value:String(a),onValueChange:l=>n(o=>({...o,[s.label]:l})),children:[e.jsx(ws,{className:"mt-1",children:e.jsx(ks,{placeholder:"Select..."})}),e.jsx(js,{children:i.map(l=>e.jsx(nt,{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(Bi,{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(zn,{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(we,{value:String(a),onChange:l=>n(o=>({...o,[s.label]:l.target.value})),className:"mt-1"})}}function sCn(){const t=Id().pathname.slice(1).split("/")[0];return N.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($9t,{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 nCn=[{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}],MFn={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",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"},LFn={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",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"},jgt={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","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 PFn(s){return jgt[s]||jgt.basic}function rCn(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}):nCn,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}}function aCn(){const t=window.location.hostname.match(/^([^.]+)\.thelocalmove\.com$/i);return t?t[1]:null}function iCn(){const s=aCn(),{data:t,isLoading:n,error:r}=mt({queryKey:["lead-site",s],queryFn:async()=>{var u;if(!s)return null;const{data:a,error:i}=await H.from("lead_sites").select("*").eq("subdomain_slug",s).eq("is_active",!0).maybeSingle();if(i)throw i;if(!a)return null;const{data:l}=await H.from("profiles").select("id, name, avatar_url, email, phone, title, bio, areas_served, years_experience, instagram_url, facebook_url, linkedin_url").eq("id",a.agent_id).single();let o=null;if(a.show_team_logo)if(a.team_logo_url)o=a.team_logo_url;else{const{data:h}=await H.from("team_members").select("team_id, teams(avatar_url, name)").eq("user_id",a.agent_id).limit(1).maybeSingle();h&&((u=h.teams)!=null&&u.avatar_url)&&(o=h.teams.avatar_url)}const c={id:a.id,agentId:a.agent_id,subdomainSlug:a.subdomain_slug,mlsProviderId:a.mls_provider_id,siteTitle:a.site_title,siteTagline:a.site_tagline,leadRegistrationMode:a.lead_registration_mode||"disabled",registrationTriggerCount:a.registration_trigger_count??1,themeConfig:a.theme_config||{},isActive:a.is_active,brokerageLegalName:a.brokerage_legal_name||null,brokerageLicenseNumber:a.brokerage_license_number||null,agentLicenseNumber:a.agent_license_number||null,licenseState:a.license_state||null,mlsDisclaimerText:a.mls_disclaimer_text||null,mlsLogoUrl:a.mls_logo_url||null,equalHousingEnabled:a.equal_housing_enabled??!0,faviconUrl:a.favicon_url||null,ogImageUrl:a.og_image_url||null,showTeamLogo:a.show_team_logo??!1,teamLogoUrl:o,noMlsMode:a.no_mls_mode===!0,bookingUrl:a.booking_url||null,pageSubtitles:a.page_subtitles||{},agent:l?{id:l.id,full_name:l.name||"",avatar_url:l.avatar_url,email:l.email,phone:l.phone,title:l.title,bio:l.bio,areas_served:l.areas_served||null,years_experience:l.years_experience??null,instagram_url:l.instagram_url||null,facebook_url:l.facebook_url||null,linkedin_url:l.linkedin_url||null}:void 0,testimonials:Array.isArray(a.testimonials)?a.testimonials.filter(h=>h&&typeof h=="object"&&h.text).map(h=>({name:String(h.name||"Client"),text:String(h.text),rating:typeof h.rating=="number"?h.rating:5,location:h.location?String(h.location):void 0})):[],seoMetaTitle:a.seo_meta_title||null,seoMetaDescription:a.seo_meta_description||null},d=rCn(a);return{siteConfig:c,themeConfig:d}},enabled:!!s,staleTime:5*60*1e3,gcTime:30*60*1e3,refetchOnWindowFocus:!1});return{siteConfig:(t==null?void 0:t.siteConfig)??null,themeConfig:(t==null?void 0:t.themeConfig)??null,isLoading:n,error:r,slug:s}}async function oCn(s,t){try{await H.functions.invoke("lead-site-notify",{body:{lead:t,lead_site_id:s}})}catch(n){console.warn("Lead notification failed:",n)}}const U9t=N.createContext(null);function TAe(){const s=N.useContext(U9t);if(!s)throw new Error("useLeadSiteAuth must be used within LeadSiteAuthProvider");return s}function lCn({siteConfig:s,children:t}){const[n,r]=N.useState(null),[a,i]=N.useState(null),[l,o]=N.useState(!0);N.useEffect(()=>{const{data:{subscription:h}}=H.auth.onAuthStateChange(async(m,f)=>{const g=(f==null?void 0:f.user)??null;if(r(g),g){const{data:y}=await H.from("lead_site_consumer_profiles").select("id, name, phone").eq("user_id",g.id).eq("lead_site_id",s.id).maybeSingle();y&&i({...y,email:g.email||""})}else i(null);o(!1)});return H.auth.getSession().then(({data:{session:m}})=>{r((m==null?void 0:m.user)??null),m!=null&&m.user?H.from("lead_site_consumer_profiles").select("id, name, phone").eq("user_id",m.user.id).eq("lead_site_id",s.id).maybeSingle().then(({data:f})=>{f&&i({...f,email:m.user.email||""}),o(!1)}):o(!1)}),()=>h.unsubscribe()},[s.id]);const c=N.useCallback(async h=>{const m=h.email.toLowerCase().trim(),f=h.phone.replace(/\D/g,""),{data:g,error:y}=await H.auth.signUp({email:m,password:f,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,f);return}throw y}if(g.user){const{error:x}=await H.from("lead_site_consumer_profiles").insert({user_id:g.user.id,lead_site_id:s.id,name:h.name.trim(),phone:h.phone.trim()});x&&console.warn("Consumer profile insert error:",x);const{error:_}=await H.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}});_&&console.error("Lead insert error (CRM sync may not trigger):",_),oCn(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=N.useCallback(async(h,m)=>{const f=m.replace(/\D/g,""),{error:g}=await H.auth.signInWithPassword({email:h.toLowerCase().trim(),password:f});if(g)throw g},[]),u=N.useCallback(async()=>{await H.auth.signOut(),r(null),i(null)},[]);return e.jsx(U9t.Provider,{value:{user:n,profile:a,isLoading:l,signUp:c,signIn:d,signOut:u},children:t})}const cCn=new Set(["7605cc2e-ce21-4f4f-8bb1-4c0f217b1109"]),dCn=new Set(["tomlois"]);function q9t(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||cCn.has(s.id||"")||dCn.has((s.subdomainSlug||"").toLowerCase())||!s.mlsProviderId:!1}function IFn(s){return`Contact ${s.split(" ")[0]||"Me"}`}const cq="#c9a96e",uCn="Schedule a Free Consultation",hCn={sm:"px-5 py-2.5 text-[11px]",md:"px-7 py-3.5 text-xs",lg:"px-9 py-4 text-xs"};function f3({bookingUrl:s,label:t=uCn,className:n="",variant:r="solid",color:a=cq,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 ${hCn[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(kT,{className:"h-4 w-4 flex-shrink-0"}),e.jsx("span",{children:t})]})}function DFn({bookingUrl:s,agentName:t,accentColor:n=cq,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:Xr,title:r.point1Title||"30 Minutes",text:r.point1Text||"A focused conversation about your goals, timeline, and options."},{icon:dW,title:r.point2Title||"A Personal Call",text:r.point2Text||`${t.split(" ")[0]} calls you at the time you choose — no phone tag.`},{icon:Hr,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,f)=>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})]},f))}),e.jsxs("div",{className:"mt-12 flex flex-col items-center gap-4",children:[e.jsx(f3,{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 RFn({bookingUrl:s,accentColor:t=cq,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(f3,{bookingUrl:s,label:"Schedule Now",color:t,size:"sm",className:"flex-shrink-0",source:l})]}):null}function mCn({bookingUrl:s,accentColor:t=cq}){const[n,r]=N.useState(!1),[a,i]=N.useState(!1);if(N.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(kT,{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(hr,{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(f3,{bookingUrl:s,label:"Schedule a Free Consultation",size:"sm",color:t,source:"sticky"})})]})}function pCn({bookingUrl:s,agentName:t}){return N.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(kT,{className:"h-8 w-8 mx-auto mb-6",style:{color:cq}}),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(f3,{bookingUrl:s,label:"Open Booking Calendar",size:"lg",source:"schedule_page"})})]})})}function JWe({open:s,mode:t,siteConfig:n,onComplete:r,onSkip:a,theme:i="default",accentColor:l}){var W;const{signUp:o,signIn:c}=TAe(),[d,u]=N.useState(!1),[h,m]=N.useState(""),[f,g]=N.useState(""),[y,x]=N.useState(""),[_,b]=N.useState(!1),[k,A]=N.useState(""),T=t==="required",P=i==="luxury",I=l||(P?"#c9a96e":"#2563eb"),M=((W=n.agent)==null?void 0:W.full_name)||"the agent",L={borderColor:`${I}66`,"--tw-ring-color":`${I}66`},z=async G=>{var te;if(G.preventDefault(),A(""),!f.trim()||!y.trim()){A("Email and phone number are required.");return}if(!d&&!h.trim()){A("Name is required.");return}if(y.replace(/\D/g,"").length<7){A("Please enter a valid phone number.");return}b(!0);try{d?await c(f,y):await o({name:h,email:f,phone:y}),r()}catch(ne){(te=ne==null?void 0:ne.message)!=null&&te.includes("Invalid login")?A("Invalid email or phone number. Please try again."):A((ne==null?void 0:ne.message)||"Something went wrong. Please try again.")}finally{b(!1)}},$=P?"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=P?L:void 0;return e.jsx(Bs,{open:s,onOpenChange:T?void 0:G=>{G||a()},children:e.jsxs(Fs,{className:`sm:max-w-md ${P?"border-white/10 bg-[#f7f1e7] text-[#201915]":""}`,onPointerDownOutside:T?G=>G.preventDefault():void 0,onEscapeKeyDown:T?G=>G.preventDefault():void 0,children:[e.jsxs(qs,{children:[e.jsx($s,{className:"text-xl",style:P?{fontFamily:"'Playfair Display', Georgia, serif"}:void 0,children:d?"Welcome Back":T?"Create a Free Account to Continue":"Save Your Search & Get Updates"}),e.jsx(Ar,{className:P?"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:z,className:"space-y-3 mt-2",children:[!d&&e.jsx("input",{type:"text",required:!0,placeholder:"Your name",value:h,onChange:G=>m(G.target.value),className:$,style:V}),e.jsx("input",{type:"email",required:!0,placeholder:"Email address",value:f,onChange:G=>g(G.target.value),className:$,style:V}),e.jsxs("div",{children:[e.jsx("input",{type:"tel",required:!0,placeholder:"Phone number",value:y,onChange:G=>x(G.target.value),className:$,style:V}),e.jsx("p",{className:`text-xs mt-1 ${P?"text-[#8a7869]":"text-gray-400"}`,children:d?"Your phone number is your password":"Your phone number will be used as your password"})]}),k&&e.jsx("p",{className:"text-red-600 text-sm",children:k}),e.jsx("button",{type:"submit",disabled:_,className:`w-full py-2.5 font-medium rounded-lg disabled:opacity-50 transition-colors ${P?"text-black hover:opacity-90 tracking-wider uppercase text-sm":"bg-blue-600 text-white hover:bg-blue-700"}`,style:P?{backgroundColor:I}:void 0,children:_?d?"Signing in...":"Creating account...":d?"Sign In":"Create Account"}),e.jsx("button",{type:"button",onClick:()=>{u(!d),A("")},className:"w-full text-center text-sm hover:opacity-80 transition-opacity",style:{color:I},children:d?"Don't have an account? Sign up":"Already have an account? Sign in"}),!T&&!d&&e.jsx("button",{type:"button",onClick:a,className:`w-full py-2 text-sm transition-colors ${P?"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 ${P?"text-[#8a7869]":"text-gray-400"}`,children:"By registering you agree to receive property updates. You can unsubscribe anytime."})]})})}function eKe({siteConfig:s,pagePath:t}){const n=s.agent;if(!n)return null;const r=`https://${s.subdomainSlug}.thelocalmove.com`,i=(n.areas_served||"").split(/,|;|\|/).map(k=>k.trim()).filter(Boolean),l=i[0]||"",[o,c]=l.split(/,\s*/),d=(n.bio||"").match(/\b(CRS|GRI|ABR|CNE|SRES|SRS|RENE|MRP|PSA|AHWD|C2EX|CIPS|CRB|e-?PRO)\b/gi)||[],u=[...new Set(d.map(k=>k.toUpperCase()))],h=s.testimonials||[],m=h.length?{"@type":"AggregateRating",ratingValue:(h.reduce((k,A)=>k+(A.rating||5),0)/h.length).toFixed(1),reviewCount:h.length,bestRating:5,worstRating:1}:void 0,f=[n.facebook_url,n.instagram_url,n.linkedin_url].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:n.title||"Real Estate Agent",description:n.bio||`${n.full_name} is a trusted local real estate professional${l?` serving ${l}`:""}.`,priceRange:"$$",...f.length&&{sameAs:f},...s.brokerageLegalName&&{worksFor:{"@type":"RealEstateAgent",name:s.brokerageLegalName,...s.brokerageLicenseNumber&&{identifier:s.brokerageLicenseNumber}}},...s.agentLicenseNumber&&{identifier:s.agentLicenseNumber},...o&&{address:{"@type":"PostalAddress",addressLocality:o,...c&&{addressRegion:c},addressCountry:"US"}},...i.length&&{areaServed:i.map(k=>{const[A,T]=k.split(/,\s*/);return{"@type":"City",name:A,...T&&{containedInPlace:{"@type":"State",name:T}}}})},...m&&{aggregateRating:m},...h.length&&{review:h.slice(0,10).map(k=>({"@type":"Review",author:{"@type":"Person",name:k.name},reviewBody:k.text,reviewRating:{"@type":"Rating",ratingValue:k.rating||5,bestRating:5,worstRating:1},...k.location&&{locationCreated:{"@type":"Place",name:k.location}}}))}},y={"@context":"https://schema.org","@type":"Person","@id":`${r}/#person`,name:n.full_name,jobTitle:n.title||"Real Estate Agent",description:n.bio||void 0,image:n.avatar_url||void 0,url:r,email:n.email,telephone:n.phone||void 0,...f.length&&{sameAs:f},...n.years_experience&&{knowsAbout:["Residential Real Estate","Home Buying","Home Selling",l?`${l} Real Estate`:"Local Real Estate"].filter(Boolean)},...u.length&&{hasCredential:u.map(k=>({"@type":"EducationalOccupationalCredential",credentialCategory:"designation",name:k}))},...s.brokerageLegalName&&{worksFor:{"@type":"Organization",name:s.brokerageLegalName}}},x={"@context":"https://schema.org","@type":"WebSite","@id":`${r}/#website`,name:s.siteTitle||`${n.full_name} Real Estate`,url:r,publisher:{"@id":`${r}/#agent`},potentialAction:{"@type":"SearchAction",target:{"@type":"EntryPoint",urlTemplate:`${r}/search?q={search_term_string}`},"query-input":"required name=search_term_string"}},_=[{name:"Search Homes",description:`Browse all current MLS listings${l?` in ${l}`:""}.`,path:"/search"},{name:"Featured Areas",description:"Explore featured neighborhoods, cities, and communities.",path:"/areas"},{name:"Sold Properties",description:"See recently sold homes and local market activity.",path:"/sold"},{name:"Home Valuation",description:"Get a free, no-obligation estimate of what your home is worth.",path:"/sell"},{name:"About",description:`Learn more about ${n.full_name}${s.brokerageLegalName?` and ${s.brokerageLegalName}`:""}.`,path:"/about"},{name:"Contact",description:`Get in touch with ${n.full_name} for buying, selling, or relocation help.`,path:"/contact"}],b={"@context":"https://schema.org","@type":"ItemList","@id":`${r}/#nav`,name:"Main Navigation",itemListElement:_.map((k,A)=>({"@type":"SiteNavigationElement",position:A+1,name:k.name,description:k.description,url:`${r}${k.path}`}))};return e.jsxs(ic,{children:[e.jsx("script",{type:"application/ld+json",children:JSON.stringify(g)}),e.jsx("script",{type:"application/ld+json",children:JSON.stringify(y)}),e.jsx("script",{type:"application/ld+json",children:JSON.stringify(x)}),e.jsx("script",{type:"application/ld+json",children:JSON.stringify(b)})]})}function OFn({items:s,siteConfig:t}){const n=`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(ic,{children:e.jsx("script",{type:"application/ld+json",children:JSON.stringify(r)})})}function FFn({listing:s,siteConfig:t}){var a;const n=`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(ic,{children:e.jsx("script",{type:"application/ld+json",children:JSON.stringify(r)})})}function fCn({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(ic,{children:e.jsx("script",{type:"application/ld+json",children:JSON.stringify(t)})})}function zFn({title:s,description:t,publishedAt:n,imageUrl:r,slug:a,siteConfig:i}){const l=`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(ic,{children:e.jsx("script",{type:"application/ld+json",children:JSON.stringify(c)})})}function tKe({siteConfig:s}){var f;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=((f=a.split(/,|;|\|/)[0])==null?void 0:f.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(g=>g.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(fCn,{faqs:m})}const Ngt="ls_visitor_geo",gCn=1e3*60*60,rIe="lu_lc_attrib_v1",xCn=1e3*60*60*24*90;function yCn(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 vCn(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 bCn(){try{const s=localStorage.getItem(Ngt);if(s){const t=JSON.parse(s);if(Date.now()-t.ts{i.current||(i.current=!0,bCn().then(l=>{a.current=l}))},[]),N.useEffect(()=>{if(!(s!=null&&s.id))return;const l=n.pathname;if(l===r.current)return;r.current=l;const o=yCn(l),c=vCn(l,o),d=localStorage.getItem(`ls_visitor_fp_${s.id}`)||null,u=a.current;(async()=>{const m=new URLSearchParams(n.search),f=m.get("luc");if(f&&/^[0-9a-f-]{36}$/i.test(f)){try{localStorage.setItem(rIe,JSON.stringify({contact_id:f,ts:Date.now()}))}catch{}return f}const g=m.get("lc");if(g&&/^[0-9a-f-]{36}$/i.test(g)){const{data:y}=await H.from("listing_email_recipients").select("contact_id").eq("id",g).maybeSingle(),x=y==null?void 0:y.contact_id;if(x){try{localStorage.setItem(rIe,JSON.stringify({contact_id:x,ts:Date.now()}))}catch{}return x}}try{const y=localStorage.getItem(rIe);if(y){const x=JSON.parse(y);if(x!=null&&x.contact_id&&Date.now()-(x.ts||0){H.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:f})=>{f&&console.error("[PageTracking] insert failed:",f.message)})})},[n.pathname,n.search,s==null?void 0:s.id,t])}const _Cn=3e4;function nKe(s,t){const n=Id(),r=N.useRef(null),a=N.useRef(null),i=N.useRef(0),l=n.pathname,o=wCn(l),c=jCn(l,o),d=o==="listing"&&l.split("/listing/")[1]||null;N.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:f}=await H.from("lead_site_active_visitors").upsert({lead_site_id:s.id,auth_user_id:t,visitor_fingerprint:u,current_page_path:l,current_page_title:c,current_mls_number:d,last_seen_at:new Date().toISOString(),listing_views_count:i.current},{onConflict:"lead_site_id,coalesce(auth_user_id::text,visitor_fingerprint,'')"}).select("id, notified_agent").single();!f&&m&&(r.current=m.id,i.current>=2&&!m.notified_agent&&H.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,_Cn),()=>{a.current&&clearInterval(a.current)}},[s==null?void 0:s.id,t,l]),N.useEffect(()=>{if(!(s!=null&&s.id)||!t)return;const u=()=>{r.current&&H.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 wCn(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 jCn(s,t){switch(t){case"home":return"Home";case"search":return"Search";case"listing":return`Listing ${s.split("/listing/")[1]||""}`;case"city":return s.replace("/homes-for-sale-in-","").split("-").map(r=>r.charAt(0).toUpperCase()+r.slice(1)).join(" ");case"subdivision":return s.replace("/homes-in-","").split("-").map(r=>r.charAt(0).toUpperCase()+r.slice(1)).join(" ");default:return s}}const bi=Number.isFinite||function(s){return typeof s=="number"&&isFinite(s)},NCn=Number.isSafeInteger||function(s){return typeof s=="number"&&Math.abs(s)<=kCn},kCn=Number.MAX_SAFE_INTEGER||9007199254740991;let ao=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}({}),lr=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}({}),Et=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 Ac={MANIFEST:"manifest",LEVEL:"level",AUDIO_TRACK:"audioTrack",SUBTITLE_TRACK:"subtitleTrack"},Ri={MAIN:"main",AUDIO:"audio",SUBTITLE:"subtitle"};class FF{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 SCn{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 FF(t),this.fast_=new FF(n),this.defaultTTFB_=a,this.ttfb_=new FF(t)}update(t,n){const{slow_:r,fast_:a,ttfb_:i}=this;r.halfLife!==t&&(this.slow_=new FF(t,r.getEstimate(),r.getTotalWeight())),a.halfLife!==n&&(this.fast_=new FF(n,a.getEstimate(),a.getTotalWeight())),i.halfLife!==t&&(this.ttfb_=new FF(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 CCn(s,t,n){return(t=TCn(t))in s?Object.defineProperty(s,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):s[t]=n,s}function rh(){return rh=Object.assign?Object.assign.bind():function(s){for(var t=1;t`):rA}function Sgt(s,t,n){return t[s]?t[s].bind(t):MCn(s,n)}const Nze=jze();function LCn(s,t,n){const r=jze();if(typeof console=="object"&&s===!0||typeof s=="object"){const a=["debug","log","info","warn","error"];a.forEach(i=>{r[i]=Sgt(i,s,n)});try{r.log(`Debug logs enabled for "${t}" in hls.js version 1.6.16`)}catch{return jze()}a.forEach(i=>{Nze[i]=Sgt(i,s)})}else rh(Nze,r);return r}const Gu=Nze;function wE(s=!0){return typeof self>"u"?void 0:(s||!self.MediaSource)&&self.ManagedMediaSource||self.MediaSource||self.WebKitMediaSource}function PCn(s){return typeof self<"u"&&s===self.ManagedMediaSource}function V9t(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 z_(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 L0(s){let t="";for(let n=0;n1||a===1&&(n=this.levelkeys[r[0]])!=null&&n.encrypted)return!0}return!1}get programDateTime(){return this._programDateTime===null&&this.rawProgramDateTime&&(this.programDateTime=Date.parse(this.rawProgramDateTime)),this._programDateTime}set programDateTime(t){if(!bi(t)){this._programDateTime=this.rawProgramDateTime=null;return}this._programDateTime=t}get ref(){return $f(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 RCn extends G9t{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 W9t(s,t){const n=Object.getPrototypeOf(s);if(n){const r=Object.getOwnPropertyDescriptor(n,t);return r||W9t(n,t)}}function OCn(s,t){const n=W9t(s,t);n&&(n.enumerable=!0,Object.defineProperty(s,t,n))}const Agt=Math.pow(2,32)-1,FCn=[].push,K9t={video:1,audio:2,id3:3,text:4};function Gg(s){return String.fromCharCode.apply(null,s)}function Y9t(s,t){const n=s[t]<<8|s[t+1];return n<0?65536+n:n}function ul(s,t){const n=Z9t(s,t);return n<0?4294967296+n:n}function Tgt(s,t){let n=ul(s,t);return n*=Math.pow(2,32),n+=ul(s,t+4),n}function Z9t(s,t){return s[t]<<24|s[t+1]<<16|s[t+2]<<8|s[t+3]}function zCn(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 wc(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=wc(s.subarray(a+8,o),t.slice(1));c.length&&FCn.apply(n,c)}a=o}return n}function BCn(s){const t=[],n=s[0];let r=8;const a=ul(s,r);r+=4;let i=0,l=0;n===0?(i=ul(s,r),l=ul(s,r+4),r+=8):(i=Tgt(s,r),l=Tgt(s,r+8),r+=16),r+=2;let o=s.length+l;const c=Y9t(s,r);r+=2;for(let d=0;d>>31===1)return Gu.warn("SIDX has hierarchical references (not supported)"),null;const g=ul(s,u);u+=4,t.push({referenceSize:m,subsegmentDuration:g,info:{duration:g/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 X9t(s){const t=[],n=wc(s,["moov","trak"]);for(let a=0;a{const i=ul(a,4),l=t[i];l&&(l.default={duration:ul(a,12),flags:ul(a,20)})}),t}function $Cn(s){const t=s.subarray(8),n=t.subarray(86),r=Gg(t.subarray(4,8));let a=r,i;const l=r==="enca"||r==="encv";if(l){const d=wc(t,[r])[0].subarray(r==="enca"?28:78);wc(d,["sinf"]).forEach(h=>{const m=wc(h,["schm"])[0];if(m){const f=Gg(m.subarray(4,8));if(f==="cbcs"||f==="cenc"){const g=wc(h,["frma"])[0];g&&(a=Gg(g))}}})}const o=a;switch(a){case"avc1":case"avc2":case"avc3":case"avc4":{const c=wc(n,["avcC"])[0];c&&c.length>3&&(a+="."+Rne(c[1])+Rne(c[2])+Rne(c[3]),i=Dne(o==="avc1"?"dva1":"dvav",n));break}case"mp4a":{const c=wc(t,[r])[0],d=wc(c.subarray(28),["esds"])[0];if(d&&d.length>7){let u=4;if(d[u++]!==3)break;u=oIe(d,u),u+=2;const h=d[u++];if(h&128&&(u+=2),h&64&&(u+=d[u++]),d[u++]!==4)break;u=oIe(d,u);const m=d[u++];if(m===64)a+="."+Rne(m);else break;if(u+=12,d[u++]!==5)break;u=oIe(d,u);const f=d[u++];let g=(f&248)>>3;g===31&&(g+=1+((f&7)<<3)+((d[u]&224)>>5)),a+="."+g}break}case"hvc1":case"hev1":{const c=wc(n,["hvcC"])[0];if(c&&c.length>12){const d=c[1],u=["","A","B","C"][d>>6],h=d&31,m=ul(c,2),f=(d&32)>>5?"H":"L",g=c[12],y=c.subarray(6,12);a+="."+u+h,a+="."+UCn(m).toString(16).toUpperCase(),a+="."+f+g;let x="";for(let _=y.length;_--;){const b=y[_];(b||x)&&(x="."+b.toString(16).toUpperCase()+x)}a+=x}i=Dne(o=="hev1"?"dvhe":"dvh1",n);break}case"dvh1":case"dvhe":case"dvav":case"dva1":case"dav1":{a=Dne(a,n)||a;break}case"vp09":{const c=wc(n,["vpcC"])[0];if(c&&c.length>6){const d=c[4],u=c[5],h=c[6]>>4&15;a+="."+bk(d)+"."+bk(u)+"."+bk(h)}break}case"av01":{const c=wc(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,f=(c[2]&32)>>5,g=d===2&&m?f?12:10:m?10:8,y=(c[2]&16)>>4,x=(c[2]&8)>>3,_=(c[2]&4)>>2,b=c[2]&3;a+="."+d+"."+bk(u)+h+"."+bk(g)+"."+y+"."+x+_+b+"."+bk(1)+"."+bk(1)+"."+bk(1)+"."+0,i=Dne("dav1",n)}break}}return{codec:a,encrypted:l,supplemental:i}}function Dne(s,t){const n=wc(t,["dvvC"]),r=n.length?n[0]:wc(t,["dvcC"])[0];if(r){const a=r[2]>>1&127,i=r[2]<<5&32|r[3]>>3&31;return s+"."+bk(a)+"."+bk(i)}}function UCn(s){let t=0;for(let n=0;n<32;n++)t|=(s>>n&1)<<31-n;return t>>>0}function oIe(s,t){const n=t+5;for(;s[t++]&128&&t{const i=r.subarray(8,24);i.some(l=>l!==0)||(Gu.log(`[eme] Patching keyId in 'enc${a?"a":"v"}>sinf>>tenc' box: ${L0(i)} -> ${L0(n)}`),r.set(n,8))})}function VCn(s){const t=[];return Q9t(s,n=>t.push(n.subarray(8,24))),t}function Q9t(s,t){wc(s,["moov","trak"]).forEach(r=>{const a=wc(r,["mdia","minf","stbl","stsd"])[0];if(!a)return;const i=a.subarray(8);let l=wc(i,["enca"]);const o=l.length>0;o||(l=wc(i,["encv"])),l.forEach(c=>{const d=o?c.subarray(28):c.subarray(78);wc(d,["sinf"]).forEach(h=>{const m=J9t(h);m&&t(m,o)})})})}function J9t(s){const t=wc(s,["schm"])[0];if(t){const n=Gg(t.subarray(4,8));if(n==="cbcs"||n==="cenc"){const r=wc(s,["schi","tenc"])[0];if(r)return r}}}function HCn(s,t,n){const r={},a=wc(s,["moof","traf"]);for(let i=0;ir[i].duration)){let i=1/0,l=0;const o=wc(s,["sidx"]);for(let c=0;ch+m.info.duration||0,0);l=Math.max(l,u+d.earliestPresentationTime/d.timescale)}}l&&bi(l)&&Object.keys(r).forEach(c=>{r[c].duration||(r[c].duration=l*r[c].timescale-r[c].start)})}return r}function GCn(s){const t={valid:null,remainder:null},n=wc(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 Sj(s,t){const n=new Uint8Array(s.length+t.length);return n.set(s),n.set(t,s.length),n}function Egt(s,t){const n=[],r=t.samples,a=t.timescale,i=t.id;let l=!1;return wc(r,["moof"]).map(c=>{const d=c.byteOffset-8;wc(c,["traf"]).map(h=>{const m=wc(h,["tfdt"]).map(f=>{const g=f[0];let y=ul(f,4);return g===1&&(y*=Math.pow(2,32),y+=ul(f,8)),y/a})[0];return m!==void 0&&(s=m),wc(h,["tfhd"]).map(f=>{const g=ul(f,4),y=ul(f,0)&16777215,x=(y&1)!==0,_=(y&2)!==0,b=(y&8)!==0;let k=0;const A=(y&16)!==0;let T=0;const P=(y&32)!==0;let I=8;g===i&&(x&&(I+=8),_&&(I+=4),b&&(k=ul(f,I),I+=4),A&&(T=ul(f,I),I+=4),P&&(I+=4),t.type==="video"&&(l=EAe(t.codec)),wc(h,["trun"]).map(M=>{const L=M[0],z=ul(M,0)&16777215,$=(z&1)!==0;let V=0;const W=(z&4)!==0,G=(z&256)!==0;let X=0;const te=(z&512)!==0;let ne=0;const me=(z&1024)!==0,ue=(z&2048)!==0;let ce=0;const ae=ul(M,4);let he=8;$&&(V=ul(M,he),he+=4),W&&(he+=4);let xe=V+d;for(let ve=0;ve>1&63;return n===39||n===40}else return(t&31)===6}function iKe(s,t,n,r){const a=ezt(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){Gu.error(`Malformed SEI payload. ${o} is too small, only ${d} bytes left to parse.`);break}if(l===4){if(a[u++]===181){const m=Y9t(a,u);if(u+=2,m===49){const f=ul(a,u);if(u+=4,f===1195456820){const g=a[u++];if(g===3){const y=a[u++],x=31&y,_=64&y,b=_?2+x*3:0,k=new Uint8Array(b);if(_){k[0]=y;for(let A=1;A16){const h=[];for(let g=0;g<16;g++){const y=a[u++].toString(16);h.push(y.length==1?"0"+y:y),(g===3||g===5||g===7||g===9)&&h.push("-")}const m=o-16,f=new Uint8Array(m);for(let g=0;g>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),YCn([112,115,115,104],new Uint8Array([r,0,0,0]),s,i,a,l,n)}function XCn(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=L0(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 f=0;f/\(Windows.+Firefox\//i.test(navigator.userAgent),z$={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 oKe(s,t){const n=z$[t];return!!n&&!!n[s.slice(0,4)]}function DZ(s,t,n=!0){return!s.split(",").some(r=>!lKe(r,t,n))}function lKe(s,t,n=!0){var r;const a=wE(n);return(r=a==null?void 0:a.isTypeSupported(RZ(s,t)))!=null?r:!1}function RZ(s,t){return`${t}/mp4;codecs=${s}`}function Mgt(s){if(s){const t=s.substring(0,4);return z$.video[t]}return 2}function V5e(s){const t=tzt();return s.split(",").reduce((n,r)=>{const i=t&&EAe(r)?9:z$.video[r];return i?(i*2+n)/(n?3:2):(z$.audio[r]+n)/(n?2:1)},0)}const lIe={};function JCn(s,t=!0){if(lIe[s])return lIe[s];const n={flac:["flac","fLaC","FLAC"],opus:["opus","Opus"],"mp4a.40.34":["mp3"]}[s];for(let a=0;aJCn(n.toLowerCase(),t))}function tAn(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)&&(Lgt(s,"audio")||Lgt(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 Lgt(s,t){return oKe(s,t)&&lKe(s,t)}function sAn(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 nAn(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 Pgt(s){const t=wE(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 kze(s){return s.replace(/^.+codecs=["']?([^"']+).*$/,"$1")}const rAn={supported:!0,powerEfficient:!0,smooth:!0},aAn={supported:!1,smooth:!1,powerEfficient:!1},szt={supported:!0,configurations:[],decodingInfoResults:[rAn]};function nzt(s,t){return{supported:!1,configurations:t,decodingInfoResults:[aAn],error:s}}function iAn(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,f)=>{if(f){const g=t.groups[f];if(!g)throw new Error(`Audio track group ${f} not found`);Object.keys(g.channels).forEach(y=>{m[y]=(m[y]||0)+g.channels[y]})}return m},{2:0})}catch{return!0}return l!==void 0&&(l.split(",").some(m=>EAe(m))||s.width>1920&&s.height>1088||s.height>1920&&s.width>1088||s.frameRate>Math.max(r,30)||s.videoRange!=="SDR"&&s.videoRange!==n||s.bitrate>Math.max(a,8e6))||!!h&&bi(u)&&Object.keys(h).some(m=>parseInt(m)>u)}function rzt(s,t,n,r={}){const a=s.videoCodec;if(!a&&!s.audioCodec||!n)return Promise.resolve(szt);const i=[],l=oAn(s),o=l.length,c=lAn(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=>EAe(h))&&tzt())return Promise.resolve(nzt(new Error(`Overriding Windows Firefox HEVC MediaCapabilities result based on user-agent string: (${u})`),i))}return Promise.all(i.map(u=>{const h=dAn(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 oAn(s){var t;const n=(t=s.videoCodec)==null?void 0:t.split(","),r=azt(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:RZ(nAn(c),"video"),width:a,height:i,bitrate:r,framerate:l};return o!=="sdr"&&(d.transferFunction=o),d}):[]}function lAn(s,t,n){var r;const a=(r=s.audioCodec)==null?void 0:r.split(","),i=azt(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(f=>{const g={contentType:RZ(f,"audio"),bitrate:n?cAn(f,i):i};m&&(g.channels=""+m),u.push(g)})}return u},l):l},[]):[]}function cAn(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 azt(s){return Math.ceil(Math.max(s.bitrate*.9,s.averageBitrate)/1e3)*1e3||1}function dAn(s){let t="";const{audio:n,video:r}=s;if(r){const a=kze(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=kze(n.contentType);t+=`${r?"_":""}${a}_c${n.channels}`}return t}const Sze=["NONE","TYPE-0","TYPE-1",null];function uAn(s){return Sze.indexOf(s)>-1}const G5e=["SDR","PQ","HLG"];function hAn(s){return!!s&&G5e.indexOf(s)>-1}var qje={No:"",Yes:"YES",v2:"v2"};function Igt(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 Rgt(this._audioGroups,t)}hasSubtitleGroup(t){return Rgt(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 Rgt(s,t){return!t||!s?!1:s.indexOf(t)!==-1}function mAn(){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 pAn(s,t){let n=!1,r=[];if(s&&(n=s!=="SDR",r=[s]),t){r=t.allowedVideoRanges||G5e.slice(0);const a=r.join("")!=="SDR"&&!t.videoCodec;n=t.preferHDR!==void 0?t.preferHDR:a&&mAn(),n||(r=["SDR"])}return{preferHDR:n,allowedVideoRanges:r}}const fAn=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}},bh=(s,t)=>JSON.stringify(s,fAn(t));function gAn(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,f=1/0,g=1/0,y=1/0,x=0,_=[];const{preferHDR:b,allowedVideoRanges:k}=pAn(t,a);for(let M=i.length;M--;){const L=s[i[M]];u||(u=L.channels[2]>0),m=Math.min(m,L.minHeight),f=Math.min(f,L.minFramerate),g=Math.min(g,L.minBitrate),k.filter($=>L.videoRanges[$]>0).length>0&&(h=!0)}m=bi(m)?m:0,f=bi(f)?f:0;const A=Math.max(1080,m),T=Math.max(30,f);g=bi(g)?g:n,n=Math.max(g,n),h||(t=void 0);const P=i.length>1;return{codecSet:i.reduce((M,L)=>{const z=s[L];if(L===M)return M;if(_=h?k.filter($=>z.videoRanges[$]>0):[],P){if(z.minBitrate>n)return ik(L,`min bitrate of ${z.minBitrate} > current estimate of ${n}`),M;if(!z.hasDefaultAudio)return ik(L,"no renditions with default or auto-select sound found"),M;if(o&&L.indexOf(o.substring(0,4))%5!==0)return ik(L,`audio codec preference "${o}" not found`),M;if(l&&!d){if(!z.channels[l])return ik(L,`no renditions with ${l} channel sound found (channels options: ${Object.keys(z.channels)})`),M}else if((!o||d)&&u&&z.channels[2]===0)return ik(L,"no renditions with stereo sound found"),M;if(z.minHeight>A)return ik(L,`min resolution of ${z.minHeight} > maximum of ${A}`),M;if(z.minFramerate>T)return ik(L,`min framerate of ${z.minFramerate} > maximum of ${T}`),M;if(!_.some($=>z.videoRanges[$]>0))return ik(L,`no variants with VIDEO-RANGE of ${bh(_)} found`),M;if(c&&L.indexOf(c.substring(0,4))%5!==0)return ik(L,`video codec preference "${c}" not found`),M;if(z.maxScore=V5e(M)||z.fragmentError>s[M].fragmentError)?M:(y=z.minIndex,x=z.maxScore,L)},void 0),videoRanges:_,preferHDR:b,minFramerate:f,minBitrate:g,minIndex:y}}function ik(s,t){Gu.log(`[abr] start candidates with "${s}" ignored because ${t}`)}function izt(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 xAn(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 Ogt(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 a5(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 gI(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 bAn(s,t,n,r,a){const i=t[r],o=t.reduce((m,f,g)=>{const y=f.uri;return(m[y]||(m[y]=[])).push(g),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=Fgt(t,r,m=>{if(m.videoRange!==c||m.frameRate!==d||m.codecSet.substring(0,4)!==u)return!1;const f=m.audioGroups,g=n.filter(y=>!f||f.indexOf(y.groupId)!==-1);return a5(s,g,a)>-1});return h>-1?h:Fgt(t,r,m=>{const f=m.audioGroups,g=n.filter(y=>!f||f.indexOf(y.groupId)!==-1);return a5(s,g,a)>-1})}function Fgt(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,f=l.minAutoLevel,g=a.level,y=this._nextAutoLevel;if(u.aborted||u.loaded&&u.loaded===u.total||g<=f){this.clearTimer(),this._nextAutoLevel=-1;return}if(!o)return;const x=y>-1&&y!==g,_=!!n||x;if(!_&&(c.paused||!c.playbackRate||!c.readyState))return;const b=l.mainForwardBufferInfo;if(!_&&b===null)return;const k=this.bwEstimator.getEstimateTTFB(),A=Math.abs(c.playbackRate);if(m<=Math.max(k,1e3*(h/(A*2))))return;const T=b?b.len/A:0,P=u.loading.first?u.loading.first-u.loading.start:-1,I=u.loaded&&P>-1,M=this.getBwEstimate(),L=l.levels,z=L[g],$=Math.max(u.loaded,Math.round(h*(a.bitrate||z.averageBitrate)/8));let V=I?m-P:m;V<1&&I&&(V=Math.min(m,u.loaded*8/M));const W=I?u.loaded*1e3/V:0,G=k/1e3,X=W?($-u.loaded)/W:$*8/M+G;if(X<=T)return;const te=W?W*8:M,ne=((r=(n==null?void 0:n.details)||this.hls.latestLevelDetails)==null?void 0:r.live)===!0,me=this.hls.config.abrBandWidthUpFactor;let ue=Number.POSITIVE_INFINITY,ce;for(ce=g-1;ce>f;ce--){const ve=L[ce].maxBitrate,ge=!L[ce].details||ne;if(ue=this.getTimeToLoadFrag(G,te,h*ve,ge),ue=X||ue>h*10)return;I?this.bwEstimator.sample(m-Math.min(k,P),u.loaded):this.bwEstimator.sampleTTFB(m);const ae=L[ce].maxBitrate;this.getBwEstimate()*me>ae&&this.resetEstimator(ae);const he=this.findBestLevel(ae,f,ce,0,T,1,1);he>-1&&(ce=he),this.warn(`Fragment ${a.sn}${i?" part "+i.index:""} of level ${g} is loading too slowly; Fragment duration: ${a.duration.toFixed(3)} Time to underbuffer: ${T.toFixed(3)} s Estimated load time for current fragment: ${X.toFixed(3)} s Estimated load time for down switch fragment: ${ue.toFixed(3)} s TTFB estimate: ${P|0} ms Current BW estimate: ${bi(M)?M|0:"Unknown"} bps New BW estimate: ${this.getBwEstimate()|0} bps Switching to level ${ce} @ ${ae|0} bps`),l.nextLoadLevel=l.nextAutoLevel=ce,this.clearTimer();const xe=()=>{if(this.clearTimer(),this.fragCurrent===a&&this.hls.loadLevel===ce&&ce>0){const ve=this.getStarvationDelay();if(this.warn(`Aborting inflight request ${ce>0?"and switching down":""} Fragment duration: ${a.duration.toFixed(3)} s Time to underbuffer: ${ve.toFixed(3)} s`),a.abortRequests(),this.fragCurrent=this.partCurrent=null,ce>f){let ge=this.findBestLevel(this.hls.levels[f].bitrate,f,ce,0,ve,1,1);ge===-1&&(ge=f),this.hls.nextLoadLevel=this.hls.nextAutoLevel=ge,this.resetEstimator(this.hls.levels[ge].bitrate)}}};x||X>ue*2?xe():this.timer=self.setInterval(xe,ue*1e3),l.trigger(Et.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 SCn(t.abrEwmaSlowVoD,t.abrEwmaFastVoD,t.abrEwmaDefaultEstimate)}registerListeners(){const{hls:t}=this;t.on(Et.MANIFEST_LOADING,this.onManifestLoading,this),t.on(Et.FRAG_LOADING,this.onFragLoading,this),t.on(Et.FRAG_LOADED,this.onFragLoaded,this),t.on(Et.FRAG_BUFFERED,this.onFragBuffered,this),t.on(Et.LEVEL_SWITCHING,this.onLevelSwitching,this),t.on(Et.LEVEL_LOADED,this.onLevelLoaded,this),t.on(Et.LEVELS_UPDATED,this.onLevelsUpdated,this),t.on(Et.MAX_AUTO_LEVEL_UPDATED,this.onMaxAutoLevelUpdated,this),t.on(Et.ERROR,this.onError,this)}unregisterListeners(){const{hls:t}=this;t&&(t.off(Et.MANIFEST_LOADING,this.onManifestLoading,this),t.off(Et.FRAG_LOADING,this.onFragLoading,this),t.off(Et.FRAG_LOADED,this.onFragLoaded,this),t.off(Et.FRAG_BUFFERED,this.onFragBuffered,this),t.off(Et.LEVEL_SWITCHING,this.onLevelSwitching,this),t.off(Et.LEVEL_LOADED,this.onLevelLoaded,this),t.off(Et.LEVELS_UPDATED,this.onLevelsUpdated,this),t.off(Et.MAX_AUTO_LEVEL_UPDATED,this.onMaxAutoLevelUpdated,this),t.off(Et.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 lr.BUFFER_ADD_CODEC_ERROR:case lr.BUFFER_APPEND_ERROR:this.lastLoadedFragLevel=-1,this.firstSelection=-1;break;case lr.FRAG_LOAD_TIMEOUT:{const r=n.frag,{fragCurrent:a,partCurrent:i}=this;if(r&&a&&r.sn===a.sn&&r.level===a.level){const l=performance.now(),o=i?i.stats:r.stats,c=l-o.loading.start,d=o.loading.first?o.loading.first-o.loading.start:-1;if(o.loaded&&d>-1){const h=this.bwEstimator.getEstimateTTFB();this.bwEstimator.sample(c-Math.min(h,d),o.loaded)}else this.bwEstimator.sampleTTFB(c)}break}}}getTimeToLoadFrag(t,n,r,a){const i=t+r/n,l=a?t+this.lastLevelLoadSec:0;return i+l}onLevelLoaded(t,n){const r=this.hls.config,{loading:a}=n.stats,i=a.end-a.first;bi(i)&&(this.lastLevelLoadSec=i/1e3),n.details.live?this.bwEstimator.update(r.abrEwmaSlowLive,r.abrEwmaFastLive):this.bwEstimator.update(r.abrEwmaSlowVoD,r.abrEwmaFastVoD),this.timer>-1&&this._abandonRulesCheck(n.levelInfo)}onFragLoaded(t,{frag:n,part:r}){const a=r?r.stats:n.stats;if(n.type===Ri.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(Et.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!==Ri.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 x=this.findBestLevel(c,l,a,d,0,u,h);if(x>=0)return this.rebufferNotice=-1,x}let m=o?Math.min(o,i.maxStarvationDelay):i.maxStarvationDelay;if(!d){const x=this.bitrateTestDelay;x&&(m=(o?Math.min(o,i.maxLoadingDelay):i.maxLoadingDelay)-x,this.info(`bitrate test took ${Math.round(1e3*x)}ms, set first fragment max fetchDuration to ${Math.round(1e3*m)} ms`),u=h=1)}const f=this.findBestLevel(c,l,a,d,m,u,h);if(this.rebufferNotice!==f&&(this.rebufferNotice=f,this.info(`${d?"rebuffering expected":"buffer is empty"}, optimal quality level ${f}`)),f>-1)return f;const g=r.levels[l],y=r.loadLevelObj;return y&&(g==null?void 0:g.bitrate)=n;te--){var X;const ne=g[te],me=te>h;if(!ne)continue;if(_.useMediaCapabilities&&!ne.supportedResult&&!ne.supportedPromise){const ge=navigator.mediaCapabilities;typeof(ge==null?void 0:ge.decodingInfo)=="function"&&iAn(ne,z,P,I,t,M)?(ne.supportedPromise=rzt(ne,z,ge,this.supportedCache),ne.supportedPromise.then(be=>{if(!this.hls)return;ne.supportedResult=be;const Se=this.hls.levels,Ie=Se.indexOf(ne);be.error?this.warn(`MediaCapabilities decodingInfo error: "${be.error}" for level ${Ie} ${bh(be)}`):be.supported?be.decodingInfoResults.some(Me=>Me.smooth===!1||Me.powerEfficient===!1)&&this.log(`MediaCapabilities decodingInfo for level ${Ie} not smooth or powerEfficient: ${bh(be)}`):(this.warn(`Unsupported MediaCapabilities decodingInfo result for level ${Ie} ${bh(be)}`),Ie>-1&&Se.length>1&&(this.log(`Removing unsupported level ${Ie}`),this.hls.removeLevel(Ie),this.hls.loadLevel===-1&&(this.hls.nextLoadLevel=0)))}).catch(be=>{this.warn(`Error handling MediaCapabilities decodingInfo: ${be}`)})):ne.supportedResult=szt}if((T&&ne.codecSet!==T||P&&ne.videoRange!==P||me&&I>ne.frameRate||!me&&I>0&&Ige.smooth===!1))&&(!A||te!==$)){G.push(te);continue}const ue=ne.details,ce=(f?ue==null?void 0:ue.partTarget:ue==null?void 0:ue.averagetargetduration)||V;let ae;me?ae=o*t:ae=l*t;const he=V&&a>=V*2&&i===0?ne.averageBitrate:ne.maxBitrate,xe=this.getTimeToLoadFrag(W,ae,he*ce,ue===void 0);if(ae>=he&&(te===u||ne.loadError===0&&ne.fragmentError===0)&&(xe<=W||!bi(xe)||k&&!this.bitrateTestDelay||xe${te} adjustedbw(${Math.round(ae)})-bitrate=${Math.round(ae-he)} ttfb:${W.toFixed(1)} avgDuration:${ce.toFixed(1)} maxFetchDuration:${d.toFixed(1)} fetchDuration:${xe.toFixed(1)} firstSelection:${A} codecSet:${ne.codecSet} videoRange:${ne.videoRange} hls.loadLevel:${x}`)),A&&(this.firstSelection=te),te}}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 ozt={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 wAn(s,t,n){if(t===null||!Array.isArray(s)||!s.length||!bi(t))return null;const r=s[0].programDateTime;if(t<(r||0))return null;const a=s[s.length-1].endProgramDateTime;if(t>=(a||0))return null;for(let i=0;i0&&o<15e-7&&(n+=15e-7),i&&s.level!==i.level&&i.end<=s.end&&(i=t[2+s.sn-t[0].sn]||null)}else n===0&&t[0].start===0&&(i=t[0]);if(i&&((!s||s.level===i.level)&&zgt(n,r,i)===0||jAn(i,s,Math.min(a,r))))return i;const l=ozt.search(t,zgt.bind(null,n,r));return l&&(l!==s||!i)?l:i}function jAn(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 zgt(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 NAn(s,t,n){const r=Math.min(t,n.duration+(n.deltaPTS?n.deltaPTS:0))*1e3;return(n.endProgramDateTime||0)-r>s}function lzt(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 ozt.search(r,l=>l.cct?-1:(i=l,l.end<=n?1:l.start>n?-1:0)),i||null}return null}function K5e(s){switch(s.details){case lr.FRAG_LOAD_TIMEOUT:case lr.KEY_LOAD_TIMEOUT:case lr.LEVEL_LOAD_TIMEOUT:case lr.MANIFEST_LOAD_TIMEOUT:return!0}return!1}function czt(s){return s.details.startsWith("key")}function dzt(s){return czt(s)&&!!s.frag&&!s.frag.decryptdata}function Bgt(s,t){const n=K5e(t);return s.default[`${n?"timeout":"error"}Retry`]}function cKe(s,t){const n=s.backoff==="linear"?1:Math.pow(2,t);return Math.min(n*s.retryDelayMs,s.maxRetryDelayMs)}function $gt(s){return $u($u({},s),{errorRetry:null,timeoutRetry:null})}function Y5e(s,t,n,r){if(!s)return!1;const a=r==null?void 0:r.code,i=t499)}function Cze(s){return s===0&&navigator.onLine===!1}var M0={DoNothing:0,SendEndCallback:1,SendAlternateToPenaltyBox:2,RemoveAlternatePermanently:3,InsertDiscontinuity:4,RetryRequest:5},e_={None:0,MoveAllAlternatesMatchingHost:1,MoveAllAlternatesMatchingHDCP:2,MoveAllAlternatesMatchingKey:4,SwitchToSDR:8};class SAn extends Ij{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(Et.ERROR,this.onError,this),t.on(Et.MANIFEST_LOADING,this.onManifestLoading,this),t.on(Et.LEVEL_UPDATED,this.onLevelUpdated,this)}unregisterListeners(){const t=this.hls;t&&(t.off(Et.ERROR,this.onError,this),t.off(Et.ERROR,this.onErrorOut,this),t.off(Et.MANIFEST_LOADING,this.onManifestLoading,this),t.off(Et.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)===Ri.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 lr.FRAG_LOAD_ERROR:case lr.FRAG_LOAD_TIMEOUT:case lr.KEY_LOAD_ERROR:case lr.KEY_LOAD_TIMEOUT:n.errorAction=this.getFragRetryOrSwitchAction(n);return;case lr.FRAG_PARSING_ERROR:if((r=n.frag)!=null&&r.gap){n.errorAction=dz();return}case lr.FRAG_GAP:case lr.FRAG_DECRYPT_ERROR:{n.errorAction=this.getFragRetryOrSwitchAction(n),n.errorAction.action=M0.SendAlternateToPenaltyBox;return}case lr.LEVEL_EMPTY_ERROR:case lr.LEVEL_PARSING_ERROR:{var l;const c=n.parent===Ri.MAIN?n.level:a.loadLevel;n.details===lr.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 lr.LEVEL_LOAD_ERROR:case lr.LEVEL_LOAD_TIMEOUT:typeof(i==null?void 0:i.level)=="number"&&(n.errorAction=this.getPlaylistRetryOrSwitchAction(n,i.level));return;case lr.AUDIO_TRACK_LOAD_ERROR:case lr.AUDIO_TRACK_LOAD_TIMEOUT:case lr.SUBTITLE_LOAD_ERROR:case lr.SUBTITLE_TRACK_LOAD_TIMEOUT:if(i){const c=a.loadLevelObj;if(c&&(i.type===Ac.AUDIO_TRACK&&c.hasAudioGroup(i.groupId)||i.type===Ac.SUBTITLE_TRACK&&c.hasSubtitleGroup(i.groupId))){n.errorAction=this.getPlaylistRetryOrSwitchAction(n,a.loadLevel),n.errorAction.action=M0.SendAlternateToPenaltyBox,n.errorAction.flags=e_.MoveAllAlternatesMatchingHost;return}}return;case lr.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED:n.errorAction={action:M0.SendAlternateToPenaltyBox,flags:e_.MoveAllAlternatesMatchingHDCP};return;case lr.KEY_SYSTEM_SESSION_UPDATE_FAILED:case lr.KEY_SYSTEM_STATUS_INTERNAL_ERROR:case lr.KEY_SYSTEM_NO_SESSION:n.errorAction={action:M0.SendAlternateToPenaltyBox,flags:e_.MoveAllAlternatesMatchingKey};return;case lr.BUFFER_ADD_CODEC_ERROR:case lr.REMUX_ALLOC_ERROR:case lr.BUFFER_APPEND_ERROR:if(!n.errorAction){var o;n.errorAction=this.getLevelSwitchAction(n,(o=n.level)!=null?o:a.loadLevel)}return;case lr.INTERNAL_EXCEPTION:case lr.BUFFER_APPENDING_ERROR:case lr.BUFFER_FULL_ERROR:case lr.LEVEL_SWITCH_ERROR:case lr.BUFFER_STALLED_ERROR:case lr.BUFFER_SEEK_OVER_HOLE:case lr.BUFFER_NUDGE_ON_STALL:n.errorAction=dz();return}n.type===ao.KEY_SYSTEM_ERROR&&(n.levelRetry=!1,n.errorAction=dz())}getPlaylistRetryOrSwitchAction(t,n){const r=this.hls,a=Bgt(r.config.playlistLoadPolicy,t),i=this.playlistError++;if(Y5e(a,i,K5e(t),t.response))return{action:M0.RetryRequest,flags:e_.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=Bgt(czt(t)?l:i,t),c=n.levels.reduce((u,h)=>u+h.fragmentError,0);if(a&&(t.details!==lr.FRAG_GAP&&a.fragmentError++,!dzt(t)&&Y5e(o,c,K5e(t),t.response)))return{action:M0.RetryRequest,flags:e_.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===lr.BUFFER_APPEND_ERROR&&a.fragmentError++;let u=-1;const{levels:h,loadLevel:m,minAutoLevel:f,maxAutoLevel:g}=r;!r.autoLevelEnabled&&!r.config.preserveManualLevelOnError&&(r.loadLevel=-1);const y=(i=t.frag)==null?void 0:i.type,_=(y===Ri.AUDIO&&d===lr.FRAG_PARSING_ERROR||t.sourceBufferName==="audio"&&(d===lr.BUFFER_ADD_CODEC_ERROR||d===lr.BUFFER_APPEND_ERROR))&&h.some(({audioCodec:P})=>a.audioCodec!==P),k=t.sourceBufferName==="video"&&(d===lr.BUFFER_ADD_CODEC_ERROR||d===lr.BUFFER_APPEND_ERROR)&&h.some(({codecSet:P,audioCodec:I})=>a.codecSet!==P&&a.audioCodec===I),{type:A,groupId:T}=(l=t.context)!=null?l:{};for(let P=h.length;P--;){const I=(P+m)%h.length;if(I!==m&&I>=f&&I<=g&&h[I].loadError===0){var o,c;const M=h[I];if(d===lr.FRAG_GAP&&y===Ri.MAIN&&t.frag){const L=h[I].details;if(L){const z=MR(t.frag,L.fragments,t.frag.start);if(z!=null&&z.gap)continue}}else{if(A===Ac.AUDIO_TRACK&&M.hasAudioGroup(T)||A===Ac.SUBTITLE_TRACK&&M.hasSubtitleGroup(T))continue;if(y===Ri.AUDIO&&(o=a.audioGroups)!=null&&o.some(L=>M.hasAudioGroup(L))||y===Ri.SUBTITLE&&(c=a.subtitleGroups)!=null&&c.some(L=>M.hasSubtitleGroup(L))||_&&a.audioCodec===M.audioCodec||k&&a.codecSet===M.codecSet||!_&&a.codecSet!==M.codecSet)continue}u=I;break}}if(u>-1&&r.loadLevel!==u)return t.levelRetry=!0,this.playlistError=0,{action:M0.SendAlternateToPenaltyBox,flags:e_.None,nextAutoLevel:u}}return{action:M0.SendAlternateToPenaltyBox,flags:e_.MoveAllAlternatesMatchingHost}}onErrorOut(t,n){var r;switch((r=n.errorAction)==null?void 0:r.action){case M0.DoNothing:break;case M0.SendAlternateToPenaltyBox:this.sendAlternateToPenaltyBox(n),!n.errorAction.resolved&&n.details!==lr.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 e_.None:this.switchLevel(t,i);break;case e_.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=Sze[Sze.indexOf(u)-1],r.resolved=!0,this.warn(`Restricting playback to HDCP-LEVEL of "${n.maxHdcpLevel}" or lower`);break}}case e_.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) ${L0(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=zF(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),One(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]=Ugt(r,a=>a.fragment.sn>=t))}fragBuffered(t,n){const r=zF(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 f=Math.max(l,a.start(u)),g=Math.min(o,a.end(u));g>f&&(i.partial=!0,i.time.push({startPTS:f,endPTS:g}))}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&&One(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||One(n))}getState(t){const n=zF(t),r=this.fragments[n];return r?r.buffered?One(r)?Yg.PARTIAL:Yg.OK:Yg.APPENDING:Yg.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=zF(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=zF(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=zF(t);t.clearElementaryStreamInfo();const r=this.activePartLists[t.type];if(r){const a=t.sn;this.activePartLists[t.type]=Ugt(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 One(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 zF(s){return`${s.type}_${s.level}_${s.sn}`}function Ugt(s,t){return s.filter(n=>{const r=t(n);return r||n.clearElementaryStreamInfo(),r})}var jE={cbc:0,ctr:1};class AAn{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 jE.cbc:return this.subtle.decrypt({name:"AES-CBC",iv:this.aesIV},n,t);case jE.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 TAn(s){const t=s.byteLength,n=t&&new DataView(s.buffer).getUint8(t-1);return n?s.slice(0,t-n):s}class EAn{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],f=new Uint32Array(256);let g=0,y=0,x=0;for(x=0;x<256;x++)x<128?f[x]=x<<1:f[x]=x<<1^283;for(x=0;x<256;x++){let _=y^y<<1^y<<2^y<<3^y<<4;_=_>>>8^_&255^99,t[g]=_,n[_]=g;const b=f[g],k=f[b],A=f[k];let T=f[_]*257^_*16843008;a[g]=T<<24|T>>>8,i[g]=T<<16|T>>>16,l[g]=T<<8|T>>>24,o[g]=T,T=A*16843009^k*65537^b*257^g*16843008,d[_]=T<<24|T>>>8,u[_]=T<<16|T>>>16,h[_]=T<<8|T>>>24,m[_]=T,g?(g=b^f[f[f[A^b]]],y^=f[f[y]]):g=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!==jE.cbc||n.byteLength!==16)return Gu.warn("SoftwareDecrypt: can only handle AES-128-CBC"),null;this.logOnce("JS AES decrypt"),o&&(t=Sj(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 EAn),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 MAn(this.subtle,n,a)}return this.fastAesKey.expandKey().then(i=>this.subtle?(this.logOnce("WebCrypto AES decrypt"),new AAn(this.subtle,new Uint8Array(r),a).decrypt(t.buffer,i)):Promise.reject(new Error("web crypto not initialized"))).catch(i=>(Gu.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%PAn;return r!==t.length&&(n=t.slice(0,r),this.remainderData=t.slice(r)),n}logOnce(t){this.logEnabled&&(Gu.log(`[decrypter]: ${t}`),this.logEnabled=!1)}}const qgt=Math.pow(2,17);class IAn{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 n4({type:ao.NETWORK_ERROR,details:lr.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(g=>g[0]==="GAP")){c(Hgt(t));return}else t.gap=!1;const d=this.loader=i?new i(a):new l(a),u=Vgt(t);t.loader=d;const h=$gt(a.fragLoadPolicy.default),m={loadPolicy:h,timeout:h.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:t.sn==="initSegment"?1/0:qgt};t.stats=d.stats;const f={onSuccess:(g,y,x,_)=>{this.resetLoader(t,d);let b=g.data;x.resetIV&&t.decryptdata&&(t.decryptdata.iv=new Uint8Array(b.slice(0,16)),b=b.slice(16)),o({frag:t,part:null,payload:b,networkDetails:_})},onError:(g,y,x,_)=>{this.resetLoader(t,d),c(new n4({type:ao.NETWORK_ERROR,details:lr.FRAG_LOAD_ERROR,fatal:!1,frag:t,response:$u({url:r,data:void 0},g),error:new Error(`HTTP Error ${g.code} ${g.text}`),networkDetails:x,stats:_}))},onAbort:(g,y,x)=>{this.resetLoader(t,d),c(new n4({type:ao.NETWORK_ERROR,details:lr.INTERNAL_ABORTED,fatal:!1,frag:t,error:new Error("Aborted"),networkDetails:x,stats:g}))},onTimeout:(g,y,x)=>{this.resetLoader(t,d),c(new n4({type:ao.NETWORK_ERROR,details:lr.FRAG_LOAD_TIMEOUT,fatal:!1,frag:t,error:new Error(`Timeout after ${m.timeout}ms`),networkDetails:x,stats:g}))}};n&&(f.onProgress=(g,y,x,_)=>n({frag:t,part:null,payload:x,networkDetails:_})),d.load(u,m,f)})}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(Hgt(t,n));return}const d=this.loader=i?new i(a):new l(a),u=Vgt(t,n);t.loader=d;const h=$gt(a.fragLoadPolicy.default),m={loadPolicy:h,timeout:h.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:qgt};n.stats=d.stats,d.load(u,m,{onSuccess:(f,g,y,x)=>{this.resetLoader(t,d),this.updateStatsFromPart(t,n);const _={frag:t,part:n,payload:f.data,networkDetails:x};r(_),o(_)},onError:(f,g,y,x)=>{this.resetLoader(t,d),c(new n4({type:ao.NETWORK_ERROR,details:lr.FRAG_LOAD_ERROR,fatal:!1,frag:t,part:n,response:$u({url:u.url,data:void 0},f),error:new Error(`HTTP Error ${f.code} ${f.text}`),networkDetails:y,stats:x}))},onAbort:(f,g,y)=>{t.stats.aborted=n.stats.aborted,this.resetLoader(t,d),c(new n4({type:ao.NETWORK_ERROR,details:lr.INTERNAL_ABORTED,fatal:!1,frag:t,part:n,error:new Error("Aborted"),networkDetails:y,stats:f}))},onTimeout:(f,g,y)=>{this.resetLoader(t,d),c(new n4({type:ao.NETWORK_ERROR,details:lr.FRAG_LOAD_TIMEOUT,fatal:!1,frag:t,part:n,error:new Error(`Timeout after ${m.timeout}ms`),networkDetails:y,stats:f}))}})})}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 Vgt(s,t=null){const n=t||s,r={frag:s,part:t,responseType:"arraybuffer",url:n.url,headers:{},rangeStart:0,rangeEnd:0},a=n.byteRangeStartOffset,i=n.byteRangeEndOffset;if(bi(a)&&bi(i)){var l;let o=a,c=i;if(s.sn==="initSegment"&&DAn((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 Hgt(s,t){const n=new Error(`GAP ${s.gap?"tag":"attribute"} found`),r={type:ao.MEDIA_ERROR,details:lr.FRAG_GAP,fatal:!1,frag:s,error:n,networkDetails:null};return t&&(r.part=t),(t||s).stats.aborted=!0,new n4(r)}function DAn(s){return s==="AES-128"||s==="AES-256"}class n4 extends Error{constructor(t){super(t.error.message),this.data=void 0,this.data=t}}class uzt extends Ij{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 uKe{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=Fne(),this.buffering={audio:Fne(),video:Fne(),audiovideo:Fne()},this.level=t,this.sn=n,this.id=r,this.size=a,this.part=i,this.partial=l}}function Fne(){return{start:0,executeStart:0,executeEnd:0,end:0}}const Ggt={length:0,start:()=>0,end:()=>0};class _l{static isBuffered(t,n){if(t){const r=_l.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=_l.getBuffered(t);return _l.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 Kgt(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 RAn(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 OAn=/^(\d+)x(\d+)$/,Ygt=/(.+?)=(".*?"|.*?)(?:,|$)/g;class fp{constructor(t,n){typeof t=="string"&&(t=fp.parseAttrList(t,n)),rh(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=OAn.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(Ygt.lastIndex=0;(r=Ygt.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":Gu.warn(`${t}: attribute ${l} is missing quotes`)}a[l]=o}return a}}const FAn="com.apple.hls.interstitial";function zAn(s){return s!=="ID"&&s!=="CLASS"&&s!=="CUE"&&s!=="START-DATE"&&s!=="DURATION"&&s!=="END-DATE"&&s!=="END-ON-NEXT"}function BAn(s){return s==="SCTE35-OUT"||s==="SCTE35-IN"||s==="SCTE35-CMD"}class mzt{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]){Gu.warn(`DATERANGE tag attribute: "${l}" does not match for tags with ID: "${t.ID}"`),this._badValueForSameId=l;break}t=rh(new fp({}),i,t)}if(this.attr=t,n?(this._startDate=n._startDate,this._cue=n._cue,this._endDate=n._endDate,this._dateAtEnd=n._dateAtEnd):this._startDate=new Date(t["START-DATE"]),"END-DATE"in this.attr){const i=(n==null?void 0:n.endDate)||new Date(this.attr["END-DATE"]);bi(i.getTime())&&(this._endDate=i)}}get id(){return this.attr.ID}get class(){return this.attr.CLASS}get cue(){const t=this._cue;return t===void 0?this._cue=this.attr.enumeratedStringList(this.attr.CUE?"CUE":"X-CUE",{pre:!1,post:!1,once:!1}):t}get startTime(){const{tagAnchor:t}=this;return t===null||t.programDateTime===null?(Gu.warn(`Expected tagAnchor Fragment with PDT set for DateRange "${this.id}": ${t}`),NaN):t.start+(this.startDate.getTime()-t.programDateTime)/1e3}get startDate(){return this._startDate}get endDate(){const t=this._endDate||this._dateAtEnd;if(t)return t;const n=this.duration;return n!==null?this._dateAtEnd=new Date(this._startDate.getTime()+n*1e3):null}get duration(){if("DURATION"in this.attr){const t=this.attr.decimalFloatingPoint("DURATION");if(bi(t))return t}else if(this._endDate)return(this._endDate.getTime()-this._startDate.getTime())/1e3;return null}get plannedDuration(){return"PLANNED-DURATION"in this.attr?this.attr.decimalFloatingPoint("PLANNED-DURATION"):null}get endOnNext(){return this.attr.bool("END-ON-NEXT")}get isInterstitial(){return this.class===FAn}get isValid(){return!!this.id&&!this._badValueForSameId&&bi(this.startDate.getTime())&&(this.duration===null||this.duration>=0)&&(!this.endOnNext||!!this.class)&&(!this.attr.CUE||!this.cue.pre&&!this.cue.post||this.cue.pre!==this.cue.post)&&(!this.isInterstitial||"X-ASSET-URI"in this.attr||"X-ASSET-LIST"in this.attr)}}const $An=10;class UAn{constructor(t){this.PTSKnown=!1,this.alignedSliding=!1,this.averagetargetduration=void 0,this.endCC=0,this.endSN=0,this.fragments=void 0,this.fragmentHint=void 0,this.partList=null,this.dateRanges=void 0,this.dateRangeTagCount=0,this.live=!0,this.requestScheduled=-1,this.ageHeader=0,this.advancedDateTime=void 0,this.updated=!0,this.advanced=!0,this.misses=0,this.startCC=0,this.startSN=0,this.startTimeOffset=null,this.targetduration=0,this.totalduration=0,this.type=null,this.url=void 0,this.m3u8="",this.version=null,this.canBlockReload=!1,this.canSkipUntil=0,this.canSkipDateRanges=!1,this.skippedSegments=0,this.recentlyRemovedDateranges=void 0,this.partHoldBack=0,this.holdBack=0,this.partTarget=0,this.preloadHint=void 0,this.renditionReports=void 0,this.tuneInGoal=0,this.deltaUpdateFailed=void 0,this.driftStartTime=0,this.driftEndTime=0,this.driftStart=0,this.driftEnd=0,this.encryptedFragments=void 0,this.playlistParsingError=null,this.variableList=null,this.hasVariableRefs=!1,this.appliedTimelineOffset=void 0,this.fragments=[],this.encryptedFragments=[],this.dateRanges={},this.url=t}reloaded(t){if(!t){this.advanced=!0,this.updated=!0;return}const n=this.lastPartSn-t.lastPartSn,r=this.lastPartIndex-t.lastPartIndex;this.updated=this.endSN!==t.endSN||!!r||!!n||!this.live,this.advanced=this.endSN>t.endSN||n>0||n===0&&r>0,this.updated||this.advanced?this.misses=Math.floor(t.misses*.6):this.misses=t.misses+1}hasKey(t){return this.encryptedFragments.some(n=>{let r=n.decryptdata;return r||(n.setKeyFormat(t.keyFormat),r=n.decryptdata),!!r&&t.matches(r)})}get hasProgramDateTime(){return this.fragments.length?bi(this.fragments[this.fragments.length-1].programDateTime):!1}get levelTargetDuration(){return this.averagetargetduration||this.targetduration||$An}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 Z5e(s,t){return s.length===t.length?!s.some((n,r)=>n!==t[r]):!1}function Zgt(s,t){return!s&&!t?!0:!s||!t?!1:Z5e(s,t)}function uz(s){return s==="AES-128"||s==="AES-256"||s==="AES-256-CTR"}function hKe(s){switch(s){case"AES-128":case"AES-256":return jE.cbc;case"AES-256-CTR":return jE.ctr;default:throw new Error(`invalid full segment method ${s}`)}}function mKe(s){return Uint8Array.from(atob(s),t=>t.charCodeAt(0))}function Tze(s){return Uint8Array.from(unescape(encodeURIComponent(s)),t=>t.charCodeAt(0))}function qAn(s){const t=Tze(s).subarray(0,16),n=new Uint8Array(16);return n.set(t,16-t.length),n}function pzt(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 fzt(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=mKe(l)):n=qAn(l)}}return n}const X5e=typeof self<"u"?self:void 0;var Np={CLEARKEY:"org.w3.clearkey",FAIRPLAY:"com.apple.fps",PLAYREADY:"com.microsoft.playready",WIDEVINE:"com.widevine.alpha"},D0={CLEARKEY:"org.w3.clearkey",FAIRPLAY:"com.apple.streamingkeydelivery",PLAYREADY:"com.microsoft.playready",WIDEVINE:"urn:uuid:edef8ba9-79d6-4ace-a3c8-27dcd51d21ed"};function Vje(s){switch(s){case D0.FAIRPLAY:return Np.FAIRPLAY;case D0.PLAYREADY:return Np.PLAYREADY;case D0.WIDEVINE:return Np.WIDEVINE;case D0.CLEARKEY:return Np.CLEARKEY}}function cIe(s){switch(s){case Np.FAIRPLAY:return D0.FAIRPLAY;case Np.PLAYREADY:return D0.PLAYREADY;case Np.WIDEVINE:return D0.WIDEVINE;case Np.CLEARKEY:return D0.CLEARKEY}}function NG(s){const{drmSystems:t,widevineLicenseUrl:n}=s,r=t?[Np.FAIRPLAY,Np.WIDEVINE,Np.PLAYREADY,Np.CLEARKEY].filter(a=>!!t[a]):[];return!r[Np.WIDEVINE]&&n&&r.push(Np.WIDEVINE),r}const gzt=function(s){return X5e!=null&&(s=X5e.navigator)!=null&&s.requestMediaKeySystemAccess?self.navigator.requestMediaKeySystemAccess.bind(self.navigator):null}();function VAn(s,t,n,r){let a;switch(s){case Np.FAIRPLAY:a=["cenc","sinf"];break;case Np.WIDEVINE:case Np.PLAYREADY:a=["cenc"];break;case Np.CLEARKEY:a=["cenc","keyids"];break;default:throw new Error(`Unknown key-system: ${s}`)}return HAn(a,t,n,r)}function HAn(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 GAn(s){var t;return!!s&&(s.sessionType==="persistent-license"||!!((t=s.sessionTypes)!=null&&t.some(n=>n==="persistent-license")))}function xzt(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=mKe(o).subarray(0,16);return pzt(c),c}}return null}let BF={};class tE{static clearKeyUriToKeyIdMap(){BF={}}static setKeyIdForUri(t,n){BF[t]=n}static addKeyIdForUri(t){const n=Object.keys(BF).length%Number.MAX_SAFE_INTEGER,r=new Uint8Array(16);return new DataView(r.buffer,12,4).setUint32(0,n),BF[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&&!uz(t),l!=null&&l.startsWith("0x")&&(this.keyId=new Uint8Array(H9t(l)))}matches(t){return t.uri===this.uri&&t.method===this.method&&t.encrypted===this.encrypted&&t.keyFormat===this.keyFormat&&Z5e(t.keyFormatVersions,this.keyFormatVersions)&&Zgt(t.iv,this.iv)&&Zgt(t.keyId,this.keyId)}isSupported(){if(this.method){if(uz(this.method)||this.method==="NONE")return!0;if(this.keyFormat==="identity")return this.method==="SAMPLE-AES";switch(this.keyFormat){case D0.FAIRPLAY:case D0.WIDEVINE:case D0.PLAYREADY:case D0.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(uz(this.method)){let i=this.iv;return i||(typeof t!="number"&&(Gu.warn(`missing IV for initialization segment with method="${this.method}" - compliance issue`),t=0),i=KAn(t)),new tE(this.method,this.uri,"identity",this.keyFormatVersions,i)}if(this.keyId){const i=BF[this.uri];if(i&&!Z5e(this.keyId,i)&&tE.setKeyIdForUri(this.uri,this.keyId),this.pssh)return this}const r=fzt(this.uri);if(r)switch(this.keyFormat){case D0.WIDEVINE:if(this.pssh=r,!this.keyId){const i=XCn(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=Xgt(n));break;case D0.PLAYREADY:{const i=new Uint8Array([154,4,240,121,152,64,66,134,171,146,230,91,224,136,95,149]);this.pssh=ZCn(i,null,r),this.keyId=xzt(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=WAn(n),i||(i=Xgt(n),i||(i=BF[this.uri])),i&&(this.keyId=i,tE.setKeyIdForUri(this.uri,i))}return this}}function WAn(s){const t=s==null?void 0:s[D0.WIDEVINE];return t?t.keyId:null}function Xgt(s){const t=s==null?void 0:s[D0.PLAYREADY];if(t){const n=fzt(t.uri);if(n)return xzt(n)}return null}function KAn(s){const t=new Uint8Array(16);for(let n=12;n<16;n++)t[n]=s>>8*(15-n)&255;return t}const Qgt=/#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,Jgt=/#EXT-X-MEDIA:(.*)/g,YAn=/^#EXT(?:INF|-X-TARGETDURATION):/m,dIe=new RegExp([/#EXTINF:\s*(\d*(?:\.\d+)?)(?:,(.*)\s+)?/.source,/(?!#) *(\S[^\r\n]*)/.source,/#.*/.source].join("|"),"g"),ZAn=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 i5{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(Jgt.lastIndex=0;(a=Jgt.exec(t))!==null;){const d=new fp(a[1],r),u=d.TYPE;if(u){const h=o[u],m=i[u]||[];i[u]=m;const f=d.LANGUAGE,g=d["ASSOC-LANGUAGE"],y=d.CHANNELS,x=d.CHARACTERISTICS,_=d["INSTREAM-ID"],b={attrs:d,bitrate:0,id:c++,groupId:d["GROUP-ID"]||"",name:d.NAME||f||"",type:u,default:d.bool("DEFAULT"),autoselect:d.bool("AUTOSELECT"),forced:d.bool("FORCED"),lang:f,url:d.URI?i5.resolve(d.URI,n):""};if(g&&(b.assocLang=g),y&&(b.channels=y),x&&(b.characteristics=x),_&&(b.instreamId=_),h!=null&&h.length){const k=i5.findGroup(h,b.groupId)||h[0];nxt(b,k,"audioCodec"),nxt(b,k,"textCodec")}m.push(b)}}return i}static parseLevelPlaylist(t,n,r,a,i,l){var o;const c={url:n},d=new UAn(n),u=d.fragments,h=[];let m=null,f=0,g=0,y=0,x=0,_=0,b=null,k=new iIe(a,c),A,T,P,I=-1,M=!1,L=null,z;if(dIe.lastIndex=0,d.m3u8=t,d.hasVariableRefs=Wgt(t),((o=dIe.exec(t))==null?void 0:o[0])!=="#EXTM3U")return d.playlistParsingError=new Error("Missing format identifier #EXTM3U"),d;for(;(A=dIe.exec(t))!==null;){M&&(M=!1,k=new iIe(a,c),k.playlistOffset=y,k.setStart(y),k.sn=f,k.cc=x,_&&(k.bitrate=_),k.level=r,m&&(k.initSegment=m,m.rawProgramDateTime&&(k.rawProgramDateTime=m.rawProgramDateTime,m.rawProgramDateTime=null),L&&(k.setByteRange(L),L=null)));const G=A[1];if(G){k.duration=parseFloat(G);const X=(" "+A[2]).slice(1);k.title=X||null,k.tagList.push(X?["INF",G,X]:["INF",G])}else if(A[3]){if(bi(k.duration)){k.playlistOffset=y,k.setStart(y),P&&axt(k,P,d),k.sn=f,k.level=r,k.cc=x,u.push(k);const X=(" "+A[3]).slice(1);k.relurl=Aze(d,X),Eze(k,b,h),b=k,y+=k.duration,f++,g=0,M=!0}}else{if(A=A[0].match(ZAn),!A){Gu.warn("No matches on slow regex match for level playlist!");continue}for(T=1;T0&&ixt(d,X,A),f=d.startSN=parseInt(te);break;case"SKIP":{d.skippedSegments&&VS(d,X,A);const me=new fp(te,d),ue=me.decimalInteger("SKIPPED-SEGMENTS");if(bi(ue)){d.skippedSegments+=ue;for(let ae=ue;ae--;)u.push(null);f+=ue}const ce=me.enumeratedString("RECENTLY-REMOVED-DATERANGES");ce&&(d.recentlyRemovedDateranges=(d.recentlyRemovedDateranges||[]).concat(ce.split(" ")));break}case"TARGETDURATION":d.targetduration!==0&&VS(d,X,A),d.targetduration=Math.max(parseInt(te),1);break;case"VERSION":d.version!==null&&VS(d,X,A),d.version=parseInt(te);break;case"INDEPENDENT-SEGMENTS":break;case"ENDLIST":d.live||VS(d,X,A),d.live=!1;break;case"#":(te||ne)&&k.tagList.push(ne?[te,ne]:[te]);break;case"DISCONTINUITY":x++,k.tagList.push(["DIS"]);break;case"GAP":k.gap=!0,k.tagList.push([X]);break;case"BITRATE":k.tagList.push([X,te]),_=parseInt(te)*1e3,bi(_)?k.bitrate=_:_=0;break;case"DATERANGE":{const me=new fp(te,d),ue=new mzt(me,d.dateRanges[me.ID],d.dateRangeTagCount);d.dateRangeTagCount++,ue.isValid||d.skippedSegments?d.dateRanges[ue.id]=ue:Gu.warn(`Ignoring invalid DATERANGE tag: "${te}"`),k.tagList.push(["EXT-X-DATERANGE",te]);break}case"DEFINE":{{const me=new fp(te,d);"IMPORT"in me?RAn(d,me,l):Kgt(d,me,n)}break}case"DISCONTINUITY-SEQUENCE":d.startCC!==0?VS(d,X,A):u.length>0&&ixt(d,X,A),d.startCC=x=parseInt(te);break;case"KEY":{const me=ext(te,n,d);if(me.isSupported()){if(me.method==="NONE"){P=void 0;break}P||(P={});const ue=P[me.keyFormat];ue!=null&&ue.matches(me)||(ue&&(P=rh({},P)),P[me.keyFormat]=me)}else Gu.warn(`[Keys] Ignoring unsupported EXT-X-KEY tag: "${te}"`);break}case"START":d.startTimeOffset=txt(te);break;case"MAP":{const me=new fp(te,d);if(k.duration){const ue=new iIe(a,c);rxt(ue,me,r,P),m=ue,k.initSegment=m,m.rawProgramDateTime&&!k.rawProgramDateTime&&(k.rawProgramDateTime=m.rawProgramDateTime)}else{const ue=k.byteRangeEndOffset;if(ue){const ce=k.byteRangeStartOffset;L=`${ue-ce}@${ce}`}else L=null;rxt(k,me,r,P),m=k,M=!0}m.cc=x;break}case"SERVER-CONTROL":{z&&VS(d,X,A),z=new fp(te),d.canBlockReload=z.bool("CAN-BLOCK-RELOAD"),d.canSkipUntil=z.optionalFloat("CAN-SKIP-UNTIL",0),d.canSkipDateRanges=d.canSkipUntil>0&&z.bool("CAN-SKIP-DATERANGES"),d.partHoldBack=z.optionalFloat("PART-HOLD-BACK",0),d.holdBack=z.optionalFloat("HOLD-BACK",0);break}case"PART-INF":{d.partTarget&&VS(d,X,A);const me=new fp(te);d.partTarget=me.decimalFloatingPoint("PART-TARGET");break}case"PART":{let me=d.partList;me||(me=d.partList=[]);const ue=g>0?me[me.length-1]:void 0,ce=g++,ae=new fp(te,d),he=new RCn(ae,k,c,ce,ue);me.push(he),k.duration+=he.duration;break}case"PRELOAD-HINT":{const me=new fp(te,d);d.preloadHint=me;break}case"RENDITION-REPORT":{const me=new fp(te,d);d.renditionReports=d.renditionReports||[],d.renditionReports.push(me);break}default:Gu.warn(`line parsed but not handled: ${A}`);break}}}b&&!b.relurl?(u.pop(),y-=b.duration,d.partList&&(d.fragmentHint=b)):d.partList&&(Eze(k,b,h),k.cc=x,d.fragmentHint=k,P&&axt(k,P,d)),d.targetduration||(d.playlistParsingError=new Error("Missing Target Duration"));const $=u.length,V=u[0],W=u[$-1];if(y+=d.skippedSegments*d.targetduration,y>0&&$&&W){d.averagetargetduration=y/$;const G=W.sn;d.endSN=G!=="initSegment"?G:0,d.live||(W.endList=!0),I>0&&(QAn(u,I),V&&h.unshift(V))}return d.fragmentHint&&(y+=d.fragmentHint.duration),d.totalduration=y,h.length&&d.dateRangeTagCount&&V&&yzt(h,d),d.endCC=x,d}}function yzt(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 f=m;f>d;f--){const g=u[f].programDateTime;if(t>=g&&tr);["video","audio","text"].forEach(r=>{const a=n.filter(i=>oKe(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 nxt(s,t,n){const r=t[n];r&&(s[n]=r)}function QAn(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 Eze(s,t,n){s.rawProgramDateTime?n.push(s):t!=null&&t.programDateTime&&(s.programDateTime=t.endProgramDateTime)}function rxt(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 axt(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 VS(s,t,n){s.playlistParsingError=new Error(`#EXT-X-${t} must not appear more than once (${n[0]})`)}function ixt(s,t,n){s.playlistParsingError=new Error(`#EXT-X-${t} must appear before the first Media Segment (${n[0]})`)}function uIe(s,t){const n=t.startPTS;if(bi(n)){let r=0,a;t.sn>s.sn?(r=n-s.start,a=s):(r=s.start-n,a=t),a.duration!==r&&a.setDuration(r)}else t.sn>s.sn?s.cc===t.cc&&s.minEndPTS?t.setStart(s.start+(s.minEndPTS-s.start)):t.setStart(s.start+s.duration):t.setStart(Math.max(s.start-t.duration,0))}function vzt(s,t,n,r,a,i,l){r-n<=0&&(l.warn("Fragment should have a positive duration",t),r=n+t.duration,i=a+t.duration);let c=n,d=r;const u=t.startPTS,h=t.endPTS;if(bi(u)){const _=Math.abs(u-n);s&&_>s.totalduration?l.warn(`media timestamps and playlist times differ by ${_}s for level ${t.level} ${s.url}`):bi(t.deltaPTS)?t.deltaPTS=Math.max(_,t.deltaPTS):t.deltaPTS=_,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 f=t.sn;if(!s||fs.endSN)return 0;let g;const y=f-s.startSN,x=s.fragments;for(x[y]=t,g=y;g>0;g--)uIe(x[g],x[g-1]);for(g=y;g=0;u--){const h=a[u].initSegment;if(h){r=h;break}}s.fragmentHint&&delete s.fragmentHint.endPTS;let i;sTn(s,t,(u,h,m,f)=>{if((!t.startCC||t.skippedSegments)&&h.cc!==u.cc){const g=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=eTn(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?vzt(t,i,i.startPTS,i.endPTS,i.startDTS,i.endDTS,n):bzt(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 eTn(s,t,n){const{dateRanges:r,recentlyRemovedDateranges:a}=t,i=rh({},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 mzt(r[c].attr,d);u.isValid?(i[c]=u,d||(u.tagOrder+=o)):n.warn(`Ignoring invalid Playlist Delta Update DATERANGE tag: "${bh(r[c].attr)}"`)}),i):r}function tTn(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 sTn(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,f=h.relurl;if(m&&nTn(m,f)){t.playlistParsingError=oxt(`media sequence mismatch ${h.sn}:`,s,t,u,h);return}else if(u.cc!==h.cc){t.playlistParsingError=oxt(`discontinuity sequence mismatch (${u.cc}!=${h.cc})`,s,t,u,h);return}}}}function oxt(s,t,n,r,a){return new Error(`${s} ${a.url} Playlist starting @${t.startSN} ${t.m3u8} Playlist starting @${n.startSN} ${n.m3u8}`)}function bzt(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 nTn(s,t){return s!==t&&t?cxt(s)!==cxt(t):!1}function cxt(s){return s.replace(/\?[^?]*$/,"")}function MK(s,t){for(let r=0,a=s.length;rs.startCC)}function dxt(s,t){const n=s.start+t;s.startPTS=n,s.setStart(n),s.endPTS=n+s.duration}function kzt(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=_l.bufferInfo(d||c,h,l.maxBufferHole),f=!m.len;if(this.log(`Media seeking to ${bi(h)?h.toFixed(3):h}, state: ${u}, ${f?"out of":"in"} buffer`),this.state===Ur.ENDED)this.resetLoadingState();else if(o){const g=l.maxFragLookUpTolerance,y=o.start-g,x=o.start+o.duration+g;if(f||xm.end){const _=h>x;(hg&&(this.lastCurrentTime=h),!this.loadingParts){const y=Math.max(m.end,h),x=this.shouldLoadParts(this.getLevelDetails(),y);x&&(this.log(`LL-Part loading ON after seeking to ${h.toFixed(2)} with buffer @${y.toFixed(2)}`),this.loadingParts=x)}}this.hls.hasEnoughToStart||(this.log(`Setting ${f?"startPosition":"nextLoadPosition"} to ${h} for seek without enough to start`),this.nextLoadPosition=h,f&&(this.startPosition=h)),f&&this.state===Ur.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 IAn(t.config),this.keyLoader=r,this.fragmentTracker=n,this.config=t.config,this.decrypter=new dKe(t.config)}registerListeners(){const{hls:t}=this;t.on(Et.MEDIA_ATTACHED,this.onMediaAttached,this),t.on(Et.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(Et.MANIFEST_LOADING,this.onManifestLoading,this),t.on(Et.MANIFEST_LOADED,this.onManifestLoaded,this),t.on(Et.ERROR,this.onError,this)}unregisterListeners(){const{hls:t}=this;t.off(Et.MEDIA_ATTACHED,this.onMediaAttached,this),t.off(Et.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(Et.MANIFEST_LOADING,this.onManifestLoading,this),t.off(Et.MANIFEST_LOADED,this.onManifestLoaded,this),t.off(Et.ERROR,this.onError,this)}doTick(){this.onTickEnd()}onTickEnd(){}startLoad(t){}stopLoad(){if(this.state===Ur.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=Ur.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=_l.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===Ur.FRAG_LOADING||!this.fragCurrent&&l===Ur.PARSING)&&(this.fragmentTracker.removeFragment(o),this.state=Ur.IDLE);return}"payload"in i&&(this.log(`Loaded ${o.type} sn: ${o.sn} of ${this.playlistLabel()} ${o.level}`),this.hls.trigger(Et.FRAG_LOADED,i)),this._handleFragmentLoadComplete(i)}).catch(i=>{this.state===Ur.STOPPED||this.state===Ur.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)===Yg.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)===Yg.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(Et.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&&uz(o.method)){const c=self.performance.now();return this.decrypter.decrypt(new Uint8Array(l),o.key.buffer,o.iv.buffer,hKe(o.method)).catch(d=>{throw a.trigger(Et.ERROR,{type:ao.MEDIA_ERROR,details:lr.FRAG_DECRYPT_ERROR,fatal:!1,error:d,reason:d.message,frag:i}),d}).then(d=>{const u=self.performance.now();return a.trigger(Et.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===Ur.STOPPED||this.state===Ur.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!==Ur.STOPPED&&(this.state=Ur.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(Et.ERROR,{type:ao.KEY_SYSTEM_ERROR,details:lr.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?iTn.toString(_l.getBuffered(r)):"(detached)"})`),$f(t)){var a;if(t.type!==Ri.SUBTITLE){const l=t.elementaryStreams;if(!Object.keys(l).some(o=>!!l[o])){this.state=Ur.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=Ur.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 uKe(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=Ur.KEY_LOADING,this.fragCurrent=t,o=this.keyLoader.load(t).then(m=>{if(!this.fragContextChanged(m.frag))return this.hls.trigger(Et.KEY_LOADED,m),this.state===Ur.KEY_LOADING&&(this.state=Ur.IDLE),m}),this.hls.trigger(Et.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($f(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&&$f(t)){const m=l.partList;if(m&&a){r>l.fragmentEnd&&l.fragmentHint&&(t=l.fragmentHint);const f=this.getNextPart(m,t,r);if(f>-1){const g=m[f];t=this.fragCurrent=g.fragment,this.log(`Loading ${t.type} sn: ${t.sn} part: ${g.index} (${f}/${m.length-1}) of ${this.fragInfo(t,!1,g)}) cc: ${t.cc} [${l.startSN}-${l.endSN}], target: ${parseFloat(r.toFixed(3))}`),this.nextLoadPosition=g.start+g.duration,this.state=Ur.FRAG_LOADING;let y;return o?y=o.then(x=>!x||this.fragContextChanged(x.frag)?null:this.doFragPartsLoad(t,g,n,a)).catch(x=>this.handleFragLoadError(x)):y=this.doFragPartsLoad(t,g,n,a).catch(x=>this.handleFragLoadError(x)),this.hls.trigger(Et.FRAG_LOADING,{frag:t,part:g,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($f(t)&&this.loadingParts){var d;this.log(`LL-Part loading OFF after next part miss @${r.toFixed(2)} Check buffer at sn: ${t.sn} loaded parts: ${(d=l.partList)==null?void 0:d.filter(m=>m.loaded).map(m=>`[${m.start}-${m.end}]`)}`),this.loadingParts=!1}else if(!t.url)return Promise.resolve(null);this.log(`Loading ${t.type} sn: ${t.sn} of ${this.fragInfo(t,!1)}) cc: ${t.cc} ${"["+l.startSN+"-"+l.endSN+"]"}, target: ${parseFloat(r.toFixed(3))}`),bi(t.sn)&&!this.bitrateTest&&(this.nextLoadPosition=t.start+t.duration),this.state=Ur.FRAG_LOADING;const u=this.config.progressive&&t.type!==Ri.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(Et.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 f=m.part;this.hls.trigger(Et.FRAG_LOADED,m);const g=lxt(r.details,t.sn,h.index+1)||jzt(d,t.sn,h.index+1);if(g)u(g);else return i({frag:t,part:f,partsLoaded:c})}).catch(l)};u(n)})}handleFragLoadError(t){if("data"in t){const n=t.data;n.frag&&n.details===lr.INTERNAL_ABORTED?this.handleFragLoadAborted(n.frag,n.part):n.frag&&n.type===ao.KEY_SYSTEM_ERROR?(n.frag.abortRequests(),this.resetStartWhenNotLoaded(),this.resetFragmentLoading(n.frag)):this.hls.trigger(Et.ERROR,n)}else this.hls.trigger(Et.ERROR,{type:ao.OTHER_ERROR,details:lr.INTERNAL_EXCEPTION,err:t,error:t,fatal:!0});return null}_handleTransmuxerFlush(t){const n=this.getCurrentContext(t);if(!n||this.state!==Ur.PARSING){!this.fragCurrent&&this.state!==Ur.STOPPED&&this.state!==Ur.ERROR&&(this.state=Ur.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===Ri.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?lxt(c,i,l):null,u=d?d.fragment:wzt(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!==Ur.PARSING)return;const{data1:l,data2:o}=t;let c=l;if(o&&(c=Sj(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(Et.BUFFER_APPENDING,h),t.dropped&&t.independent&&!r){if(i)return;this.flushBufferGap(n)}}flushBufferGap(t){const n=this.media;if(!n)return;if(!_l.isBuffered(n,n.currentTime)){this.flushMainBuffer(0,t.start);return}const r=n.currentTime,a=_l.bufferInfo(n,r,0),i=t.duration,l=Math.min(this.config.maxFragLookUpTolerance*2,i*.25),o=Math.max(Math.min(t.start-l,a.end-l),r+l);t.start-o>l&&this.flushMainBuffer(o,t.start)}getFwdBufferInfo(t,n){var r;const a=this.getLoadPosition();if(!bi(a))return null;const l=this.lastCurrentTime>a||(r=this.media)!=null&&r.paused?0:this.config.maxBufferHole;return this.getFwdBufferInfoAtPos(t,a,n,l)}getFwdBufferInfoAtPos(t,n,r,a){const i=_l.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 _l.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=Ri.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?(x=f,_=f===m?"config":"next load start"):g!==null?(x=g,_="live edge"):(x=t,_="buffer pos"),x=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(uxt(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(uxt(this.config)&&t.type!==Ri.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=wAn(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=lzt(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||(f=this.media)!=null&&f.paused||!this.startFragRequested?0:d;m=MR(i,l,t,y)}else m=l[l.length-1];if(m){const g=m.sn-r.startSN,y=this.fragmentTracker.getState(m);if((y===Yg.OK||y===Yg.PARTIAL&&m.gap)&&(i=m),i&&m.sn===i.sn&&(!h||u[0].fragment.sn>m.sn||!r.live)&&m.level===i.level){const _=l[g+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&&$f(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!==Ur.FRAG_LOADING_WAITING_RETRY)&&(this.state=Ur.IDLE)}onFragmentOrKeyLoadError(t,n){var r;if(n.chunkMeta&&!n.frag){const _=this.getCurrentContext(n.chunkMeta);_&&(n.frag=_.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===lr.FRAG_GAP;l&&this.fragmentTracker.fragBuffered(a,!0);const o=n.errorAction;if(!o){this.state=Ur.ERROR;return}const{action:c,flags:d,retryCount:u=0,retryConfig:h}=o,m=!!h,f=m&&c===M0.RetryRequest,g=m&&!o.resolved&&d===e_.MoveAllAlternatesMatchingHost,y=(r=this.hls.latestLevelDetails)==null?void 0:r.live;if(!f&&g&&$f(a)&&!a.endList&&y&&!dzt(n))this.resetFragmentErrors(t),this.treatAsGap(a),o.resolved=!0;else if((f||g)&&u=n||r&&!Cze(0))&&(r&&this.log("Connection restored (online)"),this.resetStartWhenNotLoaded(),this.state=Ur.IDLE)}reduceLengthAndFlushBuffer(t){if(this.state===Ur.PARSING||this.state===Ur.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===Ri.AUDIO&&(this.fragCurrent=null),this.hls.hasEnoughToStart||(this.startFragRequested=!1),this.state!==Ur.STOPPED&&(this.state=Ur.IDLE)}afterBufferFlushed(t,n,r){if(!t)return;const a=_l.getBuffered(t);this.fragmentTracker.detectEvictedFragments(n,a,r),this.state===Ur.ENDED&&this.resetLoadingState()}resetLoadingState(){this.log("Reset loading state"),this.fragCurrent=null,this.fragPrevious=null,this.state!==Ur.STOPPED&&(this.state=Ur.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:vzt(i,t,u.startPTS,u.endPTS,u.startDTS,u.endDTS,this);return this.hls.trigger(Et.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(Et.ERROR,{type:ao.MEDIA_ERROR,details:lr.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=Ur.PARSED,this.log(`Parsed ${t.type} sn: ${t.sn}${n?" part: "+n.index:""} of ${this.fragInfo(t,!1,n)})`),this.hls.trigger(Et.FRAG_PARSED,{frag:t,part:n})}playlistLabel(){return this.playlistType===Ri.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 uxt(s){return!!s.interstitialsController&&s.enableInterstitialPlayback!==!1}class Czt{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=oTn(t,n);else return new Uint8Array(0);return this.reset(),r}reset(){this.chunks.length=0,this.dataLength=0}}function oTn(s,t){const n=new Uint8Array(t);let r=0;for(let a=0;a0)return s.subarray(n,n+r)}function pTn(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 f=new Error(`invalid ADTS sampling index:${l}`);s.emit(Et.ERROR,Et.ERROR,{type:ao.MEDIA_ERROR,details:lr.FRAG_PARSING_ERROR,fatal:!0,error:f,reason:f.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 Gu.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 Tzt(s,t){return s[t]===255&&(s[t+1]&246)===240}function Ezt(s,t){return s[t+1]&1?7:9}function xKe(s,t){return(s[t+3]&3)<<11|s[t+4]<<3|(s[t+5]&224)>>>5}function fTn(s,t){return t+5=s.length)return!1;const r=xKe(s,t);if(r<=n)return!1;const a=t+r;return a===s.length||J5e(s,a)}return!1}function Mzt(s,t,n,r,a){if(!s.samplerate){const i=pTn(t,n,r,a);if(!i)return;rh(s,i)}}function Lzt(s){return 1024*9e4/s}function yTn(s,t){const n=Ezt(s,t);if(t+n<=s.length){const r=xKe(s,t)-n;if(r>0)return{headerLength:n,frameLength:r}}}function Pzt(s,t,n,r,a){const i=Lzt(s.samplerate),l=r+a*i,o=yTn(t,n);let c;if(o){const{frameLength:h,headerLength:m}=o,f=m+h,g=Math.max(0,n+f-t.length);g?(c=new Uint8Array(f-m),c.set(t.subarray(n+m,t.length),0)):c=t.subarray(n+m,n+f);const y={unit:c,pts:l};return g||s.samples.push(y),{sample:y,length:f,missing:g}}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 vTn(s,t){return gKe(s,t)&&MAe(s,t+6)+10<=s.length-t}function bTn(s){return s instanceof ArrayBuffer?s:s.byteOffset==0&&s.byteLength==s.buffer.byteLength?s.buffer:new Uint8Array(s).buffer}function mIe(s,t=0,n=1/0){return _Tn(s,t,n,Uint8Array)}function _Tn(s,t,n,r){const a=wTn(s);let i=1;"BYTES_PER_ELEMENT"in r&&(i=r.BYTES_PER_ELEMENT);const l=jTn(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 wTn(s){return s instanceof ArrayBuffer?s:s.buffer}function jTn(s){return s&&s.buffer instanceof ArrayBuffer&&s.byteLength!==void 0&&s.byteOffset!==void 0}function NTn(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=z_(mIe(s.data,1,r)),i=s.data[2+r],l=s.data.subarray(3+r).indexOf(0);if(l===-1)return;const o=z_(mIe(s.data,3+r,l));let c;return a==="-->"?c=z_(mIe(s.data,4+r+l)):c=bTn(s.data.subarray(4+r+l)),t.mimeType=a,t.pictureType=i,t.description=o,t.data=c,t}function kTn(s){if(s.size<2)return;const t=z_(s.data,!0),n=new Uint8Array(s.data.subarray(t.length+1));return{key:s.type,info:t,data:n.buffer}}function STn(s){if(s.size<2)return;if(s.type==="TXXX"){let n=1;const r=z_(s.data.subarray(n),!0);n+=r.length+1;const a=z_(s.data.subarray(n));return{key:s.type,info:r,data:a}}const t=z_(s.data.subarray(1));return{key:s.type,info:"",data:t}}function CTn(s){if(s.type==="WXXX"){if(s.size<2)return;let n=1;const r=z_(s.data.subarray(n),!0);n+=r.length+1;const a=z_(s.data.subarray(n));return{key:s.type,info:r,data:a}}const t=z_(s.data);return{key:s.type,info:"",data:t}}function ATn(s){return s.type==="PRIV"?kTn(s):s.type[0]==="W"?CTn(s):s.type==="APIC"?NTn(s):STn(s)}function TTn(s){const t=String.fromCharCode(s[0],s[1],s[2],s[3]),n=MAe(s,4),r=10;return{type:t,size:n,data:s.subarray(r,r+n)}}const zne=10,ETn=10;function Izt(s){let t=0;const n=[];for(;gKe(s,t);){const r=MAe(s,t+6);s[t+5]>>6&1&&(t+=zne),t+=zne;const a=t+r;for(;t+ETn0&&o.samples.push({pts:this.lastPTS,dts:this.lastPTS,data:r,type:y_.audioId3,duration:Number.POSITIVE_INFINITY});a{if(bi(s))return s*90;const r=n?n.baseTime*9e4/n.timescale:0;return t*9e4+r};let Bne=null;const PTn=[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],ITn=[44100,48e3,32e3,22050,24e3,16e3,11025,12e3,8e3],DTn=[[0,72,144,12],[0,0,0,0],[0,72,144,12],[0,144,144,12]],RTn=[0,1,1,4];function Rzt(s,t,n,r,a){if(n+24>t.length)return;const i=Ozt(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 Ozt(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=PTn[c*14+a-1]*1e3,h=ITn[(n===3?0:n===2?1:2)*3+i],m=o===3?1:2,f=DTn[n][r],g=RTn[r],y=f*8*g,x=Math.floor(f*d/h+l)*g;if(Bne===null){const k=(navigator.userAgent||"").match(/Chrome\/(\d+)/i);Bne=k?parseInt(k[1]):0}return!!Bne&&Bne<=87&&r===2&&d>=224e3&&o===0&&(s[t+3]=s[t+3]|128),{sampleRate:h,channelCount:m,frameLength:x,samplesPerFrame:y}}}function bKe(s,t){return s[t]===255&&(s[t+1]&224)===224&&(s[t+1]&6)!==0}function Fzt(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 f=(t[n+6]<<8|t[n+7])>>12-m&1,y=[2,1,2,3,3,4,4,5][h]+f,x=t[n+5]>>3,_=t[n+5]&7,b=new Uint8Array([i<<6|x<<1|_>>2,(_&3)<<6|h<<3|f<<2|c>>4,c<<4&224]),k=1536/o*9e4,A=r+a*k,T=t.subarray(n,n+u);return s.config=b,s.channelCount=y,s.samplerate=o,s.samples.push({unit:T,pts:A}),u}class BTn extends vKe{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=zZ(t,0);let r=(n==null?void 0:n.length)||0;if(n&&t[r]===11&&t[r+1]===119&&yKe(n)!==void 0&&Bzt(t,r)<=16)return!1;for(let a=t.length;r{const l=KCn(i);if($Tn.test(l.schemeIdUri)){const o=mxt(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:y_.emsg,duration:c})}else if(this.config.enableEmsgKLVMetadata&&l.schemeIdUri.startsWith("urn:misb:KLV:bin:1910.1")){const o=mxt(l,n);r.samples.push({data:l.payload,len:l.payload.byteLength,dts:o,pts:o,type:y_.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 mxt(s,t){return bi(s.presentationTime)?s.presentationTime/s.timeScale:t+s.presentationTimeDelta/s.timeScale}class qTn{constructor(t,n,r){this.keyData=void 0,this.decrypter=void 0,this.keyData=r,this.decrypter=new dKe(n,{removePKCS7Padding:!1})}decryptBuffer(t){return this.decrypter.decrypt(t,this.keyData.key.buffer,this.keyData.iv.buffer,jE.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 Uzt{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,f=0;for(i===-1&&(m=0,f=this.getNALuType(n,0),i=0,c=1);c=0){const g={data:n.subarray(m,u),type:f};o.push(g)}else{const g=this.getLastNalUnit(t.samples);g&&(l&&c<=4-l&&g.state&&(g.data=g.data.subarray(0,g.data.byteLength-l)),u>0&&(g.data=Sj(g.data,n.subarray(0,u)),g.state=0))}c=0&&i>=0){const g={data:n.subarray(m,a),type:f,state:i};o.push(g)}if(o.length===0){const g=this.getLastNalUnit(t.samples);g&&(g.data=Sj(g.data,n))}return t.naluState=i,o}}class LK{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&&Gu.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 VTn extends Uzt{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 x=d.data;if(c&&x.length>4){const _=this.readSliceType(x);(_===2||_===4||_===7||_===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,iKe(d.data,1,r.pts,n.samples);break}case 7:{var f,g;o=!0,c=!0;const y=d.data,x=this.readSPS(y);if(!t.sps||t.width!==x.width||t.height!==x.height||((f=t.pixelRatio)==null?void 0:f[0])!==x.pixelRatio[0]||((g=t.pixelRatio)==null?void 0:g[1])!==x.pixelRatio[1]){t.width=x.width,t.height=x.height,t.pixelRatio=x.pixelRatio,t.sps=[y];const _=y.subarray(1,4);let b="avc1.";for(let k=0;k<3;k++){let A=_[k].toString(16);A.length<2&&(A="0"+A),b+=A}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 LK(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,iKe(d.data,2,r.pts,n.samples);break;case 32:o=!0,t.vps||(typeof t.params!="object"&&(t.params={}),t.params=rh(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 f=this.readSPS(d.data);t.width=f.width,t.height=f.height,t.pixelRatio=f.pixelRatio,t.codec=f.codecString,t.sps=[],typeof t.params!="object"&&(t.params={});for(const g in f.params)t.params[g]=f.params[g]}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 f=this.readPPS(d.data);for(const g in f)t.params[g]=f[g]}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 LK(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 LK(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(),f=n.readUByte(),g=n.readUByte(),y=n.readUByte(),x=n.readUByte(),_=n.readUByte(),b=[],k=[];for(let Ae=0;Ae0)for(let Ae=r;Ae<8;Ae++)n.readBits(2);for(let Ae=0;Ae1&&n.readEG();for(let Ke=0;Ke0&&st<16?(he=rt[st-1],xe=Ze[st-1]):st===255&&(he=n.readBits(16),xe=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(),Se=n.readBoolean(),Se&&(n.skipUEG(),n.skipUEG(),n.skipUEG(),n.skipUEG()),n.readBoolean()&&(ge=n.readBits(32),be=n.readBits(32),n.readBoolean()&&n.readUEG(),n.readBoolean())){const Ze=n.readBoolean(),ht=n.readBoolean();let Bt=!1;(Ze||ht)&&(Bt=n.readBoolean(),Bt&&(n.readUByte(),n.readBits(5),n.readBoolean(),n.readBits(5)),n.readBits(4),n.readBits(4),Bt&&n.readBits(4),n.readBits(5),n.readBits(5),n.readBits(5));for(let Ct=0;Ct<=r;Ct++){ve=n.readBoolean();const Yt=ve||n.readBoolean();let Kt=!1;Yt?n.readEG():Kt=n.readBoolean();const Xs=Kt?1:n.readUEG()+1;if(Ze)for(let zs=0;zs>Ae&1)<<31-Ae)>>>0;let Ce=Ge.toString(16);return l===1&&Ce==="2"&&(Ce="6"),{codecString:`hvc1.${Be}${l}.${Ce}.${i?"H":"L"}${_}.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,f,g,y,x],general_level_idc:_,bit_depth:V+8,bit_depth_luma_minus8:V,bit_depth_chroma_minus8:W,min_spatial_segmentation_idc:ae,chroma_format_idc:A,frame_rate:{fixed:ve,fps:be/ge}},width:Me,height:Re,pixelRatio:[he,xe]}}readPPS(t){const n=new LK(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 Ax=188;class aA{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=aA.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(Ax*5,n-Ax)+1,a=0;for(;a1&&(l===0&&o>2||c+Ax>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:K9t[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=aA.createTrack("video"),this._videoTrack.duration=a,this._audioTrack=aA.createTrack("audio",a),this._id3Track=aA.createTrack("id3"),this._txtTrack=aA.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,f=c.pid,g=o.pesData,y=c.pesData,x=null,_=this.pmtParsed,b=this._pmtId,k=t.length;if(this.remainderData&&(t=Sj(this.remainderData,t),k=t.length,this.remainderData=null),k>4;let $;if(z>1){if($=I+5+t[I+4],$===I+Ax)continue}else $=I+4;switch(L){case u:M&&(h&&(i=$F(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($,I+Ax)),h.size+=I+Ax-$);break;case m:if(M){if(g&&(i=$F(g,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}g={data:[],size:0}}g&&(g.data.push(t.subarray($,I+Ax)),g.size+=I+Ax-$);break;case f:M&&(y&&(i=$F(y,this.logger))&&this.parseID3PES(c,i),y={data:[],size:0}),y&&(y.data.push(t.subarray($,I+Ax)),y.size+=I+Ax-$);break;case 0:M&&($+=t[$]+1),b=this._pmtId=GTn(t,$);break;case b:{M&&($+=t[$]+1);const V=WTn(t,$,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),f=V.id3Pid,f>0&&(c.pid=f),x!==null&&!_&&(this.logger.warn(`MPEG-TS PMT found at ${I} after unknown PID '${x}'. Backtracking to sync byte @${A} to parse all TS packets.`),x=null,I=A-188),_=this.pmtParsed=!0;break}case 17:case 8191:break;default:x=L;break}}else T++;T>0&&Pze(this.observer,new Error(`Found ${T} TS packet/s that do not start with 0x47`),void 0,this.logger),l.pesData=h,o.pesData=g,c.pesData=y;const P={audioTrack:o,videoTrack:l,id3Track:c,textTrack:d};return a&&this.extractRemainingSamples(P),P}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=$F(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=$F(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=$F(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 qTn(this.observer,this.config,n);return this.decrypt(a,i)}readyVideoParser(t){this.videoParser===null&&(t==="avc"?this.videoParser=new VTn:t==="hevc"&&(this.videoParser=new HTn))}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=Sj(a.sample.unit,i);else{const f=m-h;a.sample.unit.set(i.subarray(0,h),f),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=rh({},n,{type:this._videoTrack?y_.emsg:y_.audioId3,duration:Number.POSITIVE_INFINITY});t.samples.push(r)}}function Lze(s,t){return((s[t+1]&31)<<8)+s[t+2]}function GTn(s,t){return(s[t+10]&31)<<8|s[t+11]}function WTn(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,f=h;for(;f>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,f-=y}}break;case 194:case 135:return Pze(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 Pze(s,t,n,r){r.warn(`parsing error: ${t.message}`),s.emit(Et.ERROR,Et.ERROR,{type:ao.MEDIA_ERROR,details:lr.FRAG_PARSING_ERROR,fatal:!1,levelRetry:n,error:t,reason:t.message})}function pIe(s,t){t.log(`${s} with AES-128-CBC encryption found in unencrypted stream`)}function $F(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]=Sj(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 f=0,g=c.length;fy){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 KTn{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 AC=Math.pow(2,32)-1;class or{static init(){or.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 or.types)or.types.hasOwnProperty(t)&&(or.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]);or.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]);or.STTS=or.STSC=or.STCO=i,or.STSZ=new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0]),or.VMHD=new Uint8Array([0,0,0,1,0,0,0,0,0,0,0,0]),or.SMHD=new Uint8Array([0,0,0,0,0,0,0,0]),or.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]);or.FTYP=or.box(or.types.ftyp,l,c,l,o),or.DINF=or.box(or.types.dinf,or.box(or.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 or.box(or.types.mdia,or.mdhd(t.timescale||0,t.duration||0),or.hdlr(t.type),or.minf(t))}static mfhd(t){return or.box(or.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"?or.box(or.types.minf,or.box(or.types.smhd,or.SMHD),or.DINF,or.stbl(t)):or.box(or.types.minf,or.box(or.types.vmhd,or.VMHD),or.DINF,or.stbl(t))}static moof(t,n,r){return or.box(or.types.moof,or.mfhd(t),or.traf(r,n))}static moov(t){let n=t.length;const r=[];for(;n--;)r[n]=or.trak(t[n]);return or.box.apply(null,[or.types.moov,or.mvhd(t[0].timescale||0,t[0].duration||0)].concat(r).concat(or.mvex(t)))}static mvex(t){let n=t.length;const r=[];for(;n--;)r[n]=or.trex(t[n]);return or.box.apply(null,[or.types.mvex,...r])}static mvhd(t,n){n*=t;const r=Math.floor(n/(AC+1)),a=Math.floor(n%(AC+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 or.box(or.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=or.box(or.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 or.box(or.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,or.box(or.types.btrt,new Uint8Array([0,28,156,128,0,45,198,192,0,45,198,192])),or.box(or.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 or.box(or.types.mp4a,or.audioStsd(t),or.box(or.types.esds,or.esds(t)))}static mp3(t){return or.box(or.types[".mp3"],or.audioStsd(t))}static ac3(t){return or.box(or.types["ac-3"],or.audioStsd(t),or.box(or.types.dac3,t.config))}static stsd(t){const{segmentCodec:n}=t;if(t.type==="audio"){if(n==="aac")return or.box(or.types.stsd,or.STSD,or.mp4a(t));if(n==="ac3"&&t.config)return or.box(or.types.stsd,or.STSD,or.ac3(t));if(n==="mp3"&&t.codec==="mp3")return or.box(or.types.stsd,or.STSD,or.mp3(t))}else if(t.pps&&t.sps){if(n==="avc")return or.box(or.types.stsd,or.STSD,or.avc1(t));if(n==="hevc"&&t.vps)return or.box(or.types.stsd,or.STSD,or.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/(AC+1)),o=Math.floor(r%(AC+1));return or.box(or.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=or.sdtp(t),a=t.id,i=Math.floor(n/(AC+1)),l=Math.floor(n%(AC+1));return or.box(or.types.traf,or.box(or.types.tfhd,new Uint8Array([0,0,0,0,a>>24,a>>16&255,a>>8&255,a&255])),or.box(or.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])),or.trun(t,r.length+16+20+8+16+8+8),r)}static trak(t){return t.duration=t.duration||4294967295,or.box(or.types.trak,or.tkhd(t),or.mdia(t))}static trex(t){const n=t.id;return or.box(or.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 or.box(or.types.trun,l)}static initSegment(t){or.types||or.init();const n=or.moov(t);return Sj(or.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 g=0;g>8,r[g][y].length&255]),l),l+=2,o.set(r[g][y],l),l+=r[g][y].length}const d=or.box(or.types.hvcC,o),u=t.width,h=t.height,m=t.pixelRatio[0],f=t.pixelRatio[1];return or.box(or.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,or.box(or.types.btrt,new Uint8Array([0,28,156,128,0,45,198,192,0,45,198,192])),or.box(or.types.pasp,new Uint8Array([m>>24,m>>16&255,m>>8&255,m&255,f>>24,f>>16&255,f>>8&255,f&255])))}}or.types=void 0;or.HDLR_TYPES=void 0;or.STTS=void 0;or.STSC=void 0;or.STCO=void 0;or.STSZ=void 0;or.VMHD=void 0;or.SMHD=void 0;or.STSD=void 0;or.FTYP=void 0;or.DINF=void 0;const qzt=9e4;function _Ke(s,t,n=1,r=!1){const a=s*t*n;return r?Math.round(a):a}function YTn(s,t,n=1,r=!1){return _Ke(s,t,1/n,r)}function xH(s,t=!1){return _Ke(s,1e3,1/qzt,t)}function ZTn(s,t=1){return _Ke(s,qzt,1/t)}function pxt(s){const{baseTime:t,timescale:n,trackId:r}=s;return`${t/n} (${t}/${n}) trackId: ${r}`}const XTn=10*1e3,QTn=1024,JTn=1152,eEn=1536;let UF=null,fIe=null;function fxt(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 Hje extends Ij{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,UF===null){const l=(navigator.userAgent||"").match(/Chrome\/(\d+)/i);UF=l?parseInt(l[1]):0}if(fIe===null){const i=navigator.userAgent.match(/Safari\/(\d+)/i);fIe=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&&pxt(n)} > ${t&&pxt(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=d_(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,f,g,y=i,x=i;const _=t.pid>-1,b=n.pid>-1,k=n.samples.length,A=t.samples.length>0,T=o&&k>0||k>1;if((!_||A)&&(!b||T)||this.ISGenerated||o){if(this.ISGenerated){var I,M,L,z;const G=this.videoTrackConfig;(G&&(n.width!==G.width||n.height!==G.height||((I=n.pixelRatio)==null?void 0:I[0])!==((M=G.pixelRatio)==null?void 0:M[0])||((L=n.pixelRatio)==null?void 0:L[1])!==((z=G.pixelRatio)==null?void 0:z[1]))||!G&&T||this.nextAudioTs===null&&A)&&this.resetInitSegment()}this.ISGenerated||(h=this.generateIS(t,n,i,l));const $=this.isVideoContiguous;let V=-1,W;if(T&&(V=tEn(n.samples),!$&&this.config.forceKeyFrameOnDiscontinuity))if(g=!0,V>0){this.warn(`Dropped ${V} out of ${k} video samples due to a missing keyframe`);const G=this.getVideoStartPts(n.samples);n.samples=n.samples.slice(V),n.dropped+=V,x+=(n.samples[0].pts-G)/n.inputTimeScale,W=x}else V===-1&&(this.warn(`No keyframe found out of ${k} video samples`),g=!1);if(this.ISGenerated){if(A&&T){const G=this.getVideoStartPts(n.samples),te=(d_(t.samples[0].pts,G)-G)/n.inputTimeScale;y+=Math.max(0,te),x+=Math.max(0,-te)}if(A){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||T||c===Ri.AUDIO?x:void 0),T){const G=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,x,$,G)}}else T&&(d=this.remuxVideo(n,x,$,0));d&&(d.firstKeyFrame=V,d.independent=V!==-1,d.firstKeyFramePTS=W)}}return this.ISGenerated&&this._initPTS&&this._initDTS&&(r.samples.length&&(f=Vzt(r,i,this._initPTS,this._initDTS)),a.samples.length&&(m=Hzt(a,i,this._initPTS))),{audio:u,video:d,initSegment:h,independent:g,text:m,id3:f}}computeInitPts(t,n,r,a){const i=Math.round(r*n);let l=d_(t,i);if(l0?ae-1:ae].dts&&(b=!0)}b&&l.sort(function(ae,he){const xe=ae.dts-he.dts,ve=ae.pts-he.pts;return xe||ve}),g=l[0].dts,y=l[l.length-1].dts;const A=y-g,T=A?Math.round(A/(c-1)):f||t.inputTimeScale/30;if(r){const ae=g-k,he=ae>T,xe=ae<-1;if((he||xe)&&(he?this.warn(`${(t.segmentCodec||"").toUpperCase()}: ${xH(ae,!0)} ms (${ae}dts) hole between fragments detected at ${n.toFixed(3)}`):this.warn(`${(t.segmentCodec||"").toUpperCase()}: ${xH(-ae,!0)} ms (${ae}dts) overlapping between fragments detected at ${n.toFixed(3)}`),!xe||k>=l[0].pts||UF)){g=k;const ve=l[0].pts-ae;if(he)l[0].dts=g,l[0].pts=ve;else{let ge=!0;for(let be=0;beve&&ge);be++){const Se=l[be].pts;if(l[be].dts-=ae,l[be].pts-=ae,be0?he.dts-l[ae-1].dts:T;if(ge=ae>0?he.pts-l[ae-1].pts:T,Se.stretchShortVideoTrack&&this.nextAudioTs!==null){const Me=Math.floor(Se.maxBufferHole*i),Re=(a?x+a*i:this.nextAudioTs+u)-he.pts;Re>Me?(f=Re-Ie,f<0?f=Ie:V=!0,this.log(`It is approximately ${Re/90} ms to the next segment; using duration ${f/90} ms for the last video frame.`)):f=Ie}else f=Ie}const be=Math.round(he.pts-he.dts);W=Math.min(W,f),X=Math.max(X,f),G=Math.min(G,ge),te=Math.max(te,ge),o.push(fxt(he.key,f,ve,be))}if(o.length){if(UF){if(UF<70){const ae=o[0].flags;ae.dependsOn=2,ae.isNonSync=0}}else if(fIe&&te-G0&&(a&&Math.abs(k-(_+b))<9e3||Math.abs(d_(y[0].pts,k)-(_+b))<20*u),y.forEach(function(te){te.pts=d_(te.pts,k)}),!r||_<0){const te=y.length;if(y=y.filter(ne=>ne.pts>=0),te!==y.length&&this.warn(`Removed ${y.length-te} of ${te} samples (initPTS ${b} / ${l})`),!y.length)return;i===0?_=0:a&&!g?_=Math.max(0,k-b):_=y[0].pts-b}if(t.segmentCodec==="aac"){const te=this.config.maxAudioFramesDrift;for(let ne=0,me=_+b;ne=te*u&&he0){I+=x;try{P=new Uint8Array(I)}catch(he){this.observer.emit(Et.ERROR,Et.ERROR,{type:ao.MUX_ERROR,details:lr.REMUX_ALLOC_ERROR,fatal:!1,error:he,bytes:I,reason:`fail allocating audio mdat ${I}`});return}m||(new DataView(P.buffer).setUint32(0,I),P.set(or.types.mdat,4))}else return;P.set(ue,x);const ae=ue.byteLength;x+=ae,f.push(fxt(!0,d,ae,0)),T=ce}const L=f.length;if(!L)return;const z=f[f.length-1];_=T-b,this.nextAudioTs=_+c*z.duration;const $=m?new Uint8Array(0):or.moof(t.sequenceNumber++,A/c,rh({},t,{samples:f}));t.samples=[];const V=(A-b)/l,W=this.nextAudioTs/l,X={data1:$,data2:P,startPTS:V,endPTS:W,startDTS:V,endDTS:W,type:"audio",hasAudio:!0,hasVideo:!1,nb:L};return this.isAudioContiguous=!0,X}}function d_(s,t){let n;if(t===null)return s;for(t4294967296;)s+=n;return s}function tEn(s){for(let t=0;tl.pts-o.pts);const i=s.samples;return s.samples=[],{samples:i}}class sEn extends Ij{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=X9t(t);if(n)qCn(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=gxt(i,fh.AUDIO,this)),l&&(a=gxt(l,fh.VIDEO,this));const o={};i&&l?o.audiovideo={container:"video/mp4",codec:r+","+a,supplemental:l.supplemental,encrypted:l.encrypted,initSegment:t,id:"main"}:i?o.audio={container:"audio/mp4",codec:r,encrypted:i.encrypted,initSegment:t,id:"audio"}:l?o.video={container:"video/mp4",codec:a,supplemental:l.supplemental,encrypted:l.encrypted,initSegment:t,id:"main"}:this.warn("initSegment does not contain moov or trak boxes."),this.initTracks=o}remux(t,n,r,a,i,l){var o,c;let{initPTS:d,lastEndTime:u}=this;const h={audio:void 0,video:void 0,text:a,id3:r,initSegment:void 0};bi(u)||(u=this.lastEndTime=i||0);const m=n.samples;if(!m.length)return h;const f={initPTS:void 0,timescale:void 0,trackId:void 0};let g=this.initData;if((o=g)!=null&&o.length||(this.generateInitSegment(m),g=this.initData),!((c=g)!=null&&c.length))return this.warn("Failed to generate initSegment."),h;this.emitInitSegment&&(f.tracks=this.initTracks,this.emitInitSegment=!1);const y=HCn(m,g,this),x=g.audio?y[g.audio.id]:null,_=g.video?y[g.video.id]:null,b=$ne(_,1/0),k=$ne(x,1/0),A=$ne(_,0,!0),T=$ne(x,0,!0);let P=i,I=0;const M=x&&(!_||!d&&k0?this.lastEndTime=$:(this.warn("Duration parsed from mp4 should be greater than zero"),this.resetNextTimestamp());const V=!!g.audio,W=!!g.video;let G="";V&&(G+="audio"),W&&(G+="video");const X=(g.audio?g.audio.encrypted:!1)||(g.video?g.video.encrypted:!1),te={data1:m,startPTS:z,startDTS:z,endPTS:$,endDTS:$,type:G,hasAudio:V,hasVideo:W,nb:1,dropped:0,encrypted:X};h.audio=V&&!W?te:void 0,h.video=W?te:void 0;const ne=_==null?void 0:_.sampleCount;if(ne){const me=_.keyFrameIndex,ue=me!==-1;te.nb=ne,te.dropped=me===0||this.isVideoContiguous?0:ue?me:ne,te.independent=ue,te.firstKeyFrame=me,ue&&_.keyFrameStart&&(te.firstKeyFramePTS=(_.keyFrameStart-d.baseTime)/d.timescale),this.isVideoContiguous||(h.independent=ue),this.isVideoContiguous||(this.isVideoContiguous=ue),te.dropped&&this.warn(`fmp4 does not start with IDR: firstIDR ${me}/${ne} dropped: ${te.dropped} start: ${te.firstKeyFramePTS||"NA"}`)}return h.initSegment=f,h.id3=Vzt(r,i,d,d),a.samples.length&&(h.text=Hzt(a,i,d)),h}}function $ne(s,t,n=!1){return(s==null?void 0:s.start)!==void 0?(s.start+(n?s.duration:0))/s.timescale:t}function nEn(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 gxt(s,t,n){const r=s.codec;return r&&r.length>4?r:t===fh.AUDIO?r==="ec-3"||r==="ac-3"||r==="alac"?r:r==="fLaC"||r==="Opus"?H5e(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 r4;try{r4=self.performance.now.bind(self.performance)}catch{r4=Date.now}const Gje=[{demux:UTn,remux:sEn},{demux:aA,remux:Hje},{demux:FTn,remux:Hje},{demux:BTn,remux:Hje}];Gje.splice(2,0,{demux:zTn,remux:Hje});class xxt{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=r4();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:f,initSegmentChange:g}=a||o,{audioCodec:y,videoCodec:x,defaultInitPts:_,duration:b,initSegmentData:k}=c,A=rEn(l,n);if(A&&uz(A.method)){const M=this.getDecrypter(),L=hKe(A.method);if(M.isSync()){let z=M.softwareDecrypt(l,A.key.buffer,A.iv.buffer,L);if(r.part>-1){const V=M.flush();z=V&&V.buffer}if(!z)return i.executeEnd=r4(),gIe(r);l=new Uint8Array(z)}else return this.asyncResult=!0,this.decryptionPromise=M.webCryptoDecrypt(l,A.key.buffer,A.iv.buffer,L).then(z=>{const $=this.push(z,null,r);return this.decryptionPromise=null,$}),this.decryptionPromise}const T=this.needsProbing(u,h);if(T){const M=this.configureTransmuxer(l);if(M)return this.logger.warn(`[transmuxer] ${M.message}`),this.observer.emit(Et.ERROR,Et.ERROR,{type:ao.MEDIA_ERROR,details:lr.FRAG_PARSING_ERROR,fatal:!1,error:M,reason:M.message}),i.executeEnd=r4(),gIe(r)}(u||h||g||T)&&this.resetInitSegment(k,y,x,b,n),(u||g||T)&&this.resetInitialTimestamp(_),d||this.resetContiguity();const P=this.transmux(l,A,f,m,r);this.asyncResult=BZ(P);const I=this.currentTransmuxState;return I.contiguous=!0,I.discontinuity=!1,I.trackSwitch=!1,i.executeEnd=r4(),P}flush(t){const n=t.transmuxing;n.executeStart=r4();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=r4();const h=[gIe(t)];return this.asyncResult?Promise.resolve(h):h}const u=c.flush(o);return BZ(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===Ri.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=r4()}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=Gje.length;h0&&(t==null?void 0:t.key)!=null&&t.iv!==null&&t.method!=null&&(n=t),n}const gIe=s=>({remuxResult:{},chunkMeta:s});function BZ(s){return"then"in s&&s.then instanceof Function}class aEn{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 iEn{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 yxt=0;class Gzt{constructor(t,n,r,a){this.error=null,this.hls=void 0,this.id=void 0,this.instanceNo=yxt++,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(Et.ERROR,{type:ao.OTHER_ERROR,details:lr.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===Et.ERROR&&(d=d,d.parent=this.id,d.part=this.part,this.error=d.error),this.hls.trigger(c,d)};this.observer=new fKe,this.observer.on(Et.FRAG_DECRYPTED,l),this.observer.on(Et.ERROR,l);const o=Pgt(i.preferManagedMediaSource);if(this.useWorker&&typeof Worker<"u"){const c=this.hls.logger;if(i.workerPath||dTn()){try{i.workerPath?(c.log(`loading Web Worker ${i.workerPath} for "${n}"`),this.workerContext=hTn(i.workerPath)):(c.log(`injecting Web Worker for "${n}"`),this.workerContext=uTn());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:bh(i)})}catch(u){c.warn(`Error setting up "${n}" Web Worker, fallback to inline`,u),this.terminateWorker(),this.error=null,this.transmuxer=new xxt(this.observer,o,i,"",n,t.logger)}return}}this.transmuxer=new xxt(this.observer,o,i,"",n,t.logger)}reset(){if(this.frag=null,this.part=null,this.workerContext){const t=this.instanceNo;this.instanceNo=yxt++;const n=this.hls.config,r=Pgt(n.preferManagedMediaSource);this.workerContext.worker.postMessage({instanceNo:this.instanceNo,cmd:"reset",resetNo:t,typeSupported:r,id:this.id,config:bh(n)})}}terminateWorker(){if(this.workerContext){const{worker:t}=this.workerContext;this.workerContext=null,t.removeEventListener("message",this.onWorkerMessage),t.removeEventListener("error",this.onWorkerError),mTn(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:f,transmuxer:g}=this,y=l?l.start:i.start,x=i.decryptdata,_=this.frag,b=!(_&&i.cc===_.cc),k=!(_&&d.level===_.level),A=_?d.sn-_.sn:-1,T=this.part?d.part-this.part.index:-1,P=A===0&&d.id>1&&d.id===(_==null?void 0:_.stats.chunkCount),I=!k&&(A===1||A===0&&(T===1||P&&T<=0)),M=self.performance.now();(k||A||i.stats.parsing.start===0)&&(i.stats.parsing.start=M),l&&(T||!I)&&(l.stats.parsing.start=M);const L=!(_&&((h=i.initSegment)==null?void 0:h.url)===((m=_.initSegment)==null?void 0:m.url)),z=new iEn(b,I,c,k,y,L);if(!I||b||L){this.hls.logger.log(`[transmuxer-interface]: Starting new transmux session for ${i.type} sn: ${d.sn}${d.part>-1?" part: "+d.part:""} ${this.id===Ri.MAIN?"level":"track"}: ${d.level} id: ${d.id} discontinuity: ${b} trackSwitch: ${k} contiguous: ${I} accurateTimeOffset: ${c} timeOffset: ${y} initSegmentChange: ${L}`);const $=new aEn(r,a,n,o,u);this.configureTransmuxer($)}if(this.frag=i,this.part=l,this.workerContext)this.workerContext.worker.postMessage({instanceNo:f,cmd:"demux",data:t,decryptdata:x,chunkMeta:d,state:z},t instanceof ArrayBuffer?[t]:[]);else if(g){const $=g.push(t,x,d,z);BZ($)?$.then(V=>{this.handleTransmuxComplete(V)}).catch(V=>{this.transmuxerError(V,d,"transmuxer-interface push error")}):this.handleTransmuxComplete($)}}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);BZ(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(Et.ERROR,{type:ao.MEDIA_ERROR,details:lr.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 vxt=100;class oEn extends pKe{constructor(t,n,r){super(t,n,r,"audio-stream-controller",Ri.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(Et.LEVEL_LOADED,this.onLevelLoaded,this),t.on(Et.AUDIO_TRACKS_UPDATED,this.onAudioTracksUpdated,this),t.on(Et.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),t.on(Et.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),t.on(Et.BUFFER_RESET,this.onBufferReset,this),t.on(Et.BUFFER_CREATED,this.onBufferCreated,this),t.on(Et.BUFFER_FLUSHING,this.onBufferFlushing,this),t.on(Et.BUFFER_FLUSHED,this.onBufferFlushed,this),t.on(Et.INIT_PTS_FOUND,this.onInitPtsFound,this),t.on(Et.FRAG_LOADING,this.onFragLoading,this),t.on(Et.FRAG_BUFFERED,this.onFragBuffered,this)}unregisterListeners(){const{hls:t}=this;t&&(super.unregisterListeners(),t.off(Et.LEVEL_LOADED,this.onLevelLoaded,this),t.off(Et.AUDIO_TRACKS_UPDATED,this.onAudioTracksUpdated,this),t.off(Et.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),t.off(Et.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),t.off(Et.BUFFER_RESET,this.onBufferReset,this),t.off(Et.BUFFER_CREATED,this.onBufferCreated,this),t.off(Et.BUFFER_FLUSHING,this.onBufferFlushing,this),t.off(Et.BUFFER_FLUSHED,this.onBufferFlushed,this),t.off(Et.INIT_PTS_FOUND,this.onInitPtsFound,this),t.off(Et.FRAG_LOADING,this.onFragLoading,this),t.off(Et.FRAG_BUFFERED,this.onFragBuffered,this))}onInitPtsFound(t,{frag:n,id:r,initPTS:a,timescale:i,trackId:l}){if(r===Ri.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===Ur.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===Ur.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=lzt(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===Ur.IDLE&&this.doTickIdle())}startLoad(t,n){if(!this.levels){this.startPosition=t,this.state=Ur.STOPPED;return}const r=this.lastCurrentTime;this.stopLoad(),this.setInterval(vxt),r>0&&t===-1?(this.log(`Override startPosition with lastCurrentTime @${r.toFixed(3)}`),t=r,this.state=Ur.IDLE):this.state=Ur.WAITING_TRACK,this.nextLoadPosition=this.lastCurrentTime=t+this.timelineOffset,this.startPosition=n?-1:t,this.tick()}doTick(){switch(this.state){case Ur.IDLE:this.doTickIdle();break;case Ur.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=Ur.WAITING_INIT_PTS}break}case Ur.FRAG_LOADING_WAITING_RETRY:{this.checkRetryDate();break}case Ur.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=Ur.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=Ur.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=Ur.WAITING_TRACK,this.startFragRequested=!1;return}const d=this.mediaBuffer?this.mediaBuffer:this.media;this.bufferFlushed&&d&&(this.bufferFlushed=!1,this.afterBufferFlushed(d,fh.AUDIO,Ri.AUDIO));const u=this.getFwdBufferInfo(d,Ri.AUDIO);if(u===null)return;if(!this.switchingTrack&&this._streamEnded(u,c)){n.trigger(Et.BUFFER_EOS,{type:"audio"}),this.state=Ur.ENDED;return}const h=u.len,m=n.maxBufferLength,f=c.fragments,g=f[0].start,y=this.getLoadPosition(),x=this.flushing?y:u.end;if(this.switchingTrack&&a){const k=y;c.PTSKnown&&kg||u.nextStart)&&(this.log("Alt audio track ahead of main track, seek to start of alt audio track"),a.currentTime=g+.05)}if(h>=m&&!this.switchingTrack&&xb.end){const A=this.fragmentTracker.getFragAtPos(x,Ri.MAIN);A&&A.end>b.end&&(b=A,this.mainFragLoading={frag:A,targetBufferTime:null})}if(_.start>b.end)return}this.loadFragment(_,o,x)}onMediaDetaching(t,n){this.bufferFlushed=this.flushing=!1,super.onMediaDetaching(t,n)}onAudioTracksUpdated(t,{audioTracks:n}){this.resetTransmuxer(),this.levels=n.map(r=>new OZ(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!==Ur.STOPPED&&(this.setInterval(vxt),this.state=Ur.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(Et.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!==Ur.STOPPED&&(this.state=Ur.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||(Szt(i,d),i.alignedSliding||Q5e(i,d),h=i.fragmentStart)}u.details=i,this.levelLastLoaded=u,this.startFragRequested||this.setStartPosition(d,h),this.hls.trigger(Et.AUDIO_TRACK_UPDATED,{details:i,id:l,groupId:n.groupId}),this.state===Ur.WAITING_TRACK&&!this.waitForCdnTuneIn(i)&&(this.state=Ur.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 Gzt(this.hls,Ri.AUDIO,this._handleTransmuxComplete.bind(this),this._handleTransmuxerFlush.bind(this)));const f=this.initPTS[r.cc],g=(n=r.initSegment)==null?void 0:n.data;if(f!==void 0){const x=a?a.index:-1,_=x!==-1,b=new uKe(r.level,r.sn,r.stats.chunkCount,i.byteLength,x,_);m.push(i,g,h,"",r,a,u.totalduration,!1,b,f)}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 Czt,complete:!1};y.push(new Uint8Array(i)),this.state!==Ur.STOPPED&&(this.state=Ur.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===Ri.MAIN&&$f(n.frag)&&(this.mainFragLoading=n,this.state===Ur.IDLE&&this.tick())}onFragBuffered(t,n){const{frag:r,part:a}=n;if(r.type!==Ri.AUDIO){!this.audioOnly&&r.type===Ri.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($f(r)){this.fragPrevious=r;const i=this.switchingTrack;i&&(this.bufferedTrack=i,this.switchingTrack=null,this.hls.trigger(Et.AUDIO_TRACK_SWITCHED,$u({},i)))}this.fragBufferedComplete(r,a),this.media&&this.tick()}onError(t,n){var r;if(n.fatal){this.state=Ur.ERROR;return}switch(n.details){case lr.FRAG_GAP:case lr.FRAG_PARSING_ERROR:case lr.FRAG_DECRYPT_ERROR:case lr.FRAG_LOAD_ERROR:case lr.FRAG_LOAD_TIMEOUT:case lr.KEY_LOAD_ERROR:case lr.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(Ri.AUDIO,n);break;case lr.AUDIO_TRACK_LOAD_ERROR:case lr.AUDIO_TRACK_LOAD_TIMEOUT:case lr.LEVEL_PARSING_ERROR:!n.levelRetry&&this.state===Ur.WAITING_TRACK&&((r=n.context)==null?void 0:r.type)===Ac.AUDIO_TRACK&&(this.state=Ur.IDLE);break;case lr.BUFFER_ADD_CODEC_ERROR:case lr.BUFFER_APPEND_ERROR:if(n.parent!=="audio")return;this.reduceLengthAndFlushBuffer(n)||this.resetLoadingState();break;case lr.BUFFER_FULL_ERROR:if(n.parent!=="audio")return;this.reduceLengthAndFlushBuffer(n)&&(this.bufferedTrack=null,super.flushMainBuffer(0,Number.POSITIVE_INFINITY,"audio"));break;case lr.INTERNAL_EXCEPTION:this.recoverWorkerError(n);break}}onBufferFlushing(t,{type:n}){n!==fh.VIDEO&&(this.flushing=!0)}onBufferFlushed(t,{type:n}){if(n!==fh.VIDEO){this.flushing=!1,this.bufferFlushed=!0,this.state===Ur.ENDED&&(this.state=Ur.IDLE);const r=this.mediaBuffer||this.media;r&&(this.afterBufferFlushed(r,n,Ri.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:f,id3:g,initSegment:y}=i;if(this.fragContextChanged(c)||!h){this.fragmentTracker.removeFragment(c);return}if(this.state=Ur.PARSING,this.switchingTrack&&m&&this.completeAudioSwitch(this.switchingTrack),y!=null&&y.tracks){const x=c.initSegment||c;if(this.unhandledEncryptionError(y,c))return;this._bufferInitSegment(u,y.tracks,x,l),a.trigger(Et.FRAG_PARSING_INIT_SEGMENT,{frag:x,id:r,tracks:y.tracks})}if(m){const{startPTS:x,endPTS:_,startDTS:b,endDTS:k}=m;d&&(d.elementaryStreams[fh.AUDIO]={startPTS:x,endPTS:_,startDTS:b,endDTS:k}),c.setElementaryStreamInfo(fh.AUDIO,x,_,b,k),this.bufferFragmentData(m,c,d,l)}if(g!=null&&(n=g.samples)!=null&&n.length){const x=rh({id:r,frag:c,details:h},g);a.trigger(Et.FRAG_PARSING_METADATA,x)}if(f){const x=rh({id:r,frag:c,details:h},f);a.trigger(Et.FRAG_PARSING_USERDATA,x)}}_bufferInitSegment(t,n,r,a){if(this.state!==Ur.PARSING||(n.video&&delete n.video,n.audiovideo&&delete n.audiovideo,!n.audio))return;const i=n.audio;i.id=Ri.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(Et.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(Et.BUFFER_APPENDING,c)}this.tickImmediate()}loadFragment(t,n,r){const a=this.fragmentTracker.getState(t);if(this.switchingTrack||a===Yg.NOT_LOADED||a===Yg.PARTIAL){var i;if(!$f(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=Ur.WAITING_INIT_PTS;const l=this.mainDetails;l&&l.fragmentStart!==n.details.fragmentStart&&Q5e(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;VD({name:n,lang:r,assocLang:a,characteristics:i,audioCodec:l,channels:o},t,gI)||(W5e(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(Et.AUDIO_TRACK_SWITCHED,$u({},t))}}class wKe extends Ij{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&&Igt(r);return new Dgt(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){JAn(r,a,this);const b=a.playlistParsingError;if(b){this.warn(b);const k=this.hls;if(!k.config.ignorePlaylistParsingErrors){var d;const{networkDetails:A}=n;k.trigger(Et.ERROR,{type:ao.NETWORK_ERROR,details:lr.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:A,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,f=(a.edge-m)*1e3,g=_zt(a,f);if(a.requestScheduled+g0){if(L>a.targetduration*3)this.log(`Playlist last advanced ${M.toFixed(2)}s ago. Omitting segment and part directives.`),x=void 0,_=void 0;else if(r!=null&&r.tuneInGoal&&L-a.partTarget>r.tuneInGoal)this.warn(`CDN Tune-in goal increased from: ${r.tuneInGoal} to: ${z} with playlist age: ${a.age}`),z=0;else{const $=Math.floor(z/a.targetduration);if(x+=$,_!==void 0){const V=Math.round(z%a.targetduration/a.partTarget);_+=V}this.log(`CDN Tune-in age: ${a.ageHeader}s last advanced ${M.toFixed(2)}s goal: ${z} skip sn ${$} to part ${_}`)}a.tuneInGoal=z}if(y=this.getDeliveryDirectives(a,n.deliveryDirectives,x,_),b||!I){a.requestScheduled=l,this.loadingPlaylist(u,y);return}}else(a.canBlockReload||a.canSkipUntil)&&(y=this.getDeliveryDirectives(a,n.deliveryDirectives,x,_));y&&x!==void 0&&a.canBlockReload&&(a.requestScheduled=i.loading.first+Math.max(g-o*2,g/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=Igt(t);return n!=null&&n.skip&&t.deltaUpdateFailed&&(r=n.msn,a=n.part,i=qje.No),new Dgt(r,a,i)}checkRetry(t){const n=t.details,r=K5e(t),a=t.errorAction,{action:i,retryCount:l=0,retryConfig:o}=a||{},c=!!a&&!!o&&(i===M0.RetryRequest||!a.resolved&&i===M0.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=cKe(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 Wzt(s,t){if(s.length!==t.length)return!1;for(let n=0;ns[a]!==t[a])}function Ize(s,t){return t.label.toLowerCase()===s.name.toLowerCase()&&(!t.language||t.language.toLowerCase()===(s.lang||"").toLowerCase())}class lEn extends wKe{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(Et.MANIFEST_LOADING,this.onManifestLoading,this),t.on(Et.MANIFEST_PARSED,this.onManifestParsed,this),t.on(Et.LEVEL_LOADING,this.onLevelLoading,this),t.on(Et.LEVEL_SWITCHING,this.onLevelSwitching,this),t.on(Et.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),t.on(Et.ERROR,this.onError,this)}unregisterListeners(){const{hls:t}=this;t.off(Et.MANIFEST_LOADING,this.onManifestLoading,this),t.off(Et.MANIFEST_PARSED,this.onManifestParsed,this),t.off(Et.LEVEL_LOADING,this.onLevelLoading,this),t.off(Et.LEVEL_SWITCHING,this.onLevelSwitching,this),t.off(Et.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),t.off(Et.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,f)=>{m.id=f});else if(!i&&!this.tracksInGroup.length)return;this.tracksInGroup=o;const c=this.hls.config.audioPreference;if(!i&&c){const m=a5(c,o,gI);if(m>-1)i=o[m];else{const f=a5(c,this.tracks);i=this.tracks[f]}}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(Et.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(Et.ERROR,{type:ao.MEDIA_ERROR,details:lr.AUDIO_TRACK_LOAD_ERROR,fatal:!0,error:m})}}}onError(t,n){n.fatal||!n.context||n.context.type===Ac.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&&VD(t,a,gI))return a;const i=a5(t,this.tracksInGroup,gI);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=bAn(t,n.levels,r,l,gI);if(o===-1)return null;n.nextLoadLevel=o}if(t.channels||t.audioCodec){const l=a5(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(Et.AUDIO_TRACK_SWITCHING,$u({},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 bxt=/(avc[1234]|hvc1|hev1|dvh[1e]|vp09|av01)(?:\.[^.,]+)+/,Kzt="HlsJsTrackRemovedError";class dEn extends Error{constructor(t){super(t),this.name=Kzt}}class uEn extends Ij{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(Et.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=PCn(wE(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(Et.MEDIA_ATTACHING,this.onMediaAttaching,this),t.on(Et.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(Et.MANIFEST_LOADING,this.onManifestLoading,this),t.on(Et.MANIFEST_PARSED,this.onManifestParsed,this),t.on(Et.BUFFER_RESET,this.onBufferReset,this),t.on(Et.BUFFER_APPENDING,this.onBufferAppending,this),t.on(Et.BUFFER_CODECS,this.onBufferCodecs,this),t.on(Et.BUFFER_EOS,this.onBufferEos,this),t.on(Et.BUFFER_FLUSHING,this.onBufferFlushing,this),t.on(Et.LEVEL_UPDATED,this.onLevelUpdated,this),t.on(Et.FRAG_PARSED,this.onFragParsed,this),t.on(Et.FRAG_CHANGED,this.onFragChanged,this),t.on(Et.ERROR,this.onError,this)}unregisterListeners(){const{hls:t}=this;t.off(Et.MEDIA_ATTACHING,this.onMediaAttaching,this),t.off(Et.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(Et.MANIFEST_LOADING,this.onManifestLoading,this),t.off(Et.MANIFEST_PARSED,this.onManifestParsed,this),t.off(Et.BUFFER_RESET,this.onBufferReset,this),t.off(Et.BUFFER_APPENDING,this.onBufferAppending,this),t.off(Et.BUFFER_CODECS,this.onBufferCodecs,this),t.off(Et.BUFFER_EOS,this.onBufferEos,this),t.off(Et.BUFFER_FLUSHING,this.onBufferFlushing,this),t.off(Et.LEVEL_UPDATED,this.onLevelUpdated,this),t.off(Et.FRAG_PARSED,this.onFragParsed,this),t.off(Et.FRAG_CHANGED,this.onFragChanged,this),t.off(Et.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?rh(r,a.tracks):this.sourceBuffers.forEach(i=>{const[l]=i;l&&(r[l]=rh({},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=wE(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,_xt(r),hEn(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: ${bh(r,(c,d)=>c==="initSegment"?void 0:d)}; transfer tracks: ${bh(a,(c,d)=>c==="initSegment"?void 0:d)}}`),!V9t(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(Et.MEDIA_DETACHING,{}),this.onMediaAttaching(Et.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,f=u.id;if(m.hasFragments(f)||m.hasParts(f)){const x=_l.getBuffered(h);m.detectEvictedFragments(d,x,f,null,!0)}const g=xIe(d),y=[d,h];this.sourceBuffers[g]=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&&_xt(a),a.load()):this.warn("media|source.src was changed by a third party - skip cleanup")),this.media=null),this.hls.trigger(Et.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[xIe(t)]=[null,null];const n=this.tracks[t];n&&(n.buffer=void 0)}resetQueue(){this.operationQueue&&this.operationQueue.destroy(),this.operationQueue=new cEn(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:f,levelCodec:g,container:y,metadata:x,supplemental:_}=h;let b=a[c];const k=(d=this.transferData)==null||(d=d.tracks)==null?void 0:d[c],A=k!=null&&k.buffer?k:b,T=(A==null?void 0:A.pendingCodec)||(A==null?void 0:A.codec),P=A==null?void 0:A.levelCodec;b||(b=a[c]={buffer:void 0,listeners:[],codec:f,supplemental:_,container:y,levelCodec:g,metadata:x,id:m});const I=Uje(T,P),M=I==null?void 0:I.replace(bxt,"$1");let L=Uje(f,g);const z=(u=L)==null?void 0:u.replace(bxt,"$1");L&&I&&M!==z&&(c.slice(0,5)==="audio"&&(L=H5e(L,this.appendSource)),this.log(`switching codec ${T} to ${L}`),L!==(b.pendingCodec||b.codec)&&(b.pendingCodec=L),b.container=y,this.appendChangeType(c,y,L))}),(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,Ri.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&&_l.isBuffered(c.buffer,a)||((o=this.fragmentTracker.getAppendedFrag(a,Ri.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:f}=o,g=self.performance.now();h.start=g;const y=o.stats.buffering,x=c?c.stats.buffering:null;y.start===0&&(y.start=g),x&&x.start===0&&(x.start=g);const _=r.audio;let b=!1;i==="audio"&&(_==null?void 0:_.container)==="audio/mpeg"&&(b=!this.lastMpegAudioChunk||d.id===1||this.lastMpegAudioChunk.sn!==d.sn,this.lastMpegAudioChunk=d);const k=r.video,A=k==null?void 0:k.buffer;if(A&&m!=="initSegment"){const I=c||o,M=this.blockedAudioAppend;if(i==="audio"&&l!=="main"&&!this.blockedAudioAppend&&!(k.ending||k.ended)){const z=I.start+I.duration*.05,$=A.buffered,V=this.currentOp("video");!$.length&&!V?this.blockAudio(I):!V&&!_l.isBuffered(A,z)&&this.lastVideoAppendEndz||L{var I;h.executeStart=self.performance.now();const M=(I=this.tracks[i])==null?void 0:I.buffer;M&&(b?this.updateTimestampOffset(M,T,.1,i,m,f):u!==void 0&&bi(u)&&this.updateTimestampOffset(M,u,1e-6,i,m,f)),this.appendExecutor(a,i)},onStart:()=>{},onComplete:()=>{const I=self.performance.now();h.executeEnd=h.end=I,y.first===0&&(y.first=I),x&&x.first===0&&(x.first=I);const M={};this.sourceBuffers.forEach(([L,z])=>{L&&(M[L]=_l.getBuffered(z))}),this.appendErrors[i]=0,i==="audio"||i==="video"?this.appendErrors.audiovideo=0:(this.appendErrors.audio=0,this.appendErrors.video=0),this.hls.trigger(Et.BUFFER_APPENDED,{type:i,frag:o,part:c,chunkMeta:d,parent:o.type,timeRanges:M})},onError:I=>{var M;const L={type:ao.MEDIA_ERROR,parent:o.type,details:lr.BUFFER_APPEND_ERROR,sourceBufferName:i,frag:o,part:c,chunkMeta:d,error:I,err:I,fatal:!1},z=(M=this.media)==null?void 0:M.error;if(I.code===DOMException.QUOTA_EXCEEDED_ERR||I.name=="QuotaExceededError"||"quota"in I)L.details=lr.BUFFER_FULL_ERROR;else if(I.code===DOMException.INVALID_STATE_ERR&&this.mediaSourceOpenOrEnded&&!z)L.errorAction=dz(!0);else if(I.name===Kzt&&this.sourceBufferCount===0)L.errorAction=dz(!0);else{const $=++this.appendErrors[i];this.warn(`Failed ${$}/${this.hls.config.appendErrorMaxRetry} times to append segment in "${i}" sourceBuffer (${z||"no media error"})`),($>=this.hls.config.appendErrorMaxRetry||z)&&(L.fatal=!0)}this.hls.trigger(Et.ERROR,L)}};this.log(`queuing "${i}" append sn: ${m}${c?" p: "+c.index:""} of ${o.type===Ri.MAIN?"level":"track"} ${o.level} cc: ${f}`),this.append(P,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(Et.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[fh.AUDIOVIDEO]?i.push("audiovideo"):(l[fh.AUDIO]&&i.push("audio"),l[fh.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(Et.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(Et.BUFFERED_TO_END,void 0)})):(this.tracksEnded(),this.hls.trigger(Et.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===lr.BUFFER_APPEND_ERROR&&n.frag){var r;const a=(r=n.errorAction)==null?void 0:r.nextAutoLevel;bi(a)&&a!==n.frag.level&&this.resetAppendErrors()}}resetAppendErrors(){this.appendErrors={audio:0,video:0,audiovideo:0}}trimBuffers(){const{hls:t,details:n,media:r}=this;if(!r||n===null||!this.sourceBufferCount)return;const a=t.config,i=r.currentTime,l=n.levelTargetDuration,o=n.live&&a.liveBackBufferLength!==null?a.liveBackBufferLength:a.backBufferLength;if(bi(o)&&o>=0){const d=Math.max(o,l),u=Math.floor(i/l)*l-d;this.flushBackBuffer(i,l,u)}const c=a.frontBufferFlushThreshold;if(bi(c)&&c>0){const d=Math.max(a.maxBufferLength,c),u=Math.max(d,l),h=Math.floor(i/l)*l+u;this.flushFrontBuffer(i,l,h)}}flushBackBuffer(t,n,r){this.sourceBuffers.forEach(([a,i])=>{if(i){const o=_l.getBuffered(i);if(o.length>0&&r>o.start(0)){var l;this.hls.trigger(Et.BACK_BUFFER_REACHED,{bufferEnd:r});const c=this.tracks[a];if((l=this.details)!=null&&l.live)this.hls.trigger(Et.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(Et.BUFFER_FLUSHING,{startOffset:0,endOffset:r,type:a})}}})}flushFrontBuffer(t,n,r){this.sourceBuffers.forEach(([a,i])=>{if(i){const l=_l.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(Et.BUFFER_FLUSHING,{startOffset:c,endOffset:1/0,type:a})}})}getDurationAndRange(){var t;const{details:n,mediaSource:r}=this;if(!n||!this.media||(r==null?void 0:r.readyState)!=="open")return null;const a=n.edge;if(n.live&&this.hls.config.liveDurationInfinity){if(n.fragments.length&&r.setLiveSeekableRange){const d=Math.max(0,n.fragmentStart),u=Math.max(d,a);return{duration:1/0,start:d,end:u}}return{duration:1/0}}const i=(t=this.overrides)==null?void 0:t.duration;if(i)return bi(i)?{duration:i}:null;const l=this.media.duration,o=bi(r.duration)?r.duration:0;return a>o&&a>l||!bi(l)?{duration:a}:null}updateMediaSource({duration:t,start:n,end:r}){const a=this.mediaSource;!this.media||!a||a.readyState!=="open"||(a.duration!==t&&(bi(t)&&this.log(`Updating MediaSource duration to ${t.toFixed(3)}`),a.duration=t),n!==void 0&&r!==void 0&&(this.log(`MediaSource duration is set to ${a.duration}. Setting seekable range to ${n}-${r}.`),a.setLiveSeekableRange(n,r)))}get tracksReady(){const t=this.pendingTrackCount;return t>0&&(t>=this.bufferCodecEventsTotal||this.isPending(this.tracks.audiovideo))}checkPendingTracks(){const{bufferCodecEventsTotal:t,pendingTrackCount:n,tracks:r}=this;if(this.log(`checkPendingTracks (pending: ${n} codec events expected: ${t}) ${bh(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(Et.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(Et.ERROR,{type:ao.MEDIA_ERROR,details:lr.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":""} ${bh(o)}`);try{const u=r.addSourceBuffer(d),h=xIe(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(Et.ERROR,{type:ao.MEDIA_ERROR,details:lr.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")&&DZ(r,"video")&&(a=tAn(a,r));const i=Uje(a,t.levelCodec);return i?n.slice(0,5)==="audio"?H5e(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(Et.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(Et.ERROR,{type:ao.MEDIA_ERROR,details:lr.BUFFER_APPENDING_ERROR,sourceBufferName:t,error:a,fatal:!1});const i=this.currentOp(t);i&&i.onError(a)}updateTimestampOffset(t,n,r,a,i,l){const o=n-t.timestampOffset;Math.abs(o)>=r&&(this.log(`Updating ${a} SourceBuffer timestampOffset to ${n} (sn: ${i} cc: ${l})`),t.timestampOffset=n)}removeExecutor(t,n,r){const{media:a,mediaSource:i}=this,l=this.tracks[t],o=l==null?void 0:l.buffer;if(!a||!i||!o){this.warn(`Attempting to remove from the ${t} SourceBuffer, but it does not exist`),this.shiftAndExecuteNext(t);return}const c=bi(a.duration)?a.duration:1/0,d=bi(i.duration)?i.duration:1/0,u=Math.max(0,n),h=Math.min(r,c,d);h>u&&(!l.ending||l.ended)?(l.ended=!1,this.log(`Removing [${u},${h}] from the ${t} SourceBuffer`),o.remove(u,h)):this.shiftAndExecuteNext(t)}appendExecutor(t,n){const r=this.tracks[n],a=r==null?void 0:r.buffer;if(!a)throw new dEn(`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 _xt(s){const t=s.querySelectorAll("source");[].slice.call(t).forEach(n=>{s.removeChild(n)})}function hEn(s,t){const n=self.document.createElement("source");n.type="video/mp4",n.src=t,s.appendChild(n)}function xIe(s){return s==="audio"?1:0}class jKe{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(Et.FPS_DROP_LEVEL_CAPPING,this.onFpsDropLevelCapping,this),t.on(Et.MEDIA_ATTACHING,this.onMediaAttaching,this),t.on(Et.MANIFEST_PARSED,this.onManifestParsed,this),t.on(Et.LEVELS_UPDATED,this.onLevelsUpdated,this),t.on(Et.BUFFER_CODECS,this.onBufferCodecs,this),t.on(Et.MEDIA_DETACHING,this.onMediaDetaching,this)}unregisterListener(){const{hls:t}=this;t.off(Et.FPS_DROP_LEVEL_CAPPING,this.onFpsDropLevelCapping,this),t.off(Et.MEDIA_ATTACHING,this.onMediaAttaching,this),t.off(Et.MANIFEST_PARSED,this.onManifestParsed,this),t.off(Et.LEVELS_UPDATED,this.onLevelsUpdated,this),t.off(Et.BUFFER_CODECS,this.onBufferCodecs,this),t.off(Et.MEDIA_DETACHING,this.onMediaDetaching,this)}onFpsDropLevelCapping(t,n){const r=this.hls.levels[n.droppedLevel];this.isLevelAllowed(r)&&this.restrictedLevels.push({bitrate:r.bitrate,height:r.height,width:r.width})}onMediaAttaching(t,n){this.media=n.media instanceof HTMLVideoElement?n.media:null,this.clientRect=null,this.timer&&this.hls.levels.length&&this.detectPlayerSize()}onManifestParsed(t,n){const r=this.hls;this.restrictedLevels=[],this.firstLevel=n.firstLevel,r.config.capLevelToPlayerSize&&n.video&&this.startCapping()}onLevelsUpdated(t,n){this.timer&&bi(this.autoLevelCapping)&&this.detectPlayerSize()}onBufferCodecs(t,n){this.hls.config.capLevelToPlayerSize&&n.video&&this.startCapping()}onMediaDetaching(){this.stopCapping(),this.media=null}detectPlayerSize(){if(this.media){if(this.mediaHeight<=0||this.mediaWidth<=0){this.clientRect=null;return}const t=this.hls.levels;if(t.length){const n=this.hls,r=this.getMaxLevel(t.length-1);r!==this.autoLevelCapping&&n.logger.log(`Setting autoLevelCapping to ${r}: ${t[r].height}p@${t[r].bitrate} for media ${this.mediaWidth}x${this.mediaHeight}`),n.autoLevelCapping=r,n.autoLevelEnabled&&n.autoLevelCapping>this.autoLevelCapping&&this.streamController&&this.streamController.nextLevelSwitch(),this.autoLevelCapping=n.autoLevelCapping}}}getMaxLevel(t){const n=this.hls.levels;if(!n.length)return-1;const r=n.filter((a,i)=>this.isLevelAllowed(a)&&i<=t);return this.clientRect=null,jKe.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 mEn={MANIFEST:"m",AUDIO:"a",VIDEO:"v",MUXED:"av",INIT:"i",CAPTION:"c",TIMED_TEXT:"tt",KEY:"k",OTHER:"o"},M1=mEn,pEn={HLS:"h"},fEn=pEn;class B5{constructor(t,n){Array.isArray(t)&&(t=t.map(r=>r instanceof B5?r:new B5(r))),this.value=t,this.params=n}}const gEn="Dict";function xEn(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 yEn(s,t,n,r){return new Error(`failed to ${s} "${xEn(t)}" as ${n}`,{cause:r})}function $5(s,t,n){return yEn("serialize",s,t,n)}class Yzt{constructor(t){this.description=t}}const wxt="Bare Item",vEn="Boolean";function bEn(s){if(typeof s!="boolean")throw $5(s,vEn);return s?"?1":"?0"}function _En(s){return btoa(String.fromCharCode(...s))}const wEn="Byte Sequence";function jEn(s){if(ArrayBuffer.isView(s)===!1)throw $5(s,wEn);return`:${_En(s)}:`}const NEn="Integer";function kEn(s){return s<-999999999999999||99999999999999912)throw $5(s,CEn);const n=t.toString();return n.includes(".")?n:`${n}.0`}const TEn="String",EEn=/[\x00-\x1f\x7f]+/;function MEn(s){if(EEn.test(s))throw $5(s,TEn);return`"${s.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`}function LEn(s){return s.description||s.toString().slice(7,-1)}const PEn="Token";function jxt(s){const t=LEn(s);if(/^([a-zA-Z*])([!#$%&'*+\-.^_`|~\w:/]*)$/.test(t)===!1)throw $5(t,PEn);return t}function Dze(s){switch(typeof s){case"number":if(!bi(s))throw $5(s,wxt);return Number.isInteger(s)?Zzt(s):AEn(s);case"string":return MEn(s);case"symbol":return jxt(s);case"boolean":return bEn(s);case"object":if(s instanceof Date)return SEn(s);if(s instanceof Uint8Array)return jEn(s);if(s instanceof Yzt)return jxt(s);default:throw $5(s,wxt)}}const IEn="Key";function Rze(s){if(/^[a-z*][a-z0-9\-_.*]*$/.test(s)===!1)throw $5(s,IEn);return s}function NKe(s){return s==null?"":Object.entries(s).map(([t,n])=>n===!0?`;${Rze(t)}`:`;${Rze(t)}=${Dze(n)}`).join("")}function Qzt(s){return s instanceof B5?`${Dze(s.value)}${NKe(s.params)}`:Dze(s)}function DEn(s){return`(${s.value.map(Qzt).join(" ")})${NKe(s.params)}`}function REn(s,t={whitespace:!0}){if(typeof s!="object"||s==null)throw $5(s,gEn);const n=s instanceof Map?s.entries():Object.entries(s),r=t!=null&&t.whitespace?" ":"";return Array.from(n).map(([a,i])=>{i instanceof B5||(i=new B5(i));let l=Rze(a);return i.value===!0?l+=NKe(i.params):(l+="=",Array.isArray(i.value)?l+=DEn(i):l+=Qzt(i)),l}).join(`,${r}`)}function Jzt(s,t){return REn(s,t)}const ok="CMCD-Object",Jp="CMCD-Request",H6="CMCD-Session",TC="CMCD-Status",OEn={br:ok,ab:ok,d:ok,ot:ok,tb:ok,tpb:ok,lb:ok,tab:ok,lab:ok,url:ok,pb:Jp,bl:Jp,tbl:Jp,dl:Jp,ltc:Jp,mtp:Jp,nor:Jp,nrr:Jp,rc:Jp,sn:Jp,sta:Jp,su:Jp,ttfb:Jp,ttfbb:Jp,ttlb:Jp,cmsdd:Jp,cmsds:Jp,smrt:Jp,df:Jp,cs:Jp,ts:Jp,cid:H6,pr:H6,sf:H6,sid:H6,st:H6,v:H6,msd:H6,bs:TC,bsd:TC,cdn:TC,rtp:TC,bg:TC,pt:TC,ec:TC,e:TC},FEn={REQUEST:Jp};function zEn(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 BEn(s,t){const n={};if(!s)return n;const r=Object.keys(s),a=t?zEn(t):{};return r.reduce((i,l)=>{var o;const c=OEn[l]||a[l]||FEn.REQUEST,d=(o=i[c])!==null&&o!==void 0?o:i[c]={};return d[l]=s[l],i},n)}function $En(s){return["ot","sf","st","e","sta"].includes(s)}function UEn(s){return typeof s=="number"?bi(s):s!=null&&s!==""&&s!==!1}const eBt="event";function qEn(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 Wje=s=>Math.round(s),Oze=(s,t)=>Array.isArray(s)?s.map(n=>Oze(n,t)):s instanceof B5&&typeof s.value=="string"?new B5(Oze(s.value,t),s.params):(t.baseUrl&&(s=qEn(s,t.baseUrl)),t.version===1?encodeURIComponent(s):s),Une=s=>Wje(s/100)*100,VEn=(s,t)=>{let n=s;return t.version>=2&&(s instanceof B5&&typeof s.value=="string"?n=new B5([s]):typeof s=="string"&&(n=[s])),Oze(n,t)},HEn={br:Wje,d:Wje,bl:Une,dl:Une,mtp:Une,nor:VEn,rtp:Une,tb:Wje},tBt="request",sBt="response",kKe=["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"],GEn=["e"],WEn=/^[a-zA-Z0-9-.]+-[a-zA-Z0-9-.]+$/;function LAe(s){return WEn.test(s)}function KEn(s){return kKe.includes(s)||GEn.includes(s)||LAe(s)}const nBt=["d","dl","nor","ot","rtp","su"];function YEn(s){return kKe.includes(s)||nBt.includes(s)||LAe(s)}const ZEn=["cmsdd","cmsds","rc","smrt","ttfb","ttfbb","ttlb","url"];function XEn(s){return kKe.includes(s)||nBt.includes(s)||ZEn.includes(s)||LAe(s)}const QEn=["bl","br","bs","cid","d","dl","mtp","nor","nrr","ot","pr","rtp","sf","sid","st","su","tb","v"];function JEn(s){return QEn.includes(s)||LAe(s)}const e6n={[sBt]:XEn,[eBt]:KEn,[tBt]:YEn};function rBt(s,t={}){const n={};if(s==null||typeof s!="object")return n;const r=t.version||s.v||1,a=t.reportingMode||tBt,i=r===1?JEn:e6n[a];let l=Object.keys(s).filter(i);const o=t.filter;typeof o=="function"&&(l=l.filter(o));const c=a===sBt||a===eBt;c&&!l.includes("ts")&&l.push("ts"),r>1&&!l.includes("v")&&l.push("v");const d=rh({},HEn,t.formatters),u={version:r,reportingMode:a,baseUrl:t.baseUrl};return l.sort().forEach(h=>{let m=s[h];const f=d[h];if(typeof f=="function"&&(m=f(m,u)),h==="v"){if(r===1)return;m=r}h=="pr"&&m===1||(c&&h==="ts"&&!bi(m)&&(m=Date.now()),UEn(m)&&($En(h)&&typeof m=="string"&&(m=new Yzt(m)),n[h]=m))}),n}function t6n(s,t={}){const n={};if(!s)return n;const r=rBt(s,t),a=BEn(r,t==null?void 0:t.customHeaderMap);return Object.entries(a).reduce((i,[l,o])=>{const c=Jzt(o,{whitespace:!1});return c&&(i[l]=c),i},n)}function s6n(s,t,n){return rh(s,t6n(t,n))}const n6n="CMCD";function r6n(s,t={}){return s?Jzt(rBt(s,t),{whitespace:!1}):""}function a6n(s,t={}){if(!s)return"";const n=r6n(s,t);return encodeURIComponent(n)}function i6n(s,t={}){if(!s)return"";const n=a6n(s,t);return`${n6n}=${n}`}const Nxt=/CMCD=[^&#]+/;function o6n(s,t,n){const r=i6n(t,n);if(!r)return s;if(Nxt.test(s))return s.replace(Nxt,r);const a=s.includes("?")?"&":"?";return`${s}${a}${r}`}class l6n{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:M1.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===M1.VIDEO||c===M1.AUDIO||c==M1.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(Et.MEDIA_ATTACHED,this.onMediaAttached,this),t.on(Et.MEDIA_DETACHED,this.onMediaDetached,this),t.on(Et.BUFFER_CREATED,this.onBufferCreated,this)}unregisterListeners(){const t=this.hls;t.off(Et.MEDIA_ATTACHED,this.onMediaAttached,this),t.off(Et.MEDIA_DETACHED,this.onMediaDetached,this),t.off(Et.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:fEn.HLS,sid:this.sid,cid:this.cid,pr:(t=this.media)==null?void 0:t.playbackRate,mtp:this.hls.bandwidthEstimate/1e3}}apply(t,n={}){rh(n,this.createData());const r=n.ot===M1.INIT||n.ot===M1.VIDEO||n.ot===M1.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={}),s6n(t.headers,n,i)):t.url=o6n(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 M1.TIMED_TEXT;if(t.sn==="initSegment")return M1.INIT;if(n==="audio")return M1.AUDIO;if(n==="main")return this.hls.audioTracks.length?M1.VIDEO:M1.MUXED}getTopBandwidth(t){let n=0,r;const a=this.hls;if(t===M1.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===M1.AUDIO?this.audioBuffer:this.videoBuffer;return!r||!n?NaN:_l.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 c6n=3e5;class d6n extends Ij{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(Et.MANIFEST_LOADING,this.onManifestLoading,this),t.on(Et.MANIFEST_LOADED,this.onManifestLoaded,this),t.on(Et.MANIFEST_PARSED,this.onManifestParsed,this),t.on(Et.ERROR,this.onError,this)}unregisterListeners(){const t=this.hls;t&&(t.off(Et.MANIFEST_LOADING,this.onManifestLoading,this),t.off(Et.MANIFEST_LOADED,this.onManifestLoaded,this),t.off(Et.MANIFEST_PARSED,this.onManifestParsed,this),t.off(Et.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)===M0.SendAlternateToPenaltyBox&&r.flags===e_.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===lr.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: ${bh(i)} penalized: ${bh(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]>c6n&&delete r[i]});for(let i=0;i0){this.log(`Setting Pathway to "${l}"`),this.pathwayId=l,Nzt(n),this.hls.trigger(Et.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 fp(u.attrs);h["PATHWAY-ID"]=l;const m=h.AUDIO&&`${h.AUDIO}_clone_${l}`,f=h.SUBTITLES&&`${h.SUBTITLES}_clone_${l}`;m&&(r[h.AUDIO]=m,h.AUDIO=m),f&&(a[h.SUBTITLES]=f,h.SUBTITLES=f);const g=aBt(u.uri,h["STABLE-VARIANT-ID"],"PER-VARIANT-URIS",c),y=new OZ({attrs:h,audioCodec:u.audioCodec,bitrate:u.bitrate,height:u.height,name:u.name,url:g,videoCodec:u.videoCodec,width:u.width});if(u.audioGroups)for(let x=1;x{this.log(`Loaded steering manifest: "${a}"`);const g=u.data;if((g==null?void 0:g.VERSION)!==1){this.log(`Steering VERSION ${g.VERSION} not supported!`);return}this.updated=performance.now(),this.timeToLoad=g.TTL;const{"RELOAD-URI":y,"PATHWAY-CLONES":x,"PATHWAY-PRIORITY":_}=g;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),x&&this.clonePathways(x);const b={steeringManifest:g,url:a.toString()};this.hls.trigger(Et.STEERING_MANIFEST_LOADED,b),_&&this.updatePathwayPriority(_)},onError:(u,h,m,f)=>{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 g=this.timeToLoad*1e3;if(u.code===429){const y=this.loader;if(typeof(y==null?void 0:y.getResponseHeader)=="function"){const x=y.getResponseHeader("Retry-After");x&&(g=parseFloat(x)*1e3)}this.log(`Steering manifest ${h.url} rate limited`);return}this.scheduleRefresh(this.uri||h.url,g)},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 kxt(s,t,n,r){s&&Object.keys(t).forEach(a=>{const i=s.filter(l=>l.groupId===a).map(l=>{const o=rh({},l);return o.details=void 0,o.attrs=new fp(o.attrs),o.url=o.attrs.URI=aBt(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 aBt(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 hz extends Ij{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=hz.CDMCleanupPromise?[hz.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=NG(this.config));const o=l.map(cIe).filter(c=>!!c);this.keyFormatPromise=this.getKeyFormatPromise(o)}this.keyFormatPromise.then(l=>{const o=Vje(l);if(r!=="sinf"||o!==Np.FAIRPLAY){this.log(`Ignoring "${n.type}" event with init data type: "${r}" for selected key-system ${o}`);return}let c;try{const f=Gg(new Uint8Array(a)),g=mKe(JSON.parse(f).sinf),y=J9t(g);if(!y)throw new Error("'schm' box missing or not cbcs/cenc with schi > tenc");c=new Uint8Array(y.subarray(8,24))}catch(f){this.warn(`${i} Failed to parse sinf: ${f}`);return}const d=L0(c),{keyIdToKeySessionPromise:u,mediaKeySessions:h}=this;let m=u[d];for(let f=0;fthis.generateRequestWithPreferredKeySession(g,r,a,"encrypted-event-key-match")),m.catch(_=>this.handleError(_));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(Et.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.on(Et.MEDIA_DETACHED,this.onMediaDetached,this),this.hls.on(Et.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.on(Et.MANIFEST_LOADED,this.onManifestLoaded,this),this.hls.on(Et.DESTROYING,this.onDestroying,this)}unregisterListeners(){this.hls.off(Et.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.off(Et.MEDIA_DETACHED,this.onMediaDetached,this),this.hls.off(Et.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.off(Et.MANIFEST_LOADED,this.onManifestLoaded,this),this.hls.off(Et.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===Np.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 Zb?o(h):o(new Zb({type:ao.KEY_SYSTEM_ERROR,details:lr.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 gzt===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=VAn(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: ${bh(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(f=>f?this.setMediaKeysServerCertificate(m,t,f):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: ${L0(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=qne(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 ${L0(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})=>cIe(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=cIe(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=NG(this.config),r=t.map(Vje).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 Zb){const c=$u({},o.data);this.getKeyStatus(n)==="internal-error"&&(c.decryptdata=n);const d=new Zb(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 Zb){n&&(t.data.frag=n);const r=t.data.decryptdata;this.error(`${t.message}${r?` (${L0(r.keyId||[])})`:""}`),this.hls.trigger(Et.ERROR,t.data)}else this.error(t.message),this.hls.trigger(Et.ERROR,{type:ao.KEY_SYSTEM_ERROR,details:lr.KEY_SYSTEM_NO_KEYS,error:t,fatal:!0})}getKeySystemForKeyPromise(t){const n=qne(t),r=this.keyIdToKeySessionPromise[n];if(!r){const a=Vje(t.keyFormat),i=a?[a]:NG(this.config);return this.attemptKeySystemAccess(i)}return r}getKeySystemSelectionPromise(t){if(t.length||(t=NG(this.config)),t.length===0)throw new Zb({type:ao.KEY_SYSTEM_ERROR,details:lr.KEY_SYSTEM_NO_CONFIGURED_LICENSE,fatal:!0},`Missing key-system license configuration options ${bh({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 g=l.call(this.hls,n,r,t);if(!g)throw new Error("Invalid response from configured generateRequest filter");n=g.initDataType,r=g.initData?g.initData:null,t.decryptdata.pssh=r?new Uint8Array(r):null}catch(g){if(this.warn(g.message),this.hls&&this.hls.config.debug)throw g}if(r===null)return this.log(`Skipping key-session request for "${a}" (no initData)`),Promise.resolve(t);const o=qne(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 fKe,u=t._onmessage=g=>{const y=t.mediaKeysSession;if(!y){d.emit("error",new Error("invalid state"));return}const{messageType:x,message:_}=g;this.log(`"${x}" message event for session "${y.sessionId}" message size: ${_.byteLength}`),x==="license-request"||x==="license-renewal"?this.renewLicense(t,_).catch(b=>{d.eventNames().length?d.emit("error",b):this.handleError(b)}):x==="license-release"?t.keySystem===Np.FAIRPLAY&&this.updateKeySession(t,Tze("acknowledged")).then(()=>this.removeSession(t)).catch(b=>this.handleError(b)):this.warn(`unhandled media key message type "${x}"`)},h=(g,y)=>{y.keyStatus=g;let x;g.startsWith("usable")?d.emit("resolved"):g==="internal-error"||g==="output-restricted"||g==="output-downscaled"?x=Sxt(g,y.decryptdata):g==="expired"?x=new Error(`key expired (keyId: ${o})`):g==="released"?x=new Error("key released"):g==="status-pending"||this.warn(`unhandled key status change "${g}" (keyId: ${o})`),x&&(d.eventNames().length?d.emit("error",x):this.handleError(x))},m=t._onkeystatuseschange=g=>{if(!t.mediaKeysSession){d.emit("error",new Error("invalid state"));return}const x=this.getKeyStatuses(t);if(!Object.keys(x).some(A=>x[A]!=="status-pending"))return;if(x[o]==="expired"){this.log(`Expired key ${bh(x)} in key-session "${t.mediaKeysSession.sessionId}"`),this.renewKeySession(t);return}let b=x[o];if(b)h(b,t);else{var k;t.keyStatusTimeouts||(t.keyStatusTimeouts={}),(k=t.keyStatusTimeouts)[o]||(k[o]=self.setTimeout(()=>{if(!t.mediaKeysSession||!this.mediaKeys)return;const T=this.getKeyStatus(t.decryptdata);if(T&&T!=="status-pending")return this.log(`No status for keyId ${o} in key-session "${t.mediaKeysSession.sessionId}". Using session key-status ${T} from other session.`),h(T,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} (${bh(x)}).`)}};qv(t.mediaKeysSession,"message",u),qv(t.mediaKeysSession,"keystatuseschange",m);const f=new Promise((g,y)=>{d.on("error",y),d.on("resolved",g)});return t.mediaKeysSession.generateRequest(n,r).then(()=>{this.log(`Request generated for key-session "${t.mediaKeysSession.sessionId}" keyId: ${o} URI: ${c}`)}).catch(g=>{throw new Zb({type:ao.KEY_SYSTEM_ERROR,details:lr.KEY_SYSTEM_NO_SESSION,error:g,decryptdata:t.decryptdata,fatal:!1},`Error generating key-session request: ${g}`)}).then(()=>f).catch(g=>(d.removeAllListeners(),this.removeSession(t).then(()=>{throw g}))).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===Np.PLAYREADY&&i.length===16){const o=L0(i);n[o]=r,pzt(i)}const l=L0(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,f,g,y)=>{l(m.data)},onError:(m,f,g,y)=>{o(new Zb({type:ao.KEY_SYSTEM_ERROR,details:lr.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,fatal:!0,networkDetails:g,response:$u({url:c.url,data:void 0},m)},`"${t}" certificate request failed (${i}). Status: ${m.code} (${m.text})`))},onTimeout:(m,f,g)=>{o(new Zb({type:ao.KEY_SYSTEM_ERROR,details:lr.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,fatal:!0,networkDetails:g,response:{url:c.url,data:void 0}},`"${t}" certificate request timed out (${i})`))},onAbort:(m,f,g)=>{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 Zb({type:ao.KEY_SYSTEM_ERROR,details:lr.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 Zb({type:ao.KEY_SYSTEM_ERROR,details:lr.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 Tze(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 Zb({type:ao.KEY_SYSTEM_ERROR,details:lr.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==Np.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,qv(r,"encrypted",this.onMediaEncrypted),qv(r,"waitingforkey",this.onWaitingForKey);const a=this.mediaResolved;a?a():this.mediaKeys=r.mediaKeys}onMediaDetached(){const t=this.media;t&&(X1(t,"encrypted",this.onMediaEncrypted),X1(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,tE.clearKeyUriToKeyIdMap();const i=a.length;hz.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(Et.ERROR,{type:ao.OTHER_ERROR,details:lr.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(Et.ERROR,{type:ao.OTHER_ERROR,details:lr.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: ${L0((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(GAn(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(Et.ERROR,{type:ao.OTHER_ERROR,details:lr.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(Et.ERROR,{type:ao.OTHER_ERROR,details:lr.KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR,fatal:!1,error:new Error(`Could not close session: ${d}`)})})}return Promise.resolve()}}hz.CDMCleanupPromise=void 0;function qne(s){if(!s)throw new Error("Could not read keyId of undefined decryptdata");if(s.keyId===null)throw new Error("keyId is null");return L0(s.keyId)}function u6n(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 Zb 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 Sxt(s,t){const n=s==="output-restricted",r=n?lr.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED:lr.KEY_SYSTEM_STATUS_INTERNAL_ERROR;return new Zb({type:ao.KEY_SYSTEM_ERROR,details:r,fatal:!1,decryptdata:t},n?"HDCP level output restricted":`key status changed to "${s}"`)}class h6n{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(Et.MEDIA_ATTACHING,this.onMediaAttaching,this),this.hls.on(Et.MEDIA_DETACHING,this.onMediaDetaching,this)}unregisterListeners(){this.hls.off(Et.MEDIA_ATTACHING,this.onMediaAttaching,this),this.hls.off(Et.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(Et.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(Et.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 iBt(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 oBt(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){Gu.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){Gu.debug(`[texttrack-utils]: Legacy TextTrackCue fallback failed: ${a}`)}}n==="disabled"&&(s.mode=n)}function K7(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=p6n(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 Kje(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=Kje(this.media.textTracks);for(let i=0;i-1&&this.toggleTrackModes()}registerListeners(){const{hls:t}=this;t.on(Et.MEDIA_ATTACHED,this.onMediaAttached,this),t.on(Et.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(Et.MANIFEST_LOADING,this.onManifestLoading,this),t.on(Et.MANIFEST_PARSED,this.onManifestParsed,this),t.on(Et.LEVEL_LOADING,this.onLevelLoading,this),t.on(Et.LEVEL_SWITCHING,this.onLevelSwitching,this),t.on(Et.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),t.on(Et.ERROR,this.onError,this)}unregisterListeners(){const{hls:t}=this;t.off(Et.MEDIA_ATTACHED,this.onMediaAttached,this),t.off(Et.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(Et.MANIFEST_LOADING,this.onManifestLoading,this),t.off(Et.MANIFEST_PARSED,this.onManifestParsed,this),t.off(Et.LEVEL_LOADING,this.onLevelLoading,this),t.off(Et.LEVEL_SWITCHING,this.onLevelSwitching,this),t.off(Et.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),t.off(Et.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;Kje(r.textTracks).forEach(l=>{K7(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=a5(o,l);if(u>-1)i=l[u];else{const h=a5(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(Et.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=a5(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(Et.SUBTITLE_TRACK_LOADING,{url:i,id:r,groupId:a,deliveryDirectives:n||null,track:t})}toggleTrackModes(){const{media:t}=this;if(!t)return;const n=Kje(t.textTracks),r=this.currentTrack;let a;if(r&&(a=n.filter(i=>Ize(r,i))[0],a||this.warn(`Unable to find subtitle TextTrack with name "${r.name}" and language "${r.lang}"`)),[].slice.call(n).forEach(i=>{i.mode!=="disabled"&&i!==a&&(i.mode="disabled")}),a){const i=this.subtitleDisplay?"showing":"hidden";a.mode!==i&&(a.mode=i)}}setSubtitleTrack(t){const n=this.tracksInGroup;if(!this.media){this.queuedDefaultTrack=t;return}if(t<-1||t>=n.length||!bi(t)){this.warn(`Invalid subtitle track id: ${t}`);return}this.selectDefaultTrack=!1;const r=this.currentTrack,a=n[t]||null;if(this.trackId=t,this.currentTrack=a,this.toggleTrackModes(),!a){this.hls.trigger(Et.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(Et.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 g6n(){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 PK(s){let t=5381,n=s.length;for(;n;)t=t*33^s.charCodeAt(--n);return(t>>>0).toString()}const mz=.025;let eSe=function(s){return s[s.Point=0]="Point",s[s.Range=1]="Range",s}({});function x6n(s,t,n){return`${s.identifier}-${n+1}-${PK(t)}`}class y6n{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 yIe(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=yIe(n,t);return n-r<.1}return!1}get resumptionOffset(){const t=this.resumeOffset,n=bi(t)?t:this.duration;return this.cumulativeDuration+n}get resumeTime(){const t=this.startOffset+this.resumptionOffset;if(this.snapOptions.in){const n=this.resumeAnchor;if(n)return yIe(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 v6n(this)}}function yIe(s,t){return s-t.start":s.cue.post?"":""}${s.timelineStart.toFixed(2)}-${s.resumeTime.toFixed(2)}]`}function g7(s){const t=s.timelineStart,n=s.duration||0;return`["${s.identifier}" ${t.toFixed(2)}-${(t+n).toFixed(2)}]`}class b6n{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(Et.PLAYOUT_LIMIT_REACHED,{})};const i=this.hls=new t(n);this.interstitial=r,this.assetItem=a;const l=()=>{this.hasDetails=!0};i.once(Et.LEVEL_LOADED,l),i.once(Et.AUDIO_TRACK_LOADED,l),i.once(Et.SUBTITLE_TRACK_LOADED,l),i.on(Et.MEDIA_ATTACHING,(o,{media:c})=>{this.removeMediaListeners(),this.mediaAttached=c,this.interstitial.playoutLimit&&(c.addEventListener("timeupdate",this.checkPlayout),this.appendInPlace&&i.on(Et.BUFFER_APPENDED,()=>{const u=this.bufferedEnd;this.reachedPlayout(u)&&(this._bufferedEosTime=u,i.trigger(Et.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=lBt(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=_l.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=_l.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: ${g7(this.assetItem)} ${(t=this.hls)==null?void 0:t.sessionId} ${this.appendInPlace?"append-in-place":""}`}}const Cxt=.033;class _6n extends Ij{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,f=u.cue.pre,g=u.cue.post;if(h&&!f)return-1;if(f&&!h||m&&!g)return 1;if(g&&!m)return-1;if(!h&&!f&&!m&&!g){const y=d.startTime,x=u.startTime;if(y!==x)return y-x}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,f=u.cue.post,g=t[h-1]||null,y=u.appendInPlace,x=f?i:u.startOffset,_=u.duration,b=u.timelineOccupancy===eSe.Range?_:0,k=u.resumptionOffset,A=(g==null?void 0:g.startTime)===x,T=x+u.cumulativeDuration;let P=y?T+_:x+k;if(m||!f&&x<=0){const M=d;d+=b,u.timelineStart=T;const L=l;l+=_,r.push({event:u,start:T,end:P,playout:{start:L,end:l},integrated:{start:M,end:d}})}else if(x<=i){if(!A){const z=x-c;if(z>Cxt){const $=c,V=d;d+=z;const W=l;l+=z;const G={previousEvent:t[h-1]||null,nextEvent:u,start:$,end:$+z,playout:{start:W,end:l},integrated:{start:V,end:d}};r.push(G)}else z>0&&g&&(g.cumulativeDuration+=z,r[r.length-1].end=x)}f&&(P=T),u.timelineStart=T;const M=d;d+=b;const L=l;l+=_,r.push({event:u,start:T,end:P,playout:{start:L,end:l},integrated:{start:M,end:d}})}else return;const I=u.resumeTime;f||I>i?c=i:c=I}),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=MR(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+1mz?(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=MR(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 x=m.data,_=x==null?void 0:x.ASSETS;if(!Array.isArray(_)){const b=this.assignAssetListError(t,lr.ASSET_LIST_PARSING_ERROR,new Error("Invalid interstitial asset list"),g.url,f,y);this.hls.trigger(Et.ERROR,b);return}t.assetListResponse=x,this.hls.trigger(Et.ASSET_LIST_LOADED,{event:t,assetListResponse:x,networkDetails:y})},onError:(m,f,g,y)=>{const x=this.assignAssetListError(t,lr.ASSET_LIST_LOAD_ERROR,new Error(`Error loading X-ASSET-LIST: HTTP status ${m.code} ${m.text} (${f.url})`),f.url,y,g);this.hls.trigger(Et.ERROR,x)},onTimeout:(m,f,g)=>{const y=this.assignAssetListError(t,lr.ASSET_LIST_LOAD_TIMEOUT,new Error(`Timeout loading X-ASSET-LIST (${f.url})`),f.url,m,g);this.hls.trigger(Et.ERROR,y)}};return o.load(c,u,h),this.hls.trigger(Et.ASSET_LIST_LOADING,{event:t}),o}assignAssetListError(t,n,r,a,i,l){return t.error=r,{type:ao.NETWORK_ERROR,details:n,fatal:!1,interstitial:t,url:a,error:r,networkDetails:l,stats:i}}}function Axt(s){var t;s==null||(t=s.play())==null||t.catch(()=>{})}function qF(s,t){return`[${s}] Advancing timeline position to ${t}`}class j6n extends Ij{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 f=this.findItemIndex(o);let g=this.schedule.findItemIndexAtTime(r);if(g===-1&&(g=f+(l?-1:1),this.log(`seeked ${l?"back ":""}to position not covered by schedule ${r} (resolving from ${f} to ${g})`)),!this.isInterstitial(o)&&(c=this.media)!=null&&c.paused&&(this.shouldPlay=!1),!l&&g>f){const y=this.schedule.findJumpRestrictedIndex(f+1,g);if(y>f){this.setSchedulePosition(y);return}}this.setSchedulePosition(g);return}const d=this.playingAsset;if(!d){if(this.playingLastItem&&this.isInterstitial(o)){const f=o.event.assetList[0];f&&(this.endedItem=this.playingItem,this.playingItem=null,this.setScheduleToAssetAtTime(r,f))}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=>i2(y))} pos: ${this.timelinePos}`),u.length&&this.log(`Removed events ${u}`);let m=null,f=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 g=this.bufferingItem;if(g&&(f=this.updateItem(g,this.bufferedPos),this.itemsMatch(g,f)?this.bufferingItem=f:g.event&&(this.bufferingItem=this.playingItem,this.clearInterstitial(g.event,null))),r.forEach(y=>{y.assetList.forEach(x=>{this.clearAssetPlayer(x.identifier,null)})}),this.playerQueue.forEach(y=>{if(y.interstitial.appendInPlace){const x=y.assetItem.timelineStart,_=y.timelineOffset-x;if(_)try{y.timelineOffset=x}catch(b){Math.abs(_)>mz&&this.warn(`${b} ("${y.assetId}" ${y.timelineOffset}->${x})`)}}}),h||a){if(this.hls.trigger(Et.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),g&&f!==m&&this.trimInPlace(f,g),this.checkBuffer()}},this.hls=t,this.HlsPlayerClass=n,this.assetListLoader=new w6n(t),this.schedule=new _6n(this.onScheduleUpdate,t.logger),this.registerListeners()}registerListeners(){const t=this.hls;t&&(t.on(Et.MEDIA_ATTACHING,this.onMediaAttaching,this),t.on(Et.MEDIA_ATTACHED,this.onMediaAttached,this),t.on(Et.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(Et.MANIFEST_LOADING,this.onManifestLoading,this),t.on(Et.LEVEL_UPDATED,this.onLevelUpdated,this),t.on(Et.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),t.on(Et.AUDIO_TRACK_UPDATED,this.onAudioTrackUpdated,this),t.on(Et.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),t.on(Et.SUBTITLE_TRACK_UPDATED,this.onSubtitleTrackUpdated,this),t.on(Et.EVENT_CUE_ENTER,this.onInterstitialCueEnter,this),t.on(Et.ASSET_LIST_LOADED,this.onAssetListLoaded,this),t.on(Et.BUFFER_APPENDED,this.onBufferAppended,this),t.on(Et.BUFFER_FLUSHED,this.onBufferFlushed,this),t.on(Et.BUFFERED_TO_END,this.onBufferedToEnd,this),t.on(Et.MEDIA_ENDED,this.onMediaEnded,this),t.on(Et.ERROR,this.onError,this),t.on(Et.DESTROYING,this.onDestroying,this))}unregisterListeners(){const t=this.hls;t&&(t.off(Et.MEDIA_ATTACHING,this.onMediaAttaching,this),t.off(Et.MEDIA_ATTACHED,this.onMediaAttached,this),t.off(Et.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(Et.MANIFEST_LOADING,this.onManifestLoading,this),t.off(Et.LEVEL_UPDATED,this.onLevelUpdated,this),t.off(Et.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),t.off(Et.AUDIO_TRACK_UPDATED,this.onAudioTrackUpdated,this),t.off(Et.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),t.off(Et.SUBTITLE_TRACK_UPDATED,this.onSubtitleTrackUpdated,this),t.off(Et.EVENT_CUE_ENTER,this.onInterstitialCueEnter,this),t.off(Et.ASSET_LIST_LOADED,this.onAssetListLoaded,this),t.off(Et.BUFFER_CODECS,this.onBufferCodecs,this),t.off(Et.BUFFER_APPENDED,this.onBufferAppended,this),t.off(Et.BUFFER_FLUSHED,this.onBufferFlushed,this),t.off(Et.BUFFERED_TO_END,this.onBufferedToEnd,this),t.off(Et.MEDIA_ENDED,this.onMediaEnded,this),t.off(Et.ERROR,this.onError,this),t.off(Et.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){X1(t,"play",this.onPlay),X1(t,"pause",this.onPause),X1(t,"seeking",this.onSeeking),X1(t,"timeupdate",this.onTimeupdate)}onMediaAttaching(t,n){const r=this.media=n.media;qv(r,"seeking",this.onSeeking),qv(r,"timeupdate",this.onTimeupdate),qv(r,"play",this.onPlay),qv(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,f,g,y)=>{if(h){let x=h[m].start;const _=h.event;if(_){if(m==="playout"||_.timelineOccupancy!==eSe.Point){const b=r(f);(b==null?void 0:b.interstitial)===_&&(x+=b.assetItem.startOffset+b[y])}}else{const b=g==="bufferedPos"?l():t[g];x+=b-h.start}return x}return 0},i=(h,m)=>{var f;if(h!==0&&m!=="primary"&&(f=t.schedule)!=null&&f.length){var g;const y=t.schedule.findItemIndexAtTime(h),x=(g=t.schedule.items)==null?void 0:g[y];if(x){const _=x[m].start-x.start;return h+_}}return h},l=()=>{const h=t.bufferedPos;return h===Number.MAX_VALUE?o("primary"):Math.max(h,0)},o=h=>{var m,f;return(m=t.primaryDetails)!=null&&m.live?t.primaryDetails.edge:((f=t.schedule)==null?void 0:f.durations[h])||0},c=(h,m)=>{var f,g;const y=t.effectivePlayingItem;if(y!=null&&(f=y.event)!=null&&f.restrictions.skip||!t.schedule)return;t.log(`seek to ${h} "${m}"`);const x=t.effectivePlayingItem,_=t.schedule.findItemIndexAtTime(h,m),b=(g=t.schedule.items)==null?void 0:g[_],k=t.getBufferingPlayer(),A=k==null?void 0:k.interstitial,T=A==null?void 0:A.appendInPlace,P=x&&t.itemsMatch(x,b);if(x&&(T||P)){const I=r(t.playingAsset),M=(I==null?void 0:I.media)||t.primaryMedia;if(M){const L=m==="primary"?M.currentTime:a(x,m,t.playingAsset,"timelinePos","currentTime"),z=h-L,$=(T?L:M.currentTime)+z;if($>=0&&(!I||T||$<=I.duration)){M.currentTime=$;return}}}if(b){let I=h;if(m!=="primary"){const L=b[m].start,z=h-L;I=b.start+z}const M=!t.isInterstitial(b);if((!t.isInterstitial(x)||x.event.appendInPlace)&&(M||b.event.appendInPlace)){const L=t.media||(T?k==null?void 0:k.media:null);L&&(L.currentTime=I)}else if(x){const L=t.findItemIndex(x);if(_>L){const $=t.schedule.findJumpRestrictedIndex(L+1,_);if($>L){t.setSchedulePosition($);return}}let z=0;if(M)t.timelinePos=I,t.checkBuffer();else{const $=b.event.assetList,V=h-(b[m]||b).start;for(let W=$.length;W--;){const G=$[W];if(G.duration&&V>=G.startOffset&&V{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 f;return a(m,"playout",t.bufferingAsset,"bufferedPos","bufferedEnd")-m.playout.start||((f=t.bufferingAsset)==null?void 0:f.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(),f=t.effectivePlayingItem;f&&f===m&&c(h+f.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(f=>t.getAssetPlayer(f.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 f=t.findItemIndex(h);if(m.appendInPlace){const g=h.playout.start+h.event.duration;c(g+.001,"playout")}else t.advanceAfterAssetEnded(m,f,1/0)}}}}get effectivePlayingItem(){return this.waitingItem||this.playingItem||this.endedItem}get effectivePlayingAsset(){return this.playingAsset||this.endedAsset}get playingLastItem(){var t;const n=this.playingItem,r=(t=this.schedule)==null?void 0:t.items;return!this.playbackStarted||!n||!r?!1:this.findItemIndex(n)===r.length-1}get playbackStarted(){return this.effectivePlayingItem!==null}get currentTime(){var t,n;if(this.mediaSelection===null)return;const r=this.waitingItem||this.playingItem;if(this.isInterstitial(r)&&!r.event.appendInPlace)return;let a=this.media;!a&&(t=this.bufferingItem)!=null&&(t=t.event)!=null&&t.appendInPlace&&(a=this.primaryMedia);const i=(n=a)==null?void 0:n.currentTime;if(!(i===void 0||!bi(i)))return i}get primaryMedia(){var t;return this.media||((t=this.detachedData)==null?void 0:t.media)||null}isInterstitial(t){return!!(t!=null&&t.event)}retreiveMediaSource(t,n){const r=this.getAssetPlayer(t);r&&this.transferMediaFromPlayer(r,n)}transferMediaFromPlayer(t,n){const r=t.interstitial.appendInPlace,a=t.media;if(r&&a===this.primaryMedia){if(this.bufferingAsset=null,(!n||this.isInterstitial(n)&&!n.event.appendInPlace)&&n&&a){this.detachedData={media:a};return}const i=t.transferMedia();this.log(`transfer MediaSource from ${t} ${bh(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 g=this.getBufferingPlayer();g?(i=g.transferMedia(),u=`${g}`):u="detached MediaSource"}else u="detached media";if(!i){if(d)i=this.detachedData,this.log(`using detachedData: MediaSource ${bh(i)}`);else if(!this.detachedData||l.media===n){const g=this.playerQueue;g.length>1&&g.forEach(y=>{if(o&&y.interstitial.appendInPlace!==c){const x=y.interstitial;this.clearInterstitial(y.interstitial,null),x.appendInPlace=!1,x.appendInPlace&&this.warn(`Could not change append strategy for queued assets ${x}`)}}),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 f=this.schedule;if(m===i&&f){const g=o&&t.assetId===f.assetIdAtEnd;m.overrides={duration:f.duration,endOfStream:!o||g,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(qF("checkStart (preroll)",i));const l=t.findEventIndex(n[0].identifier);this.setSchedulePosition(l)}else if(i>=0||!this.primaryLive){this.log(qF("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(qF("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=vIe(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=vIe(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&&i2(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,f=m?this.getAssetPlayer(m):null;if(f&&m&&(!this.eventItemsMatch(l,i)||n!==void 0&&m!==u.assetList[n].identifier)){var c;const g=u.findAssetIndex(h);if(this.log(`INTERSTITIAL_ASSET_ENDED ${g+1}/${u.assetList.length} ${g7(h)}`),this.endedAsset=h,this.playingAsset=null,this.hls.trigger(Et.INTERSTITIAL_ASSET_ENDED,{asset:h,assetListIndex:g,event:u,schedule:a.slice(0),scheduleIndex:t,player:f}),l!==this.playingItem){this.itemsMatch(l,this.playingItem)&&!this.playingAsset&&this.advanceAfterAssetEnded(u,this.findItemIndex(this.playingItem),g);return}this.retreiveMediaSource(m,i),f.media&&!((c=this.detachedData)!=null&&c.mediaSource)&&f.detachMedia()}if(!this.eventItemsMatch(l,i)&&(this.endedItem=l,this.playingItem=null,this.log(`INTERSTITIAL_ENDED ${u} ${i2(l)}`),u.hasPlayed=!0,this.hls.trigger(Et.INTERSTITIAL_ENDED,{event:u,schedule:a.slice(0),scheduleIndex:t}),u.cue.once)){var d;this.updateSchedule();const g=(d=this.schedule)==null?void 0:d.items;if(i&&g){const y=this.findItemIndex(i);this.advanceSchedule(y,g,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 g=vIe(u,r-1);if(u.isAssetPastPlayoutLimit(g)||u.appendInPlace&&this.timelinePos===o.end){this.advanceAfterAssetEnded(u,t,r);return}r=g}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 ${i2(o)} ${u.appendInPlace?"append in place":""}`),this.hls.trigger(Et.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 f=u.assetList[r];if(!f){this.advanceAfterAssetEnded(u,t,r||0);return}if(m||(m=this.getAssetPlayer(f.identifier)),m===null||m.destroyed){const g=u.assetList.length;this.warn(`asset ${r+1}/${g} player destroyed ${u}`),m=this.createAssetPlayer(u,f,r),m.loadSource()}if(!this.eventItemsMatch(o,this.bufferingItem)&&u.appendInPlace&&this.isAssetBuffered(f))return;this.startAssetPlayer(m,r,n,t,c),this.shouldPlay&&Axt(m.media)}else o?(this.resumePrimary(o,t,a),this.shouldPlay&&Axt(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 ${i2(t)}`),!((a=this.detachedData)!=null&&a.mediaSource)){let o=this.timelinePos;(o=t.end)&&(o=this.getPrimaryResumption(t,n),this.log(qF("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 ${i2(t)}`),this.hls.trigger(Et.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:_l.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(qF("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(Et.BUFFER_CODECS,this.onBufferCodecs,this),this.hls.on(Et.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=$u($u({},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=$u($u({},this.altSelection),{},{audio:r});return}const i=$u($u({},a),{},{audio:r});this.mediaSelection=i}onSubtitleTrackUpdated(t,n){const r=this.hls.subtitleTracks[n.id],a=this.mediaSelection;if(!a){this.altSelection=$u($u({},this.altSelection),{},{subtitles:r});return}const i=$u($u({},a),{},{subtitles:r});this.mediaSelection=i}onAudioTrackSwitching(t,n){const r=Ogt(n);this.playerQueue.forEach(({hls:a})=>a&&(a.setAudioOption(n)||a.setAudioOption(r)))}onSubtitleTrackSwitch(t,n){const r=Ogt(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=_l.bufferInfo(this.primaryMedia,r,0);(a.end>r||(a.nextStart||0)>r)&&(this.log(`trim buffered interstitial ${i2(t)} (was ${i2(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=_l.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 f=i.event;if(h-o>1&&f.appendInPlace===!1||f.assetList.length===0&&f.assetListLoader)return}if(this.bufferedPos=t,c>u&&c>o)this.bufferedToItem(m);else{const f=this.primaryDetails;this.primaryLive&&f&&t>f.edge-f.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 ${i2(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(Et.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(Et.BUFFER_FLUSHING,{startOffset:t,endOffset:1/0,type:a})})}getAssetPlayerQueueIndex(t){const n=this.playerQueue;for(let r=0;r1){const T=n.duration;T&&A{if(A.live){var T;const M=new Error(`Interstitials MUST be VOD assets ${t}`),L={fatal:!0,type:ao.OTHER_ERROR,details:lr.INTERSTITIAL_ASSET_ITEM_ERROR,error:M},z=((T=this.schedule)==null?void 0:T.findEventIndex(t.identifier))||-1;this.handleAssetItemError(L,t,z,r,M.message);return}const P=A.edge-A.fragmentStart,I=n.duration;(y||I===null||P>I)&&(y=!1,this.log(`Interstitial asset "${h}" duration change ${I} > ${P}`),n.duration=P,this.updateSchedule())};g.on(Et.LEVEL_UPDATED,(A,{details:T})=>x(T)),g.on(Et.LEVEL_PTS_UPDATED,(A,{details:T})=>x(T)),g.on(Et.EVENT_CUE_ENTER,()=>this.onInterstitialCueEnter());const _=(A,T)=>{const P=this.getAssetPlayer(h);if(P&&T.tracks){P.off(Et.BUFFER_CODECS,_),P.tracks=T.tracks;const I=this.primaryMedia;this.bufferingAsset===P.assetItem&&I&&!P.media&&this.bufferAssetPlayer(P,I)}};g.on(Et.BUFFER_CODECS,_);const b=()=>{var A;const T=this.getAssetPlayer(h);if(this.log(`buffered to end of asset ${T}`),!T||!this.schedule)return;const P=this.schedule.findEventIndex(t.identifier),I=(A=this.schedule.items)==null?void 0:A[P];this.isInterstitial(I)&&this.advanceAssetBuffering(I,n)};g.on(Et.BUFFERED_TO_END,b);const k=A=>()=>{if(!this.getAssetPlayer(h)||!this.schedule)return;this.shouldPlay=!0;const P=this.schedule.findEventIndex(t.identifier);this.advanceAfterAssetEnded(t,P,A)};return g.once(Et.MEDIA_ENDED,k(r)),g.once(Et.PLAYOUT_LIMIT_REACHED,k(1/0)),g.on(Et.ERROR,(A,T)=>{if(!this.schedule)return;const P=this.getAssetPlayer(h);if(T.details===lr.BUFFER_STALLED_ERROR){if(P!=null&&P.appendInPlace){this.handleInPlaceStall(t);return}this.onTimeupdate(),this.checkBuffer(!0);return}this.handleAssetItemError(T,t,this.schedule.findEventIndex(t.identifier),r,`Asset player error ${T.error} ${t}`)}),g.on(Et.DESTROYING,()=>{if(!this.getAssetPlayer(h)||!this.schedule)return;const T=new Error(`Asset player destroyed unexpectedly ${h}`),P={fatal:!0,type:ao.OTHER_ERROR,details:lr.INTERSTITIAL_ASSET_ITEM_ERROR,error:T};this.handleAssetItemError(P,t,this.schedule.findEventIndex(t.identifier),r,T.message)}),this.log(`INTERSTITIAL_ASSET_PLAYER_CREATED ${g7(n)}`),this.hls.trigger(Et.INTERSTITIAL_ASSET_PLAYER_CREATED,{asset:n,assetListIndex:r,event:t,player:g}),g}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&&i2(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} ${g7(o)}`),this.hls.trigger(Et.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&&!V9t(h,t.tracks)){const m=new Error(`Asset ${g7(l)} SourceBuffer tracks ('${Object.keys(t.tracks)}') are not compatible with primary content tracks ('${Object.keys(h)}')`),f={fatal:!0,type:ao.OTHER_ERROR,details:lr.INTERSTITIAL_ASSET_ITEM_ERROR,error:m},g=i.findAssetIndex(l);this.handleAssetItemError(f,i,o,g,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=g;else for(let y=a;y{const _=parseFloat(y.DURATION);this.createAsset(i,x,u,c+u,_,y.URI),u+=_}),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 f=(a=this.bufferingItem)==null?void 0:a.event;if(m){var g;const y=this.schedule.findEventIndex(l),x=(g=this.schedule.items)==null?void 0:g[y];if(x){if(!this.playingItem&&this.timelinePos>x.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(x)}this.setSchedulePosition(y)}else if((f==null?void 0:f.identifier)===l){const y=i.assetList[0];if(y){const x=this.getAssetPlayer(y.identifier);if(f.appendInPlace){const _=this.primaryMedia;x&&_&&this.bufferAssetPlayer(x,_)}else x&&x.loadSource()}}}onError(t,n){if(this.schedule)switch(n.details){case lr.ASSET_LIST_PARSING_ERROR:case lr.ASSET_LIST_LOAD_ERROR:case lr.ASSET_LIST_LOAD_TIMEOUT:{const r=n.interstitial;r&&(this.updateSchedule(!0),this.primaryFallback(r));break}case lr.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 Txt=500;class N6n extends pKe{constructor(t,n,r){super(t,n,r,"subtitle-stream-controller",Ri.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(Et.LEVEL_LOADED,this.onLevelLoaded,this),t.on(Et.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),t.on(Et.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),t.on(Et.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),t.on(Et.SUBTITLE_FRAG_PROCESSED,this.onSubtitleFragProcessed,this),t.on(Et.BUFFER_FLUSHING,this.onBufferFlushing,this)}unregisterListeners(){super.unregisterListeners();const{hls:t}=this;t.off(Et.LEVEL_LOADED,this.onLevelLoaded,this),t.off(Et.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),t.off(Et.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),t.off(Et.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),t.off(Et.SUBTITLE_FRAG_PROCESSED,this.onSubtitleFragProcessed,this),t.off(Et.BUFFER_FLUSHING,this.onBufferFlushing,this)}startLoad(t,n){this.stopLoad(),this.state=Ur.IDLE,this.setInterval(Txt),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)||($f(r)&&(this.fragPrevious=r),this.state=Ur.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 OZ(r));return}this.tracksBuffered=[],this.levels=n.map(r=>{const a=new OZ(r);return this.tracksBuffered[a.id]=[],a}),this.fragmentTracker.removeFragmentsInRange(0,Number.POSITIVE_INFINITY,Ri.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!==Ur.STOPPED&&this.setInterval(Txt)}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?(Q5e(l,h),d=l.fragmentStart):m&&(d=m.start,Mze(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,Mze(l,d))}h&&!this.startFragRequested&&this.setStartPosition(h,d)}c.details=l,this.levelLastLoaded=c,o===a&&(this.hls.trigger(Et.SUBTITLE_TRACK_UPDATED,{details:l,id:o,groupId:n.groupId}),this.tick(),l.live&&!this.fragCurrent&&this.media&&this.state===Ur.IDLE&&(MR(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&&uz(a.method)){const l=performance.now();this.decrypter.decrypt(new Uint8Array(r),a.key.buffer,a.iv.buffer,hKe(a.method)).catch(o=>{throw i.trigger(Et.ERROR,{type:ao.MEDIA_ERROR,details:lr.FRAG_DECRYPT_ERROR,fatal:!1,error:o,reason:o.message,frag:n}),o}).then(o=>{const c=performance.now();i.trigger(Et.FRAG_DECRYPTED,{frag:n,payload:o,stats:{tstart:l,tdecrypt:c}})}).catch(o=>{this.warn(`${o.name}: ${o.message}`),this.state=Ur.IDLE})}}doTick(){if(!this.media){this.state=Ur.IDLE;return}if(this.state===Ur.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=_l.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,f=d.edge;let g=null;const y=this.fragPrevious;if(of-b?0:b;g=MR(y,h,Math.max(h[0].start,o),k),!g&&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 S6n={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},cBt=s=>String.fromCharCode(S6n[s]||s),d2=15,HS=100,C6n={17:1,18:3,21:5,22:7,23:9,16:11,19:12,20:14},A6n={17:2,18:4,21:6,22:8,23:10,19:13,20:15},T6n={25:1,26:3,29:5,30:7,31:9,24:11,27:12,28:14},E6n={25:2,26:4,29:6,30:8,31:10,27:13,28:15},M6n=["white","green","blue","cyan","red","yellow","magenta","black","transparent"];class L6n{constructor(){this.time=null,this.verboseLevel=0}log(t,n){if(this.verboseLevel>=t){const r=typeof n=="function"?n():n;Gu.log(`${this.time} [${t}] ${r}`)}}}const G6=function(t){const n=[];for(let r=0;rHS&&(this.logger.log(3,"Too large cursor position "+this.pos),this.pos=HS)}moveCursor(t){const n=this.pos+t;if(t>1)for(let r=this.pos+1;r=144&&this.backSpace();const n=cBt(t);if(this.pos>=HS){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 = "+bh(t));let n=t.row-1;if(this.nrRollUpRows&&n"bkgData = "+bh(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 Ext{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 bIe(r),this.nonDisplayedMemory=new bIe(r),this.lastOutputScreen=new bIe(r),this.currRollUpRow=this.displayedMemory.rows[d2-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[d2-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: "+bh(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 Mxt{constructor(t,n,r){this.channels=void 0,this.currentChannel=0,this.cmdHistory=R6n(),this.logger=void 0;const a=this.logger=new L6n;this.channels=[null,new Ext(t,n,a),new Ext(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"["+G6([n[r],n[r+1]])+"] -> ("+G6([a,i])+")");const c=this.cmdHistory;if(a>=16&&a<=31){if(D6n(a,i,c)){Vne(null,null,c),this.logger.log(3,()=>"Repeated command ("+G6([a,i])+") is dropped");continue}Vne(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 Vne(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 "+G6([a,i])+" orig: "+G6([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 ("+G6([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?C6n[t]:T6n[t]:r=l===1?A6n[t]:E6n[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 '"+cBt(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 = "+G6(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=M6n[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.");P=z,this.hasBeenReset=!0}})),Object.defineProperty(u,"positionAlign",i({},h,{get:function(){return I},set:function(z){const $=a(z);if(!$)throw new SyntaxError("An invalid or illegal string was specified.");I=$,this.hasBeenReset=!0}})),Object.defineProperty(u,"size",i({},h,{get:function(){return M},set:function(z){if(z<0||z>100)throw new Error("Size must be between 0 and 100.");M=z,this.hasBeenReset=!0}})),Object.defineProperty(u,"align",i({},h,{get:function(){return L},set:function(z){const $=a(z);if(!$)throw new SyntaxError("An invalid or illegal string was specified.");L=$,this.hasBeenReset=!0}})),u.displayState=void 0}return l.prototype.getCueAsHTML=function(){return self.WebVTT.convertCueToDOMTree(self,this.text)},l}();class O6n{decode(t,n){if(!t)return"";if(typeof t!="string")throw new Error("Error - expected string data.");return decodeURIComponent(encodeURIComponent(t))}}function uBt(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 F6n{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 hBt(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 zze=new SKe(0,0,""),Hne=zze.align==="middle"?"middle":"center";function z6n(s,t,n){const r=s;function a(){const o=uBt(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 F6n;hBt(o,function(m,f){let g;switch(m){case"region":for(let y=n.length-1;y>=0;y--)if(n[y].id===f){d.set(m,n[y].region);break}break;case"vertical":d.alt(m,f,["rl","lr"]);break;case"line":g=f.split(","),d.integer(m,g[0]),d.percent(m,g[0])&&d.set("snapToLines",!1),d.alt(m,g[0],["auto"]),g.length===2&&d.alt("lineAlign",g[1],["start",Hne,"end"]);break;case"position":g=f.split(","),d.percent(m,g[0]),g.length===2&&d.alt("positionAlign",g[1],["start",Hne,"end","line-left","line-right","auto"]);break;case"size":d.percent(m,f);break;case"align":d.alt(m,f,["start",Hne,"end","left","right"]);break}},/:/,/\s/),c.region=d.get("region",null),c.vertical=d.get("vertical","");let u=d.get("line","auto");u==="auto"&&zze.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",Hne);let h=d.get("position","auto");h==="auto"&&zze.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 mBt(s){return s.replace(//gi,` `)}class B6n{constructor(){this.state="INITIAL",this.buffer="",this.decoder=new O6n,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=mBt(i);l")===-1){n.cue.id=i;continue}case"CUE":if(!n.cue){n.state="BADCUE";continue}try{z6n(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 $6n=/\r\n|\n\r|\n|\r/g,_Ie=function(t,n,r=0){return t.slice(r,r+n.length)===n},U6n=function(t){let n=parseInt(t.slice(-3));const r=parseInt(t.slice(-6,-4)),a=parseInt(t.slice(-9,-7)),i=t.length>9?parseInt(t.substring(0,t.indexOf(":"))):0;if(!bi(n)||!bi(r)||!bi(a)||!bi(i))throw Error(`Malformed X-TIMESTAMP-MAP: Local:${t}`);return n+=1e3*r,n+=60*1e3*a,n+=60*60*1e3*i,n};function CKe(s,t,n){return PK(s.toString())+PK(t.toString())+PK(n)}const q6n=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 V6n(s,t,n,r,a,i,l){const o=new B6n,c=z_(new Uint8Array(s)).trim().replace($6n,` `).split(` `),d=[],u=t?ZTn(t.baseTime,t.timescale):0;let h="00:00.000",m=0,f=0,g,y=!0;o.oncue=function(x){const _=n[r];let b=n.ccOffset;const k=(m-u)/9e4;if(_!=null&&_.new&&(f!==void 0?b=n.ccOffset=_.start:q6n(n,r,k)),k){if(!t){g=new Error("Missing initPTS for VTT MPEGTS");return}b=k-n.presentationOffset}const A=x.endTime-x.startTime,T=d_((x.startTime+b-f)*9e4,a*9e4)/9e4;x.startTime=Math.max(T,0),x.endTime=Math.max(T+A,0);const P=x.text.trim();x.text=decodeURIComponent(encodeURIComponent(P)),x.id||(x.id=CKe(x.startTime,x.endTime,P)),x.endTime>0&&d.push(x)},o.onparsingerror=function(x){g=x},o.onflush=function(){if(g){l(g);return}i(d)},c.forEach(x=>{if(y)if(_Ie(x,"X-TIMESTAMP-MAP=")){y=!1,x.slice(16).split(",").forEach(_=>{_Ie(_,"LOCAL:")?h=_.slice(6):_Ie(_,"MPEGTS:")&&(m=parseInt(_.slice(7)))});try{f=U6n(h)/1e3}catch(_){g=_}return}else x===""&&(y=!1);o.parse(x+` `)}),o.flush()}const wIe="stpp.ttml.im1t",pBt=/^(\d{2,}):(\d{2}):(\d{2}):(\d{2})\.?(\d+)?$/,fBt=/^(\d*(?:\.\d*)?)(h|m|s|ms|f|t)$/,H6n={left:"start",center:"center",right:"end",start:"start",end:"end"};function Lxt(s,t,n,r){const a=wc(new Uint8Array(s),["mdat"]);if(a.length===0){r(new Error("Could not parse IMSC1 mdat"));return}const i=a.map(o=>z_(o)),l=YTn(t.baseTime,1,t.timescale);try{i.forEach(o=>n(G6n(o,l)))}catch(o){r(o)}}function G6n(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=Pxt(jIe(a,"styling","style")),d=Pxt(jIe(a,"layout","region")),u=jIe(a,"body","[begin]");return[].map.call(u,h=>{const m=gBt(h,o);if(!m||!h.hasAttribute("begin"))return null;const f=kIe(h.getAttribute("begin"),l),g=kIe(h.getAttribute("dur"),l);let y=kIe(h.getAttribute("end"),l);if(f===null)throw Ixt(h);if(y===null){if(g===null)throw Ixt(h);y=f+g}const x=new SKe(f-t,y-t,m);x.id=CKe(x.startTime,x.endTime,x.text);const _=d[h.getAttribute("region")],b=c[h.getAttribute("style")],k=W6n(_,b,c),{textAlign:A}=k;if(A){const T=H6n[A];T&&(x.lineAlign=T),x.align=A}return rh(x,k),x}).filter(h=>h!==null)}function jIe(s,t,n){const r=s.getElementsByTagName(t)[0];return r?[].slice.call(r.querySelectorAll(n)):[]}function Pxt(s){return s.reduce((t,n)=>{const r=n.getAttribute("xml:id");return r&&(t[r]=n),t},{})}function gBt(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?gBt(r,t):t?n+r.textContent.trim().replace(/\s+/g," "):n+r.textContent},"")}function W6n(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=NIe(t,r,c)||NIe(s,r,c)||NIe(a,r,c);return d&&(o[c]=d),o},{})}function NIe(s,t,n){return s&&s.hasAttributeNS(t,n)?s.getAttributeNS(t,n):null}function Ixt(s){return new Error(`Could not parse ttml timestamp ${s}`)}function kIe(s,t){if(!s)return null;let n=uBt(s);return n===null&&(pBt.test(s)?n=K6n(s,t):fBt.test(s)&&(n=Y6n(s,t))),n}function K6n(s,t){const n=pBt.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 Y6n(s,t){const n=fBt.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 Gne{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 Z6n{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=Rxt(),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(Et.MEDIA_ATTACHING,this.onMediaAttaching,this),t.on(Et.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(Et.MANIFEST_LOADING,this.onManifestLoading,this),t.on(Et.MANIFEST_LOADED,this.onManifestLoaded,this),t.on(Et.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),t.on(Et.FRAG_LOADING,this.onFragLoading,this),t.on(Et.FRAG_LOADED,this.onFragLoaded,this),t.on(Et.FRAG_PARSING_USERDATA,this.onFragParsingUserdata,this),t.on(Et.FRAG_DECRYPTED,this.onFragDecrypted,this),t.on(Et.INIT_PTS_FOUND,this.onInitPtsFound,this),t.on(Et.SUBTITLE_TRACKS_CLEARED,this.onSubtitleTracksCleared,this),t.on(Et.BUFFER_FLUSHING,this.onBufferFlushing,this)}destroy(){const{hls:t}=this;t.off(Et.MEDIA_ATTACHING,this.onMediaAttaching,this),t.off(Et.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(Et.MANIFEST_LOADING,this.onManifestLoading,this),t.off(Et.MANIFEST_LOADED,this.onManifestLoaded,this),t.off(Et.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),t.off(Et.FRAG_LOADING,this.onFragLoading,this),t.off(Et.FRAG_LOADED,this.onFragLoaded,this),t.off(Et.FRAG_PARSING_USERDATA,this.onFragParsingUserdata,this),t.off(Et.FRAG_DECRYPTED,this.onFragDecrypted,this),t.off(Et.INIT_PTS_FOUND,this.onInitPtsFound,this),t.off(Et.SUBTITLE_TRACKS_CLEARED,this.onSubtitleTracksCleared,this),t.off(Et.BUFFER_FLUSHING,this.onBufferFlushing,this),this.hls=this.config=this.media=null,this.cea608Parser1=this.cea608Parser2=void 0}initCea608Parsers(){const t=new Gne(this,"textTrack1"),n=new Gne(this,"textTrack2"),r=new Gne(this,"textTrack3"),a=new Gne(this,"textTrack4");this.cea608Parser1=new Mxt(1,t,n),this.cea608Parser2=new Mxt(3,r,a)}addCues(t,n,r,a,i){let l=!1;for(let o=i.length;o--;){const c=i[o],d=X6n(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(Et.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===Ri.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(Et.FRAG_LOADED,c):this.hls.trigger(Et.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{K7(a[i]),delete a[i]}),this.nonNativeCaptionsTracks={}}onManifestLoading(){this.lastCc=-1,this.lastSn=-1,this.lastPartIndex=-1,this.prevCC=-1,this.vttCCs=Rxt(),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===wIe);if(this.config.enableWebVTT||a&&this.config.enableIMSC1){if(Wzt(this.tracks,r)){this.tracks=r;return}if(this.textTracks=[],this.tracks=r,this.config.renderTextTracksNatively){const l=this.media,o=l?Kje(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(Et.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===Ri.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===Ri.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===wIe?this._parseIMSC1(r,a):this._parseVTTs(n)}}else this.hls.trigger(Et.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:r,error:new Error("Empty subtitle payload")})}_parseIMSC1(t,n){const r=this.hls;Lxt(n,this.initPTS[t.cc],a=>{this._appendCues(a,t.level),r.trigger(Et.SUBTITLE_FRAG_PROCESSED,{success:!0,frag:t})},a=>{r.logger.log(`Failed to parse IMSC1: ${a}`),r.trigger(Et.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?Sj(r.initSegment.data,new Uint8Array(a)).buffer:a;V6n(d,this.initPTS[r.cc],this.vttCCs,r.cc,r.start,u=>{this._appendCues(u,r.level),c.trigger(Et.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(Et.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:r,error:u})})}_fallbackToIMSC1(t,n){const r=this.tracks[t.level];r.textCodec||Lxt(n,this.initPTS[t.cc],()=>{r.textCodec=wIe,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=>oBt(a,i))}else{const a=this.tracks[n];if(!a)return;const i=a.default?"default":"subtitles"+n;r.trigger(Et.CUES_PARSED,{type:"subtitles",cues:t,track:i})}}onFragDecrypted(t,n){const{frag:r}=n;r.type===Ri.SUBTITLE&&this.onFragLoaded(Et.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===Ri.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 f=mBt(d.trim()),g=CKe(t,n,f);s!=null&&(h=s.cues)!=null&&h.getCueById(g)||(l=new u(t,n,f),l.id=g,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,f)=>m.line==="auto"||f.line==="auto"?0:m.line>8&&f.line>8?f.line-m.line:m.line-f.line),a.forEach(m=>oBt(s,m))),a}};function eMn(){if(self.fetch&&self.AbortController&&self.ReadableStream&&self.Request)try{return new self.ReadableStream({}),!0}catch{}return!1}const tMn=/(\d+)-(\d+)\/(\d+)/;class Oxt{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||aMn,this.controller=new self.AbortController,this.stats=new aKe}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=sMn(t,this.controller.signal),l=t.responseType==="arraybuffer",o=l?"byteLength":"length",{maxTimeToFirstByteMs:c,maxLoadTimeMs:d}=n.loadPolicy;this.context=t,this.config=n,this.callbacks=r,this.request=this.fetchSetup(t,i),self.clearTimeout(this.requestTimeout),n.timeout=c&&bi(c)?c:d,this.requestTimeout=self.setTimeout(()=>{this.callbacks&&(this.abortInternal(),this.callbacks.onTimeout(a,t,this.response))},n.timeout),(BZ(this.request)?this.request.then(self.fetch):self.fetch(this.request)).then(h=>{var m;this.response=this.loader=h;const f=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-(f-a.loading.start)),!h.ok){const{status:y,statusText:x}=h;throw new iMn(x||"fetch, bad network response",y,h)}a.loading.first=f,a.total=rMn(h.headers)||a.total;const g=(m=this.callbacks)==null?void 0:m.onProgress;return g&&bi(n.highWaterMark)?this.loadProgressively(h,a,t,n.highWaterMark,g):l?h.arrayBuffer():t.responseType==="json"?h.json():h.text()}).then(h=>{var m,f;const g=this.response;if(!g)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 x={url:g.url,data:h,code:g.status},_=(m=this.callbacks)==null?void 0:m.onProgress;_&&!bi(n.highWaterMark)&&_(a,t,h,g),(f=this.callbacks)==null||f.onSuccess(x,a,t,g)}).catch(h=>{var m;if(self.clearTimeout(this.requestTimeout),a.aborted)return;const f=h&&h.code||0,g=h?h.message:null;(m=this.callbacks)==null||m.onError({code:f,text:g},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 Czt,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 sMn(s,t){const n={method:"GET",mode:"cors",credentials:"same-origin",signal:t,headers:new self.Headers(rh({},s.headers))};return s.rangeEnd&&n.headers.set("Range","bytes="+s.rangeStart+"-"+String(s.rangeEnd-1)),n}function nMn(s){const t=tMn.exec(s);if(t)return parseInt(t[2])-parseInt(t[1])+1}function rMn(s){const t=s.get("Content-Range");if(t){const r=nMn(t);if(bi(r))return r}const n=s.get("Content-Length");if(n)return parseInt(n)}function aMn(s,t){return new self.Request(s.url,t)}class iMn extends Error{constructor(t,n,r){super(t),this.code=void 0,this.details=void 0,this.code=n,this.details=r}}const oMn=/^age:\s*[\d.]+\s*$/im;class yBt{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 aKe,this.retryDelay=0}destroy(){this.callbacks=null,this.abortInternal(),this.loader=null,this.config=null,this.context=null,this.xhrSetup=null}abortInternal(){const t=this.loader;self.clearTimeout(this.requestTimeout),self.clearTimeout(this.retryTimeout),t&&(t.onreadystatechange=null,t.onprogress=null,t.readyState!==4&&(this.stats.aborted=!0,t.abort()))}abort(){var t;this.abortInternal(),(t=this.callbacks)!=null&&t.onAbort&&this.callbacks.onAbort(this.stats,this.context,this.loader)}load(t,n,r){if(this.stats.loading.start)throw new Error("Loader can only be used once.");this.stats.loading.start=self.performance.now(),this.context=t,this.config=n,this.callbacks=r,this.loadInternal()}loadInternal(){const{config:t,context:n}=this;if(!t||!n)return;const r=this.loader=new self.XMLHttpRequest,a=this.stats;a.loading.first=0,a.loaded=0,a.aborted=!1;const i=this.xhrSetup;i?Promise.resolve().then(()=>{if(!(this.loader!==r||this.stats.aborted))return i(r,n.url)}).catch(l=>{if(!(this.loader!==r||this.stats.aborted))return r.open("GET",n.url,!0),i(r,n.url)}).then(()=>{this.loader!==r||this.stats.aborted||this.openAndSendXhr(r,n,t)}).catch(l=>{var o;(o=this.callbacks)==null||o.onError({code:r.status,text:l.message},n,r,a)}):this.openAndSendXhr(r,n,t)}openAndSendXhr(t,n,r){t.readyState||t.open("GET",n.url,!0);const a=n.headers,{maxTimeToFirstByteMs:i,maxLoadTimeMs:l}=r.loadPolicy;if(a)for(const o in a)t.setRequestHeader(o,a[o]);n.rangeEnd&&t.setRequestHeader("Range","bytes="+n.rangeStart+"-"+(n.rangeEnd-1)),t.onreadystatechange=this.readystatechange.bind(this),t.onprogress=this.loadprogress.bind(this),t.responseType=n.responseType,self.clearTimeout(this.requestTimeout),r.timeout=i&&bi(i)?i:l,this.requestTimeout=self.setTimeout(this.loadtimeout.bind(this),r.timeout),t.send()}readystatechange(){const{context:t,loader:n,stats:r}=this;if(!t||!n)return;const a=n.readyState,i=this.config;if(!r.aborted&&a>=2&&(r.loading.first===0&&(r.loading.first=Math.max(self.performance.now(),r.loading.start),i.timeout!==i.loadPolicy.maxLoadTimeMs&&(self.clearTimeout(this.requestTimeout),i.timeout=i.loadPolicy.maxLoadTimeMs,this.requestTimeout=self.setTimeout(this.loadtimeout.bind(this),i.loadPolicy.maxLoadTimeMs-(r.loading.first-r.loading.start)))),a===4)){self.clearTimeout(this.requestTimeout),n.onreadystatechange=null,n.onprogress=null;const d=n.status,u=n.responseType==="text"?n.responseText:null;if(d>=200&&d<300){const g=u??n.response;if(g!=null){var l,o;r.loading.end=Math.max(self.performance.now(),r.loading.first);const y=n.responseType==="arraybuffer"?g.byteLength:g.length;r.loaded=r.total=y,r.bwEstimate=r.total*8e3/(r.loading.end-r.loading.first);const x=(l=this.callbacks)==null?void 0:l.onProgress;x&&x(r,t,g,n);const _={url:n.responseURL,data:g,code:d};(o=this.callbacks)==null||o.onSuccess(_,r,t,n);return}}const h=i.loadPolicy.errorRetry,m=r.retry,f={url:t.url,data:void 0,code:d};if(Y5e(h,m,!1,f))this.retry(h);else{var c;Gu.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(Y5e(t,n,!0))this.retry(t);else{var r;Gu.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=cKe(t,r.retry),r.retry++,Gu.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&&oMn.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 lMn={maxTimeToFirstByteMs:8e3,maxLoadTimeMs:2e4,timeoutRetry:null,errorRetry:null},cMn=$u($u({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:yBt,fLoader:void 0,pLoader:void 0,xhrSetup:void 0,licenseXhrSetup:void 0,licenseResponseCallback:void 0,abrController:_An,bufferController:uEn,capLevelController:jKe,errorController:SAn,fpsController:h6n,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:gzt,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:lMn},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},dMn()),{},{subtitleStreamController:N6n,subtitleTrackController:f6n,timelineController:Z6n,audioStreamController:oEn,audioTrackController:lEn,emeController:hz,cmcdController:l6n,contentSteeringController:d6n,interstitialsController:j6n});function dMn(){return{cueHandler:J6n,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 uMn(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=Bze(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 f=r[o].default;switch(t[o]={default:f},u){case"TimeOut":f.maxLoadTimeMs=m,f.maxTimeToFirstByteMs=m;break;case"MaxRetry":f.errorRetry.maxNumRetry=m,f.timeoutRetry.maxNumRetry=m;break;case"RetryDelay":f.errorRetry.retryDelayMs=m,f.timeoutRetry.retryDelayMs=m;break;case"MaxRetryTimeout":f.errorRetry.maxRetryDelayMs=m,f.timeoutRetry.maxRetryDelayMs=m;break}}}),d.length&&n.warn(`hls.js config: "${d.join('", "')}" setting(s) are deprecated, use "${o}": ${bh(t[o])}`)}),$u($u({},r),t)}function Bze(s){return s&&typeof s=="object"?Array.isArray(s)?s.map(Bze):Object.keys(s).reduce((t,n)=>(t[n]=Bze(s[n]),t),{}):s}function hMn(s,t){const n=s.loader;n!==Oxt&&n!==yBt?(t.log("[config]: Custom loader detected, cannot enable progressive streaming"),s.progressive=!1):eMn()&&(s.loader=Oxt,s.progressive=!0,s.enableSoftwareAES=!0,t.log("[config]: Progressive streaming enabled, using FetchLoader"))}const Yje=2,mMn=.1,pMn=.05,fMn=100;class gMn extends uzt{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(Et.MEDIA_ENDED,{stalled:!1})}},this.hls=t,this.fragmentTracker=n,this.registerListeners()}registerListeners(){const{hls:t}=this;t&&(t.on(Et.MEDIA_ATTACHED,this.onMediaAttached,this),t.on(Et.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(Et.BUFFER_APPENDED,this.onBufferAppended,this))}unregisterListeners(){const{hls:t}=this;t&&(t.off(Et.MEDIA_ATTACHED,this.onMediaAttached,this),t.off(Et.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(Et.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(fMn),this.mediaSource=n.mediaSource;const r=this.media=n.media;qv(r,"playing",this.onMediaPlaying),qv(r,"waiting",this.onMediaWaiting),qv(r,"ended",this.onMediaEnded)}onMediaDetaching(t,n){this.clearInterval();const{media:r}=this;r&&(X1(r,"playing",this.onMediaPlaying),X1(r,"waiting",this.onMediaWaiting),X1(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(Et.MEDIA_ENDED,{stalled:!1}));return}if(!_l.getBuffered(l).length){this.nudgeRetry=0;return}const h=_l.bufferInfo(l,t,0),m=h.nextStart||0,f=this.fragmentTracker;if(o&&f&&this.hls){const P=Fxt(this.hls.inFlightFragments,t),I=h.len>Yje,M=!m||P||m-t>Yje&&!f.getPartialFragment(t);if(I||M)return;this.moved=!1}const g=(a=this.hls)==null?void 0:a.latestLevelDetails;if(!this.moved&&this.stalled!==null&&f){if(!(h.len>0)&&!m)return;const I=Math.max(m,h.start||0)-t,L=!!(g!=null&&g.live)?g.targetduration*2:Yje,z=Wne(t,f);if(I>0&&(I<=L||z)){l.paused||this._trySkipBufferHole(z);return}}const y=i.detectStallWithCurrentTimeMs,x=self.performance.now(),_=this.waiting;let b=this.stalled;if(b===null)if(_>0&&x-_=y||_)&&this.hls){var A;if(((A=this.mediaSource)==null?void 0:A.readyState)==="ended"&&!(g!=null&&g.live)&&Math.abs(t-((g==null?void 0:g.edge)||0))<1){if(this.ended)return;this.ended=t||1,this.hls.trigger(Et.MEDIA_ENDED,{stalled:!0});return}if(this._reportStall(h),!this.media||!this.hls)return}const T=_l.bufferInfo(l,t,i.maxBufferHole);this._tryFixBufferStall(T,k,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(Et.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=_l.bufferedInfo(_l.timeRangesToArray(this.buffered.audio),t,0);if(i.len>1&&n>=i.start){const l=_l.timeRangesToArray(a),o=_l.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=Wne(t,this.fragmentTracker);m&&"fragment"in m?m=m.fragment:m||(m=void 0);const f=_l.bufferInfo(this.media,t,0);this.hls.trigger(Et.ERROR,{type:ao.MEDIA_ERROR,details:lr.BUFFER_SEEK_OVER_HOLE,fatal:!1,error:h,reason:h.message,frag:m,buffer:f.len,bufferInfo:f})}}}}}_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=Wne(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,Ri.MAIN),l=r.getFragAtPos(a,Ri.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 (${bh(t)})`);this.warn(l.message),n.trigger(Et.ERROR,{type:ao.MEDIA_ERROR,details:lr.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=_l.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 g=!1;if(l===0){const y=r.getAppendedFrag(0,Ri.MAIN);y&&c"u"))return self.VTTCue||self.TextTrackCue}function SIe(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,bh(a?$u({type:a},r):r))}return i}const Kne=(()=>{const s=$ze();try{s&&new s(0,Number.POSITIVE_INFINITY,"")}catch{return Number.MAX_VALUE}return Number.POSITIVE_INFINITY})();class yMn{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(Et.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(Et.MEDIA_ATTACHING,this.onMediaAttaching,this),t.on(Et.MEDIA_ATTACHED,this.onMediaAttached,this),t.on(Et.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(Et.MANIFEST_LOADING,this.onManifestLoading,this),t.on(Et.FRAG_PARSING_METADATA,this.onFragParsingMetadata,this),t.on(Et.BUFFER_FLUSHING,this.onBufferFlushing,this),t.on(Et.LEVEL_UPDATED,this.onLevelUpdated,this),t.on(Et.LEVEL_PTS_UPDATED,this.onLevelPtsUpdated,this))}_unregisterListeners(){const{hls:t}=this;t&&(t.off(Et.MEDIA_ATTACHING,this.onMediaAttaching,this),t.off(Et.MEDIA_ATTACHED,this.onMediaAttached,this),t.off(Et.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(Et.MANIFEST_LOADING,this.onManifestLoading,this),t.off(Et.FRAG_PARSING_METADATA,this.onFragParsingMetadata,this),t.off(Et.BUFFER_FLUSHING,this.onBufferFlushing,this),t.off(Et.LEVEL_UPDATED,this.onLevelUpdated,this),t.off(Et.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&&K7(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;nKne&&(h=Kne),h-u<=0&&(h=u+xMn);for(let f=0;fu.type===y_.audioId3&&c:a==="video"?d=u=>u.type===y_.emsg&&o:d=u=>u.type===y_.audioId3&&c||u.type===y_.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=$ze();if(r&&a&&!l){const{fragmentStart:y,fragmentEnd:x}=t;let _=this.assetCue;_?(_.startTime=y,_.endTime=x):o&&(_=this.assetCue=SIe(o,y,x,{assetPlayerId:this.hls.config.assetPlayerId},"hlsjs.interstitial.asset"),_&&(_.id=r,this.id3Track||(this.id3Track=this.createTrack(this.media)),this.id3Track.addCue(_),_.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(x=>!u.includes(x));for(let x=y.length;x--;){var f;const _=y[x],b=(f=h[_])==null?void 0:f.cues;delete h[_],b&&Object.keys(b).forEach(k=>{const A=b[k];if(A){A.removeEventListener("enter",this.onEventCueEnter);try{c.removeCue(A)}catch{}}})}}else h=this.dateRangeCuesAppended={}}const g=t.fragments[t.fragments.length-1];if(!(u.length===0||!bi(g==null?void 0:g.programDateTime))){this.id3Track||(this.id3Track=this.createTrack(this.media));for(let y=0;y{if(V!==_.id){const W=d[V];if(W.class===_.class&&W.startDate>_.startDate&&(!$||_.startDate<$.startDate))return W}return $},null);z&&(P=z.startTime,T=!0)}const L=Object.keys(_.attr);for(let z=0;z.01&&(V.startTime=b,V.endTime=P);else if(o){let W=_.attr[$];BAn($)&&(W=H9t(W));const X=SIe(o,b,P,{key:$,data:W},y_.dateRange);X&&(X.id=x,this.id3Track.addCue(X),A[$]=X,l&&($==="X-ASSET-LIST"||$==="X-ASSET-URL")&&X.addEventListener("enter",this.onEventCueEnter))}}h[x]={cues:A,dateRange:_,durationKnown:T}}}}}class vMn{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,f=Math.min(h,Math.max(1,m));this.changeMediaPlaybackRate(n,f)}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(Et.MEDIA_ATTACHED,this.onMediaAttached,this),t.on(Et.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(Et.MANIFEST_LOADING,this.onManifestLoading,this),t.on(Et.LEVEL_UPDATED,this.onLevelUpdated,this),t.on(Et.ERROR,this.onError,this))}unregisterListeners(){const{hls:t}=this;t&&(t.off(Et.MEDIA_ATTACHED,this.onMediaAttached,this),t.off(Et.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(Et.MANIFEST_LOADING,this.onManifestLoading,this),t.off(Et.LEVEL_UPDATED,this.onLevelUpdated,this),t.off(Et.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===lr.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 bMn extends wKe{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(Et.MANIFEST_LOADING,this.onManifestLoading,this),t.on(Et.MANIFEST_LOADED,this.onManifestLoaded,this),t.on(Et.LEVEL_LOADED,this.onLevelLoaded,this),t.on(Et.LEVELS_UPDATED,this.onLevelsUpdated,this),t.on(Et.FRAG_BUFFERED,this.onFragBuffered,this),t.on(Et.ERROR,this.onError,this)}_unregisterListeners(){const{hls:t}=this;t.off(Et.MANIFEST_LOADING,this.onManifestLoading,this),t.off(Et.MANIFEST_LOADED,this.onManifestLoaded,this),t.off(Et.LEVEL_LOADED,this.onLevelLoaded,this),t.off(Et.LEVELS_UPDATED,this.onLevelsUpdated,this),t.off(Et.FRAG_BUFFERED,this.onFragBuffered,this),t.off(Et.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:f}=u;m&&(u.audioCodec=m=H5e(m,r)||void 0),f&&(f=u.videoCodec=sAn(f));const{width:g,height:y,unknownCodecs:x}=u,_=(x==null?void 0:x.length)||0;if(o||(o=!!(g&&y)),c||(c=!!f),d||(d=!!m),_||m&&!this.isAudioSupported(m)||f&&!this.isVideoSupported(f)){this.log(`Some or all CODECS not supported "${h.CODECS}"`);return}const{CODECS:b,"FRAME-RATE":k,"HDCP-LEVEL":A,"PATHWAY-ID":T,RESOLUTION:P,"VIDEO-RANGE":I}=h,L=`${`${T||"."}-`}${u.bitrate}-${P}-${k}-${b}-${I}-${A}`;if(i[L])if(i[L].uri!==u.url&&!u.attrs["PATHWAY-ID"]){const z=l[L]+=1;u.attrs["PATHWAY-ID"]=new Array(z+1).join(".");const $=this.createLevel(u);i[L]=$,a.push($)}else i[L].addGroupId("audio",h.AUDIO),i[L].addGroupId("text",h.SUBTITLES);else{const z=this.createLevel(u);i[L]=z,l[L]=1,a.push(z)}}),this.filterAndSortMediaOptions(a,n,o,c,d)}createLevel(t){const n=new OZ(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=nzt(a,[])}return n}isAudioSupported(t){return DZ(t,"audio",this.hls.config.preferManagedMediaSource)}isVideoSupported(t){return DZ(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:k,width:A,height:T})=>(!!b||!!(A&&T))&&hAn(k))),d.length===0){Promise.resolve().then(()=>{if(this.hls){let b="no level with compatible codecs found in manifest",k=b;n.levels.length&&(k=`one or more CODECS in variant not supported: ${bh(n.levels.map(T=>T.attrs.CODECS).filter((T,P,I)=>I.indexOf(T)===P))}`,this.warn(k),b+=` (${k})`);const A=new Error(b);this.hls.trigger(Et.ERROR,{type:ao.MEDIA_ERROR,details:lr.MANIFEST_INCOMPATIBLE_CODECS_ERROR,fatal:!0,url:n.url,error:A,reason:k})}}),u.end=performance.now();return}n.audioTracks&&(o=n.audioTracks.filter(b=>!b.audioCodec||this.isAudioSupported(b.audioCodec)),Bxt(o)),n.subtitles&&(c=n.subtitles,Bxt(c));const h=d.slice(0);d.sort((b,k)=>{if(b.attrs["HDCP-LEVEL"]!==k.attrs["HDCP-LEVEL"])return(b.attrs["HDCP-LEVEL"]||"")>(k.attrs["HDCP-LEVEL"]||"")?1:-1;if(r&&b.height!==k.height)return b.height-k.height;if(b.frameRate!==k.frameRate)return b.frameRate-k.frameRate;if(b.videoRange!==k.videoRange)return G5e.indexOf(b.videoRange)-G5e.indexOf(k.videoRange);if(b.videoCodec!==k.videoCodec){const A=Mgt(b.videoCodec),T=Mgt(k.videoCodec);if(A!==T)return T-A}if(b.uri===k.uri&&b.codecSet!==k.codecSet){const A=V5e(b.codecSet),T=V5e(k.codecSet);if(A!==T)return T-A}return b.averageBitrate!==k.averageBitrate?b.averageBitrate-k.averageBitrate:0});let m=h[0];if(this.steering&&(d=this.steering.filterParsedLevels(d),d.length!==h.length)){for(let b=0;bA&&A===this.hls.abrEwmaDefaultEstimate&&(this.hls.bandwidthEstimate=T)}break}const g=i&&!a,y=this.hls.config,x=!!(y.audioStreamController&&y.audioTrackController),_={levels:d,audioTracks:o,subtitleTracks:c,sessionData:n.sessionData,sessionKeys:n.sessionKeys,firstLevel:this._firstLevel,stats:n.stats,audio:i,video:a,altAudio:x&&!g&&o.some(b=>!!b.url)};u.end=performance.now(),this.hls.trigger(Et.MANIFEST_PARSED,_)}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(Et.ERROR,{type:ao.OTHER_ERROR,details:lr.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(Et.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===Ac.LEVEL&&n.context.level===this.level&&this.checkRetry(n)}onFragBuffered(t,{frag:n}){if(n!==void 0&&n.type===Ri.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(Et.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));Nzt(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(Et.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(Et.MAX_AUTO_LEVEL_UPDATED,{autoLevelCapping:t,levels:this.levels,maxAutoLevel:n,minAutoLevel:this.hls.minAutoLevel,maxHdcpLevel:r}))}}function Bxt(s){const t={};s.forEach(n=>{const r=n.groupId||"";n.id=t[r]=t[r]||0,t[r]++})}function vBt(){return self.SourceBuffer||self.WebKitSourceBuffer}function bBt(){if(!wE())return!1;const t=vBt();return!t||t.prototype&&typeof t.prototype.appendBuffer=="function"&&typeof t.prototype.remove=="function"}function _Mn(){if(!bBt())return!1;const s=wE();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(RZ(t,"video")))||["mp4a.40.2","fLaC"].some(t=>s.isTypeSupported(RZ(t,"audio"))))}function wMn(){var s;const t=vBt();return typeof(t==null||(s=t.prototype)==null?void 0:s.changeType)=="function"}const jMn=100;class NMn extends pKe{constructor(t,n,r){super(t,n,r,"stream-controller",Ri.MAIN),this.audioCodecSwap=!1,this.level=-1,this._forceStartLoad=!1,this._hasEnoughToStart=!1,this.altAudio=0,this.audioOnly=!1,this.fragPlaying=null,this.fragLastKbps=0,this.couldBacktrack=!1,this.backtrackFragment=null,this.audioCodecSwitch=!1,this.videoBuffer=null,this.onMediaPlaying=()=>{this.tick()},this.onMediaSeeked=()=>{const a=this.media,i=a?a.currentTime:null;if(i===null||!bi(i)||(this.log(`Media seeked to ${i.toFixed(3)}`),!this.getBufferedFrag(i)))return;const l=this.getFwdBufferInfoAtPos(a,i,Ri.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(Et.MANIFEST_PARSED,this.onManifestParsed,this),t.on(Et.LEVEL_LOADING,this.onLevelLoading,this),t.on(Et.LEVEL_LOADED,this.onLevelLoaded,this),t.on(Et.FRAG_LOAD_EMERGENCY_ABORTED,this.onFragLoadEmergencyAborted,this),t.on(Et.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),t.on(Et.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),t.on(Et.BUFFER_CREATED,this.onBufferCreated,this),t.on(Et.BUFFER_FLUSHED,this.onBufferFlushed,this),t.on(Et.LEVELS_UPDATED,this.onLevelsUpdated,this),t.on(Et.FRAG_BUFFERED,this.onFragBuffered,this)}unregisterListeners(){super.unregisterListeners();const{hls:t}=this;t.off(Et.MANIFEST_PARSED,this.onManifestParsed,this),t.off(Et.LEVEL_LOADED,this.onLevelLoaded,this),t.off(Et.FRAG_LOAD_EMERGENCY_ABORTED,this.onFragLoadEmergencyAborted,this),t.off(Et.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),t.off(Et.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),t.off(Et.BUFFER_CREATED,this.onBufferCreated,this),t.off(Et.BUFFER_FLUSHED,this.onBufferFlushed,this),t.off(Et.LEVELS_UPDATED,this.onLevelsUpdated,this),t.off(Et.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(jMn),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=Ur.IDLE,this.nextLoadPosition=this.lastCurrentTime=t+this.timelineOffset,this.startPosition=n?-1:t,this.tick()}else this._forceStartLoad=!0,this.state=Ur.STOPPED}stopLoad(){this._forceStartLoad=!1,super.stopLoad()}doTick(){switch(this.state){case Ur.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=Ur.IDLE;break}else if(this.hls.nextLoadLevel!==this.level){this.state=Ur.IDLE;break}break}case Ur.FRAG_LOADING_WAITING_RETRY:this.checkRetryDate();break}this.state===Ur.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(Et.BUFFER_EOS,y),this.state=Ur.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===Ur.WAITING_LEVEL||this.waitForLive(l)){this.level=i,this.state=Ur.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 f=this.getNextFragment(m,d);if(this.couldBacktrack&&!this.fragPrevious&&f&&$f(f)&&this.fragmentTracker.getState(f)!==Yg.OK){var g;const x=((g=this.backtrackFragment)!=null?g:f).sn-d.startSN,_=d.fragments[x-1];_&&f.cc===_.cc&&(f=_,this.fragmentTracker.removeFragment(_))}else this.backtrackFragment&&o.len&&(this.backtrackFragment=null);if(f&&this.isLoopLoading(f,m)){if(!f.gap){const x=this.audioOnly&&!this.altAudio?fh.AUDIO:fh.VIDEO,_=(x===fh.VIDEO?this.videoBuffer:this.mediaBuffer)||this.media;_&&this.afterBufferFlushed(_,x,Ri.MAIN)}f=this.getNextFragmentLoopLoading(f,d,o,Ri.MAIN,h)}f&&(this.exceedsMaxBuffer(o,h,f)||(f.initSegment&&!f.initSegment.data&&!this.bitrateTest&&(f=f.initSegment),this.loadFragment(f,l,m)))}loadFragment(t,n,r){const a=this.fragmentTracker.getState(t);a===Yg.NOT_LOADED||a===Yg.PARTIAL?$f(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,Ri.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(Et.AUDIO_TRACK_SWITCHED,n)}),r.trigger(Et.BUFFER_FLUSHING,{startOffset:0,endOffset:Number.POSITIVE_INFINITY,type:null});return}r.trigger(Et.AUDIO_TRACK_SWITCHED,n)}}onAudioTrackSwitched(t,n){const r=W5e(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===Ri.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===Ur.PARSED&&(this.state=Ur.IDLE);return}const o=a?a.stats:r.stats;this.fragLastKbps=Math.round(8*o.total/(o.buffering.end-o.loading.first)),$f(r)&&(this.fragPrevious=r),this.fragBufferedComplete(r,a)}const l=this.media;l&&(!this._hasEnoughToStart&&_l.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=Ur.ERROR;return}switch(n.details){case lr.FRAG_GAP:case lr.FRAG_PARSING_ERROR:case lr.FRAG_DECRYPT_ERROR:case lr.FRAG_LOAD_ERROR:case lr.FRAG_LOAD_TIMEOUT:case lr.KEY_LOAD_ERROR:case lr.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(Ri.MAIN,n);break;case lr.LEVEL_LOAD_ERROR:case lr.LEVEL_LOAD_TIMEOUT:case lr.LEVEL_PARSING_ERROR:!n.levelRetry&&this.state===Ur.WAITING_LEVEL&&((r=n.context)==null?void 0:r.type)===Ac.LEVEL&&(this.state=Ur.IDLE);break;case lr.BUFFER_ADD_CODEC_ERROR:case lr.BUFFER_APPEND_ERROR:if(n.parent!=="main")return;this.reduceLengthAndFlushBuffer(n)&&this.resetLoadingState();break;case lr.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 lr.INTERNAL_EXCEPTION:this.recoverWorkerError(n);break}}onFragLoadEmergencyAborted(){this.state=Ur.IDLE,this._hasEnoughToStart||(this.startFragRequested=!1,this.nextLoadPosition=this.lastCurrentTime),this.tickImmediate()}onBufferFlushed(t,{type:n}){if(n!==fh.AUDIO||!this.altAudio){const r=(n===fh.VIDEO?this.videoBuffer:this.mediaBuffer)||this.media;r&&(this.afterBufferFlushed(r,n,Ri.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=Ur.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(Et.FRAG_LOADED,r),i.bitrateTest=!1}).catch(r=>{this.state===Ur.STOPPED||this.state===Ur.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:f}=a,{details:g}=d,y=this.altAudio?void 0:a.audio;if(this.fragContextChanged(o)){this.fragmentTracker.removeFragment(o);return}if(this.state=Ur.PARSING,f){const x=f.tracks;if(x){const A=o.initSegment||o;if(this.unhandledEncryptionError(f,o))return;this._bufferInitSegment(d,x,A,i),r.trigger(Et.FRAG_PARSING_INIT_SEGMENT,{frag:A,id:n,tracks:x})}const _=f.initPTS,b=f.timescale,k=this.initPTS[o.cc];if(bi(_)&&(!k||k.baseTime!==_||k.timescale!==b)){const A=f.trackId;this.initPTS[o.cc]={baseTime:_,timescale:b,trackId:A},r.trigger(Et.INIT_PTS_FOUND,{frag:o,id:n,initPTS:_,timescale:b,trackId:A})}}if(u&&g){y&&u.type==="audiovideo"&&this.logMuxedErr(o);const x=g.fragments[o.sn-1-g.startSN],_=o.sn===g.startSN,b=!x||o.cc>x.cc;if(a.independent!==!1){const{startPTS:k,endPTS:A,startDTS:T,endDTS:P}=u;if(c)c.elementaryStreams[u.type]={startPTS:k,endPTS:A,startDTS:T,endDTS:P};else if(u.firstKeyFrame&&u.independent&&i.id===1&&!b&&(this.couldBacktrack=!0),u.dropped&&u.independent){const I=this.getMainFwdBufferInfo(),M=(I?I.end:this.getLoadPosition())+this.config.maxBufferHole,L=u.firstKeyFramePTS?u.firstKeyFramePTS:k;if(!_&&MYje&&(o.gap=!0);o.setElementaryStreamInfo(u.type,k,A,T,P),this.backtrackFragment&&(this.backtrackFragment=o),this.bufferFragmentData(u,o,c,i,_||b)}else if(_||b)o.gap=!0;else{this.backtrack(o);return}}if(y){const{startPTS:x,endPTS:_,startDTS:b,endDTS:k}=y;c&&(c.elementaryStreams[fh.AUDIO]={startPTS:x,endPTS:_,startDTS:b,endDTS:k}),o.setElementaryStreamInfo(fh.AUDIO,x,_,b,k),this.bufferFragmentData(y,o,c,i)}if(g&&m!=null&&m.samples.length){const x={id:n,frag:o,details:g,samples:m.samples};r.trigger(Et.FRAG_PARSING_METADATA,x)}if(g&&h){const x={id:n,frag:o,details:g,samples:h.samples};r.trigger(Et.FRAG_PARSING_USERDATA,x)}}logMuxedErr(t){this.warn(`${$f(t)?"Media":"Init"} segment with muxed audiovideo where only video expected: ${t.url}`)}_bufferInitSegment(t,n,r,a){if(this.state!==Ur.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=Uje(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=Ri.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=Ri.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(Et.BUFFER_CODECS,n),!this.hls)return;c.forEach(d=>{const h=n[d].initSegment;h!=null&&h.byteLength&&this.hls.trigger(Et.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,Ri.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=Ur.IDLE}checkFragmentChanged(){const t=this.media;let n=null;if(t&&t.readyState>1&&t.seeking===!1){const r=t.currentTime;if(_l.isBuffered(t,r)?n=this.getAppendedFrag(r):_l.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(Et.FRAG_CHANGED,{frag:n}),(!a||a.level!==i)&&this.hls.trigger(Et.LEVEL_SWITCHED,{level:i}))}}}get nextLevel(){const t=this.nextBufferedFrag;return t?t.level:-1}get currentFrag(){var t;if(this.fragPlaying)return this.fragPlaying;const n=((t=this.media)==null?void 0:t.currentTime)||this.lastCurrentTime;return bi(n)?this.getAppendedFrag(n):null}get currentProgramDateTime(){var t;const n=((t=this.media)==null?void 0:t.currentTime)||this.lastCurrentTime;if(bi(n)){const r=this.getLevelDetails(),a=this.currentFrag||(r?MR(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 kMn extends Ij{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=lr.KEY_LOAD_ERROR,r,a,i){return new n4({type:ao.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=Vje(o);if(c)return this.emeController.getKeySystemAccess([c])})}if(this.config.requireKeySystemAccessOnStart){const a=NG(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,lr.KEY_LOAD_ERROR,d))}const l=i.uri;if(!l)return Promise.reject(this.createKeyLoadError(t,lr.KEY_LOAD_ERROR,new Error(`Invalid key URI: "${l}"`)));const o=CIe(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: "+L0(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,lr.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=VCn(n.initSegment.data);if(l.length){let o=l[0];o.some(c=>c!==0)?(this.log(`Using keyId found in init segment ${L0(o)}`),tE.setKeyIdForUri(t.decryptdata.uri,o)):(o=tE.addKeyIdForUri(t.decryptdata.uri),this.log(`Generating keyId to patch media ${L0(o)}`)),t.decryptdata.keyId=o}}if(!t.decryptdata.keyId&&!$f(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,f,g,y)=>{const{frag:x,keyInfo:_}=g,b=CIe(_.decryptdata);if(!x.decryptdata||_!==this.keyIdToKeyInfo[b])return o(this.createKeyLoadError(x,lr.KEY_LOAD_ERROR,new Error("after key load, decryptdata unset or changed"),y));_.decryptdata.key=x.decryptdata.key=new Uint8Array(m.data),x.keyLoader=null,_.loader=null,l({frag:x,keyInfo:_})},onError:(m,f,g,y)=>{this.resetLoader(f),o(this.createKeyLoadError(n,lr.KEY_LOAD_ERROR,new Error(`HTTP Error ${m.code} loading key ${m.text}`),g,$u({url:c.url,data:void 0},m)))},onTimeout:(m,f,g)=>{this.resetLoader(f),o(this.createKeyLoadError(n,lr.KEY_LOAD_TIMEOUT,new Error("key loading timed out"),g))},onAbort:(m,f,g)=>{this.resetLoader(f),o(this.createKeyLoadError(n,lr.INTERNAL_ABORTED,new Error("key loading aborted"),g))}};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=CIe(r.decryptdata)||a;delete this.keyIdToKeyInfo[l],i&&i.destroy()}}function CIe(s){if(s.keyFormat!==D0.FAIRPLAY){const t=s.keyId;if(t)return L0(t)}return s.uri}function $xt(s){const{type:t}=s;switch(t){case Ac.AUDIO_TRACK:return Ri.AUDIO;case Ac.SUBTITLE_TRACK:return Ri.SUBTITLE;default:return Ri.MAIN}}function AIe(s,t){let n=s.url;return(n===void 0||n.indexOf("data:")===0)&&(n=t.url),n}class SMn{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(Et.MANIFEST_LOADING,this.onManifestLoading,this),t.on(Et.LEVEL_LOADING,this.onLevelLoading,this),t.on(Et.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),t.on(Et.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this),t.on(Et.LEVELS_UPDATED,this.onLevelsUpdated,this)}unregisterListeners(){const{hls:t}=this;t.off(Et.MANIFEST_LOADING,this.onManifestLoading,this),t.off(Et.LEVEL_LOADING,this.onLevelLoading,this),t.off(Et.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),t.off(Et.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this),t.off(Et.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:Ac.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:Ac.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:Ac.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:Ac.SUBTITLE_TRACK,url:i,deliveryDirectives:l,levelOrTrack:o})}onLevelsUpdated(t,n){const r=this.loaders[Ac.LEVEL];if(r){const a=r.context;a&&!n.levels.some(i=>i===a.levelOrTrack)&&(r.abort(),delete this.loaders[Ac.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===Ac.MANIFEST?i=r.manifestLoadPolicy.default:i=rh({},r.playlistLoadPolicy.default,{timeoutRetry:null,errorRetry:null}),a=this.createInternalLoader(t),bi((n=t.deliveryDirectives)==null?void 0:n.part)){let d;if(t.type===Ac.LEVEL&&t.level!==null?d=this.hls.levels[t.level].details:t.type===Ac.AUDIO_TRACK&&t.id!==null?d=this.hls.audioTracks[t.id].details:t.type===Ac.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=rh({},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 f=this.getInternalLoader(h);this.resetInternalLoader(h.type);const g=d.data;u.parsing.start=performance.now(),i5.isMediaPlaylist(g)||h.type!==Ac.MANIFEST?this.handleTrackOrLevelPlaylist(d,u,h,m||null,f):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=AIe(t,r),c=i5.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:f,variableList:g}=c;this.variableList=g,u.forEach(b=>{const{unknownCodecs:k}=b;if(k){const{preferManagedMediaSource:A}=this.hls.config;let{audioCodec:T,videoCodec:P}=b;for(let I=k.length;I--;){const M=k[I];DZ(M,"audio",A)?(b.audioCodec=T=T?`${T},${M}`:M,z$.audio[T.substring(0,4)]=2,k.splice(I,1)):DZ(M,"video",A)&&(b.videoCodec=P=P?`${P},${M}`:M,z$.video[P.substring(0,4)]=2,k.splice(I,1))}}});const{AUDIO:y=[],SUBTITLES:x,"CLOSED-CAPTIONS":_}=i5.parseMasterPlaylistMedia(l,o,c);y.length&&!y.some(k=>!k.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 fp({}),bitrate:0,url:""})),i.trigger(Et.MANIFEST_LOADED,{levels:u,audioTracks:y,subtitles:x,captions:_,contentSteering:d,url:o,stats:n,networkDetails:a,sessionData:h,sessionKeys:m,startTimeOffset:f,variableList:g})}handleTrackOrLevelPlaylist(t,n,r,a,i){const l=this.hls,{id:o,level:c,type:d}=r,u=AIe(t,r),h=bi(c)?c:bi(o)?o:0,m=$xt(r),f=i5.parseLevelPlaylist(t.data,u,h,m,0,this.variableList);if(d===Ac.MANIFEST){const g={attrs:new fp({}),bitrate:0,details:f,name:"",url:u};f.requestScheduled=n.loading.start+_zt(f,0),l.trigger(Et.MANIFEST_LOADED,{levels:[g],audioTracks:[],url:u,stats:n,networkDetails:a,sessionData:null,sessionKeys:null,contentSteering:null,startTimeOffset:null,variableList:null})}n.parsing.end=performance.now(),r.levelDetails=f,this.handlePlaylistLoaded(f,t,n,r,a,i)}handleManifestParsingError(t,n,r,a,i){this.hls.trigger(Et.ERROR,{type:ao.NETWORK_ERROR,details:lr.MANIFEST_PARSING_ERROR,fatal:n.type===Ac.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===Ac.LEVEL?l+=`: ${t.level} id: ${t.id}`:(t.type===Ac.AUDIO_TRACK||t.type===Ac.SUBTITLE_TRACK)&&(l+=` id: ${t.id} group-id: "${t.groupId}"`);const o=new Error(l);this.hls.logger.warn(`[playlist-loader]: ${l}`);let c=lr.UNKNOWN,d=!1;const u=this.getInternalLoader(t);switch(t.type){case Ac.MANIFEST:c=r?lr.MANIFEST_LOAD_TIMEOUT:lr.MANIFEST_LOAD_ERROR,d=!0;break;case Ac.LEVEL:c=r?lr.LEVEL_LOAD_TIMEOUT:lr.LEVEL_LOAD_ERROR,d=!1;break;case Ac.AUDIO_TRACK:c=r?lr.AUDIO_TRACK_LOAD_TIMEOUT:lr.AUDIO_TRACK_LOAD_ERROR,d=!1;break;case Ac.SUBTITLE_TRACK:c=r?lr.SUBTITLE_TRACK_LOAD_TIMEOUT:lr.SUBTITLE_LOAD_ERROR,d=!1;break}u&&this.resetInternalLoader(t.type);const h={type:ao.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=$u({url:m,data:void 0},a)}this.hls.trigger(Et.ERROR,h)}handlePlaylistLoaded(t,n,r,a,i,l){const o=this.hls,{type:c,level:d,levelOrTrack:u,id:h,groupId:m,deliveryDirectives:f}=a,g=AIe(n,a),y=$xt(a);let x=typeof a.level=="number"&&y===Ri.MAIN?d:void 0;const _=t.playlistParsingError;if(_){if(this.hls.logger.warn(`${_} ${t.url}`),!o.config.ignorePlaylistParsingErrors){o.trigger(Et.ERROR,{type:ao.NETWORK_ERROR,details:lr.LEVEL_PARSING_ERROR,fatal:!1,url:g,error:_,reason:_.message,response:n,context:a,level:x,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(Et.ERROR,{type:ao.NETWORK_ERROR,details:lr.LEVEL_EMPTY_ERROR,fatal:!1,url:g,error:b,reason:b.message,response:n,context:a,level:x,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 Ac.MANIFEST:case Ac.LEVEL:if(x){if(!u)x=0;else if(u!==o.levels[x]){const b=o.levels.indexOf(u);b>-1&&(x=b)}}o.trigger(Et.LEVEL_LOADED,{details:t,levelInfo:u||o.levels[0],level:x||0,id:h||0,stats:r,networkDetails:i,deliveryDirectives:f,withoutMultiVariant:c===Ac.MANIFEST});break;case Ac.AUDIO_TRACK:o.trigger(Et.AUDIO_TRACK_LOADED,{details:t,track:u,id:h||0,groupId:m||"",stats:r,networkDetails:i,deliveryDirectives:f});break;case Ac.SUBTITLE_TRACK:o.trigger(Et.SUBTITLE_TRACK_LOADED,{details:t,track:u,id:h||0,groupId:m||"",stats:r,networkDetails:i,deliveryDirectives:f});break}}}class Xk{static get version(){return FZ}static isMSESupported(){return bBt()}static isSupported(){return _Mn()}static getMediaSource(){return wE()}static get Events(){return Et}static get MetadataSchema(){return y_}static get ErrorTypes(){return ao}static get ErrorDetails(){return lr}static get DefaultConfig(){return Xk.defaultConfig?Xk.defaultConfig:cMn}static set DefaultConfig(t){Xk.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 fKe,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=LCn(t.debug||!1,"Hls instance",t.assetPlayerId),r=this.config=uMn(Xk.DefaultConfig,t,n);this.userConfig=t,r.progressive&&hMn(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 CAn(this),m=r.interstitialsController,f=m?this.interstitialsController=new m(this,Xk):null,g=this.bufferController=new i(this,h),y=this.capLevelController=new l(this),x=new c(this),_=new SMn(this),b=r.contentSteeringController,k=b?new b(this):null,A=this.levelController=new bMn(this,k),T=new yMn(this),P=new kMn(this.config,this.logger),I=this.streamController=new NMn(this,h,P),M=this.gapController=new gMn(this,h);y.setStreamController(I),x.setStreamController(I);const L=[_,A,I];f&&L.splice(1,0,f),k&&L.splice(1,0,k),this.networkControllers=L;const z=[u,g,M,y,x,T,h];this.audioTrackController=this.createController(r.audioTrackController,L);const $=r.audioStreamController;$&&L.push(this.audioStreamController=new $(this,h,P)),this.subtitleTrackController=this.createController(r.subtitleTrackController,L);const V=r.subtitleStreamController;V&&L.push(this.subtititleStreamController=new V(this,h,P)),this.createController(r.timelineController,z),P.emeController=this.emeController=this.createController(r.emeController,z),this.cmcdController=this.createController(r.cmcdController,z),this.latencyController=this.createController(vMn,z),this.coreComponents=z,L.push(d);const W=d.onErrorOut;typeof W=="function"&&this.on(Et.ERROR,W,d),this.on(Et.MANIFEST_LOADED,_.onManifestLoaded,_)}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===Et.ERROR;this.trigger(Et.ERROR,{type:ao.OTHER_ERROR,details:lr.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(Et.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(Et.ERROR,{type:ao.OTHER_ERROR,details:lr.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(Et.MEDIA_ATTACHING,a)}detachMedia(){this.logger.log("detachMedia"),this.trigger(Et.MEDIA_DETACHING,{}),this._media=null}transferMedia(){this._media=null;const t=this.bufferController.transferMedia();return this.trigger(Et.MEDIA_DETACHING,{transferMedia:t}),t}loadSource(t){this.stopLoad();const n=this.media,r=this._url,a=this._url=rKe.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(Et.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={[Ri.MAIN]:this.streamController.inFlightFrag};return this.audioStreamController&&(t[Ri.AUDIO]=this.audioStreamController.inFlightFrag),this.subtititleStreamController&&(t[Ri.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=g6n()),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){uAn(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=izt(n);return rzt(t,r,navigator.mediaCapabilities)}}Xk.defaultConfig=void 0;const CMn=/(?:player\.mediadelivery\.net|iframe\.mediadelivery\.net|iframe\.n\.net|video\.bunnycdn\.com|[a-z0-9-]+\.b-cdn\.net)/i;function Y7(s){return!!s&&CMn.test(s)&&!/\.mp4($|\?)/i.test(s)}function AMn(s){const t=s.match(/\/(?:play|embed)\/(\d+)\/([a-z0-9-]+)/i);return t?{libraryId:t[1],videoId:t[2]}:null}function TMn(s,t){if(!s)return null;const n=AMn(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 EMn(s){const t=s.match(/https:\/\/[^"']+playlist\.m3u8[^"']*/i);return t?t[0].replace(/&/g,"&").replace(/\u0026/g,"&"):null}const Uze=N.forwardRef(function({sourceUrl:t,thumbnailUrl:n,autoPlay:r,muted:a,loop:i,playsInline:l=!0,...o},c){const d=N.useRef(null),[u,h]=N.useState(null),m=N.useMemo(()=>TMn(t,{autoplay:!!r,muted:!!a,loop:!!i}),[t,r,a,i]);N.useEffect(()=>{let g=!1;if(!t){h(null);return}if(!Y7(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 x=await y.text();return EMn(x)}).then(y=>{g||h(y)}).catch(()=>{g||h(null)}),()=>{g=!0}},[m,t]),N.useEffect(()=>{const g=d.current;if(!g||!u)return;let y=null;const x=()=>{if(!r)return;const b=g.play();b&&b.catch(()=>{})};if(g.muted=!!a,g.loop=!!i,u.endsWith(".m3u8")){if(g.canPlayType("application/vnd.apple.mpegurl")){g.src=u;const b=()=>x();return g.addEventListener("loadedmetadata",b),()=>{g.removeEventListener("loadedmetadata",b),g.removeAttribute("src"),g.load()}}return Xk.isSupported()?(y=new Xk({enableWorker:!0,lowLatencyMode:!0}),y.loadSource(u),y.attachMedia(g),y.on(Xk.Events.MANIFEST_PARSED,x),()=>{y==null||y.destroy(),g.removeAttribute("src"),g.load()}):void 0}g.src=u;const _=()=>x();return g.addEventListener("loadedmetadata",_),()=>{g.removeEventListener("loadedmetadata",_),g.removeAttribute("src"),g.load()}},[r,i,a,u]),N.useEffect(()=>{const g=d.current;if(g){if(g.muted=!!a,g.loop=!!i,r&&u){const y=g.play();y&&y.catch(()=>{});return}g.pause()}},[r,i,a,u]);const f=g=>{if(d.current=g,typeof c=="function"){c(g);return}c&&(c.current=g)};return e.jsx("video",{ref:f,poster:n||void 0,autoPlay:r,muted:a,loop:i,playsInline:l,preload:"metadata",...o})}),MMn={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 LMn(){try{let s=localStorage.getItem("vg_visitor_token");return s||(s=crypto.randomUUID(),localStorage.setItem("vg_visitor_token",s)),s}catch{return null}}function Uxt(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 AKe({config:s,appSlug:t="video_greeter",preview:n=!1,embedded:r=!1}){const[a,i]=N.useState(!1),[l,o]=N.useState(!1),[c,d]=N.useState(!0),[u,h]=N.useState(!1),[m,f]=N.useState("portrait"),[g,y]=N.useState(!1),[x,_]=N.useState(!1),[b,k]=N.useState({name:"",email:"",phone:""}),[A,T]=N.useState(()=>({width:typeof window<"u"?window.innerWidth:1280,height:typeof window<"u"?window.innerHeight:720})),P=N.useRef(null),I=N.useRef(null),M=N.useRef(!1),L=async(Ae,Xe)=>{if(!n)try{await H.from("widget_events").insert({user_id:s.user_id,app_slug:t,event_type:Ae,visitor_token:LMn(),page_url:typeof window<"u"?window.location.href:null,metadata:Xe||{}})}catch{}};N.useEffect(()=>{if(u)return;const Ae=typeof window<"u"?window.location.pathname:"/",Xe=s.targeting||{mode:"all"};if(Xe.mode==="include"&&!Uxt(Xe.include,Ae)||Xe.mode==="exclude"&&Uxt(Xe.exclude,Ae))return;const $e=s.trigger||{type:"immediate"};if($e.type==="immediate"||n){i(!0);return}if($e.type==="delay"){const Ye=($e.value||3)*1e3,Je=setTimeout(()=>i(!0),Ye);return()=>clearTimeout(Je)}if($e.type==="scroll"){const Ye=($e.value||25)/100,Je=()=>{(window.scrollY+window.innerHeight)/document.documentElement.scrollHeight>=Ye&&(i(!0),window.removeEventListener("scroll",Je))};return window.addEventListener("scroll",Je,{passive:!0}),()=>window.removeEventListener("scroll",Je)}if($e.type==="exit_intent"){const Ye=Je=>{Je.clientY<=0&&i(!0)};return document.addEventListener("mouseleave",Ye),()=>document.removeEventListener("mouseleave",Ye)}},[u,s.targeting,s.trigger,n]),N.useEffect(()=>{a&&!M.current&&(M.current=!0,L("impression"))},[a]),N.useEffect(()=>{if(l&&I.current&&!Y7(s.video_url)){I.current.currentTime=0,I.current.muted=!1,d(!1);const Ae=I.current.play();Ae&&Ae.catch(()=>{})}else l&&Y7(s.video_url)&&d(!1)},[l,s.video_url]),N.useEffect(()=>{if(!s.thumbnail_url)return;let Ae=!1;const Xe=new Image;return Xe.onload=()=>{Ae||f(Xe.naturalWidth>Xe.naturalHeight?"landscape":"portrait")},Xe.src=s.thumbnail_url,()=>{Ae=!0}},[s.thumbnail_url]),N.useEffect(()=>{const Ae=()=>{T({width:window.innerWidth,height:window.innerHeight})};return Ae(),window.addEventListener("resize",Ae),()=>window.removeEventListener("resize",Ae)},[]);const z=()=>{o(!0),L("expand")},$=Ae=>{Ae.stopPropagation(),h(!0),o(!1)},V=Ae=>{L("cta_click",{cta_id:Ae.id,label:Ae.label,url:Ae.url})},W=async Ae=>{if(Ae.preventDefault(),n){y(!0);return}if(!(!b.email||!b.name)){_(!0);try{const{error:Xe}=await H.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(Xe)throw Xe;L("lead_capture",{email:b.email}),y(!0)}catch(Xe){console.error("lead submit failed",Xe)}finally{_(!1)}}};if(!a||u||!s.video_url&&!s.video_embed_url)return null;const G=MMn[m][s.size||"md"],X=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",te=s.shape==="circle"?"rounded-full":"rounded-2xl",ne=n?m==="landscape"?"w-[280px]":"w-[220px]":m==="landscape"?"w-[360px] sm:w-[420px]":"w-[300px] sm:w-[340px]",me=m==="landscape"?"aspect-video":"aspect-[9/16]",ue=s.agent||{},ce=s.lead_form_fields||["name","email","phone"],ae=!!(s.show_socials&&(ue.instagram_url||ue.facebook_url||ue.linkedin_url)),he=108+(s.ctas||[]).length*48+(s.lead_form_enabled&&!g?72+ce.length*42:0)+(g?40:0)+(ae?34:0),xe=Math.max(300,A.height-32),ve=Math.max(220,A.width-32),ge=Math.max(150,xe-he),be=Math.floor(m==="landscape"?ge*(16/9):ge*(9/16)),Se=m==="landscape"?Math.max(220,Math.min(420,ve,be)):Math.max(180,Math.min(340,ve,be)),Ie=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":`${ne} max-h-[calc(100dvh-2rem)] bg-white rounded-2xl shadow-2xl overflow-hidden border border-black/10 animate-in fade-in zoom-in-95 duration-300 flex flex-col`,Me=r?{width:`${Se}px`,maxHeight:"calc(100dvh - 2rem)"}:void 0,Re=r?"p-3 space-y-2.5":"p-4 space-y-3",Be=r?"w-9 h-9 rounded-full object-cover":"w-10 h-10 rounded-full object-cover",Ne=r?"font-bold text-[15px] text-gray-900 leading-tight":"font-bold text-gray-900 leading-tight",Ge=r?"text-[11px] text-gray-500 mt-0.5":"text-xs text-gray-500 mt-0.5",Ce=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:`${X} z-[70]`,style:{paddingBottom:"env(safe-area-inset-bottom)"},children:l?e.jsxs("div",{className:Ie,style:Me,children:[e.jsxs("div",{className:`relative bg-black ${me}`,children:[Y7(s.video_url)?e.jsx(Uze,{ref:I,sourceUrl:s.video_url,thumbnailUrl:s.thumbnail_url,autoPlay:!0,muted:c,loop:!1,className:"w-full h-full object-cover",onLoadedMetadata:Ae=>{const{videoWidth:Xe,videoHeight:$e}=Ae.currentTarget;Xe&&$e&&f(Xe>$e?"landscape":"portrait")},onEnded:()=>L("watch_complete")},`expanded-${s.video_url}-${s.thumbnail_url||"no-thumb"}-${l?"on":"off"}`):e.jsx("video",{ref:I,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:()=>L("watch_complete"),onLoadedMetadata:Ae=>{const{videoWidth:Xe,videoHeight:$e}=Ae.currentTarget;Xe&&$e&&f(Xe>$e?"landscape":"portrait")}}),e.jsx("button",{onClick:()=>{I.current&&(I.current.muted=!I.current.muted,d(I.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(PW,{className:"w-4 h-4"}):e.jsx(LW,{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(hr,{className:"w-4 h-4"})})]}),e.jsxs("div",{className:Re,children:[e.jsxs("div",{className:"flex items-center gap-3",children:[ue.avatar_url&&e.jsx("img",{src:ue.avatar_url,alt:ue.name||"",className:Be}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("p",{className:Ne,children:s.greeting_title||"Glad you're here!"}),s.greeting_subtitle&&e.jsx("p",{className:Ge,children:s.greeting_subtitle})]})]}),(s.ctas||[]).length>0&&e.jsx("div",{className:"space-y-2",children:(s.ctas||[]).map(Ae=>{var Xe;return e.jsxs("a",{href:Ae.url,target:(Xe=Ae.url)!=null&&Xe.startsWith("http")?"_blank":void 0,rel:"noopener noreferrer",onClick:()=>V(Ae),className:`flex items-center justify-between gap-2 ${r?"px-3 py-2":"px-3.5 py-2.5"} rounded-xl text-sm font-semibold transition-colors ${Ae.style==="secondary"?"bg-gray-100 text-gray-900 hover:bg-gray-200":"bg-gray-900 text-white hover:bg-gray-800"}`,children:[e.jsx("span",{children:Ae.label}),e.jsx(Tr,{className:"w-3.5 h-3.5 opacity-60"})]},Ae.id)})}),s.lead_form_enabled&&!g&&e.jsxs("form",{onSubmit:W,className:"space-y-2 pt-1",children:[ce.includes("name")&&e.jsx("input",{type:"text",placeholder:"Name",required:!0,value:b.name,onChange:Ae=>k({...b,name:Ae.target.value}),className:Ce}),ce.includes("email")&&e.jsx("input",{type:"email",placeholder:"Email",required:!0,value:b.email,onChange:Ae=>k({...b,email:Ae.target.value}),className:Ce}),ce.includes("phone")&&e.jsx("input",{type:"tel",placeholder:"Phone (optional)",value:b.phone,onChange:Ae=>k({...b,phone:Ae.target.value}),className:Ce}),e.jsxs("button",{type:"submit",disabled:x,className:Fe,children:[e.jsx(Rr,{className:"w-3.5 h-3.5"}),x?"Sending...":"Send"]})]}),g&&e.jsx("p",{className:"text-sm text-emerald-600 font-medium text-center py-2",children:"Thanks! I'll be in touch shortly."}),s.show_socials&&(ue.instagram_url||ue.facebook_url||ue.linkedin_url)&&e.jsxs("div",{className:"flex items-center justify-center gap-3 pt-2 border-t border-gray-100",children:[ue.instagram_url&&e.jsx("a",{href:ue.instagram_url,target:"_blank",rel:"noopener noreferrer",className:"text-gray-400 hover:text-gray-900",onClick:()=>L("cta_click",{social:"instagram"}),children:e.jsx(dm,{className:"w-4 h-4"})}),ue.facebook_url&&e.jsx("a",{href:ue.facebook_url,target:"_blank",rel:"noopener noreferrer",className:"text-gray-400 hover:text-gray-900",onClick:()=>L("cta_click",{social:"facebook"}),children:e.jsx(Kf,{className:"w-4 h-4"})}),ue.linkedin_url&&e.jsx("a",{href:ue.linkedin_url,target:"_blank",rel:"noopener noreferrer",className:"text-gray-400 hover:text-gray-900",onClick:()=>L("cta_click",{social:"linkedin"}),children:e.jsx(W0,{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:z,className:`relative ${te} overflow-hidden shadow-2xl ring-2 ring-white/40 hover:ring-white/80 hover:scale-105 transition-all bg-black`,style:{width:G.w,height:G.h},"aria-label":"Play video greeting",children:[Y7(s.video_url)?e.jsx(Uze,{ref:P,sourceUrl:s.video_url,thumbnailUrl:s.thumbnail_url,autoPlay:!0,muted:!0,loop:!0,className:"w-full h-full object-cover pointer-events-none",onLoadedMetadata:Ae=>{const{videoWidth:Xe,videoHeight:$e}=Ae.currentTarget;Xe&&$e&&f(Xe>$e?"landscape":"portrait")}},`collapsed-${s.video_url}-${s.thumbnail_url||"no-thumb"}`):e.jsx("video",{ref:P,src:s.video_url||void 0,poster:s.thumbnail_url||void 0,autoPlay:!0,muted:!0,loop:!0,playsInline:!0,preload:"metadata",className:"w-full h-full object-cover",onLoadedMetadata:Ae=>{const{videoWidth:Xe,videoHeight:$e}=Ae.currentTarget;Xe&&$e&&f(Xe>$e?"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:$,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(hr,{className:"w-3.5 h-3.5"})})]})})}function TKe({slug:s}){const[t,n]=N.useState(null);return N.useEffect(()=>{if(!s)return;let r=!1;return(async()=>{const{data:a,error:i}=await H.rpc("get_public_video_greeter_config",{_slug:s});!r&&!i&&a&&n(a)})(),()=>{r=!0}},[s]),t?e.jsx(AKe,{config:t}):null}const _Bt="eip_last_shown",qxt="eip_visitor_token";function PMn(){try{let s=localStorage.getItem(qxt);return s||(s=crypto.randomUUID(),localStorage.setItem(qxt,s)),s}catch{return}}function IMn(s){try{const t=Number(localStorage.getItem(_Bt)||0);return t?Date.now()-t>s*24*60*60*1e3:!0}catch{return!0}}function DMn(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 wBt({config:s,preview:t=!1,forceOpen:n=!1}){const[r,a]=N.useState(n),[i,l]=N.useState(!1),[o,c]=N.useState(!1),[d,u]=N.useState({name:"",email:"",phone:""}),h=N.useRef(!1),m=N.useRef(!1),f=async(P,I={})=>{if(!t)try{await H.from("widget_events").insert({user_id:s.user_id,app_slug:"exit_intent",event_type:P,visitor_token:PMn(),page_url:window.location.href,metadata:I})}catch{}};N.useEffect(()=>{if(t||!DMn(s.targeting)||!IMn(s.frequency_days))return;const P=/Mobi|Android/i.test(navigator.userAgent),I={low:5,medium:15,high:30}[s.trigger_sensitivity]||15,M=V=>{if(!h.current){h.current=!0,a(!0);try{localStorage.setItem(_Bt,String(Date.now()))}catch{}f("impression",{reason:V})}},L=V=>{V.clientY<=I&&M("mouse_leave")},z=()=>{s.enable_mobile_back&&P&&M("back_button")};if(s.enable_mobile_back&&P){try{window.history.pushState({eip:!0},"")}catch{}window.addEventListener("popstate",z)}else document.addEventListener("mouseleave",L);let $;return s.enable_time_fallback&&($=window.setTimeout(()=>M("time_fallback"),Math.max(5,s.time_fallback_seconds)*1e3)),()=>{document.removeEventListener("mouseleave",L),window.removeEventListener("popstate",z),$&&window.clearTimeout($)}},[s,t]),N.useEffect(()=>{r&&!m.current&&!t&&!h.current&&(m.current=!0)},[r,t]);const g=()=>{a(!1),t||f("close")},y=async P=>{if(P.preventDefault(),t){l(!0);return}if(!(!d.email||!d.name)){c(!0);try{const{error:I}=await H.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(I)throw I;f("lead_capture",{email:d.email}),l(!0),s.cta_url&&setTimeout(()=>{window.location.href=s.cta_url},1200)}catch(I){console.error("exit intent submit failed",I)}finally{c(!1)}}};if(!r)return null;const x=s.form_fields||["name","email"],_=s.agent||{},b=[_.first_name,_.last_name].filter(Boolean).join(" "),k=s.use_agent_photo&&_.avatar_url||s.image_url,A=s.theme_color||"#f97316",T=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:T,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:P=>P.stopPropagation(),children:[e.jsx("div",{className:"h-2 w-full",style:{background:`linear-gradient(90deg, ${A}, ${TIe(A,-25)})`}}),e.jsx("button",{onClick:g,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(hr,{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:[k&&e.jsx("img",{src:k,alt:b||"Agent",className:"w-14 h-14 rounded-full object-cover ring-2 shadow-md",style:{boxShadow:`0 0 0 2px ${A}33`,"--tw-ring-color":A}}),e.jsxs("div",{className:"inline-flex items-center gap-1.5 px-2.5 py-1 rounded-full text-xs font-semibold",style:{background:`${A}1A`,color:A},children:[e.jsx(Cn,{className:"w-3 h-3"}),s.offer_label]})]}),e.jsxs("div",{children:[e.jsx("h3",{className:"text-2xl font-extrabold tracking-tight leading-tight",children:s.headline}),e.jsx("p",{className:"text-sm text-muted-foreground mt-2",children:s.subheadline})]}),i?e.jsxs("div",{className:"rounded-xl p-5 text-center space-y-2",style:{background:`${A}10`,color:A},children:[e.jsx("div",{className:"text-3xl",children:"🎉"}),e.jsx("p",{className:"text-sm font-medium",style:{color:A},children:s.success_message})]}):s.form_enabled?e.jsxs("form",{onSubmit:y,className:"space-y-2.5",children:[x.includes("name")&&e.jsx("input",{type:"text",placeholder:"Your name",value:d.name,onChange:P=>u({...d,name:P.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":A},required:!0}),x.includes("email")&&e.jsx("input",{type:"email",placeholder:"you@email.com",value:d.email,onChange:P=>u({...d,email:P.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":A},required:!0}),x.includes("phone")&&e.jsx("input",{type:"tel",placeholder:"Phone (optional)",value:d.phone,onChange:P=>u({...d,phone:P.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":A}}),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, ${A}, ${TIe(A,-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:()=>f("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, ${A}, ${TIe(A,-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 TIe(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 EKe({slug:s}){const[t,n]=N.useState(null);return N.useEffect(()=>{if(!s)return;let r=!1;return(async()=>{const{data:a,error:i}=await H.rpc("get_public_exit_intent_config",{_slug:s});!r&&!i&&a&&n(a)})(),()=>{r=!0}},[s]),t?e.jsx(wBt,{config:t}):null}const Vxt="lm_dismissed",Hxt="lm_visitor_token";function RMn(){try{let s=localStorage.getItem(Hxt);return s||(s=crypto.randomUUID(),localStorage.setItem(Hxt,s)),s}catch{return}}function OMn(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 MKe({config:s,preview:t=!1}){const[n,r]=N.useState(!1),[a,i]=N.useState(!1),[l,o]=N.useState(!1),[c,d]=N.useState(!1),[u,h]=N.useState({name:"",email:"",phone:""}),m=N.useRef(!1),f=async(k,A={})=>{if(!t)try{await H.from("widget_events").insert({user_id:s.user_id,app_slug:"lead_magnet",event_type:k,visitor_token:RMn(),page_url:window.location.href,metadata:A})}catch{}};N.useEffect(()=>{if(t){r(!0);return}if(!OMn(s.targeting))return;try{if(sessionStorage.getItem(Vxt))return}catch{}const k=()=>{m.current||(m.current=!0,r(!0),f("impression"))};if(s.trigger_type==="immediate")k();else if(s.trigger_type==="delay"){const A=window.setTimeout(k,Math.max(0,s.trigger_value)*1e3);return()=>window.clearTimeout(A)}else if(s.trigger_type==="scroll"){const A=()=>{(window.scrollY+window.innerHeight)/document.documentElement.scrollHeight*100>=(s.trigger_value||30)&&k()};return window.addEventListener("scroll",A,{passive:!0}),()=>window.removeEventListener("scroll",A)}},[s,t]);const g=()=>{r(!1);try{sessionStorage.setItem(Vxt,"1")}catch{}t||f("close")},y=async k=>{if(k.preventDefault(),t){o(!0);return}if(!(!u.email||!u.name)){d(!0);try{const{error:A}=await H.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(A)throw A;f("lead_capture",{email:u.email}),o(!0),(s.delivery_method==="instant"||s.delivery_method==="both")&&s.download_url&&setTimeout(()=>{const T=document.createElement("a");T.href=s.download_url,T.target="_blank",T.rel="noopener",T.download="",document.body.appendChild(T),T.click(),T.remove()},600)}catch(A){console.error("lead magnet submit failed",A)}finally{d(!1)}}};if(!n)return null;const x=s.theme_color||"#2563eb",_=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, ${x}, ${yH(x,-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(Io,{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),f("expand")},className:"px-4 py-2 rounded-lg text-sm font-semibold bg-white shrink-0 hover:bg-white/95 transition",style:{color:x},children:s.download_label}),e.jsx("button",{onClick:g,className:"text-white/80 hover:text-white","aria-label":"Close",children:e.jsx(hr,{className:"w-4 h-4"})})]})}),a&&b()]});if(!a)return e.jsxs(e.Fragment,{children:[e.jsxs("button",{onClick:()=>{i(!0),f("expand")},className:`${_} 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, ${x}, ${yH(x,-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(Ep,{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:k=>{k.stopPropagation(),g()},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(hr,{className:"w-3 h-3"})})]}),a&&b()]});return b();function b(){const k=s.form_fields||["name","email"],A=s.agent||{},T=[A.first_name,A.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:P=>P.stopPropagation(),children:[e.jsxs("div",{className:"relative h-44 sm:h-52 overflow-hidden",style:{background:`linear-gradient(135deg, ${x}, ${yH(x,-25)})`},children:[s.cover_image_url?e.jsx("img",{src:s.cover_image_url,alt:s.title,className:"w-full h-full object-cover opacity-90"}):e.jsx("div",{className:"w-full h-full flex items-center justify-center",children:e.jsx(Wr,{className:"w-20 h-20 text-white/40"})}),e.jsxs("div",{className:"absolute top-3 left-3 inline-flex items-center gap-1.5 px-2.5 py-1 rounded-full text-[11px] font-semibold bg-white shadow",style:{color:x},children:[e.jsx(Io,{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(hr,{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:`${x}10`},children:[e.jsx(oi,{className:"w-8 h-8 mx-auto",style:{color:x}}),e.jsx("p",{className:"text-sm font-medium",style:{color:x},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:x},children:"Click here if download didn't start"})]}):s.form_enabled?e.jsxs("form",{onSubmit:y,className:"space-y-2.5",children:[k.includes("name")&&e.jsx("input",{type:"text",placeholder:"Your name",value:u.name,onChange:P=>h({...u,name:P.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":x},required:!0}),k.includes("email")&&e.jsx("input",{type:"email",placeholder:"you@email.com",value:u.email,onChange:P=>h({...u,email:P.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":x},required:!0}),k.includes("phone")&&e.jsx("input",{type:"tel",placeholder:"Phone (optional)",value:u.phone,onChange:P=>h({...u,phone:P.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":x}}),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, ${x}, ${yH(x,-20)})`},children:[e.jsx(oi,{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:()=>f("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, ${x}, ${yH(x,-20)})`},children:s.download_label}),T&&e.jsxs("p",{className:"text-[11px] text-center text-muted-foreground",children:["Curated by ",T]})]})]})})}}function yH(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 LKe({slug:s}){const[t,n]=N.useState(null);return N.useEffect(()=>{if(!s)return;let r=!1;return(async()=>{const{data:a,error:i}=await H.rpc("get_public_lead_magnet_config",{_slug:s});!r&&!i&&a&&n(a)})(),()=>{r=!0}},[s]),t?e.jsx(MKe,{config:t}):null}function FMn({children:s,siteConfig:t}){var xe,ve,ge,be,Se,Ie,Me,Re,Be;const n=Id(),r=tr(),[a,i]=N.useState(!1),[l,o]=N.useState(!1),[c,d]=N.useState(!1),[u,h]=N.useState([]),[m,f]=N.useState([]),[g,y]=N.useState(null),x=N.useRef(null),_=N.useRef(null),{user:b,profile:k,signOut:A}=TAe();sKe(t,b==null?void 0:b.id),nKe(t,b==null?void 0:b.id);const T=((xe=t.agent)==null?void 0:xe.full_name)||"Agent",P=t.siteTitle||`${T} Real Estate`,I=n.pathname==="/search",M=n.pathname==="/",L=t.leadRegistrationMode!=="disabled";N.useEffect(()=>{(async()=>{const{data:Ge}=await H.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(Ge||[])})()},[t.id]),N.useEffect(()=>{(async()=>{const{data:Ge}=await H.from("lead_site_menu_items").select("*").eq("site_id",t.id).eq("is_visible",!0).order("sort_order",{ascending:!0});f(Ge||[])})()},[t.id]),N.useEffect(()=>{const Ne=Ge=>{x.current&&!x.current.contains(Ge.target)&&d(!1),_.current&&!_.current.contains(Ge.target)&&y(null)};return document.addEventListener("mousedown",Ne),()=>document.removeEventListener("mousedown",Ne)},[]);const z=q9t(t),$=t==null?void 0:t.bookingUrl,V=z?m.filter(Ne=>{const Ge=String(Ne.target_url||"").toLowerCase(),Ce=String(Ne.label||"").toLowerCase();return Ge!=="/search"&&!Ge.startsWith("/search?")&&!Ce.includes("search")}):m,W=V.length>0,G=[{to:"/",label:"Home"},...z?[]:[{to:"/search",label:"Search"}],{to:"/sell",label:"Sell"},{to:"/blog",label:"Blog"},{to:"/community",label:"Community"},{to:"/about",label:"About"},{to:"/contact",label:"Contact"}],X=W?[]:G,te=V.filter(Ne=>!Ne.parent_id),ne=Ne=>V.filter(Ge=>Ge.parent_id===Ne),me=M?"bg-transparent text-white":"bg-white/95 backdrop-blur text-gray-900 border-b border-gray-100 shadow-sm",ue=t.siteTitle||`${T} - Real Estate`,ce=t.siteTagline||`Browse homes and listings with ${T}`,ae=t.ogImageUrl||((ve=t.agent)==null?void 0:ve.avatar_url)||"",he=`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(eKe,{siteConfig:t,pagePath:n.pathname}),e.jsx(tKe,{siteConfig:t}),e.jsxs(ic,{children:[e.jsx("title",{children:ue}),e.jsx("meta",{name:"description",content:ce}),e.jsx("meta",{property:"og:title",content:ue}),e.jsx("meta",{property:"og:description",content:ce}),e.jsx("meta",{property:"og:type",content:"website"}),e.jsx("meta",{property:"og:url",content:he+n.pathname}),ae&&e.jsx("meta",{property:"og:image",content:ae}),e.jsx("meta",{name:"twitter:card",content:"summary_large_image"}),e.jsx("meta",{name:"twitter:title",content:ue}),e.jsx("meta",{name:"twitter:description",content:ce}),ae&&e.jsx("meta",{name:"twitter:image",content:ae}),t.faviconUrl&&e.jsx("link",{rel:"icon",href:t.faviconUrl,type:"image/png"}),e.jsx("link",{rel:"canonical",href:`${he}${n.pathname}`}),t.subdomainSlug==="matthogg"&&e.jsx("script",{src:"https://analytics.ahrefs.com/analytics.js","data-key":"kyFjzruyvE0yTdMokzgCBw",async:!0})]}),e.jsxs("header",{className:`${M?"absolute":"sticky"} top-0 left-0 right-0 z-50 transition-all ${me}`,children:[e.jsx("div",{className:"max-w-7xl mx-auto px-6 lg:px-8",children:e.jsxs("div",{className:"flex items-center justify-between h-20",children:[e.jsxs(cr,{to:"/",className:"flex items-center gap-3",children:[((ge=t.agent)==null?void 0:ge.avatar_url)&&e.jsx("img",{src:t.agent.avatar_url,alt:T,className:"h-10 w-10 rounded-full object-cover ring-2 ring-white/20"}),e.jsx("div",{children:e.jsx("span",{className:"font-bold text-lg leading-none tracking-tight",children:P})})]}),e.jsxs("nav",{className:"hidden md:flex items-center gap-1",children:[t.bookingUrl&&e.jsx(f3,{bookingUrl:t.bookingUrl,label:"Schedule",size:"sm",className:"order-last ml-3",source:"nav"}),X.map(Ne=>e.jsx(cr,{to:Ne.to,className:`px-4 py-2 rounded-lg text-sm font-medium tracking-wide transition-colors ${n.pathname===Ne.to?M?"bg-white/15 text-white":"bg-gray-100 text-gray-900":M?"text-white/70 hover:text-white hover:bg-white/10":"text-gray-500 hover:text-gray-900 hover:bg-gray-50"}`,children:Ne.label},Ne.to)),W&&te.map(Ne=>{if(Ne.item_type==="dropdown"){const Ge=ne(Ne.id);return e.jsxs("div",{ref:_,className:"relative",children:[e.jsxs("button",{onClick:()=>y(g===Ne.id?null:Ne.id),className:`flex items-center gap-1 px-4 py-2 rounded-lg text-sm font-medium tracking-wide transition-colors ${M?"text-white/70 hover:text-white hover:bg-white/10":"text-gray-500 hover:text-gray-900 hover:bg-gray-50"}`,children:[Ne.label," ",e.jsx(Xo,{className:`h-3.5 w-3.5 transition-transform ${g===Ne.id?"rotate-180":""}`})]}),g===Ne.id&&Ge.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:Ge.map(Ce=>e.jsx(Yne,{item:Ce,onClick:()=>y(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"},Ce.id))})]},Ne.id)}return e.jsx(Yne,{item:Ne,className:`px-4 py-2 rounded-lg text-sm font-medium tracking-wide transition-colors ${M?"text-white/70 hover:text-white hover:bg-white/10":"text-gray-500 hover:text-gray-900 hover:bg-gray-50"}`},Ne.id)}),u.length>0&&e.jsxs("div",{ref:x,className:"relative",children:[e.jsxs("button",{onClick:()=>d(!c),className:`flex items-center gap-1 px-4 py-2 rounded-lg text-sm font-medium tracking-wide transition-colors ${n.pathname.startsWith("/homes-for-sale-in-")?M?"bg-white/15 text-white":"bg-gray-100 text-gray-900":M?"text-white/70 hover:text-white hover:bg-white/10":"text-gray-500 hover:text-gray-900 hover:bg-gray-50"}`,children:["Cities ",e.jsx(Xo,{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(Ne=>e.jsx("button",{onClick:()=>{r(`/homes-for-sale-in-${Ne.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:Ne.city_name},Ne.city_slug))})]}),b?e.jsxs("div",{className:"flex items-center gap-1 ml-2",children:[e.jsxs(cr,{to:"/account",className:`flex items-center gap-1.5 px-3 py-2 rounded-lg text-sm font-medium transition-colors ${M?"text-white/70 hover:text-white hover:bg-white/10":"text-gray-500 hover:text-gray-900 hover:bg-gray-50"}`,children:[e.jsx(co,{className:"h-4 w-4"}),e.jsx("span",{className:"hidden lg:inline",children:"Saved"})]}),e.jsxs(cr,{to:"/account",className:`flex items-center gap-1.5 px-3 py-2 rounded-lg text-sm font-medium transition-colors ${M?"text-white/70 hover:text-white hover:bg-white/10":"text-gray-500 hover:text-gray-900 hover:bg-gray-50"}`,children:[e.jsx(Ro,{className:"h-4 w-4"}),e.jsx("span",{className:"hidden lg:inline",children:((be=k==null?void 0:k.name)==null?void 0:be.split(" ")[0])||"Account"})]})]}):L?e.jsx("button",{onClick:()=>o(!0),className:`ml-2 px-4 py-2 rounded-lg text-sm font-medium transition-colors ${M?"bg-white/15 text-white hover:bg-white/25":"bg-blue-600 text-white hover:bg-blue-700"}`,children:"Sign In"}):null]}),e.jsx("button",{onClick:()=>i(!a),className:`md:hidden p-2 rounded-lg ${M?"text-white hover:bg-white/10":"text-gray-600 hover:bg-gray-100"}`,children:a?e.jsx(hr,{className:"h-5 w-5"}):e.jsx(MT,{className:"h-5 w-5"})})]})}),a&&e.jsx("div",{className:`md:hidden border-t ${M?"border-white/10 bg-black/95 backdrop-blur":"border-gray-100 bg-white"} max-h-[calc(100vh-5rem)] overflow-y-auto overscroll-contain`,children:e.jsxs("div",{className:"px-4 py-3 space-y-1 pb-8",children:[t.bookingUrl&&e.jsx(f3,{bookingUrl:t.bookingUrl,label:"Schedule a Free Consultation",size:"sm",className:"w-full mb-3",source:"mobile_nav"}),X.map(Ne=>e.jsx(cr,{to:Ne.to,onClick:()=>i(!1),className:`block px-3 py-2.5 rounded-lg text-sm font-medium ${n.pathname===Ne.to?M?"bg-white/15 text-white":"bg-gray-100 text-gray-900":M?"text-white/70 hover:bg-white/10":"text-gray-500 hover:bg-gray-50"}`,children:Ne.label},Ne.to)),W&&te.map(Ne=>{if(Ne.item_type==="dropdown"){const Ge=ne(Ne.id);return e.jsxs("div",{className:"space-y-1",children:[e.jsx("div",{className:`px-3 pt-3 pb-1 text-xs font-semibold uppercase tracking-wider ${M?"text-white/40":"text-gray-400"}`,children:Ne.label}),Ge.map(Ce=>e.jsx(Yne,{item:Ce,onClick:()=>i(!1),className:`block px-3 py-2.5 rounded-lg text-sm font-medium ${M?"text-white/70 hover:bg-white/10":"text-gray-500 hover:bg-gray-50"}`},Ce.id))]},Ne.id)}return e.jsx(Yne,{item:Ne,onClick:()=>i(!1),className:`block px-3 py-2.5 rounded-lg text-sm font-medium ${M?"text-white/70 hover:bg-white/10":"text-gray-500 hover:bg-gray-50"}`},Ne.id)}),u.length>0&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:`px-3 pt-3 pb-1 text-xs font-semibold uppercase tracking-wider ${M?"text-white/40":"text-gray-400"}`,children:"Cities"}),u.map(Ne=>e.jsx(cr,{to:`/homes-for-sale-in-${Ne.city_slug}`,onClick:()=>i(!1),className:`block px-3 py-2.5 rounded-lg text-sm font-medium ${n.pathname===`/homes-for-sale-in-${Ne.city_slug}`?M?"bg-white/15 text-white":"bg-gray-100 text-gray-900":M?"text-white/70 hover:bg-white/10":"text-gray-500 hover:bg-gray-50"}`,children:Ne.city_name},Ne.city_slug))]}),b?e.jsxs(e.Fragment,{children:[e.jsx(cr,{to:"/account",onClick:()=>i(!1),className:`block px-3 py-2.5 rounded-lg text-sm font-medium ${M?"text-white/70 hover:bg-white/10":"text-gray-500 hover:bg-gray-50"}`,children:"My Account"}),e.jsx("button",{onClick:async()=>{await A(),i(!1)},className:`block w-full text-left px-3 py-2.5 rounded-lg text-sm font-medium ${M?"text-white/70 hover:bg-white/10":"text-gray-500 hover:bg-gray-50"}`,children:"Sign Out"})]}):L?e.jsx("button",{onClick:()=>{o(!0),i(!1)},className:`block w-full text-left px-3 py-2.5 rounded-lg text-sm font-medium ${M?"text-white/70 hover:bg-white/10":"text-blue-600 hover:bg-blue-50"}`,children:"Sign In / Register"}):null]})})]}),e.jsx("main",{className:"flex-1 min-h-0 flex flex-col",children:s}),!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:[((Se=t.agent)==null?void 0:Se.avatar_url)&&e.jsx("img",{src:t.agent.avatar_url,alt:T,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:T}),e.jsx("p",{className:"text-sm text-gray-500",children:((Ie=t.agent)==null?void 0:Ie.title)||"Real Estate Professional"})]})]}),((Me=t.agent)==null?void 0:Me.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(ga,{className:"h-3.5 w-3.5"})," ",t.agent.phone]})}),((Re=t.agent)==null?void 0:Re.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(mn,{className:"h-3.5 w-3.5"})," ",t.agent.email]})})]}),e.jsxs("div",{children:[e.jsx("h4",{className:"font-semibold text-white mb-4 text-sm tracking-wider uppercase",children:"Quick Links"}),e.jsxs("ul",{className:"space-y-3 text-sm",children:[X.map(Ne=>e.jsx("li",{children:e.jsx(cr,{to:Ne.to,className:"hover:text-white transition-colors",children:Ne.label})},Ne.to)),$&&e.jsx("li",{children:e.jsx("a",{href:$,target:"_blank",rel:"noopener noreferrer",className:"hover:text-white transition-colors",children:"Schedule a Call"})})]})]}),e.jsxs("div",{children:[e.jsx("h4",{className:"font-semibold text-white mb-4 text-sm tracking-wider uppercase",children:"Get In Touch"}),e.jsx("p",{className:"text-sm text-gray-500 leading-relaxed mb-4",children:z?"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(cr,{to:"/contact",className:"inline-block px-5 py-2.5 bg-white text-gray-900 text-sm font-semibold rounded-lg hover:bg-gray-100 transition-colors",children:"Contact Me"})]})]}),e.jsxs("div",{className:"mt-14 pt-6 border-t border-gray-800/50",children:[t.showTeamLogo&&t.teamLogoUrl&&e.jsx("div",{className:"flex items-center justify-center mb-6",children:e.jsx("img",{src:t.teamLogoUrl,alt:"Team",className:"h-12 w-auto object-contain"})}),t.brokerageLegalName&&e.jsxs("div",{className:"flex flex-wrap items-center justify-center gap-x-4 gap-y-1 text-xs text-gray-500 mb-3",children:[e.jsxs("span",{children:[T," · ",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()," ",T,". Powered by LevelUp."]})]})]})]})}),!I&&((Be=t.agent)==null?void 0:Be.avatar_url)&&e.jsx(zMn,{agent:t.agent,bookingUrl:$}),l&&e.jsx(JWe,{open:l,mode:"optional",siteConfig:t,onComplete:()=>o(!1),onSkip:()=>o(!1)}),e.jsx(TKe,{slug:t.subdomainSlug}),e.jsx(EKe,{slug:t.subdomainSlug}),e.jsx(LKe,{slug:t.subdomainSlug})]})}function zMn({agent:s,bookingUrl:t}){var i;const[n,r]=N.useState(!1),a=tr();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(ga,{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(mn,{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(hr,{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 Yne({item:s,className:t,onClick:n}){const r=s.target_url||"#";return s.item_type==="external"||s.open_in_new_tab?e.jsx("a",{href:r,target:"_blank",rel:"noopener noreferrer",className:t,onClick:n,children:s.label}):e.jsx(cr,{to:r,className:t,onClick:n,children:s.label})}const Gxt={california:"California DRE License",ca:"California DRE License"};function qze(s){const t=(s||"").trim();if(!t)return"Real Estate License";const n=t.toLowerCase();return Gxt[n]?Gxt[n]:`${t.replace(/\b\w/g,a=>a.toUpperCase())} Real Estate License`}function Wxt(s){if(s)return s.replace(/^\s*DRE\s*#?\s*/i,"").replace(/^\s*#/,"").trim()||void 0}function BMn({children:s,siteConfig:t}){var he,xe,ve,ge,be,Se,Ie;const n=Id(),r=tr(),[a,i]=N.useState(!1),[l,o]=N.useState(!1),[c,d]=N.useState(!1),[u,h]=N.useState([]),[m,f]=N.useState(!1),g=N.useRef(null),{user:y,profile:x,signOut:_}=TAe();sKe(t,y==null?void 0:y.id),nKe(t,y==null?void 0:y.id);const b=((he=t.agent)==null?void 0:he.full_name)||"Agent",k=Wxt(t.agentLicenseNumber),A=Wxt(t.brokerageLicenseNumber),T=t.siteTitle||`${b} Real Estate`,P=t.brokerageLegalName?`${b} | ${t.brokerageLegalName}`:b,I=Me=>{if(!Me)return Me;const Re=b.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),Be=new RegExp(`^\\s*${Re}\\s*[|\\-–—:]\\s*`,"i");return Me.replace(Be,"").trim()},M=T&&T!==`${b} Real Estate`?T:null,L=M?I(M):null,z=L&&L.toLowerCase()!==b.toLowerCase()?L:null,$=n.pathname==="/search",V=n.pathname==="/",W=t.leadRegistrationMode!=="disabled",G="#c9a96e",X=t.bookingUrl;N.useEffect(()=>{const Me=()=>f(window.scrollY>80);return window.addEventListener("scroll",Me,{passive:!0}),()=>window.removeEventListener("scroll",Me)},[]),N.useEffect(()=>{(async()=>{const{data:Re}=await H.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(Re||[])})()},[t.id]),N.useEffect(()=>{const Me=Re=>{g.current&&!g.current.contains(Re.target)&&d(!1)};return document.addEventListener("mousedown",Me),()=>document.removeEventListener("mousedown",Me)},[]);const te=[{to:"/",label:"Home"},{to:"/search",label:"Search"},{to:"/sell",label:"Sell"},{to:"/blog",label:"Blog"},{to:"/community",label:"Community"},{to:"/about",label:"About"},{to:"/contact",label:"Contact"}],ne=t.siteTitle||`${b} - Real Estate`,me=t.siteTagline||`Browse homes and listings with ${b}`,ue=t.ogImageUrl||((xe=t.agent)==null?void 0:xe.avatar_url)||"",ce=`https://${t.subdomainSlug||""}.thelocalmove.com`,ae=V?m?"bg-[#0d0b0a]/95 backdrop-blur-lg border-b border-white/5":"bg-transparent":"bg-[#0d0b0a] border-b border-white/5";return e.jsxs("div",{className:`flex flex-col ${$?"h-screen overflow-hidden":"min-h-screen"} bg-[#0d0b0a]`,children:[e.jsx(eKe,{siteConfig:t,pagePath:n.pathname}),e.jsx(tKe,{siteConfig:t}),e.jsxs(ic,{children:[e.jsx("title",{children:ne}),e.jsx("meta",{name:"description",content:me}),e.jsx("meta",{property:"og:title",content:ne}),e.jsx("meta",{property:"og:description",content:me}),e.jsx("meta",{property:"og:type",content:"website"}),e.jsx("meta",{property:"og:url",content:ce+n.pathname}),ue&&e.jsx("meta",{property:"og:image",content:ue}),e.jsx("meta",{name:"twitter:card",content:"summary_large_image"}),e.jsx("meta",{name:"twitter:title",content:ne}),e.jsx("meta",{name:"twitter:description",content:me}),ue&&e.jsx("meta",{name:"twitter:image",content:ue}),t.faviconUrl&&e.jsx("link",{rel:"icon",href:t.faviconUrl,type:"image/png"}),e.jsx("link",{rel:"canonical",href:`${ce}${n.pathname}`}),e.jsx("link",{href:"https://fonts.googleapis.com/css2?family=Playfair+Display:ital,wght@0,400;0,500;0,600;0,700;1,400;1,500&display=swap",rel:"stylesheet"})]}),e.jsxs("header",{className:`${V?"fixed":"sticky"} top-0 left-0 right-0 z-50 transition-all duration-500 ${ae}`,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.jsx(cr,{to:"/",className:"flex items-center gap-3 min-w-0",children:e.jsxs("span",{className:"flex flex-col leading-none max-w-[320px] xl:max-w-[420px]",children:[e.jsx("span",{className:"block whitespace-normal text-white text-xl tracking-tight",style:{fontFamily:"'Playfair Display', Georgia, serif"},children:P}),z&&e.jsx("span",{className:"mt-1 text-[11px] tracking-[0.18em] uppercase text-white/70",children:z})]})}),e.jsxs("nav",{className:"hidden lg:flex items-center gap-1",children:[te.map(Me=>e.jsx(cr,{to:Me.to,className:`px-4 py-2 text-xs tracking-[0.15em] uppercase transition-colors duration-300 ${n.pathname===Me.to?"text-white":"text-white/40 hover:text-white"}`,children:Me.label},Me.to)),u.length>0&&e.jsxs("div",{ref:g,className:"relative",children:[e.jsxs("button",{onClick:()=>d(!c),className:`flex items-center gap-1 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(Xo,{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:u.map(Me=>e.jsx("button",{onClick:()=>{r(`/homes-for-sale-in-${Me.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:Me.city_name},Me.city_slug))})]}),y?e.jsxs("div",{className:"flex items-center gap-1 ml-3",children:[e.jsxs(cr,{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(co,{className:"h-3.5 w-3.5"}),e.jsx("span",{className:"hidden xl:inline",children:"Saved"})]}),e.jsxs(cr,{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(Ro,{className:"h-3.5 w-3.5"}),e.jsx("span",{className:"hidden xl:inline",children:((ve=x==null?void 0:x.name)==null?void 0:ve.split(" ")[0])||"Account"})]})]}):W?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,X&&e.jsx(f3,{bookingUrl:X,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(hr,{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:[X&&e.jsx(f3,{bookingUrl:X,label:"Schedule a Free Consultation",size:"sm",className:"w-full mb-3",source:"mobile_nav"}),te.map(Me=>e.jsx(cr,{to:Me.to,onClick:()=>i(!1),className:`block px-3 py-3 text-xs tracking-[0.2em] uppercase transition-colors ${n.pathname===Me.to?"text-white":"text-white/40 hover:text-white"}`,children:Me.label},Me.to)),u.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:G},children:"Cities"}),u.map(Me=>e.jsx(cr,{to:`/homes-for-sale-in-${Me.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:Me.city_name},Me.city_slug))]}),y?e.jsxs(e.Fragment,{children:[e.jsx(cr,{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 _(),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"})]}):W?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}),!$&&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:b}),e.jsx("p",{className:"text-white/70 text-xs tracking-[0.15em] uppercase mb-6",children:((ge=t.agent)==null?void 0:ge.title)||"Real Estate Professional"}),(k||A)&&e.jsxs("div",{className:"mb-6 p-4 border border-white/10 bg-white/5",children:[k&&e.jsxs("p",{className:"text-sm text-white font-medium tracking-wide",children:[qze(t.licenseState)," #",k]}),A&&e.jsxs("p",{className:"text-xs text-white/70 tracking-wider uppercase mt-1",children:["Brokerage License #",A]})]}),((be=t.agent)==null?void 0:be.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(ga,{className:"h-3.5 w-3.5"})," ",t.agent.phone]}),((Se=t.agent)==null?void 0:Se.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(mn,{className:"h-3.5 w-3.5"})," ",t.agent.email]})]}),e.jsxs("div",{children:[e.jsx("h4",{className:"text-xs tracking-[0.3em] uppercase mb-6 text-white",style:{color:G},children:"Quick Links"}),e.jsxs("ul",{className:"space-y-3",children:[te.map(Me=>e.jsx("li",{children:e.jsx(cr,{to:Me.to,className:"text-xs tracking-wider uppercase text-white/70 hover:text-white transition-colors",children:Me.label})},Me.to)),X&&e.jsx("li",{children:e.jsx("a",{href:X,target:"_blank",rel:"noopener noreferrer",className:"text-xs tracking-wider uppercase transition-colors hover:opacity-80",style:{color:cq},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:G},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:[X&&e.jsx(f3,{bookingUrl:X,label:"Schedule a Free Consultation",size:"sm",source:"footer"}),e.jsx(cr,{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:[b," · ",t.brokerageLegalName]}),k&&e.jsxs("span",{children:[qze(t.licenseState)," #",k]}),A&&e.jsxs("span",{children:["Brokerage #",A]})]}),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()," ",b,". Powered by LevelUp."]})]})]})]})}),!$&&((Ie=t.agent)==null?void 0:Ie.avatar_url)&&e.jsx($Mn,{agent:t.agent,agentLicense:k,siteConfig:t,accentColor:G}),l&&e.jsx(JWe,{open:l,mode:"optional",siteConfig:t,onComplete:()=>o(!1),onSkip:()=>o(!1),theme:"luxury",accentColor:G}),e.jsx(TKe,{slug:t.subdomainSlug}),e.jsx(EKe,{slug:t.subdomainSlug}),e.jsx(LKe,{slug:t.subdomainSlug})]})}function $Mn({agent:s,agentLicense:t,siteConfig:n,accentColor:r}){var o;const[a,i]=N.useState(!1),l=tr();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:qze(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(ga,{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(mn,{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(hr,{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 vH="#2c1810",lk="#b8860b";function UMn({children:s,siteConfig:t}){var M,L,z;const n=Id();tr();const[r,a]=N.useState(!1),[i,l]=N.useState(!1),[o,c]=N.useState(!1),[d,u]=N.useState([]),[h,m]=N.useState(!1),f=N.useRef(null),{user:g,profile:y,signOut:x}=TAe();sKe(t,g==null?void 0:g.id),nKe(t,g==null?void 0:g.id);const _=((M=t.agent)==null?void 0:M.full_name)||"Agent",b=t.siteTitle||`${_} Land & Ranch`,k=n.pathname==="/",A=t.leadRegistrationMode!=="disabled";N.useEffect(()=>{const $=()=>m(window.scrollY>80);return window.addEventListener("scroll",$,{passive:!0}),()=>window.removeEventListener("scroll",$)},[]),N.useEffect(()=>{(async()=>{const{data:V}=await H.from("lead_site_city_pages").select("city_name, city_slug").eq("site_id",t.id).eq("is_published",!0).order("sort_order");V&&u(V)})()},[t.id]),N.useEffect(()=>{const $=V=>{f.current&&!f.current.contains(V.target)&&c(!1)};return document.addEventListener("mousedown",$),()=>document.removeEventListener("mousedown",$)},[]);const T=[{label:"Home",path:"/"},{label:"Search Properties",path:"/search"},{label:"About",path:"/about"},{label:"Blog",path:"/blog"},{label:"Contact",path:"/contact"}],P=h||!k?"bg-white/95 backdrop-blur-md shadow-sm":"bg-transparent",I=h||!k?vH:"#ffffff";return e.jsxs("div",{className:"min-h-screen",style:{fontFamily:"'Lora', Georgia, serif"},children:[e.jsxs(ic,{children:[e.jsx("title",{children:b}),e.jsx("link",{href:"https://fonts.googleapis.com/css2?family=Playfair+Display:wght@400;600;700;800&family=Lora:wght@400;500;600&display=swap",rel:"stylesheet"})]}),e.jsx(eKe,{siteConfig:t}),e.jsx(tKe,{siteConfig:t}),e.jsxs("header",{className:`fixed top-0 left-0 right-0 z-50 transition-all duration-300 ${P}`,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(cr,{to:"/",className:"flex items-center gap-2.5",children:[e.jsx(c9,{className:"w-7 h-7",style:{color:lk}}),e.jsx("span",{className:"text-lg font-bold tracking-wide",style:{color:I,fontFamily:"'Playfair Display', Georgia, serif"},children:b})]}),e.jsxs("nav",{className:"hidden md:flex items-center gap-1",children:[T.map($=>e.jsx(cr,{to:$.path,className:"px-4 py-2 text-sm font-medium tracking-wide uppercase transition-colors hover:opacity-80",style:{color:n.pathname===$.path?lk:I},children:$.label},$.path)),d.length>0&&e.jsxs("div",{ref:f,className:"relative",children:[e.jsxs("button",{onClick:()=>c(!o),className:"px-4 py-2 text-sm font-medium tracking-wide uppercase flex items-center gap-1 transition-colors hover:opacity-80",style:{color:I},children:["Areas ",e.jsx(Xo,{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($=>e.jsx(cr,{to:`/homes-for-sale-in-${$.city_slug}`,className:"block px-4 py-2.5 text-sm hover:bg-gray-50 transition-colors",style:{color:vH},onClick:()=>c(!1),children:$.city_name},$.city_slug))})]}),g?e.jsx("div",{className:"flex items-center gap-2 ml-3",children:e.jsxs(cr,{to:"/account",className:"px-4 py-2 text-sm font-medium rounded-full border-2 transition-all hover:scale-105",style:{borderColor:lk,color:I},children:[e.jsx(Ro,{className:"w-4 h-4 inline mr-1.5"}),(y==null?void 0:y.name)||"Account"]})}):A?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:lk},children:"Sign In"}):null]}),e.jsx("button",{onClick:()=>a(!r),className:"md:hidden p-2",style:{color:I},children:r?e.jsx(hr,{className:"w-6 h-6"}):e.jsx(MT,{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:[T.map($=>e.jsx(cr,{to:$.path,className:"block px-4 py-3 text-base font-medium rounded-lg hover:bg-gray-50 transition-colors",style:{color:n.pathname===$.path?lk:vH},onClick:()=>a(!1),children:$.label},$.path)),d.length>0&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"px-4 py-2 text-xs font-semibold tracking-wider uppercase text-gray-400",children:"Areas"}),d.map($=>e.jsx(cr,{to:`/homes-for-sale-in-${$.city_slug}`,className:"block px-4 py-2.5 text-sm rounded-lg hover:bg-gray-50",style:{color:vH},onClick:()=>a(!1),children:$.city_name},$.city_slug))]}),!g&&A&&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:lk},children:"Sign In"})]})})]}),e.jsx("main",{children:s}),e.jsx("footer",{className:"py-16 px-4",style:{backgroundColor:vH},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(c9,{className:"w-6 h-6",style:{color:lk}}),e.jsx("span",{className:"text-lg font-bold text-white",style:{fontFamily:"'Playfair Display', Georgia, serif"},children:b})]}),e.jsx("p",{className:"text-white/60 text-sm leading-relaxed",children:"Your trusted specialist in land, ranch, and rural properties. Expert guidance for every acre."})]}),e.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:T.map($=>e.jsx(cr,{to:$.path,className:"block text-white/60 hover:text-white text-sm transition-colors",children:$.label},$.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:[((L=t.agent)==null?void 0:L.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(ga,{className:"w-4 h-4",style:{color:lk}}),t.agent.phone]}),((z=t.agent)==null?void 0:z.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(mn,{className:"w-4 h-4",style:{color:lk}}),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:lk}})]})]})}),i&&e.jsx(JWe,{open:i,mode:t.leadRegistrationMode==="required"?"required":"optional",siteConfig:t,onSkip:()=>l(!1),onComplete:()=>l(!1)}),e.jsx(TKe,{slug:t.subdomainSlug}),e.jsx(EKe,{slug:t.subdomainSlug}),e.jsx(LKe,{slug:t.subdomainSlug})]})}function qMn(){const{pathname:s}=Id();return N.useEffect(()=>{window.scrollTo({top:0,left:0,behavior:"auto"})},[s]),null}const VMn=N.lazy(()=>Fi(()=>import("./LeadSiteHome-CBI2c8oW.js"),__vite__mapDeps([0,1,2,3]))),HMn=N.lazy(()=>Fi(()=>import("./LeadSiteLuxuryHome-BFHPAbpO.js"),__vite__mapDeps([4,2,3]))),GMn=N.lazy(()=>Fi(()=>import("./LeadSiteLandRanchHome-DVxBwLih.js"),__vite__mapDeps([5,1,2,3]))),WMn=N.lazy(()=>Fi(()=>import("./LeadSiteSearch-sKCQAGTc.js"),__vite__mapDeps([6,1,7,3,8]))),KMn=N.lazy(()=>Fi(()=>import("./LeadSiteLuxurySearch-CKALcsU3.js"),__vite__mapDeps([9,1,7,3,8]))),YMn=N.lazy(()=>Fi(()=>import("./LeadSiteListingDetail-CJ_F1Ya0.js"),__vite__mapDeps([10,11,3,12]))),ZMn=N.lazy(()=>Fi(()=>import("./LeadSiteLuxuryListingDetail-CJ-hINuy.js"),__vite__mapDeps([13,11,3,12]))),XMn=N.lazy(()=>Fi(()=>import("./LeadSiteAbout-DqvUG-kz.js"),[])),QMn=N.lazy(()=>Fi(()=>import("./LeadSiteLuxuryAbout-B5u0t39m.js"),[])),JMn=N.lazy(()=>Fi(()=>import("./LeadSiteContact-CYj6dOU3.js"),[])),eLn=N.lazy(()=>Fi(()=>import("./LeadSiteLuxuryContact-xbkHku7T.js"),[])),tLn=N.lazy(()=>Fi(()=>import("./LeadSiteConsumerDashboard-DwopEdg-.js"),[])),Kxt=N.lazy(()=>Fi(()=>import("./LeadSiteBlog-BLlJOwEq.js"),[])),sLn=N.lazy(()=>Fi(()=>import("./LeadSiteCommunity-BmOr3TPP.js"),[])),nLn=N.lazy(()=>Fi(()=>import("./LeadSiteSellers-BpuwG8JJ.js"),[])),rLn=N.lazy(()=>Fi(()=>import("./LeadSiteCityPage-DhH-zpdT.js"),__vite__mapDeps([14,3,8]))),aLn=N.lazy(()=>Fi(()=>import("./LeadSiteSubdivisionPage-B0Io5xjp.js"),__vite__mapDeps([15,3]))),iLn=N.lazy(()=>Fi(()=>import("./LeadSiteCustomPage-CtDhxqz_.js"),[]));function oLn(){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 lLn(){var d;const{siteConfig:s,themeConfig:t,isLoading:n,error:r}=iCn();if(n)return e.jsx("div",{className:"min-h-screen flex items-center justify-center bg-white",children:e.jsxs("div",{className:"text-center",children:[e.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-blue-600 border-t-transparent mx-auto mb-4"}),e.jsx("p",{className:"text-gray-500",children:"Loading..."})]})});if(r||!s)return e.jsx("div",{className:"min-h-screen flex items-center justify-center bg-gray-50 p-6",children:e.jsxs("div",{className:"text-center max-w-md",children:[e.jsx("h1",{className:"text-2xl font-bold text-gray-900 mb-2",children:"Site Not Found"}),e.jsx("p",{className:"text-gray-500",children:"This lead site is not available or has not been set up yet."})]})});const a=(t==null?void 0:t.themeTier)==="luxury",i=(t==null?void 0:t.themeTier)==="land-ranch",l=i?UMn:a?BMn:FMn,o=q9t(s,t),c=i?e.jsx(GMn,{siteConfig:s,themeConfig:t??void 0}):a?e.jsx(HMn,{siteConfig:s,themeConfig:t??void 0}):e.jsx(VMn,{siteConfig:s,themeConfig:t??void 0});return e.jsxs(lCn,{siteConfig:s,children:[e.jsx(qMn,{}),e.jsxs(l,{siteConfig:s,children:[e.jsx(N.Suspense,{fallback:e.jsx(oLn,{}),children:e.jsxs(I2e,{children:[e.jsx(Ss,{path:"/",element:c}),e.jsx(Ss,{path:"/search",element:o?e.jsx(nN,{to:"/contact",replace:!0}):a?e.jsx(KMn,{siteConfig:s}):e.jsx(WMn,{siteConfig:s})}),e.jsx(Ss,{path:"/listing/:mlsNumber",element:o?e.jsx(nN,{to:"/contact",replace:!0}):a?e.jsx(ZMn,{siteConfig:s}):e.jsx(YMn,{siteConfig:s})}),e.jsx(Ss,{path:"/about",element:a?e.jsx(QMn,{siteConfig:s}):e.jsx(XMn,{siteConfig:s})}),e.jsx(Ss,{path:"/contact",element:a?e.jsx(eLn,{siteConfig:s}):e.jsx(JMn,{siteConfig:s})}),e.jsx(Ss,{path:"/account",element:e.jsx(tLn,{siteConfig:s})}),e.jsx(Ss,{path:"/blog",element:e.jsx(Kxt,{siteConfig:s,isLuxury:a})}),e.jsx(Ss,{path:"/blog/:slug",element:e.jsx(Kxt,{siteConfig:s,isLuxury:a})}),e.jsx(Ss,{path:"/sell",element:e.jsx(nLn,{siteConfig:s,themeConfig:t??void 0,isLuxury:a})}),e.jsx(Ss,{path:"/community",element:e.jsx(sLn,{siteConfig:s,isLuxury:a})}),e.jsx(Ss,{path:"/schedule",element:e.jsx(pCn,{bookingUrl:s.bookingUrl,agentName:((d=s.agent)==null?void 0:d.full_name)||"your agent"})}),e.jsx(Ss,{path:"/p/:pageSlug",element:e.jsx(iLn,{siteConfig:s})}),e.jsx(Ss,{path:"/*",element:e.jsx(cLn,{siteConfig:s,referralMode:o})})]})}),e.jsx(mCn,{bookingUrl:s.bookingUrl})]})]})}function cLn({siteConfig:s,referralMode:t}){const n=Id(),r=n.pathname.match(/^\/homes-in-(.+)$/);if(r)return e.jsx(aLn,{siteConfig:s,subdivisionSlug:r[1]});const a=n.pathname.match(/^\/homes-for-sale-in-(.+)$/);return a?e.jsx(rLn,{siteConfig:s,citySlugOverride:a[1],referralMode:t}):null}function dLn(){const{user:s,loading:t}=Ls(),{data:n,isLoading:r}=mt({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 H.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 uLn({children:s}){const{user:t,loading:n}=Ls(),{hasAccess:r,isLoading:a}=dLn(),i=Id();return N.useEffect(()=>{!n&&!a&&t&&!r&&ie.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(nN,{to:"/dashboard",replace:!0}):(sessionStorage.setItem("redirectAfterLogin",i.pathname),e.jsx(nN,{to:"/auth",replace:!0}))}function Yxt({children:s}){const{user:t,loading:n}=Ls(),{hasAccess:r,isLoading:a}=GUe(),i=Id();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(nN,{to:"/dashboard",replace:!0}):(sessionStorage.setItem("redirectAfterLogin",i.pathname),e.jsx(nN,{to:"/auth",replace:!0}))}const Vze={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"},hLn=["First-time buyers","Move-up buyers","Luxury","New construction","Investors","Relocation","Downsizing / seniors","Military / VA","Land & ranch","Waterfront","Condos","Multi-family"],mLn=["Buyers","Sellers","Both equally","Investors","Renters","Builders / developers"],pLn=["Warm & approachable","Bold & direct","Educational & analytical","Playful & funny","Polished & luxury","Down-to-earth & local","High-energy & motivational"],fLn=[{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"}],gLn=["Under $250k","$250k – $500k","$500k – $750k","$750k – $1M","$1M – $2M","$2M+"],xLn=["Brand new (under 1 year)","1–3 years","3–5 years","5–10 years","10–20 years","20+ years"],yLn=[{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"}],vLn=[{value:"instagram",label:"Instagram"},{value:"tiktok",label:"TikTok"},{value:"facebook",label:"Facebook"},{value:"youtube",label:"YouTube Shorts"},{value:"linkedin",label:"LinkedIn"}],bLn=[{value:"15-30s",label:"15–30 seconds"},{value:"30-45s",label:"30–45 seconds"},{value:"45-60s",label:"45–60 seconds"}],_Ln=[{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"}],wLn=[{value:"local",label:"Mostly local market content"},{value:"evergreen",label:"Mostly evergreen content"},{value:"mix",label:"A healthy mix of both"}];function jBt({value:s,label:t}){const[n,r]=N.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),ie.success(`${t} copied`),setTimeout(()=>r(!1),1600)},children:[n?e.jsx(pa,{className:"h-3.5 w-3.5 mr-1"}):e.jsx(Pa,{className:"h-3.5 w-3.5 mr-1"}),"Copy"]}):null}function W6({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(jBt,{value:n,label:s}):null]}),e.jsx("div",{className:"text-[14.5px] leading-relaxed text-foreground whitespace-pre-wrap",children:t})]})}function Zje({reel:s,index:t,onUpdate:n,readOnly:r}){var c;const[a,i]=N.useState(t===0),l=!!s.recorded_at,o=!!s.posted_at;return e.jsx(_e,{className:"rounded-2xl border-border/70 overflow-hidden",children:e.jsxs("div",{className:"p-5 sm:p-6",children:[e.jsxs("div",{className:"flex flex-wrap items-start justify-between gap-3",children:[e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsxs(We,{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(We,{variant:"outline",className:"text-[10.5px] font-medium text-muted-foreground",children:Vze[s.category]??s.category}):null,o?e.jsx(We,{className:"bg-emerald-100 text-emerald-800 border-0 text-[10.5px]",children:"Posted"}):l?e.jsx(We,{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:Ot("h-9 w-9 shrink-0",s.favorited&&"text-amber-500"),onClick:()=>n({favorited:!s.favorited}),children:e.jsx(Wa,{className:Ot("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(jBt,{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(W6,{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(na,{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(Rr,{className:"h-3.5 w-3.5 mr-1.5"}),o?"Posted":"Mark as posted"]})]}):null,e.jsxs(Kv,{open:a,onOpenChange:i,children:[e.jsx(Yv,{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(Xo,{className:Ot("h-4 w-4 transition-transform",a&&"rotate-180")})]})}),e.jsxs(Zv,{className:"space-y-5 pt-2",children:[e.jsx(Wl,{}),s.filming_directions?e.jsx(W6,{label:"How to film it",children:e.jsxs("span",{className:"flex gap-2",children:[e.jsx(l9,{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(W6,{label:"Caption",copyValue:s.caption,children:s.caption}):null,(c=s.hashtags)!=null&&c.length?e.jsx(W6,{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(W6,{label:"Pinned comment",copyValue:s.pinned_comment,children:s.pinned_comment}):null,s.reply_strategy?e.jsx(W6,{label:"Reply strategy",children:e.jsxs("span",{className:"flex gap-2",children:[e.jsx(xo,{className:"h-4 w-4 mt-0.5 shrink-0 text-muted-foreground"}),e.jsx("span",{children:s.reply_strategy})]})}):null,s.why_it_works?e.jsxs("div",{className:"rounded-xl border border-primary/20 bg-primary/5 p-4",children:[e.jsxs("div",{className:"flex items-center gap-1.5 text-[11px] font-semibold uppercase tracking-[0.09em] text-primary",children:[e.jsx(Cn,{className:"h-3.5 w-3.5"})," Why this will work"]}),e.jsx("p",{className:"mt-1.5 text-[14px] leading-relaxed text-foreground",children:s.why_it_works})]}):null,s.bonus_idea?e.jsx(W6,{label:"Bonus content idea",children:e.jsxs("span",{className:"flex gap-2",children:[e.jsx(Z2,{className:"h-4 w-4 mt-0.5 shrink-0 text-muted-foreground"}),e.jsx("span",{children:s.bonus_idea})]})}):null]})]})]})})}function NBt(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 Zxt(){const s=NBt(),[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 IK(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 PKe(s){const{user:t}=Ls(),n=s??(t==null?void 0:t.id),r=as(),a=mt({queryKey:["weekly-reels-profile",n],enabled:!!n,queryFn:async()=>{const{data:h,error:m}=await H.from("weekly_reel_profiles").select("*").eq("user_id",n).maybeSingle();if(m)throw m;return h??null}}),i=mt({queryKey:["weekly-reels-packs",n],enabled:!!n,queryFn:async()=>{const{data:h,error:m}=await H.from("weekly_reel_packs").select("*").eq("user_id",n).order("week_start_date",{ascending:!1}).limit(52);if(m)throw m;const f=(h??[]).map(y=>y.id);let g=[];if(f.length){const{data:y,error:x}=await H.from("weekly_reels").select("*").in("pack_id",f).order("position",{ascending:!0});if(x)throw x;g=y??[]}return(h??[]).map(y=>({...y,reels:g.filter(x=>x.pack_id===y.id)}))}}),l=_t({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:f}=await H.from("weekly_reel_profiles").upsert(m,{onConflict:"user_id"});if(f)throw f},onSuccess:()=>{r.invalidateQueries({queryKey:["weekly-reels-profile",n]})},onError:h=>ie.error(h.message)}),o=_t({mutationFn:async({id:h,values:m})=>{const{error:f}=await H.from("weekly_reels").update(m).eq("id",h);if(f)throw f},onSuccess:()=>r.invalidateQueries({queryKey:["weekly-reels-packs",n]}),onError:h=>ie.error(h.message)}),c=NBt(),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 Zne({icon:s,label:t,value:n,tone:r="default"}){const a=r==="good"?"text-emerald-700 bg-emerald-50 border-emerald-100":r==="warn"?"text-amber-700 bg-amber-50 border-amber-100":"text-foreground bg-muted/60 border-transparent";return e.jsxs("div",{className:`rounded-xl border px-4 py-3.5 ${a}`,children:[e.jsxs("div",{className:"flex items-center gap-1.5 text-[11px] font-semibold uppercase tracking-[0.09em] opacity-70",children:[e.jsx(s,{className:"h-3.5 w-3.5"})," ",t]}),e.jsx("div",{className:"mt-1 text-[15px] font-semibold leading-snug",children:n})]})}function jLn(){var M,L,z,$,V,W;const s=tr(),{user:t,isAdmin:n}=Ls(),{profile:r,packs:a,currentPack:i,history:l,saveProfile:o,updateReel:c}=PKe(),[d,u]=N.useState(!1),[h,m]=N.useState(""),[f,g]=N.useState("all"),[y,x]=N.useState("all"),_=(((M=r.data)==null?void 0:M.full_name)||((L=t==null?void 0:t.user_metadata)==null?void 0:L.full_name)||"there").split(" ")[0],b=!!((z=r.data)!=null&&z.onboarding_completed),k=N.useMemo(()=>(a.data??[]).flatMap(G=>G.reels.map(X=>({reel:X,pack:G}))),[a.data]),A=N.useMemo(()=>{const G=h.trim().toLowerCase();return k.filter(({pack:X})=>y==="all"?!0:X.week_start_date===y).filter(({reel:X})=>f==="all"?!0:X.category===f).filter(({reel:X})=>G?`${X.topic} ${X.hook} ${X.script}`.toLowerCase().includes(G):!0)},[k,h,f,y]),T=k.filter(({reel:G})=>G.favorited),P=async()=>{u(!0);try{const{data:G,error:X}=await H.functions.invoke("weekly-reels-generate",{body:{action:"generate_pack",force:!0}});if(X)throw X;if(G!=null&&G.error)throw new Error(G.error);ie.success("Your pack is ready"),a.refetch()}catch(G){ie.error(G instanceof Error?G.message:"Generation failed")}finally{u(!1)}},I=G=>X=>c.mutate({id:G.id,values:X});return!r.isLoading&&!b?e.jsx(Qs,{title:"Weekly Reels",children:e.jsx("div",{className:"mx-auto w-full max-w-2xl px-4 py-16 sm:px-6",children:e.jsxs(_e,{className:"rounded-2xl 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/10",children:e.jsx(Rh,{className:"h-7 w-7 text-primary"})}),e.jsx("p",{className:"mt-6 text-[11px] font-semibold uppercase tracking-[0.14em] text-primary",children:"Weekly Reels"}),e.jsx("h1",{className:"mt-2 text-2xl font-semibold tracking-tight text-foreground sm:text-3xl",children:"5 personalized Reel scripts. 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:"mt-7",onClick:()=>s("/weekly-reels/onboarding"),children:[e.jsx(Cn,{className:"h-4 w-4 mr-2"})," Start setup — about 5 minutes"]})]})})}):e.jsx(Qs,{title:"Weekly Reels",children:e.jsxs("div",{className:"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:"text-[11px] font-semibold uppercase tracking-[0.14em] text-primary",children:"Weekly Reels"}),e.jsxs("h1",{className:"mt-2 text-2xl font-semibold tracking-tight text-foreground sm:text-3xl",children:["Welcome back, ",_]}),e.jsx("p",{className:"mt-1.5 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(C9,{className:"h-4 w-4 mr-2"})," Edit my profile"]})]}),e.jsxs(_e,{className:"mt-6 rounded-2xl border-border/70 p-5 sm:p-6",children:[e.jsxs("div",{className:"grid gap-3 sm:grid-cols-2 lg:grid-cols-4",children:[e.jsx(Zne,{icon:Hr,label:"Onboarding",value:b?"Complete":"Incomplete",tone:b?"good":"warn"}),e.jsx(Zne,{icon:l9,label:"Weekly delivery",value:($=r.data)!=null&&$.delivery_active?"Active":"Paused",tone:(V=r.data)!=null&&V.delivery_active?"good":"warn"}),e.jsx(Zne,{icon:df,label:"Next pack",value:Zxt()}),e.jsx(Zne,{icon:mn,label:"Email this week",value:(i==null?void 0:i.delivery_status)==="sent"?"Delivered":(i==null?void 0:i.delivery_status)==="failed"?"Failed":"Scheduled",tone:(i==null?void 0:i.delivery_status)==="sent"?"good":(i==null?void 0:i.delivery_status)==="failed"?"warn":"default"})]}),e.jsxs("div",{className:"mt-5 flex flex-wrap items-center justify-between gap-3 border-t border-border/70 pt-4",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(zn,{checked:!!((W=r.data)!=null&&W.delivery_active),onCheckedChange:G=>o.mutate({delivery_active:G}),"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"})]}),n?e.jsxs(B,{variant:"outline",size:"sm",onClick:P,disabled:d,children:[d?e.jsx(us,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(Cn,{className:"h-4 w-4 mr-2"}),"Generate this week's pack"]}):null]})]}),e.jsxs(ya,{defaultValue:"current",className:"mt-8",children:[e.jsxs(va,{children:[e.jsx(ls,{value:"current",children:"This week"}),e.jsx(ls,{value:"history",children:"History"}),e.jsxs(ls,{value:"saved",children:["Saved",T.length?` (${T.length})`:""]})]}),e.jsx(_s,{value:"current",className:"mt-6",children:a.isLoading?e.jsx("div",{className:"flex justify-center py-16",children:e.jsx(us,{className:"h-6 w-6 animate-spin text-muted-foreground"})}):i&&i.reels.length?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"mb-4 flex flex-wrap items-center gap-2",children:[e.jsxs(We,{variant:"outline",className:"text-[11.5px]",children:["Week of ",IK(i.week_start_date)]}),e.jsxs("span",{className:"text-[13px] text-muted-foreground",children:[i.reels.filter(G=>G.posted_at).length," of ",i.reels.length," posted"]})]}),e.jsx("div",{className:"space-y-4",children:i.reels.map((G,X)=>e.jsx(Zje,{reel:G,index:X,onUpdate:I(G)},G.id))})]}):e.jsxs(_e,{className:"rounded-2xl p-10 text-center sm:p-14",children:[e.jsx("div",{className:"mx-auto flex h-12 w-12 items-center justify-center rounded-xl bg-muted",children:e.jsx(Rh,{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: ",Zxt(),"."]}),n?e.jsxs(B,{className:"mt-6",onClick:P,disabled:d,children:[d?e.jsx(us,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(Cn,{className:"h-4 w-4 mr-2"}),"Generate it now"]}):null]})}),e.jsxs(_s,{value:"history",className:"mt-6",children:[e.jsx(_e,{className:"rounded-2xl p-4 sm:p-5",children:e.jsxs("div",{className:"grid gap-3 sm:grid-cols-[1fr_auto_auto]",children:[e.jsxs("div",{className:"relative",children:[e.jsx(Gr,{className:"absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground"}),e.jsx(we,{value:h,onChange:G=>m(G.target.value),placeholder:"Search topics and scripts...",className:"pl-9"})]}),e.jsxs(Ns,{value:f,onValueChange:g,children:[e.jsx(ws,{className:"sm:w-[190px]",children:e.jsx(ks,{placeholder:"All topics"})}),e.jsxs(js,{children:[e.jsx(nt,{value:"all",children:"All topics"}),Object.entries(Vze).map(([G,X])=>e.jsx(nt,{value:G,children:X},G))]})]}),e.jsxs(Ns,{value:y,onValueChange:x,children:[e.jsx(ws,{className:"sm:w-[180px]",children:e.jsx(ks,{placeholder:"All weeks"})}),e.jsxs(js,{children:[e.jsx(nt,{value:"all",children:"All weeks"}),(a.data??[]).map(G=>e.jsx(nt,{value:G.week_start_date,children:IK(G.week_start_date)},G.id))]})]})]})}),A.length?e.jsx(qR,{type:"multiple",className:"mt-4 space-y-3",children:A.map(({reel:G,pack:X})=>e.jsxs($E,{value:G.id,className:"rounded-2xl border border-border/70 bg-card px-4 sm:px-5",children:[e.jsx(UE,{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(We,{variant:"outline",className:"text-[10.5px] shrink-0",children:IK(X.week_start_date)}),G.category?e.jsx(We,{className:"bg-muted text-muted-foreground border-0 text-[10.5px] shrink-0",children:Vze[G.category]??G.category}):null,e.jsx("span",{className:"truncate text-[14.5px] font-medium text-foreground",children:G.topic})]})}),e.jsx(qE,{className:"pb-4",children:e.jsx(Zje,{reel:G,index:G.position-1,onUpdate:I(G)})})]},G.id))}):e.jsxs(_e,{className:"mt-4 rounded-2xl p-10 text-center sm:p-14",children:[e.jsx("div",{className:"mx-auto flex h-12 w-12 items-center justify-center rounded-xl bg-muted",children:e.jsx(Gr,{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:k.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(_s,{value:"saved",className:"mt-6",children:T.length?e.jsx("div",{className:"space-y-4",children:T.map(({reel:G},X)=>e.jsx(Zje,{reel:G,index:X,onUpdate:I(G)},G.id))}):e.jsxs(_e,{className:"rounded-2xl p-10 text-center sm:p-14",children:[e.jsx("div",{className:"mx-auto flex h-12 w-12 items-center justify-center rounded-xl bg-muted",children:e.jsx(Wa,{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 K6=[{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 NLn(){const s=tr(),{user:t}=Ls(),{profile:n,saveProfile:r}=PKe(),[a,i]=N.useState(0),[l,o]=N.useState({specialties:[],client_types:[],brand_voice:[],preferred_reel_length:"30-45s",main_platform:"instagram",content_mix:"mix"}),[c,d]=N.useState(!1),[u,h]=N.useState(!1);N.useEffect(()=>{u||n.isLoading||(o(b=>{var k,A,T,P,I,M;return{...b,...n.data??{},full_name:((k=n.data)==null?void 0:k.full_name)??((A=t==null?void 0:t.user_metadata)==null?void 0:A.full_name)??"",email:((T=n.data)==null?void 0:T.email)??(t==null?void 0:t.email)??"",specialties:((P=n.data)==null?void 0:P.specialties)??[],client_types:((I=n.data)==null?void 0:I.client_types)??[],brand_voice:((M=n.data)==null?void 0:M.brand_voice)??[]}}),h(!0))},[n.isLoading,n.data,t,u]);const m=(b,k)=>o(A=>({...A,[b]:k})),f=(b,k)=>o(A=>{const T=A[b]??[];return{...A,[b]:T.includes(k)?T.filter(P=>P!==k):[...T,k]}}),g=N.useMemo(()=>{var b,k,A;return a===0?!!((b=l.full_name)!=null&&b.trim())&&!!((k=l.email)!=null&&k.trim()):a===1?!!((A=l.primary_market)!=null&&A.trim()):a===2?(l.brand_voice??[]).length>0:!0},[a,l]),y=async(b,k)=>{if(t){d(!0);try{const A=b.name.split(".").pop(),T=`${t.id}/weekly-reels-${k}-${Date.now()}.${A}`,{error:P}=await H.storage.from("avatars").upload(T,b,{upsert:!0});if(P)throw P;const{data:I}=H.storage.from("avatars").getPublicUrl(T);m(k,I.publicUrl),ie.success("Image uploaded")}catch(A){ie.error(A instanceof Error?A.message:"Upload failed")}finally{d(!1)}}},x=async()=>{await r.mutateAsync({...l,onboarding_completed:!0}),ie.success("You're all set — your first pack is on the way."),s("/weekly-reels")},_=async()=>{await r.mutateAsync(l),ie.success("Progress saved")};return e.jsx(Qs,{title:"Weekly Reels",children:e.jsxs("div",{className:"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:"text-[11px] font-semibold uppercase tracking-[0.14em] text-primary",children:"Weekly Reels"}),e.jsx("h1",{className:"mt-2 text-2xl sm:text-3xl font-semibold tracking-tight text-foreground",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 ",K6.length," · ",K6[a].title]}),e.jsxs("span",{children:[Math.round((a+1)/K6.length*100),"%"]})]}),e.jsx(ro,{value:(a+1)/K6.length*100,className:"mt-2 h-1.5"})]}),e.jsxs(_e,{className:"rounded-2xl p-5 sm:p-7",children:[e.jsx("h2",{className:"text-lg font-semibold tracking-tight text-foreground",children:K6[a].title}),e.jsx("p",{className:"mt-1 text-[14px] text-muted-foreground",children:K6[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(re,{children:"Full name *"}),e.jsx(we,{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(re,{children:"Email *"}),e.jsx(we,{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(re,{children:"Mobile number"}),e.jsx(we,{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(re,{children:"Brokerage"}),e.jsx(we,{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(re,{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:k=>{var T;const A=(T=k.target.files)==null?void 0:T[0];A&&y(A,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(us,{className:"h-4 w-4 animate-spin"}):e.jsx(ni,{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(re,{children:"Primary market — city & state *"}),e.jsx(we,{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(re,{children:"Neighborhoods or service areas"}),e.jsx(Ws,{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(re,{children:"Years in real estate"}),e.jsxs(Ns,{value:l.years_in_real_estate??"",onValueChange:b=>m("years_in_real_estate",b),children:[e.jsx(ws,{children:e.jsx(ks,{placeholder:"Select"})}),e.jsx(js,{children:xLn.map(b=>e.jsx(nt,{value:b,children:b},b))})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(re,{children:"Typical price point"}),e.jsxs(Ns,{value:l.typical_price_point??"",onValueChange:b=>m("typical_price_point",b),children:[e.jsx(ws,{children:e.jsx(ks,{placeholder:"Select"})}),e.jsx(js,{children:gLn.map(b=>e.jsx(nt,{value:b,children:b},b))})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{children:"Primary specialties / niches"}),e.jsx("div",{className:"grid gap-2 sm:grid-cols-2",children:hLn.map(b=>e.jsxs("label",{className:"flex items-center gap-2.5 text-[14px]",children:[e.jsx(Bi,{checked:(l.specialties??[]).includes(b),onCheckedChange:()=>f("specialties",b)}),b]},b))})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{children:"Client types you serve"}),e.jsx("div",{className:"grid gap-2 sm:grid-cols-2",children:mLn.map(b=>e.jsxs("label",{className:"flex items-center gap-2.5 text-[14px]",children:[e.jsx(Bi,{checked:(l.client_types??[]).includes(b),onCheckedChange:()=>f("client_types",b)}),b]},b))})]})]}),a===2&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{children:"Brand voice — pick everything that fits *"}),e.jsx("div",{className:"grid gap-2 sm:grid-cols-2",children:pLn.map(b=>e.jsxs("label",{className:"flex items-center gap-2.5 text-[14px]",children:[e.jsx(Bi,{checked:(l.brand_voice??[]).includes(b),onCheckedChange:()=>f("brand_voice",b)}),b]},b))})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(re,{children:"Anything else about how you talk?"}),e.jsx(Ws,{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(re,{children:"Humor level"}),e.jsx(K1,{value:l.humor_level??"",onValueChange:b=>m("humor_level",b),className:"space-y-1.5",children:fLn.map(b=>e.jsxs("label",{className:"flex items-center gap-2.5 text-[14px]",children:[e.jsx(Ju,{value:b.value}),b.label]},b.value))})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(re,{children:"Personal interests & hobbies"}),e.jsx(Ws,{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(re,{children:"Family or community details you're happy to reference"}),e.jsx(Ws,{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(re,{children:"Preferred Reel length"}),e.jsxs(Ns,{value:l.preferred_reel_length??"30-45s",onValueChange:b=>m("preferred_reel_length",b),children:[e.jsx(ws,{children:e.jsx(ks,{})}),e.jsx(js,{children:bLn.map(b=>e.jsx(nt,{value:b.value,children:b.label},b.value))})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(re,{children:"Preferred CTA style"}),e.jsxs(Ns,{value:l.preferred_cta_style??"",onValueChange:b=>m("preferred_cta_style",b),children:[e.jsx(ws,{children:e.jsx(ks,{placeholder:"Select"})}),e.jsx(js,{children:yLn.map(b=>e.jsx(nt,{value:b.value,children:b.label},b.value))})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(re,{children:"Main social platform"}),e.jsxs(Ns,{value:l.main_platform??"instagram",onValueChange:b=>m("main_platform",b),children:[e.jsx(ws,{children:e.jsx(ks,{})}),e.jsx(js,{children:vLn.map(b=>e.jsx(nt,{value:b.value,children:b.label},b.value))})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(re,{children:"Instagram handle"}),e.jsx(we,{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(re,{children:"Website"}),e.jsx(we,{value:l.website??"",onChange:b=>m("website",b.target.value),placeholder:"https://janerealtor.com"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{children:"On-camera comfort level"}),e.jsx(K1,{value:l.content_comfort_level??"",onValueChange:b=>m("content_comfort_level",b),className:"space-y-1.5",children:_Ln.map(b=>e.jsxs("label",{className:"flex items-center gap-2.5 text-[14px]",children:[e.jsx(Ju,{value:b.value}),b.label]},b.value))})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{children:"Local vs evergreen content"}),e.jsx(K1,{value:l.content_mix??"mix",onValueChange:b=>m("content_mix",b),className:"space-y-1.5",children:wLn.map(b=>e.jsxs("label",{className:"flex items-center gap-2.5 text-[14px]",children:[e.jsx(Ju,{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(re,{children:"Topics you love talking about"}),e.jsx(Ws,{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(re,{children:"Topics you never want to cover"}),e.jsx(Ws,{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(re,{children:"Lead magnets or offers to promote"}),e.jsx(Ws,{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(re,{children:"Current business goals"}),e.jsx(Ws,{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(re,{children:"Compliance or brokerage disclaimer notes"}),e.jsx(Ws,{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:_,disabled:r.isPending,children:"Save draft"}),ai(b=>b+1),children:["Continue ",e.jsx(vi,{className:"h-4 w-4 ml-1.5"})]}):e.jsxs(B,{type:"button",onClick:x,disabled:r.isPending,children:[r.isPending?e.jsx(us,{className:"h-4 w-4 mr-1.5 animate-spin"}):e.jsx(pa,{className:"h-4 w-4 mr-1.5"}),"Finish setup"]})]})]})]})]})})}function kBt(s,t=!1){const{user:n}=Ls(),r=as(),a=mt({queryKey:["wr-admin-members",s,t,n==null?void 0:n.id],enabled:!!n,queryFn:async()=>{let y=null;if(t){const{data:z,error:$}=await H.from("feature_entitlements").select("user_id").eq("feature_key",D7).eq("enabled",!0);if($)throw $;if(y=(z??[]).map(V=>V.user_id),!y.length)return[]}let x=H.from("profiles").select("id, email, name").order("name",{ascending:!0}).limit(t?1e3:100);if(y&&(x=x.in("id",y)),s.trim()){const z=`%${s.trim()}%`;x=x.or(`email.ilike.${z},name.ilike.${z}`)}const{data:_,error:b}=await x;if(b)throw b;const k=(_??[]).map(z=>z.id);if(!k.length)return[];const[{data:A},{data:T},{data:P}]=await Promise.all([H.from("feature_entitlements").select("user_id, enabled, tier, expires_at").eq("feature_key",D7).in("user_id",k),H.from("weekly_reel_profiles").select("user_id, onboarding_completed, delivery_active, primary_market").in("user_id",k),H.from("weekly_reel_packs").select("id, user_id, week_start_date, generation_status, delivery_status").in("user_id",k).order("week_start_date",{ascending:!1})]),I=new Map((A??[]).map(z=>[z.user_id,z])),M=new Map((T??[]).map(z=>[z.user_id,z])),L=new Map;return(P??[]).forEach(z=>{L.has(z.user_id)||L.set(z.user_id,z)}),(_??[]).map(z=>{const $=I.get(z.id),V=M.get(z.id),W=L.get(z.id);return{user_id:z.id,email:z.email,full_name:z.name,enabled:!!($!=null&&$.enabled),tier:($==null?void 0:$.tier)??null,expires_at:($==null?void 0:$.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:(W==null?void 0:W.week_start_date)??null,latest_pack_id:(W==null?void 0:W.id)??null,latest_generation_status:(W==null?void 0:W.generation_status)??null,latest_delivery_status:(W==null?void 0:W.delivery_status)??null}})}}),i=mt({queryKey:["wr-admin-generation-logs"],enabled:!!n,queryFn:async()=>{const{data:y,error:x}=await H.from("weekly_reel_generation_logs").select("*").order("created_at",{ascending:!1}).limit(100);if(x)throw x;return y??[]}}),l=mt({queryKey:["wr-admin-delivery-logs"],enabled:!!n,queryFn:async()=>{const{data:y,error:x}=await H.from("weekly_reel_delivery_logs").select("*").order("created_at",{ascending:!1}).limit(100);if(x)throw x;return y??[]}}),o=()=>{r.invalidateQueries({queryKey:["wr-admin-members"]}),r.invalidateQueries({queryKey:["wr-admin-generation-logs"]}),r.invalidateQueries({queryKey:["wr-admin-delivery-logs"]})},c=_t({mutationFn:async({userId:y,enabled:x})=>{const{error:_}=await H.from("feature_entitlements").upsert({user_id:y,feature_key:D7,enabled:x,tier:"member",enabled_by:n.id,enabled_at:new Date().toISOString()},{onConflict:"user_id,feature_key"});if(_)throw _;await H.from("feature_entitlement_audit").insert({feature_key:D7,target_user_id:y,action:x?"grant":"revoke",performed_by:n.id})},onSuccess:(y,x)=>{o(),ie.success(x.enabled?"Access granted":"Access revoked")},onError:y=>ie.error(y.message)}),d=async y=>{const{data:x,error:_}=await H.functions.invoke("weekly-reels-generate",{body:y});if(_)throw _;if(x!=null&&x.error)throw new Error(String(x.error));return x},u=_t({mutationFn:y=>d({action:"generate_pack",userId:y.userId,force:y.force??!0}),onSuccess:()=>{o(),ie.success("Pack generated")},onError:y=>ie.error(y.message)}),h=_t({mutationFn:y=>d({action:"regenerate_reel",reelId:y.reelId,instructions:y.instructions}),onSuccess:()=>{o(),ie.success("Reel regenerated")},onError:y=>ie.error(y.message)}),m=_t({mutationFn:y=>d({action:"send_pack_email",packId:y.packId}),onSuccess:()=>{o(),ie.success("Pack emailed")},onError:y=>ie.error(y.message)}),f=_t({mutationFn:y=>d({action:"send_test_email",packId:y.packId,to:y.to}),onSuccess:()=>ie.success("Test email sent"),onError:y=>ie.error(y.message)}),g=_t({mutationFn:()=>d({action:"run_weekly"}),onSuccess:y=>{o(),ie.success(`Weekly run complete${(y==null?void 0:y.processed)!=null?` — ${y.processed} agents`:""}`)},onError:y=>ie.error(y.message)});return{members:a,generationLogs:i,deliveryLogs:l,setAccess:c,generatePack:u,regenerateReel:h,sendPack:m,sendTest:f,runWeekly:g}}function Z7({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(We,{className:`${t} border-0 text-[11px] capitalize`,children:s})}function kLn({member:s,onClose:t}){var m,f,g;const n=kBt(""),{packs:r,profile:a}=PKe(s==null?void 0:s.user_id),[i,l]=N.useState(""),[o,c]=N.useState(""),[d,u]=N.useState(null),h=((m=r.data)==null?void 0:m[0])??null;return e.jsx(Bs,{open:!!s,onOpenChange:y=>!y&&t(),children:e.jsxs(Fs,{className:"max-w-3xl max-h-[88vh] overflow-y-auto",children:[e.jsxs(qs,{children:[e.jsx($s,{children:(s==null?void 0:s.full_name)||(s==null?void 0:s.email)}),e.jsxs(Ar,{children:[((f=a.data)==null?void 0:f.primary_market)??"No market on file"," ·"," ",(g=a.data)!=null&&g.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(us,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(Cn,{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(mn,{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(re,{className:"text-[12px]",children:"Send a test copy to"}),e.jsx(we,{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(Rr,{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(We,{variant:"outline",children:["Week of ",IK(h.week_start_date)]}),e.jsx(Z7,{value:h.generation_status}),e.jsx(Z7,{value:h.delivery_status})]}),h.reels.map((y,x)=>e.jsxs("div",{className:"space-y-2",children:[e.jsx(Zje,{reel:y,index:x,readOnly:!0}),d===y.id?e.jsxs("div",{className:"rounded-xl border border-border/70 p-3 space-y-2",children:[e.jsx(Ws,{rows:2,value:o,onChange:_=>c(_.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(us,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(oo,{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(oo,{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(Cr,{children:e.jsx(B,{variant:"outline",onClick:t,children:"Close"})})]})})}function SLn(){const[s,t]=N.useState(""),[n,r]=N.useState(!1),[a,i]=N.useState(null),l=kBt(s,n),o=N.useMemo(()=>l.members.data??[],[l.members.data]);return e.jsxs(Qs,{title:"Weekly Reels Admin",children:[e.jsxs("div",{className:"mx-auto w-full max-w-6xl px-4 py-8 sm:px-6",children:[e.jsxs("div",{className:"flex flex-wrap items-start justify-between gap-4",children:[e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl font-semibold tracking-tight text-foreground",children:"Weekly Reels"}),e.jsx("p",{className:"mt-1.5 text-[15px] text-muted-foreground",children:"Manage access, generate packs and monitor Monday delivery."})]}),e.jsxs(B,{onClick:()=>l.runWeekly.mutate(),disabled:l.runWeekly.isPending,children:[l.runWeekly.isPending?e.jsx(us,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(Cn,{className:"h-4 w-4 mr-2"}),"Run this week now"]})]}),e.jsxs(ya,{defaultValue:"members",className:"mt-7",children:[e.jsxs(va,{children:[e.jsx(ls,{value:"members",children:"Members"}),e.jsx(ls,{value:"generation",children:"Generation log"}),e.jsx(ls,{value:"delivery",children:"Delivery log"})]}),e.jsxs(_s,{value:"members",className:"mt-5",children:[e.jsx(_e,{className:"rounded-2xl p-4 sm:p-5",children:e.jsxs("div",{className:"flex flex-wrap items-center gap-4",children:[e.jsxs("div",{className:"relative min-w-[220px] flex-1",children:[e.jsx(Gr,{className:"absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground"}),e.jsx(we,{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(zn,{checked:n,onCheckedChange:r}),"Only members with access"]})]})}),e.jsx(_e,{className:"mt-4 rounded-2xl overflow-hidden",children:e.jsxs(Oa,{children:[e.jsx(Fa,{children:e.jsxs(un,{children:[e.jsx(Mt,{children:"Agent"}),e.jsx(Mt,{children:"Market"}),e.jsx(Mt,{children:"Onboarded"}),e.jsx(Mt,{children:"Latest week"}),e.jsx(Mt,{children:"Generation"}),e.jsx(Mt,{children:"Delivery"}),e.jsx(Mt,{className:"text-right",children:"Access"}),e.jsx(Mt,{})]})}),e.jsx(za,{children:l.members.isLoading?e.jsx(un,{children:e.jsx(gt,{colSpan:8,className:"py-10 text-center",children:e.jsx(us,{className:"mx-auto h-5 w-5 animate-spin text-muted-foreground"})})}):o.length?o.map(c=>e.jsxs(un,{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(We,{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?IK(c.latest_week):"—"}),e.jsx(gt,{children:e.jsx(Z7,{value:c.latest_generation_status})}),e.jsx(gt,{children:e.jsx(Z7,{value:c.latest_delivery_status})}),e.jsx(gt,{className:"text-right",children:e.jsx(zn,{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(un,{children:e.jsx(gt,{colSpan:8,className:"py-10 text-center text-muted-foreground",children:"No members match this search."})})})]})})]}),e.jsx(_s,{value:"generation",className:"mt-5",children:e.jsx(_e,{className:"rounded-2xl overflow-hidden",children:e.jsxs(Oa,{children:[e.jsx(Fa,{children:e.jsxs(un,{children:[e.jsx(Mt,{children:"When"}),e.jsx(Mt,{children:"Status"}),e.jsx(Mt,{children:"Model"}),e.jsx(Mt,{children:"Tokens"}),e.jsx(Mt,{children:"Cost"}),e.jsx(Mt,{children:"Error"})]})}),e.jsx(za,{children:(l.generationLogs.data??[]).map(c=>e.jsxs(un,{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(Z7,{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(_s,{value:"delivery",className:"mt-5",children:e.jsx(_e,{className:"rounded-2xl overflow-hidden",children:e.jsxs(Oa,{children:[e.jsx(Fa,{children:e.jsxs(un,{children:[e.jsx(Mt,{children:"When"}),e.jsx(Mt,{children:"Recipient"}),e.jsx(Mt,{children:"Status"}),e.jsx(Mt,{children:"Error"})]})}),e.jsx(za,{children:(l.deliveryLogs.data??[]).map(c=>e.jsxs(un,{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(Z7,{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(kLn,{member:a,onClose:()=>i(null)})]})}function RJ(){const{user:s}=Ls(),t=as(),n=mt({queryKey:["attract-settings",s==null?void 0:s.id],enabled:!!s,queryFn:async()=>{const{data:i,error:l}=await H.from("attract_settings").select("*").eq("user_id",s.id).maybeSingle();if(l)throw l;return i}}),r=_t({mutationFn:async i=>{const l={...i,user_id:s.id},{data:o,error:c}=await H.from("attract_settings").upsert(l,{onConflict:"user_id"}).select().single();if(c)throw c;return o},onSuccess:()=>{t.invalidateQueries({queryKey:["attract-settings"]}),ie.success("Settings saved")},onError:i=>ie.error(i.message)}),a=_t({mutationFn:async()=>{const{error:i}=await H.from("attract_settings").update({onboarding_completed_at:null}).eq("user_id",s.id);if(i)throw i},onSuccess:()=>{t.invalidateQueries({queryKey:["attract-settings"]}),ie.success("Onboarding reset — run it again anytime")}});return{settings:n.data,isLoading:n.isLoading,save:r,upsert:r,resetOnboarding:a}}const SBt="v1",mh={recency:22,consistency:16,value_delivered:14,kit_engagement:16,event_participation:12,follow_up_discipline:10,pipeline_momentum:10};Object.values(mh).reduce((s,t)=>s+t,0);const CBt=864e5,Hg=(s,t=new Date)=>Math.floor((new Date(t).getTime()-new Date(s).getTime())/CBt),ABt=["touch_logged","call","text","email","dm","meeting","note"];function CLn(s,t,n=new Date){var y,x,_;const a=t.activities.filter(b=>b.agent_id===s.id).filter(b=>ABt.includes(b.activity_type)).sort((b,k)=>+new Date(k.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[x=b.share_id]||(d[x]=[])).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),f=t.stageChanges.filter(b=>b.agent_id===s.id).sort((b,k)=>+new Date(k.created_at)-+new Date(b.created_at)),g=new Set(a.filter(b=>Hg(b.created_at,n)<=180).map(b=>b.created_at.slice(0,7)));return{agent:s,touches:a,lastTouchAt:i,daysSinceTouch:i?Hg(i,n):null,touches90:a.filter(b=>Hg(b.created_at,n)<=90).length,touches30:a.filter(b=>Hg(b.created_at,n)<=30).length,distinctTouchMonths:g.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,k)=>b+(k.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:f,lastStageChangeAt:((_=f[0])==null?void 0:_.created_at)||null,daysSinceStageChange:f[0]?Hg(f[0].created_at,n):null,scoreEvents:t.scoreEvents.filter(b=>b.agent_id===s.id)}}const Xje=["new_connection","building_relationship","engaging_with_value","active_conversation","exploring_options","brokerage_presentation","decision_pending","joined"],Qje=["not_right_now","not_a_fit","long_term_relationship"];function ALn(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=mh.recency,c=`Last meaningful touch ${l} day(s) ago.`,r.push("Recent personal contact")):l<=21?(o=mh.recency*.85,c=`Last touch ${l} days ago.`,r.push("Contact is still fresh")):l<=45?(o=mh.recency*.6,c=`Last touch ${l} days ago.`,i.push("Reach out within the next week to keep momentum.")):l<=90?(o=mh.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=mh.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:mh.recency,earned:Math.round(o),detail:c,direction:o>=mh.recency*.6?"positive":"negative"});const d=Math.min(s.distinctTouchMonths,6),u=mh.consistency*(d/6),h=s.touches30>6;n.push({key:"consistency",label:"Consistency of touches",weight:mh.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>=mh.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,f=mh.value_delivered*Math.min(m/3,1);n.push({key:"value_delivered",label:"Value delivered",weight:mh.value_delivered,earned:Math.round(f),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 g=(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(g,mh.kit_engagement);n.push({key:"kit_engagement",label:"Kit engagement",weight:mh.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 x=Math.min(s.attended,2)*5+(s.attendees.length?2:0)-Math.min(s.noShows,2)*2,_=Math.max(0,Math.min(x,mh.event_participation));n.push({key:"event_participation",label:"Event participation",weight:mh.event_participation,earned:_,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:_>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 k=b===0?mh.follow_up_discipline*.4:mh.follow_up_discipline*(s.completedFollowUps.length/b);k-=Math.min(s.overdueFollowUps.length,3)*2,k=Math.max(0,Math.min(k,mh.follow_up_discipline)),n.push({key:"follow_up_discipline",label:"Follow-up discipline",weight:mh.follow_up_discipline,earned:Math.round(k),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 A=Xje.indexOf(s.agent.stage);let T=0,P;if(Qje.includes(s.agent.stage))T=mh.pipeline_momentum*.3,P="Relationship is intentionally parked — long-term nurture.";else if(A<0)T=mh.pipeline_momentum*.3,P=`Stage "${s.agent.stage}" is outside the advancing ladder.`;else{const L=mh.pipeline_momentum*(A/(Xje.length-1)),z=s.daysSinceStageChange!==null&&s.daysSinceStageChange>60;T=z?L*.5:L,P=`Stage ${A+1} of ${Xje.length}`+(s.daysSinceStageChange!==null?`, last moved ${s.daysSinceStageChange} days ago.`:", never moved."),z&&(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:mh.pipeline_momentum,earned:Math.round(T),detail:P,direction:T>mh.pipeline_momentum*.5?"positive":"neutral"});let I=n.reduce((L,z)=>L+z.earned,0);s.agent.temperature==="hot"&&(I+=4,r.push("You marked this relationship hot")),s.agent.temperature==="cold"&&(I-=4,a.push("You marked this relationship cold")),h&&(I-=3),I=Math.max(0,Math.min(100,Math.round(I)));const M=I>=75?"thriving":I>=55?"healthy":I>=35?"cooling":"at_risk";return{agent_id:s.agent.id,score:I,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:{...mh},engine_version:SBt,calculated_at:t.toISOString()}}const TBt=[{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"}],TLn={urgent:100,high:70,medium:40,low:15},Ew=(s,t=new Date)=>new Date(t.getTime()+s*CBt).toISOString(),mk=s=>s.first_name||"there",ELn=3;function Mw(s,t,n={}){var o,c;const r=mk(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 MLn(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 _;return(_=t.kits.find(b=>b.id===x))==null?void 0:_.title},o=x=>{r.push({...x,message_source:"rules",rank_score:x.rank_score??TLn[x.priority]})},c=s.shares.find(x=>x.engagement_level==="high_intent");if(s.meetingRequests>0||s.questions>0||c){const x=c?l(c.kit_id):void 0,_=[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 ${mk(a)} — they are actively engaging`,reasons:_,priority:"urgent",suggested_due_at:Ew(1,n),draft_message:Mw("high_intent",s,{kitTitle:x}),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(x=>x.last_opened_at&&x.first_opened_at&&Hg(x.last_opened_at,n)<=7&&Hg(x.first_opened_at,x.last_opened_at)>=14&&(x.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:`${mk(a)} came back to a kit you shared`,reasons:[`Re-opened "${l(d.kit_id)??"a shared kit"}" ${Hg(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:Ew(2,n),draft_message:Mw("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(x=>x.checked_in_at&&Hg(x.checked_in_at,n)<=7&&x.followup_status!=="done").sort((x,_)=>+new Date(_.checked_in_at)-+new Date(x.checked_in_at))[0];if(u){const x=t.events.find(b=>b.id===u.event_id),_=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 ${(x==null?void 0:x.title)??"the event"} — ${_}h since they attended`,reasons:[`Checked in to "${(x==null?void 0:x.title)??"event"}" ${_} hours ago`,`Follow-up status is "${u.followup_status??"pending"}"`,_<=48?"Inside the 48-hour window where follow-up matters most":"Past the ideal 48-hour window — still worth doing today"],priority:_<=48?"urgent":"high",suggested_due_at:Ew(_<=48?1:0,n),draft_message:Mw("event_follow_up",s,{eventTitle:x==null?void 0:x.title}),suggested_event_id:u.event_id,suggested_kit_id:(x==null?void 0:x.resource_kit_id)??null,source_signals:{attendee_id:u.id,hours_since:_},rank_score:_<=48?96:74})}else{const x=s.attendees.find(_=>_.no_show_at&&Hg(_.no_show_at,n)<=10);if(x){const _=t.events.find(b=>b.id===x.event_id);o({agent_id:a.id,rec_key:`event_no_show:${x.event_id}`,signal_group:"event_follow_up",signal_label:"Event follow-up needed",action_type:"no_show_recovery",channel:"text",title:`${mk(a)} missed ${(_==null?void 0:_.title)??"an event"} — recover gracefully`,reasons:[`Registered but did not attend "${(_==null?void 0:_.title)??"event"}"`,"No-show recovery works best within a week, with zero guilt"],priority:"medium",suggested_due_at:Ew(2,n),draft_message:Mw("event_no_show",s,{eventTitle:_==null?void 0:_.title}),suggested_event_id:x.event_id,source_signals:{attendee_id:x.id},rank_score:52})}}const h=s.shares.find(x=>x.first_opened_at&&Hg(x.first_opened_at,n)>=3&&Hg(x.first_opened_at,n)<=30&&(s.daysSinceTouch===null||s.lastTouchAt&&new Date(s.lastTouchAt)!x.first_opened_at&&Hg(x.created_at,n)>=5&&x.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 ${Hg(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:Ew(2,n),draft_message:Mw("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 ${mk(a)} personally`,reasons:[`Shared ${Hg(m.created_at,n)} days ago and never opened`,"A personal message beats a resend"],priority:"medium",suggested_due_at:Ew(2,n),draft_message:Mw("resource_unopened",s,{kitTitle:l(m.kit_id)}),suggested_kit_id:m.kit_id,source_signals:{share_id:m.id},rank_score:46});const f=s.overdueFollowUps.sort((x,_)=>+new Date(x.due_at)-+new Date(_.due_at))[0];if(f){const x=Hg(f.due_at,n);o({agent_id:a.id,rec_key:`overdue:${f.id}`,signal_group:"overdue_commitment",signal_label:"Overdue commitment",action_type:"clear_overdue",channel:f.touch_type||"call",title:`Overdue ${x} day(s): ${f.title}`,reasons:[`Follow-up "${f.title}" was due ${x} day(s) ago`,`Priority: ${f.priority??"medium"}`],priority:x>7?"urgent":"high",suggested_due_at:Ew(0,n),draft_message:Mw("overdue_commitment",s,{followUpTitle:f.title}),source_signals:{follow_up_id:f.id,days_late:x},rank_score:92+Math.min(x,8)})}const g=Xje.indexOf(a.stage);if(!Qje.includes(a.stage)&&g>=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 ${mk(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:Ew(4,n),draft_message:Mw("ready_deeper",s),source_signals:{stage:a.stage,attended:s.attended},rank_score:72}),s.daysSinceTouch===null&&Hg(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 ${mk(a)}`,reasons:[`Added to your pipeline ${Hg(a.created_at,n)} days ago`,"No touch, kit, or event activity logged"],priority:"medium",suggested_due_at:Ew(3,n),draft_message:Mw("no_touch",s),source_signals:{created_at:a.created_at},rank_score:48});else if(s.daysSinceTouch!==null){const x=a.temperature==="hot"?14:a.temperature==="cold"?90:45;if(s.daysSinceTouch>x){const _=s.daysSinceTouch>x*2;o({agent_id:a.id,rec_key:_?"no_touch_long":"going_cold",signal_group:_?"no_touch":"going_cold",signal_label:_?"No meaningful touch recently":"Relationship going cold",action_type:"check_in",channel:"personal_check_in",title:`${mk(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 ${x} days`,s.touches90?`${s.touches90} touch(es) in the last 90 days`:"No touches in the last 90 days"],priority:_?"high":"medium",suggested_due_at:Ew(3,n),draft_message:Mw(_?"no_touch":"going_cold",s),source_signals:{days_since_touch:s.daysSinceTouch,threshold:x},rank_score:_?62:44})}}if(!s.shares.length&&!Qje.includes(a.stage)&&t.primaryPillar==="provide"){const x=t.kits.find(_=>_.status==="published"&&(!_.audience||!a.production_context||!0));x&&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 "${x.title}" with ${mk(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:Ew(5,n),draft_message:Mw("share_value",s,{kitTitle:x.title}),suggested_kit_id:x.id,source_signals:{pillar:"provide"},rank_score:38})}if(!s.attendees.length&&!Qje.includes(a.stage)&&t.primaryPillar==="connect"){const x=t.events.filter(_=>_.status==="published"&&_.starts_at&&new Date(_.starts_at)>n).sort((_,b)=>+new Date(_.starts_at)-+new Date(b.starts_at))[0];x&&o({agent_id:a.id,rec_key:`invite_event:${x.id}`,signal_group:"ready_deeper",signal_label:"Ready for a deeper conversation",action_type:"invite_to_event",channel:"event_invitation",title:`Invite ${mk(a)} to ${x.title}`,reasons:["Never invited to an event",`"${x.title}" is published and upcoming`,"Your 90-day plan primary pillar is Connect"],priority:"medium",suggested_due_at:Ew(4,n),draft_message:Mw("event_invite_nudge",s,{eventTitle:x.title,eventWhen:x.starts_at?new Date(x.starts_at).toLocaleDateString():void 0}),suggested_event_id:x.id,source_signals:{pillar:"connect",event_id:x.id},rank_score:40})}return(i?r.filter(x=>x.priority==="urgent"):r).sort((x,_)=>_.rank_score-x.rank_score).slice(0,3)}const Xxt=[{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"]}],LLn={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 PLn(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:ABt.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 ILn(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(f=>f.event_type==="file_download").length,l=a.filter(f=>f.event_type==="primary_cta_click"||f.event_type==="external_link_click").length,o=a.filter(f=>f.event_type==="question_submitted").length,c=a.filter(f=>f.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(f=>f.agent_id===s.agent.id&&new Date(f.created_at)>=new Date(r.created_at)).sort((f,g)=>+new Date(f.created_at)-+new Date(g.created_at))[0]??null,h=s.stageChanges.filter(f=>new Date(f.created_at)>new Date(r.created_at)).sort((f,g)=>+new Date(f.created_at)-+new Date(g.created_at))[0]??null;return{share:r,kitTitle:((m=t.kits.find(f=>f.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 DLn(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 Qu=H;function RLn(){const{user:s}=Ls();return mt({queryKey:["attract-intel-data",s==null?void 0:s.id],enabled:!!s,staleTime:3e4,queryFn:async()=>{var g,y;const[t,n,r,a,i,l,o,c,d,u,h,m]=await Promise.all([Qu.from("attract_agents").select("*").order("updated_at",{ascending:!1}),Qu.from("attract_activities").select("*").order("created_at",{ascending:!1}).limit(2e3),Qu.from("attract_follow_ups").select("*").order("created_at",{ascending:!1}).limit(2e3),Qu.from("attract_kit_shares").select("*").order("created_at",{ascending:!1}).limit(1e3),Qu.from("attract_kit_events").select("*").order("created_at",{ascending:!1}).limit(2e3),Qu.from("attract_event_attendees").select("*").order("created_at",{ascending:!1}).limit(2e3),Qu.from("attract_events").select("id, title, starts_at, status, resource_kit_id, public_slug").limit(500),Qu.from("attract_pipeline_history").select("*").order("created_at",{ascending:!1}).limit(2e3),Qu.from("attract_score_events").select("*").order("created_at",{ascending:!1}).limit(2e3),Qu.from("attract_resource_kits").select("id, title, audience, pillar, status, is_template").eq("is_template",!1),Qu.from("attract_event_notes").select("*").order("created_at",{ascending:!1}).limit(1e3),Qu.from("attract_settings").select("primary_pillar, attraction_style, ninety_day_plan").eq("user_id",s.id).maybeSingle()]),f=[t,n,r,a,i,l,o,c,d,u,h].find(x=>x.error);if(f)throw f.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:((g=m==null?void 0:m.data)==null?void 0:g.primary_pillar)??((y=m==null?void 0:m.data)==null?void 0:y.attraction_style)??null}}})}function gO(){const s=RLn(),t=N.useMemo(()=>{if(!s.data)return[];const r=new Date;return s.data.agents.map(a=>{const i=CLn(a,s.data,r),l=ALn(i,r),o=MLn(i,s.data,r);return{agent:a,signals:i,score:l,recommendations:o,primary:o[0]??null}})},[s.data]),n=N.useMemo(()=>new Map(t.map(r=>[r.agent.id,r])),[t]);return{...s,dataset:s.data,intel:t,byId:n}}function OLn(s){const{dataset:t,byId:n,isLoading:r,error:a,refetch:i}=gO(),l=s?n.get(s)??null:null,o=N.useMemo(()=>l&&t?PLn(l.signals,t,t.eventNotes??[]):[],[l,t]),c=N.useMemo(()=>l&&t?ILn(l.signals,t,typeof window<"u"?window.location.origin:""):[],[l,t]),d=N.useMemo(()=>l&&t?DLn(l.signals,t):null,[l,t]);return{item:l,dataset:t,timeline:o,valueShared:c,nextKit:d,isLoading:r,error:a,refetch:i}}function EBt(){const{user:s}=Ls(),t=as();return _t({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:SBt,calculated_at:i.score.calculated_at}));for(let i=0;i{t.invalidateQueries({queryKey:["attract-score-snapshots"]}),n&&!r&&ie.success(`Recalculated ${n} relationship score${n===1?"":"s"}`)},onError:n=>ie.error(n.message??"Could not save scores")})}function IKe(){const{user:s}=Ls();return mt({queryKey:["attract-recommendations",s==null?void 0:s.id],enabled:!!s,queryFn:async()=>{const{data:t,error:n}=await Qu.from("attract_recommendations").select("*").order("rank_score",{ascending:!1});if(n)throw n;return t??[]}})}function DKe(){const{user:s}=Ls(),t=as();return _t({mutationFn:async n=>{if(!s)return{inserted:0,refreshed:0};const r=n.flatMap(u=>u.recommendations),{data:a,error:i}=await Qu.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),f={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:{...f,generated_at:d.toISOString()}}):m.status==="snoozed"&&m.snoozed_until&&new Date(m.snoozed_until)<=d&&c.push({id:m.id,patch:{...f,status:"open",snoozed_until:null,generated_at:d.toISOString()}}):o.push(f)}if(o.length){const{error:u}=await Qu.from("attract_recommendations").insert(o);if(u)throw u}for(const u of c)await Qu.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=>ie.error(n.message??"Could not sync recommendations")})}function MBt(){const{user:s}=Ls(),t=as(),n=()=>{t.invalidateQueries({queryKey:["attract-recommendations"]}),t.invalidateQueries({queryKey:["attract-followups"]}),t.invalidateQueries({queryKey:["attract-intel-data"]}),t.invalidateQueries({queryKey:["attract-activities"]})},r=_t({mutationFn:async({id:c,patch:d})=>{const{error:u}=await Qu.from("attract_recommendations").update(d).eq("id",c);if(u)throw u},onSuccess:n,onError:c=>ie.error(c.message)}),a=_t({mutationFn:async c=>{const{error:d}=await Qu.from("attract_recommendations").update({status:"dismissed",dismissed_at:new Date().toISOString()}).eq("id",c);if(d)throw d},onSuccess:()=>{n(),ie.success("Dismissed")}}),i=_t({mutationFn:async({id:c,days:d})=>{const u=new Date(Date.now()+d*864e5).toISOString(),{error:h}=await Qu.from("attract_recommendations").update({status:"snoozed",snoozed_until:u}).eq("id",c);if(h)throw h},onSuccess:()=>{n(),ie.success("Snoozed")}}),l=_t({mutationFn:async c=>{if(c.follow_up_id){const{data:h}=await Qu.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 Qu.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 Qu.from("attract_recommendations").update({follow_up_id:d.id}).eq("id",c.id),{id:d.id,existed:!1}},onSuccess:c=>{n(),ie.success(c.existed?"Follow-up already exists":"Follow-up created")},onError:c=>ie.error(c.message)}),o=_t({mutationFn:async({rec:c,note:d})=>{const u=new Date().toISOString(),{error:h}=await Qu.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 Qu.from("attract_follow_ups").update({completed_at:u}).eq("id",c.follow_up_id).is("completed_at",null),await Qu.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 Qu.from("attract_recommendations").update({status:"completed",completed_at:u}).eq("id",c.id);if(m)throw m},onSuccess:()=>{n(),t.invalidateQueries({queryKey:["attract-score"]}),ie.success("Logged — timeline and score updated")},onError:c=>ie.error(c.message)});return{update:r,dismiss:a,snooze:i,createFollowUp:l,logCompleted:o}}function FLn(){const{user:s}=Ls(),t=as();return _t({mutationFn:async n=>{const{error:r}=await Qu.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"]}),ie.success("Logged")},onError:n=>ie.error(n.message)})}const Qxt={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 RKe({score:s,className:t}){const n=Qxt[s.band]??Qxt.cooling;return e.jsxs(We,{variant:"outline",className:Ot("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 LBt({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(RKe,{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:Ot("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(ml,{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(eN,{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(X2,{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 Jxt({className:s}){const{intel:t}=gO(),[n,r]=N.useState(""),[a,i]=N.useState(!1),l=tr(),o=N.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:Ot("relative",s),children:[e.jsx(Gr,{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(RKe,{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 EIe=[{to:"/attract",label:"Dashboard",icon:ET,exact:!0},{to:"/attract/opportunities",label:"Opportunities",icon:_D},{to:"/attract/pipeline",label:"Agent Pipeline",icon:Yn},{to:"/attract/plan",label:"90-Day Plan",icon:iu},{section:"The Four Pillars"},{to:"/attract/produce",label:"Produce",icon:ml,tag:"Through Production"},{to:"/attract/influence",label:"Influence",icon:Cn,tag:"Through Influence"},{to:"/attract/influence/speaking",label:"Speaking Calendar",icon:uj},{to:"/attract/provide",label:"Provide",icon:mD,tag:"Through Value"},{to:"/attract/provide/masterclasses",label:"Masterclasses",icon:Oh},{to:"/attract/connect",label:"Connect",icon:W2,tag:"Through Events"},{to:"/attract/events",label:"Events",icon:W2},{section:"Systems"},{to:"/attract/landing-page",label:"Attraction Page",icon:c3},{to:"/attract/follow-up",label:"Follow-Up Center",icon:zm},{to:"/attract/digest",label:"Weekly Digest",icon:mn},{to:"/attract/resources",label:"Resources",icon:rb},{to:"/attract/templates",label:"Templates & Scripts",icon:f5},{to:"/attract/reports",label:"Reports",icon:fl},{to:"/attract/settings",label:"Settings",icon:sc}];function zLn(){const s=Id(),{settings:t,isLoading:n}=RJ(),r=!n&&!!t&&!t.onboarding_completed_at,a=s.pathname==="/attract/onboarding";if(r&&!a&&!s.pathname.startsWith("/attract/settings"))return e.jsx(nN,{to:"/attract/onboarding",replace:!0});const l=EIe.filter(o=>!("section"in o)).slice(0,5);return e.jsxs("div",{className:"attract-root min-h-screen bg-[#F7F7FB] text-slate-900",children:[e.jsx("style",{children:` .attract-root { --a-primary: 139 92 246; --a-primary-strong: 109 40 217; --a-indigo: 79 70 229; --a-teal: 20 184 166; --a-green: 22 163 74; --a-orange: 249 115 22; --a-rose: 244 63 94; } .attract-root .btn-primary { background: linear-gradient(135deg, rgb(var(--a-primary)) 0%, rgb(var(--a-indigo)) 100%); } `}),e.jsxs("div",{className:"flex min-h-screen",children:[e.jsxs("aside",{className:"hidden lg:flex w-72 flex-col bg-[#0B0F1E] text-slate-200 border-r border-white/5",children:[e.jsxs("div",{className:"px-6 py-6 border-b border-white/10",children:[e.jsxs(wV,{to:"/dashboard",className:"inline-flex items-center gap-1.5 text-[11px] uppercase tracking-widest text-slate-400 hover:text-white transition-colors",children:[e.jsx(ka,{className:"h-3 w-3"})," LevelUp Hub"]}),e.jsxs("div",{className:"mt-3 flex items-center gap-2.5",children:[e.jsx("div",{className:"h-9 w-9 rounded-xl bg-gradient-to-br from-violet-500 to-indigo-600 grid place-items-center shadow-lg shadow-violet-900/40",children:e.jsx(c3,{className:"h-4 w-4 text-white"})}),e.jsxs("div",{children:[e.jsx("div",{className:"text-[15px] font-semibold tracking-tight text-white",children:"LEVELUP ATTRACT"}),e.jsx("div",{className:"text-[10.5px] text-slate-400 leading-tight",children:"Attract through value. Grow through relationships."})]})]})]}),e.jsx("div",{className:"px-4 pt-3",children:e.jsx(Jxt,{})}),e.jsx("nav",{className:"flex-1 overflow-y-auto py-3 px-3",children:EIe.map((o,c)=>{if("section"in o)return e.jsx("div",{className:"px-3 mt-5 mb-1.5 text-[10px] uppercase tracking-[0.14em] text-slate-500 font-semibold",children:o.section},c);const d=o.icon;return e.jsxs(wV,{to:o.to,end:o.exact,className:({isActive:u})=>Ot("group flex items-center gap-3 px-3 py-2.5 rounded-xl text-[13.5px] font-medium transition-all",u?"bg-gradient-to-r from-violet-600/30 to-indigo-600/10 text-white ring-1 ring-inset ring-violet-500/40":"text-slate-300 hover:bg-white/5 hover:text-white"),children:[e.jsx(d,{className:"h-4 w-4 flex-shrink-0 opacity-80 group-hover:opacity-100"}),e.jsx("span",{className:"flex-1",children:o.label}),o.tag&&e.jsx("span",{className:"text-[9.5px] uppercase tracking-wider text-slate-500 group-hover:text-slate-400",children:o.tag})]},o.to)})}),e.jsx("div",{className:"px-4 py-4 border-t border-white/5",children:e.jsxs("div",{className:"rounded-xl bg-white/5 p-3",children:[e.jsx("div",{className:"text-[11px] font-medium text-violet-300",children:"Beta preview"}),e.jsx("div",{className:"text-[11.5px] text-slate-400 mt-1 leading-snug",children:"Build relationships first. Personalize every message and verify brokerage and compensation info before sharing."})]})})]}),e.jsxs("div",{className:"lg:hidden fixed top-0 inset-x-0 z-40 bg-[#0B0F1E] text-white px-4 py-3 flex items-center gap-3 border-b border-white/10",children:[e.jsx(wV,{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(c3,{className:"h-4 w-4"})}),e.jsxs("div",{children:[e.jsx("div",{className:"text-[13px] font-semibold tracking-tight",children:"LEVELUP ATTRACT"}),e.jsx("div",{className:"text-[10px] text-slate-400",children:"Attract through value"})]})]}),e.jsxs("div",{className:"lg:hidden fixed bottom-0 inset-x-0 z-40 bg-[#0B0F1E]/95 backdrop-blur border-t border-white/10 flex",children:[l.map(o=>{const c=o.icon;return e.jsxs(wV,{to:o.to,end:o.exact,className:({isActive:d})=>Ot("flex-1 min-w-0 flex flex-col items-center gap-1 py-2 text-[10px]",d?"text-white":"text-slate-400"),children:[e.jsx(c,{className:"h-4 w-4"}),e.jsx("span",{className:"truncate max-w-[70px]",children:o.label})]},o.to)}),e.jsxs(l1,{children:[e.jsx(PQ,{asChild:!0,children:e.jsxs("button",{className:"flex-1 min-w-0 flex flex-col items-center gap-1 py-2 text-[10px] text-slate-400",children:[e.jsx(Iy,{className:"h-4 w-4"}),e.jsx("span",{children:"More"})]})}),e.jsx(Gy,{side:"bottom",className:"bg-[#0B0F1E] text-slate-200 border-white/10 rounded-t-3xl max-h-[75vh] overflow-y-auto",children:e.jsxs("div",{className:"pt-4 pb-8",children:[e.jsx(Jxt,{className:"mb-4"}),e.jsx("div",{className:"text-[10px] uppercase tracking-widest text-slate-500 font-semibold mb-2",children:"All sections"}),EIe.map((o,c)=>{if("section"in o)return e.jsx("div",{className:"mt-4 mb-1 text-[10px] uppercase tracking-widest text-slate-500 font-semibold",children:o.section},c);const d=o.icon;return e.jsxs(wV,{to:o.to,end:o.exact,className:({isActive:u})=>Ot("flex items-center gap-3 rounded-xl px-3 py-3 text-[13.5px] font-medium",u?"bg-violet-600/30 text-white":"text-slate-300 hover:bg-white/5"),children:[e.jsx(d,{className:"h-4 w-4 opacity-80"}),e.jsx("span",{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-[1400px] mx-auto px-4 sm:px-6 lg:px-10 py-6 lg:py-10",children:e.jsx(o_t,{})},s.pathname)})]})]})}function bH({label:s,value:t,delta:n,icon:r,tone:a="violet"}){const i={violet:"from-violet-500 to-indigo-600",teal:"from-teal-500 to-cyan-600",green:"from-emerald-500 to-green-600",orange:"from-orange-500 to-amber-600",rose:"from-rose-500 to-pink-600"};return e.jsx(_e,{className:"p-5 rounded-2xl border-slate-200/70 bg-white shadow-sm hover:shadow-md transition-shadow",children:e.jsxs("div",{className:"flex items-start justify-between",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[11.5px] uppercase tracking-wider font-medium text-slate-500",children:s}),e.jsx("div",{className:"mt-2 text-[26px] font-semibold tracking-tight text-slate-900",children:t}),n&&e.jsxs("div",{className:"mt-1 text-[11.5px] font-medium text-emerald-600 flex items-center gap-1",children:[e.jsx(i9,{className:"h-3 w-3"}),n]})]}),e.jsx("div",{className:Ot("h-10 w-10 rounded-xl bg-gradient-to-br grid place-items-center shadow-sm",i[a]),children:e.jsx(r,{className:"h-5 w-5 text-white"})})]})})}function BLn(){const{user:s}=Ls();return mt({queryKey:["attract-score",s==null?void 0:s.id],enabled:!!s,queryFn:async()=>{const{data:t,error:n}=await H.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 $Ln=[{key:"relationships_added",label:"Relationships Added",icon:f_,target:15},{key:"follow_ups_completed",label:"Follow-Ups Completed",icon:Hr,target:15},{key:"resources_shared",label:"Resources Shared",icon:Md,target:15},{key:"content_posted",label:"Agent Content Posted",icon:um,target:15},{key:"events_connections",label:"Events / Connections",icon:W2,target:20},{key:"brokerage_conversations",label:"Brokerage Conversations",icon:_9,target:20}];function ULn(){const{data:s}=BLn(),t=(s==null?void 0:s.total)??0,n=(s==null?void 0:s.byCategory)??{},r=2*Math.PI*54,a=t/100*r;return e.jsxs(_e,{className:"p-6 rounded-2xl border-slate-200/70 bg-white shadow-sm",children:[e.jsxs("div",{className:"flex items-start justify-between mb-5",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[11.5px] uppercase tracking-wider font-medium text-violet-600",children:"Your Attract Score"}),e.jsx("div",{className:"text-[19px] font-semibold text-slate-900 mt-1",children:"Great progress! Keep building relationships and providing value."})]}),e.jsx(ml,{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:$Ln.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"})})]})}const _H=H;function jb(){const{user:s}=Ls(),t=as(),n=mt({queryKey:["attract-agents",s==null?void 0:s.id],enabled:!!s,queryFn:async()=>{const{data:d,error:u}=await H.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=_t({mutationFn:async d=>{const u={...d,user_id:s.id},{data:h,error:m}=d.id?await H.from("attract_agents").update(u).eq("id",d.id).select().single():await H.from("attract_agents").insert(u).select().single();if(m)throw m;return h},onSuccess:()=>{r(),ie.success("Saved")},onError:d=>ie.error(d.message)}),i=_t({mutationFn:async({id:d,to_stage:u,from_stage:h})=>{const{error:m}=await H.from("attract_agents").update({stage:u}).eq("id",d);if(m)throw m;await H.from("attract_pipeline_history").insert({user_id:s.id,agent_id:d,from_stage:h??null,to_stage:u})},onSuccess:()=>r(),onError:d=>ie.error(d.message)}),l=_t({mutationFn:async({id:d,values:u,changedLabels:h,previousStage:m})=>{const{stage:f,...g}=u;if(Object.keys(g).length){const{error:y}=await _H.from("attract_agents").update(g).eq("id",d);if(y)throw y}if(f&&f!==m){const{error:y}=await _H.from("attract_agents").update({stage:f}).eq("id",d);if(y)throw y;await _H.from("attract_pipeline_history").insert({user_id:s.id,agent_id:d,from_stage:m??null,to_stage:f})}h.length&&await _H.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(),ie.success("Contact updated")},onError:d=>ie.error(d.message??"Could not save contact")}),o=_t({mutationFn:async({id:d,archived:u})=>{const{error:h}=await _H.from("attract_agents").update({is_archived:u}).eq("id",d);if(h)throw h},onSuccess:(d,u)=>{r(),ie.success(u.archived?"Removed from active pipeline":"Restored to pipeline")},onError:d=>ie.error(d.message)}),c=_t({mutationFn:async d=>{const{error:u}=await H.from("attract_agents").delete().eq("id",d);if(u)throw u},onSuccess:()=>{r(),ie.success("Contact permanently deleted")},onError:d=>ie.error(d.message)});return{agents:n.data??[],activeAgents:(n.data??[]).filter(d=>!d.is_archived),isLoading:n.isLoading,upsertAgent:a,saveAgentDetails:l,moveStage:i,archiveAgent:o,deleteAgent:c}}const MIe=[{key:"new_connection",label:"New Connection"},{key:"building_relationship",label:"Building Relationship"},{key:"engaging_with_value",label:"Engaging With Value"},{key:"active_conversation",label:"Active Conversation"},{key:"exploring_options",label:"Exploring Options"},{key:"brokerage_presentation",label:"Brokerage Presentation"},{key:"decision_pending",label:"Decision Pending"},{key:"joined",label:"Joined"}];function qLn(){const{agents:s}=jb(),t=Math.max(1,...MIe.map(n=>s.filter(r=>r.stage===n.key).length));return e.jsxs(_e,{className:"p-6 rounded-2xl border-slate-200/70 bg-white shadow-sm",children:[e.jsxs("div",{className:"flex items-start justify-between mb-5",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[11.5px] uppercase tracking-wider font-medium text-violet-600",children:"Pipeline Overview"}),e.jsx("div",{className:"text-[18px] font-semibold text-slate-900 mt-0.5",children:"Where relationships live right now"})]}),e.jsx(B,{asChild:!0,variant:"outline",size:"sm",className:"rounded-full gap-1",children:e.jsxs(cr,{to:"/attract/pipeline",children:["View Full Pipeline ",e.jsx(Qa,{className:"h-3.5 w-3.5"})]})})]}),e.jsx("div",{className:"space-y-2",children:MIe.map((n,r)=>{const a=s.filter(o=>o.stage===n.key).length,i=30+a/t*70,l=.35+(1-r/MIe.length)*.55;return e.jsxs("div",{className:"grid grid-cols-[180px_1fr_36px] items-center gap-3",children:[e.jsx("span",{className:"text-[12.5px] text-slate-700 font-medium",children:n.label}),e.jsx("div",{className:"h-8 rounded-lg bg-slate-50 overflow-hidden",children:e.jsx("div",{className:"h-full rounded-lg flex items-center justify-end pr-3 text-white text-[11.5px] font-semibold",style:{width:`${i}%`,background:`linear-gradient(90deg, rgba(139,92,246,${l}) 0%, rgba(79,70,229,${l}) 100%)`},children:a>0&&a})}),e.jsx("span",{className:"text-[11px] tabular-nums text-slate-500 text-right",children:a})]},n.key)})})]})}function VLn(){const{user:s}=Ls(),t=as(),n=mt({queryKey:["attract-daily-plan",s==null?void 0:s.id],enabled:!!s,queryFn:async()=>{const{data:a,error:i}=await H.from("attract_daily_plan").select("*").order("sort_order");if(i)throw i;return a??[]}}),r=_t({mutationFn:async a=>{const i=!a.completed,{error:l}=await H.from("attract_daily_plan").update({completed:i,progress:i?a.target:0}).eq("id",a.id);if(l)throw l},onSuccess:()=>t.invalidateQueries({queryKey:["attract-daily-plan"]})});return{items:n.data??[],isLoading:n.isLoading,toggle:r}}function PBt(s=!0){const{intel:t,isLoading:n}=gO(),r=EBt(),a=DKe(),i=N.useRef(!1);return N.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 HLn(){const{items:s,toggle:t}=VLn(),{data:n=[]}=IKe(),{byId:r}=gO(),{logCompleted:a}=MBt();PBt();const i=s.filter(u=>u.completed).length,l=s.length?Math.round(i/s.length*100):0,o=Date.now(),c=n.filter(u=>u.status==="open"||u.status==="snoozed"&&u.snoozed_until&&+new Date(u.snoozed_until)<=o).sort((u,h)=>h.rank_score-u.rank_score).slice(0,3),d=u=>{var m;const h=(m=r.get(u))==null?void 0:m.agent;return h?[h.first_name,h.last_name].filter(Boolean).join(" "):"this relationship"};return e.jsxs(_e,{className:"p-6 rounded-2xl border-slate-200/70 bg-white shadow-sm",children:[e.jsxs("div",{className:"flex items-start justify-between mb-4",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[11.5px] uppercase tracking-wider font-medium text-violet-600",children:"Today's Attraction Plan"}),e.jsx("div",{className:"text-[18px] font-semibold text-slate-900 mt-0.5",children:"Small daily reps compound."})]}),e.jsxs("div",{className:"text-right",children:[e.jsxs("div",{className:"text-2xl font-semibold tabular-nums text-slate-900",children:[i,e.jsxs("span",{className:"text-slate-400 text-base",children:["/",s.length]})]}),e.jsx("div",{className:"text-[11px] text-slate-500 uppercase tracking-wider",children:"complete"})]})]}),e.jsx("div",{className:"h-1.5 rounded-full bg-slate-100 mb-4 overflow-hidden",children:e.jsx("div",{className:"h-full rounded-full bg-gradient-to-r from-violet-500 to-indigo-500 transition-all",style:{width:`${l}%`}})}),e.jsx("ul",{className:"space-y-1.5",children:s.map(u=>e.jsxs("li",{onClick:()=>t.mutate(u),className:"group flex items-center gap-3 px-3 py-2.5 rounded-xl hover:bg-slate-50 cursor-pointer transition-colors",children:[e.jsx(Bi,{checked:u.completed,className:"border-slate-300 data-[state=checked]:bg-violet-600 data-[state=checked]:border-violet-600"}),e.jsx("span",{className:`flex-1 text-[13.5px] ${u.completed?"line-through text-slate-400":"text-slate-800"}`,children:u.label}),e.jsxs("span",{className:"text-[11px] tabular-nums text-slate-400",children:[u.progress,"/",u.target]}),u.completed&&e.jsx(Hr,{className:"h-4 w-4 text-emerald-500"})]},u.id))}),e.jsxs("div",{className:"mt-5 pt-5 border-t border-slate-100",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-wider font-semibold text-slate-500 mb-2.5",children:"Who to reach today"}),c.length?e.jsx("ul",{className:"space-y-2",children:c.map(u=>e.jsx("li",{className:"rounded-xl bg-slate-50 px-3 py-2.5",children:e.jsxs("div",{className:"flex items-start justify-between gap-2 flex-wrap",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx(cr,{to:`/attract/agents/${u.agent_id}`,className:"text-[13.5px] font-medium text-slate-900 hover:text-violet-700",children:d(u.agent_id)}),e.jsx("div",{className:"text-[12px] text-slate-600 mt-0.5",children:u.title}),e.jsx("div",{className:"text-[11.5px] text-slate-500 mt-0.5",children:(u.reasons??[]).slice(0,2).join(" · ")})]}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(We,{variant:"outline",className:Ot("rounded-full text-[10.5px] capitalize",u.priority==="urgent"&&"bg-rose-50 text-rose-700 border-rose-200"),children:u.priority}),e.jsx(B,{size:"sm",variant:"ghost",className:"rounded-full h-7 px-2 text-[11.5px]",onClick:()=>a.mutate({rec:u}),disabled:a.isPending,children:"Done"})]})]})},u.id))}):e.jsx("div",{className:"text-[13px] text-slate-500",children:"No recommendations right now — Attract only surfaces conversations backed by a real signal."})]}),e.jsxs("div",{className:"mt-4 flex justify-end gap-2",children:[e.jsx(B,{variant:"ghost",size:"sm",className:"text-violet-700 hover:text-violet-900",asChild:!0,children:e.jsxs(cr,{to:"/attract/opportunities",children:["All opportunities ",e.jsx(vi,{className:"h-3.5 w-3.5 ml-1.5"})]})}),e.jsx(B,{variant:"ghost",size:"sm",className:"text-violet-700 hover:text-violet-900",asChild:!0,children:e.jsx(cr,{to:"/attract/plan",children:"View full plan"})})]})]})}function IBt(s=12){const{user:t}=Ls(),n=mt({queryKey:["attract-activities",t==null?void 0:t.id,s],enabled:!!t,queryFn:async()=>{const{data:r,error:a}=await H.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 GLn={agent_joined:Cn,resource_shared:Md,presentation:ab,conversation:_9,social_engagement:co,new_agent:Yl,content_posted:um,follow_up:zm};function WLn(){const{activities:s}=IBt(8);return e.jsxs(_e,{className:"p-6 rounded-2xl border-slate-200/70 bg-white shadow-sm",children:[e.jsxs("div",{className:"mb-4",children:[e.jsx("div",{className:"text-[11.5px] uppercase tracking-wider font-medium text-violet-600",children:"Recent Activity"}),e.jsx("div",{className:"text-[18px] font-semibold text-slate-900 mt-0.5",children:"Momentum from the past few days"})]}),e.jsxs("ol",{className:"relative space-y-4",children:[s.map(t=>{const n=GLn[t.activity_type]??Cn;return e.jsxs("li",{className:"flex items-start gap-3",children:[e.jsx("div",{className:"h-8 w-8 rounded-full bg-violet-50 grid place-items-center flex-shrink-0 mt-0.5",children:e.jsx(n,{className:"h-4 w-4 text-violet-600"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("div",{className:"text-[13.5px] font-medium text-slate-900 truncate",children:t.title}),t.description&&e.jsx("div",{className:"text-[12px] text-slate-500 truncate",children:t.description}),e.jsxs("div",{className:"text-[11px] text-slate-400 mt-0.5",children:[nc(new Date(t.created_at),{addSuffix:!0}),t.pillar&&e.jsxs(e.Fragment,{children:[" · ",e.jsx("span",{className:"capitalize",children:t.pillar})]})]})]})]},t.id)}),s.length===0&&e.jsx("li",{className:"text-sm text-slate-500 text-center py-6",children:"No activity yet — start with one small touch today."})]})]})}function PAe(s){const{user:t}=Ls();return mt({queryKey:["attract-events",t==null?void 0:t.id,s],enabled:!!t,queryFn:async()=>{let n=H.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 OKe(s){return mt({queryKey:["attract-event",s],enabled:!!s,queryFn:async()=>{const{data:t,error:n}=await H.from("attract_events").select("*").eq("id",s).single();if(n)throw n;return t}})}function DBt(s){return mt({queryKey:["attract-event-attendees",s],enabled:!!s,queryFn:async()=>{const{data:t,error:n}=await H.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 KLn(s){return mt({queryKey:["attract-event-invitations",s],enabled:!!s,queryFn:async()=>{const{data:t,error:n}=await H.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 YLn(s){return mt({queryKey:["attract-event-notes",s],enabled:!!s,queryFn:async()=>{const{data:t,error:n}=await H.from("attract_event_notes").select("*").eq("event_id",s).order("created_at",{ascending:!1});if(n)throw n;return t??[]}})}function RBt(){return mt({queryKey:["attract-event-templates"],queryFn:async()=>{const{data:s,error:t}=await H.from("attract_event_templates").select("*").order("title");if(t)throw t;return s??[]}})}function OBt(){const{user:s}=Ls(),t=as();return _t({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 H.from("attract_events").insert(r).select().single();if(i)throw i;return a},onSuccess:()=>t.invalidateQueries({queryKey:["attract-events"]})})}function FBt(){const s=as();return _t({mutationFn:async({id:t,patch:n})=>{const{data:r,error:a}=await H.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 ZLn(){const s=as();return _t({mutationFn:async t=>{const{error:n}=await H.from("attract_events").delete().eq("id",t);if(n)throw n},onSuccess:()=>s.invalidateQueries({queryKey:["attract-events"]})})}function zBt(){const{user:s}=Ls(),t=as();return _t({mutationFn:async n=>{if(!s)throw new Error("Not authenticated");const r={user_id:s.id,...n},{data:a,error:i}=n.id?await H.from("attract_event_attendees").update(r).eq("id",n.id).select().single():await H.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 XLn(){const{user:s}=Ls(),t=as();return _t({mutationFn:async n=>{if(!s)throw new Error("Not authenticated");const{data:r,error:a}=await H.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 QLn(){const{user:s}=Ls(),t=as();return _t({mutationFn:async n=>{if(!s)throw new Error("Not authenticated");const{data:r,error:a}=await H.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 JLn(){const{user:s}=Ls(),t=as();return _t({mutationFn:async n=>{if(!s)throw new Error("Not authenticated");const{data:r,error:a}=await H.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,...f}=r,{data:g,error:y}=await H.from("attract_events").insert({...f,title:r.title+" (Copy)",status:"draft"}).select().single();if(y)throw y;return g},onSuccess:()=>t.invalidateQueries({queryKey:["attract-events"]})})}function IAe(s){return`${window.location.origin}/attract-event/${s}`}function ePn(s,t){return`${window.location.origin}/attract-event-checkin/${s}?a=${encodeURIComponent(t)}`}function BBt(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 tPn(){const{data:s=[]}=PAe(),t=s.slice(0,3);return e.jsxs(_e,{className:"p-6 rounded-2xl border-slate-200/70 bg-white shadow-sm",children:[e.jsxs("div",{className:"flex items-start justify-between mb-4",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[11.5px] uppercase tracking-wider font-medium text-violet-600",children:"Upcoming Events"}),e.jsx("div",{className:"text-[18px] font-semibold text-slate-900 mt-0.5",children:"Places where relationships happen"})]}),e.jsxs(B,{variant:"outline",size:"sm",className:"rounded-full gap-1",children:[e.jsx(nn,{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:Js(r,"MMM")}),e.jsx("div",{className:"text-xl font-semibold leading-tight",children:Js(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:Js(r,"p")}),"·",n.event_type==="virtual"?e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(na,{className:"h-3 w-3"})," Virtual"]}):e.jsxs("span",{className:"flex items-center gap-1 truncate",children:[e.jsx(ii,{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(W2,{className:"h-6 w-6 mx-auto text-slate-300 mb-2"}),e.jsx("div",{className:"text-sm",children:"No upcoming events yet."})]})]})]})}function $Bt(){const{user:s}=Ls(),t=mt({queryKey:["attract-resources",s==null?void 0:s.id],enabled:!!s,queryFn:async()=>{const{data:r,error:a}=await H.from("attract_resources").select("*").order("created_at",{ascending:!1});if(a)throw a;return r??[]}}),n=mt({queryKey:["attract-resource-shares",s==null?void 0:s.id],enabled:!!s,queryFn:async()=>{const{data:r,error:a}=await H.from("attract_resource_shares").select("*").order("created_at",{ascending:!1});if(a)throw a;return r??[]}});return{resources:t.data??[],shares:n.data??[],isLoading:t.isLoading}}function sPn(){const{shares:s}=$Bt(),t={resources:s.length,emails:s.filter(r=>r.channel==="email").length,opens:s.filter(r=>r.opened_at).length,clicks:s.filter(r=>r.clicked_at).length},n=[{label:"Resources Shared",value:t.resources,icon:Md,tone:"text-violet-600 bg-violet-50"},{label:"Emails Sent",value:t.emails,icon:Rr,tone:"text-teal-600 bg-teal-50"},{label:"Agent Opens",value:t.opens,icon:x9,tone:"text-emerald-600 bg-emerald-50"},{label:"Clicks",value:t.clicks,icon:ru,tone:"text-orange-600 bg-orange-50"}];return e.jsxs(_e,{className:"p-6 rounded-2xl border-slate-200/70 bg-white shadow-sm",children:[e.jsxs("div",{className:"mb-4",children:[e.jsx("div",{className:"text-[11.5px] uppercase tracking-wider font-medium text-violet-600",children:"Value Shared This Week"}),e.jsx("div",{className:"text-[18px] font-semibold text-slate-900 mt-0.5",children:"Small gifts, measured."})]}),e.jsx("div",{className:"grid grid-cols-2 gap-3",children:n.map(r=>e.jsxs("div",{className:"rounded-xl border border-slate-100 p-3.5",children:[e.jsx("div",{className:`h-8 w-8 rounded-lg grid place-items-center ${r.tone}`,children:e.jsx(r.icon,{className:"h-4 w-4"})}),e.jsx("div",{className:"text-[22px] font-semibold tabular-nums text-slate-900 mt-2 leading-none",children:r.value}),e.jsx("div",{className:"text-[11.5px] text-slate-500 mt-1",children:r.label})]},r.label))})]})}function nPn(){const{agents:s}=jb(),t=s.filter(r=>r.stage==="joined").sort((r,a)=>(a.joined_at??"").localeCompare(r.joined_at??"")),n=t.reduce((r,a)=>r+(Number(a.est_revenue_share)||0),0);return e.jsxs(_e,{className:"p-6 rounded-2xl border-slate-200/70 bg-white shadow-sm",children:[e.jsxs("div",{className:"flex items-start justify-between mb-4",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[11.5px] uppercase tracking-wider font-medium text-violet-600",children:"Agents Joined"}),e.jsxs("div",{className:"text-[18px] font-semibold text-slate-900 mt-0.5",children:["Est. annual rev share ",e.jsx("span",{className:"text-violet-700",children:_u(n)})]})]}),e.jsx(Cn,{className:"h-5 w-5 text-violet-500"})]}),e.jsxs("ul",{className:"space-y-2.5",children:[t.map(r=>{var a;return e.jsxs("li",{className:"flex items-center gap-3 p-2.5 rounded-xl hover:bg-slate-50",children:[e.jsxs("div",{className:"h-9 w-9 rounded-full bg-gradient-to-br from-violet-500 to-indigo-600 text-white grid place-items-center text-[13px] font-semibold flex-shrink-0",children:[r.first_name[0],((a=r.last_name)==null?void 0:a[0])??""]}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"text-[13.5px] font-semibold text-slate-900 truncate",children:[r.first_name," ",r.last_name]}),e.jsxs("div",{className:"text-[11.5px] text-slate-500 truncate",children:[r.brokerage," · ",r.city,", ",r.state]})]}),e.jsxs("div",{className:"text-right",children:[e.jsx("div",{className:"text-[13px] font-semibold text-emerald-600 tabular-nums",children:r.est_revenue_share?_u(Number(r.est_revenue_share)):"—"}),e.jsx("div",{className:"text-[10.5px] text-slate-400",children:r.joined_at?nc(new Date(r.joined_at),{addSuffix:!0}):""})]})]},r.id)}),t.length===0&&e.jsx("li",{className:"text-sm text-slate-500 text-center py-6",children:"No joined agents yet."})]})]})}function OJ(){const{user:s}=Ls(),t=as(),n=mt({queryKey:["attract-followups",s==null?void 0:s.id],enabled:!!s,queryFn:async()=>{const{data:a,error:i}=await H.from("attract_follow_ups").select("*").order("due_at",{ascending:!0,nullsFirst:!1});if(i)throw i;return a??[]}}),r=_t({mutationFn:async a=>{const{error:i}=await H.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 rPn(s){var r;const t=(s==null?void 0:s.user_metadata)??{},n=t.full_name||t.name||((r=s==null?void 0:s.email)==null?void 0:r.split("@")[0])||"there";return String(n).split(" ")[0]}const e0t={produce:{label:"Your primary pillar is Produce — log one recent transaction today.",cta:"Open Transaction Tracker",to:"/attract/produce/transaction-tracker"},influence:{label:"Your primary pillar is Influence — create one authority post today.",cta:"Open Content Studio",to:"/attract/influence/content-studio"},provide:{label:"Your primary pillar is Provide — share one resource with an agent today.",cta:"Open Resources",to:"/attract/resources"},connect:{label:"Your primary pillar is Connect — schedule one 1:1 this week.",cta:"Open Follow-Up Center",to:"/attract/follow-up"},balanced:{label:"Balanced plan — pick one pillar for today and go deep.",cta:"View 90-Day Plan",to:"/attract/plan"}};function aPn(){const{user:s}=Ls(),t=tr(),{agents:n}=jb(),{followUps:r}=OJ(),{settings:a}=RJ();N.useState(!1);const i=N.useMemo(()=>{const d=ey(new Date),u=n.filter(x=>!["joined","not_a_fit","not_right_now"].includes(x.stage)).length,h=n.filter(x=>new Date(x.created_at)>Ad(d,-30)).length,m=r.filter(x=>!x.completed_at&&x.due_at&&yd(new Date(x.due_at),d)).length,f=r.filter(x=>!x.completed_at&&x.due_at&&rN(new Date(x.due_at),d)).length,y=n.filter(x=>x.stage==="joined").reduce((x,_)=>x+(Number(_.est_revenue_share)||0),0);return{inPipeline:u,newRels:h,dueToday:m,overdue:f,revShare:y}},[n,r]),l=(a==null?void 0:a.primary_pillar)||(a==null?void 0:a.attraction_style)||"balanced",o=e0t[l]??e0t.balanced,c=a==null?void 0:a.ninety_day_plan;return e.jsxs("div",{children:[e.jsxs("div",{className:"flex flex-col md:flex-row md:items-center md:justify-between gap-4 mb-8",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.18em] text-violet-600 font-semibold mb-2",children:"LevelUp Attract"}),e.jsxs("h1",{className:"text-3xl md:text-[34px] font-semibold tracking-tight text-slate-900",children:["Good to see you, ",rPn(s),"."]}),e.jsxs("p",{className:"text-slate-600 mt-1.5",children:["Here's your attraction overview for today · ",Js(new Date,"EEEE, MMM d")]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(Ns,{defaultValue:"week",children:[e.jsx(ws,{className:"w-[150px] rounded-full bg-white",children:e.jsx(ks,{})}),e.jsxs(js,{children:[e.jsx(nt,{value:"week",children:"This Week"}),e.jsx(nt,{value:"month",children:"This Month"}),e.jsx(nt,{value:"90",children:"Last 90 Days"})]})]}),e.jsx(B,{variant:"outline",size:"icon",className:"rounded-full",children:e.jsx(yg,{className:"h-4 w-4"})}),e.jsxs(qd,{children:[e.jsx(Vd,{asChild:!0,children:e.jsxs(B,{className:"rounded-full bg-gradient-to-r from-violet-600 to-indigo-600 hover:from-violet-700 hover:to-indigo-700 gap-1.5 shadow-sm",children:[e.jsx(nn,{className:"h-4 w-4"})," Add New ",e.jsx(Xo,{className:"h-3.5 w-3.5 opacity-70"})]})}),e.jsxs(Ld,{align:"end",className:"w-64",children:[e.jsx(cE,{children:"Quick add"}),e.jsx(s1,{}),e.jsxs(ba,{onClick:()=>t("/attract/pipeline?new=1"),children:[e.jsx(Yl,{className:"h-4 w-4 mr-2"})," Add Agent to Pipeline"]}),e.jsxs(ba,{onClick:()=>t("/attract/produce/transaction-tracker"),children:[e.jsx(Wa,{className:"h-4 w-4 mr-2"})," Log a Transaction"]}),e.jsxs(ba,{onClick:()=>t("/attract/influence/content-studio"),children:[e.jsx(Zg,{className:"h-4 w-4 mr-2"})," Create Authority Content"]}),e.jsxs(ba,{onClick:()=>t("/attract/follow-up"),children:[e.jsx(zm,{className:"h-4 w-4 mr-2"})," Add Follow-Up"]}),e.jsxs(ba,{onClick:()=>t("/attract/events/new"),children:[e.jsx(Pv,{className:"h-4 w-4 mr-2"})," Plan an Event"]}),e.jsxs(ba,{onClick:()=>t("/attract/resources"),children:[e.jsx(rb,{className:"h-4 w-4 mr-2"})," Add Resource"]})]})]})]})]}),e.jsx(_e,{className:"p-4 rounded-2xl mb-6 bg-gradient-to-r from-violet-50 to-indigo-50 border-violet-100",children:e.jsxs("div",{className:"flex items-center gap-3 flex-wrap",children:[e.jsx("div",{className:"h-10 w-10 rounded-xl bg-white grid place-items-center text-violet-700 shadow-sm",children:e.jsx(iu,{className:"h-5 w-5"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("div",{className:"text-[10.5px] uppercase tracking-widest text-violet-700 font-semibold",children:"Today's move"}),e.jsx("div",{className:"text-[14px] font-semibold text-slate-900",children:o.label}),c&&e.jsxs("div",{className:"text-[12px] text-slate-600 mt-0.5",children:["Weekly goal: ",c.weekly_targets.new_relationships," new relationships · ",c.weekly_targets.content_pieces," content pieces"]})]}),e.jsx(B,{size:"sm",className:"rounded-full bg-gradient-to-r from-violet-600 to-indigo-600",onClick:()=>t(o.to),children:o.cta})]})}),e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-3 xl:grid-cols-5 gap-4 mb-6",children:[e.jsx(bH,{label:"Agents in Pipeline",value:i.inPipeline,delta:"+3 this week",icon:f_,tone:"violet"}),e.jsx(bH,{label:"New Relationships",value:i.newRels,delta:"+2 this week",icon:ml,tone:"teal"}),e.jsx(bH,{label:"Follow-Ups Due Today",value:i.dueToday,icon:qG,tone:"orange"}),e.jsx(bH,{label:"Overdue Follow-Ups",value:i.overdue,icon:xd,tone:"rose"}),e.jsx(bH,{label:"Est. Revenue Share",value:_u(i.revShare,!0),delta:"annualized",icon:Ed,tone:"green"})]}),e.jsxs("div",{className:"grid grid-cols-1 xl:grid-cols-3 gap-6",children:[e.jsxs("div",{className:"xl:col-span-2 space-y-6",children:[e.jsx(ULn,{}),e.jsx(qLn,{}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-6",children:[e.jsx(WLn,{}),e.jsx(tPn,{})]})]}),e.jsxs("div",{className:"space-y-6",children:[e.jsx(HLn,{}),e.jsx(sPn,{}),e.jsx(nPn,{})]})]}),e.jsx("div",{className:"mt-8 rounded-2xl overflow-hidden bg-gradient-to-r from-violet-600 via-indigo-600 to-violet-700 p-6 md:p-7 text-white shadow-lg",children:e.jsxs("div",{className:"flex items-center justify-between gap-4 flex-wrap",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.18em] opacity-80 mb-1",children:"Your 90-day promise"}),e.jsx("div",{className:"text-lg md:text-xl font-semibold",children:(c==null?void 0:c.outcome)??"Show up for agents the way you'd want someone to show up for you."}),e.jsx("div",{className:"text-white/80 mt-1 text-[13.5px]",children:"Small daily reps compound. Keep the rhythm."})]}),e.jsx(B,{asChild:!0,variant:"secondary",className:"rounded-full bg-white text-violet-700 hover:bg-white/90",children:e.jsx(cr,{to:"/attract/plan",children:"View 90-Day Plan"})})]})})]})}function Op({eyebrow:s,title:t,description:n,actions:r,className:a}){return e.jsxs("div",{className:Ot("flex flex-col md:flex-row md:items-end md:justify-between gap-4 mb-8",a),children:[e.jsxs("div",{children:[s&&e.jsx("div",{className:"text-[11px] uppercase tracking-[0.18em] text-violet-600 font-semibold mb-2",children:s}),e.jsx("h1",{className:"text-3xl md:text-[34px] font-semibold tracking-tight text-slate-900",children:t}),n&&e.jsx("p",{className:"text-slate-600 mt-2 max-w-2xl",children:n})]}),r&&e.jsx("div",{className:"flex items-center gap-2 flex-wrap",children:r})]})}function xO(){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."]})]})}const iPn=["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"],oPn={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"},Tx=s=>typeof s=="string"&&s.trim()===""?null:s,VF=s=>{const t=s.trim();return t?/^https?:\/\//i.test(t)?t:`https://${t}`:null},lPn=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},wH=s=>(s??"").replace(/[^\d]/g,""),cPn=s=>/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(s.trim()),Xne=s=>s?String(s).slice(0,10):"";function t0t(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:Xne(s.birthday_on),work_anniversary_on:Xne(s.work_anniversary_on),license_anniversary_on:Xne(s.license_anniversary_on),next_follow_up_at:Xne(s.next_follow_up_at)}}function HF({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 Cm({label:s,value:t,onChange:n,className:r,...a}){return e.jsxs("div",{className:r,children:[e.jsx(re,{className:"text-[12px] text-slate-600",children:s}),e.jsx(we,{className:"mt-1",value:t,onChange:i=>n(i.target.value),...a})]})}function UBt({agent:s,open:t,onOpenChange:n,onDeleted:r}){const{agents:a,saveAgentDetails:i,archiveAgent:l,deleteAgent:o}=jb(),[c,d]=N.useState({}),[u,h]=N.useState(!1),[m,f]=N.useState(!1),[g,y]=N.useState(!1);N.useEffect(()=>{s&&t&&(d(t0t(s)),y(!1))},[s==null?void 0:s.id,t]);const x=N.useMemo(()=>s?t0t(s):{},[s]),_=N.useMemo(()=>Object.keys(c).filter(M=>String(c[M]??"")!==String(x[M]??"")),[c,x]),b=_.length>0,k=(M,L)=>d(z=>({...z,[M]:L}));if(!s)return null;const A=M=>{if(!M&&b){h(!0);return}n(M)},T=()=>{var $;const M=($=c.email)==null?void 0:$.trim().toLowerCase(),L=wH(c.phone),z=`${c.first_name} ${c.last_name}`.trim().toLowerCase();return a.filter(V=>{var W;return V.id===s.id||V.is_archived?!1:!!(M&&((W=V.email)==null?void 0:W.toLowerCase())===M||L.length>=10&&wH(V.phone)===L||z&&`${V.first_name} ${V.last_name??""}`.trim().toLowerCase()===z)})},P=()=>{var V,W,G;if(!((V=c.first_name)!=null&&V.trim())){ie.error("First name is required");return}if((W=c.email)!=null&&W.trim()&&!cPn(c.email)){ie.error("That email address looks incomplete");return}const M=T(),L=M.some(X=>{var te,ne;return((te=c.email)==null?void 0:te.trim())&&((ne=X.email)==null?void 0:ne.toLowerCase())===c.email.trim().toLowerCase()||wH(c.phone).length>=10&&wH(X.phone)===wH(c.phone)});if(M.length&&!g){y(!0),ie.warning(L?`${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 z={first_name:c.first_name.trim(),last_name:Tx(c.last_name),preferred_name:Tx(c.preferred_name),email:(G=c.email)!=null&&G.trim()?c.email.trim().toLowerCase():null,phone:lPn(c.phone??""),website_url:VF(c.website_url??""),instagram_url:VF(c.instagram_url??""),linkedin_url:VF(c.linkedin_url??""),facebook_url:VF(c.facebook_url??""),other_url:VF(c.other_url??""),photo_url:VF(c.photo_url??""),brokerage:Tx(c.brokerage),team_name:Tx(c.team_name),city:Tx(c.city),state:Tx(c.state),postal_code:Tx(c.postal_code),market_area:Tx(c.market_area),source:Tx(c.source),relationship_owner:Tx(c.relationship_owner),temperature:c.temperature,primary_pillar:c.primary_pillar==="none"?null:c.primary_pillar,tags:String(c.tags??"").split(",").map(X=>X.trim()).filter(Boolean),goals:Tx(c.goals),challenges:Tx(c.challenges),interests:Tx(c.interests),production_context:Tx(c.production_context),notes:Tx(c.notes),birthday_on:Tx(c.birthday_on),work_anniversary_on:Tx(c.work_anniversary_on),license_anniversary_on:Tx(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},$={};if(_.forEach(X=>{X in z&&($[X]=z[X])}),!Object.keys($).length){n(!1);return}i.mutate({id:s.id,values:$,changedLabels:_.map(X=>oPn[X]??X),previousStage:s.stage},{onSuccess:()=>n(!1)})},I=T();return e.jsxs(e.Fragment,{children:[e.jsx(l1,{open:t,onOpenChange:A,children:e.jsxs(Gy,{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(gb,{className:"space-y-1 text-left",children:[e.jsxs(xb,{className:"text-white text-lg",children:["Edit ",[s.first_name,s.last_name].filter(Boolean).join(" ")]}),e.jsx(IQ,{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:[!!I.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(xd,{className:"h-4 w-4 mt-0.5 shrink-0"}),e.jsxs("span",{children:["Possible duplicate: ",I.slice(0,3).map(M=>`${M.first_name} ${M.last_name??""}`.trim()).join(", "),". You can still save — just double-check first."]})]}),e.jsxs(HF,{title:"Basic info",children:[e.jsx(Cm,{label:"First name *",value:c.first_name,onChange:M=>k("first_name",M)}),e.jsx(Cm,{label:"Last name",value:c.last_name,onChange:M=>k("last_name",M)}),e.jsx(Cm,{label:"Preferred name",value:c.preferred_name,onChange:M=>k("preferred_name",M),placeholder:"What they go by"}),e.jsx(Cm,{label:"Photo / headshot URL",value:c.photo_url,onChange:M=>k("photo_url",M),placeholder:"https://…"})]}),e.jsxs(HF,{title:"Contact & social",children:[e.jsx(Cm,{label:"Email",type:"email",value:c.email,onChange:M=>k("email",M)}),e.jsx(Cm,{label:"Phone",value:c.phone,onChange:M=>k("phone",M)}),e.jsx(Cm,{label:"Website",value:c.website_url,onChange:M=>k("website_url",M)}),e.jsx(Cm,{label:"Instagram",value:c.instagram_url,onChange:M=>k("instagram_url",M)}),e.jsx(Cm,{label:"LinkedIn",value:c.linkedin_url,onChange:M=>k("linkedin_url",M)}),e.jsx(Cm,{label:"Facebook",value:c.facebook_url,onChange:M=>k("facebook_url",M)}),e.jsx(Cm,{label:"Other link",value:c.other_url,onChange:M=>k("other_url",M),className:"sm:col-span-2"})]}),e.jsxs(HF,{title:"Brokerage & market",children:[e.jsx(Cm,{label:"Brokerage",value:c.brokerage,onChange:M=>k("brokerage",M)}),e.jsx(Cm,{label:"Team",value:c.team_name,onChange:M=>k("team_name",M)}),e.jsx(Cm,{label:"City",value:c.city,onChange:M=>k("city",M)}),e.jsx(Cm,{label:"State",value:c.state,onChange:M=>k("state",M)}),e.jsx(Cm,{label:"ZIP / postal code",value:c.postal_code,onChange:M=>k("postal_code",M)}),e.jsx(Cm,{label:"Market / service area",value:c.market_area,onChange:M=>k("market_area",M)})]}),e.jsxs(HF,{title:"Relationship intelligence",hint:"These drive scoring, recommendations, filters and reports.",children:[e.jsxs("div",{children:[e.jsx(re,{className:"text-[12px] text-slate-600",children:"Pipeline stage"}),e.jsxs(Ns,{value:c.stage,onValueChange:M=>k("stage",M),children:[e.jsx(ws,{className:"mt-1",children:e.jsx(ks,{})}),e.jsx(js,{children:iPn.map(M=>e.jsx(nt,{value:M,className:"capitalize",children:M.replace(/_/g," ")},M))})]})]}),e.jsxs("div",{children:[e.jsx(re,{className:"text-[12px] text-slate-600",children:"Temperature"}),e.jsxs(Ns,{value:c.temperature,onValueChange:M=>k("temperature",M),children:[e.jsx(ws,{className:"mt-1",children:e.jsx(ks,{})}),e.jsx(js,{children:["cold","warm","hot"].map(M=>e.jsx(nt,{value:M,className:"capitalize",children:M},M))})]})]}),e.jsxs("div",{children:[e.jsx(re,{className:"text-[12px] text-slate-600",children:"Primary pillar"}),e.jsxs(Ns,{value:c.primary_pillar,onValueChange:M=>k("primary_pillar",M),children:[e.jsx(ws,{className:"mt-1",children:e.jsx(ks,{})}),e.jsxs(js,{children:[e.jsx(nt,{value:"none",children:"Not set"}),["produce","influence","provide","connect"].map(M=>e.jsx(nt,{value:M,className:"capitalize",children:M},M))]})]})]}),e.jsx(Cm,{label:"Source",value:c.source,onChange:M=>k("source",M),placeholder:"Event, referral, social…"}),e.jsx(Cm,{label:"Relationship owner",value:c.relationship_owner,onChange:M=>k("relationship_owner",M),placeholder:"You, or a teammate"}),e.jsx(Cm,{label:"Tags (comma separated)",value:c.tags,onChange:M=>k("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(We,{variant:"outline",className:"rounded-full text-[11px]",children:M},M))})]}),e.jsxs(HF,{title:"Important dates",hint:"Birthdays and anniversaries feed Milestones & Celebrations automatically — no duplicate entry needed.",children:[e.jsx(Cm,{label:"Birthday",type:"date",value:c.birthday_on,onChange:M=>k("birthday_on",M)}),e.jsx(Cm,{label:"Work anniversary",type:"date",value:c.work_anniversary_on,onChange:M=>k("work_anniversary_on",M)}),e.jsx(Cm,{label:"License anniversary",type:"date",value:c.license_anniversary_on,onChange:M=>k("license_anniversary_on",M)}),e.jsx(Cm,{label:"Next follow-up",type:"date",value:c.next_follow_up_at,onChange:M=>k("next_follow_up_at",M)})]}),e.jsxs(HF,{title:"Notes",children:[e.jsxs("div",{className:"sm:col-span-2",children:[e.jsx(re,{className:"text-[12px] text-slate-600",children:"Goals"}),e.jsx(Ws,{className:"mt-1",rows:2,value:c.goals,onChange:M=>k("goals",M.target.value)})]}),e.jsxs("div",{className:"sm:col-span-2",children:[e.jsx(re,{className:"text-[12px] text-slate-600",children:"Challenges"}),e.jsx(Ws,{className:"mt-1",rows:2,value:c.challenges,onChange:M=>k("challenges",M.target.value)})]}),e.jsxs("div",{className:"sm:col-span-2",children:[e.jsx(re,{className:"text-[12px] text-slate-600",children:"Interests"}),e.jsx(Ws,{className:"mt-1",rows:2,value:c.interests,onChange:M=>k("interests",M.target.value)})]}),e.jsxs("div",{className:"sm:col-span-2",children:[e.jsx(re,{className:"text-[12px] text-slate-600",children:"Production context"}),e.jsx(Ws,{className:"mt-1",rows:2,value:c.production_context,onChange:M=>k("production_context",M.target.value)})]}),e.jsxs("div",{className:"sm:col-span-2",children:[e.jsx(re,{className:"text-[12px] text-slate-600",children:"Personal notes"}),e.jsx(Ws,{className:"mt-1",rows:4,value:c.notes,onChange:M=>k("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(xg,{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:()=>f(!0),children:[e.jsx(qn,{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?`${_.length} unsaved change${_.length>1?"s":""}`:"All changes saved"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(B,{variant:"ghost",className:"rounded-full",onClick:()=>A(!1),children:[e.jsx(hr,{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:P,children:[i.isPending&&e.jsx(us,{className:"h-4 w-4 mr-1.5 animate-spin"}),"Save changes"]})]})]})]})}),e.jsx(Fl,{open:u,onOpenChange:h,children:e.jsxs(kl,{children:[e.jsxs(Sl,{children:[e.jsx(Al,{children:"Discard unsaved changes?"}),e.jsxs(Tl,{children:["You have ",_.length," unsaved change(s) on this contact."]})]}),e.jsxs(Cl,{children:[e.jsx(El,{children:"Keep editing"}),e.jsx(wl,{onClick:()=>{h(!1),n(!1)},children:"Discard"})]})]})}),e.jsx(Fl,{open:m,onOpenChange:f,children:e.jsxs(kl,{children:[e.jsxs(Sl,{children:[e.jsx(Al,{children:"Delete this contact permanently?"}),e.jsx(Tl,{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(Cl,{children:[e.jsx(El,{children:"Cancel"}),e.jsx(wl,{className:"bg-rose-600 hover:bg-rose-700",onClick:()=>o.mutate(s.id,{onSuccess:()=>{f(!1),n(!1),r==null||r()}}),children:"Delete forever"})]})]})})]})}const Qne=[{key:"new_connection",label:"New Connection",color:"#94a3b8"},{key:"building_relationship",label:"Building Relationship",color:"#38bdf8"},{key:"engaging_with_value",label:"Engaging With Value",color:"#14b8a6"},{key:"active_conversation",label:"Active Conversation",color:"#8b5cf6"},{key:"exploring_options",label:"Exploring Options",color:"#6366f1"},{key:"brokerage_presentation",label:"Brokerage Presentation",color:"#f97316"},{key:"decision_pending",label:"Decision Pending",color:"#f59e0b"},{key:"joined",label:"Joined",color:"#16a34a"},{key:"not_right_now",label:"Not Right Now",color:"#64748b"},{key:"long_term_relationship",label:"Long-Term Relationship",color:"#a78bfa"},{key:"not_a_fit",label:"Not a Fit",color:"#cbd5e1"}],s0t={hot:"bg-rose-100 text-rose-700 border-rose-200",warm:"bg-orange-100 text-orange-700 border-orange-200",cold:"bg-sky-100 text-sky-700 border-sky-200"};function dPn(){const s=tr(),{agents:t,isLoading:n,upsertAgent:r,moveStage:a,archiveAgent:i,deleteAgent:l}=jb(),[o,c]=N.useState("kanban"),[d,u]=N.useState(""),[h,m]=N.useState(!1),[f,g]=N.useState(!1),[y,x]=N.useState(),[_,b]=N.useState(null),[k,A]=N.useState(null),[T,P]=N.useState(null),[I,M]=N.useState(null),{gmailEmail:L}=_f(),z=t.filter(W=>!!W.is_archived!==h?!1:d?`${W.first_name} ${W.last_name??""} ${W.brokerage??""} ${W.city??""} ${(W.tags??[]).join(" ")} ${W.email??""}`.toLowerCase().includes(d.toLowerCase()):!0),$=_?t.find(W=>W.id===_.id)??_:null,V=({agent:W})=>e.jsxs(qd,{children:[e.jsx(Vd,{asChild:!0,children:e.jsx(B,{variant:"ghost",size:"icon",className:"h-6 w-6 -mr-1",onClick:G=>G.stopPropagation(),"aria-label":"Agent actions",children:e.jsx(Ev,{className:"h-3.5 w-3.5"})})}),e.jsxs(Ld,{align:"end",onClick:G=>G.stopPropagation(),children:[e.jsxs(ba,{onClick:()=>A(W),children:[e.jsx(Ja,{className:"h-3.5 w-3.5 mr-2"})," Edit contact"]}),e.jsxs(ba,{onClick:()=>s(`/attract/agents/${W.id}`),children:[e.jsx(Tr,{className:"h-3.5 w-3.5 mr-2"})," Open relationship"]}),e.jsx(s1,{}),e.jsxs(ba,{onClick:()=>i.mutate({id:W.id,archived:!W.is_archived}),children:[e.jsx(xg,{className:"h-3.5 w-3.5 mr-2"})," ",W.is_archived?"Restore to pipeline":"Remove from pipeline"]})]})]});return e.jsxs("div",{children:[e.jsx(Op,{eyebrow:"Agent Pipeline",title:"Where relationships live",description:"Move agents through relationship-first stages. Never a target — always a real conversation.",actions:e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex bg-white border rounded-full p-0.5",children:[e.jsxs(B,{size:"sm",variant:o==="kanban"?"default":"ghost",className:"rounded-full h-8 px-3",onClick:()=>c("kanban"),children:[e.jsx(G0,{className:"h-3.5 w-3.5 mr-1"})," Board"]}),e.jsxs(B,{size:"sm",variant:o==="list"?"default":"ghost",className:"rounded-full h-8 px-3",onClick:()=>c("list"),children:[e.jsx(Kx,{className:"h-3.5 w-3.5 mr-1"})," List"]})]}),e.jsxs(B,{className:"rounded-full bg-gradient-to-r from-violet-600 to-indigo-600 hover:opacity-95",onClick:()=>{x(void 0),g(!0)},children:[e.jsx(nn,{className:"h-4 w-4 mr-1"})," Add Agent"]})]})}),e.jsxs("div",{className:"mb-4 flex items-center gap-3 flex-wrap",children:[e.jsxs("div",{className:"relative flex-1 min-w-[220px] max-w-md",children:[e.jsx(Gr,{className:"h-4 w-4 text-slate-400 absolute left-3 top-1/2 -translate-y-1/2"}),e.jsx(we,{value:d,onChange:W=>u(W.target.value),placeholder:"Search name, brokerage, city, tag, email…",className:"pl-9 rounded-full bg-white"})]}),e.jsxs(B,{variant:h?"default":"outline",size:"sm",className:"rounded-full",onClick:()=>m(W=>!W),children:[e.jsx(xg,{className:"h-3.5 w-3.5 mr-1.5"})," ",h?"Viewing archived":"Archived"]}),e.jsxs("div",{className:"text-[12.5px] text-slate-500",children:[z.length," agents"]})]}),e.jsx("div",{className:"mb-4",children:e.jsx(xO,{})}),n?e.jsx("div",{className:"py-24 text-center text-slate-500",children:"Loading pipeline…"}):o==="kanban"?e.jsxs(lo,{className:"w-full",children:[e.jsx("div",{className:"flex gap-4 pb-4",style:{minWidth:Qne.length*300},children:Qne.map(W=>{const G=z.filter(X=>X.stage===W.key);return e.jsxs("div",{className:"w-[280px] flex-shrink-0 flex flex-col",onDragOver:X=>{X.preventDefault(),X.dataTransfer.dropEffect="move"},onDrop:X=>{if(X.preventDefault(),T){const te=t.find(ne=>ne.id===T);te&&te.stage!==W.key&&a.mutate({id:T,to_stage:W.key,from_stage:te.stage}),P(null)}},children:[e.jsxs("div",{className:"flex items-center justify-between px-1 mb-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"h-2.5 w-2.5 rounded-full",style:{background:W.color}}),e.jsx("h3",{className:"text-[13px] font-semibold text-slate-800",children:W.label}),e.jsx(We,{variant:"secondary",className:"text-[10px] h-5 px-1.5",children:G.length})]}),e.jsx(B,{variant:"ghost",size:"icon",className:"h-6 w-6",onClick:()=>{x(W.key),g(!0)},children:e.jsx(nn,{className:"h-3.5 w-3.5"})})]}),e.jsxs("div",{className:"rounded-2xl bg-slate-100/60 p-2 space-y-2 min-h-[200px]",children:[G.map(X=>e.jsxs("div",{draggable:!0,onDragStart:()=>P(X.id),onClick:()=>b(X),className:"bg-white rounded-xl p-3 cursor-pointer hover:shadow-md border-l-[3px] transition-all",style:{borderLeftColor:W.color},children:[e.jsxs("div",{className:"flex items-start justify-between gap-2",children:[e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("div",{className:"text-[13.5px] font-semibold text-slate-900 truncate",children:[X.first_name," ",X.last_name]}),e.jsxs("div",{className:"text-[11.5px] text-slate-500 flex items-center gap-1 mt-0.5 truncate",children:[e.jsx(Ti,{className:"h-3 w-3"}),e.jsx("span",{className:"truncate",children:X.brokerage??"—"})]})]}),X.temperature&&e.jsxs(We,{variant:"outline",className:`text-[9.5px] px-1.5 py-0 ${s0t[X.temperature]}`,children:[e.jsx(kW,{className:"h-2.5 w-2.5 mr-0.5"}),X.temperature]}),e.jsx(V,{agent:X})]}),e.jsxs("div",{className:"mt-2 flex items-center gap-2 text-[11px] text-slate-500",children:[e.jsx(ii,{className:"h-3 w-3"}),e.jsxs("span",{className:"truncate",children:[X.city,X.state&&`, ${X.state}`]})]}),X.next_follow_up_at&&e.jsxs("div",{className:"mt-1.5 text-[10.5px] text-violet-700 font-medium",children:["Next touch · ",Js(new Date(X.next_follow_up_at),"MMM d")]})]},X.id)),G.length===0&&e.jsx("div",{className:"text-[11.5px] text-slate-400 text-center py-4",children:"Drop an agent here"})]})]},W.key)})}),e.jsx(DQ,{orientation:"horizontal"})]}):e.jsx(_e,{className:"rounded-2xl overflow-hidden",children:e.jsxs("table",{className:"w-full text-sm",children:[e.jsx("thead",{className:"bg-slate-50 text-[11px] uppercase tracking-wider text-slate-500",children:e.jsxs("tr",{children:[e.jsx("th",{className:"text-left px-4 py-3",children:"Agent"}),e.jsx("th",{className:"text-left px-4 py-3",children:"Brokerage"}),e.jsx("th",{className:"text-left px-4 py-3",children:"Location"}),e.jsx("th",{className:"text-left px-4 py-3",children:"Stage"}),e.jsx("th",{className:"text-left px-4 py-3",children:"Temp"}),e.jsx("th",{className:"text-left px-4 py-3",children:"Next Follow-Up"}),e.jsx("th",{className:"text-right px-4 py-3",children:"Actions"})]})}),e.jsxs("tbody",{children:[z.map(W=>{const G=Qne.find(X=>X.key===W.stage);return e.jsxs("tr",{onClick:()=>b(W),className:"border-t border-slate-100 hover:bg-slate-50 cursor-pointer",children:[e.jsxs("td",{className:"px-4 py-3 font-medium text-slate-900",children:[W.first_name," ",W.last_name]}),e.jsx("td",{className:"px-4 py-3 text-slate-600",children:W.brokerage}),e.jsxs("td",{className:"px-4 py-3 text-slate-600",children:[W.city,", ",W.state]}),e.jsx("td",{className:"px-4 py-3",children:e.jsx(We,{style:{background:G==null?void 0:G.color,color:"white"},children:G==null?void 0:G.label})}),e.jsx("td",{className:"px-4 py-3",children:W.temperature&&e.jsx(We,{variant:"outline",className:s0t[W.temperature],children:W.temperature})}),e.jsx("td",{className:"px-4 py-3 text-slate-600",children:W.next_follow_up_at?Js(new Date(W.next_follow_up_at),"MMM d"):"—"}),e.jsx("td",{className:"px-4 py-3 text-right",children:e.jsx(V,{agent:W})})]},W.id)}),z.length===0&&e.jsx("tr",{children:e.jsx("td",{colSpan:7,className:"px-4 py-10 text-center text-slate-500",children:"No agents match this view."})})]})]})}),e.jsx(uPn,{open:f,onOpenChange:g,defaultStage:y,onSubmit:W=>r.mutate(W,{onSuccess:()=>g(!1)})}),e.jsx(UBt,{agent:k?t.find(W=>W.id===k.id)??k:null,open:!!k,onOpenChange:W=>!W&&A(null),onDeleted:()=>b(null)}),e.jsx(l1,{open:!!_,onOpenChange:W=>!W&&b(null),children:e.jsx(Gy,{className:"w-full sm:max-w-lg overflow-y-auto",children:$&&e.jsxs(e.Fragment,{children:[e.jsxs(gb,{children:[e.jsxs(xb,{className:"text-xl",children:[$.first_name," ",$.last_name]}),e.jsxs("div",{className:"text-[12.5px] text-slate-500 flex items-center gap-2",children:[e.jsx(Ti,{className:"h-3.5 w-3.5"})," ",$.brokerage??"—"," · ",$.city,", ",$.state]})]}),e.jsxs("div",{className:"mt-6 space-y-5",children:[e.jsxs("div",{className:"flex gap-2 flex-wrap",children:[e.jsxs(B,{size:"sm",className:"gap-1.5 bg-gradient-to-r from-violet-600 to-indigo-600 text-white",onClick:()=>A($),children:[e.jsx(Ja,{className:"h-3.5 w-3.5"})," Edit contact"]}),e.jsxs(B,{variant:"outline",size:"sm",className:"gap-1.5",onClick:()=>s(`/attract/agents/${$.id}`),children:[e.jsx(Tr,{className:"h-3.5 w-3.5"})," Open relationship"]}),$.email&&e.jsxs(B,{variant:"outline",size:"sm",className:"gap-1.5",onClick:()=>M($),children:[e.jsx(mn,{className:"h-3.5 w-3.5"})," Email"]}),$.phone&&e.jsx(B,{variant:"outline",size:"sm",className:"gap-1.5",asChild:!0,children:e.jsxs("a",{href:`tel:${$.phone}`,children:[e.jsx(ga,{className:"h-3.5 w-3.5"})," Call"]})}),e.jsxs(B,{variant:"outline",size:"sm",className:"gap-1.5",onClick:()=>s(`/attract/agents/${$.id}`),children:[e.jsx(xo,{className:"h-3.5 w-3.5"})," Log touch"]})]}),e.jsxs("div",{children:[e.jsx(re,{className:"text-[11px] uppercase tracking-wider text-slate-500",children:"Stage"}),e.jsxs(Ns,{value:$.stage,onValueChange:W=>a.mutate({id:$.id,to_stage:W,from_stage:$.stage}),children:[e.jsx(ws,{className:"mt-1",children:e.jsx(ks,{})}),e.jsx(js,{children:Qne.map(W=>e.jsx(nt,{value:W.key,children:W.label},W.key))})]})]}),e.jsxs("div",{children:[e.jsx(re,{className:"text-[11px] uppercase tracking-wider text-slate-500",children:"Temperature"}),e.jsxs(Ns,{value:$.temperature??"warm",onValueChange:W=>r.mutate({id:$.id,first_name:$.first_name,temperature:W}),children:[e.jsx(ws,{className:"mt-1",children:e.jsx(ks,{})}),e.jsx(js,{children:["cold","warm","hot"].map(W=>e.jsx(nt,{value:W,className:"capitalize",children:W},W))})]})]}),!!($.tags??[]).length&&e.jsx("div",{className:"flex flex-wrap gap-1.5",children:($.tags??[]).map(W=>e.jsx(We,{variant:"outline",className:"rounded-full",children:W},W))}),e.jsx(LIe,{label:"Notes",value:$.notes}),e.jsx(LIe,{label:"Goals",value:$.goals}),e.jsx(LIe,{label:"Challenges",value:$.challenges}),e.jsxs("div",{className:"pt-4 border-t flex justify-between",children:[e.jsxs(B,{variant:"ghost",size:"sm",onClick:()=>i.mutate({id:$.id,archived:!$.is_archived}),children:[e.jsx(xg,{className:"h-4 w-4 mr-1"})," ",$.is_archived?"Restore":"Remove from pipeline"]}),e.jsxs(B,{variant:"ghost",size:"sm",className:"text-rose-600",onClick:()=>A($),children:[e.jsx(qn,{className:"h-4 w-4 mr-1"})," Delete…"]})]})]})]})})}),(I==null?void 0:I.email)&&e.jsx(Y_,{open:!!I,onOpenChange:W=>!W&&M(null),contact:{id:I.id,first_name:I.preferred_name||I.first_name,last_name:I.last_name||"",email:I.email},gmailEmail:L,sendSource:"attract",logTouchpoint:!1})]})}function LIe({label:s,value:t}){return e.jsxs("div",{children:[e.jsx(re,{className:"text-[11px] uppercase tracking-wider text-slate-500",children:s}),e.jsx("div",{className:"mt-1 text-[13.5px] text-slate-800 whitespace-pre-wrap min-h-[24px]",children:t||e.jsx("span",{className:"text-slate-400",children:"Not set"})})]})}function uPn({open:s,onOpenChange:t,defaultStage:n,onSubmit:r}){const[a,i]=N.useState({first_name:"",last_name:"",brokerage:"",city:"",state:"",temperature:"warm",primary_pillar:"connect",stage:n??"new_connection",notes:""});return e.jsx(Bs,{open:s,onOpenChange:t,children:e.jsxs(Fs,{className:"max-w-lg",children:[e.jsx(qs,{children:e.jsx($s,{children:"Add an agent to your pipeline"})}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(re,{children:"First name *"}),e.jsx(we,{value:a.first_name,onChange:l=>i({...a,first_name:l.target.value})})]}),e.jsxs("div",{children:[e.jsx(re,{children:"Last name"}),e.jsx(we,{value:a.last_name,onChange:l=>i({...a,last_name:l.target.value})})]}),e.jsxs("div",{className:"col-span-2",children:[e.jsx(re,{children:"Current brokerage"}),e.jsx(we,{value:a.brokerage,onChange:l=>i({...a,brokerage:l.target.value})})]}),e.jsxs("div",{children:[e.jsx(re,{children:"City"}),e.jsx(we,{value:a.city,onChange:l=>i({...a,city:l.target.value})})]}),e.jsxs("div",{children:[e.jsx(re,{children:"State"}),e.jsx(we,{value:a.state,onChange:l=>i({...a,state:l.target.value})})]}),e.jsxs("div",{children:[e.jsx(re,{children:"Temperature"}),e.jsxs(Ns,{value:a.temperature,onValueChange:l=>i({...a,temperature:l}),children:[e.jsx(ws,{children:e.jsx(ks,{})}),e.jsxs(js,{children:[e.jsx(nt,{value:"cold",children:"Cold"}),e.jsx(nt,{value:"warm",children:"Warm"}),e.jsx(nt,{value:"hot",children:"Hot"})]})]})]}),e.jsxs("div",{children:[e.jsx(re,{children:"Primary pillar"}),e.jsxs(Ns,{value:a.primary_pillar,onValueChange:l=>i({...a,primary_pillar:l}),children:[e.jsx(ws,{children:e.jsx(ks,{})}),e.jsxs(js,{children:[e.jsx(nt,{value:"produce",children:"Produce"}),e.jsx(nt,{value:"influence",children:"Influence"}),e.jsx(nt,{value:"provide",children:"Provide"}),e.jsx(nt,{value:"connect",children:"Connect"})]})]})]}),e.jsxs("div",{className:"col-span-2",children:[e.jsx(re,{children:"Notes"}),e.jsx(Ws,{rows:3,value:a.notes,onChange:l=>i({...a,notes:l.target.value})})]})]}),e.jsxs(Cr,{children:[e.jsx(B,{variant:"ghost",onClick:()=>t(!1),children:"Cancel"}),e.jsx(B,{disabled:!a.first_name,className:"bg-gradient-to-r from-violet-600 to-indigo-600",onClick:()=>r(a),children:"Add Agent"})]})]})})}const hPn={call:ga,email:mn,coffee:T_,gift:Io,text:mn,event:df};function mPn(){const{followUps:s,complete:t}=OJ(),{agents:n}=jb(),r=N.useMemo(()=>{const l=ey(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 f=new Date(m.due_at);rN(f,l)?o.push(m):O0(f)?c.push(m):Xcs(f)?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:Uo},{label:"Due Today",value:r.today.length,tone:"text-orange-600 bg-orange-50",icon:Xr},{label:"Completed This Week",value:r.done.filter(l=>l.completed_at&&new Date(l.completed_at)>Ad(new Date,-7)).length,tone:"text-emerald-600 bg-emerald-50",icon:Hr}];return e.jsxs("div",{children:[e.jsx(Op,{eyebrow:"Follow-Up Center",title:"One list. One rhythm. One relationship at a time.",description:"Everything you promised to do — organized so it never feels like a to-do list."}),e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-4 mb-6",children:i.map(l=>e.jsxs(_e,{className:"p-5 rounded-2xl flex items-center gap-4",children:[e.jsx("div",{className:`h-11 w-11 rounded-xl grid place-items-center ${l.tone}`,children:e.jsx(l.icon,{className:"h-5 w-5"})}),e.jsxs("div",{children:[e.jsx("div",{className:"text-2xl font-semibold text-slate-900",children:l.value}),e.jsx("div",{className:"text-[12px] uppercase tracking-wider text-slate-500",children:l.label})]})]},l.label))}),e.jsx("div",{className:"mb-6",children:e.jsx(xO,{})}),e.jsxs("div",{className:"space-y-6",children:[e.jsx(jH,{title:"Overdue",items:r.overdue,agentMap:a,onComplete:l=>t.mutate(l),tone:"rose"}),e.jsx(jH,{title:"Today",items:r.today,agentMap:a,onComplete:l=>t.mutate(l),tone:"orange"}),e.jsx(jH,{title:"Tomorrow",items:r.tomorrow,agentMap:a,onComplete:l=>t.mutate(l),tone:"violet"}),e.jsx(jH,{title:"Later This Week",items:r.later,agentMap:a,onComplete:l=>t.mutate(l),tone:"slate"}),r.done.length>0&&e.jsx(jH,{title:"Recently Completed",items:r.done.slice(0,5),agentMap:a,onComplete:()=>{},tone:"emerald",done:!0})]})]})}function jH({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(We,{variant:"secondary",className:"text-[10px]",children:t.length})]}),e.jsx(_e,{className:"rounded-2xl divide-y divide-slate-100 overflow-hidden",children:t.map(o=>{const c=n.get(o.agent_id),d=hPn[o.touch_type??""]??mn;return e.jsxs("div",{className:`flex items-start gap-3 p-4 hover:bg-slate-50 ${i?"opacity-60":""}`,children:[e.jsx(Bi,{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:Js(new Date(o.due_at),"MMM d")}),e.jsx(B,{variant:"ghost",size:"sm",children:"Snooze"})]},o.id)})})]})}const pPn={pdf:Wr,link:cd,video:na,tool:sN,guide:Ep},fPn={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 gPn(){const{resources:s,isLoading:t}=$Bt(),[n,r]=N.useState(""),[a,i]=N.useState("all"),l=Array.from(new Set(s.map(c=>c.category).filter(Boolean))),o=s.filter(c=>(a==="all"||c.category===a)&&(!n||`${c.title} ${c.description??""}`.toLowerCase().includes(n.toLowerCase())));return e.jsxs("div",{children:[e.jsx(Op,{eyebrow:"Resource Library",title:"The stack you share with future teammates.",description:"Every resource, script, and tool you use — ready to share in one click.",actions:e.jsxs(B,{className:"rounded-full bg-gradient-to-r from-violet-600 to-indigo-600",children:[e.jsx(nn,{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(Gr,{className:"h-4 w-4 text-slate-400 absolute left-3 top-1/2 -translate-y-1/2"}),e.jsx(we,{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(_e,{className:"p-12 text-center rounded-2xl",children:e.jsx("div",{className:"text-slate-500",children:"No resources yet. Add your first shareable asset above."})}):e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 xl:grid-cols-3 gap-4",children:o.map(c=>{const d=pPn[c.resource_type]??Wr;return e.jsxs(_e,{className:"p-5 rounded-2xl hover:shadow-md transition-all group",children:[e.jsxs("div",{className:"flex items-start justify-between gap-3",children:[e.jsx("div",{className:"h-11 w-11 rounded-xl bg-violet-50 grid place-items-center text-violet-600",children:e.jsx(d,{className:"h-5 w-5"})}),c.category&&e.jsx(We,{className:`${fPn[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(Md,{className:"h-3.5 w-3.5"})," Share"]})]})]},c.id)})})]})}const xPn=[{category:"First Touch",icon:xo,color:"#7c3aed",items:[{title:"Warm intro after meeting",body:"Hey {{first_name}} — really enjoyed meeting you at {{event}}. Would love to grab coffee sometime and hear more about what you're building at {{brokerage}}."},{title:"Congrats on a recent close",body:"Saw your closing at {{property}} pop up — nice work {{first_name}}. Those aren't easy right now. If you ever want to compare notes on how you're getting deals across the line, I'm always up for a coffee."}]},{category:"Value Share",icon:mn,color:"#4f46e5",items:[{title:"Sending a helpful resource",body:"Hey {{first_name}} — thought of you when I put this together. No agenda, just something I think you'll actually use: {{resource_link}}"},{title:"Market update forward",body:"Sending along this month's local market snapshot — figured you might want it for your buyer conversations this week: {{link}}"}]},{category:"Coffee Invite",icon:T_,color:"#0d9488",items:[{title:"Casual 30-min coffee",body:"Hey {{first_name}}, are you free for a 30-min coffee sometime in the next couple weeks? No agenda — just want to hear how the year is going for you."},{title:"Follow-up after coffee",body:"Really enjoyed catching up {{first_name}}. Here's the {{resource}} I mentioned — and I'll circle back in a few weeks. In the meantime, if I can help with anything, just text."}]},{category:"Check-In",icon:ga,color:"#9333ea",items:[{title:"Quarterly check-in",body:"Hey {{first_name}} — just thinking of you. How's the quarter shaping up? No ask, just checking in."},{title:"Birthday message",body:"Happy birthday {{first_name}}! Hope you get to slow down for a minute today. 🎉"}]}];function yPn(){const s=t=>{navigator.clipboard.writeText(t),ie.success("Template copied")};return e.jsxs("div",{children:[e.jsx(Op,{eyebrow:"Message Templates",title:"Words that sound like you.",description:"Starting points — never scripts. Personalize the details and let the relationship speak."}),e.jsx("div",{className:"space-y-8",children:xPn.map(t=>{const n=t.icon;return e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-3 mb-4",children:[e.jsx("div",{className:"h-10 w-10 rounded-xl grid place-items-center",style:{background:`${t.color}18`,color:t.color},children:e.jsx(n,{className:"h-5 w-5"})}),e.jsxs("div",{children:[e.jsx("h3",{className:"text-lg font-semibold text-slate-900",children:t.category}),e.jsxs("div",{className:"text-[12.5px] text-slate-500",children:[t.items.length," templates"]})]})]}),e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:t.items.map(r=>e.jsxs(_e,{className:"p-5 rounded-2xl",children:[e.jsxs("div",{className:"flex items-start justify-between gap-2",children:[e.jsx("div",{className:"font-semibold text-slate-900",children:r.title}),e.jsx(We,{variant:"outline",className:"text-[10px]",children:t.category})]}),e.jsx("p",{className:"mt-3 text-[13.5px] text-slate-700 leading-relaxed whitespace-pre-wrap",children:r.body}),e.jsx("div",{className:"mt-4 pt-4 border-t border-slate-100 flex justify-end",children:e.jsxs(B,{variant:"outline",size:"sm",className:"rounded-full gap-1",onClick:()=>s(r.body),children:[e.jsx(Pa,{className:"h-3.5 w-3.5"})," Copy"]})})]},r.title))})]},t.category)})})]})}const vPn={produce:"#7c3aed",influence:"#4f46e5",provide:"#0d9488",connect:"#9333ea"};function bPn(){const{agents:s}=jb(),{activities:t}=IBt(180),n=N.useMemo(()=>Array.from({length:12},(l,o)=>lx(zW(new Date,(11-o)*7))).map(l=>{const o=Ad(l,7),c=t.filter(d=>new Date(d.created_at)>=l&&new Date(d.created_at){const i={produce:0,influence:0,provide:0,connect:0};for(const l of t)l.pillar&&(i[l.pillar]=(i[l.pillar]||0)+1);return Object.entries(i).map(([l,o])=>({name:l,value:o,color:vPn[l]}))},[t]),a=N.useMemo(()=>["new_connection","building_relationship","engaging_with_value","active_conversation","brokerage_presentation","joined"].map(l=>({stage:l.replace(/_/g," "),count:s.filter(o=>o.stage===l).length})),[s]);return e.jsxs("div",{children:[e.jsx(Op,{eyebrow:"Reports & Insights",title:"See the compounding effect.",description:"Attraction is a long game. These reports show you the small consistent trend lines that matter."}),e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-6",children:[e.jsxs(_e,{className:"p-6 rounded-2xl",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-wider text-slate-500 mb-1",children:"Weekly Activity"}),e.jsx("div",{className:"text-lg font-semibold text-slate-900 mb-4",children:"Attraction activities · Last 12 weeks"}),e.jsx(b5,{width:"100%",height:260,children:e.jsxs(nGe,{data:n,children:[e.jsx(R5,{dataKey:"week",tick:{fontSize:11}}),e.jsx(O5,{tick:{fontSize:11}}),e.jsx(Vx,{}),e.jsx(eO,{type:"monotone",dataKey:"activities",stroke:"#7c3aed",strokeWidth:2.5,dot:{r:3}})]})})]}),e.jsxs(_e,{className:"p-6 rounded-2xl",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-wider text-slate-500 mb-1",children:"Pillar Balance"}),e.jsx("div",{className:"text-lg font-semibold text-slate-900 mb-4",children:"Where you're investing time"}),e.jsx(b5,{width:"100%",height:260,children:e.jsxs(aGe,{children:[e.jsx(jN,{data:r,dataKey:"value",nameKey:"name",cx:"50%",cy:"50%",innerRadius:55,outerRadius:90,paddingAngle:2,children:r.map((i,l)=>e.jsx(DU,{fill:i.color},l))}),e.jsx(Vx,{}),e.jsx(ID,{})]})})]}),e.jsxs(_e,{className:"p-6 rounded-2xl lg:col-span-2",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-wider text-slate-500 mb-1",children:"Pipeline Distribution"}),e.jsx("div",{className:"text-lg font-semibold text-slate-900 mb-4",children:"Agents by stage"}),e.jsx(b5,{width:"100%",height:280,children:e.jsxs(rGe,{data:a,children:[e.jsx(R5,{dataKey:"stage",tick:{fontSize:10}}),e.jsx(O5,{tick:{fontSize:11}}),e.jsx(Vx,{}),e.jsx(D5,{dataKey:"count",fill:"#4f46e5",radius:[8,8,0,0]})]})})]})]})]})}function _Pn(){const{settings:s,upsert:t,resetOnboarding:n}=RJ(),[r,a]=N.useState({});N.useEffect(()=>{s&&a(s)},[s]);const i=l=>a({...r,...l});return e.jsxs("div",{className:"max-w-3xl",children:[e.jsx(Op,{eyebrow:"Attract Settings",title:"Your attraction philosophy.",description:"A one-time setup that keeps every touch you send true to who you are."}),e.jsxs(_e,{className:"p-5 rounded-2xl mb-6 flex flex-col md:flex-row md:items-center gap-4 bg-gradient-to-r from-violet-50 to-indigo-50 border-violet-100",children:[e.jsx("div",{className:"h-11 w-11 rounded-xl bg-white text-violet-700 grid place-items-center shadow-sm",children:e.jsx(iu,{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(cr,{to:"/attract/plan",children:"View plan"})}),e.jsxs(B,{variant:"outline",className:"rounded-full",onClick:()=>n.mutate(),children:[e.jsx(hf,{className:"h-4 w-4 mr-1.5"})," Rerun onboarding"]})]})]}),e.jsxs("div",{className:"space-y-6",children:[e.jsxs(_e,{className:"p-6 rounded-2xl",children:[e.jsx("h3",{className:"text-lg font-semibold text-slate-900 mb-1",children:"Your voice & story"}),e.jsx("p",{className:"text-[13px] text-slate-600 mb-5",children:"Used to personalize scripts, invites, and shared content."}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(re,{children:"Elevator introduction"}),e.jsx(Ws,{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(re,{children:"Focus market"}),e.jsx(we,{value:r.focus_market??"",onChange:l=>i({focus_market:l.target.value}),placeholder:"Orange County, CA"})]}),e.jsxs("div",{children:[e.jsx(re,{children:"Annual attraction goal"}),e.jsx(we,{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(re,{children:'Your "why" for attraction'}),e.jsx(Ws,{rows:3,value:r.why_statement??"",onChange:l=>i({why_statement:l.target.value}),placeholder:"Because the right agents in the right room change everyone's business..."})]})]})]}),e.jsxs(_e,{className:"p-6 rounded-2xl",children:[e.jsx("h3",{className:"text-lg font-semibold text-slate-900 mb-1",children:"Cadence & rhythm"}),e.jsx("p",{className:"text-[13px] text-slate-600 mb-5",children:"How often should we remind you to show up for agents at each stage?"}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx(re,{children:"Hot leads follow-up"}),e.jsxs(Ns,{value:String(r.hot_cadence_days??3),onValueChange:l=>i({hot_cadence_days:Number(l)}),children:[e.jsx(ws,{children:e.jsx(ks,{})}),e.jsxs(js,{children:[e.jsx(nt,{value:"1",children:"Every day"}),e.jsx(nt,{value:"3",children:"Every 3 days"}),e.jsx(nt,{value:"7",children:"Every week"})]})]})]}),e.jsxs("div",{children:[e.jsx(re,{children:"Warm leads follow-up"}),e.jsxs(Ns,{value:String(r.warm_cadence_days??14),onValueChange:l=>i({warm_cadence_days:Number(l)}),children:[e.jsx(ws,{children:e.jsx(ks,{})}),e.jsxs(js,{children:[e.jsx(nt,{value:"7",children:"Weekly"}),e.jsx(nt,{value:"14",children:"Every 2 weeks"}),e.jsx(nt,{value:"30",children:"Monthly"})]})]})]}),e.jsxs("div",{children:[e.jsx(re,{children:"Long-term nurture"}),e.jsxs(Ns,{value:String(r.longterm_cadence_days??60),onValueChange:l=>i({longterm_cadence_days:Number(l)}),children:[e.jsx(ws,{children:e.jsx(ks,{})}),e.jsxs(js,{children:[e.jsx(nt,{value:"30",children:"Monthly"}),e.jsx(nt,{value:"60",children:"Every 2 months"}),e.jsx(nt,{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(zn,{checked:r.weekly_digest_enabled??!0,onCheckedChange:l=>i({weekly_digest_enabled:l})})]})})]})]}),e.jsxs(_e,{className:"p-6 rounded-2xl bg-gradient-to-br from-violet-50 to-indigo-50 border-violet-100",children:[e.jsx("h3",{className:"text-lg font-semibold text-slate-900 mb-1",children:"The Attract Trust Reminder"}),e.jsx("p",{className:"text-[13.5px] text-slate-700 leading-relaxed",children:"Attract is never a sales funnel. Every touch you make here should be something you'd be proud of if the agent saw every note you'd taken about them. Real relationships. On a rhythm. For years."})]}),e.jsx("div",{className:"flex justify-end",children:e.jsx(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 Hze=[{key:"transaction_tracker",pillar:"produce",title:"Transaction-to-Relationship Tracker",route:"/attract/produce/transaction-tracker",status:"live",tables:["attract_transactions","attract_agents"],notes:"Full CRUD, converts co-op agents into pipeline relationships."},{key:"production_goals",pillar:"produce",title:"Production Goals",route:"/attract/produce/goals",status:"live",tables:["attract_production_goals","attract_transactions"],notes:"Annual/quarterly/monthly targets, pace vs actual, auto closings from logged transactions, weekly breakdown."},{key:"awards",pillar:"produce",title:"Awards & Recognition",route:"/attract/produce/awards",status:"live",tables:["attract_awards"],notes:"CRUD + copyable proof points into Content Studio."},{key:"content_calendar",pillar:"produce",title:"Content Calendar",route:"/attract/influence/content-calendar",status:"live",tables:["attract_content_drafts","attract_market_presence","attract_speaking_opportunities"],notes:"Unified month grid; schedules undated drafts."},{key:"market_presence",pillar:"produce",title:"Market Presence",route:"/attract/produce/market-presence",status:"live",tables:["attract_market_presence"],notes:"Cadence commitments with status pipeline, past-due tracking, task + activity wiring."},{key:"testimonials",pillar:"produce",title:"Client Testimonials",route:"/attract/produce/testimonials",status:"live",tables:["attract_testimonials"],notes:"Permission tracking, approval gate, usage counter to prevent overexposure."},{key:"content_studio",pillar:"influence",title:"Authority Content Studio",route:"/attract/influence/content-studio",status:"live",tables:["attract_content_drafts"],notes:"AI-assisted drafts with status workflow."},{key:"speaking",pillar:"influence",title:"Speaking Calendar",route:"/attract/influence/speaking",status:"live",tables:["attract_speaking_opportunities","attract_follow_ups","attract_activities"],notes:"Month/week/agenda, full CRUD, status pipeline, ICS export, follow-up + activity wiring."},{key:"masterclass",pillar:"influence",title:"Masterclass Builder",route:"/attract/provide/masterclasses",status:"live",tables:["attract_masterclasses","attract_events","attract_resource_kits","attract_follow_ups"],notes:"Lives under Provide; 6-step builder, autosave, event + kit conversion."},{key:"podcast",pillar:"influence",title:"Podcast & Guest Spots",route:"/attract/influence/speaking",status:"partial",tables:["attract_speaking_opportunities"],notes:"Tracked as event_type = podcast inside the Speaking Calendar."},{key:"roundtables",pillar:"influence",title:"Agent Roundtables",route:"/attract/events/new",status:"partial",tables:["attract_events"],notes:"Uses the Connect Event Engine rather than a separate system."},{key:"resource_kits",pillar:"provide",title:"Resource Kit Builder",route:"/attract/provide/kits",status:"live",tables:["attract_resource_kits","attract_resource_kit_items","attract_kit_shares","attract_kit_events"],notes:"Flagship — build, share, track engagement."},{key:"kit_templates",pillar:"provide",title:"Starter Kit Library",route:"/attract/provide/kits/templates",status:"live",tables:["attract_kit_templates"],notes:"10 starter kits, clone to own."},{key:"masterclass_builder",pillar:"provide",title:"Masterclass Builder",route:"/attract/provide/masterclasses",status:"live",tables:["attract_masterclasses"],notes:"8 starter templates, deterministic copy generation, no auto-send."},{key:"value_library",pillar:"provide",title:"Value Library",route:"/attract/resources",status:"partial",tables:["attract_resources"],notes:"Read + save works; no categorization/search yet."},{key:"event_engine",pillar:"connect",title:"Event & Mastermind Engine",route:"/attract/events",status:"live",tables:["attract_events","attract_event_attendees","attract_event_invitations","attract_event_notes"],notes:"Builder, public registration, invitations, QR check-in, follow-up."},{key:"checkin",pillar:"connect",title:"Mobile Check-In",route:"/attract/events/:eventId/checkin",status:"live",tables:["attract_event_attendees"],notes:"QR + manual check-in."},{key:"coffee_meetings",pillar:"connect",title:"Coffee & Meetings",route:"/attract/follow-up",status:"partial",tables:["attract_follow_ups"],notes:"Handled as follow-ups; no dedicated meeting scheduler."},{key:"milestones",pillar:"connect",title:"Milestones & Celebrations",route:"/attract/connect/milestones",status:"live",tables:["attract_milestones","attract_follow_ups"],notes:"Recurring annual dates roll forward; reach-out tasks + celebration logging."},{key:"checkins",pillar:"connect",title:"Personal Check-Ins",route:"/attract/opportunities",status:"partial",tables:["attract_recommendations"],notes:"Surfaced by the intelligence layer as recommendations."},{key:"circles",pillar:"connect",title:"Agent Circles",route:"/attract/events/new",status:"partial",tables:["attract_events"],notes:"Create as a recurring mastermind event."},{key:"opportunities",pillar:"core",title:"Relationship Opportunities",route:"/attract/opportunities",status:"live",tables:["attract_recommendations","attract_agent_scores"],notes:"Ranked, explainable recommendations."},{key:"digest",pillar:"core",title:"Weekly Digest",route:"/attract/digest",status:"live",tables:["attract_digests","attract_digest_items","attract_digest_settings"],notes:"Manual send + preview via attract-send-digest."},{key:"plan",pillar:"core",title:"90-Day Plan",route:"/attract/plan",status:"live",tables:["attract_settings","attract_daily_plan"],notes:""},{key:"pipeline",pillar:"core",title:"Agent Pipeline",route:"/attract/pipeline",status:"live",tables:["attract_agents","attract_pipeline_history"],notes:"Kanban with stage history."},{key:"reports",pillar:"core",title:"Reports",route:"/attract/reports",status:"partial",tables:["attract_activities","attract_agents"],notes:"Core charts only; no export."}],Gze={live:"Live",partial:"Partial",placeholder:"Placeholder",integration_required:"Integration required"},qBt={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 wPn({tool:s,accent:t}){const[n,r]=N.useState(!1),a=tr(),i=s.icon,l=!!s.to,o=Hze.find(u=>u.key===s.key),c=(o==null?void 0:o.status)??(l?"live":"placeholder"),d=()=>{l&&s.to?a(s.to):r(!0)};return e.jsxs(e.Fragment,{children:[e.jsxs(_e,{onClick:d,className:"group p-5 rounded-2xl border-slate-200/70 bg-white shadow-sm hover:shadow-md cursor-pointer transition-all hover:-translate-y-0.5 relative",children:[e.jsxs("div",{className:`absolute top-3 right-3 inline-flex items-center gap-1 text-[10px] font-semibold uppercase tracking-wider rounded-full px-2 py-0.5 border ${qBt[c]}`,children:[c==="live"&&e.jsx(Cn,{className:"h-2.5 w-2.5"}),Gze[c]]}),e.jsxs("div",{className:"flex items-start gap-4",children:[e.jsx("div",{className:"h-11 w-11 rounded-xl grid place-items-center flex-shrink-0",style:{background:`${t}18`,color:t},children:e.jsx(i,{className:"h-5 w-5"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("div",{className:"text-[15px] font-semibold text-slate-900",children:s.title}),e.jsx("div",{className:"text-[13px] text-slate-600 mt-1 leading-relaxed",children:s.description}),e.jsxs("div",{className:"mt-3 inline-flex items-center gap-1 text-[12.5px] font-semibold",style:{color:t},children:[s.cta??(l?"Open Tool":"Preview")," ",e.jsx(Qa,{className:"h-3.5 w-3.5 group-hover:translate-x-0.5 transition-transform"})]})]})]})]}),e.jsx(Bs,{open:n,onOpenChange:r,children:e.jsxs(Fs,{className:"max-w-lg",children:[e.jsxs(qs,{children:[e.jsx("div",{className:"h-12 w-12 rounded-2xl grid place-items-center mb-2",style:{background:`${t}18`,color:t},children:e.jsx(i,{className:"h-6 w-6"})}),e.jsx($s,{children:s.title})]}),e.jsxs("div",{className:"text-[14px] text-slate-700 leading-relaxed",children:[s.description,e.jsx("div",{className:"mt-4 rounded-xl bg-violet-50 border border-violet-100 p-4 text-[13px] text-violet-900",children:"This tool is on the roadmap. Mark your interest and it will jump the queue in your next release."})]}),e.jsxs(Cr,{children:[e.jsx(B,{variant:"ghost",onClick:()=>r(!1),children:"Close"}),e.jsx(B,{className:"bg-gradient-to-r from-violet-600 to-indigo-600",onClick:()=>{ie.success("Added to your plan"),r(!1)},children:"Add to My Plan"})]})]})})]})}function FKe({pillar:s,title:t,tagline:n,intro:r,accent:a,icon:i,tools:l,stats:o}){return e.jsxs("div",{children:[e.jsxs("div",{className:"rounded-3xl p-7 md:p-10 mb-8 relative overflow-hidden text-white",style:{background:`linear-gradient(135deg, ${a} 0%, #4f46e5 100%)`},children:[e.jsx("div",{className:"absolute -right-16 -top-16 h-64 w-64 rounded-full bg-white/10 blur-2xl"}),e.jsxs("div",{className:"relative",children:[e.jsxs("div",{className:"inline-flex items-center gap-2 text-[11px] uppercase tracking-[0.18em] font-semibold opacity-80 mb-3",children:[e.jsx(i,{className:"h-4 w-4"})," Pillar ",s]}),e.jsx("h1",{className:"text-4xl md:text-5xl font-semibold tracking-tight",children:t}),e.jsx("p",{className:"text-white/85 text-lg mt-2",children:n}),e.jsx("p",{className:"text-white/70 mt-4 max-w-2xl leading-relaxed",children:r}),o&&e.jsx("div",{className:"mt-6 grid grid-cols-2 md:grid-cols-4 gap-3 max-w-2xl",children:o.map(c=>e.jsxs("div",{className:"rounded-xl bg-white/10 backdrop-blur px-4 py-3",children:[e.jsx("div",{className:"text-2xl font-semibold tabular-nums",children:c.value}),e.jsx("div",{className:"text-[11.5px] uppercase tracking-wider opacity-80",children:c.label})]},c.label))})]})]}),e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 xl:grid-cols-3 gap-4",children:l.map(c=>e.jsx(wPn,{tool:c,accent:a},c.key))})]})}function n0t(){return e.jsx(FKe,{pillar:"01",title:"Produce",accent:"#7c3aed",icon:gl,tagline:"Become the agent others want to be around.",intro:"Production isn't ego — it's proof. When you're actively closing, learning, and getting recognized, agents naturally lean in. Use these tools to make your production visible without bragging.",stats:[{label:"Closed YTD",value:24},{label:"Awards",value:3},{label:"Content Pieces",value:12},{label:"Speaking",value:2}],tools:[{key:"transaction_tracker",icon:Wa,title:"Transaction-to-Relationship Tracker",description:"Turn great cooperating agents from real transactions into long-term professional relationships.",to:"/attract/produce/transaction-tracker"},{key:"production_goals",icon:By,title:"Production Goals",description:"Set annual, quarterly, and monthly targets, then track whether you are ahead or behind pace.",to:"/attract/produce/goals"},{key:"awards",icon:ku,title:"Awards & Recognition",description:"Track brokerage and industry awards so you can reference them naturally in agent conversations.",to:"/attract/produce/awards"},{key:"content_calendar",icon:E_,title:"Content Calendar",description:"One month view of every draft, market update, and speaking date you have committed to.",to:"/attract/influence/content-calendar"},{key:"market_presence",icon:ml,title:"Market Presence",description:"Publish market updates on a set cadence so agents see you as the local voice.",to:"/attract/produce/market-presence"},{key:"testimonials",icon:Wa,title:"Client Testimonials",description:"A permission-tracked library of client quotes that make future agent conversations easier.",to:"/attract/produce/testimonials"}]})}function r0t(){return e.jsx(FKe,{pillar:"02",title:"Influence",accent:"#4f46e5",icon:Cn,tagline:"Show up in ways that draw the right agents to you.",intro:"Influence is earned by helping publicly and consistently. These tools give you simple ways to teach, speak, and be seen — so the right agents come to you first.",stats:[{label:"Speaking Slots",value:4},{label:"Podcast Guests",value:2},{label:"Masterclasses",value:6},{label:"Reach",value:"12.4k"}],tools:[{key:"content_studio",icon:f5,title:"Authority Content Studio",description:"Turn your real experience into agent-focused content — script, caption, carousel, email — in one shot.",to:"/attract/influence/content-studio"},{key:"content_calendar",icon:ld,title:"Content Calendar",description:"See drafts, market updates, and speaking dates on one month grid — and schedule what has no date.",to:"/attract/influence/content-calendar"},{key:"speaking",icon:uj,title:"Speaking Calendar",description:"Track panels, MLS talks, podcasts, and keynotes from first idea through post-event follow-up.",to:"/attract/influence/speaking"},{key:"masterclass",icon:Oh,title:"Masterclass Builder",description:"Turn what you already know into a 45-minute teaching moment agents actually attend.",to:"/attract/provide/masterclasses"},{key:"podcast",icon:na,title:"Podcast & Guest Spots",description:"Log podcast appearances in the Speaking Calendar and repurpose clips into agent touch points.",to:"/attract/influence/speaking"},{key:"roundtables",icon:Yn,title:"Agent Roundtables",description:"Host small-group conversations using the Connect Event Engine — value first, no pitching.",to:"/attract/events/new"}]})}const x7=["attract-kits"],NH=s=>["attract-kit-items",s],kH=s=>["attract-kit-shares",s??"all"],jPn=s=>["attract-kit-events",s??"all"],NPn=["attract-kit-templates"];function dq(){const{user:s}=Ls(),t=as(),n=mt({queryKey:[...x7,s==null?void 0:s.id],enabled:!!s,queryFn:async()=>{const{data:o,error:c}=await H.from("attract_resource_kits").select("*").order("updated_at",{ascending:!1});if(c)throw c;return o??[]}}),r=_t({mutationFn:async o=>{if(!s)throw new Error("not authenticated");const{data:c,error:d}=await H.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:x7})}),a=_t({mutationFn:async({id:o,patch:c})=>{const{data:d,error:u}=await H.from("attract_resource_kits").update(c).eq("id",o).select("*").single();if(u)throw u;return d},onSuccess:()=>t.invalidateQueries({queryKey:x7})}),i=_t({mutationFn:async o=>{const{error:c}=await H.from("attract_resource_kits").delete().eq("id",o);if(c)throw c},onSuccess:()=>t.invalidateQueries({queryKey:x7})}),l=_t({mutationFn:async o=>{const{data:c,error:d}=await H.rpc("duplicate_attract_kit",{_kit_id:o});if(d)throw d;return c},onSuccess:()=>t.invalidateQueries({queryKey:x7})});return{kits:n.data??[],isLoading:n.isLoading,create:r,update:a,remove:i,duplicate:l}}function VBt(s){return mt({queryKey:["attract-kit",s],enabled:!!s,queryFn:async()=>{const{data:t,error:n}=await H.from("attract_resource_kits").select("*").eq("id",s).single();if(n)throw n;return t}})}function kPn(s){const t=as(),n=mt({queryKey:NH(s??""),enabled:!!s,queryFn:async()=>{const{data:o,error:c}=await H.from("attract_resource_kit_items").select("*").eq("kit_id",s).order("sort_order");if(c)throw c;return o??[]}}),r=_t({mutationFn:async o=>{var u;const{data:c,error:d}=await H.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:NH(s??"")})}),a=_t({mutationFn:async({id:o,patch:c})=>{const{error:d}=await H.from("attract_resource_kit_items").update(c).eq("id",o);if(d)throw d},onSuccess:()=>t.invalidateQueries({queryKey:NH(s??"")})}),i=_t({mutationFn:async o=>{const{error:c}=await H.from("attract_resource_kit_items").delete().eq("id",o);if(c)throw c},onSuccess:()=>t.invalidateQueries({queryKey:NH(s??"")})}),l=_t({mutationFn:async o=>{await Promise.all(o.map((c,d)=>H.from("attract_resource_kit_items").update({sort_order:d}).eq("id",c)))},onSuccess:()=>t.invalidateQueries({queryKey:NH(s??"")})});return{items:n.data??[],isLoading:n.isLoading,add:r,update:a,remove:i,reorder:l}}function HBt(s){const{user:t}=Ls(),n=as(),r=mt({queryKey:kH(s),enabled:!!t,queryFn:async()=>{let l=H.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=_t({mutationFn:async l=>{if(!t)throw new Error("not authenticated");const{data:o,error:c}=await H.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:kH(s)}),n.invalidateQueries({queryKey:kH()});try{(o=navigator.clipboard)==null||o.writeText(WBt(l.share_token)),ie.success("Share link created and copied")}catch{ie.success("Share link created")}},onError:l=>ie.error((l==null?void 0:l.message)||"Could not create share link")}),i=_t({mutationFn:async l=>{const{error:o}=await H.from("attract_kit_shares").update({status:"revoked"}).eq("id",l);if(o)throw o},onSuccess:()=>{n.invalidateQueries({queryKey:kH(s)}),n.invalidateQueries({queryKey:kH()}),ie.success("Link revoked")},onError:l=>ie.error((l==null?void 0:l.message)||"Could not revoke link")});return{shares:r.data??[],isLoading:r.isLoading,create:a,revoke:i}}function GBt(s){return mt({queryKey:jPn(s),queryFn:async()=>{let t=H.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 SPn(){return mt({queryKey:NPn,queryFn:async()=>{const{data:s,error:t}=await H.from("attract_kit_templates").select("*").eq("is_active",!0).order("sort_order");if(t)throw t;return s??[]}})}function CPn(){const s=as();return _t({mutationFn:async t=>{const{data:n,error:r}=await H.rpc("clone_attract_kit_template",{_template_id:t});if(r)throw r;return n},onSuccess:()=>s.invalidateQueries({queryKey:x7})})}function WBt(s){return`${typeof window<"u"?window.location.origin:""}/attract-kit/${s}`}function a0t(){const{kits:s}=dq(),{data:t=[]}=GBt(),{followUps:n}=OJ(),r=N.useMemo(()=>{const l=o=>t.filter(c=>c.event_type===o).length;return{published:s.filter(o=>o.status==="published").length,drafts:s.filter(o=>o.status==="draft").length,views:l("page_view"),downloads:l("file_download"),cta:l("primary_cta_click"),questions:l("question_submitted")}},[s,t]),a=t.slice(0,8),i=n.filter(l=>!l.completed_at&&l.touch_type==="kit_engagement").slice(0,6);return e.jsxs("div",{className:"space-y-6",children:[e.jsx(Op,{eyebrow:"Pillar 03 · Provide",title:"Give more value than any agent expected.",description:"Package the value you already share into beautiful, trackable kits. See exactly which value creates conversations.",actions:e.jsxs("div",{className:"flex gap-2",children:[e.jsx(B,{variant:"outline",asChild:!0,className:"rounded-full",children:e.jsxs(cr,{to:"/attract/provide/kits/templates",children:[e.jsx(rb,{className:"h-4 w-4 mr-2"}),"Starter library"]})}),e.jsx(B,{asChild:!0,className:"rounded-full bg-gradient-to-r from-violet-600 to-indigo-600",children:e.jsxs(cr,{to:"/attract/provide/kits/new",children:[e.jsx(nn,{className:"h-4 w-4 mr-2"}),"New kit"]})})]})}),e.jsx(_e,{className:"p-6 md:p-8 rounded-2xl bg-gradient-to-br from-teal-50 via-violet-50 to-indigo-50 border-slate-200",children:e.jsxs("div",{className:"flex items-start gap-4 flex-wrap",children:[e.jsx("div",{className:"h-12 w-12 rounded-2xl bg-white grid place-items-center shadow-sm",children:e.jsx(mD,{className:"h-6 w-6 text-teal-600"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("div",{className:"text-[15px] font-semibold text-slate-900",children:"Resource Kits — the flagship of Provide"}),e.jsx("p",{className:"text-[13.5px] text-slate-700 mt-1 max-w-3xl",children:"Bundle 3–7 pieces of real value (scripts, checklists, videos, tools) into a beautiful shareable kit. Send a personalized link to an agent, then let engagement recommend the next relationship touch. No pressure. Just real value that compounds."}),e.jsxs("div",{className:"flex gap-2 mt-4",children:[e.jsx(B,{asChild:!0,size:"sm",className:"bg-gradient-to-r from-violet-600 to-indigo-600",children:e.jsx(cr,{to:"/attract/provide/kits/new",children:"Start a kit"})}),e.jsx(B,{variant:"outline",size:"sm",asChild:!0,children:e.jsx(cr,{to:"/attract/provide/kits/templates",children:"Browse 10 starter kits"})})]})]})]})}),e.jsx(_e,{className:"p-6 rounded-2xl border-slate-200",children:e.jsxs("div",{className:"flex items-start gap-4 flex-wrap",children:[e.jsx("div",{className:"h-12 w-12 rounded-2xl bg-violet-50 grid place-items-center",children:e.jsx(Cn,{className:"h-6 w-6 text-violet-600"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("div",{className:"text-[15px] font-semibold text-slate-900",children:"Masterclass Builder"}),e.jsx("p",{className:"text-[13.5px] text-slate-700 mt-1 max-w-3xl",children:"Turn what you already know into a 45-minute teaching moment. Build the curriculum, workbook, promotion drafts and run-of-show — then convert it into a Connect event or a Resource Kit in one click."}),e.jsx("div",{className:"flex gap-2 mt-4",children:e.jsx(B,{asChild:!0,size:"sm",className:"bg-gradient-to-r from-violet-600 to-indigo-600",children:e.jsx(cr,{to:"/attract/provide/masterclasses",children:"Open Masterclass Builder"})})})]})]})}),e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-6 gap-3",children:[e.jsx(GF,{label:"Published",value:r.published}),e.jsx(GF,{label:"Drafts",value:r.drafts}),e.jsx(GF,{label:"Views",value:r.views,icon:da}),e.jsx(GF,{label:"Downloads",value:r.downloads,icon:oi}),e.jsx(GF,{label:"CTA clicks",value:r.cta,icon:ru}),e.jsx(GF,{label:"Questions",value:r.questions,icon:Ud})]}),e.jsxs("div",{className:"grid grid-cols-1 xl:grid-cols-3 gap-6",children:[e.jsxs(_e,{className:"p-5 rounded-2xl xl:col-span-2",children:[e.jsxs("div",{className:"flex items-center justify-between mb-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[11px] uppercase tracking-widest text-violet-700 font-semibold",children:"Recent kit engagement"}),e.jsx("div",{className:"text-[12.5px] text-slate-500",children:"Live signals from agents opening your value."})]}),e.jsx(B,{variant:"outline",size:"sm",asChild:!0,children:e.jsxs(cr,{to:"/attract/provide/kits",children:["View kits ",e.jsx(vi,{className:"h-3.5 w-3.5 ml-1"})]})})]}),a.length===0?e.jsx("div",{className:"text-sm text-slate-500 py-8 text-center border border-dashed rounded-xl",children:"No engagement yet. Share a published kit to start seeing activity."}):e.jsx("div",{className:"space-y-2",children:a.map(l=>e.jsxs("div",{className:"flex items-center justify-between border-b py-2 text-[13px]",children:[e.jsx("div",{className:"capitalize",children:l.event_type.replace(/_/g," ")}),e.jsx("div",{className:"text-slate-500 text-[11.5px]",children:nc(new Date(l.created_at),{addSuffix:!0})})]},l.id))})]}),e.jsxs(_e,{className:"p-5 rounded-2xl",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-widest text-violet-700 font-semibold mb-2",children:"Recommended follow-ups"}),i.length===0?e.jsx("div",{className:"text-sm text-slate-500 py-6 text-center border border-dashed rounded-xl",children:"We'll surface follow-ups here as agents engage."}):e.jsx("div",{className:"space-y-2",children:i.map(l=>e.jsxs("div",{className:"border rounded-lg p-2.5 text-[12.5px]",children:[e.jsx("div",{className:"font-medium text-slate-900 line-clamp-2",children:l.title}),l.due_at&&e.jsxs("div",{className:"text-slate-500 text-[11px] mt-1",children:["Due ",nc(new Date(l.due_at),{addSuffix:!0})]})]},l.id))})]})]}),e.jsxs(_e,{className:"p-5 rounded-2xl",children:[e.jsxs("div",{className:"flex items-center justify-between mb-3",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-widest text-violet-700 font-semibold",children:"My kits"}),e.jsx(B,{size:"sm",variant:"ghost",asChild:!0,children:e.jsxs(cr,{to:"/attract/provide/kits",children:["See all ",e.jsx(vi,{className:"h-3.5 w-3.5 ml-1"})]})})]}),s.length===0?e.jsxs("div",{className:"text-sm text-slate-500 py-8 text-center border border-dashed rounded-xl",children:["No kits yet. ",e.jsx(cr,{to:"/attract/provide/kits/templates",className:"text-violet-700 underline",children:"Start from a template"}),"."]}):e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 xl:grid-cols-3 gap-3",children:s.slice(0,6).map(l=>e.jsxs(cr,{to:`/attract/provide/kits/${l.id}/edit`,className:"block p-4 rounded-xl border hover:border-violet-300 hover:shadow-sm transition",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[e.jsx(We,{variant:"outline",className:"capitalize",children:l.status}),l.pillar&&e.jsx(We,{variant:"secondary",className:"capitalize",children:l.pillar})]}),e.jsx("div",{className:"font-semibold text-slate-900 line-clamp-2",children:l.title}),l.description&&e.jsx("div",{className:"text-[12.5px] text-slate-500 line-clamp-2 mt-1",children:l.description})]},l.id))})]}),e.jsx(xO,{})]})}function GF({label:s,value:t,icon:n}){return e.jsxs(_e,{className:"p-4 rounded-2xl",children:[n&&e.jsx(n,{className:"h-4 w-4 text-violet-600"}),e.jsx("div",{className:"mt-1 text-[20px] font-semibold tabular-nums text-slate-900",children:t}),e.jsx("div",{className:"text-[11.5px] text-slate-500",children:s})]})}function i0t(){return e.jsx(FKe,{pillar:"04",title:"Connect",accent:"#9333ea",icon:pD,tagline:"Real relationships. On a rhythm. For years.",intro:"Connect is the pillar that makes the other three matter. It's showing up in the small, consistent ways real friendships require — birthdays, coffees, check-ins, celebrations.",stats:[{label:"Coffees This Q",value:14},{label:"Events Hosted",value:3},{label:"Birthdays Sent",value:22},{label:"On Cadence",value:"87%"}],tools:[{key:"coffee_meetings",icon:T_,title:"Coffee & Meetings",description:"The coffees to book this month, tracked as follow-ups in your Follow-Up Center.",to:"/attract/follow-up"},{key:"event_engine",icon:ta,title:"Attraction Events",description:"Design intimate gatherings — happy hours, dinners, mastermind lunches — with registration and check-in.",to:"/attract/events"},{key:"milestones",icon:Fm,title:"Milestones & Celebrations",description:"Never miss a birthday, license anniversary, or business milestone for a prospective agent.",to:"/attract/connect/milestones"},{key:"checkins",icon:Ud,title:"Personal Check-Ins",description:"Relationship-first check-ins surfaced by your intelligence layer, ranked by signal.",to:"/attract/opportunities"},{key:"circles",icon:f_,title:"Agent Circles",description:"Small peer groups you host quarterly — built on the Connect Event Engine.",to:"/attract/events/new"}]})}const APn=[{key:"coffee",label:"Coffee & Conversation",icon:T_,tone:"from-amber-500 to-orange-500",description:"A 1:1 or 3-person coffee where the goal is one real conversation."},{key:"roundtable",label:"Agent Roundtable",icon:f_,tone:"from-violet-500 to-indigo-500",description:"4–6 agents share what is actually working right now."},{key:"mastermind",label:"Mastermind",icon:Cn,tone:"from-fuchsia-500 to-pink-500",description:"A quarterly small group solving each other’s biggest questions."},{key:"workshop",label:"Workshop / Webinar",icon:iu,tone:"from-sky-500 to-blue-500",description:"A live hands-on session that delivers one clear outcome."},{key:"dinner",label:"Dinner or Happy Hour",icon:IW,tone:"from-rose-500 to-red-500",description:"The relationship-first gathering. No agenda, just presence."},{key:"networking_plan",label:"Networking Game Plan",icon:pD,tone:"from-teal-500 to-emerald-500",description:"Not an event — a plan for the next 5 rooms you will walk into."}];function TPn(){const s=tr(),{data:t=[]}=PAe(),{followUps:n}=OJ(),{agents:r}=jb(),a=N.useMemo(()=>{const l=new Date,o=Ad(l,7),c=t.filter(m=>m.status==="published"&&pj(new Date(m.starts_at),l)),d=t.filter(m=>m.status==="draft").length,u=t.reduce((m,f)=>m+(pj(new Date(f.created_at),Ad(l,-7))?f.registration_count:0),0),h=n.filter(m=>!m.completed_at&&m.due_at&&rN(new Date(m.due_at),o)&&(m.touch_type==="event_followup"||m.touch_type==="event_no_show")).length;return{upcoming:c,draftsNeedingInvites:d,regs:u,dueSoon:h}},[t,n]),i=a.upcoming[0];return e.jsxs("div",{className:"space-y-8",children:[e.jsxs("div",{className:"flex flex-col md:flex-row md:items-center md:justify-between gap-4",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.18em] text-violet-600 font-semibold mb-2",children:"Pillar 04 · Connect"}),e.jsx("h1",{className:"text-3xl md:text-[34px] font-semibold tracking-tight text-slate-900",children:"Real events. Small rooms. Long relationships."}),e.jsx("p",{className:"text-slate-600 mt-1.5 max-w-2xl",children:"Build the room, invite personally, host with care, capture one honest note, and follow up within 48 hours."})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(B,{variant:"outline",className:"rounded-full",onClick:()=>s("/attract/events"),children:[e.jsx(ta,{className:"h-4 w-4 mr-2"})," All events"]}),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(nn,{className:"h-4 w-4 mr-2"})," Create an event"]})]})]}),e.jsx("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4",children:[{label:"Upcoming events",value:a.upcoming.length,icon:ta,tone:"text-violet-700 bg-violet-100"},{label:"Drafts needing invites",value:a.draftsNeedingInvites,icon:Rr,tone:"text-amber-700 bg-amber-100"},{label:"Registrations this week",value:a.regs,icon:ml,tone:"text-emerald-700 bg-emerald-100"},{label:"48-hour follow-ups due",value:a.dueSoon,icon:zm,tone:"text-rose-700 bg-rose-100"}].map(l=>e.jsxs(_e,{className:"p-5 rounded-2xl border-slate-200 bg-white",children:[e.jsx("div",{className:`h-9 w-9 rounded-xl grid place-items-center ${l.tone}`,children:e.jsx(l.icon,{className:"h-4.5 w-4.5"})}),e.jsx("div",{className:"text-[26px] font-semibold tabular-nums mt-3",children:l.value}),e.jsx("div",{className:"text-[12.5px] text-slate-500 mt-0.5",children:l.label})]},l.label))}),e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-3 gap-6",children:[e.jsxs(_e,{className:"lg:col-span-2 p-6 rounded-2xl border-slate-200 bg-gradient-to-br from-slate-900 to-slate-800 text-white overflow-hidden relative",children:[e.jsx("div",{className:"text-[10.5px] uppercase tracking-widest text-white/60 mb-2",children:"Your next event"}),i?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"text-xl md:text-2xl font-semibold",children:i.title}),e.jsxs("div",{className:"text-white/70 mt-1",children:[Js(new Date(i.starts_at),"EEE, MMM d · h:mm a")," · ",i.format.replace("_"," ")]}),e.jsxs("div",{className:"flex flex-wrap gap-2 mt-4",children:[e.jsxs(We,{variant:"secondary",className:"bg-white/10 border-white/10 text-white",children:[i.registration_count," registered"]}),i.capacity&&e.jsxs(We,{variant:"secondary",className:"bg-white/10 border-white/10 text-white",children:[Math.max(0,i.capacity-i.registration_count)," seats left"]})]}),e.jsxs("div",{className:"mt-5 flex gap-2 flex-wrap",children:[e.jsxs(B,{size:"sm",className:"rounded-full bg-white text-slate-900 hover:bg-white/90",onClick:()=>s(`/attract/events/${i.id}`),children:["Open command center ",e.jsx(vi,{className:"h-3.5 w-3.5 ml-1"})]}),e.jsx(B,{size:"sm",variant:"outline",className:"rounded-full bg-transparent text-white border-white/30 hover:bg-white/10",onClick:()=>s(`/attract/events/${i.id}/checkin`),children:"Mobile check-in"})]})]}):e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"text-xl font-semibold",children:"No upcoming events yet"}),e.jsx("div",{className:"text-white/70 mt-1",children:"Start with a small coffee. One conversation is enough."}),e.jsx(B,{size:"sm",className:"mt-5 rounded-full bg-white text-slate-900 hover:bg-white/90",onClick:()=>s("/attract/events/new?type=coffee"),children:"Plan a coffee"})]})]}),e.jsxs(_e,{className:"p-6 rounded-2xl border-amber-200 bg-amber-50",children:[e.jsx("div",{className:"text-[10.5px] uppercase tracking-widest text-amber-700 font-semibold mb-2",children:"Reminder"}),e.jsx("div",{className:"text-[15px] text-slate-900 leading-relaxed",children:"Build relationships first. Personalize every invitation and follow-up, and verify brokerage and compensation information before sharing."})]})]}),e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center justify-between mb-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[11px] uppercase tracking-widest text-slate-500 font-semibold",children:"Quick starts"}),e.jsx("div",{className:"text-lg font-semibold text-slate-900",children:"What kind of room do you want to build?"})]}),e.jsxs(cr,{to:"/attract/events/new",className:"text-[13px] text-violet-700 hover:underline flex items-center gap-1",children:["Start from scratch ",e.jsx(Qa,{className:"h-3.5 w-3.5"})]})]}),e.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-4",children:APn.map(l=>e.jsxs("button",{onClick:()=>s(`/attract/events/new?type=${l.key}`),className:"group text-left rounded-2xl border border-slate-200 bg-white p-5 hover:border-violet-300 hover:shadow-md transition",children:[e.jsx("div",{className:`h-10 w-10 rounded-xl grid place-items-center bg-gradient-to-br ${l.tone} text-white shadow-sm`,children:e.jsx(l.icon,{className:"h-5 w-5"})}),e.jsx("div",{className:"text-[15px] font-semibold text-slate-900 mt-3",children:l.label}),e.jsx("div",{className:"text-[13px] text-slate-600 mt-1 leading-snug",children:l.description}),e.jsxs("div",{className:"text-[12px] text-violet-700 mt-3 flex items-center gap-1 opacity-0 group-hover:opacity-100 transition",children:["Start planning ",e.jsx(vi,{className:"h-3 w-3"})]})]},l.key))})]}),e.jsxs(_e,{className:"p-6 rounded-2xl border-slate-200 bg-white",children:[e.jsxs("div",{className:"flex items-center justify-between mb-4",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[11px] uppercase tracking-widest text-slate-500 font-semibold",children:"Personal connection goals"}),e.jsx("div",{className:"text-lg font-semibold text-slate-900",children:"This week"})]}),e.jsx(B,{variant:"outline",size:"sm",className:"rounded-full",onClick:()=>s("/attract/follow-up"),children:"Open Follow-Up Center"})]}),e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-4",children:[{label:"Coffees booked",target:3,actual:a.upcoming.filter(l=>(l.event_type_key||l.event_type)==="coffee").length,icon:T_,tone:"text-amber-600 bg-amber-50"},{label:"Roundtables/masterminds",target:1,actual:a.upcoming.filter(l=>["roundtable","mastermind"].includes(l.event_type_key||l.event_type)).length,icon:Cn,tone:"text-violet-600 bg-violet-50"},{label:"People in pipeline",target:r.length,actual:r.length,icon:f_,tone:"text-emerald-600 bg-emerald-50"}].map(l=>e.jsxs("div",{className:"rounded-xl border border-slate-100 p-4",children:[e.jsx("div",{className:`h-8 w-8 rounded-lg grid place-items-center ${l.tone}`,children:e.jsx(l.icon,{className:"h-4 w-4"})}),e.jsxs("div",{className:"text-[22px] font-semibold tabular-nums mt-2 leading-none",children:[l.actual,e.jsxs("span",{className:"text-slate-400 text-[15px] font-normal",children:[" / ",l.target]})]}),e.jsx("div",{className:"text-[12px] text-slate-500 mt-1",children:l.label})]},l.label))})]})]})}function EPn(){const s=tr(),{data:t=[],isLoading:n}=PAe(),r=JLn(),a=ZLn(),[i,l]=N.useState("all"),[o,c]=N.useState(""),d=N.useMemo(()=>t.filter(u=>!(i!=="all"&&u.status!==i||o&&!u.title.toLowerCase().includes(o.toLowerCase()))),[t,i,o]);return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex flex-col md:flex-row md:items-center md:justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.18em] text-violet-600 font-semibold mb-2",children:"Connect · Events"}),e.jsx("h1",{className:"text-3xl font-semibold tracking-tight text-slate-900",children:"Events"}),e.jsx("p",{className:"text-slate-600 mt-1",children:"Every room you have built — drafted, live, and complete."})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("div",{className:"relative",children:[e.jsx(Gr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-slate-400"}),e.jsx(we,{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(nn,{className:"h-4 w-4 mr-2"})," New event"]})]})]}),e.jsxs(ya,{value:i,onValueChange:u=>l(u),children:[e.jsxs(va,{className:"rounded-full bg-white border border-slate-200",children:[e.jsxs(ls,{value:"all",className:"rounded-full",children:["All (",t.length,")"]}),e.jsxs(ls,{value:"draft",className:"rounded-full",children:["Drafts (",t.filter(u=>u.status==="draft").length,")"]}),e.jsxs(ls,{value:"published",className:"rounded-full",children:["Published (",t.filter(u=>u.status==="published").length,")"]}),e.jsxs(ls,{value:"completed",className:"rounded-full",children:["Completed (",t.filter(u=>u.status==="completed").length,")"]})]}),e.jsx(_s,{value:i,className:"mt-5",children:n?e.jsx(_e,{className:"p-12 rounded-2xl text-center text-slate-500",children:"Loading events…"}):d.length===0?e.jsxs(_e,{className:"p-12 rounded-2xl text-center border-dashed",children:[e.jsx(ta,{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(nn,{className:"h-4 w-4 mr-2"})," Create your first event"]})]}):e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 xl:grid-cols-3 gap-5",children:d.map(u=>e.jsxs(_e,{className:"group rounded-2xl border-slate-200 bg-white overflow-hidden hover:shadow-md transition",children:[e.jsxs("div",{className:"h-32 bg-gradient-to-br from-violet-500 to-indigo-600 relative",children:[u.cover_image_url&&e.jsx("img",{src:u.cover_image_url,alt:"",className:"absolute inset-0 h-full w-full object-cover"}),e.jsxs("div",{className:"absolute top-3 left-3 flex gap-2",children:[e.jsx(We,{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(We,{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:Js(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(na,{className:"h-3.5 w-3.5"})," Virtual"]}):u.format==="hybrid"?e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(na,{className:"h-3.5 w-3.5"})," Hybrid"]}):e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(ii,{className:"h-3.5 w-3.5"})," ",u.location||"In person"]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Yn,{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(Pa,{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(IAe(u.public_slug)),ie.success("Registration link copied")},children:[e.jsx(Tr,{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:()=>{confirm("Delete this event?")&&a.mutate(u.id)},children:e.jsx(qn,{className:"h-3.5 w-3.5"})})]})]})]},u.id))})})]})]})}const MPn=[{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 o0t(){const{eventId:s}=uo(),t=tr(),[n]=$c(),r=n.get("type"),a=!!s,{data:i}=OKe(s),{data:l=[]}=RBt(),{kits:o}=dq(),c=OBt(),d=FBt(),[u,h]=N.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});N.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=_=>h(b=>({...b,..._})),f=N.useMemo(()=>l.slice(0,4),[l]),g=_=>{m({title:_.title,description:_.description,event_type_key:_.event_type_key,related_pillar:_.related_pillar,intended_audience:_.intended_audience,agenda:_.suggested_agenda||[],learning_outcomes:_.suggested_outcomes||[],registration_questions:_.suggested_questions||[],confirmation_message:_.suggested_confirmation}),ie.success(`Loaded "${_.title}"`)},y=async(_={})=>{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:_.publish?"published":u.status||"draft"};if(a)await d.mutateAsync({id:s,patch:b}),ie.success(_.publish?"Published":"Saved");else{const k=await c.mutateAsync(b);ie.success(_.publish?"Event published":"Draft saved"),t(`/attract/events/${k.id}${_.publish?"":"/edit"}`,{replace:!0})}},x=i!=null&&i.public_slug?IAe(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/events"),children:[e.jsx(ka,{className:"h-4 w-4 mr-2"})," All events"]}),e.jsxs("div",{className:"flex items-center gap-2",children:[x&&e.jsxs(B,{variant:"outline",size:"sm",className:"rounded-full",onClick:()=>{navigator.clipboard.writeText(x),ie.success("Registration link copied")},children:[e.jsx(gc,{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(Kl,{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(By,{className:"h-4 w-4 mr-2"})," ",(i==null?void 0:i.status)==="published"?"Update published":"Publish"]})]})]}),!a&&f.length>0&&e.jsxs(_e,{className:"p-5 rounded-2xl border-violet-200 bg-gradient-to-br from-violet-50 to-indigo-50",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-3",children:[e.jsx(Cn,{className:"h-4 w-4 text-violet-600"}),e.jsx("div",{className:"text-[13px] font-semibold text-slate-900",children:"Start from a premium template"})]}),e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-2",children:f.map(_=>e.jsxs("button",{onClick:()=>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:_.title}),e.jsx("div",{className:"text-[12px] text-slate-600 line-clamp-2 mt-0.5",children:_.description})]},_.id))})]}),e.jsxs(_e,{className:"p-6 rounded-2xl border-slate-200 bg-white",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-widest text-slate-500 font-semibold mb-1",children:"Step 1"}),e.jsx("div",{className:"text-lg font-semibold text-slate-900 mb-4",children:"Event basics"}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[e.jsxs("div",{className:"md:col-span-2",children:[e.jsx(re,{children:"Title"}),e.jsx(we,{value:u.title,onChange:_=>m({title:_.target.value}),placeholder:"Coffee & Systems Roundtable"})]}),e.jsxs("div",{children:[e.jsx(re,{children:"Event type"}),e.jsxs(Ns,{value:u.event_type_key,onValueChange:_=>m({event_type_key:_}),children:[e.jsx(ws,{children:e.jsx(ks,{})}),e.jsx(js,{children:MPn.map(_=>e.jsx(nt,{value:_.key,children:_.label},_.key))})]})]}),e.jsxs("div",{children:[e.jsx(re,{children:"Related pillar"}),e.jsxs(Ns,{value:u.related_pillar||"connect",onValueChange:_=>m({related_pillar:_}),children:[e.jsx(ws,{children:e.jsx(ks,{})}),e.jsxs(js,{children:[e.jsx(nt,{value:"produce",children:"Produce"}),e.jsx(nt,{value:"influence",children:"Influence"}),e.jsx(nt,{value:"provide",children:"Provide"}),e.jsx(nt,{value:"connect",children:"Connect"})]})]})]}),e.jsxs("div",{className:"md:col-span-2",children:[e.jsx(re,{children:"Intended audience"}),e.jsx(we,{value:u.intended_audience||"",onChange:_=>m({intended_audience:_.target.value}),placeholder:"Producing agents 1–5 years in"})]}),e.jsxs("div",{className:"md:col-span-2",children:[e.jsx(re,{children:"Description"}),e.jsx(Ws,{rows:4,value:u.description||"",onChange:_=>m({description:_.target.value}),placeholder:"What is this event and why does it matter?"})]}),e.jsxs("div",{children:[e.jsx(re,{children:"Starts at"}),e.jsx(we,{type:"datetime-local",value:u.starts_at||"",onChange:_=>m({starts_at:_.target.value})})]}),e.jsxs("div",{children:[e.jsx(re,{children:"Ends at"}),e.jsx(we,{type:"datetime-local",value:u.ends_at||"",onChange:_=>m({ends_at:_.target.value})})]}),e.jsxs("div",{children:[e.jsx(re,{children:"Time zone"}),e.jsxs(Ns,{value:u.timezone||"America/New_York",onValueChange:_=>m({timezone:_}),children:[e.jsx(ws,{children:e.jsx(ks,{})}),e.jsx(js,{children:["America/New_York","America/Chicago","America/Denver","America/Los_Angeles","America/Phoenix"].map(_=>e.jsx(nt,{value:_,children:_},_))})]})]}),e.jsxs("div",{children:[e.jsx(re,{children:"Format"}),e.jsxs(Ns,{value:u.format,onValueChange:_=>m({format:_}),children:[e.jsx(ws,{children:e.jsx(ks,{})}),e.jsxs(js,{children:[e.jsx(nt,{value:"in_person",children:"In person"}),e.jsx(nt,{value:"virtual",children:"Virtual"}),e.jsx(nt,{value:"hybrid",children:"Hybrid"})]})]})]}),u.format!=="virtual"&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{children:[e.jsx(re,{children:"Venue / location name"}),e.jsx(we,{value:u.location||"",onChange:_=>m({location:_.target.value}),placeholder:"Rise Coffee — Downtown"})]}),e.jsxs("div",{children:[e.jsx(re,{children:"Address"}),e.jsx(we,{value:u.address||"",onChange:_=>m({address:_.target.value}),placeholder:"123 Main St, City, ST"})]})]}),u.format!=="in_person"&&e.jsxs("div",{className:"md:col-span-2",children:[e.jsx(re,{children:"Virtual meeting URL"}),e.jsx(we,{value:u.virtual_url||"",onChange:_=>m({virtual_url:_.target.value}),placeholder:"https://zoom.us/…"})]}),e.jsxs("div",{children:[e.jsx(re,{children:"Capacity (optional)"}),e.jsx(we,{type:"number",value:u.capacity,onChange:_=>m({capacity:_.target.value}),placeholder:"No limit"})]}),e.jsxs("div",{className:"flex items-center gap-3 pt-6",children:[e.jsx(zn,{checked:u.waitlist_enabled,onCheckedChange:_=>m({waitlist_enabled:_}),id:"wl"}),e.jsx(re,{htmlFor:"wl",className:"cursor-pointer",children:"Allow waitlist if full"})]}),e.jsxs("div",{children:[e.jsx(re,{children:"Host name (as shown publicly)"}),e.jsx(we,{value:u.host_name||"",onChange:_=>m({host_name:_.target.value}),placeholder:"Jeremy from LevelUp"})]}),e.jsxs("div",{children:[e.jsx(re,{children:"Cover image URL"}),e.jsx(we,{value:u.cover_image_url||"",onChange:_=>m({cover_image_url:_.target.value}),placeholder:"https://…"})]})]})]}),e.jsxs(_e,{className:"p-6 rounded-2xl border-slate-200 bg-white",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-widest text-slate-500 font-semibold mb-1",children:"Step 2"}),e.jsx("div",{className:"text-lg font-semibold text-slate-900 mb-4",children:"Experience & agenda"}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsx(re,{children:"Agenda"}),e.jsxs(B,{size:"sm",variant:"ghost",className:"rounded-full",onClick:()=>m({agenda:[...u.agenda||[],{time:"",item:""}]}),children:[e.jsx(nn,{className:"h-3.5 w-3.5 mr-1"})," Add item"]})]}),e.jsxs("div",{className:"space-y-2",children:[(u.agenda||[]).map((_,b)=>e.jsxs("div",{className:"flex gap-2",children:[e.jsx(we,{className:"w-24",value:_.time||"",onChange:k=>{const A=[...u.agenda];A[b]={...A[b],time:k.target.value},m({agenda:A})},placeholder:"0:00"}),e.jsx(we,{value:_.item||"",onChange:k=>{const A=[...u.agenda];A[b]={...A[b],item:k.target.value},m({agenda:A})},placeholder:"What happens here"}),e.jsx(B,{size:"icon",variant:"ghost",onClick:()=>m({agenda:u.agenda.filter((k,A)=>A!==b)}),children:e.jsx(hr,{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(Wl,{}),e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsx(re,{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(nn,{className:"h-3.5 w-3.5 mr-1"})," Add outcome"]})]}),e.jsx("div",{className:"space-y-2",children:(u.learning_outcomes||[]).map((_,b)=>e.jsxs("div",{className:"flex gap-2",children:[e.jsx(we,{value:_,onChange:k=>{const A=[...u.learning_outcomes];A[b]=k.target.value,m({learning_outcomes:A})},placeholder:"One clear, honest outcome"}),e.jsx(B,{size:"icon",variant:"ghost",onClick:()=>m({learning_outcomes:u.learning_outcomes.filter((k,A)=>A!==b)}),children:e.jsx(hr,{className:"h-4 w-4"})})]},b))})]})]})]}),e.jsxs(_e,{className:"p-6 rounded-2xl border-slate-200 bg-white",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-widest text-slate-500 font-semibold mb-1",children:"Step 3"}),e.jsx("div",{className:"text-lg font-semibold text-slate-900 mb-4",children:"Registration page"}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsx(re,{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(nn,{className:"h-3.5 w-3.5 mr-1"})," Add question"]})]}),e.jsx("div",{className:"space-y-2",children:(u.registration_questions||[]).map((_,b)=>e.jsxs("div",{className:"flex gap-2 items-center",children:[e.jsx(we,{className:"flex-1",value:_.label,onChange:k=>{const A=[...u.registration_questions];A[b]={...A[b],label:k.target.value,key:_.key||`q${b+1}`},m({registration_questions:A})},placeholder:"Question shown to registrants"}),e.jsxs(Ns,{value:_.type,onValueChange:k=>{const A=[...u.registration_questions];A[b]={...A[b],type:k},m({registration_questions:A})},children:[e.jsx(ws,{className:"w-32",children:e.jsx(ks,{})}),e.jsxs(js,{children:[e.jsx(nt,{value:"text",children:"Short text"}),e.jsx(nt,{value:"long",children:"Long text"})]})]}),e.jsx(B,{size:"icon",variant:"ghost",onClick:()=>m({registration_questions:u.registration_questions.filter((k,A)=>A!==b)}),children:e.jsx(hr,{className:"h-4 w-4"})})]},b))})]}),e.jsxs("div",{children:[e.jsx(re,{children:"Confirmation message (shown after registration)"}),e.jsx(Ws,{rows:3,value:u.confirmation_message||"",onChange:_=>m({confirmation_message:_.target.value}),placeholder:"You are in — come with one honest question."})]})]})]}),e.jsxs(_e,{className:"p-6 rounded-2xl border-slate-200 bg-white",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-widest text-slate-500 font-semibold mb-1",children:"Step 4"}),e.jsx("div",{className:"text-lg font-semibold text-slate-900 mb-4",children:"Resource Kit & 48-hour follow-up"}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx(re,{children:"Attach a Resource Kit"}),e.jsxs(Ns,{value:u.resource_kit_id||"none",onValueChange:_=>m({resource_kit_id:_==="none"?null:_}),children:[e.jsx(ws,{children:e.jsx(ks,{placeholder:"None"})}),e.jsxs(js,{children:[e.jsx(nt,{value:"none",children:"None"}),(o||[]).map(_=>e.jsx(nt,{value:_.id,children:_.title},_.id))]})]})]}),e.jsxs("div",{children:[e.jsx(re,{children:"Deliver kit"}),e.jsxs(Ns,{value:u.kit_delivery_trigger||"after_attendance",onValueChange:_=>m({kit_delivery_trigger:_}),children:[e.jsx(ws,{children:e.jsx(ks,{})}),e.jsxs(js,{children:[e.jsx(nt,{value:"on_registration",children:"On registration"}),e.jsx(nt,{value:"on_confirmation",children:"On confirmation"}),e.jsx(nt,{value:"on_check_in",children:"At check-in"}),e.jsx(nt,{value:"after_attendance",children:"After attendance"}),e.jsx(nt,{value:"manual",children:"Only manually"})]})]})]}),e.jsxs("div",{children:[e.jsx(re,{children:"Default follow-up window (hours)"}),e.jsx(we,{type:"number",value:u.followup_hours??48,onChange:_=>m({followup_hours:Number(_.target.value)})})]})]}),!u.resource_kit_id&&e.jsx("div",{className:"text-[12px] text-amber-700 bg-amber-50 border border-amber-200 rounded-lg p-3 mt-4",children:"Tip: attach a Resource Kit so attendees leave with something valuable — and so follow-ups have a natural reason."})]}),e.jsxs(_e,{className:"p-6 rounded-2xl border-slate-200 bg-white",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-widest text-slate-500 font-semibold mb-1",children:"Step 5"}),e.jsx("div",{className:"text-lg font-semibold text-slate-900 mb-3",children:"Review & publish"}),e.jsxs("div",{className:"text-[13px] text-slate-600 leading-relaxed",children:["Publishing generates a premium public registration page at"," ",e.jsxs("code",{className:"bg-slate-100 px-1.5 py-0.5 rounded text-slate-800",children:["/attract-event/",(i==null?void 0:i.public_slug)||""]})," ","and enables the personal invitation flow. You can unpublish or cancel at any time."]}),e.jsxs("div",{className:"flex flex-wrap gap-2 mt-4",children:[(!u.title||!u.starts_at)&&e.jsx(We,{variant:"secondary",className:"bg-rose-50 text-rose-700 border-rose-200",children:"Add title and start time"}),(u.agenda||[]).length===0&&e.jsx(We,{variant:"secondary",className:"bg-amber-50 text-amber-700 border-amber-200",children:"No agenda yet"}),(u.learning_outcomes||[]).length===0&&e.jsx(We,{variant:"secondary",className:"bg-amber-50 text-amber-700 border-amber-200",children:"No stated outcomes"}),!u.resource_kit_id&&e.jsx(We,{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(Kl,{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(By,{className:"h-4 w-4 mr-2"})," Publish"]})]})]})]})}const Jje=s=>s?[s.first_name,s.last_name].filter(Boolean).join(" "):"";function LPn(){const{eventId:s}=uo(),t=tr(),{data:n}=OKe(s),{data:r=[]}=DBt(s),{data:a=[]}=KLn(s),{data:i=[]}=YLn(s),{agents:l}=jb(),{data:o=[]}=RBt(),c=zBt(),d=XLn(),u=QLn(),h=FBt(),m=N.useMemo(()=>{const y=r.length,x=r.filter(L=>L.status==="registered"||L.status==="confirmed").length,_=r.filter(L=>L.status==="attended").length,b=r.filter(L=>L.status==="no_show").length,k=r.filter(L=>L.status==="waitlisted").length,A=x+_+b,T=A>0?Math.round(_/A*100):0,P=a.length>0?Math.round(a.filter(L=>L.viewed_at).length/a.length*100):0,I=r.filter(L=>L.followup_status==="done").length,M=_>0?Math.round(I/_*100):0;return{total:y,registered:x,attended:_,noShow:b,waitlist:k,attendRate:T,invView:P,followed:I,followedRate:M}},[r,a]);if(!n)return e.jsx("div",{className:"p-8 text-slate-500",children:"Loading…"});const f=n.public_slug?IAe(n.public_slug):null,g=()=>{const y=new Blob([BBt(n)],{type:"text/calendar"}),x=URL.createObjectURL(y),_=document.createElement("a");_.href=x,_.download=`${n.public_slug||"event"}.ics`,_.click(),URL.revokeObjectURL(x)};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/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:g,children:[e.jsx(oi,{className:"h-3.5 w-3.5 mr-2"})," ICS"]}),f&&e.jsxs(B,{variant:"outline",size:"sm",className:"rounded-full",onClick:()=>{navigator.clipboard.writeText(f),ie.success("Link copied")},children:[e.jsx(Pa,{className:"h-3.5 w-3.5 mr-2"})," Copy link"]}),f&&e.jsx(B,{variant:"outline",size:"sm",className:"rounded-full",asChild:!0,children:e.jsxs("a",{href:f,target:"_blank",rel:"noreferrer",children:[e.jsx(Tr,{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(M_,{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(_e,{className:"p-6 rounded-2xl border-slate-200 bg-gradient-to-br from-slate-900 to-slate-800 text-white",children:e.jsxs("div",{className:"flex items-start justify-between gap-4 flex-wrap",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[e.jsx(We,{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(We,{variant:"secondary",className:"bg-white/10 border-white/10 text-white capitalize",children:n.related_pillar}),n.event_type_key&&e.jsx(We,{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(ta,{className:"h-4 w-4"})," ",Js(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(na,{className:"h-4 w-4"})," Virtual"]}):e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx(ii,{className:"h-4 w-4"})," ",n.location||"In person"]}),e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx(Yn,{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"}}),ie.success("Published")},children:"Publish now"}),n.status==="published"&&new Date(n.starts_at){await h.mutateAsync({id:n.id,patch:{status:"completed"}}),ie.success("Marked completed")},children:"Mark completed"})]})}),e.jsxs(ya,{defaultValue:"overview",children:[e.jsxs(va,{className:"rounded-full bg-white border border-slate-200 flex-wrap h-auto",children:[e.jsx(ls,{value:"overview",className:"rounded-full",children:"Overview"}),e.jsxs(ls,{value:"invitations",className:"rounded-full",children:["Invitations (",a.length,")"]}),e.jsxs(ls,{value:"registrations",className:"rounded-full",children:["Registrations (",r.length,")"]}),e.jsxs(ls,{value:"notes",className:"rounded-full",children:["Notes (",i.length,")"]}),e.jsx(ls,{value:"kit",className:"rounded-full",children:"Resource Kit"}),e.jsx(ls,{value:"followup",className:"rounded-full",children:"48-hour follow-up"}),e.jsx(ls,{value:"analytics",className:"rounded-full",children:"Analytics"})]}),e.jsxs(_s,{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(Lw,{icon:Yn,label:"Registered",value:m.registered+m.attended}),e.jsx(Lw,{icon:pa,label:"Attended",value:m.attended}),e.jsx(Lw,{icon:fl,label:"Attendance rate",value:`${m.attendRate}%`}),e.jsx(Lw,{icon:zm,label:"Follow-up completion",value:`${m.followedRate}%`})]}),e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-3 gap-6",children:[e.jsxs(_e,{className:"p-5 rounded-2xl border-slate-200 bg-white lg:col-span-2",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-widest text-slate-500 font-semibold mb-2",children:"Agenda"}),(n.agenda||[]).length===0?e.jsx("div",{className:"text-[13px] text-slate-400",children:"No agenda yet"}):e.jsx("ul",{className:"space-y-2",children:n.agenda.map((y,x)=>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})]},x))}),(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,x)=>e.jsxs("li",{className:"text-[13.5px] text-slate-700 flex gap-2",children:[e.jsx(pa,{className:"h-4 w-4 text-emerald-600 shrink-0 mt-0.5"})," ",y]},x))})]})]}),e.jsxs(_e,{className:"p-5 rounded-2xl border-slate-200 bg-white",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-widest text-slate-500 font-semibold mb-2",children:"Share"}),f?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:f}),e.jsxs(B,{size:"sm",variant:"outline",className:"rounded-full mt-2 w-full",onClick:()=>{navigator.clipboard.writeText(f),ie.success("Copied")},children:[e.jsx(Pa,{className:"h-3.5 w-3.5 mr-2"})," Copy link"]})]}):e.jsx("div",{className:"text-[13px] text-slate-500",children:"Publish the event to generate a shareable registration link."}),n.check_in_token&&e.jsxs("div",{className:"mt-4",children:[e.jsx("div",{className:"text-[12px] text-slate-500 mb-1",children:"Check-in mode"}),e.jsxs(B,{size:"sm",variant:"outline",className:"rounded-full w-full",onClick:()=>t(`/attract/events/${n.id}/checkin`),children:[e.jsx(M_,{className:"h-3.5 w-3.5 mr-2"})," Open check-in"]})]})]})]})]}),e.jsx(_s,{value:"invitations",className:"mt-5",children:e.jsx(PPn,{eventId:n.id,eventSlug:n.public_slug,agents:l,invitations:a,templates:o,onCreate:u.mutate})}),e.jsx(_s,{value:"registrations",className:"mt-5",children:e.jsx(IPn,{eventId:n.id,attendees:r,onUpsert:c.mutate,checkInToken:n.check_in_token})}),e.jsx(_s,{value:"notes",className:"mt-5",children:e.jsx(DPn,{eventId:n.id,attendees:r,notes:i,onCreate:d.mutate})}),e.jsx(_s,{value:"kit",className:"mt-5",children:e.jsxs(_e,{className:"p-6 rounded-2xl border-slate-200 bg-white",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-widest text-slate-500 font-semibold mb-1",children:"Resource Kit"}),n.resource_kit_id?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"text-[15px] font-semibold text-slate-900",children:"A Resource Kit is attached to this event."}),e.jsxs("div",{className:"text-[13px] text-slate-600 mt-1",children:["Deliver trigger: ",e.jsx("span",{className:"font-medium capitalize",children:(n.kit_delivery_trigger||"after_attendance").replace(/_/g," ")})]}),e.jsx(B,{variant:"outline",className:"rounded-full mt-4",onClick:()=>t(`/attract/provide/kits/${n.resource_kit_id}/analytics`),children:"Open kit analytics"})]}):e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"text-[15px] text-slate-700",children:"No kit attached yet. Attach one so attendees leave with something valuable."}),e.jsxs("div",{className:"flex gap-2 mt-4",children:[e.jsx(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/provide/kits/new"),children:"Create a new kit"})]})]})]})}),e.jsx(_s,{value:"followup",className:"mt-5",children:e.jsx(RPn,{eventId:n.id,attendees:r,onUpsert:c.mutate})}),e.jsxs(_s,{value:"analytics",className:"mt-5",children:[e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4",children:[e.jsx(Lw,{icon:Rr,label:"Invitations sent",value:a.length}),e.jsx(Lw,{icon:Tr,label:"Invitation view rate",value:`${m.invView}%`}),e.jsx(Lw,{icon:Yn,label:"Registered",value:m.registered+m.attended}),e.jsx(Lw,{icon:pa,label:"Attended",value:m.attended}),e.jsx(Lw,{icon:fl,label:"Attendance rate",value:`${m.attendRate}%`}),e.jsx(Lw,{icon:zm,label:"Follow-up complete (48h)",value:`${m.followedRate}%`}),e.jsx(Lw,{icon:f5,label:"Notes captured",value:i.length}),e.jsx(Lw,{icon:Yl,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 Lw({icon:s,label:t,value:n}){return e.jsxs(_e,{className:"p-4 rounded-2xl border-slate-200 bg-white",children:[e.jsxs("div",{className:"flex items-center gap-2 text-slate-500 text-[12px]",children:[e.jsx(s,{className:"h-3.5 w-3.5"})," ",t]}),e.jsx("div",{className:"text-[24px] font-semibold tabular-nums text-slate-900 mt-2",children:n})]})}function PPn({eventId:s,eventSlug:t,agents:n,invitations:r,templates:a,onCreate:i}){const[l,o]=N.useState(""),[c,d]=N.useState(""),[u,h]=N.useState(""),[m,f]=N.useState("email"),[g,y]=N.useState(""),x=a==null?void 0:a[0],_=()=>{if(!x)return;const k=m==="sms"?x.suggested_invitation_sms:m==="dm"?x.suggested_invitation_dm:x.suggested_invitation_email,A=t?`${window.location.origin}/attract-event/${t}`:"";y((k||"").replaceAll("{{first_name}}",(c||"friend").split(" ")[0]).replaceAll("{{link}}",A).replaceAll("{{date}}",""))},b=()=>{if(!c||m==="email"&&!u){ie.error("Add a name and email");return}const k=n.find(A=>A.id===l);i({event_id:s,agent_id:l||null,recipient_name:c||Jje(k),recipient_email:u||(k==null?void 0:k.email),channel:m,message_body:g,status:"sent"}),d(""),h(""),y(""),o(""),ie.success("Invitation logged")};return e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-3 gap-6",children:[e.jsxs(_e,{className:"p-5 rounded-2xl border-slate-200 bg-white lg:col-span-2",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-widest text-slate-500 font-semibold mb-3",children:"Log a personal invitation"}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(re,{children:"Attract agent (optional)"}),e.jsxs(Ns,{value:l||"none",onValueChange:k=>{o(k==="none"?"":k);const A=n.find(T=>T.id===k);A&&(d(Jje(A)),h(A.email||""))},children:[e.jsx(ws,{children:e.jsx(ks,{placeholder:"Pick an agent"})}),e.jsxs(js,{children:[e.jsx(nt,{value:"none",children:"Guest (not in pipeline)"}),n.map(k=>e.jsx(nt,{value:k.id,children:Jje(k)},k.id))]})]})]}),e.jsxs("div",{children:[e.jsx(re,{children:"Channel"}),e.jsxs(Ns,{value:m,onValueChange:f,children:[e.jsx(ws,{children:e.jsx(ks,{})}),e.jsxs(js,{children:[e.jsx(nt,{value:"email",children:"Email"}),e.jsx(nt,{value:"sms",children:"Text message"}),e.jsx(nt,{value:"dm",children:"DM"}),e.jsx(nt,{value:"call",children:"Phone call"}),e.jsx(nt,{value:"in_person",children:"In person"})]})]})]}),e.jsxs("div",{children:[e.jsx(re,{children:"Recipient name"}),e.jsx(we,{value:c,onChange:k=>d(k.target.value)})]}),e.jsxs("div",{children:[e.jsx(re,{children:"Recipient email"}),e.jsx(we,{value:u,onChange:k=>h(k.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(re,{children:"Message"}),x&&e.jsxs(B,{size:"sm",variant:"ghost",className:"rounded-full text-xs",onClick:_,children:[e.jsx(Cn,{className:"h-3 w-3 mr-1"})," Draft from template"]})]}),e.jsx(Ws,{rows:5,value:g,onChange:k=>y(k.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:()=>{g&&(navigator.clipboard.writeText(g),ie.success("Copied"))},children:[e.jsx(Pa,{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(Rr,{className:"h-3.5 w-3.5 mr-2"})," Log invitation"]})]})]})]}),e.jsxs(_e,{className:"p-5 rounded-2xl border-slate-200 bg-white",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-widest text-slate-500 font-semibold mb-3",children:"Recent invitations"}),r.length===0?e.jsx("div",{className:"text-[13px] text-slate-400",children:"None yet."}):e.jsx("div",{className:"space-y-2 max-h-[520px] overflow-auto",children:r.map(k=>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:k.recipient_name||k.recipient_email}),e.jsx(We,{variant:"secondary",className:"capitalize",children:k.status})]}),e.jsxs("div",{className:"text-[11.5px] text-slate-500 mt-0.5",children:["via ",k.channel," · ",nc(new Date(k.sent_at))," ago",k.view_count>0?` · viewed ${k.view_count}×`:""]})]},k.id))})]})]})}function IPn({eventId:s,attendees:t,onUpsert:n,checkInToken:r}){const[a,i]=N.useState(""),[l,o]=N.useState(""),c=()=>{if(!a){ie.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(""),ie.success("Walk-in added")};return e.jsxs("div",{className:"space-y-5",children:[e.jsxs(_e,{className:"p-4 rounded-2xl border-slate-200 bg-white",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-widest text-slate-500 font-semibold mb-2",children:"Add a walk-in guest"}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-4 gap-2",children:[e.jsx(we,{placeholder:"Name",value:a,onChange:d=>i(d.target.value)}),e.jsx(we,{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(Yl,{className:"h-4 w-4 mr-2"})," Add & check in"]})]})]}),e.jsx(_e,{className:"rounded-2xl border-slate-200 bg-white overflow-hidden",children:t.length===0?e.jsx("div",{className:"p-8 text-center text-slate-400",children:"No registrations yet"}):e.jsx("div",{className:"divide-y divide-slate-100",children:t.map(d=>e.jsxs("div",{className:"p-4 flex items-center justify-between gap-3 flex-wrap",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"text-[14px] font-semibold text-slate-900",children:d.guest_name||Jje(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(We,{variant:"secondary",className:"capitalize",children:d.status}),e.jsxs(Ns,{value:d.status,onValueChange:u=>n({id:d.id,event_id:s,status:u,checked_in_at:u==="attended"&&!d.checked_in_at?new Date().toISOString():d.checked_in_at}),children:[e.jsx(ws,{className:"h-8 w-40 text-xs",children:e.jsx(ks,{})}),e.jsx(js,{children:["invited","registered","confirmed","waitlisted","attended","no_show","cancelled"].map(u=>e.jsx(nt,{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(ePn(r,d.personalized_token)),ie.success("Check-in link copied")},children:e.jsx(Pa,{className:"h-3.5 w-3.5"})})]})]},d.id))})})]})}function DPn({eventId:s,attendees:t,notes:n,onCreate:r}){const[a,i]=N.useState(""),[l,o]=N.useState(""),[c,d]=N.useState("warm"),[u,h]=N.useState(!1),[m,f]=N.useState(""),g=()=>{if(!l.trim()){ie.error("Add a note");return}const y=t.find(x=>x.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(""),f(""),h(!1),ie.success("Note captured")};return e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-3 gap-6",children:[e.jsxs(_e,{className:"p-5 rounded-2xl border-slate-200 bg-white lg:col-span-2",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-widest text-slate-500 font-semibold mb-3",children:"Capture one honest note"}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{children:[e.jsx(re,{children:"Attendee (optional)"}),e.jsxs(Ns,{value:a||"none",onValueChange:y=>i(y==="none"?"":y),children:[e.jsx(ws,{children:e.jsx(ks,{placeholder:"Anyone in the room"})}),e.jsxs(js,{children:[e.jsx(nt,{value:"none",children:"General note"}),t.map(y=>e.jsx(nt,{value:y.id,children:y.guest_name||y.guest_email},y.id))]})]})]}),e.jsxs("div",{children:[e.jsx(re,{children:"Note"}),e.jsx(Ws,{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(re,{children:"Relationship temperature"}),e.jsxs(Ns,{value:c,onValueChange:d,children:[e.jsx(ws,{children:e.jsx(ks,{})}),e.jsx(js,{children:["cold","warm","hot"].map(y=>e.jsx(nt,{value:y,children:y},y))})]})]}),e.jsxs("div",{className:"md:col-span-2",children:[e.jsx(re,{children:"Recommended next action"}),e.jsx(we,{value:m,onChange:y=>f(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:g,children:[e.jsx(nn,{className:"h-4 w-4 mr-2"})," Save note"]})})]}),e.jsxs(_e,{className:"p-5 rounded-2xl border-slate-200 bg-white",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-widest text-slate-500 font-semibold mb-3",children:"Notes from this event"}),n.length===0?e.jsx("div",{className:"text-[13px] text-slate-400",children:"None yet."}):e.jsx("div",{className:"space-y-3 max-h-[520px] overflow-auto",children:n.map(y=>{const x=t.find(_=>_.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:(x==null?void 0:x.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(We,{variant:"secondary",className:"capitalize",children:y.temperature}),y.wants_one_on_one&&e.jsx(We,{className:"bg-emerald-500",children:"Wants 1:1"}),y.recommended_next_action&&e.jsxs("span",{children:["Next: ",y.recommended_next_action]})]})]},y.id)})})]})]})}function RPn({eventId:s,attendees:t,onUpsert:n}){const r=N.useMemo(()=>({attended_engaged:t.filter(l=>l.status==="attended"&&l.temperature==="hot"),attended_no_notes:t.filter(l=>l.status==="attended"),no_show:t.filter(l=>l.status==="no_show"),meeting_requested:t.filter(l=>l.meeting_requested),not_followed:t.filter(l=>l.status==="attended"&&l.followup_status!=="done")}),[t]),a=(l,o)=>n({id:l,event_id:s,followup_status:o}),i=({title:l,list:o,color:c})=>e.jsxs(_e,{className:"p-5 rounded-2xl border-slate-200 bg-white",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-3",children:[e.jsx("div",{className:`h-2 w-2 rounded-full ${c}`}),e.jsx("div",{className:"text-[13px] font-semibold text-slate-900",children:l}),e.jsxs("div",{className:"text-[12px] text-slate-500",children:["(",o.length,")"]})]}),o.length===0?e.jsx("div",{className:"text-[12px] text-slate-400",children:"Nobody here."}):e.jsx("div",{className:"space-y-2",children:o.map(d=>e.jsxs("div",{className:"flex items-center justify-between gap-2 rounded-xl border border-slate-100 p-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[13px] font-semibold text-slate-900",children:d.guest_name||d.guest_email}),e.jsxs("div",{className:"text-[11.5px] text-slate-500",children:[d.status," · followup: ",d.followup_status||"pending"]})]}),e.jsxs("div",{className:"flex gap-1",children:[e.jsx(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(pa,{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 FJ={},OPn=function(){return typeof Promise=="function"&&Promise.prototype&&Promise.prototype.then},KBt={},Q_={};let zKe;const FPn=[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];Q_.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};Q_.getSymbolTotalCodewords=function(t){return FPn[t]};Q_.getBCHDigit=function(s){let t=0;for(;s!==0;)t++,s>>>=1;return t};Q_.setToSJISFunction=function(t){if(typeof t!="function")throw new Error('"toSJISFunc" is not a valid function.');zKe=t};Q_.isKanjiModeEnabled=function(){return typeof zKe<"u"};Q_.toSJIS=function(t){return zKe(t)};var DAe={};(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}}})(DAe);function YBt(){this.buffer=[],this.length=0}YBt.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 zPn=YBt;function zJ(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)}zJ.prototype.set=function(s,t,n,r){const a=s*this.size+t;this.data[a]=n,r&&(this.reservedBit[a]=!0)};zJ.prototype.get=function(s,t){return this.data[s*this.size+t]};zJ.prototype.xor=function(s,t,n){this.data[s*this.size+t]^=n};zJ.prototype.isReserved=function(s,t){return this.reservedBit[s*this.size+t]};var BPn=zJ,ZBt={};(function(s){const t=Q_.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=f,o=1),f=a.get(m,h),f===u?c++:(c>=5&&(l+=t.N1+(c-5)),u=f,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 UPn=BKe,t$t={},r6={},$Ke={};$Ke.isValid=function(t){return!isNaN(t)&&t>=1&&t<=40};var rS={};const s$t="[0-9]+",qPn="[A-Z $%*+\\-./:]+";let UZ="(?:[u3000-u303F]|[u3040-u309F]|[u30A0-u30FF]|[uFF00-uFFEF]|[u4E00-u9FAF]|[u2605-u2606]|[u2190-u2195]|u203B|[u2010u2015u2018u2019u2025u2026u201Cu201Du2225u2260]|[u0391-u0451]|[u00A7u00A8u00B1u00B4u00D7u00F7])+";UZ=UZ.replace(/u/g,"\\u");const VPn="(?:(?![A-Z0-9 $%*+\\-./:]|"+UZ+`)(?:.|[\r ]))+`;rS.KANJI=new RegExp(UZ,"g");rS.BYTE_KANJI=new RegExp("[^A-Z0-9 $%*+\\-./:]+","g");rS.BYTE=new RegExp(VPn,"g");rS.NUMERIC=new RegExp(s$t,"g");rS.ALPHANUMERIC=new RegExp(qPn,"g");const HPn=new RegExp("^"+UZ+"$"),GPn=new RegExp("^"+s$t+"$"),WPn=new RegExp("^[A-Z0-9 $%*+\\-./:]+$");rS.testKanji=function(t){return HPn.test(t)};rS.testNumeric=function(t){return GPn.test(t)};rS.testAlphanumeric=function(t){return WPn.test(t)};(function(s){const t=$Ke,n=rS;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}}})(r6);(function(s){const t=Q_,n=RAe,r=DAe,a=r6,i=$Ke,l=7973,o=t.getBCHDigit(l);function c(m,f,g){for(let y=1;y<=40;y++)if(f<=s.getCapacity(y,g,m))return y}function d(m,f){return a.getCharCountIndicator(m,f)+4}function u(m,f){let g=0;return m.forEach(function(y){const x=d(y.mode,f);g+=x+y.getBitsLength()}),g}function h(m,f){for(let g=1;g<=40;g++)if(u(m,g)<=s.getCapacity(g,f,a.MIXED))return g}s.from=function(f,g){return i.isValid(f)?parseInt(f,10):g},s.getCapacity=function(f,g,y){if(!i.isValid(f))throw new Error("Invalid QR Code version");typeof y>"u"&&(y=a.BYTE);const x=t.getSymbolTotalCodewords(f),_=n.getTotalCodewordsCount(f,g),b=(x-_)*8;if(y===a.MIXED)return b;const k=b-d(y,f);switch(y){case a.NUMERIC:return Math.floor(k/10*3);case a.ALPHANUMERIC:return Math.floor(k/11*2);case a.KANJI:return Math.floor(k/13);case a.BYTE:default:return Math.floor(k/8)}},s.getBestVersionForData=function(f,g){let y;const x=r.from(g,r.M);if(Array.isArray(f)){if(f.length>1)return h(f,x);if(f.length===0)return 1;y=f[0]}else y=f;return c(y.mode,y.getLength(),x)},s.getEncodedBits=function(f){if(!i.isValid(f)||f<7)throw new Error("Invalid QR Code version");let g=f<<12;for(;t.getBCHDigit(g)-o>=0;)g^=l<=0;)a^=r$t<0&&(r=this.data.substr(n),a=parseInt(r,10),t.put(a,i*3+1))};var ZPn=$$;const XPn=r6,PIe=["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 U$(s){this.mode=XPn.ALPHANUMERIC,this.data=s}U$.getBitsLength=function(t){return 11*Math.floor(t/2)+6*(t%2)};U$.prototype.getLength=function(){return this.data.length};U$.prototype.getBitsLength=function(){return U$.getBitsLength(this.data.length)};U$.prototype.write=function(t){let n;for(n=0;n+2<=this.data.length;n+=2){let r=PIe.indexOf(this.data[n])*45;r+=PIe.indexOf(this.data[n+1]),t.put(r,11)}this.data.length%2&&t.put(PIe.indexOf(this.data[n]),6)};var QPn=U$;const JPn=r6;function q$(s){this.mode=JPn.BYTE,typeof s=="string"?this.data=new TextEncoder().encode(s):this.data=new Uint8Array(s)}q$.getBitsLength=function(t){return t*8};q$.prototype.getLength=function(){return this.data.length};q$.prototype.getBitsLength=function(){return q$.getBitsLength(this.data.length)};q$.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 nIn=V$,i$t={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,f,g,y,x;!o.empty();){c=o.pop(),d=c.value,h=c.cost,m=n[d]||{};for(u in m)m.hasOwnProperty(u)&&(f=m[u],g=h+f,y=l[u],x=typeof l[u]>"u",(x||y>g)&&(l[u]=g,o.push(u,g),i[u]=d))}if(typeof a<"u"&&typeof l[a]>"u"){var _=["Could not find a path from ",r," to ",a,"."].join("");throw new Error(_)}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})(i$t);var rIn=i$t.exports;(function(s){const t=r6,n=ZPn,r=QPn,a=eIn,i=nIn,l=rS,o=Q_,c=rIn;function d(_){return unescape(encodeURIComponent(_)).length}function u(_,b,k){const A=[];let T;for(;(T=_.exec(k))!==null;)A.push({data:T[0],index:T.index,mode:b,length:T[0].length});return A}function h(_){const b=u(l.NUMERIC,t.NUMERIC,_),k=u(l.ALPHANUMERIC,t.ALPHANUMERIC,_);let A,T;return o.isKanjiModeEnabled()?(A=u(l.BYTE,t.BYTE,_),T=u(l.KANJI,t.KANJI,_)):(A=u(l.BYTE_KANJI,t.BYTE,_),T=[]),b.concat(k,A,T).sort(function(I,M){return I.index-M.index}).map(function(I){return{data:I.data,mode:I.mode,length:I.length}})}function m(_,b){switch(b){case t.NUMERIC:return n.getBitsLength(_);case t.ALPHANUMERIC:return r.getBitsLength(_);case t.KANJI:return i.getBitsLength(_);case t.BYTE:return a.getBitsLength(_)}}function f(_){return _.reduce(function(b,k){const A=b.length-1>=0?b[b.length-1]:null;return A&&A.mode===k.mode?(b[b.length-1].data+=k.data,b):(b.push(k),b)},[])}function g(_){const b=[];for(let k=0;k<_.length;k++){const A=_[k];switch(A.mode){case t.NUMERIC:b.push([A,{data:A.data,mode:t.ALPHANUMERIC,length:A.length},{data:A.data,mode:t.BYTE,length:A.length}]);break;case t.ALPHANUMERIC:b.push([A,{data:A.data,mode:t.BYTE,length:A.length}]);break;case t.KANJI:b.push([A,{data:A.data,mode:t.BYTE,length:d(A.data)}]);break;case t.BYTE:b.push([{data:A.data,mode:t.BYTE,length:d(A.data)}])}}return b}function y(_,b){const k={},A={start:{}};let T=["start"];for(let P=0;P<_.length;P++){const I=_[P],M=[];for(let L=0;L=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 mIn(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 RIe(s,t,n){const r=s.size,a=dIn.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 gIn(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 xIn(s,t,n){const r=new aIn;n.forEach(function(c){r.put(c.mode.bit,4),r.put(c.getLength(),uIn.getCharCountIndicator(c.mode,s)),c.write(r)});const a=FAe.getSymbolTotalCodewords(s),i=Yze.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&&fIn(c,t),gIn(c,l),isNaN(r)&&(r=Kze.getBestMask(c,RIe.bind(null,c,n))),Kze.applyMask(r,c),RIe(c,n,r),{modules:c,version:t,errorCorrectionLevel:n,maskPattern:r,segments:a}}KBt.create=function(t,n){if(typeof t>"u"||t==="")throw new Error("No input text");let r=IIe.M,a,i;return typeof n<"u"&&(r=IIe.from(n.errorCorrectionLevel,IIe.M),a=sSe.from(n.version),i=Kze.from(n.maskPattern),n.toSJISFunc&&FAe.setToSJISFunction(n.toSJISFunc)),vIn(t,a,r,i)};var o$t={},UKe={};(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&&f>=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)}})(o$t);var l$t={};const bIn=UKe;function d0t(s,t){const n=s.a/255,r=t+'="'+s.hex+'"';return n<1?r+" "+t+'-opacity="'+n.toFixed(2).slice(1)+'"':r}function OIe(s,t,n){let r=s+t;return typeof n<"u"&&(r+=" "+n),r}function _In(s,t,n){let r="",a=0,i=!1,l=0;for(let o=0;o0&&c>0&&s[o-1]||(r+=i?OIe("M",c+n,.5+d+n):OIe("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 wIn=OPn,Zze=KBt,c$t=o$t,jIn=l$t;function qKe(s,t,n,r,a){const i=[].slice.call(arguments,1),l=i.length,o=typeof i[l-1]=="function";if(!o&&!wIn())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=Zze.create(n,r);c(s(u,t,r))}catch(u){d(u)}})}try{const c=Zze.create(n,r);a(null,s(c,t,r))}catch(c){a(c)}}FJ.create=Zze.create;FJ.toCanvas=qKe.bind(null,c$t.render);FJ.toDataURL=qKe.bind(null,c$t.renderToDataURL);FJ.toString=qKe.bind(null,function(s,t,n){return jIn.render(s,n)});function NIn(){const{eventId:s}=uo(),t=tr(),{data:n}=OKe(s),{data:r=[]}=DBt(s),a=zBt(),[i,l]=N.useState(""),[o,c]=N.useState(""),[d,u]=N.useState(""),[h,m]=N.useState(""),f=n!=null&&n.public_slug?IAe(n.public_slug):"";N.useEffect(()=>{f&&FJ.toDataURL(f,{width:320,margin:1}).then(m).catch(()=>{})},[f]);const g=N.useMemo(()=>i?r.filter(_=>(_.guest_name||"").toLowerCase().includes(i.toLowerCase())||(_.guest_email||"").toLowerCase().includes(i.toLowerCase())):r,[r,i]),y=_=>{a.mutate({id:_.id,event_id:s,status:"attended",checked_in_at:new Date().toISOString()}),ie.success(`${_.guest_name||"Guest"} checked in`)},x=()=>{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(""),ie.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(_e,{className:"p-5 rounded-2xl bg-gradient-to-br from-slate-900 to-slate-800 text-white border-0",children:[e.jsx("div",{className:"text-[10.5px] uppercase tracking-widest text-white/60",children:"Check-in mode"}),e.jsx("div",{className:"text-xl font-semibold mt-1",children:n.title}),e.jsxs("div",{className:"text-white/70 text-[13px] mt-0.5",children:[n.registration_count," registered · ",n.attendance_count," checked in"]})]}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4 mt-4",children:[e.jsxs(_e,{className:"p-5 rounded-2xl border-slate-200 bg-white",children:[e.jsxs("div",{className:"flex items-center gap-2 text-[13px] font-semibold text-slate-900",children:[e.jsx(M_,{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."}),f&&e.jsx("div",{className:"text-[11px] font-mono text-center text-slate-500 mt-2 break-all",children:f})]}),e.jsxs(_e,{className:"p-5 rounded-2xl border-slate-200 bg-white",children:[e.jsx("div",{className:"text-[13px] font-semibold text-slate-900 mb-3",children:"Add walk-in"}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(we,{placeholder:"Name",value:o,onChange:_=>c(_.target.value)}),e.jsx(we,{placeholder:"Email (optional)",value:d,onChange:_=>u(_.target.value)}),e.jsxs(B,{className:"w-full rounded-full",onClick:x,children:[e.jsx(Yl,{className:"h-4 w-4 mr-2"})," Add & check in"]})]})]})]}),e.jsxs(_e,{className:"mt-4 rounded-2xl border-slate-200 bg-white overflow-hidden",children:[e.jsxs("div",{className:"p-3 border-b border-slate-100 relative",children:[e.jsx(Gr,{className:"absolute left-6 top-1/2 -translate-y-1/2 h-4 w-4 text-slate-400"}),e.jsx(we,{placeholder:"Search attendees",value:i,onChange:_=>l(_.target.value),className:"pl-9 rounded-full border-slate-200"})]}),g.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:g.map(_=>{const b=_.status==="attended";return e.jsxs("div",{className:"p-4 flex items-center justify-between gap-3",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"text-[15px] font-semibold text-slate-900 truncate",children:_.guest_name||_.guest_email}),e.jsx("div",{className:"text-[12px] text-slate-500 truncate",children:_.guest_email})]}),b?e.jsxs(We,{className:"bg-emerald-500",children:[e.jsx(pa,{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(_),children:[e.jsx(pa,{className:"h-5 w-5 mr-2"})," Check in"]})]},_.id)})})]})]})}):e.jsx("div",{className:"p-8 text-slate-500",children:"Loading…"})}const kIn=["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"],SIn=["Lead generation","Database marketing","Listing marketing","Social media/video","Open houses","Negotiation","Systems and technology","Team building","Leadership","New construction","Luxury","Business planning"],u0t=[{key:"produce",icon:gl,title:"Produce",blurb:"Attract through visible production and excellence.",example:"Publish weekly market updates, share every closing story with the lesson attached."},{key:"influence",icon:Cn,title:"Influence",blurb:"Teach publicly and earn a following of agents.",example:"Host a monthly masterclass. Post 3 authority pieces a week."},{key:"provide",icon:mD,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:W2,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:c3,title:"Balanced Plan",blurb:"A little of all four. Best for veteran attractors.",example:"Rotate weekly focus between production, teaching, providing, and connecting."}],CIn=[{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"}],h0t=["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 m0t(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 AIn(){const s=tr(),{settings:t,save:n}=RJ(),[r,a]=N.useState(0),[i,l]=N.useState([]),[o,c]=N.useState([]),[d,u]=N.useState(null),[h,m]=N.useState({}),[f,g]=N.useState("");N.useEffect(()=>{var k,A;t&&((k=t.audiences)!=null&&k.length&&l(t.audiences),(A=t.teachables)!=null&&A.length&&c(t.teachables),t.attraction_style&&u(t.attraction_style),t.activity_baseline&&m(t.activity_baseline),t.ninety_day_outcome&&g(t.ninety_day_outcome))},[t==null?void 0:t.user_id]);const y=["Welcome","Audience","Teach","Style","Baseline","Outcome","Plan"],x=N.useMemo(()=>r===1?i.length>0:r===2?o.length>0:r===3?!!d:r===5?!!f:!0,[r,i,o,d,f]),_=(k,A,T)=>{T(k.includes(A)?k.filter(P=>P!==A):[...k,A])},b=async()=>{if(!d)return;const k=m0t({style:d,baseline:h,outcome:f});await n.mutateAsync({audiences:i,teachables:o,attraction_style:d,activity_baseline:h,ninety_day_outcome:f,ninety_day_plan:k,primary_pillar:d,onboarding_completed_at:new Date().toISOString()}),ie.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((k,A)=>e.jsx("div",{className:Ot("h-1.5 flex-1 rounded-full transition-colors",A<=r?"bg-violet-600":"bg-slate-200")},k))}),e.jsx($4e,{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:u0t.filter(k=>k.key!=="balanced").map(k=>e.jsxs(_e,{className:"p-4 rounded-2xl border-slate-200",children:[e.jsx(k.icon,{className:"h-5 w-5 text-violet-600 mb-2"}),e.jsx("div",{className:"text-[13px] font-semibold text-slate-900",children:k.title}),e.jsx("div",{className:"text-[11.5px] text-slate-500 mt-0.5",children:k.blurb})]},k.key))})]}),r===1&&e.jsx(SH,{icon:Yn,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:kIn.map(k=>e.jsx(FIe,{label:k,active:i.includes(k),onClick:()=>_(i,k,l)},k))})}),r===2&&e.jsx(SH,{icon:Oh,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:SIn.map(k=>e.jsx(FIe,{label:k,active:o.includes(k),onClick:()=>_(o,k,c)},k))})}),r===3&&e.jsx(SH,{icon:c3,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:u0t.map(k=>e.jsx(_e,{onClick:()=>u(k.key),className:Ot("p-5 rounded-2xl cursor-pointer transition-all border-2",d===k.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(k.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:k.title}),e.jsx("div",{className:"text-[12.5px] text-slate-600 mt-0.5",children:k.blurb}),e.jsxs("div",{className:"text-[11.5px] text-slate-500 italic mt-2",children:["Example: ",k.example]})]}),d===k.key&&e.jsx(pa,{className:"h-5 w-5 text-violet-600"})]})},k.key))})}),r===4&&e.jsx(SH,{icon:gg,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:CIn.map(k=>e.jsxs("div",{children:[e.jsx(re,{className:"text-[12.5px] text-slate-700",children:k.label}),e.jsx(we,{type:"number",min:0,value:h[k.key]??"",onChange:A=>m({...h,[k.key]:Number(A.target.value)||0})})]},k.key))})}),r===5&&e.jsx(SH,{icon:iu,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:[h0t.map(k=>e.jsx(FIe,{label:k,active:f===k,onClick:()=>g(k),full:!0},k)),e.jsxs("div",{className:"mt-3",children:[e.jsx(re,{className:"text-[12.5px] text-slate-700",children:"Or write your own"}),e.jsx(Ws,{rows:2,placeholder:"A specific outcome you can measure in 90 days...",value:h0t.includes(f)?"":f,onChange:k=>g(k.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(d$t,{plan:m0t({style:d,baseline:h,outcome:f})})]})]},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:!x,onClick:()=>a(r+1),children:["Continue ",e.jsx(vi,{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(By,{className:"h-4 w-4 mr-1.5"})," Activate my 90-day plan"]})]})]})}function SH({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 FIe({label:s,active:t,onClick:n,full:r}){return e.jsx("button",{type:"button",onClick:n,className:Ot("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(pa,{className:"h-4 w-4 text-violet-600"})," ",s]})})}function d$t({plan:s}){return e.jsxs("div",{className:"mt-6 space-y-6",children:[e.jsxs(_e,{className:"p-6 rounded-2xl bg-gradient-to-br from-violet-600 to-indigo-700 text-white border-0",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.18em] opacity-80",children:"Primary focus"}),e.jsx("div",{className:"text-3xl font-semibold mt-1 capitalize",children:s.primary_pillar}),e.jsx("div",{className:"text-white/85 mt-2",children:s.content_rhythm}),e.jsxs("div",{className:"text-[13px] mt-4 rounded-xl bg-white/10 p-3",children:[e.jsx("span",{className:"opacity-80",children:"90-day outcome:"})," ",s.outcome]})]}),e.jsxs("div",{children:[e.jsx("div",{className:"text-[11px] uppercase tracking-widest text-slate-500 font-semibold mb-3",children:"Weekly targets"}),e.jsx("div",{className:"grid grid-cols-2 md:grid-cols-3 gap-3",children:Object.entries(s.weekly_targets).map(([t,n])=>e.jsxs(_e,{className:"p-4 rounded-2xl",children:[e.jsx("div",{className:"text-2xl font-semibold text-slate-900 tabular-nums",children:n}),e.jsx("div",{className:"text-[11.5px] text-slate-500 capitalize mt-0.5",children:t.replace(/_/g," ")})]},t))})]}),e.jsxs("div",{children:[e.jsx("div",{className:"text-[11px] uppercase tracking-widest text-slate-500 font-semibold mb-3",children:"First 7 days"}),e.jsx(_e,{className:"p-5 rounded-2xl",children:e.jsx("ul",{className:"space-y-2",children:s.first_7_days.map((t,n)=>e.jsxs("li",{className:"flex items-start gap-2.5 text-[13.5px] text-slate-800",children:[e.jsx("div",{className:"h-5 w-5 rounded-full bg-violet-100 text-violet-700 grid place-items-center text-[11px] font-semibold flex-shrink-0 mt-0.5",children:n+1}),t]},n))})})]}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[e.jsxs(_e,{className:"p-5 rounded-2xl",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-widest text-slate-500 font-semibold mb-2",children:"Recommended first tool"}),e.jsx("div",{className:"text-[15px] font-semibold text-slate-900",children:s.suggested_tool})]}),e.jsxs(_e,{className:"p-5 rounded-2xl",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-widest text-slate-500 font-semibold mb-2",children:"Suggested first offer"}),e.jsx("div",{className:"text-[15px] font-semibold text-slate-900",children:s.suggested_offer})]})]})]})}function TIn(){const{settings:s,resetOnboarding:t}=RJ(),n=s==null?void 0:s.ninety_day_plan;return e.jsxs("div",{className:"max-w-4xl",children:[e.jsx(Op,{eyebrow:"90-Day Plan",title:"Your personalized attraction plan.",description:"Generated from your onboarding responses. Adjust any time by rerunning onboarding.",actions:e.jsxs(B,{variant:"outline",className:"rounded-full",onClick:()=>t.mutate(),children:[e.jsx(hf,{className:"h-4 w-4 mr-1.5"})," Rerun onboarding"]})}),n?e.jsx(d$t,{plan:n}):e.jsxs(_e,{className:"p-8 rounded-2xl text-center",children:[e.jsx("p",{className:"text-slate-700 mb-4",children:"You haven't set up your 90-day plan yet."}),e.jsx(B,{asChild:!0,className:"bg-gradient-to-r from-violet-600 to-indigo-600 rounded-full",children:e.jsx(cr,{to:"/attract/onboarding",children:"Start onboarding"})})]})]})}async function p0t(s,t,n,r={}){await H.rpc("award_attract_activity",{_user_id:s,_activity_type:t,_title:n,_description:r.description??null,_pillar:r.pillar??null,_agent_id:r.agent_id??null,_metadata:r.metadata??{},_dedupe_minutes:30})}function u$t(){const{user:s}=Ls(),t=as(),n=mt({queryKey:["attract-transactions",s==null?void 0:s.id],enabled:!!s,queryFn:async()=>{const{data:o,error:c}=await H.from("attract_transactions").select("*").order("closing_date",{ascending:!1,nullsFirst:!1});if(c)throw c;return o??[]}}),r=_t({mutationFn:async o=>{const c=[o.rating_communication,o.rating_professionalism,o.rating_problem_solving].filter(g=>typeof g=="number"),d=c.length?Number((c.reduce((g,y)=>g+y,0)/c.length).toFixed(2)):null,u={...o,user_id:s.id,overall_rating:d},{data:h,error:m}=o.id?await H.from("attract_transactions").update(u).eq("id",o.id).select().single():await H.from("attract_transactions").insert(u).select().single();if(m)throw m;const f=h;return o.id||await p0t(s.id,"transaction_logged",`Reviewed ${f.property_address}`,{description:f.cooperating_first_name?`Cooperating agent: ${f.cooperating_first_name} ${f.cooperating_last_name??""}`:null,pillar:"produce",metadata:{transaction_id:f.id,overall_rating:d}}),f},onSuccess:()=>{t.invalidateQueries({queryKey:["attract-transactions"]}),t.invalidateQueries({queryKey:["attract-activities"]}),ie.success("Transaction saved")},onError:o=>ie.error(o.message)}),a=_t({mutationFn:async({id:o,decision:c,notes:d})=>{const{data:u,error:h}=await H.from("attract_transactions").update({decision:c,decision_notes:d??null}).eq("id",o).select().single();if(h)throw h;return u},onSuccess:()=>{t.invalidateQueries({queryKey:["attract-transactions"]})}}),i=_t({mutationFn:async o=>{let c=o.attract_agent_id;if(!c){const{data:d}=await H.from("attract_agents").select("id").eq("user_id",s.id).eq("first_name",o.cooperating_first_name??"").eq("last_name",o.cooperating_last_name??"").maybeSingle();if(d!=null&&d.id)c=d.id;else{const{data:u,error:h}=await H.from("attract_agents").insert({user_id:s.id,first_name:o.cooperating_first_name??"Unknown",last_name:o.cooperating_last_name,email:o.cooperating_email,phone:o.cooperating_phone,brokerage:o.cooperating_brokerage,source:"cooperating_transaction",stage:"new_connection",temperature:o.enjoy_business_with==="yes"?"warm":"cold",notes:o.stood_out}).select("id").single();if(h)throw h;c=u.id}}return await H.from("attract_transactions").update({attract_agent_id:c,decision:"add_pipeline"}).eq("id",o.id),await p0t(s.id,"agent_added_from_transaction",`Added ${o.cooperating_first_name??"agent"} to pipeline`,{pillar:"produce",agent_id:c,metadata:{transaction_id:o.id}}),c},onSuccess:()=>{t.invalidateQueries({queryKey:["attract-transactions"]}),t.invalidateQueries({queryKey:["attract-agents"]}),t.invalidateQueries({queryKey:["attract-activities"]}),ie.success("Added to Agent Pipeline")},onError:o=>ie.error(o.message)}),l=_t({mutationFn:async o=>{const{error:c}=await H.from("attract_transactions").delete().eq("id",o);if(c)throw c},onSuccess:()=>{t.invalidateQueries({queryKey:["attract-transactions"]}),ie.success("Transaction removed")}});return{transactions:n.data??[],isLoading:n.isLoading,upsert:r,setDecision:a,addToPipeline:i,remove:l}}function EIn({value:s,onChange:t}){return e.jsx("div",{className:"flex gap-1",children:[1,2,3,4,5].map(n=>e.jsx("button",{type:"button",onClick:()=>t(n),children:e.jsx(Wa,{className:Ot("h-5 w-5",(s??0)>=n?"fill-amber-400 text-amber-400":"text-slate-300")})},n))})}function MIn(s,t){var l;const n=s.cooperating_first_name||"there",r=s.property_address||"the transaction",a=(l=s.stood_out)==null?void 0:l.trim(),i=a?`You ${a.replace(/^You\s+/i,"").replace(/[.!]$/,"")}.`:"You communicated clearly and handled the inevitable curveballs with real professionalism.";switch(t){case"warm":return`Hi ${n}, I really enjoyed working with you on ${r}. ${i} It made the deal feel smooth for both sides — and that's rare. Would love to stay connected. Grab coffee or a Zoom sometime this month? — `;case"peer":return`${n} — quick note. Working with you on ${r} was refreshing. ${i} We should stay in touch — I like being around agents who operate that way.`;case"text":return`Hey ${n} — just wanted to say thanks for the way you handled ${r}. ${i} Let's grab coffee soon.`;case"email":default:return`Subject: A quick thank you Hi ${n}, Wrapping up on ${r} and I wanted to send a note. ${i} It's the kind of transaction I remember for a long time. Would love to stay in touch — coffee, a Zoom, or a shared MLS thought when it hits. Whatever works. All the best, `}}const LIn={1:"Poor",2:"Fair",3:"OK",4:"Good",5:"Excellent"},zIe={add_pipeline:{label:"In Pipeline",color:"bg-emerald-100 text-emerald-800"},send_compliment:{label:"Compliment sent",color:"bg-violet-100 text-violet-800"},invite_coffee:{label:"Coffee invited",color:"bg-amber-100 text-amber-800"},share_resource:{label:"Resource shared",color:"bg-sky-100 text-sky-800"},no_action:{label:"No action",color:"bg-slate-100 text-slate-700"},pending:{label:"Needs review",color:"bg-rose-100 text-rose-800"}};function PIn(){const{transactions:s,isLoading:t,upsert:n,setDecision:r,addToPipeline:a,remove:i}=u$t(),[l,o]=N.useState(""),[c,d]=N.useState(!1),[u,h]=N.useState(null),[m,f]=N.useState(null),g=N.useMemo(()=>{const x=l.trim().toLowerCase();return x?s.filter(_=>[_.property_address,_.cooperating_first_name,_.cooperating_last_name,_.cooperating_brokerage,_.city].filter(Boolean).some(b=>String(b).toLowerCase().includes(x))):s},[s,l]),y=N.useMemo(()=>{const x=s.length,_=s.filter(A=>A.enjoy_business_with==="yes").length,b=s.filter(A=>A.decision==="add_pipeline").length,k=s.filter(A=>A.follow_up_created).length;return{reviewed:x,highFit:_,inPipeline:b,followUps:k}},[s]);return e.jsxs("div",{children:[e.jsxs(cr,{to:"/attract/produce",className:"inline-flex items-center gap-1.5 text-[12px] text-slate-500 hover:text-violet-700 mb-3",children:[e.jsx(ka,{className:"h-3.5 w-3.5"})," Back to Produce"]}),e.jsx(Op,{eyebrow:"Produce → Tool",title:"Transaction-to-Relationship Tracker",description:"Every good cooperating agent is a future relationship. Log the transaction, note what stood out, and turn the best experiences into real professional friendships.",actions:e.jsxs(B,{className:"rounded-full bg-gradient-to-r from-violet-600 to-indigo-600",onClick:()=>d(!0),children:[e.jsx(nn,{className:"h-4 w-4 mr-1.5"})," Add Transaction"]})}),e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-3 mb-6",children:[e.jsx(tre,{label:"Transactions reviewed",value:y.reviewed}),e.jsx(tre,{label:"High-fit agents",value:y.highFit,tone:"emerald"}),e.jsx(tre,{label:"Added to pipeline",value:y.inPipeline,tone:"violet"}),e.jsx(tre,{label:"Follow-ups created",value:y.followUps,tone:"amber"})]}),e.jsx("div",{className:"flex items-center gap-3 mb-4",children:e.jsxs("div",{className:"relative flex-1 max-w-md",children:[e.jsx(Gr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-slate-400"}),e.jsx(we,{value:l,onChange:x=>o(x.target.value),placeholder:"Search property, agent, brokerage...",className:"pl-9 rounded-full"})]})}),t?e.jsx("div",{className:"space-y-3",children:[0,1,2].map(x=>e.jsx(_e,{className:"p-5 rounded-2xl h-24 animate-pulse bg-slate-100"},x))}):g.length===0?e.jsxs(_e,{className:"p-10 rounded-2xl text-center",children:[e.jsx("div",{className:"h-14 w-14 rounded-2xl bg-violet-100 grid place-items-center mx-auto mb-4",children:e.jsx(Cn,{className:"h-6 w-6 text-violet-700"})}),e.jsx("h3",{className:"text-lg font-semibold text-slate-900",children:"Turn transactions into relationships"}),e.jsx("p",{className:"text-[13.5px] text-slate-600 max-w-md mx-auto mt-2",children:"Add your last 5 closed transactions to spot the agents you'd love to be in business with — then send a thoughtful compliment that opens the door."}),e.jsxs(B,{className:"mt-6 rounded-full bg-gradient-to-r from-violet-600 to-indigo-600",onClick:()=>d(!0),children:[e.jsx(nn,{className:"h-4 w-4 mr-1.5"})," Add your first transaction"]})]}):e.jsx("div",{className:"space-y-3",children:g.map(x=>{var _,b;return e.jsx(_e,{className:"p-5 rounded-2xl hover:shadow-md transition-shadow",children:e.jsxs("div",{className:"flex flex-col md:flex-row md:items-center gap-4",children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsx("div",{className:"text-[14px] font-semibold text-slate-900 truncate",children:x.property_address}),x.closing_date&&e.jsx(We,{variant:"outline",className:"text-[10.5px]",children:Js(new Date(x.closing_date),"MMM d, yyyy")}),e.jsx(We,{className:Ot("text-[10.5px] border-0",((_=zIe[x.decision])==null?void 0:_.color)??zIe.pending.color),children:((b=zIe[x.decision])==null?void 0:b.label)??"Needs review"})]}),e.jsxs("div",{className:"text-[12.5px] text-slate-600 mt-1",children:[x.cooperating_first_name||x.cooperating_last_name?`${x.cooperating_first_name??""} ${x.cooperating_last_name??""}`:"Cooperating agent",x.cooperating_brokerage?` · ${x.cooperating_brokerage}`:""]}),e.jsxs("div",{className:"flex items-center gap-3 mt-2 text-[12px] text-slate-600",children:[x.overall_rating!=null&&e.jsxs("span",{className:"inline-flex items-center gap-1",children:[e.jsx(Wa,{className:"h-3.5 w-3.5 fill-amber-400 text-amber-400"})," ",x.overall_rating]}),x.enjoy_business_with&&e.jsxs("span",{className:"capitalize",children:["Fit: ",e.jsx("span",{className:Ot("font-medium",x.enjoy_business_with==="yes"?"text-emerald-700":x.enjoy_business_with==="maybe"?"text-amber-700":"text-slate-600"),children:x.enjoy_business_with})]})]})]}),e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsxs(B,{size:"sm",variant:"outline",className:"rounded-full",onClick:()=>h(x),children:["Review ",e.jsx(Qa,{className:"h-3.5 w-3.5 ml-1"})]}),e.jsxs(B,{size:"sm",variant:"outline",className:"rounded-full",onClick:()=>f(x),children:[e.jsx(b9,{className:"h-3.5 w-3.5 mr-1"})," Message"]}),e.jsx(B,{size:"sm",variant:"ghost",className:"text-rose-600 hover:text-rose-700",onClick:()=>i.mutate(x.id),children:"Remove"})]})]})},x.id)})}),e.jsx("div",{className:"mt-8",children:e.jsx(xO,{})}),e.jsx(IIn,{open:c,onClose:()=>d(!1),onSaved:x=>{d(!1),h(x)},upsert:n}),e.jsx(DIn,{tx:u,onClose:()=>h(null),onDecision:x=>u&&r.mutate({id:u.id,decision:x}),onAddToPipeline:()=>u&&a.mutate(u),onMessage:()=>{f(u),h(null)}}),e.jsx(RIn,{tx:m,onClose:()=>f(null)})]})}function tre({label:s,value:t,tone:n="slate"}){const r={slate:"text-slate-900",emerald:"text-emerald-700",violet:"text-violet-700",amber:"text-amber-700"};return e.jsxs(_e,{className:"p-4 rounded-2xl",children:[e.jsx("div",{className:Ot("text-2xl font-semibold tabular-nums",r[n]),children:t}),e.jsx("div",{className:"text-[11.5px] text-slate-500 mt-0.5",children:s})]})}function IIn({open:s,onClose:t,onSaved:n,upsert:r}){const[a,i]=N.useState({enjoy_business_with:"maybe"}),l=c=>i({...a,...c}),o=async()=>{var d;if(!((d=a.property_address)!=null&&d.trim())){ie.error("Property address is required");return}const c=await r.mutateAsync(a);i({enjoy_business_with:"maybe"}),n(c)};return e.jsx(Bs,{open:s,onOpenChange:c=>!c&&t(),children:e.jsxs(Fs,{className:"max-w-2xl max-h-[90vh] overflow-y-auto",children:[e.jsxs(qs,{children:[e.jsx($s,{children:"Add Transaction"}),e.jsx(Ar,{children:"Capture what stood out while it's fresh."})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[e.jsxs("div",{className:"md:col-span-2",children:[e.jsx(re,{children:"Property address *"}),e.jsx(we,{value:a.property_address??"",onChange:c=>l({property_address:c.target.value})})]}),e.jsxs("div",{children:[e.jsx(re,{children:"City"}),e.jsx(we,{value:a.city??"",onChange:c=>l({city:c.target.value})})]}),e.jsxs("div",{children:[e.jsx(re,{children:"State"}),e.jsx(we,{value:a.state??"",onChange:c=>l({state:c.target.value})})]}),e.jsxs("div",{children:[e.jsx(re,{children:"Closing date"}),e.jsx(we,{type:"date",value:a.closing_date??"",onChange:c=>l({closing_date:c.target.value})})]}),e.jsxs("div",{children:[e.jsx(re,{children:"You represented"}),e.jsxs(Ns,{value:a.represented??"",onValueChange:c=>l({represented:c}),children:[e.jsx(ws,{children:e.jsx(ks,{placeholder:"Buyer or seller"})}),e.jsxs(js,{children:[e.jsx(nt,{value:"buyer",children:"Buyer"}),e.jsx(nt,{value:"seller",children:"Seller"}),e.jsx(nt,{value:"both",children:"Both"}),e.jsx(nt,{value:"other",children:"Other"})]})]})]})]}),e.jsxs("div",{className:"border-t pt-4",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-widest text-slate-500 font-semibold mb-3",children:"Cooperating agent"}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx(re,{children:"First name"}),e.jsx(we,{value:a.cooperating_first_name??"",onChange:c=>l({cooperating_first_name:c.target.value})})]}),e.jsxs("div",{children:[e.jsx(re,{children:"Last name"}),e.jsx(we,{value:a.cooperating_last_name??"",onChange:c=>l({cooperating_last_name:c.target.value})})]}),e.jsxs("div",{children:[e.jsx(re,{children:"Email"}),e.jsx(we,{type:"email",value:a.cooperating_email??"",onChange:c=>l({cooperating_email:c.target.value})})]}),e.jsxs("div",{children:[e.jsx(re,{children:"Phone"}),e.jsx(we,{value:a.cooperating_phone??"",onChange:c=>l({cooperating_phone:c.target.value})})]}),e.jsxs("div",{className:"md:col-span-2",children:[e.jsx(re,{children:"Brokerage"}),e.jsx(we,{value:a.cooperating_brokerage??"",onChange:c=>l({cooperating_brokerage:c.target.value})})]})]})]}),e.jsxs("div",{className:"border-t pt-4",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-widest text-slate-500 font-semibold mb-3",children:"Experience"}),e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-4",children:[["rating_communication","Communication"],["rating_professionalism","Professionalism"],["rating_problem_solving","Problem solving"]].map(([c,d])=>e.jsxs("div",{children:[e.jsx(re,{children:d}),e.jsx(EIn,{value:a[c],onChange:u=>l({[c]:u})}),e.jsx("div",{className:"text-[11px] text-slate-500 mt-1",children:LIn[a[c]]??"—"})]},c))}),e.jsxs("div",{className:"mt-4",children:[e.jsx(re,{children:"Would you enjoy being in business with this agent?"}),e.jsx("div",{className:"flex gap-2 mt-2",children:["yes","maybe","no"].map(c=>e.jsx("button",{type:"button",onClick:()=>l({enjoy_business_with:c}),className:Ot("rounded-full px-4 py-1.5 text-[12.5px] font-medium border capitalize",a.enjoy_business_with===c?"bg-violet-600 text-white border-violet-600":"bg-white text-slate-700 border-slate-200"),children:c},c))})]}),e.jsxs("div",{className:"mt-4",children:[e.jsx(re,{children:"What stood out?"}),e.jsx(Ws,{rows:2,value:a.stood_out??"",onChange:c=>l({stood_out:c.target.value})})]}),e.jsxs("div",{className:"mt-4",children:[e.jsx(re,{children:"Private notes"}),e.jsx(Ws,{rows:2,value:a.private_notes??"",onChange:c=>l({private_notes:c.target.value}),placeholder:"Only you can see these."})]})]})]}),e.jsxs(Cr,{children:[e.jsx(B,{variant:"ghost",onClick:t,children:"Cancel"}),e.jsx(B,{onClick:o,disabled:r.isPending,className:"bg-gradient-to-r from-violet-600 to-indigo-600",children:"Save & review"})]})]})})}function DIn({tx:s,onClose:t,onDecision:n,onAddToPipeline:r,onMessage:a}){return s?e.jsx(Bs,{open:!!s,onOpenChange:i=>!i&&t(),children:e.jsxs(Fs,{className:"max-w-lg",children:[e.jsxs(qs,{children:[e.jsx($s,{children:"Would you like to build a relationship?"}),e.jsxs(Ar,{children:[s.cooperating_first_name?`${s.cooperating_first_name} ${s.cooperating_last_name??""}`:"This agent"," on ",s.property_address,"."]})]}),e.jsxs("div",{className:"grid grid-cols-1 gap-2",children:[e.jsx(CH,{icon:Yl,label:"Add to Agent Pipeline",tone:"violet",onClick:r}),e.jsx(CH,{icon:b9,label:"Send a professional compliment",tone:"teal",onClick:()=>{n("send_compliment"),a()}}),e.jsx(CH,{icon:T_,label:"Invite to coffee",tone:"amber",onClick:()=>{n("invite_coffee"),a()}}),e.jsx(CH,{icon:Cn,label:"Share a relevant resource",tone:"sky",onClick:()=>n("share_resource")}),e.jsx(CH,{icon:Nu,label:"No action right now",tone:"slate",onClick:()=>{n("no_action"),t()}})]})]})}):null}function CH({icon:s,label:t,tone:n,onClick:r}){const a={violet:"bg-violet-50 text-violet-700 hover:bg-violet-100",teal:"bg-teal-50 text-teal-700 hover:bg-teal-100",amber:"bg-amber-50 text-amber-700 hover:bg-amber-100",sky:"bg-sky-50 text-sky-700 hover:bg-sky-100",slate:"bg-slate-50 text-slate-700 hover:bg-slate-100"};return e.jsxs("button",{onClick:r,className:Ot("flex items-center gap-3 rounded-xl px-4 py-3 text-left transition-colors",a[n]),children:[e.jsx(s,{className:"h-5 w-5"}),e.jsx("div",{className:"flex-1 text-[13.5px] font-medium",children:t}),e.jsx(Qa,{className:"h-4 w-4 opacity-60"})]})}function RIn({tx:s,onClose:t}){const[n,r]=N.useState("warm");if(!s)return null;const a=MIn(s,n);return e.jsx(Bs,{open:!!s,onOpenChange:i=>!i&&t(),children:e.jsxs(Fs,{className:"max-w-lg",children:[e.jsxs(qs,{children:[e.jsx($s,{children:"Personalized message"}),e.jsx(Ar,{children:"Adjust the tone, then copy and send from your usual inbox."})]}),e.jsx("div",{className:"flex gap-1.5 mb-3",children:[["warm","Warm & pro"],["peer","Casual peer"],["text","Short text"],["email","Email"]].map(([i,l])=>e.jsx("button",{onClick:()=>r(i),className:Ot("rounded-full px-3 py-1 text-[11.5px] font-medium border",n===i?"bg-violet-600 text-white border-violet-600":"bg-white text-slate-700 border-slate-200"),children:l},i))}),e.jsx(Ws,{value:a,readOnly:!0,rows:10,className:"font-mono text-[12.5px]"}),e.jsxs(Cr,{children:[e.jsx(B,{variant:"ghost",onClick:t,children:"Close"}),e.jsxs(B,{className:"bg-gradient-to-r from-violet-600 to-indigo-600",onClick:()=>{navigator.clipboard.writeText(a),ie.success("Copied to clipboard")},children:[e.jsx(Pa,{className:"h-4 w-4 mr-1.5"})," Copy"]})]})]})})}function h$t(){const{user:s}=Ls(),t=as(),n=mt({queryKey:["attract-content",s==null?void 0:s.id],enabled:!!s,queryFn:async()=>{const{data:o,error:c}=await H.from("attract_content_drafts").select("*").order("updated_at",{ascending:!1});if(c)throw c;return o??[]}}),r=_t({mutationFn:async o=>{const{data:c,error:d}=await H.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?ie.info("Demo generation used — configure AI provider for live results"):ie.success("Content generated")},onError:o=>ie.error(o.message)}),a=_t({mutationFn:async o=>{const{data:c,error:d}=await H.from("attract_content_drafts").update(o).eq("id",o.id).select().single();if(d)throw d;return c},onSuccess:()=>{t.invalidateQueries({queryKey:["attract-content"]}),ie.success("Saved")}}),i=_t({mutationFn:async o=>{const{error:c}=await H.from("attract_content_drafts").update({status:"posted",posted_at:new Date().toISOString()}).eq("id",o);if(c)throw c;await H.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"]}),ie.success("Marked as posted")}}),l=_t({mutationFn:async o=>{const{error:c}=await H.from("attract_content_drafts").delete().eq("id",o);if(c)throw c},onSuccess:()=>{t.invalidateQueries({queryKey:["attract-content"]}),ie.success("Draft removed")}});return{drafts:n.data??[],isLoading:n.isLoading,generate:r,save:a,markPosted:i,remove:l}}const Xze=[{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"}]}],OIn=["Direct","Educational","Fun","Contrarian","Encouraging"],FIn=["short","medium","long"],zIn=["instagram","linkedin","facebook","youtube","email"],nSe={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 BIn(){const{drafts:s,isLoading:t,generate:n,save:r,markPosted:a,remove:i}=h$t(),[l,o]=N.useState(!1),[c,d]=N.useState(null),u=N.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(cr,{to:"/attract/influence",className:"inline-flex items-center gap-1.5 text-[12px] text-slate-500 hover:text-violet-700 mb-3",children:[e.jsx(ka,{className:"h-3.5 w-3.5"})," Back to Influence"]}),e.jsx(Op,{eyebrow:"Influence → Tool",title:"Authority Content Studio",description:"Turn your real experience into agent-focused content that builds authority — without sounding like a brokerage pitch.",actions:e.jsxs(B,{className:"rounded-full bg-gradient-to-r from-violet-600 to-indigo-600",onClick:()=>{d(null),o(!0)},children:[e.jsx(Zg,{className:"h-4 w-4 mr-1.5"})," New Content"]})}),e.jsxs("div",{className:"mb-6 rounded-2xl border border-amber-200 bg-amber-50/70 px-5 py-3.5 text-[13px] text-amber-900 flex items-start gap-3",children:[e.jsx(Cn,{className:"h-4 w-4 mt-0.5"}),e.jsxs("div",{children:[e.jsx("span",{className:"font-semibold",children:"80/20 rule:"})," Aim for 80% useful industry, business, and personal content — and no more than 20% direct brokerage content."]})]}),e.jsxs(ya,{defaultValue:"all",className:"mb-8",children:[e.jsxs(va,{children:[e.jsxs(ls,{value:"all",children:["All (",s.length,")"]}),e.jsxs(ls,{value:"ready",children:["Ready (",u.ready.length,")"]}),e.jsxs(ls,{value:"draft",children:["Draft (",u.draft.length,")"]}),e.jsxs(ls,{value:"posted",children:["Posted (",u.posted.length,")"]})]}),e.jsx(_s,{value:"all",children:e.jsx(sre,{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(_s,{value:"ready",children:e.jsx(sre,{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(_s,{value:"draft",children:e.jsx(sre,{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(_s,{value:"posted",children:e.jsx(sre,{drafts:u.posted,isLoading:t,onOpen:h=>{d(h),o(!0)},onPosted:()=>{},onRemove:h=>i.mutate(h),onEmpty:()=>{d(null),o(!0)}})})]}),e.jsx(xO,{}),e.jsx($In,{open:l,editing:c,onClose:()=>{o(!1),d(null)},generate:n,save:r,markPosted:h=>a.mutate(h)})]})}function sre({drafts:s,isLoading:t,onOpen:n,onPosted:r,onRemove:a,onEmpty:i}){return t?e.jsx("div",{className:"space-y-3 mt-4",children:[0,1,2].map(l=>e.jsx(_e,{className:"p-5 rounded-2xl h-24 animate-pulse bg-slate-100"},l))}):s.length===0?e.jsxs(_e,{className:"p-10 rounded-2xl text-center mt-4",children:[e.jsx("div",{className:"h-14 w-14 rounded-2xl bg-violet-100 grid place-items-center mx-auto mb-4",children:e.jsx(O2,{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(nn,{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=Xze.find(u=>u.key===l.mode))==null?void 0:c.label)??l.mode;return e.jsx(_e,{className:"p-5 rounded-2xl hover:shadow-md transition-shadow",children:e.jsxs("div",{className:"flex items-start gap-4",children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsx(We,{className:Ot("text-[10.5px] border-0",nSe[l.status].color),children:nSe[l.status].label}),e.jsx(We,{variant:"outline",className:"text-[10.5px]",children:o}),l.tone&&e.jsx(We,{variant:"outline",className:"text-[10.5px]",children:l.tone}),l.ratio_flag&&e.jsxs(We,{className:"text-[10.5px] bg-amber-100 text-amber-900 border-0 gap-1",children:[e.jsx(xd,{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 ${Js(new Date(l.posted_at),"MMM d")}`:`Updated ${Js(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(pa,{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(qn,{className:"h-3.5 w-3.5"})})]})]})},l.id)})})}function $In({open:s,editing:t,onClose:n,generate:r,save:a,markPosted:i}){const[l,o]=N.useState((t==null?void 0:t.mode)??"transaction_lesson"),[c,d]=N.useState((t==null?void 0:t.input_json)??{}),[u,h]=N.useState((t==null?void 0:t.topic)??""),[m,f]=N.useState((t==null?void 0:t.tone)??"Educational"),[g,y]=N.useState((t==null?void 0:t.length)??"medium"),[x,_]=N.useState((t==null?void 0:t.platforms)??["instagram"]),[b,k]=N.useState((t==null?void 0:t.include_brokerage_reference)??!1),[A,T]=N.useState(t??null),[P,I]=N.useState(""),[M,L]=N.useState((t==null?void 0:t.status)??"draft"),z=Xze.find(W=>W.key===l),$=async W=>{const G=await r.mutateAsync({mode:l,topic:u,inputs:c,tone:m,length:g,platforms:x,include_brokerage_reference:b,refinement:W??P,draft_id:A==null?void 0:A.id});G!=null&&G.draft&&T(G.draft),I("")},V=async W=>{if(!A)return;const G=await a.mutateAsync({id:A.id,...W});T(G)};return e.jsx(Bs,{open:s,onOpenChange:W=>!W&&n(),children:e.jsx(Fs,{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(qs,{children:[e.jsx($s,{className:"text-base",children:"Content Studio"}),e.jsx(Ar,{className:"text-[12px]",children:z.blurb})]}),e.jsxs("div",{className:"mt-4 space-y-3",children:[e.jsxs("div",{children:[e.jsx(re,{className:"text-[12px]",children:"Content mode"}),e.jsxs(Ns,{value:l,onValueChange:W=>{o(W),d({})},children:[e.jsx(ws,{children:e.jsx(ks,{})}),e.jsx(js,{children:Xze.map(W=>e.jsx(nt,{value:W.key,children:W.label},W.key))})]})]}),e.jsxs("div",{children:[e.jsx(re,{className:"text-[12px]",children:"Topic (optional)"}),e.jsx(we,{value:u,onChange:W=>h(W.target.value),placeholder:"1-line summary"})]}),z.fields.map(W=>e.jsxs("div",{children:[e.jsx(re,{className:"text-[12px]",children:W.label}),e.jsx(Ws,{rows:2,value:c[W.key]??"",onChange:G=>d({...c,[W.key]:G.target.value}),placeholder:W.placeholder})]},W.key)),e.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[e.jsxs("div",{children:[e.jsx(re,{className:"text-[12px]",children:"Tone"}),e.jsxs(Ns,{value:m,onValueChange:f,children:[e.jsx(ws,{children:e.jsx(ks,{})}),e.jsx(js,{children:OIn.map(W=>e.jsx(nt,{value:W,children:W},W))})]})]}),e.jsxs("div",{children:[e.jsx(re,{className:"text-[12px]",children:"Length"}),e.jsxs(Ns,{value:g,onValueChange:y,children:[e.jsx(ws,{children:e.jsx(ks,{})}),e.jsx(js,{children:FIn.map(W=>e.jsx(nt,{value:W,children:W},W))})]})]})]}),e.jsxs("div",{children:[e.jsx(re,{className:"text-[12px]",children:"Platforms"}),e.jsx("div",{className:"flex flex-wrap gap-1.5 mt-1",children:zIn.map(W=>e.jsx("button",{type:"button",onClick:()=>_(x.includes(W)?x.filter(G=>G!==W):[...x,W]),className:Ot("rounded-full px-2.5 py-1 text-[11px] capitalize border",x.includes(W)?"bg-violet-600 text-white border-violet-600":"bg-white border-slate-200 text-slate-700"),children:W},W))})]}),e.jsxs("label",{className:"flex items-center gap-2 text-[12px] text-slate-700",children:[e.jsx("input",{type:"checkbox",checked:b,onChange:W=>k(W.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:()=>$(),disabled:r.isPending,children:[e.jsx(Zg,{className:"h-4 w-4 mr-1.5"})," ",r.isPending?"Generating…":A?"Regenerate":"Generate content"]})]})]}),e.jsx("div",{className:"overflow-y-auto p-6",children:A?e.jsxs("div",{className:"space-y-5",children:[A.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(xd,{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:()=>$("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(We,{className:Ot("text-[10.5px] border-0",nSe[M].color),children:nSe[M].label}),e.jsxs(Ns,{value:M,onValueChange:W=>{L(W),V({status:W})},children:[e.jsx(ws,{className:"h-8 w-32 text-[12px]",children:e.jsx(ks,{})}),e.jsxs(js,{children:[e.jsx(nt,{value:"idea",children:"Idea"}),e.jsx(nt,{value:"draft",children:"Draft"}),e.jsx(nt,{value:"ready",children:"Ready"}),e.jsx(nt,{value:"posted",children:"Posted"})]})]}),e.jsx(we,{type:"date",className:"h-8 w-40 text-[12px]",value:A.planned_at?A.planned_at.slice(0,10):"",onChange:W=>V({planned_at:W.target.value?new Date(W.target.value).toISOString():null})}),A.status!=="posted"&&e.jsxs(B,{size:"sm",variant:"outline",className:"rounded-full",onClick:()=>i(A.id),children:[e.jsx(Rr,{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(cr,{to:`/attract/provide/kits/new?seed=${encodeURIComponent(A.topic||A.mode)}`,children:[e.jsx(nn,{className:"h-3.5 w-3.5 mr-1"})," Turn into a kit"]})})]}),e.jsx(WF,{title:"Hook options",children:e.jsx("div",{className:"space-y-1.5",children:(A.hook_options??[]).map((W,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:[G+1,"."]}),e.jsx("span",{className:"flex-1",children:W}),e.jsx(Qze,{value:W})]},G))})}),e.jsx(WF,{title:"Teleprompter script",children:e.jsx(BIe,{value:A.script??"",onSave:W=>V({script:W})})}),e.jsx(WF,{title:"Social caption",children:e.jsx(BIe,{value:A.caption??"",onSave:W=>V({caption:W})})}),e.jsx(WF,{title:"Carousel outline",children:e.jsx("div",{className:"space-y-1.5",children:(A.carousel_outline??[]).map((W,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 ",W.slide??G+1]}),e.jsx("div",{className:"text-slate-800 mt-0.5",children:W.text})]},G))})}),e.jsx(WF,{title:"Email lesson",children:e.jsx(BIe,{value:A.email_lesson??"",onSave:W=>V({email_lesson:W})})}),e.jsx(WF,{title:"CTA options",children:e.jsx("div",{className:"space-y-1.5",children:(A.cta_options??[]).map((W,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:W}),e.jsx(Qze,{value:W})]},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(W=>e.jsx(B,{size:"sm",variant:"outline",className:"text-[11.5px]",onClick:()=>$(W),children:W},W))}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(we,{value:P,onChange:W=>I(W.target.value),placeholder:"Custom refinement…"}),e.jsxs(B,{variant:"outline",onClick:()=>$(),disabled:r.isPending,children:[e.jsx(oo,{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(yW,{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 WF({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(ta,{className:"h-3 w-3 opacity-0"})," ",s]}),t]})}function BIe({value:s,onSave:t}){const[n,r]=N.useState(s);return e.jsxs("div",{children:[e.jsx(Ws,{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(Qze,{value:n})]})]})}function Qze({value:s}){return e.jsx(B,{size:"sm",variant:"ghost",onClick:()=>{navigator.clipboard.writeText(s),ie.success("Copied")},children:e.jsx(Pa,{className:"h-3.5 w-3.5"})})}const UIn={draft:"bg-slate-100 text-slate-700",published:"bg-emerald-100 text-emerald-800",archived:"bg-amber-100 text-amber-800"};function qIn(){const{kits:s,isLoading:t,create:n,duplicate:r,remove:a}=dq(),i=tr(),l=async()=>{const o=await n.mutateAsync({title:"Untitled Kit",status:"draft"});i(`/attract/provide/kits/${o.id}/edit`)};return e.jsxs("div",{children:[e.jsx(Op,{eyebrow:"Provide · Resource Kits",title:"Your Resource Kits",description:"Package the value you already share, then track what actually creates conversations.",actions:e.jsxs("div",{className:"flex gap-2",children:[e.jsx(B,{variant:"outline",asChild:!0,className:"rounded-full",children:e.jsxs(cr,{to:"/attract/provide/kits/templates",children:[e.jsx(rb,{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(nn,{className:"h-4 w-4 mr-2"}),"New kit"]})]})}),t&&e.jsx("div",{className:"text-slate-500 text-sm",children:"Loading kits…"}),!t&&s.length===0&&e.jsxs(_e,{className:"p-10 text-center rounded-2xl border-dashed border-slate-300 bg-white",children:[e.jsx(Cn,{className:"h-8 w-8 mx-auto text-violet-500"}),e.jsx("div",{className:"mt-3 text-lg font-semibold",children:"You haven't built a kit yet."}),e.jsx("p",{className:"text-slate-600 max-w-md mx-auto mt-1 text-sm",children:"Start from a starter template or a blank kit. Bundle 3–7 pieces of real value and share with agents you'd love to work alongside."}),e.jsxs("div",{className:"flex gap-2 justify-center mt-5",children:[e.jsx(B,{variant:"outline",asChild:!0,children:e.jsx(cr,{to:"/attract/provide/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(_e,{className:"p-5 rounded-2xl border-slate-200 bg-white hover:shadow-md transition-shadow flex flex-col",children:[e.jsx("div",{className:"flex items-start justify-between gap-2",children:e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(We,{className:UIn[o.status]+" capitalize",children:o.status}),o.pillar&&e.jsx(We,{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(We,{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(cr,{to:`/attract/provide/kits/${o.id}/edit`,children:[e.jsx(N9,{className:"h-3.5 w-3.5 mr-1.5"}),"Edit"]})}),e.jsx(B,{size:"sm",variant:"outline",asChild:!0,children:e.jsxs(cr,{to:`/attract/provide/kits/${o.id}/analytics`,children:[e.jsx(fl,{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);ie.success("Duplicated"),i(`/attract/provide/kits/${d}/edit`)},children:e.jsx(Pa,{className:"h-3.5 w-3.5"})}),e.jsx(B,{size:"sm",variant:"ghost",onClick:()=>{confirm("Delete this kit? Shares and events will also be removed.")&&a.mutate(o.id,{onSuccess:()=>ie.success("Deleted")})},children:e.jsx(qn,{className:"h-3.5 w-3.5 text-rose-600"})})]})]},o.id)})})]})}const VIn={pdf:Wr,video:dd,link:gc,checklist:zm,template:f5,text:Wr,content_studio:Cn,resource:Wr};function m$t({kit:s,items:t,owner:n,personalNote:r,mode:a="public",onEvent:i}){const l=(o,c,d)=>i==null?void 0:i(o,c,d);return e.jsxs("div",{className:"bg-[#0B0F1E] text-slate-100 rounded-2xl overflow-hidden",children:[s.cover_image_url?e.jsxs("div",{className:"aspect-[16/7] bg-slate-800 relative",children:[e.jsx("img",{src:s.cover_image_url,alt:"",className:"w-full h-full object-cover"}),e.jsx("div",{className:"absolute inset-0 bg-gradient-to-t from-[#0B0F1E] to-transparent"})]}):e.jsx("div",{className:"h-24 bg-gradient-to-br from-violet-700 via-indigo-700 to-slate-900"}),e.jsxs("div",{className:"p-5 md:p-8",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[n.avatar_url?e.jsx("img",{src:n.avatar_url,alt:"",className:"h-11 w-11 rounded-full object-cover ring-2 ring-white/10"}):e.jsx("div",{className:"h-11 w-11 rounded-full bg-white/10 grid place-items-center text-white/70 font-semibold",children:n.display_name.slice(0,1)}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"text-[13.5px] font-semibold",children:n.display_name}),n.brokerage&&e.jsx("div",{className:"text-[11px] text-slate-400",children:n.brokerage})]})]}),e.jsx("h1",{className:"mt-5 text-2xl md:text-3xl font-semibold tracking-tight text-white",children:s.title}),s.audience&&e.jsxs("div",{className:"text-[12px] uppercase tracking-widest text-violet-300 mt-1",children:["For ",s.audience]}),s.description&&e.jsx("p",{className:"text-slate-300 mt-3 text-[14.5px] leading-relaxed",children:s.description}),(r||s.intro_text)&&e.jsxs(_e,{className:"mt-6 p-4 bg-white/5 border-white/10 text-slate-200",children:[r&&e.jsx("div",{className:"text-[13px] whitespace-pre-line",children:r}),r&&s.intro_text&&e.jsx("div",{className:"my-2 border-t border-white/10"}),s.intro_text&&e.jsx("div",{className:"text-[13px] whitespace-pre-line text-slate-300",children:s.intro_text})]}),s.intro_video_url&&e.jsx("div",{className:"mt-5 aspect-video rounded-xl overflow-hidden bg-black",children:e.jsx("iframe",{src:HIn(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=VIn[o.type]??Wr;return e.jsx(_e,{className:"p-4 bg-white/5 border-white/10 text-slate-100",children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx("div",{className:"h-9 w-9 rounded-lg bg-violet-600/20 text-violet-300 grid place-items-center flex-shrink-0",children:e.jsx(c,{className:"h-4 w-4"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("div",{className:"text-[14px] font-semibold text-white",children:o.title}),o.description&&e.jsx("div",{className:"text-[12.5px] text-slate-300 mt-0.5",children:o.description}),o.type==="checklist"&&((d=o.content)==null?void 0:d.items)&&e.jsx("ul",{className:"mt-2 space-y-1 text-[13px] text-slate-200",children:o.content.items.map((h,m)=>e.jsxs("li",{className:"flex gap-2",children:[e.jsx("span",{className:"text-violet-400",children:"•"}),h]},m))}),(o.type==="text"||o.type==="template")&&((u=o.content)==null?void 0:u.body)&&e.jsx("div",{className:"mt-2 text-[13px] text-slate-300 whitespace-pre-line",children:o.content.body}),o.url&&["video","pdf","link","resource"].includes(o.type)&&e.jsxs("div",{className:"mt-3 flex gap-2 flex-wrap",children:[e.jsx(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(Tr,{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(oi,{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 HIn(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 GIn=[{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 f0t(){var W,G;const{kitId:s}=uo(),[t]=$c(),n=tr(),{user:r}=Ls(),a=s===void 0,{create:i,update:l}=dq(),{data:o,isLoading:c}=VBt(s),{items:d,add:u,update:h,remove:m,reorder:f}=kPn(s),{shares:g,create:y,revoke:x}=HBt(s),{agents:_}=jb(),[b,k]=N.useState(null),[A,T]=N.useState("desktop"),[P,I]=N.useState("idle"),M=N.useRef(null);N.useEffect(()=>{a&&!b&&(async()=>{const X=t.get("seed"),te=await i.mutateAsync({title:X?`From: ${X}`:"Untitled Kit",status:"draft"});n(`/attract/provide/kits/${te.id}/edit`,{replace:!0})})()},[a]),N.useEffect(()=>{o&&k(o)},[o==null?void 0:o.id]);const L=X=>{s&&(k(te=>({...te,...X})),I("saving"),clearTimeout(M.current),M.current=setTimeout(async()=>{try{await l.mutateAsync({id:s,patch:X}),I("saved"),setTimeout(()=>I("idle"),1500)}catch(te){ie.error(te.message??"Save failed"),I("idle")}},800))},z=async X=>{!s||!r||await u.mutateAsync({user_id:r.id,type:X,title:`New ${X.replace("_"," ")}`})},$=(X,te)=>{const ne=[...d],me=X+te;me<0||me>=ne.length||([ne[X],ne[me]]=[ne[me],ne[X]],f.mutate(ne.map(ue=>ue.id)))},V=g.filter(X=>X.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(Op,{eyebrow:"Provide · Kit builder",title:b.title||"Untitled Kit",description:P==="saving"?"Saving…":P==="saved"?"Saved":`Last edited ${Js(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(cr,{to:"/attract/provide/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(cr,{to:`/attract/provide/kits/${s}/analytics`,children:"Analytics"})}),e.jsxs(Ns,{value:b.status,onValueChange:X=>L({status:X}),children:[e.jsx(ws,{className:"w-[130px] rounded-full",children:e.jsx(ks,{})}),e.jsxs(js,{children:[e.jsx(nt,{value:"draft",children:"Draft"}),e.jsx(nt,{value:"published",children:"Published"}),e.jsx(nt,{value:"archived",children:"Archived"})]})]})]})}),e.jsxs("div",{className:"grid grid-cols-1 xl:grid-cols-12 gap-6",children:[e.jsxs("div",{className:"xl:col-span-4 space-y-4",children:[e.jsxs(_e,{className:"p-5 rounded-2xl",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-widest text-violet-700 font-semibold",children:"Kit details"}),e.jsxs("div",{className:"space-y-3 mt-3",children:[e.jsxs("div",{children:[e.jsx(re,{children:"Title"}),e.jsx(we,{value:b.title??"",onChange:X=>L({title:X.target.value})})]}),e.jsxs("div",{children:[e.jsx(re,{children:"Short description"}),e.jsx(Ws,{rows:3,value:b.description??"",onChange:X=>L({description:X.target.value})})]}),e.jsxs("div",{children:[e.jsx(re,{children:"Cover image URL"}),e.jsx(we,{placeholder:"https://…",value:b.cover_image_url??"",onChange:X=>L({cover_image_url:X.target.value})})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[e.jsxs("div",{children:[e.jsx(re,{children:"Audience"}),e.jsx(we,{placeholder:"e.g. New agents",value:b.audience??"",onChange:X=>L({audience:X.target.value})})]}),e.jsxs("div",{children:[e.jsx(re,{children:"Pillar"}),e.jsxs(Ns,{value:b.pillar??"",onValueChange:X=>L({pillar:X}),children:[e.jsx(ws,{children:e.jsx(ks,{placeholder:"Choose"})}),e.jsxs(js,{children:[e.jsx(nt,{value:"produce",children:"Produce"}),e.jsx(nt,{value:"influence",children:"Influence"}),e.jsx(nt,{value:"provide",children:"Provide"}),e.jsx(nt,{value:"connect",children:"Connect"})]})]})]})]}),e.jsxs("div",{children:[e.jsx(re,{children:"Tags (comma separated)"}),e.jsx(we,{value:(b.tags??[]).join(", "),onChange:X=>L({tags:X.target.value.split(",").map(te=>te.trim()).filter(Boolean)})})]})]})]}),e.jsxs(_e,{className:"p-5 rounded-2xl",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-widest text-violet-700 font-semibold",children:"Personal welcome"}),e.jsxs("div",{className:"space-y-3 mt-3",children:[e.jsx(Ws,{rows:4,placeholder:"Write a short personal note that opens the kit.",value:b.intro_text??"",onChange:X=>L({intro_text:X.target.value})}),e.jsxs("div",{children:[e.jsx(re,{children:"Intro video URL (optional)"}),e.jsx(we,{placeholder:"Loom/YouTube/Vimeo",value:b.intro_video_url??"",onChange:X=>L({intro_video_url:X.target.value})})]})]})]}),e.jsxs(_e,{className:"p-5 rounded-2xl",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-widest text-violet-700 font-semibold",children:"Call to action"}),e.jsxs("div",{className:"grid grid-cols-2 gap-2 mt-3",children:[e.jsxs("div",{children:[e.jsx(re,{children:"Button label"}),e.jsx(we,{value:b.cta_label??"",onChange:X=>L({cta_label:X.target.value})})]}),e.jsxs("div",{children:[e.jsx(re,{children:"Button URL"}),e.jsx(we,{placeholder:"https://…",value:b.cta_url??"",onChange:X=>L({cta_url:X.target.value})})]})]}),e.jsxs("div",{className:"mt-3",children:[e.jsx(re,{children:"Expiration (optional)"}),e.jsx(we,{type:"datetime-local",value:b.expires_at?b.expires_at.slice(0,16):"",onChange:X=>L({expires_at:X.target.value?new Date(X.target.value).toISOString():null})})]})]}),e.jsxs(_e,{className:"p-5 rounded-2xl",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-widest text-violet-700 font-semibold",children:"Share this kit"}),e.jsx(WIn,{kitId:s,agents:_,shares:V,onCreate:X=>y.mutate(X),onRevoke:X=>x.mutate(X),status:b.status})]})]}),e.jsx("div",{className:"xl:col-span-5 space-y-4",children:e.jsxs(_e,{className:"p-5 rounded-2xl",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[11px] uppercase tracking-widest text-violet-700 font-semibold",children:"Kit sections"}),e.jsx("div",{className:"text-[13px] text-slate-600",children:"Drag order using arrows. Reorder to change how visitors experience the kit."})]}),e.jsxs(Ns,{onValueChange:X=>z(X),children:[e.jsx(ws,{className:"w-[180px]",children:e.jsx(ks,{placeholder:"+ Add item"})}),e.jsx(js,{children:GIn.map(X=>e.jsx(nt,{value:X.value,children:X.label},X.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((X,te)=>{var ne,me;return e.jsx(_e,{className:"p-4 border-slate-200",children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsxs("div",{className:"flex flex-col gap-1",children:[e.jsx("button",{className:"text-slate-400 hover:text-slate-700",onClick:()=>$(te,-1),children:e.jsx(Om,{className:"h-4 w-4"})}),e.jsx("button",{className:"text-slate-400 hover:text-slate-700",onClick:()=>$(te,1),children:e.jsx(Wf,{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(We,{variant:"outline",className:"capitalize",children:X.type.replace("_"," ")}),e.jsx(we,{className:"flex-1",value:X.title,onChange:ue=>h.mutate({id:X.id,patch:{title:ue.target.value}})})]}),e.jsx(Ws,{rows:2,placeholder:"Short description",value:X.description??"",onChange:ue=>h.mutate({id:X.id,patch:{description:ue.target.value}})}),["video","pdf","link","resource"].includes(X.type)&&e.jsx(we,{placeholder:"URL",value:X.url??"",onChange:ue=>h.mutate({id:X.id,patch:{url:ue.target.value}})}),["text","template"].includes(X.type)&&e.jsx(Ws,{rows:4,placeholder:"Body text or script",value:((ne=X.content)==null?void 0:ne.body)??"",onChange:ue=>h.mutate({id:X.id,patch:{content:{...X.content??{},body:ue.target.value}}})}),X.type==="checklist"&&e.jsx(Ws,{rows:5,placeholder:"One item per line",value:(((me=X.content)==null?void 0:me.items)??[]).join(` `),onChange:ue=>h.mutate({id:X.id,patch:{content:{items:ue.target.value.split(` `).map(ce=>ce.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(zn,{checked:X.allow_download,onCheckedChange:ue=>h.mutate({id:X.id,patch:{allow_download:ue}})}),"Allow download"]}),e.jsxs("label",{className:"flex items-center gap-2 text-[12px] text-slate-600",children:[e.jsx(zn,{checked:!X.is_hidden,onCheckedChange:ue=>h.mutate({id:X.id,patch:{is_hidden:!ue}})}),"Visible"]}),e.jsxs("button",{className:"ml-auto text-rose-600 text-[12px] flex items-center gap-1",onClick:()=>m.mutate(X.id),children:[e.jsx(qn,{className:"h-3.5 w-3.5"}),"Delete"]})]})]})]})},X.id)})]})]})}),e.jsx("div",{className:"xl:col-span-3",children:e.jsxs(_e,{className:"p-4 rounded-2xl xl:sticky xl:top-4",children:[e.jsxs("div",{className:"flex items-center justify-between mb-3",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-widest text-violet-700 font-semibold",children:"Live preview"}),e.jsx(ya,{value:A,onValueChange:X=>T(X),children:e.jsxs(va,{className:"h-8",children:[e.jsx(ls,{value:"desktop",className:"h-6 px-2",children:e.jsx(hj,{className:"h-3.5 w-3.5"})}),e.jsx(ls,{value:"mobile",className:"h-6 px-2",children:e.jsx($y,{className:"h-3.5 w-3.5"})})]})})]}),e.jsx("div",{className:A==="mobile"?"max-w-[320px] mx-auto":"",children:e.jsx(m$t,{kit:b,items:d,owner:{display_name:((W=r==null?void 0:r.user_metadata)==null?void 0:W.full_name)||(r==null?void 0:r.email)||"You",avatar_url:((G=r==null?void 0:r.user_metadata)==null?void 0:G.avatar_url)??null,brokerage:null},mode:"preview"})})]})})]})]})}function WIn({kitId:s,agents:t,shares:n,onCreate:r,onRevoke:a,status:i}){const[l,o]=N.useState("general"),[c,d]=N.useState("");return i!=="published"?e.jsx("div",{className:"text-[12.5px] text-slate-500 mt-3",children:"Publish this kit to generate share links."}):e.jsxs("div",{className:"mt-3 space-y-3",children:[e.jsxs("div",{className:"grid grid-cols-1 gap-2",children:[e.jsxs(Ns,{value:l,onValueChange:u=>o(u),children:[e.jsx(ws,{children:e.jsx(ks,{placeholder:"Choose agent"})}),e.jsxs(js,{children:[e.jsx(nt,{value:"general",children:"General share link"}),t.map(u=>e.jsxs(nt,{value:u.id,children:[u.first_name," ",u.last_name??""]},u.id))]})]}),e.jsx(Ws,{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(Md,{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 f;const h=WBt(u.share_token),m=u.agent_id?((f=t.find(g=>g.id===u.agent_id))==null?void 0:f.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(We,{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),ie.success("Link copied")},children:[e.jsx(Pa,{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(Tr,{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(o9,{className:"h-3.5 w-3.5 mr-1"}),"Revoke"]})]})]},u.id)})]})]})}const KIn={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 YIn(){const{kitId:s}=uo(),{data:t}=VBt(s),{shares:n}=HBt(s),{data:r=[]}=GBt(s),a=N.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=N.useMemo(()=>{const l=new Map;return r.forEach(o=>{const c=Js(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(Op,{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(cr,{to:`/attract/provide/kits/${s}/edit`,children:[e.jsx(ka,{className:"h-4 w-4 mr-1"}),"Edit"]})})}),e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-3 mb-6",children:[e.jsx(EC,{label:"Shares",value:a.shares,icon:da,tone:"violet"}),e.jsx(EC,{label:"Unique agents",value:a.uniqueAgents,icon:da,tone:"indigo"}),e.jsx(EC,{label:"View rate",value:`${a.viewRate}%`,icon:da,tone:"teal"}),e.jsx(EC,{label:"Engaged",value:a.engaged,icon:ru,tone:"emerald"}),e.jsx(EC,{label:"Downloads",value:a.downloads,icon:oi,tone:"orange"}),e.jsx(EC,{label:"CTA clicks",value:a.ctaClicks,icon:ru,tone:"rose"}),e.jsx(EC,{label:"Questions",value:a.questions,icon:Ud,tone:"violet"}),e.jsx(EC,{label:"Meetings",value:a.meetings,icon:df,tone:"indigo"})]}),e.jsxs("div",{className:"grid grid-cols-1 xl:grid-cols-3 gap-6",children:[e.jsxs(_e,{className:"p-5 rounded-2xl xl:col-span-2",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-widest text-violet-700 font-semibold mb-2",children:"Engagement over time"}),e.jsx("div",{className:"h-64",children:e.jsx(b5,{width:"100%",height:"100%",children:e.jsxs(nGe,{data:i,children:[e.jsx(tGe,{strokeDasharray:"3 3",stroke:"#eee"}),e.jsx(R5,{dataKey:"date",fontSize:11}),e.jsx(O5,{fontSize:11,allowDecimals:!1}),e.jsx(Vx,{}),e.jsx(eO,{type:"monotone",dataKey:"count",stroke:"#7c3aed",strokeWidth:2})]})})})]}),e.jsxs(_e,{className:"p-5 rounded-2xl",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-widest text-violet-700 font-semibold mb-2",children:"By event type"}),e.jsx("div",{className:"space-y-2",children:Object.entries(KIn).map(([l,o])=>{const c=r.filter(d=>d.event_type===l).length;return e.jsxs("div",{className:"flex justify-between text-[13px]",children:[e.jsx("span",{className:"text-slate-600",children:o}),e.jsx("span",{className:"font-semibold tabular-nums",children:c})]},l)})})]})]}),e.jsxs(_e,{className:"p-5 rounded-2xl mt-6",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-widest text-violet-700 font-semibold mb-3",children:"Recipients"}),e.jsxs("div",{className:"space-y-2",children:[n.length===0&&e.jsx("div",{className:"text-sm text-slate-500",children:"No one has been shared this kit yet."}),n.map(l=>e.jsxs("div",{className:"flex items-center justify-between border-b py-2 text-[13px]",children:[e.jsxs("div",{children:[e.jsx("div",{className:"font-medium",children:l.agent_id?"Personalized":"General link"}),e.jsxs("div",{className:"text-slate-500 text-[11.5px]",children:["Created ",Js(new Date(l.created_at),"MMM d")," · ",l.open_count," opens",l.last_opened_at&&` · last opened ${Js(new Date(l.last_opened_at),"MMM d")}`]})]}),e.jsx(We,{variant:"secondary",className:"capitalize",children:l.engagement_level.replace("_"," ")})]},l.id))]})]})]})}function EC({label:s,value:t,icon:n,tone:r}){const a={violet:"text-violet-700 bg-violet-50",indigo:"text-indigo-700 bg-indigo-50",teal:"text-teal-700 bg-teal-50",emerald:"text-emerald-700 bg-emerald-50",orange:"text-orange-700 bg-orange-50",rose:"text-rose-700 bg-rose-50"};return e.jsxs(_e,{className:"p-4 rounded-2xl",children:[e.jsx("div",{className:`h-8 w-8 rounded-lg grid place-items-center ${a[r]}`,children:e.jsx(n,{className:"h-4 w-4"})}),e.jsx("div",{className:"mt-2 text-[22px] font-semibold tabular-nums",children:t}),e.jsx("div",{className:"text-[11.5px] text-slate-500",children:s})]})}function ZIn(){const{data:s=[],isLoading:t}=SPn(),n=CPn(),r=tr(),a=async i=>{try{const l=await n.mutateAsync(i);ie.success("Added to your drafts"),r(`/attract/provide/kits/${l}/edit`)}catch(l){ie.error(l.message??"Could not clone template")}};return e.jsxs("div",{children:[e.jsx(Op,{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(cr,{to:"/attract/provide/kits",children:[e.jsx(ka,{className:"h-4 w-4 mr-2"}),"Back to my kits"]})})}),t&&e.jsx("div",{className:"text-slate-500 text-sm",children:"Loading templates…"}),e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 xl:grid-cols-3 gap-4",children:s.map(i=>{var l;return e.jsxs(_e,{className:"p-6 rounded-2xl border-slate-200 bg-white flex flex-col",children:[e.jsxs("div",{className:"flex items-center gap-2 text-[10.5px] uppercase tracking-widest text-violet-700 font-semibold",children:[e.jsx(Cn,{className:"h-3.5 w-3.5"})," Starter kit"]}),e.jsx("div",{className:"mt-2 text-[17px] font-semibold text-slate-900",children:i.title}),i.audience&&e.jsxs("div",{className:"text-[12px] text-slate-500 mt-0.5",children:["For ",i.audience]}),e.jsx("p",{className:"text-[13px] text-slate-600 mt-2 line-clamp-3",children:i.description}),e.jsxs("div",{className:"mt-3 flex flex-wrap gap-1",children:[i.pillar&&e.jsx(We,{variant:"outline",className:"capitalize",children:i.pillar}),(i.tags??[]).slice(0,4).map(o=>e.jsxs(We,{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(Zg,{className:"h-4 w-4 mr-2"}),"Use this kit"]})]},i.id)})})]})}const g0t={call:{icon:ga,label:"Call"},text:{icon:xo,label:"Text"},email:{icon:mn,label:"Email"},dm:{icon:Rr,label:"DM"},resource_share:{icon:rb,label:"Share a kit"},event_invitation:{icon:Pv,label:"Invite to event"},personal_check_in:{icon:pD,label:"Personal check-in"}},x0t={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 XIn(s){var t;return((t=TBt.find(n=>n.key===s))==null?void 0:t.blurb)??""}function p$t(s){var t;return((t=TBt.find(n=>n.key===s))==null?void 0:t.label)??s.replace(/_/g," ")}function Jze({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}=MBt(),[f,g]=N.useState(!1),[y,x]=N.useState(s.draft_message??""),_=c.isPending||d.isPending||u.isPending||h.isPending||m.isPending,b=g0t[s.channel]??g0t.personal_check_in,k=s.suggested_due_at?new Date(s.suggested_due_at):null,A=k?k{c.mutate({id:s.id,patch:{draft_message:y}},{onSuccess:()=>{g(!1),ie.success("Opening message updated")}})},P=async()=>{try{await navigator.clipboard.writeText(s.draft_message??""),ie.success("Opening message copied — send it yourself from your phone or inbox")}catch{ie.error("Could not copy — select the text manually")}};return e.jsx(_e,{className:Ot("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(We,{variant:"outline",className:Ot("rounded-full text-[10.5px] uppercase tracking-wider font-semibold ring-1 border-transparent",x0t[s.priority]??x0t.medium),children:s.priority}),e.jsx("span",{className:"text-[11px] text-violet-700 font-medium",children:p$t(s.signal_group)}),s.is_demo&&e.jsx(We,{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(cr,{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(Qa,{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]}),k&&e.jsxs("span",{className:Ot("inline-flex items-center gap-1",A?"text-rose-600 font-medium":""),children:["· ",e.jsx(Xr,{className:"h-3 w-3"})," ",A?"Due now":`Do by ${k.toLocaleDateString()}`]})]})]}),e.jsxs(qd,{children:[e.jsx(Vd,{asChild:!0,children:e.jsx(B,{variant:"ghost",size:"icon",className:"rounded-full","aria-label":"More recommendation actions",children:e.jsx(Ev,{className:"h-4 w-4"})})}),e.jsxs(Ld,{align:"end",className:"w-56",children:[e.jsx(cE,{children:"Recommendation"}),e.jsx(s1,{}),e.jsxs(ba,{onClick:()=>g(I=>!I),children:[e.jsx(Ja,{className:"h-4 w-4 mr-2"})," Edit opening message"]}),e.jsxs(ba,{onClick:P,children:[e.jsx(Pa,{className:"h-4 w-4 mr-2"})," Copy message"]}),e.jsx(s1,{}),e.jsxs(ba,{onClick:()=>u.mutate({id:s.id,days:3}),children:[e.jsx(Xr,{className:"h-4 w-4 mr-2"})," Snooze 3 days"]}),e.jsxs(ba,{onClick:()=>u.mutate({id:s.id,days:7}),children:[e.jsx(Xr,{className:"h-4 w-4 mr-2"})," Snooze 1 week"]}),e.jsxs(ba,{className:"text-rose-600",onClick:()=>d.mutate(s.id),children:[e.jsx(hr,{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(p5,{className:"h-3 w-3"})," Why this, right now"]}),e.jsx("ul",{className:"space-y-1",children:s.reasons.map((I,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:I})]},M))}),e.jsx("div",{className:"text-[11px] text-slate-400 mt-2",children:XIn(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"}),f?e.jsxs("div",{className:"space-y-2",children:[e.jsx(Ws,{value:y,onChange:I=>x(I.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:T,disabled:_,children:"Save message"}),e.jsx(B,{size:"sm",variant:"ghost",className:"rounded-full",onClick:()=>{x(s.draft_message??""),g(!1)},children:"Cancel"})]})]}):e.jsxs("button",{onClick:()=>g(!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:_,onClick:()=>m.mutate({rec:s}),children:[e.jsx(pa,{className:"h-3.5 w-3.5 mr-1.5"})," I did this"]}),e.jsxs(B,{size:"sm",variant:"outline",className:"rounded-full",disabled:_,onClick:()=>h.mutate(s),children:[e.jsx(Pv,{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:P,children:[e.jsx(Pa,{className:"h-3.5 w-3.5 mr-1.5"})," Copy message"]})]}),e.jsx("div",{className:"text-[10.5px] text-slate-400 mt-2",children:"Attract never sends messages for you — copy the opening and send it from your own phone or inbox."})]})})}function QIn({label:s="Nothing needs attention right now."}){return e.jsxs(_e,{className:"rounded-2xl border-dashed border-slate-300 bg-white/60 p-8 text-center",children:[e.jsx("div",{className:"h-11 w-11 rounded-2xl bg-emerald-50 text-emerald-600 grid place-items-center mx-auto mb-3",children:e.jsx(pa,{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 JIn=H,e8n=["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"],t8n={hot:Cu,warm:J2,cold:nj},AH=({label:s})=>e.jsxs("span",{className:"text-slate-400 italic",children:["Not recorded",s?` — add ${s}`:""]}),MC=s=>[s.first_name,s.last_name].filter(Boolean).join(" "),s8n=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 KF({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 n8n={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 r8n(){const{agentId:s}=uo(),t=tr(),{item:n,timeline:r,valueShared:a,nextKit:i,isLoading:l,error:o,refetch:c}=OLn(s),{data:d=[]}=IKe(),{upsertAgent:u,moveStage:h}=jb(),{followUps:m,complete:f}=OJ(),g=FLn(),{gmailEmail:y}=_f(),[x,_]=N.useState("all"),[b,k]=N.useState(!1),[A,T]=N.useState(!1),[P,I]=N.useState("call"),[M,L]=N.useState(""),[z,$]=N.useState(""),[V,W]=N.useState(!1),[G,X]=N.useState(""),[te,ne]=N.useState(!1),[me,ue]=N.useState(""),[ce,ae]=N.useState(new Date(Date.now()+3*864e5).toISOString().slice(0,10)),[he,xe]=N.useState(null),[ve,ge]=N.useState(!1),be=N.useMemo(()=>d.filter(Ae=>Ae.agent_id===s&&Ae.status==="open").sort((Ae,Xe)=>Xe.rank_score-Ae.rank_score),[d,s]),Se=N.useMemo(()=>m.filter(Ae=>Ae.agent_id===s),[m,s]),Ie=N.useMemo(()=>{const Ae=Xxt.find(Xe=>Xe.key===x);return!Ae||!Ae.kinds.length?r:r.filter(Xe=>Ae.kinds.includes(Xe.kind))},[r,x]);if(l)return e.jsxs("div",{className:"space-y-4",children:[e.jsx(xn,{className:"h-8 w-40"}),e.jsx(xn,{className:"h-40 w-full rounded-2xl"}),e.jsx(xn,{className:"h-64 w-full rounded-2xl"})]});if(o)return e.jsxs(_e,{className:"p-8 rounded-2xl text-center",children:[e.jsx("div",{className:"text-[15px] font-semibold text-slate-800",children:"We couldn't load this relationship."}),e.jsx("div",{className:"text-[13px] text-slate-500 mt-1",children:o.message}),e.jsxs(B,{className:"rounded-full mt-4",onClick:()=>c(),children:[e.jsx(oo,{className:"h-4 w-4 mr-2"})," Try again"]})]});if(!n)return e.jsxs(_e,{className:"p-8 rounded-2xl text-center",children:[e.jsx("div",{className:"text-[15px] font-semibold text-slate-800",children:"Agent not found"}),e.jsx("div",{className:"text-[13px] text-slate-500 mt-1",children:"This relationship may have been removed from your pipeline."}),e.jsx(B,{className:"rounded-full mt-4",onClick:()=>t("/attract/pipeline"),children:"Back to pipeline"})]});const Me=n.agent,Re=n.signals,Be=t8n[Me.temperature??""]??J2,Ne=()=>{g.mutate({agent_id:Me.id,activity_type:P,title:M||`${P.replace(/_/g," ")} with ${MC(Me)}`,description:z||void 0},{onSuccess:()=>{k(!1),L(""),$("")}})},Ge=async()=>{var Xe;if(!G.trim())return;const Ae=[(Xe=Me.notes)==null?void 0:Xe.trim(),`[${new Date().toLocaleDateString()}] ${G.trim()}`].filter(Boolean).join(` `);u.mutate({id:Me.id,first_name:Me.first_name,notes:Ae},{onSuccess:()=>{W(!1),X(""),c()}}),g.mutate({agent_id:Me.id,activity_type:"note",title:"Note added",description:G.trim()})},Ce=async()=>{if(!me.trim()){ie.error("Give the follow-up a title");return}if(Se.find(Ye=>!Ye.completed_at&&Ye.title.trim().toLowerCase()===me.trim().toLowerCase())){ie.error("An open follow-up with that title already exists");return}const{data:Xe}=await H.auth.getUser(),{error:$e}=await JIn.from("attract_follow_ups").insert({user_id:Xe.user.id,agent_id:Me.id,title:me.trim(),due_at:new Date(`${ce}T12:00:00`).toISOString(),touch_type:"call",priority:"medium"});if($e){ie.error($e.message);return}ie.success("Follow-up created"),ne(!1),ue(""),c()},Fe=()=>{he&&(window.open(he.href,"_self"),g.mutate({agent_id:Me.id,activity_type:he.kind,title:`${he.kind==="call"?"Called":he.kind==="text"?"Texted":"Emailed"} ${MC(Me)}`}),xe(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(cr,{to:"/attract",className:"hover:text-violet-700",children:"Attract"}),e.jsx(Qa,{className:"h-3 w-3"}),e.jsx(cr,{to:"/attract/pipeline",className:"hover:text-violet-700",children:"Pipeline"}),e.jsx(Qa,{className:"h-3 w-3"}),e.jsx("span",{className:"text-slate-800 font-medium truncate",children:MC(Me)})]}),e.jsxs(_e,{className:"rounded-2xl border-slate-200/70 overflow-hidden",children:[e.jsxs("div",{className:"bg-gradient-to-r from-[#0B0F1E] via-[#141a33] to-[#1d1b4b] p-5 sm:p-6 text-white",children:[e.jsxs(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:[Me.photo_url?e.jsx("img",{src:Me.photo_url,alt:`${MC(Me)} headshot`,className:"h-16 w-16 rounded-2xl object-cover ring-2 ring-white/20"}):e.jsx("div",{className:"h-16 w-16 rounded-2xl bg-gradient-to-br from-violet-500 to-indigo-600 grid place-items-center text-xl font-semibold ring-2 ring-white/10",children:s8n(Me)}),e.jsxs("div",{className:"flex-1 min-w-[220px]",children:[e.jsx("h1",{className:"text-2xl font-semibold tracking-tight",children:MC(Me)}),e.jsxs("div",{className:"text-[13px] text-slate-300 mt-1 flex flex-wrap items-center gap-x-2 gap-y-1",children:[e.jsx("span",{children:Me.brokerage||"Brokerage not recorded"}),e.jsx("span",{className:"opacity-40",children:"·"}),e.jsx("span",{children:[Me.city,Me.state].filter(Boolean).join(", ")||"Market not recorded"}),Me.is_demo&&e.jsx(We,{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(We,{className:"rounded-full bg-white/10 text-white border-transparent capitalize",children:Me.stage.replace(/_/g," ")}),e.jsxs(We,{className:"rounded-full bg-white/10 text-white border-transparent capitalize inline-flex items-center gap-1",children:[e.jsx(Be,{className:"h-3 w-3"})," ",Me.temperature??"temperature unset"]}),e.jsx(RKe,{score:n.score,className:"bg-white/10 text-white ring-white/20"}),(Me.tags??[]).map(Ae=>e.jsx(We,{variant:"outline",className:"rounded-full bg-transparent text-slate-200 border-white/20",children:Ae},Ae))]})]}),e.jsxs("div",{className:"text-[12px] text-slate-300 space-y-1 min-w-[190px]",children:[e.jsx("div",{children:Me.email?e.jsx("a",{className:"hover:text-white underline decoration-white/30",href:`mailto:${Me.email}`,children:Me.email}):"No email on file"}),e.jsx("div",{children:Me.phone?e.jsx("a",{className:"hover:text-white underline decoration-white/30",href:`tel:${Me.phone}`,children:Me.phone}):"No phone on file"}),e.jsxs("div",{children:["Last meaningful touch: ",Re.lastTouchAt?`${new Date(Re.lastTouchAt).toLocaleDateString()} (${Re.daysSinceTouch}d ago)`:"never logged"]}),e.jsxs("div",{children:["Next follow-up: ",Me.next_follow_up_at?new Date(Me.next_follow_up_at).toLocaleDateString():"none scheduled"]}),e.jsxs("div",{children:["Source: ",Me.source||"not recorded"," · Owner: ",Me.relationship_owner||"you"]})]})]})]}),e.jsxs("div",{className:"p-3 sm:p-4 bg-white flex flex-wrap gap-2",children:[e.jsxs(B,{size:"sm",variant:"outline",className:"rounded-full",onClick:()=>T(!0),children:[e.jsx(Ja,{className:"h-3.5 w-3.5 mr-1.5"})," Edit contact"]}),e.jsxs(Bs,{open:b,onOpenChange:k,children:[e.jsx(Ao,{asChild:!0,children:e.jsxs(B,{size:"sm",className:"rounded-full btn-primary text-white",children:[e.jsx(Hr,{className:"h-3.5 w-3.5 mr-1.5"})," Log touch"]})}),e.jsxs(Fs,{children:[e.jsxs(qs,{children:[e.jsx($s,{children:"Log a conversation"}),e.jsx(Ar,{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(re,{children:"Type"}),e.jsxs(Ns,{value:P,onValueChange:I,children:[e.jsx(ws,{children:e.jsx(ks,{})}),e.jsx(js,{children:["call","text","email","dm","meeting","note"].map(Ae=>e.jsx(nt,{value:Ae,className:"capitalize",children:Ae},Ae))})]})]}),e.jsxs("div",{children:[e.jsx(re,{children:"Title"}),e.jsx(we,{value:M,onChange:Ae=>L(Ae.target.value),placeholder:`Call with ${Me.first_name}`})]}),e.jsxs("div",{children:[e.jsx(re,{children:"What happened"}),e.jsx(Ws,{rows:4,value:z,onChange:Ae=>$(Ae.target.value)})]})]}),e.jsx(Cr,{children:e.jsx(B,{className:"rounded-full btn-primary text-white",onClick:Ne,disabled:g.isPending,children:"Log it"})})]})]}),e.jsxs(Bs,{open:V,onOpenChange:W,children:[e.jsx(Ao,{asChild:!0,children:e.jsxs(B,{size:"sm",variant:"outline",className:"rounded-full",children:[e.jsx(_W,{className:"h-3.5 w-3.5 mr-1.5"})," Add note"]})}),e.jsxs(Fs,{children:[e.jsx(qs,{children:e.jsx($s,{children:"Add a relationship note"})}),e.jsx(Ws,{rows:5,value:G,onChange:Ae=>X(Ae.target.value),placeholder:"What did you learn about them?"}),e.jsx(Cr,{children:e.jsx(B,{className:"rounded-full btn-primary text-white",onClick:Ge,children:"Save note"})})]})]}),e.jsxs(B,{size:"sm",variant:"outline",className:"rounded-full",disabled:!Me.phone,onClick:()=>Me.phone&&xe({kind:"call",href:`tel:${Me.phone}`}),children:[e.jsx(ga,{className:"h-3.5 w-3.5 mr-1.5"})," Call"]}),e.jsxs(B,{size:"sm",variant:"outline",className:"rounded-full",disabled:!Me.phone,onClick:()=>Me.phone&&xe({kind:"text",href:`sms:${Me.phone}`}),children:[e.jsx(xo,{className:"h-3.5 w-3.5 mr-1.5"})," Text"]}),e.jsxs(B,{size:"sm",variant:"outline",className:"rounded-full",disabled:!Me.email,onClick:()=>Me.email&&ge(!0),children:[e.jsx(mn,{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(cr,{to:"/attract/provide/kits",children:[e.jsx(rb,{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(cr,{to:"/attract/events",children:[e.jsx(Pv,{className:"h-3.5 w-3.5 mr-1.5"})," Invite to event"]})}),e.jsxs(Bs,{open:te,onOpenChange:ne,children:[e.jsx(Ao,{asChild:!0,children:e.jsxs(B,{size:"sm",variant:"outline",className:"rounded-full",children:[e.jsx(Xr,{className:"h-3.5 w-3.5 mr-1.5"})," Create follow-up"]})}),e.jsxs(Fs,{children:[e.jsx(qs,{children:e.jsx($s,{children:"Create a follow-up"})}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{children:[e.jsx(re,{children:"What will you do?"}),e.jsx(we,{value:me,onChange:Ae=>ue(Ae.target.value),placeholder:"Call about their Q3 goals"})]}),e.jsxs("div",{children:[e.jsx(re,{children:"Due"}),e.jsx(we,{type:"date",value:ce,onChange:Ae=>ae(Ae.target.value)})]})]}),e.jsx(Cr,{children:e.jsx(B,{className:"rounded-full btn-primary text-white",onClick:Ce,children:"Create"})})]})]}),e.jsxs(Ns,{value:Me.stage,onValueChange:Ae=>h.mutate({id:Me.id,to_stage:Ae,from_stage:Me.stage}),children:[e.jsxs(ws,{className:"w-[210px] h-9 rounded-full text-[13px]","aria-label":"Change stage",children:[e.jsx(c5,{className:"h-3.5 w-3.5 mr-1.5 opacity-60"}),e.jsx(ks,{})]}),e.jsx(js,{children:e8n.map(Ae=>e.jsx(nt,{value:Ae,className:"capitalize",children:Ae.replace(/_/g," ")},Ae))})]})]})]}),e.jsx(Bs,{open:!!he,onOpenChange:Ae=>!Ae&&xe(null),children:e.jsxs(Fs,{children:[e.jsxs(qs,{children:[e.jsxs($s,{children:["Open your ",(he==null?void 0:he.kind)==="email"?"email app":(he==null?void 0:he.kind)==="text"?"messaging app":"phone app","?"]}),e.jsx(Ar,{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(Cr,{children:[e.jsx(B,{variant:"ghost",className:"rounded-full",onClick:()=>xe(null),children:"Cancel"}),e.jsx(B,{className:"rounded-full btn-primary text-white",onClick:Fe,children:"Continue"})]})]})}),e.jsxs(ya,{defaultValue:"overview",children:[e.jsx(va,{className:"rounded-full bg-white border border-slate-200 p-1 flex-wrap h-auto",children:["overview","timeline","value","events","followups","notes"].map(Ae=>e.jsx(ls,{value:Ae,className:"rounded-full text-[13px] capitalize data-[state=active]:bg-violet-600 data-[state=active]:text-white",children:Ae==="value"?"Value shared":Ae==="followups"?"Follow-ups":Ae==="notes"?"Notes & insights":Ae},Ae))}),e.jsxs(_s,{value:"overview",className:"mt-5 space-y-5",children:[e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-3 gap-5",children:[e.jsxs("div",{className:"lg:col-span-2 space-y-5",children:[e.jsxs(_e,{className:"p-5 rounded-2xl",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-wider font-semibold text-violet-600 mb-3",children:"Next best relationship touch"}),be[0]?e.jsx(Jze,{rec:be[0],agentName:MC(Me),agentStage:Me.stage,showAgentLink:!1,className:"border-0 shadow-none"}):e.jsx("div",{className:"text-[13.5px] text-slate-500",children:"No open recommendation right now. Recommendations appear when real signals exist — a kit opened, an event attended, an overdue commitment, or silence beyond your cadence."})]}),e.jsxs(_e,{className:"p-5 rounded-2xl",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-wider font-semibold text-slate-500 mb-3",children:"What we actually know"}),e.jsxs("div",{className:"grid sm:grid-cols-2 gap-4",children:[e.jsx(KF,{label:"Goals",children:Me.goals||e.jsx(AH,{label:"their goals"})}),e.jsx(KF,{label:"Challenges",children:Me.challenges||e.jsx(AH,{label:"their challenges"})}),e.jsx(KF,{label:"Interests",children:Me.interests||e.jsx(AH,{label:"interests"})}),e.jsx(KF,{label:"Production context",children:Me.production_context||e.jsx(AH,{label:"production context"})}),e.jsx(KF,{label:"Primary pillar",children:Me.primary_pillar?e.jsx("span",{className:"capitalize",children:Me.primary_pillar}):e.jsx(AH,{label:"a pillar"})}),e.jsx(KF,{label:"Added to pipeline",children:new Date(Me.created_at).toLocaleDateString()})]})]}),e.jsx("div",{className:"grid sm:grid-cols-2 lg:grid-cols-4 gap-3",children:[{label:"Touches (90d)",value:Re.touches90},{label:"Kits shared",value:Re.shares.length},{label:"Kit opens",value:Re.totalKitOpens},{label:"Events attended",value:Re.attended}].map(Ae=>e.jsxs(_e,{className:"p-4 rounded-2xl",children:[e.jsx("div",{className:"text-2xl font-semibold tabular-nums text-slate-900",children:Ae.value}),e.jsx("div",{className:"text-[11.5px] text-slate-500 mt-0.5",children:Ae.label})]},Ae.label))})]}),e.jsxs(_e,{className:"p-5 rounded-2xl h-fit",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-wider font-semibold text-slate-500 mb-3",children:"Relationship health"}),e.jsx(LBt,{score:n.score})]})]}),be.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"}),be.slice(1).map(Ae=>e.jsx(Jze,{rec:Ae,agentName:MC(Me),showAgentLink:!1,compact:!0},Ae.id))]})]}),e.jsx(_s,{value:"timeline",className:"mt-5",children:e.jsxs(_e,{className:"p-4 sm:p-5 rounded-2xl",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3 flex-wrap mb-4",children:[e.jsx("div",{className:"flex gap-1.5 flex-wrap",children:Xxt.map(Ae=>e.jsx("button",{onClick:()=>_(Ae.key),className:Ot("rounded-full px-3 py-1.5 text-[12px] font-medium transition-colors",x===Ae.key?"bg-violet-600 text-white":"bg-slate-100 text-slate-600 hover:bg-slate-200"),children:Ae.label},Ae.key))}),e.jsxs(B,{size:"sm",className:"rounded-full btn-primary text-white",onClick:()=>k(!0),children:[e.jsx(Hr,{className:"h-3.5 w-3.5 mr-1.5"})," Log something"]})]}),Ie.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"}),Ie.map(Ae=>e.jsxs("li",{className:"relative pb-5",children:[e.jsx("span",{"aria-hidden":!0,className:Ot("absolute -left-[15px] sm:-left-[18px] top-1.5 h-2.5 w-2.5 rounded-full ring-2 ring-white",n8n[Ae.kind]??"bg-slate-300")}),e.jsx("div",{className:"text-[13.5px] font-medium text-slate-900",children:Ae.title}),Ae.detail&&e.jsx("div",{className:"text-[12.5px] text-slate-600 mt-0.5 whitespace-pre-wrap",children:Ae.detail}),e.jsxs("div",{className:"text-[11px] text-slate-400 mt-1",children:[new Date(Ae.at).toLocaleString()," · ",e.jsx("span",{className:"capitalize",children:Ae.kind.replace(/_/g," ")})]})]},Ae.id))]}):e.jsx("div",{className:"py-10 text-center text-[13.5px] text-slate-500",children:"Nothing in this view yet. Log a conversation to start the history."})]})}),e.jsxs(_s,{value:"value",className:"mt-5 space-y-4",children:[i&&e.jsxs(_e,{className:"p-4 rounded-2xl bg-gradient-to-r from-teal-50 to-emerald-50 border-teal-100",children:[e.jsx("div",{className:"text-[10.5px] uppercase tracking-wider font-semibold text-teal-700",children:"Suggested next kit"}),e.jsx("div",{className:"text-[15px] font-semibold text-slate-900 mt-1",children:i.kit.title}),e.jsx("div",{className:"text-[12.5px] text-slate-600 mt-0.5",children:i.why}),e.jsx(B,{size:"sm",className:"rounded-full mt-3 btn-primary text-white",asChild:!0,children:e.jsx(cr,{to:"/attract/provide/kits",children:"Open Resource Kits"})})]}),a.length?a.map(Ae=>e.jsxs(_e,{className:"p-4 sm:p-5 rounded-2xl",children:[e.jsxs("div",{className:"flex items-start justify-between gap-3 flex-wrap",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[15px] font-semibold text-slate-900",children:Ae.kitTitle}),e.jsxs("div",{className:"text-[12px] text-slate-500 mt-0.5",children:["Sent ",new Date(Ae.share.created_at).toLocaleDateString()," ·",Ae.firstViewedAt?` first viewed ${new Date(Ae.firstViewedAt).toLocaleDateString()}`:" never viewed",Ae.lastViewedAt?` · last viewed ${new Date(Ae.lastViewedAt).toLocaleDateString()}`:""]})]}),e.jsx(We,{variant:"outline",className:Ot("rounded-full border-transparent ring-1",Ae.classification==="High Intent"?"bg-rose-50 text-rose-700 ring-rose-200":Ae.classification==="Engaged"?"bg-teal-50 text-teal-700 ring-teal-200":Ae.classification==="Viewed"?"bg-amber-50 text-amber-700 ring-amber-200":"bg-slate-50 text-slate-600 ring-slate-200"),children:Ae.classification})]}),e.jsx("div",{className:"grid grid-cols-2 sm:grid-cols-5 gap-3 mt-4",children:[["Visits",Ae.visits],["Downloads",Ae.downloads],["Link clicks",Ae.ctaClicks],["Questions",Ae.questions],["Meeting asks",Ae.meetingRequests]].map(([Xe,$e])=>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:$e}),e.jsx("div",{className:"text-[10.5px] text-slate-500",children:Xe})]},Xe))}),e.jsxs("div",{className:"mt-3 text-[12.5px] text-slate-600 space-y-1",children:[e.jsxs("div",{children:["Link status: ",e.jsx("span",{className:"capitalize font-medium",children:Ae.share.status})]}),e.jsxs("div",{children:["Follow-up after sharing: ",Ae.followUp?`${Ae.followUp.title}${Ae.followUp.completed_at?" (completed)":" (open)"}`:"none created"]}),e.jsxs("div",{children:["Stage movement after sharing: ",Ae.stageAdvancedAfter?`moved to ${Ae.stageAdvancedAfter.to_stage.replace(/_/g," ")} on ${new Date(Ae.stageAdvancedAfter.created_at).toLocaleDateString()}`:"no stage movement yet"]})]}),e.jsx(B,{size:"sm",variant:"outline",className:"rounded-full mt-3",asChild:!0,children:e.jsxs("a",{href:Ae.shareUrl,target:"_blank",rel:"noreferrer",children:["Open share link ",e.jsx(Tr,{className:"h-3.5 w-3.5 ml-1.5"})]})})]},Ae.share.id)):e.jsxs(_e,{className:"p-8 rounded-2xl text-center",children:[e.jsx("div",{className:"text-[15px] font-semibold text-slate-800",children:"Nothing shared yet"}),e.jsx("div",{className:"text-[13px] text-slate-500 mt-1",children:"Value first is how this whole system works. Share a Resource Kit to begin."})]})]}),e.jsx(_s,{value:"events",className:"mt-5 space-y-3",children:Re.attendees.length?Re.attendees.map(Ae=>e.jsx(_e,{className:"p-4 rounded-2xl",children:e.jsxs("div",{className:"flex items-center justify-between gap-3 flex-wrap",children:[e.jsxs("div",{children:[e.jsx(cr,{to:`/attract/events/${Ae.event_id}`,className:"text-[14.5px] font-semibold text-slate-900 hover:text-violet-700",children:"View event"}),e.jsxs("div",{className:"text-[12px] text-slate-500 mt-0.5",children:[Ae.invited_at&&`Invited ${new Date(Ae.invited_at).toLocaleDateString()} · `,Ae.registered_at?`Registered ${new Date(Ae.registered_at).toLocaleDateString()}`:"Not registered",Ae.checked_in_at&&` · Attended ${new Date(Ae.checked_in_at).toLocaleDateString()}`,Ae.no_show_at&&" · No-show"]})]}),e.jsx(We,{variant:"outline",className:"rounded-full capitalize",children:Ae.followup_status?`follow-up ${Ae.followup_status}`:Ae.status??"invited"})]})},Ae.id)):e.jsxs(_e,{className:"p-8 rounded-2xl text-center",children:[e.jsx(f_,{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(cr,{to:"/attract/events",children:"See your events"})})]})}),e.jsx(_s,{value:"followups",className:"mt-5 space-y-3",children:Se.length?Se.map(Ae=>{const Xe=!Ae.completed_at&&Ae.due_at&&new Date(Ae.due_at)f.mutate(Ae.id),children:[e.jsx(Hr,{className:"h-3.5 w-3.5 mr-1.5"})," Complete"]})]},Ae.id)}):e.jsxs(_e,{className:"p-8 rounded-2xl text-center",children:[e.jsx("div",{className:"text-[15px] font-semibold text-slate-800",children:"No follow-ups yet"}),e.jsx(B,{size:"sm",className:"rounded-full mt-4 btn-primary text-white",onClick:()=>ne(!0),children:"Create one"})]})}),e.jsxs(_s,{value:"notes",className:"mt-5 space-y-4",children:[e.jsxs(_e,{className:"p-5 rounded-2xl",children:[e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-wider font-semibold text-slate-500",children:"Your notes"}),e.jsx(B,{size:"sm",variant:"outline",className:"rounded-full",onClick:()=>W(!0),children:"Add note"})]}),Me.notes?e.jsx("div",{className:"text-[13.5px] text-slate-700 whitespace-pre-wrap",children:Me.notes}):e.jsx("div",{className:"text-[13px] text-slate-500",children:"No notes recorded yet."})]}),e.jsxs(_e,{className:"p-5 rounded-2xl",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-wider font-semibold text-slate-500 mb-2",children:"What the data says"}),e.jsx("ul",{className:"text-[13px] text-slate-700 space-y-1.5 list-disc pl-4",children:[...n.score.positives.map(Ae=>`Strength: ${Ae}`),...n.score.negatives.map(Ae=>`Risk: ${Ae}`),...n.score.improvements.map(Ae=>`Next: ${Ae}`)].map((Ae,Xe)=>e.jsx("li",{children:Ae},Xe))})]})]})]}),e.jsx(UBt,{agent:Me,open:A,onOpenChange:T,onDeleted:()=>t("/attract/pipeline")}),Me.email&&e.jsx(Y_,{open:ve,onOpenChange:ge,contact:{id:Me.id,first_name:Me.preferred_name||Me.first_name,last_name:Me.last_name||"",email:Me.email},gmailEmail:y,sendSource:"attract",logTouchpoint:!1,onSendComplete:()=>{g.mutate({agent_id:Me.id,activity_type:"email",title:`Emailed ${MC(Me)}`})}})]})}const a8n=[{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 i8n(){const{intel:s,byId:t,isLoading:n,error:r,refetch:a}=gO(),{data:i=[],isLoading:l}=IKe(),o=DKe();PBt();const[c,d]=N.useState(""),[u,h]=N.useState("all"),[m,f]=N.useState("open"),g=_=>{var k;const b=(k=t.get(_))==null?void 0:k.agent;return b?[b.first_name,b.last_name].filter(Boolean).join(" "):"Unknown agent"},y=N.useMemo(()=>{const _=Date.now();return i.filter(b=>m==="open"?b.status==="open"||b.status==="snoozed"&&b.snoozed_until&&+new Date(b.snoozed_until)<=_: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 k=c.toLowerCase();return g(b.agent_id).toLowerCase().includes(k)||b.title.toLowerCase().includes(k)||(b.reasons??[]).join(" ").toLowerCase().includes(k)}).sort((b,k)=>k.rank_score-b.rank_score)},[i,m,u,c,t]),x=N.useMemo(()=>{const _=i.filter(b=>b.status==="open");return{open:_.length,urgent:_.filter(b=>b.priority==="urgent").length,highIntent:_.filter(b=>b.signal_group==="high_intent").length,overdue:_.filter(b=>b.suggested_due_at&&+new Date(b.suggested_due_at)e.jsx(xn,{className:"h-28 w-full rounded-2xl"},_))}):r?e.jsxs(_e,{className:"p-8 rounded-2xl text-center",children:[e.jsx("div",{className:"text-[15px] font-semibold text-slate-800",children:"We couldn't load your opportunities."}),e.jsx("div",{className:"text-[13px] text-slate-500 mt-1",children:r.message}),e.jsxs(B,{className:"rounded-full mt-4",onClick:()=>a(),children:[e.jsx(oo,{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(oo,{className:Ot("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:x.open},{label:"Urgent",value:x.urgent},{label:"High intent signals",value:x.highIntent},{label:"Past suggested date",value:x.overdue}].map(_=>e.jsxs(_e,{className:"p-4 rounded-2xl",children:[e.jsx("div",{className:"text-2xl font-semibold tabular-nums text-slate-900",children:_.value}),e.jsx("div",{className:"text-[11.5px] text-slate-500 mt-0.5",children:_.label})]},_.label))}),e.jsxs(_e,{className:"p-3 rounded-2xl flex flex-wrap items-center gap-2",children:[e.jsxs("div",{className:"relative flex-1 min-w-[220px]",children:[e.jsx(Gr,{className:"h-4 w-4 absolute left-3 top-1/2 -translate-y-1/2 text-slate-400"}),e.jsx(we,{value:c,onChange:_=>d(_.target.value),placeholder:"Search agents or reasons",className:"pl-9 rounded-full h-9","aria-label":"Search recommendations"})]}),e.jsxs(Ns,{value:u,onValueChange:h,children:[e.jsxs(ws,{className:"w-[190px] h-9 rounded-full text-[13px]",children:[e.jsx(cj,{className:"h-3.5 w-3.5 mr-1.5 opacity-60"}),e.jsx(ks,{})]}),e.jsx(js,{children:a8n.map(_=>e.jsx(nt,{value:_.key,children:_.label},_.key))})]}),e.jsxs(Ns,{value:m,onValueChange:f,children:[e.jsx(ws,{className:"w-[150px] h-9 rounded-full text-[13px]",children:e.jsx(ks,{})}),e.jsxs(js,{children:[e.jsx(nt,{value:"open",children:"Needs action"}),e.jsx(nt,{value:"snoozed",children:"Snoozed"}),e.jsx(nt,{value:"done",children:"Completed"}),e.jsx(nt,{value:"dismissed",children:"Dismissed"}),e.jsx(nt,{value:"all",children:"All"})]})]})]}),y.length?e.jsx("div",{className:"space-y-3",children:y.map(_=>{var b;return e.jsx(Jze,{rec:_,agentName:g(_.agent_id),agentStage:(b=t.get(_.agent_id))==null?void 0:b.agent.stage},_.id)})}):i.length?e.jsx(QIn,{label:"Nothing matches this view. Try switching the filter."}):e.jsxs(_e,{className:"p-10 rounded-2xl text-center",children:[e.jsx(Cn,{className:"h-6 w-6 mx-auto text-violet-500 mb-2"}),e.jsx("div",{className:"text-[15px] font-semibold text-slate-800",children:"No recommendations yet"}),e.jsx("p",{className:"text-[13px] text-slate-500 mt-1 max-w-md mx-auto",children:"Attract only recommends what it can prove. Add agents to your pipeline, share a Resource Kit, or invite someone to an event — real signals will show up here."}),e.jsxs("div",{className:"flex gap-2 justify-center mt-4",children:[e.jsx(B,{className:"rounded-full btn-primary text-white",asChild:!0,children:e.jsx(cr,{to:"/attract/pipeline",children:"Open pipeline"})}),e.jsx(B,{variant:"outline",className:"rounded-full",asChild:!0,children:e.jsx(cr,{to:"/attract/provide/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(_=>p$t(_.signal_group)))].join(", ")]})]})}const $Ie=s=>[s.first_name,s.last_name].filter(Boolean).join(" ");function o8n(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 f$t(s,t,n=new Date){const r=o8n(n),a=new Date(r.getTime()+6*864e5),i=new Date(n.getTime()-7*864e5),c=s.filter(M=>M.primary).slice().sort((M,L)=>L.primary.rank_score-M.primary.rank_score||M.score.score-L.score.score).slice(0,5).map((M,L)=>({agent_id:M.agent.id,agent_name:$Ie(M.agent),rank:L+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(L=>{const z=M(L);return z?{agent_id:L.agent.id,agent_name:$Ie(L.agent),detail:z}:null}).filter(Boolean).slice(0,8),u=d(M=>M.signals.meetingRequests>0||M.signals.questions>0||M.signals.highIntentShares.some(L=>L.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(L=>L.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),f=d(M=>M.signals.daysSinceTouch!==null&&M.signals.daysSinceTouch>60?`${M.signals.daysSinceTouch} days since a real conversation`:null),g=t.shares.filter(M=>new Date(M.created_at)>=i),y={shares:g.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},x={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,L)=>+new Date(M.starts_at)-+new Date(L.starts_at)).slice(0,3).map(M=>({title:M.title,starts_at:M.starts_at??null}))},_=[...s.filter(M=>M.agent.next_follow_up_at&&new Date(M.agent.next_follow_up_at)>n&&Hg(n,M.agent.next_follow_up_at)<=7).slice(0,5).map(M=>({label:$Ie(M.agent),detail:`Follow-up scheduled ${new Date(M.agent.next_follow_up_at).toLocaleDateString()}`})),...x.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),k={produce:0,influence:0,provide:0,connect:0};for(const M of b)M.pillar&&k[M.pillar]!==void 0&&k[M.pillar]++;const A=Object.entries(k).map(([M,L])=>({pillar:M,count:L})),T=A.slice().sort((M,L)=>M.count-L.count)[0],P=t.primaryPillar?`Your 90-day primary pillar is ${t.primaryPillar}. This week your lightest pillar was ${T.pillar} (${T.count} activities) — give it one deliberate rep.`:`Your lightest pillar this week was ${T.pillar} (${T.count} activities). Pick one action there.`,I={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:g.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:f,kit_summary:y,event_summary:x,upcoming_opportunities:_,pillar_balance:A,recommended_focus:P,wins:I}}function y0t(s,t){const n=l=>String(l??"").replace(/[<>&]/g,o=>({"<":"<",">":">","&":"&"})[o]),r=(l,o)=>o?`
${n(l)}
${o}`:"",a=l=>l.length?`
    ${l.map(o=>`
  • ${n(o.agent_name)} — ${n(o.detail)}
  • `).join("")}
`:"",i=s.conversations.map(l=>`
${l.rank}. ${n(l.agent_name)} ${n(l.channel.replace(/_/g," "))} health ${l.score}
Why: ${n(l.reason)}
${n(l.draft_message)}
Open relationship →
`).join("");return`
${r("Five conversations for this week",i||'
No recommended conversations yet — add agents to your pipeline.
')} ${r("High-intent signals",a(s.high_intent))} ${r("Renewed interest",a(s.renewed))} ${r("Overdue commitments",a(s.overdue))} ${r("Going quiet",a(s.stale))} ${r("Resource kit engagement",`
${s.kit_summary.shares} shared · ${s.kit_summary.opened} opened · ${s.kit_summary.engaged} engaged · ${s.kit_summary.high_intent} high intent · ${s.kit_summary.downloads} downloads · ${s.kit_summary.questions} questions
`)} ${r("Events",`
${s.event_summary.invited} invited · ${s.event_summary.registered} registered · ${s.event_summary.attended} attended · ${s.event_summary.no_shows} no-shows · ${s.event_summary.follow_ups_pending} follow-ups pending
`)} ${r("Four-pillar balance",`
${s.pillar_balance.map(l=>`${l.pillar}: ${l.count}`).join(" · ")}
${n(s.recommended_focus)}
`)} ${r("Wins this week",`
${s.wins.advanced} relationships advanced · ${s.wins.follow_ups_completed} follow-ups completed · ${s.wins.conversations_logged} conversations logged · ${s.wins.kits_shared} kits shared
`)}
LevelUp Attract
Your Weekly Attraction Digest
Week of ${s.week_start} → ${s.week_end}
Open Relationship Opportunities
`}const X4=H;function l8n(){const{user:s}=Ls(),t=as(),n=mt({queryKey:["attract-digest-settings",s==null?void 0:s.id],enabled:!!s,queryFn:async()=>{const{data:a,error:i}=await X4.from("attract_digest_settings").select("*").eq("user_id",s.id).maybeSingle();if(i)throw i;return a??null}}),r=_t({mutationFn:async a=>{const{error:i}=await X4.from("attract_digest_settings").upsert({user_id:s.id,...a},{onConflict:"user_id"});if(i)throw i},onSuccess:()=>{t.invalidateQueries({queryKey:["attract-digest-settings"]}),ie.success("Digest settings saved")},onError:a=>ie.error(a.message)});return{settings:n.data,isLoading:n.isLoading,save:r}}function c8n(){const{user:s}=Ls();return mt({queryKey:["attract-digests",s==null?void 0:s.id],enabled:!!s,queryFn:async()=>{const{data:t,error:n}=await X4.from("attract_digests").select("*").order("week_start",{ascending:!1}).limit(26);if(n)throw n;return t??[]}})}function d8n(s){const t=as(),n=mt({queryKey:["attract-digest-items",s],enabled:!!s,queryFn:async()=>{const{data:a,error:i}=await X4.from("attract_digest_items").select("*").eq("digest_id",s).order("rank");if(i)throw i;return a??[]}}),r=_t({mutationFn:async a=>{const{error:i}=await X4.from("attract_digest_items").update({completed_at:new Date().toISOString()}).eq("id",a);if(i)throw i},onSuccess:()=>{t.invalidateQueries({queryKey:["attract-digest-items",s]}),ie.success("Marked as done")}});return{items:n.data??[],isLoading:n.isLoading,markComplete:r}}function u8n(){const{user:s}=Ls(),t=as();return _t({mutationFn:async n=>{const{data:r,error:a}=await X4.from("attract_digests").upsert({user_id:s.id,week_start:n.week_start,payload:n,delivery_status:"generated",generated_at:n.generated_at},{onConflict:"user_id,week_start"}).select("id").single();if(a)throw a;const i=r.id;await X4.from("attract_digest_items").delete().eq("digest_id",i).is("completed_at",null);const{data:l}=await X4.from("attract_digest_items").select("agent_id").eq("digest_id",i),o=new Set((l??[]).map(d=>d.agent_id)),c=n.conversations.filter(d=>!o.has(d.agent_id)).map(d=>({digest_id:i,user_id:s.id,agent_id:d.agent_id,rank:d.rank,agent_name:d.agent_name,reason:d.reason,channel:d.channel,draft_message:d.draft_message}));if(c.length){const{error:d}=await X4.from("attract_digest_items").insert(c);if(d)throw d}return i},onSuccess:()=>{t.invalidateQueries({queryKey:["attract-digests"]}),t.invalidateQueries({queryKey:["attract-digest-items"]})},onError:n=>ie.error(n.message)})}function h8n(){const s=as();return _t({mutationFn:async t=>{const{data:n,error:r}=await H.functions.invoke("attract-send-digest",{body:t});if(r)throw r;return n},onSuccess:t=>{s.invalidateQueries({queryKey:["attract-digests"]}),t!=null&&t.ok?ie.success("Digest email sent"):ie.error((t==null?void 0:t.reason)||"Email delivery is not configured yet")},onError:t=>ie.error(t.message??"Send failed")})}const m8n=["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"];function YF({title:s,children:t}){return e.jsxs("div",{children:[e.jsx("div",{className:"text-[11px] uppercase tracking-wider font-semibold text-slate-500 mb-2",children:s}),t]})}function nre({rows:s,empty:t}){return s.length?e.jsx("ul",{className:"space-y-1.5",children:s.map(n=>e.jsxs("li",{className:"text-[13px] text-slate-700",children:[e.jsx(cr,{to:`/attract/agents/${n.agent_id}`,className:"font-medium text-slate-900 hover:text-violet-700",children:n.agent_name}),e.jsxs("span",{className:"text-slate-500",children:[" — ",n.detail]})]},n.agent_id+n.detail))}):e.jsx("div",{className:"text-[13px] text-slate-500",children:t})}function p8n(){var P;const{user:s}=Ls(),{intel:t,dataset:n,isLoading:r}=gO(),{settings:a,save:i}=l8n(),{data:l=[]}=c8n(),o=u8n(),c=h8n(),[d,u]=N.useState(),h=d??((P=l[0])==null?void 0:P.id),{items:m,markComplete:f}=d8n(h),[g,y]=N.useState(""),x=N.useMemo(()=>n?f$t(t,n):null,[t,n]),_=l.find(I=>I.id===h),b=(_==null?void 0:_.payload)??x,k=g||(a==null?void 0:a.email)||(s==null?void 0:s.email)||"",A=()=>{x&&o.mutate(x,{onSuccess:I=>{u(I),ie.success("This week's digest is ready")}})},T=I=>{if(!b)return;if(!k){ie.error("Add an email address first");return}const M=L=>c.mutate({digestId:L,to:k,subject:`Your Weekly Attraction Digest — ${b.week_start}`,html:y0t(b,window.location.origin),test:I});_?M(_.id):x&&o.mutate(x,{onSuccess:L=>{u(L),M(L)}})};return r||!b?e.jsxs("div",{className:"space-y-4",children:[e.jsx(xn,{className:"h-10 w-56"}),e.jsx(xn,{className:"h-72 w-full rounded-2xl"})]}):e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex items-end justify-between gap-4 flex-wrap",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[11.5px] uppercase tracking-wider font-medium text-violet-600",children:"Relationship Intelligence"}),e.jsx("h1",{className:"text-2xl font-semibold tracking-tight text-slate-900 mt-0.5",children:"Weekly Attraction Digest"}),e.jsxs("p",{className:"text-[13.5px] text-slate-500 mt-1",children:["Week of ",new Date(`${b.week_start}T12:00:00`).toLocaleDateString()," – ",new Date(`${b.week_end}T12:00:00`).toLocaleDateString(),_&&e.jsxs(e.Fragment,{children:[" · ",e.jsx("span",{className:"capitalize",children:_.delivery_status.replace(/_/g," ")}),_.sent_at?` ${new Date(_.sent_at).toLocaleString()}`:""]})]})]}),e.jsxs("div",{className:"flex gap-2 flex-wrap",children:[e.jsxs(B,{variant:"outline",className:"rounded-full",onClick:A,disabled:o.isPending,children:[e.jsx(oo,{className:Ot("h-3.5 w-3.5 mr-1.5",o.isPending&&"animate-spin")})," Regenerate"]}),e.jsxs(B,{variant:"outline",className:"rounded-full",onClick:()=>{navigator.clipboard.writeText(y0t(b,window.location.origin)),ie.success("Digest HTML copied")},children:[e.jsx(Pa,{className:"h-3.5 w-3.5 mr-1.5"})," Copy HTML"]}),e.jsxs(B,{className:"rounded-full btn-primary text-white",onClick:()=>T(!0),disabled:c.isPending,children:[e.jsx(Rr,{className:"h-3.5 w-3.5 mr-1.5"})," Email it to me"]})]})]}),e.jsxs(ya,{defaultValue:"digest",children:[e.jsx(va,{className:"rounded-full bg-white border border-slate-200 p-1",children:[["digest","This week"],["history","History"],["settings","Delivery settings"]].map(([I,M])=>e.jsx(ls,{value:I,className:"rounded-full text-[13px] data-[state=active]:bg-violet-600 data-[state=active]:text-white",children:M},I))}),e.jsxs(_s,{value:"digest",className:"mt-5 space-y-5",children:[e.jsx("div",{className:"grid grid-cols-2 lg:grid-cols-4 gap-3",children:[["Conversations logged",b.wins.conversations_logged],["Stage moves",b.wins.advanced],["Follow-ups completed",b.wins.follow_ups_completed],["Kits shared",b.wins.kits_shared]].map(([I,M])=>e.jsxs(_e,{className:"p-4 rounded-2xl",children:[e.jsx("div",{className:"text-2xl font-semibold tabular-nums text-slate-900",children:M}),e.jsx("div",{className:"text-[11.5px] text-slate-500 mt-0.5",children:I})]},I))}),e.jsxs(_e,{className:"p-5 rounded-2xl",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-wider font-semibold text-violet-600 mb-3",children:"Your five conversations this week"}),b.conversations.length?e.jsx("div",{className:"space-y-3",children:b.conversations.map(I=>{const M=m.find(z=>z.agent_id===I.agent_id),L=!!(M!=null&&M.completed_at);return e.jsxs("div",{className:Ot("rounded-xl border border-slate-200 p-4",L&&"bg-emerald-50/60 border-emerald-200"),children:[e.jsxs("div",{className:"flex items-start justify-between gap-3 flex-wrap",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"text-[14.5px] font-semibold text-slate-900",children:[I.rank,". ",e.jsx(cr,{to:`/attract/agents/${I.agent_id}`,className:"hover:text-violet-700",children:I.agent_name})]}),e.jsx("div",{className:"text-[12.5px] text-slate-600 mt-0.5",children:I.reason})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(We,{variant:"outline",className:"rounded-full capitalize",children:I.channel}),e.jsxs(We,{variant:"outline",className:"rounded-full",children:["Health ",I.score]})]})]}),I.draft_message&&e.jsx("div",{className:"mt-3 rounded-lg bg-slate-50 p-3 text-[13px] text-slate-700 whitespace-pre-wrap",children:I.draft_message}),e.jsxs("div",{className:"flex gap-2 mt-3",children:[e.jsxs(B,{size:"sm",variant:"outline",className:"rounded-full",onClick:()=>{navigator.clipboard.writeText(I.draft_message||""),ie.success("Copied")},children:[e.jsx(Pa,{className:"h-3.5 w-3.5 mr-1.5"})," Copy"]}),M&&!L&&e.jsxs(B,{size:"sm",className:"rounded-full btn-primary text-white",onClick:()=>f.mutate(M.id),children:[e.jsx(Hr,{className:"h-3.5 w-3.5 mr-1.5"})," Mark done"]}),L&&e.jsx("span",{className:"text-[12.5px] text-emerald-700 font-medium self-center",children:"Completed"}),e.jsx(B,{size:"sm",variant:"ghost",className:"rounded-full",asChild:!0,children:e.jsx(cr,{to:`/attract/agents/${I.agent_id}`,children:"Open relationship"})})]})]},I.agent_id)})}):e.jsx("div",{className:"text-[13px] text-slate-500",children:"No conversations to recommend yet — Attract needs real signals first."})]}),e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-4",children:[e.jsxs(_e,{className:"p-5 rounded-2xl space-y-4",children:[e.jsx(YF,{title:"High intent",children:e.jsx(nre,{rows:b.high_intent,empty:"No high-intent signals this week."})}),e.jsx(YF,{title:"Renewed interest",children:e.jsx(nre,{rows:b.renewed,empty:"Nobody re-engaged after going quiet."})})]}),e.jsxs(_e,{className:"p-5 rounded-2xl space-y-4",children:[e.jsx(YF,{title:"Overdue commitments",children:e.jsx(nre,{rows:b.overdue,empty:"Nothing overdue. Well kept."})}),e.jsx(YF,{title:"Going cold",children:e.jsx(nre,{rows:b.stale,empty:"No relationships past 60 days of silence."})})]}),e.jsx(_e,{className:"p-5 rounded-2xl",children:e.jsx(YF,{title:"Value shared",children:e.jsxs("div",{className:"text-[13px] text-slate-700 space-y-1",children:[e.jsxs("div",{children:[b.kit_summary.shares," kits shared · ",b.kit_summary.opened," opened"]}),e.jsxs("div",{children:[b.kit_summary.downloads," downloads · ",b.kit_summary.questions," questions asked"]}),e.jsxs("div",{children:[b.kit_summary.engaged," engaged · ",b.kit_summary.high_intent," high intent"]})]})})}),e.jsx(_e,{className:"p-5 rounded-2xl",children:e.jsx(YF,{title:"Events",children:e.jsxs("div",{className:"text-[13px] text-slate-700 space-y-1",children:[e.jsxs("div",{children:[b.event_summary.invited," invited · ",b.event_summary.registered," registered"]}),e.jsxs("div",{children:[b.event_summary.attended," attended · ",b.event_summary.no_shows," no-shows"]}),e.jsxs("div",{children:[b.event_summary.follow_ups_pending," attendee follow-ups still pending"]}),b.event_summary.upcoming.map(I=>e.jsxs("div",{className:"text-slate-600 flex items-center gap-1.5",children:[e.jsx(ld,{className:"h-3.5 w-3.5"})," ",I.title,I.starts_at?` — ${new Date(I.starts_at).toLocaleDateString()}`:""]},I.title))]})})})]}),e.jsxs(_e,{className:"p-5 rounded-2xl bg-gradient-to-r from-violet-50 to-indigo-50 border-violet-100",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-wider font-semibold text-violet-700",children:"Recommended focus"}),e.jsx("p",{className:"text-[14px] text-slate-800 mt-1.5",children:b.recommended_focus}),e.jsx("div",{className:"flex gap-2 mt-3 flex-wrap",children:b.pillar_balance.map(I=>e.jsxs(We,{variant:"outline",className:"rounded-full capitalize bg-white/70",children:[I.pillar,": ",I.count]},I.pillar))})]})]}),e.jsx(_s,{value:"history",className:"mt-5 space-y-3",children:l.length?l.map(I=>e.jsxs(_e,{className:Ot("p-4 rounded-2xl flex items-center justify-between gap-3 flex-wrap",I.id===h&&"ring-1 ring-violet-300"),children:[e.jsxs("div",{children:[e.jsxs("div",{className:"text-[14px] font-semibold text-slate-900",children:["Week of ",new Date(`${I.week_start}T12:00:00`).toLocaleDateString()]}),e.jsxs("div",{className:"text-[12px] text-slate-500 mt-0.5",children:[e.jsx("span",{className:"capitalize",children:I.delivery_status.replace(/_/g," ")}),I.sent_at&&` · sent ${new Date(I.sent_at).toLocaleString()}`,I.delivery_note&&` · ${I.delivery_note}`]})]}),e.jsx(B,{size:"sm",variant:"outline",className:"rounded-full",onClick:()=>u(I.id),children:"View"})]},I.id)):e.jsx(_e,{className:"p-8 rounded-2xl text-center text-[13.5px] text-slate-500",children:"No digests generated yet."})}),e.jsx(_s,{value:"settings",className:"mt-5",children:e.jsxs(_e,{className:"p-5 rounded-2xl max-w-xl space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[14px] font-medium text-slate-900",children:"Weekly email"}),e.jsx("div",{className:"text-[12.5px] text-slate-500",children:"Send the digest automatically each week."})]}),e.jsx(zn,{checked:!!(a!=null&&a.enabled),onCheckedChange:I=>i.mutate({enabled:I})})]}),e.jsxs("div",{className:"grid sm:grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(re,{children:"Day"}),e.jsxs(Ns,{value:String((a==null?void 0:a.weekday)??1),onValueChange:I=>i.mutate({weekday:Number(I)}),children:[e.jsx(ws,{children:e.jsx(ks,{})}),e.jsx(js,{children:m8n.map((I,M)=>e.jsx(nt,{value:String(M),children:I},I))})]})]}),e.jsxs("div",{children:[e.jsx(re,{children:"Hour (local)"}),e.jsxs(Ns,{value:String((a==null?void 0:a.send_hour)??7),onValueChange:I=>i.mutate({send_hour:Number(I)}),children:[e.jsx(ws,{children:e.jsx(ks,{})}),e.jsx(js,{children:Array.from({length:24},(I,M)=>e.jsxs(nt,{value:String(M),children:[M,":00"]},M))})]})]})]}),e.jsxs("div",{children:[e.jsx(re,{children:"Send to"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(we,{value:g||(a==null?void 0:a.email)||(s==null?void 0:s.email)||"",onChange:I=>y(I.target.value),placeholder:"you@example.com"}),e.jsx(B,{variant:"outline",className:"rounded-full",onClick:()=>i.mutate({email:k}),children:"Save"})]})]}),e.jsxs("div",{className:"rounded-xl bg-amber-50 border border-amber-200 p-3 text-[12.5px] text-amber-900 flex gap-2",children:[e.jsx(mn,{className:"h-4 w-4 mt-0.5 shrink-0"}),`Automatic weekly scheduling is not wired to a scheduler yet — use "Email it to me" to send on demand. If delivery isn't configured, the digest is still saved here and the status will say so honestly.`]})]})})]})]})}const Y6=H,f8n=[{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 g8n(){const{user:s}=Ls(),t=as(),{intel:n,dataset:r,isLoading:a,refetch:i}=gO(),l=DKe(),o=EBt(),[c,d]=N.useState(""),[u,h]=N.useState(!1),m=N.useMemo(()=>r?f$t(n,r):null,[n,r]),f=N.useMemo(()=>{const x=c.toLowerCase().trim();return n.filter(_=>!x||`${_.agent.first_name} ${_.agent.last_name??""}`.toLowerCase().includes(x))},[n,c]),g=async()=>{if(!s)return;h(!0);const{data:x}=await Y6.from("attract_agents").select("id").eq("user_id",s.id).eq("is_demo",!0);if((x??[]).length){ie.info("Demo agents already exist"),h(!1);return}const{data:_,error:b}=await Y6.from("attract_agents").insert(f8n.map(A=>({...A,user_id:s.id,is_demo:!0,source:"demo_seed"}))).select("id, first_name");if(b){ie.error(b.message),h(!1);return}const k=Date.now();await Y6.from("attract_activities").insert((_??[]).map((A,T)=>({user_id:s.id,agent_id:A.id,activity_type:"touch_logged",pillar:"connect",title:`Demo conversation with ${A.first_name}`,created_at:new Date(k-(T+1)*14*864e5).toISOString()}))),await Y6.from("attract_follow_ups").insert({user_id:s.id,agent_id:_[0].id,title:"Demo overdue commitment",touch_type:"call",priority:"high",due_at:new Date(k-6*864e5).toISOString()}),ie.success("Demo relationships seeded"),h(!1),t.invalidateQueries({queryKey:["attract-intel-data"]}),i()},y=async()=>{if(!s)return;h(!0);const{data:x}=await Y6.from("attract_agents").select("id").eq("user_id",s.id).eq("is_demo",!0),_=(x??[]).map(b=>b.id);if(!_.length){ie.info("No demo data to clear"),h(!1);return}for(const b of["attract_recommendations","attract_agent_scores","attract_follow_ups","attract_activities"])await Y6.from(b).delete().in("agent_id",_);await Y6.from("attract_agents").delete().in("id",_),ie.success("Demo data removed"),h(!1),t.invalidateQueries({queryKey:["attract-intel-data"]}),i()};return a?e.jsx(xn,{className:"h-72 w-full rounded-2xl"}):e.jsxs("div",{className:"p-4 sm:p-6 max-w-6xl mx-auto space-y-5",children:[e.jsx(B,{variant:"ghost",size:"sm",className:"rounded-full -ml-2",asChild:!0,children:e.jsxs(cr,{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(oo,{className:"h-3.5 w-3.5 mr-1.5"})," Recompute & persist"]}),e.jsxs(B,{variant:"outline",className:"rounded-full",onClick:g,disabled:u,children:[e.jsx(FG,{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(qn,{className:"h-3.5 w-3.5 mr-1.5"})," Clear demo data"]})]}),e.jsxs(ya,{defaultValue:"agents",children:[e.jsxs(va,{className:"rounded-full",children:[e.jsx(ls,{value:"agents",className:"rounded-full",children:"Scores & signals"}),e.jsx(ls,{value:"digest",className:"rounded-full",children:"Digest payload"})]}),e.jsxs(_s,{value:"agents",className:"mt-4 space-y-3",children:[e.jsx(we,{value:c,onChange:x=>d(x.target.value),placeholder:"Filter by name",className:"max-w-sm rounded-full"}),!f.length&&e.jsx(_e,{className:"p-6 rounded-2xl text-[13.5px] text-muted-foreground",children:"No agents in your Attract pipeline."}),f.map(x=>e.jsxs(_e,{className:"p-4 rounded-2xl",children:[e.jsxs("div",{className:"flex items-start justify-between gap-3 flex-wrap",children:[e.jsxs("div",{children:[e.jsx(cr,{to:`/attract/agents/${x.agent.id}`,className:"text-[15px] font-semibold hover:text-violet-700",children:[x.agent.first_name,x.agent.last_name].filter(Boolean).join(" ")}),e.jsxs("div",{className:"text-[12px] text-muted-foreground mt-0.5 capitalize",children:[x.agent.stage.replace(/_/g," ")," · ",x.agent.temperature??"no temperature"," · ",x.signals.daysSinceTouch??"—"," days since touch"]})]}),x.agent.is_demo&&e.jsx(We,{variant:"outline",className:"rounded-full",children:"Demo"})]}),e.jsxs("div",{className:"grid md:grid-cols-2 gap-4 mt-4",children:[e.jsx(LBt,{score:x.score}),e.jsxs("div",{children:[e.jsxs("div",{className:"text-[11px] uppercase tracking-wider font-semibold text-muted-foreground mb-1.5",children:["Recommendations (",x.recommendations.length,")"]}),x.recommendations.length?e.jsx("ul",{className:"space-y-2",children:x.recommendations.map(_=>e.jsxs("li",{className:"text-[12.5px]",children:[e.jsx("span",{className:"font-medium",children:_.title}),e.jsxs("span",{className:"text-muted-foreground",children:[" · ",_.signal_group," · rank ",_.rank_score," · ",_.priority]}),e.jsx("div",{className:"text-muted-foreground",children:_.reasons.join(" · ")})]},_.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:x.signals.touches90,kitShares:x.signals.shares.length,kitOpens:x.signals.totalKitOpens,questions:x.signals.questions,meetingRequests:x.signals.meetingRequests,overdueFollowUps:x.signals.overdueFollowUps.length,attended:x.signals.attended},null,2)})]})]},x.agent.id))]}),e.jsx(_s,{value:"digest",className:"mt-4",children:e.jsx(_e,{className:"p-4 rounded-2xl",children:e.jsx("pre",{className:"text-[11px] bg-muted p-3 rounded-lg overflow-auto max-h-[600px]",children:JSON.stringify(m,null,2)})})})]})]})}function x8n(){const[s,t]=N.useState(""),[n,r]=N.useState("all"),a=N.useMemo(()=>Hze.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=N.useMemo(()=>{const l={live:0,partial:0,placeholder:0,integration_required:0};return Hze.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(cr,{to:"/admin",children:[e.jsx(ka,{className:"h-3.5 w-3.5 mr-1.5"})," Admin"]})}),e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl font-semibold tracking-tight",children:"Attract Pillar Tools QA"}),e.jsx("p",{className:"text-[13.5px] text-muted-foreground mt-1",children:"Private status map of every Attract tool — route, database dependencies, and what still needs work."})]}),e.jsx("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-3",children:Object.keys(i).map(l=>e.jsxs(_e,{className:"p-4 rounded-2xl cursor-pointer",onClick:()=>r(n===l?"all":l),children:[e.jsx("div",{className:"text-[22px] font-semibold tabular-nums",children:i[l]}),e.jsx("div",{className:"text-[12px] text-muted-foreground",children:Gze[l]})]},l))}),e.jsxs("div",{className:"flex gap-2 flex-wrap",children:[e.jsx(we,{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(_e,{className:"p-4 rounded-2xl",children:e.jsxs("div",{className:"flex items-start justify-between gap-3 flex-wrap",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsx("span",{className:"text-[15px] font-semibold",children:l.title}),e.jsx(We,{variant:"outline",className:"rounded-full capitalize",children:l.pillar}),e.jsx(We,{variant:"outline",className:`rounded-full ${qBt[l.status]}`,children:Gze[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(cr,{to:l.route,children:[l.route," ",e.jsx(Tr,{className:"h-3 w-3 ml-1.5"})]})}):e.jsx("span",{className:"text-[12px] text-muted-foreground",children:l.route??"No route"})]})},`${l.pillar}-${l.key}`))})]})}const Z6=H,v0t=["idea","researching","pitching","applied","tentative","confirmed","completed","declined","archived"],b0t=["panel","keynote","mls_talk","podcast","webinar","mastermind","training","conference","other"],_0t=["attract-speaking"];function g$t(){const{user:s}=Ls(),t=as(),n=mt({queryKey:[..._0t,s==null?void 0:s.id],enabled:!!s,queryFn:async()=>{const{data:u,error:h}=await Z6.from("attract_speaking_opportunities").select("*").order("starts_at",{ascending:!0,nullsFirst:!1});if(h)throw h;return u??[]}}),r=()=>{t.invalidateQueries({queryKey:_0t}),t.invalidateQueries({queryKey:["attract-followups"]}),t.invalidateQueries({queryKey:["attract-activities"]})},a=_t({mutationFn:async u=>{const{data:h,error:m}=await Z6.from("attract_speaking_opportunities").insert({...u,user_id:s.id}).select("*").single();if(m)throw m;return h},onSuccess:()=>{r(),ie.success("Speaking opportunity saved")},onError:u=>ie.error(u.message)}),i=_t({mutationFn:async({id:u,...h})=>{const{error:m}=await Z6.from("attract_speaking_opportunities").update(h).eq("id",u);if(m)throw m},onSuccess:()=>{r(),ie.success("Updated")},onError:u=>ie.error(u.message)}),l=_t({mutationFn:async u=>{const{id:h,created_at:m,updated_at:f,user_id:g,...y}=u,{data:x,error:_}=await Z6.from("attract_speaking_opportunities").insert({...y,title:`${u.title} (copy)`,status:"idea",user_id:s.id}).select("id").single();if(_)throw _;return x},onSuccess:()=>{r(),ie.success("Duplicated")},onError:u=>ie.error(u.message)}),o=_t({mutationFn:async u=>{const{error:h}=await Z6.from("attract_speaking_opportunities").delete().eq("id",u);if(h)throw h},onSuccess:()=>{r(),ie.success("Deleted")},onError:u=>ie.error(u.message)}),c=_t({mutationFn:async({title:u,dueAt:h,notes:m,touchType:f="speaking"})=>{const{error:g}=await Z6.from("attract_follow_ups").insert({user_id:s.id,title:u,due_at:h??null,notes:m??null,touch_type:f,priority:"medium"});if(g)throw g},onSuccess:()=>{r(),ie.success("Added to Follow-Up Center")},onError:u=>ie.error(u.message)}),d=_t({mutationFn:async({title:u,pillar:h="influence",activityType:m="speaking_outreach",agentId:f})=>{const{error:g}=await Z6.from("attract_activities").insert({user_id:s.id,title:u,pillar:h,activity_type:m,agent_id:f??null});if(g)throw g},onSuccess:()=>{r(),ie.success("Outreach logged")},onError:u=>ie.error(u.message)});return{items:n.data??[],isLoading:n.isLoading,error:n.error,refetch:n.refetch,create:a,update:i,duplicate:l,remove:o,addTask:c,logActivity:d}}const eBe={idea:"bg-slate-100 text-slate-700 border-slate-200",researching:"bg-sky-50 text-sky-700 border-sky-200",pitching:"bg-amber-50 text-amber-700 border-amber-200",applied:"bg-orange-50 text-orange-700 border-orange-200",tentative:"bg-violet-50 text-violet-700 border-violet-200",confirmed:"bg-emerald-50 text-emerald-700 border-emerald-200",completed:"bg-teal-50 text-teal-700 border-teal-200",declined:"bg-rose-50 text-rose-700 border-rose-200",archived:"bg-slate-100 text-slate-500 border-slate-200"},UIe={title:"",organization:"",event_type:"panel",status:"idea",timezone:"America/New_York",pillar:"influence",linked_agent_ids:[]};function y8n(){const{items:s,isLoading:t,create:n,update:r,duplicate:a,remove:i,addTask:l,logActivity:o}=g$t(),{agents:c=[]}=jb(),{kits:d=[]}=dq(),u=PAe(),h=(u==null?void 0:u.events)??(u==null?void 0:u.data)??[],[m,f]=N.useState("month"),[g,y]=N.useState(new Date),[x,_]=N.useState("all"),[b,k]=N.useState("all"),[A,T]=N.useState("all"),[P,I]=N.useState(!1),[M,L]=N.useState(null),[z,$]=N.useState(null),V=N.useMemo(()=>s.filter(ae=>!(!P&&(ae.is_archived||ae.status==="archived")||x!=="all"&&ae.status!==x||b!=="all"&&ae.event_type!==b||A!=="all"&&!(ae.linked_agent_ids??[]).includes(A))),[s,x,b,A,P]),W=V.filter(ae=>ae.starts_at),G=V.filter(ae=>!ae.starts_at),X=new Date,te=N.useMemo(()=>{const ae=W.filter(be=>pj(jp(be.starts_at),X)&&["confirmed","tentative"].includes(be.status)),he=V.filter(be=>be.submission_deadline&&pj(jp(be.submission_deadline),X)),xe=V.filter(be=>["pitching","applied","researching"].includes(be.status)),ve=V.filter(be=>be.status==="confirmed"),ge=V.filter(be=>be.follow_up_date&&be.status==="completed");return{upcoming:ae,deadlines:he,pitches:xe,confirmed:ve,followUps:ge}},[V,W]),ne=N.useMemo(()=>UDe(m==="week"?{start:lx(g),end:FB(g)}:{start:lx(am(g)),end:FB(m_(g))}),[g,m]),me=ae=>W.filter(he=>yd(jp(he.starts_at),ae)),ue=async()=>{var he;if(!((he=M==null?void 0:M.title)!=null&&he.trim())){ie.error("Give the talk a title");return}const ae={...M};delete ae.created_at,delete ae.updated_at,delete ae.user_id,(ae.fee===""||ae.fee==null)&&(ae.fee=null),["starts_at","ends_at","submission_deadline","follow_up_date","linked_event_id","linked_kit_id"].forEach(xe=>{ae[xe]===""&&(ae[xe]=null)}),M.id?await r.mutateAsync(ae):await n.mutateAsync(ae),L(null)},ce=ae=>{if(!ae.starts_at){ie.error("Add a date first");return}const he=Se=>new Date(Se).toISOString().replace(/[-:]|\.\d{3}/g,""),xe=ae.ends_at??new Date(new Date(ae.starts_at).getTime()+60*6e4).toISOString(),ve=["BEGIN:VCALENDAR","VERSION:2.0","PRODID:-//LevelUp Attract//Speaking//EN","BEGIN:VEVENT",`UID:${ae.id}@levelup-attract`,`DTSTAMP:${he(new Date().toISOString())}`,`DTSTART:${he(ae.starts_at)}`,`DTEND:${he(xe)}`,`SUMMARY:${(ae.title||"").replace(/\n/g," ")}`,`LOCATION:${(ae.location||ae.virtual_link||"").replace(/\n/g," ")}`,`DESCRIPTION:${[ae.organization,ae.topic].filter(Boolean).join(" — ").replace(/\n/g," ")}`,"END:VEVENT","END:VCALENDAR"].join(`\r `),ge=URL.createObjectURL(new Blob([ve],{type:"text/calendar"})),be=document.createElement("a");be.href=ge,be.download=`${ae.title.replace(/\W+/g,"-").toLowerCase()}.ics`,be.click(),URL.revokeObjectURL(ge)};return t?e.jsxs("div",{className:"space-y-4",children:[e.jsx(xn,{className:"h-32 rounded-2xl"}),e.jsx(xn,{className:"h-96 rounded-2xl"})]}):e.jsxs("div",{className:"space-y-6",children:[e.jsx(Op,{eyebrow:"Pillar 02 · Influence",title:"Speaking Calendar",description:"Every stage, panel, podcast, and MLS talk — from first idea to post-event follow-up.",actions:e.jsxs(B,{className:"rounded-full bg-gradient-to-r from-violet-600 to-indigo-600",onClick:()=>L({...UIe}),children:[e.jsx(nn,{className:"h-4 w-4 mr-2"}),"New opportunity"]})}),e.jsxs("div",{className:"grid grid-cols-2 lg:grid-cols-5 gap-3",children:[e.jsx(TH,{label:"Upcoming talks",value:te.upcoming.length,icon:uj}),e.jsx(TH,{label:"Deadlines ahead",value:te.deadlines.length,icon:Xr}),e.jsx(TH,{label:"Pitches in flight",value:te.pitches.length,icon:Rr}),e.jsx(TH,{label:"Confirmed",value:te.confirmed.length,icon:Hr}),e.jsx(TH,{label:"Post-event follow-ups",value:te.followUps.length,icon:zm})]}),e.jsxs(_e,{className:"p-3 rounded-2xl flex flex-wrap items-center gap-2",children:[e.jsx("div",{className:"flex rounded-full bg-slate-100 p-1",children:["month","week","agenda"].map(ae=>e.jsx("button",{onClick:()=>f(ae),className:`px-3 py-1.5 rounded-full text-[12.5px] font-medium capitalize ${m===ae?"bg-white shadow-sm text-slate-900":"text-slate-500"}`,children:ae},ae))}),m!=="agenda"&&e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(B,{variant:"ghost",size:"icon",className:"rounded-full",onClick:()=>y(m==="week"?H4(g,-1):J0(g,-1)),children:e.jsx(Fc,{className:"h-4 w-4"})}),e.jsx("div",{className:"text-[13.5px] font-semibold min-w-[130px] text-center",children:Js(g,m==="week"?"'Week of' MMM d":"MMMM yyyy")}),e.jsx(B,{variant:"ghost",size:"icon",className:"rounded-full",onClick:()=>y(m==="week"?H4(g,1):J0(g,1)),children:e.jsx(Qa,{className:"h-4 w-4"})}),e.jsx(B,{variant:"ghost",size:"sm",className:"rounded-full",onClick:()=>y(new Date),children:"Today"})]}),e.jsx("div",{className:"flex-1"}),e.jsxs(Ns,{value:x,onValueChange:_,children:[e.jsx(ws,{className:"w-[140px] rounded-full h-9",children:e.jsx(ks,{placeholder:"Status"})}),e.jsxs(js,{children:[e.jsx(nt,{value:"all",children:"All statuses"}),v0t.map(ae=>e.jsx(nt,{value:ae,className:"capitalize",children:ae.replace(/_/g," ")},ae))]})]}),e.jsxs(Ns,{value:b,onValueChange:k,children:[e.jsx(ws,{className:"w-[140px] rounded-full h-9",children:e.jsx(ks,{placeholder:"Type"})}),e.jsxs(js,{children:[e.jsx(nt,{value:"all",children:"All types"}),b0t.map(ae=>e.jsx(nt,{value:ae,className:"capitalize",children:ae.replace(/_/g," ")},ae))]})]}),e.jsxs(Ns,{value:A,onValueChange:T,children:[e.jsx(ws,{className:"w-[160px] rounded-full h-9",children:e.jsx(ks,{placeholder:"Relationship"})}),e.jsxs(js,{children:[e.jsx(nt,{value:"all",children:"All relationships"}),c.map(ae=>e.jsx(nt,{value:ae.id,children:[ae.first_name,ae.last_name].filter(Boolean).join(" ")},ae.id))]})]}),e.jsxs(B,{variant:P?"default":"outline",size:"sm",className:"rounded-full",onClick:()=>I(ae=>!ae),children:[e.jsx(xg,{className:"h-3.5 w-3.5 mr-1.5"}),"Archived"]})]}),s.length===0?e.jsxs(_e,{className:"p-10 rounded-2xl text-center",children:[e.jsx(uj,{className:"h-8 w-8 mx-auto text-violet-500"}),e.jsx("div",{className:"text-[16px] font-semibold mt-3",children:"No speaking opportunities yet"}),e.jsx("p",{className:"text-[13.5px] text-slate-500 mt-1 max-w-md mx-auto",children:"Start with the rooms you already have access to — your office meeting, a local MLS class, a peer's podcast. Track the pitch, the deadline, and the follow-up in one place."}),e.jsxs(B,{className:"mt-4 rounded-full bg-gradient-to-r from-violet-600 to-indigo-600",onClick:()=>L({...UIe}),children:[e.jsx(nn,{className:"h-4 w-4 mr-2"}),"Add your first opportunity"]})]}):m==="agenda"?e.jsxs("div",{className:"space-y-3",children:[[...W,...G].length===0&&e.jsx(_e,{className:"p-8 rounded-2xl text-center text-[13.5px] text-slate-500",children:"Nothing matches these filters."}),[...W,...G].map(ae=>e.jsx(v8n,{o:ae,onEdit:()=>L(ae),onComplete:()=>$(ae),onDuplicate:()=>a.mutate(ae),onDelete:()=>i.mutate(ae.id),onArchive:()=>r.mutate({id:ae.id,is_archived:!ae.is_archived,status:ae.is_archived?"idea":"archived"}),onIcs:()=>ce(ae),onPitchTask:()=>l.mutate({title:`Pitch: ${ae.title}${ae.organization?` (${ae.organization})`:""}`,dueAt:ae.submission_deadline?new Date(ae.submission_deadline).toISOString():null,notes:ae.notes??void 0}),onLogOutreach:()=>o.mutate({title:`Outreach for ${ae.title}`}),onConfirm:()=>r.mutate({id:ae.id,status:"confirmed"})},ae.id))]}):e.jsxs(_e,{className:"rounded-2xl overflow-hidden",children:[e.jsx("div",{className:"grid grid-cols-7 border-b bg-slate-50",children:["Sun","Mon","Tue","Wed","Thu","Fri","Sat"].map(ae=>e.jsx("div",{className:"px-2 py-2 text-[11px] uppercase tracking-wider font-semibold text-slate-500 text-center",children:ae},ae))}),e.jsx("div",{className:"grid grid-cols-7",children:ne.map(ae=>{const he=me(ae);return e.jsxs("div",{className:`min-h-[92px] sm:min-h-[112px] border-b border-r p-1.5 ${MQ(ae,g)||m==="week"?"bg-white":"bg-slate-50/60"}`,children:[e.jsx("button",{onClick:()=>L({...UIe,starts_at:new Date(ae.setHours(10,0,0,0)).toISOString()}),className:`text-[11.5px] font-semibold h-6 w-6 rounded-full grid place-items-center ${yd(ae,X)?"bg-violet-600 text-white":"text-slate-500 hover:bg-slate-100"}`,children:Js(ae,"d")}),e.jsxs("div",{className:"mt-1 space-y-1",children:[he.slice(0,3).map(xe=>e.jsx("button",{onClick:()=>L(xe),className:`w-full text-left text-[11px] px-1.5 py-1 rounded-md border truncate ${eBe[xe.status]??""}`,children:xe.title},xe.id)),he.length>3&&e.jsxs("div",{className:"text-[10.5px] text-slate-400 pl-1",children:["+",he.length-3," more"]})]})]},ae.toISOString())})}),G.length>0&&e.jsxs("div",{className:"p-3 bg-slate-50 border-t",children:[e.jsxs("div",{className:"text-[11px] uppercase tracking-wider font-semibold text-slate-500 mb-2",children:["Undated (",G.length,")"]}),e.jsx("div",{className:"flex flex-wrap gap-2",children:G.map(ae=>e.jsx("button",{onClick:()=>L(ae),className:`text-[12px] px-2.5 py-1 rounded-full border ${eBe[ae.status]??""}`,children:ae.title},ae.id))})]})]}),e.jsx(xO,{}),e.jsx(Bs,{open:!!M,onOpenChange:ae=>!ae&&L(null),children:e.jsxs(Fs,{className:"max-w-3xl max-h-[90vh] overflow-y-auto",children:[e.jsx(qs,{children:e.jsx($s,{children:M!=null&&M.id?"Edit speaking opportunity":"New speaking opportunity"})}),M&&e.jsxs("div",{className:"grid sm:grid-cols-2 gap-3",children:[e.jsx(Eh,{label:"Title",className:"sm:col-span-2",children:e.jsx(we,{value:M.title??"",onChange:ae=>L({...M,title:ae.target.value}),placeholder:"Panel: Winning listings in a shifting market"})}),e.jsx(Eh,{label:"Event / organization",children:e.jsx(we,{value:M.organization??"",onChange:ae=>L({...M,organization:ae.target.value})})}),e.jsx(Eh,{label:"Event type",children:e.jsxs(Ns,{value:M.event_type??"panel",onValueChange:ae=>L({...M,event_type:ae}),children:[e.jsx(ws,{children:e.jsx(ks,{})}),e.jsx(js,{children:b0t.map(ae=>e.jsx(nt,{value:ae,className:"capitalize",children:ae.replace(/_/g," ")},ae))})]})}),e.jsx(Eh,{label:"Contact name",children:e.jsx(we,{value:M.contact_name??"",onChange:ae=>L({...M,contact_name:ae.target.value})})}),e.jsx(Eh,{label:"Contact email",children:e.jsx(we,{type:"email",value:M.contact_email??"",onChange:ae=>L({...M,contact_email:ae.target.value})})}),e.jsx(Eh,{label:"Contact phone",children:e.jsx(we,{value:M.contact_phone??"",onChange:ae=>L({...M,contact_phone:ae.target.value})})}),e.jsx(Eh,{label:"Audience",children:e.jsx(we,{value:M.audience??"",onChange:ae=>L({...M,audience:ae.target.value}),placeholder:"120 local agents"})}),e.jsx(Eh,{label:"Location",children:e.jsx(we,{value:M.location??"",onChange:ae=>L({...M,location:ae.target.value})})}),e.jsx(Eh,{label:"Virtual link",children:e.jsx(we,{value:M.virtual_link??"",onChange:ae=>L({...M,virtual_link:ae.target.value})})}),e.jsx(Eh,{label:"Starts",children:e.jsx(we,{type:"datetime-local",value:w0t(M.starts_at),onChange:ae=>L({...M,starts_at:ae.target.value?new Date(ae.target.value).toISOString():null})})}),e.jsx(Eh,{label:"Ends",children:e.jsx(we,{type:"datetime-local",value:w0t(M.ends_at),onChange:ae=>L({...M,ends_at:ae.target.value?new Date(ae.target.value).toISOString():null})})}),e.jsx(Eh,{label:"Status",children:e.jsxs(Ns,{value:M.status??"idea",onValueChange:ae=>L({...M,status:ae}),children:[e.jsx(ws,{children:e.jsx(ks,{})}),e.jsx(js,{children:v0t.map(ae=>e.jsx(nt,{value:ae,className:"capitalize",children:ae},ae))})]})}),e.jsx(Eh,{label:"Fee / honorarium",children:e.jsx(we,{type:"number",value:M.fee??"",onChange:ae=>L({...M,fee:ae.target.value===""?null:Number(ae.target.value)})})}),e.jsx(Eh,{label:"Submission deadline",children:e.jsx(we,{type:"date",value:M.submission_deadline??"",onChange:ae=>L({...M,submission_deadline:ae.target.value||null})})}),e.jsx(Eh,{label:"Follow-up date",children:e.jsx(we,{type:"date",value:M.follow_up_date??"",onChange:ae=>L({...M,follow_up_date:ae.target.value||null})})}),e.jsx(Eh,{label:"Application URL",className:"sm:col-span-2",children:e.jsx(we,{value:M.application_url??"",onChange:ae=>L({...M,application_url:ae.target.value})})}),e.jsx(Eh,{label:"Topic",className:"sm:col-span-2",children:e.jsx(we,{value:M.topic??"",onChange:ae=>L({...M,topic:ae.target.value})})}),e.jsx(Eh,{label:"Linked Connect event",children:e.jsxs(Ns,{value:M.linked_event_id??"none",onValueChange:ae=>L({...M,linked_event_id:ae==="none"?null:ae}),children:[e.jsx(ws,{children:e.jsx(ks,{placeholder:"None"})}),e.jsxs(js,{children:[e.jsx(nt,{value:"none",children:"None"}),h.map(ae=>e.jsx(nt,{value:ae.id,children:ae.title},ae.id))]})]})}),e.jsx(Eh,{label:"Linked Resource Kit",children:e.jsxs(Ns,{value:M.linked_kit_id??"none",onValueChange:ae=>L({...M,linked_kit_id:ae==="none"?null:ae}),children:[e.jsx(ws,{children:e.jsx(ks,{placeholder:"None"})}),e.jsxs(js,{children:[e.jsx(nt,{value:"none",children:"None"}),d.map(ae=>e.jsx(nt,{value:ae.id,children:ae.title},ae.id))]})]})}),e.jsx(Eh,{label:"Linked agent relationships",className:"sm:col-span-2",children:e.jsxs("div",{className:"flex flex-wrap gap-1.5 max-h-32 overflow-y-auto",children:[c.length===0&&e.jsx("div",{className:"text-[12.5px] text-slate-500",children:"No agents in your pipeline yet."}),c.map(ae=>{const he=(M.linked_agent_ids??[]).includes(ae.id);return e.jsx("button",{type:"button",onClick:()=>L({...M,linked_agent_ids:he?(M.linked_agent_ids??[]).filter(xe=>xe!==ae.id):[...M.linked_agent_ids??[],ae.id]}),className:`text-[12px] px-2.5 py-1 rounded-full border ${he?"bg-violet-600 text-white border-violet-600":"bg-white text-slate-600"}`,children:[ae.first_name,ae.last_name].filter(Boolean).join(" ")},ae.id)})]})}),e.jsx(Eh,{label:"Travel notes",className:"sm:col-span-2",children:e.jsx(Ws,{rows:2,value:M.travel_notes??"",onChange:ae=>L({...M,travel_notes:ae.target.value})})}),e.jsx(Eh,{label:"Notes",className:"sm:col-span-2",children:e.jsx(Ws,{rows:3,value:M.notes??"",onChange:ae=>L({...M,notes:ae.target.value})})})]}),e.jsxs(Cr,{className:"gap-2",children:[e.jsx(B,{variant:"ghost",onClick:()=>L(null),children:"Cancel"}),e.jsx(B,{onClick:ue,disabled:n.isPending||r.isPending,className:"bg-gradient-to-r from-violet-600 to-indigo-600",children:"Save"})]})]})}),e.jsx(b8n,{item:z,onClose:()=>$(null),onSave:async(ae,he)=>{await r.mutateAsync({id:z.id,status:"completed",outcome:ae}),he&&await l.mutateAsync({title:`Post-event follow-up: ${z.title}`,dueAt:new Date(Date.now()+2*864e5).toISOString(),notes:ae.next_actions}),await o.mutateAsync({title:`Spoke at ${z.title}`,activityType:"speaking_completed"}),$(null)}})]})}function w0t(s){if(!s)return"";const t=new Date(s),n=t.getTimezoneOffset();return new Date(t.getTime()-n*6e4).toISOString().slice(0,16)}function Eh({label:s,children:t,className:n}){return e.jsxs("div",{className:n,children:[e.jsx(re,{className:"text-[12px] text-slate-600 mb-1 block",children:s}),t]})}function TH({label:s,value:t,icon:n}){return e.jsxs(_e,{className:"p-4 rounded-2xl",children:[e.jsx(n,{className:"h-4 w-4 text-violet-600"}),e.jsx("div",{className:"mt-1 text-[22px] font-semibold tabular-nums text-slate-900",children:t}),e.jsx("div",{className:"text-[11.5px] text-slate-500",children:s})]})}function v8n({o:s,onEdit:t,onComplete:n,onDuplicate:r,onDelete:a,onArchive:i,onIcs:l,onPitchTask:o,onLogOutreach:c,onConfirm:d}){var m;const u=s,h=u.submission_deadline?Iv(jp(u.submission_deadline),new Date):null;return e.jsx(_e,{className:"p-4 rounded-2xl",children:e.jsxs("div",{className:"flex items-start justify-between gap-3 flex-wrap",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("button",{onClick:t,className:"text-[15px] font-semibold text-slate-900 hover:text-violet-700 text-left",children:u.title}),e.jsx("div",{className:"text-[12.5px] text-slate-500 mt-0.5",children:[u.organization,(m=u.event_type)==null?void 0:m.replace(/_/g," "),u.audience].filter(Boolean).join(" · ")||"No details yet"}),e.jsxs("div",{className:"text-[12.5px] text-slate-600 mt-1 flex items-center gap-3 flex-wrap",children:[u.starts_at&&e.jsxs("span",{className:"inline-flex items-center gap-1",children:[e.jsx(ld,{className:"h-3.5 w-3.5"}),Js(jp(u.starts_at),"EEE MMM d, h:mm a")]}),h!==null&&e.jsxs("span",{className:`inline-flex items-center gap-1 ${h<7?"text-orange-600":""}`,children:[e.jsx(Xr,{className:"h-3.5 w-3.5"}),"Deadline in ",h,"d"]}),(u.linked_agent_ids??[]).length>0&&e.jsxs("span",{className:"inline-flex items-center gap-1",children:[e.jsx(Yn,{className:"h-3.5 w-3.5"}),u.linked_agent_ids.length," linked"]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(We,{variant:"outline",className:`capitalize rounded-full ${eBe[u.status]??""}`,children:u.status}),e.jsxs(qd,{children:[e.jsx(Vd,{asChild:!0,children:e.jsx(B,{variant:"ghost",size:"icon",className:"rounded-full",children:e.jsx(Iy,{className:"h-4 w-4"})})}),e.jsxs(Ld,{align:"end",children:[e.jsx(ba,{onClick:t,children:"Edit"}),e.jsxs(ba,{onClick:o,children:[e.jsx(zm,{className:"h-3.5 w-3.5 mr-2"}),"Add pitch task"]}),e.jsxs(ba,{onClick:c,children:[e.jsx(Rr,{className:"h-3.5 w-3.5 mr-2"}),"Log outreach"]}),e.jsxs(ba,{onClick:d,children:[e.jsx(Hr,{className:"h-3.5 w-3.5 mr-2"}),"Mark confirmed"]}),e.jsxs(ba,{onClick:n,children:[e.jsx(Hr,{className:"h-3.5 w-3.5 mr-2"}),"Mark completed"]}),e.jsxs(ba,{onClick:l,children:[e.jsx(oi,{className:"h-3.5 w-3.5 mr-2"}),"Download .ics"]}),e.jsxs(ba,{onClick:r,children:[e.jsx(Pa,{className:"h-3.5 w-3.5 mr-2"}),"Duplicate"]}),e.jsxs(ba,{onClick:i,children:[e.jsx(xg,{className:"h-3.5 w-3.5 mr-2"}),u.is_archived?"Unarchive":"Archive"]}),e.jsxs(ba,{className:"text-destructive",onClick:a,children:[e.jsx(qn,{className:"h-3.5 w-3.5 mr-2"}),"Delete"]})]})]})]})]})})}function b8n({item:s,onClose:t,onSave:n}){const[r,a]=N.useState(""),[i,l]=N.useState(""),[o,c]=N.useState(""),[d,u]=N.useState("");return e.jsx(Bs,{open:!!s,onOpenChange:h=>!h&&t(),children:e.jsxs(Fs,{className:"max-w-lg",children:[e.jsx(qs,{children:e.jsx($s,{children:"Capture the outcome"})}),e.jsxs("div",{className:"space-y-3",children:[e.jsx(Eh,{label:"Attendance",children:e.jsx(we,{value:r,onChange:h=>a(h.target.value),placeholder:"How many were in the room?"})}),e.jsx(Eh,{label:"Leads / relationships created",children:e.jsx(Ws,{rows:2,value:i,onChange:h=>l(h.target.value)})}),e.jsx(Eh,{label:"Content captured",children:e.jsx(Ws,{rows:2,value:o,onChange:h=>c(h.target.value),placeholder:"Photos, clips, quotes"})}),e.jsx(Eh,{label:"Next actions",children:e.jsx(Ws,{rows:2,value:d,onChange:h=>u(h.target.value)})})]}),e.jsxs(Cr,{className:"gap-2",children:[e.jsx(B,{variant:"ghost",onClick:t,children:"Cancel"}),e.jsx(B,{variant:"outline",onClick:()=>n({attendance:r,leads:i,content:o,next_actions:d},!1),children:"Save only"}),e.jsx(B,{className:"bg-gradient-to-r from-violet-600 to-indigo-600",onClick:()=>n({attendance:r,leads:i,content:o,next_actions:d},!0),children:"Save + create follow-up"})]})]})})}const X7=H,tBe=["attract-masterclasses"];function _8n(){const{user:s}=Ls(),t=as(),n=mt({queryKey:[...tBe,s==null?void 0:s.id],enabled:!!s,queryFn:async()=>{const{data:o,error:c}=await X7.from("attract_masterclasses").select("*").order("updated_at",{ascending:!1});if(c)throw c;return o??[]}}),r=()=>t.invalidateQueries({queryKey:tBe}),a=_t({mutationFn:async o=>{const{data:c,error:d}=await X7.from("attract_masterclasses").insert({title:"Untitled masterclass",...o,user_id:s.id}).select("*").single();if(d)throw d;return c},onSuccess:()=>r(),onError:o=>ie.error(o.message)}),i=_t({mutationFn:async o=>{const{id:c,created_at:d,updated_at:u,user_id:h,...m}=o,{data:f,error:g}=await X7.from("attract_masterclasses").insert({...m,title:`${o.title} (copy)`,status:"draft",user_id:s.id}).select("id").single();if(g)throw g;return f},onSuccess:()=>{r(),ie.success("Duplicated")},onError:o=>ie.error(o.message)}),l=_t({mutationFn:async o=>{const{error:c}=await X7.from("attract_masterclasses").delete().eq("id",o);if(c)throw c},onSuccess:()=>{r(),ie.success("Deleted")},onError:o=>ie.error(o.message)});return{items:n.data??[],isLoading:n.isLoading,refetch:n.refetch,create:a,duplicate:i,remove:l}}function w8n(s){const t=as(),n=mt({queryKey:["attract-masterclass",s],enabled:!!s,queryFn:async()=>{const{data:a,error:i}=await X7.from("attract_masterclasses").select("*").eq("id",s).maybeSingle();if(i)throw i;return a}}),r=_t({mutationFn:async a=>{const{error:i}=await X7.from("attract_masterclasses").update(a).eq("id",s);if(i)throw i},onSuccess:()=>{t.invalidateQueries({queryKey:["attract-masterclass",s]}),t.invalidateQueries({queryKey:tBe})},onError:a=>ie.error(a.message)});return{masterclass:n.data??null,isLoading:n.isLoading,save:r}}const Am=(s,t)=>({id:crypto.randomUUID(),title:s,lessons:t.map(([n,r,a])=>({id:crypto.randomUUID(),title:n,minutes:r,talking_points:a}))}),j0t=[{key:"listing_presentation",title:"Listing Presentation Masterclass",promise:"Walk out with a listing presentation that wins the room in the first five minutes.",target_audience:"Agents who get appointments but lose listings to bigger names.",problem_solved:"Presentations that talk about the agent instead of the seller outcome.",desired_outcome:"A rebuilt opening, pricing story, and close they can use this week.",pillar:"provide",duration_minutes:60,curriculum:[Am("Open strong",[["Why sellers decide in 5 minutes",8,"Trust signals, pacing, the first question you ask"],["The pre-listing package",7,"What to send ahead and why it changes the room"]]),Am("The pricing conversation",[["Framing price without arguing",12,"Data as a story, not a spreadsheet"],["Handling the overpriced seller",10,"Language patterns and walking-away criteria"]]),Am("Close and next steps",[["Asking for the signature",8,"Assumptive close variations"],[`Follow-up if they say "we'll think about it"`,8,"48-hour sequence"]])]},{key:"database_revival",title:"Database Revival Workshop",promise:"Reactivate a cold database into real conversations in 30 days.",target_audience:"Agents with 200+ contacts and no consistent outreach.",problem_solved:"A database that exists but produces nothing.",desired_outcome:"A cleaned list, a cadence, and 10 conversations started live in class.",pillar:"provide",duration_minutes:60,curriculum:[Am("Audit",[["Sorting your list into A/B/C",10,"Criteria that actually predict referrals"],["Fixing missing data",8,"Birthdays, anniversaries, spouse names"]]),Am("The reach-out",[["The no-ask message",12,"Scripts that do not feel like prospecting"],["Voice notes and video",10,"Why they convert 3x text"]]),Am("The cadence",[["Building a 12-touch year",12,"Pop-bys, events, market notes"],["Tracking without a CRM headache",8,"Simple weekly rhythm"]])]},{key:"open_house_conversion",title:"Open House Lead Conversion",promise:"Turn a normal open house into 3-5 real buyer conversations.",target_audience:"Newer agents relying on open houses for pipeline.",problem_solved:"Sign-in sheets full of names that never convert.",desired_outcome:"A pre-, during-, and post-open-house system.",pillar:"produce",duration_minutes:45,curriculum:[Am("Before",[["Neighborhood invites",8,"Door knocking and digital invites"],["Setting the stage",7,"Materials that create conversations"]]),Am("During",[["The three questions",10,"How to qualify without interrogating"],["Capturing real contact info",8,"Sign-in that people actually complete"]]),Am("After",[["The 10-minute follow-up",7,"Speed to lead"],["Week-one nurture",5,"What to send day 1, 3, 7"]])]},{key:"social_authority",title:"Social Media Authority",promise:"Build a local social presence that makes agents and clients come to you.",target_audience:"Agents posting inconsistently with little engagement.",problem_solved:"Random posting with no positioning.",desired_outcome:"A content pillar map and 30 days of planned posts.",pillar:"influence",duration_minutes:60,curriculum:[Am("Positioning",[["Pick your lane",10,"Neighborhood, niche, or narrative"],["What to never post",6,"The credibility killers"]]),Am("Content system",[["The four content types",14,"Teach, prove, connect, invite"],["Batch filming",10,"One hour, ten pieces"]]),Am("Distribution",[["Captions and hooks",10,"First-line formulas"],["Turning comments into DMs",10,"Relationship-first outreach"]])]},{key:"ai_for_agents",title:"AI for Agents",promise:"Use AI to save 5 hours a week without sounding like a robot.",target_audience:"Agents curious about AI but unsure where to start.",problem_solved:"Tool overwhelm and generic AI output.",desired_outcome:"Three working workflows they set up live.",pillar:"influence",duration_minutes:60,curriculum:[Am("Foundations",[["What AI is good and bad at",10,"Drafting vs deciding"],["Prompting basics",10,"Context, role, constraints"]]),Am("Workflows",[["Listing descriptions and marketing",12,"Brand voice inputs"],["Follow-up and email drafts",12,"Never auto-send"]]),Am("Guardrails",[["Compliance and fair housing",10,"What to always review"],["Keeping your voice",6,"Editing pass checklist"]])]},{key:"new_construction",title:"New Construction Buyer Workshop",promise:"Represent new construction buyers with confidence and get paid.",target_audience:"Agents losing buyers to builder sales offices.",problem_solved:"Not knowing builder contracts or registration rules.",desired_outcome:"A registration process and builder relationship plan.",pillar:"produce",duration_minutes:60,curriculum:[Am("The builder landscape",[["How builder comp works",12,"Registration rules that protect you"],["Local builders worth knowing",8,"Relationship map"]]),Am("Representing the buyer",[["Contract differences",14,"What is negotiable"],["Inspections and walkthroughs",10,"Timeline checkpoints"]]),Am("Winning the relationship",[["First-visit protocol",8,"Always accompany"],["Post-close referrals",8,"The neighborhood effect"]])]},{key:"luxury_experience",title:"Luxury Client Experience",promise:"Deliver an experience that earns luxury referrals.",target_audience:"Agents moving into a higher price band.",problem_solved:"Marketing and service that feels mid-market.",desired_outcome:"An upgraded listing experience and presentation standard.",pillar:"provide",duration_minutes:60,curriculum:[Am("Standards",[["What luxury clients notice",12,"Response time, discretion, detail"],["Your materials",10,"Photography, print, web"]]),Am("The listing experience",[["Pre-market strategy",12,"Whisper listings and staging"],["Private showings",8,"Choreography"]]),Am("Referral engine",[["Post-close cadence",10,"Gifting and anniversaries"],["Building the circle",8,"Vendors and advisors"]])]},{key:"recruiting_value",title:"Recruiting Through Value",promise:"Attract agents by helping them, not pitching them.",target_audience:"Team leaders and agents building revenue share.",problem_solved:"Recruiting that feels salesy and gets ignored.",desired_outcome:"A value-first attraction plan for 20 named agents.",pillar:"connect",duration_minutes:60,curriculum:[Am("Mindset",[["Why value beats pitching",10,"Relationship-first framing"],["Choosing your 20",8,"Fit criteria"]]),Am("The value plan",[["Resource kits that help",14,"What agents actually want"],["Events and masterminds",10,"Small rooms win"]]),Am("The conversation",[["When to talk business",10,"Earned invitation"],['Handling "I am happy where I am"',8,"Stay in relationship"]])]}];function j8n(s){return{title:s.title,promise:s.promise,target_audience:s.target_audience,problem_solved:s.problem_solved,desired_outcome:s.desired_outcome,pillar:s.pillar,duration_minutes:s.duration_minutes,curriculum:s.curriculum,source_template_key:s.key,status:"draft"}}function N8n(s){const t=s.title||"Untitled masterclass",n=s.delivery_date?new Date(s.delivery_date).toLocaleString("en-US",{timeZone:"America/New_York",dateStyle:"full",timeStyle:"short"}):"Date to be announced",r=(s.curriculum??[]).flatMap(i=>i.lessons.map(l=>`• ${l.title}`)).slice(0,6).join(` `),a=s.promise||"A practical, no-pitch training session.";return{registration_copy:`${t} ${n} · ${s.duration_minutes??45} minutes · ${s.format??"virtual"} ${a} Who it's for: ${s.target_audience||"Agents who want a practical system."} What we'll cover: ${r||"• Curriculum coming soon"} What you'll leave with: ${s.desired_outcome||"A plan you can use immediately."}`,email_invite:`Subject: ${t} Hi {{first_name}}, I'm hosting ${t} on ${n}. ${a} It's built for ${s.target_audience||"agents like you"} — no pitch, just the system. We'll cover: ${r||"• Curriculum coming soon"} Want me to save you a seat? {{my_name}}`,social_post:`${a} I'm teaching ${t} on ${n}. ${r||""} Free. Comment "SEAT" and I'll send the link.`,dm_invite:`Hey {{first_name}} — I'm running a short session called "${t}" on ${n}. Thought of you because of ${s.problem_solved||"what we talked about"}. Want the link?`,reminder:`Hi {{first_name}} — quick reminder that ${t} starts ${n}. Here's the link: {{join_link}}. Bring one question.`,follow_up:`Hi {{first_name}} — thanks for joining ${t}. Here's the recording and the workbook: {{resource_link}}. One thing to try this week: ${s.desired_outcome||"pick a single takeaway and run it."} Happy to walk through it one-on-one if useful.`}}function k8n(s){const t=[`RUN OF SHOW — ${s.title||"Masterclass"}`,""];let n=0;return t.push("0:00 Welcome, why we're here, one-line promise"),n+=3,(s.curriculum??[]).forEach(r=>{t.push("",`${rre(n)} SECTION: ${r.title}`),r.lessons.forEach(a=>{t.push(`${rre(n)} ${a.title}${a.minutes?` (${a.minutes}m)`:""}${a.talking_points?` — ${a.talking_points}`:""}`),n+=a.minutes??5})}),t.push("",`${rre(n)} Q&A`,`${rre(n+7)} Close: next step + resource kit`),t.join(` `)}function rre(s){const t=Math.floor(s/60),n=s%60;return`${t}:${String(n).padStart(2,"0")}`}function S8n(){const{items:s,isLoading:t,create:n,duplicate:r,remove:a}=_8n(),i=tr(),[l,o]=N.useState(!1),c=s.filter(m=>!m.is_archived),d=s.filter(m=>m.is_archived),u=async()=>{const m=await n.mutateAsync({title:"Untitled masterclass"});i(`/attract/provide/masterclasses/${m.id}`)},h=async m=>{const f=j0t.find(y=>y.key===m),g=await n.mutateAsync(j8n(f));i(`/attract/provide/masterclasses/${g.id}`)};return t?e.jsxs("div",{className:"space-y-4",children:[e.jsx(xn,{className:"h-28 rounded-2xl"}),e.jsx(xn,{className:"h-64 rounded-2xl"})]}):e.jsxs("div",{className:"space-y-6",children:[e.jsx(Op,{eyebrow:"Pillar 03 · Provide",title:"Masterclass Builder",description:"Turn what you already know into a 45-minute teaching moment agents actually attend — curriculum, assets, promotion, run-of-show, and follow-up.",actions:e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(B,{variant:"outline",className:"rounded-full",onClick:()=>o(m=>!m),children:[e.jsx(Cn,{className:"h-4 w-4 mr-2"}),"Starter templates"]}),e.jsxs(B,{className:"rounded-full bg-gradient-to-r from-violet-600 to-indigo-600",onClick:u,disabled:n.isPending,children:[e.jsx(nn,{className:"h-4 w-4 mr-2"}),"New masterclass"]})]})}),(l||s.length===0)&&e.jsxs(_e,{className:"p-5 rounded-2xl",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-widest text-violet-700 font-semibold mb-3",children:"Starter templates"}),e.jsx("div",{className:"grid sm:grid-cols-2 xl:grid-cols-4 gap-3",children:j0t.map(m=>e.jsxs("button",{onClick:()=>h(m.key),className:"text-left p-4 rounded-xl border hover:border-violet-300 hover:shadow-sm transition",children:[e.jsx(We,{variant:"secondary",className:"capitalize mb-2",children:m.pillar}),e.jsx("div",{className:"font-semibold text-[14px] text-slate-900",children:m.title}),e.jsx("div",{className:"text-[12.5px] text-slate-500 mt-1 line-clamp-3",children:m.promise}),e.jsxs("div",{className:"text-[11.5px] text-slate-400 mt-2",children:[m.duration_minutes," min · ",m.curriculum.length," sections"]})]},m.key))})]}),c.length===0?e.jsxs(_e,{className:"p-10 rounded-2xl text-center",children:[e.jsx(Oh,{className:"h-8 w-8 mx-auto text-violet-500"}),e.jsx("div",{className:"text-[16px] font-semibold mt-3",children:"No masterclasses yet"}),e.jsx("p",{className:"text-[13.5px] text-slate-500 mt-1 max-w-md mx-auto",children:"Pick a starter template above or build one from scratch. Nothing sends automatically — every piece of copy stays an editable draft."})]}):e.jsx("div",{className:"grid sm:grid-cols-2 xl:grid-cols-3 gap-3",children:c.map(m=>e.jsxs(_e,{className:"p-4 rounded-2xl",children:[e.jsxs("div",{className:"flex items-start justify-between gap-2",children:[e.jsx(We,{variant:"outline",className:"capitalize rounded-full",children:m.status}),e.jsxs(qd,{children:[e.jsx(Vd,{asChild:!0,children:e.jsx(B,{variant:"ghost",size:"icon",className:"rounded-full h-7 w-7",children:e.jsx(Iy,{className:"h-4 w-4"})})}),e.jsxs(Ld,{align:"end",children:[e.jsx(ba,{onClick:()=>i(`/attract/provide/masterclasses/${m.id}`),children:"Open builder"}),e.jsxs(ba,{onClick:()=>r.mutate(m),children:[e.jsx(Pa,{className:"h-3.5 w-3.5 mr-2"}),"Duplicate"]}),e.jsxs(ba,{className:"text-destructive",onClick:()=>a.mutate(m.id),children:[e.jsx(qn,{className:"h-3.5 w-3.5 mr-2"}),"Delete"]})]})]})]}),e.jsxs(cr,{to:`/attract/provide/masterclasses/${m.id}`,className:"block mt-2",children:[e.jsx("div",{className:"font-semibold text-slate-900 line-clamp-2",children:m.title}),m.promise&&e.jsx("div",{className:"text-[12.5px] text-slate-500 line-clamp-2 mt-1",children:m.promise})]}),e.jsxs("div",{className:"text-[11.5px] text-slate-400 mt-3",children:[(m.curriculum??[]).length," sections · ",m.duration_minutes??45," min",m.delivery_date&&` · ${Js(new Date(m.delivery_date),"MMM d")}`]})]},m.id))}),d.length>0&&e.jsxs(_e,{className:"p-4 rounded-2xl",children:[e.jsxs("div",{className:"text-[11px] uppercase tracking-widest text-slate-500 font-semibold mb-2 flex items-center gap-1.5",children:[e.jsx(xg,{className:"h-3.5 w-3.5"}),"Archived"]}),e.jsx("div",{className:"flex flex-wrap gap-2",children:d.map(m=>e.jsx(cr,{to:`/attract/provide/masterclasses/${m.id}`,className:"text-[12.5px] px-2.5 py-1 rounded-full border text-slate-600",children:m.title},m.id))})]}),e.jsx(xO,{})]})}const N0t=H,C8n=["Strategy","Curriculum","Assets","Promotion","Delivery","Follow-up"];function A8n(){var W,G,X,te,ne,me,ue,ce,ae,he,xe,ve,ge;const{masterclassId:s}=uo(),t=tr(),{user:n}=Ls(),{masterclass:r,isLoading:a,save:i}=w8n(s),l=OBt(),{create:o}=dq(),[c,d]=N.useState(null),[u,h]=N.useState(0),[m,f]=N.useState(!1),[g,y]=N.useState("idle"),x=N.useRef(null),_=N.useRef(!1);N.useEffect(()=>{r&&!c&&d(r)},[r,c]);const b=be=>{d(Se=>Se&&{...Se,...be}),_.current=!0,y("saving"),clearTimeout(x.current),x.current=setTimeout(()=>k({...c??{},...be}),900)},k=async be=>{const{id:Se,user_id:Ie,created_at:Me,updated_at:Re,...Be}=be;await i.mutateAsync(Be),_.current=!1,y("saved"),setTimeout(()=>y(Ne=>Ne==="saved"?"idle":Ne),1800)},A=(c==null?void 0:c.curriculum)??[],T=be=>b({curriculum:be}),P=N.useMemo(()=>A.reduce((be,Se)=>be+Se.lessons.reduce((Ie,Me)=>Ie+(Me.minutes??0),0),0),[A]);if(a||!c)return e.jsxs("div",{className:"space-y-4",children:[e.jsx(xn,{className:"h-24 rounded-2xl"}),e.jsx(xn,{className:"h-96 rounded-2xl"})]});const I=()=>{b({promotion:{...c.promotion,...N8n(c)}}),ie.success("Draft copy generated — edit before you send anything")},M=()=>{b({delivery:{...c.delivery,run_of_show:k8n(c)}}),ie.success("Run of show generated")},L=async()=>{const be=await l.mutateAsync({title:c.title,description:c.promise??void 0,event_type:"masterclass",intended_audience:c.target_audience??void 0,related_pillar:c.pillar??"provide",starts_at:c.delivery_date??new Date(Date.now()+12096e5).toISOString(),format:c.format==="in_person"?"in_person":"virtual",agenda:A.flatMap(Se=>Se.lessons.map(Ie=>({item:`${Se.title}: ${Ie.title}`}))),learning_outcomes:c.desired_outcome?[c.desired_outcome]:[]});await i.mutateAsync({linked_event_id:be.id,status:"scheduled"}),d(Se=>Se&&{...Se,linked_event_id:be.id,status:"scheduled"}),ie.success("Connect event created as a draft"),t(`/attract/events/${be.id}/edit`)},z=async()=>{var Ie,Me,Re,Be,Ne;const be=await o.mutateAsync({title:`${c.title} — Resource Kit`,description:c.promise??void 0,audience:c.target_audience??void 0,pillar:c.pillar??"provide",intro_text:((Ie=c.assets)==null?void 0:Ie.workbook)??void 0,cta_label:((Me=c.assets)==null?void 0:Me.cta_label)??void 0,cta_url:((Re=c.assets)==null?void 0:Re.cta_url)??void 0}),Se=[...(((Be=c.assets)==null?void 0:Be.downloads)??[]).map((Ge,Ce)=>({type:"link",title:Ge.title,url:Ge.url,sort_order:Ce})),...(((Ne=c.assets)==null?void 0:Ne.videos)??[]).map((Ge,Ce)=>({type:"video",title:Ge.title,url:Ge.url,sort_order:100+Ce}))];Se.length&&await N0t.from("attract_resource_kit_items").insert(Se.map(Ge=>({...Ge,kit_id:be.id,user_id:n.id}))),await i.mutateAsync({linked_kit_id:be.id}),d(Ge=>Ge&&{...Ge,linked_kit_id:be.id}),ie.success("Resource Kit created from your assets"),t(`/attract/provide/kits/${be.id}/edit`)},$=async()=>{const be=Date.now(),Se=[{title:`Send recap + resources: ${c.title}`,due_at:new Date(be+1*864e5).toISOString()},{title:`Personal check-in with attendees: ${c.title}`,due_at:new Date(be+3*864e5).toISOString()},{title:`Invite engaged attendees to a 1:1: ${c.title}`,due_at:new Date(be+7*864e5).toISOString()}],{error:Ie}=await N0t.from("attract_follow_ups").insert(Se.map(Me=>({...Me,user_id:n.id,touch_type:"masterclass",priority:"medium"})));if(Ie){ie.error(Ie.message);return}ie.success("3 follow-ups added to your Follow-Up Center")};return e.jsxs("div",{className:"space-y-5",children:[e.jsx(B,{variant:"ghost",size:"sm",className:"rounded-full -ml-2",asChild:!0,children:e.jsxs(cr,{to:"/attract/provide/masterclasses",children:[e.jsx(ka,{className:"h-3.5 w-3.5 mr-1.5"}),"All masterclasses"]})}),e.jsx(Op,{eyebrow:"Pillar 03 · Provide",title:c.title||"Untitled masterclass",description:c.promise??"Build the promise, curriculum, assets, promotion, delivery and follow-up.",actions:e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsx("span",{className:"text-[12px] text-slate-500 inline-flex items-center gap-1.5",children:g==="saving"?e.jsxs(e.Fragment,{children:[e.jsx(us,{className:"h-3.5 w-3.5 animate-spin"}),"Saving…"]}):g==="saved"?e.jsxs(e.Fragment,{children:[e.jsx(pa,{className:"h-3.5 w-3.5 text-emerald-600"}),"Saved"]}):"All changes saved"}),e.jsxs(B,{variant:"outline",className:"rounded-full",onClick:()=>f(be=>!be),children:[e.jsx(da,{className:"h-4 w-4 mr-2"}),m?"Edit":"Preview"]})]})}),e.jsx(_e,{className:"p-2 rounded-2xl flex gap-1 overflow-x-auto",children:C8n.map((be,Se)=>e.jsxs("button",{onClick:()=>{f(!1),h(Se)},className:`px-3.5 py-2 rounded-xl text-[13px] font-medium whitespace-nowrap ${u===Se&&!m?"bg-violet-600 text-white":"text-slate-600 hover:bg-slate-100"}`,children:[Se+1,". ",be]},be))}),m?e.jsx(E8n,{m:c}):e.jsxs(_e,{className:"p-5 rounded-2xl space-y-4",children:[u===0&&e.jsxs("div",{className:"grid sm:grid-cols-2 gap-3",children:[e.jsx(Xp,{label:"Title",className:"sm:col-span-2",children:e.jsx(we,{value:c.title,onChange:be=>b({title:be.target.value})})}),e.jsx(Xp,{label:"The promise",className:"sm:col-span-2",children:e.jsx(Ws,{rows:2,value:c.promise??"",onChange:be=>b({promise:be.target.value}),placeholder:"Walk out with…"})}),e.jsx(Xp,{label:"Target audience",children:e.jsx(we,{value:c.target_audience??"",onChange:be=>b({target_audience:be.target.value})})}),e.jsx(Xp,{label:"Problem solved",children:e.jsx(we,{value:c.problem_solved??"",onChange:be=>b({problem_solved:be.target.value})})}),e.jsx(Xp,{label:"Desired outcome",className:"sm:col-span-2",children:e.jsx(we,{value:c.desired_outcome??"",onChange:be=>b({desired_outcome:be.target.value})})}),e.jsx(Xp,{label:"Pillar",children:e.jsxs(Ns,{value:c.pillar??"provide",onValueChange:be=>b({pillar:be}),children:[e.jsx(ws,{children:e.jsx(ks,{})}),e.jsx(js,{children:["produce","influence","provide","connect"].map(be=>e.jsx(nt,{value:be,className:"capitalize",children:be},be))})]})}),e.jsx(Xp,{label:"Format",children:e.jsxs(Ns,{value:c.format??"virtual",onValueChange:be=>b({format:be}),children:[e.jsx(ws,{children:e.jsx(ks,{})}),e.jsx(js,{children:["virtual","in_person","hybrid"].map(be=>e.jsx(nt,{value:be,className:"capitalize",children:be.replace("_"," ")},be))})]})}),e.jsx(Xp,{label:"Duration (minutes)",children:e.jsx(we,{type:"number",value:c.duration_minutes??45,onChange:be=>b({duration_minutes:Number(be.target.value)})})}),e.jsx(Xp,{label:"Delivery date",children:e.jsx(we,{type:"datetime-local",value:T8n(c.delivery_date),onChange:be=>b({delivery_date:be.target.value?new Date(be.target.value).toISOString():null})})}),e.jsx(Xp,{label:"Status",children:e.jsxs(Ns,{value:c.status,onValueChange:be=>b({status:be}),children:[e.jsx(ws,{children:e.jsx(ks,{})}),e.jsx(js,{children:["draft","ready","scheduled","delivered","archived"].map(be=>e.jsx(nt,{value:be,className:"capitalize",children:be},be))})]})})]}),u===1&&e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"text-[12.5px] text-slate-500",children:[A.length," sections · ",P," minutes planned"]}),e.jsxs(B,{size:"sm",variant:"outline",className:"rounded-full",onClick:()=>T([...A,{id:crypto.randomUUID(),title:"New section",lessons:[]}]),children:[e.jsx(nn,{className:"h-3.5 w-3.5 mr-1.5"}),"Add section"]})]}),A.length===0&&e.jsx("div",{className:"text-[13.5px] text-slate-500 border border-dashed rounded-xl p-8 text-center",children:"No sections yet. Add your first one."}),A.map((be,Se)=>e.jsxs(_e,{className:"p-4 rounded-xl bg-slate-50/60",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(we,{value:be.title,onChange:Ie=>T(A.map(Me=>Me.id===be.id?{...Me,title:Ie.target.value}:Me)),className:"font-semibold"}),e.jsx(B,{variant:"ghost",size:"icon",disabled:Se===0,onClick:()=>T(are(A,Se,Se-1)),children:e.jsx(zy,{className:"h-4 w-4"})}),e.jsx(B,{variant:"ghost",size:"icon",disabled:Se===A.length-1,onClick:()=>T(are(A,Se,Se+1)),children:e.jsx(Xo,{className:"h-4 w-4"})}),e.jsx(B,{variant:"ghost",size:"icon",className:"text-destructive",onClick:()=>T(A.filter(Ie=>Ie.id!==be.id)),children:e.jsx(qn,{className:"h-4 w-4"})})]}),e.jsxs("div",{className:"mt-3 space-y-3",children:[be.lessons.map((Ie,Me)=>e.jsxs("div",{className:"rounded-lg border bg-white p-3 space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(we,{value:Ie.title,placeholder:"Lesson title",onChange:Re=>V(be.id,Ie.id,{title:Re.target.value})}),e.jsx(we,{type:"number",className:"w-20",value:Ie.minutes??"",placeholder:"min",onChange:Re=>V(be.id,Ie.id,{minutes:Number(Re.target.value)})}),e.jsx(B,{variant:"ghost",size:"icon",disabled:Me===0,onClick:()=>T(A.map(Re=>Re.id===be.id?{...Re,lessons:are(Re.lessons,Me,Me-1)}:Re)),children:e.jsx(zy,{className:"h-4 w-4"})}),e.jsx(B,{variant:"ghost",size:"icon",disabled:Me===be.lessons.length-1,onClick:()=>T(A.map(Re=>Re.id===be.id?{...Re,lessons:are(Re.lessons,Me,Me+1)}:Re)),children:e.jsx(Xo,{className:"h-4 w-4"})}),e.jsx(B,{variant:"ghost",size:"icon",className:"text-destructive",onClick:()=>T(A.map(Re=>Re.id===be.id?{...Re,lessons:Re.lessons.filter(Be=>Be.id!==Ie.id)}:Re)),children:e.jsx(qn,{className:"h-4 w-4"})})]}),e.jsxs("div",{className:"grid sm:grid-cols-2 gap-2",children:[e.jsx(Ws,{rows:2,placeholder:"Talking points",value:Ie.talking_points??"",onChange:Re=>V(be.id,Ie.id,{talking_points:Re.target.value})}),e.jsx(Ws,{rows:2,placeholder:"Exercise",value:Ie.exercise??"",onChange:Re=>V(be.id,Ie.id,{exercise:Re.target.value})}),e.jsx(Ws,{rows:2,placeholder:"Example / story",value:Ie.example??"",onChange:Re=>V(be.id,Ie.id,{example:Re.target.value})}),e.jsx(Ws,{rows:2,placeholder:"Speaker notes",value:Ie.speaker_notes??"",onChange:Re=>V(be.id,Ie.id,{speaker_notes:Re.target.value})})]})]},Ie.id)),e.jsxs(B,{size:"sm",variant:"ghost",onClick:()=>T(A.map(Ie=>Ie.id===be.id?{...Ie,lessons:[...Ie.lessons,{id:crypto.randomUUID(),title:""}]}:Ie)),children:[e.jsx(nn,{className:"h-3.5 w-3.5 mr-1.5"}),"Add lesson"]})]})]},be.id))]}),u===2&&e.jsxs("div",{className:"space-y-3",children:[e.jsx(Xp,{label:"Slide outline",children:e.jsx(Ws,{rows:5,value:((W=c.assets)==null?void 0:W.slide_outline)??"",onChange:be=>b({assets:{...c.assets,slide_outline:be.target.value}})})}),e.jsx(Xp,{label:"Workbook / checklist outline",children:e.jsx(Ws,{rows:5,value:((G=c.assets)==null?void 0:G.workbook)??"",onChange:be=>b({assets:{...c.assets,workbook:be.target.value}})})}),e.jsx(k0t,{label:"Downloads",items:((X=c.assets)==null?void 0:X.downloads)??[],onChange:be=>b({assets:{...c.assets,downloads:be}})}),e.jsx(k0t,{label:"Videos",items:((te=c.assets)==null?void 0:te.videos)??[],onChange:be=>b({assets:{...c.assets,videos:be}})}),e.jsxs("div",{className:"grid sm:grid-cols-2 gap-3",children:[e.jsx(Xp,{label:"CTA label",children:e.jsx(we,{value:((ne=c.assets)==null?void 0:ne.cta_label)??"",onChange:be=>b({assets:{...c.assets,cta_label:be.target.value}})})}),e.jsx(Xp,{label:"CTA URL",children:e.jsx(we,{value:((me=c.assets)==null?void 0:me.cta_url)??"",onChange:be=>b({assets:{...c.assets,cta_url:be.target.value}})})})]}),e.jsxs(B,{variant:"outline",className:"rounded-full",onClick:z,disabled:o.isPending,children:[e.jsx(cW,{className:"h-4 w-4 mr-2"}),"Create Resource Kit from these assets"]}),c.linked_kit_id&&e.jsx(We,{variant:"outline",className:"ml-2",children:"Kit linked"})]}),u===3&&e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between flex-wrap gap-2",children:[e.jsx("div",{className:"text-[12.5px] text-slate-500",children:"Every piece stays an editable draft. Nothing sends automatically."}),e.jsxs(B,{variant:"outline",className:"rounded-full",onClick:I,children:[e.jsx(Zg,{className:"h-4 w-4 mr-2"}),"Generate draft copy"]})]}),[["registration_copy","Registration page copy"],["email_invite","Email invite"],["social_post","Social post"],["dm_invite","DM / text invite"],["reminder","Reminder message"],["follow_up","Follow-up message"]].map(([be,Se])=>{var Ie;return e.jsx(Xp,{label:Se,children:e.jsx(Ws,{rows:5,value:((Ie=c.promotion)==null?void 0:Ie[be])??"",onChange:Me=>b({promotion:{...c.promotion,[be]:Me.target.value}})})},be)})]}),u===4&&e.jsxs("div",{className:"space-y-3",children:[e.jsx("div",{className:"flex justify-end",children:e.jsxs(B,{variant:"outline",className:"rounded-full",onClick:M,children:[e.jsx(Zg,{className:"h-4 w-4 mr-2"}),"Build run of show"]})}),e.jsx(Xp,{label:"Run of show",children:e.jsx(Ws,{rows:12,className:"font-mono text-[12.5px]",value:((ue=c.delivery)==null?void 0:ue.run_of_show)??"",onChange:be=>b({delivery:{...c.delivery,run_of_show:be.target.value}})})}),e.jsx(Xp,{label:"Check-in link",children:e.jsx(we,{value:((ce=c.delivery)==null?void 0:ce.checkin_link)??"",onChange:be=>b({delivery:{...c.delivery,checkin_link:be.target.value}}),placeholder:"Paste the Connect event check-in URL"})}),e.jsx(Xp,{label:"Event notes",children:e.jsx(Ws,{rows:4,value:((ae=c.delivery)==null?void 0:ae.event_notes)??"",onChange:be=>b({delivery:{...c.delivery,event_notes:be.target.value}})})}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsxs(B,{variant:"outline",className:"rounded-full",onClick:L,disabled:l.isPending,children:[e.jsx(Pv,{className:"h-4 w-4 mr-2"}),"Convert to a Connect event"]}),c.linked_event_id&&e.jsx(B,{variant:"ghost",className:"rounded-full",asChild:!0,children:e.jsx(cr,{to:`/attract/events/${c.linked_event_id}`,children:"Open linked event"})})]})]}),u===5&&e.jsxs("div",{className:"space-y-3",children:[e.jsx(Xp,{label:"Attendee segmentation",children:e.jsx(Ws,{rows:3,value:((he=c.follow_up)==null?void 0:he.segments)??"",onChange:be=>b({follow_up:{...c.follow_up,segments:be.target.value}}),placeholder:"Attended + asked a question / attended / registered no-show"})}),e.jsx(Xp,{label:"Resource kit sharing note",children:e.jsx(Ws,{rows:3,value:((xe=c.follow_up)==null?void 0:xe.kit_note)??"",onChange:be=>b({follow_up:{...c.follow_up,kit_note:be.target.value}})})}),e.jsx(Xp,{label:"Suggested personal follow-ups",children:e.jsx(Ws,{rows:3,value:((ve=c.follow_up)==null?void 0:ve.personal_touches)??"",onChange:be=>b({follow_up:{...c.follow_up,personal_touches:be.target.value}})})}),e.jsx(Xp,{label:"Conversion / relationship outcomes",children:e.jsx(Ws,{rows:3,value:((ge=c.follow_up)==null?void 0:ge.outcomes)??"",onChange:be=>b({follow_up:{...c.follow_up,outcomes:be.target.value}})})}),e.jsxs(B,{variant:"outline",className:"rounded-full",onClick:$,children:[e.jsx(zm,{className:"h-4 w-4 mr-2"}),"Add 3 follow-ups to Follow-Up Center"]})]})]})]});function V(be,Se,Ie){T(A.map(Me=>Me.id===be?{...Me,lessons:Me.lessons.map(Re=>Re.id===Se?{...Re,...Ie}:Re)}:Me))}}function are(s,t,n){const r=[...s],[a]=r.splice(t,1);return r.splice(n,0,a),r}function T8n(s){if(!s)return"";const t=new Date(s);return new Date(t.getTime()-t.getTimezoneOffset()*6e4).toISOString().slice(0,16)}function Xp({label:s,children:t,className:n}){return e.jsxs("div",{className:n,children:[e.jsx(re,{className:"text-[12px] text-slate-600 mb-1 block",children:s}),t]})}function k0t({label:s,items:t,onChange:n}){return e.jsxs("div",{children:[e.jsx(re,{className:"text-[12px] text-slate-600 mb-1 block",children:s}),e.jsxs("div",{className:"space-y-2",children:[t.map((r,a)=>e.jsxs("div",{className:"flex gap-2",children:[e.jsx(we,{value:r.title,placeholder:"Title",onChange:i=>n(t.map((l,o)=>o===a?{...l,title:i.target.value}:l))}),e.jsx(we,{value:r.url,placeholder:"https://",onChange:i=>n(t.map((l,o)=>o===a?{...l,url:i.target.value}:l))}),e.jsx(B,{variant:"ghost",size:"icon",className:"text-destructive",onClick:()=>n(t.filter((i,l)=>l!==a)),children:e.jsx(qn,{className:"h-4 w-4"})})]},a)),e.jsxs(B,{size:"sm",variant:"ghost",onClick:()=>n([...t,{title:"",url:""}]),children:[e.jsx(nn,{className:"h-3.5 w-3.5 mr-1.5"}),"Add ",s.toLowerCase().slice(0,-1)]})]})]})}function E8n({m:s}){var t,n,r;return e.jsxs("div",{className:"grid lg:grid-cols-2 gap-4",children:[e.jsxs(_e,{className:"p-5 rounded-2xl",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-widest text-violet-700 font-semibold mb-2",children:"Curriculum"}),(s.curriculum??[]).length===0?e.jsx("div",{className:"text-[13px] text-slate-500",children:"Nothing yet."}):(s.curriculum??[]).map(a=>e.jsxs("div",{className:"mb-3",children:[e.jsx("div",{className:"font-semibold text-[14px]",children:a.title}),e.jsx("ul",{className:"mt-1 space-y-1",children:a.lessons.map(i=>e.jsxs("li",{className:"text-[13px] text-slate-600",children:["• ",i.title,i.minutes?` (${i.minutes}m)`:""]},i.id))})]},a.id))]}),e.jsxs(_e,{className:"p-5 rounded-2xl",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-widest text-violet-700 font-semibold mb-2",children:"Workbook outline"}),e.jsx("pre",{className:"text-[12.5px] whitespace-pre-wrap text-slate-700",children:((t=s.assets)==null?void 0:t.workbook)||"Nothing yet."})]}),e.jsxs(_e,{className:"p-5 rounded-2xl",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-widest text-violet-700 font-semibold mb-2",children:"Registration copy"}),e.jsx("pre",{className:"text-[12.5px] whitespace-pre-wrap text-slate-700",children:((n=s.promotion)==null?void 0:n.registration_copy)||"Nothing yet."})]}),e.jsxs(_e,{className:"p-5 rounded-2xl",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-widest text-violet-700 font-semibold mb-2",children:"Presenter run of show"}),e.jsx("pre",{className:"text-[12.5px] whitespace-pre-wrap font-mono text-slate-700",children:((r=s.delivery)==null?void 0:r.run_of_show)||"Nothing yet."})]})]})}const iA=H;function BJ(s,t={}){const{orderBy:n="created_at",ascending:r=!1,titleField:a="title",duplicateOverrides:i={},label:l="Record"}=t,{user:o}=Ls(),c=as(),d=[s,o==null?void 0:o.id],u=mt({queryKey:d,enabled:!!o,queryFn:async()=>{const{data:_,error:b}=await iA.from(s).select("*").order(n,{ascending:r,nullsFirst:!1});if(b)throw b;return _??[]}}),h=()=>{c.invalidateQueries({queryKey:[s]}),c.invalidateQueries({queryKey:["attract-followups"]}),c.invalidateQueries({queryKey:["attract-activities"]})},m=_t({mutationFn:async _=>{const{data:b,error:k}=await iA.from(s).insert({..._,user_id:o.id}).select("*").single();if(k)throw k;return b},onSuccess:()=>{h(),ie.success(`${l} saved`)},onError:_=>ie.error(_.message)}),f=_t({mutationFn:async({id:_,...b})=>{const{error:k}=await iA.from(s).update(b).eq("id",_);if(k)throw k},onSuccess:()=>{h(),ie.success("Updated")},onError:_=>ie.error(_.message)}),g=_t({mutationFn:async _=>{const{id:b,created_at:k,updated_at:A,user_id:T,...P}=_,I={...P,...i,user_id:o.id};a&&I[a]&&(I[a]=`${I[a]} (copy)`);const{data:M,error:L}=await iA.from(s).insert(I).select("id").single();if(L)throw L;return M},onSuccess:()=>{h(),ie.success("Duplicated")},onError:_=>ie.error(_.message)}),y=_t({mutationFn:async({id:_,archived:b})=>{const{error:k}=await iA.from(s).update({is_archived:b}).eq("id",_);if(k)throw k},onSuccess:(_,b)=>{h(),ie.success(b.archived?"Archived":"Restored")},onError:_=>ie.error(_.message)}),x=_t({mutationFn:async _=>{const{error:b}=await iA.from(s).delete().eq("id",_);if(b)throw b},onSuccess:()=>{h(),ie.success("Deleted")},onError:_=>ie.error(_.message)});return{items:u.data??[],isLoading:u.isLoading,error:u.error,refetch:u.refetch,create:m,update:f,duplicate:g,archive:y,remove:x,userId:o==null?void 0:o.id}}function zAe(){const{user:s}=Ls(),t=as();return _t({mutationFn:async({title:n,dueAt:r,notes:a,touchType:i="task",agentId:l})=>{const{error:o}=await iA.from("attract_follow_ups").insert({user_id:s.id,title:n,due_at:r??null,notes:a??null,touch_type:i,priority:"medium",agent_id:l??null});if(o)throw o},onSuccess:()=>{t.invalidateQueries({queryKey:["attract-followups"]}),t.invalidateQueries({queryKey:["attract-daily-plan"]}),ie.success("Added to Follow-Up Center & Today’s Plan")},onError:n=>ie.error(n.message)})}function $J(){const{user:s}=Ls(),t=as();return _t({mutationFn:async({title:n,description:r,pillar:a="produce",activityType:i="tool_action",agentId:l,metadata:o})=>{const{error:c}=await iA.rpc("award_attract_activity",{_user_id:s.id,_activity_type:i,_title:n,_description:r??null,_pillar:a,_agent_id:l??null,_metadata:o??{},_dedupe_minutes:5});if(c)throw c},onSuccess:()=>{t.invalidateQueries({queryKey:["attract-activities"]}),t.invalidateQueries({queryKey:["attract-score"]})},onError:n=>ie.error(n.message)})}const M8n=["annual","quarterly","monthly"],ZF=[{key:"closings",label:"Closings",target:"closings_target",actual:"closings_actual",format:"number"},{key:"gci",label:"GCI",target:"gci_target",actual:"gci_actual",format:"currency"},{key:"volume",label:"Volume",target:"volume_target",actual:"volume_actual",format:"currency"},{key:"listings",label:"Listings",target:"listings_target",actual:"listings_actual",format:"number"},{key:"buyer_sides",label:"Buyer Sides",target:"buyer_sides_target",actual:"buyer_sides_actual",format:"number"},{key:"appointments",label:"Appointments",target:"appointments_target",actual:"appointments_actual",format:"number"}];function XF(s){return s.period_type==="quarterly"?`Q${s.quarter??1} ${s.year}`:s.period_type==="monthly"?`${new Date(2e3,(s.month??1)-1,1).toLocaleString("en-US",{month:"long"})} ${s.year}`:`${s.year}`}function L8n(s,t=new Date){let n,r;if(s.period_type==="monthly"){const l=(s.month??1)-1;n=new Date(s.year,l,1),r=new Date(s.year,l+1,1)}else if(s.period_type==="quarterly"){const l=(s.quarter??1)-1;n=new Date(s.year,l*3,1),r=new Date(s.year,l*3+3,1)}else n=new Date(s.year,0,1),r=new Date(s.year+1,0,1);const a=r.getTime()-n.getTime(),i=t.getTime()-n.getTime();return Math.max(0,Math.min(1,i/a))}function P8n(s,t){if(!s)return!1;const[n,r]=s.split(/[-/T]/).map(Number);return n!==t.year?!1:t.period_type==="monthly"?r===t.month:t.period_type==="quarterly"?Math.ceil(r/3)===t.quarter:!0}function I8n(){const s=BJ("attract_production_goals",{orderBy:"year",ascending:!1,titleField:"label",label:"Goal",duplicateOverrides:{closings_actual:0,gci_actual:0,volume_actual:0,listings_actual:0,buyer_sides_actual:0,appointments_actual:0,is_archived:!1}}),{transactions:t}=u$t(),n=zAe(),r=$J(),a=N.useMemo(()=>{const i={};return s.items.forEach(l=>{i[l.id]={closings:t.filter(o=>P8n(o.closing_date,l)).length}}),i},[s.items,t]);return{...s,goals:s.items,autoProgress:a,quickTask:n,logActivity:r}}function D8n(s){const t=Number(s??0);return t?{monthly:t/12,weekly:t/52}:null}const R8n=Array.from({length:12},(s,t)=>({value:t+1,label:new Date(2e3,t,1).toLocaleString("en-US",{month:"long"})}));function GS(s,t){return Number.isFinite(s)?t==="currency"?s>=1e3?`$${Math.round(s).toLocaleString()}`:`$${s.toFixed(0)}`:Number.isInteger(s)?String(s):s.toFixed(1):"—"}function O8n({pct:s,size:t=92}){const n=(t-12)/2,r=2*Math.PI*n,a=Math.max(0,Math.min(1,s));return e.jsxs("svg",{width:t,height:t,className:"-rotate-90 flex-shrink-0",children:[e.jsx("circle",{cx:t/2,cy:t/2,r:n,stroke:"#ede9fe",strokeWidth:9,fill:"none"}),e.jsx("circle",{cx:t/2,cy:t/2,r:n,stroke:"#7c3aed",strokeWidth:9,fill:"none",strokeLinecap:"round",strokeDasharray:r,strokeDashoffset:r*(1-a)})]})}const S0t={period_type:"annual",year:new Date().getFullYear(),quarter:1,month:new Date().getMonth()+1,use_auto_progress:!0};function F8n(){const{goals:s,isLoading:t,error:n,refetch:r,create:a,update:i,duplicate:l,archive:o,remove:c,autoProgress:d,quickTask:u,logActivity:h}=I8n(),[m,f]=N.useState(!1),[g,y]=N.useState(null),[x,_]=N.useState(null),[b,k]=N.useState(null),A=N.useMemo(()=>s.filter(M=>m?M.is_archived:!M.is_archived),[s,m]),T=(M,L)=>{var $;const z=Number(M[L.actual]??0);return M.use_auto_progress&&L.key==="closings"?Math.max(z,(($=d[M.id])==null?void 0:$.closings)??0):z},P=async()=>{var L;if(!g)return;const M={label:((L=g.label)==null?void 0:L.trim())||null,period_type:g.period_type??"annual",year:Number(g.year)||new Date().getFullYear(),quarter:g.period_type==="quarterly"?Number(g.quarter)||1:null,month:g.period_type==="monthly"?Number(g.month)||1:null,closings_target:g.closings_target??null,gci_target:g.gci_target??null,volume_target:g.volume_target??null,listings_target:g.listings_target??null,buyer_sides_target:g.buyer_sides_target??null,appointments_target:g.appointments_target??null,use_auto_progress:g.use_auto_progress??!0,notes:g.notes??null};g.id?await i.mutateAsync({id:g.id,...M}):await a.mutateAsync(M),y(null)},I=async()=>{if(!x)return;const M={};ZF.forEach(L=>{M[L.actual]=Number(x[L.actual]??0)}),await i.mutateAsync({id:x.id,...M}),await h.mutateAsync({title:`Updated production progress — ${XF(x)}`,pillar:"produce",activityType:"goal_progress"}),_(null)};return e.jsxs("div",{children:[e.jsxs(cr,{to:"/attract/produce",className:"inline-flex items-center gap-1.5 text-[12px] text-slate-500 hover:text-violet-700 mb-3",children:[e.jsx(ka,{className:"h-3.5 w-3.5"})," Back to Produce"]}),e.jsx(Op,{eyebrow:"Produce → Tool",title:"Production Goals",description:"Set the annual, quarterly, and monthly numbers you're playing for — then track pace, not just totals. Progress can be updated manually or pulled from the transactions you log.",actions:e.jsxs(e.Fragment,{children:[e.jsx(B,{variant:"outline",className:"rounded-full",onClick:()=>f(M=>!M),children:m?"Show active":"Show archived"}),e.jsxs(B,{className:"rounded-full bg-gradient-to-r from-violet-600 to-indigo-600",onClick:()=>y({...S0t}),children:[e.jsx(nn,{className:"h-4 w-4 mr-1.5"})," New Goal"]})]})}),t&&e.jsx("div",{className:"grid gap-4 md:grid-cols-2",children:[0,1].map(M=>e.jsx(xn,{className:"h-56 rounded-2xl"},M))}),!t&&n&&e.jsxs(_e,{className:"p-8 rounded-2xl text-center",children:[e.jsx(Uo,{className:"h-6 w-6 text-rose-500 mx-auto mb-2"}),e.jsx("div",{className:"font-semibold text-slate-900",children:"Couldn't load your goals"}),e.jsx("div",{className:"text-[13px] text-slate-600 mt-1",children:n.message}),e.jsxs(B,{variant:"outline",className:"rounded-full mt-4",onClick:()=>r(),children:[e.jsx(hf,{className:"h-3.5 w-3.5 mr-1.5"})," Retry"]})]}),!t&&!n&&A.length===0&&e.jsxs(_e,{className:"p-10 rounded-2xl text-center border-dashed",children:[e.jsx("div",{className:"h-12 w-12 rounded-2xl bg-violet-50 text-violet-600 grid place-items-center mx-auto mb-3",children:e.jsx(iu,{className:"h-6 w-6"})}),e.jsx("div",{className:"text-[16px] font-semibold text-slate-900",children:m?"No archived goals":"No production goals yet"}),e.jsx("p",{className:"text-[13.5px] text-slate-600 mt-1.5 max-w-md mx-auto",children:"Start with one annual goal. Attract will break it into monthly and weekly activity targets and show whether you're ahead or behind pace."}),!m&&e.jsxs(B,{className:"rounded-full mt-4 bg-gradient-to-r from-violet-600 to-indigo-600",onClick:()=>y({...S0t}),children:[e.jsx(nn,{className:"h-4 w-4 mr-1.5"})," Create your first goal"]})]}),e.jsx("div",{className:"grid gap-4 md:grid-cols-2",children:A.map(M=>{const L=L8n(M),z=ZF.find(ne=>M[ne.target])??ZF[0],$=Number(M[z.target]??0),V=T(M,z),W=$?V/$:0,G=$*L,X=V>=G,te=D8n($);return e.jsxs(_e,{className:"p-5 rounded-2xl",children:[e.jsxs("div",{className:"flex items-start justify-between gap-3 flex-wrap",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsx("span",{className:"text-[16px] font-semibold text-slate-900",children:M.label||`${XF(M)} Goals`}),e.jsx(We,{variant:"outline",className:"rounded-full capitalize",children:M.period_type}),e.jsx(We,{variant:"outline",className:"rounded-full",children:XF(M)})]}),M.notes&&e.jsx("div",{className:"text-[12.5px] text-slate-600 mt-1 line-clamp-2",children:M.notes})]}),e.jsxs("div",{className:"flex gap-1",children:[e.jsx(B,{size:"icon",variant:"ghost",className:"h-8 w-8",title:"Edit",onClick:()=>y(M),children:e.jsx(Ja,{className:"h-3.5 w-3.5"})}),e.jsx(B,{size:"icon",variant:"ghost",className:"h-8 w-8",title:"Duplicate",onClick:()=>l.mutate(M),children:e.jsx(Pa,{className:"h-3.5 w-3.5"})}),e.jsx(B,{size:"icon",variant:"ghost",className:"h-8 w-8",title:M.is_archived?"Restore":"Archive",onClick:()=>o.mutate({id:M.id,archived:!M.is_archived}),children:e.jsx(xg,{className:"h-3.5 w-3.5"})}),e.jsx(B,{size:"icon",variant:"ghost",className:"h-8 w-8 text-rose-600",title:"Delete",onClick:()=>k(M),children:e.jsx(qn,{className:"h-3.5 w-3.5"})})]})]}),e.jsxs("div",{className:"flex items-center gap-4 mt-4",children:[e.jsxs("div",{className:"relative",children:[e.jsx(O8n,{pct:W}),e.jsx("div",{className:"absolute inset-0 grid place-items-center",children:e.jsxs("div",{className:"text-[15px] font-semibold tabular-nums text-slate-900",children:[Math.round(W*100),"%"]})})]}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"text-[12px] uppercase tracking-wider text-slate-500",children:z.label}),e.jsxs("div",{className:"text-[22px] font-semibold tabular-nums text-slate-900",children:[GS(V,z.format)," ",e.jsxs("span",{className:"text-slate-400 text-[15px]",children:["/ ",GS($,z.format)]})]}),e.jsxs("div",{className:`text-[12.5px] mt-0.5 font-medium ${X?"text-emerald-600":"text-amber-600"}`,children:[X?"Ahead of pace":"Behind pace"," · pace target ",GS(G,z.format)," (",Math.round(L*100),"% of period elapsed)"]})]})]}),e.jsx("div",{className:"grid grid-cols-2 sm:grid-cols-3 gap-2 mt-4",children:ZF.filter(ne=>M[ne.target]).map(ne=>{const me=Number(M[ne.target]),ue=T(M,ne);return e.jsxs("div",{className:"rounded-xl bg-slate-50 px-3 py-2",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-wider text-slate-500",children:ne.label}),e.jsxs("div",{className:"text-[13.5px] font-semibold tabular-nums text-slate-900",children:[GS(ue,ne.format)," / ",GS(me,ne.format)]}),e.jsx("div",{className:"h-1.5 rounded-full bg-slate-200 mt-1.5 overflow-hidden",children:e.jsx("div",{className:"h-full bg-violet-600",style:{width:`${Math.min(100,me?ue/me*100:0)}%`}})})]},ne.key)})}),M.period_type==="annual"&&te&&e.jsxs("div",{className:"mt-3 rounded-xl border border-violet-100 bg-violet-50/60 px-3.5 py-2.5 text-[12.5px] text-violet-900",children:["Break it down: ",e.jsx("strong",{children:GS(te.monthly,z.format)})," per month ·"," ",e.jsx("strong",{children:GS(te.weekly,z.format)})," per week of ",z.label.toLowerCase(),"."]}),e.jsxs("div",{className:"flex gap-2 mt-4 flex-wrap",children:[e.jsx(B,{size:"sm",variant:"outline",className:"rounded-full",onClick:()=>_({...M}),children:"Update progress"}),e.jsxs(B,{size:"sm",variant:"outline",className:"rounded-full",onClick:()=>u.mutate({title:`Goal push: ${z.label} — ${GS(te?te.weekly:$,z.format)} this week`,dueAt:new Date().toISOString(),notes:`From ${XF(M)} production goal`,touchType:"goal"}),children:[e.jsx(zm,{className:"h-3.5 w-3.5 mr-1.5"})," Add to Today's Plan"]}),e.jsxs(B,{size:"sm",variant:"outline",className:"rounded-full",onClick:()=>h.mutate({title:`Win logged toward ${XF(M)} goals`,pillar:"produce",activityType:"goal_win"}),children:[e.jsx(gl,{className:"h-3.5 w-3.5 mr-1.5"})," Log a win"]})]})]},M.id)})}),e.jsx(Bs,{open:!!g,onOpenChange:M=>!M&&y(null),children:e.jsxs(Fs,{className:"max-w-2xl max-h-[90vh] overflow-y-auto",children:[e.jsxs(qs,{children:[e.jsx($s,{children:g!=null&&g.id?"Edit goal":"New production goal"}),e.jsx(Ar,{children:"Only fill in the targets you actually track. Blank targets are hidden."})]}),g&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"grid sm:grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(re,{children:"Label (optional)"}),e.jsx(we,{value:g.label??"",onChange:M=>y({...g,label:M.target.value}),placeholder:"e.g. 2026 Big Rock"})]}),e.jsxs("div",{children:[e.jsx(re,{children:"Period"}),e.jsxs(Ns,{value:g.period_type,onValueChange:M=>y({...g,period_type:M}),children:[e.jsx(ws,{children:e.jsx(ks,{})}),e.jsx(js,{children:M8n.map(M=>e.jsx(nt,{value:M,className:"capitalize",children:M},M))})]})]}),e.jsxs("div",{children:[e.jsx(re,{children:"Year"}),e.jsx(we,{type:"number",value:g.year??"",onChange:M=>y({...g,year:Number(M.target.value)})})]}),g.period_type==="quarterly"&&e.jsxs("div",{children:[e.jsx(re,{children:"Quarter"}),e.jsxs(Ns,{value:String(g.quarter??1),onValueChange:M=>y({...g,quarter:Number(M)}),children:[e.jsx(ws,{children:e.jsx(ks,{})}),e.jsx(js,{children:[1,2,3,4].map(M=>e.jsxs(nt,{value:String(M),children:["Q",M]},M))})]})]}),g.period_type==="monthly"&&e.jsxs("div",{children:[e.jsx(re,{children:"Month"}),e.jsxs(Ns,{value:String(g.month??1),onValueChange:M=>y({...g,month:Number(M)}),children:[e.jsx(ws,{children:e.jsx(ks,{})}),e.jsx(js,{children:R8n.map(M=>e.jsx(nt,{value:String(M.value),children:M.label},M.value))})]})]})]}),e.jsx("div",{className:"grid sm:grid-cols-3 gap-3",children:ZF.map(M=>e.jsxs("div",{children:[e.jsxs(re,{children:[M.label," target"]}),e.jsx(we,{type:"number",value:g[M.target]??"",onChange:L=>y({...g,[M.target]:L.target.value===""?null:Number(L.target.value)})})]},M.key))}),e.jsxs("div",{className:"flex items-center justify-between rounded-xl border border-slate-200 px-4 py-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[13.5px] font-medium text-slate-900",children:"Pull closings from logged transactions"}),e.jsx("div",{className:"text-[12px] text-slate-600",children:"Uses the transactions in your Transaction-to-Relationship Tracker for this period."})]}),e.jsx(zn,{checked:g.use_auto_progress??!0,onCheckedChange:M=>y({...g,use_auto_progress:M})})]}),e.jsxs("div",{children:[e.jsx(re,{children:"Notes"}),e.jsx(Ws,{value:g.notes??"",onChange:M=>y({...g,notes:M.target.value}),rows:3})]})]}),e.jsxs(Cr,{children:[e.jsx(B,{variant:"ghost",onClick:()=>y(null),children:"Cancel"}),e.jsx(B,{className:"bg-gradient-to-r from-violet-600 to-indigo-600",onClick:P,disabled:a.isPending||i.isPending,children:"Save goal"})]})]})}),e.jsx(Bs,{open:!!x,onOpenChange:M=>!M&&_(null),children:e.jsxs(Fs,{className:"max-w-lg",children:[e.jsxs(qs,{children:[e.jsx($s,{children:"Update progress"}),e.jsxs(Ar,{children:[x?XF(x):""," — enter your actuals to date."]})]}),x&&e.jsx("div",{className:"grid sm:grid-cols-2 gap-3",children:ZF.filter(M=>x[M.target]).map(M=>e.jsxs("div",{children:[e.jsx(re,{children:M.label}),e.jsx(we,{type:"number",value:x[M.actual]??0,onChange:L=>_({...x,[M.actual]:Number(L.target.value)})})]},M.key))}),e.jsxs(Cr,{children:[e.jsx(B,{variant:"ghost",onClick:()=>_(null),children:"Cancel"}),e.jsx(B,{className:"bg-gradient-to-r from-violet-600 to-indigo-600",onClick:I,children:"Save progress"})]})]})}),e.jsx(Bs,{open:!!b,onOpenChange:M=>!M&&k(null),children:e.jsxs(Fs,{className:"max-w-md",children:[e.jsxs(qs,{children:[e.jsx($s,{children:"Delete this goal?"}),e.jsx(Ar,{children:"This can't be undone. Archive it instead if you want to keep the history."})]}),e.jsxs(Cr,{children:[e.jsx(B,{variant:"ghost",onClick:()=>k(null),children:"Cancel"}),e.jsx(B,{variant:"destructive",onClick:()=>{c.mutate(b.id),k(null)},children:"Delete"})]})]})})]})}const qIe=[{value:"award",label:"Award"},{value:"ranking",label:"Ranking"},{value:"certification",label:"Certification"},{value:"milestone",label:"Milestone"},{value:"media",label:"Media Mention"},{value:"production",label:"Production Recognition"}];function z8n(){const s=BJ("attract_awards",{orderBy:"awarded_on",ascending:!1,label:"Award",duplicateOverrides:{is_archived:!1}}),t=$J();return{...s,awards:s.items,logActivity:t}}const C0t={category:"award",status:"active",is_public:!0};function A0t(s){if(!s)return"No date";const[t,n,r]=s.split(/[-/T]/).map(Number);return new Date(t,n-1,r).toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric"})}function B8n(){const{awards:s,isLoading:t,error:n,refetch:r,create:a,update:i,duplicate:l,archive:o,remove:c,logActivity:d}=z8n(),[u,h]=N.useState(!1),[m,f]=N.useState("all"),[g,y]=N.useState(""),[x,_]=N.useState(null),[b,k]=N.useState(null),A=N.useMemo(()=>s.filter(I=>{if(u!==!!I.is_archived||m!=="all"&&I.category!==m)return!1;const M=g.toLowerCase().trim();return!M||`${I.title} ${I.issuer??""} ${I.description??""}`.toLowerCase().includes(M)}),[s,u,m,g]),T=async()=>{var M;if(!((M=x==null?void 0:x.title)!=null&&M.trim())){ie.error("Add a title");return}const I={title:x.title.trim(),issuer:x.issuer||null,awarded_on:x.awarded_on||null,category:x.category??"award",description:x.description||null,proof_url:x.proof_url||null,production_period:x.production_period||null,is_public:x.is_public??!0};x.id?await i.mutateAsync({id:x.id,...I}):(await a.mutateAsync(I),await d.mutateAsync({title:`Added recognition: ${I.title}`,pillar:"produce",activityType:"award_added"})),_(null)},P=I=>{var L;const M=[I.title,I.issuer&&`— ${I.issuer}`,I.awarded_on&&`(${A0t(I.awarded_on)})`].filter(Boolean).join(" ");(L=navigator.clipboard)==null||L.writeText(M),ie.success("Proof point copied — paste it into Content Studio")};return e.jsxs("div",{children:[e.jsxs(cr,{to:"/attract/produce",className:"inline-flex items-center gap-1.5 text-[12px] text-slate-500 hover:text-violet-700 mb-3",children:[e.jsx(ka,{className:"h-3.5 w-3.5"})," Back to Produce"]}),e.jsx(Op,{eyebrow:"Produce → Tool",title:"Awards & Recognition",description:"Your credibility file. Keep every award, ranking, and certification in one place so proof points are ready when you write content or pitch a speaking slot.",actions:e.jsxs(e.Fragment,{children:[e.jsx(B,{variant:"outline",className:"rounded-full",onClick:()=>h(I=>!I),children:u?"Show active":"Show archived"}),e.jsxs(B,{className:"rounded-full bg-gradient-to-r from-violet-600 to-indigo-600",onClick:()=>_({...C0t}),children:[e.jsx(nn,{className:"h-4 w-4 mr-1.5"})," Add Recognition"]})]})}),e.jsxs("div",{className:"flex gap-2 flex-wrap mb-4",children:[e.jsx(we,{value:g,onChange:I=>y(I.target.value),placeholder:"Search recognitions",className:"max-w-xs rounded-full"}),e.jsxs(Ns,{value:m,onValueChange:f,children:[e.jsx(ws,{className:"w-[190px] rounded-full",children:e.jsx(ks,{})}),e.jsxs(js,{children:[e.jsx(nt,{value:"all",children:"All categories"}),qIe.map(I=>e.jsx(nt,{value:I.value,children:I.label},I.value))]})]})]}),t&&e.jsx("div",{className:"grid gap-3 md:grid-cols-2",children:[0,1,2,3].map(I=>e.jsx(xn,{className:"h-36 rounded-2xl"},I))}),!t&&n&&e.jsxs(_e,{className:"p-8 rounded-2xl text-center",children:[e.jsx(Uo,{className:"h-6 w-6 text-rose-500 mx-auto mb-2"}),e.jsx("div",{className:"font-semibold text-slate-900",children:"Couldn't load recognitions"}),e.jsx("div",{className:"text-[13px] text-slate-600 mt-1",children:n.message}),e.jsxs(B,{variant:"outline",className:"rounded-full mt-4",onClick:()=>r(),children:[e.jsx(hf,{className:"h-3.5 w-3.5 mr-1.5"})," Retry"]})]}),!t&&!n&&A.length===0&&e.jsxs(_e,{className:"p-10 rounded-2xl text-center border-dashed",children:[e.jsx("div",{className:"h-12 w-12 rounded-2xl bg-violet-50 text-violet-600 grid place-items-center mx-auto mb-3",children:e.jsx(ku,{className:"h-6 w-6"})}),e.jsx("div",{className:"text-[16px] font-semibold text-slate-900",children:u?"Nothing archived":"No recognitions logged yet"}),e.jsx("p",{className:"text-[13.5px] text-slate-600 mt-1.5 max-w-md mx-auto",children:"Add awards, production rankings, and designations. Copy any one of them as a proof point when writing authority content."}),!u&&e.jsxs(B,{className:"rounded-full mt-4 bg-gradient-to-r from-violet-600 to-indigo-600",onClick:()=>_({...C0t}),children:[e.jsx(nn,{className:"h-4 w-4 mr-1.5"})," Add your first"]})]}),e.jsx("div",{className:"grid gap-3 md:grid-cols-2",children:A.map(I=>{var M;return e.jsxs(_e,{className:"p-5 rounded-2xl",children:[e.jsxs("div",{className:"flex items-start justify-between gap-3",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsx("span",{className:"text-[15.5px] font-semibold text-slate-900",children:I.title}),e.jsx(We,{variant:"outline",className:"rounded-full capitalize",children:((M=qIe.find(L=>L.value===I.category))==null?void 0:M.label)??I.category})]}),e.jsx("div",{className:"text-[12.5px] text-slate-500 mt-1",children:[I.issuer,A0t(I.awarded_on),I.production_period].filter(Boolean).join(" · ")}),I.description&&e.jsx("p",{className:"text-[13px] text-slate-600 mt-2 line-clamp-3",children:I.description})]}),e.jsxs("div",{className:"flex gap-1 flex-shrink-0",children:[e.jsx(B,{size:"icon",variant:"ghost",className:"h-8 w-8",title:"Edit",onClick:()=>_(I),children:e.jsx(Ja,{className:"h-3.5 w-3.5"})}),e.jsx(B,{size:"icon",variant:"ghost",className:"h-8 w-8",title:"Duplicate",onClick:()=>l.mutate(I),children:e.jsx(Pa,{className:"h-3.5 w-3.5"})}),e.jsx(B,{size:"icon",variant:"ghost",className:"h-8 w-8",title:I.is_archived?"Restore":"Archive",onClick:()=>o.mutate({id:I.id,archived:!I.is_archived}),children:e.jsx(xg,{className:"h-3.5 w-3.5"})}),e.jsx(B,{size:"icon",variant:"ghost",className:"h-8 w-8 text-rose-600",title:"Delete",onClick:()=>k(I),children:e.jsx(qn,{className:"h-3.5 w-3.5"})})]})]}),e.jsxs("div",{className:"flex gap-2 mt-4 flex-wrap",children:[e.jsxs(B,{size:"sm",variant:"outline",className:"rounded-full",onClick:()=>P(I),children:[e.jsx(cd,{className:"h-3.5 w-3.5 mr-1.5"})," Copy proof point"]}),e.jsx(B,{size:"sm",variant:"outline",className:"rounded-full",asChild:!0,children:e.jsxs(cr,{to:"/attract/influence/content-studio",children:[e.jsx(Cn,{className:"h-3.5 w-3.5 mr-1.5"})," Write about it"]})}),I.proof_url&&e.jsx(B,{size:"sm",variant:"ghost",className:"rounded-full",asChild:!0,children:e.jsxs("a",{href:I.proof_url,target:"_blank",rel:"noreferrer",children:["Proof ",e.jsx(Tr,{className:"h-3 w-3 ml-1.5"})]})})]})]},I.id)})}),e.jsx(Bs,{open:!!x,onOpenChange:I=>!I&&_(null),children:e.jsxs(Fs,{className:"max-w-xl max-h-[90vh] overflow-y-auto",children:[e.jsxs(qs,{children:[e.jsx($s,{children:x!=null&&x.id?"Edit recognition":"Add recognition"}),e.jsx(Ar,{children:"Keep it factual — this feeds the proof points you use publicly."})]}),x&&e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{children:[e.jsx(re,{children:"Title *"}),e.jsx(we,{value:x.title??"",onChange:I=>_({...x,title:I.target.value}),placeholder:"e.g. Top 1% Producer"})]}),e.jsxs("div",{className:"grid sm:grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(re,{children:"Issued by"}),e.jsx(we,{value:x.issuer??"",onChange:I=>_({...x,issuer:I.target.value}),placeholder:"Board, brokerage, publication"})]}),e.jsxs("div",{children:[e.jsx(re,{children:"Category"}),e.jsxs(Ns,{value:x.category??"award",onValueChange:I=>_({...x,category:I}),children:[e.jsx(ws,{children:e.jsx(ks,{})}),e.jsx(js,{children:qIe.map(I=>e.jsx(nt,{value:I.value,children:I.label},I.value))})]})]}),e.jsxs("div",{children:[e.jsx(re,{children:"Date awarded"}),e.jsx(we,{type:"date",value:x.awarded_on??"",onChange:I=>_({...x,awarded_on:I.target.value})})]}),e.jsxs("div",{children:[e.jsx(re,{children:"Production period"}),e.jsx(we,{value:x.production_period??"",onChange:I=>_({...x,production_period:I.target.value}),placeholder:"e.g. 2025"})]})]}),e.jsxs("div",{children:[e.jsx(re,{children:"Proof link"}),e.jsx(we,{value:x.proof_url??"",onChange:I=>_({...x,proof_url:I.target.value}),placeholder:"https://"})]}),e.jsxs("div",{children:[e.jsx(re,{children:"Description"}),e.jsx(Ws,{rows:3,value:x.description??"",onChange:I=>_({...x,description:I.target.value})})]})]}),e.jsxs(Cr,{children:[e.jsx(B,{variant:"ghost",onClick:()=>_(null),children:"Cancel"}),e.jsx(B,{className:"bg-gradient-to-r from-violet-600 to-indigo-600",onClick:T,disabled:a.isPending||i.isPending,children:"Save"})]})]})}),e.jsx(Bs,{open:!!b,onOpenChange:I=>!I&&k(null),children:e.jsxs(Fs,{className:"max-w-md",children:[e.jsxs(qs,{children:[e.jsx($s,{children:"Delete this recognition?"}),e.jsx(Ar,{children:"This can't be undone."})]}),e.jsxs(Cr,{children:[e.jsx(B,{variant:"ghost",onClick:()=>k(null),children:"Cancel"}),e.jsx(B,{variant:"destructive",onClick:()=>{c.mutate(b.id),k(null)},children:"Delete"})]})]})})]})}const $8n=H,T0t=[{value:"pending",label:"Permission pending"},{value:"granted",label:"Permission granted"},{value:"anonymous_only",label:"Anonymous use only"},{value:"declined",label:"Permission declined"}],U8n=["buyer","seller","both","investor","referral_partner","agent","other"];function ire(s){return s.status==="approved"&&(s.permission_status==="granted"||s.permission_status==="anonymous_only")}function q8n(){const s=BJ("attract_testimonials",{orderBy:"created_at",ascending:!1,titleField:"client_name",label:"Testimonial",duplicateOverrides:{use_count:0,last_used_at:null,usage_log:[],status:"draft",is_archived:!1}}),t=$J(),n=as(),r=_t({mutationFn:async({item:a,kind:i,note:l})=>{const o=[...a.usage_log??[],{at:new Date().toISOString(),kind:i,note:l}].slice(-25),{error:c}=await $8n.from("attract_testimonials").update({use_count:(a.use_count??0)+1,last_used_at:new Date().toISOString(),usage_log:o}).eq("id",a.id);if(c)throw c},onSuccess:()=>{n.invalidateQueries({queryKey:["attract_testimonials"]}),ie.success("Usage recorded")},onError:a=>ie.error(a.message)});return{...s,testimonials:s.items,recordUse:r,logActivity:t}}const E0t={permission_status:"pending",status:"draft",rating:5,tags:[]};function V8n(){const{testimonials:s,isLoading:t,error:n,refetch:r,create:a,update:i,duplicate:l,archive:o,remove:c,recordUse:d,logActivity:u}=q8n(),[h,m]=N.useState(!1),[f,g]=N.useState("all"),[y,x]=N.useState(""),[_,b]=N.useState(null),[k,A]=N.useState(null),T=N.useMemo(()=>s.filter(L=>{if(h!==!!L.is_archived||f==="usable"&&!ire(L)||f==="pending"&&L.permission_status!=="pending")return!1;const z=y.toLowerCase().trim();return!z||`${L.client_name} ${L.quote} ${(L.tags??[]).join(" ")}`.toLowerCase().includes(z)}),[s,h,f,y]),P=s.filter(L=>!L.is_archived&&ire(L)).length,I=async()=>{var z,$;if(!((z=_==null?void 0:_.client_name)!=null&&z.trim())||!(($=_==null?void 0:_.quote)!=null&&$.trim())){ie.error("Client name and quote are required");return}const L={client_name:_.client_name.trim(),quote:_.quote.trim(),relationship_type:_.relationship_type||null,transaction_type:_.transaction_type||null,rating:_.rating??null,received_on:_.received_on||null,source_url:_.source_url||null,permission_status:_.permission_status??"pending",market:_.market||null,status:_.status??"draft",tags:_.tags??[]};_.id?await i.mutateAsync({id:_.id,...L}):(await a.mutateAsync(L),await u.mutateAsync({title:`Captured a testimonial from ${L.client_name}`,pillar:"produce",activityType:"testimonial_added"})),b(null)},M=(L,z)=>{var $;if(!ire(L)){ie.error("Mark it approved with permission before using it publicly");return}($=navigator.clipboard)==null||$.writeText(`"${L.quote}" — ${L.permission_status==="anonymous_only"?"Client":L.client_name}`),d.mutate({item:L,kind:z})};return e.jsxs("div",{children:[e.jsxs(cr,{to:"/attract/produce",className:"inline-flex items-center gap-1.5 text-[12px] text-slate-500 hover:text-violet-700 mb-3",children:[e.jsx(ka,{className:"h-3.5 w-3.5"})," Back to Produce"]}),e.jsx(Op,{eyebrow:"Produce → Tool",title:"Client Testimonials",description:"Your social proof library. Capture the exact words clients use, track who gave permission, and see which quotes you've already used so nothing gets overexposed.",actions:e.jsxs(e.Fragment,{children:[e.jsx(B,{variant:"outline",className:"rounded-full",onClick:()=>m(L=>!L),children:h?"Show active":"Show archived"}),e.jsxs(B,{className:"rounded-full bg-gradient-to-r from-violet-600 to-indigo-600",onClick:()=>b({...E0t}),children:[e.jsx(nn,{className:"h-4 w-4 mr-1.5"})," Add Testimonial"]})]})}),e.jsxs("div",{className:"grid grid-cols-2 sm:grid-cols-3 gap-3 mb-4",children:[e.jsxs(_e,{className:"p-4 rounded-2xl",children:[e.jsx("div",{className:"text-[22px] font-semibold tabular-nums text-slate-900",children:s.filter(L=>!L.is_archived).length}),e.jsx("div",{className:"text-[12px] text-slate-500",children:"In library"})]}),e.jsxs(_e,{className:"p-4 rounded-2xl",children:[e.jsx("div",{className:"text-[22px] font-semibold tabular-nums text-emerald-600",children:P}),e.jsx("div",{className:"text-[12px] text-slate-500",children:"Cleared for use"})]}),e.jsxs(_e,{className:"p-4 rounded-2xl",children:[e.jsx("div",{className:"text-[22px] font-semibold tabular-nums text-amber-600",children:s.filter(L=>!L.is_archived&&L.permission_status==="pending").length}),e.jsx("div",{className:"text-[12px] text-slate-500",children:"Permission pending"})]})]}),e.jsxs("div",{className:"flex gap-2 flex-wrap mb-4",children:[e.jsx(we,{value:y,onChange:L=>x(L.target.value),placeholder:"Search quotes, clients, tags",className:"max-w-xs rounded-full"}),e.jsxs(Ns,{value:f,onValueChange:L=>g(L),children:[e.jsx(ws,{className:"w-[200px] rounded-full",children:e.jsx(ks,{})}),e.jsxs(js,{children:[e.jsx(nt,{value:"all",children:"All testimonials"}),e.jsx(nt,{value:"usable",children:"Cleared for use"}),e.jsx(nt,{value:"pending",children:"Permission pending"})]})]})]}),t&&e.jsx("div",{className:"grid gap-3 md:grid-cols-2",children:[0,1,2,3].map(L=>e.jsx(xn,{className:"h-40 rounded-2xl"},L))}),!t&&n&&e.jsxs(_e,{className:"p-8 rounded-2xl text-center",children:[e.jsx(Uo,{className:"h-6 w-6 text-rose-500 mx-auto mb-2"}),e.jsx("div",{className:"font-semibold text-slate-900",children:"Couldn't load testimonials"}),e.jsx("div",{className:"text-[13px] text-slate-600 mt-1",children:n.message}),e.jsxs(B,{variant:"outline",className:"rounded-full mt-4",onClick:()=>r(),children:[e.jsx(hf,{className:"h-3.5 w-3.5 mr-1.5"})," Retry"]})]}),!t&&!n&&T.length===0&&e.jsxs(_e,{className:"p-10 rounded-2xl text-center border-dashed",children:[e.jsx("div",{className:"h-12 w-12 rounded-2xl bg-violet-50 text-violet-600 grid place-items-center mx-auto mb-3",children:e.jsx(Q2,{className:"h-6 w-6"})}),e.jsx("div",{className:"text-[16px] font-semibold text-slate-900",children:"No testimonials match"}),e.jsx("p",{className:"text-[13.5px] text-slate-600 mt-1.5 max-w-md mx-auto",children:"Paste in the reviews and thank-you notes you already have. Mark permission so you always know what's safe to publish."}),!h&&e.jsxs(B,{className:"rounded-full mt-4 bg-gradient-to-r from-violet-600 to-indigo-600",onClick:()=>b({...E0t}),children:[e.jsx(nn,{className:"h-4 w-4 mr-1.5"})," Add one"]})]}),e.jsx("div",{className:"grid gap-3 md:grid-cols-2",children:T.map(L=>{var z;return e.jsxs(_e,{className:"p-5 rounded-2xl flex flex-col",children:[e.jsxs("div",{className:"flex items-start justify-between gap-3",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsx("span",{className:"text-[15px] font-semibold text-slate-900",children:L.client_name}),L.relationship_type&&e.jsx(We,{variant:"outline",className:"rounded-full capitalize",children:L.relationship_type.replace("_"," ")}),e.jsx(We,{variant:"outline",className:`rounded-full ${ire(L)?"bg-emerald-50 text-emerald-700 border-emerald-200":"bg-amber-50 text-amber-700 border-amber-200"}`,children:((z=T0t.find($=>$.value===L.permission_status))==null?void 0:z.label)??L.permission_status})]}),!!L.rating&&e.jsx("div",{className:"flex gap-0.5 mt-1.5",children:Array.from({length:5}).map(($,V)=>e.jsx(Wa,{className:`h-3.5 w-3.5 ${V<(L.rating??0)?"text-amber-500 fill-amber-500":"text-slate-200"}`},V))})]}),e.jsxs("div",{className:"flex gap-1 flex-shrink-0",children:[e.jsx(B,{size:"icon",variant:"ghost",className:"h-8 w-8",title:"Edit",onClick:()=>b(L),children:e.jsx(Ja,{className:"h-3.5 w-3.5"})}),e.jsx(B,{size:"icon",variant:"ghost",className:"h-8 w-8",title:"Duplicate",onClick:()=>l.mutate(L),children:e.jsx(Pa,{className:"h-3.5 w-3.5"})}),e.jsx(B,{size:"icon",variant:"ghost",className:"h-8 w-8",title:L.is_archived?"Restore":"Archive",onClick:()=>o.mutate({id:L.id,archived:!L.is_archived}),children:e.jsx(xg,{className:"h-3.5 w-3.5"})}),e.jsx(B,{size:"icon",variant:"ghost",className:"h-8 w-8 text-rose-600",title:"Delete",onClick:()=>A(L),children:e.jsx(qn,{className:"h-3.5 w-3.5"})})]})]}),e.jsxs("blockquote",{className:"mt-3 text-[13.5px] text-slate-700 border-l-2 border-violet-200 pl-3 italic",children:['"',L.quote,'"']}),e.jsxs("div",{className:"text-[11.5px] text-slate-500 mt-3",children:["Used ",L.use_count??0," ",L.use_count===1?"time":"times",L.last_used_at?` · last ${new Date(L.last_used_at).toLocaleDateString("en-US")}`:"",L.status==="approved"?"":" · draft"]}),e.jsxs("div",{className:"flex gap-2 mt-3 flex-wrap",children:[e.jsxs(B,{size:"sm",variant:"outline",className:"rounded-full",onClick:()=>M(L,"copied"),children:[e.jsx(Pa,{className:"h-3.5 w-3.5 mr-1.5"})," Copy & log use"]}),e.jsx(B,{size:"sm",variant:"outline",className:"rounded-full",asChild:!0,children:e.jsxs(cr,{to:"/attract/influence/content-studio",children:[e.jsx(Cn,{className:"h-3.5 w-3.5 mr-1.5"})," Draft social proof"]})}),L.status!=="approved"&&e.jsxs(B,{size:"sm",variant:"ghost",className:"rounded-full text-emerald-700",onClick:()=>i.mutate({id:L.id,status:"approved"}),children:[e.jsx(Wv,{className:"h-3.5 w-3.5 mr-1.5"})," Mark approved"]})]})]},L.id)})}),e.jsx(Bs,{open:!!_,onOpenChange:L=>!L&&b(null),children:e.jsxs(Fs,{className:"max-w-xl max-h-[90vh] overflow-y-auto",children:[e.jsxs(qs,{children:[e.jsx($s,{children:_!=null&&_.id?"Edit testimonial":"Add testimonial"}),e.jsx(Ar,{children:"Use the client's own words. Only publish quotes where permission is granted."})]}),_&&e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"grid sm:grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(re,{children:"Client name *"}),e.jsx(we,{value:_.client_name??"",onChange:L=>b({..._,client_name:L.target.value})})]}),e.jsxs("div",{children:[e.jsx(re,{children:"Relationship"}),e.jsxs(Ns,{value:_.relationship_type??"",onValueChange:L=>b({..._,relationship_type:L}),children:[e.jsx(ws,{children:e.jsx(ks,{placeholder:"Select"})}),e.jsx(js,{children:U8n.map(L=>e.jsx(nt,{value:L,className:"capitalize",children:L.replace("_"," ")},L))})]})]})]}),e.jsxs("div",{children:[e.jsx(re,{children:"Quote *"}),e.jsx(Ws,{rows:4,value:_.quote??"",onChange:L=>b({..._,quote:L.target.value})})]}),e.jsxs("div",{className:"grid sm:grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(re,{children:"Rating"}),e.jsxs(Ns,{value:String(_.rating??5),onValueChange:L=>b({..._,rating:Number(L)}),children:[e.jsx(ws,{children:e.jsx(ks,{})}),e.jsx(js,{children:[5,4,3,2,1].map(L=>e.jsxs(nt,{value:String(L),children:[L," star",L>1?"s":""]},L))})]})]}),e.jsxs("div",{children:[e.jsx(re,{children:"Received on"}),e.jsx(we,{type:"date",value:_.received_on??"",onChange:L=>b({..._,received_on:L.target.value})})]}),e.jsxs("div",{children:[e.jsx(re,{children:"Permission"}),e.jsxs(Ns,{value:_.permission_status??"pending",onValueChange:L=>b({..._,permission_status:L}),children:[e.jsx(ws,{children:e.jsx(ks,{})}),e.jsx(js,{children:T0t.map(L=>e.jsx(nt,{value:L.value,children:L.label},L.value))})]})]}),e.jsxs("div",{children:[e.jsx(re,{children:"Status"}),e.jsxs(Ns,{value:_.status??"draft",onValueChange:L=>b({..._,status:L}),children:[e.jsx(ws,{children:e.jsx(ks,{})}),e.jsxs(js,{children:[e.jsx(nt,{value:"draft",children:"Draft"}),e.jsx(nt,{value:"approved",children:"Approved"})]})]})]}),e.jsxs("div",{children:[e.jsx(re,{children:"Market / area"}),e.jsx(we,{value:_.market??"",onChange:L=>b({..._,market:L.target.value})})]}),e.jsxs("div",{children:[e.jsx(re,{children:"Source link"}),e.jsx(we,{value:_.source_url??"",onChange:L=>b({..._,source_url:L.target.value}),placeholder:"https://"})]})]})]}),e.jsxs(Cr,{children:[e.jsx(B,{variant:"ghost",onClick:()=>b(null),children:"Cancel"}),e.jsx(B,{className:"bg-gradient-to-r from-violet-600 to-indigo-600",onClick:I,disabled:a.isPending||i.isPending,children:"Save"})]})]})}),e.jsx(Bs,{open:!!k,onOpenChange:L=>!L&&A(null),children:e.jsxs(Fs,{className:"max-w-md",children:[e.jsxs(qs,{children:[e.jsx($s,{children:"Delete this testimonial?"}),e.jsx(Ar,{children:"This can't be undone."})]}),e.jsxs(Cr,{children:[e.jsx(B,{variant:"ghost",onClick:()=>A(null),children:"Cancel"}),e.jsx(B,{variant:"destructive",onClick:()=>{c.mutate(k.id),A(null)},children:"Delete"})]})]})})]})}const M0t=[{value:"market_update",label:"Market Update"},{value:"local_video",label:"Local Video"},{value:"newsletter",label:"Newsletter"},{value:"stats_post",label:"Stats Post"},{value:"neighborhood",label:"Neighborhood Content"},{value:"speaking",label:"Speaking Opportunity"}],L0t=["idea","planned","drafted","scheduled","published","skipped"],H8n=["weekly","biweekly","monthly","quarterly","one_off"];function x$t(){const s=BJ("attract_market_presence",{orderBy:"planned_for",ascending:!0,label:"Commitment",duplicateOverrides:{status:"idea",published_url:null,results_notes:null,is_archived:!1}}),t=zAe(),n=$J();return{...s,commitments:s.items,quickTask:t,logActivity:n}}const P0t={content_type:"market_update",cadence:"monthly",status:"planned"};function G8n(s){if(!s)return"Unscheduled";const[t,n,r]=s.split(/[-/T]/).map(Number);return new Date(t,n-1,r).toLocaleDateString("en-US",{weekday:"short",month:"short",day:"numeric"})}const W8n={idea:"bg-slate-100 text-slate-600 border-slate-200",planned:"bg-blue-50 text-blue-700 border-blue-200",drafted:"bg-violet-50 text-violet-700 border-violet-200",scheduled:"bg-amber-50 text-amber-700 border-amber-200",published:"bg-emerald-50 text-emerald-700 border-emerald-200",skipped:"bg-rose-50 text-rose-700 border-rose-200"};function K8n(){const{commitments:s,isLoading:t,error:n,refetch:r,create:a,update:i,duplicate:l,archive:o,remove:c,quickTask:d,logActivity:u}=x$t(),[h,m]=N.useState(!1),[f,g]=N.useState("all"),[y,x]=N.useState(null),[_,b]=N.useState(null),k=N.useMemo(()=>s.filter(M=>h!==!!M.is_archived?!1:f==="all"||M.status===f),[s,h,f]),A=s.filter(M=>{if(M.status!=="published"||!M.planned_for)return!1;const[L,z,$]=M.planned_for.split(/[-/T]/).map(Number);return(Date.now()-new Date(L,z-1,$).getTime())/864e5<=30}).length,T=s.filter(M=>{if(M.is_archived||!M.planned_for||["published","skipped"].includes(M.status))return!1;const[L,z,$]=M.planned_for.split(/[-/T]/).map(Number);return new Date(L,z-1,$){var L;if(!((L=y==null?void 0:y.title)!=null&&L.trim())){ie.error("Add a title");return}const M={title:y.title.trim(),content_type:y.content_type??"market_update",cadence:y.cadence??"monthly",planned_for:y.planned_for||null,status:y.status??"planned",channel:y.channel||null,audience:y.audience||null,campaign:y.campaign||null,notes:y.notes||null,published_url:y.published_url||null,results_notes:y.results_notes||null};y.id?await i.mutateAsync({id:y.id,...M}):await a.mutateAsync(M),x(null)},I=async M=>{await i.mutateAsync({id:M.id,status:"published"}),await u.mutateAsync({title:`Published market presence: ${M.title}`,pillar:"produce",activityType:"market_presence_published"})};return e.jsxs("div",{children:[e.jsxs(cr,{to:"/attract/produce",className:"inline-flex items-center gap-1.5 text-[12px] text-slate-500 hover:text-violet-700 mb-3",children:[e.jsx(ka,{className:"h-3.5 w-3.5"})," Back to Produce"]}),e.jsx(Op,{eyebrow:"Produce → Tool",title:"Market Presence",description:"Consistency beats intensity. Commit to a cadence of market updates and local content, then track whether you actually shipped it.",actions:e.jsxs(e.Fragment,{children:[e.jsx(B,{variant:"outline",className:"rounded-full",onClick:()=>m(M=>!M),children:h?"Show active":"Show archived"}),e.jsxs(B,{className:"rounded-full bg-gradient-to-r from-violet-600 to-indigo-600",onClick:()=>x({...P0t}),children:[e.jsx(nn,{className:"h-4 w-4 mr-1.5"})," New Commitment"]})]})}),e.jsxs("div",{className:"grid grid-cols-2 sm:grid-cols-3 gap-3 mb-4",children:[e.jsxs(_e,{className:"p-4 rounded-2xl",children:[e.jsx("div",{className:"text-[22px] font-semibold tabular-nums text-slate-900",children:s.filter(M=>!M.is_archived).length}),e.jsx("div",{className:"text-[12px] text-slate-500",children:"Active commitments"})]}),e.jsxs(_e,{className:"p-4 rounded-2xl",children:[e.jsx("div",{className:"text-[22px] font-semibold tabular-nums text-emerald-600",children:A}),e.jsx("div",{className:"text-[12px] text-slate-500",children:"Published last 30 days"})]}),e.jsxs(_e,{className:"p-4 rounded-2xl",children:[e.jsx("div",{className:"text-[22px] font-semibold tabular-nums text-amber-600",children:T.length}),e.jsx("div",{className:"text-[12px] text-slate-500",children:"Past due"})]})]}),e.jsx("div",{className:"flex gap-2 flex-wrap mb-4",children:e.jsxs(Ns,{value:f,onValueChange:g,children:[e.jsx(ws,{className:"w-[190px] rounded-full",children:e.jsx(ks,{})}),e.jsxs(js,{children:[e.jsx(nt,{value:"all",children:"All statuses"}),L0t.map(M=>e.jsx(nt,{value:M,className:"capitalize",children:M},M))]})]})}),t&&e.jsx("div",{className:"space-y-2",children:[0,1,2].map(M=>e.jsx(xn,{className:"h-24 rounded-2xl"},M))}),!t&&n&&e.jsxs(_e,{className:"p-8 rounded-2xl text-center",children:[e.jsx(Uo,{className:"h-6 w-6 text-rose-500 mx-auto mb-2"}),e.jsx("div",{className:"font-semibold text-slate-900",children:"Couldn't load commitments"}),e.jsx("div",{className:"text-[13px] text-slate-600 mt-1",children:n.message}),e.jsxs(B,{variant:"outline",className:"rounded-full mt-4",onClick:()=>r(),children:[e.jsx(hf,{className:"h-3.5 w-3.5 mr-1.5"})," Retry"]})]}),!t&&!n&&k.length===0&&e.jsxs(_e,{className:"p-10 rounded-2xl text-center border-dashed",children:[e.jsx("div",{className:"h-12 w-12 rounded-2xl bg-violet-50 text-violet-600 grid place-items-center mx-auto mb-3",children:e.jsx(Y0,{className:"h-6 w-6"})}),e.jsx("div",{className:"text-[16px] font-semibold text-slate-900",children:"No commitments yet"}),e.jsx("p",{className:"text-[13.5px] text-slate-600 mt-1.5 max-w-md mx-auto",children:"Start with one: a monthly market update. Set the date, ship it, mark it published — that rhythm is what agents notice."}),!h&&e.jsxs(B,{className:"rounded-full mt-4 bg-gradient-to-r from-violet-600 to-indigo-600",onClick:()=>x({...P0t}),children:[e.jsx(nn,{className:"h-4 w-4 mr-1.5"})," Add a commitment"]})]}),e.jsx("div",{className:"space-y-2",children:k.map(M=>{var L;return e.jsxs(_e,{className:"p-4 rounded-2xl",children:[e.jsxs("div",{className:"flex items-start justify-between gap-3 flex-wrap",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsx("span",{className:"text-[15px] font-semibold text-slate-900",children:M.title}),e.jsx(We,{variant:"outline",className:"rounded-full",children:((L=M0t.find(z=>z.value===M.content_type))==null?void 0:L.label)??M.content_type}),e.jsx(We,{variant:"outline",className:`rounded-full capitalize ${W8n[M.status]??""}`,children:M.status}),e.jsx(We,{variant:"outline",className:"rounded-full capitalize",children:M.cadence.replace("_"," ")})]}),e.jsx("div",{className:"text-[12.5px] text-slate-500 mt-1",children:[G8n(M.planned_for),M.channel,M.audience].filter(Boolean).join(" · ")}),M.notes&&e.jsx("div",{className:"text-[12.5px] text-slate-600 mt-1 line-clamp-2",children:M.notes})]}),e.jsxs("div",{className:"flex gap-1",children:[e.jsx(B,{size:"icon",variant:"ghost",className:"h-8 w-8",title:"Edit",onClick:()=>x(M),children:e.jsx(Ja,{className:"h-3.5 w-3.5"})}),e.jsx(B,{size:"icon",variant:"ghost",className:"h-8 w-8",title:"Duplicate",onClick:()=>l.mutate(M),children:e.jsx(Pa,{className:"h-3.5 w-3.5"})}),e.jsx(B,{size:"icon",variant:"ghost",className:"h-8 w-8",title:M.is_archived?"Restore":"Archive",onClick:()=>o.mutate({id:M.id,archived:!M.is_archived}),children:e.jsx(xg,{className:"h-3.5 w-3.5"})}),e.jsx(B,{size:"icon",variant:"ghost",className:"h-8 w-8 text-rose-600",title:"Delete",onClick:()=>b(M),children:e.jsx(qn,{className:"h-3.5 w-3.5"})})]})]}),e.jsxs("div",{className:"flex gap-2 mt-3 flex-wrap",children:[M.status!=="published"&&e.jsxs(B,{size:"sm",variant:"outline",className:"rounded-full",onClick:()=>I(M),children:[e.jsx(Hr,{className:"h-3.5 w-3.5 mr-1.5"})," Mark published"]}),e.jsxs(B,{size:"sm",variant:"outline",className:"rounded-full",onClick:()=>d.mutate({title:`Create: ${M.title}`,dueAt:M.planned_for?`${M.planned_for}T09:00:00`:new Date().toISOString(),notes:M.notes,touchType:"content"}),children:[e.jsx(zm,{className:"h-3.5 w-3.5 mr-1.5"})," Add task"]}),e.jsx(B,{size:"sm",variant:"ghost",className:"rounded-full",asChild:!0,children:e.jsxs(cr,{to:"/attract/influence/content-studio",children:[e.jsx(Cn,{className:"h-3.5 w-3.5 mr-1.5"})," Draft it"]})})]})]},M.id)})}),e.jsx(Bs,{open:!!y,onOpenChange:M=>!M&&x(null),children:e.jsxs(Fs,{className:"max-w-xl max-h-[90vh] overflow-y-auto",children:[e.jsxs(qs,{children:[e.jsx($s,{children:y!=null&&y.id?"Edit commitment":"New commitment"}),e.jsx(Ar,{children:"Pick something you can genuinely sustain."})]}),y&&e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{children:[e.jsx(re,{children:"Title *"}),e.jsx(we,{value:y.title??"",onChange:M=>x({...y,title:M.target.value}),placeholder:"e.g. October market update video"})]}),e.jsxs("div",{className:"grid sm:grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(re,{children:"Type"}),e.jsxs(Ns,{value:y.content_type??"market_update",onValueChange:M=>x({...y,content_type:M}),children:[e.jsx(ws,{children:e.jsx(ks,{})}),e.jsx(js,{children:M0t.map(M=>e.jsx(nt,{value:M.value,children:M.label},M.value))})]})]}),e.jsxs("div",{children:[e.jsx(re,{children:"Cadence"}),e.jsxs(Ns,{value:y.cadence??"monthly",onValueChange:M=>x({...y,cadence:M}),children:[e.jsx(ws,{children:e.jsx(ks,{})}),e.jsx(js,{children:H8n.map(M=>e.jsx(nt,{value:M,className:"capitalize",children:M.replace("_"," ")},M))})]})]}),e.jsxs("div",{children:[e.jsx(re,{children:"Planned for"}),e.jsx(we,{type:"date",value:y.planned_for??"",onChange:M=>x({...y,planned_for:M.target.value})})]}),e.jsxs("div",{children:[e.jsx(re,{children:"Status"}),e.jsxs(Ns,{value:y.status??"planned",onValueChange:M=>x({...y,status:M}),children:[e.jsx(ws,{children:e.jsx(ks,{})}),e.jsx(js,{children:L0t.map(M=>e.jsx(nt,{value:M,className:"capitalize",children:M},M))})]})]}),e.jsxs("div",{children:[e.jsx(re,{children:"Channel"}),e.jsx(we,{value:y.channel??"",onChange:M=>x({...y,channel:M.target.value}),placeholder:"Instagram, email, YouTube"})]}),e.jsxs("div",{children:[e.jsx(re,{children:"Audience"}),e.jsx(we,{value:y.audience??"",onChange:M=>x({...y,audience:M.target.value}),placeholder:"Agents, sphere, neighborhood"})]})]}),e.jsxs("div",{children:[e.jsx(re,{children:"Notes"}),e.jsx(Ws,{rows:3,value:y.notes??"",onChange:M=>x({...y,notes:M.target.value})})]}),e.jsxs("div",{className:"grid sm:grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(re,{children:"Published URL"}),e.jsx(we,{value:y.published_url??"",onChange:M=>x({...y,published_url:M.target.value}),placeholder:"https://"})]}),e.jsxs("div",{children:[e.jsx(re,{children:"Results"}),e.jsx(we,{value:y.results_notes??"",onChange:M=>x({...y,results_notes:M.target.value}),placeholder:"Reach, replies, leads"})]})]})]}),e.jsxs(Cr,{children:[e.jsx(B,{variant:"ghost",onClick:()=>x(null),children:"Cancel"}),e.jsx(B,{className:"bg-gradient-to-r from-violet-600 to-indigo-600",onClick:P,disabled:a.isPending||i.isPending,children:"Save"})]})]})}),e.jsx(Bs,{open:!!_,onOpenChange:M=>!M&&b(null),children:e.jsxs(Fs,{className:"max-w-md",children:[e.jsxs(qs,{children:[e.jsx($s,{children:"Delete this commitment?"}),e.jsx(Ar,{children:"This can't be undone."})]}),e.jsxs(Cr,{children:[e.jsx(B,{variant:"ghost",onClick:()=>b(null),children:"Cancel"}),e.jsx(B,{variant:"destructive",onClick:()=>{c.mutate(_.id),b(null)},children:"Delete"})]})]})})]})}function I0t(s){if(!s)return null;const[t]=s.split("T");return t||null}const ore={draft:{label:"Content",icon:Cn,cls:"bg-violet-50 text-violet-700 border-violet-200"},presence:{label:"Market presence",icon:Y0,cls:"bg-blue-50 text-blue-700 border-blue-200"},speaking:{label:"Speaking",icon:uj,cls:"bg-amber-50 text-amber-700 border-amber-200"}};function Y8n(){const{drafts:s,isLoading:t,save:n}=h$t(),{commitments:r,isLoading:a}=x$t(),i=g$t(),l=zAe(),[o,c]=N.useState(()=>{const T=new Date;return new Date(T.getFullYear(),T.getMonth(),1)}),[d,u]=N.useState("all"),[h,m]=N.useState(null),f=N.useMemo(()=>(i.items??[]).filter(T=>!T.is_archived).map(T=>({id:T.id,kind:"speaking",title:T.title,date:I0t(T.starts_at),status:T.status,href:"/attract/influence/speaking"})),[i.items]),g=N.useMemo(()=>{const T=s.map(I=>({id:I.id,kind:"draft",title:I.topic||I.mode.replace(/_/g," "),date:I0t(I.planned_at??I.posted_at??null),status:I.status,href:"/attract/influence/content-studio"})),P=r.filter(I=>!I.is_archived).map(I=>({id:I.id,kind:"presence",title:I.title,date:I.planned_for,status:I.status,href:"/attract/produce/market-presence"}));return[...T,...P,...f].filter(I=>d==="all"||I.kind===d)},[s,r,f,d]),y=`${o.getFullYear()}-${String(o.getMonth()+1).padStart(2,"0")}`,x=g.filter(T=>{var P;return(P=T.date)==null?void 0:P.startsWith(y)}),_=g.filter(T=>!T.date),b=N.useMemo(()=>{const T=new Date(o.getFullYear(),o.getMonth(),1),P=new Date(T);return P.setDate(T.getDate()-T.getDay()),Array.from({length:42},(I,M)=>{const L=new Date(P);L.setDate(P.getDate()+M);const z=`${L.getFullYear()}-${String(L.getMonth()+1).padStart(2,"0")}-${String(L.getDate()).padStart(2,"0")}`;return{date:L,key:z,inMonth:L.getMonth()===o.getMonth(),items:g.filter($=>$.date===z)}})},[o,g]),k=(()=>{const T=new Date;return`${T.getFullYear()}-${String(T.getMonth()+1).padStart(2,"0")}-${String(T.getDate()).padStart(2,"0")}`})(),A=t||a;return e.jsxs("div",{children:[e.jsxs(cr,{to:"/attract/influence",className:"inline-flex items-center gap-1.5 text-[12px] text-slate-500 hover:text-violet-700 mb-3",children:[e.jsx(ka,{className:"h-3.5 w-3.5"})," Back to Influence"]}),e.jsx(Op,{eyebrow:"Produce + Influence → Tool",title:"Content Calendar",description:"One month view of everything you've committed to publish — Content Studio drafts, market presence commitments, and speaking dates.",actions:e.jsx(B,{className:"rounded-full bg-gradient-to-r from-violet-600 to-indigo-600",asChild:!0,children:e.jsxs(cr,{to:"/attract/influence/content-studio",children:[e.jsx(nn,{className:"h-4 w-4 mr-1.5"})," New Draft"]})})}),e.jsxs("div",{className:"flex items-center justify-between gap-2 flex-wrap mb-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(B,{size:"icon",variant:"outline",className:"rounded-full h-9 w-9",onClick:()=>c(new Date(o.getFullYear(),o.getMonth()-1,1)),children:e.jsx(Fc,{className:"h-4 w-4"})}),e.jsx("div",{className:"text-[16px] font-semibold text-slate-900 min-w-[170px] text-center",children:o.toLocaleString("en-US",{month:"long",year:"numeric"})}),e.jsx(B,{size:"icon",variant:"outline",className:"rounded-full h-9 w-9",onClick:()=>c(new Date(o.getFullYear(),o.getMonth()+1,1)),children:e.jsx(Qa,{className:"h-4 w-4"})}),e.jsx(B,{variant:"ghost",className:"rounded-full",onClick:()=>{const T=new Date;c(new Date(T.getFullYear(),T.getMonth(),1))},children:"Today"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(We,{variant:"outline",className:"rounded-full",children:[x.length," scheduled this month"]}),e.jsxs(Ns,{value:d,onValueChange:T=>u(T),children:[e.jsx(ws,{className:"w-[180px] rounded-full",children:e.jsx(ks,{})}),e.jsxs(js,{children:[e.jsx(nt,{value:"all",children:"All types"}),e.jsx(nt,{value:"draft",children:"Content drafts"}),e.jsx(nt,{value:"presence",children:"Market presence"}),e.jsx(nt,{value:"speaking",children:"Speaking"})]})]})]})]}),A?e.jsx(xn,{className:"h-[560px] rounded-2xl"}):e.jsxs(_e,{className:"rounded-2xl overflow-hidden",children:[e.jsx("div",{className:"grid grid-cols-7 bg-slate-50 border-b",children:["Sun","Mon","Tue","Wed","Thu","Fri","Sat"].map(T=>e.jsx("div",{className:"px-2 py-2 text-[11px] uppercase tracking-wider text-slate-500 font-semibold text-center",children:T},T))}),e.jsx("div",{className:"grid grid-cols-7",children:b.map(T=>e.jsxs("div",{className:`min-h-[96px] border-b border-r p-1.5 ${T.inMonth?"":"bg-slate-50/60"}`,children:[e.jsx("div",{className:`text-[11.5px] font-medium mb-1 ${T.key===k?"text-violet-700":T.inMonth?"text-slate-700":"text-slate-400"}`,children:T.date.getDate()}),e.jsxs("div",{className:"space-y-1",children:[T.items.slice(0,3).map(P=>{const I=ore[P.kind];return e.jsx(cr,{to:P.href,className:`block truncate rounded-md border px-1.5 py-0.5 text-[11px] ${I.cls}`,title:P.title,children:P.title},`${P.kind}-${P.id}`)}),T.items.length>3&&e.jsxs("div",{className:"text-[10.5px] text-slate-500 px-1",children:["+",T.items.length-3," more"]})]})]},T.key))})]}),e.jsxs("div",{className:"grid gap-4 md:grid-cols-2 mt-5",children:[e.jsxs(_e,{className:"p-5 rounded-2xl",children:[e.jsxs("div",{className:"text-[15px] font-semibold text-slate-900 mb-1",children:["Unscheduled (",_.length,")"]}),e.jsx("p",{className:"text-[12.5px] text-slate-600 mb-3",children:"Give these a date so they show on the calendar."}),_.length===0&&e.jsx("div",{className:"text-[13px] text-slate-500",children:"Everything has a date. Nice."}),e.jsx("div",{className:"space-y-2",children:_.slice(0,8).map(T=>e.jsxs("div",{className:"flex items-center justify-between gap-2 rounded-xl bg-slate-50 px-3 py-2",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"text-[13px] font-medium text-slate-900 truncate capitalize",children:T.title}),e.jsxs("div",{className:"text-[11.5px] text-slate-500",children:[ore[T.kind].label," · ",T.status]})]}),T.kind==="draft"?e.jsx(B,{size:"sm",variant:"outline",className:"rounded-full flex-shrink-0",onClick:()=>m({id:T.id,title:T.title,date:k}),children:"Schedule"}):e.jsx(B,{size:"sm",variant:"ghost",className:"rounded-full flex-shrink-0",asChild:!0,children:e.jsx(cr,{to:T.href,children:"Open"})})]},`${T.kind}-${T.id}`))})]}),e.jsxs(_e,{className:"p-5 rounded-2xl",children:[e.jsx("div",{className:"text-[15px] font-semibold text-slate-900 mb-1",children:"This month at a glance"}),e.jsx("p",{className:"text-[12.5px] text-slate-600 mb-3",children:"Keep a steady rhythm across all three surfaces."}),e.jsx("div",{className:"space-y-2",children:Object.keys(ore).map(T=>{const P=ore[T],I=P.icon,M=x.filter(L=>L.kind===T).length;return e.jsxs("div",{className:"flex items-center gap-3 rounded-xl bg-slate-50 px-3 py-2",children:[e.jsx("div",{className:`h-8 w-8 rounded-lg grid place-items-center border ${P.cls}`,children:e.jsx(I,{className:"h-4 w-4"})}),e.jsx("div",{className:"text-[13.5px] font-medium text-slate-900 flex-1",children:P.label}),e.jsx("div",{className:"text-[16px] font-semibold tabular-nums text-slate-900",children:M})]},T)})}),e.jsxs(B,{variant:"outline",className:"rounded-full mt-4 w-full",onClick:()=>l.mutate({title:`Plan content for ${o.toLocaleString("en-US",{month:"long"})}`,dueAt:new Date().toISOString(),touchType:"content"}),children:[e.jsx(zm,{className:"h-3.5 w-3.5 mr-1.5"})," Add planning block to Today's Plan"]}),e.jsx(B,{variant:"ghost",className:"rounded-full mt-2 w-full",asChild:!0,children:e.jsxs(cr,{to:"/attract/produce/market-presence",children:[e.jsx(ld,{className:"h-3.5 w-3.5 mr-1.5"})," Manage market presence cadence"]})})]})]}),e.jsx(Bs,{open:!!h,onOpenChange:T=>!T&&m(null),children:e.jsxs(Fs,{className:"max-w-md",children:[e.jsxs(qs,{children:[e.jsx($s,{children:"Schedule draft"}),e.jsx(Ar,{className:"capitalize",children:h==null?void 0:h.title})]}),h&&e.jsxs("div",{children:[e.jsx(re,{children:"Planned date"}),e.jsx(we,{type:"date",value:h.date,onChange:T=>m({...h,date:T.target.value})})]}),e.jsxs(Cr,{children:[e.jsx(B,{variant:"ghost",onClick:()=>m(null),children:"Cancel"}),e.jsx(B,{className:"bg-gradient-to-r from-violet-600 to-indigo-600",onClick:async()=>{h&&(await n.mutateAsync({id:h.id,planned_at:`${h.date}T09:00:00`}),m(null))},children:"Save"})]})]})})]})}const D0t=[{value:"birthday",label:"Birthday"},{value:"work_anniversary",label:"Work Anniversary"},{value:"license_anniversary",label:"License Anniversary"},{value:"production_milestone",label:"Production Milestone"},{value:"team_milestone",label:"Team Milestone"},{value:"family_milestone",label:"Family Milestone"},{value:"custom",label:"Custom Date"}];function Z8n(s){const[t,n,r]=s.split(/[-/T]/).map(Number);return{y:t,m:n,d:r}}function sBe(s,t=new Date){const{y:n,m:r,d:a}=Z8n(s.milestone_on);if(!s.recurs_annually)return new Date(n,r-1,a);const i=new Date(t.getFullYear(),r-1,a),l=new Date(t.getFullYear(),t.getMonth(),t.getDate());return i{const l=[];return r.forEach(o=>{const c=[o.preferred_name||o.first_name,o.last_name].filter(Boolean).join(" ");[["birthday",o.birthday_on,`${c} — Birthday`],["work_anniversary",o.work_anniversary_on,`${c} — Work Anniversary`],["license_anniversary",o.license_anniversary_on,`${c} — License Anniversary`]].forEach(([d,u,h])=>{u&&l.push({id:`agent:${o.id}:${d}`,user_id:o.user_id,title:h,milestone_type:d,milestone_on:String(u).slice(0,10),recurs_annually:!0,linked_agent_ids:[o.id],notes:null,last_celebrated_at:null,is_archived:!1,created_at:o.created_at,updated_at:o.updated_at})})}),l},[r]),i=N.useMemo(()=>{const l=new Set(s.items.filter(c=>!c.is_archived).map(c=>{var d;return`${c.milestone_type}|${c.milestone_on.slice(5,10)}|${((d=c.linked_agent_ids)==null?void 0:d[0])??""}`}));return[...s.items.filter(c=>!c.is_archived),...a.filter(c=>!l.has(`${c.milestone_type}|${c.milestone_on.slice(5,10)}|${c.linked_agent_ids[0]}`))].map(c=>({item:c,next:sBe(c)})).map(c=>({...c,days:y$t(c.next)})).filter(c=>c.days>=0).sort((c,d)=>c.days-d.days)},[s.items,a]);return{...s,milestones:s.items,derived:a,upcoming:i,quickTask:t,logActivity:n}}const R0t={milestone_type:"birthday",recurs_annually:!0,linked_agent_ids:[]};function Q8n(s){return s.toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric"})}function J8n(){var z;const{milestones:s,upcoming:t,isLoading:n,error:r,refetch:a,create:i,update:l,duplicate:o,archive:c,remove:d,quickTask:u,logActivity:h}=X8n(),m=jb(),f=(m==null?void 0:m.agents)??(m==null?void 0:m.items)??[],[g,y]=N.useState(!1),[x,_]=N.useState("90"),[b,k]=N.useState(null),[A,T]=N.useState(null),P=N.useMemo(()=>{if(g)return s.filter(V=>V.is_archived).map(V=>({item:V,next:sBe(V),days:y$t(sBe(V))}));const $=x==="all"?1/0:Number(x);return t.filter(V=>V.days<=$)},[s,t,g,x]),I=$=>{const V=f.find(W=>W.id===$);return V?[V.preferred_name||V.first_name,V.last_name].filter(Boolean).join(" "):"Agent"},M=async()=>{var V;if(!((V=b==null?void 0:b.title)!=null&&V.trim())||!(b!=null&&b.milestone_on)){ie.error("Title and date are required");return}const $={title:b.title.trim(),milestone_type:b.milestone_type??"birthday",milestone_on:b.milestone_on,recurs_annually:b.recurs_annually??!0,linked_agent_ids:b.linked_agent_ids??[],notes:b.notes||null};b.id?await l.mutateAsync({id:b.id,...$}):await i.mutateAsync($),k(null)},L=async $=>{var V;await l.mutateAsync({id:$.id,last_celebrated_at:new Date().toISOString()}),await h.mutateAsync({title:`Celebrated: ${$.title}`,pillar:"connect",activityType:"milestone_celebrated",agentId:((V=$.linked_agent_ids)==null?void 0:V[0])??null})};return e.jsxs("div",{children:[e.jsxs(cr,{to:"/attract/connect",className:"inline-flex items-center gap-1.5 text-[12px] text-slate-500 hover:text-violet-700 mb-3",children:[e.jsx(ka,{className:"h-3.5 w-3.5"})," Back to Connect"]}),e.jsx(Op,{eyebrow:"Connect → Tool",title:"Milestones & Celebrations",description:"Remember the dates that matter to the agents in your pipeline. Recurring milestones roll forward every year so you never miss the reason to reach out.",actions:e.jsxs(e.Fragment,{children:[e.jsx(B,{variant:"outline",className:"rounded-full",onClick:()=>y($=>!$),children:g?"Show upcoming":"Show archived"}),e.jsxs(B,{className:"rounded-full bg-gradient-to-r from-violet-600 to-indigo-600",onClick:()=>k({...R0t}),children:[e.jsx(nn,{className:"h-4 w-4 mr-1.5"})," Add Milestone"]})]})}),e.jsxs("div",{className:"grid grid-cols-2 sm:grid-cols-3 gap-3 mb-4",children:[e.jsxs(_e,{className:"p-4 rounded-2xl",children:[e.jsx("div",{className:"text-[22px] font-semibold tabular-nums text-slate-900",children:t.filter($=>$.days<=7).length}),e.jsx("div",{className:"text-[12px] text-slate-500",children:"Next 7 days"})]}),e.jsxs(_e,{className:"p-4 rounded-2xl",children:[e.jsx("div",{className:"text-[22px] font-semibold tabular-nums text-violet-600",children:t.filter($=>$.days<=30).length}),e.jsx("div",{className:"text-[12px] text-slate-500",children:"Next 30 days"})]}),e.jsxs(_e,{className:"p-4 rounded-2xl",children:[e.jsx("div",{className:"text-[22px] font-semibold tabular-nums text-slate-900",children:s.filter($=>!$.is_archived).length}),e.jsx("div",{className:"text-[12px] text-slate-500",children:"Tracked total"})]})]}),!g&&e.jsx("div",{className:"flex gap-2 flex-wrap mb-4",children:e.jsxs(Ns,{value:x,onValueChange:$=>_($),children:[e.jsx(ws,{className:"w-[190px] rounded-full",children:e.jsx(ks,{})}),e.jsxs(js,{children:[e.jsx(nt,{value:"30",children:"Next 30 days"}),e.jsx(nt,{value:"90",children:"Next 90 days"}),e.jsx(nt,{value:"all",children:"All upcoming"})]})]})}),n&&e.jsx("div",{className:"space-y-2",children:[0,1,2].map($=>e.jsx(xn,{className:"h-20 rounded-2xl"},$))}),!n&&r&&e.jsxs(_e,{className:"p-8 rounded-2xl text-center",children:[e.jsx(Uo,{className:"h-6 w-6 text-rose-500 mx-auto mb-2"}),e.jsx("div",{className:"font-semibold text-slate-900",children:"Couldn't load milestones"}),e.jsx("div",{className:"text-[13px] text-slate-600 mt-1",children:r.message}),e.jsxs(B,{variant:"outline",className:"rounded-full mt-4",onClick:()=>a(),children:[e.jsx(hf,{className:"h-3.5 w-3.5 mr-1.5"})," Retry"]})]}),!n&&!r&&P.length===0&&e.jsxs(_e,{className:"p-10 rounded-2xl text-center border-dashed",children:[e.jsx("div",{className:"h-12 w-12 rounded-2xl bg-violet-50 text-violet-600 grid place-items-center mx-auto mb-3",children:e.jsx(Fm,{className:"h-6 w-6"})}),e.jsx("div",{className:"text-[16px] font-semibold text-slate-900",children:g?"Nothing archived":"No milestones in this window"}),e.jsx("p",{className:"text-[13.5px] text-slate-600 mt-1.5 max-w-md mx-auto",children:"Add birthdays, license anniversaries, and production milestones for the agents you're building relationships with."}),!g&&e.jsxs(B,{className:"rounded-full mt-4 bg-gradient-to-r from-violet-600 to-indigo-600",onClick:()=>k({...R0t}),children:[e.jsx(nn,{className:"h-4 w-4 mr-1.5"})," Add a milestone"]})]}),e.jsx("div",{className:"space-y-2",children:P.map(({item:$,next:V,days:W})=>{var X,te;const G=String($.id).startsWith("agent:");return e.jsxs(_e,{className:"p-4 rounded-2xl",children:[e.jsxs("div",{className:"flex items-start justify-between gap-3 flex-wrap",children:[e.jsxs("div",{className:"flex items-start gap-3 min-w-0",children:[e.jsx("div",{className:"h-11 w-11 rounded-xl bg-violet-50 text-violet-700 grid place-items-center flex-shrink-0",children:e.jsxs("div",{className:"text-center leading-none",children:[e.jsx("div",{className:"text-[9px] uppercase tracking-wider",children:V.toLocaleString("en-US",{month:"short"})}),e.jsx("div",{className:"text-[15px] font-semibold",children:V.getDate()})]})}),e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsx("span",{className:"text-[15px] font-semibold text-slate-900",children:$.title}),e.jsx(We,{variant:"outline",className:"rounded-full",children:((X=D0t.find(ne=>ne.value===$.milestone_type))==null?void 0:X.label)??$.milestone_type}),G&&e.jsx(We,{variant:"outline",className:"rounded-full bg-violet-50 text-violet-700 border-violet-200",children:"From contact record"}),!g&&e.jsx(We,{variant:"outline",className:`rounded-full ${W<=7?"bg-amber-50 text-amber-700 border-amber-200":""}`,children:W===0?"Today":W===1?"Tomorrow":`in ${W} days`}),$.recurs_annually&&e.jsx(We,{variant:"outline",className:"rounded-full",children:"Annual"})]}),e.jsxs("div",{className:"text-[12.5px] text-slate-500 mt-1",children:[Q8n(V),(te=$.linked_agent_ids)!=null&&te.length?` · ${$.linked_agent_ids.map(I).join(", ")}`:"",$.last_celebrated_at?` · last celebrated ${new Date($.last_celebrated_at).toLocaleDateString("en-US")}`:""]}),$.notes&&e.jsx("div",{className:"text-[12.5px] text-slate-600 mt-1 line-clamp-2",children:$.notes})]})]}),e.jsx("div",{className:"flex gap-1",children:G?e.jsx(B,{size:"sm",variant:"ghost",className:"rounded-full text-[12px]",asChild:!0,children:e.jsx(cr,{to:`/attract/agents/${$.linked_agent_ids[0]}`,children:"Open contact"})}):e.jsxs(e.Fragment,{children:[e.jsx(B,{size:"icon",variant:"ghost",className:"h-8 w-8",title:"Edit",onClick:()=>k($),children:e.jsx(Ja,{className:"h-3.5 w-3.5"})}),e.jsx(B,{size:"icon",variant:"ghost",className:"h-8 w-8",title:"Duplicate",onClick:()=>o.mutate($),children:e.jsx(Pa,{className:"h-3.5 w-3.5"})}),e.jsx(B,{size:"icon",variant:"ghost",className:"h-8 w-8",title:$.is_archived?"Restore":"Archive",onClick:()=>c.mutate({id:$.id,archived:!$.is_archived}),children:e.jsx(xg,{className:"h-3.5 w-3.5"})}),e.jsx(B,{size:"icon",variant:"ghost",className:"h-8 w-8 text-rose-600",title:"Delete",onClick:()=>T($),children:e.jsx(qn,{className:"h-3.5 w-3.5"})})]})})]}),e.jsxs("div",{className:"flex gap-2 mt-3 flex-wrap",children:[e.jsxs(B,{size:"sm",variant:"outline",className:"rounded-full",onClick:()=>{var ne;return u.mutate({title:`Reach out: ${$.title}`,dueAt:V.toISOString(),notes:$.notes,touchType:"celebration",agentId:((ne=$.linked_agent_ids)==null?void 0:ne[0])??null})},children:[e.jsx(zm,{className:"h-3.5 w-3.5 mr-1.5"})," Add reach-out task"]}),!G&&e.jsxs(B,{size:"sm",variant:"outline",className:"rounded-full",onClick:()=>L($),children:[e.jsx(uf,{className:"h-3.5 w-3.5 mr-1.5"})," Mark celebrated"]})]})]},$.id)})}),e.jsx(Bs,{open:!!b,onOpenChange:$=>!$&&k(null),children:e.jsxs(Fs,{className:"max-w-xl max-h-[90vh] overflow-y-auto",children:[e.jsxs(qs,{children:[e.jsx($s,{children:b!=null&&b.id?"Edit milestone":"Add milestone"}),e.jsx(Ar,{children:"Annual milestones roll forward automatically each year."})]}),b&&e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{children:[e.jsx(re,{children:"Title *"}),e.jsx(we,{value:b.title??"",onChange:$=>k({...b,title:$.target.value}),placeholder:"e.g. Sarah's birthday"})]}),e.jsxs("div",{className:"grid sm:grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(re,{children:"Type"}),e.jsxs(Ns,{value:b.milestone_type??"birthday",onValueChange:$=>k({...b,milestone_type:$}),children:[e.jsx(ws,{children:e.jsx(ks,{})}),e.jsx(js,{children:D0t.map($=>e.jsx(nt,{value:$.value,children:$.label},$.value))})]})]}),e.jsxs("div",{children:[e.jsx(re,{children:"Date *"}),e.jsx(we,{type:"date",value:b.milestone_on??"",onChange:$=>k({...b,milestone_on:$.target.value})})]})]}),e.jsxs("div",{className:"flex items-center justify-between rounded-xl border border-slate-200 px-4 py-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[13.5px] font-medium text-slate-900",children:"Repeats every year"}),e.jsx("div",{className:"text-[12px] text-slate-600",children:"Turn off for one-time milestones."})]}),e.jsx(zn,{checked:b.recurs_annually??!0,onCheckedChange:$=>k({...b,recurs_annually:$})})]}),f.length>0&&e.jsxs("div",{children:[e.jsx(re,{children:"Link to agent"}),e.jsxs(Ns,{value:((z=b.linked_agent_ids)==null?void 0:z[0])??"none",onValueChange:$=>k({...b,linked_agent_ids:$==="none"?[]:[$]}),children:[e.jsx(ws,{children:e.jsx(ks,{placeholder:"Optional"})}),e.jsxs(js,{children:[e.jsx(nt,{value:"none",children:"No agent"}),f.map($=>e.jsx(nt,{value:$.id,children:I($.id)},$.id))]})]})]}),e.jsxs("div",{children:[e.jsx(re,{children:"Notes"}),e.jsx(Ws,{rows:3,value:b.notes??"",onChange:$=>k({...b,notes:$.target.value}),placeholder:"Gift ideas, personal details, how you'll reach out"})]})]}),e.jsxs(Cr,{children:[e.jsx(B,{variant:"ghost",onClick:()=>k(null),children:"Cancel"}),e.jsx(B,{className:"bg-gradient-to-r from-violet-600 to-indigo-600",onClick:M,disabled:i.isPending||l.isPending,children:"Save"})]})]})}),e.jsx(Bs,{open:!!A,onOpenChange:$=>!$&&T(null),children:e.jsxs(Fs,{className:"max-w-md",children:[e.jsxs(qs,{children:[e.jsx($s,{children:"Delete this milestone?"}),e.jsx(Ar,{children:"This can't be undone."})]}),e.jsxs(Cr,{children:[e.jsx(B,{variant:"ghost",onClick:()=>T(null),children:"Cancel"}),e.jsx(B,{variant:"destructive",onClick:()=>{d.mutate(A.id),T(null)},children:"Delete"})]})]})})]})}function eDn(){var c;const{shareToken:s}=uo(),[t,n]=N.useState("loading"),[r,a]=N.useState(null),[i,l]=N.useState(!1);N.useEffect(()=>{(async()=>{if(!s){n("not_found");return}const{data:d,error:u}=await H.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"),H.rpc("public_log_attract_kit_event",{_token:s,_event_type:"page_view",_item_id:null,_metadata:{}})})()},[s]);const o=(d,u,h)=>{s&&H.rpc("public_log_attract_kit_event",{_token:s,_event_type:d,_item_id:u??null,_metadata:h??{}})};return t==="loading"?e.jsx("div",{className:"min-h-screen bg-[#05070f] grid place-items-center text-slate-300",children:"Loading…"}):t!=="ok"?e.jsx("div",{className:"min-h-screen bg-[#05070f] grid place-items-center px-6",children:e.jsxs(_e,{className:"max-w-md w-full p-8 bg-white/5 border-white/10 text-slate-100 rounded-2xl text-center",children:[e.jsx(Uo,{className:"h-8 w-8 text-amber-400 mx-auto"}),e.jsx("div",{className:"mt-3 text-xl font-semibold",children:t==="expired"?"This kit has expired":t==="revoked"?"This kit is no longer available":t==="not_found"?"This kit could not be found":"Something went wrong"}),e.jsx("p",{className:"text-slate-400 mt-2 text-sm",children:"Please reach out to the person who shared it with you for an updated link."})]})}):e.jsx("div",{className:"min-h-screen bg-[#05070f]",children:e.jsxs("div",{className:"max-w-3xl mx-auto py-6 px-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-[10.5px] uppercase tracking-widest text-violet-400 font-semibold justify-center py-3",children:[e.jsx(Cn,{className:"h-3.5 w-3.5"})," A LevelUp Attract kit"]}),e.jsx(m$t,{kit:r.kit,items:r.items,owner:r.owner,personalNote:(c=r.share)==null?void 0:c.personal_note,mode:"public",onEvent:o}),e.jsx(_e,{className:"mt-6 p-6 bg-white/5 border-white/10 text-slate-100 rounded-2xl",children:i?e.jsx(tDn,{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 tDn({token:s,onSent:t,onEvent:n}){const[r,a]=N.useState(""),[i,l]=N.useState(""),[o,c]=N.useState(""),[d,u]=N.useState(!1),h=async()=>{if(o.trim().length<2)return ie.error("Please add a short message");u(!0);const{data:m,error:f}=await H.rpc("public_submit_attract_kit_question",{_token:s,_name:r,_email:i,_message:o});if(u(!1),f||!(m!=null&&m.ok))return ie.error("Could not send — please try again");ie.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(we,{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(we,{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(Ws,{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"),ie.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 sDn(){const{slug:s}=uo(),[t]=$c(),n=t.get("inv")||null,[r,a]=N.useState("loading"),[i,l]=N.useState(null),[o,c]=N.useState({name:"",email:"",phone:"",answers:{}}),[d,u]=N.useState(!1),[h,m]=N.useState(null);N.useEffect(()=>{s&&(async()=>{const{data:y,error:x}=await H.rpc("public_get_attract_event",{_slug:s});if(x||!y||y.error){a((y==null?void 0:y.error)||"not_found");return}l(y),a("ok"),n&&H.rpc("public_track_attract_invitation_view",{_token:n})})()},[s,n]);const f=async()=>{u(!0);const{data:y,error:x}=await H.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),x){alert("Something went wrong. Please try again.");return}const _=y;if(_!=null&&_.error){alert(_.error==="invalid_email"?"That email looks off.":_.error==="full"?"This event is full.":"Could not register.");return}m(_)},g=()=>{if(!i)return;const y=new Blob([BBt(i)],{type:"text/calendar"}),x=document.createElement("a");x.href=URL.createObjectURL(y),x.download=`${s}.ics`,x.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(_e,{className:"p-6 rounded-3xl border-slate-200 bg-white",children:[e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4 text-[14px]",children:[e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx(ta,{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:Js(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(na,{className:"h-5 w-5 text-violet-600 mt-0.5"}):e.jsx(ii,{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(Yn,{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,x)=>e.jsxs("li",{className:"flex gap-2 text-[14px] text-slate-800",children:[e.jsx(pa,{className:"h-4 w-4 text-emerald-600 shrink-0 mt-0.5"})," ",y]},x))})]}),(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,x)=>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})]},x))})]})]}),h?e.jsxs(_e,{className:"mt-6 p-8 rounded-3xl border-emerald-200 bg-emerald-50 text-center",children:[e.jsx("div",{className:"mx-auto h-14 w-14 rounded-full bg-emerald-500 text-white grid place-items-center",children:e.jsx(pa,{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:g,children:[e.jsx(oi,{className:"h-4 w-4 mr-2"})," Add to calendar"]})]}):e.jsxs(_e,{className:"mt-6 p-6 rounded-3xl border-slate-200 bg-white",children:[e.jsxs("div",{className:"text-lg font-semibold text-slate-900 mb-1 flex items-center gap-2",children:[e.jsx(Cn,{className:"h-4 w-4 text-violet-600"})," Save your seat"]}),e.jsx("div",{className:"text-[13px] text-slate-500 mb-4",children:"The room is small on purpose."}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{children:[e.jsx(re,{children:"Full name"}),e.jsx(we,{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(re,{children:"Email"}),e.jsx(we,{type:"email",value:o.email,onChange:y=>c({...o,email:y.target.value})})]}),e.jsxs("div",{children:[e.jsx(re,{children:"Phone (optional)"}),e.jsx(we,{value:o.phone,onChange:y=>c({...o,phone:y.target.value})})]})]}),(i.registration_questions||[]).map(y=>e.jsxs("div",{children:[e.jsx(re,{children:y.label}),y.type==="long"?e.jsx(Ws,{rows:3,value:o.answers[y.key]||"",onChange:x=>c({...o,answers:{...o.answers,[y.key]:x.target.value}})}):e.jsx(we,{value:o.answers[y.key]||"",onChange:x=>c({...o,answers:{...o.answers,[y.key]:x.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:f,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 nDn(){const{token:s}=uo(),[t]=$c(),n=t.get("a"),[r,a]=N.useState("loading"),[i,l]=N.useState("");return N.useEffect(()=>{if(!s||!n){a("error");return}(async()=>{const{data:o}=await H.rpc("public_check_in_attendee",{_check_in_token:s,_attendee_token:n}),c=o;c!=null&&c.ok?(l(c.name||""),a(c.already?"already":"ok")):a("error")})()},[s,n]),e.jsx("div",{className:"min-h-screen grid place-items-center bg-slate-50 px-4",children:e.jsxs(_e,{className:"p-8 rounded-3xl border-slate-200 bg-white max-w-md w-full text-center",children:[r==="loading"&&e.jsx("div",{className:"text-slate-500",children:"Checking you in…"}),(r==="ok"||r==="already")&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"mx-auto h-14 w-14 rounded-full bg-emerald-500 text-white grid place-items-center",children:e.jsx(pa,{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 lre=s=>s.toLocaleString("en-US",{style:"currency",currency:"USD",maximumFractionDigits:0});function rDn(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 v$t({cfg:s,onSubmitLead:t,onTrack:n,preview:r}){var I,M,L;const a=s.primary_color||"#0f1b3d",i=s.accent_color||"#c9a84c",l=s.sections||{},[o,c]=N.useState(!1),[d,u]=N.useState(null),[h,m]=N.useState(!1),[f,g]=N.useState({first_name:"",last_name:"",email:"",phone:"",brokerage:"",message:""}),[y,x]=N.useState({first_name:"",email:""}),_=s.calculator||{},[b,k]=N.useState(15e4),A=N.useMemo(()=>{const z=Number(_.cap??16e3),$=Number(_.split??80)/100,V=Number(_.transaction_fee??250),W=Number(_.current_split??70)/100,G=Number(_.current_monthly_fees??150),X=Math.min(b*(1-$),z),te=b-X-V*12,ne=b*W-G*12;return{here:Math.max(te,0),current:Math.max(ne,0),diff:Math.max(te-ne,0),capped:X>=z}},[b,_]),T=async(z,$,V)=>{if(r||!t){u(z);return}m(!0);try{await t({first_name:$.first_name||"",last_name:$.last_name||"",email:$.email||"",phone:$.phone||"",brokerage:$.brokerage||"",message:$.message||"",source:z,metadata:V}),u(z)}catch(W){xa({title:"We couldn't send that",description:(W==null?void 0:W.message)||"Please try again in a moment.",variant:"destructive"})}finally{m(!1)}},P=z=>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:[z||s.cta_label||"Book a confidential 15-min call",e.jsx(vi,{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:[P(),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(ta,{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((z,$)=>e.jsxs("div",{className:"text-center",children:[e.jsx("div",{className:"text-2xl font-bold md:text-3xl",style:{color:i},children:z.value}),e.jsx("div",{className:"mt-1 text-xs uppercase tracking-wider text-white/50",children:z.label})]},$))})}),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:rDn(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(wp,{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((z,$)=>e.jsxs("div",{className:"rounded-2xl border border-white/10 bg-white/[0.03] p-6 transition-colors hover:border-white/25",children:[e.jsx("div",{className:"mb-3 flex h-9 w-9 items-center justify-center rounded-lg",style:{backgroundColor:`${i}22`,color:i},children:e.jsx(pa,{className:"h-4 w-4"})}),e.jsx("h3",{className:"mb-2 text-lg font-semibold",children:z.title}),e.jsx("p",{className:"text-sm leading-relaxed text-white/65",children:z.body}),z.proof&&e.jsx("p",{className:"mt-3 text-xs uppercase tracking-wider text-white/40",children:z.proof})]},$))})]})}),l.calculator!==!1&&_.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:_.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(re,{className:"text-white/70",children:"Your annual GCI"}),e.jsx("span",{className:"text-2xl font-bold",style:{color:i},children:lre(b)})]}),e.jsx("input",{type:"range",min:25e3,max:1e6,step:5e3,value:b,onChange:z=>k(Number(z.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:lre(A.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:lre(A.here)}),A.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:["+",lre(A.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:P("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((z,$)=>e.jsxs("div",{className:"flex gap-4 rounded-2xl border border-white/10 p-6",children:[e.jsx("div",{className:"mt-1 flex h-8 w-8 shrink-0 items-center justify-center rounded-full text-sm font-bold",style:{backgroundColor:i,color:"#10131c"},children:$+1}),e.jsxs("div",{children:[e.jsx("h3",{className:"mb-1.5 font-semibold",children:z.title}),e.jsx("p",{className:"text-sm leading-relaxed text-white/65",children:z.body})]})]},$))})]})}),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((z,$)=>e.jsxs("div",{className:"rounded-2xl border border-white/10 bg-white/[0.03] p-6",children:[e.jsx(Q2,{className:"mb-4 h-6 w-6",style:{color:i}}),e.jsxs("p",{className:"text-sm leading-relaxed text-white/75",children:['"',z.quote,'"']}),e.jsxs("div",{className:"mt-5 flex items-center gap-3",children:[z.photo_url?e.jsx("img",{src:z.photo_url,alt:z.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(Wa,{className:"h-4 w-4 text-white/50"})}),e.jsxs("div",{children:[e.jsx("div",{className:"text-sm font-medium",children:z.name}),z.role&&e.jsx("div",{className:"text-xs text-white/45",children:z.role})]})]})]},$))})]})}),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(qR,{type:"single",collapsible:!0,className:"w-full",children:(s.faqs||[]).map((z,$)=>e.jsxs($E,{value:`faq-${$}`,className:"border-white/10",children:[e.jsx(UE,{className:"text-left text-base font-medium text-white hover:no-underline",children:z.q}),e.jsx(qE,{className:"text-sm leading-relaxed text-white/65",children:z.a})]},$))})]})}),l.lead_magnet!==!1&&((I=s.lead_magnet)==null?void 0:I.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(oi,{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:z=>{z.preventDefault(),T("lead_magnet",{first_name:y.first_name,email:y.email,message:`Requested: ${s.lead_magnet.title}`})},children:[e.jsx(we,{required:!0,placeholder:"First name",value:y.first_name,onChange:z=>x($=>({...$,first_name:z.target.value})),className:"h-12 border-white/15 bg-white/5 text-white placeholder:text-white/35"}),e.jsx(we,{required:!0,type:"email",placeholder:"Email",value:y.email,onChange:z=>x($=>({...$,email:z.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&&((L=s.event_block)==null?void 0:L.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(pa,{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(ta,{className:"h-4 w-4"})," Pick a time"]})]}):e.jsxs("form",{onSubmit:z=>{z.preventDefault(),T("attraction_page",f,{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(re,{className:"text-sm text-white/70",children:"First name *"}),e.jsx(we,{required:!0,value:f.first_name,onChange:z=>g($=>({...$,first_name:z.target.value})),className:"h-11 border-white/15 bg-white/5 text-white"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(re,{className:"text-sm text-white/70",children:"Last name"}),e.jsx(we,{value:f.last_name,onChange:z=>g($=>({...$,last_name:z.target.value})),className:"h-11 border-white/15 bg-white/5 text-white"})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(re,{className:"text-sm text-white/70",children:"Email *"}),e.jsx(we,{required:!0,type:"email",value:f.email,onChange:z=>g($=>({...$,email:z.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(re,{className:"text-sm text-white/70",children:"Phone"}),e.jsx(we,{value:f.phone,onChange:z=>g($=>({...$,phone:z.target.value})),className:"h-11 border-white/15 bg-white/5 text-white"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(re,{className:"text-sm text-white/70",children:"Current brokerage"}),e.jsx(we,{value:f.brokerage,onChange:z=>g($=>({...$,brokerage:z.target.value})),className:"h-11 border-white/15 bg-white/5 text-white"})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(re,{className:"text-sm text-white/70",children:"What would you want to know?"}),e.jsx(Ws,{rows:3,value:f.message,onChange:z=>g($=>({...$,message:z.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(mf,{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(ga,{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(vi,{className:"h-4 w-4"})]})})]})}const cre=H;function aDn(){const{slug:s}=uo(),[t,n]=N.useState(null),[r,a]=N.useState("loading");N.useEffect(()=>{if(!s)return;let o=!1;return(async()=>{const{data:c,error:d}=await cre.rpc("public_get_attract_landing_page",{_slug:s});if(!o){if(d||!c||c.error){a("missing");return}n(c),a("ready"),cre.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&&cre.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 cre.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(ic,{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(v$t,{cfg:t,onSubmitLead:l,onTrack:i})]})}const b$t={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},O0t={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"},iDn=[{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."}],oDn=[{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."}],lDn=[{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."}],cDn="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.",dDn={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:""},uDn={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 hDn(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:iDn,sponsor_cards:lDn,faqs:oDn,lead_magnet:dDn,calculator:uDn,sections:b$t,disclaimer:cDn,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 _$t(s){return s.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,48)}const EH=H;function mDn(){const{user:s}=Ls(),t=as(),n=["attract-landing-page",s==null?void 0:s.id],{data:r,isLoading:a}=mt({queryKey:n,enabled:!!s,queryFn:async()=>{const{data:c,error:d}=await EH.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}=mt({queryKey:["attract-landing-analytics",r==null?void 0:r.id],enabled:!!(r!=null&&r.id),queryFn:async()=>{const{data:c,error:d}=await EH.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(g=>g.event_type==="view").length,m=u.filter(g=>g.event_type==="cta_click").length,f=u.filter(g=>g.event_type==="calculator_run").length;return{views:h,ctas:m,calcs:f,conversion:h?Math.round(m/h*100):0}}}),l=_t({mutationFn:async c=>{const d=_$t(c||"my-attraction-page")||"attraction-page";let u=d;for(let g=0;g<5;g++){const{data:y}=await EH.from("attract_landing_pages").select("id").eq("slug",u).maybeSingle();if(!y)break;u=`${d}-${Math.random().toString(36).slice(2,6)}`}const h=hDn(c||"Your Name"),{data:m,error:f}=await EH.from("attract_landing_pages").insert({...h,user_id:s.id,slug:u}).select("*").single();if(f)throw f;return m},onSuccess:()=>{t.invalidateQueries({queryKey:n}),ie.success("Attraction page created")},onError:c=>ie.error(c.message||"Could not create the page")}),o=_t({mutationFn:async c=>{const{error:d}=await EH.from("attract_landing_pages").update(c).eq("id",r.id);if(d)throw d},onSuccess:()=>{t.invalidateQueries({queryKey:n}),ie.success("Saved")},onError:c=>{var d;return ie.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 pDn(){var x,_,b,k,A,T,P,I,M,L,z,$;const{user:s}=Ls(),{page:t,isLoading:n,analytics:r,createPage:a,savePage:i}=mDn(),[l,o]=N.useState(null),[c,d]=N.useState(!1);N.useEffect(()=>{t&&o({...t})},[t]);const u=N.useMemo(()=>l!=null&&l.slug?`${window.location.origin}/join/${l.slug}`:"",[l==null?void 0:l.slug]),h=V=>o(W=>({...W,...V})),m=(V,W)=>h({[V]:W}),f=(V,W,G)=>m(V,l[V].map((X,te)=>te===W?{...X,...G}:X)),g=()=>{const{id:V,user_id:W,created_at:G,updated_at:X,...te}=l;i.mutate({...te,slug:_$t(te.slug)})};if(n)return e.jsx("div",{className:"p-10 text-center text-muted-foreground",children:"Loading…"});if(!t)return e.jsxs("div",{className:"mx-auto max-w-2xl px-6 py-16 text-center",children:[e.jsx("div",{className:"mx-auto mb-6 flex h-14 w-14 items-center justify-center rounded-2xl bg-primary/10 text-primary",children:e.jsx(Cn,{className:"h-7 w-7"})}),e.jsx("h1",{className:"mb-3 text-3xl font-bold tracking-tight",children:"Your Attraction Landing Page"}),e.jsx("p",{className:"mb-8 text-muted-foreground",children:"A public page built to convert agents — value stack, earnings calculator, objection-handling FAQ, and a confidential contact form that drops every lead straight into your Attract pipeline."}),e.jsx(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(v$t,{cfg:l,preview:!0})]});const y={...b$t,...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(da,{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(Tr,{className:"mr-2 h-4 w-4"})," View live"]})}),e.jsxs(B,{size:"sm",onClick:g,disabled:i.isPending,children:[e.jsx(Kl,{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(_e,{children:e.jsxs(De,{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(ya,{defaultValue:"content",children:[e.jsxs(va,{className:"mb-6 flex-wrap",children:[e.jsx(ls,{value:"content",children:"Content"}),e.jsx(ls,{value:"proof",children:"Proof & FAQ"}),e.jsx(ls,{value:"calculator",children:"Calculator"}),e.jsx(ls,{value:"sections",children:"Sections"}),e.jsx(ls,{value:"publish",children:"Publish"})]}),e.jsxs(_s,{value:"content",className:"space-y-6",children:[e.jsxs(_e,{children:[e.jsx(zt,{children:e.jsx(qt,{className:"text-base",children:"Hero"})}),e.jsxs(De,{className:"grid gap-4 md:grid-cols-2",children:[e.jsx(Ch,{label:"Your name",value:l.agent_name,onChange:V=>h({agent_name:V})}),e.jsx(Ch,{label:"Title / brokerage",value:l.agent_title,onChange:V=>h({agent_title:V})}),e.jsx(Ch,{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(re,{children:"Headline"}),e.jsx(Ws,{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(re,{children:"Subheadline"}),e.jsx(Ws,{rows:3,value:l.subheadline||"",onChange:V=>h({subheadline:V.target.value})})]}),e.jsx(Ch,{label:"Button text",value:l.cta_label,onChange:V=>h({cta_label:V})}),e.jsx(Ch,{label:"Scheduling link (Calendly etc.)",value:l.calendar_url,onChange:V=>h({calendar_url:V})}),e.jsx(Ch,{label:"Headshot URL",value:l.headshot_url,onChange:V=>h({headshot_url:V})}),e.jsx(Ch,{label:"Hero background image URL",value:l.hero_image_url,onChange:V=>h({hero_image_url:V})}),e.jsx(Ch,{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(Ch,{label:"Primary color",type:"color",value:l.primary_color,onChange:V=>h({primary_color:V})}),e.jsx(Ch,{label:"Accent color",type:"color",value:l.accent_color,onChange:V=>h({accent_color:V})})]}),e.jsx(Ch,{label:"Phone",value:l.phone,onChange:V=>h({phone:V})}),e.jsx(Ch,{label:"Email",value:l.email,onChange:V=>h({email:V})})]})]}),e.jsxs(_e,{children:[e.jsx(zt,{children:e.jsx(qt,{className:"text-base",children:"Credibility strip"})}),e.jsxs(De,{className:"space-y-3",children:[(l.credibility||[]).map((V,W)=>e.jsxs(MH,{onRemove:()=>m("credibility",l.credibility.filter((G,X)=>X!==W)),children:[e.jsx(we,{placeholder:"Value (e.g. $42M)",value:V.value||"",onChange:G=>f("credibility",W,{value:G.target.value})}),e.jsx(we,{placeholder:"Label (e.g. Closed volume)",value:V.label||"",onChange:G=>f("credibility",W,{label:G.target.value})})]},W)),e.jsx(LH,{onClick:()=>m("credibility",[...l.credibility||[],{value:"",label:""}]),label:"Add stat"})]})]}),e.jsxs(_e,{children:[e.jsx(zt,{children:e.jsx(qt,{className:"text-base",children:"Your story"})}),e.jsxs(De,{className:"space-y-4",children:[e.jsx(Ch,{label:"Section title",value:l.story_title,onChange:V=>h({story_title:V})}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(re,{children:"Story"}),e.jsx(Ws,{rows:6,value:l.story_body||"",onChange:V=>h({story_body:V.target.value})})]}),e.jsx(Ch,{label:"Story video URL (YouTube, Vimeo, Loom, MP4)",value:l.story_video_url,onChange:V=>h({story_video_url:V})})]})]}),e.jsxs(_e,{children:[e.jsx(zt,{children:e.jsx(qt,{className:"text-base",children:"Value stack"})}),e.jsxs(De,{className:"space-y-4",children:[(l.value_cards||[]).map((V,W)=>e.jsxs(MH,{vertical:!0,onRemove:()=>m("value_cards",l.value_cards.filter((G,X)=>X!==W)),children:[e.jsx(we,{placeholder:"Title",value:V.title||"",onChange:G=>f("value_cards",W,{title:G.target.value})}),e.jsx(Ws,{rows:2,placeholder:"Description",value:V.body||"",onChange:G=>f("value_cards",W,{body:G.target.value})}),e.jsx(we,{placeholder:"Proof point (optional)",value:V.proof||"",onChange:G=>f("value_cards",W,{proof:G.target.value})})]},W)),e.jsx(LH,{onClick:()=>m("value_cards",[...l.value_cards||[],{title:"",body:""}]),label:"Add value card"})]})]}),e.jsxs(_e,{children:[e.jsx(zt,{children:e.jsx(qt,{className:"text-base",children:"What you get from me"})}),e.jsxs(De,{className:"space-y-4",children:[(l.sponsor_cards||[]).map((V,W)=>e.jsxs(MH,{vertical:!0,onRemove:()=>m("sponsor_cards",l.sponsor_cards.filter((G,X)=>X!==W)),children:[e.jsx(we,{placeholder:"Title",value:V.title||"",onChange:G=>f("sponsor_cards",W,{title:G.target.value})}),e.jsx(Ws,{rows:2,placeholder:"Description",value:V.body||"",onChange:G=>f("sponsor_cards",W,{body:G.target.value})})]},W)),e.jsx(LH,{onClick:()=>m("sponsor_cards",[...l.sponsor_cards||[],{title:"",body:""}]),label:"Add commitment"})]})]}),e.jsxs(_e,{children:[e.jsx(zt,{children:e.jsx(qt,{className:"text-base",children:"Free download & upcoming event"})}),e.jsxs(De,{className:"space-y-4",children:[e.jsx(Ch,{label:"Download title",value:(x=l.lead_magnet)==null?void 0:x.title,onChange:V=>h({lead_magnet:{...l.lead_magnet,title:V}})}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(re,{children:"Download description"}),e.jsx(Ws,{rows:2,value:((_=l.lead_magnet)==null?void 0:_.body)||"",onChange:V=>h({lead_magnet:{...l.lead_magnet,body:V.target.value}})})]}),e.jsx(Ch,{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(Ch,{label:"Event title",value:(k=l.event_block)==null?void 0:k.title,onChange:V=>h({event_block:{...l.event_block,title:V}})}),e.jsx(Ch,{label:"When",value:(A=l.event_block)==null?void 0:A.when,onChange:V=>h({event_block:{...l.event_block,when:V}})}),e.jsx(Ch,{label:"Registration link",value:(T=l.event_block)==null?void 0:T.url,onChange:V=>h({event_block:{...l.event_block,url:V}})})]})]})]})]}),e.jsxs(_s,{value:"proof",className:"space-y-6",children:[e.jsxs(_e,{children:[e.jsx(zt,{children:e.jsx(qt,{className:"text-base",children:"Testimonials"})}),e.jsxs(De,{className:"space-y-4",children:[(l.testimonials||[]).map((V,W)=>e.jsxs(MH,{vertical:!0,onRemove:()=>m("testimonials",l.testimonials.filter((G,X)=>X!==W)),children:[e.jsx(Ws,{rows:3,placeholder:"Quote",value:V.quote||"",onChange:G=>f("testimonials",W,{quote:G.target.value})}),e.jsxs("div",{className:"grid gap-3 md:grid-cols-3",children:[e.jsx(we,{placeholder:"Name",value:V.name||"",onChange:G=>f("testimonials",W,{name:G.target.value})}),e.jsx(we,{placeholder:"Role / market",value:V.role||"",onChange:G=>f("testimonials",W,{role:G.target.value})}),e.jsx(we,{placeholder:"Photo URL",value:V.photo_url||"",onChange:G=>f("testimonials",W,{photo_url:G.target.value})})]})]},W)),e.jsx(LH,{onClick:()=>m("testimonials",[...l.testimonials||[],{quote:"",name:""}]),label:"Add testimonial"})]})]}),e.jsxs(_e,{children:[e.jsx(zt,{children:e.jsx(qt,{className:"text-base",children:"Objection-handling FAQ"})}),e.jsxs(De,{className:"space-y-4",children:[(l.faqs||[]).map((V,W)=>e.jsxs(MH,{vertical:!0,onRemove:()=>m("faqs",l.faqs.filter((G,X)=>X!==W)),children:[e.jsx(we,{placeholder:"Question",value:V.q||"",onChange:G=>f("faqs",W,{q:G.target.value})}),e.jsx(Ws,{rows:3,placeholder:"Answer",value:V.a||"",onChange:G=>f("faqs",W,{a:G.target.value})})]},W)),e.jsx(LH,{onClick:()=>m("faqs",[...l.faqs||[],{q:"",a:""}]),label:"Add question"})]})]}),e.jsxs(_e,{children:[e.jsx(zt,{children:e.jsx(qt,{className:"text-base",children:"Income disclaimer"})}),e.jsx(De,{children:e.jsx(Ws,{rows:4,value:l.disclaimer||"",onChange:V=>h({disclaimer:V.target.value})})})]})]}),e.jsx(_s,{value:"calculator",children:e.jsxs(_e,{children:[e.jsx(zt,{children:e.jsx(qt,{className:"text-base",children:"Earnings calculator"})}),e.jsxs(De,{className:"grid gap-4 md:grid-cols-2",children:[e.jsx(Ch,{label:"Section title",value:(P=l.calculator)==null?void 0:P.title,onChange:V=>h({calculator:{...l.calculator,title:V}}),className:"md:col-span-2"}),e.jsx(Ch,{label:"Cap ($)",type:"number",value:(I=l.calculator)==null?void 0:I.cap,onChange:V=>h({calculator:{...l.calculator,cap:Number(V)}})}),e.jsx(Ch,{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(Ch,{label:"Per-transaction fee ($)",type:"number",value:(L=l.calculator)==null?void 0:L.transaction_fee,onChange:V=>h({calculator:{...l.calculator,transaction_fee:Number(V)}})}),e.jsx(Ch,{label:"Typical competitor split (%)",type:"number",value:(z=l.calculator)==null?void 0:z.current_split,onChange:V=>h({calculator:{...l.calculator,current_split:Number(V)}})}),e.jsx(Ch,{label:"Typical competitor monthly fees ($)",type:"number",value:($=l.calculator)==null?void 0:$.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(_s,{value:"sections",children:e.jsxs(_e,{children:[e.jsx(zt,{children:e.jsx(qt,{className:"text-base",children:"Show or hide sections"})}),e.jsx(De,{className:"divide-y",children:Object.keys(O0t).map(V=>e.jsxs("div",{className:"flex items-center justify-between py-3",children:[e.jsx("span",{className:"text-sm",children:O0t[V]}),e.jsx(zn,{checked:y[V]!==!1,onCheckedChange:W=>h({sections:{...y,[V]:W}})})]},V))})]})}),e.jsxs(_s,{value:"publish",className:"space-y-6",children:[e.jsxs(_e,{children:[e.jsx(zt,{children:e.jsx(qt,{className:"text-base",children:"Publishing"})}),e.jsxs(De,{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(zn,{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(zn,{checked:!!l.noindex,onCheckedChange:V=>h({noindex:V})})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(re,{children:"Web address"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(we,{value:l.slug||"",onChange:V=>h({slug:V.target.value})}),e.jsx(B,{variant:"outline",onClick:()=>{navigator.clipboard.writeText(u),ie.success("Link copied")},children:e.jsx(Pa,{className:"h-4 w-4"})})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:u})]}),e.jsx(Ch,{label:"Search title",value:l.seo_title,onChange:V=>h({seo_title:V})}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(re,{children:"Search description"}),e.jsx(Ws,{rows:2,value:l.seo_description||"",onChange:V=>h({seo_description:V.target.value})})]})]})]}),e.jsxs(_e,{children:[e.jsx(zt,{children:e.jsxs(qt,{className:"flex items-center gap-2 text-base",children:[e.jsx(fl,{className:"h-4 w-4"})," Where leads go"]})}),e.jsx(De,{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:g,disabled:i.isPending,children:[e.jsx(Kl,{className:"mr-2 h-4 w-4"})," ",i.isPending?"Saving…":"Save changes"]})})]})}function Ch({label:s,value:t,onChange:n,type:r="text",className:a}){return e.jsxs("div",{className:`space-y-1.5 ${a||""}`,children:[e.jsx(re,{children:s}),e.jsx(we,{type:r,value:t??"",onChange:i=>n(i.target.value)})]})}function MH({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(qn,{className:"h-4 w-4"})})]})}function LH({onClick:s,label:t}){return e.jsxs(B,{variant:"outline",size:"sm",onClick:s,children:[e.jsx(nn,{className:"mr-2 h-4 w-4"})," ",t]})}function fDn(s){const{user:t}=Ls(),n=as(),r=mt({queryKey:["admin-attract-list",s,t==null?void 0:t.id],enabled:!!t,queryFn:async()=>{let o=H.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:f}=await H.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(f)throw f;(m??[]).forEach(g=>{h[g.user_id]=g})}return(c??[]).map(m=>{var f,g,y,x,_,b;return{user_id:m.id,email:m.email,full_name:m.full_name,enabled:!!((f=h[m.id])!=null&&f.enabled),tier:((g=h[m.id])==null?void 0:g.tier)??null,enabled_at:((y=h[m.id])==null?void 0:y.enabled_at)??null,expires_at:((x=h[m.id])==null?void 0:x.expires_at)??null,notes:((_=h[m.id])==null?void 0:_.notes)??null,enabled_by:((b=h[m.id])==null?void 0:b.enabled_by)??null}})}}),a=mt({queryKey:["admin-attract-audit",t==null?void 0:t.id],enabled:!!t,queryFn:async()=>{const{data:o,error:c}=await H.from("feature_entitlement_audit").select("*").eq("feature_key","levelup_attract").order("created_at",{ascending:!1}).limit(50);if(c)throw c;return o??[]}}),i=_t({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 H.from("feature_entitlements").upsert(h,{onConflict:"user_id,feature_key"});if(m)throw m;await H.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"]}),ie.success("Access granted")},onError:o=>ie.error(o.message)}),l=_t({mutationFn:async o=>{const{error:c}=await H.from("feature_entitlements").update({enabled:!1}).eq("user_id",o).eq("feature_key","levelup_attract");if(c)throw c;await H.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"]}),ie.success("Access revoked")},onError:o=>ie.error(o.message)});return{list:r,audit:a,grant:i,revoke:l}}function gDn(){const[s,t]=N.useState(""),{list:n,audit:r,grant:a,revoke:i}=fDn(s),[l,o]=N.useState(null),[c,d]=N.useState(null),[u,h]=N.useState("beta"),[m,f]=N.useState(""),[g,y]=N.useState(""),x=b=>{d(b),h(b.tier??"beta"),f(b.expires_at?b.expires_at.slice(0,10):""),y(b.notes??"")},_=async()=>{c&&(await a.mutateAsync({target_user_id:c.user_id,tier:u,expires_at:m?new Date(m).toISOString():null,notes:g||void 0}),d(null))};return e.jsxs("div",{className:"p-6",children:[e.jsx(Uh,{title:"LevelUp Attract — Access Management",description:"Grant or revoke access to LevelUp Attract for individual members. Every change is audited."}),e.jsx(_e,{className:"p-4 rounded-2xl mb-4",children:e.jsxs("div",{className:"relative max-w-md",children:[e.jsx(Gr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-slate-400"}),e.jsx(we,{value:s,onChange:b=>t(b.target.value),placeholder:"Search by name or email...",className:"pl-9"})]})}),e.jsxs(_e,{className:"rounded-2xl overflow-hidden mb-8",children:[e.jsxs("div",{className:"grid grid-cols-[1fr_auto_auto_auto] gap-3 px-5 py-3 text-[11px] uppercase tracking-widest text-slate-500 font-semibold border-b",children:[e.jsx("div",{children:"Member"}),e.jsx("div",{children:"Access"}),e.jsx("div",{children:"Enabled"}),e.jsx("div",{children:"Actions"})]}),n.isLoading&&e.jsx("div",{className:"p-6 text-center text-slate-500 text-sm",children:"Loading members…"}),!n.isLoading&&(n.data??[]).length===0&&e.jsx("div",{className:"p-6 text-center text-slate-500 text-sm",children:"No members match."}),(n.data??[]).map(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(We,{className:"bg-emerald-100 text-emerald-800 border-0 gap-1",children:[e.jsx(Cn,{className:"h-3 w-3"})," ",b.tier??"enabled"]}):e.jsx(We,{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?Js(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:()=>x(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:()=>x(b),children:[e.jsx(Wv,{className:"h-3.5 w-3.5 mr-1"})," Enable"]})})]},b.user_id))]}),e.jsxs(_e,{className:"rounded-2xl p-5",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-3 text-[12px] uppercase tracking-widest text-slate-500 font-semibold",children:[e.jsx(fD,{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(We,{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:Js(new Date(b.created_at),"MMM d h:mm a")})]},b.id))})]}),e.jsx(Bs,{open:!!c,onOpenChange:b=>!b&&d(null),children:e.jsxs(Fs,{children:[e.jsxs(qs,{children:[e.jsxs($s,{children:[c!=null&&c.enabled?"Update":"Enable"," Attract access"]}),e.jsx(Ar,{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(re,{children:"Tier"}),e.jsxs(Ns,{value:u,onValueChange:h,children:[e.jsx(ws,{children:e.jsx(ks,{})}),e.jsxs(js,{children:[e.jsx(nt,{value:"beta",children:"Beta"}),e.jsx(nt,{value:"standard",children:"Standard"}),e.jsx(nt,{value:"pro",children:"Pro"}),e.jsx(nt,{value:"founder",children:"Founder"})]})]})]}),e.jsxs("div",{children:[e.jsx(re,{children:"Expires (optional)"}),e.jsx(we,{type:"date",value:m,onChange:b=>f(b.target.value)})]}),e.jsxs("div",{children:[e.jsx(re,{children:"Internal notes (optional)"}),e.jsx(Ws,{rows:2,value:g,onChange:b=>y(b.target.value)})]})]}),e.jsxs(Cr,{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:_,disabled:a.isPending,children:c!=null&&c.enabled?"Save changes":"Enable access"})]})]})}),e.jsx(Fl,{open:!!l,onOpenChange:b=>!b&&o(null),children:e.jsxs(kl,{children:[e.jsxs(Sl,{children:[e.jsx(Al,{children:"Revoke Attract access?"}),e.jsxs(Tl,{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(Cl,{children:[e.jsx(El,{children:"Cancel"}),e.jsxs(wl,{className:"bg-rose-600 hover:bg-rose-700",onClick:async()=>{l&&await i.mutateAsync(l.user.user_id),o(null)},children:[e.jsx(Nu,{className:"h-4 w-4 mr-1.5"})," Revoke access"]})]})]})})]})}const xDn=({team:s,onSelect:t})=>{const{data:n}=mt({queryKey:["team-card-info",s.id],queryFn:async()=>{const{data:r}=await H.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 H.from("profiles").select("name, avatar_url").eq("id",i.user_id).single();l=o}return{count:a,leaderProfile:l}}});return e.jsxs(_e,{className:"cursor-pointer hover:shadow-md transition-shadow group",onClick:t,children:[e.jsx(zt,{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(qt,{className:"text-lg truncate",children:s.name}),s.description&&e.jsx(_r,{className:"mt-1 line-clamp-2",children:s.description})]}),e.jsxs(We,{variant:"secondary",className:"ml-2 shrink-0",children:[e.jsx(Yn,{className:"h-3 w-3 mr-1"}),(n==null?void 0:n.count)??"…"]})]})}),e.jsxs(De,{className:"space-y-3",children:[(n==null?void 0:n.leaderProfile)&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(Ua,{className:"h-6 w-6",children:[e.jsx(Gi,{src:n.leaderProfile.avatar_url||""}),e.jsx(qa,{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(q0,{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(mf,{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(We,{variant:"outline",className:"text-xs py-0",children:"Lead Pond"}),s.shared_assets_enabled&&e.jsx(We,{variant:"outline",className:"text-xs py-0",children:"Shared Assets"}),s.shared_videos_enabled&&e.jsx(We,{variant:"outline",className:"text-xs py-0",children:"Shared Videos"})]})]})]})},yDn=()=>{const{user:s,isAdmin:t,isBrokerageManager:n,brokerageId:r,managedBrokerages:a,selectedBrokerageId:i}=Ls(),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:f,removeMember:g,updateMemberRole:y}=ZR(o),[x,_]=N.useState(!1),[b,k]=N.useState(null),{data:A}=mt({queryKey:["all-brokerages-for-teams"],queryFn:async()=>{const{data:I,error:M}=await H.from("brokerages").select("id, name").order("name");if(M)throw M;return I||[]},enabled:t}),{data:T}=mt({queryKey:["brokerage-agents-for-teams",l],queryFn:async()=>{const{data:I,error:M}=await H.from("profiles").select("id, name, email, avatar_url").eq("brokerage_id",l).order("name");if(M)throw M;return I||[]},enabled:!!l}),P=async I=>{const M=I.brokerage_id||l||null,L=await u.mutateAsync({name:I.name,brokerage_id:M,description:I.description});if(I.leaderId&&I.leaderId!=="none"&&await f.mutateAsync({team_id:L.id,user_id:I.leaderId,role:"team_leader"}),I.memberIds)for(const z of I.memberIds)await f.mutateAsync({team_id:L.id,user_id:z,role:"team_member"});_(!1)};return!n&&!t?e.jsx(Qs,{title:"Teams",description:"Team Management",children:e.jsxs("div",{className:"flex flex-col items-center justify-center py-12 text-center",children:[e.jsx(Yn,{className:"h-12 w-12 text-muted-foreground mb-4"}),e.jsx("h2",{className:"text-xl font-semibold mb-2",children:"Access Denied"}),e.jsx("p",{className:"text-muted-foreground",children:"You need brokerage manager access to manage teams."})]})}):e.jsx(Qs,{title:"Teams",description:"Create and manage teams within your brokerage",children:e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"text-2xl font-bold tracking-tight",children:"Teams"}),e.jsx("p",{className:"text-muted-foreground",children:"Organize your agents into teams with leaders and shared resources."})]}),e.jsxs(B,{onClick:()=>_(!0),children:[e.jsx(nn,{className:"mr-2 h-4 w-4"}),"Create Team"]})]}),e.jsx(IEt,{open:x,onOpenChange:_,onCreateTeam:P,isCreating:u.isPending,brokerageAgents:T||[],isAdmin:t,allBrokerages:A,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(_e,{children:e.jsxs(De,{className:"p-6",children:[e.jsx(xn,{className:"h-5 w-32 mb-3"}),e.jsx(xn,{className:"h-4 w-48 mb-4"}),e.jsx(xn,{className:"h-8 w-full"})]})},I))}),!d&&c.length===0&&!b&&e.jsx(_e,{children:e.jsxs(De,{className:"flex flex-col items-center justify-center py-12 text-center",children:[e.jsx(Yn,{className:"h-12 w-12 text-muted-foreground mb-4"}),e.jsx("h3",{className:"text-lg font-semibold mb-2",children:"No Teams Yet"}),e.jsx("p",{className:"text-muted-foreground mb-4",children:"Create your first team to organize agents and share resources."}),e.jsxs(B,{onClick:()=>_(!0),children:[e.jsx(nn,{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(xDn,{team:I,onSelect:()=>k(I)},I.id))}),b&&e.jsx(PEt,{team:b,brokerageAgents:T||[],onBack:()=>k(null),onUpdate:I=>h.mutateAsync({id:b.id,...I}).then(M=>k(M)),onAddMember:(I,M)=>f.mutateAsync({team_id:b.id,user_id:I,role:M}),onRemoveMember:I=>g.mutateAsync({team_id:b.id,member_id:I}),onUpdateRole:(I,M)=>y.mutateAsync({team_id:b.id,member_id:I,role:M}),onDeleteTeam:()=>m.mutate(b.id),isUpdating:h.isPending,isAddingMember:f.isPending})]})})},vDn=()=>{const{data:s,isLoading:t}=Cj(),{useTeamMembers:n}=ZR(),{data:r=[],isLoading:a}=n((s==null?void 0:s.teamId)||"");if(t)return e.jsx(Qs,{title:"My Team",description:"Your team",children:e.jsxs("div",{className:"space-y-4",children:[e.jsx(xn,{className:"h-8 w-48"}),e.jsx(xn,{className:"h-40 w-full"})]})});if(!s)return e.jsx(Qs,{title:"My Team",description:"Your team",children:e.jsx(_e,{children:e.jsxs(De,{className:"flex flex-col items-center justify-center py-12 text-center",children:[e.jsx(Yn,{className:"h-12 w-12 text-muted-foreground mb-4"}),e.jsx("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 i=s.team;return e.jsx(Qs,{title:"My Team",description:i.name,children:e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("h2",{className:"text-2xl font-bold tracking-tight",children:i.name}),e.jsx(We,{variant:s.role==="team_leader"?"default":"secondary",className:"capitalize",children:s.role==="team_leader"?e.jsxs(e.Fragment,{children:[e.jsx(q0,{className:"mr-1 h-3 w-3"})," Leader"]}):"Member"})]}),i.description&&e.jsx("p",{className:"text-muted-foreground mt-1",children:i.description})]}),e.jsxs(ya,{defaultValue:"members",className:"space-y-4",children:[e.jsxs(va,{className:"flex-wrap",children:[e.jsx(ls,{value:"members",children:"Members"}),i.contact_visibility!=="private"&&e.jsxs(ls,{value:"contacts",children:[e.jsx(dD,{className:"mr-1 h-3.5 w-3.5"}),"Team Contacts"]}),i.lead_pond_enabled&&e.jsxs(ls,{value:"lead-pond",children:[e.jsx(K2,{className:"mr-1 h-3.5 w-3.5"}),"Lead Pond"]}),i.shared_assets_enabled&&e.jsxs(ls,{value:"shared-assets",children:[e.jsx(H0,{className:"mr-1 h-3.5 w-3.5"}),"Shared Assets"]})]}),e.jsx(_s,{value:"members",className:"space-y-2",children:a?e.jsx("div",{className:"space-y-3",children:[1,2,3].map(l=>e.jsx(xn,{className:"h-16 w-full"},l))}):r.map(l=>{var o,c,d,u;return e.jsx(_e,{children:e.jsxs(De,{className:"flex items-center gap-3 p-4",children:[e.jsxs(Ua,{className:"h-10 w-10",children:[e.jsx(Gi,{src:((o=l.profile)==null?void 0:o.avatar_url)||""}),e.jsx(qa,{children:(((c=l.profile)==null?void 0:c.name)||"?").charAt(0).toUpperCase()})]}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"font-medium",children:((d=l.profile)==null?void 0:d.name)||"Unknown"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:(u=l.profile)==null?void 0:u.email})]}),l.role==="team_leader"?e.jsxs(We,{className:"ml-auto bg-amber-500/10 text-amber-600 border-amber-500",children:[e.jsx(q0,{className:"mr-1 h-3 w-3"})," Leader"]}):e.jsx(We,{variant:"secondary",className:"ml-auto",children:"Member"})]})},l.id)})}),i.contact_visibility!=="private"&&e.jsx(_s,{value:"contacts",className:"space-y-4",children:e.jsx($Ve,{})}),i.lead_pond_enabled&&e.jsx(_s,{value:"lead-pond",className:"space-y-4",children:e.jsx(UVe,{teamId:s.teamId})}),i.shared_assets_enabled&&e.jsx(_s,{value:"shared-assets",className:"space-y-4",children:e.jsx(LEt,{teamId:s.teamId})})]})]})})};function bDn(){const{user:s}=Ls(),t=as(),n=mt({queryKey:["booking-settings",s==null?void 0:s.id],queryFn:async()=>{const{data:x,error:_}=await H.from("agent_booking_settings").select("*").eq("user_id",s.id).maybeSingle();if(_)throw _;return x},enabled:!!s}),r=mt({queryKey:["booking-types",s==null?void 0:s.id],queryFn:async()=>{const{data:x,error:_}=await H.from("agent_booking_types").select("*").eq("user_id",s.id).order("sort_order");if(_)throw _;return x},enabled:!!s}),a=mt({queryKey:["availability-slots",s==null?void 0:s.id],queryFn:async()=>{const{data:x,error:_}=await H.from("agent_availability_slots").select("*").eq("user_id",s.id).order("day_of_week").order("start_time");if(_)throw _;return x},enabled:!!s}),i=mt({queryKey:["blocked-dates",s==null?void 0:s.id],queryFn:async()=>{const{data:x,error:_}=await H.from("agent_blocked_dates").select("*").eq("user_id",s.id).order("blocked_date");if(_)throw _;return x},enabled:!!s}),l=mt({queryKey:["bookings",s==null?void 0:s.id],queryFn:async()=>{const{data:x,error:_}=await H.from("bookings").select("*, booking_type:agent_booking_types(*)").eq("agent_user_id",s.id).order("booking_date",{ascending:!1});if(_)throw _;return x},enabled:!!s}),o=_t({mutationFn:async()=>{const{data:x,error:_}=await H.from("agent_booking_settings").insert({user_id:s.id,slug:""}).select().single();if(_)throw _;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:k}=await H.from("agent_booking_types").insert(b.map(P=>({...P,user_id:s.id})));if(k)throw k;const A=[1,2,3,4,5].map(P=>({user_id:s.id,day_of_week:P,start_time:"09:00",end_time:"17:00"})),{error:T}=await H.from("agent_availability_slots").insert(A);if(T)throw T;return x},onSuccess:()=>{t.invalidateQueries({queryKey:["booking-settings"]}),t.invalidateQueries({queryKey:["booking-types"]}),t.invalidateQueries({queryKey:["availability-slots"]}),ie.success("Scheduler set up successfully!")},onError:x=>ie.error(x.message)}),c=_t({mutationFn:async x=>{const{error:_}=await H.from("agent_booking_settings").update(x).eq("user_id",s.id);if(_)throw _},onSuccess:()=>{t.invalidateQueries({queryKey:["booking-settings"]}),ie.success("Settings updated")},onError:x=>ie.error(x.message)}),d=_t({mutationFn:async x=>{const _={...x,user_id:s.id};if(x.id){const{error:b}=await H.from("agent_booking_types").update(_).eq("id",x.id);if(b)throw b}else{const{error:b}=await H.from("agent_booking_types").insert(_);if(b)throw b}},onSuccess:()=>{t.invalidateQueries({queryKey:["booking-types"]}),ie.success("Booking type saved")},onError:x=>ie.error(x.message)}),u=_t({mutationFn:async x=>{const{error:_}=await H.from("agent_booking_types").delete().eq("id",x);if(_)throw _},onSuccess:()=>{t.invalidateQueries({queryKey:["booking-types"]}),ie.success("Booking type deleted")},onError:x=>ie.error(x.message)}),h=_t({mutationFn:async x=>{const _={...x,user_id:s.id};if(x.id){const{error:b}=await H.from("agent_availability_slots").update(_).eq("id",x.id);if(b)throw b}else{const{error:b}=await H.from("agent_availability_slots").insert(_);if(b)throw b}},onSuccess:()=>{t.invalidateQueries({queryKey:["availability-slots"]})},onError:x=>ie.error(x.message)}),m=_t({mutationFn:async x=>{const{error:_}=await H.from("agent_availability_slots").delete().eq("id",x);if(_)throw _},onSuccess:()=>{t.invalidateQueries({queryKey:["availability-slots"]})},onError:x=>ie.error(x.message)}),f=_t({mutationFn:async x=>{const{error:_}=await H.from("agent_blocked_dates").insert({...x,user_id:s.id});if(_)throw _},onSuccess:()=>{t.invalidateQueries({queryKey:["blocked-dates"]}),ie.success("Date blocked")},onError:x=>ie.error(x.message)}),g=_t({mutationFn:async x=>{const{error:_}=await H.from("agent_blocked_dates").delete().eq("id",x);if(_)throw _},onSuccess:()=>{t.invalidateQueries({queryKey:["blocked-dates"]})},onError:x=>ie.error(x.message)}),y=_t({mutationFn:async({id:x,reason:_})=>{const{error:b}=await H.from("bookings").update({status:"cancelled",cancelled_at:new Date().toISOString(),cancel_reason:_}).eq("id",x);if(b)throw b},onSuccess:()=>{t.invalidateQueries({queryKey:["bookings"]}),ie.success("Booking cancelled")},onError:x=>ie.error(x.message)});return{settings:n.data,bookingTypes:r.data??[],availability:a.data??[],blockedDates:i.data??[],bookings:l.data??[],isLoading:n.isLoading,initializeSettings:o,updateSettings:c,upsertBookingType:d,deleteBookingType:u,upsertAvailability:h,deleteAvailability:m,addBlockedDate:f,removeBlockedDate:g,cancelBooking:y}}const F0t={Home:"🏠",Search:"🔍",DollarSign:"💰",Coffee:"☕",Calendar:"📅",Users:"👥",Phone:"📞",Video:"🎥"};function _Dn({types:s,onSave:t,onDelete:n}){const[r,a]=N.useState(null),[i,l]=N.useState(!1),o=()=>{a({name:"",description:"",duration_minutes:30,color:"#3B82F6",icon:"Calendar",is_active:!0,qualification_enabled:!1}),l(!0)},c=u=>{a({...u}),l(!0)},d=()=>{r!=null&&r.name&&(t(r),l(!1),a(null))};return e.jsxs(e.Fragment,{children:[e.jsxs(_e,{children:[e.jsxs(zt,{className:"flex flex-row items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(qt,{children:"Booking Types"}),e.jsx(_r,{children:"The meeting types prospects can book with you"})]}),e.jsxs(B,{onClick:o,size:"sm",children:[e.jsx(nn,{className:"h-4 w-4 mr-1"})," Add Type"]})]}),e.jsx(De,{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:F0t[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(We,{variant:"secondary",className:"text-xs",children:"Inactive"}),u.qualification_enabled&&e.jsxs(We,{variant:"outline",className:"text-xs gap-1",children:[e.jsx(iW,{className:"h-3 w-3"})," Qualifying"]})]}),e.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[e.jsx(Xr,{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(Ja,{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(qn,{className:"h-4 w-4"})})]})]},u.id))})})]}),e.jsx(Bs,{open:i,onOpenChange:l,children:e.jsxs(Fs,{children:[e.jsx(qs,{children:e.jsxs($s,{children:[r!=null&&r.id?"Edit":"New"," Booking Type"]})}),r&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{children:"Name"}),e.jsx(we,{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(re,{children:"Description"}),e.jsx(Ws,{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(re,{children:"Duration (minutes)"}),e.jsx(we,{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(re,{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(we,{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(re,{children:"Icon"}),e.jsx("div",{className:"flex flex-wrap gap-2",children:Object.entries(F0t).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(re,{children:"Meeting Link Override (optional)"}),e.jsx(we,{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(re,{children:"Pre-Qualification Questions"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Ask qualifying questions before booking"})]}),e.jsx(zn,{checked:r.qualification_enabled||!1,onCheckedChange:u=>a({...r,qualification_enabled:u})})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(re,{children:"Active"}),e.jsx(zn,{checked:r.is_active??!0,onCheckedChange:u=>a({...r,is_active:u})})]})]}),e.jsxs(Cr,{children:[e.jsx(B,{variant:"outline",onClick:()=>l(!1),children:"Cancel"}),e.jsx(B,{onClick:d,children:"Save"})]})]})})]})}const z0t=["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"];function wDn({slots:s,onSave:t,onDelete:n}){const[r,a]=N.useState(null),[i,l]=N.useState("09:00"),[o,c]=N.useState("17:00"),d=z0t.map((h,m)=>s.filter(f=>f.day_of_week===m)),u=()=>{r!==null&&(t({day_of_week:r,start_time:i,end_time:o,is_active:!0}),a(null),l("09:00"),c("17:00"))};return e.jsxs(_e,{children:[e.jsxs(zt,{children:[e.jsxs(qt,{className:"flex items-center gap-2",children:[e.jsx(Xr,{className:"h-5 w-5"}),"Weekly Availability"]}),e.jsx(_r,{children:"Set your available hours for each day"})]}),e.jsx(De,{className:"space-y-2",children:z0t.map((h,m)=>{const f=d[m];return e.jsxs("div",{className:"flex items-start gap-3 py-2 border-b last:border-0",children:[e.jsx("div",{className:"w-24 pt-1",children:e.jsx("p",{className:"text-sm font-medium",children:h})}),e.jsxs("div",{className:"flex-1 space-y-1",children:[f.length===0?e.jsx("p",{className:"text-sm text-muted-foreground py-1",children:"Unavailable"}):f.map(g=>{var y,x;return e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(we,{type:"time",className:"w-28 h-8 text-sm",defaultValue:(y=g.start_time)==null?void 0:y.slice(0,5),onBlur:_=>t({id:g.id,start_time:_.target.value})}),e.jsx("span",{className:"text-sm text-muted-foreground",children:"to"}),e.jsx(we,{type:"time",className:"w-28 h-8 text-sm",defaultValue:(x=g.end_time)==null?void 0:x.slice(0,5),onBlur:_=>t({id:g.id,end_time:_.target.value})}),e.jsx(zn,{checked:g.is_active,onCheckedChange:_=>t({id:g.id,is_active:_})}),e.jsx(B,{variant:"ghost",size:"sm",className:"h-8 w-8 p-0",onClick:()=>n(g.id),children:e.jsx(qn,{className:"h-3.5 w-3.5 text-muted-foreground"})})]},g.id)}),r===m?e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(we,{type:"time",className:"w-28 h-8 text-sm",value:i,onChange:g=>l(g.target.value)}),e.jsx("span",{className:"text-sm text-muted-foreground",children:"to"}),e.jsx(we,{type:"time",className:"w-28 h-8 text-sm",value:o,onChange:g=>c(g.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(nn,{className:"h-3 w-3 mr-1"})," Add hours"]})]})]},h)})})]})}const jDn={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 NDn({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(Ro,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{className:"font-medium",children:i.guest_name}),e.jsx(We,{className:`text-xs ${jDn[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(ld,{className:"h-3.5 w-3.5"}),Js(new Date(i.booking_date+"T00:00:00"),"MMM d, yyyy")]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Xr,{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(mn,{className:"h-3 w-3"}),i.guest_email]}),i.guest_phone&&e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(ga,{className:"h-3 w-3"}),i.guest_phone]})]}),i.booking_type&&e.jsx(We,{variant:"outline",className:"text-xs mt-1",children:i.booking_type.name}),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(Nu,{className:"h-4 w-4 mr-1"})," Cancel"]})]},i.id)};return e.jsxs("div",{className:"space-y-6",children:[e.jsxs(_e,{children:[e.jsxs(zt,{children:[e.jsx(qt,{children:"Upcoming Bookings"}),e.jsxs(_r,{children:[n.length," upcoming appointment",n.length!==1?"s":""]})]}),e.jsx(De,{children:n.length===0?e.jsx("p",{className:"text-center text-muted-foreground py-8",children:"No upcoming bookings"}):e.jsx("div",{className:"space-y-3",children:n.map(i=>a(i,!0))})})]}),r.length>0&&e.jsxs(_e,{children:[e.jsx(zt,{children:e.jsx(qt,{children:"Past & Cancelled"})}),e.jsx(De,{children:e.jsx("div",{className:"space-y-3",children:r.slice(0,20).map(i=>a(i))})})]})]})}function kDn({blockedDates:s,onAdd:t,onRemove:n}){const[r,a]=N.useState(!1),[i,l]=N.useState(""),[o,c]=N.useState(""),d=()=>{i&&(t({blocked_date:i,reason:o||void 0}),a(!1),l(""),c(""))};return e.jsxs(_e,{children:[e.jsxs(zt,{className:"flex flex-row items-center justify-between",children:[e.jsxs("div",{children:[e.jsxs(qt,{className:"flex items-center gap-2",children:[e.jsx($G,{className:"h-5 w-5"}),"Blocked Dates"]}),e.jsx(_r,{children:"Block specific dates (vacations, holidays, etc.)"})]}),e.jsxs(B,{size:"sm",variant:"outline",onClick:()=>a(!0),children:[e.jsx(nn,{className:"h-4 w-4 mr-1"})," Block Date"]})]}),e.jsxs(De,{children:[r&&e.jsxs("div",{className:"flex items-center gap-2 mb-3 p-3 rounded-lg border bg-muted/30",children:[e.jsx(we,{type:"date",value:i,onChange:u=>l(u.target.value),className:"w-40"}),e.jsx(we,{placeholder:"Reason (optional)",value:o,onChange:u=>c(u.target.value),className:"flex-1"}),e.jsx(B,{size:"sm",onClick:d,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:s.map(u=>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.jsx("span",{children:Js(new Date(u.blocked_date+"T00:00:00"),"MMM d, yyyy")}),u.reason&&e.jsxs("span",{className:"text-muted-foreground",children:["(",u.reason,")"]}),e.jsx("button",{onClick:()=>n(u.id),className:"ml-1 text-muted-foreground hover:text-destructive",children:e.jsx(hr,{className:"h-3.5 w-3.5"})})]},u.id))})]})]})}function SDn(){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:f,cancelBooking:g}=bDn(),[y,x]=N.useState("");N.useState(15),y||s!=null&&s.meeting_link;const _=s!=null&&s.slug?`https://booking.relevelup.com/${s.slug}`:null;return i?e.jsx(Qs,{children:e.jsx("div",{className:"flex items-center justify-center h-64",children:e.jsx("div",{className:"animate-spin rounded-full h-8 w-8 border-b-2 border-primary"})})}):s?e.jsx(Qs,{children:e.jsxs("div",{className:"space-y-6 p-4 md:p-8",children:[e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4",children:[e.jsxs("div",{children:[e.jsxs("h1",{className:"text-2xl font-bold flex items-center gap-2",children:[e.jsx(ld,{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:[_&&e.jsxs(e.Fragment,{children:[e.jsxs(B,{variant:"outline",size:"sm",onClick:()=>{navigator.clipboard.writeText(_),ie.success("Booking link copied!")},children:[e.jsx(Pa,{className:"h-4 w-4 mr-1"})," Copy Link"]}),e.jsx(B,{variant:"outline",size:"sm",asChild:!0,children:e.jsxs("a",{href:_,target:"_blank",rel:"noopener noreferrer",children:[e.jsx(Tr,{className:"h-4 w-4 mr-1"})," Preview"]})})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(re,{htmlFor:"scheduler-active",className:"text-sm",children:"Active"}),e.jsx(zn,{id:"scheduler-active",checked:s.is_active,onCheckedChange:b=>o.mutate({is_active:b})})]})]})]}),e.jsxs(ya,{defaultValue:"types",className:"space-y-4",children:[e.jsxs(va,{children:[e.jsx(ls,{value:"types",children:"Booking Types"}),e.jsx(ls,{value:"availability",children:"Availability"}),e.jsx(ls,{value:"settings",children:"Settings"}),e.jsxs(ls,{value:"bookings",children:["Bookings",a.filter(b=>b.status==="confirmed").length>0&&e.jsx(We,{variant:"secondary",className:"ml-1.5 text-xs",children:a.filter(b=>b.status==="confirmed").length})]})]}),e.jsx(_s,{value:"types",children:e.jsx(_Dn,{types:t,onSave:b=>c.mutate(b),onDelete:b=>d.mutate(b)})}),e.jsx(_s,{value:"availability",children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(wDn,{slots:n,onSave:b=>u.mutate(b),onDelete:b=>h.mutate(b)}),e.jsx(kDn,{blockedDates:r,onAdd:b=>m.mutate(b),onRemove:b=>f.mutate(b)})]})}),e.jsx(_s,{value:"settings",children:e.jsxs(_e,{children:[e.jsxs(zt,{children:[e.jsxs(qt,{className:"flex items-center gap-2",children:[e.jsx(C9,{className:"h-5 w-5"}),"General Settings"]}),e.jsx(_r,{children:"Configure your booking page defaults"})]}),e.jsxs(De,{className:"space-y-6",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{children:"Booking Page URL"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(we,{value:s.slug,readOnly:!0,className:"bg-muted"}),e.jsx(B,{variant:"outline",size:"sm",onClick:()=>{_&&(navigator.clipboard.writeText(_),ie.success("Copied!"))},children:e.jsx(Pa,{className:"h-4 w-4"})})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:_})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs(re,{htmlFor:"meeting-link",children:[e.jsx(cd,{className:"h-4 w-4 inline mr-1"}),"Default Meeting Link"]}),e.jsx(we,{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(re,{children:"Buffer Between Meetings"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(we,{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(re,{children:"Minimum Notice"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(we,{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(re,{children:"Max Advance Booking"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(we,{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.jsx(_s,{value:"bookings",children:e.jsx(NDn,{bookings:a,onCancel:b=>g.mutate({id:b})})})]})]})}):e.jsx(Qs,{children:e.jsxs("div",{className:"max-w-2xl mx-auto p-4 md:p-8 space-y-8",children:[e.jsxs("div",{className:"text-center space-y-4",children:[e.jsx("div",{className:"mx-auto w-16 h-16 bg-primary/10 rounded-2xl flex items-center justify-center",children:e.jsx(ld,{className:"h-8 w-8 text-primary"})}),e.jsx("h1",{className:"text-3xl font-bold",children:"LevelUp Scheduler"}),e.jsx("p",{className:"text-muted-foreground text-lg max-w-md mx-auto",children:"Your own booking page — built for real estate. Prospects book with you, get auto-added to your CRM, and you never miss a lead."})]}),e.jsx(_e,{children:e.jsxs(De,{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(Wl,{}),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(Cn,{className:"h-4 w-4 mr-2"}),l.isPending?"Setting up...":"Activate Scheduler"]})]})})]})})}const B0t=[{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 CDn(){const{user:s}=Ls(),t=Ya(),{toast:n}=Ci(),r=tr(),a=as(),[i,l]=N.useState(!1),[o,c]=N.useState(null),[d,u]=N.useState(null),[h,m]=N.useState({title:"",description:"",page_type:"lead_capture"}),{data:f=[],isLoading:g}=mt({queryKey:["landing-pages",t],queryFn:async()=>{const{data:b,error:k}=await H.from("landing_pages").select("*").eq("user_id",t).is("deleted_at",null).order("created_at",{ascending:!1});if(k)throw k;return b},enabled:!!t}),y=_t({mutationFn:async()=>{const b=h.title.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/(^-|-$)/g,"")+"-"+Date.now().toString(36),{data:k}=await H.from("profiles").select("name, phone, avatar_url, email").eq("id",t).single(),A=h.page_type==="just_listed"||h.page_type==="just_sold",{data:T,error:P}=await H.from("landing_pages").insert({user_id:t,title:h.title,description:h.description||null,page_type:h.page_type,slug:b,hero_headline:A?h.page_type==="just_listed"?"🏡 Just Listed":"🎉 Just Sold":h.page_type==="lead_magnet"?"📥 Free Download":h.title,agent_name:(k==null?void 0:k.name)||null,agent_phone:(k==null?void 0:k.phone)||null,agent_email:(k==null?void 0:k.email)||s.email||null,agent_photo_url:(k==null?void 0:k.avatar_url)||null,property_status:A?h.page_type.replace("just_",""):null}).select().single();if(P)throw P;const I=ADn(h.page_type);if(I.length>0){const{error:M}=await H.from("landing_page_fields").insert(I.map((L,z)=>({...L,page_id:T.id,sort_order:z})));if(M)throw M}return T},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"})}),x=_t({mutationFn:async b=>{const{error:k}=await H.from("landing_pages").update({deleted_at:new Date().toISOString(),is_published:!1}).eq("id",b);if(k)throw k},onSuccess:()=>{a.invalidateQueries({queryKey:["landing-pages"]}),c(null),n({title:"Landing page deleted"})}}),_=b=>`https://pages.relevelup.com/${b}`;return e.jsxs(Qs,{title:"Landing Pages",children:[e.jsxs("div",{className:"space-y-6 max-w-5xl mx-auto",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl font-bold",children:"Landing Pages"}),e.jsx("p",{className:"text-muted-foreground text-sm mt-1",children:"Create branded lead capture pages for events, consultations, and more"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(B,{variant:"outline",onClick:()=>r("/mission-control/landing-pages/defaults"),children:[e.jsx(sc,{className:"h-4 w-4 mr-2"})," Defaults"]}),e.jsxs(B,{onClick:()=>l(!0),children:[e.jsx(nn,{className:"h-4 w-4 mr-2"})," New Page"]})]})]}),g?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"})}):f.length===0?e.jsx(_e,{children:e.jsxs(De,{className:"flex flex-col items-center justify-center py-16",children:[e.jsx(Wr,{className:"h-12 w-12 text-muted-foreground mb-4"}),e.jsx("h3",{className:"text-lg font-semibold",children:"No landing pages yet"}),e.jsx("p",{className:"text-muted-foreground text-sm mt-1 mb-4",children:"Create your first page to start capturing leads"}),e.jsxs(B,{onClick:()=>l(!0),children:[e.jsx(nn,{className:"h-4 w-4 mr-2"})," Create Landing Page"]})]})}):e.jsx("div",{className:"grid gap-4",children:f.map(b=>{var k;return e.jsx(_e,{className:"hover:shadow-md transition-shadow",children:e.jsx(De,{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(We,{variant:b.is_published?"default":"secondary",className:"text-[10px]",children:b.is_published?"Published":"Draft"}),e.jsx(We,{variant:"outline",className:"text-[10px]",children:((k=B0t.find(A=>A.id===b.page_type))==null?void 0:k.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(da,{className:"h-3 w-3"})," ",b.view_count," views"]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Wr,{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(_(b.slug)),children:e.jsx(M_,{className:"h-3.5 w-3.5"})}),e.jsx(B,{size:"sm",variant:"outline",onClick:()=>{navigator.clipboard.writeText(_(b.slug)),n({title:"Link copied!"})},children:e.jsx(Pa,{className:"h-3.5 w-3.5"})}),e.jsx(B,{size:"sm",variant:"outline",asChild:!0,children:e.jsx("a",{href:_(b.slug),target:"_blank",rel:"noopener noreferrer",children:e.jsx(Tr,{className:"h-3.5 w-3.5"})})})]}),e.jsxs(qd,{children:[e.jsx(Vd,{asChild:!0,children:e.jsx(B,{size:"sm",variant:"ghost",children:e.jsx(Ev,{className:"h-4 w-4"})})}),e.jsxs(Ld,{align:"end",children:[e.jsxs(ba,{onClick:()=>r(`/mission-control/landing-pages/${b.id}`),children:[e.jsx(Ja,{className:"h-3.5 w-3.5 mr-2"})," Edit"]}),e.jsxs(ba,{onClick:()=>c(b.id),className:"text-destructive",children:[e.jsx(qn,{className:"h-3.5 w-3.5 mr-2"})," Delete"]})]})]})]})]})})},b.id)})})]}),e.jsx(Bs,{open:i,onOpenChange:l,children:e.jsxs(Fs,{children:[e.jsx(qs,{children:e.jsx($s,{children:"Create Landing Page"})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(re,{children:"Page Title"}),e.jsx(we,{value:h.title,onChange:b=>m(k=>({...k,title:b.target.value})),placeholder:"e.g. Veterans Home & Land Expo"})]}),e.jsxs("div",{children:[e.jsx(re,{children:"Description (optional)"}),e.jsx(Ws,{value:h.description,onChange:b=>m(k=>({...k,description:b.target.value})),placeholder:"Brief internal description...",rows:2})]}),e.jsxs("div",{children:[e.jsx(re,{children:"Page Template"}),e.jsxs(Ns,{value:h.page_type,onValueChange:b=>m(k=>({...k,page_type:b})),children:[e.jsx(ws,{children:e.jsx(ks,{})}),e.jsx(js,{children:B0t.map(b=>e.jsx(nt,{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(Cr,{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(Fl,{open:!!o,onOpenChange:()=>c(null),children:e.jsxs(kl,{children:[e.jsxs(Sl,{children:[e.jsx(Al,{children:"Delete Landing Page?"}),e.jsx(Tl,{children:"This will permanently delete this page and all its submissions."})]}),e.jsxs(Cl,{children:[e.jsx(El,{children:"Cancel"}),e.jsx(wl,{onClick:()=>o&&x.mutate(o),children:"Delete"})]})]})}),e.jsx(Bs,{open:!!d,onOpenChange:()=>u(null),children:e.jsxs(Fs,{className:"max-w-sm",children:[e.jsx(qs,{children:e.jsx($s,{children:"QR Code"})}),e.jsxs("div",{className:"flex flex-col items-center gap-4 py-4",children:[d&&e.jsx(IJ,{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(Pa,{className:"h-3.5 w-3.5 mr-1"})," Copy URL"]})]})]})})]})}function ADn(s){const t=[{field_type:"text",label:"Full Name",placeholder:"Your name",is_required:!0},{field_type:"email",label:"Email",placeholder:"your@email.com",is_required:!0},{field_type:"phone",label:"Phone",placeholder:"(555) 123-4567",is_required:!1}];switch(s){case"event_registration":return[...t,{field_type:"select",label:"How did you hear about this event?",options:JSON.stringify(["Social Media","Friend/Referral","Email","Flyer/Sign","Other"]),is_required:!1},{field_type:"textarea",label:"Any questions or special needs?",placeholder:"Let us know...",is_required:!1}];case"buyer_consultation":return[...t,{field_type:"select",label:"Interested in",options:JSON.stringify(["Buying","Selling","Both"]),is_required:!0},{field_type:"select",label:"Timeline",options:JSON.stringify(["0-3 months","3-6 months","6-12 months","Just exploring"]),is_required:!1},{field_type:"toggle",label:"Already working with a Realtor?",is_required:!1},{field_type:"toggle",label:"Do you have property to sell?",is_required:!1},{field_type:"textarea",label:"Anything else we should know?",placeholder:"Tell us about your situation...",is_required:!1}];case"home_valuation":return[...t,{field_type:"text",label:"Property Address",placeholder:"123 Main St, City, State",is_required:!0},{field_type:"select",label:"Reason for Valuation",options:JSON.stringify(["Thinking of selling","Refinancing","Curiosity","Estate planning","Other"]),is_required:!1},{field_type:"select",label:"Timeline to Sell",options:JSON.stringify(["ASAP","1-3 months","3-6 months","6+ months","Not sure"]),is_required:!1}];case"lead_magnet":return[...t,{field_type:"select",label:"Are you currently working with a Realtor?",options:JSON.stringify(["Yes","No","Not yet"]),is_required:!1}];case"just_listed":return[...t,{field_type:"select",label:"I am interested in",options:JSON.stringify(["Scheduling a showing","Getting more details","Similar properties","Selling my home"]),is_required:!0},{field_type:"textarea",label:"Message",placeholder:"Tell me more about this property...",is_required:!1}];case"just_sold":return[...t,{field_type:"select",label:"I am looking to",options:JSON.stringify(["Sell my home","Buy a home","Both","Just curious"]),is_required:!0},{field_type:"text",label:"My Property Address",placeholder:"123 Main St, City, State",is_required:!1}];default:return[...t,{field_type:"textarea",label:"Message",placeholder:"How can we help you?",is_required:!1}]}}function TDn(s,t){return t?`${(s/t*100).toFixed(1)}%`:"0%"}function EDn({pageId:s}){const{data:t=[],isLoading:n}=mt({queryKey:["landing-page-events",s],queryFn:async()=>{const l=new Date(Date.now()-2592e6).toISOString(),{data:o,error:c}=await H.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=[]}=mt({queryKey:["landing-page-submissions-analytics",s],queryFn:async()=>{const{data:l}=await H.from("landing_page_submissions").select("id, created_at").eq("page_id",s);return l||[]}}),a=N.useMemo(()=>{const l=t.filter(g=>g.event_type==="view"),o=t.filter(g=>g.event_type==="click"),c=new Set(l.map(g=>g.session_id).filter(Boolean)),d=new Map,u=new Map,h=new Map;for(const g of l){const y=g.utm_source||"Direct / unknown";if(d.set(y,(d.get(y)||0)+1),g.referrer)try{const _=new URL(g.referrer).hostname.replace(/^www\./,"");u.set(_,(u.get(_)||0)+1)}catch{}const x=g.device||"unknown";h.set(x,(h.get(x)||0)+1)}const m=[];for(let g=13;g>=0;g--){const y=new Date;y.setHours(0,0,0,0),y.setDate(y.getDate()-g);const x=new Date(y);x.setDate(y.getDate()+1);const _=y.toLocaleDateString("en-US",{month:"numeric",day:"numeric"}),b=l.filter(A=>{const T=new Date(A.created_at);return T>=y&&T{const T=new Date(A.created_at);return T>=y&&Tg.views));return{views:l.length,sessions:c.size,clicks:o.length,submissions:r.length,conversion:TDn(r.length,c.size||l.length),sourceCounts:[...d.entries()].sort((g,y)=>y[1]-g[1]).slice(0,6),referrerCounts:[...u.entries()].sort((g,y)=>y[1]-g[1]).slice(0,6),deviceCounts:[...h.entries()].sort((g,y)=>y[1]-g[1]),days:m,maxBar:f}},[t,r]);if(n)return e.jsx("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-3",children:Array.from({length:4}).map((l,o)=>e.jsx(xn,{className:"h-24"},o))});const i=[{label:"Views (30d)",value:a.views,icon:da},{label:"Unique visitors",value:a.sessions,icon:Yn},{label:"Submissions",value:a.submissions,icon:Rr},{label:"Conversion rate",value:a.conversion,icon:ml}];return e.jsxs("div",{className:"space-y-4",children:[e.jsx("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-3",children:i.map(l=>e.jsx(_e,{children:e.jsxs(De,{className:"p-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-xs text-muted-foreground",children:[e.jsx(l.icon,{className:"h-3.5 w-3.5"})," ",l.label]}),e.jsx("div",{className:"text-2xl font-semibold mt-1",children:l.value})]})},l.label))}),e.jsxs(_e,{children:[e.jsx(zt,{children:e.jsx(qt,{className:"text-base",children:"Last 14 days"})}),e.jsxs(De,{children:[a.views===0?e.jsx("p",{className:"text-sm text-muted-foreground",children:"No traffic yet. Share your page link or QR code to start collecting visits."}):e.jsx("div",{className:"flex items-end gap-1.5 h-32",children:a.days.map((l,o)=>e.jsxs("div",{className:"flex-1 flex flex-col items-center gap-1",children:[e.jsxs("div",{className:"w-full flex flex-col justify-end h-24",children:[e.jsx("div",{title:`${l.views} views · ${l.submits} submits`,className:"w-full rounded-t bg-primary/70",style:{height:`${l.views/a.maxBar*100}%`,minHeight:l.views?2:0}}),l.submits>0&&e.jsx("div",{className:"w-full bg-emerald-500",style:{height:`${Math.max(2,l.submits/a.maxBar*100)}%`}})]}),e.jsx("span",{className:"text-[10px] text-muted-foreground",children:l.label})]},o))}),e.jsxs("div",{className:"flex items-center gap-4 mt-3 text-xs text-muted-foreground",children:[e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx("span",{className:"w-2 h-2 rounded-sm bg-primary/70"})," Views"]}),e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx("span",{className:"w-2 h-2 rounded-sm bg-emerald-500"})," Submissions"]})]})]})]}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-3",children:[e.jsxs(_e,{children:[e.jsx(zt,{children:e.jsxs(qt,{className:"text-base flex items-center gap-2",children:[e.jsx(ru,{className:"h-4 w-4"})," Top sources"]})}),e.jsx(De,{children:a.sourceCounts.length===0?e.jsx("p",{className:"text-xs text-muted-foreground",children:"No UTM data yet."}):e.jsx("ul",{className:"space-y-1.5 text-sm",children:a.sourceCounts.map(([l,o])=>e.jsxs("li",{className:"flex justify-between",children:[e.jsx("span",{className:"truncate",children:l}),e.jsx("span",{className:"text-muted-foreground",children:o})]},l))})})]}),e.jsxs(_e,{children:[e.jsx(zt,{children:e.jsx(qt,{className:"text-base",children:"Top referrers"})}),e.jsx(De,{children:a.referrerCounts.length===0?e.jsx("p",{className:"text-xs text-muted-foreground",children:"No external referrers tracked."}):e.jsx("ul",{className:"space-y-1.5 text-sm",children:a.referrerCounts.map(([l,o])=>e.jsxs("li",{className:"flex justify-between",children:[e.jsx("span",{className:"truncate",children:l}),e.jsx("span",{className:"text-muted-foreground",children:o})]},l))})})]}),e.jsxs(_e,{children:[e.jsx(zt,{children:e.jsx(qt,{className:"text-base",children:"Devices"})}),e.jsx(De,{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 MDn=[{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 LDn=0;const $0t=()=>`f_${Date.now()}_${++LDn}`;function PDn({field:s,index:t,updateField:n,removeField:r}){const{attributes:a,listeners:i,setNodeRef:l,transform:o,transition:c,isDragging:d}=V3e({id:s.clientId}),u={transform:fE.Transform.toString(o),transition:c,zIndex:d?50:void 0,opacity:d?.85:1};return e.jsx(_e,{ref:l,style:u,children:e.jsx(De,{className:"p-4",children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx("button",{type:"button",...a,...i,className:"mt-1 p-1 rounded text-muted-foreground hover:text-foreground hover:bg-muted cursor-grab active:cursor-grabbing touch-none","aria-label":"Drag to reorder",children:e.jsx(Mp,{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(re,{className:"text-xs",children:"Field Type"}),e.jsxs(Ns,{value:s.field_type,onValueChange:h=>n(t,{field_type:h}),children:[e.jsx(ws,{children:e.jsx(ks,{})}),e.jsx(js,{children:MDn.map(h=>e.jsx(nt,{value:h.value,children:h.label},h.value))})]})]}),e.jsxs("div",{children:[e.jsx(re,{className:"text-xs",children:"Label"}),e.jsx(we,{value:s.label,onChange:h=>n(t,{label:h.target.value}),placeholder:"e.g. Full Name"})]}),e.jsxs("div",{children:[e.jsx(re,{className:"text-xs",children:"Placeholder"}),e.jsx(we,{value:s.placeholder||"",onChange:h=>n(t,{placeholder:h.target.value}),placeholder:"Optional hint text"})]})]}),(s.field_type==="select"||s.field_type==="multiselect")&&e.jsxs("div",{children:[e.jsx(re,{className:"text-xs",children:"Options (comma-separated)"}),e.jsx(we,{value:s.options?(typeof s.options=="string"?JSON.parse(s.options):s.options).join(", "):"",onChange:h=>n(t,{options:JSON.stringify(h.target.value.split(",").map(m=>m.trim()).filter(Boolean))}),placeholder:"Option 1, Option 2, Option 3"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(zn,{checked:s.is_required,onCheckedChange:h=>n(t,{is_required:h})}),e.jsx(re,{className:"text-xs",children:"Required"})]})]}),e.jsx(B,{variant:"ghost",size:"sm",onClick:()=>r(t),children:e.jsx(qn,{className:"h-3.5 w-3.5 text-destructive"})})]})})})}function IDn(){const{pageId:s}=uo(),t=tr(),{user:n}=Ls(),r=Ya(),{toast:a}=Ci(),i=as(),[l,o]=N.useState(null),[c,d]=N.useState(!1),{data:u,isLoading:h}=mt({queryKey:["landing-page",s],queryFn:async()=>{const{data:ce,error:ae}=await H.from("landing_pages").select("*").eq("id",s).single();if(ae)throw ae;return ce},enabled:!!s}),{data:m=[],isLoading:f}=mt({queryKey:["landing-page-fields",s],queryFn:async()=>{const{data:ce,error:ae}=await H.from("landing_page_fields").select("*").eq("page_id",s).order("sort_order");if(ae)throw ae;return ce},enabled:!!s}),{data:g=[]}=mt({queryKey:["landing-page-submissions",s],queryFn:async()=>{const{data:ce,error:ae}=await H.from("landing_page_submissions").select("*").eq("page_id",s).order("created_at",{ascending:!1});if(ae)throw ae;return ce},enabled:!!s}),{data:y=[]}=mt({queryKey:["my-listings-for-pages",r],queryFn:async()=>{const{data:ce,error:ae}=await H.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 ce},enabled:!!n&&((u==null?void 0:u.page_type)==="just_listed"||(u==null?void 0:u.page_type)==="just_sold")}),{data:x=[]}=mt({queryKey:["drips-for-landing",r],queryFn:async()=>{const{data:ce}=await H.from("drip_campaigns").select("id, name").eq("owner_user_id",r).eq("is_active",!0).order("name");return ce||[]},enabled:!!r}),{data:_}=mt({queryKey:["agent-landing-defaults",r],queryFn:async()=>{const{data:ce}=await H.from("agent_landing_page_defaults").select("*").eq("user_id",r).maybeSingle();return ce},enabled:!!r}),[b,k]=N.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:""}),[A,T]=N.useState([]);N.useEffect(()=>{var ce,ae,he,xe,ve,ge,be,Se,Ie;u&&k({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:((ce=u.settings)==null?void 0:ce.redirect_url)||"",settings_auto_responder_subject:((ae=u.settings)==null?void 0:ae.auto_responder_subject)||"",settings_auto_responder_body:((he=u.settings)==null?void 0:he.auto_responder_body)||"",settings_drip_campaign_id:((xe=u.settings)==null?void 0:xe.drip_campaign_id)||null,settings_disable_auto_responder:!!((ve=u.settings)!=null&&ve.disable_auto_responder),settings_disable_drip:!!((ge=u.settings)!=null&&ge.disable_drip),settings_event_starts_at:((be=u.settings)==null?void 0:be.event_starts_at)||"",settings_event_location_name:((Se=u.settings)==null?void 0:Se.event_location_name)||"",settings_event_address:((Ie=u.settings)==null?void 0:Ie.event_address)||""})},[u]),N.useEffect(()=>{m.length>0&&T(m.map(ce=>({id:ce.id,clientId:ce.id||$0t(),field_type:ce.field_type,label:ce.label,placeholder:ce.placeholder,is_required:ce.is_required,options:typeof ce.options=="string"?ce.options:ce.options?JSON.stringify(ce.options):null,sort_order:ce.sort_order})))},[m]);const P=_t({mutationFn:async()=>{const{error:ce}=await H.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,settings:{...(u==null?void 0:u.settings)||{},redirect_url:b.settings_redirect_url||null,auto_responder_subject:b.settings_auto_responder_subject||null,auto_responder_body:b.settings_auto_responder_body||null,drip_campaign_id:b.settings_drip_campaign_id||null,disable_auto_responder:!!b.settings_disable_auto_responder,disable_drip:!!b.settings_disable_drip,event_starts_at:b.settings_event_starts_at||null,event_location_name:b.settings_event_location_name||null,event_address:b.settings_event_address||null},updated_at:new Date().toISOString()}).eq("id",s);if(ce)throw ce;if(await H.from("landing_page_fields").delete().eq("page_id",s),A.length>0){const{error:ae}=await H.from("landing_page_fields").insert(A.map((he,xe)=>({page_id:s,field_type:he.field_type,label:he.label,placeholder:he.placeholder||null,is_required:he.is_required,options:he.options?JSON.parse(he.options):null,sort_order:xe})));if(ae)throw ae}},onSuccess:()=>{i.invalidateQueries({queryKey:["landing-page",s]}),i.invalidateQueries({queryKey:["landing-page-fields",s]}),a({title:"Page saved!"})},onError:ce=>a({title:"Error",description:ce.message,variant:"destructive"})}),I=async(ce,ae)=>{const he=ce.name.split(".").pop(),xe=`landing-pages/${n.id}/${ae}-${Date.now()}.${he}`,{error:ve}=await H.storage.from("recruit-landing").upload(xe,ce);if(ve)throw ve;const{data:{publicUrl:ge}}=H.storage.from("recruit-landing").getPublicUrl(xe);return ge},M=async(ce,ae)=>{var xe;const he=(xe=ce.target.files)==null?void 0:xe[0];if(he){o(ae);try{const ve=await I(he,ae);k(ge=>({...ge,[ae]:ve})),a({title:"Image uploaded!"})}catch(ve){a({title:"Upload failed",description:ve.message,variant:"destructive"})}finally{o(null)}}},L=async ce=>{var he;const ae=(he=ce.target.files)==null?void 0:he[0];if(ae){o("lead_magnet");try{const xe=await I(ae,"lead-magnet");k(ve=>({...ve,lead_magnet_file_url:xe,lead_magnet_file_name:ae.name})),a({title:"File uploaded!"})}catch(xe){a({title:"Upload failed",description:xe.message,variant:"destructive"})}finally{o(null)}}},z=async ce=>{const ae=ce.target.files;if(!(!ae||ae.length===0)){o("property_photos");try{const he=[];for(const xe of Array.from(ae)){const ve=await I(xe,"property-photo");he.push(ve)}k(xe=>({...xe,property_photos:[...xe.property_photos,...he]})),a({title:`${he.length} photo(s) uploaded!`})}catch(he){a({title:"Upload failed",description:he.message,variant:"destructive"})}finally{o(null)}}},$=async ce=>{const ae=y.find(xe=>xe.id===ce);if(!ae)return;const{data:he}=await H.from("listing_photos").select("photo_url").eq("listing_id",ce).order("sort_order");k(xe=>({...xe,listing_id:ce,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:(he==null?void 0:he.map(ve=>ve.photo_url))||xe.property_photos})),a({title:"Listing data imported!"})},V=()=>{T(ce=>[...ce,{clientId:$0t(),field_type:"text",label:"",placeholder:"",is_required:!1,options:null,sort_order:ce.length}])},W=(ce,ae)=>{T(he=>he.map((xe,ve)=>ve===ce?{...xe,...ae}:xe))},G=ce=>{T(ae=>ae.filter((he,xe)=>xe!==ce))},X=D3e(QB(kU,{activationConstraint:{distance:6}}),QB(F3e,{coordinateGetter:n6t})),te=ce=>{const{active:ae,over:he}=ce;!he||ae.id===he.id||T(xe=>{const ve=xe.findIndex(be=>be.clientId===ae.id),ge=xe.findIndex(be=>be.clientId===he.id);return ve<0||ge<0?xe:U3e(xe,ve,ge).map((be,Se)=>({...be,sort_order:Se}))})},ne=u?`https://pages.relevelup.com/${u.slug}`:"",me=(u==null?void 0:u.page_type)==="lead_magnet",ue=(u==null?void 0:u.page_type)==="just_listed"||(u==null?void 0:u.page_type)==="just_sold";return h||f?e.jsx(Qs,{title:"Loading...",children:e.jsx("div",{className:"flex justify-center py-12",children:e.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})})}):u?e.jsxs(Qs,{title:b.title||"Edit Page",children:[e.jsxs("div",{className:"space-y-6 max-w-4xl mx-auto",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(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(We,{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(da,{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(Yn,{className:"h-3 w-3"})," ",g.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(M_,{className:"h-3.5 w-3.5"})}),e.jsxs(B,{size:"sm",variant:"outline",onClick:()=>{navigator.clipboard.writeText(ne),a({title:"Link copied!"})},children:[e.jsx(Pa,{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:ne,target:"_blank",rel:"noopener noreferrer",children:[e.jsx(Tr,{className:"h-3.5 w-3.5 mr-1"})," Preview"]})})]}),e.jsxs(B,{onClick:()=>P.mutate(),disabled:P.isPending,children:[e.jsx(Kl,{className:"h-4 w-4 mr-2"}),P.isPending?"Saving...":"Save"]})]})]}),e.jsxs(ya,{defaultValue:"design",children:[e.jsxs(va,{children:[e.jsx(ls,{value:"design",children:"Design"}),me&&e.jsx(ls,{value:"lead_magnet",children:"Lead Magnet"}),ue&&e.jsx(ls,{value:"property",children:"Property Details"}),e.jsxs(ls,{value:"fields",children:["Form Fields (",A.length,")"]}),e.jsxs(ls,{value:"submissions",children:["Submissions (",g.length,")"]}),e.jsx(ls,{value:"automation",children:"Automation"}),e.jsx(ls,{value:"analytics",children:"Analytics"}),e.jsx(ls,{value:"settings",children:"Settings"})]}),e.jsxs(_s,{value:"design",className:"space-y-4 mt-4",children:[e.jsxs(_e,{children:[e.jsx(zt,{children:e.jsx(qt,{className:"text-base",children:"Page Details"})}),e.jsxs(De,{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(re,{children:"Page Title (internal)"}),e.jsx(we,{value:b.title,onChange:ce=>k(ae=>({...ae,title:ce.target.value}))})]}),e.jsxs("div",{children:[e.jsx(re,{children:"Description (internal)"}),e.jsx(we,{value:b.description,onChange:ce=>k(ae=>({...ae,description:ce.target.value}))})]})]})]}),e.jsxs(_e,{children:[e.jsx(zt,{children:e.jsxs(qt,{className:"text-base flex items-center gap-2",children:["Theme & Style",e.jsx(We,{variant:"secondary",className:"text-[10px]",children:"New"})]})}),e.jsxs(De,{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(re,{children:"Theme Style"}),e.jsxs(Ns,{value:b.theme_style,onValueChange:ce=>k(ae=>({...ae,theme_style:ce})),children:[e.jsx(ws,{children:e.jsx(ks,{})}),e.jsxs(js,{children:[e.jsx(nt,{value:"premium",children:"Premium — cinematic + glass form"}),e.jsx(nt,{value:"classic",children:"Classic — centered card"})]})]})]}),e.jsxs("div",{children:[e.jsx(re,{children:"Headline Font"}),e.jsxs(Ns,{value:b.heading_font,onValueChange:ce=>k(ae=>({...ae,heading_font:ce})),children:[e.jsx(ws,{children:e.jsx(ks,{})}),e.jsxs(js,{children:[e.jsx(nt,{value:"playfair",children:"Playfair Display (editorial serif)"}),e.jsx(nt,{value:"baskerville",children:"Libre Baskerville (classic serif)"}),e.jsx(nt,{value:"instrument",children:"Instrument Serif (modern serif)"}),e.jsx(nt,{value:"sans",children:"Inter (clean sans-serif)"})]})]})]})]}),e.jsxs("div",{children:[e.jsx(re,{children:"Trust Pills (comma separated, shown under CTA)"}),e.jsx(we,{value:b.trust_pills.join(", "),onChange:ce=>k(ae=>({...ae,trust_pills:ce.target.value.split(",").map(he=>he.trim()).filter(Boolean)})),placeholder:"No obligation, 100% free, 60 seconds or less"})]}),e.jsx("p",{className:"text-[11px] text-muted-foreground",children:"Premium theme uses a cinematic full-screen hero, italic accent word, glass-effect form, and trust pills — magazine-style."})]})]}),e.jsxs(_e,{children:[e.jsx(zt,{children:e.jsx(qt,{className:"text-base",children:"Hero Section"})}),e.jsxs(De,{className:"space-y-4",children:[b.theme_style==="premium"&&e.jsxs("div",{children:[e.jsx(re,{children:"Eyebrow (small label above headline)"}),e.jsx(we,{value:b.eyebrow,onChange:ce=>k(ae=>({...ae,eyebrow:ce.target.value})),placeholder:"HOME VALUE"})]}),e.jsxs("div",{children:[e.jsx(re,{children:"Headline"}),e.jsx(we,{value:b.hero_headline,onChange:ce=>k(ae=>({...ae,hero_headline:ce.target.value})),placeholder:"What Is Your Home"})]}),b.theme_style==="premium"&&e.jsxs("div",{children:[e.jsx(re,{children:"Accent Word(s) — italic & colored (optional)"}),e.jsx(we,{value:b.headline_accent,onChange:ce=>k(ae=>({...ae,headline_accent:ce.target.value})),placeholder:"Actually Worth?"})]}),e.jsxs("div",{children:[e.jsx(re,{children:"Subtext"}),e.jsx(Ws,{value:b.hero_subtext,onChange:ce=>k(ae=>({...ae,hero_subtext:ce.target.value})),rows:3,placeholder:"A brief description..."})]}),e.jsxs("div",{children:[e.jsxs(re,{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(ni,{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:ce=>M(ce,"hero_image_url")})]}),b.hero_image_url&&e.jsx(B,{variant:"ghost",size:"sm",onClick:()=>k(ce=>({...ce,hero_image_url:null})),children:e.jsx(qn,{className:"h-3.5 w-3.5"})})]})]})]})]}),e.jsxs(_e,{children:[e.jsx(zt,{children:e.jsx(qt,{className:"text-base",children:"Branding"})}),e.jsxs(De,{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(re,{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(ni,{className:"h-3.5 w-3.5 mr-1"}),l==="logo_url"?"...":"Upload"]})}),e.jsx("input",{type:"file",accept:"image/*",className:"hidden",onChange:ce=>M(ce,"logo_url")})]})]})]}),e.jsxs("div",{children:[e.jsx(re,{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(ni,{className:"h-3.5 w-3.5 mr-1"}),l==="agent_photo_url"?"...":"Upload"]})}),e.jsx("input",{type:"file",accept:"image/*",className:"hidden",onChange:ce=>M(ce,"agent_photo_url")})]})]})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx(re,{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:ce=>k(ae=>({...ae,primary_color:ce.target.value})),className:"h-9 w-12 rounded border cursor-pointer"}),e.jsx(we,{value:b.primary_color,onChange:ce=>k(ae=>({...ae,primary_color:ce.target.value})),className:"font-mono text-xs"})]})]}),e.jsxs("div",{children:[e.jsx(re,{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:ce=>k(ae=>({...ae,accent_color:ce.target.value})),className:"h-9 w-12 rounded border cursor-pointer"}),e.jsx(we,{value:b.accent_color,onChange:ce=>k(ae=>({...ae,accent_color:ce.target.value})),className:"font-mono text-xs"})]})]})]})]})]}),e.jsxs(_e,{children:[e.jsx(zt,{children:e.jsx(qt,{className:"text-base",children:"Agent Info (shown on page)"})}),e.jsx(De,{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(re,{children:"Name"}),e.jsx(we,{value:b.agent_name,onChange:ce=>k(ae=>({...ae,agent_name:ce.target.value}))})]}),e.jsxs("div",{children:[e.jsx(re,{children:"Phone"}),e.jsx(we,{value:b.agent_phone,onChange:ce=>k(ae=>({...ae,agent_phone:ce.target.value}))})]}),e.jsxs("div",{children:[e.jsx(re,{children:"Email"}),e.jsx(we,{value:b.agent_email,onChange:ce=>k(ae=>({...ae,agent_email:ce.target.value}))})]})]})})]})]}),me&&e.jsx(_s,{value:"lead_magnet",className:"space-y-4 mt-4",children:e.jsxs(_e,{children:[e.jsx(zt,{children:e.jsxs(qt,{className:"text-base flex items-center gap-2",children:[e.jsx(oi,{className:"h-4 w-4"})," Giveaway File"]})}),e.jsxs(De,{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(re,{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(We,{variant:"outline",className:"gap-1",children:[e.jsx(oi,{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(ni,{className:"h-3.5 w-3.5 mr-1"}),l==="lead_magnet"?"Uploading...":"Upload File"]})}),e.jsx("input",{type:"file",className:"hidden",onChange:L})]}),b.lead_magnet_file_url&&e.jsx(B,{variant:"ghost",size:"sm",onClick:()=>k(ce=>({...ce,lead_magnet_file_url:null,lead_magnet_file_name:null})),children:e.jsx(qn,{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(re,{className:"flex items-center gap-1",children:[e.jsx(cd,{className:"h-3.5 w-3.5"})," External URL"]}),e.jsx(we,{value:b.lead_magnet_external_url||"",onChange:ce=>k(ae=>({...ae,lead_magnet_external_url:ce.target.value||null})),placeholder:"https://drive.google.com/... or https://dropbox.com/...",className:"mt-1"}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:"Link to a file on Google Drive, Dropbox, or any URL"})]})]})]})}),ue&&e.jsxs(_s,{value:"property",className:"space-y-4 mt-4",children:[e.jsxs(_e,{children:[e.jsx(zt,{children:e.jsxs(qt,{className:"text-base flex items-center gap-2",children:[e.jsx(_a,{className:"h-4 w-4"})," Import from Listing Exchange"]})}),e.jsxs(De,{className:"space-y-4",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Pull property details and photos directly from one of your listings, or enter them manually below."}),e.jsxs(Ns,{value:b.listing_id||"",onValueChange:ce=>$(ce),children:[e.jsx(ws,{children:e.jsx(ks,{placeholder:"Select a listing to import..."})}),e.jsx(js,{children:y.map(ce=>{var ae;return e.jsxs(nt,{value:ce.id,children:[ce.property_address||`${ce.city}, ${ce.state}`," — $",(ae=ce.price)==null?void 0:ae.toLocaleString()]},ce.id)})})]})]})]}),e.jsxs(_e,{children:[e.jsx(zt,{children:e.jsx(qt,{className:"text-base",children:"Property Information"})}),e.jsxs(De,{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(re,{children:"Property Address"}),e.jsx(we,{value:b.property_address,onChange:ce=>k(ae=>({...ae,property_address:ce.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(re,{children:"Price"}),e.jsx(we,{value:b.property_price,onChange:ce=>k(ae=>({...ae,property_price:ce.target.value})),placeholder:"$450,000"})]}),e.jsxs("div",{children:[e.jsx(re,{children:"Beds"}),e.jsx(we,{value:b.property_beds,onChange:ce=>k(ae=>({...ae,property_beds:ce.target.value})),placeholder:"4"})]}),e.jsxs("div",{children:[e.jsx(re,{children:"Baths"}),e.jsx(we,{value:b.property_baths,onChange:ce=>k(ae=>({...ae,property_baths:ce.target.value})),placeholder:"3"})]}),e.jsxs("div",{children:[e.jsx(re,{children:"Sq Ft"}),e.jsx(we,{value:b.property_sqft,onChange:ce=>k(ae=>({...ae,property_sqft:ce.target.value})),placeholder:"2,400"})]})]}),e.jsxs("div",{children:[e.jsx(re,{children:"Description"}),e.jsx(Ws,{value:b.property_description,onChange:ce=>k(ae=>({...ae,property_description:ce.target.value})),rows:3,placeholder:"Beautiful home in a great neighborhood..."})]})]})]}),e.jsxs(_e,{children:[e.jsx(zt,{children:e.jsx(qt,{className:"text-base",children:"Property Photos"})}),e.jsxs(De,{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((ce,ae)=>e.jsxs("div",{className:"relative group",children:[e.jsx("img",{src:ce,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:()=>k(he=>({...he,property_photos:he.property_photos.filter((xe,ve)=>ve!==ae)})),children:e.jsx(qn,{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(ni,{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:z})]})]})]})]}),e.jsxs(_s,{value:"fields",className:"space-y-4 mt-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Configure the form fields visitors will fill out"}),e.jsxs(B,{size:"sm",onClick:V,children:[e.jsx(nn,{className:"h-3.5 w-3.5 mr-1"})," Add Field"]})]}),A.length===0?e.jsx(_e,{children:e.jsx(De,{className:"py-8 text-center text-muted-foreground",children:"No fields yet. Add fields to build your form."})}):e.jsx($3e,{sensors:X,collisionDetection:R3e,onDragEnd:te,children:e.jsx(q3e,{items:A.map(ce=>ce.clientId),strategy:dFs,children:e.jsx("div",{className:"space-y-3",children:A.map((ce,ae)=>e.jsx(PDn,{field:ce,index:ae,updateField:W,removeField:G},ce.clientId))})})})]}),e.jsx(_s,{value:"submissions",className:"mt-4",children:g.length===0?e.jsx(_e,{children:e.jsx(De,{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:g.map(ce=>e.jsx(_e,{children:e.jsx(De,{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:ce.contact_name||"Anonymous"}),ce.synced_to_crm&&e.jsx(We,{variant:"outline",className:"text-[10px]",children:"Synced"})]}),e.jsxs("div",{className:"text-sm text-muted-foreground mt-0.5",children:[ce.contact_email&&e.jsx("span",{className:"mr-3",children:ce.contact_email}),ce.contact_phone&&e.jsx("span",{children:ce.contact_phone})]}),ce.answers&&typeof ce.answers=="object"&&e.jsx("div",{className:"mt-2 text-sm space-y-1",children:Object.entries(ce.answers).map(([ae,he])=>e.jsxs("div",{children:[e.jsxs("span",{className:"font-medium text-muted-foreground",children:[ae,":"]})," ",e.jsx("span",{children:String(he)})]},ae))})]}),e.jsx("span",{className:"text-xs text-muted-foreground",children:new Date(ce.created_at).toLocaleDateString()})]})})},ce.id))})}),e.jsxs(_s,{value:"automation",className:"space-y-4 mt-4",children:[(u==null?void 0:u.page_type)==="event_registration"&&e.jsxs(_e,{children:[e.jsxs(zt,{children:[e.jsx(qt,{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(De,{className:"grid gap-3 md:grid-cols-2",children:[e.jsxs("div",{className:"space-y-1.5 md:col-span-2",children:[e.jsx(re,{children:"Starts at"}),e.jsx(we,{type:"datetime-local",value:b.settings_event_starts_at,onChange:ce=>k(ae=>({...ae,settings_event_starts_at:ce.target.value}))})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(re,{children:"Venue / location name"}),e.jsx(we,{placeholder:"e.g. The Grand Hotel",value:b.settings_event_location_name,onChange:ce=>k(ae=>({...ae,settings_event_location_name:ce.target.value}))})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(re,{children:"Address (for map link)"}),e.jsx(we,{placeholder:"123 Main St, City, ST",value:b.settings_event_address,onChange:ce=>k(ae=>({...ae,settings_event_address:ce.target.value}))})]})]})]}),e.jsxs(_e,{children:[e.jsxs(zt,{children:[e.jsx(qt,{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",_!=null&&_.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(De,{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(re,{children:"Send auto-reply for this page"}),e.jsx(zn,{checked:!b.settings_disable_auto_responder,onCheckedChange:ce=>k(ae=>({...ae,settings_disable_auto_responder:!ce}))})]}),!b.settings_disable_auto_responder&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{children:[e.jsx(re,{children:"Subject (override)"}),e.jsx(we,{value:b.settings_auto_responder_subject,onChange:ce=>k(ae=>({...ae,settings_auto_responder_subject:ce.target.value})),placeholder:(_==null?void 0:_.default_auto_responder_subject)||"Thanks for reaching out, {{client_first_name}}!"})]}),e.jsxs("div",{children:[e.jsx(re,{children:"Body (override)"}),e.jsx(Ws,{rows:8,value:b.settings_auto_responder_body,onChange:ce=>k(ae=>({...ae,settings_auto_responder_body:ce.target.value})),placeholder:(_==null?void 0:_.default_auto_responder_body)||`Hi {{client_first_name}}, Thanks for reaching out…`})]})]})]})]}),e.jsxs(_e,{children:[e.jsxs(zt,{children:[e.jsx(qt,{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.",(_==null?void 0:_.default_drip_campaign_id)&&" Account default applies if no override is selected."]})]}),e.jsxs(De,{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(re,{children:"Enroll new leads in a drip"}),e.jsx(zn,{checked:!b.settings_disable_drip,onCheckedChange:ce=>k(ae=>({...ae,settings_disable_drip:!ce}))})]}),!b.settings_disable_drip&&e.jsxs("div",{children:[e.jsx(re,{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:ce=>k(ae=>({...ae,settings_drip_campaign_id:ce.target.value||null})),children:[e.jsx("option",{value:"",children:"— Use account default —"}),x.map(ce=>e.jsx("option",{value:ce.id,children:ce.name},ce.id))]})]})]})]}),e.jsxs(_e,{children:[e.jsx(zt,{children:e.jsx(qt,{className:"text-base",children:"Redirect after submit"})}),e.jsxs(De,{children:[e.jsx(we,{value:b.settings_redirect_url,onChange:ce=>k(ae=>({...ae,settings_redirect_url:ce.target.value})),placeholder:(_==null?void 0:_.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(_s,{value:"analytics",className:"space-y-4 mt-4",children:e.jsx(EDn,{pageId:s})}),e.jsxs(_s,{value:"settings",className:"space-y-4 mt-4",children:[e.jsxs(_e,{children:[e.jsx(zt,{children:e.jsx(qt,{className:"text-base",children:"Publishing"})}),e.jsxs(De,{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(re,{children:"Published"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Make this page publicly accessible"})]}),e.jsx(zn,{checked:b.is_published,onCheckedChange:ce=>k(ae=>({...ae,is_published:ce}))})]}),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:ne})]})]})]}),e.jsxs(_e,{children:[e.jsx(zt,{children:e.jsx(qt,{className:"text-base",children:"Thank You Message"})}),e.jsx(De,{children:e.jsx(Ws,{value:b.success_message,onChange:ce=>k(ae=>({...ae,success_message:ce.target.value})),rows:2,placeholder:"Message shown after form submission"})})]})]})]})]}),e.jsx(Bs,{open:c,onOpenChange:d,children:e.jsxs(Fs,{className:"max-w-sm",children:[e.jsx(qs,{children:e.jsx($s,{children:"QR Code"})}),e.jsxs("div",{className:"flex flex-col items-center gap-4 py-4",children:[e.jsx(IJ,{value:ne,size:240}),e.jsx("p",{className:"text-xs text-muted-foreground text-center break-all",children:ne})]})]})})]}):e.jsx(Qs,{title:"Not Found",children:e.jsxs("div",{className:"text-center py-12",children:[e.jsx("p",{className:"text-muted-foreground",children:"Page not found"}),e.jsx(B,{variant:"link",onClick:()=>t("/mission-control/landing-pages"),children:"Go back"})]})})}const DDn={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},RDn=`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 ODn(){const s=Ya(),{toast:t}=Ci(),n=tr(),r=as(),[a,i]=N.useState(DDn),{data:l}=mt({queryKey:["landing-page-defaults",s],queryFn:async()=>{const{data:d}=await H.from("agent_landing_page_defaults").select("*").eq("user_id",s).maybeSingle();return d||null},enabled:!!s}),{data:o=[]}=mt({queryKey:["drip-campaigns-mine",s],queryFn:async()=>{const{data:d}=await H.from("drip_campaigns").select("id, name").eq("owner_user_id",s).eq("is_active",!0).order("name");return d||[]},enabled:!!s});N.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=_t({mutationFn:async()=>{const{error:d}=await H.from("agent_landing_page_defaults").upsert({user_id:s,...a},{onConflict:"user_id"});if(d)throw d},onSuccess:()=>{r.invalidateQueries({queryKey:["landing-page-defaults"]}),t({title:"Defaults saved"})},onError:d=>t({title:"Save failed",description:d.message,variant:"destructive"})});return e.jsx(Qs,{title:"Landing Page Defaults",children:e.jsxs("div",{className:"space-y-6 max-w-3xl mx-auto",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs(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(Kl,{className:"h-4 w-4 mr-2"})," ",c.isPending?"Saving…":"Save Defaults"]})]}),e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl font-bold",children:"Landing Page Defaults"}),e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:"These run on every landing page automatically. Any page can override them in its own settings."})]}),e.jsxs(_e,{children:[e.jsxs(zt,{children:[e.jsx(qt,{children:"Instant auto-reply to the lead"}),e.jsxs(_r,{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(De,{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(re,{children:"Subject"}),e.jsx(we,{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(re,{children:"Message body"}),e.jsx(Ws,{rows:10,value:a.default_auto_responder_body||"",onChange:d=>i(u=>({...u,default_auto_responder_body:d.target.value})),placeholder:RDn}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:"Leave blank to use the polished built-in template that adapts to each page type."})]})]})]}),e.jsxs(_e,{children:[e.jsxs(zt,{children:[e.jsx(qt,{children:"Default Smart Drip"}),e.jsx(_r,{children:"Every new lead drops into this drip unless a page overrides it."})]}),e.jsx(De,{children:e.jsxs(Ns,{value:a.default_drip_campaign_id||"none",onValueChange:d=>i(u=>({...u,default_drip_campaign_id:d==="none"?null:d})),children:[e.jsx(ws,{children:e.jsx(ks,{placeholder:"Pick a drip…"})}),e.jsxs(js,{children:[e.jsx(nt,{value:"none",children:"— No default drip —"}),o.map(d=>e.jsx(nt,{value:d.id,children:d.name},d.id))]})]})})]}),e.jsxs(_e,{children:[e.jsx(zt,{children:e.jsx(qt,{children:"Defaults for every page"})}),e.jsxs(De,{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(re,{children:"Default booking / calendar link"}),e.jsx(we,{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(re,{children:"Default redirect after submit (optional)"}),e.jsx(we,{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(re,{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(zn,{checked:a.use_brand_kit,onCheckedChange:d=>i(u=>({...u,use_brand_kit:d}))})]})]})]}),e.jsxs(_e,{children:[e.jsxs(zt,{children:[e.jsx(qt,{children:"Text me when a lead submits"}),e.jsx(_r,{children:"Get an SMS the second a lead hits your inbox. Coming soon — requires SMS sender setup."})]}),e.jsxs(De,{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between rounded-lg border p-3",children:[e.jsx(re,{className:"text-base",children:"SMS me new leads"}),e.jsx(zn,{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(re,{children:"Phone number for alerts"}),e.jsx(we,{type:"tel",value:a.agent_sms_phone||"",onChange:d=>i(u=>({...u,agent_sms_phone:d.target.value})),placeholder:"(555) 123-4567"})]})]})]})]})})}function FDn(){return mt({queryKey:["website-apps"],queryFn:async()=>{const{data:s,error:t}=await H.from("website_apps").select("*").order("sort_order",{ascending:!0});if(t)throw t;return s||[]}})}function BAe(){const{user:s}=Ls();return mt({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 H.from("agent_website_app_installs").select("*").eq("user_id",s.id);if(n)throw n;return t||[]},enabled:!!(s!=null&&s.id)})}function $Ae(){const{user:s}=Ls(),t=as();return _t({mutationFn:async({app_slug:n,enabled:r})=>{if(!(s!=null&&s.id))throw new Error("Not authenticated");const{error:a}=await H.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"]}),ie.success(r.enabled?"App installed":"App turned off")},onError:n=>ie.error(n.message||"Failed to update app")})}const zDn={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"}},BDn={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 $Dn(){const s=tr(),{data:t=[],isLoading:n}=FDn(),{data:r=[]}=BAe(),{hasLeadSite:a,siteUrl:i,isLoading:l}=Qx(),o=$Ae(),[c,d]=N.useState(!1),u=m=>{var f;return((f=r.find(g=>g.app_slug===m))==null?void 0:f.enabled)??!1},h=m=>r.some(f=>f.app_slug===m);return e.jsxs(Qs,{title:"Website Apps",description:"Conversion-boosting widgets for your website",children:[e.jsxs("div",{className:"max-w-6xl mx-auto p-6 lg:p-8 space-y-8",children:[e.jsxs("div",{className:"relative overflow-hidden rounded-3xl bg-gradient-to-br from-indigo-600 via-fuchsia-600 to-rose-500 p-8 lg:p-10 shadow-xl",children:[e.jsx("div",{className:"absolute -top-20 -right-20 w-72 h-72 rounded-full bg-white/10 blur-3xl"}),e.jsx("div",{className:"absolute -bottom-24 -left-16 w-80 h-80 rounded-full bg-fuchsia-300/20 blur-3xl"}),e.jsxs("div",{className:"relative",children:[e.jsxs("div",{className:"inline-flex items-center gap-2 px-3 py-1 rounded-full bg-white/15 backdrop-blur-sm text-white text-xs font-semibold uppercase tracking-wider mb-4",children:[e.jsx(ff,{className:"w-3.5 h-3.5"})," Boost conversions on autopilot"]}),e.jsxs("h1",{className:"text-3xl lg:text-4xl font-extrabold tracking-tight text-white flex items-center gap-3",children:[e.jsx(Cn,{className:"w-8 h-8 text-yellow-300 drop-shadow"}),"Website Apps"]}),e.jsx("p",{className:"text-white/90 mt-2 max-w-2xl text-base lg:text-lg",children:"Drop-in widgets that turn website visitors into leads. Add them to your Lead Site or embed on your own website with one line of code."}),e.jsxs(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(wp,{className:"w-5 h-5"}),"Watch: How to use Website Apps"]})]})]}),e.jsxs("div",{className:"grid gap-4 md:grid-cols-2",children:[e.jsx(_e,{className:`p-5 border-2 ${a?"border-emerald-200 bg-emerald-50/50":"border-dashed border-muted"}`,children:e.jsxs("div",{className:"flex items-start gap-4",children:[e.jsx("div",{className:`w-11 h-11 rounded-xl flex items-center justify-center flex-shrink-0 ${a?"bg-emerald-500 text-white":"bg-muted text-muted-foreground"}`,children:e.jsx(au,{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(We,{className:"bg-emerald-100 text-emerald-700 hover:bg-emerald-100 text-[10px] gap-1",children:[e.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-emerald-500 animate-pulse"})," Auto-installed"]})]}),a&&i?e.jsxs("a",{href:i,target:"_blank",rel:"noreferrer",className:"text-xs text-emerald-700 hover:underline inline-flex items-center gap-1 mt-1",children:[i.replace(/^https?:\/\//,"")," ",e.jsx(Tr,{className:"w-3 h-3"})]}):e.jsxs("p",{className:"text-xs text-muted-foreground mt-1",children:["Don't have a Local Move website yet? Visit"," ",e.jsxs("a",{href:"https://www.thelocalmove.com",target:"_blank",rel:"noreferrer",className:"text-primary font-medium hover:underline inline-flex items-center gap-0.5",children:["www.thelocalmove.com ",e.jsx(Tr,{className:"w-3 h-3"})]})," ","to learn more — apps install automatically once you have one."]})]})]})}),e.jsx(_e,{className:"p-5 border-2 border-indigo-200 bg-indigo-50/40",children:e.jsxs("div",{className:"flex items-start gap-4",children:[e.jsx("div",{className:"w-11 h-11 rounded-xl bg-gradient-to-br from-indigo-500 to-fuchsia-600 text-white flex items-center justify-center flex-shrink-0",children:e.jsx(l4,{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 f=zSe[m.icon||"Sparkles"]||Cn,g=u(m.slug),y=h(m.slug),x=m.status==="coming_soon",_=zDn[m.slug]||BDn;return e.jsxs(_e,{className:`group relative overflow-hidden border-0 ring-1 ring-border ${_.ring} hover:ring-2 transition-all hover:shadow-xl ${x?"opacity-70":""}`,children:[e.jsx("div",{className:`h-1.5 w-full bg-gradient-to-r ${_.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 ${_.iconBg} ${_.iconText} flex items-center justify-center shadow-md group-hover:scale-105 transition-transform`,children:e.jsx(f,{className:"w-7 h-7"})}),x?e.jsx(We,{variant:"secondary",children:"Coming soon"}):g?e.jsxs(We,{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(We,{variant:"outline",children:"Paused"}):e.jsx(We,{className:_.chip+" hover:"+_.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})]}),!x&&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(zn,{checked:g,onCheckedChange:b=>o.mutate({app_slug:m.slug,enabled:b})}),e.jsx("span",{className:"text-sm font-medium text-muted-foreground",children:g?"On":"Off"})]}),e.jsxs(B,{size:"sm",className:`bg-gradient-to-r ${_.gradient} text-white hover:opacity-90 shadow-md border-0`,onClick:()=>s(`/website-apps/${m.slug}`),children:[e.jsx(sc,{className:"w-3.5 h-3.5 mr-1.5"}),"Configure",e.jsx(vi,{className:"w-3.5 h-3.5 ml-1"})]})]})]})]},m.id)})})]}),e.jsx(Bs,{open:c,onOpenChange:d,children:e.jsxs(Fs,{className:"max-w-4xl p-0 overflow-hidden bg-black border-0",children:[e.jsx(qs,{className:"px-5 pt-4 pb-2 bg-background",children:e.jsx($s,{children:"How to use Website Apps"})}),c&&e.jsx("video",{src:"/website-apps-tutorial.mp4",controls:!0,autoPlay:!0,playsInline:!0,className:"w-full h-auto bg-black"})]})})]})}const VIe={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 UDn(){const{user:s}=Ls();return mt({queryKey:["video-greeter-config",s==null?void 0:s.id],queryFn:async()=>{if(!(s!=null&&s.id))return VIe;const{data:t,error:n}=await H.from("video_greeter_configs").select("*").eq("user_id",s.id).maybeSingle();if(n)throw n;return t?{...VIe,...t}:VIe},enabled:!!(s!=null&&s.id)})}function qDn(){const{user:s}=Ls(),t=as();return _t({mutationFn:async n=>{if(!(s!=null&&s.id))throw new Error("Not authenticated");const{error:r}=await H.from("video_greeter_configs").upsert({user_id:s.id,...n},{onConflict:"user_id"});if(r)throw r},onSuccess:()=>{t.invalidateQueries({queryKey:["video-greeter-config"]}),ie.success("Saved")},onError:n=>ie.error(n.message||"Failed to save")})}function VDn({label:s,value:t,onChange:n,thumbnailUrl:r,placeholder:a="https://...",hint:i}){const l=N.useRef(null),[o,c]=N.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/")){ie.error("Please select a video file");return}if(h.size>50*1024*1024){ie.error("Video must be under 50MB");return}c(!0);try{const f=h.name.split(".").pop()||"mp4",g=`lead-site/videos/${Date.now()}-${Math.random().toString(36).slice(2,6)}.${f}`,{error:y}=await H.storage.from("agent-uploads").upload(g,h,{upsert:!0});if(y)throw y;const{data:{publicUrl:x}}=H.storage.from("agent-uploads").getPublicUrl(g);n(x),ie.success("Video uploaded!")}catch(f){ie.error(f.message||"Upload failed")}finally{c(!1),l.current&&(l.current.value="")}}};return e.jsxs("div",{children:[e.jsx(re,{children:s}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(we,{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(us,{className:"h-3.5 w-3.5 animate-spin"}):e.jsx(ni,{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}):Y7(t)?e.jsx(Uze,{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(hr,{className:"h-3 w-3"})})]})})()]})}const HDn=[{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 GDn({onVideoReady:s}){const[t,n]=N.useState(!1),[r,a]=N.useState("script"),[i,l]=N.useState(""),[o,c]=N.useState(!0),[d,u]=N.useState(!1),[h,m]=N.useState(0),[f,g]=N.useState(0),y=G3(),x=()=>{a("script"),l(""),m(0),g(0),c(!0)},_=k=>{!k&&(r==="uploading"||r==="processing")||(n(k),k||x())},b=N.useCallback(async(k,A)=>{a("uploading");try{const T="Video Greeter",{videoId:P,libraryId:I}=await sO(T),{uploadUrl:M,apiKey:L}=await nO(P),z=new XMLHttpRequest;z.upload.onprogress=ue=>{ue.lengthComputable&&m(ue.loaded/ue.total*100)},await new Promise((ue,ce)=>{z.onload=()=>z.status>=200&&z.status<300?ue():ce(new Error("Upload failed")),z.onerror=()=>ce(new Error("Upload failed")),z.open("PUT",M),z.setRequestHeader("AccessKey",L),z.send(k)}),a("processing");let $=0;const V=Date.now(),W=9e4,G=`https://iframe.mediadelivery.net/embed/${I}/${P}`,X=`https://iframe.mediadelivery.net/play/${I}/${P}`;for(;$<4;){if(await new Promise(ce=>setTimeout(ce,3e3)),Date.now()-V>W){const ce=k.size/1048576,ae=await y.mutateAsync({bunny_video_id:P,playback_url:X,file_size_mb:ce,title:T,status:"processing",touch_type:"video"});s({videoId:(ae==null?void 0:ae.id)||P,playbackUrl:G,thumbnailUrl:null}),ie.success("Video saved — still encoding. Will be ready shortly."),a("done"),setTimeout(()=>{n(!1),x()},1500);return}const ue=await F5(P);if($=ue.status,g(ue.encodeProgress||0),$===5||$===6)throw new Error("Video processing failed")}const te=await F5(P),ne=(te.storageSize||k.size)/(1024*1024),me=await y.mutateAsync({bunny_video_id:P,playback_url:te.directPlayUrl||G,thumbnail_url:te.thumbnailUrl,preview_url:te.previewUrl||null,duration_seconds:te.length||A,file_size_mb:ne,title:T,status:"ready",touch_type:"video"});s({videoId:(me==null?void 0:me.id)||P,playbackUrl:te.directPlayUrl||G,thumbnailUrl:te.thumbnailUrl||null}),ie.success("Video recorded & added to your library!"),a("done"),setTimeout(()=>{n(!1),x()},1500)}catch(T){console.error(T),ie.error("Failed to process video. Please try again."),a("record")}},[y,s]);return e.jsxs(Bs,{open:t,onOpenChange:_,children:[e.jsx(Ao,{asChild:!0,children:e.jsxs(B,{variant:"default",size:"sm",className:"gap-1.5",children:[e.jsx(na,{className:"h-4 w-4"}),"Record now"]})}),e.jsxs(Fs,{className:"sm:max-w-3xl max-h-[92vh] overflow-y-auto",children:[e.jsx(qs,{children:e.jsxs($s,{className:"flex items-center gap-2",children:[e.jsx(Cn,{className:"h-5 w-5 text-primary"}),"Record your Video Greeter"]})}),r==="script"&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"font-semibold text-sm mb-1",children:"1. Pick a script (optional)"}),e.jsx("p",{className:"text-xs text-muted-foreground mb-3",children:"Edit it to sound like you, or skip and freestyle."}),e.jsx(lo,{className:"h-[280px] pr-3",children:e.jsx("div",{className:"grid sm:grid-cols-2 gap-3",children:HDn.map(k=>e.jsxs(_e,{className:"p-3 cursor-pointer hover:border-primary transition-colors",onClick:()=>l(k.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:k.title}),e.jsx(We,{variant:"outline",className:"text-[10px] shrink-0",children:k.duration})]}),e.jsx("p",{className:"text-xs text-muted-foreground line-clamp-2",children:k.description})]},k.id))})})]}),e.jsxs("div",{children:[e.jsx("h3",{className:"font-semibold text-sm mb-1",children:"2. Edit your script"}),e.jsx(Ws,{rows:5,value:i,onChange:k=>l(k.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(Wr,{className:"h-4 w-4 mr-1.5"})," Continue to recorder"]})]})]}),r==="record"&&e.jsxs("div",{className:"space-y-3",children:[e.jsx(oO,{maxDurationSeconds:60,onRecordingComplete:b,onRecordingStateChange:u,onError:k=>ie.error(k),teleprompterContent:o&&i?e.jsx(qWe,{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(Wr,{className:"h-4 w-4 mr-1.5"})," Show teleprompter"]})]})]}),r==="uploading"&&e.jsxs("div",{className:"flex flex-col items-center gap-4 py-12",children:[e.jsx(us,{className:"h-10 w-10 animate-spin text-primary"}),e.jsx("p",{className:"text-sm font-medium",children:"Uploading video..."}),e.jsx(ro,{value:h,className:"w-64"}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[Math.round(h),"%"]})]}),r==="processing"&&e.jsxs("div",{className:"flex flex-col items-center gap-4 py-12",children:[e.jsx(us,{className:"h-10 w-10 animate-spin text-primary"}),e.jsx("p",{className:"text-sm font-medium",children:"Processing video..."}),e.jsx(ro,{value:f,className:"w-64"}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[Math.round(f),"%"]})]}),r==="done"&&e.jsxs("div",{className:"flex flex-col items-center gap-3 py-12",children:[e.jsx(Po,{className:"h-12 w-12 text-emerald-500"}),e.jsx("p",{className:"text-sm font-medium",children:"Video attached to your greeter!"})]})]})]})}function WDn(){var A;const s=tr(),{user:t}=Ls(),{leadSite:n}=Qx(),{data:r}=UDn(),a=qDn(),{data:i=[]}=BAe(),l=$Ae(),[o,c]=N.useState(null),[d,u]=N.useState({impressions:0,expands:0,ctaClicks:0,leads:0});if(N.useEffect(()=>{r&&!o&&c(r)},[r,o]),N.useEffect(()=>{t!=null&&t.id&&H.from("widget_events").select("event_type",{count:"exact"}).eq("user_id",t.id).eq("app_slug","video_greeter").then(({data:T})=>{const P=T||[];u({impressions:P.filter(I=>I.event_type==="impression").length,expands:P.filter(I=>I.event_type==="expand").length,ctaClicks:P.filter(I=>I.event_type==="cta_click").length,leads:P.filter(I=>I.event_type==="lead_capture").length})})},[t==null?void 0:t.id]),!o)return e.jsx(Qs,{title:"Video Greeter",children:e.jsx("div",{className:"p-8 text-sm text-muted-foreground",children:"Loading..."})});const h=((A=i.find(T=>T.app_slug==="video_greeter"))==null?void 0:A.enabled)??!1,m=T=>c({...o,...T}),f=T=>m({ctas:T}),g=()=>f([...o.ctas||[],{id:crypto.randomUUID(),label:"New Button",url:"https://",style:"primary"}]),y=T=>f((o.ctas||[]).filter(P=>P.id!==T)),x=(T,P)=>f((o.ctas||[]).map(I=>I.id===T?{...I,...P}:I)),_=()=>a.mutate(o),b=(n==null?void 0:n.subdomain_slug)||(t==null?void 0:t.id)||"",k=`